Skip to content

Fix Whisper ASR timestamp regression - #1742

Open
anshusaurav wants to merge 4 commits into
huggingface:mainfrom
anshusaurav:fix/whisper-timestamp-regression-1684
Open

anshusaurav wants to merge 4 commits into
huggingface:mainfrom
anshusaurav:fix/whisper-timestamp-regression-1684

Conversation

@anshusaurav

Copy link
Copy Markdown

Summary

Fixes #1684 — Whisper ASR timestamp regression between v3.8.1 and v4.2.0.

Three fixes targeting the seek loop and logits processor introduced in commit 43b2662 ("Overdue Whisper fixes #1594"):

  • Use actual audio length for seek loop bounds (modeling_whisper.js): The seek loop used input_features.dims[2] (always 3000 = padded 30s) as total_frames instead of generation_config.num_frames (set by the ASR pipeline to the real mel frame count). For clips shorter than 30 seconds, this caused the loop to process silence/padding as real audio, producing hallucinated text and incorrect timestamps.

  • Apply max_initial_timestamp_index constraint (logits_process.js): A continue statement in WhisperTimeStampLogitsProcessor._call() skipped the max_initial_timestamp_index check at line 326, making it dead code. This allowed the model to generate any timestamp as its first token instead of being constrained to the allowed range. The Python reference implementation has no such early exit — both blocks execute sequentially.

  • Guard against infinite seek loop (modeling_whisper.js): If segment_offset computes to zero (e.g., from a degenerate timestamp pair), the seek loop would run forever. Added a break when segment_offset <= 0.

Test plan

  • Verify with the reproduction case from ASR (Whisper) regression for detected timestamps #1684 (Steve Jobs keynote audio) — timestamps should match v3.8.1 output
  • Verify [applause] segment is no longer dropped
  • Existing Whisper prefix token tests (test_modeling_whisper.js) still pass — they use max_new_tokens which bypasses the seek loop
  • Test with audio shorter than 30s — seek loop should terminate after one iteration
  • Test with audio longer than 30s — multi-segment seek should still work correctly

@nico-martin nico-martin self-assigned this Aug 24, 2026
@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@nico-martin nico-martin left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @anshusaurav, thank you so much for looking into this! The diagnosis and overall direction make sense. One edge case remains: num_frames can be 0, so the truthy check falls back to the padded tensor. Could you use a nullish check and add direct tests for short audio, timestamp masking, and the non-progress case? I'm holding off on merging until the zero-frame bug and untested seek-loop changes are covered.

// input_features shape: [batch=1, n_mels, total_frames]
const input_features = inputs;
const total_frames = input_features.dims[2];
const total_frames = generation_config.num_frames

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

num_frames can legitimately be 0. This truthiness check then falls back to the padded 3,000-frame tensor and reintroduces padding processing. Please distinguish an omitted value from zero, for example with generation_config.num_frames != null, and add a zero/short-frame regression test.

@anshusaurav

Copy link
Copy Markdown
Author

Thanks for the thorough review @nico-martin!

Just pushed the requested changes:

  1. Nullish check — changed generation_config.num_frames (truthy) to generation_config.num_frames != null so that num_frames=0 is correctly treated as zero frames rather than falling back to the padded tensor length.

  2. Tests added:

    • num_frames=0 — verifies the seek loop does not execute on zero frames
    • Short audio (500 frames < 3000 segment) with timestamps — verifies no crash on sub-segment input
    • Timestamp token presence — verifies return_timestamps=true produces timestamp tokens in the output

@nico-martin

Copy link
Copy Markdown
Collaborator

Thanks, the nullish check correctly fixes the num_frames=0 case. The added tests still do not exercise the changed seek-loop behavior, however: each passes max_new_tokens, and generate() explicitly bypasses _generate_with_seek() whenever that option is present.

Could you adjust the coverage so that:

  • zero frames and padded short audio run through the seek path without max_new_tokens
  • the short-audio case uses a padded 3000-frame tensor with num_frames: 500
  • timestamp masking asserts that initial timestamp IDs above timestamp_begin + max_initial_timestamp_index are masked, preferably with a direct WhisperTimeStampLogitsProcessor unit test
  • a mocked degenerate timestamp pair produces segment_offset === 0 and terminates after one pass
  • normal multi-segment output advances through the expected passes?

The current timestamp-presence assertion and short-input smoke test would pass with the corresponding fixes reverted. Also, the added Tensor import is currently unused.

@txscribe

Copy link
Copy Markdown

We ran into this independently and have been carrying a patched build of transformers.js
because of it, so here is a confirmation plus the seek-loop test this PR is waiting for.

Where it bites. Electron app, WebGPU, onnx-community/whisper-base, dtype q4,
return_timestamps: true, chunk_length_s: 30. On a 16.8-minute Chinese recording one
window decodes to [<|0.00|>, 1654, <|0.00|>, <|24.00|>]. That is a complete segment whose
end timestamp is <|0.00|>, so last_ts_pos is 0, segment_offset is 0, and the same 30
seconds is decoded again with the same result. Instrumented, we saw 200 passes at seek = 0
in 14 seconds and no return; in the app itself one run logged 552 passes before it was
killed. Nothing fails: the GPU stays busy, the progress bar stops, and every job queued
behind it waits.

The test. It drives _generate_with_seek itself, with the decoder mocked, so it does
exercise the changed path — no model, no audio, milliseconds to run:

describe("seek loop", () => {
  const NO_TIMESTAMPS = 50363;
  const TIMESTAMP_BEGIN = NO_TIMESTAMPS + 1;
  const EOS = 50257;
  const INIT = [50258, 50260, 50360];

  /** Runs the seek loop over 30 s of features with a decoder that returns `tokens` each pass. */
  const runSeek = async (tokens, cap = 50) => {
    const whisperProto = Object.getPrototypeOf(WhisperForConditionalGeneration.prototype);
    const original = Object.getOwnPropertyDescriptor(whisperProto, "generate");
    let passes = 0;
    whisperProto.generate = async ({ decoder_input_ids }) => {
      if (++passes > cap) throw new Error(`the seek loop is still decoding after ${cap} passes`);
      const ids = [...decoder_input_ids, ...tokens, EOS].map(BigInt);
      return new Tensor("int64", BigInt64Array.from(ids), [1, ids.length]);
    };
    try {
      const model = Object.create(WhisperForConditionalGeneration.prototype);
      model.config = { max_source_positions: 1500 };
      const output = await model._generate_with_seek({
        inputs: new Tensor("float32", new Float32Array(80 * 3000), [1, 80, 3000]),
        generation_config: { no_timestamps_token_id: NO_TIMESTAMPS, eos_token_id: EOS, return_timestamps: true },
        logits_processor: [],
        init_tokens: INIT,
        kwargs: {},
      });
      return { passes, tokens: output[0].tolist().map(Number) };
    } finally {
      if (original) Object.defineProperty(whisperProto, "generate", original);
      else delete whisperProto.generate;
    }
  };

  it(
    "terminates when a segment ends at <|0.00|>",
    async () => {
      // What a real decode produced: a complete segment whose end timestamp is 0.00.
      const { passes } = await runSeek([TIMESTAMP_BEGIN, 1654, TIMESTAMP_BEGIN, TIMESTAMP_BEGIN + 1200]);
      expect(passes).toBe(1);
    },
    MAX_TEST_EXECUTION_TIME,
  );

  it(
    "still advances through ordinary multi-segment output",
    async () => {
      // A segment ending at <|10.00|> is 1000 frames a pass: three passes over 3000.
      const { passes } = await runSeek([TIMESTAMP_BEGIN, 1654, TIMESTAMP_BEGIN + 500, TIMESTAMP_BEGIN + 1200]);
      expect(passes).toBe(3);
    },
    MAX_TEST_EXECUTION_TIME,
  );
});

Measured against the 4.3.0 dist, which carries the same loop as main (we have not run it
inside your harness):

| build | terminates at <|0.00|> | ordinary multi-segment |
|---|---|---|
| as shipped | fails — still decoding after 50 passes | passes (3 passes) |
| with if (segment_offset <= 0) break; | passes — returns after 1 pass | passes (3 passes) |

So the guard in this PR does fix the hang, and the first test fails without it.

Two notes on the fix itself, take or leave:

  1. break leaves the loop for good. The function already has a rule for a window with no
    complete segment — segment_offset = seek_end - seek, with tokens_to_keep left at
    generated_tokens.length. Reusing that rule when the offset computes to zero consumes the
    window instead of abandoning it: it keeps the tokens the model did produce (on the test
    above, 8 tokens including the trailing <|24.00|>, against 7 with break), and it stays
    correct if anything ever passes _generate_with_seek more than one window of features,
    where break would end the transcript at that point.
  2. A window that advances but hardly is not covered by segment_offset <= 0. Feed the same
    mock a segment end that creeps forward — 0.2 s on the first pass, growing to 2 s — and the
    same 30 seconds is re-encoded and re-decoded 20 times before the loop moves on, each pass a
    full encode and decode. We bound it: after 3 consecutive passes that advance less than a
    second, the window is consumed the same way, which takes those 20 passes to 3. That is a
    performance cliff rather than a hang, so it may belong in its own PR — happy to open one.

We apply both as a build-time source transform (we can only patch the bundle, not
node_modules), and both have been running against 4.3.0 in our own Electron build.


— txscribe.ai

@anshusaurav
anshusaurav force-pushed the fix/whisper-timestamp-regression-1684 branch from 6bb512b to 5765208 Compare October 5, 2026 09:09
@anshusaurav

Copy link
Copy Markdown
Author

Thanks @nico-martin and @txscribe. I rebased this branch onto the current main and replaced the previous smoke coverage with direct regression tests:

  • _generate_with_seek() now runs without max_new_tokens for num_frames: 0 and for a padded 3,000-frame input with num_frames: 500
  • the zero-offset timestamp case terminates after one pass
  • ordinary multi-segment output advances through the expected three passes
  • a direct WhisperTimeStampLogitsProcessor test verifies that initial timestamp IDs above timestamp_begin + max_initial_timestamp_index are masked

The focused tests pass locally (4 seek-loop tests and 1 timestamp-processor test). Could you please take another look when the refreshed CI completes?

@nico-martin

Copy link
Copy Markdown
Collaborator

Hi @anshusaurav, thanks for updating this! The new tests address my earlier coverage requests.

Two things still need fixing:

Could you handle those and add a test where a zero-offset window is followed by more audio? We should either continue safely or report an error rather than return an incomplete transcript as success.

Three fixes for the timestamp regression between v3.8.1 and v4.2.0:

1. Use actual audio length for seek loop bounds: The seek loop used
   input_features.dims[2] (always 3000 = padded 30s) instead of
   generation_config.num_frames (actual audio length). For clips
   shorter than 30s, this caused the loop to process silence as
   real audio, producing hallucinated text and wrong timestamps.

2. Apply max_initial_timestamp_index constraint: A `continue`
   statement in WhisperTimeStampLogitsProcessor skipped the
   max_initial_timestamp_index check, allowing the model to
   generate any timestamp as its first token. The Python reference
   implementation has no such early exit.

3. Guard against infinite seek loop: If segment_offset is zero
   (e.g., from a degenerate timestamp pair), the loop ran forever.
Address review feedback:
- Change truthy check to nullish check (num_frames != null) so that
  num_frames=0 is not mistaken for an omitted value, which would
  incorrectly fall back to the padded tensor length
- Add tests for zero num_frames, short audio with timestamps, and
  timestamp token presence
@anshusaurav
anshusaurav force-pushed the fix/whisper-timestamp-regression-1684 branch from 5765208 to 12a9b7b Compare November 21, 2026 21:38
@anshusaurav

Copy link
Copy Markdown
Author

Addressed the November 11 feedback and rebased onto the current main:

  • aligned missing/default max_initial_timestamp_index handling with Fix max_initial_timestamp_index never being applied in WhisperTimeStampLogitsProcessor #1823 by using a null default and a nullish guard; added omitted, null, zero, explicit-value, and later-step coverage
  • replaced the zero-offset break with safe current-window advancement, so later audio is still decoded
  • added a 6,000-frame regression test that verifies two decoding passes and retains the following window's transcript token

The focused timestamp-processor tests pass, and direct seek-loop verification completes two passes while retaining the second-window token.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ASR (Whisper) regression for detected timestamps

4 participants