🎥 Make videos programmatically with React
Make whisper-webgpu WebGPU-only
Jonny Burgerc637e653843f
diff --git a/packages/convert/app/components/transcribe/App.tsx b/packages/convert/app/components/transcribe/App.tsxindex 3d1f9eaf43..842d7bd1f7 100644--- a/packages/convert/app/components/transcribe/App.tsx+++ b/packages/convert/app/components/transcribe/App.tsx@@ -33,7 +33,6 @@ const Transcribe: React.FC<{getAvailableModels().map(async ({name: modelName}) => {const cached = await isWhisperModelCached({model: modelName,- backend: 'webgpu',}).catch(() => false);return cached ? modelName : null;}),diff --git a/packages/convert/app/components/transcribe/transcribeAudio.tsx b/packages/convert/app/components/transcribe/transcribeAudio.tsxindex 567903cc81..93eebc2ca4 100644--- a/packages/convert/app/components/transcribe/transcribeAudio.tsx+++ b/packages/convert/app/components/transcribe/transcribeAudio.tsx@@ -44,7 +44,6 @@ export default function TranscribeAudio({});await loadWhisperModel({- backend: 'webgpu',model: selectedModel,onProgress: (progress) =>setState(() => ({@@ -58,7 +57,6 @@ export default function TranscribeAudio({}));const transcription = await transcribe({- backend: 'webgpu',channelWaveform: waveform,model: selectedModel,});diff --git a/packages/convert/test/transcribe-webgpu.test.tsx b/packages/convert/test/transcribe-webgpu.test.tsxindex 09dcfc018e..41f7a3b2e4 100644--- a/packages/convert/test/transcribe-webgpu.test.tsx+++ b/packages/convert/test/transcribe-webgpu.test.tsx@@ -4,7 +4,7 @@ import ModelSelector from '../app/components/transcribe/modelSelector';afterEach(() => cleanup());-test('offers WebGPU model downloads without a WASM alternative', () => {+test('offers WebGPU model downloads', () => {const rendered = render(<ModelSelectorcachedModels={['tiny.en']}@@ -17,5 +17,4 @@ test('offers WebGPU model downloads without a WASM alternative', () => {const model = rendered.getByRole('combobox', {name: 'Whisper model'});expect(model.textContent).toContain('119.7 MB WebGPU');expect(model.textContent).toContain('Downloaded');- expect(model.textContent).not.toContain('WASM');});diff --git a/packages/docs/docs/whisper-webgpu/can-use-whisper-webgpu.mdx b/packages/docs/docs/whisper-webgpu/can-use-whisper-webgpu.mdxindex 020741998d..eb9f5880e5 100644--- a/packages/docs/docs/whisper-webgpu/can-use-whisper-webgpu.mdx+++ b/packages/docs/docs/whisper-webgpu/can-use-whisper-webgpu.mdx@@ -6,7 +6,7 @@ crumb: '@remotion/whisper-webgpu'# canUseWhisperWebGpu()<AvailableFrom v="4.0.518" />-Asynchronously checks whether a usable WebGPU adapter or the WASM fallback can run in the current browser.+Asynchronously checks whether a usable WebGPU adapter is available in the current browser.```ts twoslash title="support.ts"import {canUseWhisperWebGpu} from '@remotion/whisper-webgpu';@@ -16,20 +16,14 @@ if (!result.supported) {throw new Error(result.detailedReason);}-console.log(result.backend, result.wasmThreads);+console.log(result.supported);```-## Options--### backend?--`'auto'`, `'webgpu'`, or `'wasm'`. Default: `'auto'`, which requests a WebGPU adapter and uses WASM when no adapter is available.--Requesting `'webgpu'` reports an unsupported result when the WebGPU API or a usable adapter is unavailable, or when the page is not a secure context.+An unsupported result includes a `reason` and `detailedReason`. WebGPU requires the WebGPU API, a usable adapter, and a secure context.## Cross-origin isolation-Cross-origin isolation is not required. It only changes the WASM thread count: isolated pages may use multiple threads, while other pages use one.+Cross-origin isolation is not required.## Compatibilitydiff --git a/packages/docs/docs/whisper-webgpu/dispose-whisper-model.mdx b/packages/docs/docs/whisper-webgpu/dispose-whisper-model.mdxindex 8bae7835bd..c65bc6cf42 100644--- a/packages/docs/docs/whisper-webgpu/dispose-whisper-model.mdx+++ b/packages/docs/docs/whisper-webgpu/dispose-whisper-model.mdx@@ -20,10 +20,6 @@ await disposeWhisperModel({model: 'small.en'});Only dispose this model. Default: all loaded models.-### backend?--Only dispose the `'webgpu'` or `'wasm'` instance. Default: both backends.-## Compatibility<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering player studio hideServers />diff --git a/packages/docs/docs/whisper-webgpu/get-available-models.mdx b/packages/docs/docs/whisper-webgpu/get-available-models.mdxindex 71aed2440a..753ef18299 100644--- a/packages/docs/docs/whisper-webgpu/get-available-models.mdx+++ b/packages/docs/docs/whisper-webgpu/get-available-models.mdx@@ -15,7 +15,7 @@ const models = getAvailableModels();console.log(models);```-Each item contains the short `name`, Hugging Face `modelId`, parameter count, whether the model is multilingual, and estimated downloads for the default WebGPU and WASM configurations.+Each item contains the short `name`, Hugging Face `modelId`, parameter count, whether the model is multilingual, and the estimated WebGPU download size.Available sizes are `tiny`, `base`, `small`, `medium`, and `large-v3-turbo`. English-only `.en` variants are available through `medium`.diff --git a/packages/docs/docs/whisper-webgpu/index.mdx b/packages/docs/docs/whisper-webgpu/index.mdxindex d00cc5c77a..4013d973c3 100644--- a/packages/docs/docs/whisper-webgpu/index.mdx+++ b/packages/docs/docs/whisper-webgpu/index.mdx@@ -10,7 +10,7 @@ crumb: 'Transcribe audio in browser'<p>This package is experimental.</p></ExperimentalBadge>-Transcribe audio locally in the browser using timestamped Whisper models from Transformers.js. WebGPU is used when a usable adapter is available and single-threaded WASM is the fallback.+Transcribe audio locally in the browser using timestamped Whisper models and WebGPU through Transformers.js.For new browser transcription integrations, prefer `@remotion/whisper-webgpu`. [`@remotion/whisper-web`](/docs/whisper-web) remains supported and is not deprecated, but requires cross-origin isolation and does not use WebGPU.@@ -50,9 +50,9 @@ The model is downloaded on the first call and cached by the browser. Call [`load## Requirements-WebGPU requires HTTPS in production or `localhost` during development. Browsers without WebGPU fall back to WASM.+WebGPU requires HTTPS in production or `localhost` during development. Use [`canUseWhisperWebGpu()`](/docs/whisper-webgpu/can-use-whisper-webgpu) to check for a usable adapter.-Cross-origin isolation enables multithreaded WASM but is not required. Without it, the WASM fallback uses one thread.+Cross-origin isolation is not required.## Licensediff --git a/packages/docs/docs/whisper-webgpu/is-whisper-model-cached.mdx b/packages/docs/docs/whisper-webgpu/is-whisper-model-cached.mdxindex 1c9a270883..0a9ffe50b2 100644--- a/packages/docs/docs/whisper-webgpu/is-whisper-model-cached.mdx+++ b/packages/docs/docs/whisper-webgpu/is-whisper-model-cached.mdx@@ -13,7 +13,6 @@ import {isWhisperModelCached} from '@remotion/whisper-webgpu';const downloaded = await isWhisperModelCached({model: 'small.en',- backend: 'webgpu',});```@@ -23,10 +22,6 @@ const downloaded = await isWhisperModelCached({One of the names returned by [`getAvailableModels()`](/docs/whisper-webgpu/get-available-models).-### backend--`'webgpu'` or `'wasm'`. The cache is checked for the model files used by that specific backend.-## Return valueA `Promise<boolean>` resolving to `true` if every required model file is cached.diff --git a/packages/docs/docs/whisper-webgpu/load-whisper-model.mdx b/packages/docs/docs/whisper-webgpu/load-whisper-model.mdxindex 3323dfe791..3c06e9994c 100644--- a/packages/docs/docs/whisper-webgpu/load-whisper-model.mdx+++ b/packages/docs/docs/whisper-webgpu/load-whisper-model.mdx@@ -18,7 +18,7 @@ const result = await loadWhisperModel({},});-console.log(result.backend, result.alreadyLoaded);+console.log(result.alreadyLoaded);```## Options@@ -27,17 +27,13 @@ console.log(result.backend, result.alreadyLoaded);One of the names returned by [`getAvailableModels()`](/docs/whisper-webgpu/get-available-models).-### backend?--`'auto'`, `'webgpu'`, or `'wasm'`. Default: `'auto'`.-### onProgress?Called while model files are resolved and downloaded. `progress` is the aggregate download progress between `0` and `1` and never decreases.## Return value-Returns the selected `backend` and whether the same model pipeline was already loaded in memory.+Returns whether the same model pipeline was already loaded in memory.The browser manages its persistent Transformers.js cache. This function also retains the initialized model in memory until [`disposeWhisperModel()`](/docs/whisper-webgpu/dispose-whisper-model) is called or the page closes.diff --git a/packages/docs/docs/whisper-webgpu/table-of-contents.tsx b/packages/docs/docs/whisper-webgpu/table-of-contents.tsxindex b09afa5fbc..b78ee89d52 100644--- a/packages/docs/docs/whisper-webgpu/table-of-contents.tsx+++ b/packages/docs/docs/whisper-webgpu/table-of-contents.tsx@@ -7,7 +7,7 @@ export const TableOfContents: React.FC = () => {<Grid><TOCItem link="/docs/whisper-webgpu/can-use-whisper-webgpu"><strong>canUseWhisperWebGpu()</strong>- <div>Check which inference backend is available</div>+ <div>Check whether WebGPU is available</div></TOCItem><TOCItem link="/docs/whisper-webgpu/get-available-models"><strong>getAvailableModels()</strong>diff --git a/packages/docs/docs/whisper-webgpu/transcribe.mdx b/packages/docs/docs/whisper-webgpu/transcribe.mdxindex 58e51312f6..e3a4095e8e 100644--- a/packages/docs/docs/whisper-webgpu/transcribe.mdx+++ b/packages/docs/docs/whisper-webgpu/transcribe.mdx@@ -20,7 +20,7 @@ const result = await transcribe({language: 'en',});-console.log(result.text, result.words, result.backend);+console.log(result.text, result.words);```## Options@@ -33,10 +33,6 @@ A mono `Float32Array` sampled at 16kHz. Use [`resampleTo16Khz()`](/docs/whisper-One of the timestamped models returned by [`getAvailableModels()`](/docs/whisper-webgpu/get-available-models). `small` or `small.en` is the recommended default.-### backend?--`'auto'`, `'webgpu'`, or `'wasm'`. Default: `'auto'`.-### language?The spoken language name or language code. Default: `'auto'`. Set it when known to reduce language-detection errors.@@ -55,7 +51,7 @@ Called while the model is loaded. To load independently, use [`loadWhisperModel(## Return value-Returns the full `text`, timestamped `words`, selected `model`, and resolved `backend`.+Returns the full `text`, timestamped `words`, and selected `model`.Word-level timestamps are returned after transcription completes. Transformers.js does not currently stream word-aligned updates while inference is running.diff --git a/packages/example/src/WhisperWebGpu/index.tsx b/packages/example/src/WhisperWebGpu/index.tsxindex 3a47fc774a..109a30f2fb 100644--- a/packages/example/src/WhisperWebGpu/index.tsx+++ b/packages/example/src/WhisperWebGpu/index.tsx@@ -30,12 +30,12 @@ export const WhisperWebGpu = () => {setResult('');try {- const support = await canUseWhisperWebGpu({backend: 'auto'});+ const support = await canUseWhisperWebGpu();if (!support.supported) {throw new Error(support.detailedReason);}- setStatus(`Fetching audio for the ${support.backend} backend...`);+ setStatus('Fetching audio for WebGPU transcription...');const response = await fetch(audioFileUrl);if (!response.ok) {throw new Error(`Could not fetch audio: HTTP ${response.status}`);@@ -62,9 +62,7 @@ export const WhisperWebGpu = () => {},});const {captions} = toCaptions({whisperWebGpuOutput: transcription});- setStatus(- `Done using ${transcription.backend}: ${captions.length} timestamped words.`,- );+ setStatus(`Done: ${captions.length} timestamped words.`);setResult(captions.map(@@ -113,9 +111,7 @@ export const WhisperWebGpu = () => {{selectedModelInfo ? (<p className="rounded-md bg-slate-100 p-3 text-sm text-slate-700">{selectedModelInfo.multilingual ? 'Multilingual' : 'English-only'} ·{' '}- {formatMegabytes(selectedModelInfo.webGpuDownloadSize)} WebGPU- download · {formatMegabytes(selectedModelInfo.wasmDownloadSize)}{' '}- WASM download+ {formatMegabytes(selectedModelInfo.webGpuDownloadSize)} download</p>) : null}diff --git a/packages/whisper-webgpu/README.md b/packages/whisper-webgpu/README.mdindex ae068a1fe3..cacbfa6f40 100644--- a/packages/whisper-webgpu/README.md+++ b/packages/whisper-webgpu/README.md@@ -1,6 +1,6 @@# @remotion/whisper-webgpu-Transcribe audio in the browser using timestamped Whisper models and WebGPU.+Transcribe audio in the browser using timestamped Whisper models and WebGPU. This package is WebGPU-only and does not fall back to WASM.```bashnpx remotion add @remotion/whisper-webgpudiff --git a/packages/whisper-webgpu/src/backend.ts b/packages/whisper-webgpu/src/backend.tsdeleted file mode 100644index a2e54ce758..0000000000--- a/packages/whisper-webgpu/src/backend.ts+++ /dev/null@@ -1,44 +0,0 @@-export type WhisperWebGpuBackend = 'auto' | 'webgpu' | 'wasm';-export type ResolvedWhisperWebGpuBackend = Exclude<- WhisperWebGpuBackend,- 'auto'->;--const requestWebGpuAdapter = async (): Promise<unknown | null> => {- if (- typeof navigator === 'undefined' ||- !('gpu' in navigator) ||- globalThis.isSecureContext === false- ) {- return null;- }-- const {gpu} = navigator as unknown as {- gpu: {requestAdapter: () => Promise<unknown | null>};- };-- try {- return await gpu.requestAdapter();- } catch {- return null;- }-};--export const resolveBackend = async (- backend: WhisperWebGpuBackend,-): Promise<ResolvedWhisperWebGpuBackend> => {- if (backend === 'wasm') {- return 'wasm';- }-- const adapter = await requestWebGpuAdapter();- if (adapter) {- return 'webgpu';- }-- if (backend === 'webgpu') {- throw new Error('No usable WebGPU adapter is available in this browser.');- }-- return 'wasm';-};diff --git a/packages/whisper-webgpu/src/can-use-whisper-webgpu.ts b/packages/whisper-webgpu/src/can-use-whisper-webgpu.tsindex 9b055927c5..1c71d634b8 100644--- a/packages/whisper-webgpu/src/can-use-whisper-webgpu.ts+++ b/packages/whisper-webgpu/src/can-use-whisper-webgpu.ts@@ -1,12 +1,5 @@-import type {- WhisperWebGpuBackend,- ResolvedWhisperWebGpuBackend,-} from './backend';-import {resolveBackend} from './backend';-export enum WhisperWebGpuUnsupportedReason {WindowUndefined = 'window-undefined',- WebAssemblyUnavailable = 'webassembly-unavailable',WebGpuUnavailable = 'webgpu-unavailable',WebGpuRequiresSecureContext = 'webgpu-requires-secure-context',}@@ -14,8 +7,6 @@ export enum WhisperWebGpuUnsupportedReason {export type CanUseWhisperWebGpuResult =| {supported: true;- backend: ResolvedWhisperWebGpuBackend;- wasmThreads: number | null;}| {supported: false;@@ -23,69 +14,52 @@ export type CanUseWhisperWebGpuResult =detailedReason: string;};-export type CanUseWhisperWebGpuOptions = {- backend?: WhisperWebGpuBackend;-};--export const canUseWhisperWebGpu = async ({- backend = 'auto',-}: CanUseWhisperWebGpuOptions = {}): Promise<CanUseWhisperWebGpuResult> => {- if (typeof window === 'undefined') {- return {- supported: false,- reason: WhisperWebGpuUnsupportedReason.WindowUndefined,- detailedReason:- '`window` is not defined. @remotion/whisper-webgpu is intended for browser environments.',- };- }+export const canUseWhisperWebGpu =+ async (): Promise<CanUseWhisperWebGpuResult> => {+ if (typeof window === 'undefined') {+ return {+ supported: false,+ reason: WhisperWebGpuUnsupportedReason.WindowUndefined,+ detailedReason:+ '`window` is not defined. @remotion/whisper-webgpu is intended for browser environments.',+ };+ }- if (- backend === 'webgpu' &&- (typeof navigator === 'undefined' || !('gpu' in navigator))- ) {- return {- supported: false,- reason: WhisperWebGpuUnsupportedReason.WebGpuUnavailable,- detailedReason: 'WebGPU is not available in this browser.',- };- }+ if (typeof navigator === 'undefined' || !('gpu' in navigator)) {+ return {+ supported: false,+ reason: WhisperWebGpuUnsupportedReason.WebGpuUnavailable,+ detailedReason: 'WebGPU is not available in this browser.',+ };+ }- if (backend === 'webgpu' && !window.isSecureContext) {- return {- supported: false,- reason: WhisperWebGpuUnsupportedReason.WebGpuRequiresSecureContext,- detailedReason:- 'WebGPU requires HTTPS in production or localhost during development.',- };- }+ if (!window.isSecureContext) {+ return {+ supported: false,+ reason: WhisperWebGpuUnsupportedReason.WebGpuRequiresSecureContext,+ detailedReason:+ 'WebGPU requires HTTPS in production or localhost during development.',+ };+ }- let resolvedBackend: ResolvedWhisperWebGpuBackend;- try {- resolvedBackend = await resolveBackend(backend);- } catch {- return {- supported: false,- reason: WhisperWebGpuUnsupportedReason.WebGpuUnavailable,- detailedReason: 'No usable WebGPU adapter is available in this browser.',- };- }+ let adapter: unknown | null;+ try {+ const {gpu} = navigator as unknown as {+ gpu: {requestAdapter: () => Promise<unknown | null>};+ };+ adapter = await gpu.requestAdapter();+ } catch {+ adapter = null;+ }- if (resolvedBackend === 'wasm' && typeof WebAssembly === 'undefined') {- return {- supported: false,- reason: WhisperWebGpuUnsupportedReason.WebAssemblyUnavailable,- detailedReason: 'WebAssembly is not available in this browser.',- };- }+ if (!adapter) {+ return {+ supported: false,+ reason: WhisperWebGpuUnsupportedReason.WebGpuUnavailable,+ detailedReason:+ 'No usable WebGPU adapter is available in this browser.',+ };+ }- return {- supported: true,- backend: resolvedBackend,- wasmThreads:- resolvedBackend === 'wasm'- ? window.crossOriginIsolated- ? Math.max(1, navigator.hardwareConcurrency || 1)- : 1- : null,+ return {supported: true};};-};diff --git a/packages/whisper-webgpu/src/index.ts b/packages/whisper-webgpu/src/index.tsindex 8331233013..5b8357a0fa 100644--- a/packages/whisper-webgpu/src/index.ts+++ b/packages/whisper-webgpu/src/index.ts@@ -1,15 +1,8 @@-export type {- ResolvedWhisperWebGpuBackend,- WhisperWebGpuBackend,-} from './backend';export {canUseWhisperWebGpu,WhisperWebGpuUnsupportedReason,} from './can-use-whisper-webgpu';-export type {- CanUseWhisperWebGpuOptions,- CanUseWhisperWebGpuResult,-} from './can-use-whisper-webgpu';+export type {CanUseWhisperWebGpuResult} from './can-use-whisper-webgpu';export {disposeWhisperModel, loadWhisperModel} from './load-whisper-model';export type {DisposeWhisperModelOptions,diff --git a/packages/whisper-webgpu/src/is-whisper-model-cached.ts b/packages/whisper-webgpu/src/is-whisper-model-cached.tsindex 64750d2d65..fe67b30e56 100644--- a/packages/whisper-webgpu/src/is-whisper-model-cached.ts+++ b/packages/whisper-webgpu/src/is-whisper-model-cached.ts@@ -1,18 +1,15 @@-import type {ResolvedWhisperWebGpuBackend} from './backend';import {getModelInfo,- getWhisperModelDtype,+ WHISPER_WEBGPU_DTYPE,type WhisperWebGpuModel,} from './models';export type IsWhisperModelCachedOptions = {model: WhisperWebGpuModel;- backend: ResolvedWhisperWebGpuBackend;};export const isWhisperModelCached = async ({model,- backend,}: IsWhisperModelCachedOptions): Promise<boolean> => {const {ModelRegistry} = await import('@huggingface/transformers');const {modelId} = getModelInfo(model);@@ -21,8 +18,8 @@ export const isWhisperModelCached = async ({'automatic-speech-recognition',modelId,{- device: backend,- dtype: getWhisperModelDtype(backend),+ device: 'webgpu',+ dtype: WHISPER_WEBGPU_DTYPE,},);};diff --git a/packages/whisper-webgpu/src/load-whisper-model.ts b/packages/whisper-webgpu/src/load-whisper-model.tsindex 809cdc590c..520ba80964 100644--- a/packages/whisper-webgpu/src/load-whisper-model.ts+++ b/packages/whisper-webgpu/src/load-whisper-model.ts@@ -1,11 +1,6 @@-import type {- ResolvedWhisperWebGpuBackend,- WhisperWebGpuBackend,-} from './backend';-import {resolveBackend} from './backend';import {getModelInfo,- getWhisperModelDtype,+ WHISPER_WEBGPU_DTYPE,type WhisperWebGpuModel,} from './models';@@ -26,37 +21,24 @@ type LoadedWhisperPipeline = {dispose: () => Promise<void>;};-const pipelines = new Map<string, Promise<LoadedWhisperPipeline>>();--const getCacheKey = (- model: WhisperWebGpuModel,- backend: ResolvedWhisperWebGpuBackend,-) => `${model}:${backend}`;+const pipelines = new Map<WhisperWebGpuModel, Promise<LoadedWhisperPipeline>>();export type LoadWhisperModelOptions = {model: WhisperWebGpuModel;- backend?: WhisperWebGpuBackend;onProgress?: OnWhisperWebGpuModelLoadProgress;};export type LoadWhisperModelResult = {- backend: ResolvedWhisperWebGpuBackend;alreadyLoaded: boolean;};export const loadWhisperModel = async ({model,- backend = 'auto',onProgress,}: LoadWhisperModelOptions): Promise<LoadWhisperModelResult> => {- const resolvedBackend = await resolveBackend(backend);- const cacheKey = getCacheKey(model, resolvedBackend);const modelInfo = getModelInfo(model);- const totalBytes =- resolvedBackend === 'webgpu'- ? modelInfo.webGpuDownloadSize- : modelInfo.wasmDownloadSize;- const existing = pipelines.get(cacheKey);+ const totalBytes = modelInfo.webGpuDownloadSize;+ const existing = pipelines.get(model);if (existing) {await existing;onProgress?.({@@ -66,13 +48,10 @@ export const loadWhisperModel = async ({loadedBytes: totalBytes,totalBytes,});- return {backend: resolvedBackend, alreadyLoaded: true};+ return {alreadyLoaded: true};}- const {env, pipeline} = await import('@huggingface/transformers');- if (resolvedBackend === 'wasm') {- env.backends.onnx.wasm!.numThreads = globalThis.crossOriginIsolated ? 0 : 1;- }+ const {pipeline} = await import('@huggingface/transformers');onProgress?.({status: 'loading',@@ -87,8 +66,8 @@ export const loadWhisperModel = async ({let lastProgress = 0;let lastLoadedBytes = 0;const loading = pipeline('automatic-speech-recognition', modelId, {- device: resolvedBackend,- dtype: getWhisperModelDtype(resolvedBackend),+ device: 'webgpu',+ dtype: WHISPER_WEBGPU_DTYPE,progress_callback: onProgress? (event) => {const record = event as Record<string, unknown>;@@ -133,53 +112,44 @@ export const loadWhisperModel = async ({: undefined,}) as Promise<LoadedWhisperPipeline>;- pipelines.set(cacheKey, loading);+ pipelines.set(model, loading);try {await loading;- return {backend: resolvedBackend, alreadyLoaded: false};+ return {alreadyLoaded: false};} catch (error) {- pipelines.delete(cacheKey);+ pipelines.delete(model);throw error;}};export const getLoadedWhisperPipeline = async ({model,- backend,onProgress,}: {model: WhisperWebGpuModel;- backend: WhisperWebGpuBackend;onProgress?: OnWhisperWebGpuModelLoadProgress;}) => {- const {backend: resolvedBackend} = await loadWhisperModel({+ await loadWhisperModel({model,- backend,onProgress,});- const loaded = pipelines.get(getCacheKey(model, resolvedBackend));+ const loaded = pipelines.get(model);if (!loaded) {throw new Error(`Whisper model ${model} was not loaded.`);}- return {pipeline: await loaded, backend: resolvedBackend};+ return loaded;};export type DisposeWhisperModelOptions = {model?: WhisperWebGpuModel;- backend?: Exclude<WhisperWebGpuBackend, 'auto'>;};export const disposeWhisperModel = async ({model,- backend,}: DisposeWhisperModelOptions = {}): Promise<void> => {- const matching = [...pipelines.entries()].filter(([key]) => {- const [loadedModel, loadedBackend] = key.split(':');- return (- (model === undefined || loadedModel === model) &&- (backend === undefined || loadedBackend === backend)- );+ const matching = [...pipelines.entries()].filter(([loadedModel]) => {+ return model === undefined || loadedModel === model;});await Promise.all(diff --git a/packages/whisper-webgpu/src/models.ts b/packages/whisper-webgpu/src/models.tsindex 8a7e68c666..4e3f3e7dc4 100644--- a/packages/whisper-webgpu/src/models.ts+++ b/packages/whisper-webgpu/src/models.ts@@ -1,5 +1,3 @@-import type {ResolvedWhisperWebGpuBackend} from './backend';-export const WHISPER_WEBGPU_MODELS = ['tiny','tiny.en',@@ -20,7 +18,6 @@ export type WhisperWebGpuModelInfo = {parameters: number;multilingual: boolean;webGpuDownloadSize: number;- wasmDownloadSize: number;};const MODEL_INFO: Record<WhisperWebGpuModel, WhisperWebGpuModelInfo> = {@@ -30,7 +27,6 @@ const MODEL_INFO: Record<WhisperWebGpuModel, WhisperWebGpuModelInfo> = {parameters: 39_000_000,multilingual: true,webGpuDownloadSize: 119_699_015,- wasmDownloadSize: 40_827_373,},'tiny.en': {name: 'tiny.en',@@ -38,7 +34,6 @@ const MODEL_INFO: Record<WhisperWebGpuModel, WhisperWebGpuModelInfo> = {parameters: 39_000_000,multilingual: false,webGpuDownloadSize: 119_697_479,- wasmDownloadSize: 40_826_993,},base: {name: 'base',@@ -46,7 +41,6 @@ const MODEL_INFO: Record<WhisperWebGpuModel, WhisperWebGpuModelInfo> = {parameters: 74_000_000,multilingual: true,webGpuDownloadSize: 206_190_057,- wasmDownloadSize: 76_871_875,},'base.en': {name: 'base.en',@@ -54,7 +48,6 @@ const MODEL_INFO: Record<WhisperWebGpuModel, WhisperWebGpuModelInfo> = {parameters: 74_000_000,multilingual: false,webGpuDownloadSize: 206_188_009,- wasmDownloadSize: 76_871_369,},small: {name: 'small',@@ -62,7 +55,6 @@ const MODEL_INFO: Record<WhisperWebGpuModel, WhisperWebGpuModelInfo> = {parameters: 244_000_000,multilingual: true,webGpuDownloadSize: 586_213_010,- wasmDownloadSize: 249_036_248,},'small.en': {name: 'small.en',@@ -70,7 +62,6 @@ const MODEL_INFO: Record<WhisperWebGpuModel, WhisperWebGpuModelInfo> = {parameters: 244_000_000,multilingual: false,webGpuDownloadSize: 586_209_938,- wasmDownloadSize: 249_035_489,},medium: {name: 'medium',@@ -78,7 +69,6 @@ const MODEL_INFO: Record<WhisperWebGpuModel, WhisperWebGpuModelInfo> = {parameters: 769_000_000,multilingual: true,webGpuDownloadSize: 1_698_508_143,- wasmDownloadSize: 985_716_093,},'medium.en': {name: 'medium.en',@@ -86,7 +76,6 @@ const MODEL_INFO: Record<WhisperWebGpuModel, WhisperWebGpuModelInfo> = {parameters: 769_000_000,multilingual: false,webGpuDownloadSize: 1_698_504_047,- wasmDownloadSize: 985_710_974,},'large-v3-turbo': {name: 'large-v3-turbo',@@ -94,7 +83,6 @@ const MODEL_INFO: Record<WhisperWebGpuModel, WhisperWebGpuModelInfo> = {parameters: 809_000_000,multilingual: true,webGpuDownloadSize: 2_882_584_170,- wasmDownloadSize: 1_084_880_793,},};@@ -108,8 +96,7 @@ export const getModelInfo = (return MODEL_INFO[model];};-export const getWhisperModelDtype = (backend: ResolvedWhisperWebGpuBackend) => {- return backend === 'webgpu'- ? ({encoder_model: 'fp32', decoder_model_merged: 'q4'} as const)- : ('q8' as const);-};+export const WHISPER_WEBGPU_DTYPE = {+ encoder_model: 'fp32',+ decoder_model_merged: 'q4',+} as const;diff --git a/packages/whisper-webgpu/src/test/transcribe.test.ts b/packages/whisper-webgpu/src/test/transcribe.test.tsindex e8beab3435..8ce6adcff4 100644--- a/packages/whisper-webgpu/src/test/transcribe.test.ts+++ b/packages/whisper-webgpu/src/test/transcribe.test.ts@@ -43,7 +43,6 @@ const fakePipeline = Object.assign();mock.module('@huggingface/transformers', () => ({- env: {backends: {onnx: {wasm: {numThreads: 0}}}},ModelRegistry: {is_pipeline_cached: (task: string,@@ -103,7 +102,7 @@ mock.module('@huggingface/transformers', () => ({},}));-test('transcribes with timestamps and selects a usable backend', async () => {+test('transcribes with word timestamps using WebGPU', async () => {const api = await import('../index');const {canUseWhisperWebGpu,@@ -116,7 +115,6 @@ test('transcribes with timestamps and selects a usable backend', async () => {} = api;const channelWaveform = new Float32Array(16_000 * 3);const result = await transcribe({- backend: 'wasm',channelWaveform,language: 'en',model: 'small.en',@@ -126,8 +124,8 @@ test('transcribes with timestamps and selects a usable backend', async () => {'onnx-community/whisper-small.en_timestamped',);expect(pipelineInitialization?.options).toMatchObject({- device: 'wasm',- dtype: 'q8',+ device: 'webgpu',+ dtype: {encoder_model: 'fp32', decoder_model_merged: 'q4'},});expect(transcriptionCall?.audio).toBe(channelWaveform);expect(transcriptionCall?.options).toMatchObject({@@ -139,7 +137,6 @@ test('transcribes with timestamps and selects a usable backend', async () => {expect(result).toEqual({text: 'Hello world free today.',model: 'small.en',- backend: 'wasm',words: [{text: 'Hello', startInSeconds: 0.25, endInSeconds: 0.75},{text: ' world', startInSeconds: 1, endInSeconds: 1.5},@@ -193,14 +190,14 @@ test('transcribes with timestamps and selects a usable backend', async () => {'medium.en','large-v3-turbo',]);- expect(models.find((model) => model.name === 'small.en')).toMatchObject({+ expect(models.find((model) => model.name === 'small.en')).toEqual({+ name: 'small.en',+ modelId: 'onnx-community/whisper-small.en_timestamped',parameters: 244_000_000,multilingual: false,webGpuDownloadSize: 586_209_938,});- expect(- await isWhisperModelCached({backend: 'webgpu', model: 'small.en'}),- ).toBe(true);+ expect(await isWhisperModelCached({model: 'small.en'})).toBe(true);expect(cacheCheck).toEqual({task: 'automatic-speech-recognition',modelId: 'onnx-community/whisper-small.en_timestamped',@@ -235,43 +232,13 @@ test('transcribes with timestamps and selects a usable backend', async () => {try {expect(await canUseWhisperWebGpu()).toEqual({- supported: true,- backend: 'wasm',- wasmThreads: 1,- });- expect(await canUseWhisperWebGpu({backend: 'webgpu'})).toEqual({supported: false,reason: WhisperWebGpuUnsupportedReason.WebGpuUnavailable,detailedReason: 'No usable WebGPU adapter is available in this browser.',});- const fallbackResult = await transcribe({- backend: 'auto',- channelWaveform,- model: 'base.en',- });- expect(fallbackResult.backend).toBe('wasm');- expect(pipelineInitialization?.options).toMatchObject({- device: 'wasm',- dtype: 'q8',- });-adapter = {};- expect(await canUseWhisperWebGpu()).toEqual({- supported: true,- backend: 'webgpu',- wasmThreads: null,- });- const webGpuResult = await transcribe({- backend: 'auto',- channelWaveform,- model: 'tiny.en',- });- expect(webGpuResult.backend).toBe('webgpu');- expect(pipelineInitialization?.options).toMatchObject({- device: 'webgpu',- dtype: {encoder_model: 'fp32', decoder_model_merged: 'q4'},- });+ expect(await canUseWhisperWebGpu()).toEqual({supported: true});} finally {if (originalWindow) {Object.defineProperty(globalThis, 'window', originalWindow);@@ -298,7 +265,6 @@ test('reports model progress without reaching 100% before every file loads', asytotalBytes: number | null;}> = [];await loadWhisperModel({- backend: 'wasm',model: 'medium.en',onProgress: (progress) => {progressValues.push({@@ -312,12 +278,12 @@ test('reports model progress without reaching 100% before every file loads', asyexpect(progressValues[0]).toEqual({progress: 0,loadedBytes: 0,- totalBytes: 985_710_974,+ totalBytes: 1_698_504_047,});expect(progressValues.at(-1)).toEqual({progress: 1,- loadedBytes: 985_710_974,- totalBytes: 985_710_974,+ loadedBytes: 1_698_504_047,+ totalBytes: 1_698_504_047,});const downloading = progressValues.slice(0, -1);expect(@@ -328,8 +294,8 @@ test('reports model progress without reaching 100% before every file loads', asy]);expect(downloading.map(({progress}) => progress)).toEqual([0, 500_000_000, 600_000_000, 985_710_974].map((loaded) =>- Math.min(loaded / 985_710_974, 0.99),+ Math.min(loaded / 1_698_504_047, 0.99),),);- await disposeWhisperModel({backend: 'wasm', model: 'medium.en'});+ await disposeWhisperModel({model: 'medium.en'});});diff --git a/packages/whisper-webgpu/src/transcribe.ts b/packages/whisper-webgpu/src/transcribe.tsindex 8e43d5b8c4..d1a7123224 100644--- a/packages/whisper-webgpu/src/transcribe.ts+++ b/packages/whisper-webgpu/src/transcribe.ts@@ -1,7 +1,3 @@-import type {- ResolvedWhisperWebGpuBackend,- WhisperWebGpuBackend,-} from './backend';import {getLoadedWhisperPipeline,type OnWhisperWebGpuModelLoadProgress,@@ -18,13 +14,11 @@ export type WhisperWebGpuTranscription = {text: string;words: WhisperWebGpuWord[];model: WhisperWebGpuModel;- backend: ResolvedWhisperWebGpuBackend;};export type TranscribeOptions = {channelWaveform: Float32Array;model: WhisperWebGpuModel;- backend?: WhisperWebGpuBackend;language?: string;chunkLengthInSeconds?: number;strideLengthInSeconds?: number;@@ -44,7 +38,6 @@ type TransformersJsTranscription = {export const transcribe = async ({channelWaveform,model,- backend = 'auto',language = 'auto',chunkLengthInSeconds = 30,strideLengthInSeconds = 5,@@ -67,12 +60,10 @@ export const transcribe = async ({);}- const {pipeline: transcriber, backend: resolvedBackend} =- await getLoadedWhisperPipeline({- model,- backend,- onProgress: onModelLoadProgress,- });+ const transcriber = await getLoadedWhisperPipeline({+ model,+ onProgress: onModelLoadProgress,+ });const output = (await transcriber(channelWaveform, {return_timestamps: 'word',@@ -125,6 +116,5 @@ export const transcribe = async ({text: output.text.trimStart(),words,model,- backend: resolvedBackend,};};