diff --git a/CMakeLists.txt b/CMakeLists.txt index 15a4d07..b397508 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -52,6 +52,7 @@ set(CODEC_SOURCES src/runtime/audio_dsp.cpp src/runtime/graph.cpp src/runtime/graph_exec.cpp + src/runtime/memory.cpp src/runtime/perf_log.cpp src/runtime/log.cpp src/runtime/speaker.cpp diff --git a/include/codec.h b/include/codec.h index 42e5edc..66a2da2 100644 --- a/include/codec.h +++ b/include/codec.h @@ -53,6 +53,7 @@ enum codec_batch_mode { struct codec_model; struct codec_context; +typedef struct codec_memory * codec_memory_t; struct codec_model_params { bool use_gpu; @@ -82,6 +83,9 @@ struct codec_model_kv_override { struct codec_context_params { int32_t seed; + // Cache context across calls (default false: every call independent, as today). + bool encoder_memory; // codec_encode / codec_encode_latent + bool decoder_memory; // codec_decode / codec_decode_quantized_representation }; struct codec_encode_params { @@ -220,6 +224,27 @@ void codec_latent_buffer_free(struct codec_latent_buffer * latent); const char * codec_get_last_error(const struct codec_context * ctx); +// True when that side's output for a frame depends only on the current and +// earlier input: its look_ahead (GGUF codec..look_ahead) is 0. Memory +// then makes streamed output equal batch output; a non-causal side's memory +// has size 0. +bool codec_model_encoder_is_causal(const struct codec_model * model); +bool codec_model_decoder_is_causal(const struct codec_model * model); + +// NULL when that memory is not enabled in the context params. +codec_memory_t codec_get_encoder_memory(const struct codec_context * ctx); +codec_memory_t codec_get_decoder_memory(const struct codec_context * ctx); + +// Empty the cache: the next call behaves as on a fresh context. +void codec_memory_clear(codec_memory_t mem); + +// Save / restore the cache. get_data returns the bytes written (0 = dst +// too small); set_data returns the bytes read, or 0 when the blob does not fit +// this model and side, leaving the cache unchanged. +size_t codec_memory_state_get_size(codec_memory_t mem); +size_t codec_memory_state_get_data(codec_memory_t mem, uint8_t * dst, size_t size); +size_t codec_memory_state_set_data(codec_memory_t mem, const uint8_t * src, size_t size); + enum codec_arch codec_model_arch(const struct codec_model * model); const char * codec_model_name(const struct codec_model * model); int32_t codec_model_n_tensors(const struct codec_model * model); diff --git a/python/codec_cpp/__init__.py b/python/codec_cpp/__init__.py index 869e0ce..508d010 100644 --- a/python/codec_cpp/__init__.py +++ b/python/codec_cpp/__init__.py @@ -13,13 +13,13 @@ from . import _ffi as ffi from ._lib import backbone_lib, lib, library_path from .audio_lm import AudioLM, Vocab -from .codec import CodecError, Context, Model, Speaker, SpeakerFile +from .codec import CodecError, Context, Memory, Model, Speaker, SpeakerFile from .lm import LM, LMInfo, LMState from .tts import TTS __version__ = "0.1.0" __all__ = [ - "AudioLM", "CodecError", "Context", "LM", "LMInfo", "LMState", "Model", "Speaker", + "AudioLM", "CodecError", "Context", "LM", "LMInfo", "LMState", "Memory", "Model", "Speaker", "SpeakerFile", "TTS", "Vocab", "backbone_lib", "ffi", "lib", "library_path", ] diff --git a/python/codec_cpp/_ffi.py b/python/codec_cpp/_ffi.py index d9bc6cb..1e403df 100644 --- a/python/codec_cpp/_ffi.py +++ b/python/codec_cpp/_ffi.py @@ -86,6 +86,8 @@ class codec_model_kv_override(Structure): class codec_context_params(Structure): _fields_ = [ ("seed", c_int32), + ("encoder_memory", c_bool), + ("decoder_memory", c_bool), ] @@ -445,6 +447,15 @@ class codec_audio_lm_generation(Structure): "codec_pcm_buffer_free": (None, [POINTER(codec_pcm_buffer)]), "codec_latent_buffer_free": (None, [POINTER(codec_latent_buffer)]), "codec_get_last_error": (c_char_p, [c_void_p]), + # codec.h — codec memory + "codec_model_encoder_is_causal": (c_bool, [c_void_p]), + "codec_model_decoder_is_causal": (c_bool, [c_void_p]), + "codec_get_encoder_memory": (c_void_p, [c_void_p]), + "codec_get_decoder_memory": (c_void_p, [c_void_p]), + "codec_memory_clear": (None, [c_void_p]), + "codec_memory_state_get_size": (c_size_t, [c_void_p]), + "codec_memory_state_get_data": (c_size_t, [c_void_p, c_void_p, c_size_t]), + "codec_memory_state_set_data": (c_size_t, [c_void_p, c_void_p, c_size_t]), # codec.h — model info "codec_model_arch": (c_int, [c_void_p]), "codec_model_name": (c_char_p, [c_void_p]), diff --git a/python/codec_cpp/codec.py b/python/codec_cpp/codec.py index d5e19ea..0cfea3e 100644 --- a/python/codec_cpp/codec.py +++ b/python/codec_cpp/codec.py @@ -258,6 +258,10 @@ def has_encoder(self) -> bool: return bool(lib().codec_model_has_encoder(self.pt @property def has_decoder(self) -> bool: return bool(lib().codec_model_has_decoder(self.ptr)) @property + def encoder_is_causal(self) -> bool: return bool(lib().codec_model_encoder_is_causal(self.ptr)) + @property + def decoder_is_causal(self) -> bool: return bool(lib().codec_model_decoder_is_causal(self.ptr)) + @property def n_q(self) -> int: return int(lib().codec_model_n_q(self.ptr)) @property def codebook_size(self) -> int: return int(lib().codec_model_codebook_size(self.ptr)) @@ -354,20 +358,68 @@ def __enter__(self): return self def __exit__(self, *a): self.close() +class Memory: + """One side's codec memory (codec_memory_t): the cached context of a + context's encoder or decoder. Valid while its Context lives.""" + + def __init__(self, ptr: int, owner: "Context"): + self.ptr = ptr + self._owner = owner + + def clear(self) -> None: + lib().codec_memory_clear(self.ptr) + + def state_size(self) -> int: + return int(lib().codec_memory_state_get_size(self.ptr)) + + def get_state(self) -> bytes: + n = self.state_size() + if n == 0: + return b"" + buf = (ctypes.c_uint8 * n)() + got = int(lib().codec_memory_state_get_data(self.ptr, buf, n)) + if got != n: + raise CodecError("codec_memory_state_get_data") + return bytes(buf) + + def set_state(self, blob: bytes) -> int: + """Restores a blob from get_state; returns the bytes read (0 = rejected, + cache unchanged; also 0 for an empty blob on a size-0 memory).""" + buf = (ctypes.c_uint8 * max(1, len(blob))).from_buffer_copy(blob or b"\0") + return int(lib().codec_memory_state_set_data(self.ptr, buf, len(blob))) + + class Context: - """Inference context (codec_context): encode / decode against a Model.""" + """Inference context (codec_context): encode / decode against a Model. + + ``encoder_memory`` / ``decoder_memory``: cache that side's context across + calls (docs/proposals/codec_memory.md); see ``encoder_memory`` / + ``decoder_memory`` properties.""" - def __init__(self, model: Model, *, seed: int | None = None): + def __init__(self, model: Model, *, seed: int | None = None, + encoder_memory: bool = False, decoder_memory: bool = False): self.model = model L = lib() cp = L.codec_context_default_params() if seed is not None: cp.seed = int(seed) + cp.encoder_memory = bool(encoder_memory) + cp.decoder_memory = bool(decoder_memory) self.ptr = L.codec_init_from_model(model.ptr, cp) if not self.ptr: raise CodecError("codec_init_from_model failed") model._contexts.add(self) + @property + def encoder_memory(self) -> Memory | None: + p = lib().codec_get_encoder_memory(self.ptr) + return Memory(p, self) if p else None + + @property + def decoder_memory(self) -> Memory | None: + p = lib().codec_get_decoder_memory(self.ptr) + return Memory(p, self) if p else None + @property def last_error(self) -> str: return _str(lib().codec_get_last_error(self.ptr)) diff --git a/scripts/converters/base.py b/scripts/converters/base.py index 4b34d02..c125229 100644 --- a/scripts/converters/base.py +++ b/scripts/converters/base.py @@ -16,6 +16,15 @@ from ..utils import GGUFWriter +def write_look(writer, side: str, look_back: int, look_ahead: int) -> None: + """codec..look_back / look_ahead (side: "encoder" / "decoder"), in + codec frames: the past context the side uses (on a causal side, the + context codec memory caches) and the future frames its output depends on + (0 = causal, -1 = unbounded). See docs/proposals/codec_memory.md.""" + writer.add_int32(f"codec.{side}.look_back", int(look_back)) + writer.add_int32(f"codec.{side}.look_ahead", int(look_ahead)) + + class BaseConverter(ABC): """ Abstract base class for audio codec GGUF converters. diff --git a/scripts/converters/dac.py b/scripts/converters/dac.py index 4cfae98..f3aa100 100644 --- a/scripts/converters/dac.py +++ b/scripts/converters/dac.py @@ -18,7 +18,7 @@ except ImportError: AutoModel = None -from .base import BaseConverter +from .base import BaseConverter, write_look from utils.gguf_writer import GGUFWriter MAX_TENSOR_NAME = 63 @@ -481,6 +481,9 @@ def convert_and_save(self, output_path: Path) -> None: writer.add_uint32("codec.codebook_dim", int(self.config["codebook_dim"])) writer.add_bool("codec.has_encoder", bool(self.config["has_encoder"])) writer.add_bool("codec.has_decoder", bool(self.config["has_decoder"])) + # non-causal decoder: the window a host re-decodes around a chunk (0.32 s each side) + fps = int(self.config["sample_rate"]) / int(self.config["hop_size"]) + write_look(writer, "decoder", round(0.32 * fps), round(0.32 * fps)) mapped = OrderedDict() for raw_key, value in self.state_dict.items(): diff --git a/scripts/converters/mimi.py b/scripts/converters/mimi.py index 4412c11..1aef0f6 100644 --- a/scripts/converters/mimi.py +++ b/scripts/converters/mimi.py @@ -15,7 +15,7 @@ except ImportError: snapshot_download = None -from .base import BaseConverter +from .base import BaseConverter, write_look from utils.gguf_writer import GGUFWriter from utils import quantization as quant_utils @@ -372,6 +372,10 @@ def write_into(self, writer: GGUFWriter) -> None: writer.add_uint32("codec.intermediate_size", int(self.config.get("intermediate_size", 2048))) writer.add_bool("codec.has_encoder", True) writer.add_bool("codec.has_decoder", True) + # transformers: a sliding window of `sliding_window` steps at twice the frame rate + look = int(self.config.get("sliding_window", 250)) // 2 + write_look(writer, "encoder", look, 0) + write_look(writer, "decoder", look, 0) used_names: set[str] = set() for key in keys: diff --git a/scripts/converters/moss_audio.py b/scripts/converters/moss_audio.py index 7b11e0f..feab95c 100644 --- a/scripts/converters/moss_audio.py +++ b/scripts/converters/moss_audio.py @@ -20,6 +20,7 @@ from __future__ import annotations import json +import math from collections import OrderedDict from pathlib import Path from typing import Any, Dict, List @@ -31,7 +32,7 @@ except ImportError: torch = None -from .base import BaseConverter +from .base import BaseConverter, write_look from utils.gguf_writer import GGUFWriter @@ -182,6 +183,12 @@ def convert_and_save(self, output_path: Path) -> None: writer.add_uint32("codec.latent_dim", latent_dim) writer.add_bool("codec.has_encoder", True) writer.add_bool("codec.has_decoder", True) + # causal both ways; look_back = the longest per-block attention context, in codec frames + fps = sr / downsample + for side, key in (("encoder", "encoder_kwargs"), ("decoder", "decoder_kwargs")): + ctx_s = max([float(m.get("context_duration", 10.0)) for m in cfg.get(key, []) + if m.get("module_type") != "PatchedPretransform"] or [0.0]) + write_look(writer, side, int(math.ceil(ctx_s * fps)), 0) writer.add_uint32("moss.number_channels", n_channels) writer.add_bool("moss.channel_interleave", interleave) diff --git a/scripts/converters/nemo_nano_codec.py b/scripts/converters/nemo_nano_codec.py index cd215c4..bcb845c 100644 --- a/scripts/converters/nemo_nano_codec.py +++ b/scripts/converters/nemo_nano_codec.py @@ -18,7 +18,7 @@ import yaml -from .base import BaseConverter +from .base import BaseConverter, write_look from utils.gguf_writer import GGUFWriter @@ -264,6 +264,7 @@ def convert_and_save(self, output_path: Path) -> None: writer.add_uint32("codec.latent_dim", num_groups * codebook_dim) writer.add_bool("codec.has_encoder", True) writer.add_bool("codec.has_decoder", True) + write_look(writer, "decoder", 27, 0) # causal conv decoder, receptive field ~2.2 s state = self.state_dict mapped: Dict[str, np.ndarray] = {} diff --git a/scripts/converters/qwen3_tts_tokenizer.py b/scripts/converters/qwen3_tts_tokenizer.py index 023da36..f1f2b5d 100644 --- a/scripts/converters/qwen3_tts_tokenizer.py +++ b/scripts/converters/qwen3_tts_tokenizer.py @@ -14,7 +14,7 @@ except ImportError: snapshot_download = None -from .base import BaseConverter +from .base import BaseConverter, write_look from .mimi import ( build_weight_transforms as mimi_build_weight_transforms, map_tensor_names as mimi_map_tensor_names, @@ -447,6 +447,10 @@ def convert_and_save(self, output_path: Path) -> None: writer.add_uint32("codec.latent_dim", dec_latent_dim) writer.add_bool("codec.has_encoder", True) writer.add_bool("codec.has_decoder", True) + # encoder: the Mimi encoder (window at twice the frame rate); decoder: window at the frame rate + enc_cfg = self.config.get("encoder_config", {}) + write_look(writer, "encoder", int(enc_cfg.get("sliding_window", 250)) // 2, 0) + write_look(writer, "decoder", int(dec.get("sliding_window", 72)), 0) # Encoder metadata (Mimi-compatible) for codec_mimi_encode. writer.add_uint32("qwen3.encoder.codebook_size", int(enc.get("codebook_size", dec_codebook_size))) diff --git a/scripts/converters/wavtokenizer.py b/scripts/converters/wavtokenizer.py index 2b94ac0..fb7cdce 100644 --- a/scripts/converters/wavtokenizer.py +++ b/scripts/converters/wavtokenizer.py @@ -12,7 +12,7 @@ except ImportError: torch = None -from .base import BaseConverter +from .base import BaseConverter, write_look from utils.gguf_writer import GGUFWriter MAX_TENSOR_NAME = 63 @@ -441,6 +441,9 @@ def convert_and_save(self, output_path: Path) -> None: writer.add_uint32("codec.hop_size", int(self.config["hop_size"])) writer.add_bool("codec.has_encoder", bool(self.config["has_encoder"])) writer.add_bool("codec.has_decoder", bool(self.config["has_decoder"])) + # global attention: no window covers its reach; the accepted streaming window (1.28 s / 0.32 s) + fps = int(self.config["sample_rate"]) / int(self.config["hop_size"]) + write_look(writer, "decoder", round(1.28 * fps), round(0.32 * fps)) used_names = set() handled = set() diff --git a/src/codec.cpp b/src/codec.cpp index 3bd6322..8af72dd 100644 --- a/src/codec.cpp +++ b/src/codec.cpp @@ -22,11 +22,13 @@ #include "models/pocket_mimi.h" #include "ops/safe_math.h" #include "runtime/graph.h" +#include "runtime/memory.h" #include "runtime/gguf_kv.h" #include "runtime/tensor_utils.h" #include +#include #include #include #include @@ -225,6 +227,49 @@ const char * codec_arch_name(enum codec_arch arch) { } } +// Per-arch defaults of codec.{encoder,decoder}.{look_back,look_ahead} (codec +// frames; look_ahead 0 = causal, -1 = unbounded) for GGUFs without the keys. +// See docs/proposals/codec_memory.md. Arch init may already have set them +// from its own config (MOSS-Audio's context durations). +static void codec_model_look_defaults(codec_model * model) { + auto frames = [&](double seconds) { + return model->hop_size > 0 && model->sample_rate > 0 + ? (int32_t) std::lround(seconds * model->sample_rate / model->hop_size) : -1; + }; + switch (model->arch) { + case CODEC_ARCH_MIMI: + // transformer: 250-step sliding window at 25 Hz = 125 codec frames + model->enc_look_back = 125; model->enc_look_ahead = 0; + model->dec_look_back = 125; model->dec_look_ahead = 0; + break; + case CODEC_ARCH_QWEN3_TTS_TOKENIZER: + model->enc_look_back = 125; model->enc_look_ahead = 0; // Mimi encoder + if (model->dec_look_back < 0) model->dec_look_back = 72; + model->dec_look_ahead = 0; + break; + case CODEC_ARCH_NEMO_NANO_CODEC: + model->dec_look_back = 27; model->dec_look_ahead = 0; // causal conv receptive field + break; + case CODEC_ARCH_DAC: + // non-causal: the window a host re-decodes around a chunk (0.32 s each side) + model->dec_look_back = frames(0.32); model->dec_look_ahead = frames(0.32); + break; + case CODEC_ARCH_WAVTOKENIZER_LARGE: + model->dec_look_back = frames(1.28); model->dec_look_ahead = frames(0.32); + break; + default: + break; + } +} + +static void codec_model_load_look(codec_model * model) { + codec_model_look_defaults(model); + model->enc_look_back = codec_read_i32_kv(model->gguf, "codec.encoder.look_back", model->enc_look_back); + model->enc_look_ahead = codec_read_i32_kv(model->gguf, "codec.encoder.look_ahead", model->enc_look_ahead); + model->dec_look_back = codec_read_i32_kv(model->gguf, "codec.decoder.look_back", model->dec_look_back); + model->dec_look_ahead = codec_read_i32_kv(model->gguf, "codec.decoder.look_ahead", model->dec_look_ahead); +} + enum codec_status codec_model_init_arch(struct codec_model * model) { if (model == nullptr) { return CODEC_STATUS_INVALID_ARG; @@ -233,7 +278,11 @@ enum codec_status codec_model_init_arch(struct codec_model * model) { model->vtable = codec_model_vtable_for_arch(model->arch); } if (model->vtable != nullptr && model->vtable->init != nullptr) { - return model->vtable->init(model); + const enum codec_status st = model->vtable->init(model); + if (st == CODEC_STATUS_SUCCESS) { + codec_model_load_look(model); + } + return st; } model->sample_rate = codec_read_i32_kv(model->gguf, "codec.sample_rate", 0); model->encode_sample_rate = codec_read_i32_kv(model->gguf, "codec.encode_sample_rate", 0); @@ -246,6 +295,7 @@ enum codec_status codec_model_init_arch(struct codec_model * model) { model->win_length = codec_read_i32_kv(model->gguf, "codec.win_length", -1); model->n_mels = codec_read_i32_kv(model->gguf, "codec.n_mels", -1); model->latent_dim = codec_read_i32_kv(model->gguf, "codec.latent_dim", -1); + codec_model_load_look(model); return CODEC_STATUS_SUCCESS; } static enum codec_status codec_dispatch_encode( @@ -286,7 +336,9 @@ struct codec_model_params codec_model_default_params(void) { struct codec_context_params codec_context_default_params(void) { struct codec_context_params result = { - /*.seed =*/ CODEC_DEFAULT_SEED, + /*.seed =*/ CODEC_DEFAULT_SEED, + /*.encoder_memory =*/ false, + /*.decoder_memory =*/ false, }; return result; @@ -581,10 +633,26 @@ struct codec_context * codec_init_from_model(struct codec_model * model, struct return nullptr; } + // Codec memory: slots are planned and allocated now, so a saved state can + // be restored before the first call. A non-causal side gets an empty one. + if ((params.encoder_memory && !codec_memory_create(ctx, CODEC_MEMORY_ENCODER, &ctx->enc_mem, &err)) || + (params.decoder_memory && !codec_memory_create(ctx, CODEC_MEMORY_DECODER, &ctx->dec_mem, &err))) { + codec_log(CODEC_LOG_LEVEL_ERROR, "codec_init_from_model: codec memory: %s\n", err.c_str()); + codec_free(ctx); + return nullptr; + } + return ctx; } void codec_free(struct codec_context * ctx) { + if (ctx == nullptr) { + return; + } + codec_graph_release(ctx); + codec_memory_free(ctx->enc_mem); + codec_memory_free(ctx->dec_mem); + ctx->enc_mem = ctx->dec_mem = nullptr; codec_runtime_free(ctx); delete ctx; } @@ -776,6 +844,15 @@ enum codec_status codec_decode_batch( enum codec_status status = CODEC_STATUS_SUCCESS; int32_t n_done = 0; + // A batch holds several independent sequences and memory holds one: batch + // decode neither reads nor updates it. + struct memory_bypass_guard { + codec_context * c; + bool prev; + ~memory_bypass_guard() { c->memory_bypass = prev; } + } bypass_guard{ctx, ctx->memory_bypass}; + ctx->memory_bypass = true; + int32_t i = 0; for (; i < batch->n_seq; ++i) { if (batch->seq_id[i] < 0 || batch->seq_id[i] >= batch->n_seq_max) { diff --git a/src/codec_internal.h b/src/codec_internal.h index 080f5f8..5bef159 100644 --- a/src/codec_internal.h +++ b/src/codec_internal.h @@ -74,6 +74,13 @@ struct codec_model { int32_t encode_sample_rate; bool has_encoder; bool has_decoder; + // Context reach per side in codec frames (GGUF codec.{encoder,decoder}. + // look_back / look_ahead, else per-arch defaults); look_ahead 0 = causal, + // -1 = unbounded. See docs/proposals/codec_memory.md. + int32_t enc_look_back = -1; + int32_t enc_look_ahead = -1; + int32_t dec_look_back = -1; + int32_t dec_look_ahead = -1; int32_t hop_size; int32_t n_q; int32_t codebook_size; @@ -110,6 +117,9 @@ struct codec_graph_cache_key { // Latent decode shapes int32_t latent_dim = 0; // DAC latent dimension + + // 1 when the graph reads / writes codec memory (docs/proposals/codec_memory.md) + int32_t mem = 0; }; typedef bool (*codec_graph_build_fn)(ggml_context * ctx_eval, void * user_data, ggml_tensor ** out); @@ -153,6 +163,10 @@ struct codec_context { std::unordered_map eval_weight_casts; // weight -> its F32 cast in this graph bool eval_graph_allocated = false; // sched_alloc_graph done for current eval_ctx int32_t sched_reserved_graph_size = 0; + // Codec memory (params.encoder_memory / decoder_memory); nullptr when off. + struct codec_memory * enc_mem = nullptr; + struct codec_memory * dec_mem = nullptr; + bool memory_bypass = false; // codec_decode_batch: stateless }; struct codec_model_vtable { @@ -196,6 +210,10 @@ struct codec_model_vtable { const std::vector & pcm, int32_t sample_rate, struct codec_speaker * out); + // Codec memory: records the cache slots of `side` (0 = encoder, 1 = + // decoder) by building that side's graph in planning mode + // (codec_memory_plan_build). nullptr = no memory for this arch (size 0). + bool (*memory_plan)(struct codec_context * ctx, int32_t side, struct codec_memory * mem, std::string * err); }; // Loads `spk..` tensors + `.spk.*` metadata from the model diff --git a/src/models/mimi.cpp b/src/models/mimi.cpp index 0e04aaa..4659b13 100644 --- a/src/models/mimi.cpp +++ b/src/models/mimi.cpp @@ -7,6 +7,7 @@ #include "../ops/rope.h" #include "../ops/rvq.h" #include "../runtime/graph.h" +#include "../runtime/memory.h" #include "../runtime/tensor_utils.h" #include @@ -82,6 +83,8 @@ struct mimi_decode_build { int32_t dec_l14_kernel; int32_t dec_l14_out; const codec_model * model; + codec_memory * mem; // decoder memory, nullptr = batch graph + int32_t window; // transformer sliding window in steps (0 = unbounded), batch and memory }; @@ -179,6 +182,7 @@ static int32_t codec_mimi_encode_time_stride_reduce(int32_t t, int32_t stride) { static ggml_tensor * codec_mimi_resblock_ggml( ggml_context * ctx_eval, + codec_memory * mem, ggml_tensor * x, ggml_tensor * w1, ggml_tensor * b1, @@ -190,12 +194,12 @@ static ggml_tensor * codec_mimi_resblock_ggml( } ggml_tensor * h = codec_op_unary(ctx_eval, x, CODEC_UNARY_ELU); - ggml_tensor * y1 = codec_conv1d_causal(ctx_eval, h, w1, b1, 1, 1); + ggml_tensor * y1 = codec_memory_conv1d_causal(ctx_eval, mem, h, w1, b1, 1, 1); if (y1 == nullptr) { return nullptr; } y1 = codec_op_unary(ctx_eval, y1, CODEC_UNARY_ELU); - ggml_tensor * y2 = codec_conv1d_causal(ctx_eval, y1, w2, b2, 1, 1); + ggml_tensor * y2 = codec_memory_conv1d_causal(ctx_eval, mem, y1, w2, b2, 1, 1); if (y2 == nullptr) { return nullptr; } @@ -286,6 +290,7 @@ bool codec_mimi_init_encode_build( return false; } + build->window = codec_mimi_window_steps(ctx->model->enc_look_back, build->downsample.stride); build->n_q = std::max(1, std::min(mm.n_q, CODEC_MIMI_MAX_RVQ_LAYERS)); build->codebook_dim = std::max(1, mm.codebook_dim); build->codebook_size = std::max(2, mm.codebook_size); @@ -316,6 +321,11 @@ bool codec_mimi_build_encode_from(ggml_context * ctx_eval, const mimi_encode_bui } auto W = [&](const std::string & name) { return codec_graph_weight(ctx_eval, p->model, name); }; + codec_memory * mem = p->mem; + if (mem != nullptr && p->window <= 0) { + return false; // memory needs a bounded attention window + } + codec_memory_begin_build(mem); // Frontend conv weights — names live under the GGUF prefixes captured in // CODEC_MIMI_ENC_FRONTEND_WEIGHT_NAMES / _BIAS_NAMES (e.g. enc.l0.conv.w). @@ -333,52 +343,52 @@ bool codec_mimi_build_encode_from(ggml_context * ctx_eval, const mimi_encode_bui } } - ggml_tensor * x = codec_conv1d_causal(ctx_eval, t_pcm, t_w[0], t_b[0], p->frontend.conv[0].stride, 1); + ggml_tensor * x = codec_memory_conv1d_causal(ctx_eval, mem, t_pcm, t_w[0], t_b[0], p->frontend.conv[0].stride, 1); if (x == nullptr) { return false; } - x = codec_mimi_resblock_ggml(ctx_eval, x, t_w[1], t_b[1], t_w[2], t_b[2]); + x = codec_mimi_resblock_ggml(ctx_eval, mem, x, t_w[1], t_b[1], t_w[2], t_b[2]); if (x == nullptr) { return false; } x = codec_op_unary(ctx_eval, x, CODEC_UNARY_ELU); - x = codec_conv1d_causal(ctx_eval, x, t_w[3], t_b[3], p->frontend.conv[3].stride, 1); + x = codec_memory_conv1d_causal(ctx_eval, mem, x, t_w[3], t_b[3], p->frontend.conv[3].stride, 1); if (x == nullptr) { return false; } - x = codec_mimi_resblock_ggml(ctx_eval, x, t_w[4], t_b[4], t_w[5], t_b[5]); + x = codec_mimi_resblock_ggml(ctx_eval, mem, x, t_w[4], t_b[4], t_w[5], t_b[5]); if (x == nullptr) { return false; } x = codec_op_unary(ctx_eval, x, CODEC_UNARY_ELU); - x = codec_conv1d_causal(ctx_eval, x, t_w[6], t_b[6], p->frontend.conv[6].stride, 1); + x = codec_memory_conv1d_causal(ctx_eval, mem, x, t_w[6], t_b[6], p->frontend.conv[6].stride, 1); if (x == nullptr) { return false; } - x = codec_mimi_resblock_ggml(ctx_eval, x, t_w[7], t_b[7], t_w[8], t_b[8]); + x = codec_mimi_resblock_ggml(ctx_eval, mem, x, t_w[7], t_b[7], t_w[8], t_b[8]); if (x == nullptr) { return false; } x = codec_op_unary(ctx_eval, x, CODEC_UNARY_ELU); - x = codec_conv1d_causal(ctx_eval, x, t_w[9], t_b[9], p->frontend.conv[9].stride, 1); + x = codec_memory_conv1d_causal(ctx_eval, mem, x, t_w[9], t_b[9], p->frontend.conv[9].stride, 1); if (x == nullptr) { return false; } - x = codec_mimi_resblock_ggml(ctx_eval, x, t_w[10], t_b[10], t_w[11], t_b[11]); + x = codec_mimi_resblock_ggml(ctx_eval, mem, x, t_w[10], t_b[10], t_w[11], t_b[11]); if (x == nullptr) { return false; } x = codec_op_unary(ctx_eval, x, CODEC_UNARY_ELU); - x = codec_conv1d_causal(ctx_eval, x, t_w[12], t_b[12], p->frontend.conv[12].stride, 1); + x = codec_memory_conv1d_causal(ctx_eval, mem, x, t_w[12], t_b[12], p->frontend.conv[12].stride, 1); if (x == nullptr) { return false; } x = codec_op_unary(ctx_eval, x, CODEC_UNARY_ELU); - x = codec_conv1d_causal(ctx_eval, x, t_w[13], t_b[13], p->frontend.conv[13].stride, 1); + x = codec_memory_conv1d_causal(ctx_eval, mem, x, t_w[13], t_b[13], p->frontend.conv[13].stride, 1); if (x == nullptr) { return false; } @@ -422,28 +432,46 @@ bool codec_mimi_build_encode_from(ggml_context * ctx_eval, const mimi_encode_bui } const int64_t t_cur = q->ne[1]; - ggml_tensor * q_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, q, p->transformer.head_dim, p->transformer.n_heads, t_cur), 0, 2, 1, 3); - ggml_tensor * k_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, k, p->transformer.head_dim, p->transformer.n_heads, t_cur), 0, 2, 1, 3); - ggml_tensor * v_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, v, p->transformer.head_dim, p->transformer.n_heads, t_cur), 0, 2, 1, 3); + ggml_tensor * attn_ct = nullptr; + if (mem != nullptr) { + codec_memory_attn_params ap; + ap.head_dim = p->transformer.head_dim; + ap.n_heads = p->transformer.n_heads; + ap.n_kv_heads = p->transformer.n_heads; + ap.window = p->window; + ap.rope_theta = p->transformer.rope_theta; + ap.rope_freq_scale = freq_scale; + ap.rope_mode = CODEC_ROPE_MODE_NEOX; + ap.scale = 1.0f / std::sqrt((float) p->transformer.head_dim); + attn_ct = codec_memory_attn(ctx_eval, mem, + ggml_reshape_3d(ctx_eval, q, p->transformer.head_dim, p->transformer.n_heads, t_cur), + ggml_reshape_3d(ctx_eval, k, p->transformer.head_dim, p->transformer.n_heads, t_cur), + ggml_reshape_3d(ctx_eval, v, p->transformer.head_dim, p->transformer.n_heads, t_cur), ap); + } else { + ggml_tensor * q_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, q, p->transformer.head_dim, p->transformer.n_heads, t_cur), 0, 2, 1, 3); + ggml_tensor * k_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, k, p->transformer.head_dim, p->transformer.n_heads, t_cur), 0, 2, 1, 3); + ggml_tensor * v_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, v, p->transformer.head_dim, p->transformer.n_heads, t_cur), 0, 2, 1, 3); - ggml_tensor * q_rope = codec_op_rope(ctx_eval, q_dth, p->transformer.head_dim, p->transformer.rope_theta, freq_scale, CODEC_ROPE_MODE_NEOX); - ggml_tensor * k_rope = codec_op_rope(ctx_eval, k_dth, p->transformer.head_dim, p->transformer.rope_theta, freq_scale, CODEC_ROPE_MODE_NEOX); - if (q_rope == nullptr || k_rope == nullptr) { - return false; - } + ggml_tensor * q_rope = codec_op_rope(ctx_eval, q_dth, p->transformer.head_dim, p->transformer.rope_theta, freq_scale, CODEC_ROPE_MODE_NEOX); + ggml_tensor * k_rope = codec_op_rope(ctx_eval, k_dth, p->transformer.head_dim, p->transformer.rope_theta, freq_scale, CODEC_ROPE_MODE_NEOX); + if (q_rope == nullptr || k_rope == nullptr) { + return false; + } - codec_lm_attn_params attn_p = {}; - attn_p.scale = 1.0f / std::sqrt((float) p->transformer.head_dim); - attn_p.causal = true; - ggml_tensor * attn_ctx = codec_op_lm_attn_ctx_dth(ctx_eval, q_rope, k_rope, v_dth, &attn_p); - if (attn_ctx == nullptr) { - return false; + codec_lm_attn_params attn_p = {}; + attn_p.scale = 1.0f / std::sqrt((float) p->transformer.head_dim); + attn_p.causal = true; + attn_p.window = p->window; + ggml_tensor * attn_ctx = codec_op_lm_attn_ctx_dth(ctx_eval, q_rope, k_rope, v_dth, &attn_p); + if (attn_ctx == nullptr) { + return false; + } + attn_ct = ggml_reshape_2d( + ctx_eval, + ggml_cont(ctx_eval, ggml_permute(ctx_eval, attn_ctx, 0, 2, 1, 3)), + p->transformer.c, + t_cur); } - ggml_tensor * attn_ct = ggml_reshape_2d( - ctx_eval, - ggml_cont(ctx_eval, ggml_permute(ctx_eval, attn_ctx, 0, 2, 1, 3)), - p->transformer.c, - t_cur); if (attn_ct == nullptr) { return false; } @@ -475,7 +503,7 @@ bool codec_mimi_build_encode_from(ggml_context * ctx_eval, const mimi_encode_bui if (t_downsample_w == nullptr) { return false; } - x = codec_conv1d_causal_replicate(ctx_eval, x, t_downsample_w, nullptr, p->downsample.stride, 1); + x = codec_memory_conv1d_causal(ctx_eval, mem, x, t_downsample_w, nullptr, p->downsample.stride, 1, /*replicate=*/true); if (x == nullptr) { return false; } @@ -620,6 +648,11 @@ static bool codec_mimi_build_decode(ggml_context * ctx_eval, void * user_data, g return false; } auto W = [&](const std::string & name) { return codec_graph_weight(ctx_eval, p->model, name); }; + codec_memory * mem = p->mem; + if (mem != nullptr && p->window <= 0) { + return false; // memory needs a bounded attention window + } + codec_memory_begin_build(mem); // Per-layer RVQ decode: sum semantic/acoustic codebook vectors, then project each branch to hidden_size. const int32_t n_acu = std::max(0, p->q - p->n_sem); @@ -660,7 +693,7 @@ static bool codec_mimi_build_decode(ggml_context * ctx_eval, void * user_data, g } ggml_tensor * x = ggml_cont(ctx_eval, ggml_transpose(ctx_eval, t_latent_ct)); // [t, c] - x = codec_convtr1d_causal(ctx_eval, x, t_up_w, nullptr, p->upsample_stride, 1); + x = codec_memory_convtr1d_causal(ctx_eval, mem, x, t_up_w, nullptr, p->upsample_stride); if (x == nullptr) { return false; } @@ -700,28 +733,49 @@ static bool codec_mimi_build_decode(ggml_context * ctx_eval, void * user_data, g return false; } - ggml_tensor * q_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, q, p->transformer_head_dim, p->transformer_heads, t_cur), 0, 2, 1, 3); - ggml_tensor * k_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, k, p->transformer_head_dim, p->transformer_heads, t_cur), 0, 2, 1, 3); - ggml_tensor * v_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, v, p->transformer_head_dim, p->transformer_heads, t_cur), 0, 2, 1, 3); + ggml_tensor * ctx_2d = nullptr; + if (mem != nullptr) { + codec_memory_attn_params ap; + ap.head_dim = p->transformer_head_dim; + ap.n_heads = p->transformer_heads; + ap.n_kv_heads = p->transformer_heads; + ap.window = p->window; + ap.rope_theta = p->rope_theta; + ap.rope_freq_scale = freq_scale; + ap.rope_mode = CODEC_ROPE_MODE_NEOX; + ap.scale = 1.0f / std::sqrt((float) p->transformer_head_dim); + ctx_2d = codec_memory_attn(ctx_eval, mem, + ggml_reshape_3d(ctx_eval, q, p->transformer_head_dim, p->transformer_heads, t_cur), + ggml_reshape_3d(ctx_eval, k, p->transformer_head_dim, p->transformer_heads, t_cur), + ggml_reshape_3d(ctx_eval, v, p->transformer_head_dim, p->transformer_heads, t_cur), ap); + if (ctx_2d == nullptr) { + return false; + } + } else { + ggml_tensor * q_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, q, p->transformer_head_dim, p->transformer_heads, t_cur), 0, 2, 1, 3); + ggml_tensor * k_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, k, p->transformer_head_dim, p->transformer_heads, t_cur), 0, 2, 1, 3); + ggml_tensor * v_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, v, p->transformer_head_dim, p->transformer_heads, t_cur), 0, 2, 1, 3); - ggml_tensor * q_rope = codec_op_rope(ctx_eval, q_dth, p->transformer_head_dim, p->rope_theta, freq_scale, CODEC_ROPE_MODE_NEOX); - ggml_tensor * k_rope = codec_op_rope(ctx_eval, k_dth, p->transformer_head_dim, p->rope_theta, freq_scale, CODEC_ROPE_MODE_NEOX); - if (q_rope == nullptr || k_rope == nullptr) { - return false; - } + ggml_tensor * q_rope = codec_op_rope(ctx_eval, q_dth, p->transformer_head_dim, p->rope_theta, freq_scale, CODEC_ROPE_MODE_NEOX); + ggml_tensor * k_rope = codec_op_rope(ctx_eval, k_dth, p->transformer_head_dim, p->rope_theta, freq_scale, CODEC_ROPE_MODE_NEOX); + if (q_rope == nullptr || k_rope == nullptr) { + return false; + } - codec_lm_attn_params attn_p = {}; - attn_p.scale = 1.0f / std::sqrt((float) p->transformer_head_dim); - attn_p.causal = true; - ggml_tensor * ctx_3d = codec_op_lm_attn_ctx_dth(ctx_eval, q_rope, k_rope, v_dth, &attn_p); - if (ctx_3d == nullptr) { - return false; + codec_lm_attn_params attn_p = {}; + attn_p.scale = 1.0f / std::sqrt((float) p->transformer_head_dim); + attn_p.causal = true; + attn_p.window = p->window; + ggml_tensor * ctx_3d = codec_op_lm_attn_ctx_dth(ctx_eval, q_rope, k_rope, v_dth, &attn_p); + if (ctx_3d == nullptr) { + return false; + } + ctx_2d = ggml_reshape_2d( + ctx_eval, + ggml_cont(ctx_eval, ggml_permute(ctx_eval, ctx_3d, 0, 2, 1, 3)), + p->hidden_size, + t_cur); } - ggml_tensor * ctx_2d = ggml_reshape_2d( - ctx_eval, - ggml_cont(ctx_eval, ggml_permute(ctx_eval, ctx_3d, 0, 2, 1, 3)), - p->hidden_size, - t_cur); ggml_tensor * attn_out = mul_mat_checked("dtr.o_proj", o_w, ctx_2d); if (attn_out == nullptr) { return false; @@ -784,36 +838,36 @@ static bool codec_mimi_build_decode(ggml_context * ctx_eval, void * user_data, g return false; } - x = codec_conv1d_causal(ctx_eval, x, t_l0_w, t_l0_b, 1, 1); + x = codec_memory_conv1d_causal(ctx_eval, mem, x, t_l0_w, t_l0_b, 1, 1); if (x == nullptr) { return false; } x = codec_op_unary(ctx_eval, x, CODEC_UNARY_ELU); - x = codec_convtr1d_causal(ctx_eval, x, t_l2_w, t_l2_b, 8, 1); - x = codec_mimi_resblock_ggml(ctx_eval, x, t_r0_c1_w, t_r0_c1_b, t_r0_c2_w, t_r0_c2_b); + x = codec_memory_convtr1d_causal(ctx_eval, mem, x, t_l2_w, t_l2_b, 8); + x = codec_mimi_resblock_ggml(ctx_eval, mem, x, t_r0_c1_w, t_r0_c1_b, t_r0_c2_w, t_r0_c2_b); if (x == nullptr) { return false; } x = codec_op_unary(ctx_eval, x, CODEC_UNARY_ELU); - x = codec_convtr1d_causal(ctx_eval, x, t_l5_w, t_l5_b, 6, 1); - x = codec_mimi_resblock_ggml(ctx_eval, x, t_r1_c1_w, t_r1_c1_b, t_r1_c2_w, t_r1_c2_b); + x = codec_memory_convtr1d_causal(ctx_eval, mem, x, t_l5_w, t_l5_b, 6); + x = codec_mimi_resblock_ggml(ctx_eval, mem, x, t_r1_c1_w, t_r1_c1_b, t_r1_c2_w, t_r1_c2_b); if (x == nullptr) { return false; } x = codec_op_unary(ctx_eval, x, CODEC_UNARY_ELU); - x = codec_convtr1d_causal(ctx_eval, x, t_l8_w, t_l8_b, 5, 1); - x = codec_mimi_resblock_ggml(ctx_eval, x, t_r2_c1_w, t_r2_c1_b, t_r2_c2_w, t_r2_c2_b); + x = codec_memory_convtr1d_causal(ctx_eval, mem, x, t_l8_w, t_l8_b, 5); + x = codec_mimi_resblock_ggml(ctx_eval, mem, x, t_r2_c1_w, t_r2_c1_b, t_r2_c2_w, t_r2_c2_b); if (x == nullptr) { return false; } x = codec_op_unary(ctx_eval, x, CODEC_UNARY_ELU); - x = codec_convtr1d_causal(ctx_eval, x, t_l11_w, t_l11_b, 4, 1); - x = codec_mimi_resblock_ggml(ctx_eval, x, t_r3_c1_w, t_r3_c1_b, t_r3_c2_w, t_r3_c2_b); + x = codec_memory_convtr1d_causal(ctx_eval, mem, x, t_l11_w, t_l11_b, 4); + x = codec_mimi_resblock_ggml(ctx_eval, mem, x, t_r3_c1_w, t_r3_c1_b, t_r3_c2_w, t_r3_c2_b); if (x == nullptr) { return false; } x = codec_op_unary(ctx_eval, x, CODEC_UNARY_ELU); - ggml_tensor * t_pcm = codec_conv1d_causal(ctx_eval, x, t_l14_w, t_l14_b, 1, 1); + ggml_tensor * t_pcm = codec_memory_conv1d_causal(ctx_eval, mem, x, t_l14_w, t_l14_b, 1, 1); if (t_pcm == nullptr) { return false; } @@ -962,6 +1016,8 @@ static bool codec_mimi_init_decode_build( } build->model = ctx->model; + build->mem = nullptr; + build->window = codec_mimi_window_steps(ctx->model->dec_look_back, build->upsample_stride); return true; } @@ -998,7 +1054,8 @@ enum codec_status codec_mimi_decode_with( const int32_t t = tokens->n_frames; const int32_t q = use_n_q; - codec_graph_eval_guard eval_guard(ctx); + codec_memory * mem = codec_memory_active(ctx, CODEC_MEMORY_DECODER); + codec_graph_eval_guard eval_guard(ctx, /*persist=*/mem != nullptr); const int32_t n_sem = std::max(1, std::min(mm.num_semantic_quantizers, q)); mimi_decode_build build = {}; std::string err; @@ -1006,10 +1063,13 @@ enum codec_status codec_mimi_decode_with( codec_context_set_error(ctx, err); return CODEC_STATUS_INTERNAL_ERROR; } + build.mem = mem; + codec_graph_cache_key key = { CODEC_GRAPH_MIMI_DECODE, /*n_frames=*/t, /*n_q=*/q, /*hop=*/build.hop, /*n_in=*/0, /*latent_dim=*/0 }; + key.mem = mem != nullptr ? 1 : 0; codec_graph_cache_entry * entry = nullptr; if (!codec_graph_cache_get_or_build( ctx, - { CODEC_GRAPH_MIMI_DECODE, /*n_frames=*/t, /*n_q=*/q, /*hop=*/build.hop, /*n_in=*/0, /*latent_dim=*/0 }, + key, codec_mimi_build_decode, &build, sizeof(build), @@ -1045,11 +1105,16 @@ enum codec_status codec_mimi_decode_with( return CODEC_STATUS_INTERNAL_ERROR; } + if (!codec_memory_set_inputs(ctx, entry, mem, &err)) { + codec_context_set_error(ctx, err); + return CODEC_STATUS_INTERNAL_ERROR; + } const int32_t n_threads = ctx->n_threads; if (!codec_graph_compute(ctx, entry, n_threads, &err)) { codec_context_set_error(ctx, err); return CODEC_STATUS_INTERNAL_ERROR; } + codec_memory_commit(mem, t); const int32_t n_samples = (int32_t) t_out->ne[0]; float * pcm = static_cast(std::malloc((size_t) n_samples * sizeof(float))); @@ -1125,14 +1190,18 @@ enum codec_status codec_mimi_encode_with( return CODEC_STATUS_INTERNAL_ERROR; } build.model = ctx->model; + codec_memory * mem = codec_memory_active(ctx, CODEC_MEMORY_ENCODER); + build.mem = mem; // Eval arena only needs to hold ggml tensor metadata (no_alloc=true), which scales // with graph size, not tensor element counts. Avoid huge allocations for long inputs. - codec_graph_eval_guard eval_guard(ctx); + codec_graph_eval_guard eval_guard(ctx, /*persist=*/mem != nullptr); + codec_graph_cache_key key = { CODEC_GRAPH_MIMI_ENCODE, /*n_frames=*/0, /*n_q=*/build.n_q, /*hop=*/0, /*n_in=*/n_in, /*latent_dim=*/build.transformer.c }; + key.mem = mem != nullptr ? 1 : 0; codec_graph_cache_entry * entry = nullptr; if (!codec_graph_cache_get_or_build( ctx, - { CODEC_GRAPH_MIMI_ENCODE, /*n_frames=*/0, /*n_q=*/build.n_q, /*hop=*/0, /*n_in=*/n_in, /*latent_dim=*/build.transformer.c }, + key, codec_mimi_build_encode, &build, sizeof(build), @@ -1155,6 +1224,10 @@ enum codec_status codec_mimi_encode_with( return CODEC_STATUS_INTERNAL_ERROR; } + if (!codec_memory_set_inputs(ctx, entry, mem, &err)) { + codec_context_set_error(ctx, err); + return CODEC_STATUS_INTERNAL_ERROR; + } const int32_t n_threads = ctx->n_threads; if (!codec_graph_compute(ctx, entry, n_threads, &err)) { codec_context_set_error(ctx, err); @@ -1162,6 +1235,7 @@ enum codec_status codec_mimi_encode_with( } const int32_t t = (int32_t) t_indices->ne[0]; + codec_memory_commit(mem, t); const int32_t n_q_graph = (int32_t) t_indices->ne[1]; if (t <= 0 || n_q_graph < use_n_q) { codec_context_set_error(ctx, "Mimi encode output shape mismatch"); @@ -1237,6 +1311,31 @@ static enum codec_status codec_mimi_decode_wrap( return codec_mimi_decode(ctx, tokens, out_pcm, params); } +bool codec_mimi_memory_plan_encoder(codec_context * ctx, const codec_mimi * mimi, codec_memory * mem, std::string * err) { + mimi_encode_build build = {}; + // two frames: the stride-2 downsample needs an even transformer length + if (!codec_mimi_init_encode_build(ctx, mimi, 2 * std::max(1, mimi->hop_size), &build, err)) { + return false; + } + build.model = ctx->model; + build.mem = mem; + return codec_memory_plan_build(ctx, mem, codec_mimi_build_encode, &build, err); +} + +static bool codec_mimi_memory_plan(codec_context * ctx, int32_t side, codec_memory * mem, std::string * err) { + codec_mimi & mm = *static_cast(ctx->model->impl); + if (side == CODEC_MEMORY_ENCODER) { + return codec_mimi_memory_plan_encoder(ctx, &mm, mem, err); + } + mimi_decode_build build = {}; + const int32_t q = std::max(1, mm.n_q); + if (!codec_mimi_init_decode_build(ctx, &mm, 1, q, std::max(1, std::min(mm.num_semantic_quantizers, q)), &build, err)) { + return false; + } + build.mem = mem; + return codec_memory_plan_build(ctx, mem, codec_mimi_build_decode, &build, err); +} + const struct codec_model_vtable * codec_mimi_vtable() { static const codec_model_vtable vtable = { CODEC_ARCH_MIMI, @@ -1248,6 +1347,9 @@ const struct codec_model_vtable * codec_mimi_vtable() { codec_mimi_encode_wrap, codec_mimi_decode_wrap, nullptr, + nullptr, + nullptr, + codec_mimi_memory_plan, }; return &vtable; } diff --git a/src/models/mimi.h b/src/models/mimi.h index 121bf3b..4673e88 100644 --- a/src/models/mimi.h +++ b/src/models/mimi.h @@ -59,6 +59,14 @@ struct mimi_encode_downsample_build { }; constexpr int32_t CODEC_MIMI_MAX_RVQ_LAYERS = 32; +// The transformers' sliding window, in transformer steps, from a side's +// look_back (codec frames; GGUF codec..look_back or the per-arch default +// 125): the transformers run at `steps_per_frame` (2) times the frame rate, so +// Mimi's trained 250-step window (Kyutai's `context: 250`, HF +// MimiConfig.sliding_window). Batch and memory both apply it; 0 = unbounded. +inline int32_t codec_mimi_window_steps(int32_t look_back, int32_t steps_per_frame) { + return look_back > 0 ? look_back * steps_per_frame : 0; +} constexpr int32_t CODEC_MIMI_RVQ_GROUP_SEMANTIC = 0; constexpr int32_t CODEC_MIMI_RVQ_GROUP_ACOUSTIC = 1; @@ -76,10 +84,16 @@ struct mimi_encode_build { int32_t codebook_size = 0; std::array rvq_layers = {}; const codec_model * model = nullptr; + // codec memory (nullptr = batch graph) and the transformer's sliding window + // in steps (codec_mimi_window_steps; 0 = unbounded), batch and memory alike. + struct codec_memory * mem = nullptr; + int32_t window = 0; }; bool codec_mimi_init_encode_build( codec_context * ctx, const codec_mimi * mimi, int32_t n_in, mimi_encode_build * build, std::string * err); +// Codec memory plan of the Mimi encoder (also the Qwen3-TTS tokenizer's). +bool codec_mimi_memory_plan_encoder(codec_context * ctx, const codec_mimi * mimi, struct codec_memory * mem, std::string * err); // pcm: F32 [n_in, 1] at the model rate -> *out: I32 codes [t, n_q]. bool codec_mimi_build_encode_from(ggml_context * ctx_eval, const mimi_encode_build * build, ggml_tensor * pcm, ggml_tensor ** out); diff --git a/src/models/moss_audio.cpp b/src/models/moss_audio.cpp index 3038eef..30c9457 100644 --- a/src/models/moss_audio.cpp +++ b/src/models/moss_audio.cpp @@ -5,6 +5,7 @@ #include "../ops/lm_attn.h" #include "../ops/rope.h" #include "../runtime/graph.h" +#include "../runtime/memory.h" #include "../runtime/gguf_kv.h" #include "../runtime/tensor_utils.h" @@ -101,7 +102,8 @@ ggml_tensor * codec_moss_transformer_layer_tc( int32_t n_heads, float rope_theta, int32_t window, - int32_t n_valid) { + int32_t n_valid, + codec_memory * mem) { if (ctx == nullptr || x_tc == nullptr) return nullptr; const int64_t t = x_tc->ne[0]; @@ -122,36 +124,52 @@ ggml_tensor * codec_moss_transformer_layer_tc( ggml_tensor * q_dht = ggml_reshape_3d(ctx, q, head_dim, n_heads, t); // [d, h, t] ggml_tensor * k_dht = ggml_reshape_3d(ctx, k, head_dim, n_heads, t); ggml_tensor * v_dht = ggml_reshape_3d(ctx, v, head_dim, n_heads, t); - // MOSS RoPE: rotate pairs (q[2k], q[2k+1]) along head_dim per token - // position. We bypass codec_op_rope (which assumes a (d, t, h) input - // ordering) and call ggml_rope_ext directly with the natural (d, h, t) - // layout — that matches ggml's expected (n_embd_per_head, n_head, - // n_tokens) shape and uses NEOX-mode for interleaved pairs. - ggml_tensor * t_pos = ggml_cast(ctx, codec_op_arange(ctx, 0.0f, (float) t, 1.0f), GGML_TYPE_I32); - // ggml NEOX = half-split pairs (k, k+D/2); NORMAL = interleaved (2k, 2k+1). - // MOSS does `q.view(..., D//2, 2)` which is interleaved → NORMAL mode. - ggml_tensor * q_rope_dht = ggml_rope_ext(ctx, q_dht, t_pos, nullptr, - head_dim, GGML_ROPE_TYPE_NORMAL, 0, - rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); - ggml_tensor * k_rope_dht = ggml_rope_ext(ctx, k_dht, t_pos, nullptr, - head_dim, GGML_ROPE_TYPE_NORMAL, 0, - rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); - if (q_rope_dht == nullptr || k_rope_dht == nullptr) return nullptr; - // Permute (d, h, t) → (d, t, h) for the attention helper. - ggml_tensor * q_dth = ggml_cont(ctx, ggml_permute(ctx, q_rope_dht, 0, 2, 1, 3)); // [d, t, h] - ggml_tensor * k_dth = ggml_cont(ctx, ggml_permute(ctx, k_rope_dht, 0, 2, 1, 3)); - ggml_tensor * v_dth = ggml_cont(ctx, ggml_permute(ctx, v_dht, 0, 2, 1, 3)); - - codec_lm_attn_params attn_p = {}; - attn_p.scale = 1.0f / std::sqrt((float) head_dim); - attn_p.causal = true; - attn_p.window = window; - attn_p.n_valid = n_valid; - ggml_tensor * attn_dth = codec_op_lm_attn_ctx_dth(ctx, q_dth, k_dth, v_dth, &attn_p); - if (attn_dth == nullptr) return nullptr; - // Permute back (d, t, h) → (d, h, t) → reshape (hidden, t). - ggml_tensor * attn_dht = ggml_cont(ctx, ggml_permute(ctx, attn_dth, 0, 2, 1, 3)); - ggml_tensor * attn_ct = ggml_reshape_2d(ctx, attn_dht, hidden, t); + ggml_tensor * attn_ct = nullptr; + if (mem != nullptr) { + codec_memory_attn_params ap; + ap.head_dim = head_dim; + ap.n_heads = n_heads; + ap.n_kv_heads = n_heads; + ap.window = window; + ap.rope_theta = rope_theta; + ap.rope_freq_scale = 1.0f; + ap.rope_mode = GGML_ROPE_TYPE_NORMAL; + ap.scale = 1.0f / std::sqrt((float) head_dim); + ap.n_valid = n_valid; + attn_ct = codec_memory_attn(ctx, mem, q_dht, k_dht, v_dht, ap); + if (attn_ct == nullptr) return nullptr; + } else { + // MOSS RoPE: rotate pairs (q[2k], q[2k+1]) along head_dim per token + // position. We bypass codec_op_rope (which assumes a (d, t, h) input + // ordering) and call ggml_rope_ext directly with the natural (d, h, t) + // layout — that matches ggml's expected (n_embd_per_head, n_head, + // n_tokens) shape and uses NEOX-mode for interleaved pairs. + ggml_tensor * t_pos = ggml_cast(ctx, codec_op_arange(ctx, 0.0f, (float) t, 1.0f), GGML_TYPE_I32); + // ggml NEOX = half-split pairs (k, k+D/2); NORMAL = interleaved (2k, 2k+1). + // MOSS does `q.view(..., D//2, 2)` which is interleaved → NORMAL mode. + ggml_tensor * q_rope_dht = ggml_rope_ext(ctx, q_dht, t_pos, nullptr, + head_dim, GGML_ROPE_TYPE_NORMAL, 0, + rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); + ggml_tensor * k_rope_dht = ggml_rope_ext(ctx, k_dht, t_pos, nullptr, + head_dim, GGML_ROPE_TYPE_NORMAL, 0, + rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); + if (q_rope_dht == nullptr || k_rope_dht == nullptr) return nullptr; + // Permute (d, h, t) → (d, t, h) for the attention helper. + ggml_tensor * q_dth = ggml_cont(ctx, ggml_permute(ctx, q_rope_dht, 0, 2, 1, 3)); // [d, t, h] + ggml_tensor * k_dth = ggml_cont(ctx, ggml_permute(ctx, k_rope_dht, 0, 2, 1, 3)); + ggml_tensor * v_dth = ggml_cont(ctx, ggml_permute(ctx, v_dht, 0, 2, 1, 3)); + + codec_lm_attn_params attn_p = {}; + attn_p.scale = 1.0f / std::sqrt((float) head_dim); + attn_p.causal = true; + attn_p.window = window; + attn_p.n_valid = n_valid; + ggml_tensor * attn_dth = codec_op_lm_attn_ctx_dth(ctx, q_dth, k_dth, v_dth, &attn_p); + if (attn_dth == nullptr) return nullptr; + // Permute back (d, t, h) → (d, h, t) → reshape (hidden, t). + ggml_tensor * attn_dht = ggml_cont(ctx, ggml_permute(ctx, attn_dth, 0, 2, 1, 3)); + attn_ct = ggml_reshape_2d(ctx, attn_dht, hidden, t); + } ggml_tensor * out_ct = codec_mul_mat(ctx, out_w, attn_ct); // [hidden, t] if (out_ct == nullptr) return nullptr; ggml_tensor * out_tc = ggml_cont(ctx, ggml_transpose(ctx, out_ct)); // [t, hidden] @@ -198,7 +216,8 @@ ggml_tensor * codec_moss_projected_transformer_ct( int32_t n_layers, int32_t window, float rope_theta, - int32_t n_valid) { + int32_t n_valid, + codec_memory * mem) { auto W = [&](const std::string & name) -> ggml_tensor * { return codec_graph_weight(ctx, model, name); @@ -229,7 +248,7 @@ ggml_tensor * codec_moss_projected_transformer_ct( W(lp + ".ffn.fc2.w"), W(lp + ".ls1"), W(lp + ".ls2"), - head_dim, n_heads, rope_theta, window, n_valid); + head_dim, n_heads, rope_theta, window, n_valid, mem); if (h_tc == nullptr) return nullptr; } @@ -257,6 +276,7 @@ struct moss_encode_build { int32_t n_codes = 0; // T_audio_total / hop const codec_moss_audio * cfg = nullptr; const codec_model * model = nullptr; + codec_memory * mem = nullptr; // encoder memory, nullptr = batch graph }; static bool codec_moss_build_encode(ggml_context * ctx_eval, void * user_data, ggml_tensor ** out) { @@ -266,6 +286,7 @@ static bool codec_moss_build_encode(ggml_context * ctx_eval, void * user_data, g auto W = [&](const std::string & name) -> ggml_tensor * { return codec_graph_weight(ctx_eval, p->model, name); }; + codec_memory_begin_build(p->mem); // Input PCM laid out as a single mono-equivalent stream. When // interleaving is on the prep step has already woven channels together, @@ -312,7 +333,7 @@ static bool codec_moss_build_encode(ggml_context * ctx_eval, void * user_data, g ctx_eval, x_ct, p->model, base, cfg.enc_in_dim[mi], cfg.enc_out_dim[mi], cfg.enc_d_model[mi], cfg.enc_n_heads[mi], cfg.enc_n_layers[mi], - win_tokens, cfg.enc_max_period[mi], n_valid_block); + win_tokens, cfg.enc_max_period[mi], n_valid_block, p->mem); if (x_ct == nullptr) return false; x_tc = ggml_cont(ctx_eval, ggml_transpose(ctx_eval, x_ct)); } @@ -401,6 +422,7 @@ struct moss_decode_build { int32_t cb_dim = 0; const codec_moss_audio * cfg = nullptr; const codec_model * model = nullptr; + codec_memory * mem = nullptr; // decoder memory, nullptr = batch graph }; static bool codec_moss_build_decode(ggml_context * ctx_eval, void * user_data, ggml_tensor ** out) { @@ -410,6 +432,7 @@ static bool codec_moss_build_decode(ggml_context * ctx_eval, void * user_data, g auto W = [&](const std::string & name) -> ggml_tensor * { return codec_graph_weight(ctx_eval, p->model, name); }; + codec_memory_begin_build(p->mem); // Input codes — laid out as ne=(t, n_q) int32; each row q holds one // codebook's per-frame indices. @@ -464,7 +487,7 @@ static bool codec_moss_build_decode(ggml_context * ctx_eval, void * user_data, g ctx_eval, x_ct, p->model, base, cfg.dec_in_dim[mi], cfg.dec_out_dim[mi], cfg.dec_d_model[mi], cfg.dec_n_heads[mi], cfg.dec_n_layers[mi], - win_tokens, cfg.dec_max_period[mi], /*n_valid=*/0); + win_tokens, cfg.dec_max_period[mi], /*n_valid=*/0, p->mem); if (x_ct == nullptr) return false; x_tc = ggml_cont(ctx_eval, ggml_transpose(ctx_eval, x_ct)); } @@ -533,16 +556,20 @@ static enum codec_status codec_moss_run_encode( build.n_codes = n_codes; build.cfg = &cfg; build.model = ctx->model; + codec_memory * mem = codec_memory_active(ctx, CODEC_MEMORY_ENCODER); + build.mem = mem; - codec_graph_eval_guard guard(ctx); + codec_graph_eval_guard guard(ctx, /*persist=*/mem != nullptr); std::string err; + codec_graph_cache_key key = { CODEC_GRAPH_MOSS_AUDIO_ENCODE, + /*n_frames=*/n_codes, /*n_q=*/cfg.n_q, /*hop=*/cfg.hop_size, + /*n_in=*/n_total, /*latent_dim=*/cfg.latent_dim }; + key.mem = mem != nullptr ? 1 : 0; codec_graph_cache_entry * entry = nullptr; if (!codec_graph_cache_get_or_build( ctx, - { CODEC_GRAPH_MOSS_AUDIO_ENCODE, - /*n_frames=*/n_codes, /*n_q=*/cfg.n_q, /*hop=*/cfg.hop_size, - /*n_in=*/n_total, /*latent_dim=*/cfg.latent_dim }, + key, codec_moss_build_encode, &build, sizeof(build), @@ -565,11 +592,16 @@ static enum codec_status codec_moss_run_encode( codec_context_set_error(ctx, err); return CODEC_STATUS_INTERNAL_ERROR; } + if (!codec_memory_set_inputs(ctx, entry, mem, &err)) { + codec_context_set_error(ctx, err); + return CODEC_STATUS_INTERNAL_ERROR; + } const int32_t n_threads = ctx->n_threads; if (!codec_graph_compute(ctx, entry, n_threads, &err)) { codec_context_set_error(ctx, err); return CODEC_STATUS_INTERNAL_ERROR; } + codec_memory_commit(mem, n_codes); if (t_codes->type != GGML_TYPE_I32 || t_codes->ne[0] != n_codes || t_codes->ne[1] != cfg.n_q) { @@ -647,16 +679,20 @@ static enum codec_status codec_moss_run_decode( build.cb_dim = cfg.codebook_dim; build.cfg = &cfg; build.model = ctx->model; + codec_memory * mem = codec_memory_active(ctx, CODEC_MEMORY_DECODER); + build.mem = mem; - codec_graph_eval_guard guard(ctx); + codec_graph_eval_guard guard(ctx, /*persist=*/mem != nullptr); std::string err; + codec_graph_cache_key key = { CODEC_GRAPH_MOSS_AUDIO_DECODE, + /*n_frames=*/n_codes, /*n_q=*/n_q_dec, /*hop=*/cfg.hop_size, + /*n_in=*/0, /*latent_dim=*/cfg.latent_dim }; + key.mem = mem != nullptr ? 1 : 0; codec_graph_cache_entry * entry = nullptr; if (!codec_graph_cache_get_or_build( ctx, - { CODEC_GRAPH_MOSS_AUDIO_DECODE, - /*n_frames=*/n_codes, /*n_q=*/n_q_dec, /*hop=*/cfg.hop_size, - /*n_in=*/0, /*latent_dim=*/cfg.latent_dim }, + key, codec_moss_build_decode, &build, sizeof(build), @@ -692,11 +728,16 @@ static enum codec_status codec_moss_run_decode( return CODEC_STATUS_INTERNAL_ERROR; } + if (!codec_memory_set_inputs(ctx, entry, mem, &err)) { + codec_context_set_error(ctx, err); + return CODEC_STATUS_INTERNAL_ERROR; + } const int32_t n_threads = ctx->n_threads; if (!codec_graph_compute(ctx, entry, n_threads, &err)) { codec_context_set_error(ctx, err); return CODEC_STATUS_INTERNAL_ERROR; } + codec_memory_commit(mem, n_codes); const int32_t n_total = (int32_t) t_audio->ne[0]; std::vector raw((size_t) n_total, 0.0f); @@ -815,9 +856,53 @@ enum codec_status codec_moss_audio_init(struct codec_model * model) { model->codebook_size = cfg.codebook_size; model->latent_dim = cfg.latent_dim; model->expected_channels = cfg.number_channels; + // causal both ways; look_back = the longest per-stage attention context, in codec frames + { + const double fps = cfg.hop_size > 0 ? (double) cfg.sample_rate / (double) cfg.hop_size : 0.0; + float enc_ctx = 0.0f, dec_ctx = 0.0f; + for (int32_t i = 0; i < cfg.enc_n_modules; ++i) enc_ctx = std::max(enc_ctx, cfg.enc_context_duration[i]); + for (int32_t i = 0; i < cfg.dec_n_modules; ++i) dec_ctx = std::max(dec_ctx, cfg.dec_context_duration[i]); + model->enc_look_back = (int32_t) std::ceil(enc_ctx * fps); + model->enc_look_ahead = 0; + model->dec_look_back = (int32_t) std::ceil(dec_ctx * fps); + model->dec_look_ahead = 0; + } return CODEC_STATUS_SUCCESS; } +// Codec memory plan: build each side's graph for one code frame. +static bool codec_moss_memory_plan(codec_context * ctx, int32_t side, codec_memory * mem, std::string * err) { + codec_moss_audio & cfg = *static_cast(ctx->model->impl); + if (side == CODEC_MEMORY_ENCODER) { + moss_encode_build build = {}; + build.n_in = cfg.hop_size; + build.n_in_valid = cfg.hop_size; + build.n_channels = cfg.number_channels; + build.interleave = cfg.channel_interleave; + build.latent_dim = cfg.latent_dim; + build.rvq_dim = cfg.rvq_dim; + build.cb_dim = cfg.codebook_dim; + build.n_q = cfg.n_q; + build.n_codes = 1; + build.cfg = &cfg; + build.model = ctx->model; + build.mem = mem; + return codec_memory_plan_build(ctx, mem, codec_moss_build_encode, &build, err); + } + moss_decode_build build = {}; + build.n_codes = 1; + build.n_channels = cfg.number_channels; + build.interleave = cfg.channel_interleave; + build.n_q = cfg.n_q; + build.latent_dim = cfg.latent_dim; + build.rvq_dim = cfg.rvq_dim; + build.cb_dim = cfg.codebook_dim; + build.cfg = &cfg; + build.model = ctx->model; + build.mem = mem; + return codec_memory_plan_build(ctx, mem, codec_moss_build_decode, &build, err); +} + static void * codec_moss_create_impl() { return new (std::nothrow) codec_moss_audio(); } static void codec_moss_destroy_impl(void * ptr) { delete static_cast(ptr); } @@ -848,6 +933,10 @@ const struct codec_model_vtable * codec_moss_audio_vtable() { codec_graph_size_exact, codec_moss_encode_wrap, codec_moss_decode_wrap, + nullptr, + nullptr, + nullptr, + codec_moss_memory_plan, }; return &vtable; } diff --git a/src/models/nemo_nano_codec.cpp b/src/models/nemo_nano_codec.cpp index 72dacea..2b4cd59 100644 --- a/src/models/nemo_nano_codec.cpp +++ b/src/models/nemo_nano_codec.cpp @@ -4,6 +4,7 @@ #include "../ops/convtr1d.h" #include "../ops/ggml_ops.h" #include "../runtime/graph.h" +#include "../runtime/memory.h" #include "../runtime/tensor_utils.h" #include @@ -91,6 +92,7 @@ struct nemo_decode_build { int32_t codebook_dim = 0; int32_t codebook_size = 0; const codec_model * model = nullptr; + codec_memory * mem = nullptr; // decoder memory, nullptr = batch graph }; static bool nemo_build_encode(ggml_context * ctx_eval, void * user_data, ggml_tensor ** out) { @@ -239,6 +241,8 @@ static bool nemo_build_decode(ggml_context * ctx_eval, void * user_data, ggml_te auto W = [&](const std::string & name) -> ggml_tensor * { return codec_graph_weight(ctx_eval, p->model, name); }; + codec_memory * mem = p->mem; + codec_memory_begin_build(mem); ggml_tensor * t_tok = ggml_new_tensor_2d(ctx_eval, GGML_TYPE_I32, p->t, p->q); ggml_set_name(t_tok, "nemo.decode.tok"); @@ -263,7 +267,7 @@ static bool nemo_build_decode(ggml_context * ctx_eval, void * user_data, ggml_te if (t_pre_w == nullptr || t_pre_b == nullptr) { return false; } - x = codec_conv1d_causal(ctx_eval, x, t_pre_w, t_pre_b, 1, 1); + x = codec_memory_conv1d_causal(ctx_eval, mem, x, t_pre_w, t_pre_b, 1, 1); if (x == nullptr) { return false; } @@ -291,7 +295,7 @@ static bool nemo_build_decode(ggml_context * ctx_eval, void * user_data, ggml_te if (t_up_w == nullptr || t_up_b == nullptr) { return false; } - x = codec_convtr1d_causal(ctx_eval, x, t_up_w, t_up_b, stride, 1); + x = codec_memory_convtr1d_causal(ctx_eval, mem, x, t_up_w, t_up_b, stride); if (x == nullptr) { return false; } @@ -320,7 +324,7 @@ static bool nemo_build_decode(ggml_context * ctx_eval, void * user_data, ggml_te ggml_tensor * x_lr_r = codec_op_leaky_relu(ctx_eval, x_right_r, 0.01f); ggml_tensor * x_act = ggml_concat(ctx_eval, x_snake_r, x_lr_r, 1); - ggml_tensor * h = codec_conv1d_causal(ctx_eval, x_act, t_in_w, t_in_b, 1, dilations[ri]); + ggml_tensor * h = codec_memory_conv1d_causal(ctx_eval, mem, x_act, t_in_w, t_in_b, 1, dilations[ri]); if (h == nullptr) { return false; } @@ -331,7 +335,7 @@ static bool nemo_build_decode(ggml_context * ctx_eval, void * user_data, ggml_te ggml_tensor * h_lr = codec_op_leaky_relu(ctx_eval, h_right, 0.01f); ggml_tensor * h_act = ggml_concat(ctx_eval, h_snake, h_lr, 1); - h = codec_conv1d_causal(ctx_eval, h_act, t_sk_w, t_sk_b, 1, 1); + h = codec_memory_conv1d_causal(ctx_eval, mem, h_act, t_sk_w, t_sk_b, 1, 1); if (h == nullptr) { return false; } @@ -360,7 +364,7 @@ static bool nemo_build_decode(ggml_context * ctx_eval, void * user_data, ggml_te if (t_post_w == nullptr || t_post_b == nullptr) { return false; } - ggml_tensor * t_pcm = codec_conv1d_causal(ctx_eval, x, t_post_w, t_post_b, 1, 1); + ggml_tensor * t_pcm = codec_memory_conv1d_causal(ctx_eval, mem, x, t_post_w, t_post_b, 1, 1); if (t_pcm == nullptr) { return false; } @@ -468,14 +472,17 @@ static enum codec_status nemo_decode_graph( const int32_t q = use_n_q; const int32_t codebook_dim = std::max(1, nemo.codebook_dim); const int32_t codebook_size = std::max(2, nemo.codebook_size); - codec_graph_eval_guard eval_guard(ctx); + codec_memory * mem = codec_memory_active(ctx, CODEC_MEMORY_DECODER); + codec_graph_eval_guard eval_guard(ctx, /*persist=*/mem != nullptr); - nemo_decode_build build = { t, q, codebook_dim, codebook_size, ctx->model }; + nemo_decode_build build = { t, q, codebook_dim, codebook_size, ctx->model, mem }; + codec_graph_cache_key key = { CODEC_GRAPH_NEMO_NANO_DECODE, /*n_frames=*/t, /*n_q=*/q, /*hop=*/hop_size, /*n_in=*/0, /*latent_dim=*/0 }; + key.mem = mem != nullptr ? 1 : 0; codec_graph_cache_entry * entry = nullptr; std::string err; if (!codec_graph_cache_get_or_build( ctx, - { CODEC_GRAPH_NEMO_NANO_DECODE, /*n_frames=*/t, /*n_q=*/q, /*hop=*/hop_size, /*n_in=*/0, /*latent_dim=*/0 }, + key, nemo_build_decode, &build, sizeof(build), @@ -513,11 +520,16 @@ static enum codec_status nemo_decode_graph( return CODEC_STATUS_INTERNAL_ERROR; } + if (!codec_memory_set_inputs(ctx, entry, mem, &err)) { + codec_context_set_error(ctx, err); + return CODEC_STATUS_INTERNAL_ERROR; + } const int32_t n_threads = ctx->n_threads; if (!codec_graph_compute(ctx, entry, n_threads, &err)) { codec_context_set_error(ctx, err); return CODEC_STATUS_INTERNAL_ERROR; } + codec_memory_commit(mem, t); const int32_t n_pcm = (int32_t) t_out->ne[0]; std::vector pcm((size_t) n_pcm, 0.0f); @@ -643,6 +655,16 @@ static enum codec_status nemo_decode_wrap( return codec_nemo_nano_codec_decode(ctx, tokens, out_pcm, params); } +// Codec memory plan: the decoder graph for one frame (all convolutions). +static bool nemo_memory_plan(codec_context * ctx, int32_t side, codec_memory * mem, std::string * err) { + if (side != CODEC_MEMORY_DECODER) { + return true; + } + codec_nemo_nano_codec & nemo = *static_cast(ctx->model->impl); + nemo_decode_build build = { 1, std::max(1, nemo.n_q), std::max(1, nemo.codebook_dim), std::max(2, nemo.codebook_size), ctx->model, mem }; + return codec_memory_plan_build(ctx, mem, nemo_build_decode, &build, err); +} + const struct codec_model_vtable * codec_nemo_nano_codec_vtable() { static codec_model_vtable vtable = { CODEC_ARCH_NEMO_NANO_CODEC, @@ -654,6 +676,9 @@ const struct codec_model_vtable * codec_nemo_nano_codec_vtable() { nemo_encode_wrap, nemo_decode_wrap, nullptr, + nullptr, + nullptr, + nemo_memory_plan, }; return &vtable; } diff --git a/src/models/qwen3_tts_tokenizer.cpp b/src/models/qwen3_tts_tokenizer.cpp index d06c6d2..aa78d1c 100644 --- a/src/models/qwen3_tts_tokenizer.cpp +++ b/src/models/qwen3_tts_tokenizer.cpp @@ -6,6 +6,7 @@ #include "../ops/ggml_ops.h" #include "../ops/rope.h" #include "../runtime/graph.h" +#include "../runtime/memory.h" #include "../runtime/tensor_utils.h" #include @@ -42,6 +43,7 @@ enum codec_status codec_qwen3_tts_tokenizer_init(struct codec_model * model) { q3.intermediate_size = codec_read_i32_kv(model->gguf, "qwen3.decoder.intermediate_size", 3072); q3.rope_theta = codec_read_f32_kv(model->gguf, "qwen3.decoder.rope_theta", 10000.0f); q3.sliding_window = codec_read_i32_kv(model->gguf, "qwen3.decoder.sliding_window", 0); + model->dec_look_back = q3.sliding_window > 0 ? q3.sliding_window : -1; q3.decoder_dim = codec_read_i32_kv(model->gguf, "qwen3.decoder.decoder_dim", 1536); // upsample arrays @@ -166,6 +168,7 @@ struct q3t_decode_build { int32_t upsampling_ratios[CODEC_Q3T_MAX_UPSAMPLE]; int32_t decoder_dim; const codec_model * model; + codec_memory * mem; // decoder memory, nullptr = batch graph }; // Add bias broadcast over channels; no-op when bias is null. Used for @@ -179,6 +182,7 @@ static ggml_tensor * codec_q3t_add_bias_ct(ggml_context * ctx_eval, ggml_tensor static ggml_tensor * codec_q3t_convnext_block( ggml_context * ctx_eval, + codec_memory * mem, ggml_tensor * x_tc, ggml_tensor * dw_w, ggml_tensor * dw_b, @@ -195,7 +199,7 @@ static ggml_tensor * codec_q3t_convnext_block( } ggml_tensor * res = x_tc; - ggml_tensor * h = codec_conv1d_depthwise_causal(ctx_eval, x_tc, dw_w, dw_b, 1, 1); + ggml_tensor * h = codec_memory_conv1d_depthwise_causal(ctx_eval, mem, x_tc, dw_w, dw_b, 1, 1); if (h == nullptr) { return nullptr; } @@ -276,6 +280,11 @@ static bool codec_q3t_build_decode(ggml_context * ctx_eval, void * user_data, gg p->model == nullptr) { return false; } + if (p->mem != nullptr && p->sliding_window <= 0) { + return false; // memory needs a bounded attention window + } + codec_memory * mem = p->mem; + codec_memory_begin_build(mem); const int32_t attn_dim = p->transformer_heads * p->transformer_head_dim; const int32_t kv_dim = p->transformer_kv_heads * p->transformer_head_dim; @@ -350,7 +359,7 @@ static bool codec_q3t_build_decode(ggml_context * ctx_eval, void * user_data, gg if (t_pre_w == nullptr || t_pre_b == nullptr) { return false; } - x_tc = codec_conv1d_causal(ctx_eval, x_tc, t_pre_w, t_pre_b, 1, 1); + x_tc = codec_memory_conv1d_causal(ctx_eval, mem, x_tc, t_pre_w, t_pre_b, 1, 1); if (x_tc == nullptr) { return false; } @@ -409,34 +418,54 @@ static bool codec_q3t_build_decode(ggml_context * ctx_eval, void * user_data, gg v = codec_q3t_add_bias_ct(ctx_eval, v, v_b); const int64_t t_cur = q->ne[1]; - ggml_tensor * q_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, q, p->transformer_head_dim, p->transformer_heads, t_cur), 0, 2, 1, 3); - ggml_tensor * k_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, k, p->transformer_head_dim, p->transformer_kv_heads, t_cur), 0, 2, 1, 3); - ggml_tensor * v_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, v, p->transformer_head_dim, p->transformer_kv_heads, t_cur), 0, 2, 1, 3); + ggml_tensor * attn_ct = nullptr; + if (mem != nullptr) { + codec_memory_attn_params ap; + ap.head_dim = p->transformer_head_dim; + ap.n_heads = p->transformer_heads; + ap.n_kv_heads = p->transformer_kv_heads; + ap.window = p->sliding_window; + ap.rope_theta = p->rope_theta; + ap.rope_freq_scale = 1.0f; + ap.rope_mode = CODEC_ROPE_MODE_NEOX; + ap.scale = 1.0f / std::sqrt((float) p->transformer_head_dim); + attn_ct = codec_memory_attn(ctx_eval, mem, + ggml_reshape_3d(ctx_eval, q, p->transformer_head_dim, p->transformer_heads, t_cur), + ggml_reshape_3d(ctx_eval, k, p->transformer_head_dim, p->transformer_kv_heads, t_cur), + ggml_reshape_3d(ctx_eval, v, p->transformer_head_dim, p->transformer_kv_heads, t_cur), ap); + if (attn_ct == nullptr) { + return false; + } + } else { + ggml_tensor * q_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, q, p->transformer_head_dim, p->transformer_heads, t_cur), 0, 2, 1, 3); + ggml_tensor * k_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, k, p->transformer_head_dim, p->transformer_kv_heads, t_cur), 0, 2, 1, 3); + ggml_tensor * v_dth = ggml_permute(ctx_eval, ggml_reshape_3d(ctx_eval, v, p->transformer_head_dim, p->transformer_kv_heads, t_cur), 0, 2, 1, 3); - ggml_tensor * q_rope = codec_op_rope(ctx_eval, q_dth, p->transformer_head_dim, p->rope_theta, 1.0f, CODEC_ROPE_MODE_NEOX); - ggml_tensor * k_rope = codec_op_rope(ctx_eval, k_dth, p->transformer_head_dim, p->rope_theta, 1.0f, CODEC_ROPE_MODE_NEOX); - if (q_rope == nullptr || k_rope == nullptr) { - return false; - } - q_rope = codec_q3t_repeat_kv(ctx_eval, q_rope, p->transformer_heads, p->transformer_kv_heads); - k_rope = codec_q3t_repeat_kv(ctx_eval, k_rope, p->transformer_heads, p->transformer_kv_heads); - ggml_tensor * v_rep = codec_q3t_repeat_kv(ctx_eval, v_dth, p->transformer_heads, p->transformer_kv_heads); - if (q_rope == nullptr || k_rope == nullptr || v_rep == nullptr) { - return false; - } + ggml_tensor * q_rope = codec_op_rope(ctx_eval, q_dth, p->transformer_head_dim, p->rope_theta, 1.0f, CODEC_ROPE_MODE_NEOX); + ggml_tensor * k_rope = codec_op_rope(ctx_eval, k_dth, p->transformer_head_dim, p->rope_theta, 1.0f, CODEC_ROPE_MODE_NEOX); + if (q_rope == nullptr || k_rope == nullptr) { + return false; + } + q_rope = codec_q3t_repeat_kv(ctx_eval, q_rope, p->transformer_heads, p->transformer_kv_heads); + k_rope = codec_q3t_repeat_kv(ctx_eval, k_rope, p->transformer_heads, p->transformer_kv_heads); + ggml_tensor * v_rep = codec_q3t_repeat_kv(ctx_eval, v_dth, p->transformer_heads, p->transformer_kv_heads); + if (q_rope == nullptr || k_rope == nullptr || v_rep == nullptr) { + return false; + } - ggml_tensor * attn_scores = codec_mul_mat(ctx_eval, ggml_cont(ctx_eval, k_rope), q_rope); // [t, t, h] - attn_scores = ggml_scale_inplace(ctx_eval, attn_scores, 1.0f / std::sqrt((float) p->transformer_head_dim)); - attn_scores = codec_q3t_apply_sliding_mask(ctx_eval, attn_scores, p->sliding_window); - ggml_tensor * attn_probs = ggml_soft_max(ctx_eval, attn_scores); - - ggml_tensor * v_tdh = ggml_permute(ctx_eval, v_rep, 1, 0, 2, 3); - ggml_tensor * attn_ctx = codec_mul_mat(ctx_eval, ggml_cont(ctx_eval, v_tdh), attn_probs); // [d, t, h] - ggml_tensor * attn_ct = ggml_reshape_2d( - ctx_eval, - ggml_cont(ctx_eval, ggml_permute(ctx_eval, attn_ctx, 0, 2, 1, 3)), - attn_dim, - t_cur); + ggml_tensor * attn_scores = codec_mul_mat(ctx_eval, ggml_cont(ctx_eval, k_rope), q_rope); // [t, t, h] + attn_scores = ggml_scale_inplace(ctx_eval, attn_scores, 1.0f / std::sqrt((float) p->transformer_head_dim)); + attn_scores = codec_q3t_apply_sliding_mask(ctx_eval, attn_scores, p->sliding_window); + ggml_tensor * attn_probs = ggml_soft_max(ctx_eval, attn_scores); + + ggml_tensor * v_tdh = ggml_permute(ctx_eval, v_rep, 1, 0, 2, 3); + ggml_tensor * attn_ctx = codec_mul_mat(ctx_eval, ggml_cont(ctx_eval, v_tdh), attn_probs); // [d, t, h] + attn_ct = ggml_reshape_2d( + ctx_eval, + ggml_cont(ctx_eval, ggml_permute(ctx_eval, attn_ctx, 0, 2, 1, 3)), + attn_dim, + t_cur); + } ggml_tensor * attn_proj = codec_mul_mat(ctx_eval, o_w, attn_ct); attn_proj = codec_q3t_add_bias_ct(ctx_eval, attn_proj, o_b); x_ct = ggml_add(ctx_eval, x_ct, codec_op_channel_scale(ctx_eval, attn_proj, sa_scale)); @@ -482,8 +511,8 @@ static bool codec_q3t_build_decode(ggml_context * ctx_eval, void * user_data, gg t_pw2_w == nullptr || t_pw2_b == nullptr || t_gamma == nullptr) { return false; } - x_tc = codec_convtr1d_causal(ctx_eval, x_tc, t_up_w, t_up_b, p->upsampling_ratios[ui], 1); - x_tc = codec_q3t_convnext_block(ctx_eval, x_tc, t_dw_w, t_dw_b, t_ln_w, t_ln_b, t_pw1_w, t_pw1_b, t_pw2_w, t_pw2_b, t_gamma); + x_tc = codec_memory_convtr1d_causal(ctx_eval, mem, x_tc, t_up_w, t_up_b, p->upsampling_ratios[ui]); + x_tc = codec_q3t_convnext_block(ctx_eval, mem, x_tc, t_dw_w, t_dw_b, t_ln_w, t_ln_b, t_pw1_w, t_pw1_b, t_pw2_w, t_pw2_b, t_gamma); ggml_set_name(x_tc, (base + ".out").c_str()); } @@ -493,7 +522,7 @@ static bool codec_q3t_build_decode(ggml_context * ctx_eval, void * user_data, gg if (t_dec0_w == nullptr || t_dec0_b == nullptr) { return false; } - x_tc = codec_conv1d_causal(ctx_eval, x_tc, t_dec0_w, t_dec0_b, 1, 1); + x_tc = codec_memory_conv1d_causal(ctx_eval, mem, x_tc, t_dec0_w, t_dec0_b, 1, 1); int32_t cur_dim = p->decoder_dim; for (int32_t bi = 0; bi < p->n_upsample_rates; ++bi) { @@ -509,7 +538,7 @@ static bool codec_q3t_build_decode(ggml_context * ctx_eval, void * user_data, gg return false; } x_tc = codec_op_snake_beta(ctx_eval, x_tc, t_s0_a, t_s0_b, 1e-9f); - x_tc = codec_convtr1d_causal(ctx_eval, x_tc, t_tr_w, t_tr_b, up_rate, 1); + x_tc = codec_memory_convtr1d_causal(ctx_eval, mem, x_tc, t_tr_w, t_tr_b, up_rate); for (int32_t ri = 0; ri < CODEC_Q3T_RES_UNITS; ++ri) { const std::string rbase = base + ".r" + std::to_string(ri); @@ -528,9 +557,9 @@ static bool codec_q3t_build_decode(ggml_context * ctx_eval, void * user_data, gg ggml_tensor * res = x_tc; x_tc = codec_op_snake_beta(ctx_eval, x_tc, t_s1_a, t_s1_b, 1e-9f); - x_tc = codec_conv1d_causal(ctx_eval, x_tc, t_c1_w, t_c1_b, 1, CODEC_Q3T_RES_DILATIONS[ri]); + x_tc = codec_memory_conv1d_causal(ctx_eval, mem, x_tc, t_c1_w, t_c1_b, 1, CODEC_Q3T_RES_DILATIONS[ri]); x_tc = codec_op_snake_beta(ctx_eval, x_tc, t_s2_a, t_s2_b, 1e-9f); - x_tc = codec_conv1d_causal(ctx_eval, x_tc, t_c2_w, t_c2_b, 1, 1); + x_tc = codec_memory_conv1d_causal(ctx_eval, mem, x_tc, t_c2_w, t_c2_b, 1, 1); x_tc = ggml_add(ctx_eval, res, x_tc); } cur_dim = out_dim; @@ -546,7 +575,7 @@ static bool codec_q3t_build_decode(ggml_context * ctx_eval, void * user_data, gg } x_tc = codec_op_snake_beta(ctx_eval, x_tc, t_fs_a, t_fs_b, 1e-9f); - ggml_tensor * t_out = codec_conv1d_causal(ctx_eval, x_tc, t_out_final_w, t_out_final_b, 1, 1); + ggml_tensor * t_out = codec_memory_conv1d_causal(ctx_eval, mem, x_tc, t_out_final_w, t_out_final_b, 1, 1); if (t_out == nullptr) { return false; } @@ -597,6 +626,7 @@ static bool codec_q3t_init_decode_build(codec_context * ctx, int32_t t, int32_t build->upsampling_ratios[i] = std::max(1, q3.upsampling_ratios[i]); } build->model = ctx->model; + build->mem = nullptr; return true; } @@ -632,17 +662,22 @@ enum codec_status codec_qwen3_tts_tokenizer_decode( const int32_t t = tokens->n_frames; const int32_t q = use_n_q; - codec_graph_eval_guard eval_guard(ctx); + codec_memory * mem = codec_memory_active(ctx, CODEC_MEMORY_DECODER); + // with memory, keep the graph: the next chunk of the same length reuses it + codec_graph_eval_guard eval_guard(ctx, /*persist=*/mem != nullptr); q3t_decode_build build = {}; std::string err; if (!codec_q3t_init_decode_build(ctx, t, q, &build, &err)) { codec_context_set_error(ctx, err); return CODEC_STATUS_INTERNAL_ERROR; } + build.mem = mem; + codec_graph_cache_key key = { CODEC_GRAPH_Q3T_DECODE, /*n_frames=*/t, /*n_q=*/q, /*hop=*/build.codebook_dim, /*n_in=*/0, /*latent_dim=*/build.latent_dim }; + key.mem = mem != nullptr ? 1 : 0; codec_graph_cache_entry * entry = nullptr; if (!codec_graph_cache_get_or_build( ctx, - { CODEC_GRAPH_Q3T_DECODE, /*n_frames=*/t, /*n_q=*/q, /*hop=*/build.codebook_dim, /*n_in=*/0, /*latent_dim=*/build.latent_dim }, + key, codec_q3t_build_decode, &build, sizeof(build), @@ -686,11 +721,17 @@ enum codec_status codec_qwen3_tts_tokenizer_decode( } } + if (!codec_memory_set_inputs(ctx, entry, mem, &err)) { + codec_context_set_error(ctx, err); + return CODEC_STATUS_INTERNAL_ERROR; + } + const int32_t n_threads = ctx->n_threads; if (!codec_graph_compute(ctx, entry, n_threads, &err)) { codec_context_set_error(ctx, err); return CODEC_STATUS_INTERNAL_ERROR; } + codec_memory_commit(mem, t); const int32_t n_samples = (int32_t) t_out->ne[0]; std::vector out(n_samples, 0.0f); @@ -715,6 +756,18 @@ enum codec_status codec_qwen3_tts_tokenizer_decode( return CODEC_STATUS_SUCCESS; } +// Codec memory plan: build the decoder graph once (one frame) to record its +// cache slots. The encoder is the Mimi encoder (codec_mimi_memory_plan_encoder). +static bool codec_q3t_memory_plan_decoder(codec_context * ctx, codec_memory * mem, std::string * err) { + codec_qwen3_tts_tokenizer_impl & impl = *static_cast(ctx->model->impl); + q3t_decode_build build = {}; + if (!codec_q3t_init_decode_build(ctx, 1, std::max(1, impl.q3.n_q), &build, err)) { + return false; + } + build.mem = mem; + return codec_memory_plan_build(ctx, mem, codec_q3t_build_decode, &build, err); +} + enum codec_status codec_qwen3_tts_tokenizer_encode( struct codec_context * ctx, const std::vector & pcm, @@ -888,6 +941,14 @@ static bool codec_qwen3_tts_tokenizer_speaker_validate( return tag_ok("spk_id", true) && tag_ok("language_id", false); } +static bool codec_qwen3_tts_tokenizer_memory_plan(codec_context * ctx, int32_t side, codec_memory * mem, std::string * err) { + if (side == CODEC_MEMORY_DECODER) { + return codec_q3t_memory_plan_decoder(ctx, mem, err); + } + codec_qwen3_tts_tokenizer_impl & impl = *static_cast(ctx->model->impl); + return codec_mimi_memory_plan_encoder(ctx, &impl.mimi, mem, err); +} + const struct codec_model_vtable * codec_qwen3_tts_tokenizer_vtable() { static const codec_model_vtable vtable = { CODEC_ARCH_QWEN3_TTS_TOKENIZER, @@ -901,6 +962,7 @@ const struct codec_model_vtable * codec_qwen3_tts_tokenizer_vtable() { nullptr, codec_qwen3_tts_tokenizer_speaker_validate, codec_qwen3_tts_tokenizer_speaker_from_audio, + codec_qwen3_tts_tokenizer_memory_plan, }; return &vtable; } diff --git a/src/ops/conv1d.cpp b/src/ops/conv1d.cpp index f6e6ad5..254781a 100644 --- a/src/ops/conv1d.cpp +++ b/src/ops/conv1d.cpp @@ -391,3 +391,55 @@ ggml_tensor * codec_conv1d_depthwise_causal( } return ggml_cont(ctx, y); } + +int32_t codec_conv1d_causal_pad_left(const ggml_tensor * w, int64_t c_in, int32_t stride, int32_t dilation, bool depthwise) { + if (w == nullptr || stride <= 0 || dilation <= 0) return -1; + const int32_t kernel = depthwise ? (int32_t) w->ne[0] : (int32_t) codec_conv1d_kernel_size(w, c_in); + if (kernel < stride) return -1; + return (kernel - 1) * dilation + 1 - stride; +} + +ggml_tensor * codec_conv1d_causal_ctx( + ggml_context * ctx, + ggml_tensor * x, + ggml_tensor * prev, + ggml_tensor * w, + ggml_tensor * b, + int32_t stride, + int32_t dilation, + bool depthwise, + ggml_tensor ** x_cat, + bool replicate) { + + if (ctx == nullptr || x == nullptr || w == nullptr || stride <= 0 || dilation <= 0) { + return nullptr; + } + const int32_t pad_left = codec_conv1d_causal_pad_left(w, x->ne[1], stride, dilation, depthwise); + if (pad_left < 0 || (pad_left > 0 && (prev == nullptr || prev->ne[0] != pad_left || prev->ne[1] != x->ne[1]))) { + return nullptr; + } + b = codec_graph_cast_f32(ctx, b); + + ggml_tensor * xc = pad_left > 0 ? ggml_concat(ctx, prev, x, 0) : x; + if (x_cat != nullptr) { + *x_cat = xc; + } + const int32_t t_in = (int32_t) x->ne[0]; + const int32_t extra_pad = t_in > 0 ? (((t_in + stride - 1) / stride) * stride - t_in) : 0; + ggml_tensor * x_pad = extra_pad <= 0 ? xc + : replicate ? codec_op_pad_1d_replicate(ctx, xc, 0, extra_pad) + : codec_op_pad_1d(ctx, xc, 0, extra_pad); + if (x_pad == nullptr) { + return nullptr; + } + ggml_tensor * y = depthwise ? codec_conv1d_depthwise_impl(ctx, x_pad, w, stride, 0, dilation) + : codec_conv1d_impl(ctx, x_pad, w, stride, 0, dilation); + if (y == nullptr) { + return nullptr; + } + if (b != nullptr) { + ggml_tensor * b2 = ggml_reshape_2d(ctx, b, 1, y->ne[1]); + y = ggml_add(ctx, y, b2); + } + return ggml_cont(ctx, y); +} diff --git a/src/ops/conv1d.h b/src/ops/conv1d.h index f5ad781..9716a8b 100644 --- a/src/ops/conv1d.h +++ b/src/ops/conv1d.h @@ -50,4 +50,23 @@ ggml_tensor * codec_conv1d_depthwise_causal( int32_t stride, int32_t dilation); +// Left padding of a causal conv: (kernel - 1) * dilation + 1 - stride. +int32_t codec_conv1d_causal_pad_left(const ggml_tensor * w, int64_t c_in, int32_t stride, int32_t dilation, bool depthwise); + +// Causal conv whose left padding is `prev` ([pad_left, C_in], the cached tail +// of the previous input) instead of zeros. The right padding to a stride +// multiple is the batch op's (zeros, or the last value when `replicate`). +// *x_cat = concat(prev, x), for the next tail. +ggml_tensor * codec_conv1d_causal_ctx( + ggml_context * ctx, + ggml_tensor * x, + ggml_tensor * prev, + ggml_tensor * w, + ggml_tensor * b, + int32_t stride, + int32_t dilation, + bool depthwise, + ggml_tensor ** x_cat, + bool replicate = false); + #endif diff --git a/src/ops/convtr1d.cpp b/src/ops/convtr1d.cpp index 3087402..d73106d 100644 --- a/src/ops/convtr1d.cpp +++ b/src/ops/convtr1d.cpp @@ -150,3 +150,46 @@ ggml_tensor * codec_convtr1d_causal( const int32_t crop_right = std::max(0, kernel - stride); return codec_op_crop_1d(ctx, y, 0, crop_right); } + +int32_t codec_convtr1d_causal_overlap(const ggml_tensor * w, int64_t c_in, int32_t stride) { + if (w == nullptr || stride <= 0) return -1; + return std::max(0, (int32_t) codec_convtr1d_kernel_size(w, c_in) - stride); +} + +ggml_tensor * codec_convtr1d_causal_ctx( + ggml_context * ctx, + ggml_tensor * x, + ggml_tensor * prev, + ggml_tensor * w, + ggml_tensor * b, + int32_t stride, + ggml_tensor ** next) { + + if (ctx == nullptr || x == nullptr || w == nullptr || stride <= 0) { + return nullptr; + } + const int32_t o = codec_convtr1d_causal_overlap(w, x->ne[1], stride); + ggml_tensor * y = codec_convtr1d(ctx, x, w, nullptr, stride, 0, 1); // [(T-1)*s + K, C_out] + if (y == nullptr) { + return nullptr; + } + const int64_t n_out = x->ne[0] * stride; + if (y->ne[0] != n_out + o) { + return nullptr; + } + if (o > 0) { + if (prev == nullptr || prev->ne[0] != o || prev->ne[1] != y->ne[1]) { + return nullptr; + } + y = ggml_add(ctx, y, ggml_pad(ctx, prev, (int) (y->ne[0] - o), 0, 0, 0)); + if (next != nullptr) { + *next = ggml_view_2d(ctx, y, o, y->ne[1], y->nb[1], (size_t) n_out * y->nb[0]); + } + } + ggml_tensor * out = o > 0 ? ggml_view_2d(ctx, y, n_out, y->ne[1], y->nb[1], 0) : y; + b = codec_graph_cast_f32(ctx, b); + if (b != nullptr) { + out = ggml_add(ctx, out, ggml_reshape_2d(ctx, b, 1, y->ne[1])); + } + return ggml_cont(ctx, out); +} diff --git a/src/ops/convtr1d.h b/src/ops/convtr1d.h index f9e5386..65e3459 100644 --- a/src/ops/convtr1d.h +++ b/src/ops/convtr1d.h @@ -24,4 +24,20 @@ ggml_tensor * codec_convtr1d_causal( int32_t stride, int32_t dilation); +// Overlap a causal ConvTranspose1d carries to the next call: kernel - stride. +int32_t codec_convtr1d_causal_overlap(const ggml_tensor * w, int64_t c_in, int32_t stride); + +// Causal ConvTranspose1d that adds `prev` ([overlap, C_out], the part of the +// previous call's last frames that falls on this call's first samples, before +// the bias) and returns T * stride samples. *next = the overlap this call +// leaves for the next one (before the bias). +ggml_tensor * codec_convtr1d_causal_ctx( + ggml_context * ctx, + ggml_tensor * x, + ggml_tensor * prev, + ggml_tensor * w, + ggml_tensor * b, + int32_t stride, + ggml_tensor ** next); + #endif diff --git a/src/runtime/graph.cpp b/src/runtime/graph.cpp index fa45208..cfa612a 100644 --- a/src/runtime/graph.cpp +++ b/src/runtime/graph.cpp @@ -13,7 +13,8 @@ static bool codec_graph_key_equal(const codec_graph_cache_key & a, const codec_g a.n_q == b.n_q && a.hop == b.hop && a.n_in == b.n_in && - a.latent_dim == b.latent_dim; + a.latent_dim == b.latent_dim && + a.mem == b.mem; } struct codec_graph_count_state { @@ -453,3 +454,30 @@ ggml_tensor * codec_graph_get_tensor(codec_context * ctx, codec_graph_cache_entr } return ggml_get_tensor(ctx->eval_ctx, name); } + +bool codec_graph_build_scratch(codec_context * ctx, codec_graph_build_fn build_fn, void * user_data, std::string * error) { + if (ctx == nullptr || build_fn == nullptr) { + if (error != nullptr) *error = "invalid scratch build arguments"; + return false; + } + codec_graph_release(ctx); + if (!codec_graph_ensure_eval_arena(ctx, kCodecGraphDefaultArenaBytes, error)) { + return false; + } + ggml_init_params p = { ctx->eval_arena_size, ctx->eval_arena_buf, true }; + ctx->eval_ctx = ggml_init(p); + if (ctx->eval_ctx == nullptr) { + if (error != nullptr) *error = "failed to create scratch eval context"; + return false; + } + ggml_tensor * out = nullptr; + t_building_ctx = ctx; + const bool ok = build_fn(ctx->eval_ctx, user_data, &out); + t_building_ctx = nullptr; + codec_graph_release(ctx); + if (!ok || out == nullptr) { + if (error != nullptr) *error = "failed to build graph"; + return false; + } + return true; +} diff --git a/src/runtime/graph.h b/src/runtime/graph.h index 8c2f001..c562a8f 100644 --- a/src/runtime/graph.h +++ b/src/runtime/graph.h @@ -87,6 +87,11 @@ bool codec_graph_prepare_io( void codec_graph_release(codec_context * ctx); +// Runs `build_fn` in a throw-away eval context (nothing is allocated or +// computed): lets a builder report shapes it records while building +// (codec memory slot planning). +bool codec_graph_build_scratch(codec_context * ctx, codec_graph_build_fn build_fn, void * user_data, std::string * error); + // A constant input of the graph being built (call from a build_fn only): // creates `name` in `ctx_eval` with a copy of `data`, written automatically by // codec_graph_prepare_io. Lets reusable blocks carry their own lookup tables. diff --git a/src/runtime/memory.cpp b/src/runtime/memory.cpp new file mode 100644 index 0000000..64c9247 --- /dev/null +++ b/src/runtime/memory.cpp @@ -0,0 +1,596 @@ +#include "memory.h" + +#include "graph.h" +#include "tensor_utils.h" +#include "../ops/conv1d.h" +#include "../ops/convtr1d.h" + +#include +#include +#include +#include +#include + +// --------------------------------------------------------------------------- +// SHA-256 (FIPS 180-4), for the model fingerprint in the state blob. + +namespace { + +struct sha256_ctx { + uint32_t h[8] = {0x6a09e667u, 0xbb67ae85u, 0x3c6ef372u, 0xa54ff53au, 0x510e527fu, 0x9b05688cu, 0x1f83d9abu, 0x5be0cd19u}; + uint8_t buf[64] = {}; + size_t n = 0; + uint64_t len = 0; +}; + +constexpr uint32_t k_sha256[64] = { + 0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u, 0x3956c25bu, 0x59f111f1u, 0x923f82a4u, 0xab1c5ed5u, + 0xd807aa98u, 0x12835b01u, 0x243185beu, 0x550c7dc3u, 0x72be5d74u, 0x80deb1feu, 0x9bdc06a7u, 0xc19bf174u, + 0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu, 0x2de92c6fu, 0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau, + 0x983e5152u, 0xa831c66du, 0xb00327c8u, 0xbf597fc7u, 0xc6e00bf3u, 0xd5a79147u, 0x06ca6351u, 0x14292967u, + 0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu, 0x53380d13u, 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u, + 0xa2bfe8a1u, 0xa81a664bu, 0xc24b8b70u, 0xc76c51a3u, 0xd192e819u, 0xd6990624u, 0xf40e3585u, 0x106aa070u, + 0x19a4c116u, 0x1e376c08u, 0x2748774cu, 0x34b0bcb5u, 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu, 0x682e6ff3u, + 0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u, 0x90befffau, 0xa4506cebu, 0xbef9a3f7u, 0xc67178f2u, +}; + +inline uint32_t rotr(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); } + +void sha256_block(sha256_ctx & c, const uint8_t * p) { + uint32_t w[64]; + for (int i = 0; i < 16; ++i) { + w[i] = (uint32_t) p[4 * i] << 24 | (uint32_t) p[4 * i + 1] << 16 | (uint32_t) p[4 * i + 2] << 8 | p[4 * i + 3]; + } + for (int i = 16; i < 64; ++i) { + const uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); + const uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + s0 + w[i - 7] + s1; + } + uint32_t a = c.h[0], b = c.h[1], cc = c.h[2], d = c.h[3], e = c.h[4], f = c.h[5], g = c.h[6], h = c.h[7]; + for (int i = 0; i < 64; ++i) { + const uint32_t t1 = h + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + k_sha256[i] + w[i]; + const uint32_t t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & cc) ^ (b & cc)); + h = g; g = f; f = e; e = d + t1; d = cc; cc = b; b = a; a = t1 + t2; + } + c.h[0] += a; c.h[1] += b; c.h[2] += cc; c.h[3] += d; c.h[4] += e; c.h[5] += f; c.h[6] += g; c.h[7] += h; +} + +void sha256_update(sha256_ctx & c, const void * data, size_t n) { + const uint8_t * p = static_cast(data); + c.len += n; + while (n > 0) { + const size_t k = std::min(n, (size_t) 64 - c.n); + std::memcpy(c.buf + c.n, p, k); + c.n += k; p += k; n -= k; + if (c.n == 64) { sha256_block(c, c.buf); c.n = 0; } + } +} + +void sha256_final(sha256_ctx & c, uint8_t out[32]) { + const uint64_t bits = c.len * 8; + const uint8_t one = 0x80, zero = 0; + sha256_update(c, &one, 1); + while (c.n != 56) sha256_update(c, &zero, 1); + uint8_t lb[8]; + for (int i = 0; i < 8; ++i) lb[i] = (uint8_t) (bits >> (56 - 8 * i)); + sha256_update(c, lb, 8); + for (int i = 0; i < 8; ++i) { + out[4 * i] = (uint8_t) (c.h[i] >> 24); out[4 * i + 1] = (uint8_t) (c.h[i] >> 16); + out[4 * i + 2] = (uint8_t) (c.h[i] >> 8); out[4 * i + 3] = (uint8_t) c.h[i]; + } +} + +// Tensor names, types and shapes of the model's weights, plus the arch. +void codec_memory_fingerprint(const codec_model * model, uint8_t out[32]) { + sha256_ctx c; + const int32_t arch = (int32_t) model->arch; + sha256_update(c, &arch, sizeof(arch)); + if (model->weights != nullptr) { + for (ggml_tensor * t = ggml_get_first_tensor(model->weights); t != nullptr; t = ggml_get_next_tensor(model->weights, t)) { + sha256_update(c, t->name, std::strlen(t->name) + 1); + const int32_t type = (int32_t) t->type; + sha256_update(c, &type, sizeof(type)); + sha256_update(c, t->ne, sizeof(t->ne)); + } + } + sha256_final(c, out); +} + +constexpr char kStateMagic[4] = {'C', 'D', 'C', 'M'}; +constexpr uint32_t kStateFormatVersion = 1; +constexpr uint32_t kStateImplVersion = 1; + +std::string slot_name(int32_t side, size_t i) { + return std::string(side == CODEC_MEMORY_ENCODER ? "mem.enc.s" : "mem.dec.s") + std::to_string(i); +} + +} // namespace + +// --------------------------------------------------------------------------- +// Lifecycle + +bool codec_memory_create(codec_context * ctx, int32_t side, codec_memory ** out, std::string * err) { + *out = nullptr; + codec_memory * mem = new codec_memory(); + mem->ctx = ctx; + mem->side = side; + codec_model * model = ctx->model; + const bool causal = side == CODEC_MEMORY_ENCODER ? codec_model_encoder_is_causal(model) : codec_model_decoder_is_causal(model); + const bool has_side = side == CODEC_MEMORY_ENCODER ? model->has_encoder : model->has_decoder; + if (causal && has_side && model->vtable != nullptr && model->vtable->memory_plan != nullptr) { + mem->planning = true; + const bool ok = model->vtable->memory_plan(ctx, side, mem, err); + mem->planning = false; + if (!ok) { + delete mem; + return false; + } + } + if (!mem->specs.empty()) { + ggml_init_params p = { ggml_tensor_overhead() * (mem->specs.size() + 1), nullptr, true }; + mem->tctx = ggml_init(p); + if (mem->tctx == nullptr) { + if (err != nullptr) *err = "failed to create the memory context"; + delete mem; + return false; + } + for (size_t i = 0; i < mem->specs.size(); ++i) { + const codec_memory_slot_spec & s = mem->specs[i]; + ggml_tensor * t = ggml_new_tensor_4d(mem->tctx, s.type, s.ne[0], s.ne[1], s.ne[2], s.ne[3]); + ggml_set_name(t, slot_name(side, i).c_str()); + mem->slots.push_back(t); + } + mem->buf = ggml_backend_alloc_ctx_tensors(mem->tctx, ctx->backend); + if (mem->buf == nullptr) { + if (err != nullptr) *err = "failed to allocate the memory buffer"; + codec_memory_free(mem); + return false; + } + } + codec_memory_clear(mem); + *out = mem; + return true; +} + +void codec_memory_free(codec_memory * mem) { + if (mem == nullptr) return; + if (mem->buf != nullptr) ggml_backend_buffer_free(mem->buf); + if (mem->tctx != nullptr) ggml_free(mem->tctx); + delete mem; +} + +codec_memory * codec_memory_active(codec_context * ctx, int32_t side) { + if (ctx == nullptr || ctx->memory_bypass) return nullptr; + codec_memory * mem = side == CODEC_MEMORY_ENCODER ? ctx->enc_mem : ctx->dec_mem; + return mem != nullptr && !mem->slots.empty() ? mem : nullptr; +} + +bool codec_memory_plan_build(codec_context * ctx, codec_memory * mem, codec_graph_build_fn build_fn, void * user_data, + std::string * err) { + mem->specs.clear(); + mem->clocks.clear(); + mem->planning = true; + const bool ok = codec_graph_build_scratch(ctx, build_fn, user_data, err); + mem->next_slot = mem->next_clock = 0; + return ok; +} + +// --------------------------------------------------------------------------- +// Build-time helpers + +void codec_memory_begin_build(codec_memory * mem) { + if (mem == nullptr) return; + mem->next_slot = 0; + mem->next_clock = 0; + if (mem->planning) { + mem->specs.clear(); + mem->clocks.clear(); + } +} + +ggml_tensor * codec_memory_slot(ggml_context * ctx_eval, codec_memory * mem, uint32_t kind, ggml_type type, + int64_t ne0, int64_t ne1, int64_t ne2) { + if (mem == nullptr || ctx_eval == nullptr) return nullptr; + if (mem->planning) { + codec_memory_slot_spec s; + s.kind = kind; + s.type = type; + s.ne[0] = ne0; s.ne[1] = ne1; s.ne[2] = ne2; + mem->specs.push_back(s); + mem->next_slot++; + return ggml_new_tensor_3d(ctx_eval, type, ne0, ne1, ne2); + } + if (mem->next_slot >= mem->slots.size()) return nullptr; + ggml_tensor * t = mem->slots[mem->next_slot]; + const codec_memory_slot_spec & s = mem->specs[mem->next_slot]; + mem->next_slot++; + if (s.kind != kind || t->type != type || t->ne[0] != ne0 || t->ne[1] != ne1 || t->ne[2] != ne2) { + return nullptr; // graph structure differs from the plan + } + return t; +} + +void codec_memory_store(ggml_context * ctx_eval, codec_memory * mem, ggml_tensor * src, ggml_tensor * slot) { + if (mem == nullptr || mem->planning || src == nullptr || slot == nullptr) return; + ggml_tensor * c = ggml_cpy(ctx_eval, src, slot); + ggml_set_output(c); +} + +bool codec_memory_clock_inputs(ggml_context * ctx_eval, codec_memory * mem, int32_t cache_len, int32_t window, int64_t t, + ggml_tensor ** pos, ggml_tensor ** mask) { + if (mem == nullptr || ctx_eval == nullptr || t <= 0 || cache_len < 0) return false; + const size_t id = mem->next_clock++; + if (mem->planning) { + codec_memory_clock c; + c.cache_len = cache_len; + c.window = window; + mem->clocks.push_back(c); + } else if (id >= mem->clocks.size() || mem->clocks[id].cache_len != cache_len || mem->clocks[id].window != window) { + return false; + } + const std::string base = "mem.clk" + std::to_string(id); + *pos = ggml_new_tensor_1d(ctx_eval, GGML_TYPE_I32, t); + ggml_set_name(*pos, (base + ".pos").c_str()); + *mask = ggml_new_tensor_2d(ctx_eval, GGML_TYPE_F32, cache_len + t, t); + ggml_set_name(*mask, (base + ".mask").c_str()); + return true; +} + +ggml_tensor * codec_memory_fresh_input(ggml_context * ctx_eval, codec_memory * mem) { + if (mem == nullptr) return nullptr; + ggml_tensor * t = ggml_get_tensor(ctx_eval, "mem.fresh"); + if (t == nullptr) { + t = ggml_new_tensor_1d(ctx_eval, GGML_TYPE_F32, 1); + ggml_set_name(t, "mem.fresh"); + } + return t; +} + +// --------------------------------------------------------------------------- +// Per call + +bool codec_memory_set_inputs(codec_context * ctx, codec_graph_cache_entry * entry, codec_memory * mem, std::string * err) { + if (mem == nullptr) return true; + for (size_t id = 0; id < mem->clocks.size(); ++id) { + codec_memory_clock & c = mem->clocks[id]; + const std::string base = "mem.clk" + std::to_string(id); + ggml_tensor * tp = codec_graph_get_tensor(ctx, entry, (base + ".pos").c_str()); + ggml_tensor * tm = codec_graph_get_tensor(ctx, entry, (base + ".mask").c_str()); + if (tp == nullptr || tm == nullptr) { + c.t_call = 0; + continue; + } + const int64_t t = tp->ne[0]; + const int64_t C = c.cache_len; + c.t_call = (int32_t) t; + std::vector pos((size_t) t); + for (int64_t i = 0; i < t; ++i) pos[(size_t) i] = (int32_t) (c.n + i); + std::vector m((size_t) ((C + t) * t)); + const int64_t W = c.window; + for (int64_t i = 0; i < t; ++i) { + const int64_t p = c.n + i; + for (int64_t j = 0; j < C + t; ++j) { + const int64_t kp = j < C ? c.n - C + j : c.n + (j - C); + const bool ok = kp >= 0 && kp <= p && (W <= 0 || kp >= p - W + 1); + m[(size_t) (i * (C + t) + j)] = ok ? 0.0f : -INFINITY; + } + } + if (!codec_runtime_write_tensor(tp, pos.data(), pos.size() * sizeof(int32_t), err) || + !codec_runtime_write_tensor(tm, m.data(), m.size() * sizeof(float), err)) { + return false; + } + } + if (ggml_tensor * tf = codec_graph_get_tensor(ctx, entry, "mem.fresh")) { + const float f = mem->fresh ? 1.0f : 0.0f; + if (!codec_runtime_write_tensor(tf, &f, sizeof(f), err)) return false; + } + return true; +} + +void codec_memory_commit(codec_memory * mem, int64_t n_frames) { + if (mem == nullptr) return; + for (codec_memory_clock & c : mem->clocks) { + c.n += c.t_call; + c.t_call = 0; + } + mem->fresh = false; + mem->position += n_frames; +} + +// --------------------------------------------------------------------------- +// Stateful ops + +static ggml_tensor * codec_memory_conv_common(ggml_context * ctx, codec_memory * mem, ggml_tensor * x, ggml_tensor * w, + ggml_tensor * b, int32_t stride, int32_t dilation, bool depthwise, + bool replicate) { + const int32_t pad_left = codec_conv1d_causal_pad_left(w, x->ne[1], stride, dilation, depthwise); + if (pad_left < 0) return nullptr; + ggml_tensor * prev = nullptr; + ggml_tensor * slot = nullptr; + if (pad_left > 0) { + slot = codec_memory_slot(ctx, mem, CODEC_MEMORY_SLOT_CONV_TAIL, GGML_TYPE_F32, pad_left, x->ne[1]); + if (slot == nullptr) return nullptr; + prev = slot; + if (replicate) { + // First call after a clear: the batch op's replicate padding of the first value. + ggml_tensor * f = codec_memory_fresh_input(ctx, mem); + ggml_tensor * first = ggml_view_2d(ctx, x, 1, x->ne[1], x->nb[1], 0); + ggml_tensor * rep = ggml_repeat(ctx, first, slot); + prev = ggml_add(ctx, ggml_mul(ctx, slot, ggml_scale_bias(ctx, f, -1.0f, 1.0f)), ggml_mul(ctx, rep, f)); + } + } + ggml_tensor * x_cat = nullptr; + ggml_tensor * y = codec_conv1d_causal_ctx(ctx, x, prev, w, b, stride, dilation, depthwise, &x_cat, replicate); + if (y == nullptr) return nullptr; + if (pad_left > 0) { + ggml_tensor * tail = ggml_view_2d(ctx, x_cat, pad_left, x_cat->ne[1], x_cat->nb[1], + (size_t) (x_cat->ne[0] - pad_left) * x_cat->nb[0]); + codec_memory_store(ctx, mem, tail, slot); + } + return y; +} + +ggml_tensor * codec_memory_conv1d_causal(ggml_context * ctx, codec_memory * mem, ggml_tensor * x, ggml_tensor * w, + ggml_tensor * b, int32_t stride, int32_t dilation, bool replicate) { + if (mem == nullptr) { + return replicate ? codec_conv1d_causal_replicate(ctx, x, w, b, stride, dilation) + : codec_conv1d_causal(ctx, x, w, b, stride, dilation); + } + return codec_memory_conv_common(ctx, mem, x, w, b, stride, dilation, false, replicate); +} + +ggml_tensor * codec_memory_conv1d_depthwise_causal(ggml_context * ctx, codec_memory * mem, ggml_tensor * x, ggml_tensor * w, + ggml_tensor * b, int32_t stride, int32_t dilation) { + if (mem == nullptr) { + return codec_conv1d_depthwise_causal(ctx, x, w, b, stride, dilation); + } + return codec_memory_conv_common(ctx, mem, x, w, b, stride, dilation, true, false); +} + +ggml_tensor * codec_memory_convtr1d_causal(ggml_context * ctx, codec_memory * mem, ggml_tensor * x, ggml_tensor * w, + ggml_tensor * b, int32_t stride) { + if (mem == nullptr) { + return codec_convtr1d_causal(ctx, x, w, b, stride, 1); + } + const int32_t o = codec_convtr1d_causal_overlap(w, x->ne[1], stride); + if (o < 0) return nullptr; + ggml_tensor * slot = nullptr; + if (o > 0) { + slot = codec_memory_slot(ctx, mem, CODEC_MEMORY_SLOT_CONVTR_OVERLAP, GGML_TYPE_F32, o, w->ne[1]); + if (slot == nullptr) return nullptr; + } + ggml_tensor * next = nullptr; + ggml_tensor * y = codec_convtr1d_causal_ctx(ctx, x, slot, w, b, stride, &next); + if (y == nullptr) return nullptr; + if (o > 0) { + codec_memory_store(ctx, mem, next, slot); + } + return y; +} + +ggml_tensor * codec_memory_attn(ggml_context * ctx, codec_memory * mem, ggml_tensor * q_dht, ggml_tensor * k_dht, + ggml_tensor * v_dht, const codec_memory_attn_params & p) { + if (ctx == nullptr || mem == nullptr || q_dht == nullptr || k_dht == nullptr || v_dht == nullptr || p.window <= 0 || + p.head_dim <= 0 || p.n_heads <= 0) { + return nullptr; + } + const int32_t n_kv = p.n_kv_heads > 0 ? p.n_kv_heads : p.n_heads; + const int64_t t = q_dht->ne[2]; + const int32_t C = p.window - 1; + + ggml_tensor * pos = nullptr; + ggml_tensor * mask = nullptr; + if (!codec_memory_clock_inputs(ctx, mem, C, p.window, t, &pos, &mask)) return nullptr; + + ggml_tensor * q_r = ggml_rope_ext(ctx, q_dht, pos, nullptr, p.head_dim, p.rope_mode, 0, p.rope_theta, + p.rope_freq_scale, 0.0f, 1.0f, 0.0f, 0.0f); + ggml_tensor * k_r = ggml_rope_ext(ctx, k_dht, pos, nullptr, p.head_dim, p.rope_mode, 0, p.rope_theta, + p.rope_freq_scale, 0.0f, 1.0f, 0.0f, 0.0f); + + ggml_tensor * k_all = k_r; + ggml_tensor * v_all = v_dht; + if (C > 0) { + ggml_tensor * k_slot = codec_memory_slot(ctx, mem, CODEC_MEMORY_SLOT_K, GGML_TYPE_F32, p.head_dim, n_kv, C); + ggml_tensor * v_slot = codec_memory_slot(ctx, mem, CODEC_MEMORY_SLOT_V, GGML_TYPE_F32, p.head_dim, n_kv, C); + if (k_slot == nullptr || v_slot == nullptr) return nullptr; + k_all = ggml_concat(ctx, k_slot, ggml_cont(ctx, k_r), 2); // [d, h_kv, C + t] + v_all = ggml_concat(ctx, v_slot, ggml_cont(ctx, v_dht), 2); + codec_memory_store(ctx, mem, ggml_view_3d(ctx, k_all, p.head_dim, n_kv, C, k_all->nb[1], k_all->nb[2], (size_t) t * k_all->nb[2]), k_slot); + codec_memory_store(ctx, mem, ggml_view_3d(ctx, v_all, p.head_dim, n_kv, C, v_all->nb[1], v_all->nb[2], (size_t) t * v_all->nb[2]), v_slot); + } + const int64_t n_k = C + t; + + ggml_tensor * q_dth = ggml_permute(ctx, q_r, 0, 2, 1, 3); // [d, t, h] + ggml_tensor * k_dth = ggml_cont(ctx, ggml_permute(ctx, k_all, 0, 2, 1, 3)); // [d, n_k, h_kv] + ggml_tensor * v_dth = ggml_permute(ctx, v_all, 0, 2, 1, 3); // [d, n_k, h_kv] + if (n_kv != p.n_heads) { + k_dth = ggml_repeat(ctx, k_dth, ggml_new_tensor_3d(ctx, k_dth->type, p.head_dim, n_k, p.n_heads)); + v_dth = ggml_repeat(ctx, ggml_cont(ctx, v_dth), ggml_new_tensor_3d(ctx, v_dth->type, p.head_dim, n_k, p.n_heads)); + } + const float scale = p.scale > 0.0f ? p.scale : 1.0f / std::sqrt((float) p.head_dim); + ggml_tensor * scores = codec_mul_mat(ctx, k_dth, q_dth); // [n_k, t, h] + const bool padded = p.n_valid > 0 && p.n_valid < t; + if (padded) { + std::vector pad((size_t) n_k, 0.0f); + for (int64_t j = C + p.n_valid; j < n_k; ++j) pad[(size_t) j] = -INFINITY; + const std::string name = "mem.padmask." + std::to_string(n_k) + "." + std::to_string(p.n_valid); + mask = ggml_add(ctx, mask, codec_graph_const_f32(ctx, name.c_str(), pad, n_k, 1)); + } + ggml_tensor * probs = ggml_soft_max_ext(ctx, scores, mask, scale, 0.0f); + ggml_tensor * v_tdh = ggml_cont(ctx, ggml_permute(ctx, v_dth, 1, 0, 2, 3)); // [n_k, d, h] + ggml_tensor * out = codec_mul_mat(ctx, v_tdh, probs); // [d, t, h] + out = ggml_cont(ctx, ggml_permute(ctx, out, 0, 2, 1, 3)); // [d, h, t] + out = ggml_reshape_2d(ctx, out, (int64_t) p.head_dim * p.n_heads, t); + if (padded) { + std::vector rows((size_t) t, 0.0f); + for (int64_t i = 0; i < p.n_valid; ++i) rows[(size_t) i] = 1.0f; + const std::string name = "mem.padrows." + std::to_string(t) + "." + std::to_string(p.n_valid); + out = ggml_mul(ctx, out, codec_graph_const_f32(ctx, name.c_str(), rows, 1, t)); + } + return out; +} + +// --------------------------------------------------------------------------- +// Public API + +bool codec_model_encoder_is_causal(const struct codec_model * model) { + return model != nullptr && model->has_encoder && model->enc_look_ahead == 0; +} + +bool codec_model_decoder_is_causal(const struct codec_model * model) { + return model != nullptr && model->has_decoder && model->dec_look_ahead == 0; +} + +codec_memory_t codec_get_encoder_memory(const struct codec_context * ctx) { + return ctx != nullptr ? ctx->enc_mem : nullptr; +} + +codec_memory_t codec_get_decoder_memory(const struct codec_context * ctx) { + return ctx != nullptr ? ctx->dec_mem : nullptr; +} + +void codec_memory_clear(codec_memory_t mem) { + if (mem == nullptr) return; + if (mem->buf != nullptr) ggml_backend_buffer_clear(mem->buf, 0); + for (codec_memory_clock & c : mem->clocks) { + c.n = 0; + c.t_call = 0; + } + mem->fresh = true; + mem->position = 0; +} + +// Blob (little-endian): header, then one section per slot. +// char[4] "CDCM" | u32 format_version | u32 arch | u32 side | u8[32] fingerprint +// u32 impl_version | i64 position | u8 fresh | u8[7] pad | u32 n_clocks | i64 clock_n[n_clocks] +// u32 n_sections | per section: u32 kind, u32 ggml_type, i64 ne[4], u64 nbytes, data (8-byte aligned) +namespace { + +struct blob_writer { + uint8_t * dst; + size_t cap; + size_t n = 0; + void put(const void * p, size_t k) { + if (dst != nullptr && n + k <= cap) std::memcpy(dst + n, p, k); + n += k; + } + template void put(T v) { put(&v, sizeof(v)); } + void align8() { static const uint8_t z[8] = {}; put(z, (8 - n % 8) % 8); } +}; + +struct blob_reader { + const uint8_t * src; + size_t cap; + size_t n = 0; + bool ok = true; + void get(void * p, size_t k) { + if (!ok || n + k > cap) { ok = false; return; } + std::memcpy(p, src + n, k); + n += k; + } + template T get() { T v{}; get(&v, sizeof(v)); return v; } + void align8() { const size_t k = (8 - n % 8) % 8; if (n + k > cap) ok = false; else n += k; } +}; + +size_t codec_memory_serialize(codec_memory * mem, uint8_t * dst, size_t cap) { + blob_writer w{dst, cap}; + w.put(kStateMagic, 4); + w.put(kStateFormatVersion); + w.put((uint32_t) mem->ctx->model->arch); + w.put((uint32_t) mem->side); + uint8_t fp[32]; + codec_memory_fingerprint(mem->ctx->model, fp); + w.put(fp, 32); + w.put(kStateImplVersion); + w.put(mem->position); + w.put(mem->fresh ? 1 : 0); + static const uint8_t pad[7] = {}; + w.put(pad, 7); + w.put((uint32_t) mem->clocks.size()); + for (const codec_memory_clock & c : mem->clocks) w.put(c.n); + w.put((uint32_t) mem->slots.size()); + std::vector tmp; + for (size_t i = 0; i < mem->slots.size(); ++i) { + ggml_tensor * t = mem->slots[i]; + w.put(mem->specs[i].kind); + w.put((uint32_t) t->type); + for (int d = 0; d < 4; ++d) w.put(t->ne[d]); + const size_t nb = ggml_nbytes(t); + w.put(nb); + w.align8(); + if (dst != nullptr && w.n + nb <= cap) { + ggml_backend_tensor_get(t, dst + w.n, 0, nb); + } + w.n += nb; + } + return w.n; +} + +} // namespace + +size_t codec_memory_state_get_size(codec_memory_t mem) { + if (mem == nullptr || mem->slots.empty()) return 0; + return codec_memory_serialize(mem, nullptr, 0); +} + +size_t codec_memory_state_get_data(codec_memory_t mem, uint8_t * dst, size_t size) { + if (mem == nullptr || mem->slots.empty()) return 0; + const size_t need = codec_memory_serialize(mem, nullptr, 0); + if (dst == nullptr || size < need) return 0; + return codec_memory_serialize(mem, dst, size); +} + +size_t codec_memory_state_set_data(codec_memory_t mem, const uint8_t * src, size_t size) { + if (mem == nullptr) return 0; + if (mem->slots.empty()) return 0; // nothing to restore (size 0 blob) + if (src == nullptr) return 0; + blob_reader r{src, size}; + char magic[4]; + r.get(magic, 4); + if (!r.ok || std::memcmp(magic, kStateMagic, 4) != 0) return 0; + if (r.get() != kStateFormatVersion) return 0; + if (r.get() != (uint32_t) mem->ctx->model->arch) return 0; + if (r.get() != (uint32_t) mem->side) return 0; + uint8_t fp[32], fp_model[32]; + r.get(fp, 32); + codec_memory_fingerprint(mem->ctx->model, fp_model); + if (!r.ok || std::memcmp(fp, fp_model, 32) != 0) return 0; + if (r.get() != kStateImplVersion) return 0; + const int64_t position = r.get(); + const bool fresh = r.get() != 0; + uint8_t pad[7]; + r.get(pad, 7); + const uint32_t n_clocks = r.get(); + if (!r.ok || n_clocks != mem->clocks.size()) return 0; + std::vector clock_n(n_clocks); + for (uint32_t i = 0; i < n_clocks; ++i) clock_n[i] = r.get(); + const uint32_t n_sections = r.get(); + if (!r.ok || n_sections != mem->slots.size()) return 0; + // validate every section before touching the cache + std::vector offsets(n_sections); + for (uint32_t i = 0; i < n_sections; ++i) { + ggml_tensor * t = mem->slots[i]; + const uint32_t kind = r.get(); + const uint32_t type = r.get(); + int64_t ne[4]; + for (int d = 0; d < 4; ++d) ne[d] = r.get(); + const uint64_t nb = r.get(); + r.align8(); + if (!r.ok || kind != mem->specs[i].kind || type != (uint32_t) t->type || nb != ggml_nbytes(t) || + std::memcmp(ne, t->ne, sizeof(ne)) != 0 || r.n + nb > size) { + return 0; + } + offsets[i] = r.n; + r.n += nb; + } + for (uint32_t i = 0; i < n_sections; ++i) { + ggml_backend_tensor_set(mem->slots[i], src + offsets[i], 0, ggml_nbytes(mem->slots[i])); + } + for (uint32_t i = 0; i < n_clocks; ++i) { + mem->clocks[i].n = clock_n[i]; + mem->clocks[i].t_call = 0; + } + mem->position = position; + mem->fresh = fresh; + return r.n; +} diff --git a/src/runtime/memory.h b/src/runtime/memory.h new file mode 100644 index 0000000..15fa4d0 --- /dev/null +++ b/src/runtime/memory.h @@ -0,0 +1,134 @@ +#ifndef CODEC_RUNTIME_MEMORY_H +#define CODEC_RUNTIME_MEMORY_H + +// Codec memory (docs/proposals/codec_memory.md): the context a causal encoder +// or decoder caches between calls: convolution left tails, transposed-conv +// overlap partial sums, sliding-window K/V and the attention positions. +// +// A graph builder that supports memory takes a `codec_memory *` (nullptr = +// the stateless batch graph) and, through the helpers below: +// * reads a slot (persistent tensor, zero after a clear) as the left context +// of an op and writes the context the call leaves behind back into it, in +// the same graph (ggml_cpy side roots, as llama.cpp writes its KV cache); +// * takes per-call inputs (attention positions / validity mask, the +// "fresh stream" flag) that codec_memory_set_inputs fills after +// codec_graph_prepare_io. +// Slots and clocks are numbered in build order, which does not depend on the +// chunk length, so a plan build at context creation sizes them once. + +#include "../codec_internal.h" + +#include +#include + +enum codec_memory_slot_kind : uint32_t { + CODEC_MEMORY_SLOT_CONV_TAIL = 1, + CODEC_MEMORY_SLOT_CONVTR_OVERLAP = 2, + CODEC_MEMORY_SLOT_K = 3, + CODEC_MEMORY_SLOT_V = 4, +}; + +struct codec_memory_slot_spec { + uint32_t kind = 0; + ggml_type type = GGML_TYPE_F32; + int64_t ne[4] = {1, 1, 1, 1}; +}; + +// One attention stack's position counter: tokens seen since the clear, at +// that stack's frame rate. `cache_len` past tokens are kept; a query at +// position p sees keys in [p - window + 1, p] (window <= 0: all cached). +struct codec_memory_clock { + int32_t cache_len = 0; + int32_t window = 0; + int64_t n = 0; + int32_t t_call = 0; // tokens of the call being computed +}; + +struct codec_memory { + codec_context * ctx = nullptr; + int32_t side = 0; // 0 = encoder, 1 = decoder + + std::vector specs; + std::vector slots; // in tctx, allocated in buf + std::vector clocks; + ggml_context * tctx = nullptr; + ggml_backend_buffer_t buf = nullptr; + + bool fresh = true; // nothing fed since the clear + int64_t position = 0; // codec frames fed since the clear + + // build state + bool planning = false; + size_t next_slot = 0; + size_t next_clock = 0; +}; + +enum { CODEC_MEMORY_ENCODER = 0, CODEC_MEMORY_DECODER = 1 }; + +// Context lifecycle (codec.cpp). +bool codec_memory_create(codec_context * ctx, int32_t side, codec_memory ** out, std::string * err); +void codec_memory_free(codec_memory * mem); + +// The memory a model's encode / decode should use for this call: nullptr when +// not enabled, empty (non-causal side), or bypassed (codec_decode_batch). +codec_memory * codec_memory_active(codec_context * ctx, int32_t side); + +// Runs `build_fn` in planning mode (slot / clock shapes are recorded, nothing +// is computed). Called by a model's memory_plan hook. +bool codec_memory_plan_build(codec_context * ctx, codec_memory * mem, codec_graph_build_fn build_fn, void * user_data, + std::string * err); + +// --- build-time helpers (call from a build_fn; mem may be nullptr) --------- +void codec_memory_begin_build(codec_memory * mem); +ggml_tensor * codec_memory_slot(ggml_context * ctx_eval, codec_memory * mem, uint32_t kind, ggml_type type, + int64_t ne0, int64_t ne1, int64_t ne2 = 1); +// Writes `src` (same shape as `slot`) into the slot at the end of the compute. +void codec_memory_store(ggml_context * ctx_eval, codec_memory * mem, ggml_tensor * src, ggml_tensor * slot); +// Registers an attention clock; returns its per-call inputs: +// pos I32 [t] absolute positions of the call's tokens +// mask F32 [cache_len + t, t] 0 / -inf: cached slots then the call's tokens +bool codec_memory_clock_inputs(ggml_context * ctx_eval, codec_memory * mem, int32_t cache_len, int32_t window, int64_t t, + ggml_tensor ** pos, ggml_tensor ** mask); +// F32 [1]: 1 on the first call after a clear, else 0. +ggml_tensor * codec_memory_fresh_input(ggml_context * ctx_eval, codec_memory * mem); + +// --- per call --------------------------------------------------------------- +bool codec_memory_set_inputs(codec_context * ctx, codec_graph_cache_entry * entry, codec_memory * mem, std::string * err); +// After a successful compute: advance the clocks. +void codec_memory_commit(codec_memory * mem, int64_t n_frames); + +// --- stateful ops (mem == nullptr: the batch op) ----------------------------- +// Causal conv1d whose left padding comes from the cache. `replicate`: the +// batch op pads by repeating the first value (Mimi's downsample). +ggml_tensor * codec_memory_conv1d_causal(ggml_context * ctx, codec_memory * mem, ggml_tensor * x, ggml_tensor * w, + ggml_tensor * b, int32_t stride, int32_t dilation, bool replicate = false); +ggml_tensor * codec_memory_conv1d_depthwise_causal(ggml_context * ctx, codec_memory * mem, ggml_tensor * x, ggml_tensor * w, + ggml_tensor * b, int32_t stride, int32_t dilation); +// Causal ConvTranspose1d: the overlap the previous call's last frames add to +// this call's first samples is carried (before the bias). +ggml_tensor * codec_memory_convtr1d_causal(ggml_context * ctx, codec_memory * mem, ggml_tensor * x, ggml_tensor * w, + ggml_tensor * b, int32_t stride); + +// Cached causal attention. q_dht / k_dht / v_dht are [head_dim, n_heads(_kv), t] +// *before* RoPE; RoPE (`rope_mode`, positions from the clock) is applied here. +// Returns the context [head_dim * n_heads, t]. n_kv_heads < n_heads repeats K/V (GQA). +// `window` <= 0: unbounded causal attention, which memory cannot cache (the +// caller must pass a window when mem != nullptr). +struct codec_memory_attn_params { + int32_t head_dim = 0; + int32_t n_heads = 0; + int32_t n_kv_heads = 0; + int32_t window = 0; + float rope_theta = 10000.0f; + float rope_freq_scale = 1.0f; + int32_t rope_mode = 0; + float scale = 0.0f; + // 0 < n_valid < t: the call's tokens from n_valid on are padding; as the + // batch op (codec_lm_attn_params.n_valid) keys there are masked and their + // output rows are zero. + int32_t n_valid = 0; +}; +ggml_tensor * codec_memory_attn(ggml_context * ctx, codec_memory * mem, ggml_tensor * q_dht, ggml_tensor * k_dht, + ggml_tensor * v_dht, const codec_memory_attn_params & p); + +#endif diff --git a/tests/e2e/codec_memory_smoke.py b/tests/e2e/codec_memory_smoke.py new file mode 100644 index 0000000..8783021 --- /dev/null +++ b/tests/e2e/codec_memory_smoke.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +"""Codec memory (docs/proposals/codec_memory.md) through the public C API. + +For every causal side present under models/: + * streamed (random hop-aligned chunks, down to one frame, one chunk longer + than the attention window) vs batch on a clip longer than the window; + * state get / set into a fresh context continues the stream bit-exactly; + * a blob of another model / side, or a corrupted one, is rejected and the + cache is unchanged; + * clear == a fresh context. +Plus: a non-causal side's memory is a no-op of size 0, codec_decode_batch +neither reads nor updates memory, and the look_ahead GGUF key (via a load-time +override; the published GGUFs predate the keys and load with the per-arch +defaults) decides causality. + +Tolerances. Chunked compute reorders float reductions (attention rows of +cache + chunk keys), so streamed output equals batch to rounding, not bit for +bit; these models amplify rounding to ~1e-4..1e-3 (the batch graph itself +differs that much between clip lengths). Decode: relative RMS <= 1e-3. +Encode: codes are argmaxes at near-ties, and in the deep RVQ levels rounding +flips some (batch itself flips ~1 % between clip lengths on Mimi): the first +4 levels <= 0.5 % flips, all levels <= 5 %. +Convolution-only models (NeMo) are bit-exact. + +Usage: codec_memory_smoke.py [--seconds S] [model ...] (default: 24 s, every model found) +""" + +from __future__ import annotations + +import sys + +import numpy as np + +from _common import REPO, must, read_wav_mono_f32 +import codec_cpp + +MODELS = { + "qwen3_tts_tokenizer": REPO / "models" / "qwen3_tts_tokenizer" / "qwen3_tts_tokenizer.gguf", + "mimi": REPO / "models" / "mimi" / "mimi.gguf", + "moss_audio_nano": REPO / "models" / "moss_audio_nano" / "moss_audio_nano.gguf", + "nemo_nano_codec": REPO / "models" / "nemo_nano_codec" / "nemo_nano_codec.gguf", +} +NON_CAUSAL = REPO / "models" / "dac" / "dac.gguf" +SECONDS = 24.0 # longer than every window but MOSS's (whose windows exceed any test clip) +DEC_REL_RMS = 1e-3 +ENC_FLIPS = 0.05 +ENC_FLIPS_TOP = 0.005 # first 4 RVQ levels + + +def resample(x: np.ndarray, sr_in: int, sr_out: int) -> np.ndarray: + if sr_in == sr_out: + return x + n = int(round(len(x) * sr_out / sr_in)) + return np.interp(np.linspace(0, len(x) - 1, n), np.arange(len(x)), x).astype(np.float32) + + +def clip(model: codec_cpp.Model, stereo: bool) -> np.ndarray: + x, sr = read_wav_mono_f32(REPO / "test.wav") + x = resample(x, sr, model.sample_rate) + reps = int(np.ceil(SECONDS * model.sample_rate / len(x))) + x = np.tile(x, reps)[: int(SECONDS * model.sample_rate)] + x = x[: len(x) // model.hop_size * model.hop_size] + return np.stack([x, x], 1) if stereo else x + + +def plan(n: int, seed: int = 0) -> list[int]: + rng = np.random.default_rng(seed) + sizes, out, i = [1, 1, min(100, n // 3), 3, 1], [], 0 + while i < n: + k = sizes.pop(0) if sizes else int(rng.integers(1, 12)) + k = min(k, n - i) + out.append(k) + i += k + return out + + +def pcm(res) -> np.ndarray: + return np.asarray(res[0]).reshape(-1) + + +def stream_decode(ctx: codec_cpp.Context, codes: np.ndarray, sizes: list[int]) -> np.ndarray: + out, i = [], 0 + for k in sizes: + out.append(pcm(ctx.decode(codes[i:i + k]))) + i += k + return np.concatenate(out) + + +def stream_encode(ctx: codec_cpp.Context, x: np.ndarray, hop: int, sr: int, sizes: list[int]) -> np.ndarray: + out, i = [], 0 + for k in sizes: + out.append(ctx.encode(x[i * hop:(i + k) * hop], sr)) + i += k + return np.concatenate(out) + + +def check_state(name: str, m: codec_cpp.Model, side: str, run, other_blob: bytes) -> None: + """run(ctx, lo, hi) feeds frames [lo, hi) and returns the output.""" + kw = {f"{side}_memory": True} + T = run(None, 0, 0) # total frames + half = T // 2 + a = codec_cpp.Context(m, **kw) + mem_a = getattr(a, f"{side}_memory") + run(a, 0, half) + blob = mem_a.get_state() + must(len(blob) == mem_a.state_size() > 0, f"{name} {side}: state size") + rest_a = run(a, half, T) + + b = codec_cpp.Context(m, **kw) + mem_b = getattr(b, f"{side}_memory") + must(mem_b.set_state(blob) == len(blob), f"{name} {side}: set_state rejected its own blob") + rest_b = run(b, half, T) + must(np.array_equal(rest_a, rest_b), f"{name} {side}: restored stream differs from the uninterrupted one") + + # rejected blobs leave the cache unchanged + before = mem_b.get_state() + bad = bytearray(blob) + bad[20] ^= 0xFF # fingerprint byte + must(mem_b.set_state(bytes(bad)) == 0, f"{name} {side}: corrupted blob accepted") + if other_blob: + must(mem_b.set_state(other_blob) == 0, f"{name} {side}: foreign blob accepted") + must(mem_b.set_state(blob[: len(blob) // 2]) == 0, f"{name} {side}: truncated blob accepted") + must(mem_b.get_state() == before, f"{name} {side}: a rejected blob changed the cache") + + # clear == fresh context + mem_b.clear() + again = run(b, 0, half) + fresh = run(codec_cpp.Context(m, **kw), 0, half) + must(np.array_equal(again, fresh), f"{name} {side}: clear differs from a fresh context") + print(f" {side}: state {len(blob)} B, restore / reject / clear ok") + + +BLOBS: dict[str, bytes] = {} + + +def test_model(name: str) -> None: + path = MODELS[name] + if not path.is_file(): + print(f"[skip] {name}: {path} not found") + return + m = codec_cpp.Model(path) + stereo = name == "moss_audio_nano" + print(f"{name}: encoder causal {m.encoder_is_causal}, decoder causal {m.decoder_is_causal}") + x = clip(m, stereo) + sr, hop = m.sample_rate, m.hop_size + c = codec_cpp.Context(m) + codes = c.encode(x, sr) if m.has_encoder else None + T = len(codes) + sizes = plan(T) + + if m.decoder_is_causal: + ref = pcm(c.decode(codes)) + st = stream_decode(codec_cpp.Context(m, decoder_memory=True), codes, sizes) + must(st.shape == ref.shape, f"{name} decode: length {st.shape} vs {ref.shape}") + d = st - ref + rel = float(np.sqrt(np.mean(d ** 2)) / np.sqrt(np.mean(ref ** 2))) + print(f" decode stream vs batch ({T} frames, {len(sizes)} chunks): max|d| {np.abs(d).max():.2e}, rel rms {rel:.2e}") + must(rel <= DEC_REL_RMS, f"{name} decode: rel rms {rel:.2e} > {DEC_REL_RMS}") + + def run_dec(ctx, lo, hi): + if ctx is None: + return T + return stream_decode(ctx, codes[lo:hi], plan(hi - lo, seed=lo)) + check_state(name, m, "decoder", run_dec, BLOBS.get("decoder", b"")) + BLOBS["decoder"] = codec_cpp.Context(m, decoder_memory=True).decoder_memory.get_state() + + if m.encoder_is_causal: + sc = stream_encode(codec_cpp.Context(m, encoder_memory=True), x, hop, sr, sizes) + must(sc.shape == codes.shape, f"{name} encode: shape {sc.shape} vs {codes.shape}") + flips = float((sc != codes).mean()) + top = float((sc[:, :4] != codes[:, :4]).mean()) + print(f" encode stream vs batch: {flips * 100:.2f} % codes differ (first 4 levels {top * 100:.2f} %)") + must(flips <= ENC_FLIPS and top <= ENC_FLIPS_TOP, f"{name} encode: {flips * 100:.2f} % / {top * 100:.2f} % codes differ") + + def run_enc(ctx, lo, hi): + if ctx is None: + return T + return stream_encode(ctx, x[lo * hop:], hop, sr, plan(hi - lo, seed=lo)) + # a final chunk that is not a whole hop (the end of a microphone stream): + # processed as batch processes its clip's end + n = (T - 1) * hop + hop // 3 + xu = x[:n] + ref_u = c.encode(xu, sr) + su = codec_cpp.Context(m, encoder_memory=True) + full = n // hop + cu = np.concatenate([stream_encode(su, xu, hop, sr, plan(full)), su.encode(xu[full * hop:], sr)]) + must(cu.shape == ref_u.shape, f"{name} encode (unaligned tail): shape {cu.shape} vs {ref_u.shape}") + last = float((cu[-1] != ref_u[-1]).mean()) + top_u = float((cu[:, :4] != ref_u[:, :4]).mean()) + print(f" encode with an unaligned last chunk: last frame {last * 100:.0f} % differ, first 4 levels {top_u * 100:.2f} %") + must(top_u <= ENC_FLIPS_TOP and last <= 0.25, f"{name} encode (unaligned tail) differs from batch") + + check_state(name, m, "encoder", run_enc, BLOBS.get("encoder", b"")) + BLOBS["encoder"] = codec_cpp.Context(m, encoder_memory=True).encoder_memory.get_state() + + if m.decoder_is_causal: + # codec_decode_batch neither reads nor updates the decoder memory + ctx = codec_cpp.Context(m, decoder_memory=True) + ctx.decode(codes[:7]) + before = ctx.decoder_memory.get_state() + out = ctx.decode_batch([codes[:5], codes[5:9]]) + must(ctx.decoder_memory.get_state() == before, f"{name}: codec_decode_batch changed the memory") + must(np.array_equal(np.asarray(out[0][0]).reshape(-1), pcm(c.decode(codes[:5]))), + f"{name}: codec_decode_batch on a memory context is not stateless") + print(" decode_batch bypasses memory: ok") + + +def test_non_causal() -> None: + if not NON_CAUSAL.is_file(): + print(f"[skip] non-causal: {NON_CAUSAL} not found") + return + m = codec_cpp.Model(NON_CAUSAL) + must(not m.decoder_is_causal, "DAC decoder reported causal") + x = clip(m, False)[: m.sample_rate * 2] + codes = codec_cpp.Context(m).encode(x, m.sample_rate) + ctx = codec_cpp.Context(m, decoder_memory=True) + mem = ctx.decoder_memory + must(mem is not None and mem.state_size() == 0, "non-causal memory must have size 0") + must(mem.get_state() == b"" and mem.set_state(b"") == 0, "empty get / set") + mem.clear() + a = pcm(ctx.decode(codes)) + b = pcm(codec_cpp.Context(m).decode(codes)) + must(np.array_equal(a, b), "memory on a non-causal decoder changed the output") + print("dac: non-causal decoder memory is a size-0 no-op: ok") + + +def test_look_keys() -> None: + path = MODELS["nemo_nano_codec"] + if not path.is_file(): + return + must(codec_cpp.Model(path).decoder_is_causal, "NeMo default (no key) should be causal") + m = codec_cpp.Model(path, kv_overrides={"codec.decoder.look_ahead": 3}) + must(not m.decoder_is_causal, "codec.decoder.look_ahead = 3 should make the decoder non-causal") + must(codec_cpp.Context(m, decoder_memory=True).decoder_memory.state_size() == 0, + "non-causal by metadata: memory size must be 0") + print("look_ahead GGUF key (override) decides causality: ok") + + +def main() -> int: + global SECONDS + args = sys.argv[1:] + if args[:1] == ["--seconds"]: + SECONDS = float(args[1]) + args = args[2:] + names = args or list(MODELS) + for n in names: + test_model(n) + test_non_causal() + test_look_keys() + print("codec_memory_smoke: OK") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())