Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
b6291bc
Add beam search support with BeamHypotheses and BeamSearchScorer classes
justsml Feb 20, 2026
c162b74
Add diverse beam search support
justsml Feb 20, 2026
507e681
Add beam sampling for beam search
justsml Feb 20, 2026
c827191
Refactor model input expansion for beam search to use index selection
justsml Feb 25, 2026
f42da6d
Handle past_key_values for beam search in PreTrainedModel to prevent …
justsml Feb 25, 2026
b0b86bd
Simplify past_key_values handling in PreTrainedModel for beam search
justsml Feb 25, 2026
2444143
Merge main and adapt beam search to DynamicCache
justsml Sep 17, 2026
df53a54
Merge remote-tracking branch 'origin/main' into dan/add-beam-support
justsml Oct 20, 2026
7c43a27
Fix beam hypothesis scoring, sampling, and cache expansion
justsml Oct 20, 2026
f8e1b7d
Add reproducible remote WebGPU beam validation and benchmarks
justsml Oct 20, 2026
bab43ff
Keep aligned beam cache row selection on WebGPU
justsml Oct 20, 2026
6605358
Select beam candidates with a bounded top-k heap
justsml Oct 20, 2026
8e3cd1e
Validate GPU buffer lifetimes and pad row outputs for ONNX Runtime
justsml Oct 20, 2026
58699fa
Track buffer lifetime on ONNX Runtime's active GPU device
justsml Oct 20, 2026
61825bc
Record verified WebGPU beam benchmarks and completed host cleanup
justsml Oct 20, 2026
b65dfaf
Fix beam resource ownership and reject unsupported generation combina…
justsml Oct 20, 2026
fe16763
Support prepared multimodal prefill in beam generation
justsml Oct 20, 2026
a2510f5
Preserve streaming embeddings and prepare new cached image chunks
justsml Oct 20, 2026
e880da7
Add reproducible multimodal hardware harness and validation evidence
justsml Oct 20, 2026
48ddfe2
Fix cached Qwen image prefill and strengthen multimodal evidence
justsml Oct 21, 2026
77a166f
Guard ambiguous Qwen image caches and verify per-call resource recovery
justsml Oct 21, 2026
b482611
Track runtime WebGPU allocations and add pinned speech validation
justsml Oct 21, 2026
b379aca
chore: remove standalone beam GPU benchmark artifacts
justsml Oct 21, 2026
b17b7ea
Scope multimodal beam support separately from processor fixes
justsml Oct 22, 2026
9b96127
Inject preprocessed Qwen fixtures through processor getter
justsml Oct 22, 2026
039a241
Merge commit 'b379acab1d75f3d0e334e7ca9130077855483b3d' into t3/multi…
justsml Oct 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/transformers/docs/source/_toctree.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
120 changes: 120 additions & 0 deletions packages/transformers/docs/source/guides/beam-search.md
Original file line number Diff line number Diff line change
@@ -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();
```
9 changes: 9 additions & 0 deletions packages/transformers/src/backends/onnx.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 6 additions & 7 deletions packages/transformers/src/cache_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
/**
Expand Down Expand Up @@ -51,31 +52,29 @@ 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<string, Tensor>} 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;
}
}

/**
* 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<void>} 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);
}
Expand Down
Loading