softmax_tf ¶
log_softmax, softmax and cross_entropy without Softmax Collapse, in TensorFlow.
Reference: J. T. Barron, D. Gnanapragasam, M. Tschannen, "A Fix for Softmax and Cross-Entropy",
arXiv 2610.31642, Section 2. Same math as softmax_torch.py:
s_k = 1[k != argmax] (z_k - z_max), log_softmax_k = s_k - softplus(LSE_{j != argmax} s_j)
Works eagerly and inside tf.function.
log_softmax ¶
Drop-in replacement for tf.nn.log_softmax that does not collapse at large margins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
Logits of any shape and floating dtype (anything |
required |
axis
|
int
|
Axis to normalise over. |
-1
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Log-probabilities with the shape and dtype of |
Source code in softmax_tf.py
softmax ¶
exp(log_softmax(z, axis)); drop-in replacement for tf.nn.softmax.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Tensor
|
Logits of any shape and floating dtype. |
required |
axis
|
int
|
Axis to normalise over. |
-1
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Probabilities with the shape and dtype of |
Source code in softmax_tf.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_tf.py
cross_entropy ¶
cross_entropy(
logits: Tensor,
target: Tensor,
ignore_index: int = -100,
reduction: str = "mean",
) -> tf.Tensor
Hard-target cross-entropy -log_prob_of(logits, target), like
tf.nn.sparse_softmax_cross_entropy_with_logits plus ignore_index and reduction.
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 |