1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use smallvec::smallvec;
use crate::{Element, Recordable, Shape, Tensor};
use super::{Cotangents, Operation, Reads, unary};
/// The log-softmax of a payload along one named axis:
/// `x - ln(sum(exp(x)))`, the logarithm of the softmax probabilities.
///
/// It is a fused primitive rather than a composition because the stable
/// forward must shift by the axis maximum before exponentiating, and no
/// composition of recorded operations can express that shift without a
/// differentiable `max`. The gradient is `g - softmax * sum(g)` along the
/// axis, recovering the probabilities from the node's own output as
/// `exp(output)` — the shift cancels analytically and never appears in
/// the backward rule.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct LogSoftmax {
pub(crate) axis: usize,
}
impl LogSoftmax {
/// Returns the arity: one operand.
pub(crate) fn arity(&self) -> usize {
1
}
/// Returns the read set of the derivative rule below.
/// It reads its own output to recover the probabilities.
pub(crate) fn reads(&self) -> Reads {
Reads {
operands: [false, false],
output: true,
}
}
/// Infers the shape of the result: the operand's shape, with the
/// axis checked against its rank.
pub(crate) fn infer_shape(&self, operands: &[Shape]) -> Shape {
let operand = unary(operands);
assert!(
self.axis < operand.rank(),
"axis {} is out of rank for {operand}",
self.axis
);
operand.clone()
}
}
impl LogSoftmax {
pub(crate) fn forward<E: Element>(&self, operands: &[&Tensor<E>]) -> Tensor<E> {
unary(operands).log_softmax(self.axis)
}
}
impl<Rule: Recordable> Operation<Rule> for LogSoftmax {
fn backward(&self, _operands: &[&Rule], output: &Rule, gradient: &Rule) -> Cotangents<Rule> {
let extent = gradient.shape().axes()[self.axis];
let total = gradient
.sum_along(self.axis)
.broadcast_along(self.axis, extent);
smallvec![Some(gradient.clone() - output.exp() * total)]
}
}
#[cfg(test)]
#[path = "tests/log_softmax_tests.rs"]
mod tests;