---
title: "Max and average pooling on the GPU in C#"
url: https://recursiveai.org/onegpu/cookbook/pool-tensors-on-gpu/
description: "Max and average pooling on the GPU in C#. Includes buffer setup, real Vulkan output and a runnable .NET 10 example."
version: "1.0.0"
---

# Max and average pooling on the GPU in C#

**OneGpu** is a free, open-source GPU compute library for .NET from Recursive AI. MIT or Apache-2.0, no bundled native binaries.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneGpu.Backends) · [GitHub](https://github.com/recursive-ai-oss/onegpu-csharp) · [Docs](https://recursiveai.org/onegpu/docs/) · [Download example (.zip)](https://recursiveai.org/onegpu/cookbook/pool-tensors-on-gpu/pool-tensors-on-gpu.zip)

Pooling takes a maximum or average over each tensor window. This example requires Vulkan 1.3.

```shell
dotnet add package RecursiveAI.OneGpu.Backends
dotnet add package RecursiveAI.OneGpu.Kernels
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneGpu;
using RecursiveAI.OneGpu.Kernels;

using var device = GpuBackends.CreateDevice(
    new GpuDeviceOptions { Adapter = "discrete" });
using var input = device.CreateBuffer<float>([1, 2, 3, 4]);
using var output = device.CreateBuffer<float>(1);
using var pool = new PoolKernels(device);
var problem = new PoolProblem(1, 1, 2, 2, 2, 2);
var result = new float[1];
foreach (var kind in new[] { GpuPoolKind.Max, GpuPoolKind.Average })
{
    var commands = device.BeginCommands();
    pool.Encode(commands, problem, kind, input, output);
    device.Submit(commands);
    await output.ReadAsync(result);
    Console.WriteLine($"{kind}: {result[0]}");
    float expected = kind == GpuPoolKind.Max ? 4 : 2.5f;
    if (result[0] != expected) throw new Exception("Pool mismatch");
}
```

Unzip [the example](https://recursiveai.org/onegpu/cookbook/pool-tensors-on-gpu/pool-tensors-on-gpu.zip), then `dotnet run`.

Prints:

```text
Max: 4
Average: 2.5
```

## The full program

The input is NCHW `[1, 1, 2, 2]`, with rows `[1, 2]` and `[3, 4]`. Invalid geometry or undersized buffers throw `GpuKernelShapeException` before recording.

```csharp
using RecursiveAI.OneGpu;
using RecursiveAI.OneGpu.Kernels;

using var device = GpuBackends.CreateDevice(
    new GpuDeviceOptions { Adapter = "discrete" });
using var input = device.CreateBuffer<float>([1, 2, 3, 4]);
using var output = device.CreateBuffer<float>(1);
using var pool = new PoolKernels(device);
var problem = new PoolProblem(1, 1, 2, 2, 2, 2);
var result = new float[1];
foreach (var kind in new[] { GpuPoolKind.Max, GpuPoolKind.Average })
{
    var commands = device.BeginCommands();
    pool.Encode(commands, problem, kind, input, output);
    device.Submit(commands);
    await output.ReadAsync(result);
    Console.WriteLine($"{kind}: {result[0]}");
    float expected = kind == GpuPoolKind.Max ? 4 : 2.5f;
    if (result[0] != expected) throw new Exception("Pool mismatch");
}
Console.WriteLine("Expected max and average: passed");
Console.WriteLine($"{device.Backend}: {device.Adapter.Name}");
```

Output from an NVIDIA GeForce RTX 4070 using Vulkan:

```text
Max: 4
Average: 2.5
Expected max and average: passed
Vulkan: NVIDIA GeForce RTX 4070
```

## Variations

### Padding and the average divisor

Append this to the full program:

```csharp
problem.PadTop = 1;
problem.PadLeft = 1;
using var padded = device.CreateBuffer<float>(4);
foreach (var kind in new[] { GpuPoolKind.Max,
    GpuPoolKind.Average, GpuPoolKind.AverageIncludePad })
{
    var pass = device.BeginCommands();
    pool.Encode(pass, problem, kind, input, padded);
    device.Submit(pass);
    var values = new float[4];
    await padded.ReadAsync(values);
    Console.WriteLine($"{kind}: {string.Join(", ", values)}");
}
Console.WriteLine($"Shape: [1, 1, {problem.OutHeight}, {problem.OutWidth}]");
```

Additional output:

```text
Max: 1, 2, 3, 4
Average: 1, 1.5, 2, 2.5
AverageIncludePad: 0.25, 0.75, 1, 2.5
Shape: [1, 1, 2, 2]
```

## Related recipes

- [Compute softmax on the GPU in C#](https://recursiveai.org/onegpu/cookbook/compute-softmax-on-gpu/)
- [Gather embedding rows on the GPU in C#](https://recursiveai.org/onegpu/cookbook/gather-embedding-rows-on-gpu/)
- [Dynamic tensor quantization on the GPU in C#](https://recursiveai.org/onegpu/cookbook/quantize-tensors-on-gpu/)

## The short answer

These console examples use Vulkan on Linux or Windows with a Vulkan 1.3 driver.

Use `PoolKernels` with a `PoolProblem` describing an NCHW tensor: batch, channels, height and width. `GpuPoolKind.Max` takes a window’s maximum; `Average` divides by its valid input taps; `AverageIncludePad` also counts taps within the configured padding. These are tensor operations, not image-file filters.

The example input is one batch, one channel and two rows, `[1, 2]` and `[3, 4]`. A 2 × 2 unpadded window gives maximum `4`. The padded variation makes the difference between the average modes visible without needing a large tensor or a model file.

## What is the difference between max pooling and average pooling?

Max pooling selects the largest valid value. Average pooling adds the valid values and divides by a count. With no padding, the example’s single window contains four values: its maximum is `4` and its average is `2.5`. Padding changes the divisor for average pooling only when you choose the include-padding mode.

In the variation, top and left padding are one. The top-left output window contains only the input value `1`, plus three padded positions. `Average` returns `1`; `AverageIncludePad` returns `0.25`. The bottom-right window is fully inside the tensor, so both modes give `2.5`. Max pooling does not treat the padded positions as candidate zero values: it takes the maximum of taps inside the input.

Use the operation specified by your network rather than substituting one pooling kind for another. They do not preserve the same information. OneGpu does not provide the MaxPool indices output; this recipe returns values only. The library documents these rules under [pooling and resize](https://recursiveai.org/onegpu/docs/conv/#pooling-and-resize).

## Is max pooling always 2x2?

No. `PoolProblem` takes independent kernel height and width values. It also has independent strides and dilations for each direction, plus top, left, bottom and right padding. The constructor defaults strides and dilations to one; it does not default the stride to the window size. Set these explicitly when matching a model exported from a framework with different defaults.

Batch and channel counts remain unchanged. Windows operate within each spatial plane, so a channel is not pooled together with its neighbor. The output remains dense NCHW. Both float32 and Half buffers are supported; start with float32 to keep the fixture and readback types straightforward.

## How do I calculate max pooling output size?

Use `problem.OutHeight` and `problem.OutWidth` before allocating the result. For each spatial dimension, the usual floor-mode calculation is `floor((input + padBegin + padEnd - effectiveKernel) / stride) + 1`, where `effectiveKernel = dilation * (kernel - 1) + 1`. A window that cannot fit the padded input produces an extent of zero.

`CeilMode` switches to ceiling division, but a final window starting inside the end padding is dropped. Average-include-padding counts taps inside the padded input, not taps beyond that padding introduced by ceil mode. Allocate batch × channels × output height × output width elements, and keep all buffers on the same device.

## What is global average pooling?

Global pooling reduces each entire spatial plane to one output, rather than sliding a local window. `PoolKernels.EncodeGlobal` provides global average and global maximum operations. Use it when the required output has one value per batch/channel plane, not when you need a smaller spatial feature map. Empty local maximum windows produce the lowest finite value of the element type; empty average windows produce NaN. Max pooling skips NaN taps unless every tap is NaN. These edge rules matter if padding creates windows without any input samples.
