Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 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
1faccc6
Preserve beam ancestry for Whisper token timestamps
justsml Oct 20, 2026
8d2dd9f
Handle explicit Whisper prefixes and release beam step scratch
justsml Oct 20, 2026
fe3ce83
Fix Whisper alignment parity and bound fp16 conversion work
justsml Oct 20, 2026
e14b98d
Fix encoder preparation ownership on errors and expansion
justsml Oct 21, 2026
c26c810
Match Whisper alignment arithmetic and preserve seek padding
justsml Oct 21, 2026
b379aca
chore: remove standalone beam GPU benchmark artifacts
justsml Oct 21, 2026
4cf5f18
Align beam timestamps with the predicting-row correction in PR #1809
justsml Oct 22, 2026
898cba4
Merge commit 'b379aca' into t3/whisper-timestamped-attentions
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
114 changes: 114 additions & 0 deletions packages/transformers/docs/source/guides/beam-search.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Beam search

Set `num_beams` above 1 in `generate()` to keep several candidate continuations
for each input. Beam search works with encoder-decoder and decoder-only models.

```javascript
import { AutoModelForSeq2SeqLM, AutoTokenizer } from '@huggingface/transformers';

const model_id = 'Xenova/t5-small';
const tokenizer = await AutoTokenizer.from_pretrained(model_id);
const model = await AutoModelForSeq2SeqLM.from_pretrained(model_id);
const inputs = tokenizer('translate English to German: The house is wonderful.');

const sequences = await model.generate({
...inputs,
num_beams: 4,
num_return_sequences: 2,
max_new_tokens: 30,
length_penalty: 1.0,
early_stopping: true,
});
console.log(tokenizer.batch_decode(sequences, { skip_special_tokens: true }));
```

`num_return_sequences` must be at most `num_beams`. Batched results are ordered
by input, then by descending hypothesis score. Use left padding for batched
decoder-only inputs.

Completed hypotheses are ranked by cumulative token log probability divided by
generated length raised to `length_penalty`. Prompt tokens are excluded from
this length. Positive penalties favor longer continuations; negative penalties
favor shorter ones. `early_stopping: true` stops once enough candidates finish,
`false` uses a score heuristic, and `"never"` uses a bound on the best attainable
score up to `max_length` or `max_new_tokens`.

## Diverse beam search

Split beams into groups and penalize tokens selected by earlier groups:

```javascript
const sequences = await model.generate({
...inputs,
num_beams: 4,
num_beam_groups: 2,
diversity_penalty: 0.5,
max_new_tokens: 30,
});
```

`num_beams` must be divisible by `num_beam_groups`. Each group searches
independently, with the diversity penalty included in its scores.

## Beam sampling

Set `do_sample: true` to sample candidates from the joint beam/token
distribution. Candidate pairs are sampled without replacement, then ranked by
their cumulative scores. `top_k` limits candidates per beam, with enough tokens
retained to seed the active beams and handle EOS candidates; `temperature`
controls sampling sharpness.

```javascript
const sequences = await model.generate({
...inputs,
num_beams: 4,
do_sample: true,
top_k: 20,
temperature: 0.8,
max_new_tokens: 30,
});
```

## WebGPU

Load a model with `device: 'webgpu'` to run inference on WebGPU. Beam reordering
keeps aligned decoder-cache tensors on the GPU using buffer row copies. Candidate
ranking still runs in JavaScript. Tensors whose row sizes are not multiples of
four bytes use CPU row selection instead.

```javascript
const model = await AutoModelForSeq2SeqLM.from_pretrained(model_id, {
device: 'webgpu',
dtype: 'fp32',
});
```

## Restrictions

Beam search rejects streamers and classifier-free guidance (`guidance_scale > 1`).
Decoder-only multimodal inputs are not supported with beams.
Whisper token timestamps support short-form batches and multiple returned
hypotheses. Long-form seek requires one input and one returned sequence.
Timestamp alignment follows each hypothesis's beam ancestry and includes the
last prompt query, which predicts the first generated token. Normalization uses
the original prompt and generated attention rows before cropping all but the
final prompt row.

With `output_attentions: true`, attention tensors contain raw per-step beam rows;
`beam_indices` identifies the rows used for each selected hypothesis.
`sequence_lengths` excludes right padding. Internally retained attentions are
released after timestamp extraction unless explicitly requested by the caller.
Attention history grows with model size, beam count, and generated sequence length.
Diverse beam search cannot be combined with `do_sample: true`. Nucleus sampling
(`top_p`) is not implemented by the generation sampler.

With `return_dict_in_generate: true`, beam decoding returns the selected
`sequences` and `past_key_values: null`. The internal beam cache is released;
it does not correspond to the selected final sequences. A cache from an earlier
non-beam generation call can be supplied as input and is expanded across beams.

Release the model when finished:

```javascript
await model.dispose();
```
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