Skip to content

Parakeet tdt_loss produces NaN gradients for valid custom durations because logsumexp is evaluated on unreachable states #51468

Backlog

Description

@dovvnloading

System Info

  • Transformers version: 5.25.0.dev0
  • Branch: main
  • Commit: 539b6c4
  • Python version: 3.13.5
  • PyTorch version: 2.10.0+cpu
  • Platform: Linux x86_64, kernel 6.18.57
  • Device: CPU
  • CUDA: Not required
  • Reproduction date: November 29, 2026

The exact tdt_loss implementation from the referenced
commit was executed directly with PyTorch. A complete
Transformers installation was unavailable in the
execution environment.

Who can help?

@eustlb @ebezzam

Reproduction

The PyTorch implementation of Token-and-Duration Transducer
loss can produce NaN gradients even when its forward loss
is finite.

This occurs when the configured duration values create
unreachable states in the dynamic programming lattice.

For example, the duration list [0, 2, 3] permits a valid
alignment for an input containing three encoder frames
and one target token. However, some intermediate states
are unreachable.

The ParakeetTDTConfig documentation exposes durations
as a configurable list of predicted duration values:

class ParakeetTDTConfig(ParakeetRNNTConfig):
r"""
A TDT (Token-and-Duration Transducer) extends the base RNN-T configuration [`ParakeetRNNTConfig`] with a
`durations` field: the joint network gains a duration head (its output width grows from `vocab_size` to
`vocab_size + len(durations)`), and during greedy decoding the encoder frame pointer advances by the
predicted duration rather than a fixed single frame.
decoder_hidden_size (`int`, *optional*, defaults to 640):
Hidden size of the LSTM prediction network and joint network.
num_decoder_layers (`int`, *optional*, defaults to 2):
Number of LSTM layers in the prediction network.
max_symbols_per_step (`int`, *optional*, defaults to 10):
Maximum number of symbols to emit per encoder time step during greedy decoding.
durations (`list[int]`, *optional*, defaults to `[0, 1, 2, 3, 4]`):
Token duration values that can be predicted. Each value represents how many frames a token or blank
emission spans.
encoder_config (`Union[dict, ParakeetEncoderConfig]`, *optional*):
The config object or dictionary of the encoder.
blank_token_id (`int`, *optional*, defaults to 8192):
Blank token id. Different from `pad_token_id` for TDT.
Example:
```python
>>> from transformers import ParakeetForTDT, ParakeetTDTConfig
>>> # Initializing a Parakeet TDT configuration
>>> configuration = ParakeetTDTConfig()
>>> # Initializing a model from the configuration
>>> model = ParakeetForTDT(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```
"""
model_type = "parakeet_tdt"
durations: list[int] | tuple[int, ...] = (0, 1, 2, 3, 4)

The following deterministic reproduction uses the
documented TDT loss function and compares the custom
duration configuration against the default durations.

import torch
from transformers.loss.loss_tdt import tdt_loss

for durations in ([0, 2, 3], [0, 1, 2, 3, 4]):
    token_logits = torch.zeros(
        1, 3, 2, 3, requires_grad=True
    )

    duration_logits = torch.zeros(
        1, 3, 2, len(durations), requires_grad=True
    )

    loss = tdt_loss(
        token_logits,
        duration_logits,
        torch.tensor([[1]]),
        torch.tensor([3]),
        torch.tensor([1]),
        blank_token_id=0,
        durations=durations,
        reduction="sum",
    )

    loss.backward()

    print(
        f"durations={durations}, loss={loss.item():.6f}"
    )

    print(
        "token gradients finite:",
        torch.isfinite(token_logits.grad).all().item(),
    )

    print(
        "duration gradients finite:",
        torch.isfinite(duration_logits.grad).all().item(),
    )

    print(
        "token gradient NaNs:",
        torch.isnan(token_logits.grad).sum().item(),
    )

    print(
        "duration gradient NaNs:",
        torch.isnan(duration_logits.grad).sum().item(),
    )

Actual output:

durations=[0, 2, 3], loss=4.394449
token gradients finite: False
duration gradients finite: False
token gradient NaNs: 6
duration gradient NaNs: 6
durations=[0, 1, 2, 3, 4], loss=4.188411
token gradients finite: True
duration gradients finite: True
token gradient NaNs: 0
duration gradient NaNs: 0

The failure occurs with ordinary finite, zero-initialized
logits. It does not require mixed precision, a GPU,
large logits, or numerical overflow in the model.

Expected behavior

When a valid alignment exists and the input logits are
finite, both the forward loss and gradients should be
finite.

For the custom [0, 2, 3] duration list above, a valid
alignment exists: emit the target token with duration zero,
then emit a blank spanning three frames.

With uniform token and duration distributions, each of
these transitions has probability 1/9. The valid path
therefore has probability 1/81, giving a negative
log-likelihood of approximately 4.394449.

The forward result is consistent with this alignment,
but its gradients are incorrectly contaminated by NaNs.

Root cause

The dynamic programming lattice is initialized using
negative infinity for unreachable states.

The anti-diagonal processing constructs candidate
transitions and masks invalid candidates to negative
infinity.

Relevant implementation:

# Process anti-diagonals: all (t, u) with t + u = n have no mutual dependencies
for n in range(1, max_t + max_u - 1):
u_start = max(0, n - max_t + 1)
u_end = min(n + 1, max_u)
u_indices = torch.arange(u_start, u_end, device=device)
t_indices = n - u_indices
all_candidates = []
for i, dur in enumerate(durations):
t_prev = t_indices - dur
valid_t = t_prev >= 0
if not valid_t.any():
continue
t_src = t_prev.clamp(min=0)
# Blank arcs (dur > 0): from (t-dur, u) to (t, u)
if dur > 0:
contrib = (
log_alpha[:, t_src, u_indices]
+ blank_log_probs[:, t_src, u_indices]
+ duration_log_probs[:, t_src, u_indices, i]
)
contrib = torch.where(valid_t.unsqueeze(0), contrib, neg_inf)
all_candidates.append(contrib)
# Label arcs: from (t-dur, u-1) to (t, u), only if u > 0
valid_u = u_indices > 0
valid_both = valid_t & valid_u
if valid_both.any():
u_src = (u_indices - 1).clamp(min=0)
u_src_label = u_src.clamp(max=max_u - 2) if max_u > 1 else u_src
contrib = (
log_alpha[:, t_src, u_src]
+ label_log_probs[:, t_src, u_src_label]
+ duration_log_probs[:, t_src, u_src, i]
)
contrib = torch.where(valid_both.unsqueeze(0), contrib, neg_inf)
all_candidates.append(contrib)
if all_candidates:
stacked = torch.stack(all_candidates, dim=0)
log_alpha[:, t_indices, u_indices] = torch.logsumexp(stacked, dim=0)

The reduction at lines 132–134 is unconditional:

if all_candidates:
    stacked = torch.stack(all_candidates, dim=0)
    log_alpha[:, t_indices, u_indices] = torch.logsumexp(
        stacked, dim=0
    )

Checking whether all_candidates is non-empty does
not guarantee that an individual lattice position has
a finite incoming transition.

An unreachable position may have every candidate equal
to negative infinity.

Although torch.logsumexp() returns negative infinity
for such a position, its backward operation can produce
NaNs because the corresponding normalized exponential
weights are undefined.

These NaNs can propagate into token and duration logits
even when the terminal state has a valid alignment and
the overall forward loss is finite.

A similar reduction pattern exists in the terminal-state
accumulation:

# Terminal probability: sum over blank arcs that reach (T, U) from (T-dur, U)
batch_idx = torch.arange(batch_size, device=device)
log_probs = torch.full((batch_size,), float("-inf"), device=device)
for i, dur in enumerate(durations):
if dur == 0:
continue
t_final = logit_lengths - dur
valid = t_final >= 0
if not valid.any():
continue
t_clamped = t_final.clamp(min=0)
terminal = (
log_alpha[batch_idx, t_clamped, target_lengths]
+ token_log_probs[batch_idx, t_clamped, target_lengths, blank_token_id]
+ duration_log_probs[batch_idx, t_clamped, target_lengths, i]
)
combined = torch.stack([log_probs, terminal], dim=0)
log_probs = torch.where(valid, torch.logsumexp(combined, dim=0), log_probs)

Impact

Training custom TDT models with duration configurations
that introduce unreachable lattice states can produce
non-finite gradients despite apparently healthy loss
values.

This may cause:

  • Corrupted parameter updates.
  • NaN model weights.
  • Failed or stalled training.
  • Misleading monitoring when only the forward loss
    is checked.

The demonstrated failure concerns the PyTorch loss
implementation with custom durations. The default
duration configuration succeeds in the supplied test.

Duplicate check

Searched open and closed issues and pull requests using:

  • tdt_loss
  • TDT and NaN
  • TDT and logsumexp
  • tdt_loss and gradient
  • Parakeet, duration, and gradient

Relevant open pull requests:

Neither addresses the reproduced all-negative-infinity
reduction problem in the default PyTorch implementation.

No matching duplicate was found.

Proposed fix

Introduce an autograd-safe logsumexp reduction for
unreachable lattice positions.

Before evaluating logsumexp, identify positions for
which all candidate values are negative infinity.
Replace the inputs for those positions with finite
temporary values, perform the reduction, and then
restore negative infinity using a differentiable mask.

For example:

unreachable = torch.isneginf(stacked).all(dim=0)

safe_stacked = torch.where(
    unreachable.unsqueeze(0),
    torch.zeros_like(stacked),
    stacked,
)

reduced = torch.logsumexp(safe_stacked, dim=0)

reduced = torch.where(
    unreachable,
    torch.full_like(reduced, float("-inf")),
    reduced,
)

This prevents autograd from evaluating an undefined
logsumexp derivative for unreachable states while
preserving their correct forward probabilities.

Apply the same protection to terminal reductions where
necessary.

Add regression tests using non-consecutive durations,
including [0, 2, 3], that verify:

  1. A finite loss when a valid alignment exists.
  2. Finite token gradients.
  3. Finite duration gradients.
  4. Agreement with a reference path-probability
    calculation.
  5. Unchanged results for the default duration list.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions