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
Add v0.2.1 non-seam patch and verified apply utility
Browse filesVersion-specific source differences and before/after byte verification. Retain the upstream streaming seam implementation.
Files changed (4)
123456789# v0.2.1 non-seam source patch
Requires upstream commit 81ce60cd682ff44b8ab4a9226c097b4aff64d1f6 and GGML from llama.cpp b12359.Run `python apply.py PATH_TO_SOURCE` to check, or append `--apply` to apply and verify all output hashes.The patch retains the upstream streaming seam implementation and restores the APIs listed in the release notes.Rebuild core, CLI and server together with C++20, UTF-8 source handling and normal C++ exception semantics.Use an empty build directory or a clean rebuild. Do not mix GGML 0.27 and 1.0 DLLs or import libraries.GGML, PCRE2, ICU, ONNX Runtime and FFmpeg sources/SDKs must be supplied separately under their own terms.An ASMR adapter is a separate compatible model asset; this patch does not provide trained voice weights.1234567891011121314151617181920212223import argparse,hashlib,json,subprocessfrom pathlib import Pathp=argparse.ArgumentParser(description="Check or apply the v0.2.1 non-seam patch")p.add_argument("source",type=Path);p.add_argument("--apply",action="store_true");a=p.parse_args()here=Path(__file__).resolve().parent;m=json.loads((here/"manifest.json").read_text("utf-8"));root=a.source.resolve()sha=lambda f:hashlib.sha256(f.read_bytes()).hexdigest() if f.is_file() else Nonefor row in m["files"]: f=(root/row["path"]).resolve() if not f.is_relative_to(root) or sha(f)!=row["before"]:raise SystemExit("Unexpected source bytes: "+row["path"])patch=here/"nonseam-v021.patch"command=["git","-C",str(root),"apply","--ignore-space-change","--whitespace=nowarn"]subprocess.run(command+["--check",str(patch)],check=True)if a.apply: subprocess.run(command+[str(patch)],check=True) for row in m["files"]: f=root/row["path"];data=f.read_bytes();has_bom=data.startswith(b"\xef\xbb\xbf") if has_bom:data=data[3:] lines=data.splitlines(keepends=True);ends=[kind for kind,count in row["line_endings"] for _ in range(count)] if len(lines)!=len(ends):raise SystemExit("Post-apply line count mismatch: "+row["path"]) output=(b"\xef\xbb\xbf" if row["bom"] else b"")+b"".join(line.rstrip(b"\r\n")+{"crlf":b"\r\n","lf":b"\n","none":b""}[kind] for line,kind in zip(lines,ends)) f.write_bytes(output) if sha(f)!=row["after"]:raise SystemExit("Post-apply hash mismatch: "+row["path"])print("Applied and verified" if a.apply else "Source and patch checks passed")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245{
"upstream": "81ce60cd682ff44b8ab4a9226c097b4aff64d1f6",
"files": [
{
"path": "include/cosyvoice-lowlevel.h",
"before": "656020ee0c434a280e6eb82e1c032497d827f2bba1a6f0b4fbdc2b1ba0a0d027",
"after": "51c1981cae96cb882987a1a2ad4145682fcd3f6455eb6207c57131ea87340877",
"bom": false,
"line_endings": [
[
"lf",
542
]
]
},
{
"path": "include/cosyvoice.h",
"before": "246b3337437a0d7de5f2bc18cba48449e2cf2a3f6050c81a3a90f3068bb1f176",
"after": "1b31527d856fb746fa8c4bb7e57a2d6e8fae098f15313a989e55c68fec5194e3",
"bom": false,
"line_endings": [
[
"lf",
962
]
]
},
{
"path": "src/cosyvoice-diagnostics.h",
"before": null,
"after": "08e182101ea7ec7b29fbd67fe9511cc2fdcba99f4096a8674301ec8596fb4c24",
"bom": false,
"line_endings": [
[
"crlf",
40
]
]
},
{
"path": "src/cosyvoice-graph.cpp",
"before": "8a6138a019862bd041f4689119d3851a336382eab79ffb5d46b69bbb8a8b510d",
"after": "af19180e1ce74f5a48669da259ba402ba1c6a7e7199b5b2559143dc66a821454",
"bom": false,
"line_endings": [
[
"lf",
887
]
]
},
{
"path": "src/cosyvoice-hift-capture.h",
"before": null,
"after": "c6e6cb0dc1c60a1043d8485500ca003b125cbfd47f9b64efdbd89ef3a92d35b8",
"bom": false,
"line_endings": [
[
"crlf",
131
]
]
},
{
"path": "src/cosyvoice-internal.h",
"before": "be9e76b81a3bc907e12d25c456653f6208cbeb71f9a442054e60be358bce3f3b",
"after": "942cb468b9c59d326499ed8816cebdabe10c6f929eea20a06fc344018d38ccbe",
"bom": false,
"line_endings": [
[
"lf",
198
]
]
},
{
"path": "src/cosyvoice-kv-cache.cpp",
"before": "9b649cfd3fa1e218d020605513c321decf05b1f81ae9b0903886339e7fb56914",
"after": "d1efc94e8b7a22099494e2f83f6a392c089358f2397ddbe259a86c80f6b73f63",
"bom": false,
"line_endings": [
[
"lf",
469
]
]
},
{
"path": "src/cosyvoice-llm-job.cpp",
"before": "45f775388f8fc170f85bab899fe47b52c4ec56bcb41b14c7681af65b0c733eb7",
"after": "6c845261d2c654e45a679568151003dbbfbe545dbadcc7c273012381514339c1",
"bom": false,
"line_endings": [
[
"lf",
232
]
]
},
{
"path": "src/cosyvoice-llm.cpp",
"before": "7b404a1c45e7f7af9ca682645037a90293c0aff27a3136656eda41147c1308b8",
"after": "930a94aa38493e04dfae6c206b90a4b575abd624db3cf155dce934cbf810c904",
"bom": false,
"line_endings": [
[
"lf",
566
]
]
},
{
"path": "src/cosyvoice-loader.cpp",
"before": "16110adfc1fe7e4f2250a421e630fc0f692062779d165df1166864292d78c91a",
"after": "16110adfc1fe7e4f2250a421e630fc0f692062779d165df1166864292d78c91a",
"bom": false,
"line_endings": [
[
"lf",
1164
]
]
},
{
"path": "src/cosyvoice-lora.cpp",
"before": null,
"after": "433705739dea1bd246dbe9c7d73fb5f4b78d35ff61c648d7ffb5d26533099869",
"bom": false,
"line_endings": [
[
"crlf",
82
]
]
},
{
"path": "src/cosyvoice-model.cpp",
"before": "8b479d74a8cde59e8729d188c9df609a53e7dd5e55ce438b9a3518af0d8e63b8",
"after": "f3b900c27ea70387248a94b7b798102df9621959afc5fd6b24f4fd8157455f82",
"bom": false,
"line_endings": [
[
"lf",
657
]
]
},
{
"path": "src/cosyvoice-model.h",
"before": "d4567898df81e0f9adca8f8fc9ed1c1ff5629bb450e9905f0070e30616f5bd61",
"after": "571c034cd70d111cbe420e63a58e56da9341820acd7d3de39fd0dcad3a97b9ac",
"bom": false,
"line_endings": [
[
"lf",
243
]
]
},
{
"path": "src/cosyvoice-modules.h",
"before": "43935b206ab5b4ed190a7d8cdcad9818be9286700ba3982de47cb95eaabaef0e",
"after": "469099ad10b358c23935f5168caf6476d9ebc937e6c1130549b5968b14ae09bf",
"bom": false,
"line_endings": [
[
"lf",
432
]
]
},
{
"path": "src/cosyvoice-output-tokens.h",
"before": null,
"after": "cbdf5f10bb4f6f3a5f2218df95d8d6334a60e665a4c949f277af27c7b82a11c9",
"bom": false,
"line_endings": [
[
"crlf",
13
]
]
},
{
"path": "src/cosyvoice-token2wav.cpp",
"before": "4170b32752b834622dfe4ad22292bd28dac5221ed74365547ae5d83502a7d0c6",
"after": "c957f4e9dadfbd874ead75373a2495729853fcc8a50274a4102e5c7f5b723439",
"bom": false,
"line_endings": [
[
"lf",
652
]
]
},
{
"path": "src/cosyvoice-tts.cpp",
"before": "aba9680e115b09a16f6c5d9d26319e43768058b2df31e1a98c0f45eb9f2826e4",
"after": "ee07a51ed7a451dc147808f3fa490443eee3ca7c67f948ddd09cc32e1a4692b6",
"bom": false,
"line_endings": [
[
"lf",
465
]
]
},
{
"path": "src/cosyvoice.cpp",
"before": "6e921bd2662fdd2d6da2645b3e0690b79acc4ddbedb3f426e484be83c4270c7e",
"after": "5aa1e06ffa96554116d649d2548766ed086298956fa70ff81183d5142c46ba37",
"bom": false,
"line_endings": [
[
"lf",
842
]
]
},
{
"path": "tools/server/aitable-progress-server.h",
"before": null,
"after": "3c0b97c94c4de8a2c72087ce6b3e0f106c6b4702b80216af59b0836a973fdef8",
"bom": false,
"line_endings": [
[
"crlf",
95
]
]
},
{
"path": "tools/server/cosyvoice-server-backend.cpp",
"before": "15ddbaac4af2e30aadc217f680e9585ae880ba2b6bd0cca0c74f79eb25a7024e",
"after": "ce93afd778aaaa5ef963ad47b63056b8f32bef66a6cae95aaa3d5215fa201123",
"bom": false,
"line_endings": [
[
"lf",
920
]
]
}
]
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519--- a/include/cosyvoice-lowlevel.h+++ b/include/cosyvoice-lowlevel.h@@ -284,6 +284,12 @@ */ COSYVOICE_API const int* cosyvoice_llm_get_accepted_tokens(cosyvoice_context_t ctx); +/** Generated/accepted history includes silence consumed by the LLM.+ * These emitted tokens alone are suitable for the vocoder. Borrowed until mutation.+ */+COSYVOICE_API uint32_t cosyvoice_llm_get_n_emitted_tokens(cosyvoice_context_t ctx);+COSYVOICE_API const int* cosyvoice_llm_get_emitted_tokens(cosyvoice_context_t ctx);+ // ---------------------------------------------------------------------------- // Low-Level Inference Routines // ------------------------------------------------------------------------------- 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,32 @@ */ 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);++// Optional error-only statistics; call from this worker's progress observer or+// while idle. The caller owns output and passes its version and buffer size.+// This leaves the existing borrowed progress callback ABI unchanged.+typedef struct cosyvoice_failure_stats {+ uint32_t reason; // 0: none; 1: legacy silent resampling exhausted; 2: generation limit+ uint32_t nucleus_positive, nucleus_non_silent, raw_non_silent_mass_ppb;+ uint64_t rescue_draws;+} cosyvoice_failure_stats_t;+COSYVOICE_API bool cosyvoice_get_failure_stats(cosyvoice_context_t ctx,+ uint32_t version, size_t output_size, cosyvoice_failure_stats_t* output);++// 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@@ -1,3 +1,4 @@+#include "cosyvoice-hift-capture.h" #include "cosyvoice-model.h" #include "ggml-fft.h" #include "ggml-cpu-flag.h"@@ -244,6 +245,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 * 0.95f)); if (bias) out = ggml_add(ctx, out, bias); return out;@@ -776,9 +780,15 @@ } std::array<ggml_tensor*, 2> CausalHiFTGenerator::build_cgraph(ggml_context* ctx, ggml_tensor* speech_feat, bool finalize, SineGen2::phase_state* state) const+{ return build_cgraph_capture(ctx, speech_feat, finalize, nullptr, state); }++std::array<ggml_tensor*, 2> CausalHiFTGenerator::build_cgraph_capture(ggml_context* ctx, ggml_tensor* speech_feat, bool finalize, hift_research::Capture* capture, SineGen2::phase_state* state) const+ { auto f0 = f0_predictor.build_cgraph(ctx, speech_feat, finalize);+ if (capture) capture->keep("f0", f0); auto s_input = ggml_permute(ctx, f0, 1, 0, 2, 3); // [1, T', 1]+ s_input = ggml_interpolate(ctx, s_input, s_input->ne[0], s_input->ne[1] * scale_factor, s_input->ne[2], 1, GGML_SCALE_MODE_NEAREST); // The next chunk re-feeds the last `retain_frames` mel frames of this@@ -789,6 +799,8 @@ state->checkpoint_row = finalize ? -1 : speech_feat->ne[0] - state->retain_frames - 1; auto [s, noise] = m_source.build_cgraph(ctx, s_input, nb_harmonics, sampling_rate, scale_factor, nsf_alpha, nsf_voiced_threshold, nsf_sigma, state);+ if (capture) capture->keep("excitation", s);+ s = ggml_permute(ctx, s, 1, 0, 2, 3); // decode--- /dev/null+++ b/src/cosyvoice-hift-capture.h@@ -0,0 +1,131 @@+#pragma once
+#include "ggml.h"
+#include "ggml-backend.h"
+#include <atomic>
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <map>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <vector>
+namespace hift_research {
+// Request-owned Level 3 capture. The host reduces native level below 3 when
+// diagnostic privacy is enabled or unknown. There is no implicit capture path.
+inline constexpr size_t total_limit=512ull*1024*1024, request_limit=128ull*1024*1024;
+struct Request {
+ std::filesystem::path root;
+ unsigned calls=0;
+ size_t bytes=0;
+ bool failed=false;
+};
+inline std::mutex registry_mutex;
+inline std::map<const void*,std::shared_ptr<Request>> requests;
+inline std::atomic<unsigned long long> serial{0};
+inline size_t reserved_total=0;
+inline bool inventory_loaded=false;
+inline std::filesystem::path inventory_root;
+inline void failed(const std::shared_ptr<Request>& request,const char* code) noexcept {
+ if (request && request->failed) return;
+ if (request) request->failed=true;
+ std::fprintf(stderr,"[AITABLE_HIFT_CAPTURE] status=unavailable reason=%s\n",code);
+}
+inline std::shared_ptr<Request> request(const void* owner,bool fresh,bool enabled) noexcept {
+ if (!enabled) return {};
+ const char* path=std::getenv("AITABLE_HIFT_CAPTURE_DIR");
+ if (!path || !*path) return {};
+ try {
+ std::lock_guard lock(registry_mutex);
+ if (!fresh) {
+ auto it=requests.find(owner);
+ return it==requests.end()?nullptr:it->second;
+ }
+ requests.erase(owner);
+ if (requests.size()>=64) { failed({},"request_capacity"); return {}; }
+ const std::filesystem::path root(path);
+ if (!inventory_loaded) {
+ std::filesystem::create_directories(root);
+ size_t entries=0, existing_bytes=0;
+ for (const auto& entry:std::filesystem::recursive_directory_iterator(root)) {
+ if (++entries>8192) { failed({},"inventory_capacity"); return {}; }
+ if (entry.is_symlink()) { failed({},"unsafe_capture_entry"); return {}; }
+ if (entry.is_regular_file()) {
+ const auto size=entry.file_size();
+ if (size>total_limit || existing_bytes>total_limit-size) { failed({},"storage_capacity"); return {}; }
+ existing_bytes+=static_cast<size_t>(size);
+ }
+ }
+ reserved_total=existing_bytes;inventory_loaded=true;inventory_root=root;
+ }
+ if (inventory_root!=root || reserved_total>=total_limit) { failed({},"storage_capacity"); return {}; }
+ auto value=std::make_shared<Request>();
+ const auto stamp=std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
+ value->root=root/("request-"+std::to_string(stamp)+"-"+std::to_string(serial.fetch_add(1)));
+ if (!std::filesystem::create_directory(value->root)) { failed({},"directory_collision"); return {}; }
+ requests.emplace(owner,value);
+ return value;
+ } catch (...) { failed({},"storage_unavailable"); return {}; }
+}
+inline void finish(const void* owner,bool final) noexcept {
+ if (!final) return;
+ std::lock_guard lock(registry_mutex);requests.erase(owner);
+}
+struct Capture {
+ std::shared_ptr<Request> owner;
+ unsigned index=0,seed=0,worker=0;
+ bool complete=false;
+ std::vector<std::pair<std::string,ggml_tensor*>> tensors;
+ explicit Capture(std::shared_ptr<Request> value,unsigned seed,unsigned worker):owner(std::move(value)),seed(seed),worker(worker) {
+ if (!owner || owner->failed) { owner.reset();return; }
+ index=owner->calls++;
+ if (index>=8) { failed(owner,"request_call_capacity");owner.reset(); }
+ }
+ void keep(const char* name,ggml_tensor* tensor) noexcept {
+ if (!owner || owner->failed) return;
+ try {
+ const size_t n=ggml_nbytes(tensor), overhead=1024;
+ std::lock_guard lock(registry_mutex);
+ if (n>request_limit-overhead || owner->bytes>request_limit-n-overhead || reserved_total>total_limit-n-overhead) {
+ failed(owner,"tensor_capacity");return;
+ }
+ owner->bytes+=n+overhead;reserved_total+=n+overhead;
+ tensors.emplace_back(name,tensor);
+ ggml_set_output(tensor);
+ } catch (...) { failed(owner,"capture_allocation"); }
+ }
+ void write() noexcept {
+ if (!owner || owner->failed) return;
+ try {
+ for (const auto& [name,tensor]:tensors) {
+ std::vector<char> data(ggml_nbytes(tensor));
+ ggml_backend_tensor_get(tensor,data.data(),0,data.size());
+ auto stem=owner->root/("call"+std::to_string(index)+"."+name);
+ std::ofstream file;file.exceptions(std::ios::failbit|std::ios::badbit);
+ file.open(stem.string()+".bin",std::ios::binary|std::ios::trunc);
+ file.write(data.data(),static_cast<std::streamsize>(data.size()));file.close();
+ std::ofstream meta;meta.exceptions(std::ios::failbit|std::ios::badbit);meta.open(stem.string()+".json");
+ meta<<"{\"type\":"<<tensor->type<<",\"ne\":[";
+ for (int i=0;i<4;++i) meta<<(i?",":"")<<tensor->ne[i];
+ meta<<"],\"nb\":[";
+ for (int i=0;i<4;++i) meta<<(i?",":"")<<tensor->nb[i];
+ meta<<"],\"bytes\":"<<data.size()<<"}";meta.close();
+ }
+ complete=true;
+ } catch (...) { failed(owner,"save_failed"); }
+ }
+ void boundary(uint32_t prior,uint32_t end,uint32_t emitted,bool final,int64_t cache_frames,int64_t new_frames) noexcept {
+ if (!owner || owner->failed || !complete) return;
+ try {
+ std::ofstream out;out.exceptions(std::ios::failbit|std::ios::badbit);
+ out.open(owner->root/("call"+std::to_string(index)+".boundary.json"));
+ out<<"{\"protocol\":1,\"seed\":"<<seed<<",\"worker\":"<<worker<<",\"prior_commit\":"<<prior<<",\"new_commit\":"<<end
+ <<",\"emitted_samples\":"<<emitted<<",\"finalize\":"<<(final?"true":"false")<<",\"cache_frames\":"<<cache_frames
+ <<",\"new_frames\":"<<new_frames<<",\"tensor_capture_complete\":true}";out.close();
+ std::fprintf(stderr,"[AITABLE_HIFT_CAPTURE] status=saved call=%u seed=%u worker=%u emitted=%u final=%u\n",index,seed,worker,emitted,final?1:0);
+ } catch (...) { failed(owner,"save_failed"); }
+ }
+};
+}
--- 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,9 +1,12 @@+#include "cosyvoice-diagnostics.h" #include "cosyvoice-internal.h" #include "cosyvoice-model.h" #include <algorithm> #include <cstring>+#include <cmath> #include <exception>+#include <random> #include <stdexcept> #include <vector> @@ -16,6 +19,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;@@ -43,9 +48,6 @@ if (llm_get_n_accepted_tokens() == 0 || llm_get_kv_cache_len() == 0) { GGML_ASSERT(text);-- // A fresh generation: restart the consecutive-silence accounting.- worker->silent_token_num = 0; const auto token_type = llm.embed_tokens_weight->type; const auto token_row_size = static_cast<uint32_t>(llm.embed_tokens_weight->nb[1]);@@ -138,21 +140,33 @@ // First call: min/max from text input const auto min_len = static_cast<uint32_t>(text_len * worker->config.min_token_text_ratio); const auto max_len = static_cast<uint32_t>(text_len * worker->config.max_token_text_ratio);- const auto limit = std::min(llm_get_n_accepted_tokens() + max_new_tokens, max_len);-- // FSQ silent/breath token filtering: allow up to 5 consecutive silent tokens,- // then drop any further consecutive ones to avoid generating long silence.- // Reset the counter whenever a non-silent token appears. The counter is- // kept in the worker so it survives llm_job_ext() calls that continue- // the same generation across streaming chunks.- auto& cur_silent_token_num = worker->silent_token_num;- constexpr uint32_t max_silent_token_num = 5;- const auto& silent_tokens = cv3_shared->silent_tokens;+ const auto limit = std::min<uint64_t>(static_cast<uint64_t>(llm_get_n_accepted_tokens()) + max_new_tokens, max_len);+ for (uint32_t n = llm_get_n_accepted_tokens();; ++n) {+ 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 (n >= max_len)+ {+ // Do not report truncated synthesis as an EOS completion.+ if (worker->progress_callback) worker->failure_stats.reason = 2;+ throw std::runtime_error("LLM generated token limit reached before stop token.\n");+ }++ if (worker->progress_callback) ++worker->progress.samples;+ cosyvoice_report_progress(worker,2,3);+ // Every yielded token advances generated history and KV, including+ // silence omitted from the vocoder, matching the upstream generator. llm_prepare_probs(n > min_len);- const auto token_id = llm_sample_token();+ const int 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"); if (n > min_len && llm_is_stop_token(token_id))@@ -161,27 +175,9 @@ break; } - if (silent_tokens.count(token_id))- {- ++cur_silent_token_num;- if (cur_silent_token_num > max_silent_token_num)- {- if (n > limit)- break;-- // Excess silence is not emitted, but the token still enters- // the model state so generation can move past it instead of- // re-sampling the same logits.- cur = speech_emb + token_id * speech_row_size;- if (!llm_decode(speech_type, cur))- throw std::runtime_error("Failed to decode LLM output.\n");- continue;- }- }- else- cur_silent_token_num = 0; llm_accept_token(token_id);+ cosyvoice_report_progress(worker,2,3); if (is_stop_requested()) {@@ -228,3 +224,9 @@ return true; }++void cosyvoice_model_3::llm_accept_token(int token)+{+ worker->tokens.push_back(token);+ worker->output_tokens.accept(token, cv3_shared->silent_tokens.count(token) != 0);+}--- a/src/cosyvoice-llm.cpp+++ b/src/cosyvoice-llm.cpp@@ -96,6 +96,9 @@ if (node == cpu_pivot) cpu = true; + // Preserve device acceleration while accumulating LLM matrix products in F32.+ if (node->op == GGML_OP_MUL_MAT)+ ggml_prec_set_acc(node, GGML_PREC_F32); ggml_backend_sched_set_tensor_backend(sched, node, cpu ? cpu_backend : backend); } }@@ -116,6 +119,7 @@ auto logits = llm.llm_decoder.build_cgraph(ctx0, hidden_states); auto probs = ggml_soft_max_ext(ctx0, logits, nullptr, 1.f / worker->config.temperature, 0.f);+ ggml_set_output(probs); // Keep the full distribution alive until the host readback. if (shared->op_caps.top_k) {@@ -136,6 +140,7 @@ auto cpu_backend = worker->cpu_backend.get(); probs = ggml_dup(ctx0, probs);+ ggml_set_output(probs); // The CPU-copy distribution is also read after graph completion. auto cpu_pivot = probs; auto top_k = ggml_top_k(ctx0, probs, worker->config.sampling.top_k); @@ -172,8 +177,11 @@ 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); worker->raw_probs_masked = false;+ } bool cosyvoice_model_3::llm_prefill(@@ -182,6 +190,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;@@ -233,6 +242,7 @@ // Written once, then reused with the graph. Keep later intermediates // from overwriting these embedding indices in the allocator buffer. ggml_set_output(emb_pos);+ hidden_states = ggml_get_rows(ctx0, llm_input, emb_pos); } @@ -287,7 +297,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; } @@ -298,6 +310,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;@@ -337,6 +350,7 @@ { emb_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens); ggml_set_output(emb_pos);+ hidden_states = ggml_get_rows(ctx0, llm_input, emb_pos); } @@ -364,7 +378,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);@@ -375,6 +391,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; @@ -412,6 +429,7 @@ { emb_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, 1); ggml_set_output(emb_pos);+ hidden_states = ggml_get_rows(ctx0, llm_input, emb_pos); } @@ -437,7 +455,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);@@ -462,6 +482,7 @@ int k = worker->config.sampling.top_k; memcpy(probs, raw_probs, static_cast<size_t>(k) * sizeof(*probs)); + const float top_p = worker->config.sampling.top_p; std::sort(probs, probs + k, [](const cosyvoice_llm_token_prob_t& a, const cosyvoice_llm_token_prob_t& b) { return a.prob > b.prob; });@@ -487,6 +508,7 @@ return; } + worker->nucleus_probs_len = k; for (int i = 0; i != k; ++i) probs[i].prob /= p;@@ -501,6 +523,7 @@ const float sum = simd_dispatch<sum_kernel>(vocab_probs, vocab_size); simd_dispatch<div_kernel>(vocab_probs, vocab_size, sum); worker->raw_probs_masked = true;+ } } --- /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" @@ -166,7 +167,7 @@ bool cosyvoice_model::using_builtin_sampler() const {- return worker->sampler == reinterpret_cast<cosyvoice_sampler_t>(cosyvoice_llm_sampler);+ return shared->params.sampler == reinterpret_cast<cosyvoice_sampler_t>(cosyvoice_llm_sampler); } bool cosyvoice_model::reset_builtin_sampler_rng()@@ -510,11 +511,13 @@ void cosyvoice_model::llm_accept_token(int token) { worker->tokens.push_back(token);+ worker->output_tokens.accept(token, false); } void cosyvoice_model::llm_clear_accepted_tokens() { worker->tokens.clear();+ worker->output_tokens.clear(); } uint32_t cosyvoice_model::llm_get_n_accepted_tokens()@@ -560,13 +563,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); } @@ -606,3 +613,45 @@ 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->failure_stats={};+ 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,9 +1,11 @@ #pragma once #include "cosyvoice-modules.h"+#include "cosyvoice-diagnostics.h" #include "cosyvoice-lowlevel.h" #include "cosyvoice-interface.h" #include "cosyvoice-kv-cache.h"+#include "cosyvoice-output-tokens.h" #include <ggml-cpp.h> @@ -30,6 +32,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;@@ -60,12 +63,9 @@ std::mt19937 sampler_rng, noise_rng; - std::vector<int> tokens;-- // Consecutive-silent-token counter for the FSQ silence filtering. It must- // survive across llm_job_ext() calls that continue the same generation- // (streaming chunks), so it lives in the worker instead of the job call.- uint32_t silent_token_num{0};+ std::vector<int> tokens; // generated history, including filtered silence+ cosyvoice_output_tokens output_tokens;+ cosyvoice_kv_cache llm_kv_cache; cosyvoice_kv_cache dit_kv_cache;@@ -73,6 +73,10 @@ 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_failure_stats_t failure_stats = {}; cosyvoice_generation_config_t config; cosyvoice_sampler_t sampler; void* sampler_ctx;@@ -92,6 +96,7 @@ // preparing the nucleus is idempotent and can be repeated for one logits // state without re-filtering already normalized probabilities. std::unique_ptr<float[]> nucleus_raw;+ uint32_t nucleus_probs_capacity; int nucleus_probs_len; bool raw_probs_masked;@@ -99,6 +104,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;@@ -112,6 +118,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();@@ -167,6 +174,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;@@ -209,6 +220,7 @@ uint32_t get_hift_rand_ini_len(); void set_hift_rand_ini(const float* data); + void llm_accept_token(int token); bool llm_job(const int* text, uint32_t text_len, cosyvoice_prompt_t prompt); bool llm_job_ext(const int* text, uint32_t text_len, cosyvoice_prompt_t prompt, uint32_t max_new_tokens, bool* final); bool token2wav(const int* token_ids, uint32_t n_tokens, float speed, cosyvoice_prompt_t prompt, cosyvoice_generated_speech_ptr result);@@ -222,3 +234,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@@ -1,3 +1,4 @@+namespace hift_research { struct Capture; } #pragma once #include "cosyvoice-internal.h"@@ -35,6 +36,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; }; @@ -346,6 +351,8 @@ // phase offset and exports a checkpoint row so the next streaming chunk // resumes at the correct oscillator phase. std::array<ggml_tensor*, 2> build_cgraph(ggml_context* ctx, ggml_tensor* speech_feat, bool finalize, SineGen2::phase_state* state = nullptr) const;+ std::array<ggml_tensor*, 2> build_cgraph_capture(ggml_context* ctx, ggml_tensor* speech_feat, bool finalize, hift_research::Capture* capture, SineGen2::phase_state* state = nullptr) const;+ int overlap_length() const; void set_rand_ini(const float* data) const;--- /dev/null+++ b/src/cosyvoice-output-tokens.h@@ -0,0 +1,13 @@+#pragma once
+#include <vector>
+#include <cstdint>
+// Generated history belongs to the LLM; this buffer alone feeds the vocoder.
+struct cosyvoice_output_tokens {
+ std::vector<int> tokens;
+ uint32_t silent_run = 0;
+ void accept(int token, bool silent) {
+ silent_run = silent ? silent_run + 1 : 0;
+ if (silent_run <= 5) tokens.push_back(token);
+ }
+ void clear() { tokens.clear(); silent_run = 0; }
+};
--- a/src/cosyvoice-token2wav.cpp+++ b/src/cosyvoice-token2wav.cpp@@ -1,3 +1,5 @@+#include "cosyvoice-hift-capture.h"+#include "cosyvoice-diagnostics.h" #include "cosyvoice-internal.h" #include "cosyvoice-model.h" #include "ggml-cpu-flag.h"@@ -310,6 +312,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]); @@ -400,6 +403,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);@@ -569,7 +573,14 @@ // over the full accumulated mel, so the frame-rate rad cumsum starts from // zero and continues the previous chunks' phase by construction — the // reference implementation relies on the same property.- auto [generated_speech, noise] = hift.build_cgraph(ctx0.get(), speech_feat, finalize, nullptr);+ auto capture_request = hift_research::request(worker, cache_length == 0,+ worker->diagnostic.level.load(std::memory_order_acquire) >= 3);+ hift_research::Capture capture(capture_request, worker->sampler_seed, get_worker_no());+ capture.keep("mel", speech_feat);+ capture.keep("initial_phase", hift.m_source.l_sin_gen.rand_ini);+ auto [generated_speech, noise] = hift.build_cgraph_capture(ctx0.get(), speech_feat, finalize, &capture, nullptr);+ capture.keep("noise", noise);+ capture.keep("full_pcm", generated_speech); ggml_build_forward_expand(gf, generated_speech); set_graph_backends(gf, sched.get(), backend.get(), cpu_backend.get(), op_caps); @@ -587,6 +598,8 @@ 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]); @@ -596,8 +609,15 @@ result->length = worker->wav_offset < generated_speech->ne[0] ? static_cast<uint32_t>(generated_speech->ne[0] - worker->wav_offset) : 0; worker->status = ggml_backend_sched_graph_compute(sched.get(), gf);+ aitable_tts_diag::mark(worker->diagnostic, "hift_end", -1, get_worker_no());+ if (worker->status == GGML_STATUS_SUCCESS)+ capture.write(); shared->noise_callback(COSYVOICE_NOISE_CALLBACK_STAGE_AFTER_HIFT, noise_req, noise_buffer, shared->noise_callback_ctx);+ const auto prior_offset = worker->wav_offset; worker->wav_offset += result->length;+ capture.boundary(prior_offset, worker->wav_offset, result->length, finalize, cache_length, mel_new_frames);+ if (capture_request)+ hift_research::finish(worker, finalize || !streaming); static const bool log_phase = std::getenv("COSYVOICE_HIFT_PHASE_LOG") != nullptr; if (log_phase && streaming)--- 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,8 @@ 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 +107,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"@@ -27,8 +28,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); } @@ -36,18 +53,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(); }@@ -421,6 +442,15 @@ return ctx->llm_get_accepted_tokens(); } +uint32_t cosyvoice_llm_get_n_emitted_tokens(cosyvoice_context_t ctx)+{+ return static_cast<uint32_t>(dynamic_cast<cosyvoice_model*>(ctx)->worker->output_tokens.tokens.size());+}+const int* cosyvoice_llm_get_emitted_tokens(cosyvoice_context_t ctx)+{+ return dynamic_cast<cosyvoice_model*>(ctx)->worker->output_tokens.tokens.data();+}+ bool cosyvoice_llm_job(cosyvoice_context_t ctx, const int* text, uint32_t text_len, cosyvoice_prompt_t prompt) { return ctx->llm_job(text, text_len, prompt);@@ -478,7 +508,7 @@ } if (ctx->llm_job(text, text_len, prompt)- && ctx->token2wav(ctx->llm_get_accepted_tokens(), ctx->llm_get_n_accepted_tokens(), speed, prompt, result))+ && ctx->token2wav(cosyvoice_llm_get_emitted_tokens(ctx), cosyvoice_llm_get_n_emitted_tokens(ctx), speed, prompt, result)) { // Check if stop was requested during token2wav if (ctx->is_stop_requested())@@ -509,27 +539,30 @@ ctx->llm_clear_accepted_tokens(); uint32_t n_tokens = 0; bool final = false;- do+ for (;;) { const auto chunk_tokens = ctx->get_chunk_tokens();-- if (ctx->is_stop_requested())- return false;-- if (!final)- if (!ctx->llm_job_ext(text, text_len, prompt, chunk_tokens + 1, &final))- goto cleanup;-- n_tokens = std::min(n_tokens + chunk_tokens, ctx->llm_get_n_accepted_tokens());-+ // Hold emitted lookahead even when filtered silence consumed a whole+ // generation quota. Generated progress is bounded by the text maximum.+ while (!final && static_cast<uint64_t>(cosyvoice_llm_get_n_emitted_tokens(ctx)) <+ static_cast<uint64_t>(n_tokens) + chunk_tokens + 1)+ {+ if (ctx->is_stop_requested()) return false;+ if (!ctx->llm_job_ext(text, text_len, prompt, chunk_tokens + 1, &final)) goto cleanup;+ }+ if (ctx->is_stop_requested()) return false;+ const auto total = cosyvoice_llm_get_n_emitted_tokens(ctx);+ n_tokens = std::min(n_tokens + chunk_tokens, total);+ if (n_tokens == 0) goto cleanup; // no synthetic zero-PCM completion+ const bool finalize = final && n_tokens == total; cosyvoice_generated_speech result = {};- if (!ctx->token2wav_ext(ctx->llm_get_accepted_tokens(), n_tokens, speed, prompt, true, ctx->llm_get_n_accepted_tokens() == n_tokens, &result))+ if (!ctx->token2wav_ext(cosyvoice_llm_get_emitted_tokens(ctx), n_tokens, speed, prompt, true, finalize, &result)) 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());+ if (finalize) break;+ } return true; @@ -779,3 +812,31 @@ 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);+}++bool cosyvoice_get_failure_stats(cosyvoice_context_t ctx, uint32_t version,+ size_t output_size, cosyvoice_failure_stats_t* output)+{+ auto* model=dynamic_cast<cosyvoice_model*>(ctx);+ if (!model || !model->worker || version!=1 || !output || output_size<sizeof(*output)) return false;+ *output=model->worker->failure_stats;+ return true;+}++// 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,95 @@+// 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;
+ cosyvoice_context_t context;
+ std::atomic<bool> active{true};
+ std::atomic<uint64_t> sequence{0};
+ std::array<std::atomic<uint64_t>,16> values{};
+ record(std::string t,uint32_t s,cosyvoice_context_t ctx):token(std::move(t)),pid(static_cast<uint32_t>(AITABLE_DIAG_PID())),seed(s),context(ctx){}
+ 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);
+ cosyvoice_failure_stats_t failure{};
+ cosyvoice_get_failure_stats(r.context,1,sizeof(failure),&failure);
+ 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,failure.reason,failure.nucleus_positive,failure.nucleus_non_silent,failure.raw_non_silent_mass_ppb,failure.rescue_draws};
+ 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,16> 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"};
+ json result={{"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}};
+ if(v[11]==1 || v[11]==2)result["failure"]={{"reason",v[11]==1?"silent_resample_exhausted":"generated_token_limit"},
+ {"nucleus_positive",v[12]},{"nucleus_non_silent",v[13]},
+ {"raw_non_silent_mass_ppb",v[14]},{"rescue_draws",v[15]}};
+ return result;
+ }
+ 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,ctx);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 <format>@@ -20,6 +23,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 {@@ -30,6 +50,7 @@ float speed = 1.0f; std::string instructions; bool has_instructions = false;+ bool asmr_adapter = false; bool has_seed = false; uint32_t seed = 0;@@ -331,6 +352,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())@@ -396,6 +423,7 @@ res.status = 204; }); + aitable_progress::route(server); server.Get("/healthz", [&](const Request&, Response& res) { json payload = {@@ -403,6 +431,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"); });@@ -477,6 +511,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); @@ -531,6 +568,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) {@@ -549,6 +594,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;@@ -572,6 +620,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 ----@@ -595,6 +651,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;@@ -602,7 +659,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);@@ -614,7 +671,7 @@ if (!sink.write(wav_header.data(), wav_header.size())) { mon.join();- release_thread_slot(rt, slot);+ lease->release(); sink.done(); return true; }@@ -650,13 +707,15 @@ req_copy.speed, stream_cb, &cb_ctx); mon.join();- release_thread_slot(rt, slot);- sink.done();+ lease->release(); if (!ok && !aborted) { log_request_done(rt.log_level, log_ctx_copy, request_log_status::failed, 200, applied_seed, 0, "stream_generation_failed");+ // No terminal chunk: a failed synthesis is not a complete+ // audio response, including when earlier PCM was sent.+ return false; } else {@@ -664,9 +723,10 @@ request_log_status::ok, 200, applied_seed, 0, "stream_speech"); } + sink.done(); return true; },- [](bool /*success*/) { /* resource releaser — no-op */ });+ [lease](bool /*success*/) { lease->release(); }); log_request_details(runtime.log_level, log_ctx); return;@@ -690,7 +750,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;@@ -698,18 +758,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/20261117-01/fixes/README.mdAdded+9
releases/20261117-01/fixes/apply.pyAdded+23
releases/20261117-01/fixes/manifest.jsonAdded+245
releases/20261117-01/fixes/nonseam-v021.patchAdded+1519