Looking at your code, I can see a few optimization opportunities. The main bottleneck is likely the sliding window operation which creates a large intermediate array before averaging.
Here are several approaches to speed this up:
1. Use scipy's uniform_filter (Fastest for your use case)
from scipy.ndimage import uniform_filter
if agg:
# This is much faster than sliding_window_view + mean
data = uniform_filter(data, size=(agg + 1, agg + 1, 1), mode='constant')
norms = np.linalg.norm(data, axis=-1, keepdims=True)
norms = np.where(norms == 0, 1, norms)
uniform_filter computes a moving average without creating the large intermediate array that sliding_window_view creates. It's typically 10-100x faster for this operation.
2. Use separable filtering
Since you're doing a uniform average, you can decompose it into two 1D operations:
if agg:
# Average along rows first, then columns
data = uniform_filter1d(data, size=agg + 1, axis=0, mode='constant')
data = uniform_filter1d(data, size=agg + 1, axis=1, mode='constant')
3. Optimize the norm calculation
For large arrays, you might get a small speedup by computing the norm manually:
# Instead of np.linalg.norm
norms = np.sqrt(np.sum(data * data, axis=-1, keepdims=True))
norms = np.where(norms == 0, 1, norms)
4. Consider using numba for custom implementation
If you need even more speed and scipy isn't available:
import numba as nb
@nb.jit(nopython=True, parallel=True)
def fast_window_mean_and_norm(data, agg):
h, w, c = data.shape
if agg == 0:
return data, np.ones((h, w, 1))
window_size = agg + 1
half = window_size // 2
# Output array
result = np.zeros_like(data)
# Compute windowed mean
for i in nb.prange(h):
for j in range(w):
i_start = max(0, i - half)
i_end = min(h, i + half + 1)
j_start = max(0, j - half)
j_end = min(w, j + half + 1)
count = (i_end - i_start) * (j_end - j_start)
for k in range(c):
sum_val = 0.0
for ii in range(i_start, i_end):
for jj in range(j_start, j_end):
sum_val += data[ii, jj, k]
result[i, j, k] = sum_val / count
# Compute norms
norms = np.zeros((h, w, 1))
for i in nb.prange(h):
for j in range(w):
norm_sq = 0.0
for k in range(c):
norm_sq += result[i, j, k] ** 2
norm = np.sqrt(norm_sq)
norms[i, j, 0] = 1.0 if norm == 0 else norm
return result, norms
5. Memory-efficient approach with convolution
If memory is a concern:
from scipy.signal import convolve
if agg:
kernel = np.ones((agg + 1, agg + 1, 1)) / ((agg + 1) ** 2)
data = convolve(data, kernel, mode='same')
For your typical case (h=w=few thousand, channels=1536, agg=5), I'd recommend starting with the uniform_filter approach as it's the simplest and usually the fastest. The scipy implementation is highly optimized and handles the boundary conditions properly.
If you need to process many such arrays, you might also consider:
- Processing in chunks if memory is limited
- Using GPU acceleration with CuPy if you have a CUDA-capable GPU
- Parallelizing across multiple arrays if you're processing batches