Claude Code for Triton: Custom GPU Kernels in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for Triton: Custom GPU Kernels in Python
AI

Claude Code for Triton: Custom GPU Kernels in Python

Published: September 25, 2027
Read time: 5 min read
By: Claude Skills 360

Triton writes custom GPU kernels in Python. pip install triton. @triton.jit marks a function as a GPU kernel. tl.program_id(axis=0) returns the current block index. Core: vector addition kernel: @triton.jit\ndef add_kernel(x_ptr, y_ptr, out_ptr, n, BLOCK: tl.constexpr):\n pid = tl.program_id(0); offsets = pid * BLOCK + tl.arange(0, BLOCK); mask = offsets < n\n x = tl.load(x_ptr + offsets, mask=mask); y = tl.load(y_ptr + offsets, mask=mask)\n tl.store(out_ptr + offsets, x + y, mask=mask). Launch: add_kernel[(n + 1023) // 1024,](x, y, out, n, BLOCK=1024). tl.constexpr marks compile-time constants for block sizes. Autotuner: @triton.autotune(configs=[triton.Config({"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 64, "num_warps": 8}), ...], key=["M","N","K"]). 2D indexing for matmul: pid_m = tl.program_id(0); pid_n = tl.program_id(1). tl.dot(a_tile, b_tile) uses tensor cores automatically when dtypes are float16/bfloat16. tl.load(ptr, mask=mask, other=0.0) handles out-of-bounds safely. Fused softmax: load row, subtract max for numerical stability with tl.max(row, axis=0), compute exp(row - max), normalize by tl.sum(exp_row, axis=0). Layer norm: compute mean with tl.sum/n_cols, variance with tl.sum(diff**2)/n_cols, normalize, scale with weight/bias via tl.load. tl.atomic_add(ptr, val) for reductions across blocks. Debug: triton.testing.assert_close(torch_ref, triton_out). Bench: triton.testing.Benchmark(x_names=["N"], x_vals=[...], line_arg="provider", line_vals=["triton","torch"], ylabel="GB/s", plot_name="bandwidth"). Claude Code generates Triton kernels for attention, softmax, layer norm, matmul, and custom activation functions.

CLAUDE.md for Triton

## Triton Stack
- Version: triton >= 3.0 (ships with torch>=2.0 as torch._inductor.triton_ops)
- Kernel: @triton.jit fn(ptr, ..., BLOCK: tl.constexpr) → tl.load/store/dot/sum
- Launch: kernel[(grid,)](args, BLOCK=N) — grid is tuple of integers
- Autotuner: @triton.autotune(configs=[Config({...}, num_warps=N)], key=["M","N"])
- tl.constexpr: compile-time constants (block sizes, tile dims)
- tl.dot: tensor core matmul — requires float16/bfloat16, BLOCK multiple of 16
- Debug: triton.testing.assert_close(ref, out, atol=1e-2, rtol=1e-2)

Triton Kernels

# kernels/triton_ops.py — production Triton kernels with autotuning
from __future__ import annotations
import math

import torch
import triton
import triton.language as tl


# ── 1. Vector Addition (hello-world kernel) ───────────────────────────────────

@triton.jit
def _add_kernel(
    x_ptr, y_ptr, out_ptr,
    n_elements,
    BLOCK_SIZE: tl.constexpr,
):
    """Elementwise addition: out = x + y."""
    pid      = tl.program_id(axis=0)
    offsets  = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
    mask     = offsets < n_elements

    x = tl.load(x_ptr + offsets, mask=mask)
    y = tl.load(y_ptr + offsets, mask=mask)
    tl.store(out_ptr + offsets, x + y, mask=mask)


def triton_add(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
    assert x.shape == y.shape and x.is_cuda
    out   = torch.empty_like(x)
    n     = x.numel()
    grid  = lambda meta: (triton.cdiv(n, meta["BLOCK_SIZE"]),)
    _add_kernel[grid](x, y, out, n, BLOCK_SIZE=1024)
    return out


# ── 2. Fused Softmax ──────────────────────────────────────────────────────────

@triton.autotune(
    configs=[
        triton.Config({"BLOCK_SIZE": 512}),
        triton.Config({"BLOCK_SIZE": 1024}),
        triton.Config({"BLOCK_SIZE": 2048}),
    ],
    key=["n_cols"],
)
@triton.jit
def _softmax_kernel(
    output_ptr, input_ptr,
    input_row_stride, output_row_stride,
    n_cols,
    BLOCK_SIZE: tl.constexpr,
):
    """
    Numerically stable softmax over each row.
    One program per row — runs all of BLOCK_SIZE columns in registers.
    """
    row_idx = tl.program_id(0)

    row_start_ptr = input_ptr + row_idx * input_row_stride
    col_offsets   = tl.arange(0, BLOCK_SIZE)
    mask          = col_offsets < n_cols

    # Load row with -inf for out-of-bounds
    row = tl.load(row_start_ptr + col_offsets, mask=mask, other=-float("inf"))

    # Subtract max for numerical stability
    row_max = tl.max(row, axis=0)
    row     = row - row_max

    # Softmax
    exp_row       = tl.exp(row)
    exp_sum       = tl.sum(exp_row, axis=0)
    softmax_row   = exp_row / exp_sum

    # Write output
    out_row_ptr = output_ptr + row_idx * output_row_stride
    tl.store(out_row_ptr + col_offsets, softmax_row, mask=mask)


def triton_softmax(x: torch.Tensor) -> torch.Tensor:
    """Fused softmax — avoids 3 PyTorch kernel launches."""
    assert x.ndim == 2 and x.is_cuda
    n_rows, n_cols = x.shape
    # Pad BLOCK_SIZE to next power of 2 ≥ n_cols
    BLOCK = triton.next_power_of_2(n_cols)
    out   = torch.empty_like(x)
    _softmax_kernel[(n_rows,)](
        out, x,
        x.stride(0), out.stride(0),
        n_cols, BLOCK_SIZE=BLOCK,
    )
    return out


# ── 3. Fused Layer Normalization ──────────────────────────────────────────────

@triton.jit
def _layer_norm_fwd_kernel(
    X_ptr, W_ptr, B_ptr, Y_ptr,
    Mean_ptr, Rstd_ptr,
    stride, N,
    eps,
    BLOCK_SIZE: tl.constexpr,
):
    """Layer norm forward pass: Y = (X - mean) / std * W + B."""
    row   = tl.program_id(0)
    X_ptr = X_ptr + row * stride
    Y_ptr = Y_ptr + row * stride

    # Load with masking
    cols  = tl.arange(0, BLOCK_SIZE)
    mask  = cols < N
    x     = tl.load(X_ptr + cols, mask=mask, other=0.0).to(tl.float32)

    # Compute mean and variance in one pass
    mean  = tl.sum(x, axis=0) / N
    diff  = tl.where(mask, x - mean, 0.0)
    var   = tl.sum(diff * diff, axis=0) / N
    rstd  = 1.0 / tl.sqrt(var + eps)

    # Normalize
    x_hat = diff * rstd
    w     = tl.load(W_ptr + cols, mask=mask)
    b     = tl.load(B_ptr + cols, mask=mask)
    y     = x_hat * w + b

    tl.store(Y_ptr + cols, y, mask=mask)
    tl.store(Mean_ptr + row, mean)
    tl.store(Rstd_ptr + row, rstd)


def triton_layer_norm(
    x: torch.Tensor,
    weight: torch.Tensor,
    bias: torch.Tensor,
    eps: float = 1e-5,
) -> torch.Tensor:
    """Fused layer norm — single kernel, no intermediate allocations."""
    assert x.is_cuda and x.ndim == 2
    M, N  = x.shape
    BLOCK = triton.next_power_of_2(N)
    y     = torch.empty_like(x)
    mean  = torch.empty(M, dtype=torch.float32, device=x.device)
    rstd  = torch.empty(M, dtype=torch.float32, device=x.device)

    _layer_norm_fwd_kernel[(M,)](
        x, weight, bias, y, mean, rstd,
        x.stride(0), N, eps,
        BLOCK_SIZE=BLOCK,
        num_warps=8 if N >= 2048 else 4,
    )
    return y


# ── 4. Autotuned Matrix Multiplication ───────────────────────────────────────

@triton.autotune(
    configs=[
        triton.Config({"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 64, "GROUP_M": 8},
                      num_warps=8, num_stages=3),
        triton.Config({"BLOCK_M": 64,  "BLOCK_N": 256, "BLOCK_K": 32, "GROUP_M": 8},
                      num_warps=4, num_stages=4),
        triton.Config({"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 32, "GROUP_M": 8},
                      num_warps=4, num_stages=4),
    ],
    key=["M", "N", "K"],
)
@triton.jit
def _matmul_kernel(
    A_ptr, B_ptr, C_ptr,
    M, N, K,
    stride_am, stride_ak,
    stride_bk, stride_bn,
    stride_cm, stride_cn,
    BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr,
    GROUP_M: tl.constexpr,
):
    """Autotuned matrix multiplication C = A @ B using tensor cores."""
    # Grouped program ordering for L2 cache efficiency
    pid       = tl.program_id(0)
    num_pid_m = tl.cdiv(M, BLOCK_M)
    num_pid_n = tl.cdiv(N, BLOCK_N)
    num_pid_in_group = GROUP_M * num_pid_n
    group_id  = pid // num_pid_in_group
    first_pid_m = group_id * GROUP_M
    group_size_m = min(num_pid_m - first_pid_m, GROUP_M)
    pid_m = first_pid_m + (pid % group_size_m)
    pid_n = (pid % num_pid_in_group) // group_size_m

    # Block pointers
    offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    offs_k = tl.arange(0, BLOCK_K)

    A_blk = A_ptr + offs_m[:, None] * stride_am + offs_k[None, :] * stride_ak
    B_blk = B_ptr + offs_k[:, None] * stride_bk + offs_n[None, :] * stride_bn

    # Accumulate in fp32 for precision
    acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
    for k in range(0, tl.cdiv(K, BLOCK_K)):
        a = tl.load(A_blk, mask=(offs_m[:, None] < M) & ((k * BLOCK_K + offs_k)[None, :] < K), other=0.0)
        b = tl.load(B_blk, mask=((k * BLOCK_K + offs_k)[:, None] < K) & (offs_n[None, :] < N), other=0.0)
        acc += tl.dot(a, b)  # Tensor core matmul
        A_blk += BLOCK_K * stride_ak
        B_blk += BLOCK_K * stride_bk

    c = acc.to(tl.float16)
    C_blk = C_ptr + offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn
    tl.store(C_blk, c, mask=(offs_m[:, None] < M) & (offs_n[None, :] < N))


def triton_matmul(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """Autotuned fp16 matmul using Triton tensor cores."""
    assert a.shape[1] == b.shape[0] and a.dtype == b.dtype == torch.float16
    M, K = a.shape
    K, N = b.shape
    c    = torch.empty((M, N), dtype=torch.float16, device=a.device)
    grid = lambda meta: (triton.cdiv(M, meta["BLOCK_M"]) * triton.cdiv(N, meta["BLOCK_N"]),)
    _matmul_kernel[grid](
        a, b, c, M, N, K,
        a.stride(0), a.stride(1),
        b.stride(0), b.stride(1),
        c.stride(0), c.stride(1),
    )
    return c


# ── Benchmarking ──────────────────────────────────────────────────────────────

@triton.testing.perf_report(
    triton.testing.Benchmark(
        x_names=["N"],
        x_vals=[256, 512, 1024, 2048, 4096, 8192],
        line_arg="provider",
        line_vals=["triton", "torch"],
        line_names=["Triton", "PyTorch"],
        styles=[("blue", "-"), ("red", "--")],
        ylabel="GB/s",
        plot_name="softmax-bandwidth",
        args={},
    )
)
def benchmark_softmax(N, provider):
    x = torch.randn(4096, N, device="cuda", dtype=torch.float32)
    quantiles = [0.5, 0.2, 0.8]
    if provider == "triton":
        ms, min_ms, max_ms = triton.testing.do_bench(lambda: triton_softmax(x), quantiles=quantiles)
    else:
        ms, min_ms, max_ms = triton.testing.do_bench(lambda: torch.softmax(x, dim=-1), quantiles=quantiles)
    gbps = lambda ms: 2 * x.numel() * x.element_size() * 1e-9 / (ms * 1e-3)
    return gbps(ms), gbps(max_ms), gbps(min_ms)

For the CUDA C++ alternative when needing access to low-level CUDA features (warp-level primitives, PTX inline assembly, cooperative groups, shared memory bank conflict analysis) or custom tensor core layouts — CUDA C++ provides full hardware control while Triton abstracts the tiling and indexing math that accounts for most kernel complexity, letting Python ML engineers write efficient kernels without CUDA expertise. For the torch.compile / torch.inductor alternative when you want automatic kernel fusion of existing PyTorch operations without writing kernels — torch.compile generates Triton kernels automatically from PyTorch code while hand-written Triton kernels are needed when the automatic fusion misses opportunities or when implementing operations that aren’t expressible as compositions of PyTorch primitives (like the packed variable-length attention in Flash Attention). The Claude Skills 360 bundle includes Triton skill sets covering vector operations, fused softmax, layer norm, matmul with tensor cores, autotuner configs, and benchmarking harnesses. Start with the free tier to try custom GPU kernel generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free