From b6291bc466256bb073ca9eedefc3f14a50d372a9 Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Fri, 20 Feb 2026 14:21:58 -0700 Subject: [PATCH 01/21] Add beam search support with BeamHypotheses and BeamSearchScorer classes --- .../src/generation/beam_search.js | 231 +++++++++++++++ .../transformers/src/models/modeling_utils.js | 269 +++++++++++++++--- packages/transformers/src/transformers.js | 1 + packages/transformers/src/utils/tensor.js | 67 +++++ .../tests/utils/generation.test.js | 147 ++++++++++ 5 files changed, 675 insertions(+), 40 deletions(-) create mode 100644 packages/transformers/src/generation/beam_search.js diff --git a/packages/transformers/src/generation/beam_search.js b/packages/transformers/src/generation/beam_search.js new file mode 100644 index 000000000..e6475db8f --- /dev/null +++ b/packages/transformers/src/generation/beam_search.js @@ -0,0 +1,231 @@ +/** + * @module generation/beam_search + */ + +/** + * Stores completed beam search hypotheses for a single batch element. + */ +export class BeamHypotheses { + /** + * @param {number} num_beams Number of beams. + * @param {number} length_penalty Exponential penalty to the length. + * @param {boolean|"never"} early_stopping Whether to stop when enough hypotheses are finished. + */ + constructor(num_beams, length_penalty = 1.0, early_stopping = false) { + this.num_beams = num_beams; + this.length_penalty = length_penalty; + this.early_stopping = early_stopping; + + /** @type {{score: number, tokens: bigint[]}[]} */ + this.beams = []; + this.worst_score = 1e9; + } + + get length() { + return this.beams.length; + } + + /** + * Add a new hypothesis to the list. + * @param {number} sum_logprobs Sum of log probabilities of the hypothesis. + * @param {bigint[]} tokens The token ids of the hypothesis. + */ + add(sum_logprobs, tokens) { + const score = sum_logprobs / (tokens.length ** this.length_penalty); + if (this.beams.length < this.num_beams || score > this.worst_score) { + this.beams.push({ score, tokens }); + if (this.beams.length > this.num_beams) { + // Remove worst hypothesis + let worst_idx = 0; + for (let i = 1; i < this.beams.length; ++i) { + if (this.beams[i].score < this.beams[worst_idx].score) { + worst_idx = i; + } + } + this.beams.splice(worst_idx, 1); + } + this.worst_score = this.beams.length === this.num_beams + ? Math.min(...this.beams.map(b => b.score)) + : -1e9; + } + } + + /** + * Check whether adding more beams can possibly improve the hypotheses. + * @param {number} best_sum_logprobs Best sum of log probs among active beams. + * @param {number} cur_len Current length of generated tokens. + * @returns {boolean} + */ + is_done(best_sum_logprobs, cur_len) { + if (this.beams.length < this.num_beams) return false; + + if (this.early_stopping === true) { + return true; + } else if (this.early_stopping === 'never') { + return false; + } else { + // Heuristic: check if the best possible score for the next step + // could beat the worst completed hypothesis + const highest_attainable_score = best_sum_logprobs / (cur_len ** this.length_penalty); + return this.worst_score >= highest_attainable_score; + } + } +} + +/** + * Implements beam search scoring and beam management. + */ +export class BeamSearchScorer { + /** + * @param {number} batch_size + * @param {number} num_beams + * @param {Object} options + * @param {number} [options.length_penalty] + * @param {boolean|"never"} [options.early_stopping] + * @param {number} [options.num_return_sequences] + * @param {number|number[]|null} [options.eos_token_id] + * @param {number|null} [options.pad_token_id] + */ + constructor(batch_size, num_beams, { + length_penalty = 1.0, + early_stopping = false, + num_return_sequences = 1, + eos_token_id = null, + pad_token_id = null, + } = {}) { + this.batch_size = batch_size; + this.num_beams = num_beams; + this.length_penalty = length_penalty; + this.early_stopping = early_stopping; + this.num_return_sequences = num_return_sequences; + this.eos_token_ids = eos_token_id === null ? [] + : (Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]); + this.pad_token_id = pad_token_id ?? 0; + + if (num_return_sequences > num_beams) { + throw new Error( + `num_return_sequences (${num_return_sequences}) must be <= num_beams (${num_beams}).`, + ); + } + + /** @type {BeamHypotheses[]} */ + this._beam_hyps = Array.from( + { length: batch_size }, + () => new BeamHypotheses(num_beams, length_penalty, early_stopping), + ); + /** @type {boolean[]} */ + this._done = new Array(batch_size).fill(false); + } + + get is_done() { + return this._done.every(Boolean); + } + + /** + * Process the current beam candidates and select the next set of beams. + * + * @param {bigint[][]} all_input_ids All sequences so far, shape [batch_size * num_beams, seq_len]. + * @param {number[]} beam_scores Cumulative scores, shape [batch_size * num_beams]. + * @param {bigint[]} next_tokens Candidate tokens, shape [batch_size * 2 * num_beams]. + * @param {number[]} next_indices Which beam each candidate came from (relative to batch group), shape [batch_size * 2 * num_beams]. + * @param {number[]} next_scores New cumulative scores for candidates, shape [batch_size * 2 * num_beams]. + * @returns {{ next_beam_scores: number[], next_beam_tokens: bigint[], next_beam_indices: number[] }} + */ + process(all_input_ids, beam_scores, next_tokens, next_indices, next_scores) { + const cur_len = all_input_ids[0].length; + const total_beams = this.batch_size * this.num_beams; + + const next_beam_scores = new Array(total_beams).fill(0); + const next_beam_tokens = new Array(total_beams).fill(0n); + const next_beam_indices = new Array(total_beams).fill(0); + + for (let batch_idx = 0; batch_idx < this.batch_size; ++batch_idx) { + if (this._done[batch_idx]) { + // Pad finished batches + for (let beam_idx = 0; beam_idx < this.num_beams; ++beam_idx) { + const flat_idx = batch_idx * this.num_beams + beam_idx; + next_beam_scores[flat_idx] = 0; + next_beam_tokens[flat_idx] = BigInt(this.pad_token_id); + next_beam_indices[flat_idx] = batch_idx * this.num_beams; + } + continue; + } + + let beam_idx = 0; + const num_candidates = 2 * this.num_beams; + for (let j = 0; j < num_candidates; ++j) { + const cand_idx = batch_idx * num_candidates + j; + const beam_token = next_tokens[cand_idx]; + const beam_score = next_scores[cand_idx]; + const beam_source = next_indices[cand_idx]; // relative to batch + const abs_beam_source = batch_idx * this.num_beams + beam_source; + + const is_eos = this.eos_token_ids.some(id => BigInt(id) === beam_token); + + if (is_eos) { + // Add completed hypothesis + const hypothesis = [...all_input_ids[abs_beam_source], beam_token]; + this._beam_hyps[batch_idx].add(beam_score, hypothesis); + } else { + // Add to next active beams + const out_idx = batch_idx * this.num_beams + beam_idx; + next_beam_scores[out_idx] = beam_score; + next_beam_tokens[out_idx] = beam_token; + next_beam_indices[out_idx] = abs_beam_source; + beam_idx++; + } + + if (beam_idx === this.num_beams) break; + } + + // If we couldn't fill all beams (too many EOS), pad with last valid + if (beam_idx < this.num_beams) { + const last_valid = batch_idx * this.num_beams + Math.max(0, beam_idx - 1); + for (; beam_idx < this.num_beams; ++beam_idx) { + const out_idx = batch_idx * this.num_beams + beam_idx; + next_beam_scores[out_idx] = next_beam_scores[last_valid] ?? 0; + next_beam_tokens[out_idx] = next_beam_tokens[last_valid] ?? 0n; + next_beam_indices[out_idx] = next_beam_indices[last_valid] ?? (batch_idx * this.num_beams); + } + } + + // Check if done for this batch using next-step scores + const start = batch_idx * this.num_beams; + const end = start + this.num_beams; + const best_sum_logprobs = Math.max(...next_beam_scores.slice(start, end)); + this._done[batch_idx] = this._beam_hyps[batch_idx].is_done(best_sum_logprobs, cur_len + 1); + } + + return { next_beam_scores, next_beam_tokens, next_beam_indices }; + } + + /** + * Finalize: select best hypotheses. + * @param {bigint[][]} all_input_ids Final sequences, shape [batch_size * num_beams, seq_len]. + * @param {number[]} beam_scores Final cumulative scores. + * @returns {bigint[][]} Best sequences, shape [batch_size * num_return_sequences, seq_len]. + */ + finalize(all_input_ids, beam_scores) { + // For each batch, ensure we have enough hypotheses + for (let batch_idx = 0; batch_idx < this.batch_size; ++batch_idx) { + const hyps = this._beam_hyps[batch_idx]; + if (hyps.length < this.num_beams) { + for (let beam_idx = 0; beam_idx < this.num_beams; ++beam_idx) { + const flat_idx = batch_idx * this.num_beams + beam_idx; + hyps.add(beam_scores[flat_idx], all_input_ids[flat_idx]); + } + } + } + + // Select top num_return_sequences per batch + const results = []; + for (let batch_idx = 0; batch_idx < this.batch_size; ++batch_idx) { + const sorted = [...this._beam_hyps[batch_idx].beams] + .sort((a, b) => b.score - a.score); + for (let i = 0; i < this.num_return_sequences; ++i) { + results.push(sorted[i].tokens); + } + } + return results; + } +} diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js index 51487cec2..ef6f7088d 100644 --- a/packages/transformers/src/models/modeling_utils.js +++ b/packages/transformers/src/models/modeling_utils.js @@ -1,7 +1,7 @@ import { Callable } from '../utils/generic.js'; import { constructSessions, sessionRun } from './session.js'; import { AutoConfig, getCacheNames } from '../configs.js'; -import { Tensor, full_like, cat, zeros_like, ones_like, ones } from '../utils/tensor.js'; +import { Tensor, full_like, cat, zeros_like, ones_like, ones, index_select, index_select_async } from '../utils/tensor.js'; import { DataTypeMap } from '../utils/dtypes.js'; // These will be populated by registry.js @@ -34,7 +34,9 @@ import { import { GenerationConfig } from '../generation/configuration_utils.js'; import { EosTokenCriteria, MaxLengthCriteria, StoppingCriteriaList } from '../generation/stopping_criteria.js'; import { LogitsSampler } from '../generation/logits_sampler.js'; +import { BeamSearchScorer } from '../generation/beam_search.js'; import { DefaultProgressCallback, pick } from '../utils/core.js'; +import { log_softmax } from '../utils/maths.js'; import { ModelOutput } from './modeling_outputs.js'; import { logger } from '../utils/logger.js'; import { DynamicCache } from '../cache_utils.js'; @@ -927,27 +929,85 @@ export class PreTrainedModel extends Callable { // } const numInputs = model_inputs[model_input_name].dims.at(0); + const num_beams = generation_config.num_beams; + const is_beam_search = num_beams > 1; - // TODO: - // done is a list of booleans to keep track of which inputs are done - // const done = new Array(numInputs).fill(false); - // For efficiency purposes, we remove completed rows from model_inputs - // when the beam is complete, and we keep track of the row index - // const rowIndexToBatchIndex = new Map(); + let beam_scorer = null; + /** @type {number[]} */ + let beam_scores; + + if (is_beam_search) { + // Validate beam search configuration + if (generation_config.num_beam_groups > 1) { + throw new Error('Diverse beam search (num_beam_groups > 1) is not yet supported.'); + } + if (generation_config.do_sample) { + throw new Error('Beam sampling (num_beams > 1 with do_sample = true) is not yet supported.'); + } + if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { + throw new Error('Classifier-free guidance (guidance_scale > 1) is not supported with beam search.'); + } + if (streamer) { + throw new Error('Streaming is not supported with beam search.'); + } + + beam_scorer = new BeamSearchScorer(numInputs, num_beams, { + length_penalty: generation_config.length_penalty, + early_stopping: generation_config.early_stopping, + num_return_sequences: generation_config.num_return_sequences, + eos_token_id: generation_config.eos_token_id, + pad_token_id: generation_config.pad_token_id, + }); + } const sampler = LogitsSampler.getSampler(generation_config); - // TODO make > numInputs - const scores = new Array(numInputs).fill(0); + const scores = new Array(is_beam_search ? numInputs * num_beams : numInputs).fill(0); /** @type {bigint[][]} */ const all_input_ids = input_ids.tolist(); + + if (is_beam_search) { + // Expand all_input_ids: [A, B] -> [A, A, A, B, B, B] for num_beams=3 + const expanded_ids = []; + for (const ids of all_input_ids) { + for (let b = 0; b < num_beams; ++b) { + expanded_ids.push([...ids]); + } + } + all_input_ids.length = 0; + all_input_ids.push(...expanded_ids); + + // Expand model_inputs tensors by repeating each row num_beams times + for (const key of [model_input_name, 'attention_mask', 'decoder_attention_mask', 'encoder_outputs']) { + const tensor = model_inputs[key]; + if (tensor instanceof Tensor) { + const [batch, ...rest] = tensor.dims; + const rowSize = rest.length > 0 ? rest.reduce((a, b) => a * b, 1) : 1; + // @ts-ignore + const newData = new tensor.data.constructor(batch * num_beams * rowSize); + for (let i = 0; i < batch; ++i) { + const srcOffset = i * rowSize; + for (let b = 0; b < num_beams; ++b) { + newData.set( + tensor.data.subarray(srcOffset, srcOffset + rowSize), + (i * num_beams + b) * rowSize, + ); + } + } + model_inputs[key] = new Tensor(tensor.type, newData, [batch * num_beams, ...rest]); + } + } + + // Initialize beam_scores: first beam of each input = 0, rest = -1e9 + beam_scores = new Array(numInputs * num_beams).fill(-1e9); + for (let i = 0; i < numInputs; ++i) { + beam_scores[i * num_beams] = 0; + } + } + if (streamer) { streamer.put(all_input_ids); } - // const all_generated_input_ids = Array.from({ length: numInputs }, () => []); - - // NOTE: For now, we don't support spawning new beams - // TODO: when we do, we simply copy past key values and accumulate into single large tensor //////////////////////////////////////////////////// // Generic search which handles 4 generation modes: @@ -992,47 +1052,149 @@ export class PreTrainedModel extends Callable { /** @type {[bigint][]} */ const generated_input_ids = []; - // const new_kv_cache = [];// NOTE: Only used for beam search when concatenating new kv - // Loop over each batch - for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) { - const logs = next_tokens_scores[batch_idx]; - - const sampledTokens = await sampler(logs); - for (const [newTokenId, logProb] of sampledTokens) { - const bigint = BigInt(newTokenId); - // TODO: If branching, use previous beam as a starting point - // update generated ids, model inputs, and length for next step - scores[batch_idx] += logProb; - all_input_ids[batch_idx].push(bigint); - generated_input_ids.push([bigint]); - - // TODO: Support beam search - break; + + if (is_beam_search) { + // Beam search: score all candidates across beams, select top 2*num_beams per batch + const vocab_size = next_tokens_scores.dims.at(-1); + const total_beams = numInputs * num_beams; + + const all_next_tokens = []; + const all_next_indices = []; + const all_next_scores = []; + + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + // Collect candidates across all beams for this batch item + /** @type {{score: number, token: bigint, beam_idx: number}[]} */ + const candidates = []; + + for (let beam_idx = 0; beam_idx < num_beams; ++beam_idx) { + const flat_beam = batch_idx * num_beams + beam_idx; + const logits_data = /** @type {Float32Array} */ (next_tokens_scores[flat_beam].data); + const log_probs = log_softmax(logits_data); + + // Find top 2*num_beams candidates per beam for efficiency + /** @type {{score: number, token: bigint, beam_idx: number}[]} */ + const beam_candidates = []; + for (let v = 0; v < vocab_size; ++v) { + beam_candidates.push({ + score: beam_scores[flat_beam] + log_probs[v], + token: BigInt(v), + beam_idx, + }); + } + beam_candidates.sort((a, b) => b.score - a.score); + candidates.push(...beam_candidates.slice(0, 2 * num_beams)); + } + + // Select top 2*num_beams candidates globally for this batch item + candidates.sort((a, b) => b.score - a.score); + const top_candidates = candidates.slice(0, 2 * num_beams); + + for (const c of top_candidates) { + all_next_tokens.push(c.token); + all_next_indices.push(c.beam_idx); + all_next_scores.push(c.score); + } + } + + // Let beam_scorer process: route EOS to hypotheses, select continuing beams + const { next_beam_scores, next_beam_tokens, next_beam_indices } = + beam_scorer.process(all_input_ids, beam_scores, all_next_tokens, all_next_indices, all_next_scores); + + // Reorder all_input_ids based on beam indices and append new tokens + const new_all_input_ids = []; + for (let i = 0; i < total_beams; ++i) { + new_all_input_ids.push([...all_input_ids[next_beam_indices[i]], next_beam_tokens[i]]); + generated_input_ids.push([next_beam_tokens[i]]); + } + all_input_ids.length = 0; + all_input_ids.push(...new_all_input_ids); + + // Update beam scores + for (let i = 0; i < total_beams; ++i) { + beam_scores[i] = next_beam_scores[i]; + } + + // Reorder KV cache to match beam reordering + model_inputs['past_key_values'] = await this._reorder_cache( + this.getPastKeyValues(outputs, model_inputs.past_key_values), + next_beam_indices, + ); + } else { + // Greedy / sample: existing behavior + for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) { + const logs = next_tokens_scores[batch_idx]; + + const sampledTokens = await sampler(logs); + for (const [newTokenId, logProb] of sampledTokens) { + const bigint = BigInt(newTokenId); + scores[batch_idx] += logProb; + all_input_ids[batch_idx].push(bigint); + generated_input_ids.push([bigint]); + break; + } } } + if (streamer) { streamer.put(generated_input_ids); } + // Check stopping conditions + if (is_beam_search && beam_scorer.is_done) { + break; + } const stop = prepared_stopping_criteria(all_input_ids); if (stop.every((x) => x)) { break; } - model_inputs = this._update_model_kwargs_for_generation({ - generated_input_ids, - outputs, - model_inputs, - is_encoder_decoder, - }); + if (is_beam_search) { + // For beam search, we already updated past_key_values during reordering. + // Now update the remaining model inputs. + model_inputs['input_ids'] = new Tensor('int64', generated_input_ids.flat(), [generated_input_ids.length, 1]); + + if (!is_encoder_decoder) { + model_inputs.attention_mask = cat( + [model_inputs.attention_mask, ones([model_inputs.attention_mask.dims[0], 1])], + 1, + ); + } + + // Force recreate position_ids in next iteration + model_inputs['position_ids'] = null; + } else { + model_inputs = this._update_model_kwargs_for_generation({ + generated_input_ids, + outputs, + model_inputs, + is_encoder_decoder, + }); + } } if (streamer) { streamer.end(); } - // TODO: ensure all_input_ids is padded correctly... - const sequences = new Tensor('int64', all_input_ids.flat(), [all_input_ids.length, all_input_ids[0].length]); + let sequences; + if (is_beam_search) { + // Finalize beam search: select best hypotheses + const best_sequences = beam_scorer.finalize(all_input_ids, beam_scores); + + // Pad sequences to equal length for tensor creation + const max_len = Math.max(...best_sequences.map(s => s.length)); + const pad_id = BigInt(generation_config.pad_token_id ?? 0); + const padded = best_sequences.map(s => { + const p = [...s]; + while (p.length < max_len) p.push(pad_id); + return p; + }); + sequences = new Tensor('int64', padded.flat(), [padded.length, max_len]); + } else { + // TODO: ensure all_input_ids is padded correctly... + sequences = new Tensor('int64', all_input_ids.flat(), [all_input_ids.length, all_input_ids[0].length]); + } // Update past key values from the final forward pass const past_key_values = getPastKeyValues(outputs, model_inputs.past_key_values); @@ -1057,9 +1219,6 @@ export class PreTrainedModel extends Callable { past_key_values, ...attentions, ...return_dict_items, - // TODO: - // scores, - // logits, }; } return sequences; @@ -1081,6 +1240,36 @@ export class PreTrainedModel extends Callable { return output[outputName]; } + /** + * Reorder the past key values cache to match beam reordering. + * @param {Object} past_key_values The past key values object. + * @param {number[]} beam_indices Indices indicating which beam each new position came from. + * @returns {Promise} Reordered past key values. + */ + async _reorder_cache(past_key_values, beam_indices) { + if (!past_key_values) return past_key_values; + const reordered = Object.create(null); + for (const key in past_key_values) { + const tensor = past_key_values[key]; + const location = tensor.location; + if (key.includes('encoder')) { + // Encoder PKVs are shared across beams; pass through + reordered[key] = tensor; + } else { + if (tensor.location === 'cpu' || tensor.location === 'cpu-pinned') { + reordered[key] = index_select(tensor, beam_indices); + } else { + reordered[key] = await index_select_async(tensor, beam_indices); + } + // Dispose old tensor if it owns GPU resources + if (location === 'gpu-buffer' || location === 'texture' || location === 'ml-tensor') { + tensor.dispose(); + } + } + } + return reordered; + } + async encode_image(inputs) { return this._encode_input('vision_encoder', inputs, 'image_features'); } diff --git a/packages/transformers/src/transformers.js b/packages/transformers/src/transformers.js index ef01569ef..ca44cf018 100644 --- a/packages/transformers/src/transformers.js +++ b/packages/transformers/src/transformers.js @@ -45,6 +45,7 @@ export { PretrainedConfig, AutoConfig } from './configs.js'; export * from './generation/streamers.js'; export * from './generation/stopping_criteria.js'; export * from './generation/logits_process.js'; +export * from './generation/beam_search.js'; export { load_audio, read_audio, RawAudio } from './utils/audio.js'; export { load_image, RawImage } from './utils/image.js'; diff --git a/packages/transformers/src/utils/tensor.js b/packages/transformers/src/utils/tensor.js index 335cd25eb..5f3a31e17 100644 --- a/packages/transformers/src/utils/tensor.js +++ b/packages/transformers/src/utils/tensor.js @@ -1362,6 +1362,73 @@ export function cat(tensors, dim = 0) { return new Tensor(resultType, result, resultDims); } +/** + * Select entries from a tensor along dimension 0 using an index array. + * Equivalent to `torch.index_select(tensor, 0, indices)`. + * @param {Tensor} tensor The source tensor. + * @param {number[]} indices Array of row indices to select. + * @returns {Tensor} A new tensor with selected rows. + */ +function _index_select_from_data(tensor, indices, data) { + const [batchSize, ...restDims] = tensor.dims; + const rowSize = restDims.length > 0 ? restDims.reduce((a, b) => a * b, 1) : 1; + const newBatchSize = indices.length; + + let out; + if (ArrayBuffer.isView(data) && typeof data.subarray === 'function' && typeof data.set === 'function') { + // @ts-ignore + out = new data.constructor(newBatchSize * rowSize); + for (let i = 0; i < newBatchSize; ++i) { + const srcOffset = indices[i] * rowSize; + const dstOffset = i * rowSize; + out.set(data.subarray(srcOffset, srcOffset + rowSize), dstOffset); + } + } else { + out = new Array(newBatchSize * rowSize); + for (let i = 0; i < newBatchSize; ++i) { + const srcOffset = indices[i] * rowSize; + const dstOffset = i * rowSize; + for (let j = 0; j < rowSize; ++j) { + out[dstOffset + j] = data[srcOffset + j]; + } + } + } + + return new Tensor(tensor.type, out, [newBatchSize, ...restDims]); +} + +export function index_select(tensor, indices) { + if (tensor.location !== 'cpu' && tensor.location !== 'cpu-pinned') { + throw new Error( + `index_select only supports CPU tensors. Got location: ${tensor.location}. ` + + 'Use index_select_async to handle GPU tensors.', + ); + } + + return _index_select_from_data(tensor, indices, tensor.data); +} + +/** + * Async version of index_select that supports GPU-backed tensors by downloading data to CPU. + * @param {Tensor} tensor The source tensor. + * @param {number[]} indices Array of row indices to select. + * @returns {Promise} A new tensor with selected rows (CPU-backed). + */ +export async function index_select_async(tensor, indices) { + if (tensor.location === 'cpu' || tensor.location === 'cpu-pinned') { + return index_select(tensor, indices); + } + + // Download GPU/ML data to CPU. This will materialize CPU data and may release GPU resources. + const ort_tensor = tensor.ort_tensor; + if (!ort_tensor?.getData) { + throw new Error(`Tensor does not support getData() for location: ${tensor.location}.`); + } + + const data = await ort_tensor.getData(true); + return _index_select_from_data(tensor, indices, data); +} + /** * Stack an array of tensors along a specified dimension. * @param {Tensor[]} tensors The array of tensors to stack. diff --git a/packages/transformers/tests/utils/generation.test.js b/packages/transformers/tests/utils/generation.test.js index 231985571..ec06c2382 100644 --- a/packages/transformers/tests/utils/generation.test.js +++ b/packages/transformers/tests/utils/generation.test.js @@ -13,6 +13,8 @@ import { DynamicCache, random, full, + BeamSearchScorer, + BeamHypotheses, } from "../../src/transformers.js"; import { init, MAX_TEST_EXECUTION_TIME, MAX_MODEL_LOAD_TIME, MAX_MODEL_DISPOSE_TIME, DEFAULT_MODEL_OPTIONS } from "../init.js"; @@ -589,3 +591,148 @@ describe("PKV caching", () => { }, MAX_MODEL_DISPOSE_TIME); }); }); + +describe("Beam search", () => { + describe(`encoder-decoder`, () => { + const model_id = "hf-internal-testing/tiny-random-T5ForConditionalGeneration"; + const DUMMY_TEXT = "hello"; + + let model; + let tokenizer; + beforeAll(async () => { + model = await AutoModelForSeq2SeqLM.from_pretrained(model_id, DEFAULT_MODEL_OPTIONS); + tokenizer = await AutoTokenizer.from_pretrained(model_id); + }, MAX_MODEL_LOAD_TIME); + + it( + "basic beam search (num_beams=4)", + async () => { + const inputs = tokenizer(DUMMY_TEXT); + const outputs = await model.generate({ + ...inputs, + num_beams: 4, + max_new_tokens: 5, + }); + // Output should have shape [1, seq_len] (1 return sequence) + expect(outputs.dims[0]).toEqual(1); + expect(outputs.dims[1]).toBeGreaterThanOrEqual(2); // at least BOS + 1 token + expect(outputs.dims[1]).toBeLessThanOrEqual(6); // at most BOS + 5 tokens + }, + MAX_TEST_EXECUTION_TIME, + ); + + it( + "num_return_sequences > 1", + async () => { + const inputs = tokenizer(DUMMY_TEXT); + const outputs = await model.generate({ + ...inputs, + num_beams: 4, + num_return_sequences: 3, + max_new_tokens: 5, + }); + // Output should have shape [3, seq_len] + expect(outputs.dims[0]).toEqual(3); + }, + MAX_TEST_EXECUTION_TIME, + ); + + it( + "beam search produces different output from greedy", + async () => { + const inputs = tokenizer(DUMMY_TEXT); + const greedy_outputs = await model.generate({ + ...inputs, + max_new_tokens: 5, + }); + const beam_outputs = await model.generate({ + ...inputs, + num_beams: 4, + max_new_tokens: 5, + }); + // Both should succeed and produce valid tensors + expect(greedy_outputs.dims[0]).toEqual(1); + expect(beam_outputs.dims[0]).toEqual(1); + }, + MAX_TEST_EXECUTION_TIME, + ); + + it( + "beam search rejects classifier-free guidance", + async () => { + const inputs = tokenizer(DUMMY_TEXT); + await expect( + model.generate({ + ...inputs, + num_beams: 4, + guidance_scale: 2, + max_new_tokens: 5, + }), + ).rejects.toThrow("Classifier-free guidance (guidance_scale > 1) is not supported with beam search."); + }, + MAX_TEST_EXECUTION_TIME, + ); + + afterAll(async () => { + await model?.dispose(); + }, MAX_MODEL_DISPOSE_TIME); + }); + + describe(`decoder-only`, () => { + const model_id = "hf-internal-testing/tiny-random-LlamaForCausalLM"; + const DUMMY_TEXT = "hello"; + + let model; + let tokenizer; + beforeAll(async () => { + model = await AutoModelForCausalLM.from_pretrained(model_id, DEFAULT_MODEL_OPTIONS); + tokenizer = await AutoTokenizer.from_pretrained(model_id); + }, MAX_MODEL_LOAD_TIME); + + it( + "basic beam search (num_beams=4)", + async () => { + const inputs = tokenizer(DUMMY_TEXT); + const outputs = await model.generate({ + ...inputs, + num_beams: 4, + max_new_tokens: 5, + }); + // Output should have shape [1, seq_len] + expect(outputs.dims[0]).toEqual(1); + // seq_len = prompt_len + generated (up to max_new_tokens) + expect(outputs.dims[1]).toBeGreaterThanOrEqual(3); // at least BOS + prompt + 1 token + expect(outputs.dims[1]).toBeLessThanOrEqual(7); // at most BOS + prompt + 5 tokens + }, + MAX_TEST_EXECUTION_TIME, + ); + + it( + "num_return_sequences > 1", + async () => { + const inputs = tokenizer(DUMMY_TEXT); + const outputs = await model.generate({ + ...inputs, + num_beams: 4, + num_return_sequences: 3, + max_new_tokens: 5, + }); + // Output should have shape [3, seq_len] + expect(outputs.dims[0]).toEqual(3); + }, + MAX_TEST_EXECUTION_TIME, + ); + + afterAll(async () => { + await model?.dispose(); + }, MAX_MODEL_DISPOSE_TIME); + }); + + describe("error cases", () => { + it("num_return_sequences > num_beams throws", () => { + expect(() => { + new BeamSearchScorer(1, 4, { num_return_sequences: 5 }); + }).toThrow("num_return_sequences (5) must be <= num_beams (4)"); + }); + }); +}); From c162b748f3e194266dcb7c3e4e47a757e1133fd0 Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Fri, 20 Feb 2026 15:53:38 -0700 Subject: [PATCH 02/21] Add diverse beam search support --- .../src/generation/beam_search.js | 12 +- .../transformers/src/models/modeling_utils.js | 301 +++++++++++++++--- .../tests/utils/generation.test.js | 38 +++ 3 files changed, 303 insertions(+), 48 deletions(-) diff --git a/packages/transformers/src/generation/beam_search.js b/packages/transformers/src/generation/beam_search.js index e6475db8f..661de7fdb 100644 --- a/packages/transformers/src/generation/beam_search.js +++ b/packages/transformers/src/generation/beam_search.js @@ -206,6 +206,16 @@ export class BeamSearchScorer { * @returns {bigint[][]} Best sequences, shape [batch_size * num_return_sequences, seq_len]. */ finalize(all_input_ids, beam_scores) { + return this.finalize_with_scores(all_input_ids, beam_scores).map((x) => x.tokens); + } + + /** + * Finalize: select best hypotheses and return scores. + * @param {bigint[][]} all_input_ids Final sequences, shape [batch_size * num_beams, seq_len]. + * @param {number[]} beam_scores Final cumulative scores. + * @returns {{tokens: bigint[], score: number}[]} Best sequences with scores. + */ + finalize_with_scores(all_input_ids, beam_scores) { // For each batch, ensure we have enough hypotheses for (let batch_idx = 0; batch_idx < this.batch_size; ++batch_idx) { const hyps = this._beam_hyps[batch_idx]; @@ -223,7 +233,7 @@ export class BeamSearchScorer { const sorted = [...this._beam_hyps[batch_idx].beams] .sort((a, b) => b.score - a.score); for (let i = 0; i < this.num_return_sequences; ++i) { - results.push(sorted[i].tokens); + results.push(sorted[i]); } } return results; diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js index ef6f7088d..c8c7d47dc 100644 --- a/packages/transformers/src/models/modeling_utils.js +++ b/packages/transformers/src/models/modeling_utils.js @@ -930,16 +930,37 @@ export class PreTrainedModel extends Callable { const numInputs = model_inputs[model_input_name].dims.at(0); const num_beams = generation_config.num_beams; + const num_beam_groups = generation_config.num_beam_groups; const is_beam_search = num_beams > 1; + const is_group_beam_search = is_beam_search && num_beam_groups > 1; let beam_scorer = null; + let beam_scorers = null; /** @type {number[]} */ let beam_scores; if (is_beam_search) { // Validate beam search configuration - if (generation_config.num_beam_groups > 1) { - throw new Error('Diverse beam search (num_beam_groups > 1) is not yet supported.'); + if (generation_config.num_return_sequences > num_beams) { + throw new Error( + `num_return_sequences (${generation_config.num_return_sequences}) must be <= num_beams (${num_beams}).`, + ); + } + if (num_beam_groups < 1) { + throw new Error(`num_beam_groups must be >= 1, but got ${num_beam_groups}.`); + } + if (num_beam_groups > num_beams) { + throw new Error( + `num_beam_groups (${num_beam_groups}) must be <= num_beams (${num_beams}).`, + ); + } + if (num_beams % num_beam_groups !== 0) { + throw new Error( + `num_beams (${num_beams}) must be divisible by num_beam_groups (${num_beam_groups}).`, + ); + } + if (is_group_beam_search && generation_config.do_sample) { + throw new Error('Diverse beam sampling (num_beam_groups > 1 with do_sample = true) is not yet supported.'); } if (generation_config.do_sample) { throw new Error('Beam sampling (num_beams > 1 with do_sample = true) is not yet supported.'); @@ -951,13 +972,24 @@ export class PreTrainedModel extends Callable { throw new Error('Streaming is not supported with beam search.'); } - beam_scorer = new BeamSearchScorer(numInputs, num_beams, { - length_penalty: generation_config.length_penalty, - early_stopping: generation_config.early_stopping, - num_return_sequences: generation_config.num_return_sequences, - eos_token_id: generation_config.eos_token_id, - pad_token_id: generation_config.pad_token_id, - }); + if (is_group_beam_search) { + const group_size = num_beams / num_beam_groups; + beam_scorers = Array.from({ length: num_beam_groups }, () => new BeamSearchScorer(numInputs, group_size, { + length_penalty: generation_config.length_penalty, + early_stopping: generation_config.early_stopping, + num_return_sequences: group_size, + eos_token_id: generation_config.eos_token_id, + pad_token_id: generation_config.pad_token_id, + })); + } else { + beam_scorer = new BeamSearchScorer(numInputs, num_beams, { + length_penalty: generation_config.length_penalty, + early_stopping: generation_config.early_stopping, + num_return_sequences: generation_config.num_return_sequences, + eos_token_id: generation_config.eos_token_id, + pad_token_id: generation_config.pad_token_id, + }); + } } const sampler = LogitsSampler.getSampler(generation_config); @@ -1001,7 +1033,10 @@ export class PreTrainedModel extends Callable { // Initialize beam_scores: first beam of each input = 0, rest = -1e9 beam_scores = new Array(numInputs * num_beams).fill(-1e9); for (let i = 0; i < numInputs; ++i) { - beam_scores[i * num_beams] = 0; + const group_size = num_beams / num_beam_groups; + for (let g = 0; g < num_beam_groups; ++g) { + beam_scores[i * num_beams + g * group_size] = 0; + } } } @@ -1058,48 +1093,172 @@ export class PreTrainedModel extends Callable { const vocab_size = next_tokens_scores.dims.at(-1); const total_beams = numInputs * num_beams; - const all_next_tokens = []; - const all_next_indices = []; - const all_next_scores = []; + /** @type {number[]} */ + let next_beam_scores; + /** @type {bigint[]} */ + let next_beam_tokens; + /** @type {number[]} */ + let next_beam_indices; + + if (is_group_beam_search) { + const group_size = num_beams / num_beam_groups; + next_beam_scores = new Array(total_beams).fill(0); + next_beam_tokens = new Array(total_beams).fill(0n); + next_beam_indices = new Array(total_beams).fill(0); + + const diversity_penalty = generation_config.diversity_penalty ?? 0; + /** @type {Map[]} */ + const prev_group_tokens = Array.from({ length: numInputs }, () => new Map()); + + for (let group_idx = 0; group_idx < num_beam_groups; ++group_idx) { + const group_offset = group_idx * group_size; + + const group_all_input_ids = new Array(numInputs * group_size); + const group_beam_scores = new Array(numInputs * group_size); + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { + const global = batch_idx * num_beams + group_offset + beam_idx; + const local = batch_idx * group_size + beam_idx; + group_all_input_ids[local] = all_input_ids[global]; + group_beam_scores[local] = beam_scores[global]; + } + } - for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { - // Collect candidates across all beams for this batch item - /** @type {{score: number, token: bigint, beam_idx: number}[]} */ - const candidates = []; + const group_next_tokens = []; + const group_next_indices = []; + const group_next_scores = []; + + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + // Collect candidates across all beams for this batch item + /** @type {{score: number, token: bigint, beam_idx: number}[]} */ + const candidates = []; + + for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { + const flat_beam = batch_idx * num_beams + group_offset + beam_idx; + const logits_data = /** @type {Float32Array} */ (next_tokens_scores[flat_beam].data); + const log_probs = log_softmax(logits_data); + const beam_score = beam_scores[flat_beam]; + + // Find top 2*group_size candidates per beam for efficiency + /** @type {{score: number, token: bigint, beam_idx: number}[]} */ + const beam_candidates = []; + for (let v = 0; v < vocab_size; ++v) { + const token = BigInt(v); + let score = beam_score + log_probs[v]; + const penalty_count = prev_group_tokens[batch_idx].get(token) ?? 0; + if (penalty_count > 0) { + score -= diversity_penalty * penalty_count; + } + beam_candidates.push({ + score, + token, + beam_idx, + }); + } + beam_candidates.sort((a, b) => b.score - a.score); + candidates.push(...beam_candidates.slice(0, 2 * group_size)); + } + + // Select top 2*group_size candidates globally for this batch item + candidates.sort((a, b) => b.score - a.score); + const top_candidates = candidates.slice(0, 2 * group_size); + + for (const c of top_candidates) { + group_next_tokens.push(c.token); + group_next_indices.push(c.beam_idx); + group_next_scores.push(c.score); + } + } - for (let beam_idx = 0; beam_idx < num_beams; ++beam_idx) { - const flat_beam = batch_idx * num_beams + beam_idx; - const logits_data = /** @type {Float32Array} */ (next_tokens_scores[flat_beam].data); - const log_probs = log_softmax(logits_data); + // Let beam_scorer process: route EOS to hypotheses, select continuing beams + const { + next_beam_scores: group_next_beam_scores, + next_beam_tokens: group_next_beam_tokens, + next_beam_indices: group_next_beam_indices, + } = beam_scorers[group_idx].process( + group_all_input_ids, + group_beam_scores, + group_next_tokens, + group_next_indices, + group_next_scores, + ); - // Find top 2*num_beams candidates per beam for efficiency - /** @type {{score: number, token: bigint, beam_idx: number}[]} */ - const beam_candidates = []; - for (let v = 0; v < vocab_size; ++v) { - beam_candidates.push({ - score: beam_scores[flat_beam] + log_probs[v], - token: BigInt(v), - beam_idx, - }); + // Map group outputs into global beam arrays + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { + const global = batch_idx * num_beams + group_offset + beam_idx; + const local = batch_idx * group_size + beam_idx; + next_beam_scores[global] = group_next_beam_scores[local]; + next_beam_tokens[global] = group_next_beam_tokens[local]; + const local_source = group_next_beam_indices[local]; + const source_in_batch = local_source - batch_idx * group_size; + next_beam_indices[global] = batch_idx * num_beams + group_offset + source_in_batch; + } + } + + // Track tokens selected by this group for diversity penalty + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + const token_counts = prev_group_tokens[batch_idx]; + for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { + const global = batch_idx * num_beams + group_offset + beam_idx; + const token = next_beam_tokens[global]; + token_counts.set(token, (token_counts.get(token) ?? 0) + 1); + } } - beam_candidates.sort((a, b) => b.score - a.score); - candidates.push(...beam_candidates.slice(0, 2 * num_beams)); } + } else { + const all_next_tokens = []; + const all_next_indices = []; + const all_next_scores = []; - // Select top 2*num_beams candidates globally for this batch item - candidates.sort((a, b) => b.score - a.score); - const top_candidates = candidates.slice(0, 2 * num_beams); + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + // Collect candidates across all beams for this batch item + /** @type {{score: number, token: bigint, beam_idx: number}[]} */ + const candidates = []; + + for (let beam_idx = 0; beam_idx < num_beams; ++beam_idx) { + const flat_beam = batch_idx * num_beams + beam_idx; + const logits_data = /** @type {Float32Array} */ (next_tokens_scores[flat_beam].data); + const log_probs = log_softmax(logits_data); + + // Find top 2*num_beams candidates per beam for efficiency + /** @type {{score: number, token: bigint, beam_idx: number}[]} */ + const beam_candidates = []; + for (let v = 0; v < vocab_size; ++v) { + beam_candidates.push({ + score: beam_scores[flat_beam] + log_probs[v], + token: BigInt(v), + beam_idx, + }); + } + beam_candidates.sort((a, b) => b.score - a.score); + candidates.push(...beam_candidates.slice(0, 2 * num_beams)); + } + + // Select top 2*num_beams candidates globally for this batch item + candidates.sort((a, b) => b.score - a.score); + const top_candidates = candidates.slice(0, 2 * num_beams); - for (const c of top_candidates) { - all_next_tokens.push(c.token); - all_next_indices.push(c.beam_idx); - all_next_scores.push(c.score); + for (const c of top_candidates) { + all_next_tokens.push(c.token); + all_next_indices.push(c.beam_idx); + all_next_scores.push(c.score); + } } - } - // Let beam_scorer process: route EOS to hypotheses, select continuing beams - const { next_beam_scores, next_beam_tokens, next_beam_indices } = - beam_scorer.process(all_input_ids, beam_scores, all_next_tokens, all_next_indices, all_next_scores); + // Let beam_scorer process: route EOS to hypotheses, select continuing beams + ({ + next_beam_scores, + next_beam_tokens, + next_beam_indices, + } = beam_scorer.process( + all_input_ids, + beam_scores, + all_next_tokens, + all_next_indices, + all_next_scores, + )); + } // Reorder all_input_ids based on beam indices and append new tokens const new_all_input_ids = []; @@ -1141,8 +1300,13 @@ export class PreTrainedModel extends Callable { } // Check stopping conditions - if (is_beam_search && beam_scorer.is_done) { - break; + if (is_beam_search) { + const done = is_group_beam_search + ? beam_scorers.every((scorer) => scorer.is_done) + : beam_scorer.is_done; + if (done) { + break; + } } const stop = prepared_stopping_criteria(all_input_ids); if (stop.every((x) => x)) { @@ -1179,8 +1343,51 @@ export class PreTrainedModel extends Callable { let sequences; if (is_beam_search) { - // Finalize beam search: select best hypotheses - const best_sequences = beam_scorer.finalize(all_input_ids, beam_scores); + /** @type {bigint[][]} */ + let best_sequences; + if (is_group_beam_search) { + const group_size = num_beams / num_beam_groups; + /** @type {{tokens: bigint[], score: number}[][]} */ + const grouped = Array.from({ length: numInputs }, () => []); + + for (let group_idx = 0; group_idx < num_beam_groups; ++group_idx) { + const group_offset = group_idx * group_size; + const group_all_input_ids = new Array(numInputs * group_size); + const group_beam_scores = new Array(numInputs * group_size); + + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { + const global = batch_idx * num_beams + group_offset + beam_idx; + const local = batch_idx * group_size + beam_idx; + group_all_input_ids[local] = all_input_ids[global]; + group_beam_scores[local] = beam_scores[global]; + } + } + + const group_results = beam_scorers[group_idx].finalize_with_scores( + group_all_input_ids, + group_beam_scores, + ); + + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + const offset = batch_idx * group_size; + for (let i = 0; i < group_size; ++i) { + grouped[batch_idx].push(group_results[offset + i]); + } + } + } + + best_sequences = []; + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + const sorted = grouped[batch_idx].sort((a, b) => b.score - a.score); + for (let i = 0; i < generation_config.num_return_sequences; ++i) { + best_sequences.push(sorted[i].tokens); + } + } + } else { + // Finalize beam search: select best hypotheses + best_sequences = beam_scorer.finalize(all_input_ids, beam_scores); + } // Pad sequences to equal length for tensor creation const max_len = Math.max(...best_sequences.map(s => s.length)); diff --git a/packages/transformers/tests/utils/generation.test.js b/packages/transformers/tests/utils/generation.test.js index ec06c2382..72e449d43 100644 --- a/packages/transformers/tests/utils/generation.test.js +++ b/packages/transformers/tests/utils/generation.test.js @@ -621,6 +621,25 @@ describe("Beam search", () => { MAX_TEST_EXECUTION_TIME, ); + it( + "diverse beam search (num_beam_groups=2)", + async () => { + const inputs = tokenizer(DUMMY_TEXT); + const outputs = await model.generate({ + ...inputs, + num_beams: 4, + num_beam_groups: 2, + diversity_penalty: 0.5, + max_new_tokens: 5, + }); + // Output should have shape [1, seq_len] (1 return sequence) + expect(outputs.dims[0]).toEqual(1); + expect(outputs.dims[1]).toBeGreaterThanOrEqual(2); + expect(outputs.dims[1]).toBeLessThanOrEqual(6); + }, + MAX_TEST_EXECUTION_TIME, + ); + it( "num_return_sequences > 1", async () => { @@ -707,6 +726,25 @@ describe("Beam search", () => { MAX_TEST_EXECUTION_TIME, ); + it( + "diverse beam search (num_beam_groups=2)", + async () => { + const inputs = tokenizer(DUMMY_TEXT); + const outputs = await model.generate({ + ...inputs, + num_beams: 4, + num_beam_groups: 2, + diversity_penalty: 0.5, + max_new_tokens: 5, + }); + // Output should have shape [1, seq_len] + expect(outputs.dims[0]).toEqual(1); + expect(outputs.dims[1]).toBeGreaterThanOrEqual(3); + expect(outputs.dims[1]).toBeLessThanOrEqual(7); + }, + MAX_TEST_EXECUTION_TIME, + ); + it( "num_return_sequences > 1", async () => { From 507e6815889d98acc9af1a974f4f4d11d2850eec Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Fri, 20 Feb 2026 15:55:11 -0700 Subject: [PATCH 03/21] Add beam sampling for beam search --- .../transformers/src/models/modeling_utils.js | 60 ++++++++++++++----- .../tests/utils/generation.test.js | 38 ++++++++++++ 2 files changed, 83 insertions(+), 15 deletions(-) diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js index c8c7d47dc..8ce7f2727 100644 --- a/packages/transformers/src/models/modeling_utils.js +++ b/packages/transformers/src/models/modeling_utils.js @@ -962,9 +962,6 @@ export class PreTrainedModel extends Callable { if (is_group_beam_search && generation_config.do_sample) { throw new Error('Diverse beam sampling (num_beam_groups > 1 with do_sample = true) is not yet supported.'); } - if (generation_config.do_sample) { - throw new Error('Beam sampling (num_beams > 1 with do_sample = true) is not yet supported.'); - } if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { throw new Error('Classifier-free guidance (guidance_scale > 1) is not supported with beam search.'); } @@ -1210,6 +1207,8 @@ export class PreTrainedModel extends Callable { const all_next_tokens = []; const all_next_indices = []; const all_next_scores = []; + const do_beam_sample = generation_config.do_sample; + const top_k = generation_config.top_k; for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { // Collect candidates across all beams for this batch item @@ -1219,20 +1218,51 @@ export class PreTrainedModel extends Callable { for (let beam_idx = 0; beam_idx < num_beams; ++beam_idx) { const flat_beam = batch_idx * num_beams + beam_idx; const logits_data = /** @type {Float32Array} */ (next_tokens_scores[flat_beam].data); - const log_probs = log_softmax(logits_data); + if (do_beam_sample) { + const beam_score = beam_scores[flat_beam]; + const beam_vocab = logits_data.length; + let k = top_k > 0 ? Math.min(top_k, beam_vocab) : beam_vocab; + const indices = Array.from({ length: beam_vocab }, (_, i) => i); + indices.sort((a, b) => logits_data[b] - logits_data[a]); + if (k < indices.length) { + indices.length = k; + } + const maxLogit = logits_data[indices[0]]; + const probs = new Array(indices.length); + let sum = 0; + for (let i = 0; i < indices.length; ++i) { + const val = Math.exp(logits_data[indices[i]] - maxLogit); + probs[i] = val; + sum += val; + } + for (let i = 0; i < probs.length; ++i) { + probs[i] /= sum; + } + for (let s = 0; s < num_beams; ++s) { + const sampledIndex = sampler.randomSelect(probs); + const tokenId = indices[sampledIndex]; + candidates.push({ + score: beam_score + Math.log(probs[sampledIndex]), + token: BigInt(tokenId), + beam_idx, + }); + } + } else { + const log_probs = log_softmax(logits_data); - // Find top 2*num_beams candidates per beam for efficiency - /** @type {{score: number, token: bigint, beam_idx: number}[]} */ - const beam_candidates = []; - for (let v = 0; v < vocab_size; ++v) { - beam_candidates.push({ - score: beam_scores[flat_beam] + log_probs[v], - token: BigInt(v), - beam_idx, - }); + // Find top 2*num_beams candidates per beam for efficiency + /** @type {{score: number, token: bigint, beam_idx: number}[]} */ + const beam_candidates = []; + for (let v = 0; v < vocab_size; ++v) { + beam_candidates.push({ + score: beam_scores[flat_beam] + log_probs[v], + token: BigInt(v), + beam_idx, + }); + } + beam_candidates.sort((a, b) => b.score - a.score); + candidates.push(...beam_candidates.slice(0, 2 * num_beams)); } - beam_candidates.sort((a, b) => b.score - a.score); - candidates.push(...beam_candidates.slice(0, 2 * num_beams)); } // Select top 2*num_beams candidates globally for this batch item diff --git a/packages/transformers/tests/utils/generation.test.js b/packages/transformers/tests/utils/generation.test.js index 72e449d43..8fc2bad48 100644 --- a/packages/transformers/tests/utils/generation.test.js +++ b/packages/transformers/tests/utils/generation.test.js @@ -640,6 +640,25 @@ describe("Beam search", () => { MAX_TEST_EXECUTION_TIME, ); + it( + "beam sampling (do_sample=true)", + async () => { + const inputs = tokenizer(DUMMY_TEXT); + const outputs = await model.generate({ + ...inputs, + num_beams: 4, + do_sample: true, + top_k: 10, + max_new_tokens: 5, + }); + // Output should have shape [1, seq_len] (1 return sequence) + expect(outputs.dims[0]).toEqual(1); + expect(outputs.dims[1]).toBeGreaterThanOrEqual(2); + expect(outputs.dims[1]).toBeLessThanOrEqual(6); + }, + MAX_TEST_EXECUTION_TIME, + ); + it( "num_return_sequences > 1", async () => { @@ -745,6 +764,25 @@ describe("Beam search", () => { MAX_TEST_EXECUTION_TIME, ); + it( + "beam sampling (do_sample=true)", + async () => { + const inputs = tokenizer(DUMMY_TEXT); + const outputs = await model.generate({ + ...inputs, + num_beams: 4, + do_sample: true, + top_k: 10, + max_new_tokens: 5, + }); + // Output should have shape [1, seq_len] + expect(outputs.dims[0]).toEqual(1); + expect(outputs.dims[1]).toBeGreaterThanOrEqual(3); + expect(outputs.dims[1]).toBeLessThanOrEqual(7); + }, + MAX_TEST_EXECUTION_TIME, + ); + it( "num_return_sequences > 1", async () => { From c82719102bbc98c20e22daaad2306d05554ca866 Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Tue, 24 Feb 2026 20:26:03 -0700 Subject: [PATCH 04/21] Refactor model input expansion for beam search to use index selection --- .../transformers/src/models/modeling_utils.js | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js index 8ce7f2727..dd2aeb49d 100644 --- a/packages/transformers/src/models/modeling_utils.js +++ b/packages/transformers/src/models/modeling_utils.js @@ -1007,23 +1007,20 @@ export class PreTrainedModel extends Callable { all_input_ids.push(...expanded_ids); // Expand model_inputs tensors by repeating each row num_beams times + const expanded_indices = []; + for (let i = 0; i < numInputs; ++i) { + for (let b = 0; b < num_beams; ++b) { + expanded_indices.push(i); + } + } for (const key of [model_input_name, 'attention_mask', 'decoder_attention_mask', 'encoder_outputs']) { const tensor = model_inputs[key]; if (tensor instanceof Tensor) { - const [batch, ...rest] = tensor.dims; - const rowSize = rest.length > 0 ? rest.reduce((a, b) => a * b, 1) : 1; - // @ts-ignore - const newData = new tensor.data.constructor(batch * num_beams * rowSize); - for (let i = 0; i < batch; ++i) { - const srcOffset = i * rowSize; - for (let b = 0; b < num_beams; ++b) { - newData.set( - tensor.data.subarray(srcOffset, srcOffset + rowSize), - (i * num_beams + b) * rowSize, - ); - } + if (tensor.location === 'cpu' || tensor.location === 'cpu-pinned') { + model_inputs[key] = index_select(tensor, expanded_indices); + } else { + model_inputs[key] = await index_select_async(tensor, expanded_indices); } - model_inputs[key] = new Tensor(tensor.type, newData, [batch * num_beams, ...rest]); } } From f42da6d6c359843f4169a92fc318b98690f160c5 Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Wed, 25 Feb 2026 11:26:04 -0700 Subject: [PATCH 05/21] Handle past_key_values for beam search in PreTrainedModel to prevent caching issues --- packages/transformers/src/models/modeling_utils.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js index dd2aeb49d..6ebbf09ba 100644 --- a/packages/transformers/src/models/modeling_utils.js +++ b/packages/transformers/src/models/modeling_utils.js @@ -1448,9 +1448,17 @@ export class PreTrainedModel extends Callable { } if (generation_config.return_dict_in_generate) { + let past_key_values_for_return = past_key_values; + if (is_beam_search) { + console.warn( + 'Beam search does not return aligned past_key_values for finalized sequences. ' + + 'past_key_values will be null; re-generate without beam search if you need caching.', + ); + past_key_values_for_return = null; + } return { sequences, - past_key_values, + past_key_values: past_key_values_for_return, ...attentions, ...return_dict_items, }; From b0b86bde27a015f91adc1bb869207caf3803c895 Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Wed, 25 Feb 2026 12:18:49 -0700 Subject: [PATCH 06/21] Simplify past_key_values handling in PreTrainedModel for beam search --- packages/transformers/src/models/modeling_utils.js | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js index 6ebbf09ba..a970058cd 100644 --- a/packages/transformers/src/models/modeling_utils.js +++ b/packages/transformers/src/models/modeling_utils.js @@ -1448,14 +1448,7 @@ export class PreTrainedModel extends Callable { } if (generation_config.return_dict_in_generate) { - let past_key_values_for_return = past_key_values; - if (is_beam_search) { - console.warn( - 'Beam search does not return aligned past_key_values for finalized sequences. ' + - 'past_key_values will be null; re-generate without beam search if you need caching.', - ); - past_key_values_for_return = null; - } + const past_key_values_for_return = is_beam_search ? null : past_key_values; return { sequences, past_key_values: past_key_values_for_return, From 7c43a27d44f2ae4fa764362ce31f389a2bb489bf Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Tue, 20 Oct 2026 13:29:08 -0600 Subject: [PATCH 07/21] Fix beam hypothesis scoring, sampling, and cache expansion --- .../transformers/docs/source/_toctree.yml | 2 + .../docs/source/guides/beam-search.md | 87 ++++++++++ .../src/generation/beam_search.js | 51 ++++-- .../transformers/src/models/modeling_utils.js | 149 +++++++++++------- .../tests/utils/beam_search.test.js | 76 +++++++++ .../tests/utils/generation.test.js | 104 +++++++++++- 6 files changed, 395 insertions(+), 74 deletions(-) create mode 100644 packages/transformers/docs/source/guides/beam-search.md create mode 100644 packages/transformers/tests/utils/beam_search.test.js diff --git a/packages/transformers/docs/source/_toctree.yml b/packages/transformers/docs/source/_toctree.yml index 72c6cd4cc..089797ddb 100644 --- a/packages/transformers/docs/source/_toctree.yml +++ b/packages/transformers/docs/source/_toctree.yml @@ -27,6 +27,8 @@ - sections: - local: guides/webgpu title: Running models on WebGPU + - local: guides/beam-search + title: Beam search - local: guides/dtypes title: Using quantized models (dtypes) - local: guides/private diff --git a/packages/transformers/docs/source/guides/beam-search.md b/packages/transformers/docs/source/guides/beam-search.md new file mode 100644 index 000000000..4cc863b35 --- /dev/null +++ b/packages/transformers/docs/source/guides/beam-search.md @@ -0,0 +1,87 @@ +# Beam search + +Set `num_beams` above 1 in `generate()` to keep several candidate continuations +for each input. Beam search works with encoder-decoder and decoder-only models. + +```javascript +import { AutoModelForSeq2SeqLM, AutoTokenizer } from '@huggingface/transformers'; + +const model_id = 'Xenova/t5-small'; +const tokenizer = await AutoTokenizer.from_pretrained(model_id); +const model = await AutoModelForSeq2SeqLM.from_pretrained(model_id); +const inputs = tokenizer('translate English to German: The house is wonderful.'); + +const sequences = await model.generate({ + ...inputs, + num_beams: 4, + num_return_sequences: 2, + max_new_tokens: 30, + length_penalty: 1.0, + early_stopping: true, +}); +console.log(tokenizer.batch_decode(sequences, { skip_special_tokens: true })); +``` + +`num_return_sequences` must be at most `num_beams`. Batched results are ordered +by input, then by descending hypothesis score. Use left padding for batched +decoder-only inputs. + +Completed hypotheses are ranked by cumulative token log probability divided by +generated length raised to `length_penalty`. Prompt tokens are excluded from +this length. Positive penalties favor longer continuations; negative penalties +favor shorter ones. `early_stopping: true` stops once enough candidates finish, +`false` uses a score heuristic, and `"never"` uses a bound on the best attainable +score up to `max_length` or `max_new_tokens`. + +## Diverse beam search + +Split beams into groups and penalize tokens selected by earlier groups: + +```javascript +const sequences = await model.generate({ + ...inputs, + num_beams: 4, + num_beam_groups: 2, + diversity_penalty: 0.5, + max_new_tokens: 30, +}); +``` + +`num_beams` must be divisible by `num_beam_groups`. Each group searches +independently, with the diversity penalty included in its scores. + +## Beam sampling + +Set `do_sample: true` to sample candidates from the joint beam/token +distribution. Candidate pairs are sampled without replacement, then ranked by +their cumulative scores. `top_k` limits candidates per beam, with enough tokens +retained to seed the active beams and handle EOS candidates; `temperature` +controls sampling sharpness. + +```javascript +const sequences = await model.generate({ + ...inputs, + num_beams: 4, + do_sample: true, + top_k: 20, + temperature: 0.8, + max_new_tokens: 30, +}); +``` + +## Restrictions + +Beam search rejects streamers and classifier-free guidance (`guidance_scale > 1`). +Diverse beam search cannot be combined with `do_sample: true`. Nucleus sampling +(`top_p`) is not implemented by the generation sampler. + +With `return_dict_in_generate: true`, beam decoding returns the selected +`sequences` and `past_key_values: null`. The internal beam cache is released; +it does not correspond to the selected final sequences. A cache from an earlier +non-beam generation call can be supplied as input and is expanded across beams. + +Release the model when finished: + +```javascript +await model.dispose(); +``` diff --git a/packages/transformers/src/generation/beam_search.js b/packages/transformers/src/generation/beam_search.js index f3b9ee0af..4e6ffa907 100644 --- a/packages/transformers/src/generation/beam_search.js +++ b/packages/transformers/src/generation/beam_search.js @@ -10,11 +10,13 @@ export class BeamHypotheses { * @param {number} num_beams Number of beams. * @param {number} length_penalty Exponential penalty to the length. * @param {boolean|"never"} early_stopping Whether to stop when enough hypotheses are finished. + * @param {number} [max_length] Maximum generated length, excluding the prompt. */ - constructor(num_beams, length_penalty = 1.0, early_stopping = false) { + constructor(num_beams, length_penalty = 1.0, early_stopping = false, max_length = Infinity) { this.num_beams = num_beams; this.length_penalty = length_penalty; this.early_stopping = early_stopping; + this.max_length = max_length; /** @type {{score: number, tokens: bigint[]}[]} */ this.beams = []; @@ -29,9 +31,10 @@ export class BeamHypotheses { * Add a new hypothesis to the list. * @param {number} sum_logprobs Sum of log probabilities of the hypothesis. * @param {bigint[]} tokens The token ids of the hypothesis. + * @param {number} [generated_length] Number of generated tokens, excluding the prompt. */ - add(sum_logprobs, tokens) { - const score = sum_logprobs / tokens.length ** this.length_penalty; + add(sum_logprobs, tokens, generated_length = tokens.length) { + const score = sum_logprobs / Math.max(1, generated_length) ** this.length_penalty; if (this.beams.length < this.num_beams || score > this.worst_score) { this.beams.push({ score, tokens }); if (this.beams.length > this.num_beams) { @@ -61,7 +64,8 @@ export class BeamHypotheses { if (this.early_stopping === true) { return true; } else if (this.early_stopping === 'never') { - return false; + const length = this.length_penalty > 0 ? this.max_length : cur_len; + return this.worst_score >= best_sum_logprobs / Math.max(1, length) ** this.length_penalty; } else { // Heuristic: check if the best possible score for the next step // could beat the worst completed hypothesis @@ -84,6 +88,8 @@ export class BeamSearchScorer { * @param {number} [options.num_return_sequences] * @param {number|number[]|null} [options.eos_token_id] * @param {number|null} [options.pad_token_id] + * @param {number} [options.decoder_prompt_len] Prompt length to exclude from hypothesis scores. + * @param {number} [options.max_length] Maximum sequence length, including the prompt. */ constructor( batch_size, @@ -94,8 +100,11 @@ export class BeamSearchScorer { num_return_sequences = 1, eos_token_id = null, pad_token_id = null, + decoder_prompt_len = 0, + max_length = Infinity, } = {}, ) { + this.decoder_prompt_len = decoder_prompt_len; this.batch_size = batch_size; this.num_beams = num_beams; this.length_penalty = length_penalty; @@ -111,7 +120,7 @@ export class BeamSearchScorer { /** @type {BeamHypotheses[]} */ this._beam_hyps = Array.from( { length: batch_size }, - () => new BeamHypotheses(num_beams, length_penalty, early_stopping), + () => new BeamHypotheses(num_beams, length_penalty, early_stopping, max_length - decoder_prompt_len), ); /** @type {boolean[]} */ this._done = new Array(batch_size).fill(false); @@ -126,9 +135,9 @@ export class BeamSearchScorer { * * @param {bigint[][]} all_input_ids All sequences so far, shape [batch_size * num_beams, seq_len]. * @param {number[]} beam_scores Cumulative scores, shape [batch_size * num_beams]. - * @param {bigint[]} next_tokens Candidate tokens, shape [batch_size * 2 * num_beams]. - * @param {number[]} next_indices Which beam each candidate came from (relative to batch group), shape [batch_size * 2 * num_beams]. - * @param {number[]} next_scores New cumulative scores for candidates, shape [batch_size * 2 * num_beams]. + * @param {bigint[]} next_tokens Candidate tokens, shape [batch_size * num_candidates]. + * @param {number[]} next_indices Which beam each candidate came from (relative to batch group), shape [batch_size * num_candidates]. + * @param {number[]} next_scores New cumulative scores for candidates, shape [batch_size * num_candidates]. * @returns {{ next_beam_scores: number[], next_beam_tokens: bigint[], next_beam_indices: number[] }} */ process(all_input_ids, beam_scores, next_tokens, next_indices, next_scores) { @@ -152,7 +161,7 @@ export class BeamSearchScorer { } let beam_idx = 0; - const num_candidates = 2 * this.num_beams; + const num_candidates = next_tokens.length / this.batch_size; for (let j = 0; j < num_candidates; ++j) { const cand_idx = batch_idx * num_candidates + j; const beam_token = next_tokens[cand_idx]; @@ -163,9 +172,10 @@ export class BeamSearchScorer { const is_eos = this.eos_token_ids.some((id) => BigInt(id) === beam_token); if (is_eos) { - // Add completed hypothesis + // Only EOS candidates that survive the beam cutoff can complete. + if (j >= this.num_beams) continue; const hypothesis = [...all_input_ids[abs_beam_source], beam_token]; - this._beam_hyps[batch_idx].add(beam_score, hypothesis); + this._beam_hyps[batch_idx].add(beam_score, hypothesis, cur_len + 1 - this.decoder_prompt_len); } else { // Add to next active beams const out_idx = batch_idx * this.num_beams + beam_idx; @@ -190,10 +200,13 @@ export class BeamSearchScorer { } // Check if done for this batch using next-step scores - const start = batch_idx * this.num_beams; - const end = start + this.num_beams; - const best_sum_logprobs = Math.max(...next_beam_scores.slice(start, end)); - this._done[batch_idx] = this._beam_hyps[batch_idx].is_done(best_sum_logprobs, cur_len + 1); + const best_sum_logprobs = Math.max( + ...next_scores.slice(batch_idx * num_candidates, (batch_idx + 1) * num_candidates), + ); + this._done[batch_idx] = this._beam_hyps[batch_idx].is_done( + best_sum_logprobs, + cur_len + 1 - this.decoder_prompt_len, + ); } return { next_beam_scores, next_beam_tokens, next_beam_indices }; @@ -219,10 +232,14 @@ export class BeamSearchScorer { // For each batch, ensure we have enough hypotheses for (let batch_idx = 0; batch_idx < this.batch_size; ++batch_idx) { const hyps = this._beam_hyps[batch_idx]; - if (hyps.length < this.num_beams) { + if (!this._done[batch_idx]) { for (let beam_idx = 0; beam_idx < this.num_beams; ++beam_idx) { const flat_idx = batch_idx * this.num_beams + beam_idx; - hyps.add(beam_scores[flat_idx], all_input_ids[flat_idx]); + hyps.add( + beam_scores[flat_idx], + all_input_ids[flat_idx], + all_input_ids[flat_idx].length - this.decoder_prompt_len, + ); } } } diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js index b1fcdd1eb..066a15c2f 100644 --- a/packages/transformers/src/models/modeling_utils.js +++ b/packages/transformers/src/models/modeling_utils.js @@ -995,6 +995,8 @@ export class PreTrainedModel extends Callable { num_return_sequences: group_size, eos_token_id: generation_config.eos_token_id, pad_token_id: generation_config.pad_token_id, + decoder_prompt_len: input_ids_length, + max_length: generation_config.max_length, }), ); } else { @@ -1004,6 +1006,8 @@ export class PreTrainedModel extends Callable { num_return_sequences: generation_config.num_return_sequences, eos_token_id: generation_config.eos_token_id, pad_token_id: generation_config.pad_token_id, + decoder_prompt_len: input_ids_length, + max_length: generation_config.max_length, }); } } @@ -1032,7 +1036,14 @@ export class PreTrainedModel extends Callable { expanded_indices.push(i); } } - for (const key of [model_input_name, 'attention_mask', 'decoder_attention_mask', 'encoder_outputs']) { + for (const key of [ + model_input_name, + 'attention_mask', + 'decoder_attention_mask', + 'encoder_outputs', + 'position_ids', + 'inputs_embeds', + ]) { const tensor = model_inputs[key]; if (tensor instanceof Tensor) { if (tensor.location === 'cpu' || tensor.location === 'cpu-pinned') { @@ -1043,6 +1054,18 @@ export class PreTrainedModel extends Callable { } } + if (model_inputs.past_key_values) { + /** @type {Record} */ + const expanded_cache = {}; + for (const [key, tensor] of Object.entries(model_inputs.past_key_values)) { + expanded_cache[key] = await index_select_async( + tensor, + this._get_cache_indices(key, expanded_indices), + ); + } + model_inputs.past_key_values = new DynamicCache(expanded_cache); + } + // Initialize beam_scores: first beam of each input = 0, rest = -1e9 beam_scores = new Array(numInputs * num_beams).fill(-1e9); for (let i = 0; i < numInputs; ++i) { @@ -1096,15 +1119,28 @@ export class PreTrainedModel extends Callable { // TODO: Support float16 sampling in the sampler directly const logits = outputs.logits.slice(null, -1, null).to('float32'); + // Beam processors operate on log probabilities. Renormalizing after + // suppression would change the relative scores of different beams. + if (is_beam_search) { + const vocab_size = logits.dims.at(-1); + for (let i = 0; i < logits.dims[0]; ++i) { + const offset = i * vocab_size; + const data = /** @type {Float32Array} */ (logits.data); + data.set(log_softmax(data.subarray(offset, offset + vocab_size)), offset); + } + } const next_tokens_scores = prepared_logits_processor(all_input_ids, logits); /** @type {[bigint][]} */ const generated_input_ids = []; if (is_beam_search) { - // Beam search: score all candidates across beams, select top 2*num_beams per batch + // Beam search: retain enough candidates for active beams and all EOS ids. const vocab_size = next_tokens_scores.dims.at(-1); const total_beams = numInputs * num_beams; + const eos_ids = generation_config.eos_token_id; + const num_eos = eos_ids === null ? 0 : Array.isArray(eos_ids) ? eos_ids.length : 1; + const candidates_per_beam = Math.max(2, 1 + num_eos); /** @type {number[]} */ let next_beam_scores; @@ -1149,10 +1185,10 @@ export class PreTrainedModel extends Callable { for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { const flat_beam = batch_idx * num_beams + group_offset + beam_idx; const logits_data = /** @type {Float32Array} */ (next_tokens_scores[flat_beam].data); - const log_probs = log_softmax(logits_data); + const log_probs = logits_data; const beam_score = beam_scores[flat_beam]; - // Find top 2*group_size candidates per beam for efficiency + // Retain enough candidates per beam to fill the group after EOS. /** @type {{score: number, token: bigint, beam_idx: number}[]} */ const beam_candidates = []; for (let v = 0; v < vocab_size; ++v) { @@ -1169,12 +1205,12 @@ export class PreTrainedModel extends Callable { }); } beam_candidates.sort((a, b) => b.score - a.score); - candidates.push(...beam_candidates.slice(0, 2 * group_size)); + candidates.push(...beam_candidates.slice(0, candidates_per_beam * group_size)); } - // Select top 2*group_size candidates globally for this batch item + // Rank candidates across the group for this batch item. candidates.sort((a, b) => b.score - a.score); - const top_candidates = candidates.slice(0, 2 * group_size); + const top_candidates = candidates.slice(0, candidates_per_beam * group_size); for (const c of top_candidates) { group_next_tokens.push(c.token); @@ -1234,57 +1270,43 @@ export class PreTrainedModel extends Callable { for (let beam_idx = 0; beam_idx < num_beams; ++beam_idx) { const flat_beam = batch_idx * num_beams + beam_idx; const logits_data = /** @type {Float32Array} */ (next_tokens_scores[flat_beam].data); - if (do_beam_sample) { - const beam_score = beam_scores[flat_beam]; - const beam_vocab = logits_data.length; - let k = top_k > 0 ? Math.min(top_k, beam_vocab) : beam_vocab; - const indices = Array.from({ length: beam_vocab }, (_, i) => i); - indices.sort((a, b) => logits_data[b] - logits_data[a]); - if (k < indices.length) { - indices.length = k; - } - const maxLogit = logits_data[indices[0]]; - const probs = new Float32Array(indices.length); - let sum = 0; - for (let i = 0; i < indices.length; ++i) { - const val = Math.exp(logits_data[indices[i]] - maxLogit); - probs[i] = val; - sum += val; - } - for (let i = 0; i < probs.length; ++i) { - probs[i] /= sum; - } - for (let s = 0; s < num_beams; ++s) { - const sampledIndex = sampler.randomSelect(probs); - const tokenId = indices[sampledIndex]; - candidates.push({ - score: beam_score + Math.log(probs[sampledIndex]), - token: BigInt(tokenId), - beam_idx, - }); - } - } else { - const log_probs = log_softmax(logits_data); + const beam_candidates = Array.from(logits_data, (score, token) => ({ + score: beam_scores[flat_beam] + score, + token: BigInt(token), + beam_idx, + })); + beam_candidates.sort((a, b) => b.score - a.score); + const count = do_beam_sample + ? top_k > 0 + ? Math.max(top_k, candidates_per_beam * num_beams) + : vocab_size + : candidates_per_beam * num_beams; + for (const candidate of beam_candidates.slice(0, count)) candidates.push(candidate); + } - // Find top 2*num_beams candidates per beam for efficiency - /** @type {{score: number, token: bigint, beam_idx: number}[]} */ - const beam_candidates = []; - for (let v = 0; v < vocab_size; ++v) { - beam_candidates.push({ - score: beam_scores[flat_beam] + log_probs[v], - token: BigInt(v), - beam_idx, - }); - } - beam_candidates.sort((a, b) => b.score - a.score); - candidates.push(...beam_candidates.slice(0, 2 * num_beams)); + const count = Math.min(candidates_per_beam * num_beams, candidates.length); + let top_candidates; + if (do_beam_sample) { + // Sample across the joint beam/token distribution without + // replacement, retaining the original cumulative scores. + top_candidates = []; + for (let i = 0; i < count; ++i) { + const max_score = candidates.reduce( + (best, candidate) => Math.max(best, candidate.score), + -Infinity, + ); + const probabilities = Float32Array.from(candidates, (candidate) => + Math.exp(candidate.score - max_score), + ); + const index = sampler.randomSelect(probabilities); + top_candidates.push(candidates.splice(index, 1)[0]); } + top_candidates.sort((a, b) => b.score - a.score); + } else { + candidates.sort((a, b) => b.score - a.score); + top_candidates = candidates.slice(0, count); } - // Select top 2*num_beams candidates globally for this batch item - candidates.sort((a, b) => b.score - a.score); - const top_candidates = candidates.slice(0, 2 * num_beams); - for (const c of top_candidates) { all_next_tokens.push(c.token); all_next_indices.push(c.beam_idx); @@ -1502,6 +1524,21 @@ export class PreTrainedModel extends Callable { return output[outputName]; } + /** + * Map batch rows to cache rows, including exports that flatten attention heads. + * @param {string} key Cache input name. + * @param {number[]} indices Batch row indices. + * @returns {number[]} Cache row indices. + * @private + */ + _get_cache_indices(key, indices) { + const session = this.sessions?.decoder_model_merged ?? this.sessions?.model; + const metadata = session?.inputMetadata.find((meta) => meta.name === key); + if (metadata?.shape[0] !== 'batch_size x num_heads') return indices; + const num_heads = this.config.normalized_config.num_heads; + return indices.flatMap((index) => Array.from({ length: num_heads }, (_, head) => index * num_heads + head)); + } + /** * Reorder the past key values cache to match beam reordering. * @param {DynamicCache} past_key_values The past key values cache. @@ -1519,9 +1556,9 @@ export class PreTrainedModel extends Callable { reordered[key] = tensor; } else { if (tensor.location === 'cpu' || tensor.location === 'cpu-pinned') { - reordered[key] = index_select(tensor, beam_indices); + reordered[key] = index_select(tensor, this._get_cache_indices(key, beam_indices)); } else { - reordered[key] = await index_select_async(tensor, beam_indices); + reordered[key] = await index_select_async(tensor, this._get_cache_indices(key, beam_indices)); } // Dispose old tensor if it owns GPU resources if (location === 'gpu-buffer' || location === 'texture' || location === 'ml-tensor') { diff --git a/packages/transformers/tests/utils/beam_search.test.js b/packages/transformers/tests/utils/beam_search.test.js new file mode 100644 index 000000000..320c8b80a --- /dev/null +++ b/packages/transformers/tests/utils/beam_search.test.js @@ -0,0 +1,76 @@ +import { BeamHypotheses, BeamSearchScorer } from "../../src/generation/beam_search.js"; + +describe("Beam hypothesis scoring", () => { + it("normalizes by generated length rather than prompt length", () => { + const scorer = new BeamSearchScorer(1, 2, { decoder_prompt_len: 3, early_stopping: "never" }); + scorer.process( + [ + [10n, 11n, 12n], + [10n, 11n, 12n], + ], + [0, -1e9], + [2n, 3n, 4n, 5n], + [0, 0, 0, 0], + [-1, -2, -3, -4], + ); + const result = scorer.finalize_with_scores( + [ + [10n, 11n, 12n, 2n], + [10n, 11n, 12n, 3n], + ], + [-1, -2], + ); + expect(result[0].score).toBe(-1); + }); + + it("compares active beams with a full completed pool at the length limit", () => { + const scorer = new BeamSearchScorer(1, 2, { early_stopping: "never", length_penalty: 0 }); + scorer._beam_hyps[0].add(-5, [1n, 0n]); + scorer._beam_hyps[0].add(-6, [2n, 0n]); + expect( + scorer.finalize( + [ + [1n, 3n], + [2n, 4n], + ], + [-1, -2], + ), + ).toEqual([[1n, 3n]]); + }); + + it("does not resurrect padded beams from a finished batch", () => { + const scorer = new BeamSearchScorer(1, 2, { early_stopping: true, length_penalty: 0 }); + scorer._beam_hyps[0].add(-5, [1n, 0n]); + scorer._beam_hyps[0].add(-6, [2n, 0n]); + scorer._done[0] = true; + expect( + scorer.finalize( + [ + [1n, 9n], + [2n, 9n], + ], + [0, 0], + ), + ).toEqual([[1n, 0n]]); + }); + + it("only completes EOS candidates within the top beam ranks", () => { + const scorer = new BeamSearchScorer(1, 2, { eos_token_id: 0 }); + scorer.process([[1n], [2n]], [0, 0], [0n, 3n, 0n, 4n], [0, 0, 1, 1], [-1, -2, -3, -4]); + expect(scorer._beam_hyps[0].beams.map((beam) => beam.tokens)).toEqual([[1n, 0n]]); + }); + + it("handles more than two EOS ids without inventing active tokens", () => { + const scorer = new BeamSearchScorer(1, 2, { eos_token_id: [0, 1, 2] }); + const result = scorer.process([[9n], [9n]], [0, -1e9], [0n, 1n, 2n, 3n, 4n, 5n, 6n, 7n], Array(8).fill(0), [-1, -2, -3, -4, -5, -6, -7, -8]); + expect(result.next_beam_tokens).toEqual([3n, 4n]); + }); + + it('stops "never" when no completion can improve the score', () => { + const hypotheses = new BeamHypotheses(2, 1, "never", 5); + hypotheses.add(-1, [1n, 0n]); + hypotheses.add(-2, [2n, 0n]); + expect(hypotheses.is_done(-10, 3)).toBe(true); + expect(hypotheses.is_done(-1, 3)).toBe(false); + }); +}); diff --git a/packages/transformers/tests/utils/generation.test.js b/packages/transformers/tests/utils/generation.test.js index 129919d32..01411315a 100644 --- a/packages/transformers/tests/utils/generation.test.js +++ b/packages/transformers/tests/utils/generation.test.js @@ -10,6 +10,7 @@ import { // Other TextStreamer, + LogitsProcessor, DynamicCache, StoppingCriteria, random, @@ -639,6 +640,21 @@ describe("Beam cache reordering", () => { }); }); +describe("Flattened beam caches", () => { + it("preserves all attention heads when cache batch and heads share an axis", async () => { + const key = "past_key_values.0.key"; + const model = { + _get_cache_indices: PreTrainedModel.prototype._get_cache_indices, + config: { normalized_config: { num_heads: 2 } }, + sessions: { model: { inputMetadata: [{ name: key, shape: ["batch_size x num_heads", 1, 1] }] } }, + }; + const cache = new DynamicCache({ [key]: new Tensor("float32", [10, 11, 20, 21, 30, 31, 40, 41], [8, 1, 1]) }); + const reordered = await PreTrainedModel.prototype._reorder_cache.call(model, cache, [1, 1, 3, 2]); + expect(Array.from(reordered[key].data)).toEqual([20, 21, 20, 21, 40, 41, 30, 31]); + expect(reordered[key].dims).toEqual([8, 1, 1]); + }); +}); + describe("Beam search", () => { describe(`encoder-decoder`, () => { const model_id = "hf-internal-testing/tiny-random-T5ForConditionalGeneration"; @@ -728,6 +744,39 @@ describe("Beam search", () => { MAX_TEST_EXECUTION_TIME, ); + it.each([1, 4])( + "samples distinct first-step candidates reproducibly with top_k=%i", + async (top_k) => { + const config = { num_beams: 4, num_return_sequences: 4, do_sample: true, top_k, max_new_tokens: 1, eos_token_id: null }; + random.seed(42); + const first = await model.generate({ ...tokenizer(DUMMY_TEXT), ...config }); + random.seed(42); + const second = await model.generate({ ...tokenizer(DUMMY_TEXT), ...config }); + expect(first.tolist()).toEqual(second.tolist()); + expect(new Set(first.tolist().map((row) => row.at(-1))).size).toBe(4); + }, + MAX_TEST_EXECUTION_TIME, + ); + + it( + "passes log probabilities to beam logits processors", + async () => { + const normalizers = []; + class InspectScores extends LogitsProcessor { + _call(input_ids, scores) { + for (let i = 0; i < input_ids.length; ++i) { + normalizers.push(Array.from(scores[i].data).reduce((sum, score) => sum + Math.exp(score), 0)); + } + return scores; + } + } + await model.generate({ ...tokenizer(DUMMY_TEXT), num_beams: 2, max_new_tokens: 2, logits_processor: [new InspectScores()] }); + expect(normalizers.length).toBe(4); + for (const value of normalizers) expect(value).toBeCloseTo(1, 5); + }, + MAX_TEST_EXECUTION_TIME, + ); + it( "num_return_sequences > 1", async () => { @@ -745,7 +794,7 @@ describe("Beam search", () => { ); it( - "beam search produces different output from greedy", + "beam search and greedy both produce a sequence", async () => { const inputs = tokenizer(DUMMY_TEXT); const greedy_outputs = await model.generate({ @@ -874,6 +923,39 @@ describe("Beam search", () => { MAX_TEST_EXECUTION_TIME, ); + it.each([1, 4])( + "samples distinct first-step candidates reproducibly with top_k=%i", + async (top_k) => { + const config = { num_beams: 4, num_return_sequences: 4, do_sample: true, top_k, max_new_tokens: 1, eos_token_id: null }; + random.seed(42); + const first = await model.generate({ ...tokenizer(DUMMY_TEXT), ...config }); + random.seed(42); + const second = await model.generate({ ...tokenizer(DUMMY_TEXT), ...config }); + expect(first.tolist()).toEqual(second.tolist()); + expect(new Set(first.tolist().map((row) => row.at(-1))).size).toBe(4); + }, + MAX_TEST_EXECUTION_TIME, + ); + + it( + "passes log probabilities to beam logits processors", + async () => { + const normalizers = []; + class InspectScores extends LogitsProcessor { + _call(input_ids, scores) { + for (let i = 0; i < input_ids.length; ++i) { + normalizers.push(Array.from(scores[i].data).reduce((sum, score) => sum + Math.exp(score), 0)); + } + return scores; + } + } + await model.generate({ ...tokenizer(DUMMY_TEXT), num_beams: 2, max_new_tokens: 2, logits_processor: [new InspectScores()] }); + expect(normalizers.length).toBe(4); + for (const value of normalizers) expect(value).toBeCloseTo(1, 5); + }, + MAX_TEST_EXECUTION_TIME, + ); + it( "num_return_sequences > 1", async () => { @@ -890,6 +972,26 @@ describe("Beam search", () => { MAX_TEST_EXECUTION_TIME, ); + it( + "expands a supplied cache and position IDs across beams", + async () => { + const { sequences, past_key_values } = await model.generate({ ...tokenizer(DUMMY_TEXT), max_new_tokens: 3, return_dict_in_generate: true }); + const attention_mask = new Tensor("int64", new BigInt64Array(sequences.dims[1]).fill(1n), sequences.dims); + const position_ids = new Tensor( + "int64", + BigInt64Array.from({ length: sequences.dims[1] }, (_, i) => BigInt(i)), + sequences.dims, + ); + const config = { input_ids: sequences, attention_mask, position_ids, num_beams: 3, max_new_tokens: 3 }; + const expected = await model.generate(config); + const actual = await model.generate({ ...config, past_key_values }); + expect(actual.tolist()).toEqual(expected.tolist()); + expect(Object.values(past_key_values)[0].dims[0]).toBe(1); + await past_key_values.dispose(); + }, + MAX_TEST_EXECUTION_TIME, + ); + afterAll(async () => { await model?.dispose(); }, MAX_MODEL_DISPOSE_TIME); From f8e1b7df88bd3d557c7700b6c1942222bb376df4 Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Tue, 20 Oct 2026 14:16:40 -0600 Subject: [PATCH 08/21] Add reproducible remote WebGPU beam validation and benchmarks --- packages/transformers/src/backends/onnx.js | 9 + scripts/beam-gpu/.gitignore | 1 + scripts/beam-gpu/README.md | 51 ++++ scripts/beam-gpu/bootstrap.sh | 31 +++ scripts/beam-gpu/browser.js | 273 +++++++++++++++++++++ scripts/beam-gpu/build.mjs | 16 ++ scripts/beam-gpu/candidates.mjs | 27 ++ scripts/beam-gpu/runner.mjs | 87 +++++++ 8 files changed, 495 insertions(+) create mode 100644 scripts/beam-gpu/.gitignore create mode 100644 scripts/beam-gpu/README.md create mode 100755 scripts/beam-gpu/bootstrap.sh create mode 100644 scripts/beam-gpu/browser.js create mode 100644 scripts/beam-gpu/build.mjs create mode 100644 scripts/beam-gpu/candidates.mjs create mode 100644 scripts/beam-gpu/runner.mjs diff --git a/packages/transformers/src/backends/onnx.js b/packages/transformers/src/backends/onnx.js index 7dbfe44ba..61f13b5c3 100644 --- a/packages/transformers/src/backends/onnx.js +++ b/packages/transformers/src/backends/onnx.js @@ -310,6 +310,15 @@ export async function runInferenceSession(session, ortFeed) { return apis.IS_WEB_ENV ? (webInferenceChain = webInferenceChain.then(run)) : run(); } +/** + * Return the tensor constructor used by the active execution backend. + * @returns {typeof import('onnxruntime-common').Tensor} + * @internal + */ +export function getTensorConstructor() { + return ONNX.Tensor; +} + /** * Check if an object is an ONNX tensor. * @param {any} x The object to check diff --git a/scripts/beam-gpu/.gitignore b/scripts/beam-gpu/.gitignore new file mode 100644 index 000000000..6628455c0 --- /dev/null +++ b/scripts/beam-gpu/.gitignore @@ -0,0 +1 @@ +/results/ diff --git a/scripts/beam-gpu/README.md b/scripts/beam-gpu/README.md new file mode 100644 index 000000000..7b6d150df --- /dev/null +++ b/scripts/beam-gpu/README.md @@ -0,0 +1,51 @@ +# Beam search GPU validation + +These scripts validate and benchmark browser WebGPU on a disposable Linux NVIDIA +host. Infrastructure provisioning, SSH credentials, budgets, and teardown belong +to the caller; the scripts contain no provider credentials and create no hosts. + +`bootstrap.sh` installs Node 24.14.1, pnpm, the base PR revision, and Playwright +1.56.1/Chromium 141. A newer Chromium 156 build returned a null WebGPU adapter on +the tested NVIDIA driver; Chromium 141 worked. EGL dispatch libraries are required +in addition to the container's NVIDIA Vulkan libraries. + +Run `bootstrap.sh` on a throwaway Ubuntu GPU host, then transfer the desired source +revision into `/workspace/beam-gpu/transformers.js`. The default task root is +`/workspace/beam-gpu`; override `TASK_ROOT` for bootstrap or `BEAM_RUNNER_ROOT` and +`BEAM_PROJECT_ROOT` for the runner. `BEAM_PLAYWRIGHT_ROOT` can select another +runner's Playwright installation. The benchmark server binds to loopback only. + +```bash +export PATH=/workspace/beam-gpu/node-v24.14.1-linux-x64/bin:$PATH +cd /workspace/beam-gpu/transformers.js +node scripts/beam-gpu/build.mjs +BEAM_OPTIONS='{"mode":"validate"}' BEAM_RESULT=/workspace/beam-gpu/validate.json node scripts/beam-gpu/runner.mjs +BEAM_OPTIONS='{"mode":"micro"}' BEAM_RESULT=/workspace/beam-gpu/micro.json node scripts/beam-gpu/runner.mjs +BEAM_OPTIONS='{"mode":"generation","repeats":4,"tokens":16}' BEAM_RESULT=/workspace/beam-gpu/generation.json node scripts/beam-gpu/runner.mjs +``` + +- `probe`: requires a hardware WebGPU adapter and records browser/adapter identity. +- `validate`: verifies float32, float16, int64, uint8 and bool row selection, + duplicate rows, chained selections, preservation of caller-owned source data, + and the CPU fallback for unaligned float16 rows. +- `micro`: validates every copied element, then measures GPU-completed row + selection for 1, 8, and 64 MiB tensors. Two warmups precede ten timed samples. +- `generation`: runs T5 and Llama standard/diverse/sampling/batched beam decoding; + checks seeded repeatability, batch independence, and null returned beam caches. + One warmup precedes timed samples. JSON retains tokens and cache locations. + +For other models, pass `models`, `dtype`, and optionally `modes` (`standard`, +`diverse`, `sampling`, `batched`) in `BEAM_OPTIONS`. Set `cpuRowSelection: true` +to use the original cache-download algorithm for a matched reference. This is a +harness option, not a library configuration flag. Compare token arrays between +reference and optimized output files before interpreting timings. + +`node scripts/beam-gpu/candidates.mjs` separately compares the full-sort reference +with bounded top-k selection for 32K and 152K vocabularies and verifies identical +rankings. Its numbers are CPU microbenchmarks, not inference throughput. + +Raw results belong in the gitignored `results/` directory. Keep model caches, +provider keys, SSH keys, browser installations, and build output out of Git. +The Chromium process runs without its sandbox because this harness runs as root +inside an isolated, disposable test container; use a sandboxed browser on shared +or persistent hosts. diff --git a/scripts/beam-gpu/bootstrap.sh b/scripts/beam-gpu/bootstrap.sh new file mode 100755 index 000000000..1f42996ff --- /dev/null +++ b/scripts/beam-gpu/bootstrap.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail +# Run inside the disposable Linux GPU host. No credentials are required. +TASK_ROOT=${TASK_ROOT:-/workspace/beam-gpu} +mkdir -p "$TASK_ROOT" +cd "$TASK_ROOT" +apt-get update -qq +apt-get install -y -qq libegl1 libgl1 libglvnd0 vulkan-tools +if ! command -v node >/dev/null; then + curl -fsSL https://nodejs.org/dist/v24.14.1/node-v24.14.1-linux-x64.tar.xz -o node.tar.xz + tar -xf node.tar.xz +fi +export PATH="$TASK_ROOT/node-v24.14.1-linux-x64/bin:$PATH" +corepack enable +if [[ ! -d transformers.js/.git ]]; then + git clone --depth 1 --branch dan/add-beam-support https://github.com/justsml/transformers.js.git +fi +cd transformers.js +git checkout 7c43a27d44f2ae4fa764362ce31f389a2bb489bf +pnpm install --frozen-lockfile +pnpm build +mkdir -p "$TASK_ROOT/runner" +cd "$TASK_ROOT/runner" +if [[ ! -f package.json ]]; then + printf '{"private":true,"type":"module","packageManager":"pnpm@10.28.1"}\n' > package.json +fi +pnpm add --save-exact playwright@1.56.1 +pnpm exec playwright install --with-deps chromium +node --version +pnpm exec playwright --version +nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv diff --git a/scripts/beam-gpu/browser.js b/scripts/beam-gpu/browser.js new file mode 100644 index 000000000..72ee76dc5 --- /dev/null +++ b/scripts/beam-gpu/browser.js @@ -0,0 +1,273 @@ +import { + AutoModelForSeq2SeqLM, + AutoModelForCausalLM, + AutoTokenizer, + PreTrainedModel, + Tensor, + DynamicCache, + env, + random, +} from "../../packages/transformers/src/transformers.js"; +import { getTensorConstructor } from "../../packages/transformers/src/backends/onnx.js"; +import { index_select_async, index_select } from "../../packages/transformers/src/utils/tensor.js"; + +env.backends.onnx.wasm.wasmPaths = "/ort/"; +env.backends.onnx.wasm.numThreads = 1; +env.allowLocalModels = false; +env.remoteHost = location.origin + "/hf/"; +const emit = (value) => console.log("RESULT " + JSON.stringify(value, (_, x) => (typeof x === "bigint" ? x.toString() : x))); +const equal = (a, b) => + JSON.stringify(a, (_, x) => (typeof x === "bigint" ? x.toString() : x)) === JSON.stringify(b, (_, x) => (typeof x === "bigint" ? x.toString() : x)); +const median = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)]; + +window.runBeamGPU = async (options) => { + const adapter = await navigator.gpu?.requestAdapter({ powerPreference: "high-performance" }); + if (!adapter) throw new Error("No WebGPU adapter"); + const info = adapter.info; + const hardware = { + vendor: info.vendor, + architecture: info.architecture, + device: info.device, + description: info.description, + isFallbackAdapter: info.isFallbackAdapter, + }; + emit({ type: "adapter", ...hardware, userAgent: navigator.userAgent }); + if (info.isFallbackAdapter || /swiftshader|llvmpipe|software/i.test(hardware.description)) throw new Error("Software GPU rejected"); + env.backends.onnx.webgpu.adapter = adapter; + if (options.mode === "probe") return { hardware }; + const device = await adapter.requestDevice({ + requiredFeatures: adapter.features.has("shader-f16") ? ["shader-f16"] : [], + requiredLimits: { maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize, maxBufferSize: adapter.limits.maxBufferSize }, + }); + env.backends.onnx.webgpu.device = device; + const liveBuffers = new Set(); + let peakOwnedBuffers = 0; + const createBuffer = device.createBuffer.bind(device); + device.createBuffer = (descriptor) => { + const buffer = createBuffer(descriptor); + if (descriptor.label?.startsWith("transformers-beam-")) { + liveBuffers.add(buffer); + peakOwnedBuffers = Math.max(peakOwnedBuffers, liveBuffers.size); + const destroy = buffer.destroy.bind(buffer); + buffer.destroy = () => { + liveBuffers.delete(buffer); + destroy(); + }; + } + return buffer; + }; + const errors = []; + device.addEventListener("uncapturederror", (event) => { + errors.push(event.error.message); + console.error(event.error.message); + }); + device.lost.then((value) => { + console.error("DEVICE_LOST", value.reason, value.message); + }); + + if (options.mode === "validate") { + const cases = [ + ["float32", Float32Array, [3, 4]], + ["float16", Uint16Array, [3, 4]], + ["float16", Uint16Array, [3, 3]], + ["int64", BigInt64Array, [3, 2]], + ["uint8", Uint8Array, [3, 4]], + ["bool", Uint8Array, [3, 4]], + ]; + const results = []; + for (const [type, ArrayType, dims] of cases) { + const count = dims.reduce((a, b) => a * b, 1); + const data = ArrayType.from({ length: count }, (_, i) => (type === "int64" ? BigInt(i + 1) : type === "bool" ? i % 2 : i + 1)); + const size = Math.ceil(data.byteLength / 4) * 4; + const input = device.createBuffer({ size, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST }); + const padded = new Uint8Array(size); + padded.set(new Uint8Array(data.buffer)); + device.queue.writeBuffer(input, 0, padded); + let downloads = 0; + const original = new Tensor( + getTensorConstructor().fromGpuBuffer(input, { + dataType: type, + dims, + download: async () => { + ++downloads; + const staging = device.createBuffer({ size, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); + const encoder = device.createCommandEncoder(); + encoder.copyBufferToBuffer(input, 0, staging, 0, size); + device.queue.submit([encoder.finish()]); + await staging.mapAsync(GPUMapMode.READ); + const result = new ArrayType(staging.getMappedRange().slice(0, data.byteLength)); + staging.destroy(); + return result; + }, + }), + ); + const selected = await index_select_async(original, [2, 0, 2]); + const selectedLocation = selected.location; + const aligned = (dims[1] * ArrayType.BYTES_PER_ELEMENT) % 4 === 0; + if (selectedLocation !== (aligned ? "gpu-buffer" : "cpu")) throw new Error("Unexpected row selection location"); + if (aligned && (downloads !== 0 || original.location !== "gpu-buffer")) throw new Error("GPU selection downloaded the source"); + const chained = await index_select_async(selected, [1, 0]); + const actual = await chained.ort_tensor.getData(); + const expected = [...data.slice(0, dims[1]), ...data.slice(2 * dims[1], 3 * dims[1])]; + const actualValues = type === "float16" ? new Uint16Array(actual.buffer, actual.byteOffset, actual.byteLength / 2) : actual; + if (!equal([...actualValues], expected)) throw new Error("Typed/chained GPU selection mismatch: " + type); + chained.dispose(); + selected.dispose(); + // Source buffers must still be usable after disposing selected tensors. + const remaining = await original.ort_tensor.getData(); + if (!equal([...remaining], [...data])) throw new Error("Source ownership violated"); + original.dispose(); + input.destroy(); + if (liveBuffers.size) throw new Error("GPU row buffers were not released"); + const result = { type: "validation", dtype: type, dims, selectedLocation, chainedAndSourceOwnership: true }; + results.push(result); + emit(result); + } + await device.queue.onSubmittedWorkDone(); + if (errors.length) throw new Error(errors.join("\n")); + return { hardware, results, errors }; + } + + if (options.mode === "micro") { + const results = []; + for (const dims of [ + [4, 8, 128, 64], + [4, 8, 1024, 64], + [8, 16, 2048, 64], + ]) { + const elements = dims.reduce((a, b) => a * b, 1); + const data = Float32Array.from({ length: elements }, (_, i) => i % 997); + const input = device.createBuffer({ size: data.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST }); + device.queue.writeBuffer(input, 0, data); + const indices = Array.from({ length: dims[0] }, (_, i) => (i * 3 + 1) % dims[0]); + const source = () => + new Tensor( + getTensorConstructor().fromGpuBuffer(input, { + dataType: "float32", + dims, + download: async () => { + const staging = device.createBuffer({ size: data.byteLength, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); + const encoder = device.createCommandEncoder(); + encoder.copyBufferToBuffer(input, 0, staging, 0, data.byteLength); + device.queue.submit([encoder.finish()]); + await staging.mapAsync(GPUMapMode.READ); + const copy = new Float32Array(staging.getMappedRange().slice(0)); + staging.unmap(); + staging.destroy(); + return copy; + }, + }), + ); + const durations = []; + let outputLocation; + for (let repeat = 0; repeat < 12; ++repeat) { + const tensor = source(); + await device.queue.onSubmittedWorkDone(); + const start = performance.now(); + const output = await index_select_async(tensor, indices); + await device.queue.onSubmittedWorkDone(); + const elapsed = performance.now() - start; + outputLocation = output.location; + if (repeat >= 2) durations.push(elapsed); + if (repeat === 0) { + const actual = await output.ort_tensor.getData(); + const rowSize = elements / dims[0]; + for (let row = 0; row < dims[0]; ++row) { + for (let i = 0; i < rowSize; ++i) { + if (actual[row * rowSize + i] !== data[indices[row] * rowSize + i]) throw new Error("Row selection mismatch"); + } + } + } + output.dispose(); + tensor.dispose(); + } + input.destroy(); + const result = { type: "micro", dims, bytes: data.byteLength, medianMs: median(durations), samplesMs: durations, outputLocation }; + results.push(result); + emit(result); + } + if (errors.length) throw new Error(errors.join("\n")); + return { hardware, results, errors }; + } + + const models = options.models ?? ["hf-internal-testing/tiny-random-T5ForConditionalGeneration", "hf-internal-testing/tiny-random-LlamaForCausalLM"]; + const results = []; + for (const modelId of models) { + const Model = /T5/.test(modelId) ? AutoModelForSeq2SeqLM : AutoModelForCausalLM; + const model = await Model.from_pretrained(modelId, { device: options.device ?? "webgpu", dtype: options.dtype ?? "fp32" }); + const tokenizer = await AutoTokenizer.from_pretrained(modelId); + tokenizer.padding_side = "left"; + let cacheStats = []; + const reorder = options.cpuRowSelection + ? async (cache, indices) => { + const entries = {}; + for (const [key, tensor] of Object.entries(cache)) { + if (key.includes("encoder")) { + entries[key] = tensor; + continue; + } + const location = tensor.location; + await tensor.ort_tensor.getData(false); + entries[key] = index_select(tensor, model._get_cache_indices(key, indices)); + if (location === "gpu-buffer") tensor.dispose(); + } + return new DynamicCache(entries); + } + : model._reorder_cache.bind(model); + model._reorder_cache = async (cache, indices) => { + const before = Object.values(cache).map((t) => ({ location: t.location, size: t.size })); + const start = performance.now(); + const result = await reorder(cache, indices); + cacheStats.push({ ms: performance.now() - start, before, after: Object.values(result).map((t) => t.location) }); + return result; + }; + const configs = [ + { name: "standard", num_beams: 4, num_return_sequences: 2 }, + { name: "diverse", num_beams: 4, num_beam_groups: 2, diversity_penalty: 0.5, num_return_sequences: 2 }, + { name: "sampling", num_beams: 4, num_return_sequences: 2, do_sample: true, top_k: 10 }, + { name: "batched", num_beams: 4, num_return_sequences: 2 }, + ]; + for (const { name, ...config } of configs.filter((config) => !options.modes || options.modes.includes(config.name))) { + const texts = name === "batched" ? ["hello", "a longer input"] : ["hello"]; + const inputs = tokenizer(texts, { padding: true }); + const durations = []; + let expected; + for (let repeat = 0; repeat < (options.repeats ?? 4); ++repeat) { + random.seed(42); + cacheStats = []; + const start = performance.now(); + const output = await model.generate({ ...inputs, ...config, max_new_tokens: options.tokens ?? 16, eos_token_id: null, return_dict_in_generate: true }); + const elapsed = performance.now() - start; + if (liveBuffers.size) throw new Error("GPU row buffers leaked after generation"); + const tokens = output.sequences.tolist(); + if (output.past_key_values !== null) throw new Error("Unexpected beam cache output"); + if (expected && !equal(tokens, expected)) throw new Error("Repeated generation changed output: " + name); + expected = tokens; + if (repeat > 0) durations.push(elapsed); + } + if (name === "batched") { + for (let i = 0; i < texts.length; ++i) { + const single = await model.generate({ ...tokenizer(texts[i]), ...config, max_new_tokens: options.tokens ?? 16, eos_token_id: null }); + const tail = (rows) => rows.map((row) => row.slice(-(options.tokens ?? 16))); + if (!equal(tail(expected.slice(i * 2, i * 2 + 2)), tail(single.tolist()))) throw new Error("Batch independence failed"); + } + } + const result = { + type: "generation", + modelId, + name, + device: options.device ?? "webgpu", + medianMs: median(durations), + samplesMs: durations, + tokens: expected, + cacheStats, + }; + results.push(result); + emit({ ...result, tokens: undefined, cacheStats: undefined }); + } + await model.dispose(); + } + await device.queue.onSubmittedWorkDone(); + if (errors.length) throw new Error(errors.join("\n")); + return { hardware, results, errors, peakOwnedBuffers, remainingOwnedBuffers: liveBuffers.size }; +}; diff --git a/scripts/beam-gpu/build.mjs b/scripts/beam-gpu/build.mjs new file mode 100644 index 000000000..d8cf63439 --- /dev/null +++ b/scripts/beam-gpu/build.mjs @@ -0,0 +1,16 @@ +import path from "node:path"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +const require = createRequire(path.join(root, "packages/transformers/package.json")); +const { build } = require("esbuild"); +const { ignoreModulesPlugin } = await import("../../packages/transformers/scripts/build/plugins/ignoreModulesPlugin.mjs"); +await build({ + entryPoints: [path.join(root, "scripts/beam-gpu/browser.js")], + bundle: true, + platform: "browser", + format: "esm", + sourcemap: true, + outfile: process.env.BEAM_APP_OUT ?? "/workspace/beam-gpu/runner/app.js", + plugins: [ignoreModulesPlugin(["./onnx-node.js", "sharp", "fs", "path", "url", "stream", "stream/promises"])], +}); diff --git a/scripts/beam-gpu/candidates.mjs b/scripts/beam-gpu/candidates.mjs new file mode 100644 index 000000000..35cd41515 --- /dev/null +++ b/scripts/beam-gpu/candidates.mjs @@ -0,0 +1,27 @@ +import { performance } from "node:perf_hooks"; +import { selectBeamCandidates } from "../../packages/transformers/src/generation/beam_search_utils.js"; +const median = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)]; +for (const vocab of [32000, 151936]) { + const scores = Float32Array.from({ length: vocab }, (_, i) => Math.sin(i * 17) * 10); + for (const count of [8, 50]) { + const baseline = () => + Array.from(scores, (score, token) => ({ score: -3 + score, token: BigInt(token), beam_idx: 0 })) + .sort((a, b) => b.score - a.score) + .slice(0, count); + const optimized = () => selectBeamCandidates(scores, -3, 0, count); + const stringify = (x) => JSON.stringify(x, (_, value) => (typeof value === "bigint" ? String(value) : value)); + if (stringify(baseline()) !== stringify(optimized())) throw new Error("Candidate selection mismatch"); + const times = {}; + for (const [name, fn] of Object.entries({ baseline, optimized })) { + const samples = []; + for (let repeat = 0; repeat < 15; ++repeat) { + const start = performance.now(); + fn(); + const ms = performance.now() - start; + if (repeat >= 5) samples.push(ms); + } + times[name] = { medianMs: median(samples), samplesMs: samples }; + } + console.log(JSON.stringify({ vocab, count, ...times, identical: true })); + } +} diff --git a/scripts/beam-gpu/runner.mjs b/scripts/beam-gpu/runner.mjs new file mode 100644 index 000000000..bb6adc234 --- /dev/null +++ b/scripts/beam-gpu/runner.mjs @@ -0,0 +1,87 @@ +import http from "node:http"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +const root = process.env.BEAM_PROJECT_ROOT ?? path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +const runner = process.env.BEAM_RUNNER_ROOT ?? "/workspace/beam-gpu/runner"; +const { chromium } = await import(pathToFileURL(path.join(process.env.BEAM_PLAYWRIGHT_ROOT ?? runner, "node_modules/playwright/index.mjs"))); +const ort = path.join(root, "packages/transformers/node_modules/onnxruntime-web/dist"); +const cache = path.join(runner, "model-cache"); +fs.mkdirSync(cache, { recursive: true }); +const options = JSON.parse(process.env.BEAM_OPTIONS ?? '{"mode":"probe"}'); +const server = http.createServer(async (req, res) => { + res.setHeader("Cross-Origin-Opener-Policy", "same-origin"); + res.setHeader("Cross-Origin-Embedder-Policy", "require-corp"); + try { + const pathname = new URL(req.url, "http://localhost").pathname; + if (pathname.startsWith("/hf/")) { + const relative = pathname.slice(4); + const local = path.join(cache, relative); + if (!fs.existsSync(local)) { + const upstream = await fetch("https://huggingface.co/" + relative); + if (!upstream.ok) { + res.writeHead(upstream.status); + res.end(await upstream.text()); + return; + } + fs.mkdirSync(path.dirname(local), { recursive: true }); + fs.writeFileSync(local, Buffer.from(await upstream.arrayBuffer())); + } + res.end(fs.readFileSync(local)); + return; + } + if (pathname === "/") { + res.setHeader("Content-Type", "text/html"); + res.end(''); + return; + } + const file = pathname.startsWith("/ort/") ? path.join(ort, path.basename(pathname)) : path.join(runner, path.basename(pathname)); + res.setHeader("Content-Type", file.endsWith(".wasm") ? "application/wasm" : "text/javascript"); + res.end(fs.readFileSync(file)); + } catch (error) { + res.statusCode = 500; + res.end(String(error)); + } +}); +await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); +const browser = await chromium.launch({ + headless: true, + dumpio: process.env.BEAM_DEBUG === "1", + channel: "chromium", + args: [ + "--no-sandbox", + "--enable-gpu", + "--disable-gpu-sandbox", + "--enable-unsafe-webgpu", + "--ignore-gpu-blocklist", + "--use-angle=vulkan", + "--enable-features=Vulkan,VulkanFromANGLE,DefaultANGLEVulkan", + "--disable-vulkan-surface", + "--disable-dev-shm-usage", + ], +}); +try { + const page = await browser.newPage(); + page.on("console", (message) => console.log(message.type(), message.text())); + page.on("pageerror", (error) => console.error("PAGE_ERROR", error.message)); + await page.goto("http://127.0.0.1:" + server.address().port); + await page.waitForFunction(() => typeof window.runBeamGPU === "function"); + const result = await page.evaluate((options) => window.runBeamGPU(options), options); + const output = process.env.BEAM_RESULT ?? path.join(runner, "result.json"); + fs.writeFileSync( + output, + JSON.stringify( + { timestamp: new Date().toISOString(), browser: browser.version(), options, ...result }, + (_, x) => (typeof x === "bigint" ? x.toString() : x), + 2, + ), + ); + console.log("SAVED", output); +} catch (error) { + const cdp = await browser.newBrowserCDPSession(); + console.error("GPU_DIAGNOSTICS", JSON.stringify(await cdp.send("SystemInfo.getInfo"))); + throw error; +} finally { + await browser.close(); + server.close(); +} From bab43ff173c67465dbd0e311ac5bc7e7c6c7fe2d Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Tue, 20 Oct 2026 14:20:48 -0600 Subject: [PATCH 09/21] Keep aligned beam cache row selection on WebGPU --- .../docs/source/guides/beam-search.md | 14 ++++ packages/transformers/src/utils/tensor.js | 11 ++- packages/transformers/src/utils/webgpu.js | 71 +++++++++++++++++++ 3 files changed, 94 insertions(+), 2 deletions(-) create mode 100644 packages/transformers/src/utils/webgpu.js diff --git a/packages/transformers/docs/source/guides/beam-search.md b/packages/transformers/docs/source/guides/beam-search.md index 4cc863b35..f6bacc252 100644 --- a/packages/transformers/docs/source/guides/beam-search.md +++ b/packages/transformers/docs/source/guides/beam-search.md @@ -69,6 +69,20 @@ const sequences = await model.generate({ }); ``` +## WebGPU + +Load a model with `device: 'webgpu'` to run inference on WebGPU. Beam reordering +keeps aligned decoder-cache tensors on the GPU using buffer row copies. Candidate +ranking still runs in JavaScript. Tensors whose row sizes are not multiples of +four bytes use CPU row selection instead. + +```javascript +const model = await AutoModelForSeq2SeqLM.from_pretrained(model_id, { + device: 'webgpu', + dtype: 'fp32', +}); +``` + ## Restrictions Beam search rejects streamers and classifier-free guidance (`guidance_scale > 1`). diff --git a/packages/transformers/src/utils/tensor.js b/packages/transformers/src/utils/tensor.js index b55eee8d9..3349897d4 100644 --- a/packages/transformers/src/utils/tensor.js +++ b/packages/transformers/src/utils/tensor.js @@ -16,6 +16,7 @@ import { TensorOpRegistry } from '../ops/registry.js'; import { DataTypeMap } from './dtypes.js'; import { random } from './random.js'; +import { selectWebGPURows } from './webgpu.js'; /** * @typedef {keyof typeof DataTypeMap} DataType @@ -1503,16 +1504,22 @@ export function index_select(tensor, indices) { } /** - * Async version of index_select that supports GPU-backed tensors by downloading data to CPU. + * Async row selection. Aligned WebGPU tensors stay on the GPU; other device + * tensors are downloaded to the CPU without releasing caller-owned resources. * @param {Tensor} tensor The source tensor. * @param {number[]} indices Array of row indices to select. - * @returns {Promise} A new tensor with selected rows (CPU-backed). + * @returns {Promise} A new tensor with selected rows. */ export async function index_select_async(tensor, indices) { if (tensor.location === 'cpu' || tensor.location === 'cpu-pinned') { return index_select(tensor, indices); } + if (tensor.location === 'gpu-buffer') { + const selected = await selectWebGPURows(tensor.ort_tensor, indices); + if (selected) return new Tensor(selected); + } + // Download GPU/ML data without releasing resources owned by the caller. const ort_tensor = tensor.ort_tensor; if (!ort_tensor?.getData) { diff --git a/packages/transformers/src/utils/webgpu.js b/packages/transformers/src/utils/webgpu.js new file mode 100644 index 000000000..c29ee3374 --- /dev/null +++ b/packages/transformers/src/utils/webgpu.js @@ -0,0 +1,71 @@ +import { env } from '../env.js'; +import { getTensorConstructor } from '../backends/onnx.js'; + +/** + * Select aligned tensor rows without transferring WebGPU data to the CPU. + * Returns null when the tensor cannot use WebGPU buffer copies. + * @param {import('onnxruntime-common').Tensor} tensor + * @param {number[]} indices + * @returns {Promise} + * @internal + */ +export async function selectWebGPURows(tensor, indices) { + if (typeof GPUBufferUsage === 'undefined') return null; + const TypedArray = { + float32: Float32Array, + float16: Uint16Array, + int32: Int32Array, + uint32: Uint32Array, + int64: BigInt64Array, + uint8: Uint8Array, + bool: Uint8Array, + }[tensor.type]; + const row_size = tensor.dims.slice(1).reduce((a, b) => a * b, 1); + const row_bytes = row_size * TypedArray?.BYTES_PER_ELEMENT; + // Buffer copies require four-byte aligned offsets and lengths. Odd fp16 + // rows and packed data types keep the existing CPU fallback. + if (!row_bytes || row_bytes % 4 !== 0 || indices.length === 0) return null; + if (indices.some((index) => !Number.isInteger(index) || index < 0 || index >= tensor.dims[0])) return null; + const source = tensor.gpuBuffer; + if (!(source.usage & GPUBufferUsage.COPY_SRC)) return null; + const device = await env.backends.onnx.webgpu?.device; + if (!device) return null; + const size = indices.length * row_bytes; + if (size > device.limits.maxBufferSize) return null; + const output = device.createBuffer({ + label: 'transformers-beam-rows', + size, + usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST, + }); + try { + const encoder = device.createCommandEncoder(); + for (let row = 0; row < indices.length; ++row) { + encoder.copyBufferToBuffer(source, indices[row] * row_bytes, output, row * row_bytes, row_bytes); + } + device.queue.submit([encoder.finish()]); + return getTensorConstructor().fromGpuBuffer(output, { + dataType: /** @type {import('onnxruntime-common').Tensor.GpuBufferDataTypes} */ (tensor.type), + dims: [indices.length, ...tensor.dims.slice(1)], + dispose: () => output.destroy(), + download: async () => { + const staging = device.createBuffer({ + label: 'transformers-beam-readback', + size, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, + }); + try { + const copy = device.createCommandEncoder(); + copy.copyBufferToBuffer(output, 0, staging, 0, size); + device.queue.submit([copy.finish()]); + await staging.mapAsync(GPUMapMode.READ); + return new TypedArray(staging.getMappedRange().slice(0)); + } finally { + staging.destroy(); + } + }, + }); + } catch (error) { + output.destroy(); + throw error; + } +} From 6605358afa69d40f64c136908478b3f9e98efdac Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Tue, 20 Oct 2026 14:20:48 -0600 Subject: [PATCH 10/21] Select beam candidates with a bounded top-k heap --- .../src/generation/beam_search_utils.js | 56 +++++++++++++++++++ .../transformers/src/models/modeling_utils.js | 42 ++++++-------- .../tests/utils/beam_search_utils.test.js | 32 +++++++++++ 3 files changed, 106 insertions(+), 24 deletions(-) create mode 100644 packages/transformers/src/generation/beam_search_utils.js create mode 100644 packages/transformers/tests/utils/beam_search_utils.test.js diff --git a/packages/transformers/src/generation/beam_search_utils.js b/packages/transformers/src/generation/beam_search_utils.js new file mode 100644 index 000000000..fcd3a8fa7 --- /dev/null +++ b/packages/transformers/src/generation/beam_search_utils.js @@ -0,0 +1,56 @@ +/** + * Select the highest scoring tokens without sorting or allocating an object + * for every vocabulary entry. Ties keep ascending token order. + * @param {Float32Array} log_probs + * @param {number} beam_score + * @param {number} beam_idx + * @param {number} count + * @param {Map} [token_counts] + * @param {number} [diversity_penalty] + * @returns {{score: number, token: bigint, beam_idx: number}[]} + * @internal + */ +export function selectBeamCandidates(log_probs, beam_score, beam_idx, count, token_counts, diversity_penalty = 0) { + count = Math.min(log_probs.length, Math.max(0, Math.floor(count))); + if (count === 0) return []; + const penalties = new Map(); + if (token_counts && diversity_penalty !== 0) { + for (const [token, frequency] of token_counts) penalties.set(Number(token), frequency * diversity_penalty); + } + if (count === log_probs.length) { + return Array.from(log_probs, (score, token) => ({ + score: beam_score + score - (penalties.get(token) ?? 0), + token: BigInt(token), + beam_idx, + })).sort((a, b) => b.score - a.score); + } + /** @type {{score: number, token: number}[]} */ + const heap = []; + const worse = (a, b) => a.score < b.score || (a.score === b.score && a.token > b.token); + for (let token = 0; token < log_probs.length; ++token) { + const score = beam_score + log_probs[token] - (penalties.get(token) ?? 0); + if (heap.length < count) { + let child = heap.length; + heap.push({ score, token }); + while (child > 0) { + const parent = (child - 1) >> 1; + if (!worse(heap[child], heap[parent])) break; + [heap[child], heap[parent]] = [heap[parent], heap[child]]; + child = parent; + } + } else if (score > heap[0].score) { + heap[0] = { score, token }; + let parent = 0; + while (parent * 2 + 1 < heap.length) { + let child = parent * 2 + 1; + if (child + 1 < heap.length && worse(heap[child + 1], heap[child])) ++child; + if (!worse(heap[child], heap[parent])) break; + [heap[child], heap[parent]] = [heap[parent], heap[child]]; + parent = child; + } + } + } + return heap + .sort((a, b) => b.score - a.score || a.token - b.token) + .map(({ score, token }) => ({ score, token: BigInt(token), beam_idx })); +} diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js index 066a15c2f..07fa67276 100644 --- a/packages/transformers/src/models/modeling_utils.js +++ b/packages/transformers/src/models/modeling_utils.js @@ -54,6 +54,7 @@ import { GenerationConfig } from '../generation/configuration_utils.js'; import { EosTokenCriteria, MaxLengthCriteria, StoppingCriteriaList } from '../generation/stopping_criteria.js'; import { LogitsSampler } from '../generation/logits_sampler.js'; import { BeamSearchScorer } from '../generation/beam_search.js'; +import { selectBeamCandidates } from '../generation/beam_search_utils.js'; import { DefaultProgressCallback, pick } from '../utils/core.js'; import { log_softmax } from '../utils/maths.js'; import { ModelOutput } from './modeling_outputs.js'; @@ -1188,24 +1189,16 @@ export class PreTrainedModel extends Callable { const log_probs = logits_data; const beam_score = beam_scores[flat_beam]; - // Retain enough candidates per beam to fill the group after EOS. - /** @type {{score: number, token: bigint, beam_idx: number}[]} */ - const beam_candidates = []; - for (let v = 0; v < vocab_size; ++v) { - const token = BigInt(v); - let score = beam_score + log_probs[v]; - const penalty_count = prev_group_tokens[batch_idx].get(token) ?? 0; - if (penalty_count > 0) { - score -= diversity_penalty * penalty_count; - } - beam_candidates.push({ - score, - token, + candidates.push( + ...selectBeamCandidates( + log_probs, + beam_score, beam_idx, - }); - } - beam_candidates.sort((a, b) => b.score - a.score); - candidates.push(...beam_candidates.slice(0, candidates_per_beam * group_size)); + candidates_per_beam * group_size, + prev_group_tokens[batch_idx], + diversity_penalty, + ), + ); } // Rank candidates across the group for this batch item. @@ -1270,18 +1263,19 @@ export class PreTrainedModel extends Callable { for (let beam_idx = 0; beam_idx < num_beams; ++beam_idx) { const flat_beam = batch_idx * num_beams + beam_idx; const logits_data = /** @type {Float32Array} */ (next_tokens_scores[flat_beam].data); - const beam_candidates = Array.from(logits_data, (score, token) => ({ - score: beam_scores[flat_beam] + score, - token: BigInt(token), - beam_idx, - })); - beam_candidates.sort((a, b) => b.score - a.score); const count = do_beam_sample ? top_k > 0 ? Math.max(top_k, candidates_per_beam * num_beams) : vocab_size : candidates_per_beam * num_beams; - for (const candidate of beam_candidates.slice(0, count)) candidates.push(candidate); + for (const candidate of selectBeamCandidates( + logits_data, + beam_scores[flat_beam], + beam_idx, + count, + )) { + candidates.push(candidate); + } } const count = Math.min(candidates_per_beam * num_beams, candidates.length); diff --git a/packages/transformers/tests/utils/beam_search_utils.test.js b/packages/transformers/tests/utils/beam_search_utils.test.js new file mode 100644 index 000000000..0b0de3598 --- /dev/null +++ b/packages/transformers/tests/utils/beam_search_utils.test.js @@ -0,0 +1,32 @@ +import { selectBeamCandidates } from "../../src/generation/beam_search_utils.js"; + +const reference = (scores, beam_score, beam_idx, count, tokens = new Map(), penalty = 0) => + Array.from(scores, (score, token) => ({ score: beam_score + score - (tokens.get(BigInt(token)) ?? 0) * penalty, token: BigInt(token), beam_idx })) + .sort((a, b) => b.score - a.score) + .slice(0, count); + +describe("Beam candidate selection", () => { + it.each([1, 2, 8, 50, 1000, 1024, 2000])("matches a full vocabulary sort for top %i", (count) => { + const scores = Float32Array.from({ length: 1024 }, (_, token) => Math.sin(token * 17) * 10); + expect(selectBeamCandidates(scores, -3.25, 2, count)).toEqual(reference(scores, -3.25, 2, count)); + }); + + it("preserves token order for tied and suppressed scores", () => { + const scores = new Float32Array([1, -Infinity, 2, 2, -Infinity, 1, 2]); + for (const count of [2, 3, 5, 7]) expect(selectBeamCandidates(scores, 0, 0, count)).toEqual(reference(scores, 0, 0, count)); + }); + + it("applies diversity penalties before selecting candidates", () => { + const scores = new Float32Array([0, 2, 4, 6, 8]); + const tokens = new Map([ + [4n, 2], + [3n, 1], + ]); + expect(selectBeamCandidates(scores, -1, 3, 3, tokens, 3)).toEqual(reference(scores, -1, 3, 3, tokens, 3)); + }); + + it("handles empty selections", () => { + expect(selectBeamCandidates(new Float32Array([1, 2]), 0, 0, 0)).toEqual([]); + expect(selectBeamCandidates(new Float32Array(), 0, 0, 4)).toEqual([]); + }); +}); From 8e3cd1e1f6ade984b6ab250bbb5e235b2be16ab6 Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Tue, 20 Oct 2026 14:26:39 -0600 Subject: [PATCH 11/21] Validate GPU buffer lifetimes and pad row outputs for ONNX Runtime --- packages/transformers/src/utils/webgpu.js | 6 ++++-- scripts/beam-gpu/browser.js | 3 +++ scripts/beam-gpu/run.sh | 18 ++++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100755 scripts/beam-gpu/run.sh diff --git a/packages/transformers/src/utils/webgpu.js b/packages/transformers/src/utils/webgpu.js index c29ee3374..0ffc77de1 100644 --- a/packages/transformers/src/utils/webgpu.js +++ b/packages/transformers/src/utils/webgpu.js @@ -30,7 +30,9 @@ export async function selectWebGPURows(tensor, indices) { if (!(source.usage & GPUBufferUsage.COPY_SRC)) return null; const device = await env.backends.onnx.webgpu?.device; if (!device) return null; - const size = indices.length * row_bytes; + const byte_length = indices.length * row_bytes; + // ONNX Runtime rounds GPU transfer sizes up to sixteen bytes. + const size = Math.ceil(byte_length / 16) * 16; if (size > device.limits.maxBufferSize) return null; const output = device.createBuffer({ label: 'transformers-beam-rows', @@ -58,7 +60,7 @@ export async function selectWebGPURows(tensor, indices) { copy.copyBufferToBuffer(output, 0, staging, 0, size); device.queue.submit([copy.finish()]); await staging.mapAsync(GPUMapMode.READ); - return new TypedArray(staging.getMappedRange().slice(0)); + return new TypedArray(staging.getMappedRange().slice(0, byte_length)); } finally { staging.destroy(); } diff --git a/scripts/beam-gpu/browser.js b/scripts/beam-gpu/browser.js index 72ee76dc5..554ec86e4 100644 --- a/scripts/beam-gpu/browser.js +++ b/scripts/beam-gpu/browser.js @@ -68,7 +68,9 @@ window.runBeamGPU = async (options) => { if (options.mode === "validate") { const cases = [ ["float32", Float32Array, [3, 4]], + ["float32", Float32Array, [3, 1]], ["float16", Uint16Array, [3, 4]], + ["float16", Uint16Array, [3, 2]], ["float16", Uint16Array, [3, 3]], ["int64", BigInt64Array, [3, 2]], ["uint8", Uint8Array, [3, 4]], @@ -104,6 +106,7 @@ window.runBeamGPU = async (options) => { const selected = await index_select_async(original, [2, 0, 2]); const selectedLocation = selected.location; const aligned = (dims[1] * ArrayType.BYTES_PER_ELEMENT) % 4 === 0; + if (aligned && selected.ort_tensor.gpuBuffer.size % 16 !== 0) throw new Error("GPU output is not padded for ONNX Runtime"); if (selectedLocation !== (aligned ? "gpu-buffer" : "cpu")) throw new Error("Unexpected row selection location"); if (aligned && (downloads !== 0 || original.location !== "gpu-buffer")) throw new Error("GPU selection downloaded the source"); const chained = await index_select_async(selected, [1, 0]); diff --git a/scripts/beam-gpu/run.sh b/scripts/beam-gpu/run.sh new file mode 100755 index 000000000..a6cf02bf3 --- /dev/null +++ b/scripts/beam-gpu/run.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +set -euo pipefail +OUTPUT_ROOT=${BEAM_OUTPUT_ROOT:-/workspace/beam-gpu} +mkdir -p "$OUTPUT_ROOT" +trap 'code=$?; printf "%s\n" "$code" > "$OUTPUT_ROOT/final-exit-status"' EXIT +git rev-parse HEAD > "$OUTPUT_ROOT/final-source-commit" +git status --porcelain > "$OUTPUT_ROOT/final-source-status" +node scripts/beam-gpu/build.mjs +run_case() { + BEAM_OPTIONS="$2" BEAM_RESULT="$OUTPUT_ROOT/$1.json" node scripts/beam-gpu/runner.mjs +} +run_case final-validation '{"mode":"validate"}' +run_case final-micro '{"mode":"micro"}' +run_case final-generation '{"mode":"generation","tokens":16,"repeats":4}' +run_case smollm-optimized '{"mode":"generation","models":["onnx-community/SmolLM2-135M-Instruct-ONNX"],"dtype":"fp32","modes":["standard","batched"],"tokens":32,"repeats":4}' +run_case final-stress '{"mode":"generation","models":["hf-internal-testing/tiny-random-LlamaForCausalLM"],"modes":["standard"],"tokens":8,"repeats":25}' +node scripts/beam-gpu/candidates.mjs > "$OUTPUT_ROOT/candidates-remote.jsonl" +pnpm build > "$OUTPUT_ROOT/final-build.log" 2>&1 From 58699fa153ece4803a2e3bd4206f59197fa4ec26 Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Tue, 20 Oct 2026 14:29:12 -0600 Subject: [PATCH 12/21] Track buffer lifetime on ONNX Runtime's active GPU device --- scripts/beam-gpu/browser.js | 40 +++++++++++++++++++++++-------------- scripts/beam-gpu/run.sh | 1 + 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/scripts/beam-gpu/browser.js b/scripts/beam-gpu/browser.js index 554ec86e4..d90393f05 100644 --- a/scripts/beam-gpu/browser.js +++ b/scripts/beam-gpu/browser.js @@ -42,20 +42,26 @@ window.runBeamGPU = async (options) => { env.backends.onnx.webgpu.device = device; const liveBuffers = new Set(); let peakOwnedBuffers = 0; - const createBuffer = device.createBuffer.bind(device); - device.createBuffer = (descriptor) => { - const buffer = createBuffer(descriptor); - if (descriptor.label?.startsWith("transformers-beam-")) { - liveBuffers.add(buffer); - peakOwnedBuffers = Math.max(peakOwnedBuffers, liveBuffers.size); - const destroy = buffer.destroy.bind(buffer); - buffer.destroy = () => { - liveBuffers.delete(buffer); - destroy(); - }; - } - return buffer; + const trackedDevices = new WeakSet(); + const trackDevice = (gpuDevice) => { + if (trackedDevices.has(gpuDevice)) return; + trackedDevices.add(gpuDevice); + const createBuffer = gpuDevice.createBuffer.bind(gpuDevice); + gpuDevice.createBuffer = (descriptor) => { + const buffer = createBuffer(descriptor); + if (descriptor.label?.startsWith("transformers-beam-")) { + liveBuffers.add(buffer); + peakOwnedBuffers = Math.max(peakOwnedBuffers, liveBuffers.size); + const destroy = buffer.destroy.bind(buffer); + buffer.destroy = () => { + liveBuffers.delete(buffer); + destroy(); + }; + } + return buffer; + }; }; + trackDevice(device); const errors = []; device.addEventListener("uncapturederror", (event) => { errors.push(event.error.message); @@ -128,7 +134,7 @@ window.runBeamGPU = async (options) => { } await device.queue.onSubmittedWorkDone(); if (errors.length) throw new Error(errors.join("\n")); - return { hardware, results, errors }; + return { hardware, results, errors, peakOwnedBuffers, remainingOwnedBuffers: liveBuffers.size }; } if (options.mode === "micro") { @@ -190,7 +196,7 @@ window.runBeamGPU = async (options) => { emit(result); } if (errors.length) throw new Error(errors.join("\n")); - return { hardware, results, errors }; + return { hardware, results, errors, peakOwnedBuffers, remainingOwnedBuffers: liveBuffers.size }; } const models = options.models ?? ["hf-internal-testing/tiny-random-T5ForConditionalGeneration", "hf-internal-testing/tiny-random-LlamaForCausalLM"]; @@ -198,6 +204,7 @@ window.runBeamGPU = async (options) => { for (const modelId of models) { const Model = /T5/.test(modelId) ? AutoModelForSeq2SeqLM : AutoModelForCausalLM; const model = await Model.from_pretrained(modelId, { device: options.device ?? "webgpu", dtype: options.dtype ?? "fp32" }); + trackDevice(await env.backends.onnx.webgpu.device); const tokenizer = await AutoTokenizer.from_pretrained(modelId); tokenizer.padding_side = "left"; let cacheStats = []; @@ -255,6 +262,9 @@ window.runBeamGPU = async (options) => { if (!equal(tail(expected.slice(i * 2, i * 2 + 2)), tail(single.tolist()))) throw new Error("Batch independence failed"); } } + if (!options.cpuRowSelection && cacheStats.some((step) => step.before.some((tensor) => tensor.location === "gpu-buffer")) && peakOwnedBuffers === 0) { + throw new Error("GPU buffer lifetime tracking did not observe the row-copy path"); + } const result = { type: "generation", modelId, diff --git a/scripts/beam-gpu/run.sh b/scripts/beam-gpu/run.sh index a6cf02bf3..deffb1c54 100755 --- a/scripts/beam-gpu/run.sh +++ b/scripts/beam-gpu/run.sh @@ -2,6 +2,7 @@ set -euo pipefail OUTPUT_ROOT=${BEAM_OUTPUT_ROOT:-/workspace/beam-gpu} mkdir -p "$OUTPUT_ROOT" +printf "running\n" > "$OUTPUT_ROOT/final-exit-status" trap 'code=$?; printf "%s\n" "$code" > "$OUTPUT_ROOT/final-exit-status"' EXIT git rev-parse HEAD > "$OUTPUT_ROOT/final-source-commit" git status --porcelain > "$OUTPUT_ROOT/final-source-status" From 61825bca679832542a5b9ac4396497858d12b593 Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Tue, 20 Oct 2026 14:41:57 -0600 Subject: [PATCH 13/21] Record verified WebGPU beam benchmarks and completed host cleanup --- scripts/beam-gpu/RESULTS.md | 113 ++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 scripts/beam-gpu/RESULTS.md diff --git a/scripts/beam-gpu/RESULTS.md b/scripts/beam-gpu/RESULTS.md new file mode 100644 index 000000000..cfde234f7 --- /dev/null +++ b/scripts/beam-gpu/RESULTS.md @@ -0,0 +1,113 @@ +# WebGPU beam decoding experiment — 2026-10-20 + +Branch: `dan/beam-webgpu-performance`, based on PR #1539 at `7c43a27`. +Product and hardware-validation revision: `58699fa153ece4803a2e3bd4206f59197fa4ec26`. + +## Changes + +- Keep aligned WebGPU cache rows on GPU with buffer-to-buffer copies. Other + device tensors and unaligned rows retain CPU fallback. Outputs have ONNX + Runtime's required 16-byte allocation padding and explicit disposal/download + callbacks. The active runtime's Tensor factory avoids package-version identity + mismatches when wrapping GPU buffers. +- Replace full-vocabulary object allocation/sorting with bounded top-k selection. + Ranking, diversity penalties, token tie order, and seeded outputs are preserved. +- Add an isolated, reproducible browser harness, dtype and ownership checks, + candidate-selection reference tests, benchmarks, and a GPU usage guide. + +## Hardware and method + +Runpod Secure Cloud RTX 4090, 24,564 MiB VRAM, NVIDIA driver 595.91.07, +Ubuntu 24.04 container/Linux 6.8, Node 24.14.1, Chromium 141.0.7390.37. +The adapter reported `nvidia` / `lovelace` and `isFallbackAdapter: false`. +The host allocation had 12 vCPUs and 100 GB system RAM. + +Model inference used fp32 and four beams, returning two sequences. Tiny models +used 16 new tokens; SmolLM2 used 32. Batched cases used two inputs. Each timing +is the median of three measured runs after one warmup. Model downloads and +initial session creation are excluded. Source code, backend, model bytes and +inputs were matched; raw model hashes are retained locally. + +The reference uses the original CPU cache-download/reorder algorithm and full +vocabulary sorting. The tuned path includes both GPU copies and bounded top-k. +These are workload-specific measurements, not general speedup guarantees. + +## End-to-end results + +| Model | Mode | Reference (ms) | Tuned (ms) | Speedup | +|---|---|---:|---:|---:| +| tiny-random-T5ForConditionalGeneration | standard | 2564.5 | 475.7 | 5.39x | +| tiny-random-T5ForConditionalGeneration | diverse | 2409.3 | 610.4 | 3.95x | +| tiny-random-T5ForConditionalGeneration | sampling | 2524.8 | 650.3 | 3.88x | +| tiny-random-T5ForConditionalGeneration | batched | 3201.3 | 805.6 | 3.97x | +| tiny-random-LlamaForCausalLM | standard | 2475.1 | 914.2 | 2.71x | +| tiny-random-LlamaForCausalLM | diverse | 2598.7 | 989.1 | 2.63x | +| tiny-random-LlamaForCausalLM | sampling | 2697.2 | 1079.4 | 2.50x | +| tiny-random-LlamaForCausalLM | batched | 4601.0 | 1738.8 | 2.65x | +| SmolLM2-135M-Instruct-ONNX | standard | 15571.3 | 1676.0 | 9.29x | +| SmolLM2-135M-Instruct-ONNX | batched | 19463.8 | 2014.7 | 9.66x | + +All ten reference-versus-tuned token arrays match exactly. A separate CPU/WASM +reference also matches all eight tiny-model WebGPU cases, including seeded +sampling and batched/diverse decoding. + +## Cache row-copy microbenchmarks + +Each result validates every copied element and measures completion on the GPU +queue. Two warmups precede ten samples. These numbers measure one synthetic +cache tensor, not full generation. + +| Tensor size | CPU-transfer reference (ms) | GPU copy (ms) | Speedup | +|---|---:|---:|---:| +| 1 MiB | 6.165 | 0.275 | 22.42x | +| 8 MiB | 25.690 | 1.640 | 15.66x | +| 64 MiB | 140.395 | 7.075 | 19.84x | + +## Verification + +- Full workspace CPU suite: **2,278 passed, 47 skipped, 30 suites passed**. +- Eight real-GPU boundary fixtures cover float32, float16, int64, uint8, bool, + duplicated/chained rows, unaligned fallback, small output padding, and + caller-owned source preservation. +- A 25-generation stress run leaves zero owned row-copy buffers live after every + generation. The active inference-device instrumentation observes a peak of + 60 owned buffers on SmolLM2 and zero remaining at completion. This checks + buffers owned by this implementation, not all runtime/driver allocations. +- Ten candidate-selection tests match a full-sort reference, including ties, + suppressed tokens, diversity penalties, large k, and empty input. +- Both packages build with declarations on macOS and the Linux worker; docs + generation and changed-file Prettier checks pass. +- Repository-wide formatting retains the two previously verified failures in + untouched `tensor.test.js` and `tensor_ops.test.js`. + +## Scope and setup findings + +Validation covers Linux/NVIDIA browser WebGPU with fp32 model inference. +The container required EGL dispatch libraries before Vulkan could initialize. +Chromium 156 returned a null WebGPU adapter on this host; pinned Chromium 141 +worked. The Qwen 0.5B fp16 attempt was rejected by the browser capability check; +its fp32 export hit a browser runtime allocation limit. Those attempts are +setup/coverage limits, not successful model validation. + +## Cost and cleanup + +Pod `tlouzqbaj8jchl` ran from 19:44:51 UTC to verified deletion at 20:38:26 UTC: +**53.6 minutes**, below the two-hour authorization. Compute was $0.89/hour; +40 GB disposable storage brought the estimate to about $0.90/hour. Estimated +total: **$0.80**. The account balance decreased by $0.7993, and final reported +compute spend was $0/hour; the per-pod billing ledger had not posted records. + +A fresh provider read returned 404 after deletion. No volume was created. +The scheduled cleanup backup was removed after deletion, and the local +watchdog/result archiver were signaled to exit. Automatic approval review +rejected copying the account API key onto the worker; no API key was copied +there. Credentials stayed local, with local sleep prevention and a scheduled +cleanup backup guarding the deadline. + +## Retained evidence + +Raw JSON/logs, source identity/status, model hashes, manifests and intermediate +archives are retained in the gitignored `scripts/beam-gpu/results/` directory. +The bootstrap and test harness are tracked in this directory. Run `run.sh` to +repeat the complete hardware-validation/benchmark sequence on an already +provisioned host. Provider credentials and SSH keys are not part of the repo. From b65dfaff9ca5e7e518c6e99f1d84f7453efd27c1 Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Tue, 20 Oct 2026 15:01:14 -0600 Subject: [PATCH 14/21] Fix beam resource ownership and reject unsupported generation combinations --- .../docs/source/guides/beam-search.md | 2 + packages/transformers/src/cache_utils.js | 13 +- .../src/generation/beam_search.js | 17 +- .../transformers/src/models/modeling_utils.js | 883 +++++++++--------- .../tests/utils/beam_ownership.test.js | 176 ++++ .../tests/utils/beam_search.test.js | 18 + 6 files changed, 683 insertions(+), 426 deletions(-) create mode 100644 packages/transformers/tests/utils/beam_ownership.test.js diff --git a/packages/transformers/docs/source/guides/beam-search.md b/packages/transformers/docs/source/guides/beam-search.md index f6bacc252..6ada53dd8 100644 --- a/packages/transformers/docs/source/guides/beam-search.md +++ b/packages/transformers/docs/source/guides/beam-search.md @@ -86,6 +86,8 @@ const model = await AutoModelForSeq2SeqLM.from_pretrained(model_id, { ## Restrictions Beam search rejects streamers and classifier-free guidance (`guidance_scale > 1`). +Decoder-only multimodal inputs and `output_attentions` (including Whisper token +timestamps) are not supported with beams. Diverse beam search cannot be combined with `do_sample: true`. Nucleus sampling (`top_p`) is not implemented by the generation sampler. diff --git a/packages/transformers/src/cache_utils.js b/packages/transformers/src/cache_utils.js index f49dcbab3..b9a459f06 100644 --- a/packages/transformers/src/cache_utils.js +++ b/packages/transformers/src/cache_utils.js @@ -9,7 +9,8 @@ import { Tensor } from './utils/tensor.js'; /** - * A cache class that stores past key values as named tensors. + * A cache class that owns past key values as named tensors. + * Replacing or disposing entries invalidates their tensor objects on every device. */ class _DynamicCache { /** @@ -51,14 +52,14 @@ class _DynamicCache { } /** - * Update the cache in-place with new entries, disposing replaced GPU tensors. + * Update the cache in-place with new entries, disposing replaced tensors. * @param {Record} newEntries The new name → Tensor mappings. */ update(newEntries) { for (const key in newEntries) { const oldValue = this[key]; const newValue = newEntries[key]; - if (oldValue && oldValue !== newValue && oldValue.location === 'gpu-buffer') { + if (oldValue && oldValue !== newValue) { oldValue.dispose(); } this[key] = newValue; @@ -66,16 +67,14 @@ class _DynamicCache { } /** - * Dispose all contained tensors whose data resides on the GPU. + * Dispose all contained tensors, including downloaded tensors that retain GPU resources. * Returns a promise that resolves when all disposals are complete. * @returns {Promise} Promise that resolves when all GPU tensors are disposed. */ async dispose() { const promises = []; for (const t of /** @type {Tensor[]} */ (Object.values(this))) { - if (t.location === 'gpu-buffer') { - promises.push(t.dispose()); - } + promises.push(t.dispose()); } await Promise.all(promises); } diff --git a/packages/transformers/src/generation/beam_search.js b/packages/transformers/src/generation/beam_search.js index 4e6ffa907..fa5c5efa3 100644 --- a/packages/transformers/src/generation/beam_search.js +++ b/packages/transformers/src/generation/beam_search.js @@ -144,7 +144,7 @@ export class BeamSearchScorer { const cur_len = all_input_ids[0].length; const total_beams = this.batch_size * this.num_beams; - const next_beam_scores = new Array(total_beams).fill(0); + const next_beam_scores = new Array(total_beams).fill(-Infinity); const next_beam_tokens = new Array(total_beams).fill(0n); const next_beam_indices = new Array(total_beams).fill(0); @@ -188,6 +188,21 @@ export class BeamSearchScorer { if (beam_idx === this.num_beams) break; } + if (beam_idx === 0) { + if (this._beam_hyps[batch_idx].length < this.num_return_sequences) { + throw new Error( + 'Beam search has too few valid hypotheses. Check logits processors and EOS tokens.', + ); + } + this._done[batch_idx] = true; + for (let i = 0; i < this.num_beams; ++i) { + const out_idx = batch_idx * this.num_beams + i; + next_beam_tokens[out_idx] = BigInt(this.pad_token_id); + next_beam_indices[out_idx] = batch_idx * this.num_beams; + } + continue; + } + // If we couldn't fill all beams (too many EOS), pad with last valid if (beam_idx < this.num_beams) { const last_valid = batch_idx * this.num_beams + Math.max(0, beam_idx - 1); diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js index 07fa67276..2632dfef7 100644 --- a/packages/transformers/src/models/modeling_utils.js +++ b/packages/transformers/src/models/modeling_utils.js @@ -876,6 +876,22 @@ export class PreTrainedModel extends Callable { }); const is_encoder_decoder = this.config.is_encoder_decoder; + if (generation_config.num_beams > 1) { + if (generation_config.output_attentions) { + throw new Error('Beam search does not support output_attentions or token timestamps.'); + } + const modality_inputs = [ + 'pixel_values', + 'pixel_values_videos', + 'audio_values', + 'input_features', + 'image_grid_thw', + 'video_grid_thw', + ]; + if (!is_encoder_decoder && modality_inputs.some((key) => model_inputs[key] != null)) { + throw new Error('Beam search does not yet support decoder-only multimodal inputs.'); + } + } // 4. Define other model kwargs if (!is_encoder_decoder) { @@ -1019,487 +1035,514 @@ export class PreTrainedModel extends Callable { /** @type {bigint[][]} */ const all_input_ids = input_ids.tolist(); - if (is_beam_search) { - // Expand all_input_ids: [A, B] -> [A, A, A, B, B, B] for num_beams=3 - const expanded_ids = []; - for (const ids of all_input_ids) { - for (let b = 0; b < num_beams; ++b) { - expanded_ids.push([...ids]); + // Only copies created by this call are owned here; caller inputs survive. + const expanded_tensors = new Set(); + const caller_cache = model_inputs.past_key_values; + let outputs; + try { + if (is_beam_search) { + // Expand all_input_ids: [A, B] -> [A, A, A, B, B, B] for num_beams=3 + const expanded_ids = []; + for (const ids of all_input_ids) { + for (let b = 0; b < num_beams; ++b) { + expanded_ids.push([...ids]); + } } - } - all_input_ids.length = 0; - all_input_ids.push(...expanded_ids); - - // Expand model_inputs tensors by repeating each row num_beams times - const expanded_indices = []; - for (let i = 0; i < numInputs; ++i) { - for (let b = 0; b < num_beams; ++b) { - expanded_indices.push(i); + all_input_ids.length = 0; + all_input_ids.push(...expanded_ids); + + // Expand model_inputs tensors by repeating each row num_beams times + const expanded_indices = []; + for (let i = 0; i < numInputs; ++i) { + for (let b = 0; b < num_beams; ++b) { + expanded_indices.push(i); + } } - } - for (const key of [ - model_input_name, - 'attention_mask', - 'decoder_attention_mask', - 'encoder_outputs', - 'position_ids', - 'inputs_embeds', - ]) { - const tensor = model_inputs[key]; - if (tensor instanceof Tensor) { - if (tensor.location === 'cpu' || tensor.location === 'cpu-pinned') { - model_inputs[key] = index_select(tensor, expanded_indices); - } else { - model_inputs[key] = await index_select_async(tensor, expanded_indices); + for (const key of [ + model_input_name, + 'attention_mask', + 'decoder_attention_mask', + 'encoder_outputs', + 'position_ids', + 'inputs_embeds', + ]) { + const tensor = model_inputs[key]; + if (tensor instanceof Tensor) { + if (tensor.location === 'cpu' || tensor.location === 'cpu-pinned') { + model_inputs[key] = index_select(tensor, expanded_indices); + } else { + model_inputs[key] = await index_select_async(tensor, expanded_indices); + } + expanded_tensors.add(model_inputs[key]); } } - } - if (model_inputs.past_key_values) { - /** @type {Record} */ - const expanded_cache = {}; - for (const [key, tensor] of Object.entries(model_inputs.past_key_values)) { - expanded_cache[key] = await index_select_async( - tensor, - this._get_cache_indices(key, expanded_indices), - ); + if (model_inputs.past_key_values) { + /** @type {Record} */ + const expanded_cache = {}; + for (const [key, tensor] of Object.entries(model_inputs.past_key_values)) { + expanded_cache[key] = await index_select_async( + tensor, + this._get_cache_indices(key, expanded_indices), + ); + expanded_tensors.add(expanded_cache[key]); + } + model_inputs.past_key_values = new DynamicCache(expanded_cache); } - model_inputs.past_key_values = new DynamicCache(expanded_cache); - } - // Initialize beam_scores: first beam of each input = 0, rest = -1e9 - beam_scores = new Array(numInputs * num_beams).fill(-1e9); - for (let i = 0; i < numInputs; ++i) { - const group_size = num_beams / num_beam_groups; - for (let g = 0; g < num_beam_groups; ++g) { - beam_scores[i * num_beams + g * group_size] = 0; + // Initialize beam_scores: first beam of each input = 0, rest = -1e9 + beam_scores = new Array(numInputs * num_beams).fill(-1e9); + for (let i = 0; i < numInputs; ++i) { + const group_size = num_beams / num_beam_groups; + for (let g = 0; g < num_beam_groups; ++g) { + beam_scores[i * num_beams + g * group_size] = 0; + } } } - } - if (streamer) { - streamer.put(all_input_ids); - } - - //////////////////////////////////////////////////// - // Generic search which handles 4 generation modes: - // - GenerationMode.GREEDY_SEARCH - // - GenerationMode.SAMPLE - // - GenerationMode.BEAM_SEARCH - // - GenerationMode.BEAM_SAMPLE - //////////////////////////////////////////////////// - let outputs; - let attentions = {}; - let return_dict_items = {}; - while (true) { - // prepare model inputs - model_inputs = this.prepare_inputs_for_generation(all_input_ids, model_inputs, generation_config); - outputs = await this.forward(model_inputs); + if (streamer) { + streamer.put(all_input_ids); + } - if (generation_config.return_dict_in_generate) { - if (generation_config.output_attentions) { - // Get attentions if they are present - const token_attentions = getAttentions(outputs); - for (const key in token_attentions) { - if (!(key in attentions)) { - attentions[key] = []; + //////////////////////////////////////////////////// + // Generic search which handles 4 generation modes: + // - GenerationMode.GREEDY_SEARCH + // - GenerationMode.SAMPLE + // - GenerationMode.BEAM_SEARCH + // - GenerationMode.BEAM_SAMPLE + //////////////////////////////////////////////////// + let attentions = {}; + let return_dict_items = {}; + while (true) { + // prepare model inputs + model_inputs = this.prepare_inputs_for_generation(all_input_ids, model_inputs, generation_config); + outputs = await this.forward(model_inputs); + + if (generation_config.return_dict_in_generate) { + if (generation_config.output_attentions) { + // Get attentions if they are present + const token_attentions = getAttentions(outputs); + for (const key in token_attentions) { + if (!(key in attentions)) { + attentions[key] = []; + } + attentions[key].push(token_attentions[key]); } - attentions[key].push(token_attentions[key]); + } else if (this._return_dict_in_generate_keys) { + Object.assign(return_dict_items, pick(outputs, this._return_dict_in_generate_keys)); } - } else if (this._return_dict_in_generate_keys) { - Object.assign(return_dict_items, pick(outputs, this._return_dict_in_generate_keys)); } - } - // Logits are of the form [batch_size, out_seq_length, vocab_size] - // In most cases, this will be [batch_size, 1, vocab_size] - // So, we select the last token's logits: - // (equivalent to `logits = outputs.logits[:, -1, :]`) - // The `.to('float32')` is necessary for models with float16 logits, - // and is a no-op for float32 logits. - // TODO: Support float16 sampling in the sampler directly - const logits = outputs.logits.slice(null, -1, null).to('float32'); - - // Beam processors operate on log probabilities. Renormalizing after - // suppression would change the relative scores of different beams. - if (is_beam_search) { - const vocab_size = logits.dims.at(-1); - for (let i = 0; i < logits.dims[0]; ++i) { - const offset = i * vocab_size; - const data = /** @type {Float32Array} */ (logits.data); - data.set(log_softmax(data.subarray(offset, offset + vocab_size)), offset); + // Logits are of the form [batch_size, out_seq_length, vocab_size] + // In most cases, this will be [batch_size, 1, vocab_size] + // So, we select the last token's logits: + // (equivalent to `logits = outputs.logits[:, -1, :]`) + // The `.to('float32')` is necessary for models with float16 logits, + // and is a no-op for float32 logits. + // TODO: Support float16 sampling in the sampler directly + const logits = outputs.logits.slice(null, -1, null).to('float32'); + + // Beam processors operate on log probabilities. Renormalizing after + // suppression would change the relative scores of different beams. + if (is_beam_search) { + const vocab_size = logits.dims.at(-1); + for (let i = 0; i < logits.dims[0]; ++i) { + const offset = i * vocab_size; + const data = /** @type {Float32Array} */ (logits.data); + data.set(log_softmax(data.subarray(offset, offset + vocab_size)), offset); + } } - } - const next_tokens_scores = prepared_logits_processor(all_input_ids, logits); - - /** @type {[bigint][]} */ - const generated_input_ids = []; - - if (is_beam_search) { - // Beam search: retain enough candidates for active beams and all EOS ids. - const vocab_size = next_tokens_scores.dims.at(-1); - const total_beams = numInputs * num_beams; - const eos_ids = generation_config.eos_token_id; - const num_eos = eos_ids === null ? 0 : Array.isArray(eos_ids) ? eos_ids.length : 1; - const candidates_per_beam = Math.max(2, 1 + num_eos); - - /** @type {number[]} */ - let next_beam_scores; - /** @type {bigint[]} */ - let next_beam_tokens; - /** @type {number[]} */ - let next_beam_indices; - - if (is_group_beam_search) { - const group_size = num_beams / num_beam_groups; - next_beam_scores = new Array(total_beams).fill(0); - next_beam_tokens = new Array(total_beams).fill(0n); - next_beam_indices = new Array(total_beams).fill(0); + const next_tokens_scores = prepared_logits_processor(all_input_ids, logits); + + /** @type {[bigint][]} */ + const generated_input_ids = []; + + if (is_beam_search) { + // Beam search: retain enough candidates for active beams and all EOS ids. + const vocab_size = next_tokens_scores.dims.at(-1); + const total_beams = numInputs * num_beams; + const eos_ids = generation_config.eos_token_id; + const num_eos = eos_ids === null ? 0 : Array.isArray(eos_ids) ? eos_ids.length : 1; + const candidates_per_beam = Math.max(2, 1 + num_eos); + + /** @type {number[]} */ + let next_beam_scores; + /** @type {bigint[]} */ + let next_beam_tokens; + /** @type {number[]} */ + let next_beam_indices; + + if (is_group_beam_search) { + const group_size = num_beams / num_beam_groups; + next_beam_scores = new Array(total_beams).fill(0); + next_beam_tokens = new Array(total_beams).fill(0n); + next_beam_indices = new Array(total_beams).fill(0); + + const diversity_penalty = generation_config.diversity_penalty ?? 0; + /** @type {Map[]} */ + const prev_group_tokens = Array.from({ length: numInputs }, () => new Map()); + + for (let group_idx = 0; group_idx < num_beam_groups; ++group_idx) { + const group_offset = group_idx * group_size; + + const group_all_input_ids = new Array(numInputs * group_size); + const group_beam_scores = new Array(numInputs * group_size); + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { + const global = batch_idx * num_beams + group_offset + beam_idx; + const local = batch_idx * group_size + beam_idx; + group_all_input_ids[local] = all_input_ids[global]; + group_beam_scores[local] = beam_scores[global]; + } + } - const diversity_penalty = generation_config.diversity_penalty ?? 0; - /** @type {Map[]} */ - const prev_group_tokens = Array.from({ length: numInputs }, () => new Map()); + const group_next_tokens = []; + const group_next_indices = []; + const group_next_scores = []; + + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + // Collect candidates across all beams for this batch item + /** @type {{score: number, token: bigint, beam_idx: number}[]} */ + const candidates = []; + + for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { + const flat_beam = batch_idx * num_beams + group_offset + beam_idx; + const logits_data = /** @type {Float32Array} */ ( + next_tokens_scores[flat_beam].data + ); + const log_probs = logits_data; + const beam_score = beam_scores[flat_beam]; + + candidates.push( + ...selectBeamCandidates( + log_probs, + beam_score, + beam_idx, + candidates_per_beam * group_size, + prev_group_tokens[batch_idx], + diversity_penalty, + ), + ); + } + + // Rank candidates across the group for this batch item. + candidates.sort((a, b) => b.score - a.score); + const top_candidates = candidates.slice(0, candidates_per_beam * group_size); + + for (const c of top_candidates) { + group_next_tokens.push(c.token); + group_next_indices.push(c.beam_idx); + group_next_scores.push(c.score); + } + } - for (let group_idx = 0; group_idx < num_beam_groups; ++group_idx) { - const group_offset = group_idx * group_size; + // Let beam_scorer process: route EOS to hypotheses, select continuing beams + const { + next_beam_scores: group_next_beam_scores, + next_beam_tokens: group_next_beam_tokens, + next_beam_indices: group_next_beam_indices, + } = beam_scorers[group_idx].process( + group_all_input_ids, + group_beam_scores, + group_next_tokens, + group_next_indices, + group_next_scores, + ); + + // Map group outputs into global beam arrays + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { + const global = batch_idx * num_beams + group_offset + beam_idx; + const local = batch_idx * group_size + beam_idx; + next_beam_scores[global] = group_next_beam_scores[local]; + next_beam_tokens[global] = group_next_beam_tokens[local]; + const local_source = group_next_beam_indices[local]; + const source_in_batch = local_source - batch_idx * group_size; + next_beam_indices[global] = batch_idx * num_beams + group_offset + source_in_batch; + } + } - const group_all_input_ids = new Array(numInputs * group_size); - const group_beam_scores = new Array(numInputs * group_size); - for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { - for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { - const global = batch_idx * num_beams + group_offset + beam_idx; - const local = batch_idx * group_size + beam_idx; - group_all_input_ids[local] = all_input_ids[global]; - group_beam_scores[local] = beam_scores[global]; + // Track tokens selected by this group for diversity penalty + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + const token_counts = prev_group_tokens[batch_idx]; + for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { + const global = batch_idx * num_beams + group_offset + beam_idx; + const token = next_beam_tokens[global]; + token_counts.set(token, (token_counts.get(token) ?? 0) + 1); + } } } - - const group_next_tokens = []; - const group_next_indices = []; - const group_next_scores = []; + } else { + const all_next_tokens = []; + const all_next_indices = []; + const all_next_scores = []; + const do_beam_sample = generation_config.do_sample; + const top_k = generation_config.top_k; for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { // Collect candidates across all beams for this batch item /** @type {{score: number, token: bigint, beam_idx: number}[]} */ const candidates = []; - for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { - const flat_beam = batch_idx * num_beams + group_offset + beam_idx; + for (let beam_idx = 0; beam_idx < num_beams; ++beam_idx) { + const flat_beam = batch_idx * num_beams + beam_idx; const logits_data = /** @type {Float32Array} */ (next_tokens_scores[flat_beam].data); - const log_probs = logits_data; - const beam_score = beam_scores[flat_beam]; - - candidates.push( - ...selectBeamCandidates( - log_probs, - beam_score, - beam_idx, - candidates_per_beam * group_size, - prev_group_tokens[batch_idx], - diversity_penalty, - ), - ); + const count = do_beam_sample + ? top_k > 0 + ? Math.max(top_k, candidates_per_beam * num_beams) + : vocab_size + : candidates_per_beam * num_beams; + for (const candidate of selectBeamCandidates( + logits_data, + beam_scores[flat_beam], + beam_idx, + count, + )) { + candidates.push(candidate); + } } - // Rank candidates across the group for this batch item. - candidates.sort((a, b) => b.score - a.score); - const top_candidates = candidates.slice(0, candidates_per_beam * group_size); + const count = Math.min(candidates_per_beam * num_beams, candidates.length); + let top_candidates; + if (do_beam_sample) { + // Sample across the joint beam/token distribution without + // replacement, retaining the original cumulative scores. + top_candidates = []; + for (let i = 0; i < count; ++i) { + const max_score = candidates.reduce( + (best, candidate) => Math.max(best, candidate.score), + -Infinity, + ); + const probabilities = Float32Array.from(candidates, (candidate) => + Math.exp(candidate.score - max_score), + ); + const index = sampler.randomSelect(probabilities); + top_candidates.push(candidates.splice(index, 1)[0]); + } + top_candidates.sort((a, b) => b.score - a.score); + } else { + candidates.sort((a, b) => b.score - a.score); + top_candidates = candidates.slice(0, count); + } for (const c of top_candidates) { - group_next_tokens.push(c.token); - group_next_indices.push(c.beam_idx); - group_next_scores.push(c.score); + all_next_tokens.push(c.token); + all_next_indices.push(c.beam_idx); + all_next_scores.push(c.score); } } // Let beam_scorer process: route EOS to hypotheses, select continuing beams - const { - next_beam_scores: group_next_beam_scores, - next_beam_tokens: group_next_beam_tokens, - next_beam_indices: group_next_beam_indices, - } = beam_scorers[group_idx].process( - group_all_input_ids, - group_beam_scores, - group_next_tokens, - group_next_indices, - group_next_scores, - ); - - // Map group outputs into global beam arrays - for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { - for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { - const global = batch_idx * num_beams + group_offset + beam_idx; - const local = batch_idx * group_size + beam_idx; - next_beam_scores[global] = group_next_beam_scores[local]; - next_beam_tokens[global] = group_next_beam_tokens[local]; - const local_source = group_next_beam_indices[local]; - const source_in_batch = local_source - batch_idx * group_size; - next_beam_indices[global] = batch_idx * num_beams + group_offset + source_in_batch; - } - } - - // Track tokens selected by this group for diversity penalty - for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { - const token_counts = prev_group_tokens[batch_idx]; - for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { - const global = batch_idx * num_beams + group_offset + beam_idx; - const token = next_beam_tokens[global]; - token_counts.set(token, (token_counts.get(token) ?? 0) + 1); - } - } + ({ next_beam_scores, next_beam_tokens, next_beam_indices } = beam_scorer.process( + all_input_ids, + beam_scores, + all_next_tokens, + all_next_indices, + all_next_scores, + )); } - } else { - const all_next_tokens = []; - const all_next_indices = []; - const all_next_scores = []; - const do_beam_sample = generation_config.do_sample; - const top_k = generation_config.top_k; - for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { - // Collect candidates across all beams for this batch item - /** @type {{score: number, token: bigint, beam_idx: number}[]} */ - const candidates = []; - - for (let beam_idx = 0; beam_idx < num_beams; ++beam_idx) { - const flat_beam = batch_idx * num_beams + beam_idx; - const logits_data = /** @type {Float32Array} */ (next_tokens_scores[flat_beam].data); - const count = do_beam_sample - ? top_k > 0 - ? Math.max(top_k, candidates_per_beam * num_beams) - : vocab_size - : candidates_per_beam * num_beams; - for (const candidate of selectBeamCandidates( - logits_data, - beam_scores[flat_beam], - beam_idx, - count, - )) { - candidates.push(candidate); - } - } + // Reorder all_input_ids based on beam indices and append new tokens + const new_all_input_ids = []; + for (let i = 0; i < total_beams; ++i) { + new_all_input_ids.push([...all_input_ids[next_beam_indices[i]], next_beam_tokens[i]]); + generated_input_ids.push([next_beam_tokens[i]]); + } + all_input_ids.length = 0; + all_input_ids.push(...new_all_input_ids); - const count = Math.min(candidates_per_beam * num_beams, candidates.length); - let top_candidates; - if (do_beam_sample) { - // Sample across the joint beam/token distribution without - // replacement, retaining the original cumulative scores. - top_candidates = []; - for (let i = 0; i < count; ++i) { - const max_score = candidates.reduce( - (best, candidate) => Math.max(best, candidate.score), - -Infinity, - ); - const probabilities = Float32Array.from(candidates, (candidate) => - Math.exp(candidate.score - max_score), - ); - const index = sampler.randomSelect(probabilities); - top_candidates.push(candidates.splice(index, 1)[0]); - } - top_candidates.sort((a, b) => b.score - a.score); - } else { - candidates.sort((a, b) => b.score - a.score); - top_candidates = candidates.slice(0, count); - } + // Update beam scores + for (let i = 0; i < total_beams; ++i) { + beam_scores[i] = next_beam_scores[i]; + } - for (const c of top_candidates) { - all_next_tokens.push(c.token); - all_next_indices.push(c.beam_idx); - all_next_scores.push(c.score); + // Reorder KV cache to match beam reordering + model_inputs['past_key_values'] = await this._reorder_cache( + getPastKeyValues(outputs, model_inputs.past_key_values), + next_beam_indices, + ); + } else { + // Greedy / sample: existing behavior + for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) { + const logs = next_tokens_scores[batch_idx]; + + const sampledTokens = await sampler(logs); + for (const [newTokenId, logProb] of sampledTokens) { + const bigint = BigInt(newTokenId); + scores[batch_idx] += logProb; + all_input_ids[batch_idx].push(bigint); + generated_input_ids.push([bigint]); + break; } } - - // Let beam_scorer process: route EOS to hypotheses, select continuing beams - ({ next_beam_scores, next_beam_tokens, next_beam_indices } = beam_scorer.process( - all_input_ids, - beam_scores, - all_next_tokens, - all_next_indices, - all_next_scores, - )); - } - - // Reorder all_input_ids based on beam indices and append new tokens - const new_all_input_ids = []; - for (let i = 0; i < total_beams; ++i) { - new_all_input_ids.push([...all_input_ids[next_beam_indices[i]], next_beam_tokens[i]]); - generated_input_ids.push([next_beam_tokens[i]]); } - all_input_ids.length = 0; - all_input_ids.push(...new_all_input_ids); - // Update beam scores - for (let i = 0; i < total_beams; ++i) { - beam_scores[i] = next_beam_scores[i]; + if (streamer) { + streamer.put(generated_input_ids); } - // Reorder KV cache to match beam reordering - model_inputs['past_key_values'] = await this._reorder_cache( - getPastKeyValues(outputs, model_inputs.past_key_values), - next_beam_indices, - ); - } else { - // Greedy / sample: existing behavior - for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) { - const logs = next_tokens_scores[batch_idx]; - - const sampledTokens = await sampler(logs); - for (const [newTokenId, logProb] of sampledTokens) { - const bigint = BigInt(newTokenId); - scores[batch_idx] += logProb; - all_input_ids[batch_idx].push(bigint); - generated_input_ids.push([bigint]); + // Check stopping conditions + if (is_beam_search) { + const done = is_group_beam_search + ? beam_scorers.every((scorer) => scorer.is_done) + : beam_scorer.is_done; + if (done) { break; } } - } - - if (streamer) { - streamer.put(generated_input_ids); - } - - // Check stopping conditions - if (is_beam_search) { - const done = is_group_beam_search - ? beam_scorers.every((scorer) => scorer.is_done) - : beam_scorer.is_done; - if (done) { + const stop = prepared_stopping_criteria(all_input_ids); + if (stop.every((x) => x)) { break; } - } - const stop = prepared_stopping_criteria(all_input_ids); - if (stop.every((x) => x)) { - break; - } - if (is_beam_search) { - // For beam search, we already updated past_key_values during reordering. - // Now update the remaining model inputs. - model_inputs['input_ids'] = new Tensor('int64', generated_input_ids.flat(), [ - generated_input_ids.length, - 1, - ]); - - if (!is_encoder_decoder) { - model_inputs.attention_mask = cat( - [model_inputs.attention_mask, ones([model_inputs.attention_mask.dims[0], 1])], - 1, - ); - } else if ('decoder_attention_mask' in model_inputs) { - model_inputs.decoder_attention_mask = cat( - [model_inputs.decoder_attention_mask, ones([model_inputs.decoder_attention_mask.dims[0], 1])], + if (is_beam_search) { + // For beam search, we already updated past_key_values during reordering. + // Now update the remaining model inputs. + model_inputs['input_ids'] = new Tensor('int64', generated_input_ids.flat(), [ + generated_input_ids.length, 1, - ); + ]); + + if (!is_encoder_decoder) { + model_inputs.attention_mask = cat( + [model_inputs.attention_mask, ones([model_inputs.attention_mask.dims[0], 1])], + 1, + ); + } else if ('decoder_attention_mask' in model_inputs) { + model_inputs.decoder_attention_mask = cat( + [ + model_inputs.decoder_attention_mask, + ones([model_inputs.decoder_attention_mask.dims[0], 1]), + ], + 1, + ); + } + + // Force recreate position_ids in next iteration + model_inputs['position_ids'] = null; + } else { + model_inputs = this._update_model_kwargs_for_generation({ + generated_input_ids, + outputs, + model_inputs, + is_encoder_decoder, + }); } + } - // Force recreate position_ids in next iteration - model_inputs['position_ids'] = null; - } else { - model_inputs = this._update_model_kwargs_for_generation({ - generated_input_ids, - outputs, - model_inputs, - is_encoder_decoder, - }); + if (streamer) { + streamer.end(); } - } - if (streamer) { - streamer.end(); - } + let sequences; + if (is_beam_search) { + /** @type {bigint[][]} */ + let best_sequences; + if (is_group_beam_search) { + const group_size = num_beams / num_beam_groups; + /** @type {{tokens: bigint[], score: number}[][]} */ + const grouped = Array.from({ length: numInputs }, () => []); - let sequences; - if (is_beam_search) { - /** @type {bigint[][]} */ - let best_sequences; - if (is_group_beam_search) { - const group_size = num_beams / num_beam_groups; - /** @type {{tokens: bigint[], score: number}[][]} */ - const grouped = Array.from({ length: numInputs }, () => []); + for (let group_idx = 0; group_idx < num_beam_groups; ++group_idx) { + const group_offset = group_idx * group_size; + const group_all_input_ids = new Array(numInputs * group_size); + const group_beam_scores = new Array(numInputs * group_size); - for (let group_idx = 0; group_idx < num_beam_groups; ++group_idx) { - const group_offset = group_idx * group_size; - const group_all_input_ids = new Array(numInputs * group_size); - const group_beam_scores = new Array(numInputs * group_size); + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { + const global = batch_idx * num_beams + group_offset + beam_idx; + const local = batch_idx * group_size + beam_idx; + group_all_input_ids[local] = all_input_ids[global]; + group_beam_scores[local] = beam_scores[global]; + } + } - for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { - for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) { - const global = batch_idx * num_beams + group_offset + beam_idx; - const local = batch_idx * group_size + beam_idx; - group_all_input_ids[local] = all_input_ids[global]; - group_beam_scores[local] = beam_scores[global]; + const group_results = beam_scorers[group_idx].finalize_with_scores( + group_all_input_ids, + group_beam_scores, + ); + + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + const offset = batch_idx * group_size; + for (let i = 0; i < group_size; ++i) { + grouped[batch_idx].push(group_results[offset + i]); + } } } - const group_results = beam_scorers[group_idx].finalize_with_scores( - group_all_input_ids, - group_beam_scores, - ); - + best_sequences = []; for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { - const offset = batch_idx * group_size; - for (let i = 0; i < group_size; ++i) { - grouped[batch_idx].push(group_results[offset + i]); + const sorted = grouped[batch_idx].sort((a, b) => b.score - a.score); + for (let i = 0; i < generation_config.num_return_sequences; ++i) { + best_sequences.push(sorted[i].tokens); } } + } else { + // Finalize beam search: select best hypotheses + best_sequences = beam_scorer.finalize(all_input_ids, beam_scores); } - best_sequences = []; - for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { - const sorted = grouped[batch_idx].sort((a, b) => b.score - a.score); - for (let i = 0; i < generation_config.num_return_sequences; ++i) { - best_sequences.push(sorted[i].tokens); - } - } + // Pad sequences to equal length for tensor creation + const max_len = Math.max(...best_sequences.map((s) => s.length)); + const pad_id = BigInt(generation_config.pad_token_id ?? 0); + const padded = best_sequences.map((s) => { + const p = [...s]; + while (p.length < max_len) p.push(pad_id); + return p; + }); + sequences = new Tensor('int64', padded.flat(), [padded.length, max_len]); } else { - // Finalize beam search: select best hypotheses - best_sequences = beam_scorer.finalize(all_input_ids, beam_scores); + // TODO: ensure all_input_ids is padded correctly... + sequences = new Tensor('int64', all_input_ids.flat(), [all_input_ids.length, all_input_ids[0].length]); } - // Pad sequences to equal length for tensor creation - const max_len = Math.max(...best_sequences.map((s) => s.length)); - const pad_id = BigInt(generation_config.pad_token_id ?? 0); - const padded = best_sequences.map((s) => { - const p = [...s]; - while (p.length < max_len) p.push(pad_id); - return p; - }); - sequences = new Tensor('int64', padded.flat(), [padded.length, max_len]); - } else { - // TODO: ensure all_input_ids is padded correctly... - sequences = new Tensor('int64', all_input_ids.flat(), [all_input_ids.length, all_input_ids[0].length]); - } + // Beam search already extracted and reordered the final cache. Do not restore + // the original output tensors, which may have been disposed during reordering. + const past_key_values = is_beam_search + ? model_inputs.past_key_values + : getPastKeyValues(outputs, model_inputs.past_key_values); - // Beam search already extracted and reordered the final cache. Do not restore - // the original output tensors, which may have been disposed during reordering. - const past_key_values = is_beam_search - ? model_inputs.past_key_values - : getPastKeyValues(outputs, model_inputs.past_key_values); - - // Dispose output tensors not held by the cache - const cachedTensors = new Set(Object.values(past_key_values)); - for (const tensor of Object.values(outputs)) { - if (tensor.location === 'gpu-buffer' && !cachedTensors.has(tensor)) { - tensor.dispose(); + // Dispose output tensors not held by the cache + const cachedTensors = new Set(Object.values(past_key_values)); + for (const tensor of Object.values(outputs)) { + if (tensor.location === 'gpu-buffer' && !cachedTensors.has(tensor)) { + tensor.dispose(); + } } - } - // Dispose cache tensors if no one needs them - const keepCacheAlive = - !is_beam_search && ('past_key_values' in kwargs || generation_config.return_dict_in_generate); - if (!keepCacheAlive) { - await past_key_values.dispose(); - } + // Dispose cache tensors if no one needs them + const keepCacheAlive = + !is_beam_search && ('past_key_values' in kwargs || generation_config.return_dict_in_generate); + if (!keepCacheAlive) { + await past_key_values.dispose(); + } - if (generation_config.return_dict_in_generate) { - const past_key_values_for_return = is_beam_search ? null : past_key_values; - return { - sequences, - past_key_values: past_key_values_for_return, - ...attentions, - ...return_dict_items, - }; + if (generation_config.return_dict_in_generate) { + const past_key_values_for_return = is_beam_search ? null : past_key_values; + return { + sequences, + past_key_values: past_key_values_for_return, + ...attentions, + ...return_dict_items, + }; + } + return sequences; + } finally { + if (is_beam_search) { + // Also run on forward/processor/reorder failures and partial expansion. + const owned = new Set(expanded_tensors); + if (model_inputs.past_key_values !== caller_cache) { + for (const tensor of Object.values(model_inputs.past_key_values ?? {})) owned.add(tensor); + } + for (const tensor of Object.values(outputs ?? {})) owned.add(tensor); + for (const tensor of owned) { + if (expanded_tensors.has(tensor) || tensor.location === 'gpu-buffer') tensor.dispose(); + } + if (model_inputs.past_key_values !== caller_cache) { + await model_inputs.past_key_values?.dispose(); + } + } } - return sequences; } /** @@ -1542,23 +1585,27 @@ export class PreTrainedModel extends Callable { async _reorder_cache(past_key_values, beam_indices) { if (!past_key_values) return past_key_values; const reordered = Object.create(null); - for (const key in past_key_values) { - const tensor = past_key_values[key]; - const location = tensor.location; - if (key.includes('encoder')) { - // Encoder PKVs are shared across beams; pass through - reordered[key] = tensor; - } else { - if (tensor.location === 'cpu' || tensor.location === 'cpu-pinned') { - reordered[key] = index_select(tensor, this._get_cache_indices(key, beam_indices)); + const replaced = new Set(); + try { + for (const key in past_key_values) { + const tensor = past_key_values[key]; + if (key.includes('encoder')) { + // Encoder PKVs are shared across beams; pass through. + reordered[key] = tensor; } else { reordered[key] = await index_select_async(tensor, this._get_cache_indices(key, beam_indices)); - } - // Dispose old tensor if it owns GPU resources - if (location === 'gpu-buffer' || location === 'texture' || location === 'ml-tensor') { - tensor.dispose(); + replaced.add(tensor); } } + } catch (error) { + // A failed reorder must not strand copies or consume its source cache. + for (const [key, tensor] of Object.entries(reordered)) { + if (tensor !== past_key_values[key] && tensor.location === 'gpu-buffer') tensor.dispose(); + } + throw error; + } + for (const tensor of replaced) { + tensor.dispose(); } return new DynamicCache(reordered); } diff --git a/packages/transformers/tests/utils/beam_ownership.test.js b/packages/transformers/tests/utils/beam_ownership.test.js new file mode 100644 index 000000000..789d83025 --- /dev/null +++ b/packages/transformers/tests/utils/beam_ownership.test.js @@ -0,0 +1,176 @@ +import { env } from "../../src/env.js"; +import { Tensor, index_select_async } from "../../src/utils/tensor.js"; +import { getTensorConstructor } from "../../src/backends/onnx.js"; +import { PreTrainedModel } from "../../src/models/modeling_utils.js"; +import { GenerationConfig } from "../../src/generation/configuration_utils.js"; +import { DynamicCache } from "../../src/cache_utils.js"; + +// Mock only the GPU allocation boundary; execute the real generation/cache code. +describe("Beam resource ownership", () => { + let allocated, originalDevice, originalUsage; + beforeEach(() => { + allocated = []; + originalDevice = env.backends.onnx.webgpu.device; + originalUsage = globalThis.GPUBufferUsage; + globalThis.GPUBufferUsage = { COPY_SRC: 1, COPY_DST: 2, STORAGE: 4, MAP_READ: 8 }; + env.backends.onnx.webgpu.device = { + limits: { maxBufferSize: 1e9 }, + createBuffer(options) { + const buffer = { + ...options, + destroyed: false, + destroy() { + this.destroyed = true; + }, + }; + allocated.push(buffer); + return buffer; + }, + createCommandEncoder() { + return { + copyBufferToBuffer() {}, + finish() { + return {}; + }, + }; + }, + queue: { submit() {} }, + }; + }); + afterEach(() => { + env.backends.onnx.webgpu.device = originalDevice; + if (originalUsage === undefined) delete globalThis.GPUBufferUsage; + else globalThis.GPUBufferUsage = originalUsage; + }); + + const gpu = (dims, options = {}, usage = 1) => new Tensor(getTensorConstructor().fromGpuBuffer({ usage }, { dataType: "float32", dims, ...options })); + const modelWith = (extra = {}) => + Object.assign(Object.create(PreTrainedModel.prototype), { + config: { is_encoder_decoder: false }, + _validate_model_class() {}, + _prepare_generation_config(config, kwargs) { + return new GenerationConfig(kwargs); + }, + _prepare_model_inputs() { + const ids = new Tensor("int64", [1n], [1, 1]); + return { inputs_tensor: ids, model_input_name: "input_ids", model_inputs: { input_ids: ids, attention_mask: new Tensor("int64", [1n], [1, 1]), ...extra } }; + }, + prepare_inputs_for_generation(ids, inputs) { + return inputs; + }, + async forward() { + return { logits: new Tensor("float32", [0, 1, 2, 3, 0, 1, 2, 3], [2, 1, 4]) }; + }, + }); + + it.each([false, true])("releases expanded inputs on forward failure=%s without consuming caller input", async (fail) => { + const positions = gpu([1, 1], { dataType: "int64" }); + const model = modelWith({ position_ids: positions }); + if (fail) + model.forward = async () => { + throw new Error("forward failed"); + }; + const result = model.generate({ num_beams: 2, max_new_tokens: 1, eos_token_id: null }); + if (fail) await expect(result).rejects.toThrow("forward failed"); + else expect((await result).tolist()).toEqual([[1n, 3n]]); + expect(allocated.length).toBe(1); + expect(allocated.every((buffer) => buffer.destroyed)).toBe(true); + expect(positions.location).toBe("gpu-buffer"); + positions.dispose(); + }); + + it("rolls back partial cache copies without consuming source tensors", async () => { + const first = gpu([2, 4]); + const second = gpu( + [2, 4], + { + download: async () => { + throw new Error("readback failed"); + }, + }, + 0, + ); + const cache = new DynamicCache({ first, second }); + await expect(PreTrainedModel.prototype._reorder_cache.call({ _get_cache_indices: (_key, indices) => indices }, cache, [1, 0])).rejects.toThrow("readback failed"); + expect(allocated.length).toBe(1); + expect(allocated.every((buffer) => buffer.destroyed)).toBe(true); + expect(first.location).toBe("gpu-buffer"); + expect(second.location).toBe("gpu-buffer"); + await cache.dispose(); + }); + + it.each(["dispose", "update"])("releases downloaded GPU cache resources through %s", async (action) => { + let destroyed = false; + const odd = gpu([1, 3], { + dataType: "float16", + download: async () => new Uint16Array(3), + dispose: () => { + destroyed = true; + }, + }); + const cache = new DynamicCache({ odd }); + await index_select_async(odd, [0, 0]); + expect(odd.location).toBe("cpu"); + expect(destroyed).toBe(false); + if (action === "dispose") await cache.dispose(); + else cache.update({ odd: new Tensor("float16", new Uint16Array(3), [1, 3]) }); + expect(destroyed).toBe(true); + }); + + it("releases previously downloaded cache sources after successful reordering", async () => { + let destroyed = false; + const source = gpu([1, 4], { + download: async () => new Float32Array([1, 2, 3, 4]), + dispose: () => { + destroyed = true; + }, + }); + await source.ort_tensor.getData(false); + const reordered = await PreTrainedModel.prototype._reorder_cache.call({ _get_cache_indices: (_key, indices) => indices }, new DynamicCache({ source }), [0, 0]); + expect(Array.from(reordered.source.data)).toEqual([1, 2, 3, 4, 1, 2, 3, 4]); + expect(destroyed).toBe(true); + await reordered.dispose(); + }); + + it("releases the active cache when a later forward fails and preserves a supplied cache", async () => { + const source = gpu([1, 1, 1, 4]); + const caller = new DynamicCache({ "past_key_values.0.key": source }); + const model = modelWith({ past_key_values: caller }); + let calls = 0; + let outputDestroyed = false; + model.forward = async () => { + if (++calls === 2) throw new Error("second forward failed"); + return { + logits: new Tensor("float32", [0, 1, 2, 3, 0, 1, 2, 3], [2, 1, 4]), + "present.0.key": gpu([2, 1, 1, 4], { + dispose: () => { + outputDestroyed = true; + }, + }), + }; + }; + await expect(model.generate({ num_beams: 2, max_new_tokens: 3, eos_token_id: null })).rejects.toThrow("second forward failed"); + expect(calls).toBe(2); + expect(allocated.length).toBe(2); + expect(allocated.every((buffer) => buffer.destroyed)).toBe(true); + expect(outputDestroyed).toBe(true); + expect(source.location).toBe("gpu-buffer"); + await caller.dispose(); + }); + + it("rejects decoder-only multimodal beams before inference", async () => { + const model = modelWith({ pixel_values: new Tensor("float32", [1], [1, 1]) }); + model.forward = async () => { + throw new Error("must not run"); + }; + await expect(model.generate({ num_beams: 2, max_new_tokens: 1 })).rejects.toThrow("decoder-only multimodal inputs"); + }); + + it("rejects beam attentions used for token timestamps before inference", async () => { + const model = modelWith(); + model.forward = async () => { + throw new Error("must not run"); + }; + await expect(model.generate({ num_beams: 2, output_attentions: true, max_new_tokens: 1 })).rejects.toThrow("output_attentions or token timestamps"); + }); +}); diff --git a/packages/transformers/tests/utils/beam_search.test.js b/packages/transformers/tests/utils/beam_search.test.js index 320c8b80a..cfb9ca28d 100644 --- a/packages/transformers/tests/utils/beam_search.test.js +++ b/packages/transformers/tests/utils/beam_search.test.js @@ -74,3 +74,21 @@ describe("Beam hypothesis scoring", () => { expect(hypotheses.is_done(-1, 3)).toBe(false); }); }); + +describe("Exhausted beam candidates", () => { + it("returns a real EOS hypothesis when no continuation exists", () => { + const scorer = new BeamSearchScorer(1, 2, { eos_token_id: [1, 2], decoder_prompt_len: 1, max_length: 2 }); + const next = scorer.process([[9n], [9n]], [0, -1e9], [1n, 2n, 1n, 2n], [0, 0, 1, 1], [-0.3, -1.3, -1e9, -1e9]); + expect(scorer.is_done).toBe(true); + expect(next.next_beam_scores).toEqual([-Infinity, -Infinity]); + expect( + scorer.finalize( + [ + [9n, 0n], + [9n, 0n], + ], + next.next_beam_scores, + ), + ).toEqual([[9n, 1n]]); + }); +}); From 1faccc63c7b563dfecd12d29d0e125bc9785f23d Mon Sep 17 00:00:00 2001 From: Dan Levy Date: Tue, 20 Oct 2026 15:35:18 -0600 Subject: [PATCH 15/21] Preserve beam ancestry for Whisper token timestamps --- .../src/generation/beam_search.js | 22 +- .../transformers/src/generation/parameters.js | 2 +- .../transformers/src/models/modeling_utils.js | 82 +++- .../src/models/whisper/generation_whisper.js | 4 +- .../src/models/whisper/modeling_whisper.js | 453 ++++++++++-------- .../tests/utils/beam_ownership.test.js | 37 +- .../utils/whisper_beam_timestamps.test.js | 144 ++++++ scripts/beam-timestamps/.gitignore | 4 + scripts/beam-timestamps/README.md | 52 ++ scripts/beam-timestamps/browser.html | 14 + scripts/beam-timestamps/harness.mjs | 124 +++++ scripts/beam-timestamps/native.mjs | 18 + scripts/beam-timestamps/offline-tests.js | 5 + scripts/beam-timestamps/verify-results.mjs | 52 ++ 14 files changed, 795 insertions(+), 218 deletions(-) create mode 100644 packages/transformers/tests/utils/whisper_beam_timestamps.test.js create mode 100644 scripts/beam-timestamps/.gitignore create mode 100644 scripts/beam-timestamps/README.md create mode 100644 scripts/beam-timestamps/browser.html create mode 100644 scripts/beam-timestamps/harness.mjs create mode 100644 scripts/beam-timestamps/native.mjs create mode 100644 scripts/beam-timestamps/offline-tests.js create mode 100644 scripts/beam-timestamps/verify-results.mjs diff --git a/packages/transformers/src/generation/beam_search.js b/packages/transformers/src/generation/beam_search.js index fa5c5efa3..524617612 100644 --- a/packages/transformers/src/generation/beam_search.js +++ b/packages/transformers/src/generation/beam_search.js @@ -18,7 +18,7 @@ export class BeamHypotheses { this.early_stopping = early_stopping; this.max_length = max_length; - /** @type {{score: number, tokens: bigint[]}[]} */ + /** @type {{score: number, tokens: bigint[], beam_indices: number[]}[]} */ this.beams = []; this.worst_score = 1e9; } @@ -32,11 +32,12 @@ export class BeamHypotheses { * @param {number} sum_logprobs Sum of log probabilities of the hypothesis. * @param {bigint[]} tokens The token ids of the hypothesis. * @param {number} [generated_length] Number of generated tokens, excluding the prompt. + * @param {number[]} [beam_indices] Global parent row for each generated token. */ - add(sum_logprobs, tokens, generated_length = tokens.length) { + add(sum_logprobs, tokens, generated_length = tokens.length, beam_indices = []) { const score = sum_logprobs / Math.max(1, generated_length) ** this.length_penalty; if (this.beams.length < this.num_beams || score > this.worst_score) { - this.beams.push({ score, tokens }); + this.beams.push({ score, tokens: [...tokens], beam_indices: [...beam_indices] }); if (this.beams.length > this.num_beams) { // Remove worst hypothesis let worst_idx = 0; @@ -138,9 +139,11 @@ export class BeamSearchScorer { * @param {bigint[]} next_tokens Candidate tokens, shape [batch_size * num_candidates]. * @param {number[]} next_indices Which beam each candidate came from (relative to batch group), shape [batch_size * num_candidates]. * @param {number[]} next_scores New cumulative scores for candidates, shape [batch_size * num_candidates]. + * @param {number[][]} [beam_indices] Active ancestry in scorer row order. + * @param {number[]} [row_indices] Mapping from scorer rows to global attention rows. * @returns {{ next_beam_scores: number[], next_beam_tokens: bigint[], next_beam_indices: number[] }} */ - process(all_input_ids, beam_scores, next_tokens, next_indices, next_scores) { + process(all_input_ids, beam_scores, next_tokens, next_indices, next_scores, beam_indices = [], row_indices = null) { const cur_len = all_input_ids[0].length; const total_beams = this.batch_size * this.num_beams; @@ -175,7 +178,10 @@ export class BeamSearchScorer { // Only EOS candidates that survive the beam cutoff can complete. if (j >= this.num_beams) continue; const hypothesis = [...all_input_ids[abs_beam_source], beam_token]; - this._beam_hyps[batch_idx].add(beam_score, hypothesis, cur_len + 1 - this.decoder_prompt_len); + this._beam_hyps[batch_idx].add(beam_score, hypothesis, cur_len + 1 - this.decoder_prompt_len, [ + ...(beam_indices[abs_beam_source] ?? []), + row_indices?.[abs_beam_source] ?? abs_beam_source, + ]); } else { // Add to next active beams const out_idx = batch_idx * this.num_beams + beam_idx; @@ -241,9 +247,10 @@ export class BeamSearchScorer { * Finalize: select best hypotheses and return scores. * @param {bigint[][]} all_input_ids Final sequences, shape [batch_size * num_beams, seq_len]. * @param {number[]} beam_scores Final cumulative scores. - * @returns {{tokens: bigint[], score: number}[]} Best sequences with scores. + * @param {number[][]} [beam_indices] Active ancestry in scorer row order. + * @returns {{tokens: bigint[], score: number, beam_indices: number[]}[]} Best sequences with scores. */ - finalize_with_scores(all_input_ids, beam_scores) { + finalize_with_scores(all_input_ids, beam_scores, beam_indices = []) { // For each batch, ensure we have enough hypotheses for (let batch_idx = 0; batch_idx < this.batch_size; ++batch_idx) { const hyps = this._beam_hyps[batch_idx]; @@ -254,6 +261,7 @@ export class BeamSearchScorer { beam_scores[flat_idx], all_input_ids[flat_idx], all_input_ids[flat_idx].length - this.decoder_prompt_len, + beam_indices[flat_idx] ?? [], ); } } diff --git a/packages/transformers/src/generation/parameters.js b/packages/transformers/src/generation/parameters.js index d6ce27c5a..5a5a210cb 100644 --- a/packages/transformers/src/generation/parameters.js +++ b/packages/transformers/src/generation/parameters.js @@ -27,7 +27,7 @@ * @property {import('./streamers.js').BaseStreamer} [streamer=null] (`BaseStreamer`, *optional*): * Streamer object used to stream the generated sequences. Generated tokens are passed * through `streamer.put(token_ids)` and the streamer is responsible for any further processing. - * @property {number[]|import('../utils/tensor.js').Tensor} [decoder_input_ids=null] (`number[]` or `Tensor`, *optional*): + * @property {number[]|number[][]|import('../utils/tensor.js').Tensor} [decoder_input_ids=null] (`number[]`, `number[][]` or `Tensor`, *optional*): * If the model is an encoder-decoder model, this argument is used to pass the `decoder_input_ids`. * @property {import('../cache_utils.js').DynamicCache | null} [past_key_values=null] (`DynamicCache`, *optional*): * A cache object that stores previously computed key/value states. When provided, the model will diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js index 2632dfef7..8b88cfb1c 100644 --- a/packages/transformers/src/models/modeling_utils.js +++ b/packages/transformers/src/models/modeling_utils.js @@ -851,6 +851,10 @@ export class PreTrainedModel extends Callable { /** * Generate token sequences with a language-modeling head. + * Returned attentions use step/layer/tensor layout with global forward rows. + * Beam dictionary outputs include `beam_indices` (global parent rows, one column per generated + * token starting at column zero, including EOS, padded with -1) and `sequence_lengths` + * (valid lengths including the decoder prefix and EOS). Attention tensors remain caller-owned. * @param {import('../generation/parameters.js').GenerationFunctionParameters} options * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores. */ @@ -877,9 +881,6 @@ export class PreTrainedModel extends Callable { const is_encoder_decoder = this.config.is_encoder_decoder; if (generation_config.num_beams > 1) { - if (generation_config.output_attentions) { - throw new Error('Beam search does not support output_attentions or token timestamps.'); - } const modality_inputs = [ 'pixel_values', 'pixel_values_videos', @@ -893,6 +894,7 @@ export class PreTrainedModel extends Callable { } } + let owned_encoder_output = null; // 4. Define other model kwargs if (!is_encoder_decoder) { // decoder-only models should use left-padding for generation @@ -905,6 +907,7 @@ export class PreTrainedModel extends Callable { model_input_name, generation_config, }); + owned_encoder_output = model_inputs.encoder_outputs; } // 5. Prepare `input_ids` which will be used for auto-regressive generation @@ -968,6 +971,10 @@ export class PreTrainedModel extends Callable { const is_beam_search = num_beams > 1; const is_group_beam_search = is_beam_search && num_beam_groups > 1; + const sequence_lengths = new Array(numInputs).fill(null); + let beam_history = Array.from({ length: numInputs * num_beams }, () => []); + const retained_attentions = new Set(); + let returned_attentions = false; let beam_scorer = null; let beam_scorers = null; /** @type {number[]} */ @@ -1127,6 +1134,7 @@ export class PreTrainedModel extends Callable { attentions[key] = []; } attentions[key].push(token_attentions[key]); + for (const tensor of token_attentions[key]) retained_attentions.add(tensor); } } else if (this._return_dict_in_generate_keys) { Object.assign(return_dict_items, pick(outputs, this._return_dict_in_generate_keys)); @@ -1247,6 +1255,17 @@ export class PreTrainedModel extends Callable { group_next_tokens, group_next_indices, group_next_scores, + Array.from( + { length: numInputs * group_size }, + (_, i) => + beam_history[ + Math.floor(i / group_size) * num_beams + group_offset + (i % group_size) + ], + ), + Array.from( + { length: numInputs * group_size }, + (_, i) => Math.floor(i / group_size) * num_beams + group_offset + (i % group_size), + ), ); // Map group outputs into global beam arrays @@ -1339,10 +1358,12 @@ export class PreTrainedModel extends Callable { all_next_tokens, all_next_indices, all_next_scores, + beam_history, )); } // Reorder all_input_ids based on beam indices and append new tokens + beam_history = next_beam_indices.map((parent) => [...beam_history[parent], parent]); const new_all_input_ids = []; for (let i = 0; i < total_beams; ++i) { new_all_input_ids.push([...all_input_ids[next_beam_indices[i]], next_beam_tokens[i]]); @@ -1391,6 +1412,10 @@ export class PreTrainedModel extends Callable { } } const stop = prepared_stopping_criteria(all_input_ids); + if (!is_beam_search) + for (let i = 0; i < stop.length; ++i) { + if (stop[i] && sequence_lengths[i] === null) sequence_lengths[i] = all_input_ids[i].length; + } if (stop.every((x) => x)) { break; } @@ -1435,6 +1460,7 @@ export class PreTrainedModel extends Callable { } let sequences; + let selected_hypotheses = []; if (is_beam_search) { /** @type {bigint[][]} */ let best_sequences; @@ -1460,6 +1486,13 @@ export class PreTrainedModel extends Callable { const group_results = beam_scorers[group_idx].finalize_with_scores( group_all_input_ids, group_beam_scores, + Array.from( + { length: numInputs * group_size }, + (_, i) => + beam_history[ + Math.floor(i / group_size) * num_beams + group_offset + (i % group_size) + ], + ), ); for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { @@ -1475,11 +1508,13 @@ export class PreTrainedModel extends Callable { const sorted = grouped[batch_idx].sort((a, b) => b.score - a.score); for (let i = 0; i < generation_config.num_return_sequences; ++i) { best_sequences.push(sorted[i].tokens); + selected_hypotheses.push(sorted[i]); } } } else { // Finalize beam search: select best hypotheses - best_sequences = beam_scorer.finalize(all_input_ids, beam_scores); + selected_hypotheses = beam_scorer.finalize_with_scores(all_input_ids, beam_scores, beam_history); + best_sequences = selected_hypotheses.map((x) => x.tokens); } // Pad sequences to equal length for tensor creation @@ -1505,7 +1540,11 @@ export class PreTrainedModel extends Callable { // Dispose output tensors not held by the cache const cachedTensors = new Set(Object.values(past_key_values)); for (const tensor of Object.values(outputs)) { - if (tensor.location === 'gpu-buffer' && !cachedTensors.has(tensor)) { + if ( + tensor.location === 'gpu-buffer' && + !cachedTensors.has(tensor) && + !retained_attentions.has(tensor) + ) { tensor.dispose(); } } @@ -1519,6 +1558,31 @@ export class PreTrainedModel extends Callable { if (generation_config.return_dict_in_generate) { const past_key_values_for_return = is_beam_search ? null : past_key_values; + if (is_beam_search) { + const width = sequences.dims[1]; + // Ancestry starts at column zero (the first generated token), + // independent of prefix length. Unused columns are -1. + return_dict_items.beam_indices = new Tensor( + 'int64', + selected_hypotheses.flatMap((x) => [ + ...x.beam_indices.map(BigInt), + ...Array(width - x.beam_indices.length).fill(-1n), + ]), + sequences.dims, + ); + return_dict_items.sequence_lengths = new Tensor( + 'int64', + selected_hypotheses.map((x) => BigInt(x.tokens.length)), + [selected_hypotheses.length], + ); + } + if (!is_beam_search) + return_dict_items.sequence_lengths = new Tensor( + 'int64', + all_input_ids.map((ids, i) => BigInt(sequence_lengths[i] ?? ids.length)), + [all_input_ids.length], + ); + returned_attentions = true; return { sequences, past_key_values: past_key_values_for_return, @@ -1528,6 +1592,8 @@ export class PreTrainedModel extends Callable { } return sequences; } finally { + owned_encoder_output?.dispose(); + if (!returned_attentions) for (const tensor of retained_attentions) tensor.dispose(); if (is_beam_search) { // Also run on forward/processor/reorder failures and partial expansion. const owned = new Set(expanded_tensors); @@ -1536,7 +1602,11 @@ export class PreTrainedModel extends Callable { } for (const tensor of Object.values(outputs ?? {})) owned.add(tensor); for (const tensor of owned) { - if (expanded_tensors.has(tensor) || tensor.location === 'gpu-buffer') tensor.dispose(); + if ( + !retained_attentions.has(tensor) && + (expanded_tensors.has(tensor) || tensor.location === 'gpu-buffer') + ) + tensor.dispose(); } if (model_inputs.past_key_values !== caller_cache) { await model_inputs.past_key_values?.dispose(); diff --git a/packages/transformers/src/models/whisper/generation_whisper.js b/packages/transformers/src/models/whisper/generation_whisper.js index 0fd1daa7d..fddbca631 100644 --- a/packages/transformers/src/models/whisper/generation_whisper.js +++ b/packages/transformers/src/models/whisper/generation_whisper.js @@ -16,8 +16,8 @@ export class WhisperGenerationConfig extends GenerationConfig { return_token_timestamps = null; /** - * The number of audio frames available in this chunk. This is only used generating word-level timestamps. - * @type {number} + * Valid mel frames (10 ms each), shared or one count per input. Used for word-level timestamps. + * @type {number|number[]} */ num_frames = null; diff --git a/packages/transformers/src/models/whisper/modeling_whisper.js b/packages/transformers/src/models/whisper/modeling_whisper.js index 0e46f0652..a045c00a8 100644 --- a/packages/transformers/src/models/whisper/modeling_whisper.js +++ b/packages/transformers/src/models/whisper/modeling_whisper.js @@ -1,4 +1,4 @@ -import { cat, mean, Tensor, stack, std_mean } from '../../utils/tensor.js'; +import { Tensor } from '../../utils/tensor.js'; import { PreTrainedModel } from '../modeling_utils.js'; import { WhisperGenerationConfig } from './generation_whisper.js'; import { whisper_language_to_code } from './common_whisper.js'; @@ -9,7 +9,6 @@ import { WhisperTimeStampLogitsProcessor, } from '../../generation/logits_process.js'; import { medianFilter, dynamic_time_warping } from '../../utils/maths.js'; -import { mergeArrays } from '../../utils/core.js'; import { ModelOutput } from '../modeling_outputs.js'; import { logger } from '../../utils/logger.js'; @@ -116,21 +115,29 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel { ...kwargs }) { generation_config = this._prepare_generation_config(generation_config, kwargs); + const public_attentions = generation_config.output_attentions; const init_tokens = kwargs.decoder_input_ids instanceof Tensor ? prepareTensorForDecode(kwargs.decoder_input_ids) : (kwargs.decoder_input_ids ?? this._retrieve_init_tokens(generation_config)); + const prefix = /** @type {number[]} */ (Array.isArray(init_tokens[0]) ? init_tokens[0] : init_tokens); + const prefix_length = prefix.length; + const batch_size = /** @type {Tensor} */ (inputs ?? kwargs.input_features)?.dims[0] ?? 1; + const decoder_input_ids = Array.isArray(init_tokens[0]) + ? /** @type {number[][]} */ (init_tokens) + : Array.from({ length: batch_size }, () => [...prefix]); + if (generation_config.return_timestamps) { logits_processor ??= new LogitsProcessorList(); - logits_processor.push(new WhisperTimeStampLogitsProcessor(generation_config, init_tokens)); + logits_processor.push(new WhisperTimeStampLogitsProcessor(generation_config, prefix)); } if (generation_config.begin_suppress_tokens) { logits_processor ??= new LogitsProcessorList(); logits_processor.push( - new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, init_tokens.length), + new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, prefix_length), ); } @@ -146,6 +153,8 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel { logger.warn("Token-level timestamps may not be reliable for task 'translate'."); } + kwargs.output_attentions = true; + kwargs.return_dict_in_generate = true; generation_config.output_attentions = true; generation_config.return_dict_in_generate = true; } @@ -154,12 +163,24 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel { // This matches Python's WhisperForConditionalGeneration.generate() which uses a seek loop // to handle audio that the model doesn't fully transcribe in a single pass. // Skip the seek loop when max_new_tokens is explicitly set (e.g., for prefix token tests). - if (generation_config.return_timestamps && !kwargs.max_new_tokens) { + if (generation_config.return_timestamps && !generation_config.max_new_tokens) { + if ( + /** @type {Tensor} */ (inputs ?? kwargs.input_features)?.dims[0] !== 1 || + generation_config.num_return_sequences !== 1 + ) { + throw new Error( + 'Whisper seek generation supports only a single input and a single returned sequence. Set max_new_tokens for short-form batch/multiple returns.', + ); + } + if (public_attentions) + throw new Error( + 'Whisper seek generation does not expose public per-step attentions; use short-form generation.', + ); return this._generate_with_seek({ - inputs, + inputs: inputs ?? kwargs.input_features, generation_config, logits_processor, - init_tokens, + init_tokens: prefix, kwargs, }); } @@ -168,19 +189,41 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel { inputs, generation_config, logits_processor, - decoder_input_ids: init_tokens, + decoder_input_ids, ...kwargs, }); if (generation_config.return_token_timestamps) { - outputs['token_timestamps'] = this._extract_token_timestamps( - // @ts-expect-error TS2345 - outputs, - generation_config.alignment_heads, - generation_config.num_frames, - 0.02, - init_tokens.length, - ); + let aligned = false; + outputs['num_beams'] = generation_config.num_beams; + try { + for (const step of outputs['cross_attentions'] ?? []) + for (const tensor of step) await tensor.ort_tensor.getData(false); + outputs['token_timestamps'] = this._extract_token_timestamps( + // @ts-expect-error TS2345 + outputs, + generation_config.alignment_heads, + Array.isArray(generation_config.num_frames) + ? generation_config.num_frames.map((x) => Math.floor(x / 2)) + : generation_config.num_frames == null + ? null + : Math.floor(generation_config.num_frames / 2), + 0.02, + prefix_length, + ); + aligned = true; + } finally { + if (!public_attentions || !aligned) { + for (const key of ['cross_attentions', 'decoder_attentions', 'encoder_attentions']) { + for (const step of outputs[key] ?? []) for (const tensor of step) tensor.dispose(); + delete outputs[key]; + } + } + if (!aligned) { + await outputs['past_key_values']?.dispose(); + for (const value of Object.values(outputs)) if (value instanceof Tensor) value.dispose(); + } + } } return outputs; @@ -200,8 +243,13 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel { const return_token_timestamps = generation_config.return_token_timestamps; // input_features shape: [batch=1, n_mels, total_frames] - const input_features = inputs; - const total_frames = input_features.dims[2]; + const input_features = inputs ?? kwargs.input_features; + const total_frames = Math.min( + input_features.dims[2], + (Array.isArray(generation_config.num_frames) + ? generation_config.num_frames[0] + : generation_config.num_frames) ?? Infinity, + ); // The encoder downsamples by input_stride (=2 for whisper), so: // num_segment_frames = input_stride * max_source_positions = 3000 mel frames per segment @@ -226,11 +274,13 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel { if (segment_frames < num_segment_frames) { const n_mels = input_features.dims[1]; const padded_data = new Float32Array(n_mels * num_segment_frames); - const src = /** @type {Float32Array} */ (segment_input.data); + const numeric_segment = segment_input.to('float32'); + const src = /** @type {Float32Array} */ (numeric_segment.data); // Copy each mel band row separately to handle the stride difference for (let m = 0; m < n_mels; ++m) { padded_data.set(src.subarray(m * segment_frames, (m + 1) * segment_frames), m * num_segment_frames); } + if (numeric_segment !== segment_input) numeric_segment.dispose(); segment_features = new Tensor('float32', padded_data, [1, n_mels, num_segment_frames]); } else { segment_features = segment_input; @@ -245,105 +295,132 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel { } } - const outputs = /** @type {any} */ ( - await super.generate({ - inputs: segment_features, + /** @type {any} */ + let outputs; + try { + outputs = await super.generate({ generation_config, logits_processor, decoder_input_ids: init_tokens, ...kwargs, - }) - ); - - // Extract tokens (skip init_tokens prefix) - const raw_sequence = return_token_timestamps ? outputs.sequences : /** @type {Tensor} */ (outputs); - const generated_tokens = raw_sequence[0].tolist().map(Number).slice(init_tokens.length); - - // Extract token-level timestamps for this seek pass if needed - let seek_token_timestamps; - if (return_token_timestamps) { - outputs['token_timestamps'] = this._extract_token_timestamps( - outputs, - generation_config.alignment_heads, - Math.floor((seek_end - seek) / input_stride), - 0.02, - init_tokens.length, - ); - const time_offset = (seek / input_stride) * 0.02; - seek_token_timestamps = outputs.token_timestamps[0] - .tolist() - .slice(init_tokens.length) - .map((/** @type {number} */ t) => t + time_offset); + input_features: segment_features, + }); + } finally { + segment_features.dispose(); + if (segment_features !== segment_input) segment_input.dispose(); } - // Remove trailing EOS - if (generated_tokens.length > 0 && generated_tokens.at(-1) === eos_token_id) { - generated_tokens.pop(); - } + try { + // Extract tokens (skip init_tokens prefix) + const raw_sequence = outputs.sequences ?? outputs; + const generated_tokens = raw_sequence[0].tolist().map(Number).slice(init_tokens.length); - if (generated_tokens.length === 0) { - // No tokens generated — skip the rest of the audio - break; - } + // Remove trailing EOS + if (generated_tokens.length > 0 && generated_tokens.at(-1) === eos_token_id) { + generated_tokens.pop(); + } - // Determine seek advancement using the same logic as Python's _retrieve_segment: - // 1. Find consecutive timestamp token pairs (segment boundaries) - // 2. If the sequence ends with a single timestamp (no speech after it), - // consume all remaining frames in this segment - // 3. Otherwise, seek to the last complete segment boundary - const is_timestamp = generated_tokens.map((t) => t >= timestamp_begin); - - // Check for single_timestamp_ending: last token is timestamp, second-to-last is not - const single_timestamp_ending = - generated_tokens.length >= 2 && - is_timestamp[generated_tokens.length - 1] && - !is_timestamp[generated_tokens.length - 2]; - - // Find consecutive timestamp pairs (segment boundaries) - const segment_boundary_indices = []; - for (let i = 0; i < generated_tokens.length - 1; ++i) { - if (is_timestamp[i] && is_timestamp[i + 1]) { - segment_boundary_indices.push(i + 1); // index of the second token in the pair + if (generated_tokens.length === 0) { + // No tokens generated — skip the rest of the audio + break; } - } - let segment_offset; - let tokens_to_keep = generated_tokens.length; - if (segment_boundary_indices.length > 0) { - if (single_timestamp_ending) { - // Ends with a single timestamp after the last pair — no more speech - segment_offset = seek_end - seek; + // Determine seek advancement using the same logic as Python's _retrieve_segment: + // 1. Find consecutive timestamp token pairs (segment boundaries) + // 2. If the sequence ends with a single timestamp (no speech after it), + // consume all remaining frames in this segment + // 3. Otherwise, seek to the last complete segment boundary + const is_timestamp = generated_tokens.map((t) => t >= timestamp_begin); + + // Check for single_timestamp_ending: last token is timestamp, second-to-last is not + const single_timestamp_ending = + generated_tokens.length >= 2 && + is_timestamp[generated_tokens.length - 1] && + !is_timestamp[generated_tokens.length - 2]; + + // Find consecutive timestamp pairs (segment boundaries) + const segment_boundary_indices = []; + for (let i = 0; i < generated_tokens.length - 1; ++i) { + if (is_timestamp[i] && is_timestamp[i + 1]) { + segment_boundary_indices.push(i + 1); // index of the second token in the pair + } + } + + let segment_offset; + let tokens_to_keep = generated_tokens.length; + if (segment_boundary_indices.length > 0) { + if (single_timestamp_ending) { + // Ends with a single timestamp after the last pair — no more speech + segment_offset = seek_end - seek; + } else { + // Ends mid-segment — seek to the last pair's end timestamp + // Discard tokens after the last pair (they're from an incomplete segment) + // Keep up to the first token of the last pair (the end-of-segment timestamp), + // excluding the second token (the start-of-next-segment marker) + const last_boundary = segment_boundary_indices.at(-1); + const last_ts_pos = generated_tokens[last_boundary - 1] - timestamp_begin; + segment_offset = last_ts_pos * input_stride; + tokens_to_keep = last_boundary; + } } else { - // Ends mid-segment — seek to the last pair's end timestamp - // Discard tokens after the last pair (they're from an incomplete segment) - // Keep up to the first token of the last pair (the end-of-segment timestamp), - // excluding the second token (the start-of-next-segment marker) - const last_boundary = segment_boundary_indices.at(-1); - const last_ts_pos = generated_tokens[last_boundary - 1] - timestamp_begin; - segment_offset = last_ts_pos * input_stride; - tokens_to_keep = last_boundary; + // No consecutive pairs found — consume entire segment + segment_offset = seek_end - seek; } - } else { - // No consecutive pairs found — consume entire segment - segment_offset = seek_end - seek; - } - // Offset timestamp tokens by the current seek position so they're - // monotonically increasing across segments. Cap at the maximum valid - // timestamp token (30.00s = 1500 positions) to stay within the token vocab. - const timestamp_offset = Math.floor(seek / input_stride); - const max_timestamp_token = timestamp_begin + 1500; - for (let i = 0; i < tokens_to_keep; ++i) { - if (generated_tokens[i] >= timestamp_begin) { - generated_tokens[i] = Math.min(generated_tokens[i] + timestamp_offset, max_timestamp_token); + // Align only the retained segment, before normalization and DTW. + // Include one terminal slot so the final retained token can use its + // query from the next forward, when that query exists. + let seek_token_timestamps; + if (return_token_timestamps) { + outputs.num_beams = generation_config.num_beams; + const valid_length = Math.min( + Number(outputs.sequence_lengths?.data[0] ?? raw_sequence.dims[1]), + init_tokens.length + tokens_to_keep + 1, + ); + outputs.sequence_lengths?.dispose(); + outputs.sequence_lengths = new Tensor('int64', [BigInt(valid_length)], [1]); + for (const step of outputs.cross_attentions ?? []) + for (const tensor of step) await tensor.ort_tensor.getData(false); + outputs.token_timestamps = this._extract_token_timestamps( + outputs, + generation_config.alignment_heads, + Math.floor(segment_offset / input_stride), + 0.02, + init_tokens.length, + ); + const time_offset = (seek / input_stride) * 0.02; + seek_token_timestamps = outputs.token_timestamps[0] + .tolist() + .slice(init_tokens.length) + .map((t) => t + time_offset); } - } - allTokens.push(...generated_tokens.slice(0, tokens_to_keep)); - if (seek_token_timestamps) { - allTokenTimestamps.push(...seek_token_timestamps.slice(0, tokens_to_keep)); + // Offset timestamp tokens by the current seek position so they're + // monotonically increasing across segments. Cap at the maximum valid + // timestamp token (30.00s = 1500 positions) to stay within the token vocab. + const timestamp_offset = Math.floor(seek / input_stride); + const max_timestamp_token = timestamp_begin + 1500; + for (let i = 0; i < tokens_to_keep; ++i) { + if (generated_tokens[i] >= timestamp_begin) { + generated_tokens[i] = Math.min(generated_tokens[i] + timestamp_offset, max_timestamp_token); + } + } + + allTokens.push(...generated_tokens.slice(0, tokens_to_keep)); + if (seek_token_timestamps) { + allTokenTimestamps.push(...seek_token_timestamps.slice(0, tokens_to_keep)); + } + if (segment_offset <= 0 || segment_offset > seek_end - seek) + throw new Error('Whisper returned an invalid seek offset.'); + seek += segment_offset; + } finally { + for (const key of ['cross_attentions', 'decoder_attentions', 'encoder_attentions']) { + for (const step of outputs[key] ?? []) for (const tensor of step) tensor.dispose(); + } + await outputs.past_key_values?.dispose(); + if (outputs instanceof Tensor) outputs.dispose(); + else for (const value of Object.values(outputs)) if (value instanceof Tensor) value.dispose(); } - seek += segment_offset; } // Add EOS back @@ -355,7 +432,11 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel { // Return dict format with sequences and token_timestamps const sequences = new Tensor('int64', full_sequence.map(BigInt), [1, full_sequence.length]); // Pad token_timestamps to match full_sequence (init_tokens get 0.0) - const full_timestamps = [...new Array(init_tokens.length).fill(0), ...allTokenTimestamps, 0]; + const full_timestamps = [ + ...new Array(init_tokens.length).fill(0), + ...allTokenTimestamps, + allTokenTimestamps.at(-1) ?? 0, + ]; const token_timestamps = new Tensor('float32', new Float32Array(full_timestamps), [ 1, full_timestamps.length, @@ -371,9 +452,12 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel { * If `num_frames` is specified, the encoder-decoder cross-attentions will be cropped before applying DTW. * @param {Object} generate_outputs Outputs generated by the model * @param {Tensor[][]} generate_outputs.cross_attentions The cross attentions output by the model + * @param {Tensor} [generate_outputs.beam_indices] Global parent row for each generated token; padded with -1. + * @param {Tensor} [generate_outputs.sequence_lengths] Valid sequence lengths including the prefix and EOS. + * @param {number} [generate_outputs.num_beams] Beam count per input. * @param {Tensor} generate_outputs.sequences The sequences output by the model * @param {number[][]} alignment_heads Alignment heads of the model - * @param {number} [num_frames=null] Number of frames in the input audio. + * @param {number|number[]} [num_frames=null] Valid encoder frames (20 ms each), per input or shared. * @param {number} [time_precision=0.02] Precision of the timestamps in seconds * @param {number} [num_input_ids=0] Number of decoder input ids (prefix tokens) to skip in DTW * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token @@ -405,106 +489,77 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel { median_filter_width = 7; } - // TODO: Improve batch processing - const batch = generate_outputs.cross_attentions; - // Create a list with `decoder_layers` elements, each a tensor of shape - // (batch size, attention_heads, output length, input length). - const cross_attentions = Array.from( - // @ts-expect-error TS2339 - { length: this.config.decoder_layers }, - // Concatenate the cross attentions for each layer across sequence length dimension. - (_, i) => - cat( - batch.map((x) => x[i]), - 2, - ), - ); - - const weights = stack( - alignment_heads.map(([l, h]) => { - if (l >= cross_attentions.length) { - throw new Error( - `Layer index ${l} is out of bounds for cross attentions (length ${cross_attentions.length}).`, - ); + if (!alignment_heads.length) throw new Error('Timestamp alignment requires at least one attention head.'); + const steps = generate_outputs.cross_attentions; + const shape = generate_outputs.sequences.dims; + const timestamps = new Tensor('float32', new Float32Array(shape[0] * shape[1]), shape); + const ancestry = generate_outputs.beam_indices?.tolist(); + const lengths = generate_outputs.sequence_lengths?.tolist(); + for (let result = 0; result < shape[0]; ++result) { + const valid = lengths ? Number(lengths[result]) : shape[1]; + const generated = valid - num_input_ids; + // Forward zero contains prefix queries only. Each later forward contains + // the preceding generated token. The final token (including EOS) has no + // query of its own; assign it the last aligned boundary. + const queries = Math.max(0, generated - 1); + if (!queries) continue; + const firstRow = ancestry ? Number(ancestry[result][0]) : result; + const inputIndex = Math.floor(firstRow / (generate_outputs.num_beams ?? 1)); + const requestedFrames = Array.isArray(num_frames) ? num_frames[inputIndex] : num_frames; + const frames = Math.min(steps[0][alignment_heads[0][0]].dims[3], requestedFrames ?? Infinity); + if (!Number.isInteger(frames) || frames <= 0) + throw new Error('Timestamp encoder frame count must be positive.'); + const prefixQueries = steps[0][alignment_heads[0][0]].dims[2]; + const validQueries = prefixQueries + queries; + const matrix = Array.from({ length: queries }, () => new Float32Array(frames)); + for (const [layer, head] of alignment_heads) { + const weights = []; + for (let token = 0; token < validQueries; ++token) { + const step = token < prefixQueries ? 0 : token - prefixQueries + 1; + const source = steps[step]?.[layer]; + if (!source || head >= source.dims[1]) + throw new Error('Missing timestamp alignment attention head or step.'); + const row = ancestry ? Number(ancestry[result][step]) : result; + if (row < 0 || row >= source.dims[0]) throw new Error('Invalid timestamp beam ancestry.'); + const numeric = source.to('float32'); + // Cached decoders expose one query; uncached decoders expose the + // complete history, whose final query is the preceding token. + const offset = + ((row * source.dims[1] + head) * source.dims[2] + (step === 0 ? token : source.dims[2] - 1)) * + source.dims[3]; + weights.push(Float32Array.from(numeric.data.slice(offset, offset + frames))); + if (numeric !== source) numeric.dispose(); } - return num_frames - ? cross_attentions[l].slice(null, h, null, [0, num_frames]) - : cross_attentions[l].slice(null, h); - }), - ).permute(1, 0, 2, 3); - - const [std, calculatedMean] = std_mean(weights, -2, 0, true); - - // Normalize and smoothen the weights. - const smoothedWeights = weights.clone(); // [1, 8, seqLength, 1500] - - for (let a = 0; a < smoothedWeights.dims[0]; ++a) { - const aTensor = smoothedWeights[a]; // [8, seqLength, 1500] - - for (let b = 0; b < aTensor.dims[0]; ++b) { - const bTensor = aTensor[b]; // [seqLength, 1500] - - const stdTensorData = std[a][b][0].data; // [1500] - const meanTensorData = calculatedMean[a][b][0].data; // [1500] - - for (let c = 0; c < bTensor.dims[0]; ++c) { - let cTensorData = bTensor[c].data; // [1500] - for (let d = 0; d < cTensorData.length; ++d) { - cTensorData[d] = (cTensorData[d] - meanTensorData[d]) / stdTensorData[d]; - } - - // Apply median filter. - cTensorData.set(medianFilter(cTensorData, median_filter_width)); + // Crop the selected hypothesis before computing statistics: other + // beams and padding must not affect normalization. Valid prefix queries + // participate in normalization, matching Whisper, but not in DTW. + for (let frame = 0; frame < frames; ++frame) { + let average = 0; + for (const row of weights) average += row[frame] / validQueries; + let variance = 0; + for (const row of weights) variance += (row[frame] - average) ** 2 / validQueries; + const scale = Math.sqrt(variance); + for (const row of weights) row[frame] = scale > 0 ? (row[frame] - average) / scale : 0; } - } - } - - // Skip decoder_input_ids in the cross-attention weights - const croppedWeights = - num_input_ids > 0 - ? smoothedWeights.slice(null, null, [num_input_ids, smoothedWeights.dims[2]], null) - : smoothedWeights; - - // Average the different cross-attention heads. - const batchedMatrices = [mean(croppedWeights, 1)]; - - const timestampsShape = generate_outputs.sequences.dims; - - const timestamps = new Tensor( - 'float32', - new Float32Array(timestampsShape[0] * timestampsShape[1]), - timestampsShape, - ); - - // Perform dynamic time warping on each element of the batch. - for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) { - // NOTE: Since we run only one batch at a time, we can squeeze to get the same dimensions - // as the python implementation - const matrix = batchedMatrices[batch_idx].neg().squeeze_(0); - const [text_indices, time_indices] = dynamic_time_warping(matrix.tolist()); - - const diffs = Array.from( - { length: text_indices.length - 1 }, - (v, i) => text_indices[i + 1] - text_indices[i], - ); - const jumps = mergeArrays([1], diffs).map((x) => !!x); // convert to boolean - - const jump_times = []; - for (let i = 0; i < jumps.length; ++i) { - if (jumps[i]) { - // NOTE: No point in rounding here, since we set to Float32Array later - jump_times.push(time_indices[i] * time_precision); + for (let token = 0; token < queries; ++token) { + // A cropped recording can be shorter than the configured reflection window. + const filtered = medianFilter( + weights[prefixQueries + token], + Math.min(median_filter_width, 2 * frames - 1), + ); + for (let frame = 0; frame < frames; ++frame) + matrix[token][frame] -= filtered[frame] / alignment_heads.length; } } - - // Pad with num_input_ids zeros at the start (for prefix tokens), - // then DTW jump_times, then duplicate last value (for eos token) - const padded = new Array(num_input_ids).fill(0); - padded.push(...jump_times); - if (jump_times.length > 0) { - padded.push(jump_times.at(-1)); + const [text, times] = dynamic_time_warping(matrix.map((row) => Array.from(row))); + let last = 0; + for (let i = 0; i < text.length; ++i) { + if (i === 0 || text[i] !== text[i - 1]) { + last = times[i] * time_precision; + timestamps.data[result * shape[1] + num_input_ids + text[i]] = last; + } } - timestamps[batch_idx].data.set(padded); + timestamps.data[result * shape[1] + valid - 1] = last; } return timestamps; diff --git a/packages/transformers/tests/utils/beam_ownership.test.js b/packages/transformers/tests/utils/beam_ownership.test.js index 789d83025..37703b203 100644 --- a/packages/transformers/tests/utils/beam_ownership.test.js +++ b/packages/transformers/tests/utils/beam_ownership.test.js @@ -158,6 +158,23 @@ describe("Beam resource ownership", () => { await caller.dispose(); }); + it.each([false, true])("releases the internally encoded source after beam expansion (failure=%s)", async (fail) => { + const model = modelWith(); + let destroyed = 0; + const encoded = gpu([1, 1, 4], { dispose: () => ++destroyed }); + model.config.is_encoder_decoder = true; + model._prepare_encoder_decoder_kwargs_for_generation = async ({ model_inputs }) => ({ ...model_inputs, encoder_outputs: encoded }); + if (fail) + model.forward = async () => { + throw Error("injected encoder continuation failure"); + }; + const result = model.generate({ num_beams: 2, max_new_tokens: 1, decoder_start_token_id: 1 }); + if (fail) await expect(result).rejects.toThrow("injected encoder continuation failure"); + else await result; + expect(destroyed).toBe(1); + expect(allocated.every((buffer) => buffer.destroyed)).toBe(true); + }); + it("rejects decoder-only multimodal beams before inference", async () => { const model = modelWith({ pixel_values: new Tensor("float32", [1], [1, 1]) }); model.forward = async () => { @@ -166,11 +183,25 @@ describe("Beam resource ownership", () => { await expect(model.generate({ num_beams: 2, max_new_tokens: 1 })).rejects.toThrow("decoder-only multimodal inputs"); }); - it("rejects beam attentions used for token timestamps before inference", async () => { + it.each([false, true])("retains public attention buffers and releases them on error=%s", async (fail) => { const model = modelWith(); + let destroyed = 0; + let calls = 0; model.forward = async () => { - throw new Error("must not run"); + if (++calls === 2 && fail) throw new Error("injected"); + return { logits: new Tensor("float32", [0, 1, 2, 3, 0, 1, 2, 3], [2, 1, 4]), "cross_attentions.0": gpu([2, 1, 1, 4], { dispose: () => ++destroyed }) }; }; - await expect(model.generate({ num_beams: 2, output_attentions: true, max_new_tokens: 1 })).rejects.toThrow("output_attentions or token timestamps"); + const promise = model.generate({ num_beams: 2, output_attentions: true, return_dict_in_generate: true, max_new_tokens: 2 }); + if (fail) { + await expect(promise).rejects.toThrow("injected"); + expect(destroyed).toBe(1); + } else { + const result = await promise; + expect(result.cross_attentions.length).toBe(2); + expect(destroyed).toBe(0); + expect(result.beam_indices.tolist()[0].slice(0, 2)).toEqual([0n, 0n]); + for (const step of result.cross_attentions) for (const tensor of step) tensor.dispose(); + expect(destroyed).toBe(2); + } }); }); diff --git a/packages/transformers/tests/utils/whisper_beam_timestamps.test.js b/packages/transformers/tests/utils/whisper_beam_timestamps.test.js new file mode 100644 index 000000000..2e30ea0fa --- /dev/null +++ b/packages/transformers/tests/utils/whisper_beam_timestamps.test.js @@ -0,0 +1,144 @@ +import { jest } from "@jest/globals"; +import { PreTrainedModel } from "../../src/models/modeling_utils.js"; +import { Tensor } from "../../src/utils/tensor.js"; +import { WhisperForConditionalGeneration } from "../../src/models/whisper/modeling_whisper.js"; +import { BeamSearchScorer } from "../../src/generation/beam_search.js"; + +const extract = (outputs, frames = 6) => WhisperForConditionalGeneration.prototype._extract_token_timestamps.call({ config: { median_filter_width: 1 } }, outputs, [[0, 0]], frames, 0.02, 2); +const sequences = () => new Tensor("int64", [9n, 8n, 1n, 2n, 3n, 0n, 9n, 8n, 4n, 0n, 0n, 0n], [2, 6]); + +it.each([false, true])("reconstructs changing rows, query offsets, EOS and padding (uncached=%s)", (uncached) => { + const history = [ + [0n, 1n, 0n, 1n, -1n, -1n], + [2n, 3n, -1n, -1n, -1n, -1n], + ]; + const steps = Array.from({ length: 4 }, (_, step) => { + const queries = step === 0 ? 2 : uncached ? 2 + step : 1; + const data = new Float32Array(4 * queries * 8).fill(-100); + for (let row = 0; row < 4; ++row) { + const offset = (row * queries + queries - 1) * 8; + // Unselected rows and padded frames are intentionally misleading. + data.fill(500 + row * 10 + step, offset, offset + 8); + if (step > 0 && row === Number(history[0][step])) { + data.fill(0, offset, offset + 6); + data[offset + (step - 1) * 2] = 10; + data[offset + (step - 1) * 2 + 1] = 10; + } + } + return [new Tensor("float32", data, [4, 1, queries, 8])]; + }); + const result = extract({ sequences: sequences(), cross_attentions: steps, beam_indices: new Tensor("int64", history.flat(), [2, 6]), sequence_lengths: new Tensor("int64", [6n, 4n], [2]), num_beams: 2 }, [6, 4]); + expect(Array.from(result.data.slice(0, 6))).toEqual([0, 0, 0, Math.fround(0.04), Math.fround(0.08), Math.fround(0.08)]); + expect(Array.from(result.data.slice(6))).toEqual([0, 0, 0, 0, 0, 0]); + expect(Array.from(result.data).every(Number.isFinite)).toBe(true); +}); + +it("converts fp16 attention values numerically and handles constant variance", () => { + const steps = Array.from({ length: 4 }, (_, i) => [new Tensor("float16", new Uint16Array(12).fill(i % 2 ? 0xbc00 : 0x3c00), [2, 1, 1, 6])]); + const output = { sequences: sequences(), cross_attentions: steps, sequence_lengths: new Tensor("int64", [6n, 4n], [2]) }; + const half = extract(output); + const float = extract({ ...output, cross_attentions: steps.map((step) => step.map((t) => t.to("float32"))) }); + expect(half.tolist()).toEqual(float.tolist()); + expect(Array.from(half.data).every(Number.isFinite)).toBe(true); +}); + +it("snapshots finished EOS ancestry using global diverse-group rows", () => { + const scorer = new BeamSearchScorer(2, 2, { eos_token_id: 0, decoder_prompt_len: 1 }); + const history = [[4], [5], [12], [13]]; + scorer.process( + [ + [9n, 1n], + [9n, 2n], + [9n, 3n], + [9n, 4n], + ], + [0, 0, 0, 0], + [0n, 1n, 2n, 0n, 1n, 2n], + [1, 0, 1, 0, 0, 1], + [-1, -2, -3, -1, -2, -3], + history, + [4, 5, 12, 13], + ); + history[1][0] = 999; + expect(scorer._beam_hyps[0].beams[0].beam_indices).toEqual([5, 5]); + expect(scorer._beam_hyps[1].beams[0].beam_indices).toEqual([12, 12]); + expect(scorer._beam_hyps[0].beams[0].tokens).toEqual([9n, 2n, 0n]); +}); + +it.each([ + { batch: 2, returns: 1 }, + { batch: 1, returns: 2 }, +])("rejects unsupported seek combinations before forward: %j", async ({ batch, returns }) => { + const model = Object.assign(Object.create(WhisperForConditionalGeneration.prototype), { + _prepare_generation_config: () => ({ return_timestamps: true, return_token_timestamps: true, alignment_heads: [[0, 0]], num_return_sequences: returns }), + _retrieve_init_tokens: () => [9, 8], + forward: () => { + throw Error("must not allocate"); + }, + }); + await expect(model.generate({ inputs: new Tensor("float32", new Float32Array(batch * 8), [batch, 1, 8]) })).rejects.toThrow("single input and a single returned sequence"); +}); + +it("keeps tiny cropped recordings finite with the default median window", () => { + const output = { sequences: new Tensor("int64", [9n, 8n, 1n, 0n], [1, 4]), cross_attentions: [[new Tensor("float32", [1], [1, 1, 1, 1])], [new Tensor("float32", [1], [1, 1, 1, 1])]] }; + const result = WhisperForConditionalGeneration.prototype._extract_token_timestamps.call({ config: { median_filter_width: 7 } }, output, [[0, 0]], 1, 0.02, 2); + expect(result.tolist()).toEqual([[0, 0, 0, 0]]); +}); + +it("keeps active ancestry when finalizing at the token limit", () => { + const scorer = new BeamSearchScorer(1, 2, { decoder_prompt_len: 2, num_return_sequences: 2 }); + const history = [ + [1, 0], + [0, 1], + ]; + const results = scorer.finalize_with_scores( + [ + [9n, 8n, 2n, 3n], + [9n, 8n, 4n, 5n], + ], + [-2, -1], + history, + ); + history[1][1] = 99; + expect(results.map((x) => x.beam_indices)).toEqual([ + [0, 1], + [1, 0], + ]); + expect(results.map((x) => x.tokens.at(-1))).toEqual([5n, 3n]); +}); + +it.each([false, true])("crops retained seek segments before alignment and releases scratch (failure=%s)", async (fail) => { + const owned = []; + const calls = []; + let segment = 0; + const forward = jest.spyOn(PreTrainedModel.prototype, "generate").mockImplementation(async () => { + const ids = segment++ === 0 ? [9n, 100n, 1n, 102n, 102n, 2n, 0n] : [9n, 100n, 2n, 102n, 0n]; + const sequences = new Tensor("int64", ids, [1, ids.length]); + const attention = new Tensor("float32", [1, 2, 3, 4], [1, 1, 1, 4]); + owned.push(jest.spyOn(sequences, "dispose"), jest.spyOn(attention, "dispose")); + return { sequences, cross_attentions: [[attention]] }; + }); + const model = Object.assign(Object.create(WhisperForConditionalGeneration.prototype), { + config: { max_source_positions: 4 }, + _extract_token_timestamps(outputs, heads, frames) { + calls.push({ frames, length: Number(outputs.sequence_lengths.data[0]) }); + if (fail) throw Error("alignment failed"); + return new Tensor("float32", new Float32Array(outputs.sequences.dims[1]), outputs.sequences.dims); + }, + }); + try { + const result = model._generate_with_seek({ inputs: new Tensor("float32", new Float32Array(8), [1, 1, 8]), generation_config: { no_timestamps_token_id: 99, eos_token_id: 0, return_token_timestamps: true, alignment_heads: [[0, 0]], num_beams: 2 }, init_tokens: [9], kwargs: {} }); + if (fail) await expect(result).rejects.toThrow("alignment failed"); + else { + const output = await result; + expect(calls).toEqual([ + { frames: 2, length: 5 }, + { frames: 2, length: 5 }, + ]); + expect(output.sequences.tolist()).toEqual([[9n, 100n, 1n, 102n, 102n, 2n, 104n, 0n]]); + } + for (const dispose of owned) expect(dispose).toHaveBeenCalledTimes(1); + } finally { + forward.mockRestore(); + } +}); diff --git a/scripts/beam-timestamps/.gitignore b/scripts/beam-timestamps/.gitignore new file mode 100644 index 000000000..5ebc93e7b --- /dev/null +++ b/scripts/beam-timestamps/.gitignore @@ -0,0 +1,4 @@ +model-cache/ +jfk.wav +results/*.log +results/*.json diff --git a/scripts/beam-timestamps/README.md b/scripts/beam-timestamps/README.md new file mode 100644 index 000000000..d7cb07bf7 --- /dev/null +++ b/scripts/beam-timestamps/README.md @@ -0,0 +1,52 @@ +# Beam timestamp validation + +This branch changes only beam ancestry and Whisper timestamp reconstruction. It does not enable decoder-only multimodal beams. Base: `b65dfaff9ca5e7e518c6e99f1d84f7453efd27c1`. + +## Output contract + +With `return_dict_in_generate`, beam generation returns: + +- `cross_attentions`, `decoder_attentions`, `encoder_attentions` when requested: the existing **step → layer → tensor** layout. Tensor row indices are the global forward rows (`input * num_beams + beam`), including diverse groups. Returned attention tensors remain caller-owned and readable until disposed. +- `beam_indices`: int64 `[returned_sequences, padded_sequence_length]`. Column **zero means the first generated token**, not the first prefix token. Each entry identifies the parent forward row for that step, including the step selecting EOS. Unused columns are `-1`. +- `sequence_lengths`: int64 valid lengths including prefix and EOS. Padding is not aligned. + +Whisper reconstructs the selected ancestry before computing statistics. First-forward prefix queries participate in normalization, but are excluded from DTW. Later forwards contribute the final query (the preceding generated token), for cached and uncached decoders. The final generated token has no query and repeats the last aligned boundary; padding timestamps are zero. fp16 storage is numerically converted to fp32. Constant variance produces zero normalized weights. The median window is bounded to the valid cropped recording; the general median-filter implementation is unchanged. + +Public `num_frames` is a mel-frame count (10 ms), scalar or per input. Alignment uses `floor(num_frames / 2)` encoder frames (20 ms). Short-form batch and multiple returns are supported with `max_new_tokens`. Seek mode supports one input and one return; other combinations fail before encoding. Seek mode currently rejects explicit public attention output because its concatenated transcript does not have a single encoder/attention time axis. Internal seek attentions are released after alignment. + +## Pinned fixtures + +- `onnx-community/whisper-tiny.en_timestamped` at `aeaa13760958b03fac5062f457d317d3319c3168`, with real `encoder_model.onnx` and `decoder_model_merged.onnx` exports; fp16 uses their `_fp16.onnx` counterparts. The export includes alignment heads. +- `Xenova/transformers.js-docs/jfk.wav` at dataset revision `542437c29cc5273cfd29e25c77696f2b349badd7`. +- The shared harness decodes PCM16, averages channels, and linearly resamples to 16 kHz identically in Node and browsers. Long audio is exactly 35 seconds of this waveform repeated. No microphone or variable input is used. + +## Native + +From this worktree, after `pnpm install --offline --frozen-lockfile` (use a frozen network install only if the store is incomplete): + +```sh +pnpm --filter @huggingface/transformers build +node scripts/beam-timestamps/native.mjs '{"device":"cpu","dtype":"fp32","batch":true,"returns":2,"repeats":3}' > scripts/beam-timestamps/results/native-cpu.json +node scripts/beam-timestamps/native.mjs '{"device":"cpu","dtype":"fp32","returns":2,"repeats":3}' > scripts/beam-timestamps/results/native-single.json +node scripts/beam-timestamps/native.mjs '{"device":"cpu","dtype":"fp32","batch":true,"returns":2,"beams":4,"groups":2,"publicAttentions":true,"repeats":25}' > scripts/beam-timestamps/results/native-diverse.json +node scripts/beam-timestamps/native.mjs '{"device":"cpu","dtype":"fp32","long":true,"repeats":3}' > scripts/beam-timestamps/results/native-long.json +node scripts/beam-timestamps/verify-results.mjs +``` + +`TIMESTAMP_AUDIO` can point to the pinned WAV. `TIMESTAMP_CACHE` sets a cache directory; default is branch-local `model-cache/`. Never copy the parent's model cache. `offline-tests.js` provides read-only shared-cache use for the test suite when `TRANSFORMERS_SHARED_CACHE` is set (remote model loading disabled). + +On parent-owned NVIDIA hardware, change `device` to `cuda` and run each dtype separately. Record GPU/driver/runtime and an ONNX Runtime provider profile confirming execution; do not infer CUDA execution from a successful request. There is no ROCm/MIGraphX mapping in this repository. + +## Browser (AMD/NVIDIA WebGPU and WASM) + +Serve the repo root on localhost after building, then open `/scripts/beam-timestamps/browser.html`. Set `?options={"device":"webgpu","dtype":"fp16","repeats":25}` (URL-encoded), or call `window.runTimestamps(options)` from the attached automation browser and save its JSON. Repeat short batch/returns, diverse groups, and single-return long cases above. Use `device:"wasm", dtype:"fp32"` for browser WASM. + +The harness records adapter identity, rejects known fallback adapters, and requires `shader-f16` for WebGPU fp16. Attach a browser GPU trace showing actual model execution, exact commit/status, model-file SHA256s, GPU driver, runtime version and raw console logs. `providerExecutionVerified:false` deliberately remains false until that independent evidence is supplied. + +Same-backend/dtype batch vs independent comparison requires exact tokens, order, and <=20 ms timestamp error. For cross-backend/dtype comparisons record transcript differences; for equal tokens, initial timing gates are median <=20 ms and maximum <=40 ms. A pinned Python Whisper alignment comparison is still required separately; it does not establish JS execution-provider support. + +## Overlap and remaining evidence + +Read-only metadata checked for PR1755 (attention/encoder memory), PR1742 (seek/logits regression), and PR1797 (oversized median reflection). This branch necessarily intersects attention ownership in PR1755. It does not import the logits fix or general reflection patch. Invalid seek advancement fails explicitly instead of hanging. + +Parent owns hardware validation and both postimplementation review rounds. CPU results and synthetic GPU ownership boundaries are not AMD/NVIDIA execution proof. Full suite, Python alignment parity, browser WASM, hardware cells, and full allocation accounting must be reported individually; no final-readiness claim follows from this harness. diff --git a/scripts/beam-timestamps/browser.html b/scripts/beam-timestamps/browser.html new file mode 100644 index 000000000..d31d08651 --- /dev/null +++ b/scripts/beam-timestamps/browser.html @@ -0,0 +1,14 @@ +Whisper beam timestamp validation +

+
diff --git a/scripts/beam-timestamps/harness.mjs b/scripts/beam-timestamps/harness.mjs
new file mode 100644
index 000000000..4eaf785f9
--- /dev/null
+++ b/scripts/beam-timestamps/harness.mjs
@@ -0,0 +1,124 @@
+// Shared native/browser runner. The caller supplies the branch-local library.
+export const fixture = {
+  model: "onnx-community/whisper-tiny.en_timestamped",
+  revision: "aeaa13760958b03fac5062f457d317d3319c3168",
+  audio: "https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/542437c29cc5273cfd29e25c77696f2b349badd7/jfk.wav",
+};
+export async function run(
+  lib,
+  {
+    device = "cpu",
+    dtype = "fp32",
+    repeats = 3,
+    long = false,
+    batch = false,
+    beams = 2,
+    returns = 1,
+    groups = 1,
+    publicAttentions = false,
+    audioBytes = null,
+  } = {},
+) {
+  const { AutoProcessor, WhisperForConditionalGeneration, Tensor, cat } = lib;
+  const bytes = audioBytes ?? (await (await fetch(fixture.audio)).arrayBuffer());
+  // Decode the pinned stereo PCM16 WAV and deterministically resample to mono 16 kHz.
+  const view = new DataView(bytes);
+  let offset = 12,
+    samples,
+    channels,
+    rate;
+  while (offset + 8 <= view.byteLength) {
+    const tag = String.fromCharCode(...new Uint8Array(bytes, offset, 4));
+    const size = view.getUint32(offset + 4, true);
+    if (tag === "fmt ") {
+      if (view.getUint16(offset + 8, true) !== 1 || view.getUint16(offset + 22, true) !== 16) throw Error("Expected PCM16");
+      channels = view.getUint16(offset + 10, true);
+      rate = view.getUint32(offset + 12, true);
+    }
+    if (tag === "data") {
+      const mono = Float32Array.from({ length: size / (2 * channels) }, (_, i) => {
+        let value = 0;
+        for (let c = 0; c < channels; ++c) value += view.getInt16(offset + 8 + 2 * (i * channels + c), true) / (32768 * channels);
+        return value;
+      });
+      samples = Float32Array.from({ length: Math.floor((mono.length * 16000) / rate) }, (_, i) => {
+        const position = (i * rate) / 16000,
+          left = Math.floor(position),
+          fraction = position - left;
+        return mono[left] * (1 - fraction) + mono[Math.min(left + 1, mono.length - 1)] * fraction;
+      });
+      break;
+    }
+    offset += 8 + size + (size % 2);
+  }
+  if (!samples) throw Error("Missing PCM data");
+  if (long) {
+    const repeated = new Float32Array(16000 * 35);
+    for (let i = 0; i < repeated.length; ++i) repeated[i] = samples[i % samples.length];
+    samples = repeated;
+  }
+  const processor = await AutoProcessor.from_pretrained(fixture.model, { revision: fixture.revision });
+  const model = await WhisperForConditionalGeneration.from_pretrained(fixture.model, {
+    revision: fixture.revision,
+    device,
+    dtype,
+    session_options: { intraOpNumThreads: 1, interOpNumThreads: 1 },
+  });
+  const processed = await processor(samples, { truncation: !long });
+  const input = batch ? cat([processed.input_features, processed.input_features], 0) : processed.input_features;
+  const options = {
+    input_features: input,
+    num_beams: beams,
+    num_beam_groups: groups,
+    diversity_penalty: groups > 1 ? 1 : 0,
+    num_return_sequences: returns,
+    return_token_timestamps: true,
+    return_timestamps: long,
+    output_attentions: publicAttentions,
+    num_frames: Math.floor(samples.length / 160),
+    ...(long ? {} : { max_new_tokens: 64 }),
+  };
+  const timings = [],
+    outputs = [];
+  try {
+    for (let iteration = -1; iteration < repeats; ++iteration) {
+      const start = performance.now();
+      const result = await model.generate(options);
+      const elapsed = performance.now() - start;
+      console.error(JSON.stringify({ iteration, elapsed_ms: elapsed, memory: typeof process !== "undefined" ? process.memoryUsage() : null }));
+      const record = {
+        tokens: result.sequences.tolist().map((row) => row.map(Number)),
+        timestamps: result.token_timestamps.tolist(),
+        beam_indices: result.beam_indices?.tolist().map((row) => row.map(Number)),
+        lengths: result.sequence_lengths?.tolist().map(Number),
+        retainedAttentionBytes: 0,
+      };
+      for (const key of ["cross_attentions", "decoder_attentions", "encoder_attentions"])
+        for (const step of result[key] ?? [])
+          for (const tensor of step) {
+            const data = await tensor.ort_tensor.getData(false);
+            record.retainedAttentionBytes += data.byteLength;
+            tensor.dispose();
+          }
+      if (!record.timestamps.flat().every(Number.isFinite)) throw Error("Nonfinite timestamps");
+      for (const value of Object.values(result)) if (value instanceof Tensor) value.dispose();
+      await result.past_key_values?.dispose();
+      if (iteration >= 0) {
+        timings.push(elapsed);
+        outputs.push(record);
+      }
+    }
+    return {
+      fixture,
+      requested: { device, dtype, beams, groups, returns, batch, long, repeats },
+      timings_ms: timings,
+      outputs,
+      providerExecutionVerified: false,
+      note: "Attach runtime EP profiling / browser GPU trace and driver identity; requested device alone is not execution proof.",
+    };
+  } finally {
+    await model.dispose();
+    input.dispose();
+    if (input !== processed.input_features) processed.input_features.dispose();
+  }
+}
diff --git a/scripts/beam-timestamps/native.mjs b/scripts/beam-timestamps/native.mjs
new file mode 100644
index 000000000..1e00c0258
--- /dev/null
+++ b/scripts/beam-timestamps/native.mjs
@@ -0,0 +1,18 @@
+import * as lib from "../../packages/transformers/src/transformers.js";
+import { run } from "./harness.mjs";
+import fs from "node:fs";
+import { execFileSync } from "node:child_process";
+lib.env.cacheDir = process.env.TIMESTAMP_CACHE ?? new URL("./model-cache", import.meta.url).pathname;
+const options = JSON.parse(process.argv[2] ?? "{}");
+if (process.env.TIMESTAMP_AUDIO) {
+  const b = fs.readFileSync(process.env.TIMESTAMP_AUDIO);
+  options.audioBytes = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);
+}
+const result = await run(lib, options);
+console.log(
+  JSON.stringify(
+    { sha: execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(), runtime: process.version, platform: process.platform, ...result },
+    null,
+    2,
+  ),
+);
diff --git a/scripts/beam-timestamps/offline-tests.js b/scripts/beam-timestamps/offline-tests.js
new file mode 100644
index 000000000..adebe1642
--- /dev/null
+++ b/scripts/beam-timestamps/offline-tests.js
@@ -0,0 +1,5 @@
+import { env } from "../../packages/transformers/src/env.js";
+if (process.env.TRANSFORMERS_SHARED_CACHE) {
+  env.cacheDir = process.env.TRANSFORMERS_SHARED_CACHE;
+  env.allowRemoteModels = false;
+}
diff --git a/scripts/beam-timestamps/verify-results.mjs b/scripts/beam-timestamps/verify-results.mjs
new file mode 100644
index 000000000..8312ea280
--- /dev/null
+++ b/scripts/beam-timestamps/verify-results.mjs
@@ -0,0 +1,52 @@
+import assert from "node:assert/strict";
+import fs from "node:fs";
+const read = (name) => JSON.parse(fs.readFileSync(new URL(`results/${name}.json`, import.meta.url)));
+const batch = read("native-cpu"),
+  single = read("native-single"),
+  diverse = read("native-diverse"),
+  long = read("native-long");
+for (const result of [batch, single, diverse, long]) {
+  assert.equal(result.fixture.revision, "aeaa13760958b03fac5062f457d317d3319c3168");
+  for (const output of result.outputs) {
+    assert.equal(output.tokens.length, output.timestamps.length);
+    output.tokens.forEach((tokens, row) => {
+      const times = output.timestamps[row],
+        length = output.lengths?.[row] ?? tokens.length;
+      assert.equal(tokens.length, times.length);
+      assert(times.every(Number.isFinite));
+      for (let i = 1; i < length; ++i) assert(times[i] >= times[i - 1], `non-monotonic row ${row} at ${i}`);
+      assert(times.slice(length).every((t) => t === 0));
+      if (output.beam_indices) {
+        const history = output.beam_indices[row].filter((x) => x !== -1);
+        // Short-form English prefix has two tokens.
+        assert.equal(history.length, length - 2);
+        const input = Math.floor(row / result.requested.returns);
+        assert(history.every((x) => Math.floor(x / result.requested.beams) === input));
+      }
+    });
+    assert.deepEqual(output, result.outputs[0], "repeated call output drift");
+  }
+}
+for (let row = 0; row < batch.outputs[0].tokens.length; ++row) {
+  const rank = row % 2;
+  assert.deepEqual(batch.outputs[0].tokens[row], single.outputs[0].tokens[rank]);
+  assert.deepEqual(batch.outputs[0].timestamps[row], single.outputs[0].timestamps[rank]);
+}
+assert.equal(diverse.outputs.length, 25);
+assert(diverse.outputs.every((x) => x.retainedAttentionBytes > 0));
+console.log(
+  JSON.stringify(
+    {
+      passed: true,
+      checks: [
+        "batch vs independent exact tokens and timestamps",
+        "25 diverse public-attention calls stable",
+        "global ancestry and valid lengths",
+        "35-second seek monotonicity",
+        "EOS and zero padding",
+      ],
+    },
+    null,
+    2,
+  ),
+);

From 8d2dd9ff62e0bfd3b266544ad61521fe2362b5eb Mon Sep 17 00:00:00 2001
From: Dan Levy 
Date: Tue, 20 Oct 2026 15:42:14 -0600
Subject: [PATCH 16/21] Handle explicit Whisper prefixes and release beam step
 scratch

---
 .../transformers/src/models/modeling_utils.js | 12 ++++++++++
 .../src/models/whisper/modeling_whisper.js    |  4 ++--
 .../tests/utils/beam_ownership.test.js        | 14 ++++++++++++
 .../utils/whisper_beam_timestamps.test.js     | 19 ++++++++++++++++
 scripts/beam-timestamps/README.md             |  2 +-
 scripts/beam-timestamps/native.mjs            | 22 +++++++++++++------
 scripts/beam-timestamps/results/.gitkeep      |  0
 7 files changed, 63 insertions(+), 10 deletions(-)
 create mode 100644 scripts/beam-timestamps/results/.gitkeep

diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js
index 8b88cfb1c..10913d83a 100644
--- a/packages/transformers/src/models/modeling_utils.js
+++ b/packages/transformers/src/models/modeling_utils.js
@@ -1382,6 +1382,18 @@ export class PreTrainedModel extends Callable {
                         getPastKeyValues(outputs, model_inputs.past_key_values),
                         next_beam_indices,
                     );
+                    // Reordering consumes the old cache, but merged decoders may
+                    // also return unused encoder-cache outputs. Release step-local
+                    // GPU scratch before the next forward overwrites `outputs`.
+                    const active_cache_tensors = new Set(Object.values(model_inputs.past_key_values));
+                    for (const tensor of Object.values(outputs)) {
+                        if (
+                            tensor.location === 'gpu-buffer' &&
+                            !active_cache_tensors.has(tensor) &&
+                            !retained_attentions.has(tensor)
+                        )
+                            tensor.dispose();
+                    }
                 } else {
                     // Greedy / sample: existing behavior
                     for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) {
diff --git a/packages/transformers/src/models/whisper/modeling_whisper.js b/packages/transformers/src/models/whisper/modeling_whisper.js
index a045c00a8..ded039f52 100644
--- a/packages/transformers/src/models/whisper/modeling_whisper.js
+++ b/packages/transformers/src/models/whisper/modeling_whisper.js
@@ -189,8 +189,8 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
             inputs,
             generation_config,
             logits_processor,
-            decoder_input_ids,
             ...kwargs,
+            decoder_input_ids,
         });
 
         if (generation_config.return_token_timestamps) {
@@ -301,8 +301,8 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
                 outputs = await super.generate({
                     generation_config,
                     logits_processor,
-                    decoder_input_ids: init_tokens,
                     ...kwargs,
+                    decoder_input_ids: init_tokens,
                     input_features: segment_features,
                 });
             } finally {
diff --git a/packages/transformers/tests/utils/beam_ownership.test.js b/packages/transformers/tests/utils/beam_ownership.test.js
index 37703b203..a27cd37b1 100644
--- a/packages/transformers/tests/utils/beam_ownership.test.js
+++ b/packages/transformers/tests/utils/beam_ownership.test.js
@@ -175,6 +175,20 @@ describe("Beam resource ownership", () => {
     expect(allocated.every((buffer) => buffer.destroyed)).toBe(true);
   });
 
+  it("releases unused GPU step outputs before the next forward", async () => {
+    const model = modelWith();
+    let calls = 0,
+      destroyed = 0;
+    model.forward = async () => {
+      expect(destroyed).toBe(calls);
+      ++calls;
+      return { logits: new Tensor("float32", [0, 1, 2, 3, 0, 1, 2, 3], [2, 1, 4]), unused: gpu([2, 1, 4], { dispose: () => ++destroyed }) };
+    };
+    await model.generate({ num_beams: 2, max_new_tokens: 3 });
+    expect(calls).toBe(3);
+    expect(destroyed).toBe(3);
+  });
+
   it("rejects decoder-only multimodal beams before inference", async () => {
     const model = modelWith({ pixel_values: new Tensor("float32", [1], [1, 1]) });
     model.forward = async () => {
diff --git a/packages/transformers/tests/utils/whisper_beam_timestamps.test.js b/packages/transformers/tests/utils/whisper_beam_timestamps.test.js
index 2e30ea0fa..1e7dd6071 100644
--- a/packages/transformers/tests/utils/whisper_beam_timestamps.test.js
+++ b/packages/transformers/tests/utils/whisper_beam_timestamps.test.js
@@ -142,3 +142,22 @@ it.each([false, true])("crops retained seek segments before alignment and releas
     forward.mockRestore();
   }
 });
+
+it("expands an explicitly supplied flat prefix across the short-form batch", async () => {
+  const forward = jest.spyOn(PreTrainedModel.prototype, "generate").mockImplementation(async ({ decoder_input_ids }) => {
+    expect(decoder_input_ids).toEqual([
+      [9, 8],
+      [9, 8],
+    ]);
+    return new Tensor("int64", [9n, 8n, 1n, 9n, 8n, 1n], [2, 3]);
+  });
+  const model = Object.assign(Object.create(WhisperForConditionalGeneration.prototype), {
+    _prepare_generation_config: () => ({ max_new_tokens: 1 }),
+  });
+  try {
+    await model.generate({ input_features: new Tensor("float32", new Float32Array(16), [2, 1, 8]), decoder_input_ids: [9, 8] });
+    expect(forward).toHaveBeenCalledTimes(1);
+  } finally {
+    forward.mockRestore();
+  }
+});
diff --git a/scripts/beam-timestamps/README.md b/scripts/beam-timestamps/README.md
index d7cb07bf7..d160ff656 100644
--- a/scripts/beam-timestamps/README.md
+++ b/scripts/beam-timestamps/README.md
@@ -47,6 +47,6 @@ Same-backend/dtype batch vs independent comparison requires exact tokens, order,
 
 ## Overlap and remaining evidence
 
-Read-only metadata checked for PR1755 (attention/encoder memory), PR1742 (seek/logits regression), and PR1797 (oversized median reflection). This branch necessarily intersects attention ownership in PR1755. It does not import the logits fix or general reflection patch. Invalid seek advancement fails explicitly instead of hanging.
+Read-only metadata checked for PR1755 (attention/encoder memory), PR1742 (seek/logits regression), and PR1797 (oversized median reflection). This branch necessarily intersects attention and encoder ownership in PR1755. Its beam-loop cleanup also releases unused GPU step outputs before the next forward; it does not copy the general getPastKeyValues patch. It does not import the logits fix or general reflection patch. Invalid seek advancement fails explicitly instead of hanging.
 
 Parent owns hardware validation and both postimplementation review rounds. CPU results and synthetic GPU ownership boundaries are not AMD/NVIDIA execution proof. Full suite, Python alignment parity, browser WASM, hardware cells, and full allocation accounting must be reported individually; no final-readiness claim follows from this harness.
diff --git a/scripts/beam-timestamps/native.mjs b/scripts/beam-timestamps/native.mjs
index 1e00c0258..9c4e03cbe 100644
--- a/scripts/beam-timestamps/native.mjs
+++ b/scripts/beam-timestamps/native.mjs
@@ -1,6 +1,7 @@
 import * as lib from "../../packages/transformers/src/transformers.js";
 import { run } from "./harness.mjs";
 import fs from "node:fs";
+import { createHash } from "node:crypto";
 import { execFileSync } from "node:child_process";
 lib.env.cacheDir = process.env.TIMESTAMP_CACHE ?? new URL("./model-cache", import.meta.url).pathname;
 const options = JSON.parse(process.argv[2] ?? "{}");
@@ -8,11 +9,18 @@ if (process.env.TIMESTAMP_AUDIO) {
   const b = fs.readFileSync(process.env.TIMESTAMP_AUDIO);
   options.audioBytes = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);
 }
-const result = await run(lib, options);
-console.log(
-  JSON.stringify(
-    { sha: execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(), runtime: process.version, platform: process.platform, ...result },
-    null,
-    2,
+const sourcePaths = ["generation/beam_search.js", "models/modeling_utils.js", "models/whisper/modeling_whisper.js"];
+const provenance = {
+  sha: execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(),
+  status: execFileSync("git", ["status", "--porcelain"], { encoding: "utf8" }).trim(),
+  sources: Object.fromEntries(
+    sourcePaths.map((path) => [
+      path,
+      createHash("sha256")
+        .update(fs.readFileSync(new URL(`../../packages/transformers/src/${path}`, import.meta.url)))
+        .digest("hex"),
+    ]),
   ),
-);
+};
+const result = await run(lib, options);
+console.log(JSON.stringify({ ...provenance, runtime: process.version, platform: process.platform, ...result }, null, 2));
diff --git a/scripts/beam-timestamps/results/.gitkeep b/scripts/beam-timestamps/results/.gitkeep
new file mode 100644
index 000000000..e69de29bb

From fe3ce83e81b128680709dd1d13de740d3840f248 Mon Sep 17 00:00:00 2001
From: Dan Levy 
Date: Tue, 20 Oct 2026 15:50:37 -0600
Subject: [PATCH 17/21] Fix Whisper alignment parity and bound fp16 conversion
 work

---
 .../transformers/src/models/modeling_utils.js | 1278 +++++++++--------
 .../src/models/whisper/modeling_whisper.js    |   40 +-
 .../tests/utils/beam_ownership.test.js        |   14 +
 .../utils/whisper_beam_timestamps.test.js     |   44 +
 scripts/beam-timestamps/README.md             |    8 +-
 scripts/beam-timestamps/harness.mjs           |   32 +
 scripts/beam-timestamps/verify-results.mjs    |   21 +
 7 files changed, 783 insertions(+), 654 deletions(-)

diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js
index 10913d83a..fe5bb5a02 100644
--- a/packages/transformers/src/models/modeling_utils.js
+++ b/packages/transformers/src/models/modeling_utils.js
@@ -895,735 +895,751 @@ export class PreTrainedModel extends Callable {
         }
 
         let owned_encoder_output = null;
-        // 4. Define other model kwargs
-        if (!is_encoder_decoder) {
-            // decoder-only models should use left-padding for generation
-        } else if (!('encoder_outputs' in model_inputs)) {
-            // if model is encoder decoder encoder_outputs are created
-            // and added to `model_kwargs`
-            model_inputs = await this._prepare_encoder_decoder_kwargs_for_generation({
-                inputs_tensor,
-                model_inputs,
-                model_input_name,
-                generation_config,
-            });
-            owned_encoder_output = model_inputs.encoder_outputs;
-        }
-
-        // 5. Prepare `input_ids` which will be used for auto-regressive generation
-        // TODO: Update to align with HF transformers' implementation
-        let input_ids;
-        if (is_encoder_decoder) {
-            // Generating from the encoder outputs
-            ({ input_ids, model_inputs } = this._prepare_decoder_input_ids_for_generation({
-                batch_size: model_inputs[model_input_name].dims.at(0),
-                model_input_name,
-                model_kwargs: model_inputs,
-                decoder_start_token_id: generation_config.decoder_start_token_id,
-                bos_token_id: generation_config.bos_token_id,
-                generation_config,
-            }));
-        } else {
-            input_ids = model_inputs[model_input_name];
-        }
-
-        // 6. Prepare `max_length` depending on other stopping criteria.
-        let input_ids_length = input_ids.dims.at(-1);
-
-        if (generation_config.max_new_tokens !== null) {
-            generation_config.max_length = input_ids_length + generation_config.max_new_tokens;
-        }
+        try {
+            // 4. Define other model kwargs
+            if (!is_encoder_decoder) {
+                // decoder-only models should use left-padding for generation
+            } else if (!('encoder_outputs' in model_inputs)) {
+                // if model is encoder decoder encoder_outputs are created
+                // and added to `model_kwargs`
+                model_inputs = await this._prepare_encoder_decoder_kwargs_for_generation({
+                    inputs_tensor,
+                    model_inputs,
+                    model_input_name,
+                    generation_config,
+                });
+                owned_encoder_output = model_inputs.encoder_outputs;
+            }
 
-        // input_ids_length = model_inputs[model_input_name].dims.at(1);
-        // // inputs instanceof Tensor ?  : inputs.length;
+            // 5. Prepare `input_ids` which will be used for auto-regressive generation
+            // TODO: Update to align with HF transformers' implementation
+            let input_ids;
+            if (is_encoder_decoder) {
+                // Generating from the encoder outputs
+                ({ input_ids, model_inputs } = this._prepare_decoder_input_ids_for_generation({
+                    batch_size: model_inputs[model_input_name].dims.at(0),
+                    model_input_name,
+                    model_kwargs: model_inputs,
+                    decoder_start_token_id: generation_config.decoder_start_token_id,
+                    bos_token_id: generation_config.bos_token_id,
+                    generation_config,
+                }));
+            } else {
+                input_ids = model_inputs[model_input_name];
+            }
 
-        // // decoder-only
-        // if (input_ids_length === 0) {
-        //     throw Error("Must supply a non-empty array of input token ids.")
-        // }
+            // 6. Prepare `max_length` depending on other stopping criteria.
+            let input_ids_length = input_ids.dims.at(-1);
 
-        // let decoder_input_ids =
-        // generation_config.decoder_input_ids
-        // ?? generation_config.decoder_start_token_id
-        // ?? generation_config.bos_token_id
-        // ?? generation_config.eos_token_id;
+            if (generation_config.max_new_tokens !== null) {
+                generation_config.max_length = input_ids_length + generation_config.max_new_tokens;
+            }
 
-        // Update logits processor
-        // 8. prepare distribution pre_processing samplers
-        const prepared_logits_processor = this._get_logits_processor(
-            generation_config,
-            input_ids_length,
-            logits_processor,
-        );
+            // input_ids_length = model_inputs[model_input_name].dims.at(1);
+            // // inputs instanceof Tensor ?  : inputs.length;
 
-        // 9. prepare stopping criteria
-        const prepared_stopping_criteria = this._get_stopping_criteria(generation_config, stopping_criteria);
+            // // decoder-only
+            // if (input_ids_length === 0) {
+            //     throw Error("Must supply a non-empty array of input token ids.")
+            // }
 
-        // /** @type {number[]} */
-        // let eos_token_ids = generation_config.eos_token_id;
-        // if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) {
-        //     eos_token_ids = [eos_token_ids];
-        // }
+            // let decoder_input_ids =
+            // generation_config.decoder_input_ids
+            // ?? generation_config.decoder_start_token_id
+            // ?? generation_config.bos_token_id
+            // ?? generation_config.eos_token_id;
 
-        const numInputs = model_inputs[model_input_name].dims.at(0);
-        const num_beams = generation_config.num_beams;
-        const num_beam_groups = generation_config.num_beam_groups;
-        const is_beam_search = num_beams > 1;
-        const is_group_beam_search = is_beam_search && num_beam_groups > 1;
-
-        const sequence_lengths = new Array(numInputs).fill(null);
-        let beam_history = Array.from({ length: numInputs * num_beams }, () => []);
-        const retained_attentions = new Set();
-        let returned_attentions = false;
-        let beam_scorer = null;
-        let beam_scorers = null;
-        /** @type {number[]} */
-        let beam_scores;
-
-        if (is_beam_search) {
-            // Validate beam search configuration
-            if (generation_config.num_return_sequences > num_beams) {
-                throw new Error(
-                    `num_return_sequences (${generation_config.num_return_sequences}) must be <= num_beams (${num_beams}).`,
-                );
-            }
-            if (num_beam_groups < 1) {
-                throw new Error(`num_beam_groups must be >= 1, but got ${num_beam_groups}.`);
-            }
-            if (num_beam_groups > num_beams) {
-                throw new Error(`num_beam_groups (${num_beam_groups}) must be <= num_beams (${num_beams}).`);
-            }
-            if (num_beams % num_beam_groups !== 0) {
-                throw new Error(`num_beams (${num_beams}) must be divisible by num_beam_groups (${num_beam_groups}).`);
-            }
-            if (is_group_beam_search && generation_config.do_sample) {
-                throw new Error(
-                    'Diverse beam sampling (num_beam_groups > 1 with do_sample = true) is not yet supported.',
-                );
-            }
-            if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {
-                throw new Error('Classifier-free guidance (guidance_scale > 1) is not supported with beam search.');
-            }
-            if (streamer) {
-                throw new Error('Streaming is not supported with beam search.');
-            }
+            // Update logits processor
+            // 8. prepare distribution pre_processing samplers
+            const prepared_logits_processor = this._get_logits_processor(
+                generation_config,
+                input_ids_length,
+                logits_processor,
+            );
 
-            if (is_group_beam_search) {
-                const group_size = num_beams / num_beam_groups;
-                beam_scorers = Array.from(
-                    { length: num_beam_groups },
-                    () =>
-                        new BeamSearchScorer(numInputs, group_size, {
-                            length_penalty: generation_config.length_penalty,
-                            early_stopping: generation_config.early_stopping,
-                            num_return_sequences: group_size,
-                            eos_token_id: generation_config.eos_token_id,
-                            pad_token_id: generation_config.pad_token_id,
-                            decoder_prompt_len: input_ids_length,
-                            max_length: generation_config.max_length,
-                        }),
-                );
-            } else {
-                beam_scorer = new BeamSearchScorer(numInputs, num_beams, {
-                    length_penalty: generation_config.length_penalty,
-                    early_stopping: generation_config.early_stopping,
-                    num_return_sequences: generation_config.num_return_sequences,
-                    eos_token_id: generation_config.eos_token_id,
-                    pad_token_id: generation_config.pad_token_id,
-                    decoder_prompt_len: input_ids_length,
-                    max_length: generation_config.max_length,
-                });
-            }
-        }
+            // 9. prepare stopping criteria
+            const prepared_stopping_criteria = this._get_stopping_criteria(generation_config, stopping_criteria);
 
-        const sampler = LogitsSampler.getSampler(generation_config);
+            // /** @type {number[]} */
+            // let eos_token_ids = generation_config.eos_token_id;
+            // if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) {
+            //     eos_token_ids = [eos_token_ids];
+            // }
 
-        const scores = new Array(is_beam_search ? numInputs * num_beams : numInputs).fill(0);
-        /** @type {bigint[][]} */
-        const all_input_ids = input_ids.tolist();
+            const numInputs = model_inputs[model_input_name].dims.at(0);
+            const num_beams = generation_config.num_beams;
+            const num_beam_groups = generation_config.num_beam_groups;
+            const is_beam_search = num_beams > 1;
+            const is_group_beam_search = is_beam_search && num_beam_groups > 1;
+
+            const sequence_lengths = new Array(numInputs).fill(null);
+            let beam_history = Array.from({ length: numInputs * num_beams }, () => []);
+            const retained_attentions = new Set();
+            let returned_attentions = false;
+            let beam_scorer = null;
+            let beam_scorers = null;
+            /** @type {number[]} */
+            let beam_scores;
 
-        // Only copies created by this call are owned here; caller inputs survive.
-        const expanded_tensors = new Set();
-        const caller_cache = model_inputs.past_key_values;
-        let outputs;
-        try {
             if (is_beam_search) {
-                // Expand all_input_ids: [A, B] -> [A, A, A, B, B, B] for num_beams=3
-                const expanded_ids = [];
-                for (const ids of all_input_ids) {
-                    for (let b = 0; b < num_beams; ++b) {
-                        expanded_ids.push([...ids]);
-                    }
+                // Validate beam search configuration
+                if (generation_config.num_return_sequences > num_beams) {
+                    throw new Error(
+                        `num_return_sequences (${generation_config.num_return_sequences}) must be <= num_beams (${num_beams}).`,
+                    );
                 }
-                all_input_ids.length = 0;
-                all_input_ids.push(...expanded_ids);
-
-                // Expand model_inputs tensors by repeating each row num_beams times
-                const expanded_indices = [];
-                for (let i = 0; i < numInputs; ++i) {
-                    for (let b = 0; b < num_beams; ++b) {
-                        expanded_indices.push(i);
-                    }
+                if (num_beam_groups < 1) {
+                    throw new Error(`num_beam_groups must be >= 1, but got ${num_beam_groups}.`);
                 }
-                for (const key of [
-                    model_input_name,
-                    'attention_mask',
-                    'decoder_attention_mask',
-                    'encoder_outputs',
-                    'position_ids',
-                    'inputs_embeds',
-                ]) {
-                    const tensor = model_inputs[key];
-                    if (tensor instanceof Tensor) {
-                        if (tensor.location === 'cpu' || tensor.location === 'cpu-pinned') {
-                            model_inputs[key] = index_select(tensor, expanded_indices);
-                        } else {
-                            model_inputs[key] = await index_select_async(tensor, expanded_indices);
-                        }
-                        expanded_tensors.add(model_inputs[key]);
-                    }
+                if (num_beam_groups > num_beams) {
+                    throw new Error(`num_beam_groups (${num_beam_groups}) must be <= num_beams (${num_beams}).`);
                 }
-
-                if (model_inputs.past_key_values) {
-                    /** @type {Record} */
-                    const expanded_cache = {};
-                    for (const [key, tensor] of Object.entries(model_inputs.past_key_values)) {
-                        expanded_cache[key] = await index_select_async(
-                            tensor,
-                            this._get_cache_indices(key, expanded_indices),
-                        );
-                        expanded_tensors.add(expanded_cache[key]);
-                    }
-                    model_inputs.past_key_values = new DynamicCache(expanded_cache);
+                if (num_beams % num_beam_groups !== 0) {
+                    throw new Error(
+                        `num_beams (${num_beams}) must be divisible by num_beam_groups (${num_beam_groups}).`,
+                    );
+                }
+                if (is_group_beam_search && generation_config.do_sample) {
+                    throw new Error(
+                        'Diverse beam sampling (num_beam_groups > 1 with do_sample = true) is not yet supported.',
+                    );
+                }
+                if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {
+                    throw new Error('Classifier-free guidance (guidance_scale > 1) is not supported with beam search.');
+                }
+                if (streamer) {
+                    throw new Error('Streaming is not supported with beam search.');
                 }
 
-                // Initialize beam_scores: first beam of each input = 0, rest = -1e9
-                beam_scores = new Array(numInputs * num_beams).fill(-1e9);
-                for (let i = 0; i < numInputs; ++i) {
+                if (is_group_beam_search) {
                     const group_size = num_beams / num_beam_groups;
-                    for (let g = 0; g < num_beam_groups; ++g) {
-                        beam_scores[i * num_beams + g * group_size] = 0;
-                    }
+                    beam_scorers = Array.from(
+                        { length: num_beam_groups },
+                        () =>
+                            new BeamSearchScorer(numInputs, group_size, {
+                                length_penalty: generation_config.length_penalty,
+                                early_stopping: generation_config.early_stopping,
+                                num_return_sequences: group_size,
+                                eos_token_id: generation_config.eos_token_id,
+                                pad_token_id: generation_config.pad_token_id,
+                                decoder_prompt_len: input_ids_length,
+                                max_length: generation_config.max_length,
+                            }),
+                    );
+                } else {
+                    beam_scorer = new BeamSearchScorer(numInputs, num_beams, {
+                        length_penalty: generation_config.length_penalty,
+                        early_stopping: generation_config.early_stopping,
+                        num_return_sequences: generation_config.num_return_sequences,
+                        eos_token_id: generation_config.eos_token_id,
+                        pad_token_id: generation_config.pad_token_id,
+                        decoder_prompt_len: input_ids_length,
+                        max_length: generation_config.max_length,
+                    });
                 }
             }
 
-            if (streamer) {
-                streamer.put(all_input_ids);
-            }
+            const sampler = LogitsSampler.getSampler(generation_config);
 
-            ////////////////////////////////////////////////////
-            // Generic search which handles 4 generation modes:
-            // - GenerationMode.GREEDY_SEARCH
-            // - GenerationMode.SAMPLE
-            // - GenerationMode.BEAM_SEARCH
-            // - GenerationMode.BEAM_SAMPLE
-            ////////////////////////////////////////////////////
-            let attentions = {};
-            let return_dict_items = {};
-            while (true) {
-                // prepare model inputs
-                model_inputs = this.prepare_inputs_for_generation(all_input_ids, model_inputs, generation_config);
-                outputs = await this.forward(model_inputs);
+            const scores = new Array(is_beam_search ? numInputs * num_beams : numInputs).fill(0);
+            /** @type {bigint[][]} */
+            const all_input_ids = input_ids.tolist();
 
-                if (generation_config.return_dict_in_generate) {
-                    if (generation_config.output_attentions) {
-                        // Get attentions if they are present
-                        const token_attentions = getAttentions(outputs);
-                        for (const key in token_attentions) {
-                            if (!(key in attentions)) {
-                                attentions[key] = [];
+            // Only copies created by this call are owned here; caller inputs survive.
+            const expanded_tensors = new Set();
+            const caller_cache = model_inputs.past_key_values;
+            let outputs;
+            try {
+                if (is_beam_search) {
+                    // Expand all_input_ids: [A, B] -> [A, A, A, B, B, B] for num_beams=3
+                    const expanded_ids = [];
+                    for (const ids of all_input_ids) {
+                        for (let b = 0; b < num_beams; ++b) {
+                            expanded_ids.push([...ids]);
+                        }
+                    }
+                    all_input_ids.length = 0;
+                    all_input_ids.push(...expanded_ids);
+
+                    // Expand model_inputs tensors by repeating each row num_beams times
+                    const expanded_indices = [];
+                    for (let i = 0; i < numInputs; ++i) {
+                        for (let b = 0; b < num_beams; ++b) {
+                            expanded_indices.push(i);
+                        }
+                    }
+                    for (const key of [
+                        model_input_name,
+                        'attention_mask',
+                        'decoder_attention_mask',
+                        'encoder_outputs',
+                        'position_ids',
+                        'inputs_embeds',
+                    ]) {
+                        const tensor = model_inputs[key];
+                        if (tensor instanceof Tensor) {
+                            if (tensor.location === 'cpu' || tensor.location === 'cpu-pinned') {
+                                model_inputs[key] = index_select(tensor, expanded_indices);
+                            } else {
+                                model_inputs[key] = await index_select_async(tensor, expanded_indices);
                             }
-                            attentions[key].push(token_attentions[key]);
-                            for (const tensor of token_attentions[key]) retained_attentions.add(tensor);
+                            expanded_tensors.add(model_inputs[key]);
                         }
-                    } else if (this._return_dict_in_generate_keys) {
-                        Object.assign(return_dict_items, pick(outputs, this._return_dict_in_generate_keys));
                     }
-                }
 
-                // Logits are of the form [batch_size, out_seq_length, vocab_size]
-                // In most cases, this will be [batch_size, 1, vocab_size]
-                // So, we select the last token's logits:
-                // (equivalent to `logits = outputs.logits[:, -1, :]`)
-                // The `.to('float32')` is necessary for models with float16 logits,
-                // and is a no-op for float32 logits.
-                // TODO: Support float16 sampling in the sampler directly
-                const logits = outputs.logits.slice(null, -1, null).to('float32');
-
-                // Beam processors operate on log probabilities. Renormalizing after
-                // suppression would change the relative scores of different beams.
-                if (is_beam_search) {
-                    const vocab_size = logits.dims.at(-1);
-                    for (let i = 0; i < logits.dims[0]; ++i) {
-                        const offset = i * vocab_size;
-                        const data = /** @type {Float32Array} */ (logits.data);
-                        data.set(log_softmax(data.subarray(offset, offset + vocab_size)), offset);
+                    if (model_inputs.past_key_values) {
+                        /** @type {Record} */
+                        const expanded_cache = {};
+                        for (const [key, tensor] of Object.entries(model_inputs.past_key_values)) {
+                            expanded_cache[key] = await index_select_async(
+                                tensor,
+                                this._get_cache_indices(key, expanded_indices),
+                            );
+                            expanded_tensors.add(expanded_cache[key]);
+                        }
+                        model_inputs.past_key_values = new DynamicCache(expanded_cache);
+                    }
+
+                    // Initialize beam_scores: first beam of each input = 0, rest = -1e9
+                    beam_scores = new Array(numInputs * num_beams).fill(-1e9);
+                    for (let i = 0; i < numInputs; ++i) {
+                        const group_size = num_beams / num_beam_groups;
+                        for (let g = 0; g < num_beam_groups; ++g) {
+                            beam_scores[i * num_beams + g * group_size] = 0;
+                        }
                     }
                 }
-                const next_tokens_scores = prepared_logits_processor(all_input_ids, logits);
 
-                /** @type {[bigint][]} */
-                const generated_input_ids = [];
+                if (streamer) {
+                    streamer.put(all_input_ids);
+                }
 
-                if (is_beam_search) {
-                    // Beam search: retain enough candidates for active beams and all EOS ids.
-                    const vocab_size = next_tokens_scores.dims.at(-1);
-                    const total_beams = numInputs * num_beams;
-                    const eos_ids = generation_config.eos_token_id;
-                    const num_eos = eos_ids === null ? 0 : Array.isArray(eos_ids) ? eos_ids.length : 1;
-                    const candidates_per_beam = Math.max(2, 1 + num_eos);
-
-                    /** @type {number[]} */
-                    let next_beam_scores;
-                    /** @type {bigint[]} */
-                    let next_beam_tokens;
-                    /** @type {number[]} */
-                    let next_beam_indices;
+                ////////////////////////////////////////////////////
+                // Generic search which handles 4 generation modes:
+                // - GenerationMode.GREEDY_SEARCH
+                // - GenerationMode.SAMPLE
+                // - GenerationMode.BEAM_SEARCH
+                // - GenerationMode.BEAM_SAMPLE
+                ////////////////////////////////////////////////////
+                let attentions = {};
+                let return_dict_items = {};
+                while (true) {
+                    // prepare model inputs
+                    model_inputs = this.prepare_inputs_for_generation(all_input_ids, model_inputs, generation_config);
+                    outputs = await this.forward(model_inputs);
+
+                    if (generation_config.return_dict_in_generate) {
+                        if (generation_config.output_attentions) {
+                            // Get attentions if they are present
+                            const token_attentions = getAttentions(outputs);
+                            for (const key in token_attentions) {
+                                if (!(key in attentions)) {
+                                    attentions[key] = [];
+                                }
+                                attentions[key].push(token_attentions[key]);
+                                for (const tensor of token_attentions[key]) retained_attentions.add(tensor);
+                            }
+                        } else if (this._return_dict_in_generate_keys) {
+                            Object.assign(return_dict_items, pick(outputs, this._return_dict_in_generate_keys));
+                        }
+                    }
 
-                    if (is_group_beam_search) {
-                        const group_size = num_beams / num_beam_groups;
-                        next_beam_scores = new Array(total_beams).fill(0);
-                        next_beam_tokens = new Array(total_beams).fill(0n);
-                        next_beam_indices = new Array(total_beams).fill(0);
+                    // Logits are of the form [batch_size, out_seq_length, vocab_size]
+                    // In most cases, this will be [batch_size, 1, vocab_size]
+                    // So, we select the last token's logits:
+                    // (equivalent to `logits = outputs.logits[:, -1, :]`)
+                    // The `.to('float32')` is necessary for models with float16 logits,
+                    // and is a no-op for float32 logits.
+                    // TODO: Support float16 sampling in the sampler directly
+                    const logits = outputs.logits.slice(null, -1, null).to('float32');
+
+                    // Beam processors operate on log probabilities. Renormalizing after
+                    // suppression would change the relative scores of different beams.
+                    if (is_beam_search) {
+                        const vocab_size = logits.dims.at(-1);
+                        for (let i = 0; i < logits.dims[0]; ++i) {
+                            const offset = i * vocab_size;
+                            const data = /** @type {Float32Array} */ (logits.data);
+                            data.set(log_softmax(data.subarray(offset, offset + vocab_size)), offset);
+                        }
+                    }
+                    const next_tokens_scores = prepared_logits_processor(all_input_ids, logits);
+
+                    /** @type {[bigint][]} */
+                    const generated_input_ids = [];
+
+                    if (is_beam_search) {
+                        // Beam search: retain enough candidates for active beams and all EOS ids.
+                        const vocab_size = next_tokens_scores.dims.at(-1);
+                        const total_beams = numInputs * num_beams;
+                        const eos_ids = generation_config.eos_token_id;
+                        const num_eos = eos_ids === null ? 0 : Array.isArray(eos_ids) ? eos_ids.length : 1;
+                        const candidates_per_beam = Math.max(2, 1 + num_eos);
+
+                        /** @type {number[]} */
+                        let next_beam_scores;
+                        /** @type {bigint[]} */
+                        let next_beam_tokens;
+                        /** @type {number[]} */
+                        let next_beam_indices;
+
+                        if (is_group_beam_search) {
+                            const group_size = num_beams / num_beam_groups;
+                            next_beam_scores = new Array(total_beams).fill(0);
+                            next_beam_tokens = new Array(total_beams).fill(0n);
+                            next_beam_indices = new Array(total_beams).fill(0);
+
+                            const diversity_penalty = generation_config.diversity_penalty ?? 0;
+                            /** @type {Map[]} */
+                            const prev_group_tokens = Array.from({ length: numInputs }, () => new Map());
+
+                            for (let group_idx = 0; group_idx < num_beam_groups; ++group_idx) {
+                                const group_offset = group_idx * group_size;
+
+                                const group_all_input_ids = new Array(numInputs * group_size);
+                                const group_beam_scores = new Array(numInputs * group_size);
+                                for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
+                                    for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) {
+                                        const global = batch_idx * num_beams + group_offset + beam_idx;
+                                        const local = batch_idx * group_size + beam_idx;
+                                        group_all_input_ids[local] = all_input_ids[global];
+                                        group_beam_scores[local] = beam_scores[global];
+                                    }
+                                }
 
-                        const diversity_penalty = generation_config.diversity_penalty ?? 0;
-                        /** @type {Map[]} */
-                        const prev_group_tokens = Array.from({ length: numInputs }, () => new Map());
+                                const group_next_tokens = [];
+                                const group_next_indices = [];
+                                const group_next_scores = [];
+
+                                for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
+                                    // Collect candidates across all beams for this batch item
+                                    /** @type {{score: number, token: bigint, beam_idx: number}[]} */
+                                    const candidates = [];
+
+                                    for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) {
+                                        const flat_beam = batch_idx * num_beams + group_offset + beam_idx;
+                                        const logits_data = /** @type {Float32Array} */ (
+                                            next_tokens_scores[flat_beam].data
+                                        );
+                                        const log_probs = logits_data;
+                                        const beam_score = beam_scores[flat_beam];
+
+                                        candidates.push(
+                                            ...selectBeamCandidates(
+                                                log_probs,
+                                                beam_score,
+                                                beam_idx,
+                                                candidates_per_beam * group_size,
+                                                prev_group_tokens[batch_idx],
+                                                diversity_penalty,
+                                            ),
+                                        );
+                                    }
+
+                                    // Rank candidates across the group for this batch item.
+                                    candidates.sort((a, b) => b.score - a.score);
+                                    const top_candidates = candidates.slice(0, candidates_per_beam * group_size);
+
+                                    for (const c of top_candidates) {
+                                        group_next_tokens.push(c.token);
+                                        group_next_indices.push(c.beam_idx);
+                                        group_next_scores.push(c.score);
+                                    }
+                                }
 
-                        for (let group_idx = 0; group_idx < num_beam_groups; ++group_idx) {
-                            const group_offset = group_idx * group_size;
+                                // Let beam_scorer process: route EOS to hypotheses, select continuing beams
+                                const {
+                                    next_beam_scores: group_next_beam_scores,
+                                    next_beam_tokens: group_next_beam_tokens,
+                                    next_beam_indices: group_next_beam_indices,
+                                } = beam_scorers[group_idx].process(
+                                    group_all_input_ids,
+                                    group_beam_scores,
+                                    group_next_tokens,
+                                    group_next_indices,
+                                    group_next_scores,
+                                    Array.from(
+                                        { length: numInputs * group_size },
+                                        (_, i) =>
+                                            beam_history[
+                                                Math.floor(i / group_size) * num_beams + group_offset + (i % group_size)
+                                            ],
+                                    ),
+                                    Array.from(
+                                        { length: numInputs * group_size },
+                                        (_, i) =>
+                                            Math.floor(i / group_size) * num_beams + group_offset + (i % group_size),
+                                    ),
+                                );
+
+                                // Map group outputs into global beam arrays
+                                for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
+                                    for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) {
+                                        const global = batch_idx * num_beams + group_offset + beam_idx;
+                                        const local = batch_idx * group_size + beam_idx;
+                                        next_beam_scores[global] = group_next_beam_scores[local];
+                                        next_beam_tokens[global] = group_next_beam_tokens[local];
+                                        const local_source = group_next_beam_indices[local];
+                                        const source_in_batch = local_source - batch_idx * group_size;
+                                        next_beam_indices[global] =
+                                            batch_idx * num_beams + group_offset + source_in_batch;
+                                    }
+                                }
 
-                            const group_all_input_ids = new Array(numInputs * group_size);
-                            const group_beam_scores = new Array(numInputs * group_size);
-                            for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
-                                for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) {
-                                    const global = batch_idx * num_beams + group_offset + beam_idx;
-                                    const local = batch_idx * group_size + beam_idx;
-                                    group_all_input_ids[local] = all_input_ids[global];
-                                    group_beam_scores[local] = beam_scores[global];
+                                // Track tokens selected by this group for diversity penalty
+                                for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
+                                    const token_counts = prev_group_tokens[batch_idx];
+                                    for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) {
+                                        const global = batch_idx * num_beams + group_offset + beam_idx;
+                                        const token = next_beam_tokens[global];
+                                        token_counts.set(token, (token_counts.get(token) ?? 0) + 1);
+                                    }
                                 }
                             }
-
-                            const group_next_tokens = [];
-                            const group_next_indices = [];
-                            const group_next_scores = [];
+                        } else {
+                            const all_next_tokens = [];
+                            const all_next_indices = [];
+                            const all_next_scores = [];
+                            const do_beam_sample = generation_config.do_sample;
+                            const top_k = generation_config.top_k;
 
                             for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
                                 // Collect candidates across all beams for this batch item
                                 /** @type {{score: number, token: bigint, beam_idx: number}[]} */
                                 const candidates = [];
 
-                                for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) {
-                                    const flat_beam = batch_idx * num_beams + group_offset + beam_idx;
+                                for (let beam_idx = 0; beam_idx < num_beams; ++beam_idx) {
+                                    const flat_beam = batch_idx * num_beams + beam_idx;
                                     const logits_data = /** @type {Float32Array} */ (
                                         next_tokens_scores[flat_beam].data
                                     );
-                                    const log_probs = logits_data;
-                                    const beam_score = beam_scores[flat_beam];
-
-                                    candidates.push(
-                                        ...selectBeamCandidates(
-                                            log_probs,
-                                            beam_score,
-                                            beam_idx,
-                                            candidates_per_beam * group_size,
-                                            prev_group_tokens[batch_idx],
-                                            diversity_penalty,
-                                        ),
-                                    );
+                                    const count = do_beam_sample
+                                        ? top_k > 0
+                                            ? Math.max(top_k, candidates_per_beam * num_beams)
+                                            : vocab_size
+                                        : candidates_per_beam * num_beams;
+                                    for (const candidate of selectBeamCandidates(
+                                        logits_data,
+                                        beam_scores[flat_beam],
+                                        beam_idx,
+                                        count,
+                                    )) {
+                                        candidates.push(candidate);
+                                    }
                                 }
 
-                                // Rank candidates across the group for this batch item.
-                                candidates.sort((a, b) => b.score - a.score);
-                                const top_candidates = candidates.slice(0, candidates_per_beam * group_size);
+                                const count = Math.min(candidates_per_beam * num_beams, candidates.length);
+                                let top_candidates;
+                                if (do_beam_sample) {
+                                    // Sample across the joint beam/token distribution without
+                                    // replacement, retaining the original cumulative scores.
+                                    top_candidates = [];
+                                    for (let i = 0; i < count; ++i) {
+                                        const max_score = candidates.reduce(
+                                            (best, candidate) => Math.max(best, candidate.score),
+                                            -Infinity,
+                                        );
+                                        const probabilities = Float32Array.from(candidates, (candidate) =>
+                                            Math.exp(candidate.score - max_score),
+                                        );
+                                        const index = sampler.randomSelect(probabilities);
+                                        top_candidates.push(candidates.splice(index, 1)[0]);
+                                    }
+                                    top_candidates.sort((a, b) => b.score - a.score);
+                                } else {
+                                    candidates.sort((a, b) => b.score - a.score);
+                                    top_candidates = candidates.slice(0, count);
+                                }
 
                                 for (const c of top_candidates) {
-                                    group_next_tokens.push(c.token);
-                                    group_next_indices.push(c.beam_idx);
-                                    group_next_scores.push(c.score);
+                                    all_next_tokens.push(c.token);
+                                    all_next_indices.push(c.beam_idx);
+                                    all_next_scores.push(c.score);
                                 }
                             }
 
                             // Let beam_scorer process: route EOS to hypotheses, select continuing beams
-                            const {
-                                next_beam_scores: group_next_beam_scores,
-                                next_beam_tokens: group_next_beam_tokens,
-                                next_beam_indices: group_next_beam_indices,
-                            } = beam_scorers[group_idx].process(
-                                group_all_input_ids,
-                                group_beam_scores,
-                                group_next_tokens,
-                                group_next_indices,
-                                group_next_scores,
-                                Array.from(
-                                    { length: numInputs * group_size },
-                                    (_, i) =>
-                                        beam_history[
-                                            Math.floor(i / group_size) * num_beams + group_offset + (i % group_size)
-                                        ],
-                                ),
-                                Array.from(
-                                    { length: numInputs * group_size },
-                                    (_, i) => Math.floor(i / group_size) * num_beams + group_offset + (i % group_size),
-                                ),
-                            );
-
-                            // Map group outputs into global beam arrays
-                            for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
-                                for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) {
-                                    const global = batch_idx * num_beams + group_offset + beam_idx;
-                                    const local = batch_idx * group_size + beam_idx;
-                                    next_beam_scores[global] = group_next_beam_scores[local];
-                                    next_beam_tokens[global] = group_next_beam_tokens[local];
-                                    const local_source = group_next_beam_indices[local];
-                                    const source_in_batch = local_source - batch_idx * group_size;
-                                    next_beam_indices[global] = batch_idx * num_beams + group_offset + source_in_batch;
-                                }
-                            }
-
-                            // Track tokens selected by this group for diversity penalty
-                            for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
-                                const token_counts = prev_group_tokens[batch_idx];
-                                for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) {
-                                    const global = batch_idx * num_beams + group_offset + beam_idx;
-                                    const token = next_beam_tokens[global];
-                                    token_counts.set(token, (token_counts.get(token) ?? 0) + 1);
-                                }
-                            }
+                            ({ next_beam_scores, next_beam_tokens, next_beam_indices } = beam_scorer.process(
+                                all_input_ids,
+                                beam_scores,
+                                all_next_tokens,
+                                all_next_indices,
+                                all_next_scores,
+                                beam_history,
+                            ));
                         }
-                    } else {
-                        const all_next_tokens = [];
-                        const all_next_indices = [];
-                        const all_next_scores = [];
-                        const do_beam_sample = generation_config.do_sample;
-                        const top_k = generation_config.top_k;
 
-                        for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
-                            // Collect candidates across all beams for this batch item
-                            /** @type {{score: number, token: bigint, beam_idx: number}[]} */
-                            const candidates = [];
-
-                            for (let beam_idx = 0; beam_idx < num_beams; ++beam_idx) {
-                                const flat_beam = batch_idx * num_beams + beam_idx;
-                                const logits_data = /** @type {Float32Array} */ (next_tokens_scores[flat_beam].data);
-                                const count = do_beam_sample
-                                    ? top_k > 0
-                                        ? Math.max(top_k, candidates_per_beam * num_beams)
-                                        : vocab_size
-                                    : candidates_per_beam * num_beams;
-                                for (const candidate of selectBeamCandidates(
-                                    logits_data,
-                                    beam_scores[flat_beam],
-                                    beam_idx,
-                                    count,
-                                )) {
-                                    candidates.push(candidate);
-                                }
-                            }
+                        // Reorder all_input_ids based on beam indices and append new tokens
+                        beam_history = next_beam_indices.map((parent) => [...beam_history[parent], parent]);
+                        const new_all_input_ids = [];
+                        for (let i = 0; i < total_beams; ++i) {
+                            new_all_input_ids.push([...all_input_ids[next_beam_indices[i]], next_beam_tokens[i]]);
+                            generated_input_ids.push([next_beam_tokens[i]]);
+                        }
+                        all_input_ids.length = 0;
+                        all_input_ids.push(...new_all_input_ids);
 
-                            const count = Math.min(candidates_per_beam * num_beams, candidates.length);
-                            let top_candidates;
-                            if (do_beam_sample) {
-                                // Sample across the joint beam/token distribution without
-                                // replacement, retaining the original cumulative scores.
-                                top_candidates = [];
-                                for (let i = 0; i < count; ++i) {
-                                    const max_score = candidates.reduce(
-                                        (best, candidate) => Math.max(best, candidate.score),
-                                        -Infinity,
-                                    );
-                                    const probabilities = Float32Array.from(candidates, (candidate) =>
-                                        Math.exp(candidate.score - max_score),
-                                    );
-                                    const index = sampler.randomSelect(probabilities);
-                                    top_candidates.push(candidates.splice(index, 1)[0]);
-                                }
-                                top_candidates.sort((a, b) => b.score - a.score);
-                            } else {
-                                candidates.sort((a, b) => b.score - a.score);
-                                top_candidates = candidates.slice(0, count);
-                            }
+                        // Update beam scores
+                        for (let i = 0; i < total_beams; ++i) {
+                            beam_scores[i] = next_beam_scores[i];
+                        }
 
-                            for (const c of top_candidates) {
-                                all_next_tokens.push(c.token);
-                                all_next_indices.push(c.beam_idx);
-                                all_next_scores.push(c.score);
+                        // Reorder KV cache to match beam reordering
+                        model_inputs['past_key_values'] = await this._reorder_cache(
+                            getPastKeyValues(outputs, model_inputs.past_key_values),
+                            next_beam_indices,
+                        );
+                        // Reordering consumes the old cache, but merged decoders may
+                        // also return unused encoder-cache outputs. Release step-local
+                        // GPU scratch before the next forward overwrites `outputs`.
+                        const active_cache_tensors = new Set(Object.values(model_inputs.past_key_values));
+                        for (const tensor of Object.values(outputs)) {
+                            if (
+                                tensor.location === 'gpu-buffer' &&
+                                !active_cache_tensors.has(tensor) &&
+                                !retained_attentions.has(tensor)
+                            )
+                                tensor.dispose();
+                        }
+                    } else {
+                        // Greedy / sample: existing behavior
+                        for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) {
+                            const logs = next_tokens_scores[batch_idx];
+
+                            const sampledTokens = await sampler(logs);
+                            for (const [newTokenId, logProb] of sampledTokens) {
+                                const bigint = BigInt(newTokenId);
+                                scores[batch_idx] += logProb;
+                                all_input_ids[batch_idx].push(bigint);
+                                generated_input_ids.push([bigint]);
+                                break;
                             }
                         }
-
-                        // Let beam_scorer process: route EOS to hypotheses, select continuing beams
-                        ({ next_beam_scores, next_beam_tokens, next_beam_indices } = beam_scorer.process(
-                            all_input_ids,
-                            beam_scores,
-                            all_next_tokens,
-                            all_next_indices,
-                            all_next_scores,
-                            beam_history,
-                        ));
                     }
 
-                    // Reorder all_input_ids based on beam indices and append new tokens
-                    beam_history = next_beam_indices.map((parent) => [...beam_history[parent], parent]);
-                    const new_all_input_ids = [];
-                    for (let i = 0; i < total_beams; ++i) {
-                        new_all_input_ids.push([...all_input_ids[next_beam_indices[i]], next_beam_tokens[i]]);
-                        generated_input_ids.push([next_beam_tokens[i]]);
+                    if (streamer) {
+                        streamer.put(generated_input_ids);
                     }
-                    all_input_ids.length = 0;
-                    all_input_ids.push(...new_all_input_ids);
 
-                    // Update beam scores
-                    for (let i = 0; i < total_beams; ++i) {
-                        beam_scores[i] = next_beam_scores[i];
-                    }
-
-                    // Reorder KV cache to match beam reordering
-                    model_inputs['past_key_values'] = await this._reorder_cache(
-                        getPastKeyValues(outputs, model_inputs.past_key_values),
-                        next_beam_indices,
-                    );
-                    // Reordering consumes the old cache, but merged decoders may
-                    // also return unused encoder-cache outputs. Release step-local
-                    // GPU scratch before the next forward overwrites `outputs`.
-                    const active_cache_tensors = new Set(Object.values(model_inputs.past_key_values));
-                    for (const tensor of Object.values(outputs)) {
-                        if (
-                            tensor.location === 'gpu-buffer' &&
-                            !active_cache_tensors.has(tensor) &&
-                            !retained_attentions.has(tensor)
-                        )
-                            tensor.dispose();
-                    }
-                } else {
-                    // Greedy / sample: existing behavior
-                    for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) {
-                        const logs = next_tokens_scores[batch_idx];
-
-                        const sampledTokens = await sampler(logs);
-                        for (const [newTokenId, logProb] of sampledTokens) {
-                            const bigint = BigInt(newTokenId);
-                            scores[batch_idx] += logProb;
-                            all_input_ids[batch_idx].push(bigint);
-                            generated_input_ids.push([bigint]);
+                    // Check stopping conditions
+                    if (is_beam_search) {
+                        const done = is_group_beam_search
+                            ? beam_scorers.every((scorer) => scorer.is_done)
+                            : beam_scorer.is_done;
+                        if (done) {
                             break;
                         }
                     }
-                }
-
-                if (streamer) {
-                    streamer.put(generated_input_ids);
-                }
-
-                // Check stopping conditions
-                if (is_beam_search) {
-                    const done = is_group_beam_search
-                        ? beam_scorers.every((scorer) => scorer.is_done)
-                        : beam_scorer.is_done;
-                    if (done) {
+                    const stop = prepared_stopping_criteria(all_input_ids);
+                    if (!is_beam_search)
+                        for (let i = 0; i < stop.length; ++i) {
+                            if (stop[i] && sequence_lengths[i] === null) sequence_lengths[i] = all_input_ids[i].length;
+                        }
+                    if (stop.every((x) => x)) {
                         break;
                     }
-                }
-                const stop = prepared_stopping_criteria(all_input_ids);
-                if (!is_beam_search)
-                    for (let i = 0; i < stop.length; ++i) {
-                        if (stop[i] && sequence_lengths[i] === null) sequence_lengths[i] = all_input_ids[i].length;
-                    }
-                if (stop.every((x) => x)) {
-                    break;
-                }
-
-                if (is_beam_search) {
-                    // For beam search, we already updated past_key_values during reordering.
-                    // Now update the remaining model inputs.
-                    model_inputs['input_ids'] = new Tensor('int64', generated_input_ids.flat(), [
-                        generated_input_ids.length,
-                        1,
-                    ]);
 
-                    if (!is_encoder_decoder) {
-                        model_inputs.attention_mask = cat(
-                            [model_inputs.attention_mask, ones([model_inputs.attention_mask.dims[0], 1])],
+                    if (is_beam_search) {
+                        // For beam search, we already updated past_key_values during reordering.
+                        // Now update the remaining model inputs.
+                        model_inputs['input_ids'] = new Tensor('int64', generated_input_ids.flat(), [
+                            generated_input_ids.length,
                             1,
-                        );
-                    } else if ('decoder_attention_mask' in model_inputs) {
-                        model_inputs.decoder_attention_mask = cat(
-                            [
-                                model_inputs.decoder_attention_mask,
-                                ones([model_inputs.decoder_attention_mask.dims[0], 1]),
-                            ],
-                            1,
-                        );
+                        ]);
+
+                        if (!is_encoder_decoder) {
+                            model_inputs.attention_mask = cat(
+                                [model_inputs.attention_mask, ones([model_inputs.attention_mask.dims[0], 1])],
+                                1,
+                            );
+                        } else if ('decoder_attention_mask' in model_inputs) {
+                            model_inputs.decoder_attention_mask = cat(
+                                [
+                                    model_inputs.decoder_attention_mask,
+                                    ones([model_inputs.decoder_attention_mask.dims[0], 1]),
+                                ],
+                                1,
+                            );
+                        }
+
+                        // Force recreate position_ids in next iteration
+                        model_inputs['position_ids'] = null;
+                    } else {
+                        model_inputs = this._update_model_kwargs_for_generation({
+                            generated_input_ids,
+                            outputs,
+                            model_inputs,
+                            is_encoder_decoder,
+                        });
                     }
+                }
 
-                    // Force recreate position_ids in next iteration
-                    model_inputs['position_ids'] = null;
-                } else {
-                    model_inputs = this._update_model_kwargs_for_generation({
-                        generated_input_ids,
-                        outputs,
-                        model_inputs,
-                        is_encoder_decoder,
-                    });
+                if (streamer) {
+                    streamer.end();
                 }
-            }
 
-            if (streamer) {
-                streamer.end();
-            }
+                let sequences;
+                let selected_hypotheses = [];
+                if (is_beam_search) {
+                    /** @type {bigint[][]} */
+                    let best_sequences;
+                    if (is_group_beam_search) {
+                        const group_size = num_beams / num_beam_groups;
+                        /** @type {{tokens: bigint[], score: number}[][]} */
+                        const grouped = Array.from({ length: numInputs }, () => []);
 
-            let sequences;
-            let selected_hypotheses = [];
-            if (is_beam_search) {
-                /** @type {bigint[][]} */
-                let best_sequences;
-                if (is_group_beam_search) {
-                    const group_size = num_beams / num_beam_groups;
-                    /** @type {{tokens: bigint[], score: number}[][]} */
-                    const grouped = Array.from({ length: numInputs }, () => []);
+                        for (let group_idx = 0; group_idx < num_beam_groups; ++group_idx) {
+                            const group_offset = group_idx * group_size;
+                            const group_all_input_ids = new Array(numInputs * group_size);
+                            const group_beam_scores = new Array(numInputs * group_size);
 
-                    for (let group_idx = 0; group_idx < num_beam_groups; ++group_idx) {
-                        const group_offset = group_idx * group_size;
-                        const group_all_input_ids = new Array(numInputs * group_size);
-                        const group_beam_scores = new Array(numInputs * group_size);
+                            for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
+                                for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) {
+                                    const global = batch_idx * num_beams + group_offset + beam_idx;
+                                    const local = batch_idx * group_size + beam_idx;
+                                    group_all_input_ids[local] = all_input_ids[global];
+                                    group_beam_scores[local] = beam_scores[global];
+                                }
+                            }
 
-                        for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
-                            for (let beam_idx = 0; beam_idx < group_size; ++beam_idx) {
-                                const global = batch_idx * num_beams + group_offset + beam_idx;
-                                const local = batch_idx * group_size + beam_idx;
-                                group_all_input_ids[local] = all_input_ids[global];
-                                group_beam_scores[local] = beam_scores[global];
+                            const group_results = beam_scorers[group_idx].finalize_with_scores(
+                                group_all_input_ids,
+                                group_beam_scores,
+                                Array.from(
+                                    { length: numInputs * group_size },
+                                    (_, i) =>
+                                        beam_history[
+                                            Math.floor(i / group_size) * num_beams + group_offset + (i % group_size)
+                                        ],
+                                ),
+                            );
+
+                            for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
+                                const offset = batch_idx * group_size;
+                                for (let i = 0; i < group_size; ++i) {
+                                    grouped[batch_idx].push(group_results[offset + i]);
+                                }
                             }
                         }
 
-                        const group_results = beam_scorers[group_idx].finalize_with_scores(
-                            group_all_input_ids,
-                            group_beam_scores,
-                            Array.from(
-                                { length: numInputs * group_size },
-                                (_, i) =>
-                                    beam_history[
-                                        Math.floor(i / group_size) * num_beams + group_offset + (i % group_size)
-                                    ],
-                            ),
-                        );
-
+                        best_sequences = [];
                         for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
-                            const offset = batch_idx * group_size;
-                            for (let i = 0; i < group_size; ++i) {
-                                grouped[batch_idx].push(group_results[offset + i]);
+                            const sorted = grouped[batch_idx].sort((a, b) => b.score - a.score);
+                            for (let i = 0; i < generation_config.num_return_sequences; ++i) {
+                                best_sequences.push(sorted[i].tokens);
+                                selected_hypotheses.push(sorted[i]);
                             }
                         }
+                    } else {
+                        // Finalize beam search: select best hypotheses
+                        selected_hypotheses = beam_scorer.finalize_with_scores(
+                            all_input_ids,
+                            beam_scores,
+                            beam_history,
+                        );
+                        best_sequences = selected_hypotheses.map((x) => x.tokens);
                     }
 
-                    best_sequences = [];
-                    for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) {
-                        const sorted = grouped[batch_idx].sort((a, b) => b.score - a.score);
-                        for (let i = 0; i < generation_config.num_return_sequences; ++i) {
-                            best_sequences.push(sorted[i].tokens);
-                            selected_hypotheses.push(sorted[i]);
-                        }
-                    }
+                    // Pad sequences to equal length for tensor creation
+                    const max_len = Math.max(...best_sequences.map((s) => s.length));
+                    const pad_id = BigInt(generation_config.pad_token_id ?? 0);
+                    const padded = best_sequences.map((s) => {
+                        const p = [...s];
+                        while (p.length < max_len) p.push(pad_id);
+                        return p;
+                    });
+                    sequences = new Tensor('int64', padded.flat(), [padded.length, max_len]);
                 } else {
-                    // Finalize beam search: select best hypotheses
-                    selected_hypotheses = beam_scorer.finalize_with_scores(all_input_ids, beam_scores, beam_history);
-                    best_sequences = selected_hypotheses.map((x) => x.tokens);
+                    // TODO: ensure all_input_ids is padded correctly...
+                    sequences = new Tensor('int64', all_input_ids.flat(), [
+                        all_input_ids.length,
+                        all_input_ids[0].length,
+                    ]);
                 }
 
-                // Pad sequences to equal length for tensor creation
-                const max_len = Math.max(...best_sequences.map((s) => s.length));
-                const pad_id = BigInt(generation_config.pad_token_id ?? 0);
-                const padded = best_sequences.map((s) => {
-                    const p = [...s];
-                    while (p.length < max_len) p.push(pad_id);
-                    return p;
-                });
-                sequences = new Tensor('int64', padded.flat(), [padded.length, max_len]);
-            } else {
-                // TODO: ensure all_input_ids is padded correctly...
-                sequences = new Tensor('int64', all_input_ids.flat(), [all_input_ids.length, all_input_ids[0].length]);
-            }
+                // Beam search already extracted and reordered the final cache. Do not restore
+                // the original output tensors, which may have been disposed during reordering.
+                const past_key_values = is_beam_search
+                    ? model_inputs.past_key_values
+                    : getPastKeyValues(outputs, model_inputs.past_key_values);
 
-            // Beam search already extracted and reordered the final cache. Do not restore
-            // the original output tensors, which may have been disposed during reordering.
-            const past_key_values = is_beam_search
-                ? model_inputs.past_key_values
-                : getPastKeyValues(outputs, model_inputs.past_key_values);
-
-            // Dispose output tensors not held by the cache
-            const cachedTensors = new Set(Object.values(past_key_values));
-            for (const tensor of Object.values(outputs)) {
-                if (
-                    tensor.location === 'gpu-buffer' &&
-                    !cachedTensors.has(tensor) &&
-                    !retained_attentions.has(tensor)
-                ) {
-                    tensor.dispose();
+                // Dispose output tensors not held by the cache
+                const cachedTensors = new Set(Object.values(past_key_values));
+                for (const tensor of Object.values(outputs)) {
+                    if (
+                        tensor.location === 'gpu-buffer' &&
+                        !cachedTensors.has(tensor) &&
+                        !retained_attentions.has(tensor)
+                    ) {
+                        tensor.dispose();
+                    }
                 }
-            }
 
-            // Dispose cache tensors if no one needs them
-            const keepCacheAlive =
-                !is_beam_search && ('past_key_values' in kwargs || generation_config.return_dict_in_generate);
-            if (!keepCacheAlive) {
-                await past_key_values.dispose();
-            }
+                // Dispose cache tensors if no one needs them
+                const keepCacheAlive =
+                    !is_beam_search && ('past_key_values' in kwargs || generation_config.return_dict_in_generate);
+                if (!keepCacheAlive) {
+                    await past_key_values.dispose();
+                }
 
-            if (generation_config.return_dict_in_generate) {
-                const past_key_values_for_return = is_beam_search ? null : past_key_values;
+                if (generation_config.return_dict_in_generate) {
+                    const past_key_values_for_return = is_beam_search ? null : past_key_values;
+                    if (is_beam_search) {
+                        const width = sequences.dims[1];
+                        // Ancestry starts at column zero (the first generated token),
+                        // independent of prefix length. Unused columns are -1.
+                        return_dict_items.beam_indices = new Tensor(
+                            'int64',
+                            selected_hypotheses.flatMap((x) => [
+                                ...x.beam_indices.map(BigInt),
+                                ...Array(width - x.beam_indices.length).fill(-1n),
+                            ]),
+                            sequences.dims,
+                        );
+                        return_dict_items.sequence_lengths = new Tensor(
+                            'int64',
+                            selected_hypotheses.map((x) => BigInt(x.tokens.length)),
+                            [selected_hypotheses.length],
+                        );
+                    }
+                    if (!is_beam_search)
+                        return_dict_items.sequence_lengths = new Tensor(
+                            'int64',
+                            all_input_ids.map((ids, i) => BigInt(sequence_lengths[i] ?? ids.length)),
+                            [all_input_ids.length],
+                        );
+                    returned_attentions = true;
+                    return {
+                        sequences,
+                        past_key_values: past_key_values_for_return,
+                        ...attentions,
+                        ...return_dict_items,
+                    };
+                }
+                return sequences;
+            } finally {
+                if (!returned_attentions) for (const tensor of retained_attentions) tensor.dispose();
                 if (is_beam_search) {
-                    const width = sequences.dims[1];
-                    // Ancestry starts at column zero (the first generated token),
-                    // independent of prefix length. Unused columns are -1.
-                    return_dict_items.beam_indices = new Tensor(
-                        'int64',
-                        selected_hypotheses.flatMap((x) => [
-                            ...x.beam_indices.map(BigInt),
-                            ...Array(width - x.beam_indices.length).fill(-1n),
-                        ]),
-                        sequences.dims,
-                    );
-                    return_dict_items.sequence_lengths = new Tensor(
-                        'int64',
-                        selected_hypotheses.map((x) => BigInt(x.tokens.length)),
-                        [selected_hypotheses.length],
-                    );
+                    // Also run on forward/processor/reorder failures and partial expansion.
+                    const owned = new Set(expanded_tensors);
+                    if (model_inputs.past_key_values !== caller_cache) {
+                        for (const tensor of Object.values(model_inputs.past_key_values ?? {})) owned.add(tensor);
+                    }
+                    for (const tensor of Object.values(outputs ?? {})) owned.add(tensor);
+                    for (const tensor of owned) {
+                        if (
+                            !retained_attentions.has(tensor) &&
+                            (expanded_tensors.has(tensor) || tensor.location === 'gpu-buffer')
+                        )
+                            tensor.dispose();
+                    }
+                    if (model_inputs.past_key_values !== caller_cache) {
+                        await model_inputs.past_key_values?.dispose();
+                    }
                 }
-                if (!is_beam_search)
-                    return_dict_items.sequence_lengths = new Tensor(
-                        'int64',
-                        all_input_ids.map((ids, i) => BigInt(sequence_lengths[i] ?? ids.length)),
-                        [all_input_ids.length],
-                    );
-                returned_attentions = true;
-                return {
-                    sequences,
-                    past_key_values: past_key_values_for_return,
-                    ...attentions,
-                    ...return_dict_items,
-                };
             }
-            return sequences;
         } finally {
             owned_encoder_output?.dispose();
-            if (!returned_attentions) for (const tensor of retained_attentions) tensor.dispose();
-            if (is_beam_search) {
-                // Also run on forward/processor/reorder failures and partial expansion.
-                const owned = new Set(expanded_tensors);
-                if (model_inputs.past_key_values !== caller_cache) {
-                    for (const tensor of Object.values(model_inputs.past_key_values ?? {})) owned.add(tensor);
-                }
-                for (const tensor of Object.values(outputs ?? {})) owned.add(tensor);
-                for (const tensor of owned) {
-                    if (
-                        !retained_attentions.has(tensor) &&
-                        (expanded_tensors.has(tensor) || tensor.location === 'gpu-buffer')
-                    )
-                        tensor.dispose();
-                }
-                if (model_inputs.past_key_values !== caller_cache) {
-                    await model_inputs.past_key_values?.dispose();
-                }
-            }
         }
     }
 
diff --git a/packages/transformers/src/models/whisper/modeling_whisper.js b/packages/transformers/src/models/whisper/modeling_whisper.js
index ded039f52..5d8f6afd4 100644
--- a/packages/transformers/src/models/whisper/modeling_whisper.js
+++ b/packages/transformers/src/models/whisper/modeling_whisper.js
@@ -509,44 +509,42 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
             const frames = Math.min(steps[0][alignment_heads[0][0]].dims[3], requestedFrames ?? Infinity);
             if (!Number.isInteger(frames) || frames <= 0)
                 throw new Error('Timestamp encoder frame count must be positive.');
-            const prefixQueries = steps[0][alignment_heads[0][0]].dims[2];
-            const validQueries = prefixQueries + queries;
             const matrix = Array.from({ length: queries }, () => new Float32Array(frames));
             for (const [layer, head] of alignment_heads) {
                 const weights = [];
-                for (let token = 0; token < validQueries; ++token) {
-                    const step = token < prefixQueries ? 0 : token - prefixQueries + 1;
+                for (let token = 0; token < queries; ++token) {
+                    const step = token + 1;
                     const source = steps[step]?.[layer];
                     if (!source || head >= source.dims[1])
                         throw new Error('Missing timestamp alignment attention head or step.');
                     const row = ancestry ? Number(ancestry[result][step]) : result;
                     if (row < 0 || row >= source.dims[0]) throw new Error('Invalid timestamp beam ancestry.');
-                    const numeric = source.to('float32');
-                    // Cached decoders expose one query; uncached decoders expose the
-                    // complete history, whose final query is the preceding token.
+                    // Convert only the selected row/head/query and valid frames, rather
+                    // than all beam rows and heads for every selected hypothesis.
                     const offset =
-                        ((row * source.dims[1] + head) * source.dims[2] + (step === 0 ? token : source.dims[2] - 1)) *
-                        source.dims[3];
-                    weights.push(Float32Array.from(numeric.data.slice(offset, offset + frames)));
-                    if (numeric !== source) numeric.dispose();
+                        ((row * source.dims[1] + head) * source.dims[2] + source.dims[2] - 1) * source.dims[3];
+                    const selected = new Tensor(source.type, source.data.slice(offset, offset + frames), [frames]);
+                    const numeric = selected.to('float32');
+                    weights.push(Float32Array.from(numeric.data));
+                    if (numeric !== selected) numeric.dispose();
+                    selected.dispose();
                 }
-                // Crop the selected hypothesis before computing statistics: other
-                // beams and padding must not affect normalization. Valid prefix queries
-                // participate in normalization, matching Whisper, but not in DTW.
+                // Exclude prefix queries, other beams, and padding before statistics,
+                // matching Transformers v4.57.1 Whisper alignment.
                 for (let frame = 0; frame < frames; ++frame) {
                     let average = 0;
-                    for (const row of weights) average += row[frame] / validQueries;
+                    for (const row of weights) average += row[frame] / queries;
                     let variance = 0;
-                    for (const row of weights) variance += (row[frame] - average) ** 2 / validQueries;
+                    for (const row of weights) variance += (row[frame] - average) ** 2 / queries;
                     const scale = Math.sqrt(variance);
                     for (const row of weights) row[frame] = scale > 0 ? (row[frame] - average) / scale : 0;
                 }
                 for (let token = 0; token < queries; ++token) {
-                    // A cropped recording can be shorter than the configured reflection window.
-                    const filtered = medianFilter(
-                        weights[prefixQueries + token],
-                        Math.min(median_filter_width, 2 * frames - 1),
-                    );
+                    // Python leaves recordings too short for reflection padding unchanged.
+                    const filtered =
+                        frames <= Math.floor(median_filter_width / 2)
+                            ? weights[token]
+                            : medianFilter(weights[token], median_filter_width);
                     for (let frame = 0; frame < frames; ++frame)
                         matrix[token][frame] -= filtered[frame] / alignment_heads.length;
                 }
diff --git a/packages/transformers/tests/utils/beam_ownership.test.js b/packages/transformers/tests/utils/beam_ownership.test.js
index a27cd37b1..4d70dd862 100644
--- a/packages/transformers/tests/utils/beam_ownership.test.js
+++ b/packages/transformers/tests/utils/beam_ownership.test.js
@@ -175,6 +175,20 @@ describe("Beam resource ownership", () => {
     expect(allocated.every((buffer) => buffer.destroyed)).toBe(true);
   });
 
+  it.each(["beam validation", "processor preparation"])("releases encoded output after %s fails", async (failure) => {
+    const model = modelWith();
+    let destroyed = 0;
+    const encoded = gpu([1, 1, 4], { dispose: () => ++destroyed });
+    model.config.is_encoder_decoder = true;
+    model._prepare_encoder_decoder_kwargs_for_generation = async ({ model_inputs }) => ({ ...model_inputs, encoder_outputs: encoded });
+    if (failure === "processor preparation")
+      model._get_logits_processor = () => {
+        throw Error("injected processor failure");
+      };
+    await expect(model.generate({ num_beams: 2, num_return_sequences: 3, max_new_tokens: 1, decoder_start_token_id: 1 })).rejects.toThrow(failure === "beam validation" ? "must be <= num_beams" : "injected processor failure");
+    expect(destroyed).toBe(1);
+  });
+
   it("releases unused GPU step outputs before the next forward", async () => {
     const model = modelWith();
     let calls = 0,
diff --git a/packages/transformers/tests/utils/whisper_beam_timestamps.test.js b/packages/transformers/tests/utils/whisper_beam_timestamps.test.js
index 1e7dd6071..a927fc9fe 100644
--- a/packages/transformers/tests/utils/whisper_beam_timestamps.test.js
+++ b/packages/transformers/tests/utils/whisper_beam_timestamps.test.js
@@ -161,3 +161,47 @@ it("expands an explicitly supplied flat prefix across the short-form batch", asy
     forward.mockRestore();
   }
 });
+
+// Pinned Python Transformers v4.57.1 reference: prefix is cropped before
+// population mean/std, median smoothing, head averaging and DTW.
+const referenceFixture = (frames = 6) => {
+  let seed = 1234;
+  const rows = Array.from({ length: 5 }, () =>
+    Float32Array.from({ length: frames }, () => {
+      seed = (1664525 * seed + 1013904223) >>> 0;
+      return seed / 2 ** 32;
+    }),
+  );
+  return {
+    sequences: new Tensor("int64", [9n, 8n, 1n, 2n, 3n, 0n], [1, 6]),
+    cross_attentions: [[new Tensor("float32", Float32Array.from([...rows[0], ...rows[1]]), [1, 1, 2, frames])], ...rows.slice(2).map((row) => [new Tensor("float32", row, [1, 1, 1, frames])])],
+  };
+};
+it("matches the pinned Python alignment reference and ignores prefix values", () => {
+  const output = referenceFixture();
+  const expected = [[0, 0, 0, 0, Math.fround(0.04), Math.fround(0.04)]];
+  expect(extract(output).tolist()).toEqual(expected);
+  output.cross_attentions[0][0].data.fill(100000);
+  expect(extract(output).tolist()).toEqual(expected);
+});
+it.each([2, 3])("does not median-filter %s frames with a seven-frame window", (frames) => {
+  const output = referenceFixture(frames);
+  const filtered = WhisperForConditionalGeneration.prototype._extract_token_timestamps.call({ config: { median_filter_width: 7 } }, output, [[0, 0]], frames, 0.02, 2);
+  expect(filtered.tolist()).toEqual(extract(output, frames).tolist());
+});
+it("converts only selected fp16 attention elements", () => {
+  const output = referenceFixture();
+  output.cross_attentions = output.cross_attentions.map((step) => step.map((t) => new Tensor("float16", new Uint16Array(4 * 3 * t.dims[2] * 6).fill(0x3c00), [4, 3, t.dims[2], 6])));
+  let elements = 0;
+  const original = Tensor.prototype.to;
+  const spy = jest.spyOn(Tensor.prototype, "to").mockImplementation(function (type) {
+    if (this.type === "float16" && type === "float32") elements += this.data.length;
+    return original.call(this, type);
+  });
+  try {
+    expect(extract(output).data.every(Number.isFinite)).toBe(true);
+    expect(elements).toBe(3 * 6);
+  } finally {
+    spy.mockRestore();
+  }
+});
diff --git a/scripts/beam-timestamps/README.md b/scripts/beam-timestamps/README.md
index d160ff656..fd917d630 100644
--- a/scripts/beam-timestamps/README.md
+++ b/scripts/beam-timestamps/README.md
@@ -10,7 +10,7 @@ With `return_dict_in_generate`, beam generation returns:
 - `beam_indices`: int64 `[returned_sequences, padded_sequence_length]`. Column **zero means the first generated token**, not the first prefix token. Each entry identifies the parent forward row for that step, including the step selecting EOS. Unused columns are `-1`.
 - `sequence_lengths`: int64 valid lengths including prefix and EOS. Padding is not aligned.
 
-Whisper reconstructs the selected ancestry before computing statistics. First-forward prefix queries participate in normalization, but are excluded from DTW. Later forwards contribute the final query (the preceding generated token), for cached and uncached decoders. The final generated token has no query and repeats the last aligned boundary; padding timestamps are zero. fp16 storage is numerically converted to fp32. Constant variance produces zero normalized weights. The median window is bounded to the valid cropped recording; the general median-filter implementation is unchanged.
+Whisper reconstructs the selected ancestry before computing statistics. First-forward prefix queries are excluded before normalization and DTW, matching Python Transformers v4.57.1. Later forwards contribute the final query (the preceding generated token), for cached and uncached decoders. The final generated token has no query and repeats the last aligned boundary; padding timestamps are zero. fp16 storage is numerically converted to fp32. Constant variance produces zero normalized weights. Recordings with at most half the median window in frames skip median filtering, matching Python; the general median-filter implementation is unchanged.
 
 Public `num_frames` is a mel-frame count (10 ms), scalar or per input. Alignment uses `floor(num_frames / 2)` encoder frames (20 ms). Short-form batch and multiple returns are supported with `max_new_tokens`. Seek mode supports one input and one return; other combinations fail before encoding. Seek mode currently rejects explicit public attention output because its concatenated transcript does not have a single encoder/attention time axis. Internal seek attentions are released after alignment.
 
@@ -30,7 +30,7 @@ node scripts/beam-timestamps/native.mjs '{"device":"cpu","dtype":"fp32","batch":
 node scripts/beam-timestamps/native.mjs '{"device":"cpu","dtype":"fp32","returns":2,"repeats":3}' > scripts/beam-timestamps/results/native-single.json
 node scripts/beam-timestamps/native.mjs '{"device":"cpu","dtype":"fp32","batch":true,"returns":2,"beams":4,"groups":2,"publicAttentions":true,"repeats":25}' > scripts/beam-timestamps/results/native-diverse.json
 node scripts/beam-timestamps/native.mjs '{"device":"cpu","dtype":"fp32","long":true,"repeats":3}' > scripts/beam-timestamps/results/native-long.json
-node scripts/beam-timestamps/verify-results.mjs
+node scripts/beam-timestamps/verify-results.mjs "$(git rev-parse HEAD)"
 ```
 
 `TIMESTAMP_AUDIO` can point to the pinned WAV. `TIMESTAMP_CACHE` sets a cache directory; default is branch-local `model-cache/`. Never copy the parent's model cache. `offline-tests.js` provides read-only shared-cache use for the test suite when `TRANSFORMERS_SHARED_CACHE` is set (remote model loading disabled).
@@ -50,3 +50,7 @@ Same-backend/dtype batch vs independent comparison requires exact tokens, order,
 Read-only metadata checked for PR1755 (attention/encoder memory), PR1742 (seek/logits regression), and PR1797 (oversized median reflection). This branch necessarily intersects attention and encoder ownership in PR1755. Its beam-loop cleanup also releases unused GPU step outputs before the next forward; it does not copy the general getPastKeyValues patch. It does not import the logits fix or general reflection patch. Invalid seek advancement fails explicitly instead of hanging.
 
 Parent owns hardware validation and both postimplementation review rounds. CPU results and synthetic GPU ownership boundaries are not AMD/NVIDIA execution proof. Full suite, Python alignment parity, browser WASM, hardware cells, and full allocation accounting must be reported individually; no final-readiness claim follows from this harness.
+
+Internal attention instrumentation reports peak live attention bytes and verifies zero remaining tracked bytes after each call, including timestamp-only mode. This is tensor-lifetime accounting, not the driver's allocator high-water mark or total KV/model memory. Explicit public attention histories remain caller-owned. Timestamp-only calls currently retain complete histories too; large models, beam counts and long generations need separate memory admission measurements. fp16 alignment converts only the selected head/row/query frame range.
+
+The verifier requires an immutable full source SHA, clean-checkout provenance, and matching source hashes for every result; stale evidence fails closed. CPU fixture results are not independent Python parity or hardware execution proof. The deterministic numerical regression uses Python Transformers v4.57.1's prefix cropping and short-median-window semantics.
diff --git a/scripts/beam-timestamps/harness.mjs b/scripts/beam-timestamps/harness.mjs
index 4eaf785f9..a4e8385ca 100644
--- a/scripts/beam-timestamps/harness.mjs
+++ b/scripts/beam-timestamps/harness.mjs
@@ -78,10 +78,37 @@ export async function run(
     num_frames: Math.floor(samples.length / 160),
     ...(long ? {} : { max_new_tokens: 64 }),
   };
+  // Instrument actual internal attention lifetime, including timestamp-only calls.
+  // This measures attention allocations, not total ORT/GPU allocator residency.
+  const liveAttentions = new Map();
+  let liveAttentionBytes = 0,
+    peakAttentionBytes = 0;
+  const originalDispose = Tensor.prototype.dispose;
+  Tensor.prototype.dispose = function (...args) {
+    const bytes = liveAttentions.get(this);
+    if (bytes !== undefined) {
+      liveAttentionBytes -= bytes;
+      liveAttentions.delete(this);
+    }
+    return originalDispose.apply(this, args);
+  };
+  const originalForward = model.forward;
+  model.forward = async function (...args) {
+    const result = await originalForward.apply(this, args);
+    for (const [name, tensor] of Object.entries(result)) {
+      if (!/^(cross|decoder|encoder)_attentions/.test(name) || liveAttentions.has(tensor)) continue;
+      const bytes = tensor.dims.reduce((a, b) => a * b, 1) * ({ float16: 2, float32: 4, float64: 8 }[tensor.type] ?? 4);
+      liveAttentions.set(tensor, bytes);
+      liveAttentionBytes += bytes;
+      peakAttentionBytes = Math.max(peakAttentionBytes, liveAttentionBytes);
+    }
+    return result;
+  };
   const timings = [],
     outputs = [];
   try {
     for (let iteration = -1; iteration < repeats; ++iteration) {
+      peakAttentionBytes = liveAttentionBytes;
       const start = performance.now();
       const result = await model.generate(options);
       const elapsed = performance.now() - start;
@@ -92,6 +119,7 @@ export async function run(
         beam_indices: result.beam_indices?.tolist().map((row) => row.map(Number)),
         lengths: result.sequence_lengths?.tolist().map(Number),
         retainedAttentionBytes: 0,
+        peakInternalAttentionBytes: peakAttentionBytes,
       };
       for (const key of ["cross_attentions", "decoder_attentions", "encoder_attentions"])
         for (const step of result[key] ?? [])
@@ -103,6 +131,8 @@ export async function run(
       if (!record.timestamps.flat().every(Number.isFinite)) throw Error("Nonfinite timestamps");
       for (const value of Object.values(result)) if (value instanceof Tensor) value.dispose();
       await result.past_key_values?.dispose();
+      record.liveAttentionBytesAfterCleanup = liveAttentionBytes;
+      if (liveAttentionBytes !== 0) throw Error(`Attention allocation leak: ${liveAttentionBytes} bytes`);
       if (iteration >= 0) {
         timings.push(elapsed);
         outputs.push(record);
@@ -117,6 +147,8 @@ export async function run(
       note: "Attach runtime EP profiling / browser GPU trace and driver identity; requested device alone is not execution proof.",
     };
   } finally {
+    model.forward = originalForward;
+    Tensor.prototype.dispose = originalDispose;
     await model.dispose();
     input.dispose();
     if (input !== processed.input_features) processed.input_features.dispose();
diff --git a/scripts/beam-timestamps/verify-results.mjs b/scripts/beam-timestamps/verify-results.mjs
index 8312ea280..3dfed9b07 100644
--- a/scripts/beam-timestamps/verify-results.mjs
+++ b/scripts/beam-timestamps/verify-results.mjs
@@ -1,13 +1,34 @@
 import assert from "node:assert/strict";
 import fs from "node:fs";
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+const requestedRevision = process.argv[2];
+assert(requestedRevision, "Pass the exact expected source commit as the first argument");
+const expectedRevision = execFileSync("git", ["rev-parse", `${requestedRevision}^{commit}`], { encoding: "utf8" }).trim();
+assert.equal(requestedRevision, expectedRevision, "Use a full immutable commit SHA");
+const sourcePaths = ["generation/beam_search.js", "models/modeling_utils.js", "models/whisper/modeling_whisper.js"];
+const expectedSources = Object.fromEntries(
+  sourcePaths.map((path) => [
+    path,
+    createHash("sha256")
+      .update(execFileSync("git", ["show", `${expectedRevision}:packages/transformers/src/${path}`]))
+      .digest("hex"),
+  ]),
+);
 const read = (name) => JSON.parse(fs.readFileSync(new URL(`results/${name}.json`, import.meta.url)));
 const batch = read("native-cpu"),
   single = read("native-single"),
   diverse = read("native-diverse"),
   long = read("native-long");
 for (const result of [batch, single, diverse, long]) {
+  assert.equal(result.sha, expectedRevision, "Stale result revision");
+  assert.equal(result.status, "", "Results must come from a clean checkout");
+  assert.deepEqual(result.sources, expectedSources, "Source bytes do not match the requested revision");
+  assert(result.outputs.length >= 3, "Require three measured repeats");
   assert.equal(result.fixture.revision, "aeaa13760958b03fac5062f457d317d3319c3168");
   for (const output of result.outputs) {
+    assert(output.peakInternalAttentionBytes > 0);
+    assert.equal(output.liveAttentionBytesAfterCleanup, 0);
     assert.equal(output.tokens.length, output.timestamps.length);
     output.tokens.forEach((tokens, row) => {
       const times = output.timestamps[row],

From e14b98d41943e37d13077c82d8863754b75756c0 Mon Sep 17 00:00:00 2001
From: Dan Levy 
Date: Wed, 21 Oct 2026 15:17:59 -0600
Subject: [PATCH 18/21] Fix encoder preparation ownership on errors and
 expansion

---
 .../transformers/src/models/modeling_utils.js | 59 +++++++++-------
 .../encoder_preparation_ownership.test.js     | 69 +++++++++++++++++++
 2 files changed, 102 insertions(+), 26 deletions(-)
 create mode 100644 packages/transformers/tests/utils/encoder_preparation_ownership.test.js

diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js
index fe5bb5a02..3cd0c2da6 100644
--- a/packages/transformers/src/models/modeling_utils.js
+++ b/packages/transformers/src/models/modeling_utils.js
@@ -757,36 +757,43 @@ export class PreTrainedModel extends Callable {
             };
         }
         let { last_hidden_state } = await encoder_forward(this, model_inputs);
-
-        // for classifier free guidance we need to add a 'null' input to our encoder hidden states
-        if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {
-            last_hidden_state = cat([last_hidden_state, full_like(last_hidden_state, 0.0)], 0);
-
-            if ('attention_mask' in model_inputs) {
-                model_inputs['attention_mask'] = cat(
-                    [model_inputs['attention_mask'], zeros_like(model_inputs['attention_mask'])],
-                    0,
-                );
-            }
-        } else if (model_inputs.decoder_input_ids) {
-            // Ensure that the encoder outputs have the same batch size as the decoder inputs,
-            // allowing for more efficient batched generation for single inputs
-            const decoder_input_ids_batch_size = toI64Tensor(model_inputs.decoder_input_ids).dims[0];
-            if (decoder_input_ids_batch_size !== last_hidden_state.dims[0]) {
-                if (last_hidden_state.dims[0] !== 1) {
-                    throw new Error(
-                        `The encoder outputs have a different batch size (${last_hidden_state.dims[0]}) than the decoder inputs (${decoder_input_ids_batch_size}).`,
+        const owned = new Set([last_hidden_state]);
+        try {
+            // Add a null encoder input for classifier-free guidance.
+            if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {
+                const null_state = full_like(last_hidden_state, 0.0);
+                owned.add(null_state);
+                last_hidden_state = cat([last_hidden_state, null_state], 0);
+                owned.add(last_hidden_state);
+
+                if ('attention_mask' in model_inputs) {
+                    const null_mask = zeros_like(model_inputs.attention_mask);
+                    owned.add(null_mask);
+                    model_inputs.attention_mask = cat([model_inputs.attention_mask, null_mask], 0);
+                }
+            } else if (model_inputs.decoder_input_ids) {
+                // A single encoder input may serve multiple decoder prefixes.
+                const decoder_input_ids_batch_size = toI64Tensor(model_inputs.decoder_input_ids).dims[0];
+                if (decoder_input_ids_batch_size !== last_hidden_state.dims[0]) {
+                    if (last_hidden_state.dims[0] !== 1) {
+                        throw new Error(
+                            `The encoder outputs have a different batch size (${last_hidden_state.dims[0]}) than the decoder inputs (${decoder_input_ids_batch_size}).`,
+                        );
+                    }
+                    last_hidden_state = cat(
+                        Array.from({ length: decoder_input_ids_batch_size }, () => last_hidden_state),
+                        0,
                     );
+                    owned.add(last_hidden_state);
                 }
-                last_hidden_state = cat(
-                    Array.from({ length: decoder_input_ids_batch_size }, () => last_hidden_state),
-                    0,
-                );
             }
+            model_inputs.encoder_outputs = last_hidden_state;
+            // Transfer only the final encoder state to generate's outer cleanup.
+            owned.delete(last_hidden_state);
+            return model_inputs;
+        } finally {
+            for (const tensor of owned) tensor.dispose();
         }
-        model_inputs['encoder_outputs'] = last_hidden_state;
-
-        return model_inputs;
     }
 
     /**
diff --git a/packages/transformers/tests/utils/encoder_preparation_ownership.test.js b/packages/transformers/tests/utils/encoder_preparation_ownership.test.js
new file mode 100644
index 000000000..fd4112a4d
--- /dev/null
+++ b/packages/transformers/tests/utils/encoder_preparation_ownership.test.js
@@ -0,0 +1,69 @@
+import { jest } from "@jest/globals";
+import { PreTrainedModel } from "../../src/models/modeling_utils.js";
+import { Tensor } from "../../src/utils/tensor.js";
+import { getTensorConstructor } from "../../src/backends/onnx.js";
+
+const prepare = (encoded, model_inputs, guidance_scale = null) => PreTrainedModel.prototype._prepare_encoder_decoder_kwargs_for_generation.call({ sessions: { model: { inputNames: ["input_ids"], run: async () => ({ last_hidden_state: encoded }) } } }, { model_inputs, generation_config: { guidance_scale } });
+
+it("releases the encoder GPU allocation if decoder batch validation throws", async () => {
+  const dispose = jest.fn();
+  const encoded = getTensorConstructor().fromGpuBuffer({ usage: 1 }, { dataType: "float32", dims: [2, 1, 4], dispose });
+  const ids = new Tensor("int64", [1n, 2n], [2, 1]);
+  await expect(prepare(encoded, { input_ids: ids, decoder_input_ids: [[1], [2], [3]] })).rejects.toThrow("different batch size");
+  expect(dispose).toHaveBeenCalledTimes(1);
+  expect(ids.tolist()).toEqual([[1n], [2n]]);
+});
+
+it.each(["broadcast", "guidance", "unchanged"])("transfers only final encoder output and frees temporary %s tensors", async (mode) => {
+  const encoded = new Tensor("float32", [2, 3], [1, 1, 2]);
+  const ids = new Tensor("int64", [1n], [1, 1]);
+  const mask = new Tensor("int64", [1n], [1, 1]);
+  const disposed = [];
+  const original = Tensor.prototype.dispose;
+  const spy = jest.spyOn(Tensor.prototype, "dispose").mockImplementation(function () {
+    disposed.push(this.ort_tensor);
+    return original.call(this);
+  });
+  try {
+    const result = await prepare(encoded, { input_ids: ids, attention_mask: mask, decoder_input_ids: mode === "broadcast" ? [[1], [2]] : [[1]] }, mode === "guidance" ? 2 : null);
+    expect(result.encoder_outputs.tolist()).toEqual(mode === "guidance" ? [[[2, 3]], [[0, 0]]] : mode === "broadcast" ? [[[2, 3]], [[2, 3]]] : [[[2, 3]]]);
+    expect(disposed.filter((x) => x === encoded.ort_tensor)).toHaveLength(mode === "unchanged" ? 0 : 1);
+    expect(disposed).not.toContain(result.encoder_outputs.ort_tensor);
+    expect(disposed).not.toContain(mask.ort_tensor);
+    expect(disposed).not.toContain(ids.ort_tensor);
+    expect(disposed).toHaveLength(mode === "guidance" ? 3 : mode === "broadcast" ? 1 : 0);
+    expect(mask.tolist()).toEqual([[1n]]);
+    if (mode === "guidance") {
+      expect(result.attention_mask.tolist()).toEqual([[1n], [0n]]);
+      result.attention_mask.dispose();
+    }
+    result.encoder_outputs.dispose();
+  } finally {
+    spy.mockRestore();
+  }
+});
+
+it("releases original, null and expanded encoder states if guidance preparation fails", async () => {
+  const encoded = new Tensor("float32", [2, 3], [1, 1, 2]);
+  const inputs = {
+    input_ids: new Tensor("int64", [1n], [1, 1]),
+    get attention_mask() {
+      throw Error("mask preparation failed");
+    },
+  };
+  const disposed = [];
+  const original = Tensor.prototype.dispose;
+  const spy = jest.spyOn(Tensor.prototype, "dispose").mockImplementation(function () {
+    disposed.push(this.ort_tensor);
+    return original.call(this);
+  });
+  try {
+    await expect(prepare(encoded, inputs, 2)).rejects.toThrow("mask preparation failed");
+    expect(disposed).toHaveLength(3);
+    expect(new Set(disposed).size).toBe(3);
+    expect(disposed).toContain(encoded.ort_tensor);
+    expect(inputs.input_ids.tolist()).toEqual([[1n]]);
+  } finally {
+    spy.mockRestore();
+  }
+});

From c26c8108c316494fedb57aebb2514d19bcbb8654 Mon Sep 17 00:00:00 2001
From: Dan Levy 
Date: Wed, 21 Oct 2026 15:26:49 -0600
Subject: [PATCH 19/21] Match Whisper alignment arithmetic and preserve seek
 padding

---
 .../src/models/whisper/modeling_whisper.js    | 21 ++++--
 packages/transformers/src/utils/maths.js      |  7 +-
 ..._pipelines_automatic_speech_recognition.js |  7 +-
 .../transformers/tests/utils/maths.test.js    | 15 +++-
 .../utils/whisper_beam_timestamps.test.js     | 70 +++++++++++++++++++
 scripts/beam-timestamps/README.md             | 15 ++++
 6 files changed, 127 insertions(+), 8 deletions(-)

diff --git a/packages/transformers/src/models/whisper/modeling_whisper.js b/packages/transformers/src/models/whisper/modeling_whisper.js
index 5d8f6afd4..2f3c2e6d2 100644
--- a/packages/transformers/src/models/whisper/modeling_whisper.js
+++ b/packages/transformers/src/models/whisper/modeling_whisper.js
@@ -266,7 +266,13 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
         while (seek < total_frames) {
             // Slice input features for this segment
             const seek_end = Math.min(seek + num_segment_frames, total_frames);
-            const segment_input = input_features.slice(null, null, [seek, seek_end]);
+            // Keep the feature extractor's normalized silence padding. Valid audio
+            // frames bound seek/alignment, but replacing existing padded features
+            // with zeros changes the encoder input (zero is not log-mel silence).
+            const segment_input = input_features.slice(null, null, [
+                seek,
+                Math.min(seek + num_segment_frames, input_features.dims[2]),
+            ]);
 
             // Pad to full segment size if needed (whisper expects fixed-length input)
             let segment_features;
@@ -536,8 +542,12 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
                     for (const row of weights) average += row[frame] / queries;
                     let variance = 0;
                     for (const row of weights) variance += (row[frame] - average) ** 2 / queries;
-                    const scale = Math.sqrt(variance);
-                    for (const row of weights) row[frame] = scale > 0 ? (row[frame] - average) / scale : 0;
+                    // Torch uses fp32 statistics and elementwise arithmetic. Rounding
+                    // matters when near-equal DTW costs choose different boundaries.
+                    average = Math.fround(average);
+                    const scale = Math.fround(Math.sqrt(variance));
+                    for (const row of weights)
+                        row[frame] = scale > 0 ? Math.fround(Math.fround(row[frame] - average) / scale) : 0;
                 }
                 for (let token = 0; token < queries; ++token) {
                     // Python leaves recordings too short for reflection padding unchanged.
@@ -549,7 +559,10 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
                         matrix[token][frame] -= filtered[frame] / alignment_heads.length;
                 }
             }
-            const [text, times] = dynamic_time_warping(matrix.map((row) => Array.from(row)));
+            const [text, times] = dynamic_time_warping(
+                matrix.map((row) => Array.from(row)),
+                true,
+            );
             let last = 0;
             for (let i = 0; i < text.length; ++i) {
                 if (i === 0 || text[i] !== text[i - 1]) {
diff --git a/packages/transformers/src/utils/maths.js b/packages/transformers/src/utils/maths.js
index 1ba3865c3..47789ff05 100644
--- a/packages/transformers/src/utils/maths.js
+++ b/packages/transformers/src/utils/maths.js
@@ -966,15 +966,18 @@ export function bankers_round(x) {
  * Measures similarity between two temporal sequences (e.g., input audio and output tokens
  * to generate token-level timestamps).
  * @param {number[][]} matrix
+ * @param {boolean} [float32_cost=false] Accumulate costs in float32 to match Whisper alignment.
  * @returns {number[][]}
  */
-export function dynamic_time_warping(matrix) {
+export function dynamic_time_warping(matrix, float32_cost = false) {
     const output_length = matrix.length;
     const input_length = matrix[0].length;
 
     const outputShape = [output_length + 1, input_length + 1];
 
-    const cost = Array.from({ length: outputShape[0] }, () => Array(outputShape[1]).fill(Infinity));
+    const cost = Array.from({ length: outputShape[0] }, () =>
+        float32_cost ? new Float32Array(outputShape[1]).fill(Infinity) : Array(outputShape[1]).fill(Infinity),
+    );
     cost[0][0] = 0;
 
     const trace = Array.from({ length: outputShape[0] }, () => Array(outputShape[1]).fill(-1));
diff --git a/packages/transformers/tests/pipelines/test_pipelines_automatic_speech_recognition.js b/packages/transformers/tests/pipelines/test_pipelines_automatic_speech_recognition.js
index 8cdcf7a1d..fa941e542 100644
--- a/packages/transformers/tests/pipelines/test_pipelines_automatic_speech_recognition.js
+++ b/packages/transformers/tests/pipelines/test_pipelines_automatic_speech_recognition.js
@@ -249,10 +249,15 @@ export default () => {
                 { text: " meaning", timestamp: [11.62, 11.78] },
                 { text: " of", timestamp: [11.78, 12.12] },
                 { text: " its", timestamp: [12.12, 12.64] },
-                { text: " creed.", timestamp: [12.64, 13.6] },
+                // The fixture is 13 seconds; the final valid encoder frame starts at 12.98.
+                // Aligning padded silence used to place this boundary beyond the recording.
+                { text: " creed.", timestamp: [12.64, 12.98] },
               ],
             };
             expect(output).toBeCloseToNested(target, 1);
+            for (const chunk of output.chunks) {
+              expect(chunk.timestamp[1]).toBeLessThanOrEqual(audio.length / 16000);
+            }
           },
           MAX_TEST_EXECUTION_TIME,
         );
diff --git a/packages/transformers/tests/utils/maths.test.js b/packages/transformers/tests/utils/maths.test.js
index 56f09b42b..ffdabf275 100644
--- a/packages/transformers/tests/utils/maths.test.js
+++ b/packages/transformers/tests/utils/maths.test.js
@@ -1,4 +1,4 @@
-import { FFT, medianFilter, bankers_round, log_softmax } from "../../src/utils/maths.js";
+import { FFT, medianFilter, bankers_round, log_softmax, dynamic_time_warping } from "../../src/utils/maths.js";
 import { init } from "../init.js";
 
 // Initialise the testing environment
@@ -193,3 +193,16 @@ describe("Mathematical operations", () => {
     }
   });
 });
+
+// Pinned Transformers v4.57.1 alignment matrix: rounding changes the optimal path.
+it("preserves default DTW precision and supports upstream fp32 cost ties", () => {
+  const matrix = [
+    [-1.0, -1.0000001192092896, 1.7881393432617188e-7, -0.0, -5.960464477539063e-8, 2.9802322387695312e-8, 0.9999998807907104, 1.0, -5.364418029785156e-7, -0.0],
+    [1.0, 0.9999999403953552, 1.4901161193847656e-7, 5.960464477539063e-8, -0.0, 5.960464477539063e-8, -1.000000238418579, -1.0, -5.066394805908203e-7, 2.9802322387695312e-8],
+  ];
+  expect(dynamic_time_warping(matrix, true)).toEqual([
+    [0, 0, 1, 1, 1, 1, 1, 1, 1, 1],
+    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
+  ]);
+  expect(dynamic_time_warping(matrix)[0]).toEqual([0, 0, 0, 0, 0, 0, 1, 1, 1, 1]);
+});
diff --git a/packages/transformers/tests/utils/whisper_beam_timestamps.test.js b/packages/transformers/tests/utils/whisper_beam_timestamps.test.js
index a927fc9fe..54b43ed5c 100644
--- a/packages/transformers/tests/utils/whisper_beam_timestamps.test.js
+++ b/packages/transformers/tests/utils/whisper_beam_timestamps.test.js
@@ -205,3 +205,73 @@ it("converts only selected fp16 attention elements", () => {
     spy.mockRestore();
   }
 });
+
+it("preserves preprocessed silence padding while bounding seek to valid audio frames", async () => {
+  const inputs = new Tensor("float32", [1, 2, 3, -1.5, -1.5, -1.5, -1.5, -1.5], [1, 1, 8]);
+  const forward = jest.spyOn(PreTrainedModel.prototype, "generate").mockImplementation(async ({ input_features }) => {
+    expect(input_features.tolist()).toEqual(inputs.tolist());
+    return new Tensor("int64", [9n, 100n, 2n, 101n, 0n], [1, 5]);
+  });
+  const model = Object.assign(Object.create(WhisperForConditionalGeneration.prototype), { config: { max_source_positions: 4 } });
+  try {
+    const output = await model._generate_with_seek({ inputs, generation_config: { num_frames: 3, no_timestamps_token_id: 99, eos_token_id: 0, return_token_timestamps: false }, init_tokens: [9], kwargs: {} });
+    expect(forward).toHaveBeenCalledTimes(1);
+    expect(output.tolist()).toEqual([[9n, 100n, 2n, 101n, 0n]]);
+    expect(inputs.tolist()[0][0][7]).toBe(-1.5);
+  } finally {
+    forward.mockRestore();
+  }
+});
+
+// Golden boundaries from independently executed Transformers v4.57.1 Python
+// alignment, including a shorter EOS result and per-input valid frame lengths.
+it.each([1, 7])("matches upstream fp32 alignment near DTW ties (median=%s)", (median) => {
+  const histories = [
+    [0, 1, 0, 1, 1, -1, -1, -1],
+    [2, 3, 2, -1, -1, -1, -1, -1],
+  ];
+  const steps = Array.from({ length: 5 }, (_, step) =>
+    Array.from({ length: 2 }, (_, layer) => {
+      const dims = [4, 2, step === 0 ? 3 : 1, 16];
+      const data = Float32Array.from({ length: dims.reduce((a, b) => a * b) }, (_, i) => Math.sin(i * 0.83 + step * 2.31 + layer) * 0.6 + Math.cos(i * 0.12 + step) * 0.3);
+      return new Tensor("float32", data, dims);
+    }),
+  );
+  const outputs = {
+    sequences: new Tensor(
+      "int64",
+      Array.from({ length: 16 }, (_, i) => BigInt(i)),
+      [2, 8],
+    ),
+    cross_attentions: steps,
+    beam_indices: new Tensor("int64", histories.flat().map(BigInt), [2, 8]),
+    sequence_lengths: new Tensor("int64", [8n, 6n], [2]),
+    num_beams: 2,
+  };
+  const actual = WhisperForConditionalGeneration.prototype._extract_token_timestamps
+    .call(
+      { config: { median_filter_width: median } },
+      outputs,
+      [
+        [0, 0],
+        [1, 1],
+      ],
+      [16, 10],
+      0.02,
+      3,
+    )
+    .tolist();
+  const expected = {
+    1: [
+      [0.0, 0.0, 0.0, 0.0, 0.25999999046325684, 0.25999999046325684, 0.30000001192092896, 0.30000001192092896],
+      [0.0, 0.0, 0.0, 0.0, 0.03999999910593033, 0.03999999910593033],
+    ],
+    7: [
+      [0.0, 0.0, 0.0, 0.0, 0.25999999046325684, 0.25999999046325684, 0.30000001192092896, 0.30000001192092896],
+      [0.0, 0.0, 0.0, 0.0, 0.14000000059604645, 0.14000000059604645],
+    ],
+  };
+  expect(actual[0]).toEqual(expected[median][0]);
+  expect(actual[1].slice(0, 6)).toEqual(expected[median][1]);
+  expect(actual[1].slice(6)).toEqual([0, 0]);
+});
diff --git a/scripts/beam-timestamps/README.md b/scripts/beam-timestamps/README.md
index fd917d630..24f47017e 100644
--- a/scripts/beam-timestamps/README.md
+++ b/scripts/beam-timestamps/README.md
@@ -54,3 +54,18 @@ Parent owns hardware validation and both postimplementation review rounds. CPU r
 Internal attention instrumentation reports peak live attention bytes and verifies zero remaining tracked bytes after each call, including timestamp-only mode. This is tensor-lifetime accounting, not the driver's allocator high-water mark or total KV/model memory. Explicit public attention histories remain caller-owned. Timestamp-only calls currently retain complete histories too; large models, beam counts and long generations need separate memory admission measurements. fp16 alignment converts only the selected head/row/query frame range.
 
 The verifier requires an immutable full source SHA, clean-checkout provenance, and matching source hashes for every result; stale evidence fails closed. CPU fixture results are not independent Python parity or hardware execution proof. The deterministic numerical regression uses Python Transformers v4.57.1's prefix cropping and short-median-window semantics.
+
+Round-two numerical validation independently executed the unmodified alignment,
+median-filter, and DTW functions extracted from Python Transformers v4.57.1 with
+PyTorch 2.9.0 and NumPy 2.3.4. Sixteen synthetic comparisons cover changing beam
+ancestry, heterogeneous EOS lengths/frame counts, short median windows, and
+fp16-quantized inputs decoded to fp32. All boundaries match exactly after making
+Whisper statistics and DTW cost accumulation explicitly fp32. The general DTW
+helper retains its previous precision unless the new option is requested. This
+is algorithm parity, not full Python model-inference parity. Near-tie regressions
+are retained in the unit tests.
+
+Seek generation preserves existing processor-provided log-mel silence padding
+while bounding alignment to valid audio frames. The English speech fixture lasts
+13 seconds: its final word now ends at 12.98 seconds (the last valid encoder frame)
+instead of the previous out-of-recording 13.6-second golden.

From b379acab1d75f3d0e334e7ca9130077855483b3d Mon Sep 17 00:00:00 2001
From: Dan Levy 
Date: Wed, 21 Oct 2026 16:12:17 -0600
Subject: [PATCH 20/21] chore: remove standalone beam GPU benchmark artifacts

---
 scripts/beam-gpu/.gitignore     |   1 -
 scripts/beam-gpu/README.md      |  51 ------
 scripts/beam-gpu/RESULTS.md     | 113 -------------
 scripts/beam-gpu/bootstrap.sh   |  31 ----
 scripts/beam-gpu/browser.js     | 286 --------------------------------
 scripts/beam-gpu/build.mjs      |  16 --
 scripts/beam-gpu/candidates.mjs |  27 ---
 scripts/beam-gpu/run.sh         |  19 ---
 scripts/beam-gpu/runner.mjs     |  87 ----------
 9 files changed, 631 deletions(-)
 delete mode 100644 scripts/beam-gpu/.gitignore
 delete mode 100644 scripts/beam-gpu/README.md
 delete mode 100644 scripts/beam-gpu/RESULTS.md
 delete mode 100755 scripts/beam-gpu/bootstrap.sh
 delete mode 100644 scripts/beam-gpu/browser.js
 delete mode 100644 scripts/beam-gpu/build.mjs
 delete mode 100644 scripts/beam-gpu/candidates.mjs
 delete mode 100755 scripts/beam-gpu/run.sh
 delete mode 100644 scripts/beam-gpu/runner.mjs

diff --git a/scripts/beam-gpu/.gitignore b/scripts/beam-gpu/.gitignore
deleted file mode 100644
index 6628455c0..000000000
--- a/scripts/beam-gpu/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/results/
diff --git a/scripts/beam-gpu/README.md b/scripts/beam-gpu/README.md
deleted file mode 100644
index 7b6d150df..000000000
--- a/scripts/beam-gpu/README.md
+++ /dev/null
@@ -1,51 +0,0 @@
-# Beam search GPU validation
-
-These scripts validate and benchmark browser WebGPU on a disposable Linux NVIDIA
-host. Infrastructure provisioning, SSH credentials, budgets, and teardown belong
-to the caller; the scripts contain no provider credentials and create no hosts.
-
-`bootstrap.sh` installs Node 24.14.1, pnpm, the base PR revision, and Playwright
-1.56.1/Chromium 141. A newer Chromium 156 build returned a null WebGPU adapter on
-the tested NVIDIA driver; Chromium 141 worked. EGL dispatch libraries are required
-in addition to the container's NVIDIA Vulkan libraries.
-
-Run `bootstrap.sh` on a throwaway Ubuntu GPU host, then transfer the desired source
-revision into `/workspace/beam-gpu/transformers.js`. The default task root is
-`/workspace/beam-gpu`; override `TASK_ROOT` for bootstrap or `BEAM_RUNNER_ROOT` and
-`BEAM_PROJECT_ROOT` for the runner. `BEAM_PLAYWRIGHT_ROOT` can select another
-runner's Playwright installation. The benchmark server binds to loopback only.
-
-```bash
-export PATH=/workspace/beam-gpu/node-v24.14.1-linux-x64/bin:$PATH
-cd /workspace/beam-gpu/transformers.js
-node scripts/beam-gpu/build.mjs
-BEAM_OPTIONS='{"mode":"validate"}' BEAM_RESULT=/workspace/beam-gpu/validate.json node scripts/beam-gpu/runner.mjs
-BEAM_OPTIONS='{"mode":"micro"}' BEAM_RESULT=/workspace/beam-gpu/micro.json node scripts/beam-gpu/runner.mjs
-BEAM_OPTIONS='{"mode":"generation","repeats":4,"tokens":16}' BEAM_RESULT=/workspace/beam-gpu/generation.json node scripts/beam-gpu/runner.mjs
-```
-
-- `probe`: requires a hardware WebGPU adapter and records browser/adapter identity.
-- `validate`: verifies float32, float16, int64, uint8 and bool row selection,
-  duplicate rows, chained selections, preservation of caller-owned source data,
-  and the CPU fallback for unaligned float16 rows.
-- `micro`: validates every copied element, then measures GPU-completed row
-  selection for 1, 8, and 64 MiB tensors. Two warmups precede ten timed samples.
-- `generation`: runs T5 and Llama standard/diverse/sampling/batched beam decoding;
-  checks seeded repeatability, batch independence, and null returned beam caches.
-  One warmup precedes timed samples. JSON retains tokens and cache locations.
-
-For other models, pass `models`, `dtype`, and optionally `modes` (`standard`,
-`diverse`, `sampling`, `batched`) in `BEAM_OPTIONS`. Set `cpuRowSelection: true`
-to use the original cache-download algorithm for a matched reference. This is a
-harness option, not a library configuration flag. Compare token arrays between
-reference and optimized output files before interpreting timings.
-
-`node scripts/beam-gpu/candidates.mjs` separately compares the full-sort reference
-with bounded top-k selection for 32K and 152K vocabularies and verifies identical
-rankings. Its numbers are CPU microbenchmarks, not inference throughput.
-
-Raw results belong in the gitignored `results/` directory. Keep model caches,
-provider keys, SSH keys, browser installations, and build output out of Git.
-The Chromium process runs without its sandbox because this harness runs as root
-inside an isolated, disposable test container; use a sandboxed browser on shared
-or persistent hosts.
diff --git a/scripts/beam-gpu/RESULTS.md b/scripts/beam-gpu/RESULTS.md
deleted file mode 100644
index cfde234f7..000000000
--- a/scripts/beam-gpu/RESULTS.md
+++ /dev/null
@@ -1,113 +0,0 @@
-# WebGPU beam decoding experiment — 2026-10-20
-
-Branch: `dan/beam-webgpu-performance`, based on PR #1539 at `7c43a27`.
-Product and hardware-validation revision: `58699fa153ece4803a2e3bd4206f59197fa4ec26`.
-
-## Changes
-
-- Keep aligned WebGPU cache rows on GPU with buffer-to-buffer copies. Other
-  device tensors and unaligned rows retain CPU fallback. Outputs have ONNX
-  Runtime's required 16-byte allocation padding and explicit disposal/download
-  callbacks. The active runtime's Tensor factory avoids package-version identity
-  mismatches when wrapping GPU buffers.
-- Replace full-vocabulary object allocation/sorting with bounded top-k selection.
-  Ranking, diversity penalties, token tie order, and seeded outputs are preserved.
-- Add an isolated, reproducible browser harness, dtype and ownership checks,
-  candidate-selection reference tests, benchmarks, and a GPU usage guide.
-
-## Hardware and method
-
-Runpod Secure Cloud RTX 4090, 24,564 MiB VRAM, NVIDIA driver 595.91.07,
-Ubuntu 24.04 container/Linux 6.8, Node 24.14.1, Chromium 141.0.7390.37.
-The adapter reported `nvidia` / `lovelace` and `isFallbackAdapter: false`.
-The host allocation had 12 vCPUs and 100 GB system RAM.
-
-Model inference used fp32 and four beams, returning two sequences. Tiny models
-used 16 new tokens; SmolLM2 used 32. Batched cases used two inputs. Each timing
-is the median of three measured runs after one warmup. Model downloads and
-initial session creation are excluded. Source code, backend, model bytes and
-inputs were matched; raw model hashes are retained locally.
-
-The reference uses the original CPU cache-download/reorder algorithm and full
-vocabulary sorting. The tuned path includes both GPU copies and bounded top-k.
-These are workload-specific measurements, not general speedup guarantees.
-
-## End-to-end results
-
-| Model | Mode | Reference (ms) | Tuned (ms) | Speedup |
-|---|---|---:|---:|---:|
-| tiny-random-T5ForConditionalGeneration | standard | 2564.5 | 475.7 | 5.39x |
-| tiny-random-T5ForConditionalGeneration | diverse | 2409.3 | 610.4 | 3.95x |
-| tiny-random-T5ForConditionalGeneration | sampling | 2524.8 | 650.3 | 3.88x |
-| tiny-random-T5ForConditionalGeneration | batched | 3201.3 | 805.6 | 3.97x |
-| tiny-random-LlamaForCausalLM | standard | 2475.1 | 914.2 | 2.71x |
-| tiny-random-LlamaForCausalLM | diverse | 2598.7 | 989.1 | 2.63x |
-| tiny-random-LlamaForCausalLM | sampling | 2697.2 | 1079.4 | 2.50x |
-| tiny-random-LlamaForCausalLM | batched | 4601.0 | 1738.8 | 2.65x |
-| SmolLM2-135M-Instruct-ONNX | standard | 15571.3 | 1676.0 | 9.29x |
-| SmolLM2-135M-Instruct-ONNX | batched | 19463.8 | 2014.7 | 9.66x |
-
-All ten reference-versus-tuned token arrays match exactly. A separate CPU/WASM
-reference also matches all eight tiny-model WebGPU cases, including seeded
-sampling and batched/diverse decoding.
-
-## Cache row-copy microbenchmarks
-
-Each result validates every copied element and measures completion on the GPU
-queue. Two warmups precede ten samples. These numbers measure one synthetic
-cache tensor, not full generation.
-
-| Tensor size | CPU-transfer reference (ms) | GPU copy (ms) | Speedup |
-|---|---:|---:|---:|
-| 1 MiB | 6.165 | 0.275 | 22.42x |
-| 8 MiB | 25.690 | 1.640 | 15.66x |
-| 64 MiB | 140.395 | 7.075 | 19.84x |
-
-## Verification
-
-- Full workspace CPU suite: **2,278 passed, 47 skipped, 30 suites passed**.
-- Eight real-GPU boundary fixtures cover float32, float16, int64, uint8, bool,
-  duplicated/chained rows, unaligned fallback, small output padding, and
-  caller-owned source preservation.
-- A 25-generation stress run leaves zero owned row-copy buffers live after every
-  generation. The active inference-device instrumentation observes a peak of
-  60 owned buffers on SmolLM2 and zero remaining at completion. This checks
-  buffers owned by this implementation, not all runtime/driver allocations.
-- Ten candidate-selection tests match a full-sort reference, including ties,
-  suppressed tokens, diversity penalties, large k, and empty input.
-- Both packages build with declarations on macOS and the Linux worker; docs
-  generation and changed-file Prettier checks pass.
-- Repository-wide formatting retains the two previously verified failures in
-  untouched `tensor.test.js` and `tensor_ops.test.js`.
-
-## Scope and setup findings
-
-Validation covers Linux/NVIDIA browser WebGPU with fp32 model inference.
-The container required EGL dispatch libraries before Vulkan could initialize.
-Chromium 156 returned a null WebGPU adapter on this host; pinned Chromium 141
-worked. The Qwen 0.5B fp16 attempt was rejected by the browser capability check;
-its fp32 export hit a browser runtime allocation limit. Those attempts are
-setup/coverage limits, not successful model validation.
-
-## Cost and cleanup
-
-Pod `tlouzqbaj8jchl` ran from 19:44:51 UTC to verified deletion at 20:38:26 UTC:
-**53.6 minutes**, below the two-hour authorization. Compute was $0.89/hour;
-40 GB disposable storage brought the estimate to about $0.90/hour. Estimated
-total: **$0.80**. The account balance decreased by $0.7993, and final reported
-compute spend was $0/hour; the per-pod billing ledger had not posted records.
-
-A fresh provider read returned 404 after deletion. No volume was created.
-The scheduled cleanup backup was removed after deletion, and the local
-watchdog/result archiver were signaled to exit. Automatic approval review
-rejected copying the account API key onto the worker; no API key was copied
-there. Credentials stayed local, with local sleep prevention and a scheduled
-cleanup backup guarding the deadline.
-
-## Retained evidence
-
-Raw JSON/logs, source identity/status, model hashes, manifests and intermediate
-archives are retained in the gitignored `scripts/beam-gpu/results/` directory.
-The bootstrap and test harness are tracked in this directory. Run `run.sh` to
-repeat the complete hardware-validation/benchmark sequence on an already
-provisioned host. Provider credentials and SSH keys are not part of the repo.
diff --git a/scripts/beam-gpu/bootstrap.sh b/scripts/beam-gpu/bootstrap.sh
deleted file mode 100755
index 1f42996ff..000000000
--- a/scripts/beam-gpu/bootstrap.sh
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-# Run inside the disposable Linux GPU host. No credentials are required.
-TASK_ROOT=${TASK_ROOT:-/workspace/beam-gpu}
-mkdir -p "$TASK_ROOT"
-cd "$TASK_ROOT"
-apt-get update -qq
-apt-get install -y -qq libegl1 libgl1 libglvnd0 vulkan-tools
-if ! command -v node >/dev/null; then
-  curl -fsSL https://nodejs.org/dist/v24.14.1/node-v24.14.1-linux-x64.tar.xz -o node.tar.xz
-  tar -xf node.tar.xz
-fi
-export PATH="$TASK_ROOT/node-v24.14.1-linux-x64/bin:$PATH"
-corepack enable
-if [[ ! -d transformers.js/.git ]]; then
-  git clone --depth 1 --branch dan/add-beam-support https://github.com/justsml/transformers.js.git
-fi
-cd transformers.js
-git checkout 7c43a27d44f2ae4fa764362ce31f389a2bb489bf
-pnpm install --frozen-lockfile
-pnpm build
-mkdir -p "$TASK_ROOT/runner"
-cd "$TASK_ROOT/runner"
-if [[ ! -f package.json ]]; then
-  printf '{"private":true,"type":"module","packageManager":"pnpm@10.28.1"}\n' > package.json
-fi
-pnpm add --save-exact playwright@1.56.1
-pnpm exec playwright install --with-deps chromium
-node --version
-pnpm exec playwright --version
-nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv
diff --git a/scripts/beam-gpu/browser.js b/scripts/beam-gpu/browser.js
deleted file mode 100644
index d90393f05..000000000
--- a/scripts/beam-gpu/browser.js
+++ /dev/null
@@ -1,286 +0,0 @@
-import {
-  AutoModelForSeq2SeqLM,
-  AutoModelForCausalLM,
-  AutoTokenizer,
-  PreTrainedModel,
-  Tensor,
-  DynamicCache,
-  env,
-  random,
-} from "../../packages/transformers/src/transformers.js";
-import { getTensorConstructor } from "../../packages/transformers/src/backends/onnx.js";
-import { index_select_async, index_select } from "../../packages/transformers/src/utils/tensor.js";
-
-env.backends.onnx.wasm.wasmPaths = "/ort/";
-env.backends.onnx.wasm.numThreads = 1;
-env.allowLocalModels = false;
-env.remoteHost = location.origin + "/hf/";
-const emit = (value) => console.log("RESULT " + JSON.stringify(value, (_, x) => (typeof x === "bigint" ? x.toString() : x)));
-const equal = (a, b) =>
-  JSON.stringify(a, (_, x) => (typeof x === "bigint" ? x.toString() : x)) === JSON.stringify(b, (_, x) => (typeof x === "bigint" ? x.toString() : x));
-const median = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)];
-
-window.runBeamGPU = async (options) => {
-  const adapter = await navigator.gpu?.requestAdapter({ powerPreference: "high-performance" });
-  if (!adapter) throw new Error("No WebGPU adapter");
-  const info = adapter.info;
-  const hardware = {
-    vendor: info.vendor,
-    architecture: info.architecture,
-    device: info.device,
-    description: info.description,
-    isFallbackAdapter: info.isFallbackAdapter,
-  };
-  emit({ type: "adapter", ...hardware, userAgent: navigator.userAgent });
-  if (info.isFallbackAdapter || /swiftshader|llvmpipe|software/i.test(hardware.description)) throw new Error("Software GPU rejected");
-  env.backends.onnx.webgpu.adapter = adapter;
-  if (options.mode === "probe") return { hardware };
-  const device = await adapter.requestDevice({
-    requiredFeatures: adapter.features.has("shader-f16") ? ["shader-f16"] : [],
-    requiredLimits: { maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize, maxBufferSize: adapter.limits.maxBufferSize },
-  });
-  env.backends.onnx.webgpu.device = device;
-  const liveBuffers = new Set();
-  let peakOwnedBuffers = 0;
-  const trackedDevices = new WeakSet();
-  const trackDevice = (gpuDevice) => {
-    if (trackedDevices.has(gpuDevice)) return;
-    trackedDevices.add(gpuDevice);
-    const createBuffer = gpuDevice.createBuffer.bind(gpuDevice);
-    gpuDevice.createBuffer = (descriptor) => {
-      const buffer = createBuffer(descriptor);
-      if (descriptor.label?.startsWith("transformers-beam-")) {
-        liveBuffers.add(buffer);
-        peakOwnedBuffers = Math.max(peakOwnedBuffers, liveBuffers.size);
-        const destroy = buffer.destroy.bind(buffer);
-        buffer.destroy = () => {
-          liveBuffers.delete(buffer);
-          destroy();
-        };
-      }
-      return buffer;
-    };
-  };
-  trackDevice(device);
-  const errors = [];
-  device.addEventListener("uncapturederror", (event) => {
-    errors.push(event.error.message);
-    console.error(event.error.message);
-  });
-  device.lost.then((value) => {
-    console.error("DEVICE_LOST", value.reason, value.message);
-  });
-
-  if (options.mode === "validate") {
-    const cases = [
-      ["float32", Float32Array, [3, 4]],
-      ["float32", Float32Array, [3, 1]],
-      ["float16", Uint16Array, [3, 4]],
-      ["float16", Uint16Array, [3, 2]],
-      ["float16", Uint16Array, [3, 3]],
-      ["int64", BigInt64Array, [3, 2]],
-      ["uint8", Uint8Array, [3, 4]],
-      ["bool", Uint8Array, [3, 4]],
-    ];
-    const results = [];
-    for (const [type, ArrayType, dims] of cases) {
-      const count = dims.reduce((a, b) => a * b, 1);
-      const data = ArrayType.from({ length: count }, (_, i) => (type === "int64" ? BigInt(i + 1) : type === "bool" ? i % 2 : i + 1));
-      const size = Math.ceil(data.byteLength / 4) * 4;
-      const input = device.createBuffer({ size, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST });
-      const padded = new Uint8Array(size);
-      padded.set(new Uint8Array(data.buffer));
-      device.queue.writeBuffer(input, 0, padded);
-      let downloads = 0;
-      const original = new Tensor(
-        getTensorConstructor().fromGpuBuffer(input, {
-          dataType: type,
-          dims,
-          download: async () => {
-            ++downloads;
-            const staging = device.createBuffer({ size, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
-            const encoder = device.createCommandEncoder();
-            encoder.copyBufferToBuffer(input, 0, staging, 0, size);
-            device.queue.submit([encoder.finish()]);
-            await staging.mapAsync(GPUMapMode.READ);
-            const result = new ArrayType(staging.getMappedRange().slice(0, data.byteLength));
-            staging.destroy();
-            return result;
-          },
-        }),
-      );
-      const selected = await index_select_async(original, [2, 0, 2]);
-      const selectedLocation = selected.location;
-      const aligned = (dims[1] * ArrayType.BYTES_PER_ELEMENT) % 4 === 0;
-      if (aligned && selected.ort_tensor.gpuBuffer.size % 16 !== 0) throw new Error("GPU output is not padded for ONNX Runtime");
-      if (selectedLocation !== (aligned ? "gpu-buffer" : "cpu")) throw new Error("Unexpected row selection location");
-      if (aligned && (downloads !== 0 || original.location !== "gpu-buffer")) throw new Error("GPU selection downloaded the source");
-      const chained = await index_select_async(selected, [1, 0]);
-      const actual = await chained.ort_tensor.getData();
-      const expected = [...data.slice(0, dims[1]), ...data.slice(2 * dims[1], 3 * dims[1])];
-      const actualValues = type === "float16" ? new Uint16Array(actual.buffer, actual.byteOffset, actual.byteLength / 2) : actual;
-      if (!equal([...actualValues], expected)) throw new Error("Typed/chained GPU selection mismatch: " + type);
-      chained.dispose();
-      selected.dispose();
-      // Source buffers must still be usable after disposing selected tensors.
-      const remaining = await original.ort_tensor.getData();
-      if (!equal([...remaining], [...data])) throw new Error("Source ownership violated");
-      original.dispose();
-      input.destroy();
-      if (liveBuffers.size) throw new Error("GPU row buffers were not released");
-      const result = { type: "validation", dtype: type, dims, selectedLocation, chainedAndSourceOwnership: true };
-      results.push(result);
-      emit(result);
-    }
-    await device.queue.onSubmittedWorkDone();
-    if (errors.length) throw new Error(errors.join("\n"));
-    return { hardware, results, errors, peakOwnedBuffers, remainingOwnedBuffers: liveBuffers.size };
-  }
-
-  if (options.mode === "micro") {
-    const results = [];
-    for (const dims of [
-      [4, 8, 128, 64],
-      [4, 8, 1024, 64],
-      [8, 16, 2048, 64],
-    ]) {
-      const elements = dims.reduce((a, b) => a * b, 1);
-      const data = Float32Array.from({ length: elements }, (_, i) => i % 997);
-      const input = device.createBuffer({ size: data.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST });
-      device.queue.writeBuffer(input, 0, data);
-      const indices = Array.from({ length: dims[0] }, (_, i) => (i * 3 + 1) % dims[0]);
-      const source = () =>
-        new Tensor(
-          getTensorConstructor().fromGpuBuffer(input, {
-            dataType: "float32",
-            dims,
-            download: async () => {
-              const staging = device.createBuffer({ size: data.byteLength, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
-              const encoder = device.createCommandEncoder();
-              encoder.copyBufferToBuffer(input, 0, staging, 0, data.byteLength);
-              device.queue.submit([encoder.finish()]);
-              await staging.mapAsync(GPUMapMode.READ);
-              const copy = new Float32Array(staging.getMappedRange().slice(0));
-              staging.unmap();
-              staging.destroy();
-              return copy;
-            },
-          }),
-        );
-      const durations = [];
-      let outputLocation;
-      for (let repeat = 0; repeat < 12; ++repeat) {
-        const tensor = source();
-        await device.queue.onSubmittedWorkDone();
-        const start = performance.now();
-        const output = await index_select_async(tensor, indices);
-        await device.queue.onSubmittedWorkDone();
-        const elapsed = performance.now() - start;
-        outputLocation = output.location;
-        if (repeat >= 2) durations.push(elapsed);
-        if (repeat === 0) {
-          const actual = await output.ort_tensor.getData();
-          const rowSize = elements / dims[0];
-          for (let row = 0; row < dims[0]; ++row) {
-            for (let i = 0; i < rowSize; ++i) {
-              if (actual[row * rowSize + i] !== data[indices[row] * rowSize + i]) throw new Error("Row selection mismatch");
-            }
-          }
-        }
-        output.dispose();
-        tensor.dispose();
-      }
-      input.destroy();
-      const result = { type: "micro", dims, bytes: data.byteLength, medianMs: median(durations), samplesMs: durations, outputLocation };
-      results.push(result);
-      emit(result);
-    }
-    if (errors.length) throw new Error(errors.join("\n"));
-    return { hardware, results, errors, peakOwnedBuffers, remainingOwnedBuffers: liveBuffers.size };
-  }
-
-  const models = options.models ?? ["hf-internal-testing/tiny-random-T5ForConditionalGeneration", "hf-internal-testing/tiny-random-LlamaForCausalLM"];
-  const results = [];
-  for (const modelId of models) {
-    const Model = /T5/.test(modelId) ? AutoModelForSeq2SeqLM : AutoModelForCausalLM;
-    const model = await Model.from_pretrained(modelId, { device: options.device ?? "webgpu", dtype: options.dtype ?? "fp32" });
-    trackDevice(await env.backends.onnx.webgpu.device);
-    const tokenizer = await AutoTokenizer.from_pretrained(modelId);
-    tokenizer.padding_side = "left";
-    let cacheStats = [];
-    const reorder = options.cpuRowSelection
-      ? async (cache, indices) => {
-          const entries = {};
-          for (const [key, tensor] of Object.entries(cache)) {
-            if (key.includes("encoder")) {
-              entries[key] = tensor;
-              continue;
-            }
-            const location = tensor.location;
-            await tensor.ort_tensor.getData(false);
-            entries[key] = index_select(tensor, model._get_cache_indices(key, indices));
-            if (location === "gpu-buffer") tensor.dispose();
-          }
-          return new DynamicCache(entries);
-        }
-      : model._reorder_cache.bind(model);
-    model._reorder_cache = async (cache, indices) => {
-      const before = Object.values(cache).map((t) => ({ location: t.location, size: t.size }));
-      const start = performance.now();
-      const result = await reorder(cache, indices);
-      cacheStats.push({ ms: performance.now() - start, before, after: Object.values(result).map((t) => t.location) });
-      return result;
-    };
-    const configs = [
-      { name: "standard", num_beams: 4, num_return_sequences: 2 },
-      { name: "diverse", num_beams: 4, num_beam_groups: 2, diversity_penalty: 0.5, num_return_sequences: 2 },
-      { name: "sampling", num_beams: 4, num_return_sequences: 2, do_sample: true, top_k: 10 },
-      { name: "batched", num_beams: 4, num_return_sequences: 2 },
-    ];
-    for (const { name, ...config } of configs.filter((config) => !options.modes || options.modes.includes(config.name))) {
-      const texts = name === "batched" ? ["hello", "a longer input"] : ["hello"];
-      const inputs = tokenizer(texts, { padding: true });
-      const durations = [];
-      let expected;
-      for (let repeat = 0; repeat < (options.repeats ?? 4); ++repeat) {
-        random.seed(42);
-        cacheStats = [];
-        const start = performance.now();
-        const output = await model.generate({ ...inputs, ...config, max_new_tokens: options.tokens ?? 16, eos_token_id: null, return_dict_in_generate: true });
-        const elapsed = performance.now() - start;
-        if (liveBuffers.size) throw new Error("GPU row buffers leaked after generation");
-        const tokens = output.sequences.tolist();
-        if (output.past_key_values !== null) throw new Error("Unexpected beam cache output");
-        if (expected && !equal(tokens, expected)) throw new Error("Repeated generation changed output: " + name);
-        expected = tokens;
-        if (repeat > 0) durations.push(elapsed);
-      }
-      if (name === "batched") {
-        for (let i = 0; i < texts.length; ++i) {
-          const single = await model.generate({ ...tokenizer(texts[i]), ...config, max_new_tokens: options.tokens ?? 16, eos_token_id: null });
-          const tail = (rows) => rows.map((row) => row.slice(-(options.tokens ?? 16)));
-          if (!equal(tail(expected.slice(i * 2, i * 2 + 2)), tail(single.tolist()))) throw new Error("Batch independence failed");
-        }
-      }
-      if (!options.cpuRowSelection && cacheStats.some((step) => step.before.some((tensor) => tensor.location === "gpu-buffer")) && peakOwnedBuffers === 0) {
-        throw new Error("GPU buffer lifetime tracking did not observe the row-copy path");
-      }
-      const result = {
-        type: "generation",
-        modelId,
-        name,
-        device: options.device ?? "webgpu",
-        medianMs: median(durations),
-        samplesMs: durations,
-        tokens: expected,
-        cacheStats,
-      };
-      results.push(result);
-      emit({ ...result, tokens: undefined, cacheStats: undefined });
-    }
-    await model.dispose();
-  }
-  await device.queue.onSubmittedWorkDone();
-  if (errors.length) throw new Error(errors.join("\n"));
-  return { hardware, results, errors, peakOwnedBuffers, remainingOwnedBuffers: liveBuffers.size };
-};
diff --git a/scripts/beam-gpu/build.mjs b/scripts/beam-gpu/build.mjs
deleted file mode 100644
index d8cf63439..000000000
--- a/scripts/beam-gpu/build.mjs
+++ /dev/null
@@ -1,16 +0,0 @@
-import path from "node:path";
-import { createRequire } from "node:module";
-import { fileURLToPath } from "node:url";
-const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
-const require = createRequire(path.join(root, "packages/transformers/package.json"));
-const { build } = require("esbuild");
-const { ignoreModulesPlugin } = await import("../../packages/transformers/scripts/build/plugins/ignoreModulesPlugin.mjs");
-await build({
-  entryPoints: [path.join(root, "scripts/beam-gpu/browser.js")],
-  bundle: true,
-  platform: "browser",
-  format: "esm",
-  sourcemap: true,
-  outfile: process.env.BEAM_APP_OUT ?? "/workspace/beam-gpu/runner/app.js",
-  plugins: [ignoreModulesPlugin(["./onnx-node.js", "sharp", "fs", "path", "url", "stream", "stream/promises"])],
-});
diff --git a/scripts/beam-gpu/candidates.mjs b/scripts/beam-gpu/candidates.mjs
deleted file mode 100644
index 35cd41515..000000000
--- a/scripts/beam-gpu/candidates.mjs
+++ /dev/null
@@ -1,27 +0,0 @@
-import { performance } from "node:perf_hooks";
-import { selectBeamCandidates } from "../../packages/transformers/src/generation/beam_search_utils.js";
-const median = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)];
-for (const vocab of [32000, 151936]) {
-  const scores = Float32Array.from({ length: vocab }, (_, i) => Math.sin(i * 17) * 10);
-  for (const count of [8, 50]) {
-    const baseline = () =>
-      Array.from(scores, (score, token) => ({ score: -3 + score, token: BigInt(token), beam_idx: 0 }))
-        .sort((a, b) => b.score - a.score)
-        .slice(0, count);
-    const optimized = () => selectBeamCandidates(scores, -3, 0, count);
-    const stringify = (x) => JSON.stringify(x, (_, value) => (typeof value === "bigint" ? String(value) : value));
-    if (stringify(baseline()) !== stringify(optimized())) throw new Error("Candidate selection mismatch");
-    const times = {};
-    for (const [name, fn] of Object.entries({ baseline, optimized })) {
-      const samples = [];
-      for (let repeat = 0; repeat < 15; ++repeat) {
-        const start = performance.now();
-        fn();
-        const ms = performance.now() - start;
-        if (repeat >= 5) samples.push(ms);
-      }
-      times[name] = { medianMs: median(samples), samplesMs: samples };
-    }
-    console.log(JSON.stringify({ vocab, count, ...times, identical: true }));
-  }
-}
diff --git a/scripts/beam-gpu/run.sh b/scripts/beam-gpu/run.sh
deleted file mode 100755
index deffb1c54..000000000
--- a/scripts/beam-gpu/run.sh
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-OUTPUT_ROOT=${BEAM_OUTPUT_ROOT:-/workspace/beam-gpu}
-mkdir -p "$OUTPUT_ROOT"
-printf "running\n" > "$OUTPUT_ROOT/final-exit-status"
-trap 'code=$?; printf "%s\n" "$code" > "$OUTPUT_ROOT/final-exit-status"' EXIT
-git rev-parse HEAD > "$OUTPUT_ROOT/final-source-commit"
-git status --porcelain > "$OUTPUT_ROOT/final-source-status"
-node scripts/beam-gpu/build.mjs
-run_case() {
-  BEAM_OPTIONS="$2" BEAM_RESULT="$OUTPUT_ROOT/$1.json" node scripts/beam-gpu/runner.mjs
-}
-run_case final-validation '{"mode":"validate"}'
-run_case final-micro '{"mode":"micro"}'
-run_case final-generation '{"mode":"generation","tokens":16,"repeats":4}'
-run_case smollm-optimized '{"mode":"generation","models":["onnx-community/SmolLM2-135M-Instruct-ONNX"],"dtype":"fp32","modes":["standard","batched"],"tokens":32,"repeats":4}'
-run_case final-stress '{"mode":"generation","models":["hf-internal-testing/tiny-random-LlamaForCausalLM"],"modes":["standard"],"tokens":8,"repeats":25}'
-node scripts/beam-gpu/candidates.mjs > "$OUTPUT_ROOT/candidates-remote.jsonl"
-pnpm build > "$OUTPUT_ROOT/final-build.log" 2>&1
diff --git a/scripts/beam-gpu/runner.mjs b/scripts/beam-gpu/runner.mjs
deleted file mode 100644
index bb6adc234..000000000
--- a/scripts/beam-gpu/runner.mjs
+++ /dev/null
@@ -1,87 +0,0 @@
-import http from "node:http";
-import fs from "node:fs";
-import path from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
-const root = process.env.BEAM_PROJECT_ROOT ?? path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
-const runner = process.env.BEAM_RUNNER_ROOT ?? "/workspace/beam-gpu/runner";
-const { chromium } = await import(pathToFileURL(path.join(process.env.BEAM_PLAYWRIGHT_ROOT ?? runner, "node_modules/playwright/index.mjs")));
-const ort = path.join(root, "packages/transformers/node_modules/onnxruntime-web/dist");
-const cache = path.join(runner, "model-cache");
-fs.mkdirSync(cache, { recursive: true });
-const options = JSON.parse(process.env.BEAM_OPTIONS ?? '{"mode":"probe"}');
-const server = http.createServer(async (req, res) => {
-  res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
-  res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
-  try {
-    const pathname = new URL(req.url, "http://localhost").pathname;
-    if (pathname.startsWith("/hf/")) {
-      const relative = pathname.slice(4);
-      const local = path.join(cache, relative);
-      if (!fs.existsSync(local)) {
-        const upstream = await fetch("https://huggingface.co/" + relative);
-        if (!upstream.ok) {
-          res.writeHead(upstream.status);
-          res.end(await upstream.text());
-          return;
-        }
-        fs.mkdirSync(path.dirname(local), { recursive: true });
-        fs.writeFileSync(local, Buffer.from(await upstream.arrayBuffer()));
-      }
-      res.end(fs.readFileSync(local));
-      return;
-    }
-    if (pathname === "/") {
-      res.setHeader("Content-Type", "text/html");
-      res.end('');
-      return;
-    }
-    const file = pathname.startsWith("/ort/") ? path.join(ort, path.basename(pathname)) : path.join(runner, path.basename(pathname));
-    res.setHeader("Content-Type", file.endsWith(".wasm") ? "application/wasm" : "text/javascript");
-    res.end(fs.readFileSync(file));
-  } catch (error) {
-    res.statusCode = 500;
-    res.end(String(error));
-  }
-});
-await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
-const browser = await chromium.launch({
-  headless: true,
-  dumpio: process.env.BEAM_DEBUG === "1",
-  channel: "chromium",
-  args: [
-    "--no-sandbox",
-    "--enable-gpu",
-    "--disable-gpu-sandbox",
-    "--enable-unsafe-webgpu",
-    "--ignore-gpu-blocklist",
-    "--use-angle=vulkan",
-    "--enable-features=Vulkan,VulkanFromANGLE,DefaultANGLEVulkan",
-    "--disable-vulkan-surface",
-    "--disable-dev-shm-usage",
-  ],
-});
-try {
-  const page = await browser.newPage();
-  page.on("console", (message) => console.log(message.type(), message.text()));
-  page.on("pageerror", (error) => console.error("PAGE_ERROR", error.message));
-  await page.goto("http://127.0.0.1:" + server.address().port);
-  await page.waitForFunction(() => typeof window.runBeamGPU === "function");
-  const result = await page.evaluate((options) => window.runBeamGPU(options), options);
-  const output = process.env.BEAM_RESULT ?? path.join(runner, "result.json");
-  fs.writeFileSync(
-    output,
-    JSON.stringify(
-      { timestamp: new Date().toISOString(), browser: browser.version(), options, ...result },
-      (_, x) => (typeof x === "bigint" ? x.toString() : x),
-      2,
-    ),
-  );
-  console.log("SAVED", output);
-} catch (error) {
-  const cdp = await browser.newBrowserCDPSession();
-  console.error("GPU_DIAGNOSTICS", JSON.stringify(await cdp.send("SystemInfo.getInfo")));
-  throw error;
-} finally {
-  await browser.close();
-  server.close();
-}

From 4cf5f1850afe8b8a2c5e12ccee03df5e93704f97 Mon Sep 17 00:00:00 2001
From: Dan Levy 
Date: Thu, 22 Oct 2026 08:49:28 -0600
Subject: [PATCH 21/21] Align beam timestamps with the predicting-row
 correction in PR #1809

Preserve original prompt rows during normalization, align EOS and token-limit outputs through their predicting queries, and trim seek segments without retaining a discarded next query. Compare selected beam histories against the independent PR #1809 algorithm and update its real ASR goldens. Remove standalone benchmark scripts from the published patch while preserving local copies.
---
 .../docs/source/guides/beam-search.md         |  15 +-
 .../src/models/whisper/modeling_whisper.js    |  77 +++--
 packages/transformers/src/utils/maths.js      |   7 +-
 ..._pipelines_automatic_speech_recognition.js | 244 ++++++++-------
 .../utils/fixtures/whisper_timestamp_1809.js  | 107 +++++++
 .../transformers/tests/utils/maths.test.js    |  15 +-
 .../utils/whisper_beam_timestamps.test.js     | 113 +++----
 scripts/beam-gpu/.gitignore                   |   1 -
 scripts/beam-gpu/README.md                    |  51 ----
 scripts/beam-gpu/RESULTS.md                   | 113 -------
 scripts/beam-gpu/bootstrap.sh                 |  31 --
 scripts/beam-gpu/browser.js                   | 286 ------------------
 scripts/beam-gpu/build.mjs                    |  16 -
 scripts/beam-gpu/candidates.mjs               |  27 --
 scripts/beam-gpu/run.sh                       |  19 --
 scripts/beam-gpu/runner.mjs                   |  87 ------
 scripts/beam-timestamps/.gitignore            |   4 -
 scripts/beam-timestamps/README.md             |  71 -----
 scripts/beam-timestamps/browser.html          |  14 -
 scripts/beam-timestamps/harness.mjs           | 156 ----------
 scripts/beam-timestamps/native.mjs            |  26 --
 scripts/beam-timestamps/offline-tests.js      |   5 -
 scripts/beam-timestamps/results/.gitkeep      |   0
 scripts/beam-timestamps/verify-results.mjs    |  73 -----
 24 files changed, 343 insertions(+), 1215 deletions(-)
 create mode 100644 packages/transformers/tests/utils/fixtures/whisper_timestamp_1809.js
 delete mode 100644 scripts/beam-gpu/.gitignore
 delete mode 100644 scripts/beam-gpu/README.md
 delete mode 100644 scripts/beam-gpu/RESULTS.md
 delete mode 100755 scripts/beam-gpu/bootstrap.sh
 delete mode 100644 scripts/beam-gpu/browser.js
 delete mode 100644 scripts/beam-gpu/build.mjs
 delete mode 100644 scripts/beam-gpu/candidates.mjs
 delete mode 100755 scripts/beam-gpu/run.sh
 delete mode 100644 scripts/beam-gpu/runner.mjs
 delete mode 100644 scripts/beam-timestamps/.gitignore
 delete mode 100644 scripts/beam-timestamps/README.md
 delete mode 100644 scripts/beam-timestamps/browser.html
 delete mode 100644 scripts/beam-timestamps/harness.mjs
 delete mode 100644 scripts/beam-timestamps/native.mjs
 delete mode 100644 scripts/beam-timestamps/offline-tests.js
 delete mode 100644 scripts/beam-timestamps/results/.gitkeep
 delete mode 100644 scripts/beam-timestamps/verify-results.mjs

diff --git a/packages/transformers/docs/source/guides/beam-search.md b/packages/transformers/docs/source/guides/beam-search.md
index 6ada53dd8..111ea2d5f 100644
--- a/packages/transformers/docs/source/guides/beam-search.md
+++ b/packages/transformers/docs/source/guides/beam-search.md
@@ -86,8 +86,19 @@ const model = await AutoModelForSeq2SeqLM.from_pretrained(model_id, {
 ## Restrictions
 
 Beam search rejects streamers and classifier-free guidance (`guidance_scale > 1`).
-Decoder-only multimodal inputs and `output_attentions` (including Whisper token
-timestamps) are not supported with beams.
+Decoder-only multimodal inputs are not supported with beams.
+Whisper token timestamps support short-form batches and multiple returned
+hypotheses. Long-form seek requires one input and one returned sequence.
+Timestamp alignment follows each hypothesis's beam ancestry and includes the
+last prompt query, which predicts the first generated token. Normalization uses
+the original prompt and generated attention rows before cropping all but the
+final prompt row.
+
+With `output_attentions: true`, attention tensors contain raw per-step beam rows;
+`beam_indices` identifies the rows used for each selected hypothesis.
+`sequence_lengths` excludes right padding. Internally retained attentions are
+released after timestamp extraction unless explicitly requested by the caller.
+Attention history grows with model size, beam count, and generated sequence length.
 Diverse beam search cannot be combined with `do_sample: true`. Nucleus sampling
 (`top_p`) is not implemented by the generation sampler.
 
diff --git a/packages/transformers/src/models/whisper/modeling_whisper.js b/packages/transformers/src/models/whisper/modeling_whisper.js
index 2f3c2e6d2..dbf2e8806 100644
--- a/packages/transformers/src/models/whisper/modeling_whisper.js
+++ b/packages/transformers/src/models/whisper/modeling_whisper.js
@@ -1,4 +1,4 @@
-import { Tensor } from '../../utils/tensor.js';
+import { Tensor, std_mean } from '../../utils/tensor.js';
 import { PreTrainedModel } from '../modeling_utils.js';
 import { WhisperGenerationConfig } from './generation_whisper.js';
 import { whisper_language_to_code } from './common_whisper.js';
@@ -374,14 +374,14 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
                 }
 
                 // Align only the retained segment, before normalization and DTW.
-                // Include one terminal slot so the final retained token can use its
-                // query from the next forward, when that query exists.
+                // Every retained token uses the query that predicted it; do not
+                // include the next segment token in normalization.
                 let seek_token_timestamps;
                 if (return_token_timestamps) {
                     outputs.num_beams = generation_config.num_beams;
                     const valid_length = Math.min(
                         Number(outputs.sequence_lengths?.data[0] ?? raw_sequence.dims[1]),
-                        init_tokens.length + tokens_to_keep + 1,
+                        init_tokens.length + tokens_to_keep,
                     );
                     outputs.sequence_lengths?.dispose();
                     outputs.sequence_lengths = new Tensor('int64', [BigInt(valid_length)], [1]);
@@ -504,10 +504,9 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
         for (let result = 0; result < shape[0]; ++result) {
             const valid = lengths ? Number(lengths[result]) : shape[1];
             const generated = valid - num_input_ids;
-            // Forward zero contains prefix queries only. Each later forward contains
-            // the preceding generated token. The final token (including EOS) has no
-            // query of its own; assign it the last aligned boundary.
-            const queries = Math.max(0, generated - 1);
+            // Each forward predicts one generated token, including EOS. The last
+            // prefill query predicts the first token (the convention in PR #1809).
+            const queries = Math.max(0, generated);
             if (!queries) continue;
             const firstRow = ancestry ? Number(ancestry[result][0]) : result;
             const inputIndex = Math.floor(firstRow / (generate_outputs.num_beams ?? 1));
@@ -518,50 +517,51 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
             const matrix = Array.from({ length: queries }, () => new Float32Array(frames));
             for (const [layer, head] of alignment_heads) {
                 const weights = [];
-                for (let token = 0; token < queries; ++token) {
-                    const step = token + 1;
+                for (let step = 0; step < queries; ++step) {
                     const source = steps[step]?.[layer];
                     if (!source || head >= source.dims[1])
                         throw new Error('Missing timestamp alignment attention head or step.');
                     const row = ancestry ? Number(ancestry[result][step]) : result;
                     if (row < 0 || row >= source.dims[0]) throw new Error('Invalid timestamp beam ancestry.');
-                    // Convert only the selected row/head/query and valid frames, rather
-                    // than all beam rows and heads for every selected hypothesis.
-                    const offset =
-                        ((row * source.dims[1] + head) * source.dims[2] + source.dims[2] - 1) * source.dims[3];
-                    const selected = new Tensor(source.type, source.data.slice(offset, offset + frames), [frames]);
-                    const numeric = selected.to('float32');
-                    weights.push(Float32Array.from(numeric.data));
-                    if (numeric !== selected) numeric.dispose();
-                    selected.dispose();
+                    // Preserve original prefill rows for normalization. Uncached later
+                    // forwards repeat the prefix: take only their final query.
+                    const firstQuery = step === 0 ? 0 : source.dims[2] - 1;
+                    for (let query = firstQuery; query < source.dims[2]; ++query) {
+                        const offset = ((row * source.dims[1] + head) * source.dims[2] + query) * source.dims[3];
+                        const selected = new Tensor(source.type, source.data.slice(offset, offset + frames), [frames]);
+                        const numeric = selected.to('float32');
+                        weights.push(Float32Array.from(numeric.data));
+                        if (numeric !== selected) numeric.dispose();
+                        selected.dispose();
+                    }
                 }
-                // Exclude prefix queries, other beams, and padding before statistics,
-                // matching Transformers v4.57.1 Whisper alignment.
-                for (let frame = 0; frame < frames; ++frame) {
-                    let average = 0;
-                    for (const row of weights) average += row[frame] / queries;
-                    let variance = 0;
-                    for (const row of weights) variance += (row[frame] - average) ** 2 / queries;
-                    // Torch uses fp32 statistics and elementwise arithmetic. Rounding
-                    // matters when near-equal DTW costs choose different boundaries.
-                    average = Math.fround(average);
-                    const scale = Math.fround(Math.sqrt(variance));
-                    for (const row of weights)
-                        row[frame] = scale > 0 ? Math.fround(Math.fround(row[frame] - average) / scale) : 0;
+                // Normalize before cropping prompt rows, matching PR #1809's
+                // single-beam algorithm while excluding other hypotheses and padding.
+                const allWeights = new Tensor('float32', Float32Array.from(weights.flatMap((row) => Array.from(row))), [
+                    weights.length,
+                    frames,
+                ]);
+                const [std, average] = std_mean(allWeights, 0, 0);
+                for (const row of weights) {
+                    for (let frame = 0; frame < frames; ++frame) {
+                        row[frame] = std.data[frame] > 0 ? (row[frame] - average.data[frame]) / std.data[frame] : 0;
+                    }
                 }
+                allWeights.dispose();
+                std.dispose();
+                average.dispose();
+                const skipped = weights.length - queries;
                 for (let token = 0; token < queries; ++token) {
                     // Python leaves recordings too short for reflection padding unchanged.
                     const filtered =
                         frames <= Math.floor(median_filter_width / 2)
-                            ? weights[token]
-                            : medianFilter(weights[token], median_filter_width);
-                    for (let frame = 0; frame < frames; ++frame)
-                        matrix[token][frame] -= filtered[frame] / alignment_heads.length;
+                            ? weights[skipped + token]
+                            : medianFilter(weights[skipped + token], median_filter_width);
+                    for (let frame = 0; frame < frames; ++frame) matrix[token][frame] += filtered[frame];
                 }
             }
             const [text, times] = dynamic_time_warping(
-                matrix.map((row) => Array.from(row)),
-                true,
+                matrix.map((row) => Array.from(row, (value) => -Math.fround(value / alignment_heads.length))),
             );
             let last = 0;
             for (let i = 0; i < text.length; ++i) {
@@ -570,7 +570,6 @@ export class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
                     timestamps.data[result * shape[1] + num_input_ids + text[i]] = last;
                 }
             }
-            timestamps.data[result * shape[1] + valid - 1] = last;
         }
 
         return timestamps;
diff --git a/packages/transformers/src/utils/maths.js b/packages/transformers/src/utils/maths.js
index 47789ff05..1ba3865c3 100644
--- a/packages/transformers/src/utils/maths.js
+++ b/packages/transformers/src/utils/maths.js
@@ -966,18 +966,15 @@ export function bankers_round(x) {
  * Measures similarity between two temporal sequences (e.g., input audio and output tokens
  * to generate token-level timestamps).
  * @param {number[][]} matrix
- * @param {boolean} [float32_cost=false] Accumulate costs in float32 to match Whisper alignment.
  * @returns {number[][]}
  */
-export function dynamic_time_warping(matrix, float32_cost = false) {
+export function dynamic_time_warping(matrix) {
     const output_length = matrix.length;
     const input_length = matrix[0].length;
 
     const outputShape = [output_length + 1, input_length + 1];
 
-    const cost = Array.from({ length: outputShape[0] }, () =>
-        float32_cost ? new Float32Array(outputShape[1]).fill(Infinity) : Array(outputShape[1]).fill(Infinity),
-    );
+    const cost = Array.from({ length: outputShape[0] }, () => Array(outputShape[1]).fill(Infinity));
     cost[0][0] = 0;
 
     const trace = Array.from({ length: outputShape[0] }, () => Array(outputShape[1]).fill(-1));
diff --git a/packages/transformers/tests/pipelines/test_pipelines_automatic_speech_recognition.js b/packages/transformers/tests/pipelines/test_pipelines_automatic_speech_recognition.js
index fa941e542..a4473df4c 100644
--- a/packages/transformers/tests/pipelines/test_pipelines_automatic_speech_recognition.js
+++ b/packages/transformers/tests/pipelines/test_pipelines_automatic_speech_recognition.js
@@ -132,26 +132,26 @@ export default () => {
             const target = {
               text: " I have a dream. Good one day. This nation will rise up. Live out the true meaning of its dream.",
               chunks: [
-                { text: " I", timestamp: [1.36, 1.68] },
-                { text: " have", timestamp: [1.68, 1.94] },
-                { text: " a", timestamp: [1.94, 2.52] },
-                { text: " dream.", timestamp: [2.52, 2.74] },
-                { text: " Good", timestamp: [3.98, 4.18] },
-                { text: " one", timestamp: [4.18, 4.78] },
-                { text: " day.", timestamp: [4.78, 4.84] },
-                { text: " This", timestamp: [6.56, 7.2] },
-                { text: " nation", timestamp: [7.2, 7.84] },
-                { text: " will", timestamp: [7.84, 8.3] },
-                { text: " rise", timestamp: [8.3, 9.24] },
-                { text: " up.", timestamp: [9.84, 9.86] },
-                { text: " Live", timestamp: [10.56, 10.98] },
-                { text: " out", timestamp: [10.98, 11.02] },
-                { text: " the", timestamp: [11.02, 11.3] },
-                { text: " true", timestamp: [11.3, 11.58] },
-                { text: " meaning", timestamp: [11.58, 11.86] },
-                { text: " of", timestamp: [11.86, 12.06] },
-                { text: " its", timestamp: [12.06, 12.56] },
-                { text: " dream.", timestamp: [12.56, 12.58] },
+                { text: " I", timestamp: [0, 1.36] },
+                { text: " have", timestamp: [1.36, 1.68] },
+                { text: " a", timestamp: [1.68, 1.94] },
+                { text: " dream.", timestamp: [1.94, 2.54] },
+                { text: " Good", timestamp: [3.74, 3.98] },
+                { text: " one", timestamp: [3.98, 4.18] },
+                { text: " day.", timestamp: [4.18, 4.8] },
+                { text: " This", timestamp: [4.84, 6.56] },
+                { text: " nation", timestamp: [6.56, 7.2] },
+                { text: " will", timestamp: [7.2, 7.84] },
+                { text: " rise", timestamp: [7.84, 8.3] },
+                { text: " up.", timestamp: [8.3, 9.24] },
+                { text: " Live", timestamp: [10.2, 10.56] },
+                { text: " out", timestamp: [10.56, 10.98] },
+                { text: " the", timestamp: [10.98, 11.02] },
+                { text: " true", timestamp: [11.02, 11.3] },
+                { text: " meaning", timestamp: [11.3, 11.58] },
+                { text: " of", timestamp: [11.58, 11.86] },
+                { text: " its", timestamp: [11.86, 12.06] },
+                { text: " dream.", timestamp: [12.06, 12.58] },
               ],
             };
             expect(output).toBeCloseToNested(target, 1);
@@ -229,29 +229,27 @@ export default () => {
             const target = {
               text: " I have a dream that one day this nation will rise up and live out the true meaning of its creed.",
               chunks: [
-                { text: " I", timestamp: [1.4, 1.7] },
-                { text: " have", timestamp: [1.7, 1.88] },
-                { text: " a", timestamp: [1.88, 2.4] },
-                { text: " dream", timestamp: [2.4, 3.92] },
-                { text: " that", timestamp: [3.92, 4.22] },
-                { text: " one", timestamp: [4.22, 5.12] },
-                { text: " day", timestamp: [5.12, 6.66] },
-                { text: " this", timestamp: [6.66, 7.34] },
-                { text: " nation", timestamp: [7.34, 7.86] },
-                { text: " will", timestamp: [7.86, 8.34] },
-                { text: " rise", timestamp: [8.34, 9.9] },
-                { text: " up", timestamp: [9.9, 10.3] },
-                { text: " and", timestamp: [10.3, 10.6] },
-                { text: " live", timestamp: [10.6, 10.86] },
-                { text: " out", timestamp: [10.86, 11.04] },
-                { text: " the", timestamp: [11.04, 11.14] },
-                { text: " true", timestamp: [11.34, 11.38] },
-                { text: " meaning", timestamp: [11.62, 11.78] },
-                { text: " of", timestamp: [11.78, 12.12] },
-                { text: " its", timestamp: [12.12, 12.64] },
-                // The fixture is 13 seconds; the final valid encoder frame starts at 12.98.
-                // Aligning padded silence used to place this boundary beyond the recording.
-                { text: " creed.", timestamp: [12.64, 12.98] },
+                { text: " I", timestamp: [0, 1.4] },
+                { text: " have", timestamp: [1.4, 1.7] },
+                { text: " a", timestamp: [1.7, 1.88] },
+                { text: " dream", timestamp: [1.88, 2.4] },
+                { text: " that", timestamp: [2.4, 3.92] },
+                { text: " one", timestamp: [3.92, 4.22] },
+                { text: " day", timestamp: [4.22, 5.12] },
+                { text: " this", timestamp: [5.12, 6.66] },
+                { text: " nation", timestamp: [6.66, 7.34] },
+                { text: " will", timestamp: [7.34, 7.86] },
+                { text: " rise", timestamp: [7.86, 8.34] },
+                { text: " up", timestamp: [8.34, 9.9] },
+                { text: " and", timestamp: [9.9, 10.3] },
+                { text: " live", timestamp: [10.3, 10.6] },
+                { text: " out", timestamp: [10.6, 10.86] },
+                { text: " the", timestamp: [10.86, 11.04] },
+                { text: " true", timestamp: [11.04, 11.14] },
+                { text: " meaning", timestamp: [11.38, 11.62] },
+                { text: " of", timestamp: [11.62, 11.78] },
+                { text: " its", timestamp: [11.78, 12.12] },
+                { text: " creed.", timestamp: [12.12, 12.66] },
               ],
             };
             expect(output).toBeCloseToNested(target, 1);
@@ -341,86 +339,86 @@ export default () => {
           const target = {
             text: " everyday style. True classic delivers premium essentials built for real life. Grab yours at Target, Costco, or head to TrueClassic.com slash P4P. Get hooked up today. Now before we go, just want to give a big shout out to the CEO and founder Ryan brother for coming on our show and just showing some love. Now let's get back to the episode. I mean, like I said, we're going through that. We're losing stars. And then we kind of...",
             chunks: [
-              { text: " everyday", timestamp: [0.42, 0.82] },
-              { text: " style.", timestamp: [0.82, 1.3] },
-              { text: " True", timestamp: [1.56, 1.9] },
-              { text: " classic", timestamp: [1.9, 2.5] },
-              { text: " delivers", timestamp: [2.5, 3.02] },
-              { text: " premium", timestamp: [3.02, 3.54] },
-              { text: " essentials", timestamp: [3.54, 3.84] },
-              { text: " built", timestamp: [3.84, 4.08] },
-              { text: " for", timestamp: [4.08, 4.4] },
-              { text: " real", timestamp: [4.4, 4.8] },
-              { text: " life.", timestamp: [4.92, 5.46] },
-              { text: " Grab", timestamp: [5.64, 6.04] },
-              { text: " yours", timestamp: [6.04, 6.36] },
-              { text: " at", timestamp: [6.36, 6.84] },
-              { text: " Target,", timestamp: [6.84, 7.2] },
-              { text: " Costco,", timestamp: [7.7, 8.28] },
-              { text: " or", timestamp: [8.3, 8.5] },
-              { text: " head", timestamp: [8.5, 8.7] },
-              { text: " to", timestamp: [8.7, 8.92] },
-              { text: " TrueClassic", timestamp: [8.92, 9.68] },
-              { text: ".com", timestamp: [9.68, 10.78] },
-              { text: " slash", timestamp: [10.78, 11.3] },
-              { text: " P4P.", timestamp: [11.3, 12.86] },
-              { text: " Get", timestamp: [13.06, 13.3] },
-              { text: " hooked", timestamp: [13.3, 13.52] },
-              { text: " up", timestamp: [13.52, 13.92] },
-              { text: " today.", timestamp: [13.92, 14] },
-              { text: " Now", timestamp: [14.24, 14.46] },
-              { text: " before", timestamp: [14.46, 14.62] },
-              { text: " we", timestamp: [14.62, 14.82] },
-              { text: " go,", timestamp: [14.82, 15.06] },
-              { text: " just", timestamp: [15.24, 15.42] },
-              { text: " want", timestamp: [15.42, 15.48] },
-              { text: " to", timestamp: [15.48, 15.56] },
-              { text: " give", timestamp: [15.56, 15.68] },
-              { text: " a", timestamp: [15.68, 15.86] },
-              { text: " big", timestamp: [15.86, 16.1] },
-              { text: " shout", timestamp: [16.1, 16.28] },
-              { text: " out", timestamp: [16.28, 16.74] },
-              { text: " to", timestamp: [16.74, 16.9] },
-              { text: " the", timestamp: [16.9, 17.52] },
-              { text: " CEO", timestamp: [17.52, 17.86] },
-              { text: " and", timestamp: [17.86, 18.3] },
-              { text: " founder", timestamp: [18.3, 18.56] },
-              { text: " Ryan", timestamp: [18.6, 18.72] },
-              { text: " brother", timestamp: [18.86, 19.06] },
-              { text: " for", timestamp: [19.06, 19.2] },
-              { text: " coming", timestamp: [19.2, 19.36] },
-              { text: " on", timestamp: [19.36, 19.5] },
-              { text: " our", timestamp: [19.5, 19.74] },
-              { text: " show", timestamp: [19.74, 20.4] },
-              { text: " and", timestamp: [20.4, 20.6] },
-              { text: " just", timestamp: [20.6, 20.86] },
-              { text: " showing", timestamp: [20.86, 21.08] },
-              { text: " some", timestamp: [21.08, 21.26] },
-              { text: " love.", timestamp: [21.26, 21.48] },
-              { text: " Now", timestamp: [21.6, 22.3] },
-              { text: " let's", timestamp: [22.3, 22.46] },
-              { text: " get", timestamp: [22.46, 22.68] },
-              { text: " back", timestamp: [22.68, 23.06] },
-              { text: " to", timestamp: [23.06, 23.2] },
-              { text: " the", timestamp: [23.2, 23.56] },
-              { text: " episode.", timestamp: [23.56, 23.6] },
-              { text: " I", timestamp: [24.42, 24.6] },
-              { text: " mean,", timestamp: [24.6, 25.1] },
-              { text: " like", timestamp: [25.42, 25.54] },
-              { text: " I", timestamp: [25.54, 25.68] },
-              { text: " said,", timestamp: [25.68, 25.9] },
-              { text: " we're", timestamp: [25.9, 26.34] },
-              { text: " going", timestamp: [26.34, 26.58] },
-              { text: " through", timestamp: [26.58, 26.84] },
-              { text: " that.", timestamp: [26.84, 27] },
-              { text: " We're", timestamp: [27.24, 27.54] },
-              { text: " losing", timestamp: [27.54, 28.04] },
-              { text: " stars.", timestamp: [28.04, 28.96] },
-              { text: " And", timestamp: [29.3, 29.38] },
-              { text: " then", timestamp: [29.38, 29.58] },
-              { text: " we", timestamp: [29.58, 29.84] },
-              { text: " kind", timestamp: [29.84, 29.98] },
-              { text: " of", timestamp: [29.98, 29.98] },
+              { text: " everyday", timestamp: [0, 0.42] },
+              { text: " style.", timestamp: [0.42, 0.84] },
+              { text: " True", timestamp: [1.28, 1.56] },
+              { text: " classic", timestamp: [1.56, 1.9] },
+              { text: " delivers", timestamp: [1.9, 2.5] },
+              { text: " premium", timestamp: [2.5, 3.02] },
+              { text: " essentials", timestamp: [3.02, 3.54] },
+              { text: " built", timestamp: [3.54, 3.84] },
+              { text: " for", timestamp: [3.84, 4.08] },
+              { text: " real", timestamp: [4.08, 4.4] },
+              { text: " life.", timestamp: [4.4, 4.8] },
+              { text: " Grab", timestamp: [5.64, 5.64] },
+              { text: " yours", timestamp: [5.64, 6.04] },
+              { text: " at", timestamp: [6.04, 6.36] },
+              { text: " Target,", timestamp: [6.36, 6.86] },
+              { text: " Costco,", timestamp: [7.18, 7.72] },
+              { text: " or", timestamp: [8.26, 8.3] },
+              { text: " head", timestamp: [8.3, 8.5] },
+              { text: " to", timestamp: [8.5, 8.7] },
+              { text: " TrueClassic", timestamp: [8.7, 9.32] },
+              { text: ".com", timestamp: [9.32, 10.02] },
+              { text: " slash", timestamp: [10.02, 10.78] },
+              { text: " P4P.", timestamp: [10.78, 12.24] },
+              { text: " Get", timestamp: [12.84, 13.06] },
+              { text: " hooked", timestamp: [13.06, 13.3] },
+              { text: " up", timestamp: [13.3, 13.52] },
+              { text: " today.", timestamp: [13.52, 13.94] },
+              { text: " Now", timestamp: [14.18, 14.24] },
+              { text: " before", timestamp: [14.24, 14.46] },
+              { text: " we", timestamp: [14.46, 14.62] },
+              { text: " go,", timestamp: [14.62, 14.84] },
+              { text: " just", timestamp: [15.04, 15.24] },
+              { text: " want", timestamp: [15.24, 15.42] },
+              { text: " to", timestamp: [15.42, 15.48] },
+              { text: " give", timestamp: [15.48, 15.56] },
+              { text: " a", timestamp: [15.56, 15.68] },
+              { text: " big", timestamp: [15.68, 15.86] },
+              { text: " shout", timestamp: [15.86, 16.1] },
+              { text: " out", timestamp: [16.1, 16.28] },
+              { text: " to", timestamp: [16.28, 16.74] },
+              { text: " the", timestamp: [16.74, 16.9] },
+              { text: " CEO", timestamp: [16.9, 17.52] },
+              { text: " and", timestamp: [17.52, 17.86] },
+              { text: " founder", timestamp: [17.86, 18.3] },
+              { text: " Ryan", timestamp: [18.3, 18.56] },
+              { text: " brother", timestamp: [18.72, 18.86] },
+              { text: " for", timestamp: [18.86, 19.06] },
+              { text: " coming", timestamp: [19.06, 19.2] },
+              { text: " on", timestamp: [19.2, 19.36] },
+              { text: " our", timestamp: [19.36, 19.5] },
+              { text: " show", timestamp: [19.5, 19.74] },
+              { text: " and", timestamp: [19.74, 20.4] },
+              { text: " just", timestamp: [20.4, 20.6] },
+              { text: " showing", timestamp: [20.6, 20.86] },
+              { text: " some", timestamp: [20.86, 21.08] },
+              { text: " love.", timestamp: [21.08, 21.28] },
+              { text: " Now", timestamp: [21.46, 21.6] },
+              { text: " let's", timestamp: [21.6, 22.36] },
+              { text: " get", timestamp: [22.36, 22.46] },
+              { text: " back", timestamp: [22.46, 22.68] },
+              { text: " to", timestamp: [22.68, 23.06] },
+              { text: " the", timestamp: [23.06, 23.2] },
+              { text: " episode.", timestamp: [23.2, 23.58] },
+              { text: " I", timestamp: [23.6, 24.42] },
+              { text: " mean,", timestamp: [24.42, 24.62] },
+              { text: " like", timestamp: [25.08, 25.42] },
+              { text: " I", timestamp: [25.42, 25.54] },
+              { text: " said,", timestamp: [25.54, 25.7] },
+              { text: " we're", timestamp: [25.9, 26.12] },
+              { text: " going", timestamp: [26.12, 26.34] },
+              { text: " through", timestamp: [26.34, 26.58] },
+              { text: " that.", timestamp: [26.58, 26.86] },
+              { text: " We're", timestamp: [27.04, 27.34] },
+              { text: " losing", timestamp: [27.34, 27.54] },
+              { text: " stars.", timestamp: [27.54, 28.06] },
+              { text: " And", timestamp: [28.96, 29.3] },
+              { text: " then", timestamp: [29.3, 29.38] },
+              { text: " we", timestamp: [29.38, 29.58] },
+              { text: " kind", timestamp: [29.58, 29.84] },
+              { text: " of", timestamp: [29.84, 29.98] },
               { text: "...", timestamp: [29.98, 29.98] },
             ],
           };
diff --git a/packages/transformers/tests/utils/fixtures/whisper_timestamp_1809.js b/packages/transformers/tests/utils/fixtures/whisper_timestamp_1809.js
new file mode 100644
index 000000000..0354b7b92
--- /dev/null
+++ b/packages/transformers/tests/utils/fixtures/whisper_timestamp_1809.js
@@ -0,0 +1,107 @@
+// Independent pre-beam implementation with PR #1809's two indexing changes.
+// https://github.com/huggingface/transformers.js/pull/1809
+import { Tensor, cat, stack, std_mean, mean } from "../../../src/utils/tensor.js";
+import { medianFilter, dynamic_time_warping } from "../../../src/utils/maths.js";
+import { mergeArrays } from "../../../src/utils/core.js";
+import { logger } from "../../../src/utils/logger.js";
+export function upstream1809(generate_outputs, alignment_heads, num_frames = null, time_precision = 0.02, num_input_ids = 0) {
+  if (!generate_outputs.cross_attentions) {
+    throw new Error("Model outputs must contain cross attentions to extract timestamps. " + "This is most likely because the model was not exported with `output_attentions=True`.");
+  }
+  if (num_frames == null) {
+    logger.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. " + "This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");
+  }
+
+  // @ts-expect-error TS2339
+  let median_filter_width = this.config.median_filter_width;
+  if (median_filter_width === undefined) {
+    logger.warn("Model config has no `median_filter_width`, using default value of 7.");
+    median_filter_width = 7;
+  }
+
+  // TODO: Improve batch processing
+  const batch = generate_outputs.cross_attentions;
+  // Create a list with `decoder_layers` elements, each a tensor of shape
+  // (batch size, attention_heads, output length, input length).
+  const cross_attentions = Array.from(
+    // @ts-expect-error TS2339
+    { length: this.config.decoder_layers },
+    // Concatenate the cross attentions for each layer across sequence length dimension.
+    (_, i) =>
+      cat(
+        batch.map((x) => x[i]),
+        2,
+      ),
+  );
+
+  const weights = stack(
+    alignment_heads.map(([l, h]) => {
+      if (l >= cross_attentions.length) {
+        throw new Error(`Layer index ${l} is out of bounds for cross attentions (length ${cross_attentions.length}).`);
+      }
+      return num_frames ? cross_attentions[l].slice(null, h, null, [0, num_frames]) : cross_attentions[l].slice(null, h);
+    }),
+  ).permute(1, 0, 2, 3);
+
+  const [std, calculatedMean] = std_mean(weights, -2, 0, true);
+
+  // Normalize and smoothen the weights.
+  const smoothedWeights = weights.clone(); // [1, 8, seqLength, 1500]
+
+  for (let a = 0; a < smoothedWeights.dims[0]; ++a) {
+    const aTensor = smoothedWeights[a]; // [8, seqLength, 1500]
+
+    for (let b = 0; b < aTensor.dims[0]; ++b) {
+      const bTensor = aTensor[b]; // [seqLength, 1500]
+
+      const stdTensorData = std[a][b][0].data; // [1500]
+      const meanTensorData = calculatedMean[a][b][0].data; // [1500]
+
+      for (let c = 0; c < bTensor.dims[0]; ++c) {
+        let cTensorData = bTensor[c].data; // [1500]
+        for (let d = 0; d < cTensorData.length; ++d) {
+          cTensorData[d] = (cTensorData[d] - meanTensorData[d]) / stdTensorData[d];
+        }
+
+        // Apply median filter.
+        cTensorData.set(medianFilter(cTensorData, median_filter_width));
+      }
+    }
+  }
+
+  // Keep the final prompt query, which predicts the first generated token.
+  const croppedWeights = num_input_ids > 1 ? smoothedWeights.slice(null, null, [num_input_ids - 1, smoothedWeights.dims[2]], null) : smoothedWeights;
+
+  // Average the different cross-attention heads.
+  const batchedMatrices = [mean(croppedWeights, 1)];
+
+  const timestampsShape = generate_outputs.sequences.dims;
+
+  const timestamps = new Tensor("float32", new Float32Array(timestampsShape[0] * timestampsShape[1]), timestampsShape);
+
+  // Perform dynamic time warping on each element of the batch.
+  for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) {
+    // NOTE: Since we run only one batch at a time, we can squeeze to get the same dimensions
+    // as the python implementation
+    const matrix = batchedMatrices[batch_idx].neg().squeeze_(0);
+    const [text_indices, time_indices] = dynamic_time_warping(matrix.tolist());
+
+    const diffs = Array.from({ length: text_indices.length - 1 }, (v, i) => text_indices[i + 1] - text_indices[i]);
+    const jumps = mergeArrays([1], diffs).map((x) => !!x); // convert to boolean
+
+    const jump_times = [];
+    for (let i = 0; i < jumps.length; ++i) {
+      if (jumps[i]) {
+        // NOTE: No point in rounding here, since we set to Float32Array later
+        jump_times.push(time_indices[i] * time_precision);
+      }
+    }
+
+    // Prompt tokens get zero; each generated token gets its predicting row time.
+    const padded = new Array(Math.max(num_input_ids - 1, 0) + 1).fill(0);
+    padded.push(...jump_times);
+    timestamps[batch_idx].data.set(padded.slice(0, timestampsShape[1]));
+  }
+
+  return timestamps;
+}
diff --git a/packages/transformers/tests/utils/maths.test.js b/packages/transformers/tests/utils/maths.test.js
index ffdabf275..56f09b42b 100644
--- a/packages/transformers/tests/utils/maths.test.js
+++ b/packages/transformers/tests/utils/maths.test.js
@@ -1,4 +1,4 @@
-import { FFT, medianFilter, bankers_round, log_softmax, dynamic_time_warping } from "../../src/utils/maths.js";
+import { FFT, medianFilter, bankers_round, log_softmax } from "../../src/utils/maths.js";
 import { init } from "../init.js";
 
 // Initialise the testing environment
@@ -193,16 +193,3 @@ describe("Mathematical operations", () => {
     }
   });
 });
-
-// Pinned Transformers v4.57.1 alignment matrix: rounding changes the optimal path.
-it("preserves default DTW precision and supports upstream fp32 cost ties", () => {
-  const matrix = [
-    [-1.0, -1.0000001192092896, 1.7881393432617188e-7, -0.0, -5.960464477539063e-8, 2.9802322387695312e-8, 0.9999998807907104, 1.0, -5.364418029785156e-7, -0.0],
-    [1.0, 0.9999999403953552, 1.4901161193847656e-7, 5.960464477539063e-8, -0.0, 5.960464477539063e-8, -1.000000238418579, -1.0, -5.066394805908203e-7, 2.9802322387695312e-8],
-  ];
-  expect(dynamic_time_warping(matrix, true)).toEqual([
-    [0, 0, 1, 1, 1, 1, 1, 1, 1, 1],
-    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
-  ]);
-  expect(dynamic_time_warping(matrix)[0]).toEqual([0, 0, 0, 0, 0, 0, 1, 1, 1, 1]);
-});
diff --git a/packages/transformers/tests/utils/whisper_beam_timestamps.test.js b/packages/transformers/tests/utils/whisper_beam_timestamps.test.js
index 54b43ed5c..b5e54b425 100644
--- a/packages/transformers/tests/utils/whisper_beam_timestamps.test.js
+++ b/packages/transformers/tests/utils/whisper_beam_timestamps.test.js
@@ -1,3 +1,4 @@
+import { upstream1809 } from "./fixtures/whisper_timestamp_1809.js";
 import { jest } from "@jest/globals";
 import { PreTrainedModel } from "../../src/models/modeling_utils.js";
 import { Tensor } from "../../src/utils/tensor.js";
@@ -19,17 +20,23 @@ it.each([false, true])("reconstructs changing rows, query offsets, EOS and paddi
       const offset = (row * queries + queries - 1) * 8;
       // Unselected rows and padded frames are intentionally misleading.
       data.fill(500 + row * 10 + step, offset, offset + 8);
-      if (step > 0 && row === Number(history[0][step])) {
-        data.fill(0, offset, offset + 6);
-        data[offset + (step - 1) * 2] = 10;
-        data[offset + (step - 1) * 2 + 1] = 10;
+      if (row === Number(history[0][step])) {
+        data.fill(0, offset, offset + 8);
+        data[offset + step * 2] = 10;
+        data[offset + step * 2 + 1] = 10;
       }
     }
+    if (step < 2) {
+      const offset = (Number(history[1][step]) * queries + queries - 1) * 8;
+      data.fill(0, offset, offset + 4);
+      data[offset + step * 2] = 10;
+      data[offset + step * 2 + 1] = 10;
+    }
     return [new Tensor("float32", data, [4, 1, queries, 8])];
   });
-  const result = extract({ sequences: sequences(), cross_attentions: steps, beam_indices: new Tensor("int64", history.flat(), [2, 6]), sequence_lengths: new Tensor("int64", [6n, 4n], [2]), num_beams: 2 }, [6, 4]);
-  expect(Array.from(result.data.slice(0, 6))).toEqual([0, 0, 0, Math.fround(0.04), Math.fround(0.08), Math.fround(0.08)]);
-  expect(Array.from(result.data.slice(6))).toEqual([0, 0, 0, 0, 0, 0]);
+  const result = extract({ sequences: sequences(), cross_attentions: steps, beam_indices: new Tensor("int64", history.flat(), [2, 6]), sequence_lengths: new Tensor("int64", [6n, 4n], [2]), num_beams: 2 }, [8, 4]);
+  expect(Array.from(result.data.slice(0, 6))).toEqual([0, 0, 0, Math.fround(0.02), Math.fround(0.06), Math.fround(0.1)]);
+  expect(Array.from(result.data.slice(6))).toEqual([0, 0, 0, Math.fround(0.02), 0, 0]);
   expect(Array.from(result.data).every(Number.isFinite)).toBe(true);
 });
 
@@ -132,8 +139,8 @@ it.each([false, true])("crops retained seek segments before alignment and releas
     else {
       const output = await result;
       expect(calls).toEqual([
-        { frames: 2, length: 5 },
-        { frames: 2, length: 5 },
+        { frames: 2, length: 4 },
+        { frames: 2, length: 4 },
       ]);
       expect(output.sequences.tolist()).toEqual([[9n, 100n, 1n, 102n, 102n, 2n, 104n, 0n]]);
     }
@@ -162,8 +169,7 @@ it("expands an explicitly supplied flat prefix across the short-form batch", asy
   }
 });
 
-// Pinned Python Transformers v4.57.1 reference: prefix is cropped before
-// population mean/std, median smoothing, head averaging and DTW.
+// Compare against the independent, pre-beam PR #1809 algorithm.
 const referenceFixture = (frames = 6) => {
   let seed = 1234;
   const rows = Array.from({ length: 5 }, () =>
@@ -177,12 +183,14 @@ const referenceFixture = (frames = 6) => {
     cross_attentions: [[new Tensor("float32", Float32Array.from([...rows[0], ...rows[1]]), [1, 1, 2, frames])], ...rows.slice(2).map((row) => [new Tensor("float32", row, [1, 1, 1, frames])])],
   };
 };
-it("matches the pinned Python alignment reference and ignores prefix values", () => {
-  const output = referenceFixture();
-  const expected = [[0, 0, 0, 0, Math.fround(0.04), Math.fround(0.04)]];
-  expect(extract(output).tolist()).toEqual(expected);
-  output.cross_attentions[0][0].data.fill(100000);
-  expect(extract(output).tolist()).toEqual(expected);
+it.each([1, 3])("matches PR #1809 single-beam alignment including prefix normalization (median=%s)", (median) => {
+  const output = referenceFixture(12);
+  const config = { median_filter_width: median, decoder_layers: 1 };
+  const actual = () => WhisperForConditionalGeneration.prototype._extract_token_timestamps.call({ config }, output, [[0, 0]], 12, 0.02, 2).tolist();
+  const expected = () => upstream1809.call({ config }, output, [[0, 0]], 12, 0.02, 2).tolist();
+  expect(actual()).toEqual(expected());
+  output.cross_attentions[0][0].data.set([5, -8, 12, 0, 1, 20, -4, 2, 19, -5, 1, 9]);
+  expect(actual()).toEqual(expected());
 });
 it.each([2, 3])("does not median-filter %s frames with a seven-frame window", (frames) => {
   const output = referenceFixture(frames);
@@ -200,7 +208,7 @@ it("converts only selected fp16 attention elements", () => {
   });
   try {
     expect(extract(output).data.every(Number.isFinite)).toBe(true);
-    expect(elements).toBe(3 * 6);
+    expect(elements).toBe(5 * 6);
   } finally {
     spy.mockRestore();
   }
@@ -223,18 +231,21 @@ it("preserves preprocessed silence padding while bounding seek to valid audio fr
   }
 });
 
-// Golden boundaries from independently executed Transformers v4.57.1 Python
-// alignment, including a shorter EOS result and per-input valid frame lengths.
-it.each([1, 7])("matches upstream fp32 alignment near DTW ties (median=%s)", (median) => {
+// Reconstruct each hypothesis independently and compare with the upstream
+// non-beam oracle, including early EOS and a second selected attention head.
+it.each([1, 7])("matches PR #1809 for selected beam histories (median=%s)", (median) => {
   const histories = [
-    [0, 1, 0, 1, 1, -1, -1, -1],
-    [2, 3, 2, -1, -1, -1, -1, -1],
+    [0, 1, 0, 1, 1],
+    [2, 3, 2],
   ];
   const steps = Array.from({ length: 5 }, (_, step) =>
     Array.from({ length: 2 }, (_, layer) => {
       const dims = [4, 2, step === 0 ? 3 : 1, 16];
-      const data = Float32Array.from({ length: dims.reduce((a, b) => a * b) }, (_, i) => Math.sin(i * 0.83 + step * 2.31 + layer) * 0.6 + Math.cos(i * 0.12 + step) * 0.3);
-      return new Tensor("float32", data, dims);
+      return new Tensor(
+        "float32",
+        Float32Array.from({ length: dims.reduce((a, b) => a * b) }, (_, i) => Math.sin(i * 0.83 + step * 2.31 + layer) * 0.6 + Math.cos(i * 0.12 + step) * 0.3),
+        dims,
+      );
     }),
   );
   const outputs = {
@@ -244,34 +255,32 @@ it.each([1, 7])("matches upstream fp32 alignment near DTW ties (median=%s)", (me
       [2, 8],
     ),
     cross_attentions: steps,
-    beam_indices: new Tensor("int64", histories.flat().map(BigInt), [2, 8]),
+    beam_indices: new Tensor("int64", histories.flatMap((row) => [...row, ...Array(8 - row.length).fill(-1)]).map(BigInt), [2, 8]),
     sequence_lengths: new Tensor("int64", [8n, 6n], [2]),
     num_beams: 2,
   };
-  const actual = WhisperForConditionalGeneration.prototype._extract_token_timestamps
-    .call(
-      { config: { median_filter_width: median } },
-      outputs,
-      [
-        [0, 0],
-        [1, 1],
-      ],
-      [16, 10],
-      0.02,
-      3,
-    )
-    .tolist();
-  const expected = {
-    1: [
-      [0.0, 0.0, 0.0, 0.0, 0.25999999046325684, 0.25999999046325684, 0.30000001192092896, 0.30000001192092896],
-      [0.0, 0.0, 0.0, 0.0, 0.03999999910593033, 0.03999999910593033],
-    ],
-    7: [
-      [0.0, 0.0, 0.0, 0.0, 0.25999999046325684, 0.25999999046325684, 0.30000001192092896, 0.30000001192092896],
-      [0.0, 0.0, 0.0, 0.0, 0.14000000059604645, 0.14000000059604645],
-    ],
-  };
-  expect(actual[0]).toEqual(expected[median][0]);
-  expect(actual[1].slice(0, 6)).toEqual(expected[median][1]);
-  expect(actual[1].slice(6)).toEqual([0, 0]);
+  const config = { median_filter_width: median, decoder_layers: 2 };
+  const heads = [
+    [0, 0],
+    [1, 1],
+  ];
+  const actual = WhisperForConditionalGeneration.prototype._extract_token_timestamps.call({ config }, outputs, heads, [16, 10], 0.02, 3).tolist();
+  for (let result = 0; result < 2; ++result) {
+    const history = histories[result];
+    const single = { sequences: new Tensor("int64", Array(history.length + 3).fill(1n), [1, history.length + 3]), cross_attentions: history.map((row, step) => steps[step].map((t) => t.slice([row, row + 1]))) };
+    const expected = upstream1809.call({ config }, single, heads, [16, 10][result], 0.02, 3).tolist()[0];
+    expect(actual[result].slice(0, expected.length)).toEqual(expected);
+    expect(actual[result].slice(expected.length).every((x) => x === 0)).toBe(true);
+  }
+});
+
+it.each([0n, 7n])("aligns the final predicting query at EOS or token limit (%s)", (lastToken) => {
+  const output = referenceFixture(12);
+  output.sequences.data[5] = lastToken;
+  const config = { median_filter_width: 1, decoder_layers: 1 };
+  expect(extract(output, 12).tolist()).toEqual(upstream1809.call({ config }, output, [[0, 0]], 12, 0.02, 2).tolist());
+});
+it("handles EOS on the first forward without a subsequent query", () => {
+  const output = { sequences: new Tensor("int64", [9n, 8n, 0n], [1, 3]), cross_attentions: referenceFixture().cross_attentions.slice(0, 1), beam_indices: new Tensor("int64", [0n, -1n, -1n], [1, 3]), sequence_lengths: new Tensor("int64", [3n], [1]), num_beams: 1 };
+  expect(extract(output).tolist()).toEqual([[0, 0, 0]]);
 });
diff --git a/scripts/beam-gpu/.gitignore b/scripts/beam-gpu/.gitignore
deleted file mode 100644
index 6628455c0..000000000
--- a/scripts/beam-gpu/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/results/
diff --git a/scripts/beam-gpu/README.md b/scripts/beam-gpu/README.md
deleted file mode 100644
index 7b6d150df..000000000
--- a/scripts/beam-gpu/README.md
+++ /dev/null
@@ -1,51 +0,0 @@
-# Beam search GPU validation
-
-These scripts validate and benchmark browser WebGPU on a disposable Linux NVIDIA
-host. Infrastructure provisioning, SSH credentials, budgets, and teardown belong
-to the caller; the scripts contain no provider credentials and create no hosts.
-
-`bootstrap.sh` installs Node 24.14.1, pnpm, the base PR revision, and Playwright
-1.56.1/Chromium 141. A newer Chromium 156 build returned a null WebGPU adapter on
-the tested NVIDIA driver; Chromium 141 worked. EGL dispatch libraries are required
-in addition to the container's NVIDIA Vulkan libraries.
-
-Run `bootstrap.sh` on a throwaway Ubuntu GPU host, then transfer the desired source
-revision into `/workspace/beam-gpu/transformers.js`. The default task root is
-`/workspace/beam-gpu`; override `TASK_ROOT` for bootstrap or `BEAM_RUNNER_ROOT` and
-`BEAM_PROJECT_ROOT` for the runner. `BEAM_PLAYWRIGHT_ROOT` can select another
-runner's Playwright installation. The benchmark server binds to loopback only.
-
-```bash
-export PATH=/workspace/beam-gpu/node-v24.14.1-linux-x64/bin:$PATH
-cd /workspace/beam-gpu/transformers.js
-node scripts/beam-gpu/build.mjs
-BEAM_OPTIONS='{"mode":"validate"}' BEAM_RESULT=/workspace/beam-gpu/validate.json node scripts/beam-gpu/runner.mjs
-BEAM_OPTIONS='{"mode":"micro"}' BEAM_RESULT=/workspace/beam-gpu/micro.json node scripts/beam-gpu/runner.mjs
-BEAM_OPTIONS='{"mode":"generation","repeats":4,"tokens":16}' BEAM_RESULT=/workspace/beam-gpu/generation.json node scripts/beam-gpu/runner.mjs
-```
-
-- `probe`: requires a hardware WebGPU adapter and records browser/adapter identity.
-- `validate`: verifies float32, float16, int64, uint8 and bool row selection,
-  duplicate rows, chained selections, preservation of caller-owned source data,
-  and the CPU fallback for unaligned float16 rows.
-- `micro`: validates every copied element, then measures GPU-completed row
-  selection for 1, 8, and 64 MiB tensors. Two warmups precede ten timed samples.
-- `generation`: runs T5 and Llama standard/diverse/sampling/batched beam decoding;
-  checks seeded repeatability, batch independence, and null returned beam caches.
-  One warmup precedes timed samples. JSON retains tokens and cache locations.
-
-For other models, pass `models`, `dtype`, and optionally `modes` (`standard`,
-`diverse`, `sampling`, `batched`) in `BEAM_OPTIONS`. Set `cpuRowSelection: true`
-to use the original cache-download algorithm for a matched reference. This is a
-harness option, not a library configuration flag. Compare token arrays between
-reference and optimized output files before interpreting timings.
-
-`node scripts/beam-gpu/candidates.mjs` separately compares the full-sort reference
-with bounded top-k selection for 32K and 152K vocabularies and verifies identical
-rankings. Its numbers are CPU microbenchmarks, not inference throughput.
-
-Raw results belong in the gitignored `results/` directory. Keep model caches,
-provider keys, SSH keys, browser installations, and build output out of Git.
-The Chromium process runs without its sandbox because this harness runs as root
-inside an isolated, disposable test container; use a sandboxed browser on shared
-or persistent hosts.
diff --git a/scripts/beam-gpu/RESULTS.md b/scripts/beam-gpu/RESULTS.md
deleted file mode 100644
index cfde234f7..000000000
--- a/scripts/beam-gpu/RESULTS.md
+++ /dev/null
@@ -1,113 +0,0 @@
-# WebGPU beam decoding experiment — 2026-10-20
-
-Branch: `dan/beam-webgpu-performance`, based on PR #1539 at `7c43a27`.
-Product and hardware-validation revision: `58699fa153ece4803a2e3bd4206f59197fa4ec26`.
-
-## Changes
-
-- Keep aligned WebGPU cache rows on GPU with buffer-to-buffer copies. Other
-  device tensors and unaligned rows retain CPU fallback. Outputs have ONNX
-  Runtime's required 16-byte allocation padding and explicit disposal/download
-  callbacks. The active runtime's Tensor factory avoids package-version identity
-  mismatches when wrapping GPU buffers.
-- Replace full-vocabulary object allocation/sorting with bounded top-k selection.
-  Ranking, diversity penalties, token tie order, and seeded outputs are preserved.
-- Add an isolated, reproducible browser harness, dtype and ownership checks,
-  candidate-selection reference tests, benchmarks, and a GPU usage guide.
-
-## Hardware and method
-
-Runpod Secure Cloud RTX 4090, 24,564 MiB VRAM, NVIDIA driver 595.91.07,
-Ubuntu 24.04 container/Linux 6.8, Node 24.14.1, Chromium 141.0.7390.37.
-The adapter reported `nvidia` / `lovelace` and `isFallbackAdapter: false`.
-The host allocation had 12 vCPUs and 100 GB system RAM.
-
-Model inference used fp32 and four beams, returning two sequences. Tiny models
-used 16 new tokens; SmolLM2 used 32. Batched cases used two inputs. Each timing
-is the median of three measured runs after one warmup. Model downloads and
-initial session creation are excluded. Source code, backend, model bytes and
-inputs were matched; raw model hashes are retained locally.
-
-The reference uses the original CPU cache-download/reorder algorithm and full
-vocabulary sorting. The tuned path includes both GPU copies and bounded top-k.
-These are workload-specific measurements, not general speedup guarantees.
-
-## End-to-end results
-
-| Model | Mode | Reference (ms) | Tuned (ms) | Speedup |
-|---|---|---:|---:|---:|
-| tiny-random-T5ForConditionalGeneration | standard | 2564.5 | 475.7 | 5.39x |
-| tiny-random-T5ForConditionalGeneration | diverse | 2409.3 | 610.4 | 3.95x |
-| tiny-random-T5ForConditionalGeneration | sampling | 2524.8 | 650.3 | 3.88x |
-| tiny-random-T5ForConditionalGeneration | batched | 3201.3 | 805.6 | 3.97x |
-| tiny-random-LlamaForCausalLM | standard | 2475.1 | 914.2 | 2.71x |
-| tiny-random-LlamaForCausalLM | diverse | 2598.7 | 989.1 | 2.63x |
-| tiny-random-LlamaForCausalLM | sampling | 2697.2 | 1079.4 | 2.50x |
-| tiny-random-LlamaForCausalLM | batched | 4601.0 | 1738.8 | 2.65x |
-| SmolLM2-135M-Instruct-ONNX | standard | 15571.3 | 1676.0 | 9.29x |
-| SmolLM2-135M-Instruct-ONNX | batched | 19463.8 | 2014.7 | 9.66x |
-
-All ten reference-versus-tuned token arrays match exactly. A separate CPU/WASM
-reference also matches all eight tiny-model WebGPU cases, including seeded
-sampling and batched/diverse decoding.
-
-## Cache row-copy microbenchmarks
-
-Each result validates every copied element and measures completion on the GPU
-queue. Two warmups precede ten samples. These numbers measure one synthetic
-cache tensor, not full generation.
-
-| Tensor size | CPU-transfer reference (ms) | GPU copy (ms) | Speedup |
-|---|---:|---:|---:|
-| 1 MiB | 6.165 | 0.275 | 22.42x |
-| 8 MiB | 25.690 | 1.640 | 15.66x |
-| 64 MiB | 140.395 | 7.075 | 19.84x |
-
-## Verification
-
-- Full workspace CPU suite: **2,278 passed, 47 skipped, 30 suites passed**.
-- Eight real-GPU boundary fixtures cover float32, float16, int64, uint8, bool,
-  duplicated/chained rows, unaligned fallback, small output padding, and
-  caller-owned source preservation.
-- A 25-generation stress run leaves zero owned row-copy buffers live after every
-  generation. The active inference-device instrumentation observes a peak of
-  60 owned buffers on SmolLM2 and zero remaining at completion. This checks
-  buffers owned by this implementation, not all runtime/driver allocations.
-- Ten candidate-selection tests match a full-sort reference, including ties,
-  suppressed tokens, diversity penalties, large k, and empty input.
-- Both packages build with declarations on macOS and the Linux worker; docs
-  generation and changed-file Prettier checks pass.
-- Repository-wide formatting retains the two previously verified failures in
-  untouched `tensor.test.js` and `tensor_ops.test.js`.
-
-## Scope and setup findings
-
-Validation covers Linux/NVIDIA browser WebGPU with fp32 model inference.
-The container required EGL dispatch libraries before Vulkan could initialize.
-Chromium 156 returned a null WebGPU adapter on this host; pinned Chromium 141
-worked. The Qwen 0.5B fp16 attempt was rejected by the browser capability check;
-its fp32 export hit a browser runtime allocation limit. Those attempts are
-setup/coverage limits, not successful model validation.
-
-## Cost and cleanup
-
-Pod `tlouzqbaj8jchl` ran from 19:44:51 UTC to verified deletion at 20:38:26 UTC:
-**53.6 minutes**, below the two-hour authorization. Compute was $0.89/hour;
-40 GB disposable storage brought the estimate to about $0.90/hour. Estimated
-total: **$0.80**. The account balance decreased by $0.7993, and final reported
-compute spend was $0/hour; the per-pod billing ledger had not posted records.
-
-A fresh provider read returned 404 after deletion. No volume was created.
-The scheduled cleanup backup was removed after deletion, and the local
-watchdog/result archiver were signaled to exit. Automatic approval review
-rejected copying the account API key onto the worker; no API key was copied
-there. Credentials stayed local, with local sleep prevention and a scheduled
-cleanup backup guarding the deadline.
-
-## Retained evidence
-
-Raw JSON/logs, source identity/status, model hashes, manifests and intermediate
-archives are retained in the gitignored `scripts/beam-gpu/results/` directory.
-The bootstrap and test harness are tracked in this directory. Run `run.sh` to
-repeat the complete hardware-validation/benchmark sequence on an already
-provisioned host. Provider credentials and SSH keys are not part of the repo.
diff --git a/scripts/beam-gpu/bootstrap.sh b/scripts/beam-gpu/bootstrap.sh
deleted file mode 100755
index 1f42996ff..000000000
--- a/scripts/beam-gpu/bootstrap.sh
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-# Run inside the disposable Linux GPU host. No credentials are required.
-TASK_ROOT=${TASK_ROOT:-/workspace/beam-gpu}
-mkdir -p "$TASK_ROOT"
-cd "$TASK_ROOT"
-apt-get update -qq
-apt-get install -y -qq libegl1 libgl1 libglvnd0 vulkan-tools
-if ! command -v node >/dev/null; then
-  curl -fsSL https://nodejs.org/dist/v24.14.1/node-v24.14.1-linux-x64.tar.xz -o node.tar.xz
-  tar -xf node.tar.xz
-fi
-export PATH="$TASK_ROOT/node-v24.14.1-linux-x64/bin:$PATH"
-corepack enable
-if [[ ! -d transformers.js/.git ]]; then
-  git clone --depth 1 --branch dan/add-beam-support https://github.com/justsml/transformers.js.git
-fi
-cd transformers.js
-git checkout 7c43a27d44f2ae4fa764362ce31f389a2bb489bf
-pnpm install --frozen-lockfile
-pnpm build
-mkdir -p "$TASK_ROOT/runner"
-cd "$TASK_ROOT/runner"
-if [[ ! -f package.json ]]; then
-  printf '{"private":true,"type":"module","packageManager":"pnpm@10.28.1"}\n' > package.json
-fi
-pnpm add --save-exact playwright@1.56.1
-pnpm exec playwright install --with-deps chromium
-node --version
-pnpm exec playwright --version
-nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv
diff --git a/scripts/beam-gpu/browser.js b/scripts/beam-gpu/browser.js
deleted file mode 100644
index d90393f05..000000000
--- a/scripts/beam-gpu/browser.js
+++ /dev/null
@@ -1,286 +0,0 @@
-import {
-  AutoModelForSeq2SeqLM,
-  AutoModelForCausalLM,
-  AutoTokenizer,
-  PreTrainedModel,
-  Tensor,
-  DynamicCache,
-  env,
-  random,
-} from "../../packages/transformers/src/transformers.js";
-import { getTensorConstructor } from "../../packages/transformers/src/backends/onnx.js";
-import { index_select_async, index_select } from "../../packages/transformers/src/utils/tensor.js";
-
-env.backends.onnx.wasm.wasmPaths = "/ort/";
-env.backends.onnx.wasm.numThreads = 1;
-env.allowLocalModels = false;
-env.remoteHost = location.origin + "/hf/";
-const emit = (value) => console.log("RESULT " + JSON.stringify(value, (_, x) => (typeof x === "bigint" ? x.toString() : x)));
-const equal = (a, b) =>
-  JSON.stringify(a, (_, x) => (typeof x === "bigint" ? x.toString() : x)) === JSON.stringify(b, (_, x) => (typeof x === "bigint" ? x.toString() : x));
-const median = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)];
-
-window.runBeamGPU = async (options) => {
-  const adapter = await navigator.gpu?.requestAdapter({ powerPreference: "high-performance" });
-  if (!adapter) throw new Error("No WebGPU adapter");
-  const info = adapter.info;
-  const hardware = {
-    vendor: info.vendor,
-    architecture: info.architecture,
-    device: info.device,
-    description: info.description,
-    isFallbackAdapter: info.isFallbackAdapter,
-  };
-  emit({ type: "adapter", ...hardware, userAgent: navigator.userAgent });
-  if (info.isFallbackAdapter || /swiftshader|llvmpipe|software/i.test(hardware.description)) throw new Error("Software GPU rejected");
-  env.backends.onnx.webgpu.adapter = adapter;
-  if (options.mode === "probe") return { hardware };
-  const device = await adapter.requestDevice({
-    requiredFeatures: adapter.features.has("shader-f16") ? ["shader-f16"] : [],
-    requiredLimits: { maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize, maxBufferSize: adapter.limits.maxBufferSize },
-  });
-  env.backends.onnx.webgpu.device = device;
-  const liveBuffers = new Set();
-  let peakOwnedBuffers = 0;
-  const trackedDevices = new WeakSet();
-  const trackDevice = (gpuDevice) => {
-    if (trackedDevices.has(gpuDevice)) return;
-    trackedDevices.add(gpuDevice);
-    const createBuffer = gpuDevice.createBuffer.bind(gpuDevice);
-    gpuDevice.createBuffer = (descriptor) => {
-      const buffer = createBuffer(descriptor);
-      if (descriptor.label?.startsWith("transformers-beam-")) {
-        liveBuffers.add(buffer);
-        peakOwnedBuffers = Math.max(peakOwnedBuffers, liveBuffers.size);
-        const destroy = buffer.destroy.bind(buffer);
-        buffer.destroy = () => {
-          liveBuffers.delete(buffer);
-          destroy();
-        };
-      }
-      return buffer;
-    };
-  };
-  trackDevice(device);
-  const errors = [];
-  device.addEventListener("uncapturederror", (event) => {
-    errors.push(event.error.message);
-    console.error(event.error.message);
-  });
-  device.lost.then((value) => {
-    console.error("DEVICE_LOST", value.reason, value.message);
-  });
-
-  if (options.mode === "validate") {
-    const cases = [
-      ["float32", Float32Array, [3, 4]],
-      ["float32", Float32Array, [3, 1]],
-      ["float16", Uint16Array, [3, 4]],
-      ["float16", Uint16Array, [3, 2]],
-      ["float16", Uint16Array, [3, 3]],
-      ["int64", BigInt64Array, [3, 2]],
-      ["uint8", Uint8Array, [3, 4]],
-      ["bool", Uint8Array, [3, 4]],
-    ];
-    const results = [];
-    for (const [type, ArrayType, dims] of cases) {
-      const count = dims.reduce((a, b) => a * b, 1);
-      const data = ArrayType.from({ length: count }, (_, i) => (type === "int64" ? BigInt(i + 1) : type === "bool" ? i % 2 : i + 1));
-      const size = Math.ceil(data.byteLength / 4) * 4;
-      const input = device.createBuffer({ size, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST });
-      const padded = new Uint8Array(size);
-      padded.set(new Uint8Array(data.buffer));
-      device.queue.writeBuffer(input, 0, padded);
-      let downloads = 0;
-      const original = new Tensor(
-        getTensorConstructor().fromGpuBuffer(input, {
-          dataType: type,
-          dims,
-          download: async () => {
-            ++downloads;
-            const staging = device.createBuffer({ size, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
-            const encoder = device.createCommandEncoder();
-            encoder.copyBufferToBuffer(input, 0, staging, 0, size);
-            device.queue.submit([encoder.finish()]);
-            await staging.mapAsync(GPUMapMode.READ);
-            const result = new ArrayType(staging.getMappedRange().slice(0, data.byteLength));
-            staging.destroy();
-            return result;
-          },
-        }),
-      );
-      const selected = await index_select_async(original, [2, 0, 2]);
-      const selectedLocation = selected.location;
-      const aligned = (dims[1] * ArrayType.BYTES_PER_ELEMENT) % 4 === 0;
-      if (aligned && selected.ort_tensor.gpuBuffer.size % 16 !== 0) throw new Error("GPU output is not padded for ONNX Runtime");
-      if (selectedLocation !== (aligned ? "gpu-buffer" : "cpu")) throw new Error("Unexpected row selection location");
-      if (aligned && (downloads !== 0 || original.location !== "gpu-buffer")) throw new Error("GPU selection downloaded the source");
-      const chained = await index_select_async(selected, [1, 0]);
-      const actual = await chained.ort_tensor.getData();
-      const expected = [...data.slice(0, dims[1]), ...data.slice(2 * dims[1], 3 * dims[1])];
-      const actualValues = type === "float16" ? new Uint16Array(actual.buffer, actual.byteOffset, actual.byteLength / 2) : actual;
-      if (!equal([...actualValues], expected)) throw new Error("Typed/chained GPU selection mismatch: " + type);
-      chained.dispose();
-      selected.dispose();
-      // Source buffers must still be usable after disposing selected tensors.
-      const remaining = await original.ort_tensor.getData();
-      if (!equal([...remaining], [...data])) throw new Error("Source ownership violated");
-      original.dispose();
-      input.destroy();
-      if (liveBuffers.size) throw new Error("GPU row buffers were not released");
-      const result = { type: "validation", dtype: type, dims, selectedLocation, chainedAndSourceOwnership: true };
-      results.push(result);
-      emit(result);
-    }
-    await device.queue.onSubmittedWorkDone();
-    if (errors.length) throw new Error(errors.join("\n"));
-    return { hardware, results, errors, peakOwnedBuffers, remainingOwnedBuffers: liveBuffers.size };
-  }
-
-  if (options.mode === "micro") {
-    const results = [];
-    for (const dims of [
-      [4, 8, 128, 64],
-      [4, 8, 1024, 64],
-      [8, 16, 2048, 64],
-    ]) {
-      const elements = dims.reduce((a, b) => a * b, 1);
-      const data = Float32Array.from({ length: elements }, (_, i) => i % 997);
-      const input = device.createBuffer({ size: data.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST });
-      device.queue.writeBuffer(input, 0, data);
-      const indices = Array.from({ length: dims[0] }, (_, i) => (i * 3 + 1) % dims[0]);
-      const source = () =>
-        new Tensor(
-          getTensorConstructor().fromGpuBuffer(input, {
-            dataType: "float32",
-            dims,
-            download: async () => {
-              const staging = device.createBuffer({ size: data.byteLength, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
-              const encoder = device.createCommandEncoder();
-              encoder.copyBufferToBuffer(input, 0, staging, 0, data.byteLength);
-              device.queue.submit([encoder.finish()]);
-              await staging.mapAsync(GPUMapMode.READ);
-              const copy = new Float32Array(staging.getMappedRange().slice(0));
-              staging.unmap();
-              staging.destroy();
-              return copy;
-            },
-          }),
-        );
-      const durations = [];
-      let outputLocation;
-      for (let repeat = 0; repeat < 12; ++repeat) {
-        const tensor = source();
-        await device.queue.onSubmittedWorkDone();
-        const start = performance.now();
-        const output = await index_select_async(tensor, indices);
-        await device.queue.onSubmittedWorkDone();
-        const elapsed = performance.now() - start;
-        outputLocation = output.location;
-        if (repeat >= 2) durations.push(elapsed);
-        if (repeat === 0) {
-          const actual = await output.ort_tensor.getData();
-          const rowSize = elements / dims[0];
-          for (let row = 0; row < dims[0]; ++row) {
-            for (let i = 0; i < rowSize; ++i) {
-              if (actual[row * rowSize + i] !== data[indices[row] * rowSize + i]) throw new Error("Row selection mismatch");
-            }
-          }
-        }
-        output.dispose();
-        tensor.dispose();
-      }
-      input.destroy();
-      const result = { type: "micro", dims, bytes: data.byteLength, medianMs: median(durations), samplesMs: durations, outputLocation };
-      results.push(result);
-      emit(result);
-    }
-    if (errors.length) throw new Error(errors.join("\n"));
-    return { hardware, results, errors, peakOwnedBuffers, remainingOwnedBuffers: liveBuffers.size };
-  }
-
-  const models = options.models ?? ["hf-internal-testing/tiny-random-T5ForConditionalGeneration", "hf-internal-testing/tiny-random-LlamaForCausalLM"];
-  const results = [];
-  for (const modelId of models) {
-    const Model = /T5/.test(modelId) ? AutoModelForSeq2SeqLM : AutoModelForCausalLM;
-    const model = await Model.from_pretrained(modelId, { device: options.device ?? "webgpu", dtype: options.dtype ?? "fp32" });
-    trackDevice(await env.backends.onnx.webgpu.device);
-    const tokenizer = await AutoTokenizer.from_pretrained(modelId);
-    tokenizer.padding_side = "left";
-    let cacheStats = [];
-    const reorder = options.cpuRowSelection
-      ? async (cache, indices) => {
-          const entries = {};
-          for (const [key, tensor] of Object.entries(cache)) {
-            if (key.includes("encoder")) {
-              entries[key] = tensor;
-              continue;
-            }
-            const location = tensor.location;
-            await tensor.ort_tensor.getData(false);
-            entries[key] = index_select(tensor, model._get_cache_indices(key, indices));
-            if (location === "gpu-buffer") tensor.dispose();
-          }
-          return new DynamicCache(entries);
-        }
-      : model._reorder_cache.bind(model);
-    model._reorder_cache = async (cache, indices) => {
-      const before = Object.values(cache).map((t) => ({ location: t.location, size: t.size }));
-      const start = performance.now();
-      const result = await reorder(cache, indices);
-      cacheStats.push({ ms: performance.now() - start, before, after: Object.values(result).map((t) => t.location) });
-      return result;
-    };
-    const configs = [
-      { name: "standard", num_beams: 4, num_return_sequences: 2 },
-      { name: "diverse", num_beams: 4, num_beam_groups: 2, diversity_penalty: 0.5, num_return_sequences: 2 },
-      { name: "sampling", num_beams: 4, num_return_sequences: 2, do_sample: true, top_k: 10 },
-      { name: "batched", num_beams: 4, num_return_sequences: 2 },
-    ];
-    for (const { name, ...config } of configs.filter((config) => !options.modes || options.modes.includes(config.name))) {
-      const texts = name === "batched" ? ["hello", "a longer input"] : ["hello"];
-      const inputs = tokenizer(texts, { padding: true });
-      const durations = [];
-      let expected;
-      for (let repeat = 0; repeat < (options.repeats ?? 4); ++repeat) {
-        random.seed(42);
-        cacheStats = [];
-        const start = performance.now();
-        const output = await model.generate({ ...inputs, ...config, max_new_tokens: options.tokens ?? 16, eos_token_id: null, return_dict_in_generate: true });
-        const elapsed = performance.now() - start;
-        if (liveBuffers.size) throw new Error("GPU row buffers leaked after generation");
-        const tokens = output.sequences.tolist();
-        if (output.past_key_values !== null) throw new Error("Unexpected beam cache output");
-        if (expected && !equal(tokens, expected)) throw new Error("Repeated generation changed output: " + name);
-        expected = tokens;
-        if (repeat > 0) durations.push(elapsed);
-      }
-      if (name === "batched") {
-        for (let i = 0; i < texts.length; ++i) {
-          const single = await model.generate({ ...tokenizer(texts[i]), ...config, max_new_tokens: options.tokens ?? 16, eos_token_id: null });
-          const tail = (rows) => rows.map((row) => row.slice(-(options.tokens ?? 16)));
-          if (!equal(tail(expected.slice(i * 2, i * 2 + 2)), tail(single.tolist()))) throw new Error("Batch independence failed");
-        }
-      }
-      if (!options.cpuRowSelection && cacheStats.some((step) => step.before.some((tensor) => tensor.location === "gpu-buffer")) && peakOwnedBuffers === 0) {
-        throw new Error("GPU buffer lifetime tracking did not observe the row-copy path");
-      }
-      const result = {
-        type: "generation",
-        modelId,
-        name,
-        device: options.device ?? "webgpu",
-        medianMs: median(durations),
-        samplesMs: durations,
-        tokens: expected,
-        cacheStats,
-      };
-      results.push(result);
-      emit({ ...result, tokens: undefined, cacheStats: undefined });
-    }
-    await model.dispose();
-  }
-  await device.queue.onSubmittedWorkDone();
-  if (errors.length) throw new Error(errors.join("\n"));
-  return { hardware, results, errors, peakOwnedBuffers, remainingOwnedBuffers: liveBuffers.size };
-};
diff --git a/scripts/beam-gpu/build.mjs b/scripts/beam-gpu/build.mjs
deleted file mode 100644
index d8cf63439..000000000
--- a/scripts/beam-gpu/build.mjs
+++ /dev/null
@@ -1,16 +0,0 @@
-import path from "node:path";
-import { createRequire } from "node:module";
-import { fileURLToPath } from "node:url";
-const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
-const require = createRequire(path.join(root, "packages/transformers/package.json"));
-const { build } = require("esbuild");
-const { ignoreModulesPlugin } = await import("../../packages/transformers/scripts/build/plugins/ignoreModulesPlugin.mjs");
-await build({
-  entryPoints: [path.join(root, "scripts/beam-gpu/browser.js")],
-  bundle: true,
-  platform: "browser",
-  format: "esm",
-  sourcemap: true,
-  outfile: process.env.BEAM_APP_OUT ?? "/workspace/beam-gpu/runner/app.js",
-  plugins: [ignoreModulesPlugin(["./onnx-node.js", "sharp", "fs", "path", "url", "stream", "stream/promises"])],
-});
diff --git a/scripts/beam-gpu/candidates.mjs b/scripts/beam-gpu/candidates.mjs
deleted file mode 100644
index 35cd41515..000000000
--- a/scripts/beam-gpu/candidates.mjs
+++ /dev/null
@@ -1,27 +0,0 @@
-import { performance } from "node:perf_hooks";
-import { selectBeamCandidates } from "../../packages/transformers/src/generation/beam_search_utils.js";
-const median = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)];
-for (const vocab of [32000, 151936]) {
-  const scores = Float32Array.from({ length: vocab }, (_, i) => Math.sin(i * 17) * 10);
-  for (const count of [8, 50]) {
-    const baseline = () =>
-      Array.from(scores, (score, token) => ({ score: -3 + score, token: BigInt(token), beam_idx: 0 }))
-        .sort((a, b) => b.score - a.score)
-        .slice(0, count);
-    const optimized = () => selectBeamCandidates(scores, -3, 0, count);
-    const stringify = (x) => JSON.stringify(x, (_, value) => (typeof value === "bigint" ? String(value) : value));
-    if (stringify(baseline()) !== stringify(optimized())) throw new Error("Candidate selection mismatch");
-    const times = {};
-    for (const [name, fn] of Object.entries({ baseline, optimized })) {
-      const samples = [];
-      for (let repeat = 0; repeat < 15; ++repeat) {
-        const start = performance.now();
-        fn();
-        const ms = performance.now() - start;
-        if (repeat >= 5) samples.push(ms);
-      }
-      times[name] = { medianMs: median(samples), samplesMs: samples };
-    }
-    console.log(JSON.stringify({ vocab, count, ...times, identical: true }));
-  }
-}
diff --git a/scripts/beam-gpu/run.sh b/scripts/beam-gpu/run.sh
deleted file mode 100755
index deffb1c54..000000000
--- a/scripts/beam-gpu/run.sh
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-OUTPUT_ROOT=${BEAM_OUTPUT_ROOT:-/workspace/beam-gpu}
-mkdir -p "$OUTPUT_ROOT"
-printf "running\n" > "$OUTPUT_ROOT/final-exit-status"
-trap 'code=$?; printf "%s\n" "$code" > "$OUTPUT_ROOT/final-exit-status"' EXIT
-git rev-parse HEAD > "$OUTPUT_ROOT/final-source-commit"
-git status --porcelain > "$OUTPUT_ROOT/final-source-status"
-node scripts/beam-gpu/build.mjs
-run_case() {
-  BEAM_OPTIONS="$2" BEAM_RESULT="$OUTPUT_ROOT/$1.json" node scripts/beam-gpu/runner.mjs
-}
-run_case final-validation '{"mode":"validate"}'
-run_case final-micro '{"mode":"micro"}'
-run_case final-generation '{"mode":"generation","tokens":16,"repeats":4}'
-run_case smollm-optimized '{"mode":"generation","models":["onnx-community/SmolLM2-135M-Instruct-ONNX"],"dtype":"fp32","modes":["standard","batched"],"tokens":32,"repeats":4}'
-run_case final-stress '{"mode":"generation","models":["hf-internal-testing/tiny-random-LlamaForCausalLM"],"modes":["standard"],"tokens":8,"repeats":25}'
-node scripts/beam-gpu/candidates.mjs > "$OUTPUT_ROOT/candidates-remote.jsonl"
-pnpm build > "$OUTPUT_ROOT/final-build.log" 2>&1
diff --git a/scripts/beam-gpu/runner.mjs b/scripts/beam-gpu/runner.mjs
deleted file mode 100644
index bb6adc234..000000000
--- a/scripts/beam-gpu/runner.mjs
+++ /dev/null
@@ -1,87 +0,0 @@
-import http from "node:http";
-import fs from "node:fs";
-import path from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
-const root = process.env.BEAM_PROJECT_ROOT ?? path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
-const runner = process.env.BEAM_RUNNER_ROOT ?? "/workspace/beam-gpu/runner";
-const { chromium } = await import(pathToFileURL(path.join(process.env.BEAM_PLAYWRIGHT_ROOT ?? runner, "node_modules/playwright/index.mjs")));
-const ort = path.join(root, "packages/transformers/node_modules/onnxruntime-web/dist");
-const cache = path.join(runner, "model-cache");
-fs.mkdirSync(cache, { recursive: true });
-const options = JSON.parse(process.env.BEAM_OPTIONS ?? '{"mode":"probe"}');
-const server = http.createServer(async (req, res) => {
-  res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
-  res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
-  try {
-    const pathname = new URL(req.url, "http://localhost").pathname;
-    if (pathname.startsWith("/hf/")) {
-      const relative = pathname.slice(4);
-      const local = path.join(cache, relative);
-      if (!fs.existsSync(local)) {
-        const upstream = await fetch("https://huggingface.co/" + relative);
-        if (!upstream.ok) {
-          res.writeHead(upstream.status);
-          res.end(await upstream.text());
-          return;
-        }
-        fs.mkdirSync(path.dirname(local), { recursive: true });
-        fs.writeFileSync(local, Buffer.from(await upstream.arrayBuffer()));
-      }
-      res.end(fs.readFileSync(local));
-      return;
-    }
-    if (pathname === "/") {
-      res.setHeader("Content-Type", "text/html");
-      res.end('');
-      return;
-    }
-    const file = pathname.startsWith("/ort/") ? path.join(ort, path.basename(pathname)) : path.join(runner, path.basename(pathname));
-    res.setHeader("Content-Type", file.endsWith(".wasm") ? "application/wasm" : "text/javascript");
-    res.end(fs.readFileSync(file));
-  } catch (error) {
-    res.statusCode = 500;
-    res.end(String(error));
-  }
-});
-await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
-const browser = await chromium.launch({
-  headless: true,
-  dumpio: process.env.BEAM_DEBUG === "1",
-  channel: "chromium",
-  args: [
-    "--no-sandbox",
-    "--enable-gpu",
-    "--disable-gpu-sandbox",
-    "--enable-unsafe-webgpu",
-    "--ignore-gpu-blocklist",
-    "--use-angle=vulkan",
-    "--enable-features=Vulkan,VulkanFromANGLE,DefaultANGLEVulkan",
-    "--disable-vulkan-surface",
-    "--disable-dev-shm-usage",
-  ],
-});
-try {
-  const page = await browser.newPage();
-  page.on("console", (message) => console.log(message.type(), message.text()));
-  page.on("pageerror", (error) => console.error("PAGE_ERROR", error.message));
-  await page.goto("http://127.0.0.1:" + server.address().port);
-  await page.waitForFunction(() => typeof window.runBeamGPU === "function");
-  const result = await page.evaluate((options) => window.runBeamGPU(options), options);
-  const output = process.env.BEAM_RESULT ?? path.join(runner, "result.json");
-  fs.writeFileSync(
-    output,
-    JSON.stringify(
-      { timestamp: new Date().toISOString(), browser: browser.version(), options, ...result },
-      (_, x) => (typeof x === "bigint" ? x.toString() : x),
-      2,
-    ),
-  );
-  console.log("SAVED", output);
-} catch (error) {
-  const cdp = await browser.newBrowserCDPSession();
-  console.error("GPU_DIAGNOSTICS", JSON.stringify(await cdp.send("SystemInfo.getInfo")));
-  throw error;
-} finally {
-  await browser.close();
-  server.close();
-}
diff --git a/scripts/beam-timestamps/.gitignore b/scripts/beam-timestamps/.gitignore
deleted file mode 100644
index 5ebc93e7b..000000000
--- a/scripts/beam-timestamps/.gitignore
+++ /dev/null
@@ -1,4 +0,0 @@
-model-cache/
-jfk.wav
-results/*.log
-results/*.json
diff --git a/scripts/beam-timestamps/README.md b/scripts/beam-timestamps/README.md
deleted file mode 100644
index 24f47017e..000000000
--- a/scripts/beam-timestamps/README.md
+++ /dev/null
@@ -1,71 +0,0 @@
-# Beam timestamp validation
-
-This branch changes only beam ancestry and Whisper timestamp reconstruction. It does not enable decoder-only multimodal beams. Base: `b65dfaff9ca5e7e518c6e99f1d84f7453efd27c1`.
-
-## Output contract
-
-With `return_dict_in_generate`, beam generation returns:
-
-- `cross_attentions`, `decoder_attentions`, `encoder_attentions` when requested: the existing **step → layer → tensor** layout. Tensor row indices are the global forward rows (`input * num_beams + beam`), including diverse groups. Returned attention tensors remain caller-owned and readable until disposed.
-- `beam_indices`: int64 `[returned_sequences, padded_sequence_length]`. Column **zero means the first generated token**, not the first prefix token. Each entry identifies the parent forward row for that step, including the step selecting EOS. Unused columns are `-1`.
-- `sequence_lengths`: int64 valid lengths including prefix and EOS. Padding is not aligned.
-
-Whisper reconstructs the selected ancestry before computing statistics. First-forward prefix queries are excluded before normalization and DTW, matching Python Transformers v4.57.1. Later forwards contribute the final query (the preceding generated token), for cached and uncached decoders. The final generated token has no query and repeats the last aligned boundary; padding timestamps are zero. fp16 storage is numerically converted to fp32. Constant variance produces zero normalized weights. Recordings with at most half the median window in frames skip median filtering, matching Python; the general median-filter implementation is unchanged.
-
-Public `num_frames` is a mel-frame count (10 ms), scalar or per input. Alignment uses `floor(num_frames / 2)` encoder frames (20 ms). Short-form batch and multiple returns are supported with `max_new_tokens`. Seek mode supports one input and one return; other combinations fail before encoding. Seek mode currently rejects explicit public attention output because its concatenated transcript does not have a single encoder/attention time axis. Internal seek attentions are released after alignment.
-
-## Pinned fixtures
-
-- `onnx-community/whisper-tiny.en_timestamped` at `aeaa13760958b03fac5062f457d317d3319c3168`, with real `encoder_model.onnx` and `decoder_model_merged.onnx` exports; fp16 uses their `_fp16.onnx` counterparts. The export includes alignment heads.
-- `Xenova/transformers.js-docs/jfk.wav` at dataset revision `542437c29cc5273cfd29e25c77696f2b349badd7`.
-- The shared harness decodes PCM16, averages channels, and linearly resamples to 16 kHz identically in Node and browsers. Long audio is exactly 35 seconds of this waveform repeated. No microphone or variable input is used.
-
-## Native
-
-From this worktree, after `pnpm install --offline --frozen-lockfile` (use a frozen network install only if the store is incomplete):
-
-```sh
-pnpm --filter @huggingface/transformers build
-node scripts/beam-timestamps/native.mjs '{"device":"cpu","dtype":"fp32","batch":true,"returns":2,"repeats":3}' > scripts/beam-timestamps/results/native-cpu.json
-node scripts/beam-timestamps/native.mjs '{"device":"cpu","dtype":"fp32","returns":2,"repeats":3}' > scripts/beam-timestamps/results/native-single.json
-node scripts/beam-timestamps/native.mjs '{"device":"cpu","dtype":"fp32","batch":true,"returns":2,"beams":4,"groups":2,"publicAttentions":true,"repeats":25}' > scripts/beam-timestamps/results/native-diverse.json
-node scripts/beam-timestamps/native.mjs '{"device":"cpu","dtype":"fp32","long":true,"repeats":3}' > scripts/beam-timestamps/results/native-long.json
-node scripts/beam-timestamps/verify-results.mjs "$(git rev-parse HEAD)"
-```
-
-`TIMESTAMP_AUDIO` can point to the pinned WAV. `TIMESTAMP_CACHE` sets a cache directory; default is branch-local `model-cache/`. Never copy the parent's model cache. `offline-tests.js` provides read-only shared-cache use for the test suite when `TRANSFORMERS_SHARED_CACHE` is set (remote model loading disabled).
-
-On parent-owned NVIDIA hardware, change `device` to `cuda` and run each dtype separately. Record GPU/driver/runtime and an ONNX Runtime provider profile confirming execution; do not infer CUDA execution from a successful request. There is no ROCm/MIGraphX mapping in this repository.
-
-## Browser (AMD/NVIDIA WebGPU and WASM)
-
-Serve the repo root on localhost after building, then open `/scripts/beam-timestamps/browser.html`. Set `?options={"device":"webgpu","dtype":"fp16","repeats":25}` (URL-encoded), or call `window.runTimestamps(options)` from the attached automation browser and save its JSON. Repeat short batch/returns, diverse groups, and single-return long cases above. Use `device:"wasm", dtype:"fp32"` for browser WASM.
-
-The harness records adapter identity, rejects known fallback adapters, and requires `shader-f16` for WebGPU fp16. Attach a browser GPU trace showing actual model execution, exact commit/status, model-file SHA256s, GPU driver, runtime version and raw console logs. `providerExecutionVerified:false` deliberately remains false until that independent evidence is supplied.
-
-Same-backend/dtype batch vs independent comparison requires exact tokens, order, and <=20 ms timestamp error. For cross-backend/dtype comparisons record transcript differences; for equal tokens, initial timing gates are median <=20 ms and maximum <=40 ms. A pinned Python Whisper alignment comparison is still required separately; it does not establish JS execution-provider support.
-
-## Overlap and remaining evidence
-
-Read-only metadata checked for PR1755 (attention/encoder memory), PR1742 (seek/logits regression), and PR1797 (oversized median reflection). This branch necessarily intersects attention and encoder ownership in PR1755. Its beam-loop cleanup also releases unused GPU step outputs before the next forward; it does not copy the general getPastKeyValues patch. It does not import the logits fix or general reflection patch. Invalid seek advancement fails explicitly instead of hanging.
-
-Parent owns hardware validation and both postimplementation review rounds. CPU results and synthetic GPU ownership boundaries are not AMD/NVIDIA execution proof. Full suite, Python alignment parity, browser WASM, hardware cells, and full allocation accounting must be reported individually; no final-readiness claim follows from this harness.
-
-Internal attention instrumentation reports peak live attention bytes and verifies zero remaining tracked bytes after each call, including timestamp-only mode. This is tensor-lifetime accounting, not the driver's allocator high-water mark or total KV/model memory. Explicit public attention histories remain caller-owned. Timestamp-only calls currently retain complete histories too; large models, beam counts and long generations need separate memory admission measurements. fp16 alignment converts only the selected head/row/query frame range.
-
-The verifier requires an immutable full source SHA, clean-checkout provenance, and matching source hashes for every result; stale evidence fails closed. CPU fixture results are not independent Python parity or hardware execution proof. The deterministic numerical regression uses Python Transformers v4.57.1's prefix cropping and short-median-window semantics.
-
-Round-two numerical validation independently executed the unmodified alignment,
-median-filter, and DTW functions extracted from Python Transformers v4.57.1 with
-PyTorch 2.9.0 and NumPy 2.3.4. Sixteen synthetic comparisons cover changing beam
-ancestry, heterogeneous EOS lengths/frame counts, short median windows, and
-fp16-quantized inputs decoded to fp32. All boundaries match exactly after making
-Whisper statistics and DTW cost accumulation explicitly fp32. The general DTW
-helper retains its previous precision unless the new option is requested. This
-is algorithm parity, not full Python model-inference parity. Near-tie regressions
-are retained in the unit tests.
-
-Seek generation preserves existing processor-provided log-mel silence padding
-while bounding alignment to valid audio frames. The English speech fixture lasts
-13 seconds: its final word now ends at 12.98 seconds (the last valid encoder frame)
-instead of the previous out-of-recording 13.6-second golden.
diff --git a/scripts/beam-timestamps/browser.html b/scripts/beam-timestamps/browser.html
deleted file mode 100644
index d31d08651..000000000
--- a/scripts/beam-timestamps/browser.html
+++ /dev/null
@@ -1,14 +0,0 @@
-Whisper beam timestamp validation
-

-
diff --git a/scripts/beam-timestamps/harness.mjs b/scripts/beam-timestamps/harness.mjs
deleted file mode 100644
index a4e8385ca..000000000
--- a/scripts/beam-timestamps/harness.mjs
+++ /dev/null
@@ -1,156 +0,0 @@
-// Shared native/browser runner. The caller supplies the branch-local library.
-export const fixture = {
-  model: "onnx-community/whisper-tiny.en_timestamped",
-  revision: "aeaa13760958b03fac5062f457d317d3319c3168",
-  audio: "https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/542437c29cc5273cfd29e25c77696f2b349badd7/jfk.wav",
-};
-export async function run(
-  lib,
-  {
-    device = "cpu",
-    dtype = "fp32",
-    repeats = 3,
-    long = false,
-    batch = false,
-    beams = 2,
-    returns = 1,
-    groups = 1,
-    publicAttentions = false,
-    audioBytes = null,
-  } = {},
-) {
-  const { AutoProcessor, WhisperForConditionalGeneration, Tensor, cat } = lib;
-  const bytes = audioBytes ?? (await (await fetch(fixture.audio)).arrayBuffer());
-  // Decode the pinned stereo PCM16 WAV and deterministically resample to mono 16 kHz.
-  const view = new DataView(bytes);
-  let offset = 12,
-    samples,
-    channels,
-    rate;
-  while (offset + 8 <= view.byteLength) {
-    const tag = String.fromCharCode(...new Uint8Array(bytes, offset, 4));
-    const size = view.getUint32(offset + 4, true);
-    if (tag === "fmt ") {
-      if (view.getUint16(offset + 8, true) !== 1 || view.getUint16(offset + 22, true) !== 16) throw Error("Expected PCM16");
-      channels = view.getUint16(offset + 10, true);
-      rate = view.getUint32(offset + 12, true);
-    }
-    if (tag === "data") {
-      const mono = Float32Array.from({ length: size / (2 * channels) }, (_, i) => {
-        let value = 0;
-        for (let c = 0; c < channels; ++c) value += view.getInt16(offset + 8 + 2 * (i * channels + c), true) / (32768 * channels);
-        return value;
-      });
-      samples = Float32Array.from({ length: Math.floor((mono.length * 16000) / rate) }, (_, i) => {
-        const position = (i * rate) / 16000,
-          left = Math.floor(position),
-          fraction = position - left;
-        return mono[left] * (1 - fraction) + mono[Math.min(left + 1, mono.length - 1)] * fraction;
-      });
-      break;
-    }
-    offset += 8 + size + (size % 2);
-  }
-  if (!samples) throw Error("Missing PCM data");
-  if (long) {
-    const repeated = new Float32Array(16000 * 35);
-    for (let i = 0; i < repeated.length; ++i) repeated[i] = samples[i % samples.length];
-    samples = repeated;
-  }
-  const processor = await AutoProcessor.from_pretrained(fixture.model, { revision: fixture.revision });
-  const model = await WhisperForConditionalGeneration.from_pretrained(fixture.model, {
-    revision: fixture.revision,
-    device,
-    dtype,
-    session_options: { intraOpNumThreads: 1, interOpNumThreads: 1 },
-  });
-  const processed = await processor(samples, { truncation: !long });
-  const input = batch ? cat([processed.input_features, processed.input_features], 0) : processed.input_features;
-  const options = {
-    input_features: input,
-    num_beams: beams,
-    num_beam_groups: groups,
-    diversity_penalty: groups > 1 ? 1 : 0,
-    num_return_sequences: returns,
-    return_token_timestamps: true,
-    return_timestamps: long,
-    output_attentions: publicAttentions,
-    num_frames: Math.floor(samples.length / 160),
-    ...(long ? {} : { max_new_tokens: 64 }),
-  };
-  // Instrument actual internal attention lifetime, including timestamp-only calls.
-  // This measures attention allocations, not total ORT/GPU allocator residency.
-  const liveAttentions = new Map();
-  let liveAttentionBytes = 0,
-    peakAttentionBytes = 0;
-  const originalDispose = Tensor.prototype.dispose;
-  Tensor.prototype.dispose = function (...args) {
-    const bytes = liveAttentions.get(this);
-    if (bytes !== undefined) {
-      liveAttentionBytes -= bytes;
-      liveAttentions.delete(this);
-    }
-    return originalDispose.apply(this, args);
-  };
-  const originalForward = model.forward;
-  model.forward = async function (...args) {
-    const result = await originalForward.apply(this, args);
-    for (const [name, tensor] of Object.entries(result)) {
-      if (!/^(cross|decoder|encoder)_attentions/.test(name) || liveAttentions.has(tensor)) continue;
-      const bytes = tensor.dims.reduce((a, b) => a * b, 1) * ({ float16: 2, float32: 4, float64: 8 }[tensor.type] ?? 4);
-      liveAttentions.set(tensor, bytes);
-      liveAttentionBytes += bytes;
-      peakAttentionBytes = Math.max(peakAttentionBytes, liveAttentionBytes);
-    }
-    return result;
-  };
-  const timings = [],
-    outputs = [];
-  try {
-    for (let iteration = -1; iteration < repeats; ++iteration) {
-      peakAttentionBytes = liveAttentionBytes;
-      const start = performance.now();
-      const result = await model.generate(options);
-      const elapsed = performance.now() - start;
-      console.error(JSON.stringify({ iteration, elapsed_ms: elapsed, memory: typeof process !== "undefined" ? process.memoryUsage() : null }));
-      const record = {
-        tokens: result.sequences.tolist().map((row) => row.map(Number)),
-        timestamps: result.token_timestamps.tolist(),
-        beam_indices: result.beam_indices?.tolist().map((row) => row.map(Number)),
-        lengths: result.sequence_lengths?.tolist().map(Number),
-        retainedAttentionBytes: 0,
-        peakInternalAttentionBytes: peakAttentionBytes,
-      };
-      for (const key of ["cross_attentions", "decoder_attentions", "encoder_attentions"])
-        for (const step of result[key] ?? [])
-          for (const tensor of step) {
-            const data = await tensor.ort_tensor.getData(false);
-            record.retainedAttentionBytes += data.byteLength;
-            tensor.dispose();
-          }
-      if (!record.timestamps.flat().every(Number.isFinite)) throw Error("Nonfinite timestamps");
-      for (const value of Object.values(result)) if (value instanceof Tensor) value.dispose();
-      await result.past_key_values?.dispose();
-      record.liveAttentionBytesAfterCleanup = liveAttentionBytes;
-      if (liveAttentionBytes !== 0) throw Error(`Attention allocation leak: ${liveAttentionBytes} bytes`);
-      if (iteration >= 0) {
-        timings.push(elapsed);
-        outputs.push(record);
-      }
-    }
-    return {
-      fixture,
-      requested: { device, dtype, beams, groups, returns, batch, long, repeats },
-      timings_ms: timings,
-      outputs,
-      providerExecutionVerified: false,
-      note: "Attach runtime EP profiling / browser GPU trace and driver identity; requested device alone is not execution proof.",
-    };
-  } finally {
-    model.forward = originalForward;
-    Tensor.prototype.dispose = originalDispose;
-    await model.dispose();
-    input.dispose();
-    if (input !== processed.input_features) processed.input_features.dispose();
-  }
-}
diff --git a/scripts/beam-timestamps/native.mjs b/scripts/beam-timestamps/native.mjs
deleted file mode 100644
index 9c4e03cbe..000000000
--- a/scripts/beam-timestamps/native.mjs
+++ /dev/null
@@ -1,26 +0,0 @@
-import * as lib from "../../packages/transformers/src/transformers.js";
-import { run } from "./harness.mjs";
-import fs from "node:fs";
-import { createHash } from "node:crypto";
-import { execFileSync } from "node:child_process";
-lib.env.cacheDir = process.env.TIMESTAMP_CACHE ?? new URL("./model-cache", import.meta.url).pathname;
-const options = JSON.parse(process.argv[2] ?? "{}");
-if (process.env.TIMESTAMP_AUDIO) {
-  const b = fs.readFileSync(process.env.TIMESTAMP_AUDIO);
-  options.audioBytes = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);
-}
-const sourcePaths = ["generation/beam_search.js", "models/modeling_utils.js", "models/whisper/modeling_whisper.js"];
-const provenance = {
-  sha: execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(),
-  status: execFileSync("git", ["status", "--porcelain"], { encoding: "utf8" }).trim(),
-  sources: Object.fromEntries(
-    sourcePaths.map((path) => [
-      path,
-      createHash("sha256")
-        .update(fs.readFileSync(new URL(`../../packages/transformers/src/${path}`, import.meta.url)))
-        .digest("hex"),
-    ]),
-  ),
-};
-const result = await run(lib, options);
-console.log(JSON.stringify({ ...provenance, runtime: process.version, platform: process.platform, ...result }, null, 2));
diff --git a/scripts/beam-timestamps/offline-tests.js b/scripts/beam-timestamps/offline-tests.js
deleted file mode 100644
index adebe1642..000000000
--- a/scripts/beam-timestamps/offline-tests.js
+++ /dev/null
@@ -1,5 +0,0 @@
-import { env } from "../../packages/transformers/src/env.js";
-if (process.env.TRANSFORMERS_SHARED_CACHE) {
-  env.cacheDir = process.env.TRANSFORMERS_SHARED_CACHE;
-  env.allowRemoteModels = false;
-}
diff --git a/scripts/beam-timestamps/results/.gitkeep b/scripts/beam-timestamps/results/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/scripts/beam-timestamps/verify-results.mjs b/scripts/beam-timestamps/verify-results.mjs
deleted file mode 100644
index 3dfed9b07..000000000
--- a/scripts/beam-timestamps/verify-results.mjs
+++ /dev/null
@@ -1,73 +0,0 @@
-import assert from "node:assert/strict";
-import fs from "node:fs";
-import { execFileSync } from "node:child_process";
-import { createHash } from "node:crypto";
-const requestedRevision = process.argv[2];
-assert(requestedRevision, "Pass the exact expected source commit as the first argument");
-const expectedRevision = execFileSync("git", ["rev-parse", `${requestedRevision}^{commit}`], { encoding: "utf8" }).trim();
-assert.equal(requestedRevision, expectedRevision, "Use a full immutable commit SHA");
-const sourcePaths = ["generation/beam_search.js", "models/modeling_utils.js", "models/whisper/modeling_whisper.js"];
-const expectedSources = Object.fromEntries(
-  sourcePaths.map((path) => [
-    path,
-    createHash("sha256")
-      .update(execFileSync("git", ["show", `${expectedRevision}:packages/transformers/src/${path}`]))
-      .digest("hex"),
-  ]),
-);
-const read = (name) => JSON.parse(fs.readFileSync(new URL(`results/${name}.json`, import.meta.url)));
-const batch = read("native-cpu"),
-  single = read("native-single"),
-  diverse = read("native-diverse"),
-  long = read("native-long");
-for (const result of [batch, single, diverse, long]) {
-  assert.equal(result.sha, expectedRevision, "Stale result revision");
-  assert.equal(result.status, "", "Results must come from a clean checkout");
-  assert.deepEqual(result.sources, expectedSources, "Source bytes do not match the requested revision");
-  assert(result.outputs.length >= 3, "Require three measured repeats");
-  assert.equal(result.fixture.revision, "aeaa13760958b03fac5062f457d317d3319c3168");
-  for (const output of result.outputs) {
-    assert(output.peakInternalAttentionBytes > 0);
-    assert.equal(output.liveAttentionBytesAfterCleanup, 0);
-    assert.equal(output.tokens.length, output.timestamps.length);
-    output.tokens.forEach((tokens, row) => {
-      const times = output.timestamps[row],
-        length = output.lengths?.[row] ?? tokens.length;
-      assert.equal(tokens.length, times.length);
-      assert(times.every(Number.isFinite));
-      for (let i = 1; i < length; ++i) assert(times[i] >= times[i - 1], `non-monotonic row ${row} at ${i}`);
-      assert(times.slice(length).every((t) => t === 0));
-      if (output.beam_indices) {
-        const history = output.beam_indices[row].filter((x) => x !== -1);
-        // Short-form English prefix has two tokens.
-        assert.equal(history.length, length - 2);
-        const input = Math.floor(row / result.requested.returns);
-        assert(history.every((x) => Math.floor(x / result.requested.beams) === input));
-      }
-    });
-    assert.deepEqual(output, result.outputs[0], "repeated call output drift");
-  }
-}
-for (let row = 0; row < batch.outputs[0].tokens.length; ++row) {
-  const rank = row % 2;
-  assert.deepEqual(batch.outputs[0].tokens[row], single.outputs[0].tokens[rank]);
-  assert.deepEqual(batch.outputs[0].timestamps[row], single.outputs[0].timestamps[rank]);
-}
-assert.equal(diverse.outputs.length, 25);
-assert(diverse.outputs.every((x) => x.retainedAttentionBytes > 0));
-console.log(
-  JSON.stringify(
-    {
-      passed: true,
-      checks: [
-        "batch vs independent exact tokens and timestamps",
-        "25 diverse public-attention calls stable",
-        "global ancestry and valid lengths",
-        "35-second seek monotonicity",
-        "EOS and zero padding",
-      ],
-    },
-    null,
-    2,
-  ),
-);