PyTorch torch.logcumsumexp function
PyTorch torch reference manual
torch.logcumsumexp is a function in PyTorch used to compute the log of the cumulative sum of exponentials. It exponentiates the elements, then cumulatively sums them, and finally takes the logarithm, which avoids numerical overflow.
Function definition
torch.logcumsumexp(input, dim)
Parameter Description:
input: the input tensordim: Dimension along which to compute the cumulative sum
Usage examples
Example
import
torch
Creating tensors
x
=
torch.
tensor
(
[
1.0
,
2.0
,
3.0
]
)
Compute the log of the cumulative sum of exponentials
y
=
torch.
logcumsumexp
(
x
,
dim
=
0
)
(
y
)
The output is:
tensor([1.0000, 2.3133, 3.1000])
Example
import
torch
Verify: log(exp(1) + exp(2)) = log(exp(1) + exp(2))
log(e^1 + e^2) = log(e^1 + e^2) ≈ 2.3133
x
=
torch.
tensor
(
[
1.0
,
2.0
]
)
y
=
torch.
logcumsumexp
(
x
,
dim
=
0
)
Compare with direct computation
import
math
direct
=
math
.
log
(
math
.
exp
(
1
)
math
.
exp
(
2
)
)
(
"logcumsumexp:"
,
y
[
1
]
.
item
(
)
)
(
"direct:"
,
direct
)
The output is:
logcumsumexp: 2.313261505126953
direct: 2.313261505126953