π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(augmentation): rasterise all RandomRain drops in one indexed write (#4675)
Pranjal Mishra2dbcda4b47a7
diff --git a/changelog.d/4675.fixed.md b/changelog.d/4675.fixed.mdnew file mode 100644index 000000000..ba06f9e6f--- /dev/null+++ b/changelog.d/4675.fixed.md@@ -0,0 +1,7 @@+`RandomRain` now rasterises every drop of every sample in a single indexed write instead of one+`index_put_` per step of each drop per sample, removing the per-sample host-to-device copies and+`.item()` syncs as well. Output is unchanged: verified bit-identical (`torch.equal`) against the+previous implementation over 12,482 configurations across four device/dtype combinations (cpu+float32 and float64, mps float32 and float16). On MPS at batch 32+(`128 x 128`) this is 45.0 ms to 5.1 ms, and at batch 8 (`256 x 256`) 12.0 ms to 3.6 ms; CPU is+faster at every shape measured. Fixes #4530.diff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.pyindex f6398e87a..546badcd8 100644--- a/kornia/augmentation/_2d/intensity/random_rain.py+++ b/kornia/augmentation/_2d/intensity/random_rain.py@@ -117,33 +117,87 @@ class RandomRain(IntensityAugmentationBase2D):bool(torch.all(torch.abs(params["drop_width_factor"]) < image.shape[3])),"Width of drop should be less than image width.",)- modeified_img = image.clone()- for i in range(image.shape[0]):- number_of_drops: int = int(params["number_of_drops_factor"][i])- # We generate torch.Tensor with maximum number of drops, and then remove unnecessary drops.-- coordinates_of_drops: torch.Tensor = params["coordinates_factor"][i][:number_of_drops]- height_of_drop: int = int(params["drop_height_factor"][i])- width_of_drop: int = int(params["drop_width_factor"][i])-+ output = image.clone()+ batch_size, _, image_height, image_width = image.shape+ coordinates: torch.Tensor = params["coordinates_factor"] # (B, max drops, 2) in [0, 1]+ max_drops = coordinates.shape[1]+ if batch_size == 0 or max_drops == 0:+ return output++ # The three per-sample integers are read once for the whole batch: one device sync per+ # parameter instead of three per sample. `int()` truncates exactly as `int(params[...][i])`+ # did per element.+ drops_per_sample = [int(v) for v in params["number_of_drops_factor"].tolist()]+ heights = [int(v) for v in params["drop_height_factor"].tolist()]+ widths = [int(v) for v in params["drop_width_factor"].tolist()]++ # Every drop of every sample is rasterised in one batched computation and written with ONE+ # indexed assignment (#4530). Before, each sample paid `size_of_line` separate `index_put_`+ # launches, one per step of the line, plus its own host-to-device copies: ~100 writes and+ # 204 adds at batch 8. The per-sample work that remains below runs on the host and touches+ # no device: it builds the line shape for each sample exactly as before, with the same+ # `torch.linspace` in the same dtype, so the pixels are the ones the step loop painted, and+ # all are set to one constant, so write order cannot change the result.+ #+ # The line shape differs per sample (its height, width and step count are all drawn), so the+ # shapes are padded to the longest line in the batch and a mask drops the padding. The staging+ # buffers are pinned to the CPU explicitly rather than left to the default device, so a+ # `torch.set_default_device` in the caller cannot turn the host loop into per-sample device+ # launches, or a copy from `meta` that cannot be made.+ longest_line = max(max(h, abs(w)) for h, w in zip(heights, widths))+ lines = torch.zeros(batch_size, 2, longest_line, dtype=torch.long, device="cpu")+ # One row per sample, packed so the host-side integers cross to the device in a single copy:+ # [admissible start rows, admissible start cols, col shift, line length, drop count].+ # The admissible start region: a drop may start anywhere its far end stays inside the image.+ # The far end is the line's last offset -- the end point is included once there are at least+ # two steps, and a single-pixel drop is the start alone. Derived from the Python ints rather+ # than read off `x[-1]`/`y[-1]`, which would sync the device per sample.+ meta = torch.empty(batch_size, 5, dtype=torch.long, device="cpu")+ for i, (height_of_drop, width_of_drop) in enumerate(zip(heights, widths)):# Generate how our drop will look like into the image- size_of_line: int = max(height_of_drop, abs(width_of_drop))- x = torch.linspace(start=0, end=height_of_drop, steps=size_of_line, dtype=torch.long).to(image.device)- y = torch.linspace(start=0, end=width_of_drop, steps=size_of_line, dtype=torch.long).to(image.device)-- # A drop may start anywhere its far end stays inside the image. The far end is the line's last- # offset -- the end point is included once there are at least two steps, and a single-pixel drop- # is the start alone. Derived in Python rather than read off `x[-1]`/`y[-1]`, which would sync the- # device on every batch element. The clamp is for the MPS half `rand` that can return exactly 1.0- # (#4553): it keeps such a draw on the last admissible start instead of one past it. Main was safe- # there only by accident, its multiplier being one smaller.+ size_of_line = max(height_of_drop, abs(width_of_drop))+ lines[i, 0, :size_of_line] = torch.linspace(+ 0, height_of_drop, steps=size_of_line, dtype=torch.long, device="cpu"+ )+ lines[i, 1, :size_of_line] = torch.linspace(+ 0, width_of_drop, steps=size_of_line, dtype=torch.long, device="cpu"+ )last_dy, last_dx = (height_of_drop, width_of_drop) if size_of_line > 1 else (0, 0)- rows, cols = image.shape[2] - last_dy, image.shape[3] - abs(last_dx)- random_y_coords = (coordinates_of_drops[:, 0] * rows).long().clamp(max=rows - 1)- random_x_coords = (coordinates_of_drops[:, 1] * cols).long().clamp(max=cols - 1) + max(-last_dx, 0)-- coords = torch.stack([random_y_coords, random_x_coords]).to(image.device)- # Draw lines- for k in range(x.shape[0]):- modeified_img[i, :, coords[0] + x[k], coords[1] + y[k]] = 200 / 255- return modeified_img+ meta[i, 0] = image_height - last_dy+ meta[i, 1] = image_width - abs(last_dx)+ meta[i, 2] = max(-last_dx, 0)+ meta[i, 3] = size_of_line+ meta[i, 4] = drops_per_sample[i]++ # Start coordinates, computed on the device the draw lives on so the float product rounds as+ # it always has, then moved once. The clamp is for the MPS half `rand` that can return exactly+ # 1.0 (#4553): it keeps such a draw on the last admissible start instead of one past it.+ meta_c = meta.to(coordinates.device)+ rows_c, cols_c, shift_c = meta_c[:, 0:1], meta_c[:, 1:2], meta_c[:, 2:3]+ start_rows = torch.minimum((coordinates[..., 0] * rows_c).long(), rows_c - 1)+ start_cols = torch.minimum((coordinates[..., 1] * cols_c).long(), cols_c - 1) + shift_c++ # Two device copies for the whole batch: the host-built shapes and metadata as one flat+ # buffer, and the two start-coordinate grids as one stacked tensor.+ device = image.device+ host = torch.cat([lines.reshape(-1), meta.reshape(-1)]).to(device)+ lines = host[: lines.numel()].view(batch_size, 2, longest_line)+ meta = host[lines.numel() :].view(batch_size, 5)+ starts = torch.stack([start_rows, start_cols]).to(device)+ # (B, max drops, longest line): every start offset by every step of its sample's line.+ drop_rows = starts[0].unsqueeze(2) + lines[:, 0].unsqueeze(1)+ drop_cols = starts[1].unsqueeze(2) + lines[:, 1].unsqueeze(1)++ # Keep drop j of sample i only while j < its drawn drop count (the generator allocates the+ # batch maximum), and step k only while k < its line length (padding above). The mask is+ # resolved with a single `nonzero` (one device sync) and the batch index is recovered from+ # the flat position arithmetically, rather than boolean-indexing three tensors, which would+ # call `nonzero` three times.+ drop_valid = torch.arange(max_drops, device=device).unsqueeze(0) < meta[:, 4:5]+ step_valid = torch.arange(longest_line, device=device).unsqueeze(0) < meta[:, 3:4]+ valid = drop_valid.unsqueeze(2) & step_valid.unsqueeze(1)+ flat = valid.reshape(-1).nonzero().squeeze(1)+ batch_index = torch.div(flat, max_drops * longest_line, rounding_mode="floor")++ output[batch_index, :, drop_rows.reshape(-1)[flat], drop_cols.reshape(-1)[flat]] = 200 / 255+ return outputdiff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex a25c1e2a3..4016ae57f 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -5874,6 +5874,48 @@ class TestRandomRain(BaseTester):else:assert (*(1,) * (4 - len(batch_shape)), *batch_shape) == output_data.shape+ @pytest.mark.parametrize("same_on_batch", [False, True])+ @pytest.mark.parametrize(+ "drop_height,drop_width,number_of_drops",+ [((1, 1), (0, 0), (1, 1)), ((1, 2), (-3, -2), (1, 3)), ((3, 3), (2, 3), (5, 10)), ((5, 20), (-5, 5), (20, 40))],+ )+ def test_batched_rasterisation_matches_per_drop_reference_4530(+ self, device, dtype, same_on_batch, drop_height, drop_width, number_of_drops+ ):+ # The drops are rasterised for the whole batch in one indexed write (#4530). This pins that+ # against the straightforward formulation it replaced: one write per step of every drop of+ # every sample. Both are fed the same params, so only the drawing code is compared, and the+ # comparison is exact: a vectorised rewrite that moved a single pixel would fail here.+ torch.manual_seed(0)+ image = torch.rand(4, 3, 24, 30, device=device, dtype=dtype)+ aug = RandomRain(+ p=1.0,+ drop_height=drop_height,+ drop_width=drop_width,+ number_of_drops=number_of_drops,+ same_on_batch=same_on_batch,+ )+ torch.manual_seed(1)+ params = aug.forward_parameters(image.shape)++ reference = image.clone()+ for i in range(image.shape[0]):+ n = int(params["number_of_drops_factor"][i])+ h, w = int(params["drop_height_factor"][i]), int(params["drop_width_factor"][i])+ size = max(h, abs(w))+ x = torch.linspace(0, h, steps=size, dtype=torch.long).to(device)+ y = torch.linspace(0, w, steps=size, dtype=torch.long).to(device)+ last_dy, last_dx = (h, w) if size > 1 else (0, 0)+ rows, cols = image.shape[2] - last_dy, image.shape[3] - abs(last_dx)+ coords = params["coordinates_factor"][i][:n]+ r0 = (coords[:, 0] * rows).long().clamp(max=rows - 1).to(device)+ c0 = (coords[:, 1] * cols).long().clamp(max=cols - 1).to(device) + max(-last_dx, 0)+ for k in range(size):+ reference[i, :, r0 + x[k], c0 + y[k]] = 200 / 255++ out = aug.apply_transform(image, params, {})+ assert torch.equal(out, reference)+def test_smoke(self, device, dtype):input_data = torch.rand(1, 3, 8, 9, device=device, dtype=dtype)aug = RandomRain(p=1.0, drop_height=(2, 3), drop_width=(2, 3), number_of_drops=(1, 3))