惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
Google Online Security Blog
Google Online Security Blog
Engineering at Meta
Engineering at Meta
U
Unit 42
Security Latest
Security Latest
G
Google Developers Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
D
Docker
T
Tailwind CSS Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
云风的 BLOG
云风的 BLOG
Hugging Face - Blog
Hugging Face - Blog
M
MIT News - Artificial intelligence
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
MongoDB | Blog
MongoDB | Blog
H
Help Net Security
Stack Overflow Blog
Stack Overflow Blog
C
Check Point Blog
S
Security Affairs
T
The Exploit Database - CXSecurity.com
S
SegmentFault 最新的问题
N
News and Events Feed by Topic
The GitHub Blog
The GitHub Blog
Apple Machine Learning Research
Apple Machine Learning Research
S
Securelist
IT之家
IT之家
P
Palo Alto Networks Blog
D
DataBreaches.Net
Help Net Security
Help Net Security
N
Netflix TechBlog - Medium
B
Blog RSS Feed
AWS News Blog
AWS News Blog
Scott Helme
Scott Helme
爱范儿
爱范儿
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
腾讯CDC
I
Intezer
J
Java Code Geeks
大猫的无限游戏
大猫的无限游戏
Microsoft Security Blog
Microsoft Security Blog
人人都是产品经理
人人都是产品经理
G
GRAHAM CLULEY
N
News | PayPal Newsroom
博客园 - 三生石上(FineUI控件)
A
Arctic Wolf
F
Fortinet All Blogs
The Register - Security
The Register - Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
博客园 - 【当耐特】

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Calling CUDA from Go without cgo
Eitamos Ring · 2026-05-17 · via DEV Community

Go is great at infrastructure.

It gives us fast builds, simple deployment, lightweight concurrency, and the ability to ship a single binary.

But Go has always been awkward around one increasingly important area: GPUs.

A lot of modern AI, analytics, vector processing, and high-throughput data work now runs on NVIDIA GPUs through CUDA. The problem is that most CUDA access from application code still lives in the Python world.

This post is about why calling CUDA from Go matters, why cgo is often painful, and what a pure-Go runtime-loaded CUDA Driver API approach can look like.

The problem

Many production backend systems are written in Go.

But most GPU tooling is centered around Python libraries like:

  • PyTorch
  • TensorFlow
  • JAX
  • CuPy

That often creates an architecture like this:

Go service
  -> HTTP/gRPC
  -> Python GPU worker
  -> CUDA
  -> Python GPU worker
  -> Go service

Enter fullscreen mode Exit fullscreen mode

This works, but it adds:

  • another service
  • another runtime
  • serialization overhead
  • extra deployment complexity
  • extra observability/debugging surface

Sometimes the Python service exists only because the Go service cannot easily talk to CUDA directly.

Why not just use cgo?

The usual way to call native libraries from Go is cgo.

For CUDA, that might look like this:

// #cgo LDFLAGS: -lcuda
// #include <cuda.h>
import "C"

Enter fullscreen mode Exit fullscreen mode

That works, but it changes the Go developer experience.

Now you need:

  • a C compiler
  • CUDA headers
  • CUDA libraries available at build time
  • more fragile CI builds
  • harder cross-compilation
  • platform-specific linking behavior

One of Go’s best properties is this:

CGO_ENABLED=0 go build ./...

Enter fullscreen mode Exit fullscreen mode

A clean binary.

No C toolchain.

No build-time CUDA dependency.

So the interesting question is:

Can Go talk to CUDA without cgo?

Yes — by loading the CUDA Driver API dynamically at runtime.

Runtime-loading CUDA

CUDA exposes a Driver API through the NVIDIA driver library.

On Linux:

libcuda.so.1

Enter fullscreen mode Exit fullscreen mode

On Windows:

nvcuda.dll

Enter fullscreen mode Exit fullscreen mode

Instead of linking to CUDA at build time, a Go program can open the driver library at runtime and bind the symbols it needs.

Conceptually:

Go binary
  -> open libcuda.so.1
  -> find cuInit
  -> find cuDriverGetVersion
  -> call CUDA Driver API

Enter fullscreen mode Exit fullscreen mode

The important part is that the binary can still be built like this:

CGO_ENABLED=0 go build ./...

Enter fullscreen mode Exit fullscreen mode

CUDA only needs to exist on the machine where the program actually runs.

Minimal example: initialize CUDA from Go

A small example could look like this:

package main

import (
    "fmt"

    "github.com/eitamring/gocudrv/cuda"
)

func main() {
    driver, err := cuda.Open()
    if err != nil {
        panic(err)
    }
    defer driver.Close()

    if err := driver.Init(0); err != nil {
        panic(err)
    }

    version, err := driver.DriverVersion()
    if err != nil {
        panic(err)
    }

    fmt.Println("CUDA driver version:", version)
}

Enter fullscreen mode Exit fullscreen mode

Example output:

loading CUDA driver: libcuda.so.1
cuInit(0)
DriverVersion() = 12040
CUDA driver version: 12040

Enter fullscreen mode Exit fullscreen mode

This is not ML.

This is the foundation: initialize CUDA, call Driver API functions, then build up to memory management, PTX loading, and kernel launches.

Loading PTX

CUDA kernels can be compiled into PTX.

A simplified PTX kernel might look like this:

.version 7.8
.target sm_75
.address_size 64

.visible .entry vecAdd(
    .param .u64 a,
    .param .u64 b,
    .param .u64 c,
    .param .u32 n
)
{
    ret;
}

Enter fullscreen mode Exit fullscreen mode

Go can load that PTX module at runtime:

module, err := ctx.LoadPTX(ptxBytes)
if err != nil {
    panic(err)
}

kernel, err := module.Function("vecAdd")
if err != nil {
    panic(err)
}

fmt.Println("PTX loaded successfully")

Enter fullscreen mode Exit fullscreen mode

Example output:

PTX loaded successfully

Enter fullscreen mode Exit fullscreen mode

Launching a CUDA kernel from Go

Once the PTX is loaded, Go can launch the kernel directly:

err = kernel.Launch(
    cuda.GridDim{X: 1024, Y: 1, Z: 1},
    cuda.BlockDim{X: 256, Y: 1, Z: 1},
    0,
    stream,
    args,
)
if err != nil {
    panic(err)
}

Enter fullscreen mode Exit fullscreen mode

Runtime logs might look like this:

using device 0: NVIDIA GeForce RTX 4090
loading PTX module...
PTX loaded successfully
kernel launch configuration: grid=1024 block=256
launch successful
execution completed
elapsed: 0.186 ms

Enter fullscreen mode Exit fullscreen mode

That is the core idea:

Go -> CUDA Driver API -> GPU

Enter fullscreen mode Exit fullscreen mode

No Python sidecar.

No cgo.

No build-time CUDA toolkit.

Example: vector addition

A simple starter workload is vector addition.

Input:

a = [1, 2, 3, 4]
b = [10, 20, 30, 40]

Enter fullscreen mode Exit fullscreen mode

Expected output:

c = [11, 22, 33, 44]

Enter fullscreen mode Exit fullscreen mode

The Go-side flow looks like this:

aDev, err := ctx.MemAlloc(size)
if err != nil {
    panic(err)
}
defer aDev.Free()

bDev, err := ctx.MemAlloc(size)
if err != nil {
    panic(err)
}
defer bDev.Free()

cDev, err := ctx.MemAlloc(size)
if err != nil {
    panic(err)
}
defer cDev.Free()

if err := ctx.MemcpyHtoD(aDev, aHost); err != nil {
    panic(err)
}

if err := ctx.MemcpyHtoD(bDev, bHost); err != nil {
    panic(err)
}

err = kernel.Launch(
    cuda.GridDim{X: blocks},
    cuda.BlockDim{X: threads},
    0,
    stream,
    []cuda.KernelArg{
        cuda.DevicePtrArg(aDev),
        cuda.DevicePtrArg(bDev),
        cuda.DevicePtrArg(cDev),
        cuda.Uint32Arg(uint32(n)),
    },
)
if err != nil {
    panic(err)
}

if err := ctx.MemcpyDtoH(cHost, cDev); err != nil {
    panic(err)
}

Enter fullscreen mode Exit fullscreen mode

This is intentionally low-level.

It gives Go access to the same CUDA primitives used elsewhere:

  • allocate device memory
  • copy host memory to device memory
  • load a module
  • launch a kernel
  • copy device memory back to host memory
  • synchronize

What this is useful for

This is not trying to replace PyTorch.

PyTorch is still the right tool for training models and high-level ML research.

The better use cases for CUDA from Go are infrastructure workloads:

  • custom inference kernels
  • vector search acceleration
  • embeddings pipelines
  • columnar data processing
  • compression/decompression experiments
  • image/video processing
  • batch scoring
  • database or analytics engine experiments

For example:

HTTP request
  -> parse vectors in Go
  -> copy batch to GPU memory
  -> launch similarity kernel
  -> copy result back
  -> return response

Enter fullscreen mode Exit fullscreen mode

No Python worker required.

The tradeoff

Runtime-loading CUDA is not magic.

You still need:

  • an NVIDIA GPU
  • a compatible NVIDIA driver
  • compiled PTX
  • careful memory management
  • enough batch size to justify GPU overhead

Small workloads can be slower than CPU code because you pay for:

  • memory transfers
  • kernel launch overhead
  • synchronization
  • device setup

A useful rule of thumb:

Tiny batch:
CPU wins

Large batch:
GPU may win

Repeated large batch:
GPU likely wins

Enter fullscreen mode Exit fullscreen mode

The goal is not “GPU everything.”

The goal is to make GPU access available to Go when it actually makes sense.

Why CGO_ENABLED=0 is the interesting part

The technical detail I care about most is not just “Go can call CUDA.”

It is this:

CGO_ENABLED=0 go build ./...

Enter fullscreen mode Exit fullscreen mode

That means you can build without:

  • CUDA headers
  • the CUDA toolkit
  • a C compiler
  • cgo
  • build-time GPU dependencies

Then, at runtime:

try loading libcuda.so.1
if available:
  use GPU path
else:
  fall back to CPU path

Enter fullscreen mode Exit fullscreen mode

That fits infrastructure software much better.

The binary does not need to be built on a GPU machine. It only needs the NVIDIA driver on the machine where GPU execution actually happens.

Final thought

AI made GPUs mainstream, but GPUs are not only for AI.

They are throughput machines.

They are useful when you have large batches of repetitive work: matrix math, vector math, scans, filters, hashing, encoding, simulation, image processing, or data conversion.

Go already owns a lot of backend infrastructure.

So it makes sense for Go to have better access to accelerated computing.

Not through a Python sidecar.

Not through a fragile cgo setup.

But through a simple Go API that can load the CUDA Driver API when available.

That is the experiment behind https://github.com/eitamring/gocudrv