diff --git a/packages/transformers/docs/source/_toctree.yml b/packages/transformers/docs/source/_toctree.yml index 0a6349615..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 @@ -69,6 +71,8 @@ title: Stopping Criteria - local: api/generation/streamers title: Streamers + - local: api/generation/beam_search + title: Beam search - local: api/generation/cache title: Cache title: Generation 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..111ea2d5f --- /dev/null +++ b/packages/transformers/docs/source/guides/beam-search.md @@ -0,0 +1,114 @@ +# 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, +}); +``` + +## 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`). +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. + +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/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/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 new file mode 100644 index 000000000..524617612 --- /dev/null +++ b/packages/transformers/src/generation/beam_search.js @@ -0,0 +1,280 @@ +/** + * @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. + * @param {number} [max_length] Maximum generated length, excluding the prompt. + */ + 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[], beam_indices: number[]}[]} */ + 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. + * @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, 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: [...tokens], beam_indices: [...beam_indices] }); + 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') { + 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 + 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] + * @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, + num_beams, + { + length_penalty = 1.0, + early_stopping = false, + 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; + 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, max_length - decoder_prompt_len), + ); + /** @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 * 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, beam_indices = [], row_indices = null) { + 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(-Infinity); + 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 = 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]; + 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) { + // 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, [ + ...(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; + 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 (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); + 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 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 }; + } + + /** + * 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) { + 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. + * @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, 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]; + 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], + all_input_ids[flat_idx].length - this.decoder_prompt_len, + beam_indices[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]); + } + } + return results; + } +} 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/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 6973b627c..3cd0c2da6 100644 --- a/packages/transformers/src/models/modeling_utils.js +++ b/packages/transformers/src/models/modeling_utils.js @@ -11,7 +11,16 @@ 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 @@ -44,7 +53,10 @@ 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 { 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'; import { logger } from '../utils/logger.js'; import { DynamicCache } from '../cache_utils.js'; @@ -745,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; } /** @@ -839,6 +858,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. */ @@ -864,213 +887,767 @@ export class PreTrainedModel extends Callable { }); const is_encoder_decoder = this.config.is_encoder_decoder; - - // 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, - }); + if (generation_config.num_beams > 1) { + 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.'); + } } - // 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]; - } + let owned_encoder_output = null; + 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; + } - // 6. Prepare `max_length` depending on other stopping criteria. - let input_ids_length = input_ids.dims.at(-1); + // 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]; + } - if (generation_config.max_new_tokens !== null) { - generation_config.max_length = input_ids_length + generation_config.max_new_tokens; - } + // 6. Prepare `max_length` depending on other stopping criteria. + let input_ids_length = input_ids.dims.at(-1); - // input_ids_length = model_inputs[model_input_name].dims.at(1); - // // inputs instanceof Tensor ? : inputs.length; + if (generation_config.max_new_tokens !== null) { + generation_config.max_length = input_ids_length + generation_config.max_new_tokens; + } - // // decoder-only - // if (input_ids_length === 0) { - // throw Error("Must supply a non-empty array of input token ids.") - // } + // input_ids_length = model_inputs[model_input_name].dims.at(1); + // // inputs instanceof Tensor ? : inputs.length; - // 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; + // // decoder-only + // if (input_ids_length === 0) { + // throw Error("Must supply a non-empty array of input token ids.") + // } - // Update logits processor - // 8. prepare distribution pre_processing samplers - const prepared_logits_processor = this._get_logits_processor( - generation_config, - input_ids_length, - logits_processor, - ); + // 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; - // 9. prepare stopping criteria - const prepared_stopping_criteria = this._get_stopping_criteria(generation_config, stopping_criteria); + // Update logits processor + // 8. prepare distribution pre_processing samplers + const prepared_logits_processor = this._get_logits_processor( + generation_config, + input_ids_length, + logits_processor, + ); - // /** @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]; - // } + // 9. prepare stopping criteria + const prepared_stopping_criteria = this._get_stopping_criteria(generation_config, stopping_criteria); - const numInputs = model_inputs[model_input_name].dims.at(0); + // /** @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]; + // } - // 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(); + 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.'); + } - const sampler = LogitsSampler.getSampler(generation_config); + 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, + }); + } + } - // TODO make > numInputs - const scores = new Array(numInputs).fill(0); - /** @type {bigint[][]} */ - const all_input_ids = input_ids.tolist(); - 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: - // - 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 (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] = []; + const sampler = LogitsSampler.getSampler(generation_config); + + const scores = new Array(is_beam_search ? numInputs * num_beams : numInputs).fill(0); + /** @type {bigint[][]} */ + const all_input_ids = input_ids.tolist(); + + // 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); + } + 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), + ); + 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; } - 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)); } - } - // 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'); - - const next_tokens_scores = prepared_logits_processor(all_input_ids, logits); - - /** @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 (streamer) { + streamer.put(all_input_ids); } - } - if (streamer) { - streamer.put(generated_input_ids); - } - const stop = prepared_stopping_criteria(all_input_ids); - if (stop.every((x) => x)) { - break; - } + //////////////////////////////////////////////////// + // 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)); + } + } - model_inputs = this._update_model_kwargs_for_generation({ - generated_input_ids, - outputs, - model_inputs, - is_encoder_decoder, - }); - } + // 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 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); + } + } + + // 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); + } + } + } + } 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); + } + } + + 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) { + 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 + ({ 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, + )); + } - if (streamer) { - streamer.end(); - } + // 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); - // 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]); + // Update beam scores + for (let i = 0; i < total_beams; ++i) { + beam_scores[i] = next_beam_scores[i]; + } - // Update past key values from the final forward pass - const past_key_values = getPastKeyValues(outputs, model_inputs.past_key_values); + // 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; + } + } + } - // 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(); - } - } + if (streamer) { + streamer.put(generated_input_ids); + } - // Dispose cache tensors if no one needs them - const keepCacheAlive = 'past_key_values' in kwargs || generation_config.return_dict_in_generate; - if (!keepCacheAlive) { - await past_key_values.dispose(); - } + // 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; + } + } + 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 (generation_config.return_dict_in_generate) { - return { - sequences, - past_key_values, - ...attentions, - ...return_dict_items, - // TODO: - // scores, - // logits, - }; + 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, + }); + } + } + + 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 }, () => []); + + 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, + 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]); + } + } + } + + 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]); + } + } + } 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); + } + + // 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); + + // 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(); + } + + 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) { + // 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(); + } + } + } + } finally { + owned_encoder_output?.dispose(); } - return sequences; } /** @@ -1089,6 +1666,55 @@ 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. + * @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); + 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)); + 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); + } + /** * Encode image inputs into features for multimodal generation. * @param {any} inputs Vision encoder inputs. 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..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 { cat, mean, Tensor, stack, std_mean } 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'; @@ -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, ...kwargs, + decoder_input_ids, }); 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 @@ -218,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; @@ -226,11 +280,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 +301,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); + decoder_input_ids: init_tokens, + 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. + // 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, + ); + 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); + } + + // 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)); + 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 +438,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 +458,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 +495,81 @@ 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; + // 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)); + 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 matrix = Array.from({ length: queries }, () => new Float32Array(frames)); + for (const [layer, head] of alignment_heads) { + const weights = []; + 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.'); + // 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(); + } } - 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]; + // 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; } - - // Apply median filter. - cTensorData.set(medianFilter(cTensorData, median_filter_width)); + } + 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[skipped + token] + : medianFilter(weights[skipped + token], median_filter_width); + for (let frame = 0; frame < frames; ++frame) matrix[token][frame] += filtered[frame]; } } - } - - // 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 [text, times] = dynamic_time_warping( + matrix.map((row) => Array.from(row, (value) => -Math.fround(value / alignment_heads.length))), ); - 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); + 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; } } - - // 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)); - } - timestamps[batch_idx].data.set(padded); } return timestamps; diff --git a/packages/transformers/src/transformers.js b/packages/transformers/src/transformers.js index e92689ee1..022c6cea8 100644 --- a/packages/transformers/src/transformers.js +++ b/packages/transformers/src/transformers.js @@ -68,6 +68,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 { GenerationConfig } from './generation/configuration_utils.js'; export { load_audio, read_audio, RawAudio } from './utils/audio.js'; diff --git a/packages/transformers/src/utils/tensor.js b/packages/transformers/src/utils/tensor.js index b1bf8c107..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 @@ -1449,6 +1450,86 @@ 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. + * @param {DataArray} data The materialized tensor data. + * @returns {Tensor} A new tensor with selected rows. + */ +function _index_select_from_data(tensor, indices, data) { + const [, ...restDims] = tensor.dims; + const rowSize = restDims.length > 0 ? restDims.reduce((a, b) => a * b, 1) : 1; + const newBatchSize = indices.length; + + let out; + if (!Array.isArray(data)) { + // @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]); +} + +/** + * Select tensor rows along the batch dimension. + * @param {Tensor} tensor The source CPU tensor. + * @param {number[]} indices The row indices to select. + * @returns {Tensor} A new tensor containing the selected rows. + */ +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 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. + */ +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) { + throw new Error(`Tensor does not support getData() for location: ${tensor.location}.`); + } + + const data = await ort_tensor.getData(false); + 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/src/utils/webgpu.js b/packages/transformers/src/utils/webgpu.js new file mode 100644 index 000000000..0ffc77de1 --- /dev/null +++ b/packages/transformers/src/utils/webgpu.js @@ -0,0 +1,73 @@ +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 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', + 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, byte_length)); + } finally { + staging.destroy(); + } + }, + }); + } catch (error) { + output.destroy(); + throw error; + } +} 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..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,30 +229,33 @@ 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] }, - { text: " creed.", timestamp: [12.64, 13.6] }, + { 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); + for (const chunk of output.chunks) { + expect(chunk.timestamp[1]).toBeLessThanOrEqual(audio.length / 16000); + } }, MAX_TEST_EXECUTION_TIME, ); @@ -336,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/beam_ownership.test.js b/packages/transformers/tests/utils/beam_ownership.test.js new file mode 100644 index 000000000..4d70dd862 --- /dev/null +++ b/packages/transformers/tests/utils/beam_ownership.test.js @@ -0,0 +1,235 @@ +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.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.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, + 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 () => { + throw new Error("must not run"); + }; + await expect(model.generate({ num_beams: 2, max_new_tokens: 1 })).rejects.toThrow("decoder-only multimodal inputs"); + }); + + 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 () => { + 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 }) }; + }; + 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/beam_search.test.js b/packages/transformers/tests/utils/beam_search.test.js new file mode 100644 index 000000000..cfb9ca28d --- /dev/null +++ b/packages/transformers/tests/utils/beam_search.test.js @@ -0,0 +1,94 @@ +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); + }); +}); + +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]]); + }); +}); 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([]); + }); +}); 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(); + } +}); 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/generation.test.js b/packages/transformers/tests/utils/generation.test.js index d827ba3e3..01411315a 100644 --- a/packages/transformers/tests/utils/generation.test.js +++ b/packages/transformers/tests/utils/generation.test.js @@ -10,10 +10,15 @@ import { // Other TextStreamer, + LogitsProcessor, DynamicCache, StoppingCriteria, random, full, + BeamSearchScorer, + BeamHypotheses, + PreTrainedModel, + Tensor, } from "../../src/transformers.js"; import { init, MAX_TEST_EXECUTION_TIME, MAX_MODEL_LOAD_TIME, MAX_MODEL_DISPOSE_TIME, DEFAULT_MODEL_OPTIONS } from "../init.js"; @@ -615,3 +620,388 @@ describe("PKV caching", () => { }, MAX_MODEL_DISPOSE_TIME); }); }); + +describe("Beam cache reordering", () => { + it("preserves DynamicCache methods and reorders decoder rows within each batch", async () => { + const decoder = new Tensor("float32", [1, 2, 3, 4], [4, 1, 1, 1]); + const encoder = new Tensor("float32", [10, 10, 20, 20], [4, 1, 1, 1]); + const cache = new DynamicCache({ + "past_key_values.0.decoder.key": decoder, + "past_key_values.0.encoder.key": encoder, + }); + const reordered = await PreTrainedModel.prototype._reorder_cache(cache, [1, 1, 3, 2]); + expect(reordered).toBeInstanceOf(DynamicCache); + expect(reordered.get_seq_length()).toBe(1); + expect(Array.from(reordered["past_key_values.0.decoder.key"].data)).toEqual([2, 2, 4, 3]); + expect(reordered["past_key_values.0.encoder.key"]).toBe(encoder); + reordered.update({ "past_key_values.0.decoder.key": full([4, 1, 2, 1], 0.0) }); + expect(reordered.get_seq_length()).toBe(2); + await reordered.dispose(); + }); +}); + +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"; + 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( + "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( + "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.each([ + ["standard", {}], + ["diverse", { num_beam_groups: 2, diversity_penalty: 0.5 }], + ])( + "%s beam search keeps batch items independent", + async (_name, options) => { + tokenizer.padding_side = "left"; + const texts = ["hello", "a longer input"]; + const inputs = tokenizer(texts, { padding: true }); + const config = { num_beams: 4, num_return_sequences: 2, max_new_tokens: 3, ...options }; + const batched = await model.generate({ ...inputs, ...config, return_dict_in_generate: true }); + expect(batched.past_key_values).toBeNull(); + expect(batched.sequences.dims[0]).toBe(4); + for (let i = 0; i < texts.length; ++i) { + const single = await model.generate({ ...tokenizer(texts[i]), ...config }); + const tail = (rows) => rows.map((row) => row.slice(-3)); + expect(tail(batched.sequences.tolist().slice(i * 2, i * 2 + 2))).toEqual(tail(single.tolist())); + } + }, + 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 () => { + 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 and greedy both produce a sequence", + 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( + "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( + "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.each([ + ["standard", {}], + ["diverse", { num_beam_groups: 2, diversity_penalty: 0.5 }], + ])( + "%s beam search keeps batch items independent", + async (_name, options) => { + tokenizer.padding_side = "left"; + const texts = ["hello", "a longer input"]; + const inputs = tokenizer(texts, { padding: true }); + const config = { num_beams: 4, num_return_sequences: 2, max_new_tokens: 3, ...options }; + const batched = await model.generate({ ...inputs, ...config, return_dict_in_generate: true }); + expect(batched.past_key_values).toBeNull(); + expect(batched.sequences.dims[0]).toBe(4); + for (let i = 0; i < texts.length; ++i) { + const single = await model.generate({ ...tokenizer(texts[i]), ...config }); + const tail = (rows) => rows.map((row) => row.slice(-3)); + expect(tail(batched.sequences.tolist().slice(i * 2, i * 2 + 2))).toEqual(tail(single.tolist())); + } + }, + 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 () => { + 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( + "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); + }); + + 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)"); + }); + }); +}); 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..b5e54b425 --- /dev/null +++ b/packages/transformers/tests/utils/whisper_beam_timestamps.test.js @@ -0,0 +1,286 @@ +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"; +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 (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 }, [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); +}); + +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: 4 }, + { frames: 2, length: 4 }, + ]); + 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(); + } +}); + +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(); + } +}); + +// Compare against the independent, pre-beam PR #1809 algorithm. +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.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); + 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(5 * 6); + } finally { + 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(); + } +}); + +// 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], + [2, 3, 2], + ]; + const steps = Array.from({ length: 5 }, (_, step) => + Array.from({ length: 2 }, (_, layer) => { + const dims = [4, 2, step === 0 ? 3 : 1, 16]; + 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 = { + sequences: new Tensor( + "int64", + Array.from({ length: 16 }, (_, i) => BigInt(i)), + [2, 8], + ), + cross_attentions: steps, + 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 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]]); +});