@qvac/tts-ggml 0.11.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ 'use strict'
2
+
3
+ const os = require('bare-os')
4
+ const proc = require('bare-process')
5
+
6
+ const platform = os.platform()
7
+ const isMobile = platform === 'ios' || platform === 'android'
8
+ const isApple = platform === 'darwin' || platform === 'ios'
9
+
10
+ const NO_GPU = !!proc.env && proc.env.NO_GPU === 'true'
11
+ const GPU_ONLY_USE_GPU = !isMobile
12
+ const SKIP_PARLER_GPU_ONLY = NO_GPU || (!isMobile && !isApple)
13
+ const PARLER_GPU_ONLY_USE_GPU = isApple && !isMobile
14
+
15
+ module.exports = { NO_GPU, GPU_ONLY_USE_GPU, SKIP_PARLER_GPU_ONLY, PARLER_GPU_ONLY_USE_GPU }
@@ -0,0 +1,34 @@
1
+ 'use strict'
2
+
3
+ const GPU_BACKEND_IDS = { metal: 1, cuda: 2, vulkan: 3, opencl: 4 }
4
+
5
+ // The native engine reads TTS_CPP_GPU_BACKEND. Check its reported backend as
6
+ // well: a different GPU must not make a CUDA/Vulkan validation lane pass.
7
+ function assertMossBackend(t, label, stats, useGPU, pinnedBackend = '') {
8
+ if (!stats) {
9
+ t.fail(`${label}: missing runtime stats; cannot verify the backend`)
10
+ return
11
+ }
12
+ t.is(stats.backendDevice, useGPU ? 1 : 0, `${label}: requested compute device`)
13
+ if (!useGPU) {
14
+ t.is(stats.backendId, 0, `${label}: CPU requested explicitly`)
15
+ return
16
+ }
17
+ t.is(stats.gpuUnsupported, 0, `${label}: no GPU fallback`)
18
+ pinnedBackend = pinnedBackend.toLowerCase()
19
+ if (pinnedBackend) {
20
+ if (!Object.prototype.hasOwnProperty.call(GPU_BACKEND_IDS, pinnedBackend)) {
21
+ t.fail(`${label}: unknown TTS_CPP_GPU_BACKEND=${pinnedBackend}`)
22
+ return
23
+ }
24
+ t.is(
25
+ stats.backendId,
26
+ GPU_BACKEND_IDS[pinnedBackend],
27
+ `${label}: TTS_CPP_GPU_BACKEND=${pinnedBackend}`
28
+ )
29
+ } else {
30
+ t.ok(Object.values(GPU_BACKEND_IDS).includes(stats.backendId), `${label}: known GPU backend`)
31
+ }
32
+ }
33
+
34
+ module.exports = { assertMossBackend }
@@ -0,0 +1,70 @@
1
+ 'use strict'
2
+
3
+ const fs = require('bare-fs')
4
+ const path = require('bare-path')
5
+
6
+ const ENCODER_RE = /^moss-codec-encoder(-[a-z0-9_]+)?\.gguf$/i
7
+ const DIALOGUE_BACKBONE_RE = /^moss-ttsd(-[a-z0-9_]+)?\.gguf$/i
8
+ const REQUIRED_MODELS = {
9
+ QVAC_TEST_MOSS_MODEL_DIR: [
10
+ ['TTS backbone', /^moss-tts-delay(-[a-z0-9_]+)?\.gguf$/i],
11
+ ['TTSD backbone', DIALOGUE_BACKBONE_RE],
12
+ ['codec decoder', /^moss-codec-decoder(-[a-z0-9_]+)?\.gguf$/i],
13
+ ['codec encoder', ENCODER_RE]
14
+ ],
15
+ QVAC_TEST_MOSS_SPEECH_MODEL_DIR: [
16
+ ['Speech backbone', /^moss-speech(-(?!codec)[a-z0-9_]+)?\.gguf$/i],
17
+ ['Speech codec', /^moss-speech-codec(-[a-z0-9_]+)?\.gguf$/i]
18
+ ]
19
+ }
20
+
21
+ function requireValidation(condition, message) {
22
+ if (!condition) throw new Error(`MOSS full GPU validation: ${message}`)
23
+ }
24
+
25
+ function isFile(file) {
26
+ return fs.existsSync(file) && fs.statSync(file).isFile()
27
+ }
28
+
29
+ // Called before either suite registers tests. Reuse each suite's reference WAV
30
+ // resolver so preflight and inference cannot silently select different audio.
31
+ function createMossGpuValidation(env, referenceAudio, gpuOnlyUseGPU = true) {
32
+ const enabled = env.QVAC_TEST_MOSS_FULL_GPU === 'true'
33
+ const completed = new Set()
34
+ if (enabled) {
35
+ requireValidation(env.NO_GPU !== 'true', 'NO_GPU=true conflicts with full GPU validation')
36
+ requireValidation(gpuOnlyUseGPU, 'full GPU validation requires the desktop GPU cases')
37
+ requireValidation(
38
+ ['cuda', 'vulkan', 'metal', 'opencl'].includes((env.TTS_CPP_GPU_BACKEND || '').toLowerCase()),
39
+ 'set TTS_CPP_GPU_BACKEND to cuda, vulkan, metal or opencl'
40
+ )
41
+ for (const [variable, requirements] of Object.entries(REQUIRED_MODELS)) {
42
+ const directory = env[variable]
43
+ requireValidation(
44
+ directory && fs.existsSync(directory) && fs.statSync(directory).isDirectory(),
45
+ `${variable} must name an existing model directory`
46
+ )
47
+ const files = fs.readdirSync(directory).filter((entry) => isFile(path.join(directory, entry)))
48
+ for (const [label, pattern] of requirements) {
49
+ requireValidation(
50
+ files.some((file) => pattern.test(file)),
51
+ `${variable}: missing ${label}`
52
+ )
53
+ }
54
+ }
55
+ requireValidation(isFile(referenceAudio), `reference WAV is missing: ${referenceAudio}`)
56
+ }
57
+ return {
58
+ enabled,
59
+ completed(caseName) {
60
+ completed.add(caseName)
61
+ },
62
+ assertComplete(t, expected) {
63
+ for (const caseName of expected) {
64
+ t.ok(completed.has(caseName), `full GPU validation executed ${caseName}`)
65
+ }
66
+ }
67
+ }
68
+ }
69
+
70
+ module.exports = { createMossGpuValidation, ENCODER_RE, DIALOGUE_BACKBONE_RE }
@@ -0,0 +1,275 @@
1
+ 'use strict'
2
+ // Performance-recording helper shared by the tts-ggml integration tests
3
+ // (Chatterbox English/MTL, Supertonic, Supertonic MTL, GPU smoke). Holds the
4
+ // singleton perf-reporter, the mobile-safe inline fallback, and
5
+ // `recordTtsStats()` which turns an addon `response.stats` payload into a perf
6
+ // row.
7
+ //
8
+ // Lives in test/utils/ (not test/integration/) so it sits next to the other
9
+ // shared runners (runChatterboxTTS.js, runSupertonicTTS.js, ...) and is never
10
+ // picked up by the mobile test generator or the brittle test runner, which
11
+ // only discover test/integration/*.test.js.
12
+ //
13
+ // Mirrors the structure of the Parakeet/LLM helpers: on desktop we require the
14
+ // shared scripts/test-utils/performance-reporter directly; on mobile that path
15
+ // lives outside the addon package and bare-pack can't bundle it, so we fall
16
+ // back to an inline lightweight reporter that emits [PERF_REPORT_START]/
17
+ // [PERF_CHUNK] markers extract-from-log.js already understands.
18
+
19
+ const fs = require('bare-fs')
20
+ const path = require('bare-path')
21
+ const os = require('bare-os')
22
+ const process = require('bare-process')
23
+
24
+ const platform = os.platform()
25
+ const arch = os.arch()
26
+ const platformLabel = `${platform}-${arch}`
27
+ const isMobile = platform === 'ios' || platform === 'android'
28
+
29
+ // Inject bare-subprocess so performance-reporter.js's _detectGpu() can shell
30
+ // out to nvidia-smi / vulkaninfo / system_profiler on desktop runners.
31
+ // Resolving from this caller file works (it lives next to the addon's
32
+ // node_modules); resolving from inside scripts/test-utils/ does not because
33
+ // require('child_process') throws under Bare. Without this, device.gpu stays
34
+ // null and the perf report shows "N/A" for the GPU. Mirrors the LLM addon's
35
+ // _perf-helper.js. Mobile doesn't need it — the inline fallback below leaves
36
+ // gpu null on Device Farm where the probes wouldn't work anyway.
37
+ let _subprocess = null
38
+ try {
39
+ _subprocess = require('bare-subprocess')
40
+ } catch (_) {}
41
+
42
+ let createPerformanceReporter
43
+ const _scriptBase = path.join('..', '..', '..', '..', 'scripts', 'test-utils')
44
+ try {
45
+ const perfReporterMod = require(path.join(_scriptBase, 'performance-reporter'))
46
+ perfReporterMod.configure({ fs, path, process, os, subprocess: _subprocess })
47
+ createPerformanceReporter = perfReporterMod.createPerformanceReporter
48
+ } catch (_) {
49
+ createPerformanceReporter = function (opts) {
50
+ const _results = []
51
+ const _startedAt = new Date().toISOString()
52
+ const _addon = (opts && opts.addon) || 'tts-ggml'
53
+ const _addonType = (opts && opts.addonType) || 'tts'
54
+ const _device = {
55
+ name: platform,
56
+ platform,
57
+ os_version: '',
58
+ arch: os.arch ? os.arch() : '',
59
+ // GPU label only filled in for desktop runners by
60
+ // performance-reporter.js's _detectGpu(). On Device Farm we leave it
61
+ // null and let the aggregator fall back to the device name.
62
+ gpu: null,
63
+ runner: 'device-farm'
64
+ }
65
+
66
+ return {
67
+ record(testName, metrics, extra) {
68
+ const entry = {
69
+ test: testName,
70
+ execution_provider: (extra && extra.execution_provider) || null,
71
+ model: (extra && extra.model) || null,
72
+ metrics: Object.assign(
73
+ {
74
+ total_time_ms: null,
75
+ tps: null,
76
+ real_time_factor: null,
77
+ sample_count: null,
78
+ audio_duration_ms: null
79
+ },
80
+ metrics
81
+ ),
82
+ input: (extra && extra.input) || null,
83
+ output: (extra && extra.output) || null
84
+ }
85
+ _results.push(entry)
86
+ },
87
+ toJSON() {
88
+ return {
89
+ schema_version: '1.0',
90
+ addon: _addon,
91
+ addon_type: _addonType,
92
+ timestamp: _startedAt,
93
+ device: _device,
94
+ results: _results
95
+ }
96
+ },
97
+ writeReport() {
98
+ const json = JSON.stringify(this.toJSON())
99
+ const dirs = []
100
+ if (global.testDir) dirs.push(global.testDir)
101
+ if (platform === 'android') {
102
+ dirs.push('/sdcard/Android/data/io.tether.test.qvac/files')
103
+ dirs.push('/storage/emulated/0/Android/data/io.tether.test.qvac/files')
104
+ dirs.push('/data/local/tmp')
105
+ }
106
+ dirs.push('/tmp')
107
+ for (let di = 0; di < dirs.length; di++) {
108
+ try {
109
+ try {
110
+ fs.mkdirSync(dirs[di], { recursive: true })
111
+ } catch (_) {}
112
+ const p = path.join(dirs[di], 'perf-report.json')
113
+ fs.writeFileSync(p, json)
114
+ console.log('[PERF_REPORT_PATH]' + p)
115
+ } catch (e) {
116
+ console.log('[perf-reporter] write to ' + dirs[di] + ' failed: ' + e.message)
117
+ }
118
+ }
119
+ },
120
+ writeStepSummary() {},
121
+ writeToConsole() {
122
+ try {
123
+ const json = JSON.stringify(this.toJSON())
124
+ const CHUNK = 800
125
+ if (json.length <= CHUNK) {
126
+ console.log('[PERF_REPORT_START]' + json + '[PERF_REPORT_END]')
127
+ } else {
128
+ const id = Date.now().toString(36)
129
+ const n = Math.ceil(json.length / CHUNK)
130
+ for (let i = 0; i < n; i++) {
131
+ console.log(
132
+ '[PERF_CHUNK:' +
133
+ id +
134
+ ':' +
135
+ i +
136
+ ':' +
137
+ n +
138
+ ']' +
139
+ json.substring(i * CHUNK, (i + 1) * CHUNK)
140
+ )
141
+ }
142
+ }
143
+ } catch (err) {
144
+ console.log('[perf-reporter] mobile console write failed: ' + err.message)
145
+ }
146
+ },
147
+ get length() {
148
+ return _results.length
149
+ }
150
+ }
151
+ }
152
+ }
153
+
154
+ const _perfReporter = createPerformanceReporter({
155
+ addon: 'tts-ggml',
156
+ addonType: 'tts'
157
+ })
158
+
159
+ const _reportPath = path.resolve('.', 'test/results/performance-report.json')
160
+ let _reportScheduled = false
161
+
162
+ function _flushPerfReport() {
163
+ if (_perfReporter.length === 0) return
164
+ try {
165
+ _perfReporter.writeReport(_reportPath)
166
+ } catch (_) {}
167
+ try {
168
+ _perfReporter.writeStepSummary()
169
+ } catch (_) {}
170
+ try {
171
+ _perfReporter.writeToConsole()
172
+ } catch (_) {}
173
+ }
174
+
175
+ function _scheduleReportWrite() {
176
+ if (_reportScheduled) return
177
+ _reportScheduled = true
178
+ process.on('exit', _flushPerfReport)
179
+ }
180
+
181
+ function _num(v) {
182
+ return typeof v === 'number' && Number.isFinite(v) ? v : null
183
+ }
184
+
185
+ /**
186
+ * Record a Chatterbox (ggml) synthesis stats row through the shared perf
187
+ * reporter.
188
+ *
189
+ * @param {string} label - Test label, e.g. 'chatterbox english 1'. A leading
190
+ * [CPU]/[GPU] is optional and only used as a fallback
191
+ * hint — the row is tagged from the resolved backend
192
+ * (stats.backendDevice) when available, and the prefix
193
+ * is normalized to match.
194
+ * @param {Object} stats - response.stats from the addon:
195
+ * { realTimeFactor, audioDurationMs, totalSamples,
196
+ * backendDevice, ... }
197
+ * @param {Object} [extra] - Optional overrides:
198
+ * { wallMs, sampleCount, model, output,
199
+ * executionProvider }.
200
+ */
201
+ function recordTtsStats(label, stats, extra) {
202
+ const s = stats || {}
203
+ const resolvedEp = s.backendDevice === 1 ? 'gpu' : s.backendDevice === 0 ? 'cpu' : null
204
+ const epOverride = extra && extra.executionProvider
205
+ const labelEp = /\[gpu\]/i.test(label) ? 'gpu' : /\[cpu\]/i.test(label) ? 'cpu' : null
206
+ const ep = resolvedEp || epOverride || labelEp
207
+
208
+ const baseLabel = label.replace(/^\s*\[(?:cpu|gpu)\]\s*/i, '')
209
+ const finalLabel = ep ? `[${ep.toUpperCase()}] ${baseLabel}` : baseLabel
210
+
211
+ const rtf = _num(s.realTimeFactor)
212
+ const sampleCount =
213
+ (extra && _num(extra.sampleCount)) != null ? _num(extra.sampleCount) : _num(s.totalSamples)
214
+ const audioMs = _num(s.audioDurationMs) != null ? Math.round(_num(s.audioDurationMs)) : null
215
+ const wallMs = extra && _num(extra.wallMs) != null ? Math.round(_num(extra.wallMs)) : null
216
+ const tps = _num(s.tokensPerSecond)
217
+
218
+ // When the addon doesn't report a positive realTimeFactor (e.g. Supertonic /
219
+ // some GPU paths), derive it from the measured wall time and audio duration
220
+ // — the same fallback the RTF benchmark uses — so the row still carries an
221
+ // RTF instead of n/a. Callers that already pass a derived realTimeFactor
222
+ // (addon.test.js) keep it untouched.
223
+ //
224
+ // The two bases aren't comparable (compute-RTF excludes JS/marshalling
225
+ // overhead that wall-RTF includes), so record rtf_source per row: anyone
226
+ // comparing numbers across rows in a single report can see which is which.
227
+ const usingComputeRtf = rtf != null && rtf > 0
228
+ const effRtf = usingComputeRtf ? rtf : wallMs != null && audioMs ? wallMs / audioMs : null
229
+ const rtfSource = usingComputeRtf ? 'compute' : effRtf != null ? 'wall' : null
230
+
231
+ _perfReporter.record(
232
+ finalLabel,
233
+ {
234
+ total_time_ms: wallMs,
235
+ tps,
236
+ real_time_factor: effRtf,
237
+ rtf_source: rtfSource,
238
+ sample_count: sampleCount,
239
+ audio_duration_ms: audioMs
240
+ },
241
+ {
242
+ execution_provider: ep,
243
+ model: (extra && extra.model) || null,
244
+ output: extra && extra.output ? String(extra.output) : null
245
+ }
246
+ )
247
+ _scheduleReportWrite()
248
+
249
+ if (isMobile) {
250
+ try {
251
+ _perfReporter.writeReport()
252
+ } catch (_) {}
253
+ try {
254
+ _perfReporter.writeToConsole()
255
+ } catch (_) {}
256
+ }
257
+
258
+ const lines = [
259
+ `${finalLabel} Performance Metrics (platform=${platformLabel}):`,
260
+ ` - Wall time: ${wallMs !== null ? wallMs + 'ms' : 'n/a'}`,
261
+ ` - RTF: ${effRtf !== null ? effRtf.toFixed(4) + ' (' + rtfSource + ')' : 'n/a'}`,
262
+ ` - Samples: ${sampleCount !== null ? sampleCount : 'n/a'}`,
263
+ ` - Audio: ${audioMs !== null ? audioMs + 'ms' : 'n/a'}`
264
+ ]
265
+ return lines.join('\n')
266
+ }
267
+
268
+ module.exports = {
269
+ platform,
270
+ arch,
271
+ platformLabel,
272
+ isMobile,
273
+ recordTtsStats,
274
+ flushTtsPerfReport: _flushPerfReport
275
+ }
@@ -0,0 +1,5 @@
1
+ 'use strict'
2
+
3
+ const TTS_TEST_THREADS = 4
4
+
5
+ module.exports = { TTS_TEST_THREADS }
package/lib/backends.d.ts DELETED
@@ -1,10 +0,0 @@
1
- export declare const PREBUILT_HOSTS: string[];
2
- export interface BackendsDirSources {
3
- localPrebuildsDir: string;
4
- host: string | null;
5
- directoryExists: (dir: string) => boolean;
6
- resolveManifest: (specifier: string) => string | null;
7
- }
8
- export declare function hostPlatformPackage(host: string): string;
9
- export declare function resolveBackendsDirFrom(sources: BackendsDirSources): string;
10
- export declare function resolveBackendsDir(): string;
package/lib/backends.js DELETED
@@ -1,76 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PREBUILT_HOSTS = void 0;
4
- exports.hostPlatformPackage = hostPlatformPackage;
5
- exports.resolveBackendsDirFrom = resolveBackendsDirFrom;
6
- exports.resolveBackendsDir = resolveBackendsDir;
7
- /* eslint-disable @typescript-eslint/no-require-imports -- Bare modules expose CommonJS export shapes. */
8
- const fs = require("bare-fs");
9
- const path = require("bare-path");
10
- /* eslint-enable @typescript-eslint/no-require-imports */
11
- const PACKAGE_ROOT = path.join(__dirname, "..");
12
- const PREBUILDS_DIR_NAME = "prebuilds";
13
- const PLATFORM_ADDON_DIR_NAME = "addon";
14
- const PLATFORM_PACKAGE_PREFIX = "@qvac/tts-ggml-";
15
- const PLATFORM_MANIFEST_SUBPATH = "/package";
16
- const IOS_PLATFORM = "ios";
17
- const HOST_SEPARATOR = "-";
18
- exports.PREBUILT_HOSTS = [
19
- "linux-x64",
20
- "linux-arm64",
21
- "darwin-arm64",
22
- "darwin-x64",
23
- "win32-x64",
24
- "android-arm64",
25
- "ios-arm64",
26
- "ios-arm64-simulator",
27
- "ios-x64-simulator",
28
- ];
29
- function hostPlatformPackage(host) {
30
- const platform = host.split(HOST_SEPARATOR)[0];
31
- const suffix = platform === IOS_PLATFORM ? IOS_PLATFORM : host;
32
- return PLATFORM_PACKAGE_PREFIX + suffix;
33
- }
34
- function resolveBackendsDirFrom(sources) {
35
- if (sources.directoryExists(sources.localPrebuildsDir)) {
36
- return sources.localPrebuildsDir;
37
- }
38
- return platformPackagePrebuildsDir(sources) ?? sources.localPrebuildsDir;
39
- }
40
- function platformPackagePrebuildsDir(sources) {
41
- if (!sources.host) {
42
- return null;
43
- }
44
- const manifestPath = sources.resolveManifest(hostPlatformPackage(sources.host) + PLATFORM_MANIFEST_SUBPATH);
45
- if (!manifestPath) {
46
- return null;
47
- }
48
- return path.join(path.dirname(manifestPath), PLATFORM_ADDON_DIR_NAME, PREBUILDS_DIR_NAME);
49
- }
50
- function resolveBackendsDir() {
51
- return resolveBackendsDirFrom({
52
- localPrebuildsDir: path.join(PACKAGE_ROOT, PREBUILDS_DIR_NAME),
53
- host: currentHost(),
54
- directoryExists: safeDirectoryExists,
55
- resolveManifest: safeResolveManifest,
56
- });
57
- }
58
- function currentHost() {
59
- return require.addon ? require.addon.host : null;
60
- }
61
- function safeDirectoryExists(dir) {
62
- try {
63
- return fs.existsSync(dir);
64
- }
65
- catch {
66
- return false;
67
- }
68
- }
69
- function safeResolveManifest(specifier) {
70
- try {
71
- return require.resolve(specifier);
72
- }
73
- catch {
74
- return null;
75
- }
76
- }