Skip to content

Expose ONNX Runtime memory arena options in session/public API - #3500

Closed
negbie wants to merge 4 commits into
k2-fsa:masterfrom
negbie:master
Closed

negbie wants to merge 4 commits into
k2-fsa:masterfrom
negbie:master

Conversation

@negbie

@negbie negbie commented Apr 11, 2026 •

Copy link
Copy Markdown
Contributor

This PR exposes ONNX Runtime memory allocation settings so users can control:

  • enable_mem_pattern
  • enable_cpu_mem_arena

The main motivation is to allow bindings and downstream users to disable ONNX Runtime memory arena behavior when needed, while keeping the current default behavior unchanged.

Summary by CodeRabbit

  • New Features
    • Added tri-state toggles for ONNX Runtime CPU memory arena and memory pattern across many model configs (ASR, VAD, TTS, spoken-language ID, speaker embedding, keyword spotting, audio tagging, punctuation, speaker segmentation, denoiser, source separation). Defaults are enabled; configs can explicitly enable, disable, or inherit the default behavior.

…preserving default behavior

This PR exposes ONNX Runtime memory allocation settings so users can control:

- `enable_mem_pattern`
- `enable_cpu_mem_arena`

The main motivation is to allow bindings and downstream users to disable ONNX Runtime memory arena behavior when needed, while keeping the current default behavior unchanged.
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 11, 2026
@negbie negbie changed the title Expose ONNX Runtime memory arena options in session/public API while … Expose ONNX Runtime memory arena options in session/public API Apr 11, 2026
@coderabbitai

coderabbitai Bot commented Apr 11, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 492bcebb-3291-4bf7-ad31-33806d011d1e

📥 Commits

Reviewing files that changed from the base of the PR and between 5a1dc37 and 2988337.

📒 Files selected for processing (2)
  • sherpa-onnx/c-api/c-api.cc
  • sherpa-onnx/c-api/c-api.h
✅ Files skipped from review due to trivial changes (1)
  • sherpa-onnx/c-api/c-api.cc
🚧 Files skipped from review as they are similar to previous changes (1)
  • sherpa-onnx/c-api/c-api.h

📝 Walkthrough

Walkthrough

Adds two ONNX Runtime tuning flags—enable_cpu_mem_arena and enable_mem_pattern—to many public and internal model/config structs, propagates them into ProviderConfig, and uses them when constructing session options to conditionally call ONNX Runtime APIs that disable mem-pattern or CPU mem-arena.

Changes

Cohort / File(s) Summary
C API headers
sherpa-onnx/c-api/c-api.h
Added int32_t enable_cpu_mem_arena and int32_t enable_mem_pattern to multiple public C structs (12 model/config types).
C API impl
sherpa-onnx/c-api/c-api.cc
Added internal resolver SherpaOnnxResolveOptionalBool(int32_t, bool) and populated memory flags when building internal configs for recognizers, VAD, keyword spotter, SLID, speaker extractor, punctuation, denoiser, TTS, etc.
C++ API headers & wrappers
sherpa-onnx/c-api/cxx-api.h, sherpa-onnx/c-api/cxx-api.cc
Added enable_cpu_mem_arena / enable_mem_pattern to C++ config structs (default true) and copied them into internal/C API configs during Create/Convert paths.
ProviderConfig
sherpa-onnx/csrc/provider-config.h, sherpa-onnx/csrc/provider-config.cc
Added enable_cpu_mem_arena and enable_mem_pattern members with constructor params (default true), registered parse options, and included them in ToString().
Session construction
sherpa-onnx/csrc/session.h, sherpa-onnx/csrc/session.cc
GetSessionOptions now constructs a ProviderConfig from config flags; GetSessionOptionsImpl conditionally calls sess_opts.DisableMemPattern() and sess_opts.DisableCpuMemArena() when flags are false.
Model config headers
sherpa-onnx/csrc/...-model-config.h
(audio-tagging, offline/online-punctuation, offline-tts, offline-source-separation, offline-speaker-segmentation, offline-speech-denoiser, offline-model-config, vad-model-config, speaker-embedding-extractor.h, spoken-language-identification.h, ...)
Added bool enable_cpu_mem_arena and bool enable_mem_pattern members (default true) and extended constructors to accept these optional parameters across numerous model config structs.

Sequence Diagram(s)

sequenceDiagram
    participant C as "C API / Caller"
    participant Cpp as "C++ API / Wrappers"
    participant Prov as "ProviderConfig"
    participant Sess as "SessionOptions"
    participant ORT as "ONNX Runtime"

    rect rgba(200,200,255,0.5)
    C->>Cpp: pass model/config (may include int flags)
    end

    rect rgba(200,255,200,0.5)
    Cpp->>Prov: construct ProviderConfig(provider, enable_cpu_mem_arena, enable_mem_pattern)
    end

    rect rgba(255,200,200,0.5)
    Prov->>Sess: GetSessionOptionsImpl(num_threads, provider, &Prov)
    Sess->>ORT: if enable_mem_pattern == false -> DisableMemPattern()
    Sess->>ORT: if enable_cpu_mem_arena == false -> DisableCpuMemArena()
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

size:XL

Suggested reviewers

  • csukuangfj

Poem

🐰 I hopped through structs and flags today,

toggled arenas in a tidy way,
patterns checked and options sewn,
configs travel from API to session throne,
now runtime hums with choices known.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.88% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately describes the main change: exposing ONNX Runtime memory arena configuration options (enable_cpu_mem_arena and enable_mem_pattern) in the public API across multiple config structs.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds support for configuring ONNX Runtime's CPU memory arena and memory pattern optimization across various components in the C and C++ APIs. Reviewers identified a logic error in the C API where the default value prevents users from disabling these features, a compilation error due to missing fields in the C++ OfflineModelConfig struct, and an issue where these settings are not correctly propagated to components that do not use ProviderConfig.

Comment thread sherpa-onnx/c-api/c-api.cc Outdated
Comment thread sherpa-onnx/c-api/cxx-api.cc
Comment thread sherpa-onnx/csrc/session.cc

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@sherpa-onnx/c-api/c-api.cc`:
- Around line 114-117: The code currently uses SHERPA_ONNX_OR(config->..., 1)
which coerces an explicit 0 to 1 so callers cannot disable flags; replace those
OR uses with a presence check that preserves explicit 0, e.g. use
SHERPA_ONNX_HAS(config->model_config.enable_cpu_mem_arena) ?
config->model_config.enable_cpu_mem_arena : 1 (and similarly for
enable_mem_pattern), and apply the same pattern to the other affected builders
(the places setting
recognizer_config.model_config.provider_config.enable_cpu_mem_arena,
enable_mem_pattern and the five other analogous flag assignments referenced in
the comment so an explicit 0 from the C API is honored).

In `@sherpa-onnx/c-api/c-api.h`:
- Around line 245-248: You added new fields into public C structs (e.g.,
SherpaOnnxOnlineModelConfig, SherpaOnnxOfflineModelConfig,
SherpaOnnxVadModelConfig, etc.), which breaks ABI; instead introduce versioned
structs (e.g., SherpaOnnxOnlineModelConfigV2, SherpaOnnxOfflineModelConfigV2,
SherpaOnnxVadModelConfigV2, etc.) that include the two new int32_t fields, leave
the original structs unchanged, and add new factory/create functions (e.g.,
SherpaOnnxCreateOnlineModelConfigV2 or SherpaOnnxOnlineModelConfig_CreateV2) and
overloaded/new model-creation APIs that accept the V2 types; internally convert
or map V2 -> internal representation used by existing code paths so runtime
behavior is unchanged for older binaries while new binaries can opt into V2
fields.

In `@sherpa-onnx/c-api/cxx-api.cc`:
- Around line 276-278: The C++ wrapper struct OfflineModelConfig is missing the
fields that the C API struct SherpaOnnxOfflineModelConfig exposes; add bool
enable_cpu_mem_arena and bool enable_mem_pattern to OfflineModelConfig in
cxx-api.h (with sensible defaults), then update the conversion helpers used in
cxx-api.cc (the functions that map between SherpaOnnxOfflineModelConfig and
OfflineModelConfig at the sites referencing these fields) to read/write these
two fields so the assignments at lines ~106–108, ~276–278 and ~701–703 compile
correctly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f846d7b0-1754-4f90-b132-5a4b1f4ec24a

📥 Commits

Reviewing files that changed from the base of the PR and between aa9019c and 45898be.

📒 Files selected for processing (7)
  • sherpa-onnx/c-api/c-api.cc
  • sherpa-onnx/c-api/c-api.h
  • sherpa-onnx/c-api/cxx-api.cc
  • sherpa-onnx/c-api/cxx-api.h
  • sherpa-onnx/csrc/provider-config.cc
  • sherpa-onnx/csrc/provider-config.h
  • sherpa-onnx/csrc/session.cc

Comment thread sherpa-onnx/c-api/c-api.cc Outdated
Comment thread sherpa-onnx/c-api/c-api.h Outdated
Comment thread sherpa-onnx/c-api/cxx-api.cc

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@sherpa-onnx/c-api/c-api.cc`:
- Around line 72-76: The resolver SherpaOnnxResolveOptionalBool currently treats
any negative v as "default" (v < 0) which contradicts its tri-state comment;
change the check to only treat v == -1 as the default case so that other
negative values are evaluated as non-zero/true or zero/false accordingly (update
the conditional in SherpaOnnxResolveOptionalBool to use v == -1 and keep the
fallback as (v != 0) with default_value returned when v == -1).
- Around line 72-76: The three offline C API builder functions
GetOfflineTtsConfig, GetOfflinePunctuationConfig, and
GetOfflineSpeechDenoiserConfig currently ignore the C struct fields
enable_cpu_mem_arena and enable_mem_pattern; update each builder to read those
fields from the corresponding C structs (SherpaOnnxOfflineTtsConfig,
SherpaOnnxOfflinePunctuationConfig, SherpaOnnxOfflineSpeechDenoiserConfig) and
assign them into the created C++ config via SherpaOnnxResolveOptionalBool (using
the same default semantics as the other offline builders). Follow the pattern
used in the existing builders (e.g.,
GetOfflineRecognizerConfig/GetOfflineVadConfig): call
SherpaOnnxResolveOptionalBool(arg->enable_cpu_mem_arena, default_value) and
SherpaOnnxResolveOptionalBool(arg->enable_mem_pattern, default_value) and set
the resulting booleans on the returned config object.

In `@sherpa-onnx/csrc/vad-model-config.h`:
- Around line 30-33: The VadModelConfig constructor currently requires the new
boolean flags enable_cpu_mem_arena and enable_mem_pattern which breaks existing
positional calls; update the constructor signature for VadModelConfig(const
SileroVadModelConfig&, const TenVadModelConfig&, int32_t sample_rate, int32_t
num_threads, const std::string& provider, bool enable_cpu_mem_arena = true, bool
enable_mem_pattern = true, bool debug) so both flags default to true, preserving
source compatibility and old behavior for existing call sites that do not pass
these arguments.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5974c839-1cbe-4e47-86da-a71d2d40f273

📥 Commits

Reviewing files that changed from the base of the PR and between 45898be and 66f7e8d.

📒 Files selected for processing (15)
  • sherpa-onnx/c-api/c-api.cc
  • sherpa-onnx/c-api/c-api.h
  • sherpa-onnx/c-api/cxx-api.h
  • sherpa-onnx/csrc/audio-tagging-model-config.h
  • sherpa-onnx/csrc/offline-model-config.h
  • sherpa-onnx/csrc/offline-punctuation-model-config.h
  • sherpa-onnx/csrc/offline-source-separation-model-config.h
  • sherpa-onnx/csrc/offline-speaker-segmentation-model-config.h
  • sherpa-onnx/csrc/offline-speech-denoiser-model-config.h
  • sherpa-onnx/csrc/offline-tts-model-config.h
  • sherpa-onnx/csrc/online-punctuation-model-config.h
  • sherpa-onnx/csrc/session.h
  • sherpa-onnx/csrc/speaker-embedding-extractor.h
  • sherpa-onnx/csrc/spoken-language-identification.h
  • sherpa-onnx/csrc/vad-model-config.h
✅ Files skipped from review due to trivial changes (1)
  • sherpa-onnx/c-api/c-api.h
🚧 Files skipped from review as they are similar to previous changes (1)
  • sherpa-onnx/c-api/cxx-api.h

Comment thread sherpa-onnx/c-api/c-api.cc Outdated
Comment thread sherpa-onnx/csrc/vad-model-config.h Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
sherpa-onnx/c-api/c-api.cc (1)

72-76: ⚠️ Potential issue | 🟡 Minor

Resolver semantics still don’t match the documented tri-state contract.

On Line 75, v < 0 treats all negative values as “default”, but the comment on Line 72 documents only -1 as default. This keeps behavior inconsistent for values like -2.

🔧 Proposed fix
 static inline bool SherpaOnnxResolveOptionalBool(int32_t v,
                                                  bool default_value) {
-  return v < 0 ? default_value : (v != 0);
+  return v == -1 ? default_value : (v != 0);
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@sherpa-onnx/c-api/c-api.cc` around lines 72 - 76, The resolver treats any
negative int as "default" but the contract says only -1 should be default;
update SherpaOnnxResolveOptionalBool to check for v == -1 instead of v < 0 so
only -1 returns default_value, e.g. change the condition in
SherpaOnnxResolveOptionalBool to "v == -1 ? default_value : (v != 0)"; keep the
rest of the logic unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@sherpa-onnx/c-api/c-api.cc`:
- Around line 72-76: The resolver treats any negative int as "default" but the
contract says only -1 should be default; update SherpaOnnxResolveOptionalBool to
check for v == -1 instead of v < 0 so only -1 returns default_value, e.g. change
the condition in SherpaOnnxResolveOptionalBool to "v == -1 ? default_value : (v
!= 0)"; keep the rest of the logic unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f26d28ca-d313-41fa-a4c6-bdb9c3816831

📥 Commits

Reviewing files that changed from the base of the PR and between 66f7e8d and 5a1dc37.

📒 Files selected for processing (2)
  • sherpa-onnx/c-api/c-api.cc
  • sherpa-onnx/csrc/vad-model-config.h
🚧 Files skipped from review as they are similar to previous changes (1)
  • sherpa-onnx/csrc/vad-model-config.h

@csukuangfj

Copy link
Copy Markdown
Collaborator

Thank you for your contribution!

Instead of introducing more fields, please use a config file, which is already supported.

What you need to do is to change only session.cc.

See also

if (config.find("LogSeverityLevel") != config.end()) {
int32_t log_severity_level = ToIntOrDefault(
config["LogSeverityLevel"],
static_cast<int32_t>(OrtLoggingLevel::ORT_LOGGING_LEVEL_WARNING));
sess_opts.SetLogSeverityLevel(
static_cast<OrtLoggingLevel>(log_severity_level));
config.erase("LogSeverityLevel");
}

You use it like

--provider="cpu:/path/to/your.config"

and your.config is a txt file, in which every line looks like below

foo = bar
LogSeverityLevel = 1
enable_mem_pattern = 1
enable_cpu_mem_arena = 100

@negbie

negbie commented Apr 12, 2026

Copy link
Copy Markdown
Contributor Author

Ok thanks. I will open a new pr.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants