diff --git a/AGENTS.md b/AGENTS.md index 7829a37..955e17b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -98,11 +98,12 @@ README.md and `docs/` are the documentation for users; what a developer needs is of `speech serve --open`, plain HTML, CSS and JavaScript modules compiled into `speech`, which `page.cpp` serves with the endpoints that fetch and load models; `access.cpp` guards them with the Host and the Origin. - `wasm/` holds what goes beside the library built for WebAssembly, which `emcmake cmake` configures: the C API - compiled whole into `libspeech.js` and `libspeech.wasm`, with the families `SPEECH_WASM_FAMILIES` names, each a line - of the table of families that the build keeps. `speech.mjs` is the thin module that calls it from a Worker and reads - a model from its Blob through WORKERFS, `wav.mjs` reads a WAVE file as `src/common/wav.cpp` does, and `index.html`, - `page.mjs` and `worker.mjs` are a page that detects speech in a file with them. The build makes neither the - executables nor the checks. + compiled whole into `libspeech.js` and `libspeech.wasm`, or with `SPEECH_WASM_THREADS` into `libspeech-threads.js` + and `libspeech-threads.wasm`, with the families `SPEECH_WASM_FAMILIES` names, each a line of the table of families + that the build keeps. `speech.mjs` is the thin module that calls it from a Worker and reads a model from its Blob + through WORKERFS, `wav.mjs` reads a WAVE file as `src/common/wav.cpp` does, `index.html`, `page.mjs` and `worker.mjs` + are a page that detects speech in a file with them, and `serve.py` serves the folder cross-origin isolated, as the + module with threads needs. The build makes neither the executables nor the checks. - The smoke scripts in `checks/smoke/` drive each entry point as its caller does and fail on a defect: `worker_smoke.py`, `worker_recognition_smoke.py`, `worker_enhancement_smoke.py` and `worker_dialogue_smoke.py` the worker protocol through @@ -245,7 +246,8 @@ comment. `checks/smoke/server_enhancement_smoke.py`, `checks/smoke/server_dialogue_smoke.py` and `checks/smoke/server_page_smoke.py`, one to the page `checks/smoke/server_page_browser_smoke.mjs` (with `--dialogue` and Haru for the talk panel), one to the command line or the parser `checks/smoke/speech_cli_smoke.py`, with a model of each family, one to `tools/catalog/` `checks/smoke/models_smoke.py`, and one to `wasm/`, to the library's code that a WebAssembly build compiles - differently or to the table of families `checks/smoke/wasm_browser_smoke.mjs`, with Silero VAD. + differently or to the table of families `checks/smoke/wasm_browser_smoke.mjs`, with Silero VAD, on the module without + threads and with `--threads 4` on the module with them. - Never commit on main. Every change reaches main through a pull request, one coherent unit each: a model's stage, a fix, a refactor or a documentation change. - Commit messages and pull request titles are one English sentence in the imperative, without a prefix diff --git a/CMakeLists.txt b/CMakeLists.txt index 69c5eb7..93d8701 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -22,13 +22,19 @@ endif() # for projects that read a 32-bit platform from it, and ggml compiles its SIMD128 code only for a processor named wasm; # for any other it falls back to its generic C. ggml repacks weights only for instructions of x86, Arm and RISC-V, # and its repacking code, never run in WebAssembly, was 50 KB of the 410 KB of a gzipped module of Silero VAD -# (Emscripten 7.0.0, 2026-11-21). +# (Emscripten 7.0.0, 2026-11-21). With SPEECH_WASM_THREADS every file, ggml's included, is compiled for threads, since +# wasm-ld links no file compiled without atomics into a module of shared memory. if (EMSCRIPTEN) + option(SPEECH_WASM_THREADS "Build the WebAssembly library with threads, which a page runs only cross-origin isolated" OFF) set(CMAKE_SYSTEM_PROCESSOR wasm32) set(GGML_OPENMP OFF CACHE BOOL "" FORCE) set(GGML_CPU_REPACK OFF CACHE BOOL "" FORCE) add_compile_options(-fwasm-exceptions) add_link_options(-fwasm-exceptions) + if (SPEECH_WASM_THREADS) + add_compile_options(-pthread) + add_link_options(-pthread) + endif() endif() # CI builds the submodule's ggml once, installs it with static libraries, and reuses it while the # submodule's commit stays the same; Vulkan's shaders alone take minutes to compile. @@ -277,15 +283,26 @@ foreach(family ${SPEECH_FAMILIES}) endforeach() set_source_files_properties(src/api/speech.cpp PROPERTIES COMPILE_DEFINITIONS "${SPEECH_FAMILY_DEFINITIONS}") -# A WebAssembly build makes the C API once, as libspeech.js and libspeech.wasm, an ES module for a Worker that -# wasm/speech.mjs wraps, and nothing else: the executables and the checks run processes, terminals, devices and the -# network, which a browser does not give them. The module exports every function speech.h declares, and Emscripten's -# file system with WORKERFS, which reads a model from a Blob as it is asked, so that the weights are held once, in the -# module's memory. The memory grows as the model needs, up to the 4 GB a 32-bit address reaches. Emscripten gives the -# stack 64 KB, and ggml builds a graph by recursing once for each node of its longest chain: RE-USE's graph on 2 s of -# audio overflowed 64 KB and ran in 128 KB (Emscripten 7.0.0, 2026-11-21). The stack is 1 MB, as on Windows' main -# thread, the least the library runs on in a native build. +# A WebAssembly build makes the C API once, as libspeech.js and libspeech.wasm (libspeech-threads.js and .wasm with +# threads), an ES module for a Worker that wasm/speech.mjs wraps, and nothing else: the executables and the checks run +# processes, terminals, devices and the network, which a browser does not give them. The module exports every function +# speech.h declares, and Emscripten's file system with WORKERFS, which reads a model from a Blob as it is asked, so +# that the weights are held once, in the module's memory. The memory grows as the model needs, up to the 4 GB a +# 32-bit address reaches, or 1 GB with threads: Safari on iOS counts a shared memory's maximum against the memory of the +# process as it makes it, and refused one of 2 GB on iOS 16.2. The module with threads starts a Worker for each of the +# browser's logical processors before it runs, since a thread that the library starts while it computes would wait for +# a Worker to start, which it cannot until the module returns; a thread past them fails to start rather than waits. +# Emscripten gives the stack 64 KB, and ggml builds a graph by recursing once for each node of its longest chain: +# RE-USE's graph on 2 s of audio overflowed 64 KB and ran in 128 KB (Emscripten 7.0.0, 2026-11-21). The stack is 1 MB, +# as on Windows' main thread, the least the library runs on in a native build. if (EMSCRIPTEN) + if (SPEECH_WASM_THREADS) + set(output libspeech-threads) + set(memory -sMAXIMUM_MEMORY=1GB -sPTHREAD_POOL_SIZE=navigator.hardwareConcurrency -sPTHREAD_POOL_SIZE_STRICT=2) + else() + set(output libspeech) + set(memory -sMAXIMUM_MEMORY=4GB) + endif() file(STRINGS include/speech.h api_lines REGEX "^SPEECH_API .*speech_[a-z0-9_]+\\(") set(exports _malloc _free) foreach(line ${api_lines}) @@ -298,15 +315,16 @@ if (EMSCRIPTEN) target_include_directories(speech-wasm PRIVATE include src/engines) target_link_libraries(speech-wasm PRIVATE ${SPEECH_FAMILY_LIBRARIES}) target_compile_definitions(speech-wasm PRIVATE SPEECH_VERSION="${PROJECT_VERSION}") - set_target_properties(speech-wasm PROPERTIES OUTPUT_NAME libspeech SUFFIX .js) + set_target_properties(speech-wasm PROPERTIES OUTPUT_NAME ${output} SUFFIX .js) target_link_options(speech-wasm PRIVATE -sMODULARIZE -sEXPORT_ES6 -sENVIRONMENT=worker - -sALLOW_MEMORY_GROWTH -sMAXIMUM_MEMORY=4GB -sSTACK_SIZE=1MB + -sALLOW_MEMORY_GROWTH -sSTACK_SIZE=1MB ${memory} -sEXPORTED_FUNCTIONS=${exports} -sEXPORTED_RUNTIME_METHODS=FS,WORKERFS,UTF8ToString,stringToNewUTF8,HEAPU8,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP64 -lworkerfs.js) - # The module that wraps the library and the page that tries it go beside it, as a release's archive holds them. - foreach(file speech.mjs wav.mjs worker.mjs page.mjs index.html) + # The module that wraps the library, the page that tries it and the server that serves the page cross-origin + # isolated go beside it, as a release's archive holds them. + foreach(file speech.mjs wav.mjs worker.mjs page.mjs index.html serve.py) configure_file(wasm/${file} ${CMAKE_CURRENT_BINARY_DIR}/${file} COPYONLY) endforeach() return() diff --git a/checks/smoke/wasm_browser_smoke.mjs b/checks/smoke/wasm_browser_smoke.mjs index 5f8275c..b4a6936 100644 --- a/checks/smoke/wasm_browser_smoke.mjs +++ b/checks/smoke/wasm_browser_smoke.mjs @@ -4,20 +4,27 @@ // option past what the C API takes, as errors naming the input rather than an abort or a value of another size, and // answer the next request after them; a run must keep its model while another loads one. It prints the time to load // the model, the RTFx of each file and the most memory the module held. The page is served from 127.0.0.1 with COOP and -// COEP, which the build with threads needs, and the files given at /files/. Chrome is the one at $CHROME, or macOS's; -// the server and Chrome are stopped however the script ends. -// usage: node checks/smoke/wasm_browser_smoke.mjs ... +// COEP, which the build with threads needs, and the files given at /files/. With --threads N the page runs the build +// with threads on N threads, and audio of more than its 1 GB must be refused as out_of_memory before the module writes +// it, after which the module still answers. Chrome is the one at $CHROME, or macOS's; the server and Chrome are stopped +// however the script ends. +// usage: node checks/smoke/wasm_browser_smoke.mjs ... [--threads N] import { spawn, execFileSync } from 'node:child_process'; import fs from 'node:fs'; import http from 'node:http'; import os from 'node:os'; import path from 'node:path'; -const [speech, build, model, ...audio] = process.argv.slice(2); -if (!audio.length) { - console.error('usage: node checks/smoke/wasm_browser_smoke.mjs ...'); +const argv = process.argv.slice(2); +const threadsAt = argv.indexOf('--threads'); +const threads = threadsAt >= 0 ? Number(argv[threadsAt + 1]) : null; +if (threadsAt >= 0) argv.splice(threadsAt, 2); +const [speech, build, model, ...audio] = argv; +if (!audio.length || (threadsAt >= 0 && !(threads > 1))) { + console.error('usage: node checks/smoke/wasm_browser_smoke.mjs ... [--threads N, 2 or more]'); process.exit(2); } +const library = threads ? 'libspeech-threads' : 'libspeech'; const CHROME = process.env.CHROME ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; const wait = (ms) => new Promise((r) => setTimeout(r, ms)); @@ -82,8 +89,10 @@ const running = []; let ws = null; let server = null; try { - for (const file of ['libspeech.js', 'libspeech.wasm', 'speech.mjs', 'index.html']) { - if (!fs.existsSync(path.join(build, file))) throw new Error(`${build} has no ${file}; build it with emcmake cmake and cmake --build`); + for (const file of [`${library}.js`, `${library}.wasm`, 'speech.mjs', 'index.html']) { + if (!fs.existsSync(path.join(build, file))) { + throw new Error(`${build} has no ${file}; build it with emcmake cmake${threads ? ' -DSPEECH_WASM_THREADS=ON' : ''} and cmake --build`); + } } const lines = execFileSync(speech, ['vad', model, '--format', 'json', ...audio], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] }); const native = lines.trim().split('\n').map((line) => JSON.parse(line).regions); @@ -147,25 +156,29 @@ try { if (!isolated) throw new Error('the page is not cross-origin isolated, though the server sends COOP and COEP'); const run = (args) => page(`return await speechPage.run(${args}).catch(failure);`); - const all = `{ model: ${JSON.stringify(urls[0])}, audio: ${JSON.stringify(urls.slice(1))} }`; + const on = threads ? `, threads: ${threads}` : ''; + const all = `{ model: ${JSON.stringify(urls[0])}, audio: ${JSON.stringify(urls.slice(1))}${on} }`; const first = await run(all); if (first.error) throw new Error(`the page failed: ${JSON.stringify(first.error)}`); const differs = departure(first.detections, native); if (differs) throw new Error(differs); - console.log(`speech.cpp ${first.version}: the module started in ${first.open.toFixed(1)} ms, and ${first.info.name} ` - + `${first.info.weight_type} loaded in ${first.load.toFixed(1)} ms`); + if (first.info.threads !== (threads ?? 1)) throw new Error(`the model computes with ${first.info.threads} threads, where ${threads ?? 1} were asked for`); + console.log(`speech.cpp ${first.version}, ${library}: the module started in ${first.open.toFixed(1)} ms, and ${first.info.name} ` + + `${first.info.weight_type} loaded in ${first.load.toFixed(1)} ms on ${first.info.threads} threads`); first.detections.forEach((d, f) => { console.log(`${path.basename(audio[f])}: ${d.regions.length} regions as speech vad finds them, ${d.seconds.toFixed(2)} s of audio in ` + `${d.ms.toFixed(1)} ms, RTFx ${(d.seconds / (d.ms / 1000)).toFixed(0)}`); }); console.log(`the module's memory: ${(first.memory / 2 ** 20).toFixed(1)} MiB at most`); - const one = `audio: ${JSON.stringify(urls.slice(1, 2))}`; - const threads = await run(`{ model: ${JSON.stringify(urls[0])}, ${one}, threads: 2 }`); - if (threads.error?.status !== 'invalid_argument' || threads.error.option !== 'threads') { - throw new Error(`two threads in the build without threads: ${JSON.stringify(threads)}, where invalid_argument naming threads was due`); + const one = `audio: ${JSON.stringify(urls.slice(1, 2))}${on}`; + // One thread more than the build starts: 2 without threads, or one past the browser's logical processors with them. + const most = threads ? await page('return navigator.hardwareConcurrency;') : 1; + const many = await run(`{ model: ${JSON.stringify(urls[0])}, audio: ${JSON.stringify(urls.slice(1, 2))}, threads: ${most + 1}, threaded: ${!!threads} }`); + if (many.error?.status !== 'invalid_argument' || many.error.option !== 'threads') { + throw new Error(`${most + 1} threads in ${library}: ${JSON.stringify(many)}, where invalid_argument naming threads was due`); } - console.log(`two threads refused: ${threads.error.status} (${threads.error.option}): ${threads.error.message}`); + console.log(`${most + 1} threads refused: ${many.error.status} (${many.error.option}): ${many.error.message}`); // The model cut in half is loaded while a run of the whole one is under way, which must keep its own model. Both are // Blobs at hand, so that the second load reaches the Worker before the first run's detection. const [whole, cut] = await page(` @@ -189,6 +202,39 @@ try { } console.log(`min_speech_duration_ms of ${value} refused: ${wide.error.status}: ${wide.error.message}`); } + if (threads) { + // Audio past the 1 GB of the build with threads, in a Worker of its own, since the page reads audio from WAVE files: + // malloc() gives 0 for it, and the module must refuse it before it writes there, then answer the next request. + const big = await page(` + const source = 'import { openSpeech } from ' + JSON.stringify(location.origin + '/speech.mjs') + ';' + + 'onmessage = async ({ data: { blob, threads } }) => {' + + ' const speech = await openSpeech({ threads: true });' + + ' const model = speech.load(blob, { threads });' + + ' const failed = (e) => ({ status: e.status ?? null, message: e.message });' + + ' let big;' + + ' try { big = { regions: model.detect(new Float32Array(2 ** 28 + 2 ** 20), 16000) }; } catch (e) { big = failed(e); }' + + ' let after;' + + ' try { after = { regions: model.detect(new Float32Array(16000), 16000) }; } catch (e) { after = failed(e); }' + + ' postMessage({ big, after, memory: speech.memory });' + + '};'; + const worker = new Worker(URL.createObjectURL(new Blob([source], { type: 'text/javascript' })), { type: 'module' }); + const blob = await (await fetch(${JSON.stringify(urls[0])})).blob(); + const answer = new Promise((resolve, reject) => { + worker.onmessage = ({ data }) => resolve(data); + worker.onerror = (e) => reject(new Error(e.message)); + }); + worker.postMessage({ blob, threads: ${threads} }); + try { + return await answer; + } finally { + worker.terminate(); + } + `); + if (big.big.status !== 'out_of_memory' || !big.after.regions || big.after.regions.length) { + throw new Error(`audio past 1 GB: ${JSON.stringify(big)}, where out_of_memory and then a second of silence without regions were due`); + } + console.log(`audio past 1 GB refused: ${big.big.status}: ${big.big.message}; a second of silence after it: no regions`); + } const again = await run(`{ model: ${JSON.stringify(urls[0])}, ${one} }`); if (again.error) throw new Error(`the page failed after the errors: ${JSON.stringify(again.error)}`); const differsAgain = departure(again.detections, native.slice(0, 1)); diff --git a/docs/adr/releases-run-on-macos-arm64-with-metal-windows-x64-with-vulkan-linux-x64-on-glibc-2.34-with-vulkan-or-the-cpu-and-browsers-in-webassembly.md b/docs/adr/releases-run-on-macos-arm64-with-metal-windows-x64-with-vulkan-linux-x64-on-glibc-2.34-with-vulkan-or-the-cpu-and-browsers-in-webassembly.md index 565642c..689038e 100644 --- a/docs/adr/releases-run-on-macos-arm64-with-metal-windows-x64-with-vulkan-linux-x64-on-glibc-2.34-with-vulkan-or-the-cpu-and-browsers-in-webassembly.md +++ b/docs/adr/releases-run-on-macos-arm64-with-metal-windows-x64-with-vulkan-linux-x64-on-glibc-2.34-with-vulkan-or-the-cpu-and-browsers-in-webassembly.md @@ -41,8 +41,9 @@ catches, which in WebAssembly takes its exceptions: Chrome 95, Firefox 100 and S Windows does not ship. - **No CUDA build is released.** - **Browsers have one archive** (`wasm`): the C API built with Emscripten for WebAssembly with SIMD128 and its - exceptions, with the module that calls it from a module Worker and a page that tries it, which Chrome 95, Firefox 114 - and Safari 16.4 and later run. It runs on the CPU and holds the families that are checked in a browser. + exceptions, on one thread and with threads, with the module that calls it from a module Worker and a page that tries + it, which Chrome 95, Firefox 114 and Safari 16.4 and later run. It runs on the CPU and holds the families that are + checked in a browser. The alternatives were turned down: diff --git a/docs/adr/the-webassembly-build-has-a-module-with-threads-for-isolated-pages-of-1-gb-with-a-worker-per-logical-processor.md b/docs/adr/the-webassembly-build-has-a-module-with-threads-for-isolated-pages-of-1-gb-with-a-worker-per-logical-processor.md new file mode 100644 index 0000000..c09f5da --- /dev/null +++ b/docs/adr/the-webassembly-build-has-a-module-with-threads-for-isolated-pages-of-1-gb-with-a-worker-per-logical-processor.md @@ -0,0 +1,39 @@ +# The WebAssembly build has a module with threads for isolated pages, of 1 GB, with a Worker per logical processor + +## Context + +Threads in WebAssembly are Workers that share the module's memory, a SharedArrayBuffer, which a browser gives only to a +page that is cross-origin isolated: served with `Cross-Origin-Opener-Policy: same-origin` and +`Cross-Origin-Embedder-Policy: require-corp`, and loading from other origins only what they allow. A page that embeds +content of other origins cannot always be isolated. A Worker starts only once the code that asked for it returns to +the browser, and ggml starts its threads for each graph and waits for them within the same call. A shared memory +declares the most it may grow to when it is made, and Safari on iOS counts that most against the process at once: it +refused a shared memory of 2 GB on iOS 16.2, as others reported, where 1 GB was made. + +## Decision + +- **Two modules**: `libspeech`, on one thread, for any page, and `libspeech-threads` (`SPEECH_WASM_THREADS`), for a page + that is cross-origin isolated. `speech.mjs` loads either, and refuses the one with threads in a page that is not + isolated. +- **The module with threads starts a Worker for each of the browser's logical processors before it runs**, and the + library refuses more threads than that at `speech_load_params_set_threads()`. A thread past them fails to start + rather than waits for a Worker. +- **It computes on 4 threads by default**, or on the logical processors where they are fewer. Silero VAD F32 on a minute + of audio, on an Apple M5 of 10 logical processors in Chrome 158 (2026-11-21): RTFx 560 on the first request and 1350 + on the fifth with 4 threads, and 100 and 700 to 1000 with 10. +- **Its memory grows to 1 GB at most**, and the module without threads to 4 GB. + +The alternatives were turned down: + +- One module, with threads. A page that cannot be cross-origin isolated could not run speech.cpp at all. +- Starting a Worker when a thread is asked for. ggml waits for its threads inside the call that started them, and the + Worker would start only after that call returned: the call would never end. +- The machine's logical processors by default, as `navigator.hardwareConcurrency` gives them. A browser does not tell + performance cores from the others, and with all of them the first request was six times slower than with 4. +- A shared memory of 2 GB or 4 GB, which Safari on iOS refuses as the module starts. + +## Consequences + +A page that runs the module with threads serves its own files with both headers, and fetches a model from another +origin only where that origin sends CORS or `Cross-Origin-Resource-Policy` headers. A model larger than about 1 GB, with +its requests, runs only in the module without threads. diff --git a/docs/adr/the-webassembly-build-runs-the-c-api-in-a-worker-and-reads-a-model-from-its-blob-through-workerfs.md b/docs/adr/the-webassembly-build-runs-the-c-api-in-a-worker-and-reads-a-model-from-its-blob-through-workerfs.md index 1c8c89c..4caccc8 100644 --- a/docs/adr/the-webassembly-build-runs-the-c-api-in-a-worker-and-reads-a-model-from-its-blob-through-workerfs.md +++ b/docs/adr/the-webassembly-build-runs-the-c-api-in-a-worker-and-reads-a-model-from-its-blob-through-workerfs.md @@ -20,8 +20,8 @@ gives less of, and a page downloads every byte of the module before it runs. The - **The families a module holds are chosen when it is built** (`SPEECH_WASM_FAMILIES`), each a line of the table of families that the build keeps or leaves out, so that a page downloads the code of the models it runs and no more. Silero VAD's module is 360 KB gzipped, and one of every family 936 KB (Emscripten 7.0.0, 2026-11-21). -- **The module without threads refuses more than one** at `speech_load_params_set_threads()`, where ggml would abort - the module when the thread it starts does not. +- **A module refuses more threads than it can start** at `speech_load_params_set_threads()`, one without threads more + than one, where ggml would abort the module when the thread it starts does not. - **A WAVE file is read in JavaScript as the library reads one** (`wasm/wav.mjs`), since the C API takes samples, so that a page and `speech` give a model the same samples of the same file. diff --git a/docs/browser.md b/docs/browser.md index 2d51bd8..86b4920 100644 --- a/docs/browser.md +++ b/docs/browser.md @@ -7,12 +7,14 @@ leaves the browser. It holds Silero VAD, which finds where someone speaks in a r | File | What it is | |---|---| -| `libspeech.js`, `libspeech.wasm` | the library: the C API compiled to WebAssembly, an ES module for a Worker | +| `libspeech.js`, `libspeech.wasm` | the library: the C API compiled to WebAssembly, an ES module for a Worker, on one thread | +| `libspeech-threads.js`, `libspeech-threads.wasm` | the same library with threads, for a page that is cross-origin isolated | | `speech.mjs` | the module a Worker imports to load a model and run requests | | `wav.mjs` | reads a WAVE file into samples as `speech` reads it | | `index.html`, `page.mjs`, `worker.mjs` | a page that finds the regions of speech in a WAVE file you choose | +| `serve.py` | serves the folder on 127.0.0.1 with the headers the build with threads needs | -It runs on the CPU, on one thread, in Chrome and Edge 95, Firefox 114 and Safari 16.4 and later, on phones too. +It runs on the CPU in Chrome and Edge 95, Firefox 114 and Safari 16.4 and later, on phones too. ## Try the page @@ -20,13 +22,14 @@ Serve the folder over HTTP, since a page opened from a file cannot load modules, ```sh cd build-wasm -python3 -m http.server 8000 +python3 serve.py ``` -Open , choose the model, `silero-vad-309K-v6.2-F32.gguf` (`speech pull silero-vad` fetches it, +Open , choose the model, `silero-vad-309K-v6.2-F32.gguf` (`speech pull silero-vad` fetches it, or take it from [Hugging Face](https://huggingface.co/sakasegawa/silero-vad-GGUF)), and a WAVE file, and press -**Detect speech**. The page shows each region, the load time, the RTFx and the module's memory. A link can name both -files on the same server: `index.html?model=silero-vad-309K-v6.2-F32.gguf&audio=meeting.wav` runs as it opens. +**Detect speech**. The page shows each region, the load time, the RTFx and the module's memory. With more than one +thread it runs the build with threads. A link can name the files on the same server: +`index.html?model=silero-vad-309K-v6.2-F32.gguf&audio=meeting.wav&threads=4` runs as it opens. ## Use it in a page @@ -55,7 +58,7 @@ worker.postMessage({ model: modelInput.files[0], audio: audioInput.files[0] }); | In `speech.mjs` | What it does | |---|---| -| `await openSpeech()` | loads `libspeech.js` and `libspeech.wasm` from beside `speech.mjs` | +| `await openSpeech()` | loads `libspeech.js` and `libspeech.wasm` from beside `speech.mjs`; `openSpeech({ threads: true })` loads the build with threads | | `speech.version` | the release, as `speech_version()` gives it | | `speech.memory` | the bytes of the module's memory, which grows as needed and never shrinks | | `speech.load(blob, { threads })` | loads a model from a Blob or File, as `speech_model_load()` does | @@ -64,7 +67,22 @@ worker.postMessage({ model: modelInput.files[0], audio: audioInput.files[0] }); | `model.free()` | frees the model | Every call blocks the Worker until the library returns. A failure throws a `SpeechError` with the C API's `status` -(`invalid_argument`, `model_file`, …), its `message`, and the `option` at fault, or null. +(`invalid_argument`, `model_file`, `out_of_memory`, …), its `message`, and the `option` at fault, or null. + +## One thread or several + +| | `libspeech` | `libspeech-threads` | +|---|---|---| +| threads | 1; more is `invalid_argument` | 4 by default, at most `navigator.hardwareConcurrency` | +| the page | any | cross-origin isolated: served with `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` | +| the module's memory | up to 4 GB | up to 1 GB | +| at the start | the module | the module and a Worker for each logical processor | + +The build with threads shares its memory between Workers, which a browser allows only in a page that is cross-origin +isolated; `openSpeech({ threads: true })` refuses to start in another. A cross-origin isolated page loads a resource of +another origin only when that origin allows it (`Cross-Origin-Resource-Policy`, or CORS), which `serve.py` does not +need for files of its own folder. Its memory is limited to 1 GB because Safari on iOS counts the most a shared memory +may grow to as the memory is made, and refuses it when that is too large. ## Limits @@ -73,30 +91,32 @@ Every call blocks the Worker until the library returns. A failure throws a `Spee - **The model is read from its Blob.** The library reads the file a piece at a time as it loads, and holds the weights once, in the module's memory. The Blob must not change while the model is loaded. A model the page fetches is a Blob the browser keeps as well. -- **4 GB.** The module's memory grows as a model and its requests need, up to 4 GB, the most a 32-bit WebAssembly - address reaches; a phone's browser gives a page less. A request copies its audio into the module's memory, beside - the Worker's `Float32Array`. -- **One thread.** The library computes on one thread and refuses `threads` above 1 as `invalid_argument`. +- **4 GB, or 1 GB with threads.** The module's memory grows as a model and its requests need, up to 4 GB, the most a + 32-bit WebAssembly address reaches, or 1 GB in the build with threads; a phone's browser may give a page less. A + request copies its audio into the module's memory, beside the Worker's `Float32Array`, and audio past what the memory + can hold is refused as `out_of_memory`. - **Silero VAD alone.** A model of another family is refused as `model_file`, a model of an architecture this build does not run. ## Size and speed -Silero VAD F32 on an Apple M5 (macOS 26.2) in headless Chrome 158, built with Emscripten 7.0.0, 2026-11-21: +Silero VAD F32 on an Apple M5 (macOS 26.2, 10 logical processors) in headless Chrome 158, built with Emscripten +7.0.0, a minute of audio, the medians of three runs, 2026-11-21: -| | | -|---|---| -| `libspeech.wasm`, gzipped | 360 KB (1.1 MB as it is) | -| `libspeech.js`, gzipped | 18 KB | -| the module started, from the same machine | 6 ms | -| load time | 9 ms | -| a minute of audio, the first request after loading | 0.12 s, an RTFx of 490 | -| a minute of audio, the later requests | 0.09 s, an RTFx of 670 | -| the module's memory, at most | 29.9 MiB | - -The first request is slower because the browser compiles the module's code again, faster, once it runs often. `speech -vad` on the same CPU with one thread takes 0.089 s, an RTFx of 675. The page gives the regions `speech vad` gives, number -for number, in Chrome and in Safari on iOS 26.5. +| | `libspeech` | `libspeech-threads`, 2 threads | `libspeech-threads`, 4 threads | +|---|---|---|---| +| `.wasm` and `.js`, gzipped | 360 KB and 18 KB | 340 KB and 22 KB | 340 KB and 22 KB | +| the module started, from the same machine | 6 ms | 17 ms | 19 ms | +| load time | 9 ms | 8 ms | 9 ms | +| the first request after loading | 0.13 s, RTFx 480 | 0.09 s, RTFx 640 | 0.11 s, RTFx 560 | +| the fifth request | 0.09 s, RTFx 670 | 0.06 s, RTFx 1080 | 0.04 s, RTFx 1350 | +| the module's memory, at most | 29.9 MiB | 29.9 MiB | 35.9 MiB | + +The first requests are slower because the browser compiles the module's code again, faster, once it runs often. With +all 10 logical processors the first request took 0.6 s, since the library starts its threads anew for each part of +the work. `speech vad` on the same CPU takes 0.091 s with one thread (RTFx 660) and 0.049 s with four (RTFx 1220). The page +gives the regions `speech vad` gives, number for number, in Chrome and in Safari on the iOS 26.5 simulator, with and +without threads. ## Build it @@ -112,8 +132,11 @@ source ./emsdk_env.sh cd ../speech.cpp emcmake cmake -B build-wasm cmake --build build-wasm -j +emcmake cmake -B build-wasm-threads -DSPEECH_WASM_THREADS=ON +cmake --build build-wasm-threads -j ``` -It makes `build-wasm/libspeech.js`, `libspeech.wasm` and the files beside them in the table above. -`-DSPEECH_WASM_FAMILIES="silero-vad;qwen3-asr"` builds other families in, by their folders in `src/families/`, or -`all`; each adds to the module, and only Silero VAD is checked in a browser. +The first makes `build-wasm/libspeech.js`, `libspeech.wasm` and the files beside them in the table above, the second +`build-wasm-threads/libspeech-threads.js` and `libspeech-threads.wasm`; copy these two beside the others for the page to +find them. `-DSPEECH_WASM_FAMILIES="silero-vad;qwen3-asr"` builds other families in, by their folders in +`src/families/`, or `all`; each adds to the module, and only Silero VAD is checked in a browser. diff --git a/docs/c-api.md b/docs/c-api.md index 108672c..5b65d6e 100644 --- a/docs/c-api.md +++ b/docs/c-api.md @@ -133,7 +133,8 @@ and link `speech.lib`. Inside this CMake project, link the target `speech` (shar no other device takes its place. - the CPU's threads, which apply to whatever runs on the CPU; by default the machine's performance cores, or its physical cores where the system does not tell them apart. The WebAssembly build ([browser.md](browser.md)) computes - on one thread and refuses more. + on one thread and refuses more, and its build with threads on 4 by default and at most the browser's logical + processors. - a warm-up that runs a short request while the model loads, so that a GPU compiles its kernels before the first request. It is off by default; `speech worker` and `speech serve` turn it on. - **Model information.** `speech_model_info_open()` reads what a model file says of its model from its metadata, without diff --git a/docs/install.md b/docs/install.md index 612fbc6..42dadae 100644 --- a/docs/install.md +++ b/docs/install.md @@ -139,7 +139,7 @@ It makes `build/speech` and the shared library beside it. A build from source is | CPU | `cmake -B build` elsewhere | checked and released for Linux | | Vulkan | `cmake -B build -DGGML_VULKAN=ON` | checked on NVIDIA and released for Windows and Linux; needs the Vulkan SDK to build | | CUDA | `cmake -B build -DGGML_CUDA=ON` | builds, but is not checked or released | -| WebAssembly | `emcmake cmake -B build-wasm` | the library alone, for a web page; needs Emscripten ([browser.md](browser.md#build-it)) | +| WebAssembly | `emcmake cmake -B build-wasm`, with threads `-DSPEECH_WASM_THREADS=ON` | the library alone, for a web page; needs Emscripten ([browser.md](browser.md#build-it)) | On Linux, the [Vulkan SDK](https://vulkan.lunarg.com/sdk/home#linux) brings everything the Vulkan build needs in one archive: diff --git a/include/speech.h b/include/speech.h index dbd1c4a..7288a39 100644 --- a/include/speech.h +++ b/include/speech.h @@ -610,8 +610,9 @@ SPEECH_API speech_status speech_load_params_set_device(speech_load_params * para * whatever the model computes on the CPU: all of its graphs for a model on the CPU, and for a model on a GPU those it * computes on the CPU, such as a decoding with decode_on_cpu, or none. Without it the library takes the machine's * performance cores, or its physical cores where the system does not tell them apart. The model's information reports - * the number in effect (speech_model_info_threads()). A WebAssembly build without threads computes with 1 alone and - * refuses more as SPEECH_ERROR_INVALID_ARGUMENT. + * the number in effect (speech_model_info_threads()). A WebAssembly build without threads computes with 1 alone, and + * one with threads with at most the browser's logical processors, 4 by default; each refuses more as + * SPEECH_ERROR_INVALID_ARGUMENT. */ SPEECH_API speech_status speech_load_params_set_threads(speech_load_params * params, int threads); diff --git a/src/common/backend.cpp b/src/common/backend.cpp index 9d05115..bf2370b 100644 --- a/src/common/backend.cpp +++ b/src/common/backend.cpp @@ -25,6 +25,9 @@ #include #include #endif +#ifdef __EMSCRIPTEN_PTHREADS__ +#include +#endif namespace { @@ -122,7 +125,12 @@ ggml_backend_t start_device(ggml_backend_dev_t device, int threads) { int default_threads() { static const int threads = std::min(max_threads(), [] { -#ifdef __APPLE__ +#if defined(__EMSCRIPTEN_PTHREADS__) + // A browser tells no performance cores from the others, and ggml starts its threads for each graph. Silero VAD + // F32 on a minute of audio, on an Apple M5 of 10 logical processors in Chrome 158 (2026-11-21): RTFx 520 on the + // first request and 1100 to 1500 on the fifth with 4 threads, and 100 and 700 to 1000 with 10. + return std::min(4, emscripten_num_logical_cores()); +#elif defined(__APPLE__) for (const char * key : {"hw.perflevel0.physicalcpu", "hw.physicalcpu"}) { int n = 0; size_t size = sizeof n; @@ -168,7 +176,11 @@ int default_threads() { } int max_threads() { -#if defined(__EMSCRIPTEN__) && !defined(__EMSCRIPTEN_PTHREADS__) +#if defined(__EMSCRIPTEN_PTHREADS__) + // The build with threads starts a Worker for each of the browser's logical processors before it runs, and a thread + // past them would wait for a Worker that cannot start while the module computes. + return std::max(1, emscripten_num_logical_cores()); +#elif defined(__EMSCRIPTEN__) return 1; #else return std::numeric_limits::max(); diff --git a/src/common/backend.h b/src/common/backend.h index 792f2d2..b08336b 100644 --- a/src/common/backend.h +++ b/src/common/backend.h @@ -30,13 +30,14 @@ ggml_backend_t start_device(ggml_backend_dev_t device, int threads); /** * The CPU threads the library computes with when the caller does not choose: the machine's performance cores, or its * physical cores where the system does not tell them apart, or its logical processors where it tells neither, up to - * max_threads(). + * max_threads(); in WebAssembly with threads, 4 or the browser's logical processors where they are fewer. */ int default_threads(); /** - * The most CPU threads this build can compute with: one in WebAssembly without threads, which starts none, and no limit - * elsewhere. ggml aborts the process when a thread it starts does not. + * The most CPU threads this build can compute with: one in WebAssembly without threads, which starts none, the + * browser's logical processors in WebAssembly with threads, and no limit elsewhere. ggml aborts the process when a + * thread it starts does not. */ int max_threads(); diff --git a/wasm/index.html b/wasm/index.html index 72fe585..980aaa0 100644 --- a/wasm/index.html +++ b/wasm/index.html @@ -12,7 +12,7 @@ p { margin: 0 0 1rem; color: var(--muted); } form { display: grid; gap: 0.75rem; margin-bottom: 1.5rem; } label { display: grid; gap: 0.25rem; font-weight: 600; } - input[type=text] { font: inherit; padding: 0.4rem; border: 1px solid var(--line); border-radius: 6px; background: transparent; color: inherit; } + input[type=text], input[type=number] { font: inherit; padding: 0.4rem; border: 1px solid var(--line); border-radius: 6px; background: transparent; color: inherit; } button { justify-self: start; font: inherit; padding: 0.45rem 1.2rem; border-radius: 6px; border: 1px solid var(--line); cursor: pointer; } button:disabled { cursor: default; opacity: 0.5; } #error { color: var(--error); white-space: pre-wrap; } @@ -29,6 +29,8 @@

speech.cpp in the browser

+ +

diff --git a/wasm/page.mjs b/wasm/page.mjs index 42cd5e5..b164dc7 100644 --- a/wasm/page.mjs +++ b/wasm/page.mjs @@ -1,13 +1,16 @@ // The page in index.html: finds the regions where someone speaks in a WAVE file with a detection model, both chosen by // the person, through speech.mjs in a Worker (worker.mjs), and shows the regions, the load time, the RTFx and the module's // memory. window.speechPage.run() does the same for a script, such as checks/smoke/wasm_browser_smoke.mjs, from URLs or -// Blobs: run({ model, audio: [...], threads, options }) loads the model once and detects in each audio in turn. A link -// with ?model=URL&audio=URL runs on those files as the page opens, as on a phone, where a script cannot reach the page. +// Blobs: run({ model, audio: [...], threads, threaded, options }) loads the model once and detects in each audio in +// turn, in the build with threads where `threaded` says, by default where more than one thread is asked for. A link with +// ?model=URL&audio=URL&threads=N runs on those files as the page opens, as on a phone, where a script cannot reach the +// page. The build with threads needs the page cross-origin isolated. const $ = (id) => document.getElementById(id); let worker = null; let opened = null; +let threaded = null; let next = 0; const waiting = new Map(); @@ -29,12 +32,17 @@ function answered({ data: { id, value, error } }) { reject(e); } -/** The Worker with the library loaded, started on first use. */ -function library() { +/** The Worker with the library loaded, the build with threads or the one without, started again for the other build. */ +function library(threads) { + if (opened && threaded !== threads) { + worker.terminate(); + opened = null; + } if (!opened) { worker = new Worker(new URL('./worker.mjs', import.meta.url), { type: 'module' }); worker.onmessage = answered; - opened = call('open'); + threaded = threads; + opened = call('open', { threads }); } return opened; } @@ -48,8 +56,8 @@ async function blobOf(source) { } /** Loads `model` and detects speech in each of `audio`, with the threads and the request options given. */ -async function runNow({ model, audio, threads, options = {} }) { - const open = await library(); +async function runNow({ model, audio, threads, threaded = threads > 1, options = {} }) { + const open = await library(threaded); const loaded = await call('load', { blob: await blobOf(model), threads }); const detections = []; for (const source of audio) detections.push(await call('detect', { blob: await blobOf(source), options })); @@ -75,6 +83,7 @@ function show(result) { $('version').textContent = `speech.cpp ${result.version}`; $('stats').replaceChildren(...[ ['Model', `${result.info.name} (${result.info.weight_type})`], + ['Threads', String(result.info.threads)], ['Load time', `${result.load.toFixed(1)} ms`], ['Audio', seconds(detection.seconds)], ['Detection', `${detection.ms.toFixed(1)} ms`], @@ -99,14 +108,14 @@ function show(result) { $('result').hidden = false; } -/** Runs on the model and audio given, or the files chosen, showing the result or the error. */ +/** Runs on the model and audio given, or the files chosen, with the threads chosen, showing the result or the error. */ async function detect({ model = $('model').files[0], audio = $('audio').files[0] } = {}) { $('error').hidden = true; $('detect').disabled = true; $('status').textContent = 'Detecting…'; try { const options = $('options').value.trim() ? JSON.parse($('options').value) : {}; - show(await run({ model, audio: [audio], options })); + show(await run({ model, audio: [audio], threads: Number($('threads').value), options })); } catch (e) { $('error').textContent = e.status ? `${e.status}${e.option ? ` (${e.option})` : ''}: ${e.message}` : e.message; $('error').hidden = false; @@ -126,5 +135,11 @@ $('form').addEventListener('submit', (event) => { ready(); window.speechPage = { run }; +$('threads').max = navigator.hardwareConcurrency; +$('isolation').textContent = crossOriginIsolated + ? `More than 1 runs the build with threads, up to this browser's ${navigator.hardwareConcurrency}.` + : 'This page is not cross-origin isolated, so it runs on 1 thread.'; +$('threads').disabled = !crossOriginIsolated; const linked = new URLSearchParams(location.search); +if (linked.has('threads')) $('threads').value = linked.get('threads'); if (linked.has('model') && linked.has('audio')) detect({ model: linked.get('model'), audio: linked.get('audio') }); diff --git a/wasm/serve.py b/wasm/serve.py new file mode 100644 index 0000000..86f428c --- /dev/null +++ b/wasm/serve.py @@ -0,0 +1,24 @@ +"""Serves the folder this file is in over HTTP on 127.0.0.1, with the headers that make a page cross-origin isolated +(Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy), which the build with threads needs to share its memory. + +usage: python3 serve.py [port] +""" + +import functools +import http.server +import os +import sys + + +class Handler(http.server.SimpleHTTPRequestHandler): + def end_headers(self): + self.send_header("Cross-Origin-Opener-Policy", "same-origin") + self.send_header("Cross-Origin-Embedder-Policy", "require-corp") + super().end_headers() + + +port = int(sys.argv[1]) if len(sys.argv) > 1 else 8000 +folder = os.path.dirname(os.path.abspath(__file__)) +with http.server.ThreadingHTTPServer(("127.0.0.1", port), functools.partial(Handler, directory=folder)) as server: + print(f"serving {folder} at http://127.0.0.1:{port}/") + server.serve_forever() diff --git a/wasm/speech.mjs b/wasm/speech.mjs index 4e3c861..cd540f9 100644 --- a/wasm/speech.mjs +++ b/wasm/speech.mjs @@ -1,12 +1,13 @@ // speech.cpp's C API in a Worker, over the library compiled to WebAssembly: libspeech.js and libspeech.wasm. A model is // read from a Blob or File through Emscripten's WORKERFS, which reads the file a piece at a time as the library asks for // it, so that the weights are held once, in the module's memory. Each call blocks until the library returns, as the C -// API's do, and WORKERFS reads with FileReaderSync, which a Worker alone has: the module runs in a Worker. +// API's do, and WORKERFS reads with FileReaderSync, which a Worker alone has: the module runs in a Worker. With threads +// it loads libspeech-threads.js and libspeech-threads.wasm instead. // // usage, in a module Worker: // import { openSpeech } from './speech.mjs'; -// const speech = await openSpeech(); -// const model = speech.load(file); // a Blob or File of a GGUF model +// const speech = await openSpeech(); // { threads: true } for the build with threads +// const model = speech.load(file, { threads: 4 }); // a Blob or File of a GGUF model // const regions = model.detect(samples, 16000, { threshold: 0.5 }); // [{ start, end }] in seconds // model.free(); @@ -23,9 +24,18 @@ export class SpeechError extends Error { } } -/** The library, loaded from libspeech.js beside this file, or from `url`. */ -export async function openSpeech({ url } = {}) { - const module = url ?? new URL('./libspeech.js', import.meta.url).href; +/** + * The library, loaded from libspeech.js beside this file, or libspeech-threads.js with `threads`, or from `url`. The + * build with threads shares its memory between Workers, which a browser allows only in a page that is cross-origin + * isolated, served with the headers Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: + * require-corp. + */ +export async function openSpeech({ threads = false, url } = {}) { + if (threads && !globalThis.crossOriginIsolated) { + throw new Error('the build with threads needs a page that is cross-origin isolated: serve it with the headers ' + + 'Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp'); + } + const module = url ?? new URL(threads ? './libspeech-threads.js' : './libspeech.js', import.meta.url).href; const { default: create } = await import(module); return new Speech(await create()); } diff --git a/wasm/worker.mjs b/wasm/worker.mjs index e89e5cd..ecb1702 100644 --- a/wasm/worker.mjs +++ b/wasm/worker.mjs @@ -1,7 +1,8 @@ // The Worker of the page in index.html: runs speech.mjs on the page's messages, one at a time, and answers each with -// its value or its error. A message is { id, op, ...arguments }: "open" loads the library; "load" loads a model from a -// Blob, freeing the one before; "detect" reads a WAVE Blob as `speech` reads the file and finds the regions where -// someone speaks. Each answer carries the milliseconds the library took and the bytes of its memory. +// its value or its error. A message is { id, op, ...arguments }: "open" loads the library, the build with threads or +// the one without; "load" loads a model from a Blob, freeing the one before; "detect" reads a WAVE Blob as `speech` +// reads the file and finds the regions where someone speaks. Each answer carries the milliseconds the library took and +// the bytes of its memory. import { openSpeech } from './speech.mjs'; import { readWav } from './wav.mjs'; @@ -9,9 +10,9 @@ let speech = null; let model = null; const ops = { - async open() { + async open({ threads }) { const start = performance.now(); - speech = await openSpeech(); + speech = await openSpeech({ threads }); return { version: speech.version, ms: performance.now() - start }; }, load({ blob, threads }) {