MOSS-TTS-Nano icon indicating copy to clipboard operation
MOSS-TTS-Nano copied to clipboard

Bug: RoPE inv_freq buffers are corrupted after loading MOSS-TTS-Nano with from_pretrained, causing NaN logits during inference

Open padmanabanSampath opened this issue 7 months ago • 2 comments

Bug: RoPE inv_freq buffers are corrupted after loading MOSS-TTS-Nano with from_pretrained, causing NaN logits during inference

Summary

When loading OpenMOSS-Team/MOSS-TTS-Nano with AutoModelForCausalLM.from_pretrained(..., trust_remote_code=True), the RoPE rotary embedding buffer inv_freq is corrupted after model loading/materialization.

This causes inference to fail with non-finite text logits:

RuntimeError: Non-finite text logits during generation: dtype=torch.float32 shape=(1, 16792) finite=0/16792 min=nan max=nan

The issue appears to affect the original base model, not only a fine-tuned or tokenizer-surgery checkpoint.

Environment

Observed on Kaggle notebook environment.

Approximate package/runtime setup:

Python: 3.12
torch: 2.7.0
transformers: 4.57.1
CUDA: enabled
Model: OpenMOSS-Team/MOSS-TTS-Nano
Audio tokenizer: OpenMOSS-Team/MOSS-Audio-Tokenizer-Nano
Load method: AutoModelForCausalLM.from_pretrained(..., trust_remote_code=True)

Expected behavior

For RoPE with dim=64 and base=10000, each MossTTSNanoGPT2RotaryEmbedding.inv_freq buffer should be finite, positive, and smoothly decreasing.

Expected first values are approximately:

[1.0, 0.749894, 0.562341, 0.421696, 0.316228, ...]

Expected range:

min ≈ 0.000133352
max = 1.0

Actual behavior

After loading the model, inv_freq contains random-looking garbage values: huge numbers, tiny denormals, zeros, and negative values.

Example output from the untouched base model:

transformer.h.0.attn.rotary_emb finite: True
min: -1.3073432061655048e-22
max: 1.1495482003995554e+24
first5: [3.448679564144186e-09, 4.447581195920537e-41, -1.3073432061655048e-22, 0.0, 0.0]

transformer.h.1.attn.rotary_emb finite: True
min: 1.576620464692849e-19
max: 2.8825913516525303e+32
first5: [1.1495482003995554e+24, 3.095554490839592e-18, 3.7747874159776984e-08, 8.265632622794783e-10, 1.0243667893095054e-11]

transformer.h.8.attn.rotary_emb finite: True
min: 0.0
max: 7.930346393097399e+34
first5: [0.0, 0.0006194331217557192, 1.8787745704090386e+31, 1.721986333012212e+22, 2.1714818704400124e-18]

local_transformer.h.0.attn.rotary_emb finite: True
min: 1.576620464692849e-19
max: 7.930346393097399e+34
first5: [1.093051650968846e-05, 0.00017583079170435667, 2.6684123799469717e-09, 2.3051111800592716e-12, 1.8787635691840801e+31]

These values are finite, so a simple NaN/Inf check does not catch the problem, but they are clearly invalid for RoPE.

Reproduction

import torch
from pathlib import Path
from transformers import AutoModelForCausalLM

BASE_MODEL = Path("/kaggle/working/MOSS-TTS-Nano/models/MOSS-TTS-Nano")
# Or use: "OpenMOSS-Team/MOSS-TTS-Nano"

model = AutoModelForCausalLM.from_pretrained(
    str(BASE_MODEL),
    trust_remote_code=True,
    torch_dtype=torch.float32,
).cuda().eval()

for name, module in model.named_modules():
    if module.__class__.__name__ == "MossTTSNanoGPT2RotaryEmbedding":
        inv = module.inv_freq.detach()
        print(
            name,
            "finite:", torch.isfinite(inv).all().item(),
            "min:", float(inv.float().min().item()),
            "max:", float(inv.float().max().item()),
            "first5:", inv[:5].detach().cpu().tolist(),
        )

Inference failure

During generation, the model eventually fails with all-NaN text logits:

WARNING:root:retrying inference with dtype=float32 attn_implementation=sdpa due to numerical instability

RuntimeError: Non-finite text logits during generation:
dtype=torch.float32
shape=(1, 16792)
finite=0/16792
min=nan
max=nan

A forward hook showed the first non-finite output appears around RoPE/attention:

FIRST NON-FINITE MODULE: transformer.h.1.attn.rotary_emb
module: MossTTSNanoGPT2RotaryEmbedding
output: {'shape': (1, 94, 1, 64), 'dtype': 'torch.float32', 'finite_count': 5850, 'total': 6016}

The input position IDs were normal:

shape: (1, 94)
dtype: torch.int64
min: 0
max: 93
finite: True

So the issue is not caused by invalid position IDs.

Cause / suspicion

The RoPE buffer is registered as non-persistent:

self.register_buffer("inv_freq", inv_freq, persistent=False)

Because persistent=False, the buffer is not stored in the checkpoint and must be correctly initialized during model construction.

However, after loading/materialization, inv_freq appears to contain uninitialized or corrupted memory.

The rotary embedding class appears to initialize it correctly:

class MossTTSNanoGPT2RotaryEmbedding(nn.Module):
    def __init__(self, dim: int, base: float = 10000.0) -> None:
        super().__init__()
        if dim % 2 != 0:
            raise ValueError(f"RoPE head_dim must be even, got {dim}")
        inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
        self.register_buffer("inv_freq", inv_freq, persistent=False)

So the corruption may be happening during Hugging Face/Transformers materialization/loading of the custom model, especially for non-persistent buffers.

Workaround

Manually resetting all RoPE inv_freq buffers immediately after loading fixes the issue:

import torch

def reset_moss_rope_inv_freq(model):
    fixed = 0
    for name, module in model.named_modules():
        if module.__class__.__name__ == "MossTTSNanoGPT2RotaryEmbedding":
            dim = int(module.inv_freq.numel() * 2)
            base = 10000.0

            inv_freq = 1.0 / (
                base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)
            )

            module.inv_freq = inv_freq.to(
                device=module.inv_freq.device,
                dtype=torch.float32,
            )

            fixed += 1

    print("reset rope modules:", fixed)

Usage:

model = AutoModelForCausalLM.from_pretrained(
    "OpenMOSS-Team/MOSS-TTS-Nano",
    trust_remote_code=True,
    torch_dtype=torch.float32,
).cuda().eval()

reset_moss_rope_inv_freq(model)

After reset, the buffers become correct:

reset transformer.h.0.attn.rotary_emb
min 0.0001333521504420787
max 1.0
first5 [1.0, 0.7498942017555237, 0.5623413324356079, 0.4216965138912201, 0.3162277638912201]

...
reset rope modules: 13

With this workaround, inference succeeds.

Suggested fix

Possible fixes:

  1. Make inv_freq persistent:

    self.register_buffer("inv_freq", inv_freq, persistent=True)
    
  2. Recompute inv_freq inside forward() or in a post-load hook.

  3. Add a model method such as:

    def reset_rope_inv_freq(self):
        ...
    

    and call it after loading.

  4. Add a sanity check during inference:

    if not torch.isfinite(inv_freq).all() or inv_freq.max() > 1.0 or inv_freq.min() <= 0:
        reset_rope_inv_freq(...)
    
  5. Investigate whether the issue is triggered by transformers model materialization with persistent=False buffers.

Impact

This bug can cause:

  • non-finite logits during generation,
  • failed inference,
  • unstable behavior that looks like training/fine-tuning failure,
  • difficult-to-debug NaNs because the corrupted buffers are finite but numerically invalid.

The workaround is simple and restores correct behavior.

padmanabanSampath avatar Apr 17 '26 14:04 padmanabanSampath

Thanks for the report and for the detailed debugging. We tested this again on our side and could not reproduce the reported issue. Both CPU and CUDA inference worked normally, and we did not observe corrupted RoPE inv_freq buffers or NaN text logits after loading with from_pretrained(..., trust_remote_code=True). Could you please double-check that the runtime environment is correct, especially whether transformers==4.57.1 is actually being used during execution? Thanks again for reporting this. We will continue to monitor for similar issues in future development.

alpacaking avatar Apr 21 '26 12:04 alpacaking

I also faced the same issues and the proposed work around does help.

neouyghur avatar May 28 '26 07:05 neouyghur