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..237e81103 --- /dev/null +++ b/packages/transformers/docs/source/guides/beam-search.md @@ -0,0 +1,120 @@ +# 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`). +Image inputs are supported for Llava, Idefics3, SmolVLM, and Qwen2VL. Ultravox +supports audio inputs. Each original image or audio input is encoded before beam +expansion; prefill embeddings are consumed once. Supplied `inputs_embeds` must +already contain merged modality features, alongside the original `input_ids` +and the corresponding attention mask. The caller retains ownership of supplied +embeddings and caches. + +Video inputs, other decoder-only multimodal families, and `output_attentions` +(including Whisper token timestamps) are not supported with beams. Ultravox's +processor currently accepts one audio example at a time; equal-length processed +audio tensors can be collated for batched generation. Qwen2VL generation accepts +preprocessed multi-image patch tensors and grids; support for passing multiple +raw images through its processor is tracked separately in +[PR #1812](https://github.com/huggingface/transformers.js/pull/1812). For Qwen2VL cached +continuation, retain the original image grid or supply the matching `rope_deltas` +with the input ids and attention mask. Appending raw images to an image-containing +Qwen2VL cache is not supported: use prepared query embeddings and matching +positions/rotary offsets, or regenerate the full conversation without a cache. +Raw-image chunks after a text-only cache require full input-id history. +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..fa5c5efa3 --- /dev/null +++ b/packages/transformers/src/generation/beam_search.js @@ -0,0 +1,272 @@ +/** + * @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[]}[]} */ + 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. + */ + add(sum_logprobs, tokens, generated_length = tokens.length) { + const score = sum_logprobs / Math.max(1, generated_length) ** this.length_penalty; + if (this.beams.length < this.num_beams || score > this.worst_score) { + this.beams.push({ score, tokens }); + if (this.beams.length > this.num_beams) { + // 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]. + * @returns {{ next_beam_scores: number[], next_beam_tokens: bigint[], next_beam_indices: number[] }} + */ + process(all_input_ids, beam_scores, next_tokens, next_indices, next_scores) { + const cur_len = all_input_ids[0].length; + const total_beams = this.batch_size * this.num_beams; + + const next_beam_scores = new Array(total_beams).fill(-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); + } 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. + * @returns {{tokens: bigint[], score: number}[]} Best sequences with scores. + */ + finalize_with_scores(all_input_ids, beam_scores) { + // For each batch, ensure we have enough hypotheses + for (let batch_idx = 0; batch_idx < this.batch_size; ++batch_idx) { + const hyps = this._beam_hyps[batch_idx]; + 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, + ); + } + } + } + + // 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..247b481d0 100644 --- a/packages/transformers/src/generation/parameters.js +++ b/packages/transformers/src/generation/parameters.js @@ -9,6 +9,13 @@ * method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs` * should be in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of * `input_ids`, `input_values`, `input_features`, or `pixel_values`. + * @property {import('../utils/tensor.js').Tensor} [inputs_embeds=null] Prepared prefill embeddings for models that accept them. + * For multimodal generation these must already include merged modality features. Supply the original + * `input_ids` for token history and length accounting, and the matching `attention_mask`. Embeddings + * are used only for prefill by the supported merged-modality families (Llava, Idefics3, + * SmolVLM, Qwen2VL images, and Ultravox); the caller retains ownership of this tensor. + * @property {import('../utils/tensor.js').Tensor} [rope_deltas=null] Qwen2VL per-example rotary position offsets, + * with shape `[batch_size, 1]`. Retain these when continuing from a cache without the original image grid. * @property {import('./configuration_utils.js').GenerationConfig} [generation_config=null] (`GenerationConfig`, *optional*): * The generation configuration to use as the base parameters for the generation call. * `**kwargs` passed to generate that match attributes of `generation_config` will override them. diff --git a/packages/transformers/src/models/llava/modeling_llava.js b/packages/transformers/src/models/llava/modeling_llava.js index 3b8fcd748..a389e1bb4 100644 --- a/packages/transformers/src/models/llava/modeling_llava.js +++ b/packages/transformers/src/models/llava/modeling_llava.js @@ -8,6 +8,15 @@ export class LlavaPreTrainedModel extends PreTrainedModel { * The LLAVA model which consists of a vision backbone and a language model. */ export class LlavaForConditionalGeneration extends LlavaPreTrainedModel { + _multimodal_generation_config() { + if (!['llava', 'idefics3', 'smolvlm'].includes(this.config.model_type)) return null; + return { + modality_input_names: ['pixel_values'], + modality_output_name: 'image_features', + batch_axes: { position_ids: 0, rope_deltas: 0 }, + }; + } + _merge_input_ids_with_image_features(kwargs) { const vision_hidden_size = kwargs.image_features.dims.at(-1); const reshaped_image_hidden_states = kwargs.image_features.view(-1, vision_hidden_size); diff --git a/packages/transformers/src/models/llava/processing_llava.js b/packages/transformers/src/models/llava/processing_llava.js index 5e4394b66..1f7e21eec 100644 --- a/packages/transformers/src/models/llava/processing_llava.js +++ b/packages/transformers/src/models/llava/processing_llava.js @@ -27,7 +27,7 @@ export class LlavaProcessor extends Processor { text = [text]; } for (let i = 0; i < text.length; ++i) { - text[i] = text[i].replace(image_token, image_token.repeat(num_image_tokens)); + text[i] = text[i].replaceAll(image_token, image_token.repeat(num_image_tokens)); } } diff --git a/packages/transformers/src/models/modeling_utils.js b/packages/transformers/src/models/modeling_utils.js index 6973b627c..a6089d017 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'; @@ -662,6 +674,11 @@ export class PreTrainedModel extends Callable { return this._prepare_inputs_for_generation(this, ...args); } + // Opt in only families whose merge and batch axes have been verified. + _multimodal_generation_config() { + return null; + } + /** * * @param {Object} inputs @@ -706,7 +723,9 @@ export class PreTrainedModel extends Callable { * @returns {{inputs_tensor: Tensor, model_inputs: Record & {past_key_values?: DynamicCache}, model_input_name: string}} The model-specific inputs for generation. */ _prepare_model_inputs({ inputs, bos_token_id, model_kwargs }) { - const model_inputs = pick(model_kwargs, this.forward_params); + const model_inputs = pick(model_kwargs, this._multimodal_generation_config() + ? [...this.forward_params, 'inputs_embeds', 'rope_deltas'] + : this.forward_params); const input_name = this.main_input_name; if (input_name in model_inputs) { if (inputs) { @@ -864,6 +883,35 @@ export class PreTrainedModel extends Callable { }); const is_encoder_decoder = this.config.is_encoder_decoder; + const modality = !is_encoder_decoder && this._multimodal_generation_config(); + if (generation_config.num_beams > 1) { + if (generation_config.output_attentions) { + throw new Error('Beam search does not support output_attentions or token timestamps.'); + } + const modality_inputs = [ + 'pixel_values', + 'pixel_values_videos', + 'audio_values', + 'input_features', + 'image_grid_thw', + 'video_grid_thw', + ]; + if ( + !is_encoder_decoder && + modality_inputs.some((key) => (kwargs[key] ?? model_inputs[key]) != null) && + (!modality || + kwargs.pixel_values_videos != null || + kwargs.video_grid_thw != null || + ['pixel_values', 'audio_values', 'input_features'].some( + (key) => + (kwargs[key] ?? model_inputs[key]) != null && !modality.modality_input_names.includes(key), + )) + ) { + throw new Error( + `Beam search does not yet support decoder-only multimodal inputs for ${this.config.model_type ?? 'this model'} with the supplied modality keys.`, + ); + } + } // 4. Define other model kwargs if (!is_encoder_decoder) { @@ -935,142 +983,618 @@ export class PreTrainedModel extends Callable { // } const numInputs = model_inputs[model_input_name].dims.at(0); + const num_beams = generation_config.num_beams; + const num_beam_groups = generation_config.num_beam_groups; + const is_beam_search = num_beams > 1; + const is_group_beam_search = is_beam_search && num_beam_groups > 1; + + let beam_scorer = null; + let beam_scorers = null; + /** @type {number[]} */ + let beam_scores; + + if (is_beam_search) { + // Validate beam search configuration + if (generation_config.num_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.'); + } - // 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(); + 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, + }); + } + } const sampler = LogitsSampler.getSampler(generation_config); - // TODO make > numInputs - const scores = new Array(numInputs).fill(0); + const scores = new Array(is_beam_search ? numInputs * num_beams : numInputs).fill(0); /** @type {bigint[][]} */ const all_input_ids = input_ids.tolist(); - if (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] = []; + // 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; + const prepared_tensors = new Set(); + try { + if (modality) { + // Run family position/cache preparation on the original batch, before expanding. + model_inputs = this.prepare_inputs_for_generation(all_input_ids, model_inputs, generation_config); + const prepared = await prepare_multimodal_inputs(this, { ...model_inputs, ...modality }); + if (prepared.inputs_embeds !== model_inputs.inputs_embeds) prepared_tensors.add(prepared.inputs_embeds); + if (prepared.attention_mask !== model_inputs.attention_mask) + prepared_tensors.add(prepared.attention_mask); + Object.assign(model_inputs, prepared); + // Raw modality groups are flattened/ragged, not batch-major decoder inputs. + for (const key of modality.modality_input_names) delete model_inputs[key]; + delete model_inputs.pixel_attention_mask; + delete model_inputs.image_grid_thw; + } + 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', + 'rope_deltas', + ]) { + const tensor = model_inputs[key]; + if (tensor instanceof Tensor) { + const axis = modality?.batch_axes?.[key] ?? 0; + if (axis === 1) { + model_inputs[key] = index_select(tensor.transpose(1, 0, 2), expanded_indices).transpose( + 1, + 0, + 2, + ); + } else if (tensor.location === 'cpu' || tensor.location === 'cpu-pinned') { + model_inputs[key] = index_select(tensor, expanded_indices); + } else { + model_inputs[key] = await index_select_async(tensor, expanded_indices); } - attentions[key].push(token_attentions[key]); + expanded_tensors.add(model_inputs[key]); + if (key === 'inputs_embeds' && prepared_tensors.delete(tensor)) tensor.dispose(); + } + } + + 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; } - } 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 + if (streamer) { + streamer.put(all_input_ids); + } + + //////////////////////////////////////////////////// + // Generic search which handles 4 generation modes: + // - GenerationMode.GREEDY_SEARCH + // - GenerationMode.SAMPLE + // - GenerationMode.BEAM_SEARCH + // - GenerationMode.BEAM_SAMPLE + //////////////////////////////////////////////////// + let attentions = {}; + let return_dict_items = {}; + while (true) { + // prepare model inputs + model_inputs = this.prepare_inputs_for_generation(all_input_ids, model_inputs, generation_config); + const prefill_embeddings = model_inputs.inputs_embeds; + outputs = await this.forward(model_inputs); + if (modality) { + // Opted-in families consume merged embeddings only during prefill. + model_inputs.inputs_embeds = null; + if (prepared_tensors.delete(prefill_embeddings) || expanded_tensors.delete(prefill_embeddings)) { + prefill_embeddings.dispose(); + } + } + + 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]); + } + } else if (this._return_dict_in_generate_keys) { + Object.assign(return_dict_items, pick(outputs, this._return_dict_in_generate_keys)); + } + } + + // Logits are of the form [batch_size, out_seq_length, vocab_size] + // In most cases, this will be [batch_size, 1, vocab_size] + // So, we select the last token's logits: + // (equivalent to `logits = outputs.logits[:, -1, :]`) + // The `.to('float32')` is necessary for models with float16 logits, + // and is a no-op for float32 logits. + // TODO: Support float16 sampling in the sampler directly + const logits = outputs.logits.slice(null, -1, null).to('float32'); + + // Beam processors operate on log probabilities. Renormalizing after + // suppression would change the relative scores of different beams. + if (is_beam_search) { + const vocab_size = logits.dims.at(-1); + for (let i = 0; i < logits.dims[0]; ++i) { + const offset = i * vocab_size; + const data = /** @type {Float32Array} */ (logits.data); + data.set(log_softmax(data.subarray(offset, offset + vocab_size)), offset); + } + } + 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, + ); + + // 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, + )); + } + + // Reorder all_input_ids based on beam indices and append new tokens + const new_all_input_ids = []; + for (let i = 0; i < total_beams; ++i) { + new_all_input_ids.push([...all_input_ids[next_beam_indices[i]], next_beam_tokens[i]]); + generated_input_ids.push([next_beam_tokens[i]]); + } + all_input_ids.length = 0; + all_input_ids.push(...new_all_input_ids); + + // Update beam scores + for (let i = 0; i < total_beams; ++i) { + beam_scores[i] = next_beam_scores[i]; + } + + // Reorder KV cache to match beam reordering + model_inputs['past_key_values'] = await this._reorder_cache( + getPastKeyValues(outputs, model_inputs.past_key_values), + next_beam_indices, + ); + } else { + // Greedy / sample: existing behavior + for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) { + const logs = next_tokens_scores[batch_idx]; + + const sampledTokens = await sampler(logs); + for (const [newTokenId, logProb] of sampledTokens) { + const bigint = BigInt(newTokenId); + scores[batch_idx] += logProb; + all_input_ids[batch_idx].push(bigint); + generated_input_ids.push([bigint]); + break; + } + } + } + + if (streamer) { + streamer.put(generated_input_ids); + } + + // Check stopping conditions + if (is_beam_search) { + const done = is_group_beam_search + ? beam_scorers.every((scorer) => scorer.is_done) + : beam_scorer.is_done; + if (done) { + break; + } + } + const stop = prepared_stopping_criteria(all_input_ids); + if (stop.every((x) => x)) { break; } + + if (is_beam_search) { + // For beam search, we already updated past_key_values during reordering. + // Now update the remaining model inputs. + model_inputs['input_ids'] = new Tensor('int64', generated_input_ids.flat(), [ + generated_input_ids.length, + 1, + ]); + + if (!is_encoder_decoder) { + model_inputs.attention_mask = cat( + [model_inputs.attention_mask, ones([model_inputs.attention_mask.dims[0], 1])], + 1, + ); + } else if ('decoder_attention_mask' in model_inputs) { + model_inputs.decoder_attention_mask = cat( + [ + model_inputs.decoder_attention_mask, + ones([model_inputs.decoder_attention_mask.dims[0], 1]), + ], + 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.put(generated_input_ids); + streamer.end(); } - const stop = prepared_stopping_criteria(all_input_ids); - if (stop.every((x) => x)) { - break; - } + let sequences; + if (is_beam_search) { + /** @type {bigint[][]} */ + let best_sequences; + if (is_group_beam_search) { + const group_size = num_beams / num_beam_groups; + /** @type {{tokens: bigint[], score: number}[][]} */ + const grouped = Array.from({ length: numInputs }, () => []); + + for (let group_idx = 0; group_idx < num_beam_groups; ++group_idx) { + const group_offset = group_idx * group_size; + const group_all_input_ids = new Array(numInputs * group_size); + const group_beam_scores = new Array(numInputs * group_size); + + for (let 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]; + } + } - model_inputs = this._update_model_kwargs_for_generation({ - generated_input_ids, - outputs, - model_inputs, - is_encoder_decoder, - }); - } + const group_results = beam_scorers[group_idx].finalize_with_scores( + group_all_input_ids, + group_beam_scores, + ); - if (streamer) { - streamer.end(); - } + 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]); + } + } + } - // 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]); + best_sequences = []; + for (let batch_idx = 0; batch_idx < numInputs; ++batch_idx) { + const sorted = grouped[batch_idx].sort((a, b) => b.score - a.score); + for (let i = 0; i < generation_config.num_return_sequences; ++i) { + best_sequences.push(sorted[i].tokens); + } + } + } else { + // Finalize beam search: select best hypotheses + best_sequences = beam_scorer.finalize(all_input_ids, beam_scores); + } - // Update past key values from the final forward pass - const past_key_values = getPastKeyValues(outputs, model_inputs.past_key_values); + // 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]); + } - // 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(); + // Beam search already extracted and reordered the final cache. Do not restore + // the original output tensors, which may have been disposed during reordering. + const past_key_values = is_beam_search + ? model_inputs.past_key_values + : getPastKeyValues(outputs, model_inputs.past_key_values); + + // Dispose output tensors not held by the cache + const cachedTensors = new Set(Object.values(past_key_values)); + for (const tensor of Object.values(outputs)) { + if (tensor.location === 'gpu-buffer' && !cachedTensors.has(tensor)) { + tensor.dispose(); + } } - } - // Dispose 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(); - } + // 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) { - return { - sequences, - past_key_values, - ...attentions, - ...return_dict_items, - // TODO: - // scores, - // logits, - }; + if (generation_config.return_dict_in_generate) { + const past_key_values_for_return = is_beam_search ? null : past_key_values; + return { + sequences, + past_key_values: past_key_values_for_return, + ...attentions, + ...return_dict_items, + }; + } + return sequences; + } finally { + for (const tensor of prepared_tensors) 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 (expanded_tensors.has(tensor) || tensor.location === 'gpu-buffer') tensor.dispose(); + } + if (model_inputs.past_key_values !== caller_cache) { + await model_inputs.past_key_values?.dispose(); + } + } } - return sequences; } /** @@ -1089,6 +1613,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. @@ -1383,6 +1956,56 @@ export async function decoder_forward(self, model_inputs, is_encoder_decoder = f return await sessionRun(session, fixed); } +// Own only encoder results. Caller-provided embeddings are already merged and borrowed. +async function prepare_multimodal_inputs(self, params) { + let { + inputs_embeds, + attention_mask, + input_ids, + past_key_values, + encode_function, + merge_function, + modality_input_names, + modality_output_name, + } = params; + if (inputs_embeds) return { inputs_embeds, attention_mask }; + inputs_embeds = await self.encode_text({ ...params, input_ids }); + let features; + try { + const modality_token_id = + modality_output_name === 'audio_features' + ? (self.config.ignore_index ?? self.config.audio_token_id ?? self.config.audio_token_index) + : (self.config.image_token_index ?? self.config.image_token_id); + // A supplied cache can precede a new multimodal prompt chunk. Merge + // placeholders still present in the unprocessed query, but do not + // re-encode old modality inputs on ordinary cached text decode steps. + const has_unprocessed_modality = + modality_token_id == null + ? input_ids.dims[1] !== 1 + : input_ids.data.some((token) => token == modality_token_id); + if ( + (!past_key_values?.get_seq_length() || has_unprocessed_modality) && + modality_input_names.some((key) => params[key] != null) + ) { + features = await (encode_function ?? self.encode_image.bind(self))(params); + const merged = (merge_function ?? self._merge_input_ids_with_image_features.bind(self))({ + [modality_output_name]: features, + inputs_embeds, + input_ids, + attention_mask, + }); + if (merged.inputs_embeds !== inputs_embeds) inputs_embeds.dispose(); + ({ inputs_embeds, attention_mask } = merged); + } + return { inputs_embeds, attention_mask }; + } catch (error) { + inputs_embeds.dispose(); + throw error; + } finally { + features?.dispose(); + } +} + /** * Abstract forward pass function for image-text-to-text or audio-text-to-text models. * @param {Object} self The model object. @@ -1429,83 +2052,64 @@ async function generic_text_to_text_forward( ...kwargs }, ) { - if (!inputs_embeds) { - // 1. Extract the text embeddings. - inputs_embeds = await self.encode_text({ input_ids, ...kwargs }); - - // 2. Possibly, merge text and modality values - const modality_values = pick(kwargs, modality_input_names); - if (Object.keys(modality_values).length > 0) { - if (input_ids.dims[1] !== 1) { - const modality_features = await encode_function({ - // Pass the modality values under its expected key. - // The caller knows whether this is audio or image. - ...modality_values, - ...kwargs, - }); - ({ inputs_embeds, attention_mask } = merge_function({ - [modality_output_name]: modality_features, - inputs_embeds, - input_ids, - attention_mask, - })); - } else if (past_key_values && input_ids.dims[1] === 1) { - // This branch handles the cache case. - const target_length = input_ids.dims[1]; // always 1 - const past_length = past_key_values.get_seq_length(); - - attention_mask = cat( - [ - ones([input_ids.dims[0], past_length]), - attention_mask.slice(null, [attention_mask.dims[1] - target_length, attention_mask.dims[1]]), - ], - 1, - ); + const prepared = await prepare_multimodal_inputs(self, { + input_ids, + inputs_embeds, + attention_mask, + past_key_values, + encode_function, + merge_function, + modality_input_names, + modality_output_name, + ...kwargs, + }); + const owned_embeddings = prepared.inputs_embeds !== inputs_embeds; + ({ inputs_embeds, attention_mask } = prepared); + try { + if (!position_ids) { + if ( + // Handle special case for qwen vl models + [ + 'qwen2_vl', + 'qwen2_vl_text', + 'qwen2_5_vl', + 'qwen2_5_vl_text', + 'qwen3_vl', + 'qwen3_vl_text', + 'qwen3_vl_moe', + 'qwen3_vl_moe_text', + 'qwen3_5', + 'qwen3_5_text', + 'qwen3_5_moe', + 'qwen3_5_moe_text', + 'glm_ocr', + 'glm_ocr_text', + ].includes(self.config.model_type) + ) { + // @ts-ignore + const { image_grid_thw, video_grid_thw } = kwargs; + [position_ids] = self.get_rope_index(input_ids, image_grid_thw, video_grid_thw, attention_mask); } } - } - if (!position_ids) { - if ( - // Handle special case for qwen vl models - [ - 'qwen2_vl', - 'qwen2_vl_text', - 'qwen2_5_vl', - 'qwen2_5_vl_text', - 'qwen3_vl', - 'qwen3_vl_text', - 'qwen3_vl_moe', - 'qwen3_vl_moe_text', - 'qwen3_5', - 'qwen3_5_text', - 'qwen3_5_moe', - 'qwen3_5_moe_text', - 'glm_ocr', - 'glm_ocr_text', - ].includes(self.config.model_type) - ) { - // @ts-ignore - const { image_grid_thw, video_grid_thw } = kwargs; - [position_ids] = self.get_rope_index(input_ids, image_grid_thw, video_grid_thw, attention_mask); - } + // 3. Call the decoder forward using the updated inputs. + const outputs = await decoder_forward( + self, + { + inputs_embeds, + past_key_values, + attention_mask, + position_ids, + generation_config, + logits_processor, + num_logits_to_keep, + }, + true, + ); + return outputs; + } finally { + if (owned_embeddings) inputs_embeds.dispose(); } - - // 3. Call the decoder forward using the updated inputs. - const outputs = await decoder_forward( - self, - { - inputs_embeds, - past_key_values, - attention_mask, - position_ids, - generation_config, - logits_processor, - num_logits_to_keep, - }, - true, - ); - return outputs; } /** @@ -1665,6 +2269,19 @@ function multimodal_text_to_text_prepare_inputs_for_generation(self, ...args) { } } +function number_to_float16(value) { + const sign = value < 0 || Object.is(value, -0) ? 0x8000 : 0; + const magnitude = Math.abs(value); + if (Number.isNaN(magnitude)) return 0x7e00; + if (magnitude >= 65520) return sign | 0x7c00; + if (magnitude === 0) return sign; + const exponent = Math.max(-14, Math.floor(Math.log2(magnitude))); + const scaled = magnitude / 2 ** (exponent - 10); + const floor = Math.floor(scaled); + const rounded = floor + (scaled - floor > 0.5 || (scaled - floor === 0.5 && floor % 2) ? 1 : 0); + return sign | (rounded < 1024 ? rounded : ((exponent + 14) << 10) + rounded); +} + function default_merge_input_ids_with_features({ modality_token_id, inputs_embeds, @@ -1684,19 +2301,37 @@ function default_merge_input_ids_with_features({ throw new Error(`Number of tokens and features do not match: tokens: ${n_tokens}, features ${n_features}`); } - // Currently, we require modality features to be in float32 for correct scatter behavior. - // TODO: In future, detect dtype of embeds and cast modality features to the same dtype before scattering. - // modality_features = modality_features.to('float32'); - - // Equivalent to performing a masked_scatter - let img = 0; + if (inputs_embeds.dims.at(-1) !== modality_features.dims.at(-1)) { + throw new Error('Modality features and text embeddings must have the same hidden size.'); + } + // ONNX Runtime may return Uint16-backed half tensors even in runtimes with + // Float16Array. Match numeric values as well as the declared tensor dtype. + const same_storage = inputs_embeds.data instanceof Uint16Array === modality_features.data instanceof Uint16Array; + const converted = + modality_features.type === inputs_embeds.type && same_storage + ? modality_features + : modality_features.to('float32'); + const to_half = + inputs_embeds.type === 'float16' && inputs_embeds.data instanceof Uint16Array && converted.type !== 'float16'; + const hidden_size = inputs_embeds.dims.at(-1); + const sequence_length = inputs_embeds.dims[1]; + const target = inputs_embeds.data; + const source = converted.data; + + // Scatter directly into storage: Tensor row views may change the backing + // representation of float16 on platforms with native Float16Array support. + let feature = 0; for (let i = 0; i < token_positions.length; ++i) { - const tokens = token_positions[i]; - const embeds = inputs_embeds[i]; - for (let j = 0; j < tokens.length; ++j) { - embeds[tokens[j]].data.set(modality_features[img++].data); + for (const token of token_positions[i]) { + const values = source.subarray(feature * hidden_size, (feature + 1) * hidden_size); + ++feature; + target.set( + to_half ? Uint16Array.from(values, number_to_float16) : values, + (i * sequence_length + token) * hidden_size, + ); } } + if (converted !== modality_features) converted.dispose(); return { inputs_embeds, attention_mask }; } diff --git a/packages/transformers/src/models/qwen2_vl/modeling_qwen2_vl.js b/packages/transformers/src/models/qwen2_vl/modeling_qwen2_vl.js index ea9f415a9..66d054238 100644 --- a/packages/transformers/src/models/qwen2_vl/modeling_qwen2_vl.js +++ b/packages/transformers/src/models/qwen2_vl/modeling_qwen2_vl.js @@ -5,7 +5,7 @@ import { setNumLogitsToKeep, } from '../modeling_utils.js'; import { sessionRun } from '../session.js'; -import { stack, Tensor, ones_like, zeros } from '../../utils/tensor.js'; +import { stack, Tensor, ones_like, zeros, cat } from '../../utils/tensor.js'; import { max } from '../../utils/maths.js'; export class Qwen2VLPreTrainedModel extends PreTrainedModel { @@ -22,6 +22,15 @@ export class Qwen2VLPreTrainedModel extends PreTrainedModel { ]; } export class Qwen2VLForConditionalGeneration extends Qwen2VLPreTrainedModel { + _multimodal_generation_config() { + if (!['qwen2_vl', 'qwen2_vl_text'].includes(this.config.model_type)) return null; + return { + modality_input_names: ['pixel_values'], + modality_output_name: 'image_features', + batch_axes: { position_ids: 1, rope_deltas: 0 }, + }; + } + // NOTE: This is used as the base class for all Qwen VL models and their CausalLM variants. // CausalLM variants (e.g., Qwen2VLForCausalLM) extend this class but load only // embed_tokens + decoder_model_merged (no vision_encoder) via MultimodalLanguageModelOnly type. @@ -272,6 +281,32 @@ export class Qwen2VLForConditionalGeneration extends Qwen2VLPreTrainedModel { } async encode_image({ pixel_values, image_grid_thw }) { + // Qwen2VL exports trace a single image grid. Encode each original image + // once, before beam expansion, preserving flattened patch order. + if (['qwen2_vl', 'qwen2_vl_text'].includes(this.config.model_type) && image_grid_thw.dims[0] > 1) { + const features = []; + let offset = 0; + try { + for (let i = 0; i < image_grid_thw.dims[0]; ++i) { + const grid = image_grid_thw.slice([i, i + 1]); + const length = Number(grid.data[0] * grid.data[1] * grid.data[2]); + features.push( + ( + await sessionRun(this.sessions['vision_encoder'], { + pixel_values: pixel_values.slice([offset, offset + length]), + [this.image_grid_thw_name]: grid, + }) + ).image_features, + ); + offset += length; + } + if (offset !== pixel_values.dims[0]) + throw new Error('Image grids do not match the number of pixel patches.'); + return cat(features, 0); + } finally { + for (const feature of features) feature.dispose(); + } + } const features = ( await sessionRun(this.sessions['vision_encoder'], { pixel_values, @@ -292,6 +327,46 @@ export class Qwen2VLForConditionalGeneration extends Qwen2VLPreTrainedModel { prepare_inputs_for_generation(input_ids, model_inputs, generation_config) { setNumLogitsToKeep(this, model_inputs, 1n); + // Full-history image grids and new-query pixel patches have different + // indexing contracts. Do not silently scatter old image features into a + // new image chunk; this continuation needs explicit prepared embeddings. + if (this._multimodal_generation_config() && model_inputs.pixel_values && !model_inputs.inputs_embeds) { + const pastLength = model_inputs.past_key_values?.get_seq_length() ?? 0; + // @ts-ignore Model-specific configuration field. + const imageToken = this.config.image_token_id; + if ( + pastLength >= model_inputs.input_ids.dims[1] && + model_inputs.input_ids.data.some((id) => id == imageToken) + ) { + throw new Error( + 'Qwen2VL cached raw-image prompts require full input_ids history; supply prepared inputs_embeds for query-only image chunks.', + ); + } + if (pastLength && pastLength < model_inputs.input_ids.dims[1]) { + for (const row of model_inputs.input_ids.tolist()) { + if ( + row.slice(0, pastLength).some((id) => id == imageToken) && + row.slice(pastLength).some((id) => id == imageToken) + ) { + throw new Error( + 'Qwen2VL cannot append raw images after an image-containing cache; supply prepared inputs_embeds and matching position_ids/rope_deltas.', + ); + } + } + } + } + + // Caller-supplied prefill positions still need the image-dependent offset + // on subsequent decode steps, after raw image grids have been cleared. + if (model_inputs.position_ids && !model_inputs.rope_deltas && model_inputs.image_grid_thw) { + [, model_inputs.rope_deltas] = this.get_rope_index( + model_inputs.input_ids, + model_inputs.image_grid_thw, + null, + model_inputs.attention_mask, + ); + } + // Overwritten -- in specific circumstances we don't want to forward image inputs to the model if (!model_inputs.attention_mask || model_inputs.position_ids) { return model_inputs; @@ -311,8 +386,8 @@ export class Qwen2VLForConditionalGeneration extends Qwen2VLPreTrainedModel { model_inputs.attention_mask, ); } else { - model_inputs.pixel_values = null; - // model_inputs.pixel_values_videos = null; + // Keep supplied image data until the unprocessed query is sliced. + // Shared preparation encodes it only if that query has image tokens. const past_length = model_inputs.past_key_values.get_seq_length(); diff --git a/packages/transformers/src/models/ultravox/modeling_ultravox.js b/packages/transformers/src/models/ultravox/modeling_ultravox.js index 7752237a3..d14d160a3 100644 --- a/packages/transformers/src/models/ultravox/modeling_ultravox.js +++ b/packages/transformers/src/models/ultravox/modeling_ultravox.js @@ -5,13 +5,34 @@ export class UltravoxPreTrainedModel extends PreTrainedModel { } export class UltravoxModel extends UltravoxPreTrainedModel { + _multimodal_generation_config() { + if (this.config.model_type !== 'ultravox') return null; + return { + modality_input_names: ['audio_values'], + modality_output_name: 'audio_features', + encode_function: this.encode_audio.bind(this), + merge_function: this._merge_input_ids_with_audio_features.bind(this), + batch_axes: { position_ids: 0 }, + }; + } + _merge_input_ids_with_audio_features(kwargs) { const audio_hidden_size = kwargs.audio_features.dims.at(-1); const reshaped_audio_features = kwargs.audio_features.view(-1, audio_hidden_size); + // This export has no per-example audio frame lengths. A padded ragged + // batch cannot be scattered using only a total feature count. + // @ts-ignore + const audio_token_id = this.config.ignore_index ?? this.config.audio_token_id ?? this.config.audio_token_index; + const counts = kwargs.input_ids.tolist().map((ids) => ids.filter((id) => id == audio_token_id).length); + const features_per_sample = reshaped_audio_features.dims[0] / counts.length; + if (counts.some((count) => count !== features_per_sample)) { + throw new Error( + 'Ultravox requires equal audio feature counts per sample; variable-length padded audio is unsupported.', + ); + } return default_merge_input_ids_with_audio_features({ - // @ts-ignore - audio_token_id: this.config.ignore_index ?? this.config.audio_token_id ?? this.config.audio_token_index, + audio_token_id, ...kwargs, audio_features: reshaped_audio_features, }); 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/helpers/multimodal.js b/packages/transformers/tests/helpers/multimodal.js new file mode 100644 index 000000000..d0844418c --- /dev/null +++ b/packages/transformers/tests/helpers/multimodal.js @@ -0,0 +1,73 @@ +import { jest } from "@jest/globals"; +import { RawImage, Tensor, cat } from "../../src/transformers.js"; + +export const revisions = { + llava: "a61a79a541cec4898722bdfb5b016984c29fb061", + idefics3: "5c0505e5c04d9e87b7cdb599076e6cf0cedf707d", + qwen2_vl: "2e2ed20b74bd5157aafd082b00e87fe25b2231a6", +}; + +export function collate(samples) { + const length = Math.max(...samples.map((x) => x.input_ids.dims[1])); + const result = {}; + for (const key of ["input_ids", "attention_mask"]) { + result[key] = new Tensor( + "int64", + samples.flatMap((x) => [...new Array(length - x[key].dims[1]).fill(0n), ...x[key].data]), + [samples.length, length], + ); + } + for (const key of ["pixel_values", "pixel_attention_mask", "image_grid_thw", "audio_values"]) { + if (!samples[0][key]) continue; + let tensors = samples.map((x) => x[key]); + if (key === "pixel_attention_mask" || (key === "pixel_values" && tensors[0].dims.length === 5)) { + const n = Math.max(...tensors.map((t) => t.dims[1])); + tensors = tensors.map((t) => { + if (t.dims[1] === n) return t; + const dims = [...t.dims]; + dims[1] = n - t.dims[1]; + return cat([t, new Tensor(t.type, new t.data.constructor(dims.reduce((a, b) => a * b, 1)), dims)], 1); + }); + } + result[key] = cat(tensors, 0); + } + return result; +} + +// Exercise generation with valid preprocessed image groups independently of +// the Qwen multi-image processor fix tracked in upstream PR #1812. +async function processImages(processor, family, text, images) { + if (family === "llava") return processor(images, text); + if (family !== "qwen2_vl") return processor(text, images, { do_image_splitting: false }); + const imageProcessor = processor.image_processor; + const processed = await Promise.all(images.map((image) => imageProcessor(image))); + const imageInputs = { + pixel_values: cat( + processed.map((x) => x.pixel_values), + 0, + ), + image_grid_thw: cat( + processed.map((x) => x.image_grid_thw), + 0, + ), + }; + const imageInputsStub = Object.assign(async () => imageInputs, { config: imageProcessor.config }); + const imageProcessorGetter = jest.spyOn(processor, "image_processor", "get").mockReturnValue(imageInputsStub); + try { + // Retain the real processor's token expansion using the supplied grids. + return await processor(text, images); + } finally { + imageProcessorGetter.mockRestore(); + } +} + +export async function makeSamples(processor, family) { + const image = (value) => new RawImage(new Uint8ClampedArray(56 * 56 * 3).fill(value), 56, 56, 3); + const samples = []; + for (let i = 0; i < 2; ++i) { + const images = i ? [image(255), image(127)] : [image(0)]; + const text = family === "llava" ? `${"".repeat(images.length)}${i ? "Describe this image in detail." : "Hi"}` : processor.apply_chat_template([{ role: "user", content: [...images.map(() => ({ type: "image" })), { type: "text", text: i ? "Describe this image in detail." : "Hi" }] }], { add_generation_prompt: true }); + samples.push(await processImages(processor, family, text, images)); + } + return samples; +} diff --git a/packages/transformers/tests/multimodal_integration.test.js b/packages/transformers/tests/multimodal_integration.test.js new file mode 100644 index 000000000..e7b4d434a --- /dev/null +++ b/packages/transformers/tests/multimodal_integration.test.js @@ -0,0 +1,201 @@ +import { existsSync } from "node:fs"; +import path from "node:path"; +import { env } from "../src/env.js"; +import { makeSamples, collate, revisions } from "./helpers/multimodal.js"; +import { jest } from "@jest/globals"; +import { LlavaForConditionalGeneration, LlavaProcessor, Idefics3ForConditionalGeneration, Idefics3Processor, Qwen2VLForConditionalGeneration, Qwen2VLProcessor, RawImage, Tensor, cat, random } from "../src/transformers.js"; +import { init } from "./init.js"; +init(); +const models = [ + ["llava", LlavaForConditionalGeneration, LlavaProcessor, "Xenova/tiny-random-LlavaForConditionalGeneration"], + ["idefics3", Idefics3ForConditionalGeneration, Idefics3Processor, "hf-internal-testing/tiny-random-Idefics3ForConditionalGeneration"], + ["qwen2_vl", Qwen2VLForConditionalGeneration, Qwen2VLProcessor, "hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration"], +]; +const image = (value) => new RawImage(new Uint8ClampedArray(56 * 56 * 3).fill(value), 56, 56, 3); +// Collate independently processed examples to test actual left padding, independent +// of processor batching support. Image features remain in original sample order. +function batchInputs(samples, family) { + const length = Math.max(...samples.map((x) => x.input_ids.dims[1])); + const output = {}; + for (const key of ["input_ids", "attention_mask"]) { + output[key] = new Tensor( + "int64", + samples.flatMap((x) => [...new Array(length - x[key].dims[1]).fill(0n), ...x[key].data]), + [samples.length, length], + ); + } + for (const key of ["pixel_values", "pixel_attention_mask", "image_grid_thw"]) { + if (samples[0][key]) + output[key] = cat( + samples.map((x) => x[key]), + 0, + ); + } + return output; +} +for (const [family, Model, Processor, model_id] of models) { + describe(`Real multimodal generation: ${family}`, () => { + let model, processor, samples, batch; + beforeAll(async () => { + const cached = path.join(env.cacheDir, model_id); + const source = existsSync(path.join(cached, "config.json")) ? cached : model_id; + const options = { revision: revisions[family], dtype: "fp32", session_options: { intraOpNumThreads: 1 } }; + model = await Model.from_pretrained(source, options); + processor = await Processor.from_pretrained(source, options); + samples = []; + for (let i = 0; i < 2; ++i) { + const text = family === "llava" ? `${i ? "Describe this image in detail." : "Hi"}` : processor.apply_chat_template([{ role: "user", content: [{ type: "image" }, { type: "text", text: i ? "Describe this image in detail." : "Hi" }] }], { add_generation_prompt: true }); + samples.push(family === "llava" ? await processor(image(i * 255), text) : await processor(text, image(i * 255), { do_image_splitting: false })); + } + batch = batchInputs(samples, family); + }, 120000); + it("matches cached continuation and caller-supplied embeddings", async () => { + const sample = samples[0]; + const options = { do_sample: false, eos_token_id: null, max_new_tokens: 2 }; + const prefill = await model.generate({ ...sample, ...options, return_dict_in_generate: true }); + const attention_mask = cat([sample.attention_mask, new Tensor("int64", [1n, 1n], [1, 2])], 1); + const continuation = { ...sample, input_ids: prefill.sequences, attention_mask, ...options, num_beams: 2 }; + const continuationEncoder = jest.spyOn(model, "encode_image"); + let cached; + try { + cached = await model.generate({ ...continuation, past_key_values: prefill.past_key_values }); + expect(continuationEncoder).not.toHaveBeenCalled(); + } finally { + continuationEncoder.mockRestore(); + } + const uncached = await model.generate(continuation); + expect(cached.tolist()).toEqual(uncached.tolist()); + await prefill.past_key_values.dispose(); + + const inputs_embeds = await model.encode_text(sample); + const image_features = await model.encode_image(sample); + const merged = model._merge_input_ids_with_image_features({ ...sample, inputs_embeds, image_features }); + image_features.dispose(); + const expected = await model.generate({ ...sample, ...options, num_beams: 2 }); + const encoder = jest.spyOn(model, "encode_image"); + try { + const actual = await model.generate({ ...sample, ...merged, ...options, num_beams: 2 }); + expect(actual.tolist()).toEqual(expected.tolist()); + expect(encoder).not.toHaveBeenCalled(); + expect(inputs_embeds.data.length).toBeGreaterThan(0); + } finally { + encoder.mockRestore(); + inputs_embeds.dispose(); + } + }, 120000); + it(`merges a new image prompt following a supplied text-prefix cache (${family === "idefics3" ? "greedy: export GQA limits cached multi-token batches" : "two beams"})`, async () => { + const prefix = await model.generate({ input_ids: new Tensor("int64", [1n, 2n], [1, 2]), attention_mask: new Tensor("int64", [1n, 1n], [1, 2]), max_new_tokens: 1, do_sample: false, eos_token_id: null, return_dict_in_generate: true }); + try { + const input_ids = cat([prefix.sequences, samples[0].input_ids], 1); + const attention_mask = cat([new Tensor("int64", [1n, 1n, 1n], [1, 3]), samples[0].attention_mask], 1); + // This tiny Idefics3 export requires batch_size=1 for multi-token cached prefill. + const options = { ...samples[0], input_ids, attention_mask, num_beams: family === "idefics3" ? 1 : 2, max_new_tokens: 2, do_sample: false, eos_token_id: null }; + const encoder = jest.spyOn(model, "encode_image"); + let cached; + try { + cached = await model.generate({ ...options, past_key_values: prefix.past_key_values }); + expect(encoder).toHaveBeenCalledTimes(1); + expect(encoder.mock.calls[0][0].pixel_values).toBe(samples[0].pixel_values); + // Tiny random models can emit identical tokens even when vision is + // silently skipped. Inspect the actual merged decoder embeddings. + const embeddings = []; + const originalForward = model.forward.bind(model); + const forward = jest.spyOn(model, "forward").mockImplementation(async function (inputs) { + if (inputs.inputs_embeds) embeddings.push(Array.from(inputs.inputs_embeds.data)); + return originalForward(inputs); + }); + try { + encoder.mockClear(); + for (const pixel_values of [samples[0].pixel_values, samples[1].pixel_values]) { + await model.generate({ ...options, pixel_values, past_key_values: prefix.past_key_values }); + } + expect(encoder).toHaveBeenCalledTimes(2); + expect(embeddings).toHaveLength(2); + expect(embeddings[0]).not.toEqual(embeddings[1]); + } finally { + forward.mockRestore(); + } + } finally { + encoder.mockRestore(); + } + const reference = await model.generate(options); + expect(cached.tolist()).toEqual(reference.tolist()); + } finally { + await prefix.past_key_values.dispose(); + } + }, 120000); + if (family === "qwen2_vl") + it("rejects raw new images after an image-containing cache before encoding", async () => { + const prefix = await model.generate({ ...samples[0], max_new_tokens: 1, eos_token_id: null, return_dict_in_generate: true }); + const encode = jest.spyOn(model, "encode_image"); + try { + const input_ids = cat([prefix.sequences, samples[1].input_ids], 1); + const attention_mask = new Tensor("int64", new BigInt64Array(input_ids.size).fill(1n), input_ids.dims); + // Full-history grids are required for rotary positions, but raw features + // cannot safely be selected from old and new image groups yet. + await expect( + model.generate({ + ...samples[1], + input_ids, + attention_mask, + image_grid_thw: cat( + samples.map((sample) => sample.image_grid_thw), + 0, + ), + past_key_values: prefix.past_key_values, + num_beams: 2, + max_new_tokens: 2, + }), + ).rejects.toThrow("cannot append raw images after an image-containing cache"); + await expect(model.generate({ ...samples[0], past_key_values: prefix.past_key_values, num_beams: 2, max_new_tokens: 2 })).rejects.toThrow("cached raw-image prompts require full input_ids history"); + expect(encode).not.toHaveBeenCalled(); + } finally { + encode.mockRestore(); + await prefix.past_key_values.dispose(); + } + }, 120000); + it("preserves unequal image groups with two beams", async () => { + const ragged = await makeSamples(processor, family); + const batch = collate(ragged); + const options = { num_beams: 2, max_new_tokens: 2, do_sample: false, repetition_penalty: 2, eos_token_id: null }; + const result = await model.generate({ ...batch, ...options }); + const expected = []; + for (let i = 0; i < ragged.length; ++i) { + const single = await model.generate({ ...ragged[i], input_ids: batch.input_ids.slice([i, i + 1]), attention_mask: batch.attention_mask.slice([i, i + 1]), ...options }); + expected.push(...single.tolist().map((row) => row.slice(batch.input_ids.dims[1]))); + } + expect(result.tolist().map((row) => row.slice(batch.input_ids.dims[1]))).toEqual(expected); + }, 120000); + afterAll(async () => { + await model?.dispose(); + }, 10000); + it.each([1, 2, 4])( + "matches independent outputs with padding and %s beams", + async (num_beams) => { + const options = { do_sample: false, repetition_penalty: 2, num_beams, max_new_tokens: 3, eos_token_id: null, num_return_sequences: num_beams > 1 ? 2 : 1 }; + const encoder = jest.spyOn(model, "encode_image"); + const result = await model.generate({ ...batch, ...options }); + expect(encoder).toHaveBeenCalledTimes(1); + encoder.mockRestore(); + const expected = []; + for (let i = 0; i < samples.length; ++i) { + const sample = { ...samples[i], input_ids: batch.input_ids.slice([i, i + 1]), attention_mask: batch.attention_mask.slice([i, i + 1]) }; + const single = await model.generate({ ...sample, ...options }); + expected.push(...single.tolist().map((row) => row.slice(sample.input_ids.dims[1]))); + } + expect(result.tolist().map((row) => row.slice(batch.input_ids.dims[1]))).toEqual(expected); + }, + 120000, + ); + it("runs diverse search and reproducible seeded beam sampling", async () => { + const diverse = await model.generate({ ...samples[0], do_sample: false, max_new_tokens: 2, num_beams: 4, num_beam_groups: 2, diversity_penalty: 1, num_return_sequences: 2 }); + expect(diverse.dims).toEqual([2, samples[0].input_ids.dims[1] + 2]); + const options = { ...batch, max_new_tokens: 2, num_beams: 2, do_sample: true, top_k: 10 }; + random.seed(123); + const a = await model.generate(options); + random.seed(123); + const b = await model.generate(options); + expect(a.tolist()).toEqual(b.tolist()); + }, 120000); + }); +} diff --git a/packages/transformers/tests/utils/beam_ownership.test.js b/packages/transformers/tests/utils/beam_ownership.test.js new file mode 100644 index 000000000..789d83025 --- /dev/null +++ b/packages/transformers/tests/utils/beam_ownership.test.js @@ -0,0 +1,176 @@ +import { env } from "../../src/env.js"; +import { Tensor, index_select_async } from "../../src/utils/tensor.js"; +import { getTensorConstructor } from "../../src/backends/onnx.js"; +import { PreTrainedModel } from "../../src/models/modeling_utils.js"; +import { GenerationConfig } from "../../src/generation/configuration_utils.js"; +import { DynamicCache } from "../../src/cache_utils.js"; + +// Mock only the GPU allocation boundary; execute the real generation/cache code. +describe("Beam resource ownership", () => { + let allocated, originalDevice, originalUsage; + beforeEach(() => { + allocated = []; + originalDevice = env.backends.onnx.webgpu.device; + originalUsage = globalThis.GPUBufferUsage; + globalThis.GPUBufferUsage = { COPY_SRC: 1, COPY_DST: 2, STORAGE: 4, MAP_READ: 8 }; + env.backends.onnx.webgpu.device = { + limits: { maxBufferSize: 1e9 }, + createBuffer(options) { + const buffer = { + ...options, + destroyed: false, + destroy() { + this.destroyed = true; + }, + }; + allocated.push(buffer); + return buffer; + }, + createCommandEncoder() { + return { + copyBufferToBuffer() {}, + finish() { + return {}; + }, + }; + }, + queue: { submit() {} }, + }; + }); + afterEach(() => { + env.backends.onnx.webgpu.device = originalDevice; + if (originalUsage === undefined) delete globalThis.GPUBufferUsage; + else globalThis.GPUBufferUsage = originalUsage; + }); + + const gpu = (dims, options = {}, usage = 1) => new Tensor(getTensorConstructor().fromGpuBuffer({ usage }, { dataType: "float32", dims, ...options })); + const modelWith = (extra = {}) => + Object.assign(Object.create(PreTrainedModel.prototype), { + config: { is_encoder_decoder: false }, + _validate_model_class() {}, + _prepare_generation_config(config, kwargs) { + return new GenerationConfig(kwargs); + }, + _prepare_model_inputs() { + const ids = new Tensor("int64", [1n], [1, 1]); + return { inputs_tensor: ids, model_input_name: "input_ids", model_inputs: { input_ids: ids, attention_mask: new Tensor("int64", [1n], [1, 1]), ...extra } }; + }, + prepare_inputs_for_generation(ids, inputs) { + return inputs; + }, + async forward() { + return { logits: new Tensor("float32", [0, 1, 2, 3, 0, 1, 2, 3], [2, 1, 4]) }; + }, + }); + + it.each([false, true])("releases expanded inputs on forward failure=%s without consuming caller input", async (fail) => { + const positions = gpu([1, 1], { dataType: "int64" }); + const model = modelWith({ position_ids: positions }); + if (fail) + model.forward = async () => { + throw new Error("forward failed"); + }; + const result = model.generate({ num_beams: 2, max_new_tokens: 1, eos_token_id: null }); + if (fail) await expect(result).rejects.toThrow("forward failed"); + else expect((await result).tolist()).toEqual([[1n, 3n]]); + expect(allocated.length).toBe(1); + expect(allocated.every((buffer) => buffer.destroyed)).toBe(true); + expect(positions.location).toBe("gpu-buffer"); + positions.dispose(); + }); + + it("rolls back partial cache copies without consuming source tensors", async () => { + const first = gpu([2, 4]); + const second = gpu( + [2, 4], + { + download: async () => { + throw new Error("readback failed"); + }, + }, + 0, + ); + const cache = new DynamicCache({ first, second }); + await expect(PreTrainedModel.prototype._reorder_cache.call({ _get_cache_indices: (_key, indices) => indices }, cache, [1, 0])).rejects.toThrow("readback failed"); + expect(allocated.length).toBe(1); + expect(allocated.every((buffer) => buffer.destroyed)).toBe(true); + expect(first.location).toBe("gpu-buffer"); + expect(second.location).toBe("gpu-buffer"); + await cache.dispose(); + }); + + it.each(["dispose", "update"])("releases downloaded GPU cache resources through %s", async (action) => { + let destroyed = false; + const odd = gpu([1, 3], { + dataType: "float16", + download: async () => new Uint16Array(3), + dispose: () => { + destroyed = true; + }, + }); + const cache = new DynamicCache({ odd }); + await index_select_async(odd, [0, 0]); + expect(odd.location).toBe("cpu"); + expect(destroyed).toBe(false); + if (action === "dispose") await cache.dispose(); + else cache.update({ odd: new Tensor("float16", new Uint16Array(3), [1, 3]) }); + expect(destroyed).toBe(true); + }); + + it("releases previously downloaded cache sources after successful reordering", async () => { + let destroyed = false; + const source = gpu([1, 4], { + download: async () => new Float32Array([1, 2, 3, 4]), + dispose: () => { + destroyed = true; + }, + }); + await source.ort_tensor.getData(false); + const reordered = await PreTrainedModel.prototype._reorder_cache.call({ _get_cache_indices: (_key, indices) => indices }, new DynamicCache({ source }), [0, 0]); + expect(Array.from(reordered.source.data)).toEqual([1, 2, 3, 4, 1, 2, 3, 4]); + expect(destroyed).toBe(true); + await reordered.dispose(); + }); + + it("releases the active cache when a later forward fails and preserves a supplied cache", async () => { + const source = gpu([1, 1, 1, 4]); + const caller = new DynamicCache({ "past_key_values.0.key": source }); + const model = modelWith({ past_key_values: caller }); + let calls = 0; + let outputDestroyed = false; + model.forward = async () => { + if (++calls === 2) throw new Error("second forward failed"); + return { + logits: new Tensor("float32", [0, 1, 2, 3, 0, 1, 2, 3], [2, 1, 4]), + "present.0.key": gpu([2, 1, 1, 4], { + dispose: () => { + outputDestroyed = true; + }, + }), + }; + }; + await expect(model.generate({ num_beams: 2, max_new_tokens: 3, eos_token_id: null })).rejects.toThrow("second forward failed"); + expect(calls).toBe(2); + expect(allocated.length).toBe(2); + expect(allocated.every((buffer) => buffer.destroyed)).toBe(true); + expect(outputDestroyed).toBe(true); + expect(source.location).toBe("gpu-buffer"); + await caller.dispose(); + }); + + it("rejects decoder-only multimodal beams before inference", async () => { + const model = modelWith({ pixel_values: new Tensor("float32", [1], [1, 1]) }); + model.forward = async () => { + throw new Error("must not run"); + }; + await expect(model.generate({ num_beams: 2, max_new_tokens: 1 })).rejects.toThrow("decoder-only multimodal inputs"); + }); + + it("rejects beam attentions used for token timestamps before inference", async () => { + const model = modelWith(); + model.forward = async () => { + throw new Error("must not run"); + }; + await expect(model.generate({ num_beams: 2, output_attentions: true, max_new_tokens: 1 })).rejects.toThrow("output_attentions or token timestamps"); + }); +}); diff --git a/packages/transformers/tests/utils/beam_search.test.js b/packages/transformers/tests/utils/beam_search.test.js 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/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/multimodal_generation.test.js b/packages/transformers/tests/utils/multimodal_generation.test.js new file mode 100644 index 000000000..ca175b993 --- /dev/null +++ b/packages/transformers/tests/utils/multimodal_generation.test.js @@ -0,0 +1,198 @@ +import { UltravoxModel } from "../../src/models/ultravox/modeling_ultravox.js"; +import { SmolVLMForConditionalGeneration } from "../../src/models/smolvlm/modeling_smolvlm.js"; +import { jest } from "@jest/globals"; +import { Tensor } from "../../src/utils/tensor.js"; +import { GenerationConfig } from "../../src/generation/configuration_utils.js"; +import { LlavaForConditionalGeneration } from "../../src/models/llava/modeling_llava.js"; +import { default_merge_input_ids_with_image_features } from "../../src/models/modeling_utils.js"; +import { DynamicCache } from "../../src/cache_utils.js"; + +const tensor = (type, data, dims) => new Tensor(type, data, dims); +const ids = () => tensor("int64", [0n, 9n, 1n, 9n, 9n, 2n], [2, 3]); +function synthetic(extra = {}) { + const forwards = []; + const allocated = []; + const own = (t) => { + t.dispose = jest.fn(t.dispose.bind(t)); + allocated.push(t); + return t; + }; + const model = Object.assign(Object.create(LlavaForConditionalGeneration.prototype), { + config: { model_type: "llava", image_token_index: 9, is_encoder_decoder: false }, + _validate_model_class() {}, + _prepare_generation_config: (_config, kwargs) => new GenerationConfig(kwargs), + _prepare_model_inputs() { + const input_ids = ids(); + return { model_input_name: "input_ids", inputs_tensor: input_ids, model_inputs: { input_ids, attention_mask: tensor("int64", [0n, 1n, 1n, 1n, 1n, 1n], [2, 3]), pixel_values: tensor("float32", [2, 4, 6], [3, 1]), ...extra } }; + }, + prepare_inputs_for_generation(_ids, inputs) { + return inputs; + }, + encode_text: jest.fn(async ({ input_ids }) => own(tensor("float32", new Float32Array(input_ids.size * 2), [...input_ids.dims, 2]))), + encode_image: jest.fn(async () => own(tensor("float16", new Uint16Array([0x4000, 0x4200, 0x4400, 0x4500, 0x4600, 0x4700]), [3, 2]))), + async forward(inputs) { + forwards.push({ embeds: inputs.inputs_embeds?.tolist(), mask: inputs.attention_mask.tolist(), positions: inputs.position_ids?.tolist(), deltas: inputs.rope_deltas?.tolist(), ids: inputs.input_ids.tolist() }); + const batch = inputs.input_ids.dims[0]; + const logits = tensor( + "float32", + Array.from({ length: batch * 10 }, (_, i) => i % 10), + [batch, 1, 10], + ); + const length = inputs.attention_mask.dims[1]; + return { logits, "present.0.key": tensor("float32", new Float32Array(batch * length), [batch, 1, length, 1]), "present.0.value": tensor("float32", new Float32Array(batch * length), [batch, 1, length, 1]) }; + }, + }); + return { model, forwards, allocated }; +} + +describe("Prepared multimodal generation", () => { + it("shares preparation with audio without treating raw audio as beam rows", async () => { + const { model, forwards } = synthetic({ pixel_values: null, audio_values: tensor("float32", [2, 4, 6], [3, 1]) }); + Object.setPrototypeOf(model, UltravoxModel.prototype); + model.config = { model_type: "ultravox", audio_token_id: 9, is_encoder_decoder: false }; + model.encode_audio = jest.fn(async () => tensor("float32", [2, 3, 4, 5], [2, 1, 2])); + const prepare = model._prepare_model_inputs.bind(model); + model._prepare_model_inputs = () => { + const result = prepare(); + result.model_inputs.input_ids.data[4] = 0n; + return result; + }; + await model.generate({ num_beams: 4, max_new_tokens: 2 }); + expect(model.encode_audio).toHaveBeenCalledTimes(1); + expect(forwards[0].embeds[4][0]).toEqual([4, 5]); + expect(forwards[1].embeds).toBeUndefined(); + }); + it("rejects ragged raw audio before scattering features into the wrong sample", async () => { + const { model } = synthetic({ pixel_values: null, audio_values: tensor("float32", [2, 4, 6], [3, 1]) }); + Object.setPrototypeOf(model, UltravoxModel.prototype); + model.config = { model_type: "ultravox", audio_token_id: 9, is_encoder_decoder: false }; + model.encode_audio = model.encode_image; + await expect(model.generate({ num_beams: 2, max_new_tokens: 1 })).rejects.toThrow("variable-length padded audio is unsupported"); + }); + it.each(["pixel_values_videos", "video_grid_thw"])("guards unsupported %s before encoder allocation", async (key) => { + const { model } = synthetic(); + await expect(model.generate({ num_beams: 2, max_new_tokens: 1, [key]: tensor("int64", [1n], [1, 1]) })).rejects.toThrow("decoder-only multimodal inputs"); + expect(model.encode_text).not.toHaveBeenCalled(); + expect(model.encode_image).not.toHaveBeenCalled(); + }); + it("opts SmolVLM images in explicitly", () => { + const model = Object.assign(Object.create(SmolVLMForConditionalGeneration.prototype), { config: { model_type: "smolvlm" } }); + expect(model._multimodal_generation_config().modality_input_names).toEqual(["pixel_values"]); + model.config.model_type = "custom"; + expect(model._multimodal_generation_config()).toBeNull(); + }); + it("keeps original token history lengths separate from an expanded embedding prefix", async () => { + const { model, forwards } = synthetic(); + model._merge_input_ids_with_image_features = () => ({ + inputs_embeds: tensor("float32", new Float32Array(20), [2, 5, 2]), + attention_mask: tensor("int64", [0n, 1n, 1n, 1n, 1n, 1n, 1n, 1n, 1n, 1n], [2, 5]), + }); + const result = await model.generate({ num_beams: 2, max_new_tokens: 2 }); + expect(result.dims).toEqual([2, 5]); + expect(forwards[0].embeds[0]).toHaveLength(5); + expect(forwards[1].mask[0]).toEqual([0n, 1n, 1n, 1n, 1n, 1n]); + }); + it("releases prepared tensors over 25 consecutive calls", async () => { + const { model, allocated } = synthetic(); + for (let i = 0; i < 25; ++i) await model.generate({ num_beams: 2, max_new_tokens: 2 }); + expect(allocated).toHaveLength(50); + expect(allocated.every((t) => t.dispose.mock.calls.length === 1)).toBe(true); + }); + it.each([1, 2, 4])("encodes a ragged padded batch once, consumes prefill once (%s beams)", async (num_beams) => { + const { model, forwards, allocated } = synthetic(); + const output = await model.generate({ num_beams, max_new_tokens: 3, eos_token_id: null }); + expect(output.dims).toEqual([2, 6]); + expect(model.encode_image).toHaveBeenCalledTimes(1); + expect(model.encode_text).toHaveBeenCalledTimes(1); + expect(forwards[0].embeds).toEqual([ + ...Array.from({ length: num_beams }, () => [ + [0, 0], + [2, 3], + [0, 0], + ]), + ...Array.from({ length: num_beams }, () => [ + [4, 5], + [6, 7], + [0, 0], + ]), + ]); + expect(forwards[1].embeds).toBeUndefined(); + expect(forwards[2].embeds).toBeUndefined(); + expect(forwards[1].mask[0]).toEqual([0n, 1n, 1n, 1n]); + expect(allocated.every((t) => t.dispose.mock.calls.length === 1)).toBe(true); + }); + it("preserves caller embeddings, bypassing both encoders", async () => { + const inputs_embeds = tensor("float32", new Float32Array(12).fill(7), [2, 3, 2]); + const dispose = jest.spyOn(inputs_embeds, "dispose"); + const { model, forwards } = synthetic({ inputs_embeds }); + await model.generate({ num_beams: 2, max_new_tokens: 2 }); + expect(model.encode_text).not.toHaveBeenCalled(); + expect(model.encode_image).not.toHaveBeenCalled(); + expect(forwards[1].embeds).toBeUndefined(); + expect(dispose).not.toHaveBeenCalled(); + expect(inputs_embeds.data[0]).toBe(7); + }); + it.each(["encode", "merge", "forward"])("releases owned allocations after %s failure", async (stage) => { + const { model, allocated } = synthetic(); + if (stage === "encode") + model.encode_image = async () => { + throw new Error("injected"); + }; + if (stage === "merge") + model._merge_input_ids_with_image_features = () => { + throw new Error("injected"); + }; + if (stage === "forward") + model.forward = async () => { + throw new Error("injected"); + }; + await expect(model.generate({ num_beams: 2, max_new_tokens: 2 })).rejects.toThrow("injected"); + expect(allocated.length).toBeGreaterThan(0); + expect(allocated.every((t) => t.dispose.mock.calls.length === 1)).toBe(true); + }); + it("expands Qwen positions on axis 1 and rope deltas on axis 0", async () => { + const position_ids = tensor("int64", [1n, 2n, 3n, 11n, 12n, 13n, 21n, 22n, 23n, 31n, 32n, 33n, 41n, 42n, 43n, 51n, 52n, 53n], [3, 2, 3]); + const { model, forwards } = synthetic({ position_ids, rope_deltas: tensor("int64", [7n, 17n], [2, 1]) }); + const config = model._multimodal_generation_config(); + model._multimodal_generation_config = () => ({ ...config, batch_axes: { position_ids: 1, rope_deltas: 0 } }); + await model.generate({ num_beams: 2, max_new_tokens: 2 }); + expect(forwards[0].positions).toEqual(position_ids.tolist().map((rows) => rows.flatMap((row) => [row, row]))); + expect(forwards[0].deltas).toEqual([[7n], [7n], [17n], [17n]]); + expect(forwards[1].deltas).toEqual(forwards[0].deltas); + }); + it("does not re-encode modalities for supplied nonempty cache", async () => { + const cache = new DynamicCache({ "past_key_values.0.key": tensor("float32", new Float32Array(12), [2, 1, 3, 2]) }); + const { model } = synthetic({ past_key_values: cache, input_ids: tensor("int64", [1n, 2n], [2, 1]) }); + await model.generate({ num_beams: 2, max_new_tokens: 1 }); + expect(model.encode_image).not.toHaveBeenCalled(); + expect(cache.get_seq_length()).toBe(3); + }); + it("merges newly supplied image placeholders after a cached text prefix", async () => { + const cache = new DynamicCache({ "past_key_values.0.key": tensor("float32", new Float32Array(12), [2, 1, 3, 2]) }); + const { model, forwards } = synthetic({ past_key_values: cache }); + await model.generate({ num_beams: 2, max_new_tokens: 1 }); + expect(model.encode_image).toHaveBeenCalledTimes(1); + expect(forwards[0].embeds[0][1]).toEqual([2, 3]); + expect(cache.get_seq_length()).toBe(3); + }); + it.each(["float32", "float16"])("handles ONNX Uint16-backed embeddings with %s features", (type) => { + const embeddings = tensor("float16", new Uint16Array(2), [1, 1, 2]); + // Native ONNX feeds/results may expose Uint16 storage on modern Node too. + embeddings.ort_tensor.cpuData = new Uint16Array(2); + const features = type === "float32" ? tensor(type, [1, -2], [1, 2]) : tensor(type, new Uint16Array([0x3c00, 0xc000]), [1, 2]); + default_merge_input_ids_with_image_features({ image_token_id: 9, input_ids: tensor("int64", [9n], [1, 1]), inputs_embeds: embeddings, image_features: features }); + expect(Array.from(embeddings.data)).toEqual([0x3c00, 0xc000]); + }); + it("handles Uint16-backed half features with native half embeddings", () => { + const embeddings = tensor("float16", new Uint16Array(2), [1, 1, 2]); + const features = tensor("float16", new Uint16Array(2), [1, 2]); + features.ort_tensor.cpuData = new Uint16Array([0x3c00, 0xc000]); + default_merge_input_ids_with_image_features({ image_token_id: 9, input_ids: tensor("int64", [9n], [1, 1]), inputs_embeds: embeddings, image_features: features }); + expect(Array.from(embeddings.to("float32").data)).toEqual([1, -2]); + }); + it("numerically converts float32 features into half embeddings", () => { + const embeddings = tensor("float16", new Uint16Array(6), [1, 1, 6]); + default_merge_input_ids_with_image_features({ image_token_id: 9, input_ids: tensor("int64", [9n], [1, 1]), inputs_embeds: embeddings, image_features: tensor("float32", [1, -2, 0.5, 65504, 2 ** -24, -0], [1, 6]) }); + expect(Array.from(new Uint16Array(embeddings.data.buffer))).toEqual([0x3c00, 0xc000, 0x3800, 0x7bff, 1, 0x8000]); + }); +});