2 Write your first kernel in Triton
This chapter covers
- Writing a full Triton kernel
- Mapping work with program IDs
- Vectorized loads, stores, and masks
- Launching grids from Python
- Tracing Triton’s JIT compilation
- Benchmarking kernel performance
You now have a picture of how GPUs organize computation: blocks of threads running across Streaming Multiprocessors, a layered memory system, and a compiler that handles the low-level details for you. That foundation is enough to start writing real code. In this chapter, we put it to use and write your first Triton kernel. We begin with a complete, working kernel for a simple task: vector addition. Then we break it down line by line to explain Triton’s syntax, its programming model, and the compiler that drives it. We finish by benchmarking the kernel against pure Python, NumPy, and PyTorch to see the difference that parallel execution makes. By the end of this chapter, you will know how to write, launch, debug, and benchmark a basic Triton kernel, and how that kernel flows through Triton’s compilation pipeline.
Note
This chapter is a foundation for everything that follows, so it deserves careful attention. We will walk through every line of code together. You only need an intermediate understanding of Python to follow along. If you need a refresher, The Quick Python Book by Naomi Ceder is a reliable resource.