Great question! Yes, the EMA can be computed using a parallel prefix sum (scan) algorithm by rewriting the EMA recurrence in a form that allows parallelization.
Background
The EMA recurrence is:
[
y_t = \alpha x_t + (1-\alpha) y_{t-1}
]
with ( y_0 = x_0 ).
This can be unrolled as:
[
y_t = \alpha \sum_{k=0}^t (1-\alpha)^{t-k} x_k + (1-\alpha)^{t+1} y_{-1}
]
Assuming ( y_{-1} = 0 ) or ( y_0 = x_0 ), the formula simplifies to:
[
y_t = \alpha \sum_{k=0}^t (1-\alpha)^{t-k} x_k
]
Parallel Prefix Sum Formulation
Define:
[
w_k = (1-\alpha)^k
]
Then:
[
y_t = \alpha \sum_{k=0}^t w_{t-k} x_k = \alpha \sum_{k=0}^t w_{t-k} x_k
]
Re-index the sum:
[
y_t = \alpha \sum_{j=0}^t w_j x_{t-j}
]
This is a convolution of (x) with (w).
Using JAX to compute EMA via parallel scan
We can compute the EMA by:
- Computing the prefix sums of (x_k \cdot w_k) weighted by powers of ((1-\alpha)).
- Using a parallel scan to compute the weighted sums efficiently.
Implementation in JAX
import jax
import jax.numpy as jnp
def ema_parallel(data: jnp.ndarray, alpha: float) -> jnp.ndarray:
"""
Compute EMA using parallel prefix sums (scan) in JAX.
Args:
data: 1D array of data points.
alpha: decay factor (0 < alpha < 1).
Returns:
ema: 1D array of EMA values.
"""
n = data.shape[0]
one_minus_alpha = 1.0 - alpha
# Compute powers of (1-alpha): w_k = (1-alpha)^k
w = one_minus_alpha ** jnp.arange(n)
# Weighted data: x_k * w_k
weighted_data = data * w
# Compute prefix sums of weighted_data
prefix_sum = jnp.cumsum(weighted_data)
# Compute EMA using the formula:
# y_t = alpha * sum_{k=0}^t (1-alpha)^{t-k} x_k
# = alpha * (prefix_sum[t] / w[t])
ema = alpha * prefix_sum / w
return ema
# Example usage
if __name__ == "__main__":
import numpy as np
data = np.random.randn(10).astype(np.float32)
alpha = 0.1
ema_result = ema_parallel(data, alpha)
print("Data:", data)
print("EMA:", ema_result)
Explanation
- We precompute the weights (w_k = (1-\alpha)^k).
- Multiply the data by these weights.
- Compute the prefix sums of the weighted data (this is a parallelizable operation).
- Divide the prefix sums by (w_t) to get the EMA at each time step.
- Multiply by (\alpha) to finalize the EMA.
Performance