Run this model with HF Jobs
Run Roland2531/cosyvoice.cpp-AiTable-Vulkan-Windows-x64 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Roland2531/cosyvoice.cpp-AiTable-Vulkan-Windows-x64. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Roland2531/cosyvoice.cpp-AiTable-Vulkan-Windows-x64 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Roland2531/cosyvoice.cpp-AiTable-Vulkan-Windows-x64 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- CosyVoice
How to use Roland2531/cosyvoice.cpp-AiTable-Vulkan-Windows-x64 with CosyVoice:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Release 20261023-01: preserve nucleus during silent-token retries
Browse filesFiles changed (7)
- releases/20261023-01/CosyVoice-Vulkan-Windows-x64-20261023-01.zipAdded+3
- releases/20261023-01/README.mdAdded+33
- releases/20261023-01/SHA256SUMS.txtAdded+6
- releases/20261023-01/build-manifest-20261023-01.jsonAdded+35
- releases/20261023-01/fixes/apply-cosy-fixes-20261023-01.pyAdded+67
- releases/20261023-01/fixes/cosy-fixes-manifest-20261023-01.jsonAdded+79
- releases/20261023-01/fixes/cosy-native-fixes-20261023-01.patchAdded+1118
123version https://git-lfs.github.com/spec/v1oid sha256:06fd67e4d8d715ce324b7492359cd878e4b688359dbc2d11ce855e6f2ce8f27asize 108308323123456789101112131415161718192021222324252627282930313233# CosyVoice.cpp Windows Vulkan Runtime — 20261023-01
Community runtime based on Lourdle/cosyvoice.cpp v0.2.0, commit `67d45feb2f654bbc66cca25bff78464b3ec08fa1`, with native streaming, sampling and diagnostic extensions. Windows x64; tested with Radeon RX 9070 / Vulkan and CPU. This is not an upstream release or a model/voice download.
## Changes since 20261021-01
- Prepare the sampling nucleus once per logits state. Rejected silent draws reuse it instead of repeatedly applying in-place top-p normalization. Preserve cancellation, stop-token gating, bounded rejection and failure cleanup.- Retain the request progress and per-request diagnostic level APIs added after the previous release. Diagnostic levels are 0 essential, 1 P2/P3, 2 adds P0/P1, 3 performance tuning. This does not claim that all native diagnostic cost is removed at level 0.- Retain cumulative mel / quiet handoff streaming, text-buffer reset and optional dynamic adapter interfaces. No trained adapter is supplied.
## Install and run
Extract the full archive. Keep the EXEs and DLLs together in `runtime/`; do not mix GGML dependencies from other builds. A compatible Vulkan driver and Microsoft VC++ x64 runtime may be required. Python and the build toolchain are not needed to run these binaries.
Obtain a compatible model and reference separately from [upstream model downloads](https://huggingface.co/Lourdle/Fun-CosyVoice3-0.5B-2512-GGUF). Model and dependency licenses are separate.
```batruntime\cosyvoice-cli.exe --model "MODEL.gguf" --prompt-speech "REFERENCE.gguf" --mode cross-lingual --text "This is a short test." --output "test.wav" --backend vulkan0```
`--backend cpu` selects CPU inference. `--help` lists supported options. Frontend-only reference preparation requires the separately downloaded tokenizer/campplus ONNX assets.
## Validation and limitations
With a local F16 derivative and cached reference, one recovered native request failed in the previous core on all six attempts across two fresh process starts (113 accepted tokens, no PCM). The patched core produced finite, nonempty PCM on three attempts. In a three-segment sequence repeated three times, both cores succeeded and all nine corresponding PCM files were identical. Other tested seeds succeeded on nine attempts; these tests do not establish a general failure rate or a bad-seed blacklist. Strict seed was disabled, and historical context warm-up was not fully reconstructed.
This sampler correction is separate from the remaining streaming click/loudness investigation in [upstream Issue #36](https://github.com/Lourdle/cosyvoice.cpp/issues/36#issuecomment-6357547734). It is not an artifact-free audio or listening-quality guarantee. A genuine all-silent candidate distribution can still fail with a bounded error. F32 single-buffer allocation limits on AMD Vulkan are not fixed. No new throughput/RTF/VRAM ranking is claimed.
## Source patch
The `fixes/` directory contains a cumulative patch for the exact upstream v0.2.0 source above, a hash manifest and a Python application script. Use a separate LF checkout (`git -c core.autocrlf=false clone ...`, then checkout the pinned commit). The script defaults to checks only; `--apply` creates a backup and applies atomically, and rejects mismatched or already patched files. It does not compile, download models or start a service. Full source snapshots are not included; the patch is not a bit-for-bit build reproducibility guarantee.
Core SHA256: `29e4375ba73895e01da66cb857deb071392daf5fd7349aac4a2ebcef57b90ade`. Review `build-manifest-20261023-01.json`, the SHA256 list and bundled dependency licenses.123456b849c8d8fcc1e98f8bc8b79f9fea08d60e20b21b091316ad6c7f851a34e4e27a build-manifest-20261023-01.json06fd67e4d8d715ce324b7492359cd878e4b688359dbc2d11ce855e6f2ce8f27a CosyVoice-Vulkan-Windows-x64-20261023-01.zip6059bd172e331a38110ae82bc6daf7f4ac98531fde470ac9f7bc561e9cdf0a38 fixes/apply-cosy-fixes-20261023-01.pyc4cde529e9b7b4c9b36f31a801660cbae67d3c152c302260774400e53f0edd3d fixes/cosy-fixes-manifest-20261023-01.json79b4ffb616822e8cb3d54619c3d8d0c295908d953400582b55351f4957f49348 fixes/cosy-native-fixes-20261023-01.patch76d119bce5d1fe30c78929f380fb1751db9f7de5c10c0a3bd90c39b0e57be7b6 README.md1234567891011121314151617181920212223242526272829303132333435{ "release": "20261023-01", "upstream_commit": "67d45feb2f654bbc66cca25bff78464b3ec08fa1", "runtime_files": { "runtime/avcodec-62.dll": "13dae8e27fb521d7fe2f387ebc143a071fd1204d1b70ea21c303d292d2a4821c", "runtime/avdevice-62.dll": "5921b7e8d06cb63db9f41dcdc7b5db85ef81126f516a43b678ef3488dab9fea9", "runtime/avfilter-11.dll": "14210aaa0a6426c3b73a29bb81dfdd925d02f55262da9366f3cd0ee9359eb8f7", "runtime/avformat-62.dll": "de4edb05dd144bbe3232a70052b3a6b849f2f0ffa0e59b0e0cd919a2529c5367", "runtime/avutil-60.dll": "1c8cb40ef03d13aeae7603d1b7c21e0deb105346adbf6140edd15ae16c0b6628", "runtime/cosyvoice-cli.exe": "5bc5c3ee0fe74f367c1df1d9e3f0c032bd54d5955e8165d55627e7e5cb2718dd", "runtime/cosyvoice-server.exe": "8a102f3a5d3234b38f1bdd81004b0346c02d6acc524ae969eb076e20fd14956c", "runtime/cosyvoice.dll": "29e4375ba73895e01da66cb857deb071392daf5fd7349aac4a2ebcef57b90ade", "runtime/ggml-base.dll": "df7e8d4f935620e7bd6c4cc346786a7a778d6711cfcb1bdfd10c9db64d43d00f", "runtime/ggml-cpu-sse42.dll": "c71727180721f13785ffdd921c029be9f0d64b98e459d1779bfc27448f037bca", "runtime/ggml-cpu-x64.dll": "8fc299ed003cb64fec5c09e8bb02c2a9af7937e2087f7d8e8c7cee47738fbc32", "runtime/ggml-cpu-zen4.dll": "e11cb7bd2ac684a35a27a7500a7da31ae43ce1e2a96e1c47009ca3db472ed20b", "runtime/ggml-rpc.dll": "746cba70f9a7b873ccb80870b63df2d51a90cf843e57e55f7948da894b166cf2", "runtime/ggml-vulkan.dll": "1eefd2ca8347f0eb5fb29835d4deb596818381537a996cafe5a48b7136fcd082", "runtime/ggml.dll": "3113a27c04130a3623b308a6ce782099bf809376a4f4f025a8993b7e257ad30d", "runtime/icudt78.dll": "b937bcec6cbcab5891029d91e2e7a2f803cc2ce258a3546970d0284a528709d5", "runtime/icuin78.dll": "4d5ac61334757813f8ddf5c1ab5e28302ae2392d266450a187968aa66e164e7c", "runtime/icuio78.dll": "aafea4f5bd2cfefd734acb12cfccad1eef5f64f31c6854ff4048ca126d4c9005", "runtime/icutu78.dll": "0638be559795ecd358431e510e108b5c861c4a7a1f3fe6565732b4ec17e94881", "runtime/icuuc78.dll": "2566e47efc4fe7edc5ea6a333051ae522cd1cbeaf353ece5f3ac97e056e39c9a", "runtime/libomp.dll": "a12116ba72d1d6820407cf30be23da04ce79d6bb8a71a5ee71759c5a1faa6f1c", "runtime/onnxruntime.dll": "7e39e2bdbba836d98071ef28620735ba36a47c554cf794585269aecc50fab0da", "runtime/onnxruntime_providers_shared.dll": "b9b7ab9e2a8b08ee7ae4a7ac1c8bfd44a741f17ad8d0f764953140a57de0b796", "runtime/quantize.exe": "a208042c7dfc9153b66359f017f5e462302534314956114c4d9c7d516ce65375", "runtime/swresample-6.dll": "8dda56981dabeff97e0296d336d042e3312f5703ddef5117d5497dc1466c2cc9", "runtime/swscale-9.dll": "1f6ba4fa84bfd5ac371b7d8699bd53c86756bd0f69895dd03bf4a7871ecbccab" }, "patch_files": 18, "core_sha256": "29e4375ba73895e01da66cb857deb071392daf5fd7349aac4a2ebcef57b90ade", "validation": "Native request replay; see README. Not full live/HTTP/listening acceptance."}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""Check or apply the version-pinned version-pinned native patch. No build/start."""import argparseimport hashlibimport jsonfrom pathlib import Path, PurePosixPathimport shutilimport subprocessimport uuid
def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source', required=True, type=Path, help='Separate upstream source checkout; do not target installed runtimes') parser.add_argument('--apply', action='store_true', help='Apply after checks; default checks only') args = parser.parse_args() bundle = Path(__file__).resolve().parent manifest = json.loads((bundle / 'cosy-fixes-manifest-20261023-01.json').read_text(encoding='utf-8')) patch = bundle / 'cosy-native-fixes-20261023-01.patch' if digest(patch) != manifest['patch_sha256']: raise RuntimeError('Patch checksum mismatch') source = args.source.resolve(strict=True) if not source.is_dir(): raise RuntimeError('Source must be a directory') targets = {} for name, hashes in manifest['files'].items(): relative = PurePosixPath(name) if relative.is_absolute() or '..' in relative.parts or ':' in name or '\\' in name: raise RuntimeError('Unsafe manifest path: ' + name) target = source.joinpath(*relative.parts) if not target.resolve().is_relative_to(source) or target.is_symlink(): raise RuntimeError('Target escapes the source tree: ' + name) if target.exists() and not target.is_file(): raise RuntimeError('Target is not a regular file: ' + name) if digest(target) != hashes['before']: raise RuntimeError('Source differs from pinned upstream (or already patched): ' + name) targets[name] = target git_apply = ['git', '-c', 'core.autocrlf=false', '-c', 'apply.whitespace=nowarn', 'apply'] subprocess.run([*git_apply, '--check', str(patch)], cwd=source, check=True, timeout=30) if not args.apply: print('CHECK PASSED: upstream ' + manifest['upstream_commit'] + '; no files modified') return backup = source.parent / (source.name + '-aitable-backup-' + uuid.uuid4().hex) backup.mkdir() for name, target in targets.items(): if target.exists(): saved = backup / name saved.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(target, saved) (backup / 'restore-manifest.json').write_text(json.dumps({ 'source': str(source), 'files': manifest['files'], 'restore': 'Stop builds first. Restore saved files; remove only files whose before hash is null. Refuse to overwrite later changes unless verified.' }, indent=2), encoding='utf-8') print('BACKUP: ' + str(backup), flush=True) # Git apply is atomic by default; never pass --reject or allow partial application. subprocess.run([*git_apply, str(patch)], cwd=source, check=True, timeout=30) for name, target in targets.items(): if digest(target) != manifest['files'][name]['after']: raise RuntimeError('Post-apply checksum mismatch; inspect retained backup: ' + name) print('APPLIED AND VERIFIED. No compilation, model download or service start performed.')
if __name__ == '__main__': main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879{ "upstream_commit": "67d45feb2f654bbc66cca25bff78464b3ec08fa1", "patch_sha256": "79b4ffb616822e8cb3d54619c3d8d0c295908d953400582b55351f4957f49348", "files": { "CMakeLists.txt": { "before": "1885afffb9eb73a9dd969f918ad1c9c8baec59e6b3d7e74c2c3b8b9047990abb", "after": "8b39b9dd9c8c0ad84794cd3ba55e954ab61c1d78d98431a82c095dbb21b79c1c" }, "include/cosyvoice.h": { "before": "246b3337437a0d7de5f2bc18cba48449e2cf2a3f6050c81a3a90f3068bb1f176", "after": "62e1a28d6ea219e41cf1c556b7fa34dcc130d447afcc11d8fd031fb99ccb8371" }, "src/cosyvoice-diagnostics.h": { "before": null, "after": "1be0f35595a79f55a9240b996716953a8e8b55ea56b88ce86836c0a5b4c609d3" }, "src/cosyvoice-graph.cpp": { "before": "5225031cde4af043e4a6378ed54f018c27bbc656f61535f36ca9e464f5e723bb", "after": "96a5d60c52a8d57ac7c0255669f188145722465723bd91da8be52d00c3842e27" }, "src/cosyvoice-internal.h": { "before": "be9e76b81a3bc907e12d25c456653f6208cbeb71f9a442054e60be358bce3f3b", "after": "942cb468b9c59d326499ed8816cebdabe10c6f929eea20a06fc344018d38ccbe" }, "src/cosyvoice-kv-cache.cpp": { "before": "9b649cfd3fa1e218d020605513c321decf05b1f81ae9b0903886339e7fb56914", "after": "d1efc94e8b7a22099494e2f83f6a392c089358f2397ddbe259a86c80f6b73f63" }, "src/cosyvoice-llm-job.cpp": { "before": "2480ddc925ce1f715d600889943c056aa5fc3afecee98c11ba264aa4af8a1d94", "after": "6b84ce1991bd24598f2ed52fee21cfab3cc0cc6bcf2d5a32ea594d95b97514ea" }, "src/cosyvoice-llm.cpp": { "before": "1b020c86aa872bbe5b3dc2915074e9cab0b73019aef1eebc61bdc73d65e0f4f1", "after": "eba1933760e743ac315be232f876e473af48aedd3fd5e7f37e276605b2b3abc1" }, "src/cosyvoice-lora.cpp": { "before": null, "after": "184d469d00d737e45875b6a2589c65adde8e9efdc2effb459a0a5855df339b89" }, "src/cosyvoice-model.cpp": { "before": "cd6574ad2ee0ca4ea87e2f95a961c27c6cdee423ac592dfd62e51723886e56eb", "after": "cf43e07388cd75cb080b1853de64f8c82d4ba5d7fdbf51f43fd72d6811557208" }, "src/cosyvoice-model.h": { "before": "da76f096aa7c4c7b010e00411712bad1285d9815bde6472deac80c7249942dce", "after": "50aa9abd9a4674779ab85a2ad812535f57e9574c8f7d28a540319c1c3b5bd771" }, "src/cosyvoice-modules.h": { "before": "6fe4b0df465d264f0deb337dd1d4cda1b66b3263158c68b6c3b7d56aee7b5760", "after": "bc78f7a13ea1e20e88a97374f85493b4d8344a2720afe8a6d300fe58e77e3359" }, "src/cosyvoice-streaming-handoff.h": { "before": null, "after": "c217f96d7bf81fe7d9a75c1438b53716c30358cd35441f6688fcea2d5e08a597" }, "src/cosyvoice-token2wav.cpp": { "before": "6d680401c5b632bd9caaca356df0aad82a8d016e532640315d147e548b98a8f3", "after": "d347c3d4736f70fea0442e8a8263242a3ef2e400e67f91720da1f58d4803058f" }, "src/cosyvoice-tts.cpp": { "before": "aba9680e115b09a16f6c5d9d26319e43768058b2df31e1a98c0f45eb9f2826e4", "after": "1272a455c90055aab3313a6900c3bccc39946d178b9bd721dd51c73deb014423" }, "src/cosyvoice.cpp": { "before": "5f497e30aeb5a8a464695a002f3444c4d4c82c7c6456b8eadc3cb585d6ab4131", "after": "e18542597dfea23c7061c11ade028ca8c899b096a853d87e0b2ca7eb1fa46e54" }, "tools/server/aitable-progress-server.h": { "before": null, "after": "d638d49a930879094374c1c768485f08d13a0c8b6f5e6d1596038b6136b2dae1" }, "tools/server/cosyvoice-server-backend.cpp": { "before": "52f55e5178aff64093da9bc0df8b0fb2d8679ed5ec42df41eb40368863e9e43a", "after": "e074a47905a8325099b8090edc488d4629d630aaa8d4874ff086222f68eb879b" } }, "release": "20261023-01"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -399,9 +399,11 @@ # ----------------------------------------------------------------------------- # Tools (Executables) # -----------------------------------------------------------------------------+# Diagnostic library build: reuse the unchanged installed server executable.++# -----------------------------------------------------------------------------+# Post-Build & Installation Rules+# -----------------------------------------------------------------------------+include(cmake/Install.cmake)+ add_subdirectory(tools)--# ------------------------------------------------------------------------------# Post-Build & Installation Rules-# ------------------------------------------------------------------------------include(cmake/Install.cmake)--- a/include/cosyvoice.h+++ b/include/cosyvoice.h@@ -24,6 +24,14 @@ // ---------------------------------------------------------------------------- // Enumerations+// AiTable fixed rank-4/alpha-8 Q/V adapter. Caller verifies the exact base and+// factor container before this typed boundary. Status: 0 ok, 1 busy, 2 incompatible,+// 3 malformed/not-loaded, 4 allocation failed. Loading never enables the adapter.+// Factors: layers 0..23, q then v, A[4,896] then B[out,4], row-major FP32.+COSYVOICE_API int cosyvoice_lora_load_f32(struct cosyvoice_context* ctx, const float* factors, size_t count);+COSYVOICE_API int cosyvoice_lora_set_enabled(struct cosyvoice_context* ctx, bool enabled);+// State: 0 unloaded, 1 disabled, 2 enabled. generation changes only on a mode transition.+COSYVOICE_API int cosyvoice_lora_state(struct cosyvoice_context* ctx, uint64_t* generation, size_t* bytes); // ---------------------------------------------------------------------------- /**@@ -921,6 +929,21 @@ */ COSYVOICE_API bool cosyvoice_is_stop_requested(cosyvoice_context_t ctx); +// Optional metadata observer. The caller owns callback data until generation+// and all callbacks have ended; setting it never changes sampling or output.+typedef struct cosyvoice_progress {+ uint32_t stage, phase, worker, seed, thread_id;+ uint64_t samples, accepted, rejected_streak, kv_length, clock_ms;+ bool cancelled;+} cosyvoice_progress_t;+typedef void (*cosyvoice_progress_callback_t)(const cosyvoice_progress_t*, void*);+COSYVOICE_API void cosyvoice_set_progress_callback(cosyvoice_context_t ctx,+ cosyvoice_progress_callback_t callback, void* user_data);++// AiTable request-scoped diagnostics. False means invalid level/context or busy worker.+COSYVOICE_API bool cosyvoice_set_debug_level(cosyvoice_context_t ctx,uint32_t level);+COSYVOICE_API uint32_t cosyvoice_get_debug_level(cosyvoice_context_t ctx);+ #ifdef __cplusplus } #endif--- /dev/null+++ b/src/cosyvoice-diagnostics.h@@ -0,0 +1,40 @@+// Request-owned diagnostic budget. No TLS: native jobs can cross threads.+#pragma once+#include <atomic>+#include <cstdio>+#include <chrono>+namespace aitable_tts_diag {+struct state {+ std::atomic<unsigned> level{0};+ std::atomic<unsigned> remaining{0};+ void configure(unsigned value) noexcept {+ remaining.store(value >= 2 ? 128 : 0, std::memory_order_relaxed);+ level.store(value, std::memory_order_release);+ }+ bool enabled() const noexcept { return level.load(std::memory_order_acquire) >= 2; }+ bool take() noexcept {+ if (!enabled()) return false;+ unsigned n=remaining.load(std::memory_order_relaxed);+ while (n && !remaining.compare_exchange_weak(n,n-1,std::memory_order_relaxed)) {}+ return n!=0;+ }+};+inline void mark(state& owner,const char* stage,int count=-1,int worker=-1) noexcept {+ // Return before reading the clock, formatting, counters or stdio.+ if (!owner.take()) return;+ const auto ms=static_cast<unsigned long long>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count());+ char line[192];+ if (count>=0 && worker>=0)+ std::snprintf(line,sizeof(line),"[AITABLE_TTS_STAGE] stage=%s count=%d worker=%d clock_ms=%llu\n",stage,count,worker,ms);+ else if (worker>=0)+ std::snprintf(line,sizeof(line),"[AITABLE_TTS_STAGE] stage=%s worker=%d clock_ms=%llu\n",stage,worker,ms);+ else+ std::snprintf(line,sizeof(line),"[AITABLE_TTS_STAGE] stage=%s clock_ms=%llu\n",stage,ms);+ std::fputs(line,stderr);std::fflush(stderr);+}+struct scope {+ state& owner;const char* end;int worker;+ scope(state& s,const char* begin,const char* end,int worker=-1) noexcept:owner(s),end(end),worker(worker) {mark(owner,begin,-1,worker);}+ ~scope(){mark(owner,end,-1,worker);}+};+}--- a/src/cosyvoice-graph.cpp+++ b/src/cosyvoice-graph.cpp@@ -244,6 +244,9 @@ ggml_tensor* Linear::build_cgraph(ggml_context* ctx, ggml_tensor* x) const { auto out = ggml_mul_mat(ctx, weight, x);+ if (lora_enabled && *lora_enabled)+ out = ggml_add(ctx, out, ggml_scale(ctx,+ ggml_mul_mat(ctx, lora_b, ggml_mul_mat(ctx, lora_a, x)), 2.f)); if (bias) out = ggml_add(ctx, out, bias); return out;--- a/src/cosyvoice-internal.h+++ b/src/cosyvoice-internal.h@@ -1,3 +1,4 @@+#include <shared_mutex> #pragma once #if defined(_WIN32) && !defined(COSYVOICE_STATIC)@@ -150,6 +151,9 @@ struct use_count_guard { cosyvoice_worker_context* worker;+ void* adapter_owner = nullptr;+ std::shared_lock<std::shared_mutex> adapter_read;+ void protect_adapter(cosyvoice_model* model); use_count_guard(cosyvoice_context* ctx); use_count_guard(cosyvoice_model* model);--- a/src/cosyvoice-kv-cache.cpp+++ b/src/cosyvoice-kv-cache.cpp@@ -251,8 +251,8 @@ { size_t nbytes = 0; auto object_size = get_offloaded_kv_cache_struct_size(layers);- for (auto i = 0; i != layers; ++i)- nbytes += advance_ptr(offloaded_cache, object_size)->buffer.capacity();+ for (int i = 0; i != n_offloaded_kv_slots; ++i)+ nbytes += advance_ptr(offloaded_cache, object_size * i)->buffer.capacity(); return nbytes; } else return 0;@@ -262,11 +262,13 @@ { if (offloaded_cache) {- ggml_free(offloaded_cache->ctx); auto object_size = get_offloaded_kv_cache_struct_size(layers);- for (auto i = 0; i != layers; ++i)- {- auto cur = advance_ptr(offloaded_cache, object_size);+ // Invalidate each allocated offload slot; contexts remain owned until+ // destruction and are reused by subsequent prefill/offload operations.+ for (int i = 0; i != n_offloaded_kv_slots; ++i)+ {+ auto cur = advance_ptr(offloaded_cache, object_size * i);+ ggml_reset(cur->ctx); std::vector<char>().swap(cur->buffer); cur->len = 0; }--- a/src/cosyvoice-llm-job.cpp+++ b/src/cosyvoice-llm-job.cpp@@ -1,3 +1,4 @@+#include "cosyvoice-diagnostics.h" #include "cosyvoice-internal.h" #include "cosyvoice-model.h" @@ -16,6 +17,8 @@ bool cosyvoice_model_3::llm_job_ext(const int* text, uint32_t text_len, cosyvoice_prompt_t prompt, uint32_t max_new_tokens, bool* final) { use_count_guard _guard(this);+ aitable_tts_diag::scope diagnostic(worker->diagnostic, "llm_begin", "llm_end", get_worker_no());+ cosyvoice_progress_scope progress_scope(worker,4); const auto& params = shared->params; auto& sched = worker->sched; const auto& llm = cv3_shared->llm;@@ -144,9 +147,29 @@ constexpr uint32_t max_silent_token_num = 5; const auto& silent_tokens = cv3_shared->silent_tokens; + // Rejected samples keep the current logits/KV unchanged. Bound draws+ // on that unchanged state separately from the accepted-token budget.+ // Use the current generation limit, widened before adding its existing+ // two-draw termination envelope; successful acceptance resets retries.+ const uint64_t silent_resample_limit = static_cast<uint64_t>(limit) + 2;+ uint64_t silent_resamples = 0; for (uint32_t n = llm_get_n_accepted_tokens();; ++n) {- llm_prepare_probs(n > min_len);+ if (is_stop_requested())+ {+ worker->llm_input = nullptr;+ cosyvoice_call_ggml_log_callback(GGML_LOG_LEVEL_INFO, "LLM generation stopped by user.\n");+ if (params.builtin_sampler_rng_policy == COSYVOICE_BUILTIN_SAMPLER_RNG_POLICY_RESET_PER_SESSION)+ reset_builtin_sampler_rng();+ return false;+ }++ if (worker->progress_callback) ++worker->progress.samples;+ cosyvoice_report_progress(worker,2,3);+ // Rejected silent draws do not decode or refresh logits. Prepare+ // once per logits state; repeated normalization shrinks the nucleus.+ if (silent_resamples == 0)+ llm_prepare_probs(n > min_len); const auto token_id = llm_sample_token(); if (token_id == -1) throw std::runtime_error("Failed to sample token from LLM output. This might be wrong with the model or caused by an issue with the sampling parameters.\n");@@ -161,10 +184,13 @@ ++cur_silent_token_num; if (cur_silent_token_num > max_silent_token_num) {- // Drop excess silent tokens — the token is already in the- // KV cache (from llm_decode), so update cur to keep the- // model state consistent, but skip llm_accept_token so- // it does not appear in the output.+ // Re-sample the current logits without accepting this token.+ // No decode has consumed this sampled token yet. Cancellation+ // and a consecutive rejection budget bound this path.+ if (worker->progress_callback) worker->progress.rejected_streak=silent_resamples+1;+ cosyvoice_report_progress(worker,2,3);+ if (++silent_resamples >= silent_resample_limit)+ throw std::runtime_error("LLM consecutive silent resampling limit exceeded.\n"); cur = speech_emb + token_id * speech_row_size; --n; continue;@@ -173,7 +199,10 @@ else cur_silent_token_num = 0; + silent_resamples = 0;+ if (worker->progress_callback) worker->progress.rejected_streak=0; llm_accept_token(token_id);+ cosyvoice_report_progress(worker,2,3); if (is_stop_requested()) {--- a/src/cosyvoice-llm.cpp+++ b/src/cosyvoice-llm.cpp@@ -169,7 +169,9 @@ worker->probs.get(), 0, sizeof(float) * cv3_shared->llm.llm_decoder.weight->ne[1]);+ cosyvoice_report_progress(worker,7); ggml_backend_synchronize(backend);+ cosyvoice_report_progress(worker,8); } bool cosyvoice_model_3::llm_prefill(@@ -178,6 +180,7 @@ uint32_t n_tokens ) {+ cosyvoice_progress_scope progress_scope(worker,1); auto kv_cache = &worker->llm_kv_cache; auto total_len = n_tokens + kv_cache->cur_len; if (total_len > shared->params.n_max_seq - 1) return false;@@ -280,7 +283,9 @@ kv_cache->cur_len += n_tokens; } + cosyvoice_report_progress(worker,5); worker->status = ggml_backend_sched_graph_compute(worker->sched.get(), gf);+ cosyvoice_report_progress(worker,6); return worker->status == GGML_STATUS_SUCCESS; } @@ -291,6 +296,7 @@ ) { if (n_tokens == 1) return llm_decode(type, data);+ cosyvoice_progress_scope progress_scope(worker,1); auto kv_cache = &worker->llm_kv_cache; auto total_len = n_tokens + kv_cache->cur_len;@@ -356,7 +362,9 @@ kv_cache->set_input_v_idxs(worker->backend.get(), shared->full_position_ids.get() + kv_cache->cur_len, n_tokens, n_tokens); ggml_backend_tensor_set_async(worker->backend.get(), llm_input, data, 0, ggml_nbytes(llm_input)); kv_cache->cur_len += n_tokens;+ cosyvoice_report_progress(worker,5); worker->status = ggml_backend_sched_graph_compute(worker->sched.get(), gf);+ cosyvoice_report_progress(worker,6); if (worker->status == GGML_STATUS_SUCCESS) { fetch_llm_probs(worker, shared, cv3_shared);@@ -367,6 +375,7 @@ bool cosyvoice_model_3::llm_decode(ggml_type type, const void* data) {+ cosyvoice_progress_scope progress_scope(worker,2); auto kv_cache = &worker->llm_kv_cache; if (kv_cache->cur_len + 1 > shared->params.n_max_seq) return false; @@ -428,7 +437,9 @@ ++kv_cache->cur_len; } + cosyvoice_report_progress(worker,5); worker->status = ggml_backend_sched_graph_compute(worker->sched.get(), gf);+ cosyvoice_report_progress(worker,6); if (worker->status == GGML_STATUS_SUCCESS) { fetch_llm_probs(worker, shared, cv3_shared);--- /dev/null+++ b/src/cosyvoice-lora.cpp@@ -0,0 +1,82 @@+#include "cosyvoice-model.h"+#include <algorithm>+#include <cmath>+#include <span>+#include <cstdio>++extern bool aitable_adapter_read_owned(void* owner);+namespace {+constexpr size_t factor_count = 270336;+void invalidate(cosyvoice_model_3* model) {+ // All workers are idle under the exclusive adapter gate. No model weights+ // or noise state are changed; prefill and decode graphs must see the mode.+ for (uint32_t i=0; i<model->shared->params.n_workers; ++i) {+ auto& w=model->workers[i];+ ggml_backend_synchronize(w.backend.get());+ ggml_backend_sched_reset(w.sched.get());+ w.gf=nullptr; w.llm_input=nullptr; w.llm_probs=nullptr;+ w.prompt_crc32=0; w.llm_kv_cache.cur_len=0;+ w.llm_kv_cache.clear_offloaded_cache();+ }+}+}+int cosyvoice_lora_load_f32(cosyvoice_context* ctx,const float* data,size_t count) {+ auto* model=dynamic_cast<cosyvoice_model_3*>(ctx);+ if (!model || !data || count!=factor_count) return 3;+ auto& state=*model->cv3_shared;+ std::unique_lock gate(model->shared->adapter_mutex,std::try_to_lock);+ if (!gate.owns_lock()) return 1;+ if (state.lora_buffer || state.llm.layers.size()!=24) return 2;+ if (!std::all_of(data,data+count,[](float f){return std::isfinite(f);})) return 3;+ for (auto& layer:state.llm.layers) {+ auto* q=layer.self_attn.q_proj.weight;auto* v=layer.self_attn.v_proj.weight;+ if (!q || !v || q->type!=GGML_TYPE_F16 || v->type!=GGML_TYPE_F16 ||+ q->ne[0]!=896 || q->ne[1]!=896 || v->ne[0]!=896 || v->ne[1]!=128) return 2;+ }+ try {+ ggml_context_ptr storage(ggml_init({ggml_tensor_overhead()*100, nullptr, true}));+ if (!storage) return 4;+ std::vector<std::pair<ggml_tensor*,ggml_tensor*>> tensors;+ for (int i=0;i<24;++i) for(int output:{896,128}) {+ tensors.emplace_back(ggml_new_tensor_2d(storage.get(),GGML_TYPE_F32,896,4),+ ggml_new_tensor_2d(storage.get(),GGML_TYPE_F32,4,output));+ }+ ggml_backend_buffer_ptr buffer(ggml_backend_alloc_ctx_tensors(storage.get(),model->worker->backend.get()));+ if (!buffer) return 4;+ size_t offset=0;+ for (auto [a,b]:tensors) {+ for (auto* tensor:{a,b}) {+ auto bytes=ggml_nbytes(tensor);+ ggml_backend_tensor_set(tensor,data+offset,0,bytes); offset+=bytes/sizeof(float);+ }+ }+ // Commit only after every tensor is allocated and uploaded.+ state.lora_ctx=std::move(storage);state.lora_buffer=std::move(buffer);+ size_t index=0;+ for(auto& layer:state.llm.layers) for(auto* linear:{&layer.self_attn.q_proj,&layer.self_attn.v_proj}) {+ auto [a,b]=tensors[index++];linear->lora_a=a;linear->lora_b=b;+ linear->lora_enabled=&state.lora_enabled;+ }+ return 0;+ } catch(const std::bad_alloc&) {return 4;}+}+int cosyvoice_lora_set_enabled(cosyvoice_context* ctx,bool enabled) {+ auto* model=dynamic_cast<cosyvoice_model_3*>(ctx);if(!model)return 2;+ std::unique_lock gate(model->shared->adapter_mutex,std::try_to_lock);+ if(!gate.owns_lock())return 1;+ auto& state=*model->cv3_shared;+ if(enabled && !state.lora_buffer)return 3;+ if(enabled==state.lora_enabled)return 0;+ invalidate(model);+ state.lora_enabled=enabled;++state.lora_generation;+ return 0;+}+int cosyvoice_lora_state(cosyvoice_context* ctx,uint64_t* generation,size_t* bytes) {+ auto* model=dynamic_cast<cosyvoice_model_3*>(ctx);if(!model)return -1;+ std::shared_lock<std::shared_mutex> gate;+ if(!aitable_adapter_read_owned(model->shared))gate=std::shared_lock(model->shared->adapter_mutex);+ auto& state=*model->cv3_shared;+ if(generation)*generation=state.lora_generation;+ if(bytes)*bytes=state.lora_buffer?ggml_backend_buffer_get_size(state.lora_buffer.get()):0;+ return !state.lora_buffer?0:state.lora_enabled?2:1;+}--- a/src/cosyvoice-model.cpp+++ b/src/cosyvoice-model.cpp@@ -1,3 +1,4 @@+#include "cosyvoice-diagnostics.h" #include "cosyvoice-model.h" #include "common.h" @@ -557,13 +558,17 @@ worker->stop_flag.store(true, std::memory_order_release); { std::unique_lock<std::mutex> lock(worker->cv_mutex);+ aitable_tts_diag::mark(worker->diagnostic, "stop_wait_begin", static_cast<int>(worker->use_count.load(std::memory_order_acquire)), get_worker_no()); worker->cv.wait(lock, [this]() { return worker->use_count.load(std::memory_order_acquire) == 0; });+ aitable_tts_diag::mark(worker->diagnostic, "stop_wait_end", static_cast<int>(worker->use_count.load(std::memory_order_acquire)), get_worker_no()); } cleanup: worker->offset = 0;+ worker->flow_cache.clear();+ worker->chunk_boundaries.clear(); worker->stop_flag.store(false, std::memory_order_release); } @@ -603,3 +608,44 @@ ggml_backend_sched_reset(sched); kv_cache.load_cache(worker->backend.get(), sched); }++#include <chrono>+#if defined(_WIN32)+#ifndef NOMINMAX+#define NOMINMAX+#endif+#include <windows.h>+#elif defined(__linux__)+#include <unistd.h>+#include <sys/syscall.h>+#endif++void cosyvoice_model::set_progress_callback(cosyvoice_progress_callback_t callback, void* user_data)+{+ worker->progress_callback=callback;+ worker->progress_user_data=user_data;+ worker->progress={};+ worker->progress.worker=get_worker_no();+ cosyvoice_report_progress(worker,1);+}++void cosyvoice_report_progress(cosyvoice_worker_context* worker, uint32_t stage, uint32_t phase) noexcept+{+ if (!worker->progress_callback) return;+ auto& p=worker->progress;+ p.stage=stage;+ if (phase) p.phase=phase;+ p.seed=worker->sampler_seed;+ p.accepted=worker->tokens.size();+ p.kv_length=worker->llm_kv_cache.cur_len;+ p.cancelled=worker->stop_flag.load(std::memory_order_acquire);+ p.clock_ms=std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();+#if defined(_WIN32)+ p.thread_id=GetCurrentThreadId();+#elif defined(__linux__)+ p.thread_id=static_cast<uint32_t>(syscall(SYS_gettid));+#else+ p.thread_id=0;+#endif+ worker->progress_callback(&p,worker->progress_user_data);+}--- a/src/cosyvoice-model.h+++ b/src/cosyvoice-model.h@@ -1,6 +1,7 @@ #pragma once #include "cosyvoice-modules.h"+#include "cosyvoice-diagnostics.h" #include "cosyvoice-lowlevel.h" #include "cosyvoice-interface.h" #include "cosyvoice-kv-cache.h"@@ -30,6 +31,7 @@ std::mt19937 noise_rng; std::shared_mutex noise_mutex;+ std::shared_mutex adapter_mutex; std::unique_ptr<float[]> rand_noise; uint32_t rand_noise_len; cosyvoice_generation_config_t config;@@ -68,6 +70,9 @@ ggml_status status; uint32_t prompt_crc32; uint32_t sampler_seed;+ cosyvoice_progress_callback_t progress_callback = nullptr;+ void* progress_user_data = nullptr;+ cosyvoice_progress_t progress = {}; cosyvoice_generation_config_t config; cosyvoice_sampler_t sampler; void* sampler_ctx;@@ -85,6 +90,7 @@ ggml_backend_buffer_ptr llm_kv_buffer; ggml_backend_buffer_ptr dit_kv_buffer; + aitable_tts_diag::state diagnostic; std::atomic<bool> stop_flag{false}; std::atomic<int> use_count{0}; std::mutex cv_mutex;@@ -98,6 +104,7 @@ virtual void load(gguf_loader& loader) = 0; + void set_progress_callback(cosyvoice_progress_callback_t callback, void* user_data); uint32_t get_worker_no(); uint32_t get_n_workers(); void request_stop();@@ -153,6 +160,10 @@ struct cosyvoice_model_3_shared {+ ggml_context_ptr lora_ctx;+ ggml_backend_buffer_ptr lora_buffer;+ bool lora_enabled = false;+ uint64_t lora_generation = 0; CausalMaskedDiffWithDiT flow; CausalHiFTGenerator hift; CosyVoice3LM llm;@@ -168,6 +179,7 @@ ggml_context_ptr ctx1; ggml_backend_buffer_ptr token2wav_buffer;+ uint32_t committed_speech_samples = 0; }; struct cosyvoice_model_3 : cosyvoice_model@@ -208,3 +220,10 @@ cosyvoice_3_worker_context* cv3_workers; cosyvoice_3_worker_context* cv3_worker; };++void cosyvoice_report_progress(cosyvoice_worker_context*, uint32_t stage, uint32_t phase = 0) noexcept;+struct cosyvoice_progress_scope {+ cosyvoice_worker_context* worker; uint32_t phase;+ cosyvoice_progress_scope(cosyvoice_worker_context* w, uint32_t p) noexcept : worker(w),phase(p) { cosyvoice_report_progress(worker,3,phase); }+ ~cosyvoice_progress_scope() { cosyvoice_report_progress(worker,4,phase); }+};--- a/src/cosyvoice-modules.h+++ b/src/cosyvoice-modules.h@@ -35,6 +35,10 @@ struct Linear : BasicModule {+ // Optional low-rank branch. Disabled means the original graph, not scale zero.+ ggml_tensor* lora_a = nullptr;+ ggml_tensor* lora_b = nullptr;+ const bool* lora_enabled = nullptr; ggml_tensor* build_cgraph(ggml_context* ctx, ggml_tensor* x) const; }; --- /dev/null+++ b/src/cosyvoice-streaming-handoff.h@@ -0,0 +1,30 @@+#pragma once+#include <algorithm>+#include <cstdint>+#include <limits>+#include <span>+#include <stdexcept>++namespace cosyvoice_streaming {+// Select only from the currently available prefix. Uncommitted samples are+// taken from the next cumulative HiFT result; finalization emits everything.+inline uint32_t commit_end(std::span<const float> wave, uint32_t prior, uint32_t rate, bool finalize) {+ if (wave.size() > std::numeric_limits<uint32_t>::max() || wave.size() < prior)+ throw std::runtime_error("CosyVoice streaming prefix regressed or exceeded sample capacity");+ const auto end = static_cast<uint32_t>(wave.size());+ if (finalize) return end;+ const uint32_t half = std::max(1u,rate/100), min_hold = std::max(1u,rate/50);+ const uint32_t max_hold = std::max(1u,rate/4), stride = std::max(1u,rate/1000);+ // Short prefixes cannot provide a complete energy window. Preserve the+ // existing available output rather than inventing silence or dropping it.+ if (end <= max_hold || static_cast<uint64_t>(prior)+half+min_hold > end) return end;+ uint32_t selected = end;+ double best = std::numeric_limits<double>::infinity();+ for (uint32_t j = std::max(prior+half,end-max_hold); j <= end-min_hold; j+=stride) {+ double energy=0;+ for (uint32_t k=j-half;k<j+half;++k) { const double x=wave[k]; energy+=x*x; }+ if (energy<best) { best=energy; selected=j; }+ }+ return selected;+}+}--- a/src/cosyvoice-token2wav.cpp+++ b/src/cosyvoice-token2wav.cpp@@ -1,3 +1,5 @@+#include "cosyvoice-streaming-handoff.h"+#include "cosyvoice-diagnostics.h" #include "cosyvoice-internal.h" #include "cosyvoice-model.h" #include "ggml-cpu-flag.h"@@ -223,6 +225,7 @@ kv_cache->cur_len = 0; worker->chunk_boundaries.clear(); worker->flow_cache.clear();+ cv3_worker->committed_speech_samples = 0; } ggml_reset(ctx0.get());@@ -289,6 +292,7 @@ else full_len = seq_len; + aitable_tts_diag::mark(worker->diagnostic, "flow_begin", -1, get_worker_no()); float* noise_buffer = shared->noise_callback(COSYVOICE_NOISE_CALLBACK_STAGE_BEFORE_FLOW, noise_req, nullptr, shared->noise_callback_ctx); ggml_backend_tensor_set_async(backend.get(), ditctx.x, noise_buffer + noise_req - noise_len, 0, ditctx.x->nb[2]); @@ -357,6 +361,7 @@ load_kv(0); worker->status = ggml_backend_sched_graph_compute(sched.get(), gf);+ aitable_tts_diag::mark(worker->diagnostic, "flow_first_step_end", -1, get_worker_no()); shared->noise_callback(COSYVOICE_NOISE_CALLBACK_STAGE_AFTER_FLOW, noise_req, noise_buffer, shared->noise_callback_ctx); if (params.inference_buffer_policy != COSYVOICE_INFERENCE_BUFFER_POLICY_DEDICATED) llm_set_kv_cache_len(0);@@ -455,6 +460,9 @@ // Phase 3: Copy flow output to speech_feat (persistent buffer) ggml_reset(ctx1.get()); const auto cache_length = streaming ? static_cast<int64_t>(worker->flow_cache.size() / feat->ne[0]) : 0;+ // The cumulative mel history is bounded by this context's existing token capacity.+ if (streaming && feat->ne[1] + cache_length > static_cast<int64_t>(params.n_max_seq) * flow.token_mel_ratio)+ throw std::runtime_error("CosyVoice streaming mel exceeds context capacity"); ggml_tensor* speech_feat = ggml_new_tensor_2d(ctx1.get(), feat->type, feat->ne[0], feat->ne[1] + cache_length); if (cache_length != 0) {@@ -478,20 +486,12 @@ ggml_backend_tensor_copy_async(backend.get(), backend.get(), feat, speech_feat); } - if (streaming && !finalize)- {- const auto overlap = static_cast<int64_t>(shared->hift_overlap);- const auto n_feat_frames = feat->ne[1];- const auto frames_to_keep = std::min(overlap, n_feat_frames);- const auto elements_to_keep = static_cast<size_t>(frames_to_keep * feat->ne[0]);-- worker->flow_cache.resize(elements_to_keep);- if (frames_to_keep > 0)- {- const auto byte_offset = static_cast<size_t>((n_feat_frames - frames_to_keep) * feat->nb[1]);- const auto byte_size = static_cast<size_t>(frames_to_keep * feat->nb[1]);- ggml_backend_tensor_get_async(backend.get(), feat, worker->flow_cache.data(), byte_offset, byte_size);- }+ if (streaming && !finalize) {+ // Complete input copies before vector growth can invalidate their source.+ ggml_backend_synchronize(backend.get());+ worker->flow_cache.resize(ggml_nelements(speech_feat));+ ggml_backend_tensor_get_async(backend.get(), speech_feat, worker->flow_cache.data(), 0, speech_feat->nb[2]);+ ggml_backend_synchronize(backend.get()); } if (config[flow.decoder.diffusion_steps - 1].cache_kv)@@ -529,13 +529,24 @@ hift.f0_predictor.condnet_0.output_length(speech_feat->ne[0], finalize), true), true), true), true) * hift.scale_factor * noise->ne[0]); noise_req = std::max(noise_req, noise_len);+ aitable_tts_diag::mark(worker->diagnostic, "flow_end", -1, get_worker_no());+ aitable_tts_diag::mark(worker->diagnostic, "hift_begin", -1, get_worker_no()); noise_buffer = shared->noise_callback(COSYVOICE_NOISE_CALLBACK_STAGE_BEFORE_HIFT, noise_req, nullptr, shared->noise_callback_ctx); ggml_backend_tensor_set_async(backend.get(), noise, noise_buffer + noise_req - noise_len, 0, noise->nb[2]); result->data = reinterpret_cast<float*>(generated_speech->data); result->length = static_cast<uint32_t>(generated_speech->ne[0]); worker->status = ggml_backend_sched_graph_compute(sched.get(), gf);+ aitable_tts_diag::mark(worker->diagnostic, "hift_end", -1, get_worker_no()); shared->noise_callback(COSYVOICE_NOISE_CALLBACK_STAGE_AFTER_HIFT, noise_req, noise_buffer, shared->noise_callback_ctx); + if (worker->status == GGML_STATUS_SUCCESS && streaming) {+ const auto prior = cv3_worker->committed_speech_samples;+ const auto end = cosyvoice_streaming::commit_end(std::span<const float>(result->data,result->length),prior,get_sample_rate(),finalize);+ result->data += prior;+ result->length = end-prior;+ cv3_worker->committed_speech_samples = finalize ? 0 : end;+ if (finalize) worker->flow_cache.clear();+ } return worker->status == GGML_STATUS_SUCCESS; }--- a/src/cosyvoice-tts.cpp+++ b/src/cosyvoice-tts.cpp@@ -1,4 +1,6 @@-#include "cosyvoice-internal.h"+#include "cosyvoice-diagnostics.h"+#include "cosyvoice-internal.h"+#include "cosyvoice-model.h" #include "cosyvoice-text-chunk.h" #include <algorithm>@@ -45,6 +47,7 @@ static inline bool strip_emoji(std::string_view text, std::string& result) {+ result.clear();
result.reserve(text.size()); bool removed = false; bool prev_emoji = false;@@ -103,6 +106,7 @@ bool tts_job(const char* text, const char* instruction, float speed, cosyvoice_inference_mode mode, cosyvoice_generated_speech_ptr result, cosyvoice_tts_audio_callback_t callback, void* user_data) {+ aitable_tts_diag::scope diagnostic(dynamic_cast<cosyvoice_model*>(ctx)->worker->diagnostic,"high_level_enter", "high_level_return"); instruction_cache.resize(prefix_len); if (instruction) {--- a/src/cosyvoice.cpp+++ b/src/cosyvoice.cpp@@ -1,3 +1,4 @@+#include "cosyvoice-diagnostics.h" #include "cosyvoice-internal.h" #include "cosyvoice-tokenizer.h" #include "cosyvoice-model.h"@@ -25,8 +26,24 @@ return dist(gen); } +// Nested LLM/Flow guards run on the same host thread as the outer TTS guard.+// Share its reader rather than recursively locking std::shared_mutex.+static thread_local std::vector<void*> adapter_readers;+bool aitable_adapter_read_owned(void* owner) { return std::find(adapter_readers.begin(),adapter_readers.end(),owner)!=adapter_readers.end(); }+void use_count_guard::protect_adapter(cosyvoice_model* model)+{+ auto owner = static_cast<void*>(model->shared);+ if (std::find(adapter_readers.begin(), adapter_readers.end(), owner) == adapter_readers.end())+ {+ adapter_read = std::shared_lock(model->shared->adapter_mutex);+ adapter_readers.push_back(owner);+ adapter_owner = owner;+ }+}+ use_count_guard::use_count_guard(cosyvoice_model* model) : worker(model->worker) {+ protect_adapter(model); worker->use_count.fetch_add(1, std::memory_order_relaxed); } @@ -34,18 +51,22 @@ { auto* model = dynamic_cast<cosyvoice_model*>(ctx); worker = model->worker;+ protect_adapter(model); if(worker->use_count.load(std::memory_order_acquire) != 0) { std::unique_lock<std::mutex> lock(worker->cv_mutex);+ aitable_tts_diag::mark(worker->diagnostic, "guard_wait_begin", static_cast<int>(worker->use_count.load(std::memory_order_acquire)), model->get_worker_no()); worker->cv.wait(lock, [this]() { return worker->use_count.load(std::memory_order_acquire) == 0; });+ aitable_tts_diag::mark(worker->diagnostic, "guard_wait_end", static_cast<int>(worker->use_count.load(std::memory_order_acquire)), model->get_worker_no()); } worker->use_count.fetch_add(1, std::memory_order_relaxed); } use_count_guard::~use_count_guard() {+ if (adapter_owner) adapter_readers.pop_back(); if (worker->use_count.fetch_sub(1, std::memory_order_release) == 1) worker->cv.notify_all(); }@@ -480,7 +501,7 @@ goto cleanup; if (result.data && result.length > 0- && !callback(result.data, result.length, user_data))+ && (aitable_tts_diag::mark(dynamic_cast<cosyvoice_model*>(ctx)->worker->diagnostic, "pcm_callback"), !callback(result.data, result.length, user_data))) goto cleanup; } while (n_tokens != ctx->llm_get_n_accepted_tokens()); @@ -732,3 +753,22 @@ f.write(reinterpret_cast<const char*>(data), static_cast<std::streamsize>(sizeof(float) * data_len)); return f.good(); }++void cosyvoice_set_progress_callback(cosyvoice_context_t ctx, cosyvoice_progress_callback_t callback, void* user_data)+{+ dynamic_cast<cosyvoice_model*>(ctx)->set_progress_callback(callback,user_data);+}++// Set only while this worker is idle; the server's slot lease owns the level.+bool cosyvoice_set_debug_level(cosyvoice_context_t ctx,uint32_t level)+{+ auto* model=dynamic_cast<cosyvoice_model*>(ctx);+ if (!model || !model->worker || level>3 || model->worker->use_count.load(std::memory_order_acquire)!=0) return false;+ model->worker->diagnostic.configure(level);+ return true;+}+uint32_t cosyvoice_get_debug_level(cosyvoice_context_t ctx)+{+ auto* model=dynamic_cast<cosyvoice_model*>(ctx);+ return model && model->worker ? model->worker->diagnostic.level.load(std::memory_order_acquire) : UINT32_MAX;+}--- /dev/null+++ b/tools/server/aitable-progress-server.h@@ -0,0 +1,88 @@+// Bounded metadata only. Never holds the registry mutex during inference or I/O.+#pragma once+#include <array>+#include <memory>+#include <mutex>+#include <deque>+#include <atomic>+#if defined(_WIN32)+#include <process.h>+#else+#include <unistd.h>+#endif+#if defined(_WIN32)+#define AITABLE_DIAG_PID _getpid+#else+#define AITABLE_DIAG_PID getpid+#endif+namespace aitable_progress {+inline uint64_t now_ms() { return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count(); }+struct record {+ std::string token;+ uint32_t pid,seed;+ std::atomic<bool> active{true};+ std::atomic<uint64_t> sequence{0};+ std::array<std::atomic<uint64_t>,11> values{};+ record(std::string t,uint32_t s):token(std::move(t)),pid(static_cast<uint32_t>(AITABLE_DIAG_PID())),seed(s){}+ static void observe(const cosyvoice_progress_t* p,void* data) noexcept {+ auto& r=*static_cast<record*>(data);+ r.sequence.fetch_add(1,std::memory_order_acq_rel);+ const uint64_t fields[]={p->stage,p->phase,p->worker,p->seed,p->thread_id,p->samples,p->accepted,p->rejected_streak,p->kv_length,p->clock_ms,p->cancelled?1u:0u};+ for(size_t i=0;i<r.values.size();++i)r.values[i].store(fields[i],std::memory_order_relaxed);+ r.sequence.fetch_add(1,std::memory_order_release);+ }+ json snapshot() const {+ for(int attempt=0;attempt<8;++attempt){+ auto before=sequence.load(std::memory_order_acquire);if(before&1)continue;+ std::array<uint64_t,11> v{};for(size_t i=0;i<v.size();++i)v[i]=values[i].load(std::memory_order_relaxed);+ if(before!=sequence.load(std::memory_order_acquire))continue;+ static constexpr const char* stages[]={"unknown","request_ready","sampling","phase_begin","phase_end","compute_begin","compute_end","sync_begin","sync_end"};+ static constexpr const char* phases[]={"unknown","prefill","decode","sampling","llm"};+ return {{"schema","aitable.cosy_progress@1"},{"request_token",token},{"pid",pid},{"seed",seed},{"active",active.load()},+ {"stage",v[0]<9?stages[v[0]]:"unknown"},{"phase",v[1]<5?phases[v[1]]:"unknown"},{"worker",v[2]},{"native_seed",v[3]},+ {"thread_id",v[4]},{"samples",v[5]},{"accepted",v[6]},{"rejected_streak",v[7]},{"kv_length",v[8]},+ {"last_progress_ms",v[9]},{"age_ms",v[9]?now_ms()-v[9]:0},{"cancelled",v[10]!=0},{"sequence",before}};+ }+ return {{"status","snapshot_busy"}};+ }+};+inline std::mutex records_mutex;+inline std::deque<std::shared_ptr<record>> records;+inline bool valid_token(const std::string& s){return s.size()==32 && s.find_first_not_of("0123456789abcdef")==std::string::npos;}+inline std::shared_ptr<record> begin(const Request& req,Response& res,cosyvoice_context_t ctx,uint32_t seed){+ const auto token=req.get_header_value("X-AiTable-Trace");+ if(!valid_token(token))return {};+ std::shared_ptr<record> r;+ {+ std::lock_guard guard(records_mutex);+ for(const auto& old:records)if(old->token==token)return {};+ if(records.size()>=32){+ auto old=std::find_if(records.begin(),records.end(),[](const auto& row){return !row->active.load();});+ if(old==records.end())return {};records.erase(old);+ }+ r=std::make_shared<record>(token,seed);records.push_back(r);+ }+ cosyvoice_set_progress_callback(ctx,record::observe,r.get());+ res.set_header("X-AiTable-Trace",token);+ res.set_header("X-AiTable-Pid",std::to_string(r->pid));+ res.set_header("X-AiTable-Seed",std::to_string(seed));+ res.set_header("X-AiTable-Worker",std::to_string(r->values[2].load()));+ return r;+}+inline void end(const std::shared_ptr<record>& r,cosyvoice_context_t ctx){+ if(r){cosyvoice_set_progress_callback(ctx,nullptr,nullptr);r->active.store(false);}+}+inline void route(Server& server){+ server.Get(R"(/aitable/progress/([0-9a-f]{32}))",[](const Request& req,Response& res){+ if(req.remote_addr!="127.0.0.1" && req.remote_addr!="::1"){res.status=403;return;}+ std::shared_ptr<record> selected;+ {+ std::lock_guard guard(records_mutex);+ for(auto& row:records)if(row->token==req.matches[1].str()){selected=row;break;}+ }+ if(!selected){res.status=404;return;}+ auto payload=selected->snapshot();res.status=payload.contains("schema")?200:503;+ res.set_header("Cache-Control","no-store");res.set_content(payload.dump(),"application/json");+ });+}+}--- a/tools/server/cosyvoice-server-backend.cpp+++ b/tools/server/cosyvoice-server-backend.cpp@@ -6,6 +6,9 @@ #endif #include <cmath>+#include <fstream>+#include <cstdlib>+#include <chrono> #include <cstdint> #include <ctime> #include <limits>@@ -19,6 +22,23 @@ #endif using json = nlohmann::json;+#include "aitable-progress-server.h"+static bool prepare_adapter(server_runtime&,cosyvoice_context_t,bool,Response&);+// A provider may be discarded before its first callback. Keep slot ownership+// until either execution finishes or httplib releases that provider, exactly once.+struct adapter_stream_slot {+ server_runtime& runtime;uint32_t slot;std::atomic<bool> active{true};+ std::shared_ptr<aitable_progress::record> progress;+ adapter_stream_slot(server_runtime& r,uint32_t s,std::shared_ptr<aitable_progress::record> p={}):runtime(r),slot(s),progress(std::move(p)){}+ void release(){if(active.exchange(false)){+ auto ctx=get_slot_model_context(runtime,slot);+ aitable_progress::end(progress,ctx);+ if(!cosyvoice_set_debug_level(ctx,0)) std::fputs("[AITABLE_DEBUG] worker_debug_cleanup_busy\n",stderr);+ release_thread_slot(runtime,slot);+ }}+ ~adapter_stream_slot(){release();}+};+ struct speech_request {@@ -29,6 +49,7 @@ float speed = 1.0f; std::string instructions; bool has_instructions = false;+ bool asmr_adapter = false; bool has_seed = false; uint32_t seed = 0;@@ -330,6 +351,12 @@ request->has_chunk_tokens = true; } + if (body.contains("asmr_adapter")) {+ if (!body["asmr_adapter"].is_boolean()) {+ set_openai_error(res,400,"asmr_adapter must be boolean","invalid_request_error","asmr_adapter","invalid_type");return false;+ }+ request->asmr_adapter=body["asmr_adapter"].get<bool>();+ } const auto it_instructions = body.find("instructions"); const auto it_instruction = body.find("instruction"); if (it_instructions != body.end())@@ -395,6 +422,7 @@ res.status = 204; }); + aitable_progress::route(server); server.Get("/healthz", [&](const Request&, Response& res) { json payload = {@@ -402,6 +430,12 @@ { "model", runtime.served_model_name }, { "voices", runtime.voice_names } };+ {+ std::lock_guard lock(runtime.slot_mutex);+ payload["active_synthesis_slots"]=std::count(runtime.slot_in_use.begin(),runtime.slot_in_use.end(),true);+ }+ payload["asmr_lora_protocol"]=1;+ payload["aitable_debug_policy"]=1; res.status = 200; res.set_content(payload.dump(), "application/json"); });@@ -476,6 +510,9 @@ return; } + if (request.asmr_adapter && (!request.has_instructions || request.instructions!="Please say a sentence in a very soft voice.")) {+ set_openai_error(res,400,"ASMR requires the bound soft-voice preset","invalid_request_error","instructions","adapter_prompt_mismatch");return;+ } fill_request_log_context_from_request(&log_ctx, request); log_request_details(runtime.log_level, log_ctx); @@ -530,6 +567,14 @@ return; } + const auto debug_header=req.get_header_value("X-AiTable-Debug-Level");+ uint32_t debug_level=0;+ if(!debug_header.empty()) {+ if(debug_header.size()!=1 || debug_header[0]<'0' || debug_header[0]>'3') {+ set_openai_error(res,400,"X-AiTable-Debug-Level must be 0..3","invalid_request_error",nullptr,"invalid_debug_level");return;+ }+ debug_level=static_cast<uint32_t>(debug_header[0]-'0');+ } const uint32_t slot = acquire_thread_slot(runtime); if (slot == UINT32_MAX) {@@ -548,6 +593,9 @@ return; } + if (!prepare_adapter(runtime,model_ctx,request.asmr_adapter,res)) {+ release_thread_slot(runtime,slot);return;+ } std::string payload; std::string encoding_error; std::string generation_error;@@ -571,6 +619,14 @@ return; } + if(!cosyvoice_set_debug_level(model_ctx,debug_level)) {+ release_thread_slot(runtime,slot);+ set_openai_error(res,503,"Worker is not idle","server_error",nullptr,"worker_busy");return;+ }+ res.set_header("X-AiTable-Debug-Protocol","1");+ res.set_header("X-AiTable-Debug-Level",std::to_string(debug_level));+ auto progress=debug_level>=2 ? aitable_progress::begin(req,res,model_ctx,applied_seed) : std::shared_ptr<aitable_progress::record>{};+ auto diagnostic_lease=std::make_shared<adapter_stream_slot>(runtime,slot,progress); const bool is_streaming = request.stream || runtime.stream; // ---- Streaming path ----@@ -594,6 +650,7 @@ // IMPORTANT: the provider runs AFTER the route handler returns, so // any value captured by reference would be a dangling reference. // Capture by value or via raw pointers that outlive the handler.+ auto lease=diagnostic_lease; auto& rt = runtime; auto* vctx = voice_ctx; auto log_ctx_copy = log_ctx;@@ -601,7 +658,7 @@ auto conn_checker = req.is_connection_closed; // copy the socket-checker function res.set_chunked_content_provider(content_type,- [&rt, slot, req_copy, vctx, format, wav_header, has_wav, log_ctx_copy, applied_seed, conn_checker]+ [&rt, slot, req_copy, vctx, format, wav_header, has_wav, log_ctx_copy, applied_seed, conn_checker, lease] (size_t /*offset*/, DataSink& sink) -> bool { auto model_ctx = get_slot_model_context(rt, slot);@@ -613,7 +670,7 @@ if (!sink.write(wav_header.data(), wav_header.size())) { mon.join();- release_thread_slot(rt, slot);+ lease->release(); sink.done(); return true; }@@ -649,7 +706,7 @@ req_copy.speed, stream_cb, &cb_ctx); mon.join();- release_thread_slot(rt, slot);+ lease->release(); sink.done(); if (!ok && !aborted)@@ -665,7 +722,7 @@ return true; },- [](bool /*success*/) { /* resource releaser — no-op */ });+ [lease](bool /*success*/) { lease->release(); }); log_request_details(runtime.log_level, log_ctx); return;@@ -689,7 +746,7 @@ if (!ok || !generated.data || generated.length == 0) {- release_thread_slot(runtime, slot);+ diagnostic_lease->release(); set_openai_error(res, 500, "TTS generation failed.", "server_error", nullptr, "generation_failed"); log_request_done(runtime.log_level, log_ctx, request_log_status::failed, res.status, applied_seed, res.body.size(), "generation_failed"); return;@@ -697,18 +754,58 @@ if (!build_audio_payload(format, generated, runtime, &payload, &encoding_error)) {- release_thread_slot(runtime, slot);+ diagnostic_lease->release(); set_openai_error(res, 500, encoding_error, "server_error", nullptr, "audio_encode_failed"); log_request_done(runtime.log_level, log_ctx, request_log_status::failed, res.status, applied_seed, res.body.size(), "audio_encode_failed"); return; } - release_thread_slot(runtime, slot);+ diagnostic_lease->release(); res.status = 200; res.set_content(std::move(payload), response_format_to_content_type(format)); log_request_done(runtime.log_level, log_ctx, request_log_status::ok, res.status, applied_seed, res.body.size(), "speech"); } });+}++// The host verifies the exact model/container before starting this owned+// subprocess. Only this local startup path may select an adapter file; HTTP+// clients select a mode, never a filesystem path or arbitrary weights.+static bool prepare_adapter(server_runtime& rt,cosyvoice_context_t ctx,bool enabled,Response& res) {+ const auto begin=std::chrono::steady_clock::now();+ uint64_t generation=0;size_t bytes=0;+ int state=cosyvoice_lora_state(ctx,&generation,&bytes);+ if (enabled && rt.concurrency!=1) {+ set_openai_error(res,400,"Adapter requires one owned synthesis slot","invalid_request_error","asmr_adapter","adapter_concurrency_unsupported");return false;+ }+ if(enabled && state==0) {+ const char* path=std::getenv("AITABLE_COSY_ASMR_F32");+ if(!path || !*path) {+ set_openai_error(res,400,"No verified ASMR adapter configured","invalid_request_error","asmr_adapter","adapter_unavailable");return false;+ }+ std::ifstream file(path,std::ios::binary|std::ios::ate);+ constexpr size_t size=270336*sizeof(float);+ if(!file || file.tellg()!=size) {+ set_openai_error(res,500,"Invalid ASMR factor container","server_error","asmr_adapter","adapter_container_invalid");return false;+ }+ std::vector<float> data(270336);file.seekg(0);file.read(reinterpret_cast<char*>(data.data()),size);+ int status=file?cosyvoice_lora_load_f32(ctx,data.data(),data.size()):3;+ if(status) {+ set_openai_error(res,500,"ASMR adapter load failed","server_error","asmr_adapter","adapter_load_failed");return false;+ }+ }+ // Do not change ordinary multi-slot servers with no configured adapter.+ if(enabled || state!=0) {+ if(cosyvoice_lora_set_enabled(ctx,enabled)!=0) {+ set_openai_error(res,409,"ASMR adapter is busy or unavailable","server_error","asmr_adapter","adapter_switch_failed");return false;+ }+ }+ state=cosyvoice_lora_state(ctx,&generation,&bytes);+ res.set_header("X-AiTable-LoRA-State",state==2?"enabled":state==1?"disabled":"unloaded");+ res.set_header("X-AiTable-LoRA-Generation",std::to_string(generation));+ res.set_header("X-AiTable-LoRA-Bytes",std::to_string(bytes));+ res.set_header("X-AiTable-LoRA-Switch-Microseconds",std::to_string(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now()-begin).count()));+ return true; } int cosyvoice_server_backend_run(server_runtime& runtime)releases/20261023-01/CosyVoice-Vulkan-Windows-x64-20261023-01.zipAdded+3
releases/20261023-01/README.mdAdded+33
releases/20261023-01/SHA256SUMS.txtAdded+6
releases/20261023-01/build-manifest-20261023-01.jsonAdded+35
releases/20261023-01/fixes/apply-cosy-fixes-20261023-01.pyAdded+67
releases/20261023-01/fixes/cosy-fixes-manifest-20261023-01.jsonAdded+79
releases/20261023-01/fixes/cosy-native-fixes-20261023-01.patchAdded+1118