torch.cumprod
function cumprod(input: unknown, dim: unknown, options: unknown): TensorReturns the cumulative product along a dimension.
Computes running products, where each element is the product of all previous elements along the specified dimension. Useful for multiplicative processes and probability chains.
Commonly used for:
- Computing joint probabilities (product of independent probabilities)
- Factorial and combinatorial computations
- Multiplicative growth/decay processes (interest, population)
- Computing path weights in importance sampling
- Sequential model computations
- Shape is preserved - output has the same shape as input
- Multiplication can underflow (result → 0) or overflow (result → ∞) with many elements
- For numerical stability with many elements, consider computing in log-domain with cumsum(log(x))
- Unlike cumsum, products depend on all previous values - very sensitive to zeros
Parameters
inputunknown- The input tensor (any shape)
dimunknown- The dimension along which to compute cumulative product (0 to rank-1)
optionsunknown- Optional settings:
Returns
Tensor– Tensor with same shape as input, containing cumulative productsExamples
// Basic 1D cumulative product
const x = torch.tensor([1, 2, 3, 4, 5]);
torch.cumprod(x, 0); // [1, 2, 6, 24, 120] (factorials)
// 2D cumulative product along different dimensions
const x = torch.tensor([[1, 2, 3], [4, 5, 6]]);
torch.cumprod(x, 0); // [[1, 2, 3], [4, 10, 18]] - product along rows
torch.cumprod(x, 1); // [[1, 2, 6], [4, 20, 120]] - product along columns
// Joint probability computation
const probs = torch.tensor([0.9, 0.8, 0.7]); // Independent event probabilities
const joint = torch.cumprod(probs, 0); // [0.9, 0.72, 0.504]
// Discount factors (e.g., compound interest)
const rate = 1.05; // 5% growth
const years = torch.tensor([1, 2, 3, 4, 5], { dtype: 'float32' });
const factors = torch.fill(torch.empty([5]), rate);
const compound = torch.cumprod(factors, 0); // [1.05, 1.1025, 1.157625, ...]See Also
- PyTorch torch.cumprod()
- cumsum - Cumulative sum instead of product
- cumprod_ - In-place cumulative product
- logcumsumexp - Stable log computation for avoiding underflow
- prod - Total product (non-cumulative reduction)