softmax_torch ¶
log_softmax, softmax and cross_entropy without Softmax Collapse, in PyTorch.
Author: Ke Xu (https://github.com/kevinkexu) Reference: J. T. Barron, D. Gnanapragasam, M. Tschannen, "A Fix for Softmax and Cross-Entropy", arXiv 2610.31642, Section 2.
The standard log-softmax forms 1 + e^{-m}, which rounds to 1 once the top logit leads by a
margin m past half an ulp (16.6 in float32, 5.5 in bfloat16): the top entry's log-probability
and gradient become 0 and the row's gradient no longer sums to zero. The fix never forms that sum:
s_k = 1[k != argmax] (z_k - z_max), log_softmax_k = s_k - softplus(LSE_{j != argmax} s_j)
so the argmax logit enters only through differences and autodiff gives it minus the sum of the
other gradients. log_prob_of uses the target in place of the argmax.
log_softmax ¶
Drop-in replacement for torch.log_softmax that does not collapse at large margins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
Logits of any shape and floating dtype. |
required |
dim
|
int
|
Dimension to normalise over. |
-1
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Log-probabilities with the shape and dtype of |
Source code in softmax_torch.py
softmax ¶
exp(log_softmax(z, dim)); drop-in replacement for torch.softmax.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
Logits of any shape and floating dtype. |
required |
dim
|
int
|
Dimension to normalise over. |
-1
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Probabilities with the shape and dtype of |
Source code in softmax_torch.py
log_prob_of ¶
Log-probability of one class per row, log_softmax(z)[..., target], without forming the
full log-softmax. Useful for policy gradients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
Logits |
required |
target
|
Tensor
|
Integer class indices of shape |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
|
Source code in softmax_torch.py
cross_entropy ¶
cross_entropy(
logits: Tensor,
target: Tensor,
ignore_index: int = -100,
reduction: str = "mean",
) -> torch.Tensor
Hard-target cross-entropy -log_prob_of(logits, target).
Unlike torch.nn.functional.cross_entropy, the class dimension is the last one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Logits |
required |
target
|
Tensor
|
Integer class indices |
required |
ignore_index
|
int
|
Rows with this target contribute 0 and are left out of the |
-100
|
reduction
|
str
|
|
'mean'
|
Returns:
| Type | Description |
|---|---|
Tensor
|
The loss; |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |