Skip to content
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 122 additions & 2 deletions cv-utils/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,128 @@
---
license: apache-2.0
tags:
- kernels
- kernels
---

# cv_utils

This is a build for some kernel utilities for computer vision, including generic_nms and connected_components
Kernels for computer vision pre- and post-processing.

| function | computes | backend |
|---|---|---|
| `cc_2d` | connected-component labels of binary masks, optionally with component areas | CUDA |
| `connected_component_areas` | the component area of every pixel of a mask of any height and width | CUDA |
| `generic_nms` | non-maximum suppression of boxes | CUDA |
| `resize_normalize` | antialiased resize to one size per image, center crop, rescale and normalize of uint8 images | Triton |
| `resize_normalize_patchify` | the same, written in the Qwen2-VL `pixel_values` patch layout, for images and videos | Triton |
| `upsample_argmax` | the class of every pixel of bilinearly upsampled segmentation logits, without storing the upsampled logits | Triton |

## Usage

```python
from kernels import get_kernel

cv_utils = get_kernel("kernels-community/cv-utils", version=2)
pixel_values = cv_utils.resize_normalize(images, [(224, 224)] * len(images), image_mean, image_std, 1 / 255, "bicubic")
```

`transformers` image processors call these kernels when loaded with `use_kernels=True`.

## How it works

The resize is separable. A horizontal pass resizes the width of every image into a scratch buffer, and a vertical pass
resizes the height, rescales, normalizes and writes the output. Images of different sizes share each launch. The
horizontal pass is skipped when no image changes width.

The per-image sizes, offsets and normalized filter weights depend only on the shapes and sizes of the batch. They are
computed once per batch layout, with one copy to the device and one launch, and cached. A call with a known layout
then launches only the two passes.

The filter weights follow `torch.nn.functional.interpolate(..., antialias=True)`. By default (`round_to_uint8=True`),
each pass rounds to uint8, like torchvision on uint8 tensors.

`resize_normalize_patchify` takes uint8 `(T, C, H, W)` inputs, with `T=1` for an image, and one target size
per input. It writes each value directly at its place in the patch layout, in `block_size x block_size` blocks of
patches, and returns `grid_thw` as an int64 tensor.

### `upsample_argmax`

Semantic segmentation models predict logits at a low resolution, for example 150 classes at 128x128. The class map is
`interpolate(logits, size=(H, W), mode="bilinear").argmax(0)`. In torch, that stores every class at full size before
the argmax: 150 x 480 x 640 float32 values, or 184 MB for one photo. The kernel computes each output pixel from 4
logits per class and keeps only the best class. It writes one int64 per pixel, which is 2.4 MB for the same photo.

One output pixel, 2x2 logits upsampled to 4x4, output pixel `(1, 2)`:

```
source position: row = (1 + 0.5) * 2/4 - 0.5 = 0.25 column = (2 + 0.5) * 2/4 - 0.5 = 0.75

weights of the 4 neighbors class 0 logits class 1 logits
(1-0.25)(1-0.75) (1-0.25)(0.75) 2 0 0 1
(0.25)(1-0.75) (0.25)(0.75) 1 3 2 1
= 0.1875 0.5625
0.0625 0.1875

class 0: 0.1875*2 + 0.5625*0 + 0.0625*1 + 0.1875*3 = 1.000 <- best so far, class 0
class 1: 0.1875*0 + 0.5625*1 + 0.0625*2 + 0.1875*1 = 0.875 not better, keep class 0
```

The loop over classes keeps only the best value and its class. The upsampled logits are never stored. When both sides
grow at least 2x, a program computes a 32x64 output tile for each class as `row_weights @ patch @ column_weights`
on tensor cores, where `patch` is the block of logits under the tile.

A batch has one output size per image. The work is cut into tiles of output pixels: 256 pixels, or 32x64 on tensor
cores. All tiles of all images go to one launch. For example, with images of 4, 2 and 3 tiles:

```
tiles of the launch 0 1 2 3 | 4 5 | 6 7 8
image 0 0 0 0 | 1 1 | 2 2 2
last tile + 1 per image 4 | 6 | 9

program 7: images whose tiles end at or before 7 -> 2 (ends 4 and 6) -> image 2
first tile of image 2 is 6 -> tile 1 of image 2
```

The table of tile ends and the output sizes and offsets of each image are copied once and cached per batch layout.
When all images have the same output size, as with one image, there is no table: the launch grid has one row per
image and the output size is a kernel argument.

A photo of 480x640 is 150 tiles on tensor cores, fewer than one wave on an A100. With one launch per image, most of
the GPU waits at the end of each launch. With one launch per batch, the tiles of the next image fill it.

A100, real logits, 16 COCO photos of different sizes, median ms:

| model | one launch per image | one launch per batch | speedup |
|---|---|---|---|
| SegFormer ADE20K (150 classes) | 1.36 | 0.86 | 1.58x |
| RF-DETR-Seg large (91 classes) | 0.83 | 0.43 | 1.92x |
| SegFormer Cityscapes (19 classes) | 0.74 | 0.46 | 1.63x |
| Mask2Former ADE20K (float32 path) | 2.71 | 2.03 | 1.34x |

Batches with one output size run at the same speed as before.

## Limitations

- `upsample_argmax` runs on tensor cores in float16 when both sides are upsampled at least 2x. Then a few pixels
at near-ties between two classes can get another class than in float32 (about 1e-4 of pixels on ADE20K, with no
change in mIoU). Smaller upsampling factors run in float32.
- Inputs are uint8 `(C, H, W)` tensors on one CUDA device, with the same channel count.
- Bilinear and bicubic only. The output is float32.
- `resize_normalize` takes the resized size of each image from the caller, and an optional crop no larger than
any of them. It returns one `(C, H, W)` tensor per image.
- `resize_normalize_patchify` needs target sizes that are multiples of `patch_size * block_size`.
- With `round_to_uint8=True`, results can differ from torch by one uint8 level where a value falls on a rounding
boundary.
- The metadata of a batch layout is cached, up to 1024 layouts. The key is the tuple of all sizes in the batch, so a
batch of photos with different sizes almost never hits the cache. A miss costs one extra copy to the device, plus
one extra launch for the resize. Measured on an A100:

| call | known layout | new layout | reference |
|---|---|---|---|
| `resize_normalize`, 32 photos of different sizes | 0.73 ms | 0.78 ms | torchvision 6.3 ms |
| `resize_normalize`, 1 photo | 0.16 ms | 0.49 ms | torchvision 0.43 ms |
| `upsample_argmax`, 16 photos of different sizes | 0.86 ms | 1.14 ms | one launch per image 1.36 ms |
| `upsample_argmax`, 1 image | 0.13 ms | 0.15 ms | one launch per image 0.13 ms |

At batch 1 with a new size on every call, `resize_normalize` is about 13% slower than torchvision. `upsample_argmax`
keeps no device metadata when all output sizes are equal, so a new size there adds only about 0.02 ms on the CPU.
2 changes: 1 addition & 1 deletion cv-utils/build.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[general]
name = "cv-utils"
version = 1
version = 2
edition = 5
license = "Apache-2.0"
backends = ["cuda"]
Expand Down
4 changes: 4 additions & 0 deletions cv-utils/pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[pytest]

markers =
kernels_ci: mark test to run in kernels CI environment
13 changes: 12 additions & 1 deletion cv-utils/tests/test_cv_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import torch


cv_utils = kernels.get_kernel("kernels-community/cv-utils", version=1)
cv_utils = kernels.get_kernel("kernels-community/cv-utils", version=2)

pytestmark = pytest.mark.kernels_ci

Expand Down Expand Up @@ -237,6 +237,17 @@ def test_cc_2d_patterns():
check_cc(patterns)


@pytest.mark.parametrize("shape", [(1, 1, 5, 7), (2, 1, 30, 46), (1, 1, 63, 65)])
def test_connected_component_areas_any_size(shape):
g = torch.Generator().manual_seed(sum(shape))
mask = torch.rand(shape, generator=g) < 0.45
areas = cv_utils.connected_component_areas(mask.to(DEVICE))
assert areas.shape == mask.shape
for n in range(shape[0]):
_, sizes_ref = cc_ref(mask[n, 0].to(torch.uint8))
assert areas[n, 0].tolist() == sizes_ref


def test_cc_2d_non_zero_values_are_foreground():
inputs = torch.tensor([[[[0, 7], [255, 0]]]], dtype=torch.uint8)
labels, counts = cv_utils.cc_2d(inputs.to(DEVICE), True)
Expand Down
183 changes: 183 additions & 0 deletions cv-utils/tests/test_resize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
"""Tests for the cv-utils resize kernels, checked against `torch.nn.functional.interpolate`.

The whole suite is small and fast, so every test is part of the CI subset.
"""

import kernels
import pytest
import torch
import torch.nn.functional as F


cv_utils = kernels.get_kernel("kernels-community/cv-utils", version=2)

pytestmark = pytest.mark.kernels_ci

DEVICE = "cuda"

MEAN = [0.48145466, 0.4578275, 0.40821073]
STD = [0.26862954, 0.26130258, 0.27577711]


def random_images(sizes):
generator = torch.Generator().manual_seed(0)
return [
torch.randint(0, 256, (3, height, width), generator=generator, dtype=torch.uint8).to(DEVICE)
for height, width in sizes
]


def reference(image, size, resample, antialias=True):
resized = F.interpolate(image[None].float(), size=size, mode=resample, antialias=antialias, align_corners=False)[0]
return (resized / 255 - torch.tensor(MEAN, device=image.device)[:, None, None]) / torch.tensor(
STD, device=image.device
)[:, None, None]


def shortest_edge_size(height, width, shortest_edge):
if height <= width:
return shortest_edge, int(width * shortest_edge / height)
return int(height * shortest_edge / width), shortest_edge


@pytest.mark.parametrize("antialias", [True, False])
@pytest.mark.parametrize("resample", ["bilinear", "bicubic"])
@pytest.mark.parametrize(
"shortest_edge, crop_size", [(None, None), (None, (224, 224)), (256, (224, 224)), (256, None)]
)
def test_resize_normalize_matches_interpolate(antialias, resample, shortest_edge, crop_size):
images = random_images([(480, 640), (300, 300), (1024, 768)])
if shortest_edge is None:
sizes = [(256, 256)] * len(images)
else:
sizes = [shortest_edge_size(*image.shape[1:], shortest_edge) for image in images]
output = cv_utils.resize_normalize(
images, sizes, MEAN, STD, 1 / 255, resample, crop_size=crop_size, antialias=antialias, round_to_uint8=False
)
assert len(output) == len(images)
for image, size, result in zip(images, sizes, output):
expected = reference(image, size, resample, antialias)
crop_height, crop_width = crop_size or size
top, left = (size[0] - crop_height) // 2, (size[1] - crop_width) // 2
torch.testing.assert_close(
result, expected[:, top : top + crop_height, left : left + crop_width], atol=2e-3, rtol=0
)


@pytest.mark.parametrize(
"input_sizes, size",
[([(480, 640)] * 3, (256, 256)), ([(224, 224)] * 2, (224, 224)), ([(300, 224)] * 2, (224, 224))],
)
def test_resize_normalize_same_shape_batch(input_sizes, size):
images = random_images(input_sizes)
output = cv_utils.resize_normalize(
images, [size] * len(images), MEAN, STD, 1 / 255, "bicubic", round_to_uint8=False
)
for image, result in zip(images, output):
torch.testing.assert_close(result, reference(image, size, "bicubic"), atol=2e-3, rtol=0)


@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="needs two CUDA devices")
def test_resize_normalize_other_device():
images = [image.to("cuda:1") for image in random_images([(480, 640), (300, 300)])]
with torch.cuda.device(0):
output = cv_utils.resize_normalize(
images, [(256, 256)] * 2, MEAN, STD, 1 / 255, "bicubic", round_to_uint8=False
)
pixel_values, grid_thw = cv_utils.resize_normalize_patchify(
[image[None] for image in images], [(252, 336), (280, 280)], MEAN, STD, 1 / 255, "bicubic", 14, 2, 2
)
assert pixel_values.device == torch.device("cuda:1")
assert grid_thw.tolist() == [[1, 18, 24], [1, 20, 20]]
for image, result in zip(images, output):
assert result.device == torch.device("cuda:1")
torch.testing.assert_close(result, reference(image, (256, 256), "bicubic"), atol=2e-3, rtol=0)


def test_resize_normalize_patchify_matches_reference():
frames = random_images([(280, 420), (140, 140), (140, 140), (140, 140)])
inputs = [frames[0][None], torch.stack(frames[1:])]
target_sizes = [(224, 336), (112, 112)]
patch, merge, temporal = 14, 2, 2
pixel_values, grid_thw = cv_utils.resize_normalize_patchify(
inputs, target_sizes, MEAN, STD, 1 / 255, "bicubic", patch, merge, temporal, round_to_uint8=False
)

expected = []
for input_frames, target_size in zip(inputs, target_sizes):
clip = torch.stack([reference(frame, target_size, "bicubic") for frame in input_frames])
clip = torch.cat([clip, clip[-1:].expand(-clip.shape[0] % temporal, -1, -1, -1)])
grid_t, (height, width) = clip.shape[0] // temporal, clip.shape[-2:]
patches = clip.view(
grid_t, temporal, 3, height // patch // merge, merge, patch, width // patch // merge, merge, patch
)
expected.append(patches.permute(0, 3, 6, 4, 7, 2, 1, 5, 8).reshape(-1, 3 * temporal * patch * patch))
assert grid_thw.dtype == torch.int64
assert grid_thw.tolist() == [[1, 16, 24], [2, 8, 8]]
torch.testing.assert_close(pixel_values, torch.cat(expected), atol=2e-3, rtol=0)


@pytest.mark.parametrize("crop_size", [None, (200, 200)])
@pytest.mark.parametrize("resample", ["bilinear", "bicubic"])
def test_resize_normalize_rounds_like_two_uint8_passes(resample, crop_size):
images = random_images([(480, 640), (1024, 768)])
sizes = [(224, 224)] * len(images)
output = cv_utils.resize_normalize(images, sizes, MEAN, STD, 1 / 255, resample, crop_size=crop_size)
unrounded = cv_utils.resize_normalize(
images, sizes, MEAN, STD, 1 / 255, resample, crop_size=crop_size, round_to_uint8=False
)
mean = torch.tensor(MEAN, device=images[0].device)[:, None, None]
std = torch.tensor(STD, device=images[0].device)[:, None, None]
for image, result, unrounded_result in zip(images, output, unrounded):
wide = F.interpolate(image[None].float(), size=(image.shape[1], 224), mode=resample, antialias=True)
wide = wide.round().clamp(0, 255)
resized = F.interpolate(wide, size=(224, 224), mode=resample, antialias=True).round().clamp(0, 255)[0]
if crop_size is not None:
resized = resized[:, 12:212, 12:212]
rounded_levels = (result * std + mean) * 255
levels = (rounded_levels - resized).abs()
assert levels.max().item() <= 1.01
assert (levels > 0.5).float().mean().item() < 0.05
# The rounded output sits on uint8 levels, the unrounded one does not.
torch.testing.assert_close(rounded_levels, rounded_levels.round(), atol=1e-3, rtol=0)
assert not torch.equal(result, unrounded_result)


def test_invalid_inputs_raise():
image = random_images([(64, 64)])[0]
with pytest.raises(ValueError, match="uint8"):
cv_utils.resize_normalize([image.float()], [(32, 32)], MEAN, STD, 1 / 255, "bilinear")
with pytest.raises(ValueError, match="at least one"):
cv_utils.resize_normalize([], [], MEAN, STD, 1 / 255, "bilinear")
with pytest.raises(ValueError, match="crop_size"):
cv_utils.resize_normalize([image], [(32, 32)], MEAN, STD, 1 / 255, "bilinear", crop_size=(48, 48))
with pytest.raises(ValueError, match="one size per image"):
cv_utils.resize_normalize([image, image], [(32, 32)], MEAN, STD, 1 / 255, "bilinear")
with pytest.raises(ValueError, match="one value per channel"):
cv_utils.resize_normalize([image], [(32, 32)], [0.5, 0.5], [0.5, 0.5], 1 / 255, "bilinear")
with pytest.raises(ValueError, match="multiple"):
cv_utils.resize_normalize_patchify([image[None]], [(42, 56)], MEAN, STD, 1 / 255, "bicubic", 14, 2, 2)


def test_single_mean_and_std_apply_to_every_channel():
images = random_images([(64, 64)])
single = cv_utils.resize_normalize(images, [(32, 32)], 0.5, 0.5, 1 / 255, "bilinear")
per_channel = cv_utils.resize_normalize(images, [(32, 32)], [0.5] * 3, [0.5] * 3, 1 / 255, "bilinear")
torch.testing.assert_close(single, per_channel, atol=0, rtol=0)


@pytest.mark.parametrize("patch, target_sizes", [(14, [(280, 420), (504, 336)]), (16, [(288, 448), (512, 320)])])
def test_resize_normalize_patchify_row_by_row_with_block_size_one(patch, target_sizes):
frames = random_images([(300, 450), (500, 333)])
inputs = [frame[None] for frame in frames]
pixel_values, grid_thw = cv_utils.resize_normalize_patchify(
inputs, target_sizes, MEAN, STD, 1 / 255, "bicubic", patch, 1, 1, round_to_uint8=False
)

expected = []
for frame, (height, width) in zip(frames, target_sizes):
image = reference(frame, (height, width), "bicubic")
patches = image.view(3, height // patch, patch, width // patch, patch).permute(1, 3, 0, 2, 4)
expected.append(patches.reshape(-1, 3 * patch * patch))
assert grid_thw.tolist() == [[1, height // patch, width // patch] for height, width in target_sizes]
torch.testing.assert_close(pixel_values, torch.cat(expected), atol=2e-3, rtol=0)
Loading
Loading