Skip to content

Latest commit

 

History

History
187 lines (149 loc) · 10 KB

shared_helpers.md

File metadata and controls

187 lines (149 loc) · 10 KB

Shared helpers

Purpose and boundary

Use these helpers for common preprocessing, segmentation, accumulation and cache retention. They operate on caller-supplied data; they do not select model policies. A bounded graph cache, a KV cache and a disk cache solve different problems.

Public API

Resampling

Header.

API Use and result
try_resample_mono_soxr(samples,source_rate,target_rate,options) Prefer the configured SOXR algorithm; returns optional samples when runtime support is available
resample_mono_soxr_or_linear(...) SOXR with explicit warning and portable linear fallback
resample_mono_soxr_or_sinc(...) SOXR with explicit warning and torchaudio-compatible sinc-Hann fallback
resample_mono_linear(samples,source_rate,target_rate) Explicit linear interpolation
resample_mono_torchaudio_sinc_hann(...,options) Explicit cached sinc-Hann filtering
set_resample_kernel_cache_budget_bytes(bytes) Bound retained sinc kernels; zero disables caching

SoxrResampleOptions::profile selects QualityOnly or ExplicitFloat32Runtime. output_length_policy is ActualOutput, ClampToExpected or ExactExpected; also resolve output_padding, require_full_input and reject_empty_output. warning_context and fallback_description identify the caller and fallback in diagnostics. The wrapper fallback is a different algorithm; do not assume SOXR length/quality settings make its output identical.

TorchaudioSincHannResampleOptions defines lowpass_filter_width (default 6), rolloff (0.99), kernel computation/storage mode and accumulation precision. Use torchaudio_sinc_hann_float32_options() when matching that explicit F32 contract. Defaults compute/store the kernel and accumulate according to the header's distinct mode fields; weight precision is unrelated.

StreamingSoxrResampler retains filter state: construct once per stream, call process(samples,false) for successive blocks, then flush once with process({},true). Do not run the stateless resampler independently on each streaming chunk: it loses boundary state. This strict streaming API requires SOXR; it does not expose the stateless fallback wrappers' behavior.

Text and audio chunking

Text chunking splits by UTF-8 codepoint budget, not bytes or tokenizer tokens. TextChunkMode selects Default, TagAware, Japanese or Endline; choose the mode from the model's text contract. TagAware splits as Default does (words, CJK punctuation, CJK runs cut to the budget) but keeps each tag, [...], <...> or (...), whole. parse_text_chunk_size_override() and parse_text_chunk_mode_override() interpret option maps; the model still decides which options it accepts and when it applies the returned override.

In TagAware, a paired tag such as <whisper>...</whisper> is one unit together with the words it wraps, so no chunk opens the tag and leaves the next one to close it. When that unit is longer than the budget, its words are chunked by the same rules within the budget left after the tags, and each piece is wrapped in the tags again.

Audio chunking separates planning, copying, processing and merging:

  1. Configure AudioChunkSpec{chunk_samples,hop_samples,pad_mode,tail_alignment,...} in sample frames and call plan_audio_chunks(input_samples,spec).
  2. Each AudioChunkSpan identifies output position, valid sample count, source copy position and valid offset within the padded chunk. Use copy_interleaved_chunk_to_planar() or copy_planar_chunk() with that span.
  3. Process the complete padded chunk in the model.
  4. For overlapping outputs, call overlap_add_planar_chunk() with a chosen triangular/fade window, then normalize_overlap_added_planar() once. Allocate the output and weight arrays for the complete target frame count; AudioChunkCounterMode determines whether weight counters are shared across lanes or stored per lane. Match the counter layout in both calls.

Use plan_vad_audio_chunks() for known speech segments or a supplied VAD session, plan_quiet_energy_audio_chunks() for low-energy boundary search, and plan_silence_audio_chunks() for recording-relative silence cuts. The silence planner uses centered 2048-sample RMS, hop 512 and a 30 dB relative threshold; its trigger_samples keeps shorter recordings whole. These algorithms are not interchangeable fixed-window implementations.

slice_audio_buffer() copies a source TimeSpan. To retain chunk-local word metadata, append_chunk_word_timestamps() has source/keep-span overloads and explicit source/timestamp sample rates. append_chunk_speech_metadata() handles speech metadata under the same retained-region contract. Context removal must use the correct source and timestamp clocks, especially after resampling.

Cache slots and runtime caches

CacheSlots is a bounded, in-memory LRU container for a model-defined key and value. find() on a mutable cache refreshes recency; const lookup does not. put() replaces a matching key or evicts the least recently used entry. set_capacity() immediately evicts to fit; capacity zero disables retention. clear() destroys stored values.

Choose a key containing every dependency of the retained object: shape, precision, backend and relevant mask/constant/configuration identity. Store owning values such as unique_ptr<PreparedGraph> when the slot should own teardown. The helper does not synchronize GPU work or infer graph compatibility.

RuntimeCache stores typed values in std::any under string keys. find<T>() returns null for a miss or wrong type; it has no eviction/capacity policy. Use it for explicit session-owned objects, not unbounded graph retention across arbitrary request shapes.

Other cache Appropriate contents Distinct lifetime contract
ConstantTensorCache Immutable uploaded tensors Replay the same sequence; equal shape does not update values
SharedWeightCache Shared weight resources Follow its backend/source identity and ownership contract
CachedDecodeRuntime Graph plus transformer KV policy Factory rebuild/growth and explicit state export/import
Transformer KV cache Decode keys/values and positions Capacity, valid rows and wrap position are semantic state
DiskCache Serialized owned byte payloads Filesystem validation, locking and eviction
MoE expert cache Resident expert slots Owned by MoE engine; not generic CacheSlots

Integration example

Cache the result of shared text segmentation with an explicit bounded capacity. This demonstrates the container interface, not a recommendation to cache every text request.

#include "engine/framework/runtime/cache_slots.h"
#include "engine/framework/text/chunking.h"

std::vector<std::string> split_cached(
    engine::runtime::CacheSlots<std::string, std::vector<std::string>> & cache,
    const std::string & text) {
    // This cache has one fixed policy: Default mode and a 160-codepoint budget.
    if (auto * existing = cache.find(text)) return *existing;
    auto chunks = engine::text::split_text_chunks(text, 160,
        engine::text::TextChunkMode::Default);
    cache.put(text, chunks);
    return chunks;
}

For ordinary SOXR-with-sinc fallback, pass all rates and options explicitly:

#include "engine/framework/audio/resampling.h"

std::vector<float> resample_reference(const std::vector<float> & mono,
    int input_rate, int model_rate) {
    engine::audio::SoxrResampleOptions options;
    options.warning_context = "reference_frontend";
    return engine::audio::resample_mono_soxr_or_sinc(mono, input_rate, model_rate, options);
}

Ownership and lifecycle

Cache lookup returns borrowed pointers. Insertion, replacement, capacity change or clear can invalidate them; do not retain pointers across cache mutation. CacheSlots is not thread-safe. Drain any queued graph consumers before eviction can destroy their storage. Streaming resampler state belongs to one stream; retain it until final flush and destroy it before creating a new stream.

Data and mathematical contracts

Keep sample frames separate from interleaved scalar counts and from seconds. Text budgets count codepoints. Resampling changes both values and sometimes frame counts; explicit rates are required for timestamp transformations. Overlap-add assumes outputs correspond to the supplied spans/window, not arbitrary shorter model outputs. Cache-key equality must imply reuse is mathematically valid.

Configuration and backends

These helpers mostly manipulate host data and apply across inference backends. A graph stored in a cache still belongs to its original backend/context. Sinc kernel caching changes retained host memory; it does not make full audio buffers bounded. Streaming output assembly can still retain the complete final waveform.

Errors and limitations

SOXR runtime unavailability and a resampling execution error are different cases; follow the API's error behavior rather than catching everything and recomputing. Do not use overlap-add to hide model boundary artifacts. Eviction only destroys the value; it does not invent backend synchronization or state migration.

Callers and validation

See text chunking tests and audio chunking tests. Cache-slot implementation is header-only and its recency/eviction logic is visible beside the API. Validate chunk tails, non-aligned lengths, context clipping and clock conversion separately from model inference. Resampling quality requires an independent algorithm reference, not a cache-hit versus cache-miss comparison.