# How I added dilation to average pooling in Burn

Imagine moving a trained model into a new framework and getting numbers that are quietly wrong, with no error. That was the risk in Burn for ONNX models that used average pooling with a setting called dilation: on the 2D import path, the dilation was simply dropped.

Burn is a deep learning framework written in Rust. antimora filed [issue #6148](https://github.com/tracel-ai/burn/issues/6148) asking for dilation in average pooling, I picked it up, and it was merged in [tracel-ai/burn#6235](https://github.com/tracel-ai/burn/pull/6235). Max pooling in Burn already had the option, so most of the work was following its path.

## Pooling and dilation in plain words

A tensor is a grid of numbers, like the pixels of an image. A pooling layer shrinks that grid. It slides a small window, say 2 by 2, across the grid, and at each spot keeps one number: max pooling keeps the biggest, average pooling keeps the average.

Dilation spreads the window out. With a dilation of 2, a 2 by 2 window doesn't read four neighbours. It reads every other row and column, so it covers a 3 by 3 area while still reading only four numbers. Think of a survey that knocks on every second house along a street instead of four houses in a row: the same number of doors, a wider reach.

## Why it mattered

ONNX is a common file format for sharing trained models between tools, and burn-onnx is the project that imports those files into Burn. ONNX's `AveragePool` operation has had a `dilations` setting since opset 19, a version of ONNX's list of operations. Burn had nowhere to put it. As the issue explained, the 2D import dropped the dilation and gave wrong output with no error, and the new 3D import would have to reject such models. PyTorch's average pooling has no dilation, so for now ONNX import is the only user.

The issue also spelled out exactly what the feature should mean:

- window element `k` reads input position `start + k * dilation`;
- `count_include_pad`, which decides whether padding cells around the edge count when dividing for the average, counts the spread out window steps that land in padding;
- `ceil_mode`, which rounds the output size up, uses the spread out window size, `(kernel - 1) * dilation + 1`.

## Where dilation was missing

Pretty much everywhere. The options type had no field for it, the backend methods had no argument for it, and the kernels, the low level loops that do the actual math, had it fixed at 1. The CPU kernel, called Flex, even said so in a comment:

```rust
// Avg pool doesn't use dilation in typical implementations
let dilation_d = 1;
let dilation_h = 1;
let dilation_w = 1;
```

So the job was to carry one new value through every layer, along max pooling's path.

## Following max pooling's path

It starts with the public options type, where users set it (doc comment left out):

```rust
pub fn with_dilation(mut self, dilation: [usize; N]) -> Self {
    self.dilation = dilation.map(|d| check_nonzero(d, "dilation must be non-zero"));
    self
}
```

It takes one dilation per direction and refuses zero. The default is 1, so existing code pools exactly as before. From there, the value passes through each layer of Burn: the tensor API, the backend trait, automatic gradients, the fusion layer that merges operations, the router, and finally the CPU (Flex) and GPU (CubeCL) kernels. In every function I put `dilation` right after `padding`, the same spot max pooling uses, so the two read alike. That came to 24 files.

In the Flex kernel, the math change itself is small. Each step through the window now jumps by the dilation:

```rust
// safe: valid range guarantees no underflow
let id = od * stride_d + kd * dilation_d - pad_d;
```

`id` is the input position being read: the output position times the stride, plus the window step times the dilation, minus the padding. Max pooling already had a helper that works out which window steps land inside the input, dilation included. Average pooling had its own copy of that formula without it, so I renamed max pooling's helper to `valid_kernel_range` and used it for both.

This is a breaking change: some existing code must change to keep compiling. `AvgPoolOptions` has public fields, so code that builds it field by field now needs `dilation: [1; N]`, and third party backends get a new argument. The changelog says both, and the PR title is `feat(tensor)!`, where the `!` marks the break.

## The GPU 2D path

On the GPU side, Burn's 2D average pooling calls into CubeK, a separate library, and CubeK's 2D average pooling had no dilation. Burn has its own 3D average pooling kernel, which this PR also teaches dilation. So for a dilated 2D pool only, I turn the input into a 3D one with a depth of one and run that. It's like treating a single photo as a one frame video so you can use the video tool on it:

```rust
if dilation != [1, 1] {
    // The CubeK kernel has no dilation; pool as a 3D input of depth one instead.
    let x = reshape(x, Shape::new([batch_size, channels, 1, in_h, in_w]));
    let output = avg_pool3d(
        x,
        [1, kernel_size[0], kernel_size[1]],
        // trimmed: stride and padding
        [1, dilation[0], dilation[1]],
        // trimmed
    );
    // trimmed: reshape the result back to 2D and return it
}
```

Undilated 2D pooling still goes through CubeK, unchanged.

## Testing it

Where ONNX had reference test cases, I used them. This one is ONNX's `test_averagepool_2d_dilations`, on a 4 by 4 input holding the numbers 1 to 16 (trimmed):

```rust
let output = avg_pool2d(
    x,
    AvgPoolOptions::new([2, 2])
        .with_stride([1, 1])
        .with_dilation([2, 2])
        .with_ceil_mode(true),
);

TestTensor::<4>::from([[[[6.0, 7.0], [10.0, 11.0]]]])
```

The first output averages 1, 3, 9 and 11, the four corners of the top left 3 by 3 area, which gives 6. There are new forward tests for 1D, 2D and 3D, and gradient tests for 2D and 3D, in both `count_include_pad` modes. They pass on Flex and on Metal, the GPU backend on macOS. With the Flex kernels forced back to a dilation of 1, all the new tests fail.

One thing I left alone on purpose: ceil mode together with `count_include_pad`. Burn counts only the window steps inside the input plus its padding, like PyTorch. The ONNX reference also counts steps that fall past the padding, with or without dilation. That difference already existed, so I noted it in the PR and kept Burn's convention.

## What review added

laggui approved it with a note on the GPU fallback: it copies inputs with more than one channel back into a different memory layout (NHWC to NCHW, two orders for storing image data), which undoes a layout optimization and adds a full copy of the tensor. laggui marked it non blocking, said they would handle it in a separate CubeK PR, and linked [tracel-ai/cubek#974](https://github.com/tracel-ai/cubek/pull/974), which adds dilation to average pooling inside CubeK itself and was merged the same day. laggui merged the Burn PR on 27 October 2026.

Thanks antimora for an issue with the meaning written down, and laggui for the review and the CubeK follow up.

## What I'm keeping from this one

When a feature already exists next door, copy its path exactly. Max pooling's dilation showed me where every argument had to go.

And a fallback can be correct and still cost something. Mine gave the right numbers but threw away a layout optimization, and the proper fix belonged in CubeK.

Do you use dilated pooling in your own models, or do you mostly meet it in imported ONNX files? I'd like to know.

