Skip to content
Open
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,8 @@ def _build_tile_mask(self, tile, is_bound, border):
"""Build border weight mask for tile blending."""
_, _, _, h, w = tile.shape
border_h, border_w = border
border_h = min(h, border_h)
border_w = min(w, border_w)
is_top, is_bottom, is_left, is_right = is_bound

mask = torch.ones(1, 1, 1, h, w, dtype=tile.dtype, device=tile.device)
Expand All @@ -1068,15 +1070,15 @@ def _build_tile_mask(self, tile, is_bound, border):

if not is_bottom and border_h > 0:
for y in range(border_h):
mask[:, :, :, h - 1 - y, :] *= y / border_h
mask[:, :, :, h - border_h + y, :] *= 1 - y / border_h
Comment on lines 1072 to +1073

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using a Python loop to perform element-wise multiplication on PyTorch tensors is inefficient because it incurs Python loop overhead and launches multiple small CUDA kernels. We can vectorize this operation using torch.arange and broadcasting, which is much faster and more idiomatic.

Note: The is_top and is_left blocks can also be vectorized in a similar manner.

Suggested change
for y in range(border_h):
mask[:, :, :, h - 1 - y, :] *= y / border_h
mask[:, :, :, h - border_h + y, :] *= 1 - y / border_h
weights = 1.0 - torch.arange(border_h, device=mask.device, dtype=mask.dtype) / border_h
mask[:, :, :, h - border_h :, :] *= weights.view(1, 1, 1, border_h, 1)


if not is_left and border_w > 0:
for x in range(border_w):
mask[:, :, :, :, x] *= x / border_w

if not is_right and border_w > 0:
for x in range(border_w):
mask[:, :, :, :, w - 1 - x] *= x / border_w
mask[:, :, :, :, w - border_w + x] *= 1 - x / border_w
Comment on lines 1080 to +1081

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Similarly, this loop can be vectorized to avoid Python loop overhead and multiple CUDA kernel launches, improving performance.

Suggested change
for x in range(border_w):
mask[:, :, :, :, w - 1 - x] *= x / border_w
mask[:, :, :, :, w - border_w + x] *= 1 - x / border_w
weights = 1.0 - torch.arange(border_w, device=mask.device, dtype=mask.dtype) / border_w
mask[:, :, :, :, w - border_w :] *= weights.view(1, 1, 1, 1, border_w)


return mask

Expand Down