Module contents
Lesson 5 of 28Core 110 min

Triton kernels I: programming the GPU in blocks

Triton enables GPU kernels in Python expressed in blocks instead of threads, with a compiler handling coalescing, shared memory and synchronization. We prepare a compatible environment and record the actual GPU used; this run uses an RTX 3060 with WSL2 Ubuntu. We debug on CPU with interpreter mode and write first kernels: vector addition, fused elementwise operations and row softmax, measured against actual bandwidth, PyTorch and torch.compile.

After this lesson you can

  • Translate an elementwise or rowwise problem into Triton's block-program model.
  • Write kernels with correct masks, strides and pointer arithmetic for noncontiguous tensors.
  • Measure effective kernel bandwidth with do_bench and compare it with the measured GPU peak.
  • Apply autotuning and explain how the best configuration changes with problem size.
  • Debug a kernel on CPU in interpreter mode before executing it on the GPU.

Before you start

Think in blocks

An addition, GELU, and dropout can form one mathematical expression, but if each operation materializes its output in global memory, data travels several times. Fusion reduces reads, writes, and launches. It does not itself promise greater speed: the kernel may lose occupancy, use registers, or perform expensive operations. Compare actual work, not just the number of Python calls.

In the Triton programming model, each program instance processes a block of indices. The launch grid has as many instances as the problem requires blocks. tl.program_id identifies an instance and tl.arange creates a vector of local indices; the compiler decides how to distribute work among threads and which instructions to emit. The CUDA execution model helps explain that translation without identifying a Triton element with a particular thread. The author remains responsible for shapes, masks, types, dependencies, and launch dimensions. There is no general barrier between independent programs in one grid.

InteractiveFrom indices to programs
Dark blue marks the selected program. Gaps mark indices outside N. The matrix uses tiles of 4 × 8. The sector count assumes groups of 32 indices, 4-byte elements, aligned 32-byte segments, and no cache. Triton leaves assignment of indices to individual threads unspecified.
100
Shape
BLOCK_SIZE
Stride in elements
Program 0
Programs4
Masked lanes28
Modelled read sectors13
Choose vector or matrix, size, and block. Play through instances; gaps are masked lanes. The sector counter is an explicit model without cache, not a trace of CUDA transactions.

For a vector of length NN and block BB, program pp covers pB,…,pB+B−1pB,\dots,pB+B-1, with mask i<Ni<N. The grid has ⌈N/B⌉\lceil N/B\rceil programs. For a matrix, a two-dimensional grid can assign one tile per program; the address of (i,j)(i,j) is base + i * stride_row + j * stride_col. Strides are measured in elements, not bytes. A transpose often shares storage and changes strides, so a formula assuming contiguity can read the wrong position.

For example, a contiguous 3×53\times5 matrix has strides (5,1)(5,1): element (2,3)(2,3) is 13 elements from the base using zero-based code indices. Its transposed view has shape 5×35\times3 and strides (1,5)(1,5); element (3,2)(3,2) reaches the same offset 13. A new output may be contiguous even when the input is not, so its formula must use its own strides. Passing read and write strides separately avoids confusing a view with a copy.

Triton memory operations include masked tl.load and tl.store. other defines the value of lanes that are not loaded. For addition, zero is usually neutral; for the softmax maximum use negative infinity. Mask writes too. An invalid index can silently corrupt data without an obvious failure. Coalescing details depend on compiled assignment and hardware: the figure’s sector model illustrates addresses, not a substitute for GPU counters.

Fusion, traffic, and limits

This lab’s fused elementwise kernel computes addition, approximate GELU, dropout, and scaling in one program. The generator uses seed and index to reconstruct a reproducible mask. During training retain or regenerate that same mask for backward, and vary the seed between steps when appropriate. The example writes the mask as a byte for comparison; a production kernel may not save it.

InteractiveWhich bytes cross memory
Read x and biasAddGELUDropout and scaleWrite y and mask

The FP32 model uses two 4-byte reads, one 4-byte write, and one byte for the written mask. Each split adds an FP32 write and read. The copy baseline was 62.74 GB/s on an RTX 3060 under shared load in WSL. It provides an idealized comparison; actual throughput and PyTorch performance can differ.

2^24
Logical traffic464 MiB
Bytes per element29
Ideal copy time7.75 ms
Measured Triton time at 2^244.524 ms
Add or remove breaks between operations. The model counts logical reads and writes; compare its ideal time with the fused step measured on an RTX 3060 for 2^24 elements.

In the figure’s FP32 model, reading xx and bias, writing output, and writing one mask byte costs 13 bytes per element. Each break materializing an intermediate tensor adds 4 bytes written and 4 read. This sum excludes cache traffic, instructions, internal temporaries, and bandwidth variation. The 62.74 GB/s copy reference and 4.524 ms fused kernel come from one run with 2^24 elements in WSL on a shared GPU. PyTorch eager in the same test uses the already generated mask, so its work differs from the kernel which also generates it. The arithmetic-intensity model and bottleneck taxonomy help interpret, not guarantee, speed.

Reduce a row without overflow

A row reduction must coordinate the elements of a row. For zjz_j, define m=max⁡jzjm=\max_j z_j and compute exp⁡(zj−m)/∑kexp⁡(zk−m)\exp(z_j-m)/\sum_k\exp(z_k-m). Subtracting mm does not change softmax and prevents exponential overflow. If the row fits in the block, each program loads a row, reduces maximum and sum, and writes once. Otherwise a program can traverse tiles in several passes: global maximum, exponential sum, and output. That solution is correct but reads input several times; another implementation can use online softmax and combine block statistics.

The equality follows by canceling the same factor: exp⁡(zj−m)/∑kexp⁡(zk−m)=exp⁡(zj)exp⁡(−m)/(exp⁡(−m)∑kexp⁡(zk))\exp(z_j-m)/\sum_k\exp(z_k-m)=\exp(z_j)\exp(-m)/(\exp(-m)\sum_k\exp(z_k)). The right-hand expression is a real-number identity; the left-hand expression is evaluated because it avoids forming large exponentials. In the third pass of the kernel below, every input is read again to produce its output. That read cost may be acceptable when a full row does not fit in local resources, but it must be measured.

Triton autotuning tries configurations and stores a choice per key. num_warps, block size, and num_stages can change occupancy, registers, and memory. The autotuner runs each candidate multiple times: if a kernel updates rather than overwrites its output, reset it between tests. Compilation cost is not part of steady-state kernel latency. Official documentation describes keys and hooks.

InteractiveThe autotuning landscape
Block size2 warps4 warps8 warps
5128.19 µs7.17 µs8.19 µs
10248.19 µs7.17 µs7.71 µs

More intense shading means a longer time for the selected length. These are medians from a run with 256 FP32 rows, Triton 3.6, and an RTX 3060 in WSL under shared load. The measurement resolution produces ties. The best configuration depends on the setting.

Columns per row
Best recorded time7.17 µs
Configurations tied at the minimum2
Change the number of columns in the row. Cells show measured medians of valid configurations; multiple minima may tie at the observed resolution. They do not extrapolate to another shape or GPU.

Lab: a small interpreter

Before running on GPU, model sequential programs with NumPy. This interpreter counts logical bytes of valid accesses: it does not model parallelism, cache, warps, instructions, or performance. A mask protects access even when the index vector contains values outside the array.

[ ]Launch programs and access with masksBrowser
import numpy as np

class Memory:
    def __init__(self,a):
        self.a=np.asarray(a).reshape(-1); self.read=self.written=0
    def load(self,offsets,mask,other=0):
        offsets=np.asarray(offsets); mask=np.asarray(mask,dtype=bool)
        valid=offsets[mask]
        if np.any((valid<0)|(valid>=self.a.size)): raise IndexError('lectura fuera del buffer')
        out=np.full(offsets.shape,other,dtype=self.a.dtype)
        out[mask]=self.a[valid]; self.read+=valid.size*self.a.itemsize
        return out
    def store(self,offsets,values,mask):
        offsets=np.asarray(offsets); mask=np.asarray(mask,dtype=bool)
        valid=offsets[mask]
        if np.any((valid<0)|(valid>=self.a.size)): raise IndexError('escritura fuera del buffer')
        self.a[valid]=np.asarray(values)[mask]; self.written+=valid.size*self.a.itemsize

def launch(grid,kernel):
    for pid in np.ndindex(*grid): kernel(*pid)

def add(x,y,block):
    a,b=Memory(x),Memory(y); out=Memory(np.zeros_like(x)); n=x.size
    def kernel(pid):
        i=pid*block+np.arange(block); mask=i<n
        out.store(i,a.load(i,mask)+b.load(i,mask),mask)
    launch(((n+block-1)//block,),kernel)
    return out.a,a.read+b.read+out.written

rng=np.random.default_rng(5)
x=rng.normal(size=1003).astype('float32'); y=rng.normal(size=1003).astype('float32')
z,bytes_add=add(x,y,128)
assert np.allclose(z,x+y)
print('programas:',(1003+127)//128,'carriles vacíos:',8*128-1003,'bytes:',bytes_add)
[ ]Transpose and softmax in the interpreterBrowser
def transpose(x,tile):
    rows,cols=x.shape; a=Memory(x.copy()); out=Memory(np.zeros(cols*rows,dtype=x.dtype))
    def kernel(pr,pc):
        r=pr*tile+np.arange(tile)[:,None]; c=pc*tile+np.arange(tile)[None,:]
        rr=np.broadcast_to(r,(tile,tile)); cc=np.broadcast_to(c,(tile,tile))
        mask=(rr<rows)&(cc<cols)
        out.store(cc*rows+rr,a.load(rr*cols+cc,mask),mask)
    launch(((rows+tile-1)//tile,(cols+tile-1)//tile),kernel)
    return out.a.reshape(cols,rows),a.read+out.written

def softmax_rows(x,block):
    rows,cols=x.shape
    if block<cols: raise ValueError('la fila debe caber en el bloque')
    a=Memory(x.copy()); out=Memory(np.zeros_like(x))
    def kernel(row):
        c=np.arange(block); mask=c<cols
        z=a.load(row*cols+c,mask,other=-np.inf)
        e=np.exp(z-np.max(z)); e/=np.sum(e)
        out.store(row*cols+c,e,mask)
    launch((rows,),kernel)
    return out.a.reshape(x.shape),a.read+out.written

a=rng.normal(size=(37,51)).astype('float32')
t,bt=transpose(a,16); sm,bs=softmax_rows(a,64)
reference=np.exp(a-a.max(1,keepdims=True)); reference/=reference.sum(1,keepdims=True)
assert np.array_equal(t,a.T) and np.allclose(sm,reference,atol=1e-7)
print('bytes transposición:',bt,'softmax:',bs,'error máximo:',np.max(np.abs(sm-reference)))

In the first cell, 10031003 elements with block 128 need eight programs and 21 masked lanes. Two reads and one FP32 write total 1003⋅12=120361003\cdot12=12036 bytes. The 37×5137\times51 matrix uses 37⋅51⋅8=1509637\cdot51\cdot8=15096 bytes for one read and one write in each of the two examples. These are not physical GPU transactions.

[ ]Sector model per warpBrowser
def sectors(offsets,mask,itemsize=4,segment=32,warp=32):
    offsets=np.asarray(offsets).ravel(); mask=np.asarray(mask,dtype=bool).ravel()
    return sum(len(set((offsets[i:i+warp][mask[i:i+warp]]*itemsize//segment).tolist()))
               for i in range(0,len(offsets),warp))
lane=np.arange(32)
print('contiguo:',sectors(lane,lane<32),'stride 4:',sectors(4*lane,lane<32))

The model counts four 32-byte sectors for 32 contiguous, aligned FP32 reads, versus 16 at stride 4. It assumes an aligned base and one transaction per distinct sector, with no cache or combining across warps. A profiler and the actual architecture determine which traffic reaches memory.

For a contiguous 32×3232\times32 matrix, the next control compares two idealized orders. The naive one assigns a warp to each input row: it reads contiguously but writes a scattered output column. The tiled version assumes values are rearranged in nearby memory after loading and each warp writes a contiguous output row. The count includes only global sectors, not rearrangement or synchronization cost. The compiler does not automatically guarantee this pattern for every kernel.

[ ]Transpose sectors, two ordersBrowser
c=np.arange(32); mask=c<32
read=sum(sectors(r*32+c,mask) for r in range(32))
naive_write=sum(sectors(c*32+r,mask) for r in range(32))
tiled_write=sum(sectors(r*32+c,mask) for r in range(32))
print('lecturas:',read,'escrituras ingenuas:',naive_write,'escrituras reordenadas:',tiled_write)
assert (read,naive_write,tiled_write)==(128,1024,128)

Local lab: real Triton

You need PyTorch and Triton in a CUDA-compatible Linux environment. On Windows you can use WSL2; this run used Ubuntu with PyTorch 2.11.0+cu128, Triton 3.6.0, and an RTX 3060. The following measurements concern that GPU. These cells install nothing. The addition tutorial explains grids and masks; the softmax tutorial develops row reduction.

In this environment the cell’s virtual name contains non-ASCII characters, and the ptxas version rejects that name in line information. Before importing Triton, TRITON_DISABLE_LINE_INFO=1 is enabled, an option documented by Triton that omits this information from compiled code. The consequence is losing that debugging information; in a file with a compatible ASCII path you can omit the option to retain it. This does not change operations or inputs.

[ ]Addition, fusion and two softmax kernelsLocal GPU
import os
os.environ['TRITON_DISABLE_LINE_INFO']='1'
import json, torch, triton, triton.language as tl
import triton.testing
import torch.nn.functional as F

@triton.jit
def add_kernel(X,Y,O,N,SX:tl.constexpr,SY:tl.constexpr,B:tl.constexpr):
    i=tl.program_id(0)*B+tl.arange(0,B); mask=i<N
    x=tl.load(X+i*SX,mask,other=0); y=tl.load(Y+i*SY,mask,other=0)
    tl.store(O+i,x+y,mask)

@triton.jit
def fused(X,Bias,O,Keep,N,P:tl.constexpr,SEED:tl.constexpr,B:tl.constexpr):
    i=tl.program_id(0)*B+tl.arange(0,B); mask=i<N
    x=tl.load(X+i,mask,other=0).to(tl.float32)
    bias=tl.load(Bias+i,mask,other=0).to(tl.float32)
    z=x+bias
    t=0.7978845608028654*(z+0.044715*z*z*z)
    gelu=0.5*z*(1+2/(1+tl.exp(2*(-t)))-1)
    keep=tl.rand(SEED,i)>=P
    tl.store(O+i,tl.where(keep,gelu/(1-P),0),mask)
    tl.store(Keep+i,keep,mask)

@triton.jit
def row_softmax(X,O,N,XR:tl.constexpr,XC:tl.constexpr,OR:tl.constexpr,OC:tl.constexpr,B:tl.constexpr):
    row=tl.program_id(0); c=tl.arange(0,B); mask=c<N
    x=tl.load(X+row*XR+c*XC,mask,other=-float('inf')).to(tl.float32)
    ex=tl.exp(x-tl.max(x,0)); y=ex/tl.sum(ex,0)
    tl.store(O+row*OR+c*OC,y,mask)

@triton.jit
def long_softmax(X,O,N:tl.constexpr,XR:tl.constexpr,XC:tl.constexpr,OR:tl.constexpr,OC:tl.constexpr,B:tl.constexpr):
    row=tl.program_id(0); c=tl.arange(0,B)
    maximum=tl.full((),-float('inf'),tl.float32)
    for start in range(0,N,B):
        k=start+c
        x=tl.load(X+row*XR+k*XC,k<N,other=-float('inf')).to(tl.float32)
        maximum=tl.maximum(maximum,tl.max(x,0))
    denom=tl.full((),0,tl.float32)
    for start in range(0,N,B):
        k=start+c
        x=tl.load(X+row*XR+k*XC,k<N,other=-float('inf')).to(tl.float32)
        denom+=tl.sum(tl.exp(x-maximum),0)
    for start in range(0,N,B):
        k=start+c
        x=tl.load(X+row*XR+k*XC,k<N,other=-float('inf')).to(tl.float32)
        tl.store(O+row*OR+k*OC,tl.exp(x-maximum)/denom,k<N)

@triton.autotune(configs=[triton.Config({},num_warps=w,num_stages=s)
                         for w in (2,4,8) for s in (2,3)],key=['N'])
@triton.jit
def tuned(X,O,N,XR:tl.constexpr,XC:tl.constexpr,OR:tl.constexpr,OC:tl.constexpr,B:tl.constexpr):
    row=tl.program_id(0); c=tl.arange(0,B); mask=c<N
    x=tl.load(X+row*XR+c*XC,mask,other=-float('inf')).to(tl.float32)
    ex=tl.exp(x-tl.max(x,0))
    tl.store(O+row*OR+c*OC,ex/tl.sum(ex,0),mask)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The dropout kernel uses tl.rand(seed, índice). The same seed reproduces the same mask for that indexing; it does not promise to reproduce PyTorch generator bits. To compare values, we save the generated mask and apply it to the reference. The dropout documentation explains generation by index. The test uses two views with different strides and transposed matrices; it also checks rows longer than the three-pass version’s block.

[ ]Check results and stridesLocal GPU
assert torch.cuda.is_available()
torch.manual_seed(5)
device='cuda'
a=torch.randn(2006,device=device)[::2]; b=torch.randn(3009,device=device)[::3]
out=torch.empty(a.numel(),device=device)
add_kernel[(triton.cdiv(a.numel(),128),)](a,b,out,a.numel(),a.stride(0),b.stride(0),128)
torch.testing.assert_close(out,a+b)
x=torch.randn(1003,device=device); bias=torch.randn_like(x)
out=torch.empty_like(x); keep=torch.empty_like(x,dtype=torch.uint8)
fused[(triton.cdiv(x.numel(),128),)](x,bias,out,keep,x.numel(),.2,33,128)
reference=F.gelu(x+bias,approximate='tanh')*keep/(1-.2)
torch.testing.assert_close(out,reference,rtol=2e-5,atol=2e-6)
out2=torch.empty_like(x); keep2=torch.empty_like(keep)
fused[(triton.cdiv(x.numel(),128),)](x,bias,out2,keep2,x.numel(),.2,33,128)
assert torch.equal(keep,keep2) and torch.equal(out,out2)
for length in (127,513,4097):
    x=torch.randn(length,7,device=device).T
    y=torch.full_like(x,float('nan'),memory_format=torch.contiguous_format)
    long_softmax[(x.shape[0],)](x,y,length,*x.stride(),*y.stride(),256)
    torch.testing.assert_close(y,torch.softmax(x,dim=1),rtol=2e-5,atol=2e-6)
    row_softmax[(x.shape[0],)](x,y,length,*x.stride(),*y.stride(),triton.next_power_of_2(length))
    torch.testing.assert_close(y,torch.softmax(x,dim=1),rtol=2e-5,atol=2e-6)
print('suma con strides, fusión y ambas softmax correctas en',torch.cuda.get_device_name())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The one-row version needs a power-of-two block at least as large as the row length; that can consume too many resources for very long rows. The three-pass variant uses block 256 with length 4097 and keeps the reduction numerically stable. Every row in these examples is nonempty. A fully masked row would need an explicit policy to avoid −∞−(−∞)-\infty-(-\infty).

[ ]Autotuning and measurement by shapeLocal GPU
results=[]
for length in (128,512,1024,4096):
    x=torch.randn(256,length,device='cuda'); y=torch.empty_like(x)
    for block in (triton.next_power_of_2(length),2*triton.next_power_of_2(length)):
        for warps in (2,4,8):
            def call():
                row_softmax[(x.shape[0],)](x,y,length,*x.stride(),*y.stride(),block,num_warps=warps)
            call()
            torch.testing.assert_close(y,torch.softmax(x,dim=1),rtol=2e-5,atol=2e-6)
            ms=triton.testing.do_bench(call,warmup=20,rep=50,return_mode='median')
            results.append(dict(length=length,block=block,warps=warps,ms=ms))
            print('longitud:',length,'bloque:',block,'warps:',warps,'mediana ms:',ms)
    tuned[(x.shape[0],)](x,y,length,*x.stride(),*y.stride(),triton.next_power_of_2(length))
    torch.testing.assert_close(y,torch.softmax(x,dim=1),rtol=2e-5,atol=2e-6)
    print('autotune:',tuned.best_config)
with open('triton-landscape.json','w',encoding='utf-8') as f:
    json.dump(results,f,indent=2)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The figure uses an earlier run of that cell: 256 FP32 rows, four lengths, and six combinations per length. Observed minima change with length, but ties occur and load from other processes alters results. The autotuner also tries two num_stages values; its choice may differ from the lowest displayed cell because they are different measurements. Your output replaces that evidence with your device’s, but does not change the packaged figure.

[ ]Fusion versus eager and torch.compileLocal GPU
n=16*1024*1024
x=torch.randn(n,device='cuda'); bias=torch.randn_like(x); y=torch.empty_like(x)
keep=torch.empty_like(x,dtype=torch.uint8)
def fused_call():
    fused[(triton.cdiv(n,1024),)](x,bias,y,keep,n,.2,33,1024)
fused_call()
def eager(a,b,k): return F.gelu(a+b,approximate='tanh')*k/(1-.2)
expected=eager(x,bias,keep)
torch.testing.assert_close(y,expected,rtol=2e-5,atol=2e-6)
compiled=torch.compile(eager)
torch.testing.assert_close(compiled(x,bias,keep),expected,rtol=2e-5,atol=2e-6)
src=torch.randn_like(x); dst=torch.empty_like(x)
copy_ms=triton.testing.do_bench(lambda:dst.copy_(src),warmup=20,rep=50,return_mode='median')
for name,fn in [('triton',fused_call),('eager',lambda:eager(x,bias,keep)),('compile',lambda:compiled(x,bias,keep))]:
    ms=triton.testing.do_bench(fn,warmup=20,rep=50,return_mode='median')
    print(name,'mediana ms:',ms)
print('referencia de copia, GB/s:',2*n*4/(copy_ms*1e6))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The Triton kernel computes and writes the mask; the PyTorch functions receive that mask already calculated. The comparison verifies arithmetic with the same mask, but does not charge eager or torch.compile for generating randomness. Count 13 logical bytes per element in this example’s Triton kernel: two FP32 reads, one FP32 write, and a one-byte write. Dividing those bytes by time gives model-effective bandwidth, not a direct measurement of physical traffic. do_bench excludes warm-up and returns milliseconds; one campaign under load cannot establish which version always wins.

Debug before compiling

The Triton interpreter executes each program sequentially using equivalent CPU operations. TRITON_INTERPRET=1 must be set before importing Triton, so this cell starts a subprocess and saves a small Python file. The interpreter helps inspect indices and masks; it does not simulate GPU races, performance, instructions, or synchronization. Here its addition is compared with CPU PyTorch.

[ ]Run the Triton interpreter on CPULocal GPU
import os, sys, subprocess
from pathlib import Path
source = '''import torch
import triton
import triton.language as tl
@triton.jit
def add(X,Y,O,N,B:tl.constexpr):
    i=tl.program_id(0)*B+tl.arange(0,B)
    mask=i<N
    tl.store(O+i,tl.load(X+i,mask,other=0)+tl.load(Y+i,mask,other=0),mask)
torch.manual_seed(5)
x=torch.randn(1003); y=torch.randn(1003); out=torch.empty_like(x)
add[(triton.cdiv(x.numel(),128),)](x,y,out,x.numel(),128)
torch.testing.assert_close(out,x+y)
print('intérprete CPU: suma correcta; programas:',triton.cdiv(x.numel(),128))
'''
path=Path('triton_interprete.py'); path.write_text(source,encoding='utf-8')
env=os.environ.copy(); env['TRITON_INTERPRET']='1'; env['PYTHONUTF8']='1'
result=subprocess.run([sys.executable,str(path)],env=env,text=True,encoding='utf-8',capture_output=True,check=True)
print(result.stdout.strip())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Do not confuse Dynamo graph capture with the kernel: torch.compile can generate or select fused code, but can also recompile when shapes change. A fair test separates initial compilation from later runs, verifies results, controls the seed, and synchronizes before reading times. The effect of operator fusion and compilation and CUDA graph options depends on version and actual shapes. Continually changing a tl.constexpr value can create many specializations.

Exercises

Numeric
For N = 1000000 and BLOCK_SIZE = 1024, how many lanes are masked in the last program?
Numeric
With N = 1000000 and BLOCK_SIZE = 1024, how many program instances does the one-dimensional grid launch?
Numeric
A kernel reads two FP16 tensors and writes another, each with 64 million elements, in 2.0 ms. What is the effective bandwidth in decimal GB/s?
Quiz
Which statements correctly describe the division of responsibilities?

More than one answer may be correct.

Proof
Prove: Subtracting the maximum preserves softmax and avoids evaluating large positive exponentials for a nonempty finite row.
0
Let z be a finite row and m its maximum.

Step 1 of 3. What factor appears in every numerator after shifting?

Code
Implement transpose_blocks(x, tile) with NumPy: for each input tile copy values to their transposed positions, including incomplete edges. Return a new matrix and do not use the full transpose as the implementation.
import numpy as np
def transpose_blocks(x, tile):
  pass
Shift+Enter to run
Code
Implement the Triton kernel softmax_long(X, O, N, XR, XC, OR, OC, B), one program per row, using three passes over blocks of B: global maximum, exponential sum, and output. N and B are constexpr; strides are in elements. Tests use noncontiguous inputs and rows exceeding B.
import triton
import triton.language as tl
@triton.jit
def softmax_long(X,O,N:tl.constexpr,XR:tl.constexpr,XC:tl.constexpr,OR:tl.constexpr,OC:tl.constexpr,B:tl.constexpr):
  pass
Shift+Enter to run
Key idea
A block kernel combines indices, masks, and reduction. Validate every shape and stride before measuring, and distinguish logical bytes, physical traffic, compilation, and execution time.