🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat: 2d augmentation benchmarks (#2853)
João Gustavo A. Amorim46a5e40a0dbf
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 23adeab7d..4a4e9b24e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -142,6 +142,55 @@ repository under your GitHub account.commands of the [Makefile](./Makefile). Read more about the code standards adopted [here](#coding-standards).+## Benchmarking++We have a benchmark suite configured in [benchmarks/](./benchmarks/). We used the+ [pytest-benchmark](https://pypi.org/project/pytest-benchmark/) library to benchmark our functions units.++Our [Makefile](./Makefile) has an `benchmark` command as an alias on how to run our benchmarks.++```console+# To run all suite+$ make benchmark++# To run a specific file you can pass `BENCHMARK_SOURCE`+$ make benchmark BENCHMARK_SOURCE=benchmarks/augmentation/2d_geometric_test.py++# To run a specific benchmark you use `BENCHMARK_SOURCE` as the pytest standard behaviour+$ make benchmark BENCHMARK_SOURCE=benchmarks/augmentation/2d_geometric_test.py::test_aug_2d_elastic_transform++# To update the optimizer backends desired to execute you can pass `BENCHMARK_BACKENDS=`+$ make benchmark BENCHMARK_BACKENDS='inductor,eager'++# To pass other options to the runner, you can use `BENCHMARK_OPTS`+# Example, setup to run the benchmark on cuda on verbose mode+$ make benchmark BENCHMARK_OPTS='--device=cuda -vv'+```++We use the same tests generator suite, so you can setup the device within `--device`, the dtype within+`--dtype`, and the optimizer backend within `--optimizer`.++The optimizer backend supported on the suite, are the torch compile backend on non experimental mode,+ and the `''` or `None` which will do the same as `eager` mode and do anything, and `'jit'` which will+ try to `torch.jit.script` the operation.++You can use the `BENCHMARK_OPTS` on `make benchmark` to overload the default options we use on pytest-benchmark.++We are using as default:+- the warmup, because the optimizer/jit may had an overhead.+- the group: to display the benchmark per each test+- the precision: to have a better precision on the results+- the default for `BENCHMARK_BACKENDS` are `'inductor,eager'`.+- the default for `BENCHMARK_SOURCE` is `benchmarks/`.++You can also run the benchmark within docker:+```console+$ make benchmark-docker+```++which will build and run the image [docker/Dockerfile.benchmark](docker/Dockerfile.benchmark).+ The benchmark command can be used within `BENCHMARK_BACKENDS` and `BENCHMARK_SOURCE`.+# Coding StandardsThis section provides general guidance for developing code for the project. The following rules will serve as a guide indiff --git a/Makefile b/Makefileindex 1e4822429..5f93bfc6e 100644--- a/Makefile+++ b/Makefile@@ -1,3 +1,7 @@+BENCHMARK_SOURCE = benchmarks/+BENCHMARK_BACKENDS = inductor,eager+BENCHMARK_OPTS =+.PHONY: test test-cpu test-cuda lint mypy build-docs install uninstall FORCEtest: mypy lint build-docs test-all@@ -57,7 +61,17 @@ install-dev: FORCEpython setup.py developbenchmark: FORCE- for f in tests/performance/*.py ; do python -utt $${f}; done+ # We want to always run within warmup because torch optimizer backend+ pytest $(BENCHMARK_SOURCE) --benchmark-warmup=on --benchmark-warmup-iterations=100 --benchmark-calibration-precision=10 --benchmark-group-by=func --optimizer=$(BENCHMARK_BACKENDS) $(BENCHMARK_OPTS) $(0)++benchmark-docker:+ docker image rm kornia-benchmark:latest --force+ docker build -t kornia-benchmark:latest -f docker/Dockerfile.benchmark .+ docker run -e "TERM=xterm-256color" \+ -e "BACKENDS=$(BENCHMARK_BACKENDS)" \+ -e "OPTS=$(BENCHMARK_OPTS)" \+ --gpus all\+ -it kornia-benchmark:latestuninstall: FORCEpip uninstall korniadiff --git a/benchmarks/augmentation/2d_geometric_test.py b/benchmarks/augmentation/2d_geometric_test.pynew file mode 100644index 000000000..27cc4958b--- /dev/null+++ b/benchmarks/augmentation/2d_geometric_test.py@@ -0,0 +1,187 @@+import torch++from kornia.augmentation import (+ CenterCrop,+ PadTo,+ RandomAffine,+ RandomCrop,+ RandomElasticTransform,+ RandomErasing,+ RandomFisheye,+ RandomHorizontalFlip,+ RandomPerspective,+ RandomResizedCrop,+ RandomRotation,+ RandomShear,+ RandomThinPlateSpline,+ RandomTranslate,+ RandomVerticalFlip,+ Resize,+)+++def test_aug_2d_centercrop(benchmark, device, dtype, torch_optimizer, shape):+ w_target = h_target = 64+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = CenterCrop((h_target, w_target), p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == (*shape[:-2], h_target, w_target)+++def test_aug_2d_padto(benchmark, device, dtype, torch_optimizer, shape):+ w_target = h_target = 256+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = PadTo((h_target, w_target))+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == (*shape[:-2], h_target, w_target)+++def test_aug_2d_affine(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomAffine(degrees=45, translate=0.25, scale=(0.9, 1.1), shear=1.25, p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_crop(benchmark, device, dtype, torch_optimizer, shape):+ w_target = h_target = 64+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomCrop((h_target, w_target), pad_if_needed=True, p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == (*shape[:-2], h_target, w_target)+++def test_aug_2d_elastic_transform(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomElasticTransform(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_erasing(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomErasing(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_fisheye(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ center_x = center_y = torch.tensor([-0.3, 0.3], device=device, dtype=dtype)+ gamma = torch.tensor([0.9, 1.0], device=device, dtype=dtype)+ aug = RandomFisheye(center_x, center_y, gamma, p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_horizontal_flip(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomHorizontalFlip(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_perspective(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomPerspective(0.5, p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_resized_crop(benchmark, device, dtype, torch_optimizer, shape):+ w_target = h_target = 64+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomResizedCrop((h_target, w_target), p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == (*shape[:-2], h_target, w_target)+++def test_aug_2d_rotation(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomRotation(45, p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_shear(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomShear((-5.0, 2.0, 5.0, 10.0), p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_thin_plate_spline(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomThinPlateSpline(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_translate(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomTranslate((-0.2, 0.2), (-0.1, 0.1), p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_vertical_flip(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomVerticalFlip(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_resize(benchmark, device, dtype, torch_optimizer, shape):+ w_target = h_target = 64+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = Resize((h_target, w_target), p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == (*shape[:-2], h_target, w_target)diff --git a/benchmarks/augmentation/2d_intensity_test.py b/benchmarks/augmentation/2d_intensity_test.pynew file mode 100644index 000000000..dc86686f5--- /dev/null+++ b/benchmarks/augmentation/2d_intensity_test.py@@ -0,0 +1,407 @@+import pytest+import torch++from kornia.augmentation import (+ ColorJiggle,+ ColorJitter,+ Denormalize,+ Normalize,+ RandomAutoContrast,+ RandomBoxBlur,+ RandomBrightness,+ RandomChannelShuffle,+ RandomClahe,+ RandomContrast,+ RandomEqualize,+ RandomGamma,+ RandomGaussianBlur,+ RandomGaussianIllumination,+ RandomGaussianNoise,+ RandomGrayscale,+ RandomHue,+ RandomInvert,+ RandomLinearCornerIllumination,+ RandomLinearIllumination,+ RandomMedianBlur,+ RandomMotionBlur,+ RandomPlanckianJitter,+ RandomPlasmaBrightness,+ RandomPlasmaContrast,+ RandomPlasmaShadow,+ RandomPosterize,+ RandomRain,+ RandomRGBShift,+ RandomSaltAndPepperNoise,+ RandomSaturation,+ RandomSharpness,+ RandomSnow,+ RandomSolarize,+)+++def test_aug_2d_collor_jiggle(benchmark, device, dtype, torch_optimizer, shape):+ if shape[1] != 3:+ pytest.skip("Skipping because input should be rgb")+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_collor_jitter(benchmark, device, dtype, torch_optimizer, shape):+ if shape[1] != 3:+ pytest.skip("Skipping because input should be rgb")+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)+ op = torch_optimizer(aug)+ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_denormalize(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = Denormalize(0.0, 1.0, p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_auto_contrast(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomAutoContrast(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_box_blur(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomBoxBlur(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_brightness(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomBrightness((0.1, 1), p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_channel_shuffle(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomChannelShuffle(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_clahe(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomClahe((10, 40), p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_contrast(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomContrast((0.1, 1), p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_equalize(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomEqualize(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_gamma(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomGamma((0.0, 1.0), (0.0, 1.0), p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_gaussian_blur(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomGaussianBlur(3, (1.6, 1.7), p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_gaussian_illumination(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomGaussianIllumination(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_gaussian_noise(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomGaussianNoise(0.0, 1.0, p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_grayscale(benchmark, device, dtype, torch_optimizer, shape):+ if shape[1] != 3:+ pytest.skip("Skipping because input should be rgb")+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomGrayscale(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_hue(benchmark, device, dtype, torch_optimizer, shape):+ if shape[1] != 3:+ pytest.skip("Skipping because input should be rgb")+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomHue((0.0, 0.5), p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_invert(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomInvert(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++# TODO(joao.amorim): figure out dynamo issue with it+# def test_aug_2d_jpeg(benchmark, device, dtype, torch_optimizer, shape):+# data = torch.rand(*shape, device=device, dtype=dtype)+# aug = RandomJPEG(p=1.0)+# op = torch_optimizer(aug)+#+# actual = benchmark(op, input=data)+#+# assert actual.shape == shape+++def test_aug_2d_linear_corner_illumination(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomLinearCornerIllumination(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_linear_illumination(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomLinearIllumination(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_median_blur(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomMedianBlur(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_motion_blur(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomMotionBlur((3, 3), 45.0, 5.5, p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_normalize(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = Normalize(25.0, 2.5, p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_plackian_jitter(benchmark, device, dtype, torch_optimizer, shape):+ if shape[1] != 3:+ pytest.skip("Skipping because input should be rgb")++ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomPlanckianJitter(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_plasma_briggtness(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomPlasmaBrightness(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_plasma_contrast(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomPlasmaContrast(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_plasma_shadow(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomPlasmaShadow(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_posterize(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomPosterize(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_rain(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomRain(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_rgb_shift(benchmark, device, dtype, torch_optimizer, shape):+ if shape[1] != 3:+ pytest.skip("Skipping because input should be rgb")+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomRGBShift(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_salt_and_peper_noise(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomSaltAndPepperNoise(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_saturation(benchmark, device, dtype, torch_optimizer, shape):+ if shape[1] != 3:+ pytest.skip("Skipping because input should be rgb")+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomSaturation((0.0, 2.0), p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_sharpness(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomSharpness(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_snow(benchmark, device, dtype, torch_optimizer, shape):+ if shape[1] != 3:+ pytest.skip("Skipping because input should be rgb")++ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomSnow(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape+++def test_aug_2d_solarize(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomSolarize(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shapediff --git a/benchmarks/augmentation/conftest.py b/benchmarks/augmentation/conftest.pynew file mode 100644index 000000000..7239aa0b3--- /dev/null+++ b/benchmarks/augmentation/conftest.py@@ -0,0 +1,16 @@+from itertools import product++import pytest+++def shape(B, C, H, W):+ return (B, C, H, W)+++def pytest_generate_tests(metafunc):+ B = [1, 5]+ C = [1, 3]+ H = W = [128] # , 237, 512]+ params = list(product(B, C, H, W))+ metafunc.parametrize("B, C, H, W", params)diff --git a/benchmarks/color/gray_test.py b/benchmarks/color/gray_test.pyindex 03f7e0598..57b69462c 100644--- a/benchmarks/color/gray_test.py+++ b/benchmarks/color/gray_test.py@@ -8,21 +8,8 @@ from kornia.color import grayscale_to_rgb@pytest.mark.parametrize("C", [1])@pytest.mark.parametrize("H", [128, 237, 512])@pytest.mark.parametrize("W", [128, 237, 512])-def test_grayscale_to_rgb(benchmark, device, dtype, B, C, H, W):+def test_grayscale_to_rgb(benchmark, device, dtype, torch_optimizer, B, C, H, W):data = torch.rand(B, C, H, W, device=device, dtype=dtype)-- actual = benchmark(grayscale_to_rgb, image=data)-- assert actual.shape == (B, 3, H, W)--[email protected]("B", [1, 5])[email protected]("C", [1])[email protected]("H", [128, 237, 512])[email protected]("W", [128, 237, 512])-def test_grayscale_to_rgb_compile(benchmark, device, dtype, torch_optimizer, B, C, H, W):- data = torch.rand(B, C, H, W, device=device, dtype=dtype)-op = torch_optimizer(grayscale_to_rgb)actual = benchmark(op, image=data)diff --git a/conftest.py b/conftest.pyindex 58c697f34..5f31dac81 100644--- a/conftest.py+++ b/conftest.py@@ -1,4 +1,5 @@import sys+from functools import partialfrom itertools import productfrom typing import Dict@@ -9,6 +10,13 @@ import torchimport korniafrom kornia.utils._compat import torch_version+try:+ import torch._dynamo++ _backends_non_experimental = torch._dynamo.list_backends()+except ImportError:+ _backends_non_experimental = []+def get_test_devices() -> Dict[str, torch.device]:"""Create a dictionary with the devices to test the source code. CUDA devices will be test only in case the@@ -49,7 +57,7 @@ def get_test_dtypes() -> Dict[str, torch.dtype]:TEST_DEVICES: Dict[str, torch.device] = get_test_devices()TEST_DTYPES: Dict[str, torch.dtype] = get_test_dtypes()-+TEST_OPTIMIZER_BACKEND = {"", None, "jit", *_backends_non_experimental}# Combinations of device and dtype to be excluded from testing.# DEVICE_DTYPE_BLACKLIST = {('cpu', 'float16')}DEVICE_DTYPE_BLACKLIST = {}@@ -65,12 +73,21 @@ def dtype(dtype_name) -> torch.dtype:return TEST_DTYPES[dtype_name][email protected](scope="session")-def torch_optimizer():+def torch_optimizer(optimizer_backend):+ if not optimizer_backend:+ return lambda x: x++ if optimizer_backend == "jit":+ return torch.jit.script+if hasattr(torch, "compile") and sys.platform == "linux":if not (sys.version_info[:2] == (3, 11) and torch_version() in {"2.0.0", "2.0.1"}):+ torch._dynamo.reset()# torch compile just have support for python 3.11 after torch 2.1.0- return torch.compile+ return partial(+ torch.compile, backend=optimizer_backend+ ) # TODO: explore the others parameters of torch compilepytest.skip(f"skipped because {torch.__version__} not have `compile` available! Failed to setup dynamo.")@@ -78,6 +95,8 @@ def torch_optimizer():def pytest_generate_tests(metafunc):device_names = Nonedtype_names = None+ optimizer_backends_names = None+if "device_name" in metafunc.fixturenames:raw_value = metafunc.config.getoption("--device")if raw_value == "all":@@ -90,7 +109,23 @@ def pytest_generate_tests(metafunc):dtype_names = list(TEST_DTYPES.keys())else:dtype_names = raw_value.split(",")- if device_names is not None and dtype_names is not None:++ if "optimizer_backend" in metafunc.fixturenames:+ raw_value = metafunc.config.getoption("--optimizer")+ if raw_value == "all":+ optimizer_backends_names = TEST_OPTIMIZER_BACKEND+ else:+ optimizer_backends_names = raw_value.split(",")++ if device_names is not None and dtype_names is not None and optimizer_backends_names is not None:+ # Exclude any blacklisted device/dtype combinations.+ params = [+ combo+ for combo in product(device_names, dtype_names, optimizer_backends_names)+ if combo not in DEVICE_DTYPE_BLACKLIST+ ]+ metafunc.parametrize("device_name,dtype_name,optimizer_backend", params)+ elif device_names is not None and dtype_names is not None and optimizer_backends_names is None:# Exclude any blacklisted device/dtype combinations.params = [combo for combo in product(device_names, dtype_names) if combo not in DEVICE_DTYPE_BLACKLIST]metafunc.parametrize("device_name,dtype_name", params)@@ -98,6 +133,8 @@ def pytest_generate_tests(metafunc):metafunc.parametrize("device_name", device_names)elif dtype_names is not None:metafunc.parametrize("dtype_name", dtype_names)+ elif optimizer_backends_names is not None:+ metafunc.parametrize("optimizer_backend", optimizer_backends_names)def pytest_collection_modifyitems(config, items):@@ -114,6 +151,7 @@ def pytest_collection_modifyitems(config, items):def pytest_addoption(parser):parser.addoption("--device", action="store", default="cpu")parser.addoption("--dtype", action="store", default="float32")+ parser.addoption("--optimizer", action="store", default="inductor")parser.addoption("--runslow", action="store_true", default=False, help="run slow tests")@@ -145,6 +183,51 @@ def pytest_sessionstart(session):# TODO: cache all torch.load weights/states here to not impact on test suite+def _get_env_info() -> Dict[str, Dict[str, str]]:+ if not hasattr(torch.utils, "collect_env"):+ return {}++ run_lmb = torch.utils.collect_env.run+ separator = ":"+ br = "\n"++ def _get_key_value(v: str):+ parts = v.split(separator)+ return parts[0].strip(), parts[-1].strip()++ def _get_cpu_info() -> Dict[str, str]:+ cpu_info = {}+ cpu_str = torch.utils.collect_env.get_cpu_info(run_lmb)+ if not cpu_str:+ return {}++ for data in cpu_str.split(br):+ key, value = _get_key_value(data)+ cpu_info[key] = value++ return cpu_info++ def _get_gpu_info() -> Dict[str, str]:+ gpu_info = {}+ gpu_str = torch.utils.collect_env.get_gpu_info(run_lmb)++ if not gpu_str:+ return {}++ for data in gpu_str.split(br):+ key, value = _get_key_value(data)+ gpu_info[key] = value++ return gpu_info++ return {+ "cpu": _get_cpu_info(),+ "gpu": _get_gpu_info(),+ "nvidia": torch.utils.collect_env.get_nvidia_driver_version(run_lmb),+ "gcc": torch.utils.collect_env.get_gcc_version(run_lmb),+ }++def pytest_report_header(config):try:import accelerate@@ -156,17 +239,34 @@ def pytest_report_header(config):import kornia_rsimport onnx+ env_info = _get_env_info()++ if "cpu" in env_info:+ desired_cpu_info = ["Model name", "Architecture", "CPU(s)", "Thread(s) per core", "CPU max MHz", "CPU min MHz"]+ cpu_info = "cpu info:\n" + "\n".join(+ f'\t- {i}: {env_info["cpu"][i]}' for i in desired_cpu_info if i in env_info["cpu"]+ )+ else:+ cpu_info = ""+ gpu_info = f"gpu info: {env_info['gpu']}" if "gpu" in env_info else ""+ gcc_info = f"gcc info: {env_info['gcc']}" if "gcc" in env_info else ""+return f"""+{cpu_info}+{gpu_info}main deps:- kornia-{kornia.__version__}- torch-{torch.__version__}- commit: {torch.version.git_version}- cuda: {torch.version.cuda}+ - nvidia-driver: {env_info['nvidia'] if 'nvidia' in env_info else None}x deps:- {accelerate_info}dev deps:- kornia_rs-{kornia_rs.__version__}- onnx-{onnx.__version__}+{gcc_info}+available optimizers: {TEST_OPTIMIZER_BACKEND}"""diff --git a/docker/Dockerfile.benchmark b/docker/Dockerfile.benchmarknew file mode 100644index 000000000..da08022b6--- /dev/null+++ b/docker/Dockerfile.benchmark@@ -0,0 +1,33 @@+FROM pytorch/pytorch:2.2.1-cuda12.1-cudnn8-runtime++# This allow us to setup the benchmark parameters from env vars+ENV BACKENDS='eager,inductor'+ENV OPTS=''++# Setup make and gcc+RUN DEBIAN_FRONTEND=noninteractive apt update && \+ DEBIAN_FRONTEND=noninteractive apt install make g++ -y++# Setup Kornia dev mode+WORKDIR /tmp/kornia-lib/+COPY kornia/ kornia/+COPY pyproject.toml ./+COPY requirements/ requirements/++RUN pip install .[dev,x]++# Setup benchmarks+WORKDIR /kornia-benchmarks/+COPY benchmarks/ benchmarks/+COPY Makefile ./+COPY conftest.py ./++# Cleanup+RUN rm -rf /tmp/kornia-lib/+RUN DEBIAN_FRONTEND=noninteractive apt autopurge -y+RUN DEBIAN_FRONTEND=noninteractive apt autoclean -y+RUN DEBIAN_FRONTEND=noninteractive apt autoremove -y+RUN rm -rf /var/lib/apt/lists/*++# CMD+CMD ["make", "benchmark", "BENCHMARK_BACKENDS=$(BACKENDS)", "BENCHMARK_OPTS=$(OPTS)"]diff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rstindex bf5021035..6aca66dd1 100644--- a/docs/source/augmentation.module.rst+++ b/docs/source/augmentation.module.rst@@ -13,6 +13,7 @@ Intensity.. autoclass:: ColorJiggle.. autoclass:: ColorJitter+.. autoclass:: RandomAutoContrast.. autoclass:: RandomBoxBlur.. autoclass:: RandomBrightness.. autoclass:: RandomChannelShuffle@@ -25,9 +26,10 @@ Intensity.. autoclass:: RandomGaussianNoise.. autoclass:: RandomGrayscale.. autoclass:: RandomHue+.. autoclass:: RandomInvert.. autoclass:: RandomJPEG-.. autoclass:: RandomLinearIllumination.. autoclass:: RandomLinearCornerIllumination+.. autoclass:: RandomLinearIllumination.. autoclass:: RandomMedianBlur.. autoclass:: RandomMotionBlur.. autoclass:: RandomPlanckianJitter@@ -35,14 +37,15 @@ Intensity.. autoclass:: RandomPlasmaContrast.. autoclass:: RandomPlasmaShadow.. autoclass:: RandomPosterize-.. autoclass:: RandomRGBShift.. autoclass:: RandomRain-.. autoclass:: RandomSaturation+.. autoclass:: RandomRGBShift.. autoclass:: RandomSaltAndPepperNoise+.. autoclass:: RandomSaturation.. autoclass:: RandomSharpness.. autoclass:: RandomSnow.. autoclass:: RandomSolarize+Geometric~~~~~~~~~@@ -54,13 +57,14 @@ Geometric.. autoclass:: RandomErasing.. autoclass:: RandomFisheye.. autoclass:: RandomHorizontalFlip-.. autoclass:: RandomInvert.. autoclass:: RandomPerspective.. autoclass:: RandomResizedCrop.. autoclass:: RandomRotation+.. autoclass:: RandomShear.. autoclass:: RandomThinPlateSpline.. autoclass:: RandomVerticalFlip+Mix~~~diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.pyindex 4e22be0f4..879f7b48c 100644--- a/kornia/augmentation/_2d/geometric/perspective.py+++ b/kornia/augmentation/_2d/geometric/perspective.py@@ -13,11 +13,11 @@ class RandomPerspective(GeometricAugmentationBase2D):.. image:: _static/img/RandomPerspective.pngArgs:- p: probability of the image being perspectively transformed.distortion_scale: the degree of distortion, ranged from 0 to 1.resample: the interpolation method to use.same_on_batch: apply the same transformation across the batch. Default: False.align_corners: interpolation flag.+ p: probability of the image being perspectively transformed.keepdim: whether to keep the output shape the same as input (True) or broadcast itto the batch form (False).sampling_method: ``'basic'`` | ``'area_preserving'``. Default: ``'basic'``diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.pyindex 51b4d9796..240bfd986 100644--- a/kornia/augmentation/_2d/geometric/resize.py+++ b/kornia/augmentation/_2d/geometric/resize.py@@ -19,6 +19,7 @@ class Resize(GeometricAugmentationBase2D):resample: Resampling mode.align_corners: interpolation flag.antialias: if True, then image will be filtered with Gaussian before downscaling. No effect for upscaling.+ p: probability of the augmentation been applied.keepdim: whether to keep the output shape the same as input (True) or broadcast itto the batch form (False)."""diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.pyindex 9623b36ee..07ec15e9b 100644--- a/kornia/augmentation/_2d/geometric/resized_crop.py+++ b/kornia/augmentation/_2d/geometric/resized_crop.py@@ -20,6 +20,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):resample: the interpolation mode.same_on_batch: apply the same transformation across the batch.align_corners: interpolation flag.+ p: probability of the augmentation been applied.keepdim: whether to keep the output shape the same as input (True) or broadcast itto the batch form (False).cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor baseddiff --git a/kornia/augmentation/_2d/intensity/brightness.py b/kornia/augmentation/_2d/intensity/brightness.pyindex a4486b8be..57e867dc6 100644--- a/kornia/augmentation/_2d/intensity/brightness.py+++ b/kornia/augmentation/_2d/intensity/brightness.py@@ -15,11 +15,11 @@ class RandomBrightness(IntensityAugmentationBase2D):.. image:: _static/img/RandomBrightness.pngArgs:- p: probability of applying the transformation.brightness: the brightness factor to applyclip_output: if true clip outputsilence_instantiation_warning: if True, silence the warning at instantiation.same_on_batch: apply the same transformation across the batch.+ p: probability of applying the transformation.keepdim: whether to keep the output shape the same as input (True) or broadcast itto the batch form (False).Shape:diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.pyindex ed2f4dfd1..e0dac7484 100644--- a/kornia/augmentation/_2d/intensity/color_jitter.py+++ b/kornia/augmentation/_2d/intensity/color_jitter.py@@ -22,13 +22,13 @@ class ColorJitter(IntensityAugmentationBase2D):.. image:: _static/img/ColorJitter.pngArgs:- p: probability of applying the transformation.brightness: The brightness factor to apply.contrast: The contrast factor to apply.saturation: The saturation factor to apply.hue: The hue factor to apply.silence_instantiation_warning: if True, silence the warning at instantiation.same_on_batch: apply the same transformation across the batch.+ p: probability of applying the transformation.keepdim: whether to keep the output shape the same as input (True) or broadcast itto the batch form (False).Shape:diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.pyindex 995a7346a..fe4b91f73 100644--- a/kornia/augmentation/_2d/intensity/contrast.py+++ b/kornia/augmentation/_2d/intensity/contrast.py@@ -15,10 +15,10 @@ class RandomContrast(IntensityAugmentationBase2D):.. image:: _static/img/RandomContrast.pngArgs:- p: probability of applying the transformation.contrast: the contrast factor to apply.clip_output: if true clip output.same_on_batch: apply the same transformation across the batch.+ p: probability of applying the transformation.keepdim: whether to keep the output shape the same as input (True) or broadcast itto the batch form (False).Shape:diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.pyindex b2989def5..97a2f737d 100644--- a/kornia/augmentation/_2d/intensity/hue.py+++ b/kornia/augmentation/_2d/intensity/hue.py@@ -16,9 +16,9 @@ class RandomHue(IntensityAugmentationBase2D):.. image:: _static/img/RandomHue.pngArgs:- p: probability of applying the transformation.hue: the saturation factor to apply.same_on_batch: apply the same transformation across the batch.+ p: probability of applying the transformation.keepdim: whether to keep the output shape the same as input (True) or broadcast itto the batch form (False).Shape:diff --git a/kornia/augmentation/_2d/intensity/planckian_jitter.py b/kornia/augmentation/_2d/intensity/planckian_jitter.pyindex ca83d1077..6e53cf70f 100644--- a/kornia/augmentation/_2d/intensity/planckian_jitter.py+++ b/kornia/augmentation/_2d/intensity/planckian_jitter.py@@ -3,6 +3,7 @@ from typing import Any, Dict, List, Optional, Unionfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.core import Tensor, stack, tensor+from kornia.core.check import KORNIA_CHECK_SHAPEdef get_planckian_coeffs(mode: str) -> Tensor:@@ -157,6 +158,7 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):if select_from is not None:_pl = _pl[select_from]self.register_buffer("pl", _pl)+ self.pl: Tensor# the range of the sampling parameters_param_min: float = 0.0@@ -168,7 +170,8 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None) -> Tensor:list_idx = params["idx"].tolist()-+ KORNIA_CHECK_SHAPE(input, ["*", "3", "H", "W"])+ self.pl = self.pl.to(device=input.device)coeffs = self.pl[list_idx]r_w = coeffs[:, 0][..., None, None]diff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.pyindex d09810614..a089bbe86 100644--- a/kornia/augmentation/_2d/intensity/random_rain.py+++ b/kornia/augmentation/_2d/intensity/random_rain.py@@ -36,12 +36,12 @@ class RandomRain(IntensityAugmentationBase2D):def __init__(self,- same_on_batch: bool = False,- p: float = 0.5,- keepdim: bool = False,number_of_drops: tuple[int, int] = (1000, 2000),drop_height: tuple[int, int] = (5, 20),drop_width: tuple[int, int] = (-5, 5),+ same_on_batch: bool = False,+ p: float = 0.5,+ keepdim: bool = False,) -> None:super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)self._param_generator = RainGenerator(number_of_drops, drop_height, drop_width)diff --git a/requirements/requirements-dev.txt b/requirements/requirements-dev.txtindex 557e537ef..a92163ddb 100644--- a/requirements/requirements-dev.txt+++ b/requirements/requirements-dev.txt@@ -5,5 +5,6 @@ onnxpre-commit>=2pydocstylepytest==8.1.1+pytest-benchmarkpytest-timeoutrequestsdiff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 389c3c609..01fcb9402 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -3976,14 +3976,14 @@ class TestPlanckianJitter(BaseTester):def test_planckian_jitter_blackbody(self, device, dtype):torch.manual_seed(0)- f = RandomPlanckianJitter(select_from=1).to(device)+ f = RandomPlanckianJitter(select_from=1)input = self._get_input(device, dtype)expected = self._get_expected_output_blackbody(device, dtype)self.assert_close(f(input), expected, low_tolerance=True)def test_planckian_jitter_cied(self, device, dtype):torch.manual_seed(0)- f = RandomPlanckianJitter(mode="CIED", select_from=1).to(device)+ f = RandomPlanckianJitter(mode="CIED", select_from=1)input = self._get_input(device, dtype)expected = self._get_expected_output_cied(device, dtype)self.assert_close(f(input), expected, low_tolerance=True)@@ -3993,7 +3993,7 @@ class TestPlanckianJitter(BaseTester):input = self._get_input(device, dtype).repeat(2, 1, 1, 1)select_from = [1, 2, 24]- f = RandomPlanckianJitter(select_from=select_from).to(device)+ f = RandomPlanckianJitter(select_from=select_from)expected = self._get_expected_output_batch(device, dtype)self.assert_close(f(input), expected, low_tolerance=True)@@ -4002,7 +4002,7 @@ class TestPlanckianJitter(BaseTester):input = self._get_input(device, dtype).repeat(2, 1, 1, 1)select_from = [1, 2, 24, 3, 4, 5]- f = RandomPlanckianJitter(select_from=select_from, same_on_batch=True, p=1.0).to(device)+ f = RandomPlanckianJitter(select_from=select_from, same_on_batch=True, p=1.0)expected = self._get_expected_output_same_on_batch(device, dtype)self.assert_close(f(input), expected, low_tolerance=True)diff --git a/tests/contrib/test_prompter.py b/tests/contrib/test_prompter.pyindex 98febccbb..3118937cd 100644--- a/tests/contrib/test_prompter.py+++ b/tests/contrib/test_prompter.py@@ -86,7 +86,7 @@ class TestVisualPrompter(BaseTester):def test_module(self): ...@pytest.mark.skipif(torch_version() in {"2.0.0", "2.0.1", "2.1.2"}, reason="Not working on 2.0.x and 2.1.x")- def test_dynamo(self, device, torch_optimizer):+ def test_dynamo(self, device):dtype = torch.float32batch_size = 1N = 2