diff --git a/docs/sdk.md b/docs/sdk.md index 2dbae8a..0d9d7cc 100644 --- a/docs/sdk.md +++ b/docs/sdk.md @@ -88,6 +88,9 @@ int transcribe(const float* samples, size_t count, int sample_rate) { nemo_speech_asr_backend_config backend{}; backend.size = sizeof(backend); backend.gpu = 0; // -1 for CPU + // backend.threads = 4; // CPU backend threads; 0 = min(8, usable CPUs). On Linux that + // follows the CPU affinity mask and the cgroup v2 quota (a cgroup v1 quota is not read); + // other platforms use the hardware thread count. nemo_speech_asr_model_config model{}; model.size = sizeof(model); diff --git a/include/nemo_speech/asr.h b/include/nemo_speech/asr.h index 8658345..8573f4c 100644 --- a/include/nemo_speech/asr.h +++ b/include/nemo_speech/asr.h @@ -63,6 +63,12 @@ typedef enum nemo_speech_asr_decoder_kind { typedef struct nemo_speech_asr_backend_config { size_t size; int32_t gpu; // -1 = CPU + // Unused. Fills what was tail padding on 64-bit targets, so `size` from a caller built + // before `threads` existed never covers it. + int32_t reserved; + // CPU backend threads; 0 = min(8, usable CPUs): on Linux the CPU affinity mask and the + // cgroup v2 quota (a cgroup v1 quota is not read), elsewhere the hardware thread count. + int32_t threads; } nemo_speech_asr_backend_config; typedef struct nemo_speech_asr_model_config { diff --git a/include/nemo_speech/tts.h b/include/nemo_speech/tts.h index 9cb2547..925e6a9 100644 --- a/include/nemo_speech/tts.h +++ b/include/nemo_speech/tts.h @@ -76,7 +76,9 @@ typedef struct nemo_speech_tts_model_config { typedef struct nemo_speech_tts_runtime_config { size_t size; int32_t speaker; - int32_t threads; // CPU threads; 0 = min(8, hardware threads) + // CPU threads; 0 = min(8, usable CPUs): on Linux the CPU affinity mask and the cgroup v2 + // quota (a cgroup v1 quota is not read), elsewhere the hardware thread count. + int32_t threads; int32_t codec_threads; // 0 = threads int32_t seed; int32_t steps; diff --git a/src/asr/CMakeLists.txt b/src/asr/CMakeLists.txt index 32a9ee3..af3c1f5 100644 --- a/src/asr/CMakeLists.txt +++ b/src/asr/CMakeLists.txt @@ -91,7 +91,8 @@ target_include_directories(nemo_speech_asr_c PUBLIC $ $) target_compile_definitions(nemo_speech_asr_c PRIVATE NEMO_SPEECH_ASR_BUILD) -# SOVERSION 2: nemo_speech_asr_salm_config grew (n_cpu_moe, batched) +# SOVERSION 2: nemo_speech_asr_salm_config grew (n_cpu_moe, batched); since then +# nemo_speech_asr_backend_config grew too (reserved, threads), append-only, same SOVERSION set_target_properties(nemo_speech_asr_c PROPERTIES CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN ON diff --git a/src/asr/c_api.cpp b/src/asr/c_api.cpp index 184d0cc..3ed2fa9 100644 --- a/src/asr/c_api.cpp +++ b/src/asr/c_api.cpp @@ -72,6 +72,8 @@ to_config(const nemo_speech_asr_recognizer_config* c) { const auto* b = c->backend; if (HAS_FIELD(b, nemo_speech_asr_backend_config, gpu)) cfg.backend.gpu = b->gpu; + if (HAS_FIELD(b, nemo_speech_asr_backend_config, threads) && b->threads > 0) + cfg.backend.threads = b->threads; } if (HAS_FIELD(c, nemo_speech_asr_recognizer_config, model) && c->model) { const auto* m = c->model; diff --git a/src/asr/recognizer.cpp b/src/asr/recognizer.cpp index e5f7e43..eb4ebe6 100644 --- a/src/asr/recognizer.cpp +++ b/src/asr/recognizer.cpp @@ -15,6 +15,7 @@ #include #include +#include "cpu_threads.h" #include "gguf.h" #include "model.h" #include "silero_vad.h" @@ -45,13 +46,7 @@ make_backend(const BackendConfig& backend) { p.use_gpu = (backend.gpu >= 0); p.gpu_device_idx = std::max(backend.gpu, 0); p.pe_bin_path = const_cast(""); - if (backend.threads > 0) { - p.n_threads = backend.threads; - } else { - // More busy-waiting CPU workers than hardware threads slows the graph down. - const unsigned hw = std::thread::hardware_concurrency(); - p.n_threads = hw > 0 ? std::min(8, static_cast(hw)) : 8; - } + p.n_threads = backend.threads > 0 ? backend.threads : common::default_cpu_threads(); return std::make_unique(p); } diff --git a/src/asr/recognizer.h b/src/asr/recognizer.h index 0b0f804..36d035d 100644 --- a/src/asr/recognizer.h +++ b/src/asr/recognizer.h @@ -31,10 +31,12 @@ class Recognizer; struct BackendConfig { int gpu = 0; // -1 = CPU - int threads = 0; // CPU backend threads; 0 = min(8, hardware threads) + int threads = 0; // CPU backend threads; 0 = min(8, usable CPUs) void Register(common::ParameterParser& p) { p.Register("gpu", &gpu, "GPU device index (-1 = CPU)", {"--gpu", "-g"}); - p.Register("threads", &threads, "CPU backend threads (0 = min(8, hardware threads))"); + p.Register( + "threads", &threads, + "CPU backend threads (0 = min(8, usable CPUs: Linux affinity and cgroup v2 quota))"); } }; diff --git a/src/common/cpu_threads.h b/src/common/cpu_threads.h new file mode 100644 index 0000000..fcf20ec --- /dev/null +++ b/src/common/cpu_threads.h @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// Default CPU thread count of the compute backends. +#pragma once + +#include +#include +#include +#include + +#if defined(__linux__) +#include +#endif + +namespace nemo_speech::common { + +// CPU limit in a cgroup v2 cpu.max file (" " in microseconds, or "max "), +// rounded up to whole CPUs. 0 = no limit, also when the file is missing or unreadable. +inline int +cgroup_cpu_limit(const char* cpu_max_path) { + long long quota = 0; + long long period = 0; + std::FILE* f = std::fopen(cpu_max_path, "r"); + if (!f) + return 0; + const bool parsed = std::fscanf(f, "%lld %lld", "a, &period) == 2; + std::fclose(f); + if (!parsed || quota <= 0 || period <= 0) + return 0; + const long long cpus = quota / period + (quota % period != 0 ? 1 : 0); + return static_cast(std::min(cpus, INT_MAX)); +} + +// min(8, CPUs this process may use). More busy-waiting CPU workers than usable CPUs slows +// the graphs down, so on Linux the count follows the CPU affinity mask and the cgroup v2 CPU +// quota as seen at /sys/fs/cgroup/cpu.max (a container limited to 4 CPUs gets 4 threads, +// whatever the host has). +inline int +default_cpu_threads() { + int cpus = static_cast(std::thread::hardware_concurrency()); +#if defined(__linux__) + // The calling thread's mask, which the backend's workers inherit. + cpu_set_t set; + if (sched_getaffinity(0, sizeof(set), &set) == 0) + cpus = CPU_COUNT(&set); + if (const int limit = cgroup_cpu_limit("/sys/fs/cgroup/cpu.max"); limit > 0) + cpus = std::min(cpus, limit); +#endif + return cpus > 0 ? std::min(8, cpus) : 8; +} + +} // namespace nemo_speech::common diff --git a/src/speechlm/salm_recognizer.cpp b/src/speechlm/salm_recognizer.cpp index 5759484..cb0e5d6 100644 --- a/src/speechlm/salm_recognizer.cpp +++ b/src/speechlm/salm_recognizer.cpp @@ -22,6 +22,7 @@ #include #include "audio_resampler.h" +#include "cpu_threads.h" #include "errors.h" #include "salm_engine.h" #include "salm_guards.h" @@ -60,12 +61,9 @@ engine_config(const asr::RecognizerConfig& c) { out.ctc_path = s.ctc_path; out.llm_path = c.model.path; out.gpu = c.backend.gpu; - // host-side decoder work: asr.backend.threads, as for the other models (0 = min(8, hardware - // threads)) - const unsigned hw = std::thread::hardware_concurrency(); - out.threads = c.backend.threads > 0 ? c.backend.threads - : hw > 0 ? std::min(8, static_cast(hw)) - : 8; + // host-side decoder work: asr.backend.threads, as for the other models (0 = min(8, usable + // CPUs)) + out.threads = c.backend.threads > 0 ? c.backend.threads : common::default_cpu_threads(); out.max_sequences = s.max_sequences; out.n_ctx_per_sequence = s.n_ctx_per_sequence; out.max_context = s.max_context; diff --git a/src/tts/magpietts/config.cpp b/src/tts/magpietts/config.cpp index ed22b6d..c2276ea 100644 --- a/src/tts/magpietts/config.cpp +++ b/src/tts/magpietts/config.cpp @@ -136,7 +136,9 @@ register_runtime_config(common::ParameterParser& p, MagpieRuntimeConfig& c) { p.Register("codec-model", &c.codec_model, "NanoCodec decoder GGUF path"); p.Register("speaker", &c.speaker, "Default baked speaker index"); p.Register( - "threads", &c.threads, "CPU threads for Magpie and codec (0 = min(8, hardware threads))", + "threads", &c.threads, + "CPU threads for Magpie and codec (0 = min(8, usable CPUs: Linux affinity and cgroup v2 " + "quota))", {"--threads"}); p.Register("codec-threads", &c.codec_threads, "Codec CPU threads; 0 uses threads"); p.Register("seed", &c.seed, "Default RNG seed; -1 uses current time"); diff --git a/src/tts/magpietts/runtime.cpp b/src/tts/magpietts/runtime.cpp index edff096..78ff51a 100644 --- a/src/tts/magpietts/runtime.cpp +++ b/src/tts/magpietts/runtime.cpp @@ -7,9 +7,9 @@ #include #include #include -#include #include +#include "cpu_threads.h" #include "magpietts.h" #include "model_logging.h" #include "token_utils.h" @@ -170,13 +170,7 @@ class MagpieTtsRuntime::Impl { params.warmup_tokens = tokens; params.warmup_token_chunks = token_chunks; params.speaker = options.speaker >= 0 ? options.speaker : config_.speaker; - if (config_.threads > 0) { - params.threads = config_.threads; - } else { - // More busy-waiting CPU workers than hardware threads slows the graphs down. - const unsigned hw = std::thread::hardware_concurrency(); - params.threads = hw > 0 ? std::min(8, static_cast(hw)) : 8; - } + params.threads = config_.threads > 0 ? config_.threads : common::default_cpu_threads(); params.codec_threads = config_.codec_threads > 0 ? config_.codec_threads : params.threads; params.seed = options.seed >= 0 ? options.seed : config_.seed; params.steps = options.steps > 0 ? options.steps : config_.steps; diff --git a/src/tts/magpietts/runtime.h b/src/tts/magpietts/runtime.h index 684dfcf..75badfc 100644 --- a/src/tts/magpietts/runtime.h +++ b/src/tts/magpietts/runtime.h @@ -32,7 +32,7 @@ struct MagpieRuntimeConfig { std::string magpie_model; std::string codec_model; int speaker = 0; - int threads = 0; // 0 = min(8, hardware threads) + int threads = 0; // 0 = min(8, usable CPUs: Linux affinity and cgroup v2 quota) int codec_threads = 0; // 0 = threads int seed = -1; int steps = -1; diff --git a/tests/cpp/CMakeLists.txt b/tests/cpp/CMakeLists.txt index 189d491..680fb30 100644 --- a/tests/cpp/CMakeLists.txt +++ b/tests/cpp/CMakeLists.txt @@ -20,6 +20,11 @@ add_executable(test_subtitles target_link_libraries(test_subtitles PRIVATE nemo_speech_common) add_test(NAME subtitles COMMAND test_subtitles) +add_executable(test_cpu_threads + ${CMAKE_SOURCE_DIR}/tests/cpp/common/test_cpu_threads.cpp) +target_link_libraries(test_cpu_threads PRIVATE nemo_speech_common) +add_test(NAME cpu_threads COMMAND test_cpu_threads) + add_executable(test_audio_ingest ${CMAKE_SOURCE_DIR}/tests/cpp/common/test_audio_ingest.cpp) target_link_libraries(test_audio_ingest PRIVATE nemo_speech_common) diff --git a/tests/cpp/common/test_cpu_threads.cpp b/tests/cpp/common/test_cpu_threads.cpp new file mode 100644 index 0000000..9be9c4c --- /dev/null +++ b/tests/cpp/common/test_cpu_threads.cpp @@ -0,0 +1,80 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) +#include +#endif + +#include "cpu_threads.h" + +namespace { + +void +require(bool condition, const char* message) { + if (!condition) { + std::cerr << "FAIL: " << message << '\n'; + std::exit(1); + } +} + +int +limit_of(const std::string& path, const char* cpu_max) { + std::ofstream(path) << cpu_max; + return nemo_speech::common::cgroup_cpu_limit(path.c_str()); +} + +} // namespace + +int +main() { + using nemo_speech::common::cgroup_cpu_limit; + using nemo_speech::common::default_cpu_threads; + + // A directory of this run only: create_directory fails on a name that exists, so runs do not + // share the fixture and nothing placed in the temporary directory beforehand is followed. + std::filesystem::path dir; + std::random_device random; + do { + dir = std::filesystem::temp_directory_path() / + ("nemo_speech_test_cpu_threads_" + std::to_string(random())); + } while (!std::filesystem::create_directory(dir)); + const std::string path = (dir / "cpu.max").string(); + require(limit_of(path, "max 100000\n") == 0, "max is no limit"); + require(limit_of(path, "200000 100000\n") == 2, "two CPUs"); + require(limit_of(path, "250000 100000\n") == 3, "a fractional quota rounds up"); + require(limit_of(path, "0 100000\n") == 0, "a zero quota is no limit"); + require(limit_of(path, "9223372036854775807 1\n") == INT_MAX, "a huge quota does not wrap"); + require(limit_of(path, "") == 0, "an empty file is no limit"); + std::filesystem::remove_all(dir); + require(cgroup_cpu_limit(path.c_str()) == 0, "a missing file is no limit"); + + const int threads = default_cpu_threads(); + std::cout << "default_cpu_threads: " << threads << '\n'; + require(threads >= 1 && threads <= 8, "default is within [1, 8]"); +#if defined(__linux__) + // The mask does not fit a cpu_set_t on hosts with more than 1024 CPUs; the library falls + // back to the hardware thread count there. + cpu_set_t allowed; + if (sched_getaffinity(0, sizeof(allowed), &allowed) == 0) { + require(threads <= CPU_COUNT(&allowed), "default does not exceed the affinity mask"); + // Pin the process to one of its CPUs: the default follows the mask, not the host. + int cpu = 0; + while (!CPU_ISSET(cpu, &allowed)) ++cpu; + cpu_set_t one; + CPU_ZERO(&one); + CPU_SET(cpu, &one); + require(sched_setaffinity(0, sizeof(one), &one) == 0, "sched_setaffinity"); + require(default_cpu_threads() == 1, "one usable CPU gives one thread"); + } +#endif + std::cout << "PASS\n"; + return 0; +}