From 181b3e148cdee67a4e03d93786a73b883beab24e Mon Sep 17 00:00:00 2001 From: Alexey Shabalin Date: Thu, 3 Dec 2026 20:33:42 +0300 Subject: [PATCH 01/11] feat(gigaam): keep the RNN-T decoder state across streaming chunks decode_rnnt_stream continues a persistent predictor state (LSTM h/c, the last emitted token and whether the stream started) instead of restarting the greedy loop per chunk, and numbers emitted frames from the utterance start. The state is self-contained, so a resumed stream does not re-pass its token list. The one-shot entry point is a thin wrapper over the same loop. The unit test feeds the same frames in 2, 3 and 5 chunks and requires identical tokens and frames, then runs one tail from two different predictor states and requires the resulting state to differ. That last check fails if the decoder resets the state at entry (verified by mutation). Part of #310 --- src/arch/gigaam/decoder.cpp | 114 +++++++++++----- src/arch/gigaam/decoder.h | 29 ++++ tests/CMakeLists.txt | 7 + tests/gigaam_rnnt_stream_unit.cpp | 220 ++++++++++++++++++++++++++++++ 4 files changed, 333 insertions(+), 37 deletions(-) create mode 100644 tests/gigaam_rnnt_stream_unit.cpp diff --git a/src/arch/gigaam/decoder.cpp b/src/arch/gigaam/decoder.cpp index 0aa81bb98..3166785aa 100644 --- a/src/arch/gigaam/decoder.cpp +++ b/src/arch/gigaam/decoder.cpp @@ -340,16 +340,14 @@ static void joint_argmax_span(const HostDecoderWeights & h, // // Returns the emitted token sequence (excluding blanks) and the // per-token encoder frame indices. -transcribe_status decode_rnnt_greedy(const HostDecoderWeights & host, - const GigaamHParams & hp, - const float * encoded, - int T_enc, - int max_symbols_per_step, - std::vector & out_tokens, - std::vector & out_frames) { - out_tokens.clear(); - out_frames.clear(); - +static transcribe_status decode_rnnt_run(const HostDecoderWeights & host, + const GigaamHParams & hp, + const float * encoded, + int T_enc, + int max_symbols_per_step, + RnntDecodeState & state, + std::vector & out_tokens, + std::vector & out_frames) { const int H = hp.pred_hidden; const int enc_d = hp.enc_d_model; const int joint_h = hp.joint_hidden; @@ -378,20 +376,26 @@ transcribe_status decode_rnnt_greedy(const HostDecoderWeights & host, } } - std::vector h_cur(H, 0.0f); - std::vector c_cur(H, 0.0f); - std::vector h_next(H, 0.0f); - std::vector c_next(H, 0.0f); - std::vector gates(4 * H, 0.0f); - std::vector pred_in(H, 0.0f); // embed lookup output - std::vector jh(joint_h, 0.0f); - std::vector logits(n_class, 0.0f); - std::vector span_pred_proj; - std::vector span_join; - std::vector span_logits; - std::vector span_tokens; - - bool fresh = true; // first step uses zero input + zero state (reference predict(None, None)) + if (state.h.size() != static_cast(H)) { + state.h.assign(static_cast(H), 0.0f); + } + if (state.c.size() != static_cast(H)) { + state.c.assign(static_cast(H), 0.0f); + } + std::vector & h_cur = state.h; + std::vector & c_cur = state.c; + std::vector h_next(H, 0.0f); + std::vector c_next(H, 0.0f); + std::vector gates(4 * H, 0.0f); + std::vector pred_in(H, 0.0f); // embed lookup output + std::vector jh(joint_h, 0.0f); + std::vector logits(n_class, 0.0f); + std::vector span_pred_proj; + std::vector span_join; + std::vector span_logits; + std::vector span_tokens; + + bool & fresh = state.fresh; // first step uses zero input + zero state (reference predict(None, None)) // Predictor-dirty cache: on a blank emission `(prev_token, h_cur, c_cur)` // are unchanged, so the next LSTM step would deterministically produce @@ -414,8 +418,8 @@ transcribe_status decode_rnnt_greedy(const HostDecoderWeights & host, if (fresh) { std::fill(pred_in.begin(), pred_in.end(), 0.0f); } else { - const int prev = out_tokens.back(); - std::memcpy(pred_in.data(), host.pred_embed.data() + static_cast(prev) * H, H * sizeof(float)); + std::memcpy(pred_in.data(), host.pred_embed.data() + static_cast(state.prev_token) * H, + H * sizeof(float)); } lstm_step(pred_in.data(), h_cur.data(), c_cur.data(), host.lstm_Wx[0].data(), host.lstm_Wh[0].data(), host.lstm_b[0].data(), H, h_next.data(), c_next.data(), gates.data()); @@ -441,18 +445,19 @@ transcribe_status decode_rnnt_greedy(const HostDecoderWeights & host, t += offset; int tok = span_tokens[offset]; out_tokens.push_back(tok); - out_frames.push_back(t); - h_cur = h_next; - c_cur = c_next; - fresh = false; - predictor_dirty = true; + out_frames.push_back(state.frame_offset + t); + state.prev_token = tok; + h_cur = h_next; + c_cur = c_next; + fresh = false; + predictor_dirty = true; // A frame may emit more than one token. Continue with scalar scoring // on this frame until blank or max_symbols_per_step advances time. int sym_count = 1; while (max_symbols_per_step <= 0 || sym_count < max_symbols_per_step) { - const int prev = out_tokens.back(); - std::memcpy(pred_in.data(), host.pred_embed.data() + static_cast(prev) * H, H * sizeof(float)); + std::memcpy(pred_in.data(), host.pred_embed.data() + static_cast(state.prev_token) * H, + H * sizeof(float)); lstm_step(pred_in.data(), h_cur.data(), c_cur.data(), host.lstm_Wx[0].data(), host.lstm_Wh[0].data(), host.lstm_b[0].data(), H, h_next.data(), c_next.data(), gates.data()); predictor_dirty = false; @@ -465,10 +470,11 @@ transcribe_status decode_rnnt_greedy(const HostDecoderWeights & host, } // A token commits the candidate state and invalidates the cache. out_tokens.push_back(tok); - out_frames.push_back(t); - h_cur = h_next; - c_cur = c_next; - predictor_dirty = true; + out_frames.push_back(state.frame_offset + t); + state.prev_token = tok; + h_cur = h_next; + c_cur = c_next; + predictor_dirty = true; ++sym_count; } ++t; @@ -477,6 +483,40 @@ transcribe_status decode_rnnt_greedy(const HostDecoderWeights & host, return TRANSCRIBE_OK; } +transcribe_status decode_rnnt_greedy(const HostDecoderWeights & host, + const GigaamHParams & hp, + const float * encoded, + int T_enc, + int max_symbols_per_step, + std::vector & out_tokens, + std::vector & out_frames) { + out_tokens.clear(); + out_frames.clear(); + RnntDecodeState state; + return decode_rnnt_run(host, hp, encoded, T_enc, max_symbols_per_step, state, out_tokens, out_frames); +} + +transcribe_status decode_rnnt_stream(const HostDecoderWeights & host, + const GigaamHParams & hp, + const float * encoded, + int T_enc, + int max_symbols_per_step, + RnntDecodeState & state, + std::vector & out_tokens, + std::vector & out_frames) { + const size_t before = out_tokens.size(); + const transcribe_status st = + decode_rnnt_run(host, hp, encoded, T_enc, max_symbols_per_step, state, out_tokens, out_frames); + // The caller advances the utterance-relative frame base by the frames it + // just decoded, so the next call keeps numbering from the same origin. + state.frame_offset += T_enc; + // `out_frames` mirrors `out_tokens`; drop a partial pair on failure. + if (st != TRANSCRIBE_OK) { + out_tokens.resize(before); + } + return st; +} + // CTC greedy decode. The 1×1 Conv1d head is a per-frame linear: // logits[t, :] = ctc_w @ encoded[t, :] + ctc_b // Layout of host.ctc_w after readback: ggml ne=[1, d_model, n_classes] diff --git a/src/arch/gigaam/decoder.h b/src/arch/gigaam/decoder.h index dd980c463..4760b5955 100644 --- a/src/arch/gigaam/decoder.h +++ b/src/arch/gigaam/decoder.h @@ -54,6 +54,35 @@ transcribe_status decode_rnnt_greedy(const HostDecoderWeights & host, std::vector & out_tokens, std::vector & out_frames); +// Decoder state carried across streaming feeds: the predictor LSTM state and +// whether the stream has emitted anything yet. `frame_offset` is the absolute +// index of the first frame in the buffer handed to the next call, so emitted +// token frames stay relative to the utterance. +struct RnntDecodeState { + std::vector h; // [pred_hidden] + std::vector c; // [pred_hidden] + bool fresh = true; // no token emitted yet: zero predictor input + // Last token this stream emitted, i.e. the next predictor input. Kept here + // rather than read back from out_tokens so a resumed stream does not have + // to re-pass the whole token list. + int prev_token = 0; + int frame_offset = 0; +}; + +// Streaming RNN-T greedy decode. Continues `state` over `encoded` +// ([T_enc * d_model], T-major) and appends the tokens it emits to +// `out_tokens`, with their utterance-relative frames appended to +// `out_frames`. Equivalent to one `decode_rnnt_greedy` call over the +// concatenated buffers when the caller feeds the chunks in order. +transcribe_status decode_rnnt_stream(const HostDecoderWeights & host, + const GigaamHParams & hp, + const float * encoded, + int T_enc, + int max_symbols_per_step, + RnntDecodeState & state, + std::vector & out_tokens, + std::vector & out_frames); + // CTC greedy decode. `encoded` matches the RNN-T layout // ([T_enc * d_model] T-major). The 1×1 Conv1d head reduces to a // per-frame linear projection (logits = W @ frame + b), followed by diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 266867543..16e9140c9 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -211,6 +211,13 @@ transcribe_apply_warnings(transcribe_parakeet_chunked_limited_window_mask_unit) add_test(NAME transcribe_parakeet_chunked_limited_window_mask_unit COMMAND transcribe_parakeet_chunked_limited_window_mask_unit) +# Streaming RNN-T decode must equal one shot over the same frames. +add_executable(transcribe_gigaam_rnnt_stream_unit gigaam_rnnt_stream_unit.cpp) +target_link_libraries(transcribe_gigaam_rnnt_stream_unit PRIVATE transcribe ggml) +target_include_directories(transcribe_gigaam_rnnt_stream_unit PRIVATE ${CMAKE_SOURCE_DIR}/src) +transcribe_apply_warnings(transcribe_gigaam_rnnt_stream_unit) +add_test(NAME transcribe_gigaam_rnnt_stream_unit COMMAND transcribe_gigaam_rnnt_stream_unit) + # Long-form pause segmenter vs kestrel-generated expected cut points. add_executable(transcribe_parakeet_longform_unit parakeet_longform_unit.cpp) target_link_libraries(transcribe_parakeet_longform_unit PRIVATE transcribe ggml) diff --git a/tests/gigaam_rnnt_stream_unit.cpp b/tests/gigaam_rnnt_stream_unit.cpp new file mode 100644 index 000000000..5aa5bb715 --- /dev/null +++ b/tests/gigaam_rnnt_stream_unit.cpp @@ -0,0 +1,220 @@ +// gigaam_rnnt_stream_unit.cpp - streaming RNN-T decode must equal one shot. +// +// Feeds the same encoder frames through decode_rnnt_greedy and through +// decode_rnnt_stream split into two and three chunks, and compares the tokens +// and their utterance-relative frames. Synthetic weights: the test is about +// state carry-over, not model quality. + +#include "arch/gigaam/decoder.h" +#include "arch/gigaam/gigaam.h" + +#include +#include +#include + +namespace { + +int g_failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + ++g_failures; \ + } \ + } while (0) + +struct Lcg { + unsigned state = 0x12345678u; + + float next() { + state = state * 1664525u + 1013904223u; + return (static_cast((state >> 8) & 0xffffu) / 65535.0f - 0.5f) * 0.2f; + } +}; + +transcribe::gigaam::GigaamHParams make_hparams() { + transcribe::gigaam::GigaamHParams hp; + hp.pred_hidden = 4; + hp.enc_d_model = 8; + hp.joint_hidden = 4; + hp.joint_n_classes = 6; // last class is blank + hp.pred_vocab = 6; + hp.pred_n_layers = 1; + return hp; +} + +transcribe::gigaam::HostDecoderWeights make_weights(const transcribe::gigaam::GigaamHParams & hp) { + using transcribe::gigaam::HostDecoderWeights; + HostDecoderWeights w; + Lcg rng; + const int H = hp.pred_hidden; + w.pred_embed.assign(static_cast(hp.pred_vocab) * H, 0.0f); + for (float & v : w.pred_embed) { + v = rng.next(); + } + w.lstm_Wx.resize(1); + w.lstm_Wh.resize(1); + w.lstm_b.resize(1); + w.lstm_Wx[0].assign(static_cast(4 * H) * H, 0.0f); + w.lstm_Wh[0].assign(static_cast(4 * H) * H, 0.0f); + w.lstm_b[0].assign(static_cast(4 * H), 0.0f); + for (float & v : w.lstm_Wx[0]) { + v = rng.next(); + } + for (float & v : w.lstm_Wh[0]) { + v = rng.next(); + } + w.joint_enc_w.assign(static_cast(hp.joint_hidden) * hp.enc_d_model, 0.0f); + w.joint_enc_b.assign(static_cast(hp.joint_hidden), 0.0f); + w.joint_pred_b.assign(static_cast(hp.joint_hidden), 0.0f); + // The joint must see the predictor state, or a test of state carry-over + // cannot fail: route h[0] into joint lane 0 and let the output rows read + // that lane, so class 0 wins on h[0] > 0 and class 1 on h[0] < 0. + w.joint_pred_w.assign(static_cast(hp.joint_hidden) * H, 0.0f); + w.joint_pred_w[0] = 0.5f; + w.joint_out_w.assign(static_cast(hp.joint_n_classes) * hp.joint_hidden, 0.0f); + w.joint_out_w[0] = 1.0f; + w.joint_out_w[static_cast(hp.joint_hidden)] = -1.0f; + w.joint_out_b.assign(static_cast(hp.joint_n_classes), 0.0f); + w.joint_out_b.back() = -5.0f; + return w; +} + +std::vector make_encoded(const transcribe::gigaam::GigaamHParams & hp, int T) { + Lcg rng; + std::vector encoded(static_cast(T) * hp.enc_d_model); + for (float & v : encoded) { + v = rng.next(); + } + return encoded; +} + +struct Result { + std::vector tokens; + std::vector frames; +}; + +Result one_shot(const transcribe::gigaam::HostDecoderWeights & w, + const transcribe::gigaam::GigaamHParams & hp, + const std::vector & encoded, + int T) { + Result r; + CHECK(transcribe::gigaam::decode_rnnt_greedy(w, hp, encoded.data(), T, /*max_symbols=*/4, r.tokens, r.frames) == + TRANSCRIBE_OK); + return r; +} + +Result streamed(const transcribe::gigaam::HostDecoderWeights & w, + const transcribe::gigaam::GigaamHParams & hp, + const std::vector & encoded, + const std::vector & cuts, + transcribe::gigaam::RnntDecodeState * out_state = nullptr) { + using transcribe::gigaam::RnntDecodeState; + Result r; + RnntDecodeState state; + int start = 0; + for (int end : cuts) { + const int T = end - start; + CHECK(transcribe::gigaam::decode_rnnt_stream(w, hp, + encoded.data() + static_cast(start) * hp.enc_d_model, T, + /*max_symbols=*/4, state, r.tokens, r.frames) == TRANSCRIBE_OK); + start = end; + } + if (out_state != nullptr) { + *out_state = state; + } + return r; +} + +void check_eq_int(long long actual, long long expected, const char * what, int line) { + if (actual != expected) { + std::fprintf(stderr, "FAIL %s:%d: %s = %lld, expected %lld\n", __FILE__, line, what, actual, expected); + ++g_failures; + } +} + +#define CHECK_EQ_INT(actual, expected) check_eq_int((actual), (expected), #actual, __LINE__) + +bool all_zero(const std::vector & v) { + for (float x : v) { + if (x != 0.0f) { + return false; + } + } + return true; +} + +void compare(const Result & a, const Result & b, const char * label) { + CHECK(a.tokens.size() == b.tokens.size()); + CHECK(a.frames.size() == b.frames.size()); + if (a.tokens.size() != b.tokens.size()) { + std::fprintf(stderr, "%s: %zu tokens vs %zu\n", label, a.tokens.size(), b.tokens.size()); + return; + } + for (size_t i = 0; i < a.tokens.size(); ++i) { + if (a.tokens[i] != b.tokens[i] || a.frames[i] != b.frames[i]) { + std::fprintf(stderr, "%s: token %zu is (%d @ %d), expected (%d @ %d)\n", label, i, b.tokens[i], b.frames[i], + a.tokens[i], a.frames[i]); + ++g_failures; + return; + } + } +} + +} // namespace + +int main() { + const auto hp = make_hparams(); + const auto w = make_weights(hp); + const int T_total = 12; + const auto encoded = make_encoded(hp, T_total); + + const Result base = one_shot(w, hp, encoded, T_total); + CHECK(!base.tokens.empty()); + + transcribe::gigaam::RnntDecodeState carried; + compare(base, streamed(w, hp, encoded, { 5, T_total }, &carried), "two chunks"); + compare(base, streamed(w, hp, encoded, { 4, 8, T_total }), "three chunks"); + compare(base, streamed(w, hp, encoded, { 1, 2, 3, 7, T_total }), "five chunks"); + + CHECK(!carried.fresh); + CHECK_EQ_INT(carried.frame_offset, T_total); + + // The comparisons above would also hold if the decoder ignored the state + // it was handed, so prove the state is an input: run the same tail from + // two different predictor states and require a different result. + const auto run_tail = [&](transcribe::gigaam::RnntDecodeState state) { + Result r; + CHECK(transcribe::gigaam::decode_rnnt_stream(w, hp, encoded.data() + 5 * hp.enc_d_model, T_total - 5, + /*max_symbols=*/4, state, r.tokens, r.frames) == TRANSCRIBE_OK); + return std::pair(r, state); + }; + + transcribe::gigaam::RnntDecodeState from_carried = carried; + const auto [tail_a, after_a] = run_tail(from_carried); + transcribe::gigaam::RnntDecodeState from_other = carried; + from_other.h[0] += 1000.0f; + const auto [tail_b, after_b] = run_tail(from_other); + // h[0] is an input: the state left behind differs, which it cannot if the + // decoder resets the predictor at entry. + CHECK(after_a.h != after_b.h); + (void) tail_a; + (void) tail_b; + + // A fresh state numbers its frames from zero; the carried one keeps + // counting from the utterance start. + transcribe::gigaam::RnntDecodeState fresh_state; + Result tail_only; + CHECK(transcribe::gigaam::decode_rnnt_stream(w, hp, encoded.data() + 5 * hp.enc_d_model, T_total - 5, + /*max_symbols=*/4, fresh_state, tail_only.tokens, + tail_only.frames) == TRANSCRIBE_OK); + CHECK_EQ_INT(fresh_state.frame_offset, T_total - 5); + + if (g_failures != 0) { + std::fprintf(stderr, "gigaam_rnnt_stream_unit: %d failures\n", g_failures); + return 1; + } + std::fprintf(stdout, "gigaam_rnnt_stream_unit: ok (%zu tokens)\n", base.tokens.size()); + return 0; +} From bdc60256f1b99c8668dff47926ee794e3d59d66d Mon Sep 17 00:00:00 2001 From: Alexey Shabalin Date: Thu, 3 Dec 2026 20:33:42 +0300 Subject: [PATCH 02/11] feat(gigaam): read and write the v4 streaming hparams GigaAM-v4 checkpoints ship cfg.streaming.contexts, the future-context presets the reference's stateful stream supports. The converter validates them against the encoder's chunk_size/window_size spelling of the same attention band and writes them into the GGUF; the loader reads them into GigaamHParams. A GGUF without the keys stays offline, and stt.capability.streaming stays false until the family registers the stream hooks, so nothing changes for an existing checkpoint. The loader bounds the frame and both contexts (the contexts in frames, since that is what the graph sizes a mask from), checks that frame_ms matches the frontend's own frame, and the converter refuses a config the loader would reject. Part of #310 --- scripts/convert-gigaam-v4.py | 103 ++++++++++++++++++++++ scripts/test_gigaam_v4.py | 126 +++++++++++++++++++++++++++ src/arch/gigaam/weights.cpp | 88 +++++++++++++++++++ src/arch/gigaam/weights.h | 10 +++ tests/fixtures/make_gguf_fixtures.py | 9 ++ tests/gigaam_smoke.cpp | 14 +++ 6 files changed, 350 insertions(+) diff --git a/scripts/convert-gigaam-v4.py b/scripts/convert-gigaam-v4.py index 8456bb4a6..f138adf6e 100644 --- a/scripts/convert-gigaam-v4.py +++ b/scripts/convert-gigaam-v4.py @@ -170,6 +170,102 @@ def refuse(key, value, why): raise ValueError("cfg.language_conditioning is unexpected for GigaAM-v4") +# Mirrors kMaxStreamChunkFrames / kMaxStreamLeftFrames in +# src/arch/gigaam/weights.cpp: a config the loader would refuse must not +# convert. +MAX_CHUNK_FRAMES = 256 +MAX_LEFT_FRAMES = 256 + + +def streaming_contexts(cfg: dict, enc_cfg: dict, pre_cfg: dict) -> tuple[int, list[int], list[int]]: + """Validate cfg.streaming.contexts against the encoder's chunk geometry. + + Returns (frame_ms, future_context_ms, left_context), or (0, [], []) when + the checkpoint carries no streaming config. The streaming graph attends + with a fixed band: query frame q sees keys in [q - left_context, q + chunk). + The Zapformer config spells the same band twice, as chunk_size and + window_size, so refuse a config where the two disagree instead of porting + one and silently ignoring the other. + """ + streaming = cfg.get("streaming") + if streaming is None: + streaming = {} + if not isinstance(streaming, dict): + raise ValueError("cfg.streaming must be a mapping") + contexts = streaming.get("contexts") + if contexts is None: + return 0, [], [] + if not isinstance(contexts, list) or not all(isinstance(c, dict) for c in contexts): + raise ValueError("cfg.streaming.contexts must be a list of {future_context_ms, left_context}") + + try: + sample_rate = int(pre_cfg["sample_rate"]) + hop_length = int(pre_cfg["hop_length"]) + except (KeyError, TypeError, ValueError) as e: + raise ValueError(f"cfg.preprocessor sample_rate/hop_length is missing or not an integer: {e}") from e + if sample_rate <= 0: + raise ValueError(f"cfg.preprocessor.sample_rate is {sample_rate}; it must be positive") + # Subsampling is fixed at 4 by the Zapformer frontend; the converter writes + # that value as stt.gigaam.encoder.subsampling_factor. + frame_ms = hop_length * 4 * 1000 // sample_rate + if frame_ms <= 0: + raise ValueError(f"preprocessor gives a non-positive frame_ms ({frame_ms})") + + windows = enc_cfg.get("window_size", (-1, -1)) + if not isinstance(windows, (list, tuple)): + raise ValueError(f"cfg.encoder.window_size is {windows!r}; expected a list of pairs") + if windows and not isinstance(windows[0], (list, tuple)): + windows = [windows] + if not all(isinstance(w, (list, tuple)) and len(w) == 2 for w in windows): + raise ValueError(f"cfg.encoder.window_size is {windows!r}; expected a list of [left, right] pairs") + streaming_windows = [list(w) for w in windows if list(w) != [-1, -1]] + if len(streaming_windows) != len(contexts): + raise ValueError( + f"cfg.streaming.contexts has {len(contexts)} entries but cfg.encoder.window_size " + f"describes {len(streaming_windows)} streaming bands") + chunk_size_raw = enc_cfg.get("chunk_size", -1) + if chunk_size_raw is None: + raise ValueError("cfg.encoder.chunk_size is null; expected an int or a list of ints") + chunk_sizes = parse_int_list(chunk_size_raw) + + futures: list[int] = [] + lefts: list[int] = [] + for i, context in enumerate(contexts): + try: + future = int(context["future_context_ms"]) + left = int(context["left_context"]) + except KeyError as e: + raise ValueError(f"cfg.streaming.contexts[{i}] has no {e.args[0]}") from e + except (TypeError, ValueError) as e: + raise ValueError(f"cfg.streaming.contexts[{i}] is not a pair of integers: {e}") from e + if future <= 0 or future % frame_ms: + raise ValueError( + f"cfg.streaming.contexts[{i}].future_context_ms is {future}; it must be a positive " + f"multiple of the {frame_ms} ms encoder frame") + if left < 0: + raise ValueError(f"cfg.streaming.contexts[{i}].left_context is {left}; it must be >= 0") + window = streaming_windows[i] + if window != [left, 0]: + raise ValueError( + f"cfg.streaming.contexts[{i}] says left_context={left}, but cfg.encoder.window_size " + f"is {window}; the graph implements [left, 0] only") + if future // frame_ms > MAX_CHUNK_FRAMES: + raise ValueError( + f"cfg.streaming.contexts[{i}] is {future // frame_ms} frames at {frame_ms} ms; " + f"the loader accepts at most {MAX_CHUNK_FRAMES}") + if left > MAX_LEFT_FRAMES: + raise ValueError( + f"cfg.streaming.contexts[{i}].left_context is {left} frames; " + f"the loader accepts at most {MAX_LEFT_FRAMES}") + futures.append(future) + lefts.append(left) + if chunk_sizes != [-1] + [f // frame_ms for f in futures]: + raise ValueError( + f"cfg.encoder.chunk_size is {chunk_sizes}, but the streaming contexts imply " + f"{[f // frame_ms for f in futures]}") + return frame_ms, futures, lefts + + def convert(model_dir: Path, out_path: Path, head: str, repo_id: str) -> None: cfg_path = model_dir / "config.json" st_path = model_dir / "model.safetensors" @@ -185,6 +281,7 @@ def convert(model_dir: Path, out_path: Path, head: str, repo_id: str) -> None: lang_cfg = cfg.get("language_conditioning") if lang_cfg and head != "e2e": raise ValueError("only the Multilingual-v2 e2e head is supported") + stream_frame_ms, stream_futures, stream_lefts = streaming_contexts(cfg, enc_cfg, pre_cfg) tok_path = model_dir / dec_cfg["model_path"] tok = extract_sp_tokenizer(tok_path) @@ -335,6 +432,12 @@ def get_f32(key: str) -> np.ndarray: writer.add_float32("stt.gigaam.encoder.out_norm.scale", out_norm_scale) writer.add_float32("stt.gigaam.encoder.out_norm.eps", out_norm_eps) writer.add_float32("stt.gigaam.encoder.rope_base", 10000.0) + if stream_futures: + # The streaming graph reads these; stt.capability.streaming stays + # false until the family registers the stream hooks. + writer.add_uint32("stt.gigaam.streaming.frame_ms", stream_frame_ms) + writer.add_array("stt.gigaam.streaming.future_context_ms", stream_futures) + writer.add_array("stt.gigaam.streaming.left_context", stream_lefts) # RNN-T predictor + joint writer.add_uint32("stt.gigaam.predictor.hidden", pred_hidden) diff --git a/scripts/test_gigaam_v4.py b/scripts/test_gigaam_v4.py index 4dec3a522..8c0d8b8a6 100644 --- a/scripts/test_gigaam_v4.py +++ b/scripts/test_gigaam_v4.py @@ -220,5 +220,131 @@ def test_a_key_zapformer_encoder_does_not_take_is_refused(self): self.check({"lang_film": True}) +class StreamingContextsTest(unittest.TestCase): + def cfg(self, contexts=None, **enc): + cfg = copy.deepcopy(_V4_CFG) + cfg["encoder"].update(enc) + if contexts is not None: + cfg["streaming"] = {"contexts": contexts} + cfg["preprocessor"] = {"sample_rate": 16000, "hop_length": 160} + return cfg + + @staticmethod + def contexts(): + return [ + {"future_context_ms": 160, "left_context": 32}, + {"future_context_ms": 320, "left_context": 32}, + {"future_context_ms": 640, "left_context": 32}, + ] + + def parse(self, cfg): + return convert_v4.streaming_contexts(cfg, cfg["encoder"], cfg["preprocessor"]) + + def test_the_v4_streaming_contexts_are_accepted(self): + cfg = self.cfg(self.contexts()) + self.assertEqual(self.parse(cfg), (40, [160, 320, 640], [32, 32, 32])) + + def test_a_checkpoint_without_streaming_config_is_offline(self): + self.assertEqual(self.parse(self.cfg(None)), (0, [], [])) + + def test_a_future_context_that_is_not_a_frame_multiple_is_refused(self): + contexts = self.contexts() + contexts[0]["future_context_ms"] = 150 + with self.assertRaisesRegex(ValueError, r"multiple of the 40 ms"): + self.parse(self.cfg(contexts)) + + def test_a_negative_left_context_is_refused(self): + contexts = self.contexts() + contexts[0]["left_context"] = -1 + with self.assertRaisesRegex(ValueError, r"left_context is -1"): + self.parse(self.cfg(contexts)) + + def test_a_window_that_disagrees_with_left_context_is_refused(self): + cfg = self.cfg(self.contexts(), window_size=[[-1, -1], [16, 0], [32, 0], [32, 0]]) + with self.assertRaisesRegex(ValueError, r"window_size is \[16, 0\]"): + self.parse(cfg) + + def test_a_chunk_size_that_disagrees_with_the_contexts_is_refused(self): + cfg = self.cfg(self.contexts(), chunk_size=[-1, 4, 8, 32]) + with self.assertRaisesRegex(ValueError, r"chunk_size is \[-1, 4, 8, 32\]"): + self.parse(cfg) + + def test_a_malformed_streaming_block_is_refused_with_a_value_error(self): + # None (and a missing key) means "no streaming config"; a list or a + # scalar is a malformed block. + self.assertEqual(self.parse(self.cfg(None)), (0, [], [])) + for bad in ([], "x", 3): + cfg = self.cfg(None) + cfg["streaming"] = bad + with self.assertRaisesRegex(ValueError, r"cfg\.streaming must be a mapping"): + self.parse(cfg) + cfg = self.cfg(None) + cfg["streaming"] = {"contexts": {"future_context_ms": 160}} + with self.assertRaisesRegex(ValueError, r"must be a list of"): + self.parse(cfg) + + def test_a_context_without_left_context_is_refused(self): + contexts = self.contexts() + del contexts[0]["left_context"] + with self.assertRaisesRegex(ValueError, r"has no left_context"): + self.parse(self.cfg(contexts)) + + def test_a_non_integer_context_is_refused(self): + contexts = self.contexts() + contexts[0]["future_context_ms"] = [160] + with self.assertRaisesRegex(ValueError, r"not a pair of integers"): + self.parse(self.cfg(contexts)) + + def test_a_zero_sample_rate_is_refused(self): + cfg = self.cfg(self.contexts()) + cfg["preprocessor"]["sample_rate"] = 0 + with self.assertRaisesRegex(ValueError, r"sample_rate is 0"): + self.parse(cfg) + + def test_a_chunk_size_without_a_positive_entry_is_refused(self): + with self.assertRaisesRegex(ValueError, r"chunk_size is \[-1\]"): + self.parse(self.cfg(self.contexts(), chunk_size=[-1])) + + def test_a_falsy_non_list_contexts_is_refused(self): + for bad in (0, {}, "", False): + cfg = self.cfg(None) + cfg["streaming"] = {"contexts": bad} + with self.assertRaisesRegex(ValueError, r"must be a list of"): + self.parse(cfg) + + def test_a_null_chunk_size_is_refused(self): + with self.assertRaisesRegex(ValueError, r"chunk_size is null"): + self.parse(self.cfg(self.contexts(), chunk_size=None)) + + def test_a_window_entry_that_is_not_a_pair_is_refused(self): + cfg = self.cfg(self.contexts(), window_size=[[-1, -1], 32, [32, 0], [32, 0]]) + with self.assertRaisesRegex(ValueError, r"expected a list of \[left, right\] pairs"): + self.parse(cfg) + + def test_a_missing_hop_length_is_refused(self): + cfg = self.cfg(self.contexts()) + del cfg["preprocessor"]["hop_length"] + with self.assertRaisesRegex(ValueError, r"hop_length is missing or not an integer"): + self.parse(cfg) + + def test_a_chunk_beyond_the_loader_bound_is_refused(self): + contexts = self.contexts() + contexts[0]["future_context_ms"] = 20000 # 500 frames at 40 ms + with self.assertRaisesRegex(ValueError, r"the loader accepts at most 256"): + self.parse(self.cfg(contexts)) + + def test_a_left_context_beyond_the_loader_bound_is_refused(self): + contexts = self.contexts() + contexts[0]["left_context"] = 512 + cfg = self.cfg(contexts, window_size=[[-1, -1], [512, 0], [32, 0], [32, 0]]) + with self.assertRaisesRegex(ValueError, r"left_context is 512 frames"): + self.parse(cfg) + + def test_a_context_count_that_disagrees_with_the_windows_is_refused(self): + cfg = self.cfg(self.contexts()[:-1]) + with self.assertRaisesRegex(ValueError, r"2 entries but .* describes 3"): + self.parse(cfg) + + if __name__ == "__main__": unittest.main() diff --git a/src/arch/gigaam/weights.cpp b/src/arch/gigaam/weights.cpp index 43f57c958..aab4dd3ec 100644 --- a/src/arch/gigaam/weights.cpp +++ b/src/arch/gigaam/weights.cpp @@ -51,6 +51,19 @@ transcribe_status read_language_conditioning(const gguf_context * gguf, GigaamHP } // namespace +namespace { + +// Upper bounds for the streaming hparams. The reference advertises 160..640 ms +// of future context (4..16 frames) and a 32-frame left context. The context +// bounds are in frames, because that is what the graph sizes a band mask from: +// a millisecond bound alone would let a small frame_ms turn a modest value into +// a huge frame count. +constexpr int32_t kMaxStreamChunkFrames = 256; +constexpr int32_t kMaxStreamLeftFrames = 256; +constexpr uint32_t kMaxStreamFrameMs = 200; + +} // namespace + transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & hp) { if (gguf == nullptr) { return TRANSCRIBE_ERR_INVALID_ARG; @@ -281,6 +294,66 @@ transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & } int64_t total_layers = 0; + + // Optional streaming config. A GGUF without these keys is offline + // only, which is every checkpoint that predates the streaming port. + // BadType is a converter bug, so it is an error rather than "absent". + { + uint32_t frame_ms = 40; + const KvResult frame_kv = read_uint32_kv(gguf, "stt.gigaam.streaming.frame_ms", frame_ms); + if (frame_kv == KvResult::BadType) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: stt.gigaam.streaming.frame_ms is not a uint32"); + return TRANSCRIBE_ERR_GGUF; + } + if (frame_kv == KvResult::Ok) { + // Checked before the narrowing cast: 0xFFFFFFFF would + // otherwise become -1 and pass every later check as a + // negative divisor. + if (frame_ms == 0 || frame_ms > kMaxStreamFrameMs) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: stt.gigaam.streaming.frame_ms is %u, expected 1..%u", + frame_ms, kMaxStreamFrameMs); + return TRANSCRIBE_ERR_GGUF; + } + hp.stream_frame_ms = static_cast(frame_ms); + } + + std::vector future; + std::vector left; + const KvResult future_kv = read_int32_array_kv(gguf, "stt.gigaam.streaming.future_context_ms", future); + const KvResult left_kv = read_int32_array_kv(gguf, "stt.gigaam.streaming.left_context", left); + if (future_kv == KvResult::BadType || left_kv == KvResult::BadType) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, + "gigaam: stt.gigaam.streaming.future_context_ms and left_context must be i32 arrays"); + return TRANSCRIBE_ERR_GGUF; + } + if (future_kv == KvResult::Ok || left_kv == KvResult::Ok) { + if (future_kv != KvResult::Ok || left_kv != KvResult::Ok) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, + "gigaam: the streaming config needs both future_context_ms and left_context"); + return TRANSCRIBE_ERR_GGUF; + } + if (future.empty() || future.size() != left.size()) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, + "gigaam: streaming arrays are empty or differ in length (%zu vs %zu)", future.size(), + left.size()); + return TRANSCRIBE_ERR_GGUF; + } + for (size_t i = 0; i < future.size(); ++i) { + const int32_t chunk_frames = future[i] / hp.stream_frame_ms; + if (future[i] <= 0 || future[i] % hp.stream_frame_ms != 0 || chunk_frames > kMaxStreamChunkFrames || + left[i] < 0 || left[i] > kMaxStreamLeftFrames) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, + "gigaam: streaming context %zu is invalid (future=%d ms, left=%d frames, " + "frame_ms=%d)", + i, future[i], left[i], hp.stream_frame_ms); + return TRANSCRIBE_ERR_GGUF; + } + } + hp.stream_future_context_ms = std::move(future); + hp.stream_left_context = std::move(left); + } + } + hp.zap_stages.resize(n_stages); for (size_t s = 0; s < n_stages; ++s) { auto & st = hp.zap_stages[s]; @@ -481,6 +554,21 @@ transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & return st; } + // The streaming frame must be the frame the encoder actually produces: + // otherwise the future context and the chunk size the graph derives from + // it describe a different timeline than the audio. Checked here because the + // frontend hparams are read above. + if (hp.has_streaming() && hp.fe_sample_rate > 0 && hp.enc_subsampling_factor > 0) { + const int64_t expected_ms = + static_cast(hp.fe_hop_length) * hp.enc_subsampling_factor * 1000 / hp.fe_sample_rate; + if (expected_ms != hp.stream_frame_ms) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, + "gigaam: stt.gigaam.streaming.frame_ms is %d, but the frontend produces a %lld ms frame", + hp.stream_frame_ms, static_cast(expected_ms)); + return TRANSCRIBE_ERR_GGUF; + } + } + return TRANSCRIBE_OK; } diff --git a/src/arch/gigaam/weights.h b/src/arch/gigaam/weights.h index f73d474c8..a333d8d63 100644 --- a/src/arch/gigaam/weights.h +++ b/src/arch/gigaam/weights.h @@ -93,6 +93,16 @@ struct GigaamHParams { int32_t language_dim = 0; std::vector film_layers; + // Streaming (Zapformer only). Empty when the checkpoint carries no + // streaming config; the family then stays offline. The graph attends with + // a fixed band: query frame q sees keys in [q - left_context, q + chunk), + // where chunk = future_context_ms / stream_frame_ms. + int32_t stream_frame_ms = 40; + std::vector stream_future_context_ms; + std::vector stream_left_context; + + bool has_streaming() const { return !stream_future_context_ms.empty(); } + // RNN-T predictor + joint (HeadKind::RNNT only). int32_t pred_hidden = 0; int32_t pred_n_layers = 0; diff --git a/tests/fixtures/make_gguf_fixtures.py b/tests/fixtures/make_gguf_fixtures.py index 62462a7f8..025e27914 100644 --- a/tests/fixtures/make_gguf_fixtures.py +++ b/tests/fixtures/make_gguf_fixtures.py @@ -829,6 +829,12 @@ def _granite5_ctc_tensors() -> list[Tensor]: "fe_n_fft": 64, "fe_win_length": 64, "fe_hop_length": 32, + # Streaming config the converter writes from cfg.streaming.contexts. + # The toy frontend is hop 32 at 16 kHz with subsampling 4, so its encoder + # frame is 8 ms; the loader rejects a frame_ms that disagrees. + "stream_frame_ms": 8, + "stream_future_context_ms": [160, 320, 640], + "stream_left_context": [32, 32, 32], } @@ -863,6 +869,9 @@ def arr(key: str) -> list: _pack_kv_float32("stt.gigaam.encoder.out_norm.scale", 0.2), _pack_kv_float32("stt.gigaam.encoder.out_norm.eps", 0.1), _pack_kv_float32("stt.gigaam.encoder.rope_base", 10000.0), + _pack_kv_uint32("stt.gigaam.streaming.frame_ms", hp["stream_frame_ms"]), + _pack_kv_array_int32("stt.gigaam.streaming.future_context_ms", hp["stream_future_context_ms"]), + _pack_kv_array_int32("stt.gigaam.streaming.left_context", hp["stream_left_context"]), _pack_kv_uint32("stt.gigaam.predictor.hidden", hp["pred_hidden"]), _pack_kv_uint32("stt.gigaam.predictor.n_layers", hp["pred_n_layers"]), _pack_kv_uint32("stt.gigaam.predictor.vocab", hp["vocab"]), diff --git a/tests/gigaam_smoke.cpp b/tests/gigaam_smoke.cpp index 26a9da5e1..90eb7a7d9 100644 --- a/tests/gigaam_smoke.cpp +++ b/tests/gigaam_smoke.cpp @@ -95,6 +95,20 @@ void check_valid_model(const transcribe_model * model) { CHECK_EQ(hp.pred_vocab, 16); CHECK_EQ(hp.joint_n_classes, 16); + // The converter carries cfg.streaming.contexts into the GGUF; the loader + // keeps them for the streaming graph. + CHECK(hp.has_streaming()); + CHECK_EQ(hp.stream_frame_ms, 8); + CHECK_EQ(hp.stream_future_context_ms.size(), 3); + CHECK_EQ(hp.stream_left_context.size(), 3); + if (hp.stream_future_context_ms.size() == 3 && hp.stream_left_context.size() == 3) { + const int future[3] = { 160, 320, 640 }; + for (size_t i = 0; i < 3; ++i) { + CHECK_EQ(hp.stream_future_context_ms[i], future[i]); + CHECK_EQ(hp.stream_left_context[i], 32); + } + } + const auto & zw = gm->weights.zapformer; CHECK(zw.frontend.out_w != nullptr); if (zw.frontend.out_w != nullptr) { From 9bb2d6d798294df6da169adaaa0b32afefb9485c Mon Sep 17 00:00:00 2001 From: Alexey Shabalin Date: Thu, 3 Dec 2026 20:53:46 +0300 Subject: [PATCH 03/11] fix(gigaam): validate the streaming decoder and hparams loader inputs Entry validation for the streaming decoder (shapes, and a carried token inside the predictor vocab, which indexes the embedding table), output arrays trimmed together on failure, and the frame base advanced only on success. The loader validates the mel geometry unconditionally (positive sample rate, n_fft, win_length, hop_length, and win_length <= n_fft), requires one predictor LSTM layer as the decoder drives a single layer, refuses a streaming config whose frontend hparams cannot produce its frame, bounds the frame computation against int64 overflow, and caps the context list at the encoder stage count. The decoder unit test gains a write-back check that fails if the state is mutated only in local copies (verified by mutation), plus refusals for an out-of-vocab carried token, a negative one and a null input. One negative GGUF fixture covers each new loader refusal; gigaam_smoke asserts both TRANSCRIBE_ERR_GGUF and the diagnostic of the guard, so a fixture that regresses to an earlier rejection does not pass. Part of #310 --- src/arch/gigaam/decoder.cpp | 37 ++++++--- src/arch/gigaam/weights.cpp | 50 ++++++++++-- tests/CMakeLists.txt | 12 +++ tests/fixtures/make_gguf_fixtures.py | 33 ++++++-- tests/gigaam_rnnt_stream_unit.cpp | 47 ++++++++++++ tests/gigaam_smoke.cpp | 109 ++++++++++++++++++++++----- 6 files changed, 248 insertions(+), 40 deletions(-) diff --git a/src/arch/gigaam/decoder.cpp b/src/arch/gigaam/decoder.cpp index 3166785aa..d4efd646c 100644 --- a/src/arch/gigaam/decoder.cpp +++ b/src/arch/gigaam/decoder.cpp @@ -348,11 +348,23 @@ static transcribe_status decode_rnnt_run(const HostDecoderWeights & host, RnntDecodeState & state, std::vector & out_tokens, std::vector & out_frames) { - const int H = hp.pred_hidden; - const int enc_d = hp.enc_d_model; - const int joint_h = hp.joint_hidden; - const int n_class = hp.joint_n_classes; + const int H = hp.pred_hidden; + const int enc_d = hp.enc_d_model; + const int joint_h = hp.joint_hidden; + const int n_class = hp.joint_n_classes; + + if (encoded == nullptr || T_enc <= 0 || H <= 0 || enc_d <= 0 || joint_h <= 0 || n_class <= 0) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam decoder (rnnt): invalid shapes or input"); + return TRANSCRIBE_ERR_INVALID_ARG; + } const int blank_id = n_class - 1; + // A carried token indexes the predictor embedding: an out-of-range value + // would read past `pred_embed`, so refuse it before the loop. + if (!state.fresh && (state.prev_token < 0 || state.prev_token >= static_cast(host.pred_embed.size()) / H)) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam decoder (rnnt): carried token %d is outside the predictor vocab", + state.prev_token); + return TRANSCRIBE_ERR_INVALID_ARG; + } // Precompute encoder projection for every frame in one BLAS sgemm // (or a fallback loop). The joint's enc_w @ f_t + enc_b is independent @@ -504,17 +516,22 @@ transcribe_status decode_rnnt_stream(const HostDecoderWeights & host, RnntDecodeState & state, std::vector & out_tokens, std::vector & out_frames) { - const size_t before = out_tokens.size(); + const size_t before_tokens = out_tokens.size(); + const size_t before_frames = out_frames.size(); const transcribe_status st = decode_rnnt_run(host, hp, encoded, T_enc, max_symbols_per_step, state, out_tokens, out_frames); + if (st != TRANSCRIBE_OK) { + // The only failure today is entry validation, which runs before the + // state is touched. Trim a partial pair (if one is ever added) and + // leave the frame base where it was, so a retry keeps numbering. + out_tokens.resize(before_tokens); + out_frames.resize(before_frames); + return st; + } // The caller advances the utterance-relative frame base by the frames it // just decoded, so the next call keeps numbering from the same origin. state.frame_offset += T_enc; - // `out_frames` mirrors `out_tokens`; drop a partial pair on failure. - if (st != TRANSCRIBE_OK) { - out_tokens.resize(before); - } - return st; + return TRANSCRIBE_OK; } // CTC greedy decode. The 1×1 Conv1d head is a per-frame linear: diff --git a/src/arch/gigaam/weights.cpp b/src/arch/gigaam/weights.cpp index aab4dd3ec..83a06ff53 100644 --- a/src/arch/gigaam/weights.cpp +++ b/src/arch/gigaam/weights.cpp @@ -13,6 +13,7 @@ #include "transcribe-weights-util.h" #include +#include #include #include @@ -332,10 +333,11 @@ transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & "gigaam: the streaming config needs both future_context_ms and left_context"); return TRANSCRIBE_ERR_GGUF; } - if (future.empty() || future.size() != left.size()) { + if (future.empty() || future.size() != left.size() || (n_stages != 0 && future.size() > n_stages)) { log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, - "gigaam: streaming arrays are empty or differ in length (%zu vs %zu)", future.size(), - left.size()); + "gigaam: streaming arrays are empty, differ in length (%zu vs %zu), or name more " + "bands than the encoder has stages (%zu)", + future.size(), left.size(), n_stages); return TRANSCRIBE_ERR_GGUF; } for (size_t i = 0; i < future.size(); ++i) { @@ -470,6 +472,15 @@ transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & hp.joint_n_classes); return TRANSCRIBE_ERR_GGUF; } + // The decoder drives exactly one predictor LSTM layer. A larger count + // would be silently ignored; zero would leave the weight arrays empty + // and the decoder would index them. + if (hp.pred_n_layers != 1) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, + "gigaam: stt.gigaam.predictor.n_layers is %d, expected 1 (the decoder drives one LSTM layer)", + hp.pred_n_layers); + return TRANSCRIBE_ERR_GGUF; + } } else { // CTC if (auto st = read_required_u32_kv(gguf, "stt.gigaam.head.feat_in", kFamilyTag, hp.head_feat_in); st != TRANSCRIBE_OK) { @@ -554,13 +565,40 @@ transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & return st; } + // The mel frontend sizes its FFT buffers from n_fft, writes win_length + // samples into a 2*n_fft buffer and divides by hop_length. Validate that + // geometry here, for offline models too: a crafted GGUF with n_fft or + // hop_length 0 would otherwise reach the frontend and crash. + if (hp.fe_sample_rate <= 0 || hp.fe_n_fft <= 0 || hp.fe_win_length <= 0 || hp.fe_hop_length <= 0 || + hp.fe_win_length > hp.fe_n_fft) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, + "gigaam: invalid frontend geometry (sample_rate=%d n_fft=%d win_length=%d hop_length=%d)", + hp.fe_sample_rate, hp.fe_n_fft, hp.fe_win_length, hp.fe_hop_length); + return TRANSCRIBE_ERR_GGUF; + } + // The streaming frame must be the frame the encoder actually produces: // otherwise the future context and the chunk size the graph derives from // it describe a different timeline than the audio. Checked here because the // frontend hparams are read above. - if (hp.has_streaming() && hp.fe_sample_rate > 0 && hp.enc_subsampling_factor > 0) { - const int64_t expected_ms = - static_cast(hp.fe_hop_length) * hp.enc_subsampling_factor * 1000 / hp.fe_sample_rate; + if (hp.has_streaming()) { + if (hp.enc_subsampling_factor <= 0) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, + "gigaam: the streaming config needs a positive encoder subsampling factor (got %d)", + hp.enc_subsampling_factor); + return TRANSCRIBE_ERR_GGUF; + } + const int64_t hop = hp.fe_hop_length; + const int64_t sub = hp.enc_subsampling_factor; + // hop and sub are int32; their product can exceed int64 before the + // divide, so bound it first. + if (hop > INT64_MAX / 1000 / sub) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, + "gigaam: frontend hop %lld and subsampling %lld overflow the streaming frame computation", + static_cast(hop), static_cast(sub)); + return TRANSCRIBE_ERR_GGUF; + } + const int64_t expected_ms = hop * sub * 1000 / hp.fe_sample_rate; if (expected_ms != hp.stream_frame_ms) { log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: stt.gigaam.streaming.frame_ms is %d, but the frontend produces a %lld ms frame", diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 16e9140c9..1230aaa38 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -649,6 +649,18 @@ set(TRANSCRIBE_FIXTURE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_symmetric_frontend.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_short_stage_array.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_squeezeformer.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_stream_frame_mismatch.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_stream_frame_zero.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_stream_future_not_multiple.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_stream_future_out_of_bounds.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_stream_left_out_of_bounds.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_stream_too_many_contexts.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_frontend_hop_zero.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_frontend_win_gt_fft.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_stream_frame_overflow.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_stream_zero_subsampling.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_pred_zero_layers.gguf + ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_pred_two_layers.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_qwen3_asr_minimal.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_ecapa_tdnn_minimal.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_ecapa_tdnn_q8_0.gguf diff --git a/tests/fixtures/make_gguf_fixtures.py b/tests/fixtures/make_gguf_fixtures.py index 025e27914..8c7d4e3d7 100644 --- a/tests/fixtures/make_gguf_fixtures.py +++ b/tests/fixtures/make_gguf_fixtures.py @@ -853,7 +853,7 @@ def arr(key: str) -> list: _pack_kv_uint32("stt.gigaam.encoder.n_layers", sum(hp["stage_layers"])), _pack_kv_uint32("stt.gigaam.encoder.d_model", hp["d_model"]), _pack_kv_uint32("stt.gigaam.encoder.feat_in", hp["feat_in"]), - _pack_kv_uint32("stt.gigaam.encoder.subsampling_factor", 4), + _pack_kv_uint32("stt.gigaam.encoder.subsampling_factor", hp.get("enc_subsampling_factor", 4)), _pack_kv_bool("stt.gigaam.encoder.causal_frontend", hp["causal_frontend"]), _pack_kv_array_int32("stt.gigaam.encoder.frontend_channels", hp["frontend_channels"]), ] @@ -1019,10 +1019,11 @@ def _with_stage(hp: dict, key: str, stage: int, value: int) -> dict: return out -# One mutant per stage-geometry rejection in read_gigaam_hparams. Each entry -# is (file suffix, hparams, stage array emitted one entry short). The KV check -# fails before tensors are bound; tensors follow the mutated hparams where -# that gives a well-formed table, else the valid ones. +# One mutant per rejection in read_gigaam_hparams, stage geometry and +# streaming hparams alike. Each entry is (file suffix, hparams, stage array +# emitted one entry short). The KV check fails before tensors are bound; +# tensors follow the mutated hparams where that gives a well-formed table, +# else the valid ones. GIGAAM_V4_MUTANTS: list[tuple[str, dict, str | None]] = [ ("odd_qdim", _with_stage(GIGAAM_V4_HP, "stage_qdim", 1, 3), None), ("even_conv_kernel", _with_stage(GIGAAM_V4_HP, "stage_conv_kernel", 2, 4), None), @@ -1033,6 +1034,28 @@ def _with_stage(hp: dict, key: str, stage: int, value: int) -> dict: ("symmetric_frontend", {**GIGAAM_V4_HP, "causal_frontend": False}, None), ("short_stage_array", GIGAAM_V4_HP, "stage_dims"), ("squeezeformer", {**GIGAAM_V4_HP, "encoder_type": "squeezeformer"}, None), + # Streaming hparams. All leave the stage geometry valid, so they reach the + # streaming block. + ("stream_frame_mismatch", {**GIGAAM_V4_HP, "stream_frame_ms": 16}, None), + ("stream_frame_zero", {**GIGAAM_V4_HP, "stream_frame_ms": 0}, None), + ("stream_future_not_multiple", {**GIGAAM_V4_HP, "stream_future_context_ms": [160, 324, 640]}, None), + ("stream_future_out_of_bounds", {**GIGAAM_V4_HP, "stream_future_context_ms": [160, 320, 40960]}, None), + ("stream_left_out_of_bounds", {**GIGAAM_V4_HP, "stream_left_context": [32, 32, 257]}, None), + ("stream_too_many_contexts", + {**GIGAAM_V4_HP, "stream_future_context_ms": [160, 320, 640, 1280], + "stream_left_context": [32, 32, 32, 32]}, None), + # Frontend geometry, checked for offline models too, and the frame + # computation overflow. hop 10e6 with subsampling 2e9 passes the positive + # checks but overflows hop * sub * 1000 before the divide. + ("frontend_hop_zero", {**GIGAAM_V4_HP, "fe_hop_length": 0}, None), + ("frontend_win_gt_fft", {**GIGAAM_V4_HP, "fe_win_length": 128}, None), + ("stream_frame_overflow", + {**GIGAAM_V4_HP, "fe_hop_length": 10_000_000, "enc_subsampling_factor": 2_000_000_000}, None), + ("stream_zero_subsampling", {**GIGAAM_V4_HP, "enc_subsampling_factor": 0}, None), + # The decoder drives one predictor LSTM layer; zero would index empty + # weight arrays, more than one would be silently ignored. + ("pred_zero_layers", {**GIGAAM_V4_HP, "pred_n_layers": 0}, None), + ("pred_two_layers", {**GIGAAM_V4_HP, "pred_n_layers": 2}, None), ] diff --git a/tests/gigaam_rnnt_stream_unit.cpp b/tests/gigaam_rnnt_stream_unit.cpp index 5aa5bb715..85419962e 100644 --- a/tests/gigaam_rnnt_stream_unit.cpp +++ b/tests/gigaam_rnnt_stream_unit.cpp @@ -202,6 +202,21 @@ int main() { (void) tail_a; (void) tail_b; + // Write-back: the caller's state must move, not a local copy of it. Force + // a token on every frame (a joint bias makes class 0 win whatever the + // state) so the predictor state is committed; a decoder that mutates only + // copies would leave it at its zero initialization. + auto forced_w = w; + forced_w.joint_enc_b[0] = 10.0f; + transcribe::gigaam::RnntDecodeState forced_state; + Result forced; + CHECK(transcribe::gigaam::decode_rnnt_stream(forced_w, hp, encoded.data(), 4, /*max_symbols=*/4, forced_state, + forced.tokens, forced.frames) == TRANSCRIBE_OK); + // max_symbols_per_step=4 on each of 4 frames, and class 0 always wins. + CHECK_EQ_INT(forced.tokens.size(), 16); + CHECK(!all_zero(forced_state.h)); + CHECK(!all_zero(forced_state.c)); + // A fresh state numbers its frames from zero; the carried one keeps // counting from the utterance start. transcribe::gigaam::RnntDecodeState fresh_state; @@ -211,6 +226,38 @@ int main() { tail_only.frames) == TRANSCRIBE_OK); CHECK_EQ_INT(fresh_state.frame_offset, T_total - 5); + // A carried token outside the predictor vocab would index past the + // embedding table; it must be refused before the loop runs. + transcribe::gigaam::RnntDecodeState bad_state = carried; + bad_state.prev_token = hp.pred_vocab; + Result ignored; + CHECK(transcribe::gigaam::decode_rnnt_stream(w, hp, encoded.data(), T_total, /*max_symbols=*/4, bad_state, + ignored.tokens, ignored.frames) == TRANSCRIBE_ERR_INVALID_ARG); + CHECK(ignored.tokens.empty()); + CHECK(ignored.frames.empty()); + CHECK_EQ_INT(bad_state.frame_offset, carried.frame_offset); + + // The same bound from below, and invalid input shapes, are refused the + // same way: nothing appended, the frame base untouched. + transcribe::gigaam::RnntDecodeState negative_state = carried; + negative_state.prev_token = -1; + CHECK(transcribe::gigaam::decode_rnnt_stream(w, hp, encoded.data(), T_total, /*max_symbols=*/4, negative_state, + ignored.tokens, ignored.frames) == TRANSCRIBE_ERR_INVALID_ARG); + CHECK(ignored.tokens.empty()); + CHECK_EQ_INT(negative_state.frame_offset, carried.frame_offset); + + transcribe::gigaam::RnntDecodeState null_state; + CHECK(transcribe::gigaam::decode_rnnt_stream(w, hp, nullptr, 4, /*max_symbols=*/4, null_state, ignored.tokens, + ignored.frames) == TRANSCRIBE_ERR_INVALID_ARG); + CHECK(ignored.tokens.empty()); + CHECK_EQ_INT(null_state.frame_offset, 0); + + transcribe::gigaam::RnntDecodeState empty_state; + CHECK(transcribe::gigaam::decode_rnnt_stream(w, hp, encoded.data(), 0, /*max_symbols=*/4, empty_state, + ignored.tokens, ignored.frames) == TRANSCRIBE_ERR_INVALID_ARG); + CHECK(ignored.tokens.empty()); + CHECK_EQ_INT(empty_state.frame_offset, 0); + if (g_failures != 0) { std::fprintf(stderr, "gigaam_rnnt_stream_unit: %d failures\n", g_failures); return 1; diff --git a/tests/gigaam_smoke.cpp b/tests/gigaam_smoke.cpp index 90eb7a7d9..f1acf9745 100644 --- a/tests/gigaam_smoke.cpp +++ b/tests/gigaam_smoke.cpp @@ -3,9 +3,10 @@ // Loads a tiny but complete three-stage Zapformer GGUF through the public C // ABI, checks arch, variant, the stage hparams and representative tensor // shapes, runs one second of silence through the encoder graph and RNN-T -// decoder, then loads one mutant per stage-geometry rejection in -// read_gigaam_hparams and asserts each is refused with TRANSCRIBE_ERR_GGUF. -// Fixtures come from tests/fixtures/make_gguf_fixtures.py (GIGAAM_V4_HP, +// decoder, then loads one mutant per rejection in read_gigaam_hparams and +// asserts each is refused with TRANSCRIBE_ERR_GGUF and the diagnostic that +// names the guard, so a mutant cannot silently start failing on a later +// check. Fixtures come from tests/fixtures/make_gguf_fixtures.py (GIGAAM_V4_HP, // GIGAAM_V4_MUTANTS). #include "arch/gigaam/gigaam.h" @@ -17,6 +18,7 @@ #include #include #include +#include #include #include @@ -55,6 +57,45 @@ std::string fixture_path(const char * name) { return std::string(TRANSCRIBE_TEST_FIXTURES_DIR) + "/" + name; } +// ---- log capture ------------------------------------------------------------ + +// Each mutant is identified by the diagnostic its guard emits, not just by the +// status: several guards can share TRANSCRIBE_ERR_GGUF, so a status-only check +// would stay green if a mutant regressed to an earlier rejection. + +std::mutex g_log_mu; +std::vector g_log; + +void capture_log(transcribe_log_level level, const char * msg, void * /*userdata*/) { + if (msg == nullptr || level == TRANSCRIBE_LOG_LEVEL_DEBUG || level == TRANSCRIBE_LOG_LEVEL_CONT) { + return; + } + std::lock_guard lock(g_log_mu); + g_log.emplace_back(msg); +} + +void clear_log() { + std::lock_guard lock(g_log_mu); + g_log.clear(); +} + +bool log_has(const char * needle) { + std::lock_guard lock(g_log_mu); + for (const auto & line : g_log) { + if (line.find(needle) != std::string::npos) { + return true; + } + } + return false; +} + +void dump_log() { + std::lock_guard lock(g_log_mu); + for (const auto & line : g_log) { + std::fprintf(stderr, " log: %s\n", line.c_str()); + } +} + transcribe_status load_cpu(const std::string & path, transcribe_model ** out) { transcribe_model_load_params load_params; transcribe_model_load_params_init(&load_params); @@ -165,17 +206,34 @@ void check_silent_run(transcribe_model * model, } // namespace +struct Mutant { + const char * file; + const char * expect; // substring of the refusal diagnostic +}; + int main() { - const char * mutants[] = { - "arch_gigaam_multilingual_v2_duplicate.gguf", - "arch_gigaam_v4_bad_odd_qdim.gguf", - "arch_gigaam_v4_bad_even_conv_kernel.gguf", - "arch_gigaam_v4_bad_zero_downsampling.gguf", - "arch_gigaam_v4_bad_intermediate_downsampling.gguf", - "arch_gigaam_v4_bad_mixed_qdim.gguf", - "arch_gigaam_v4_bad_symmetric_frontend.gguf", - "arch_gigaam_v4_bad_short_stage_array.gguf", - "arch_gigaam_v4_bad_squeezeformer.gguf", + static const Mutant kMutants[] = { + { "arch_gigaam_multilingual_v2_duplicate.gguf", "invalid or duplicate language code" }, + { "arch_gigaam_v4_bad_odd_qdim.gguf", "qdim=3" }, + { "arch_gigaam_v4_bad_even_conv_kernel.gguf", "conv_kernel=4" }, + { "arch_gigaam_v4_bad_zero_downsampling.gguf", "downsampling=0" }, + { "arch_gigaam_v4_bad_intermediate_downsampling.gguf", "downsampling 2 is not supported" }, + { "arch_gigaam_v4_bad_mixed_qdim.gguf", "qdim 6 differs from stage 0 qdim 4" }, + { "arch_gigaam_v4_bad_symmetric_frontend.gguf", "causal_frontend=false" }, + { "arch_gigaam_v4_bad_short_stage_array.gguf", "stage_dims has 2 entries" }, + { "arch_gigaam_v4_bad_squeezeformer.gguf", "encoder.type=squeezeformer" }, + { "arch_gigaam_v4_bad_stream_frame_mismatch.gguf", "but the frontend produces a 8 ms frame" }, + { "arch_gigaam_v4_bad_stream_frame_zero.gguf", "frame_ms is 0, expected 1..200" }, + { "arch_gigaam_v4_bad_stream_future_not_multiple.gguf", "future=324 ms" }, + { "arch_gigaam_v4_bad_stream_future_out_of_bounds.gguf", "future=40960 ms" }, + { "arch_gigaam_v4_bad_stream_left_out_of_bounds.gguf", "left=257 frames" }, + { "arch_gigaam_v4_bad_stream_too_many_contexts.gguf", "more bands than the encoder has stages" }, + { "arch_gigaam_v4_bad_frontend_hop_zero.gguf", "invalid frontend geometry" }, + { "arch_gigaam_v4_bad_frontend_win_gt_fft.gguf", "invalid frontend geometry" }, + { "arch_gigaam_v4_bad_stream_frame_overflow.gguf", "overflow the streaming frame computation" }, + { "arch_gigaam_v4_bad_stream_zero_subsampling.gguf", "needs a positive encoder subsampling factor" }, + { "arch_gigaam_v4_bad_pred_zero_layers.gguf", "n_layers is 0, expected 1" }, + { "arch_gigaam_v4_bad_pred_two_layers.gguf", "n_layers is 2, expected 1" }, }; const std::string valid = fixture_path("arch_gigaam_v4_minimal.gguf"); @@ -183,17 +241,20 @@ int main() { std::fprintf(stderr, "gigaam_smoke: fixture not found: %s\n", valid.c_str()); return 77; } - for (const char * name : mutants) { - if (!file_exists(fixture_path(name))) { - std::fprintf(stderr, "gigaam_smoke: fixture not found: %s\n", fixture_path(name).c_str()); + for (const Mutant & m : kMutants) { + if (!file_exists(fixture_path(m.file))) { + std::fprintf(stderr, "gigaam_smoke: fixture not found: %s\n", fixture_path(m.file).c_str()); return 77; } } + transcribe_log_set(capture_log, nullptr); + transcribe_model * model = nullptr; const transcribe_status st = load_cpu(valid, &model); if (st != TRANSCRIBE_OK || model == nullptr) { std::fprintf(stderr, "FAIL load %s: %s\n", valid.c_str(), transcribe_status_string(st)); + dump_log(); return EXIT_FAILURE; } check_valid_model(model); @@ -217,20 +278,30 @@ int main() { transcribe_model_free(model); for (const char * name : mutants) { + + for (const Mutant & m : kMutants) { + clear_log(); transcribe_model * bad = nullptr; - const transcribe_status bad_st = load_cpu(fixture_path(name), &bad); + const transcribe_status bad_st = load_cpu(fixture_path(m.file), &bad); if (bad_st != TRANSCRIBE_ERR_GGUF) { - std::fprintf(stderr, "FAIL %s: load returned %s, expected TRANSCRIBE_ERR_GGUF\n", name, + std::fprintf(stderr, "FAIL %s: load returned %s, expected TRANSCRIBE_ERR_GGUF\n", m.file, transcribe_status_string(bad_st)); + dump_log(); + ++g_failures; + } else if (!log_has(m.expect)) { + std::fprintf(stderr, "FAIL %s: refusal did not report \"%s\"\n", m.file, m.expect); + dump_log(); ++g_failures; } if (bad != nullptr) { - std::fprintf(stderr, "FAIL %s: model pointer is not NULL after a refused load\n", name); + std::fprintf(stderr, "FAIL %s: model pointer is not NULL after a refused load\n", m.file); ++g_failures; transcribe_model_free(bad); } } + transcribe_log_set(nullptr, nullptr); + if (g_failures != 0) { std::fprintf(stderr, "gigaam_smoke: %d failures\n", g_failures); return EXIT_FAILURE; From 2c327605efbbb795e044e2e678d54ee92bf4c759 Mon Sep 17 00:00:00 2001 From: Alexey Shabalin Date: Thu, 3 Dec 2026 23:01:45 +0300 Subject: [PATCH 04/11] feat(gigaam): compute the streaming feed and attention geometry The chunked streaming encoder needs three host-side pieces before the graph exists: how many frontend frames a feed consumes, the band attention bias per stage (chunk alignment over absolute frames plus the left context, with key validity for a partially filled final feed and for the valid tail of the past cache), and the cache roll. The unit test pins the mask with hand-computed scenarios for ds=1 and ds=2, a partially valid final feed and a full-attention chunk mode, then sweeps invariants that do not restate the formula: invalid keys are always masked, the chunk rule opens the whole chunk, the band opens [left, 0], and no allowed past key falls outside those two. Part of #310 --- src/CMakeLists.txt | 1 + src/arch/gigaam/stream.cpp | 78 ++++++++ src/arch/gigaam/stream.h | 54 ++++++ tests/CMakeLists.txt | 16 ++ tests/gigaam_stream_geometry_unit.cpp | 258 ++++++++++++++++++++++++++ 5 files changed, 407 insertions(+) create mode 100644 src/arch/gigaam/stream.cpp create mode 100644 src/arch/gigaam/stream.h create mode 100644 tests/gigaam_stream_geometry_unit.cpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 9d1f787dc..5763a615b 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -131,6 +131,7 @@ add_library(transcribe arch/gigaam/encoder.cpp arch/gigaam/decoder.cpp arch/gigaam/mel.cpp + arch/gigaam/stream.cpp arch/granite/model.cpp arch/granite/diarize.cpp arch/granite/capabilities.cpp diff --git a/src/arch/gigaam/stream.cpp b/src/arch/gigaam/stream.cpp new file mode 100644 index 000000000..1dfc46799 --- /dev/null +++ b/src/arch/gigaam/stream.cpp @@ -0,0 +1,78 @@ +// arch/gigaam/stream.cpp - GigaAM-v4 streaming geometry and cache helpers. + +#include "stream.h" + +#include +#include +#include +#include + +namespace transcribe::gigaam { + +int stream_ready_frames(int pending, int new_frames, int chunk, bool final, int * remaining) { + const int total = std::max(0, pending) + std::max(0, new_frames); + int ready = total; + if (!final) { + ready = chunk > 0 ? total / chunk * chunk : 0; + } + if (remaining != nullptr) { + *remaining = total - ready; + } + return ready; +} + +void stream_attn_bias_f32(float * out, + int n_q, + int n_keys, + int64_t position, + int ds, + int n_past, + int n_past_valid, + int n_valid, + StreamContext geom) { + const float masked = -std::numeric_limits::infinity(); + const int64_t base = position - static_cast(n_past) * ds; + for (int q = 0; q < n_q; ++q) { + const int64_t q_abs = position + static_cast(q) * ds; + float * row = out + static_cast(q) * n_keys; + bool any = false; + for (int k = 0; k < n_keys; ++k) { + const int64_t k_abs = base + static_cast(k) * ds; + // Past keys count only in the valid tail of the cache; current + // keys only up to the valid frame count. + const bool valid = k >= n_past - n_past_valid && k < n_past + n_valid; + // Same chunk (chunk alignment over absolute frames) or within the + // left band behind the query. The reference's window is [left, 0]; + // a non-positive chunk means full attention (no chunk rule, no + // band), as the reference's _attention_mask returns all-ones. + const bool same_chunk = geom.chunk > 0 && q_abs / geom.chunk == k_abs / geom.chunk; + const bool band = k_abs <= q_abs && k_abs >= q_abs - geom.left; + const bool open = geom.chunk <= 0 || same_chunk || band; + const bool usable = valid && open; + row[k] = usable ? 0.0f : masked; + any = any || usable; + } + // A query with no usable key (a feed with zero valid frames) must + // still produce a finite row: an all -INF softmax is NaN, and the + // conv mean would spread it to the valid frames. The reference opens + // all-masked rows the same way. + if (!any && n_keys > 0) { + row[0] = 0.0f; + } + } +} + +void stream_cache_roll_f32(float * dst, int dst_rows, const float * src, int src_rows, int rows, int row_elems) { + if (dst == nullptr || src == nullptr || dst_rows <= 0 || src_rows <= 0 || row_elems <= 0) { + return; + } + rows = std::min(rows, std::min(src_rows, dst_rows)); + rows = std::max(rows, 0); + const size_t elems = static_cast(row_elems); + const size_t zero = static_cast(dst_rows - rows) * elems; + std::memset(dst, 0, zero * sizeof(float)); + std::memcpy(dst + zero, src + static_cast(src_rows - rows) * elems, + static_cast(rows) * elems * sizeof(float)); +} + +} // namespace transcribe::gigaam diff --git a/src/arch/gigaam/stream.h b/src/arch/gigaam/stream.h new file mode 100644 index 000000000..0d48e5f4a --- /dev/null +++ b/src/arch/gigaam/stream.h @@ -0,0 +1,54 @@ +// arch/gigaam/stream.h - GigaAM-v4 streaming geometry and cache helpers. +// +// Host-side pieces of the chunked streaming encoder: how many frames a feed +// consumes, the band attention mask the reference builds per stage, and the +// cache roll. The graph side lives in encoder.cpp. + +#pragma once + +#include + +namespace transcribe::gigaam { + +// Streaming preset from the GGUF hparams: the future context selects the feed +// length in frontend frames (40 ms each), the left context bounds attention. +struct StreamContext { + int chunk = 0; // frontend frames per feed (4, 8 or 16) + int left = 0; // left attention context, frontend frames +}; + +// Frames to process from `pending + new_frames` buffered frontend frames. +// While the stream is open only whole chunks are processed; the final feed +// takes everything. `remaining` receives the frames left for the next feed. +int stream_ready_frames(int pending, int new_frames, int chunk, bool final, int * remaining); + +// Additive attention bias over one stage's keys, ggml layout ne=[n_keys, +// n_queries] (element (k, q) at q * n_keys + k). A query frame attends a key +// when both fall in the same `chunk` of absolute frontend frames, or the key +// is within `geom.left` frames behind the query (the reference's window is +// [left, 0]); invalid keys -- outside the valid tail of the past cache or past +// the current valid frames -- never attend. Allowed cells are 0, masked cells +// are -INF. +// +// `position` is the absolute frontend frame of the first query of this feed, +// `ds` the stage downsampling (both query and key positions are spaced `ds`), +// `n_past` the cache length in stage frames and `n_past_valid` the valid tail +// of that cache. A query with no usable key gets its first cell opened so the +// row stays finite. +void stream_attn_bias_f32(float * out, + int n_q, + int n_keys, + int64_t position, + int ds, + int n_past, + int n_past_valid, + int n_valid, + StreamContext geom); + +// Copy the last `rows` rows of a [row_elems, src_rows] buffer into the tail of +// a [row_elems, dst_rows] cache and zero the rows in front of it. `rows` is +// clamped to both sizes. Used by the streaming session driver when it carries +// the caches between feeds. +void stream_cache_roll_f32(float * dst, int dst_rows, const float * src, int src_rows, int rows, int row_elems); + +} // namespace transcribe::gigaam diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 1230aaa38..5013e13af 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1810,6 +1810,22 @@ transcribe_apply_warnings(transcribe_mel_unit) add_test(NAME transcribe_mel_unit COMMAND transcribe_mel_unit) +# ----------------------------------------------------------------------------- +# GigaAM-v4 streaming geometry: feed arithmetic, band attention mask, cache roll +# ----------------------------------------------------------------------------- + +add_executable(transcribe_gigaam_stream_geometry_unit + gigaam_stream_geometry_unit.cpp) + +target_link_libraries(transcribe_gigaam_stream_geometry_unit PRIVATE transcribe) + +target_include_directories(transcribe_gigaam_stream_geometry_unit PRIVATE + ${CMAKE_SOURCE_DIR}/src) + +transcribe_apply_warnings(transcribe_gigaam_stream_geometry_unit) + +add_test(NAME transcribe_gigaam_stream_geometry_unit COMMAND transcribe_gigaam_stream_geometry_unit) + # ----------------------------------------------------------------------------- # Tokenizer decode-only mode unit test # ----------------------------------------------------------------------------- diff --git a/tests/gigaam_stream_geometry_unit.cpp b/tests/gigaam_stream_geometry_unit.cpp new file mode 100644 index 000000000..710a58a5c --- /dev/null +++ b/tests/gigaam_stream_geometry_unit.cpp @@ -0,0 +1,258 @@ +// gigaam_stream_geometry_unit.cpp - streaming feed arithmetic, the band +// attention mask and the cache roll. +// +// The mask is the part of the streaming port that is easy to get subtly +// wrong: chunk alignment over absolute frames, the left band, and key +// validity for a partially valid final feed. Scenarios are hand-computed +// from the reference's _attention_mask / _stream_geometry, plus invariant +// sweeps that do not restate the formula. + +#include "arch/gigaam/stream.h" + +#include +#include +#include + +namespace { + +int g_failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + ++g_failures; \ + } \ + } while (0) + +bool masked(float v) { + return v < -1e30f; +} + +// allowed[q] is the set of key indices the query may attend. +struct Scenario { + const char * name; + int n_q; + int n_keys; + long long position; + int ds; + int n_past; + int n_past_valid; + int n_valid; + transcribe::gigaam::StreamContext geom; + std::vector> allowed; +}; + +void check_scenario(const Scenario & s) { + std::vector bias(static_cast(s.n_q) * s.n_keys, 0.0f); + transcribe::gigaam::stream_attn_bias_f32(bias.data(), s.n_q, s.n_keys, s.position, s.ds, s.n_past, s.n_past_valid, + s.n_valid, s.geom); + for (int q = 0; q < s.n_q; ++q) { + for (int k = 0; k < s.n_keys; ++k) { + bool expect_allowed = false; + for (int allowed : s.allowed[q]) { + if (allowed == k) { + expect_allowed = true; + } + } + const float v = bias[static_cast(q) * s.n_keys + k]; + if (expect_allowed && masked(v)) { + std::fprintf(stderr, "FAIL %s: q=%d k=%d masked, expected allowed\n", s.name, q, k); + ++g_failures; + } + if (!expect_allowed && !masked(v)) { + std::fprintf(stderr, "FAIL %s: q=%d k=%d allowed (%.1f), expected masked\n", s.name, q, k, v); + ++g_failures; + } + } + } +} + +void check_invariants(const Scenario & s) { + std::vector bias(static_cast(s.n_q) * s.n_keys, 0.0f); + transcribe::gigaam::stream_attn_bias_f32(bias.data(), s.n_q, s.n_keys, s.position, s.ds, s.n_past, s.n_past_valid, + s.n_valid, s.geom); + const long long base = s.position - static_cast(s.n_past) * s.ds; + for (int q = 0; q < s.n_q; ++q) { + const long long q_abs = s.position + static_cast(q) * s.ds; + for (int k = 0; k < s.n_keys; ++k) { + const long long k_abs = base + static_cast(k) * s.ds; + const float v = bias[static_cast(q) * s.n_keys + k]; + const bool allowed = !masked(v); + const bool valid = k >= s.n_past - s.n_past_valid && k < s.n_past + s.n_valid; + // Only two values exist. + CHECK(v == 0.0f || masked(v)); + if (!valid) { + CHECK(!allowed); + continue; + } + if (s.geom.chunk <= 0) { + // Full attention: every valid key is open. + CHECK(allowed); + continue; + } + // A key never attends from behind the left band unless the chunk + // rule reaches it, and a future key only through the chunk rule. + if (allowed && k_abs < q_abs) { + CHECK(k_abs >= q_abs - s.geom.left || q_abs / s.geom.chunk == k_abs / s.geom.chunk); + } + if (allowed && k_abs > q_abs) { + CHECK(s.geom.chunk > 0 && q_abs / s.geom.chunk == k_abs / s.geom.chunk); + } + // Conversely, the band and the chunk itself are always open. + if (k_abs <= q_abs && k_abs >= q_abs - s.geom.left) { + CHECK(allowed); + } + if (s.geom.chunk > 0 && q_abs / s.geom.chunk == k_abs / s.geom.chunk) { + CHECK(allowed); + } + } + } +} + +void test_ready_frames() { + int rem = -1; + CHECK(transcribe::gigaam::stream_ready_frames(0, 4, 4, false, &rem) == 4 && rem == 0); + CHECK(transcribe::gigaam::stream_ready_frames(0, 3, 4, false, &rem) == 0 && rem == 3); + CHECK(transcribe::gigaam::stream_ready_frames(3, 5, 4, false, &rem) == 8 && rem == 0); + CHECK(transcribe::gigaam::stream_ready_frames(3, 5, 4, true, &rem) == 8 && rem == 0); + CHECK(transcribe::gigaam::stream_ready_frames(0, 3, 4, true, &rem) == 3 && rem == 0); + CHECK(transcribe::gigaam::stream_ready_frames(2, 4, 8, false, &rem) == 0 && rem == 6); + CHECK(transcribe::gigaam::stream_ready_frames(6, 10, 8, false, &rem) == 16 && rem == 0); + CHECK(transcribe::gigaam::stream_ready_frames(0, 5, 0, false, &rem) == 0 && rem == 5); + CHECK(transcribe::gigaam::stream_ready_frames(0, 5, 0, true, &rem) == 5 && rem == 0); +} + +void test_cache_roll() { + // src is a [3, 6] history; the cache keeps its last 4 rows. + std::vector src(3 * 6); + for (int t = 0; t < 6; ++t) { + for (int c = 0; c < 3; ++c) { + src[static_cast(t) * 3 + c] = static_cast(10 * t + c); + } + } + std::vector dst(3 * 4, -7.0f); + transcribe::gigaam::stream_cache_roll_f32(dst.data(), 4, src.data(), 6, 4, 3); + for (int t = 0; t < 4; ++t) { + for (int c = 0; c < 3; ++c) { + CHECK(dst[static_cast(t) * 3 + c] == src[static_cast(t + 2) * 3 + c]); + } + } + + // Fewer source rows than cache slots: the front is zeroed. + std::vector short_src(3 * 2, 5.0f); + dst.assign(3 * 4, -7.0f); + transcribe::gigaam::stream_cache_roll_f32(dst.data(), 4, short_src.data(), 2, 4, 3); + for (int c = 0; c < 3; ++c) { + CHECK(dst[static_cast(0) * 3 + c] == 0.0f); + CHECK(dst[static_cast(1) * 3 + c] == 0.0f); + CHECK(dst[static_cast(2) * 3 + c] == 5.0f); + CHECK(dst[static_cast(3) * 3 + c] == 5.0f); + } + + // Zero rows wipes the cache; null inputs are a no-op. + dst.assign(3 * 4, -7.0f); + transcribe::gigaam::stream_cache_roll_f32(dst.data(), 4, src.data(), 6, 0, 3); + for (float v : dst) { + CHECK(v == 0.0f); + } + transcribe::gigaam::stream_cache_roll_f32(nullptr, 4, src.data(), 6, 4, 3); + transcribe::gigaam::stream_cache_roll_f32(dst.data(), 4, nullptr, 6, 4, 3); +} + +void test_masks() { + using transcribe::gigaam::StreamContext; + + // First feed: empty cache, chunk 4, left 32. Every key in the first chunk + // is visible and nothing before it is. + const Scenario first{ + "first feed", + 4, + 36, + 0, + 1, + 32, + 0, + 4, + StreamContext{ 4, 32 }, + { { 32, 33, 34, 35 }, { 32, 33, 34, 35 }, { 32, 33, 34, 35 }, { 32, 33, 34, 35 } }, + }; + check_scenario(first); + check_invariants(first); + + // Narrow left band: q=20 sees keys 18..20 through the band and 20..23 + // through the chunk; keys 16, 17 are out of both. + const Scenario narrow{ + "narrow band", + 4, + 8, + 20, + 1, + 4, + 4, + 4, + StreamContext{ 4, 2 }, + { { 2, 3, 4, 5, 6, 7 }, { 3, 4, 5, 6, 7 }, { 4, 5, 6, 7 }, { 4, 5, 6, 7 } }, + }; + check_scenario(narrow); + check_invariants(narrow); + + // Partial final feed: only 2 of the 4 chunk frames are real, so keys 22 + // and 23 stay masked even though they share the chunk. + const Scenario partial{ + "partial final feed", + 4, + 8, + 20, + 1, + 4, + 4, + 2, + StreamContext{ 4, 2 }, + { { 2, 3, 4, 5 }, { 3, 4, 5 }, { 4, 5 }, { 4, 5 } }, + }; + check_scenario(partial); + check_invariants(partial); + + // Stage downsampling 2: positions are spaced 2, the chunk is still in + // absolute frontend frames, and only the valid tail of the cache counts. + const Scenario downsampled{ + "ds=2", 2, 6, 16, 2, 4, 2, 2, StreamContext{ 8, 4 }, + { { 2, 3, 4, 5 }, { 3, 4, 5 } }, + }; + check_scenario(downsampled); + check_invariants(downsampled); + + // Zero valid keys (a degenerate feed): every row would be all-masked and + // softmax would be NaN, so the builder opens the first cell of each row. + { + std::vector bias(static_cast(2) * 2, 0.0f); + transcribe::gigaam::stream_attn_bias_f32(bias.data(), 2, 2, 0, 1, 0, 0, 0, StreamContext{ 4, 0 }); + for (int q = 0; q < 2; ++q) { + CHECK(bias[static_cast(q) * 2 + 0] == 0.0f); + CHECK(masked(bias[static_cast(q) * 2 + 1])); + } + } + + // Full attention (chunk <= 0) opens every valid cell. + const Scenario full{ + "full attention", 2, 4, 0, 1, 2, 2, 2, StreamContext{ 0, 0 }, + { { 0, 1, 2, 3 }, { 0, 1, 2, 3 } }, + }; + check_scenario(full); + check_invariants(full); +} + +} // namespace + +int main() { + test_ready_frames(); + test_cache_roll(); + test_masks(); + if (g_failures != 0) { + std::fprintf(stderr, "gigaam_stream_geometry_unit: %d failures\n", g_failures); + return 1; + } + std::fprintf(stdout, "gigaam_stream_geometry_unit: ok\n"); + return 0; +} From 9e4a065c7ae981eb85649c4593f34b4e67f59266 Mon Sep 17 00:00:00 2001 From: Alexey Shabalin Date: Thu, 3 Dec 2026 23:18:00 +0300 Subject: [PATCH 05/11] feat(gigaam): stream the Zapformer frontend with conv caches A feed consumes 4 * chunk mel frames and carries the four conv input caches that replace the offline graph's causal zero padding. The graph is chunk-size independent: the unit test runs the same mel sequence as one feed and as three, copying each cache to the next feed, and requires the encoder frames to match. Part of #310 --- src/arch/gigaam/encoder.cpp | 121 +++++++++++ src/arch/gigaam/encoder.h | 22 ++ tests/CMakeLists.txt | 16 ++ tests/gigaam_stream_frontend_unit.cpp | 286 ++++++++++++++++++++++++++ 4 files changed, 445 insertions(+) create mode 100644 tests/gigaam_stream_frontend_unit.cpp diff --git a/src/arch/gigaam/encoder.cpp b/src/arch/gigaam/encoder.cpp index ccc2d0279..b9bcea517 100644 --- a/src/arch/gigaam/encoder.cpp +++ b/src/arch/gigaam/encoder.cpp @@ -702,6 +702,127 @@ EncoderBuild build_zapformer_encoder_graph(ggml_context * ctx, } // namespace +// Streaming frontend: the offline graph's causal padding is replaced by the +// cached rows of each conv input, so a feed consumes exactly 4 * chunk mel +// frames and the caches carry the only cross-feed state. Feeding N chunks +// equals the offline causal frontend over the same mel frames. +ZapStreamFrontend build_zapformer_stream_frontend(ggml_context * ctx, + const ZapformerFrontendWeights & fe, + int64_t n_mels, + int64_t chunk, + bool direct_conv) { + ZapStreamFrontend sf{}; + if (ctx == nullptr || fe.conv0_w == nullptr || fe.conv1_w == nullptr || fe.conv2_w == nullptr || + fe.cn_dw_w == nullptr || fe.out_w == nullptr || n_mels <= 0 || chunk <= 0) { + return sf; + } + + const int64_t T_mel = 4 * chunk; + const int64_t F = n_mels; + const int64_t c0 = fe.conv0_w->ne[3]; + const int64_t c1 = fe.conv1_w->ne[3]; + const int64_t c2 = fe.conv2_w->ne[3]; + // Conv2/conv3 stride 2 on both axes without frequency padding. + const int64_t F2 = (F - 3) / 2 + 1; + const int64_t F3 = (F2 - 3) / 2 + 1; + if (c0 <= 0 || c1 <= 0 || c2 <= 0 || F2 <= 0 || F3 <= 0) { + return sf; + } + + sf.mel_in = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, T_mel, F, 1); + ggml_set_name(sf.mel_in, "zap.stream.mel"); + ggml_set_input(sf.mel_in); + + struct CacheSpec { + int64_t w; + int64_t rows; + int64_t c; + const char * in_name; + const char * out_name; + }; + + const CacheSpec specs[4] = { + { F, 2, 1, "zap.stream.cache0", "zap.stream.cache0.next" }, + { F, 1, c0, "zap.stream.cache1", "zap.stream.cache1.next" }, + { F2, 1, c1, "zap.stream.cache2", "zap.stream.cache2.next" }, + { F3, 2, c2, "zap.stream.cache3", "zap.stream.cache3.next" }, + }; + for (int i = 0; i < 4; ++i) { + sf.cache_in[i] = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, specs[i].w, specs[i].rows, specs[i].c, 1); + ggml_set_name(sf.cache_in[i], specs[i].in_name); + ggml_set_input(sf.cache_in[i]); + sf.cache_rows[i] = specs[i].rows; + } + + // Stage lengths: conv1 keeps 4 * chunk, conv2 halves, conv3 halves again, + // convnext keeps the conv3 length. + const int64_t valid_lens[4] = { T_mel, T_mel / 2, chunk, chunk }; + for (int i = 0; i < 4; ++i) { + sf.valid_in[i] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, valid_lens[i]); + ggml_set_name(sf.valid_in[i], "zap.stream.frontend.valid"); + ggml_set_input(sf.valid_in[i]); + } + + auto tail_rows = [&](ggml_tensor * joined, int64_t rows, const char * name) { + ggml_tensor * v = + ggml_view_4d(ctx, joined, joined->ne[0], rows, joined->ne[2], joined->ne[3], joined->nb[1], joined->nb[2], + joined->nb[3], static_cast(joined->ne[1] - rows) * joined->nb[1]); + ggml_tensor * o = ggml_cont(ctx, v); + ggml_set_name(o, name); + ggml_set_output(o); + return o; + }; + + // [T_mel, F, 1] -> [W=F, H=T_mel, C=1, B=1]. + ggml_tensor * x = ggml_cont(ctx, ggml_permute(ctx, sf.mel_in, 1, 0, 2, 3)); + x = ggml_reshape_4d(ctx, x, F, T_mel, 1, 1); + + // Conv1: the causal left pad comes from the cache instead of zeros. + ggml_tensor * j = ggml_concat(ctx, sf.cache_in[0], x, 1); + sf.cache_out[0] = tail_rows(j, 2, specs[0].out_name); + x = conf::conv_2d_f32(ctx, fe.conv0_w, j, 1, 1, /*p0=*/1, /*p1=*/0, 1, 1); + x = ggml_silu(ctx, conf::add_conv_bias(ctx, x, fe.conv0_b)); + x = ggml_mul(ctx, x, sf.valid_in[0]); + + // Conv2/conv3: the left pad row comes from the cache, the right pad is + // gone; stride 2 keeps the chunk alignment. + j = ggml_concat(ctx, sf.cache_in[1], x, 1); + sf.cache_out[1] = tail_rows(j, 1, specs[1].out_name); + x = zap_conv_2d(ctx, fe.conv1_w, j, 2, 2, 0, 0, direct_conv); + x = ggml_silu(ctx, conf::add_conv_bias(ctx, x, fe.conv1_b)); + x = ggml_mul(ctx, x, sf.valid_in[1]); + + j = ggml_concat(ctx, sf.cache_in[2], x, 1); + sf.cache_out[2] = tail_rows(j, 1, specs[2].out_name); + x = zap_conv_2d(ctx, fe.conv2_w, j, 2, 2, 0, 0, direct_conv); + x = ggml_silu(ctx, conf::add_conv_bias(ctx, x, fe.conv2_b)); + x = ggml_mul(ctx, x, sf.valid_in[2]); + + // ConvNeXt: depthwise conv over the joined rows, residual on the + // uncached conv3 output. + ggml_tensor * res = x; + j = ggml_concat(ctx, sf.cache_in[3], x, 1); + sf.cache_out[3] = tail_rows(j, 2, specs[3].out_name); + ggml_tensor * y = conf::conv_2d_dw_direct_f32(ctx, fe.cn_dw_w, j, 1, 1, /*p0=*/1, /*p1=*/0, 1, 1); + y = conf::add_conv_bias(ctx, y, fe.cn_dw_b); + y = zap_conv_2d(ctx, fe.cn_pw1_w, y, 1, 1, 0, 0, direct_conv); + y = ggml_silu(ctx, conf::add_conv_bias(ctx, y, fe.cn_pw1_b)); + y = zap_conv_2d(ctx, fe.cn_pw2_w, y, 1, 1, 0, 0, direct_conv); + y = conf::add_conv_bias(ctx, y, fe.cn_pw2_b); + x = ggml_add(ctx, res, y); + + // Flatten and project exactly as build_zapformer_frontend does. + x = ggml_cont(ctx, ggml_permute(ctx, x, 0, 2, 1, 3)); + x = ggml_reshape_3d(ctx, x, x->ne[0] * x->ne[1], x->ne[2], x->ne[3]); + x = ggml_add(ctx, ggml_mul_mat(ctx, fe.out_w, x), fe.out_b); + x = ggml_mul(ctx, x, sf.valid_in[3]); + + ggml_set_name(x, "zap.stream.out"); + ggml_set_output(x); + sf.out = x; + return sf; +} + // One stride-2 conv with symmetric (k-1)/2 padding: floor((in-1)/2)+1. // GigaAM's k=5/pad=2 and parakeet's k=3/pad=1 both reduce to this. static int pre_encode_t_out(int in) { diff --git a/src/arch/gigaam/encoder.h b/src/arch/gigaam/encoder.h index c0f268f49..1997b5fc8 100644 --- a/src/arch/gigaam/encoder.h +++ b/src/arch/gigaam/encoder.h @@ -108,4 +108,26 @@ EncoderBuild build_encoder_graph(ggml_context * compute_ctx, // angle, rounded through F16 as the GigaAM-v4 checkpoint stores them. void fill_zapformer_rope_tables(const EncoderBuild & eb, const GigaamHParams & hp); +// Streaming frontend: one feed of 4 * chunk mel frames plus the four conv +// input caches. `cache_in` tensors are graph inputs to fill before compute; +// `cache_out` are outputs with the same shapes to copy back for the next feed. +struct ZapStreamFrontend { + ggml_tensor * mel_in = nullptr; // [4 * chunk, n_mels, 1] + ggml_tensor * cache_in[4] = {}; + ggml_tensor * cache_out[4] = {}; + int64_t cache_rows[4] = { 2, 1, 1, 2 }; + // Per-stage valid masks [1, T_stage, 1, 1] (1 real / 0 pad), applied + // after each conv output so the final padded feed matches the reference. + ggml_tensor * valid_in[4] = {}; + ggml_tensor * out = nullptr; // [d_model, chunk, 1] +}; + +struct ZapformerFrontendWeights; + +ZapStreamFrontend build_zapformer_stream_frontend(ggml_context * ctx, + const ZapformerFrontendWeights & fe, + int64_t n_mels, + int64_t chunk, + bool direct_conv); + } // namespace transcribe::gigaam diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5013e13af..5c1d57ea3 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1826,6 +1826,22 @@ transcribe_apply_warnings(transcribe_gigaam_stream_geometry_unit) add_test(NAME transcribe_gigaam_stream_geometry_unit COMMAND transcribe_gigaam_stream_geometry_unit) +# ----------------------------------------------------------------------------- +# GigaAM-v4 streaming frontend: chunked feeds equal the offline causal frontend +# ----------------------------------------------------------------------------- + +add_executable(transcribe_gigaam_stream_frontend_unit + gigaam_stream_frontend_unit.cpp) + +target_link_libraries(transcribe_gigaam_stream_frontend_unit PRIVATE transcribe ggml) + +target_include_directories(transcribe_gigaam_stream_frontend_unit PRIVATE + ${CMAKE_SOURCE_DIR}/src) + +transcribe_apply_warnings(transcribe_gigaam_stream_frontend_unit) + +add_test(NAME transcribe_gigaam_stream_frontend_unit COMMAND transcribe_gigaam_stream_frontend_unit) + # ----------------------------------------------------------------------------- # Tokenizer decode-only mode unit test # ----------------------------------------------------------------------------- diff --git a/tests/gigaam_stream_frontend_unit.cpp b/tests/gigaam_stream_frontend_unit.cpp new file mode 100644 index 000000000..8672b54a3 --- /dev/null +++ b/tests/gigaam_stream_frontend_unit.cpp @@ -0,0 +1,286 @@ +// gigaam_stream_frontend_unit.cpp - the streaming frontend is feed-size +// independent. +// +// Builds a toy Zapformer frontend, runs the same mel sequence as one feed and +// as several feeds of 4 * chunk, and requires the outputs to match. The +// caches are the only state carried between feeds; a wrong, missing or stale +// cache row shows up as a mismatch in the frames that follow. +// +// Mel values are laid out the way ggml sees them, ne=[frames, mels]: frame +// index runs fastest, so a feed's slice is gathered per mel band. + +#include "arch/gigaam/encoder.h" +#include "arch/gigaam/weights.h" +#include "ggml-backend.h" +#include "ggml-cpu.h" +#include "ggml.h" + +#include +#include +#include +#include +#include + +namespace { + +int g_failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + ++g_failures; \ + } \ + } while (0) + +struct Lcg { + unsigned state = 0x9e3779b9u; + + float next() { + state = state * 1664525u + 1013904223u; + return (static_cast((state >> 8) & 0xffffu) / 65535.0f - 0.5f); + } +}; + +constexpr int64_t kMels = 8; +constexpr int64_t kC0 = 2; +constexpr int64_t kC1 = 4; +constexpr int64_t kC2 = 4; +constexpr int64_t kDModel = 8; + +struct Tensors { + transcribe::gigaam::ZapformerFrontendWeights fe; + std::vector tensors; + std::vector elems; +}; + +ggml_tensor * add_tensor(ggml_context * ctx, Tensors & t, int n_dims, const int64_t * ne) { + ggml_tensor * x = nullptr; + switch (n_dims) { + case 1: + x = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ne[0]); + break; + case 2: + x = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, ne[0], ne[1]); + break; + case 3: + x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, ne[0], ne[1], ne[2]); + break; + default: + x = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, ne[0], ne[1], ne[2], ne[3]); + break; + } + t.tensors.push_back(x); + t.elems.push_back(static_cast(ggml_nelements(x))); + return x; +} + +Tensors make_weights(ggml_context * ctx) { + Tensors t{}; + const int64_t conv0_w[4] = { 3, 3, 1, kC0 }; + const int64_t conv1_w[4] = { 3, 3, kC0, kC1 }; + const int64_t conv2_w[4] = { 3, 3, kC1, kC2 }; + const int64_t cn_dw[4] = { 3, 3, 1, kC2 }; + const int64_t cn_pw1[4] = { 1, 1, kC2, 3 * kC2 }; + const int64_t cn_pw2[4] = { 1, 1, 3 * kC2, kC2 }; + const int64_t out_w[2] = { kC2, kDModel }; // the frequency axis collapses to 1 + const int64_t cn_pw1_b_n = 3 * kC2; + + t.fe.conv0_w = add_tensor(ctx, t, 4, conv0_w); + t.fe.conv0_b = add_tensor(ctx, t, 1, &kC0); + t.fe.conv1_w = add_tensor(ctx, t, 4, conv1_w); + t.fe.conv1_b = add_tensor(ctx, t, 1, &kC1); + t.fe.conv2_w = add_tensor(ctx, t, 4, conv2_w); + t.fe.conv2_b = add_tensor(ctx, t, 1, &kC2); + t.fe.cn_dw_w = add_tensor(ctx, t, 4, cn_dw); + t.fe.cn_dw_b = add_tensor(ctx, t, 1, &kC2); + t.fe.cn_pw1_w = add_tensor(ctx, t, 4, cn_pw1); + t.fe.cn_pw1_b = add_tensor(ctx, t, 1, &cn_pw1_b_n); + t.fe.cn_pw2_w = add_tensor(ctx, t, 4, cn_pw2); + t.fe.cn_pw2_b = add_tensor(ctx, t, 1, &kC2); + t.fe.out_w = add_tensor(ctx, t, 2, out_w); + t.fe.out_b = add_tensor(ctx, t, 1, &kDModel); + return t; +} + +void fill_weights(Tensors & t, ggml_backend_t backend) { + Lcg rng; + std::vector buf; + for (size_t i = 0; i < t.tensors.size(); ++i) { + buf.resize(t.elems[i]); + for (float & v : buf) { + v = rng.next(); + } + ggml_backend_tensor_set(t.tensors[i], buf.data(), 0, buf.size() * sizeof(float)); + } +} + +// Frame-fastest layout: mel[m * frames + t]. +std::vector make_mel(int64_t frames) { + Lcg rng; + std::vector mel(static_cast(kMels * frames)); + for (float & v : mel) { + v = rng.next(); + } + return mel; +} + +std::vector feed_slice(const std::vector & mel, int64_t total_frames, int64_t first, int64_t n_frames) { + std::vector out(static_cast(kMels * n_frames)); + for (int64_t m = 0; m < kMels; ++m) { + for (int64_t t = 0; t < n_frames; ++t) { + out[static_cast(m * n_frames + t)] = mel[static_cast(m * total_frames + first + t)]; + } + } + return out; +} + +void fill_full_valid(const transcribe::gigaam::ZapStreamFrontend & fe, ggml_backend_t backend) { + for (ggml_tensor * mask : fe.valid_in) { + std::vector v(static_cast(mask->ne[1]), 1.0f); + ggml_backend_tensor_set(mask, v.data(), 0, v.size() * sizeof(float)); + } +} + +bool run_graph(ggml_backend_t backend, ggml_cgraph * graph, ggml_tensor * out, std::vector & result) { + if (ggml_backend_graph_compute(backend, graph) != GGML_STATUS_SUCCESS) { + return false; + } + result.resize(static_cast(ggml_nelements(out))); + ggml_backend_tensor_get(out, result.data(), 0, result.size() * sizeof(float)); + return true; +} + +// Feed the sequence through `n_feeds` graphs of `4 * chunk` mel frames each, +// carrying every cache to the next feed, and return the concatenated encoder +// frames. +bool run_streaming(const std::vector & mel, + int64_t total_frames, + int64_t chunk, + int64_t n_feeds, + std::vector & out) { + const int64_t mels_per_feed = 4 * chunk; + if (total_frames != n_feeds * mels_per_feed) { + return false; + } + + ggml_init_params params{ 64u * 1024 * 1024, nullptr, true }; + ggml_context * ctx = ggml_init(params); + if (ctx == nullptr) { + return false; + } + Tensors t = make_weights(ctx); + + std::vector feeds; + for (int64_t f = 0; f < n_feeds; ++f) { + auto sf = transcribe::gigaam::build_zapformer_stream_frontend(ctx, t.fe, kMels, chunk, + /*direct_conv=*/false); + if (sf.out == nullptr) { + ggml_free(ctx); + return false; + } + feeds.push_back(sf); + } + + ggml_backend_t backend = ggml_backend_cpu_init(); + if (backend == nullptr) { + ggml_free(ctx); + return false; + } + ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, backend); + if (buf == nullptr) { + ggml_backend_free(backend); + ggml_free(ctx); + return false; + } + ggml_backend_buffer_clear(buf, 0); + fill_weights(t, backend); + for (const auto & feed : feeds) { + fill_full_valid(feed, backend); + } + + for (int64_t f = 0; f < n_feeds; ++f) { + const std::vector feed = feed_slice(mel, total_frames, f * mels_per_feed, mels_per_feed); + ggml_backend_tensor_set(feeds[f].mel_in, feed.data(), 0, feed.size() * sizeof(float)); + } + + bool ok = true; + for (int64_t f = 0; f < n_feeds && ok; ++f) { + ggml_cgraph * graph = ggml_new_graph_custom(ctx, 4096, false); + ggml_build_forward_expand(graph, feeds[f].out); + for (ggml_tensor * c : feeds[f].cache_out) { + ggml_build_forward_expand(graph, c); + } + std::vector chunk_out; + ok = run_graph(backend, graph, feeds[f].out, chunk_out); + if (!ok) { + break; + } + out.insert(out.end(), chunk_out.begin(), chunk_out.end()); + + if (f + 1 < n_feeds) { + for (int c = 0; c < 4; ++c) { + std::vector cache(static_cast(ggml_nelements(feeds[f].cache_out[c]))); + ggml_backend_tensor_get(feeds[f].cache_out[c], cache.data(), 0, cache.size() * sizeof(float)); + ggml_backend_tensor_set(feeds[f + 1].cache_in[c], cache.data(), 0, cache.size() * sizeof(float)); + } + } + } + + ggml_backend_buffer_free(buf); + ggml_backend_free(backend); + ggml_free(ctx); + return ok; +} + +void test_feed_size_independence() { + // One feed processes 4 mel frames per encoder frame, so 48 mel frames are + // 12 encoder frames: one chunk of 12, or three chunks of 4. + const int64_t total_mels = 48; + std::vector mel = make_mel(total_mels); + + std::vector one_shot; + CHECK(run_streaming(mel, total_mels, /*chunk=*/total_mels / 4, /*n_feeds=*/1, one_shot)); + std::vector chunked; + CHECK(run_streaming(mel, total_mels, /*chunk=*/4, /*n_feeds=*/3, chunked)); + + CHECK(one_shot.size() == chunked.size()); + if (one_shot.size() != chunked.size()) { + return; + } + float max_abs = 0.0f; + double sum_abs = 0.0; + for (size_t i = 0; i < one_shot.size(); ++i) { + const float d = std::fabs(one_shot[i] - chunked[i]); + max_abs = std::max(max_abs, d); + sum_abs += d; + } + if (max_abs > 1e-5f) { + std::fprintf(stderr, "FAIL one shot vs chunked: max abs %.3e (mean %.3e), %zu values\n", max_abs, + sum_abs / static_cast(one_shot.size()), one_shot.size()); + ++g_failures; + } +} + +void test_invalid_args() { + ggml_init_params params{ 1024 * 1024, nullptr, true }; + ggml_context * ctx = ggml_init(params); + CHECK(ctx != nullptr); + Tensors t = make_weights(ctx); + CHECK(transcribe::gigaam::build_zapformer_stream_frontend(ctx, t.fe, kMels, 0, false).out == nullptr); + CHECK(transcribe::gigaam::build_zapformer_stream_frontend(ctx, t.fe, 0, 4, false).out == nullptr); + ggml_free(ctx); +} + +} // namespace + +int main() { + test_feed_size_independence(); + test_invalid_args(); + if (g_failures != 0) { + std::fprintf(stderr, "gigaam_stream_frontend_unit: %d failures\n", g_failures); + return 1; + } + std::fprintf(stdout, "gigaam_stream_frontend_unit: ok\n"); + return 0; +} From 4d01b71a87073af907759f4a6a6052af5f965703 Mon Sep 17 00:00:00 2001 From: Alexey Shabalin Date: Fri, 4 Dec 2026 00:25:05 +0300 Subject: [PATCH 06/11] feat(gigaam): stream the Zapformer encoder with per-layer caches Mirrors the reference _stream_layer / _forward_chunk: attention over the cached query/value history with the band mask and RoPE at absolute positions, the conv module over the cached mean window with chunk-local future taps, and per-stage downsampling. Every cache is a graph input/output pair the caller carries between feeds. The unit test builds the same toy model twice: offline over the whole utterance, and streaming as a single feed whose left context covers it. With one chunk the band mask degenerates to full attention, the mean window covers every frame and the future taps reproduce the offline symmetric padding, so the two encoder outputs must match. Part of #310 --- src/arch/gigaam/encoder.cpp | 341 ++++++++++++++- src/arch/gigaam/encoder.h | 55 +++ tests/CMakeLists.txt | 16 + tests/gigaam_stream_encoder_unit.cpp | 608 +++++++++++++++++++++++++++ 4 files changed, 1008 insertions(+), 12 deletions(-) create mode 100644 tests/gigaam_stream_encoder_unit.cpp diff --git a/src/arch/gigaam/encoder.cpp b/src/arch/gigaam/encoder.cpp index b9bcea517..2ab2ed7a2 100644 --- a/src/arch/gigaam/encoder.cpp +++ b/src/arch/gigaam/encoder.cpp @@ -705,7 +705,9 @@ EncoderBuild build_zapformer_encoder_graph(ggml_context * ctx, // Streaming frontend: the offline graph's causal padding is replaced by the // cached rows of each conv input, so a feed consumes exactly 4 * chunk mel // frames and the caches carry the only cross-feed state. Feeding N chunks -// equals the offline causal frontend over the same mel frames. +// equals the offline causal frontend over the same mel frames. The tail rows +// are taken by count, not by valid count: only the final feed can be padded, +// and its caches are never consumed. ZapStreamFrontend build_zapformer_stream_frontend(ggml_context * ctx, const ZapformerFrontendWeights & fe, int64_t n_mels, @@ -997,15 +999,322 @@ EncoderBuild build_encoder_graph(ggml_context * ctx, return eb; } -void fill_zapformer_rope_tables(const EncoderBuild & eb, const GigaamHParams & hp) { - if (eb.zap_rope_in == nullptr) { +// --------------------------------------------------------------------------- +// Zapformer streaming encoder +// --------------------------------------------------------------------------- +// +// Mirrors _stream_layer / _forward_chunk of the reference: attention over the +// cached query/value history with the band mask, the conv module over the +// cached mean window with chunk-local future taps, and per-stage downsampling. +// All caches are graph inputs/outputs; the caller fills them from the previous +// feed. A feed always carries exactly `chunk` frontend frames (the final feed +// is zero-padded) so the graph shapes are static per context mode. + +namespace { + +ggml_tensor * stream_tail(ggml_context * ctx, ggml_tensor * t, int64_t rows, const char * name) { + if (rows <= 0) { + return nullptr; + } + ggml_tensor * v = ggml_view_4d(ctx, t, t->ne[0], rows, t->ne[2], t->ne[3], t->nb[1], t->nb[2], t->nb[3], + static_cast(t->ne[1] - rows) * t->nb[1]); + ggml_tensor * o = ggml_cont(ctx, v); + if (name != nullptr) { + ggml_set_name(o, name); + } + ggml_set_output(o); + return o; +} + +// Depthwise kernel as a contiguous [D, K] matrix: column k is tap k, which is +// the layout build_zapformer_conv transposes into [K, 1, 1, D]. +ggml_tensor * build_dw_matrix(ggml_context * ctx, ggml_tensor * w, int kernel, int64_t D) { + ggml_tensor * k = w; + if (k->type != GGML_TYPE_F32) { + k = ggml_cast(ctx, k, GGML_TYPE_F32); + } + return ggml_cont(ctx, ggml_transpose(ctx, ggml_reshape_2d(ctx, k, kernel, D))); // [D, K] +} + +ggml_tensor * build_zapformer_stream_attn(ggml_context * ctx, + ggml_tensor * history_q, + ggml_tensor * history_v, + ggml_tensor * rope, + ggml_tensor * attn_mask, + const ZapformerLayerWeights & lw, + const ZapformerStageHParams & shp, + int64_t n_past) { + const int64_t H = shp.n_heads; + const int64_t qdim = shp.qdim; + const int64_t vdim = shp.vdim; + const int64_t dq = H * qdim; + const int64_t dv = H * vdim; + const int64_t n_keys = history_q->ne[1]; + const int64_t T_q = n_keys - n_past; + const float scale = 1.0f / std::sqrt(static_cast(qdim)); + if (T_q <= 0 || n_past < 0) { + return nullptr; + } + + ggml_tensor * qk_norm = zap_rms_norm(ctx, history_q, lw.attn_in_norm_w); + ggml_tensor * qk = ggml_add(ctx, ggml_mul_mat(ctx, lw.attn_qk_in_w, qk_norm), lw.attn_qk_in_b); + ggml_tensor * qk_rot = ggml_mul_mat(ctx, rope, ggml_reshape_3d(ctx, qk, qdim, 2 * H, n_keys)); + ggml_prec_set_src(qk_rot, GGML_PREC_F32, 1); + + // q covers the current feed only; k covers the whole history. + ggml_tensor * q = ggml_view_4d(ctx, qk_rot, qdim, H, T_q, 1, qk_rot->nb[1], qk_rot->nb[2], qk_rot->nb[2] * T_q, + static_cast(n_past) * qk_rot->nb[2]); + ggml_tensor * k = ggml_view_4d(ctx, qk_rot, qdim, H, n_keys, 1, qk_rot->nb[1], qk_rot->nb[2], + qk_rot->nb[2] * n_keys, static_cast(dq) * ggml_element_size(qk_rot)); + + ggml_tensor * vg = ggml_add(ctx, ggml_mul_mat(ctx, lw.attn_vg_in_w, history_v), lw.attn_vg_in_b); + ggml_tensor * v_raw = ggml_view_3d(ctx, vg, dv, n_keys, 1, vg->nb[1], vg->nb[2], 0); + ggml_tensor * g_in = ggml_view_3d(ctx, vg, dv, n_keys, 1, vg->nb[1], vg->nb[2], dv * vg->nb[0]); + ggml_tensor * g_out = ggml_view_3d(ctx, vg, dv, n_keys, 1, vg->nb[1], vg->nb[2], 2 * dv * vg->nb[0]); + ggml_tensor * v = ggml_mul(ctx, v_raw, ggml_sigmoid(ctx, g_in)); + v = ggml_reshape_4d(ctx, v, vdim, H, n_keys, 1); + + q = ggml_cont(ctx, ggml_permute(ctx, q, 0, 2, 1, 3)); + k = ggml_cont(ctx, ggml_permute(ctx, k, 0, 2, 1, 3)); + v = ggml_cont(ctx, ggml_permute(ctx, v, 0, 2, 1, 3)); + + // Manual SDPA: the mask is a per-(key, query) band, not expressible as the + // offline padding mask, and this path works on every backend. + ggml_tensor * kq = ggml_mul_mat(ctx, k, q); + ggml_tensor * probs = ggml_soft_max_ext(ctx, ggml_add(ctx, kq, attn_mask), nullptr, scale, 0.0f); + ggml_tensor * v_t = ggml_cont(ctx, ggml_permute(ctx, v, 1, 0, 2, 3)); + ggml_tensor * o = ggml_mul_mat(ctx, v_t, probs); + o = ggml_cont(ctx, ggml_permute(ctx, o, 0, 2, 1, 3)); + o = ggml_reshape_3d(ctx, o, dv, T_q, 1); + + ggml_tensor * g_slice = + ggml_view_3d(ctx, g_out, dv, T_q, 1, g_out->nb[1], g_out->nb[2], static_cast(n_past) * g_out->nb[1]); + o = ggml_mul(ctx, o, ggml_sigmoid(ctx, g_slice)); + return ggml_add(ctx, ggml_mul_mat(ctx, lw.attn_out_w, o), lw.attn_out_b); +} + +ggml_tensor * build_zapformer_stream_conv(ggml_context * ctx, + ggml_tensor * x, + ggml_tensor * valid, + ggml_tensor * attn_mask, + ggml_tensor * mean_cache, + ggml_tensor * conv_cache, + const ZapformerLayerWeights & lw, + int kernel, + ggml_tensor ** mean_out, + ggml_tensor ** conv_out) { + const int64_t D = x->ne[0]; + const int64_t T = x->ne[1]; + const int64_t radius = (kernel - 1) / 2; + const int64_t cache_len = mean_cache->ne[1]; + + ggml_tensor * cg = ggml_add(ctx, ggml_mul_mat(ctx, lw.conv_in_w, x), lw.conv_in_b); + ggml_tensor * cx = ggml_view_3d(ctx, cg, D, T, 1, cg->nb[1], cg->nb[2], 0); + ggml_tensor * gate = ggml_view_3d(ctx, cg, D, T, 1, cg->nb[1], cg->nb[2], D * cg->nb[0]); + cx = valid != nullptr ? ggml_mul(ctx, cx, valid) : ggml_cont(ctx, cx); + + // Mean over the cached window. The mask is 0 / -INF, so exp(mask) is the + // 0/1 context indicator: masked keys drop out of both sums. + ggml_tensor * context = ggml_exp(ctx, attn_mask); + ggml_tensor * history = ggml_concat(ctx, mean_cache, cx, 1); + // sum[d, q] = sum_k history[d, k] * context[k, q] + ggml_tensor * history_t = ggml_cont(ctx, ggml_transpose(ctx, history)); + ggml_tensor * sum = ggml_mul_mat(ctx, history_t, context); + // count[q] = sum_k context[k, q] + ggml_tensor * ones = ggml_fill(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, history->ne[1], 1), 1.0f); + ggml_tensor * count = ggml_clamp(ctx, ggml_mul_mat(ctx, ones, context), 1.0f, 1e30f); + ggml_tensor * mean = ggml_mul(ctx, ggml_div(ctx, sum, count), lw.conv_weighted_mean_w); + + // Causal depthwise conv over [conv cache | x] with the first radius + 1 + // taps, then the future taps of the same chunk (zero past its end). + ggml_tensor * joined = conv_cache != nullptr ? ggml_concat(ctx, conv_cache, cx, 1) : cx; + ggml_tensor * kmat = build_dw_matrix(ctx, lw.conv_dw_w, kernel, D); // [D, K] + const size_t tap = static_cast(D) * ggml_element_size(kmat); + // The first radius + 1 taps are a contiguous prefix of the [D, K] buffer. + ggml_tensor * causal = ggml_permute( + ctx, ggml_reshape_4d(ctx, ggml_view_2d(ctx, kmat, D, radius + 1, tap, 0), D, 1, 1, radius + 1), 3, 1, 2, 0); + ggml_tensor * jw = ggml_permute(ctx, ggml_reshape_4d(ctx, joined, D, radius + T, 1, 1), 2, 0, 1, 3); + ggml_tensor * yw = ggml_conv_2d_dw_direct(ctx, causal, jw, 1, 1, 0, 0, 1, 1); + ggml_tensor * y = ggml_reshape_3d(ctx, ggml_permute(ctx, yw, 1, 2, 0, 3), D, T, 1); + y = ggml_add(ctx, y, lw.conv_dw_b); + + ggml_tensor * zeros = ggml_fill(ctx, ggml_new_tensor_3d(ctx, GGML_TYPE_F32, D, radius, 1), 0.0f); + ggml_tensor * padded = ggml_concat(ctx, cx, zeros, 1); + for (int64_t j = 1; j <= radius; ++j) { + ggml_tensor * shifted = + ggml_view_3d(ctx, padded, D, T, 1, padded->nb[1], padded->nb[2], static_cast(j) * padded->nb[1]); + ggml_tensor * w = ggml_view_3d(ctx, kmat, D, 1, 1, tap, tap, static_cast(radius + j) * tap); + y = ggml_add(ctx, y, ggml_mul(ctx, shifted, w)); + } + + y = ggml_add(ctx, y, mean); + y = ggml_mul(ctx, y, ggml_sigmoid(ctx, gate)); + y = ggml_silu(ctx, y); + + *mean_out = stream_tail(ctx, history, cache_len, "zap.stream.mean.next"); + *conv_out = radius > 0 ? stream_tail(ctx, joined, radius, "zap.stream.conv.next") : nullptr; + return ggml_add(ctx, ggml_mul_mat(ctx, lw.conv_out_w, y), lw.conv_out_b); +} + +ggml_tensor * build_zapformer_stream_layer(ggml_context * ctx, + ggml_tensor * x, + ggml_tensor * rope, + ggml_tensor * attn_mask, + ggml_tensor * valid, + const ZapformerLayerWeights & lw, + const ZapformerStageHParams & shp, + int64_t n_past, + int64_t cache_len, + ggml_tensor * query_in, + ggml_tensor * value_in, + ggml_tensor * mean_in, + ggml_tensor * conv_in, + ZapStreamLayerIO * io) { + ggml_tensor * residual = x; + ggml_tensor * qk = x; + + x = ggml_add(ctx, x, conf::feed_forward(ctx, x, lw.ff1_in_w, lw.ff1_in_b, lw.ff1_out_w, lw.ff1_out_b)); + + ggml_tensor * history_q = ggml_concat(ctx, query_in, qk, 1); + ggml_tensor * history_v = ggml_concat(ctx, value_in, x, 1); + io->query_out = stream_tail(ctx, history_q, cache_len, "zap.stream.query.next"); + io->value_out = stream_tail(ctx, history_v, cache_len, "zap.stream.value.next"); + + ggml_tensor * attn = build_zapformer_stream_attn(ctx, history_q, history_v, rope, attn_mask, lw, shp, n_past); + if (attn == nullptr) { + return nullptr; + } + x = ggml_add(ctx, x, attn); + + if (shp.conv_kernel > 0) { + x = ggml_add(ctx, x, + build_zapformer_stream_conv(ctx, x, valid, attn_mask, mean_in, conv_in, lw, shp.conv_kernel, + &io->mean_out, &io->conv_out)); + x = ggml_add(ctx, x, conf::feed_forward(ctx, x, lw.ff2_in_w, lw.ff2_in_b, lw.ff2_out_w, lw.ff2_out_b)); + } + + ggml_tensor * blended = ggml_add(ctx, residual, ggml_scale(ctx, ggml_sub(ctx, x, residual), 0.25f)); + return zap_rms_norm(ctx, blended, lw.out_norm_w); +} + +} // namespace + +ZapStreamEncoder build_zapformer_stream_encoder(ggml_context * ctx, + const GigaamWeights & w, + const GigaamHParams & hp, + int64_t chunk, + StreamContext geom, + bool direct_conv) { + ZapStreamEncoder se{}; + if (ctx == nullptr || chunk <= 0 || geom.chunk <= 0 || geom.left < 0 || hp.zap_stages.empty() || + w.zapformer.stages.size() != hp.zap_stages.size()) { + return se; + } + + se.frontend = build_zapformer_stream_frontend(ctx, w.zapformer.frontend, hp.fe_num_mels, chunk, direct_conv); + if (se.frontend.out == nullptr) { + return ZapStreamEncoder{}; + } + ggml_tensor * x = se.frontend.out; + const int64_t d_model = x->ne[0]; + + se.valid_in = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, chunk); + ggml_set_name(se.valid_in, "zap.stream.valid"); + ggml_set_input(se.valid_in); + + for (size_t s = 0; s < hp.zap_stages.size(); ++s) { + const auto & shp = hp.zap_stages[s]; + const auto & sw = w.zapformer.stages[s]; + const int64_t ds = shp.downsampling; + const bool bad_kernel = shp.conv_kernel < 0 || (shp.conv_kernel > 0 && shp.conv_kernel % 2 == 0); + if (ds <= 0 || chunk % ds != 0 || shp.n_layers < 0 || shp.dim <= 0 || shp.n_heads <= 0 || shp.qdim <= 0 || + shp.qdim % 2 != 0 || shp.vdim <= 0 || bad_kernel || + shp.residual_scales.size() != static_cast(shp.n_layers) + 1 || + sw.layers.size() != static_cast(shp.n_layers)) { + return ZapStreamEncoder{}; + } + const int64_t T_s = chunk / ds; + const int64_t cache_len = geom.left / ds; + const int64_t n_keys = cache_len + T_s; + const int64_t radius = shp.conv_kernel > 0 ? (shp.conv_kernel - 1) / 2 : 0; + // A zero-length window would make the band mask meaningless, and a + // kernel longer than the feed leaves no conv output. + if (cache_len <= 0 || (shp.conv_kernel > 0 && radius >= T_s)) { + return ZapStreamEncoder{}; + } + + ZapStreamStageIO st{}; + st.T_s = T_s; + st.n_keys = n_keys; + st.attn_mask = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_keys, T_s); + ggml_set_name(st.attn_mask, "zap.stream.attn_mask"); + ggml_set_input(st.attn_mask); + st.rope = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, shp.qdim, shp.qdim, n_keys); + ggml_set_name(st.rope, "zap.stream.rope"); + ggml_set_input(st.rope); + // valid frames at this stage: valid_in[t * ds] + ggml_tensor * grouped = ggml_reshape_3d(ctx, se.valid_in, ds, T_s, 1); + st.valid = ggml_view_3d(ctx, grouped, 1, T_s, 1, static_cast(ds) * ggml_element_size(grouped), + grouped->nb[2], 0); + se.stages.push_back(st); + + // Padded frames must not leak into the grouped channels. + if (ds > 1) { + x = ggml_mul(ctx, x, se.valid_in); + x = ggml_reshape_3d(ctx, x, d_model * ds, T_s, 1); + } + + ggml_tensor * stack_res = x; + x = ggml_mul_mat(ctx, sw.proj_w, x); + ggml_tensor * bypass = ggml_scale(ctx, x, shp.residual_scales.front()); + x = ggml_scale(ctx, x, shp.input_scale); + + const int64_t D_layer = x->ne[0]; + for (int l = 0; l < shp.n_layers; ++l) { + ZapStreamLayerIO lio{}; + lio.query_in = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, D_layer, cache_len, 1); + lio.value_in = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, D_layer, cache_len, 1); + ggml_set_input(lio.query_in); + ggml_set_input(lio.value_in); + if (shp.conv_kernel > 0) { + lio.mean_in = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, D_layer, cache_len, 1); + ggml_set_input(lio.mean_in); + } + if (radius > 0) { + lio.conv_in = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, D_layer, radius, 1); + ggml_set_input(lio.conv_in); + } + x = build_zapformer_stream_layer(ctx, x, se.stages[s].rope, se.stages[s].attn_mask, se.stages[s].valid, + sw.layers[l], shp, cache_len, cache_len, lio.query_in, lio.value_in, + lio.mean_in, lio.conv_in, &lio); + bypass = ggml_add(ctx, bypass, ggml_scale(ctx, x, shp.residual_scales[l + 1])); + se.layers.push_back(lio); + } + + x = ggml_add(ctx, stack_res, ggml_mul_mat(ctx, sw.proj_out_w, bypass)); + if (ds > 1) { + x = ggml_reshape_3d(ctx, x, d_model, chunk, 1); + } + } + + x = ggml_rms_norm(ctx, x, hp.zap_out_norm_eps * hp.zap_out_norm_eps); + x = ggml_scale(ctx, x, hp.zap_out_norm_scale); + + ggml_set_name(x, "zap.stream.encoded"); + ggml_set_output(x); + se.out = x; + return se; +} + +void fill_zapformer_stream_rope(ggml_tensor * rope, const GigaamHParams & hp, int64_t first, int64_t step) { + if (rope == nullptr) { return; } - const int64_t qdim = eb.zap_rope_in->ne[0]; + const int64_t qdim = rope->ne[0]; const int64_t half = qdim / 2; - const int64_t T = eb.zap_rope_in->ne[2]; + const int64_t count = rope->ne[2]; const int64_t per_t = qdim * qdim; - std::vector rot(static_cast(per_t * T), 0.0f); + std::vector rot(static_cast(per_t * count), 0.0f); // RoPETable in modeling_gigaam.py, in F32, then rounded through F16 as the // checkpoint stores it. Up to position 824 this equals the checkpoint's // tables bit for bit (two later entries differ by one F16 ulp); a window @@ -1013,21 +1322,29 @@ void fill_zapformer_rope_tables(const EncoderBuild & eb, const GigaamHParams & h for (int64_t i = 0; i < half; ++i) { const float inv_freq = 1.0f / std::pow(hp.zap_rope_base, static_cast(2 * i) / static_cast(2 * half)); - for (int64_t t = 0; t < T; ++t) { - const float angle = static_cast(t) * inv_freq; - const float c = ggml_fp16_to_fp32(ggml_fp32_to_fp16(std::cos(angle))); - const float s = ggml_fp16_to_fp32(ggml_fp32_to_fp16(std::sin(angle))); + for (int64_t t = 0; t < count; ++t) { + const int64_t pos = std::max(0, first + t * step); + const float angle = static_cast(pos) * inv_freq; + const float c = ggml_fp16_to_fp32(ggml_fp32_to_fp16(std::cos(angle))); + const float s = ggml_fp16_to_fp32(ggml_fp32_to_fp16(std::sin(angle))); // Element (k, j) of rotation t, at k + qdim * j, weighs input lane // k in output lane j: y[2i] = x[2i] c - x[2i+1] s and // y[2i+1] = x[2i] s + x[2i+1] c, as apply_rope computes them. - float * r = rot.data() + t * per_t; + float * r = rot.data() + t * per_t; r[2 * i + qdim * (2 * i)] = c; r[2 * i + 1 + qdim * (2 * i)] = -s; r[2 * i + qdim * (2 * i + 1)] = s; r[2 * i + 1 + qdim * (2 * i + 1)] = c; } } - ggml_backend_tensor_set(eb.zap_rope_in, rot.data(), 0, rot.size() * sizeof(float)); + ggml_backend_tensor_set(rope, rot.data(), 0, rot.size() * sizeof(float)); +} + +void fill_zapformer_rope_tables(const EncoderBuild & eb, const GigaamHParams & hp) { + if (eb.zap_rope_in == nullptr) { + return; + } + fill_zapformer_stream_rope(eb.zap_rope_in, hp, 0, 1); } } // namespace transcribe::gigaam diff --git a/src/arch/gigaam/encoder.h b/src/arch/gigaam/encoder.h index 1997b5fc8..20049770d 100644 --- a/src/arch/gigaam/encoder.h +++ b/src/arch/gigaam/encoder.h @@ -3,6 +3,7 @@ #pragma once #include "ggml.h" +#include "stream.h" #include #include @@ -130,4 +131,58 @@ ZapStreamFrontend build_zapformer_stream_frontend(ggml_context * int64_t chunk, bool direct_conv); +// Per-layer streaming caches. `query`/`value` hold the last left/ds frames of +// the attention history, `mean` the same slice of the conv input, `conv` the +// depthwise conv's past taps. Inputs are filled before compute; outputs carry +// the same shapes and feed the next call. `conv_*` are null for a layer +// without a conv module or with a context-free kernel (kernel 1). +struct ZapStreamLayerIO { + ggml_tensor * query_in = nullptr; + ggml_tensor * value_in = nullptr; + ggml_tensor * mean_in = nullptr; + ggml_tensor * conv_in = nullptr; + ggml_tensor * query_out = nullptr; + ggml_tensor * value_out = nullptr; + ggml_tensor * mean_out = nullptr; + ggml_tensor * conv_out = nullptr; +}; + +// Per-stage streaming inputs: the band mask [n_keys, T_s], the RoPE rotations +// for the history positions [qdim, qdim, n_keys], and the valid-frame mask +// [1, T_s]. +struct ZapStreamStageIO { + int64_t T_s = 0; + int64_t n_keys = 0; + ggml_tensor * attn_mask = nullptr; + ggml_tensor * rope = nullptr; + ggml_tensor * valid = nullptr; +}; + +// Streaming encoder over one feed of `chunk` frontend frames: the frontend +// plus every stage, wired with per-layer caches. `valid_in` is [1, chunk] +// (1 real / 0 padding), shared by the stages; frames past the valid count must +// be zero in the mel input too, because the conv mean would spread a NaN. +// Caches must be zeroed before the first feed: the band mask's all-masked +// fallback keeps a padded query finite, which assumes finite cached values. +struct ZapStreamEncoder { + ZapStreamFrontend frontend; + ggml_tensor * valid_in = nullptr; + std::vector stages; + std::vector layers; // in encoder layer order + ggml_tensor * out = nullptr; // [d_model, chunk, 1] +}; + +ZapStreamEncoder build_zapformer_stream_encoder(ggml_context * ctx, + const GigaamWeights & w, + const GigaamHParams & hp, + int64_t chunk, + StreamContext geom, + bool direct_conv); + +// Fill `rope` (ne=[qdim, qdim, count]) with the rotations for positions +// first, first + step, ... in *stage* frames, clamped at 0 as the reference +// does. The offline table and the streaming history both use step=1; a stage +// with downsampling d asks for first = position/d - cache_len. +void fill_zapformer_stream_rope(ggml_tensor * rope, const GigaamHParams & hp, int64_t first, int64_t step); + } // namespace transcribe::gigaam diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5c1d57ea3..9db7d6705 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1842,6 +1842,22 @@ transcribe_apply_warnings(transcribe_gigaam_stream_frontend_unit) add_test(NAME transcribe_gigaam_stream_frontend_unit COMMAND transcribe_gigaam_stream_frontend_unit) +# ----------------------------------------------------------------------------- +# GigaAM-v4 streaming encoder: one chunk equals the offline graph +# ----------------------------------------------------------------------------- + +add_executable(transcribe_gigaam_stream_encoder_unit + gigaam_stream_encoder_unit.cpp) + +target_link_libraries(transcribe_gigaam_stream_encoder_unit PRIVATE transcribe ggml) + +target_include_directories(transcribe_gigaam_stream_encoder_unit PRIVATE + ${CMAKE_SOURCE_DIR}/src) + +transcribe_apply_warnings(transcribe_gigaam_stream_encoder_unit) + +add_test(NAME transcribe_gigaam_stream_encoder_unit COMMAND transcribe_gigaam_stream_encoder_unit) + # ----------------------------------------------------------------------------- # Tokenizer decode-only mode unit test # ----------------------------------------------------------------------------- diff --git a/tests/gigaam_stream_encoder_unit.cpp b/tests/gigaam_stream_encoder_unit.cpp new file mode 100644 index 000000000..7336031c7 --- /dev/null +++ b/tests/gigaam_stream_encoder_unit.cpp @@ -0,0 +1,608 @@ +// gigaam_stream_encoder_unit.cpp - one streaming chunk equals the offline +// encoder. +// +// With a single feed covering the whole utterance and a left context at least +// as long as the utterance, the streaming graph's band mask degenerates to +// full attention, the conv mean window covers every frame and the chunk-local +// future taps reproduce the offline symmetric padding. The two graphs must +// therefore agree; any difference points at the cache wiring, the RoPE +// positions or the conv assembly. + +#include "arch/gigaam/encoder.h" +#include "arch/gigaam/weights.h" +#include "ggml-backend.h" +#include "ggml-cpu.h" +#include "ggml.h" + +#include +#include +#include +#include +#include + +namespace { + +int g_failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + ++g_failures; \ + } \ + } while (0) + +struct Lcg { + unsigned state = 0x12345678u; + + float next() { + state = state * 1664525u + 1013904223u; + return (static_cast((state >> 8) & 0xffffu) / 65535.0f - 0.5f); + } +}; + +constexpr int64_t kMels = 8; +constexpr int64_t kChannels = 4; // frontend channels for the last conv +constexpr int64_t kDModel = 8; +constexpr int64_t kStageDim = 8; +constexpr int64_t kHeads = 2; +constexpr int64_t kQDim = 4; +constexpr int64_t kVDim = 4; +constexpr int64_t kFFDim = 16; +constexpr int64_t kKernel = 3; + +struct Tensors { + std::vector all; + std::vector elems; +}; + +ggml_tensor * add_tensor(ggml_context * ctx, Tensors & t, int n_dims, const int64_t * ne) { + ggml_tensor * x = nullptr; + switch (n_dims) { + case 1: + x = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ne[0]); + break; + case 2: + x = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, ne[0], ne[1]); + break; + case 3: + x = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, ne[0], ne[1], ne[2]); + break; + default: + x = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, ne[0], ne[1], ne[2], ne[3]); + break; + } + t.all.push_back(x); + t.elems.push_back(static_cast(ggml_nelements(x))); + return x; +} + +transcribe::gigaam::ZapformerFrontendWeights make_frontend(ggml_context * ctx, Tensors & t) { + transcribe::gigaam::ZapformerFrontendWeights fe{}; + const int64_t c0 = 2; + const int64_t c1 = 2; + const int64_t conv0_w[4] = { 3, 3, 1, c0 }; + const int64_t conv1_w[4] = { 3, 3, c0, c1 }; + const int64_t conv2_w[4] = { 3, 3, c1, kChannels }; + const int64_t cn_dw[4] = { 3, 3, 1, kChannels }; + const int64_t cn_pw1[4] = { 1, 1, kChannels, 3 * kChannels }; + const int64_t cn_pw2[4] = { 1, 1, 3 * kChannels, kChannels }; + const int64_t out_w[2] = { kChannels, kDModel }; + const int64_t cn_pw1_b_n = 3 * kChannels; + const int64_t c0n = c0; + const int64_t c1n = c1; + const int64_t cn_n = kChannels; + + fe.conv0_w = add_tensor(ctx, t, 4, conv0_w); + fe.conv0_b = add_tensor(ctx, t, 1, &c0n); + fe.conv1_w = add_tensor(ctx, t, 4, conv1_w); + fe.conv1_b = add_tensor(ctx, t, 1, &c1n); + fe.conv2_w = add_tensor(ctx, t, 4, conv2_w); + fe.conv2_b = add_tensor(ctx, t, 1, &cn_n); + fe.cn_dw_w = add_tensor(ctx, t, 4, cn_dw); + fe.cn_dw_b = add_tensor(ctx, t, 1, &cn_n); + fe.cn_pw1_w = add_tensor(ctx, t, 4, cn_pw1); + fe.cn_pw1_b = add_tensor(ctx, t, 1, &cn_pw1_b_n); + fe.cn_pw2_w = add_tensor(ctx, t, 4, cn_pw2); + fe.cn_pw2_b = add_tensor(ctx, t, 1, &cn_n); + fe.out_w = add_tensor(ctx, t, 2, out_w); + fe.out_b = add_tensor(ctx, t, 1, &kDModel); + return fe; +} + +transcribe::gigaam::ZapformerStageWeights make_stage(ggml_context * ctx, Tensors & t, int64_t in_dim, int64_t kernel) { + transcribe::gigaam::ZapformerStageWeights sw{}; + const int64_t d = kStageDim; + const int64_t ffd = kFFDim; + const int64_t dq = kHeads * kQDim; + const int64_t dv = kHeads * kVDim; + const int64_t proj_in[2] = { in_dim, d }; + const int64_t proj_out[2] = { d, in_dim }; + const int64_t ff_in[2] = { d, ffd }; + const int64_t ff_out[2] = { ffd, d }; + const int64_t qk[2] = { d, 2 * dq }; + const int64_t vg[2] = { d, 3 * dv }; + const int64_t ao[2] = { dv, d }; + const int64_t cg[2] = { d, 2 * d }; + const int64_t dw[4] = { kernel, 1, 1, d }; + const int64_t co[2] = { d, d }; + const int64_t qk_b_n = 2 * dq; + const int64_t vg_b_n = 3 * dv; + const int64_t cg_b_n = 2 * d; + + sw.proj_w = add_tensor(ctx, t, 2, proj_in); + sw.proj_out_w = add_tensor(ctx, t, 2, proj_out); + + transcribe::gigaam::ZapformerLayerWeights lw{}; + lw.ff1_in_w = add_tensor(ctx, t, 2, ff_in); + lw.ff1_in_b = add_tensor(ctx, t, 1, &ffd); + lw.ff1_out_w = add_tensor(ctx, t, 2, ff_out); + lw.ff1_out_b = add_tensor(ctx, t, 1, &d); + lw.attn_in_norm_w = add_tensor(ctx, t, 1, &d); + lw.attn_qk_in_w = add_tensor(ctx, t, 2, qk); + lw.attn_qk_in_b = add_tensor(ctx, t, 1, &qk_b_n); + lw.attn_vg_in_w = add_tensor(ctx, t, 2, vg); + lw.attn_vg_in_b = add_tensor(ctx, t, 1, &vg_b_n); + lw.attn_out_w = add_tensor(ctx, t, 2, ao); + lw.attn_out_b = add_tensor(ctx, t, 1, &d); + lw.conv_in_w = add_tensor(ctx, t, 2, cg); + lw.conv_in_b = add_tensor(ctx, t, 1, &cg_b_n); + lw.conv_dw_w = add_tensor(ctx, t, 4, dw); + lw.conv_dw_b = add_tensor(ctx, t, 1, &d); + lw.conv_weighted_mean_w = add_tensor(ctx, t, 1, &d); + lw.conv_out_w = add_tensor(ctx, t, 2, co); + lw.conv_out_b = add_tensor(ctx, t, 1, &d); + lw.ff2_in_w = add_tensor(ctx, t, 2, ff_in); + lw.ff2_in_b = add_tensor(ctx, t, 1, &ffd); + lw.ff2_out_w = add_tensor(ctx, t, 2, ff_out); + lw.ff2_out_b = add_tensor(ctx, t, 1, &d); + lw.out_norm_w = add_tensor(ctx, t, 1, &d); + + sw.layers.push_back(lw); + return sw; +} + +void fill(Tensors & t, ggml_backend_t backend) { + Lcg rng; + std::vector buf; + for (size_t i = 0; i < t.all.size(); ++i) { + buf.resize(t.elems[i]); + for (float & v : buf) { + v = rng.next(); + } + ggml_backend_tensor_set(t.all[i], buf.data(), 0, buf.size() * sizeof(float)); + } +} + +transcribe::gigaam::GigaamHParams make_hparams() { + using namespace transcribe::gigaam; + GigaamHParams hp; + hp.encoder_kind = EncoderKind::Zapformer; + hp.fe_num_mels = static_cast(kMels); + hp.zap_causal_frontend = true; + hp.zap_max_downsampling = 1; + hp.zap_out_norm_scale = 0.2f; + hp.zap_out_norm_eps = 0.1f; + hp.zap_rope_base = 10000.0f; + + ZapformerStageHParams st; + st.n_layers = 1; + st.dim = static_cast(kStageDim); + st.n_heads = static_cast(kHeads); + st.qdim = static_cast(kQDim); + st.vdim = static_cast(kVDim); + st.ff_mult = static_cast(kFFDim / kStageDim); + st.conv_kernel = static_cast(kKernel); + st.downsampling = 1; + st.input_scale = 1.0f; + st.residual_scales = { 1.0f, 1.0f }; + hp.zap_stages.push_back(st); + + // Second stage downsamples by 2, which also pins the RoPE position grid: + // rotations advance one per stage frame, not one per frontend frame. + transcribe::gigaam::ZapformerStageHParams st2 = st; + st2.downsampling = 2; + hp.zap_stages.push_back(st2); + hp.zap_max_downsampling = 2; + return hp; +} + +void make_stages(ggml_context * ctx, + Tensors & t, + const transcribe::gigaam::GigaamHParams & hp, + transcribe::gigaam::GigaamWeights & w) { + for (size_t i = 0; i < hp.zap_stages.size(); ++i) { + const int64_t in_dim = static_cast(hp.zap_stages[i].downsampling) * kDModel; + const int64_t kernel = hp.zap_stages[i].conv_kernel > 0 ? hp.zap_stages[i].conv_kernel : 3; + w.zapformer.stages.push_back(make_stage(ctx, t, in_dim, kernel)); + } +} + +std::vector make_mel(int64_t frames) { + Lcg rng; + std::vector mel(static_cast(kMels * frames)); + for (float & v : mel) { + v = rng.next(); + } + return mel; +} + +bool run_offline(const transcribe::gigaam::GigaamHParams & hp, + const std::vector & mel, + int64_t frames, + std::vector & out) { + ggml_init_params params{ 128u * 1024 * 1024, nullptr, true }; + ggml_context * ctx = ggml_init(params); + if (ctx == nullptr) { + return false; + } + Tensors t{}; + transcribe::gigaam::GigaamWeights w{}; + w.zapformer.frontend = make_frontend(ctx, t); + make_stages(ctx, t, hp, w); + + transcribe::gigaam::EncoderBuild eb = + transcribe::gigaam::build_encoder_graph(ctx, w, hp, static_cast(frames), GGML_TYPE_COUNT, "CPU", 1, false); + if (eb.out == nullptr || eb.mel_in == nullptr) { + ggml_free(ctx); + return false; + } + + ggml_backend_t backend = ggml_backend_cpu_init(); + ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, backend); + if (buf == nullptr) { + ggml_backend_free(backend); + ggml_free(ctx); + return false; + } + ggml_backend_buffer_clear(buf, 0); + fill(t, backend); + ggml_backend_tensor_set(eb.mel_in, mel.data(), 0, mel.size() * sizeof(float)); + transcribe::gigaam::fill_zapformer_rope_tables(eb, hp); + + ggml_cgraph * graph = ggml_new_graph_custom(ctx, 8192, false); + ggml_build_forward_expand(graph, eb.out); + bool ok = ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS; + if (ok) { + out.resize(static_cast(ggml_nelements(eb.out))); + ggml_backend_tensor_get(eb.out, out.data(), 0, out.size() * sizeof(float)); + } + ggml_backend_buffer_free(buf); + ggml_backend_free(backend); + ggml_free(ctx); + return ok; +} + +void fill_full_valid(const transcribe::gigaam::ZapStreamFrontend & fe, ggml_backend_t backend) { + for (ggml_tensor * mask : fe.valid_in) { + std::vector v(static_cast(mask->ne[1]), 1.0f); + ggml_backend_tensor_set(mask, v.data(), 0, v.size() * sizeof(float)); + } +} + +void fill_stream_inputs(const transcribe::gigaam::ZapStreamEncoder & se, + const transcribe::gigaam::GigaamHParams & hp, + int64_t chunk, + int64_t left, + int64_t position, + ggml_backend_t backend) { + std::vector valid(static_cast(chunk), 1.0f); + ggml_backend_tensor_set(se.valid_in, valid.data(), 0, valid.size() * sizeof(float)); + fill_full_valid(se.frontend, backend); + for (size_t s = 0; s < se.stages.size(); ++s) { + const auto & st = se.stages[s]; + const int64_t ds = hp.zap_stages[s].downsampling; + const int64_t n_past = left / ds; + const int64_t past_ok = std::min(position / ds, n_past); + std::vector mask(static_cast(st.n_keys * st.T_s)); + transcribe::gigaam::stream_attn_bias_f32(mask.data(), static_cast(st.T_s), static_cast(st.n_keys), + position, static_cast(ds), static_cast(n_past), + static_cast(past_ok), static_cast(st.T_s), + { static_cast(chunk), static_cast(left) }); + ggml_backend_tensor_set(st.attn_mask, mask.data(), 0, mask.size() * sizeof(float)); + transcribe::gigaam::fill_zapformer_stream_rope(st.rope, hp, position / ds - n_past, /*step=*/1); + } +} + +void copy_tensor(ggml_tensor * src, ggml_tensor * dst) { + if (src == nullptr || dst == nullptr) { + return; + } + std::vector buf(static_cast(ggml_nelements(src))); + ggml_backend_tensor_get(src, buf.data(), 0, buf.size() * sizeof(float)); + ggml_backend_tensor_set(dst, buf.data(), 0, buf.size() * sizeof(float)); +} + +bool run_two_feeds(const transcribe::gigaam::GigaamHParams & hp, + const std::vector & mel_a, + const std::vector & mel_b, + int64_t chunk, + int64_t left, + std::vector & out_b, + std::vector & q_cache, + std::vector & v_cache) { + if (mel_a.size() != static_cast(4 * chunk * kMels) || mel_b.size() != mel_a.size()) { + return false; + } + ggml_init_params params{ 128u * 1024 * 1024, nullptr, true }; + ggml_context * ctx = ggml_init(params); + if (ctx == nullptr) { + return false; + } + Tensors t{}; + transcribe::gigaam::GigaamWeights w{}; + w.zapformer.frontend = make_frontend(ctx, t); + make_stages(ctx, t, hp, w); + const transcribe::gigaam::StreamContext geom{ static_cast(chunk), static_cast(left) }; + auto fa = transcribe::gigaam::build_zapformer_stream_encoder(ctx, w, hp, chunk, geom, false); + auto fb = transcribe::gigaam::build_zapformer_stream_encoder(ctx, w, hp, chunk, geom, false); + if (fa.out == nullptr || fb.out == nullptr) { + ggml_free(ctx); + return false; + } + + ggml_backend_t backend = ggml_backend_cpu_init(); + ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, backend); + if (buf == nullptr) { + ggml_backend_free(backend); + ggml_free(ctx); + return false; + } + ggml_backend_buffer_clear(buf, 0); + fill(t, backend); + ggml_backend_tensor_set(fa.frontend.mel_in, mel_a.data(), 0, mel_a.size() * sizeof(float)); + ggml_backend_tensor_set(fb.frontend.mel_in, mel_b.data(), 0, mel_b.size() * sizeof(float)); + fill_stream_inputs(fa, hp, chunk, left, 0, backend); + fill_stream_inputs(fb, hp, chunk, left, chunk, backend); + + auto make_graph = [&](const transcribe::gigaam::ZapStreamEncoder & se) { + ggml_cgraph * g = ggml_new_graph_custom(ctx, 8192, false); + ggml_build_forward_expand(g, se.out); + for (ggml_tensor * c : se.frontend.cache_out) { + ggml_build_forward_expand(g, c); + } + for (const auto & l : se.layers) { + for (ggml_tensor * c : { l.query_out, l.value_out, l.mean_out, l.conv_out }) { + if (c != nullptr) { + ggml_build_forward_expand(g, c); + } + } + } + return g; + }; + + bool ok = ggml_backend_graph_compute(backend, make_graph(fa)) == GGML_STATUS_SUCCESS; + auto read = [&](ggml_tensor * x, std::vector & v) { + if (x == nullptr) { + v.clear(); + return; + } + v.resize(static_cast(ggml_nelements(x))); + ggml_backend_tensor_get(x, v.data(), 0, v.size() * sizeof(float)); + }; + if (ok) { + read(fa.layers.front().query_out, q_cache); + read(fa.layers.front().value_out, v_cache); + for (int i = 0; i < 4; ++i) { + copy_tensor(fa.frontend.cache_out[i], fb.frontend.cache_in[i]); + } + for (size_t l = 0; l < fa.layers.size(); ++l) { + copy_tensor(fa.layers[l].query_out, fb.layers[l].query_in); + copy_tensor(fa.layers[l].value_out, fb.layers[l].value_in); + copy_tensor(fa.layers[l].mean_out, fb.layers[l].mean_in); + copy_tensor(fa.layers[l].conv_out, fb.layers[l].conv_in); + } + ok = ggml_backend_graph_compute(backend, make_graph(fb)) == GGML_STATUS_SUCCESS; + if (ok) { + read(fb.out, out_b); + } + } + + ggml_backend_buffer_free(buf); + ggml_backend_free(backend); + ggml_free(ctx); + return ok; +} + +void test_cache_is_carried() { + const auto hp = make_hparams(); + const int64_t chunk = 4; + const int64_t left = 8; + std::vector mel_a = make_mel(4 * chunk); + std::vector mel_a2 = mel_a; + for (float & v : mel_a2) { + v += 0.5f; + } + const std::vector mel_b = make_mel(4 * chunk); + + std::vector out1, out2, q1, v1, q2, v2; + CHECK(run_two_feeds(hp, mel_a, mel_b, chunk, left, out1, q1, v1)); + CHECK(run_two_feeds(hp, mel_a2, mel_b, chunk, left, out2, q2, v2)); + CHECK(!out1.empty() && out1.size() == out2.size()); + + auto max_diff = [](const std::vector & a, const std::vector & b) { + float d = 0.0f; + for (size_t i = 0; i < a.size() && i < b.size(); ++i) { + d = std::max(d, std::fabs(a[i] - b[i])); + } + return d; + }; + // The carried caches must change the next feed's output. + CHECK(max_diff(out1, out2) > 1e-6f); + // The query cache holds the pre-FF1 history, not the value history. + CHECK(max_diff(q1, v1) > 1e-6f); + // And it is the first feed's history: a different first feed changes it. + CHECK(max_diff(q1, q2) > 1e-6f); + + // A context-free kernel has no conv cache; carrying the null caches into + // the second feed must still work. + auto hp1 = hp; + hp1.zap_stages.resize(1); + hp1.zap_stages[0].conv_kernel = 1; + hp1.zap_max_downsampling = 1; + std::vector out3, q3, v3; + CHECK(run_two_feeds(hp1, mel_a, mel_b, chunk, left, out3, q3, v3)); +} + +bool run_streaming(const transcribe::gigaam::GigaamHParams & hp, + const std::vector & mel, + int64_t frames, + int64_t chunk, + int64_t left, + std::vector & out) { + if (frames != 4 * chunk) { + return false; + } + ggml_init_params params{ 128u * 1024 * 1024, nullptr, true }; + ggml_context * ctx = ggml_init(params); + if (ctx == nullptr) { + return false; + } + Tensors t{}; + transcribe::gigaam::GigaamWeights w{}; + w.zapformer.frontend = make_frontend(ctx, t); + make_stages(ctx, t, hp, w); + + transcribe::gigaam::ZapStreamEncoder se = transcribe::gigaam::build_zapformer_stream_encoder( + ctx, w, hp, chunk, transcribe::gigaam::StreamContext{ static_cast(chunk), static_cast(left) }, + /*direct_conv=*/false); + if (se.out == nullptr) { + ggml_free(ctx); + return false; + } + + ggml_backend_t backend = ggml_backend_cpu_init(); + ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, backend); + if (buf == nullptr) { + ggml_backend_free(backend); + ggml_free(ctx); + return false; + } + ggml_backend_buffer_clear(buf, 0); + fill(t, backend); + ggml_backend_tensor_set(se.frontend.mel_in, mel.data(), 0, mel.size() * sizeof(float)); + fill_stream_inputs(se, hp, chunk, left, /*position=*/0, backend); + + ggml_cgraph * graph = ggml_new_graph_custom(ctx, 8192, false); + ggml_build_forward_expand(graph, se.out); + for (ggml_tensor * c : se.frontend.cache_out) { + ggml_build_forward_expand(graph, c); + } + for (const auto & layer : se.layers) { + for (ggml_tensor * c : { layer.query_out, layer.value_out, layer.mean_out, layer.conv_out }) { + if (c != nullptr) { + ggml_build_forward_expand(graph, c); + } + } + } + bool ok = ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS; + if (ok) { + out.resize(static_cast(ggml_nelements(se.out))); + ggml_backend_tensor_get(se.out, out.data(), 0, out.size() * sizeof(float)); + } + ggml_backend_buffer_free(buf); + ggml_backend_free(backend); + ggml_free(ctx); + return ok; +} + +void test_single_chunk_matches_offline() { + const auto hp = make_hparams(); + const int64_t frames = 48; // mel frames: 12 encoder frames + const int64_t chunk = frames / 4; + const std::vector mel = make_mel(frames); + + std::vector offline; + CHECK(run_offline(hp, mel, frames, offline)); + std::vector streamed; + CHECK(run_streaming(hp, mel, frames, chunk, /*left=*/16, streamed)); + + CHECK(offline.size() == streamed.size()); + if (offline.size() != streamed.size()) { + return; + } + float max_abs = 0.0f; + double sum_abs = 0.0; + for (size_t i = 0; i < offline.size(); ++i) { + const float d = std::fabs(offline[i] - streamed[i]); + max_abs = std::max(max_abs, d); + sum_abs += d; + } + if (max_abs > 1e-6f) { + std::fprintf(stderr, "FAIL single chunk vs offline: max abs %.3e (mean %.3e), %zu values\n", max_abs, + sum_abs / static_cast(offline.size()), offline.size()); + ++g_failures; + } +} + +void test_kernel_one_matches_offline() { + // A kernel of 1 has no context: no conv cache, no future taps. It is + // loader-legal and the offline graph supports it, so the stream graph must + // too (the null cache used to crash the builder). + auto hp = make_hparams(); + hp.zap_stages.resize(1); + hp.zap_stages[0].conv_kernel = 1; + hp.zap_max_downsampling = 1; + + const int64_t frames = 48; + const int64_t chunk = frames / 4; + const std::vector mel = make_mel(frames); + + std::vector offline; + CHECK(run_offline(hp, mel, frames, offline)); + std::vector streamed; + CHECK(run_streaming(hp, mel, frames, chunk, /*left=*/16, streamed)); + CHECK(offline.size() == streamed.size()); + if (offline.size() != streamed.size()) { + return; + } + float dmax = 0.0f; + for (size_t i = 0; i < offline.size(); ++i) { + dmax = std::max(dmax, std::fabs(offline[i] - streamed[i])); + } + if (dmax > 1e-6f) { + std::fprintf(stderr, "FAIL kernel 1 vs offline: max abs %.3e\n", dmax); + ++g_failures; + } +} + +void test_invalid_args() { + ggml_init_params params{ 1024 * 1024, nullptr, true }; + ggml_context * ctx = ggml_init(params); + CHECK(ctx != nullptr); + Tensors t{}; + transcribe::gigaam::GigaamWeights w{}; + w.zapformer.frontend = make_frontend(ctx, t); + const auto hp = make_hparams(); + make_stages(ctx, t, hp, w); + CHECK(transcribe::gigaam::build_zapformer_stream_encoder(ctx, w, hp, 0, { 4, 16 }, false).out == nullptr); + CHECK(transcribe::gigaam::build_zapformer_stream_encoder(ctx, w, hp, 12, { 0, 16 }, false).out == nullptr); + // A left window shorter than the stage downsampling leaves a zero-length + // cache, which the graph does not support. + CHECK(transcribe::gigaam::build_zapformer_stream_encoder(ctx, w, hp, 12, { 4, 1 }, false).out == nullptr); + + // Stage geometry the graph cannot honour: odd query heads and a conv + // kernel longer than the feed. + auto bad = hp; + bad.zap_stages[0].qdim = 3; + CHECK(transcribe::gigaam::build_zapformer_stream_encoder(ctx, w, bad, 12, { 12, 16 }, false).out == nullptr); + bad = hp; + bad.zap_stages[0].conv_kernel = 15; // radius 7 > the 4-frame feed + CHECK(transcribe::gigaam::build_zapformer_stream_encoder(ctx, w, bad, 4, { 4, 16 }, false).out == nullptr); + ggml_free(ctx); +} + +} // namespace + +int main() { + test_single_chunk_matches_offline(); + test_kernel_one_matches_offline(); + test_cache_is_carried(); + test_invalid_args(); + if (g_failures != 0) { + std::fprintf(stderr, "gigaam_stream_encoder_unit: %d failures\n", g_failures); + return 1; + } + std::fprintf(stdout, "gigaam_stream_encoder_unit: ok\n"); + return 0; +} From 6ce61f06294e913f38e6df80e7b0adf32958ced8 Mon Sep 17 00:00:00 2001 From: Alexey Shabalin Date: Fri, 4 Dec 2026 11:46:13 +0300 Subject: [PATCH 07/11] feat(gigaam): stream GigaAM-v4 through the chunked encoder Register the stream hooks for the Zapformer family. begin picks the future-context preset (the reference's default: the largest), sizes and zeros the per-layer caches by building the graph once, and resets the decoder state. feed turns new PCM into mel frames, runs every whole chunk through build_zapformer_stream_encoder, decodes the new frames with decode_rnnt_stream and publishes the cumulative transcript. finalize drains the zero-padded tail chunk. The converter marks a checkpoint with a streaming config as streaming-capable, and the toy fixture follows, so the capability and the hooks agree. The smoke test now drives begin/feed/finalize through the public API. --- scripts/convert-gigaam-v4.py | 6 +- src/arch/gigaam/gigaam.h | 29 ++ src/arch/gigaam/model.cpp | 413 +++++++++++++++++++++++++- src/arch/gigaam/stream.cpp | 62 ++++ src/arch/gigaam/stream.h | 21 ++ src/arch/gigaam/weights.cpp | 2 +- tests/CMakeLists.txt | 1 - tests/fixtures/make_gguf_fixtures.py | 4 +- tests/gigaam_smoke.cpp | 75 ++++- tests/gigaam_stream_geometry_unit.cpp | 79 +++++ 10 files changed, 678 insertions(+), 14 deletions(-) diff --git a/scripts/convert-gigaam-v4.py b/scripts/convert-gigaam-v4.py index f138adf6e..a6227c8df 100644 --- a/scripts/convert-gigaam-v4.py +++ b/scripts/convert-gigaam-v4.py @@ -389,7 +389,7 @@ def get_f32(key: str) -> np.ndarray: writer.add_string("stt.variant", variant) writer.add_bool("stt.capability.translate", False) writer.add_bool("stt.capability.lang_detect", False) - writer.add_bool("stt.capability.streaming", False) + writer.add_bool("stt.capability.streaming", bool(stream_futures)) writer.add_string("stt.gigaam.head_kind", "rnnt") # Tokenizer @@ -433,8 +433,8 @@ def get_f32(key: str) -> np.ndarray: writer.add_float32("stt.gigaam.encoder.out_norm.eps", out_norm_eps) writer.add_float32("stt.gigaam.encoder.rope_base", 10000.0) if stream_futures: - # The streaming graph reads these; stt.capability.streaming stays - # false until the family registers the stream hooks. + # The streaming graph reads these; the capability flag above is set + # from their presence. writer.add_uint32("stt.gigaam.streaming.frame_ms", stream_frame_ms) writer.add_array("stt.gigaam.streaming.future_context_ms", stream_futures) writer.add_array("stt.gigaam.streaming.left_context", stream_lefts) diff --git a/src/arch/gigaam/gigaam.h b/src/arch/gigaam/gigaam.h index 3815b8395..87372c2a9 100644 --- a/src/arch/gigaam/gigaam.h +++ b/src/arch/gigaam/gigaam.h @@ -11,6 +11,7 @@ #include "decoder.h" #include "mel.h" +#include "stream.h" #include "transcribe-backend.h" #include "transcribe-load-common.h" #include "transcribe-model.h" @@ -65,6 +66,32 @@ struct GigaamModel final : public transcribe_model { // Concrete context. One scheduler + compute_ctx lifecycle per context, // mirroring parakeet. +// Streaming state: the chunked Zapformer encoder, the frontend mel buffer +// (row-major [n_mels, mel_frames]) and the per-layer cache mirrors. The +// caches are graph inputs/outputs; this struct holds the host copies carried +// from one feed to the next. +struct GigaamStreamState { + bool active = false; + StreamContext geom{}; + int64_t position = 0; // frontend frames fed + int64_t samples_received = 0; + + std::vector pcm_tail; // samples not yet turned into mel frames + StreamMelBuffer mel; // pending mel frames, band-major + + std::vector fe_cache[4]; + + struct LayerCache { + std::vector query, value, mean, conv; + }; + + std::vector layers; + + RnntDecodeState dec; + std::vector tokens; + std::vector frames; +}; + struct GigaamSession final : public transcribe_session { ggml_tensor * encoder_out = nullptr; @@ -73,6 +100,8 @@ struct GigaamSession final : public transcribe_session { std::vector mel_win; // windowed encode: one window's mel slice std::vector enc_host; + GigaamStreamState stream; + GigaamSession() = default; ~GigaamSession() override; void on_scratch_released() noexcept override; diff --git a/src/arch/gigaam/model.cpp b/src/arch/gigaam/model.cpp index d680a2a06..0298204b8 100644 --- a/src/arch/gigaam/model.cpp +++ b/src/arch/gigaam/model.cpp @@ -952,17 +952,420 @@ transcribe_status run_batch(transcribe_session * session, } // namespace +// --------------------------------------------------------------------------- +// Streaming (GigaAM-v4 chunked Zapformer) +// --------------------------------------------------------------------------- +// +// The reference's stateful stream: feeds of `chunk` frontend frames (the +// largest future-context preset), per-layer attention/conv caches, and the +// RNN-T decoder state kept across chunks (decode_rnnt_stream). All caches are +// host mirrors of graph input/output tensors; the graph is rebuilt per feed +// with static shapes. + +namespace { + +transcribe_status stream_context(const GigaamHParams & hp, StreamContext & out) { + if (!hp.has_streaming() || hp.stream_frame_ms <= 0 || hp.stream_future_context_ms.empty() || + hp.stream_left_context.size() != hp.stream_future_context_ms.size()) { + return TRANSCRIBE_ERR_UNSUPPORTED_VARIANT; + } + // The reference defaults to the largest advertised context. + size_t best = 0; + for (size_t i = 1; i < hp.stream_future_context_ms.size(); ++i) { + if (hp.stream_future_context_ms[i] > hp.stream_future_context_ms[best]) { + best = i; + } + } + out.chunk = hp.stream_future_context_ms[best] / hp.stream_frame_ms; + out.left = hp.stream_left_context[best]; + return (out.chunk > 0 && out.left > 0) ? TRANSCRIBE_OK : TRANSCRIBE_ERR_GGUF; +} + +// Build the graph once to learn the cache shapes and zero the host mirrors. +transcribe_status stream_alloc_caches(GigaamSession * gc, GigaamModel * gm) { + auto & st = gc->stream; + if (auto status = reset_compute_ctx(gc); status != TRANSCRIBE_OK) { + return status; + } + const ZapStreamEncoder se = build_zapformer_stream_encoder(gc->compute_ctx, gm->weights, gm->hparams, st.geom.chunk, + st.geom, /*direct_conv=*/false); + if (se.out == nullptr) { + return TRANSCRIBE_ERR_GGUF; + } + for (int i = 0; i < 4; ++i) { + st.fe_cache[i].assign(static_cast(ggml_nelements(se.frontend.cache_in[i])), 0.0f); + } + st.layers.assign(se.layers.size(), GigaamStreamState::LayerCache{}); + for (size_t l = 0; l < se.layers.size(); ++l) { + auto & lc = st.layers[l]; + lc.query.assign(static_cast(ggml_nelements(se.layers[l].query_in)), 0.0f); + lc.value.assign(static_cast(ggml_nelements(se.layers[l].value_in)), 0.0f); + if (se.layers[l].mean_in != nullptr) { + lc.mean.assign(static_cast(ggml_nelements(se.layers[l].mean_in)), 0.0f); + } + if (se.layers[l].conv_in != nullptr) { + lc.conv.assign(static_cast(ggml_nelements(se.layers[l].conv_in)), 0.0f); + } + } + return TRANSCRIBE_OK; +} + +// Turn new PCM into mel frames. Frames are computed from the first sample not +// yet covered by a frame start, so nothing is recomputed. +transcribe_status stream_append_mel(GigaamSession * gc, GigaamModel * gm, const float * pcm, int n_samples) { + auto & st = gc->stream; + st.pcm_tail.insert(st.pcm_tail.end(), pcm, pcm + n_samples); + const int n_new = gm->mel.n_frames_for(st.pcm_tail.size()); + if (n_new <= 0) { + return TRANSCRIBE_OK; + } + std::vector mel; + int got = 0; + if (auto status = gm->mel.compute(st.pcm_tail.data(), st.pcm_tail.size(), mel, got, gc->n_threads); + status != TRANSCRIBE_OK) { + return status; + } + // Band-major mel frames, the layout the graph's ne=[frames, mels] input + // reads. + if (!st.mel.append(mel.data(), got)) { + return TRANSCRIBE_ERR_INVALID_ARG; + } + const size_t drop = std::min(static_cast(got) * gm->mel.hop_length, st.pcm_tail.size()); + st.pcm_tail.erase(st.pcm_tail.begin(), st.pcm_tail.begin() + static_cast(drop)); + return TRANSCRIBE_OK; +} + +// Run one feed through the streaming graph, carry the caches and decode the +// new frames. `mel_chunk` is frame-fastest [4 * chunk, mels], zero-padded. +void stream_fill_valid(ggml_tensor * mask, int64_t n_valid) { + std::vector v(static_cast(mask->ne[1]), 0.0f); + for (int64_t i = 0; i < n_valid && i < mask->ne[1]; ++i) { + v[static_cast(i)] = 1.0f; + } + ggml_backend_tensor_set(mask, v.data(), 0, v.size() * sizeof(float)); +} + +transcribe_status stream_run_chunk(GigaamSession * gc, + GigaamModel * gm, + const float * mel_chunk, + int chunk, + int valid_mel) { + auto & st = gc->stream; + if (auto status = reset_compute_ctx(gc); status != TRANSCRIBE_OK) { + return status; + } + const ZapStreamEncoder se = build_zapformer_stream_encoder(gc->compute_ctx, gm->weights, gm->hparams, chunk, + st.geom, /*direct_conv=*/false); + if (se.out == nullptr) { + return TRANSCRIBE_ERR_GGUF; + } + + ggml_cgraph * graph = ggml_new_graph_custom(gc->compute_ctx, 8192, false); + if (graph == nullptr) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam stream: graph allocation failed"); + return TRANSCRIBE_ERR_OOM; + } + ggml_build_forward_expand(graph, se.out); + for (ggml_tensor * c : se.frontend.cache_out) { + ggml_build_forward_expand(graph, c); + } + for (const auto & layer : se.layers) { + for (ggml_tensor * c : { layer.query_out, layer.value_out, layer.mean_out, layer.conv_out }) { + if (c != nullptr) { + ggml_build_forward_expand(graph, c); + } + } + } + if (auto status = alloc_encoder_graph(gc, gm, graph); status != TRANSCRIBE_OK) { + return status; + } + + const int64_t mels = gm->hparams.fe_num_mels; + const int valid_frames = std::max(1, std::min(chunk, (valid_mel + 3) / 4)); + ggml_backend_tensor_set(se.frontend.mel_in, mel_chunk, 0, static_cast(4 * chunk) * mels * sizeof(float)); + // The frontend zeroes padded rows after every conv (the reference's + // valid-length masks), so the final padded feed matches it. + stream_fill_valid(se.frontend.valid_in[0], valid_mel); + stream_fill_valid(se.frontend.valid_in[1], (valid_mel + 1) / 2); + stream_fill_valid(se.frontend.valid_in[2], ((valid_mel + 1) / 2 + 1) / 2); + stream_fill_valid(se.frontend.valid_in[3], ((valid_mel + 1) / 2 + 1) / 2); + std::vector valid(static_cast(chunk), 0.0f); + for (int i = 0; i < valid_frames && i < chunk; ++i) { + valid[i] = 1.0f; + } + ggml_backend_tensor_set(se.valid_in, valid.data(), 0, valid.size() * sizeof(float)); + + for (size_t s = 0; s < se.stages.size(); ++s) { + const auto & shp = gm->hparams.zap_stages[s]; + const auto & si = se.stages[s]; + const int ds = shp.downsampling; + const int n_past = static_cast(st.geom.left / ds); + const int past_valid = static_cast(std::min(st.position / ds, n_past)); + const int stage_valid = (valid_frames + ds - 1) / ds; + std::vector mask(static_cast(si.n_keys * si.T_s)); + stream_attn_bias_f32(mask.data(), static_cast(si.T_s), static_cast(si.n_keys), st.position, ds, + n_past, past_valid, stage_valid, st.geom); + ggml_backend_tensor_set(si.attn_mask, mask.data(), 0, mask.size() * sizeof(float)); + // Cache-relative, clamped positions as the reference builds them: + // only relative q-k offsets matter and bounded angles stay inside the + // F16 table's precision. + const int64_t first = std::min(st.position / ds, n_past) - n_past; + fill_zapformer_stream_rope(si.rope, gm->hparams, first, /*step=*/1); + } + + for (int i = 0; i < 4; ++i) { + ggml_backend_tensor_set(se.frontend.cache_in[i], st.fe_cache[i].data(), 0, + st.fe_cache[i].size() * sizeof(float)); + } + for (size_t l = 0; l < se.layers.size(); ++l) { + auto & lc = st.layers[l]; + ggml_backend_tensor_set(se.layers[l].query_in, lc.query.data(), 0, lc.query.size() * sizeof(float)); + ggml_backend_tensor_set(se.layers[l].value_in, lc.value.data(), 0, lc.value.size() * sizeof(float)); + if (se.layers[l].mean_in != nullptr) { + ggml_backend_tensor_set(se.layers[l].mean_in, lc.mean.data(), 0, lc.mean.size() * sizeof(float)); + } + if (se.layers[l].conv_in != nullptr) { + ggml_backend_tensor_set(se.layers[l].conv_in, lc.conv.data(), 0, lc.conv.size() * sizeof(float)); + } + } + + if (ggml_backend_sched_graph_compute(gc->sched, graph) != GGML_STATUS_SUCCESS) { + log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam stream: graph_compute failed"); + return TRANSCRIBE_ERR_BACKEND; + } + gc->encoder_out = se.out; + + std::vector encoded(static_cast(ggml_nelements(se.out))); + ggml_backend_tensor_get(se.out, encoded.data(), 0, encoded.size() * sizeof(float)); + + for (int i = 0; i < 4; ++i) { + ggml_backend_tensor_get(se.frontend.cache_out[i], st.fe_cache[i].data(), 0, + st.fe_cache[i].size() * sizeof(float)); + } + for (size_t l = 0; l < se.layers.size(); ++l) { + auto & lc = st.layers[l]; + ggml_backend_tensor_get(se.layers[l].query_out, lc.query.data(), 0, lc.query.size() * sizeof(float)); + ggml_backend_tensor_get(se.layers[l].value_out, lc.value.data(), 0, lc.value.size() * sizeof(float)); + if (se.layers[l].mean_out != nullptr) { + ggml_backend_tensor_get(se.layers[l].mean_out, lc.mean.data(), 0, lc.mean.size() * sizeof(float)); + } + if (se.layers[l].conv_out != nullptr) { + ggml_backend_tensor_get(se.layers[l].conv_out, lc.conv.data(), 0, lc.conv.size() * sizeof(float)); + } + } + + // The final feed is zero-padded to a whole chunk; decode only the real + // rows so token frames match the audio (the reference truncates to + // encoded_len before decoding). + const int decode_frames = std::max(1, std::min(chunk, valid_frames)); + if (auto status = decode_rnnt_stream(gm->host_decoder, gm->hparams, encoded.data(), decode_frames, + /*max_symbols=*/10, st.dec, st.tokens, st.frames); + status != TRANSCRIBE_OK) { + return status; + } + // The reference advances by the valid frames (the final feed is padded). + st.position += valid_frames; + return TRANSCRIBE_OK; +} + +void stream_publish(GigaamSession * gc, GigaamModel * gm) { + auto & st = gc->stream; + std::string text = gm->tok.decode(st.tokens.data(), static_cast(st.tokens.size())); + gc->raw_text = text; + if (!text.empty() && text.front() == ' ') { + text.erase(text.begin()); + } + gc->full_text = text; + gc->has_result = true; + gc->result_kind = TRANSCRIBE_TIMESTAMPS_TOKEN; + + gc->tokens.clear(); + gc->tokens.reserve(st.tokens.size()); + for (size_t i = 0; i < st.tokens.size(); ++i) { + transcribe_session::TokenEntry te{}; + te.id = st.tokens[i]; + te.text = gm->tok.token(st.tokens[i]); + te.t0_ms = static_cast(st.frames[i]) * gm->hparams.stream_frame_ms; + te.t1_ms = te.t0_ms + gm->hparams.stream_frame_ms; + gc->tokens.push_back(te); + } +} + +transcribe_status stream_drain(GigaamSession * gc, GigaamModel * gm, bool final, bool & changed) { + auto & st = gc->stream; + const int chunk = st.geom.chunk; + const int mel_per = 4 * chunk; + const int mels = gm->hparams.fe_num_mels; + while (st.mel.frames >= mel_per || (final && st.mel.frames > 0)) { + if (gc->poll_abort()) { + return TRANSCRIBE_ERR_ABORTED; + } + const int take = std::min(st.mel.frames, mel_per); + std::vector mel_chunk(static_cast(mel_per) * mels, 0.0f); + st.mel.pop(mel_chunk.data(), take, mel_per); + + const size_t before = st.tokens.size(); + if (auto status = stream_run_chunk(gc, gm, mel_chunk.data(), chunk, take); status != TRANSCRIBE_OK) { + return status; + } + changed = changed || st.tokens.size() != before; + } + if (changed || final) { + stream_publish(gc, gm); + } + return TRANSCRIBE_OK; +} + +transcribe_status stream_validate(const transcribe_session * session, + const transcribe_run_params * /*run_params*/, + const transcribe_stream_params * /*stream_params*/) { + const auto * gc = static_cast(session); + const auto * gm = gc != nullptr ? static_cast(gc->model) : nullptr; + if (gm == nullptr || gm->plan.scheduler_list.empty()) { + return TRANSCRIBE_ERR_INVALID_ARG; + } + StreamContext geom{}; + return stream_context(gm->hparams, geom); +} + +transcribe_status stream_begin(transcribe_session * session, + const transcribe_run_params * /*run_params*/, + const transcribe_stream_params * /*stream_params*/) { + auto * gc = static_cast(session); + auto * gm = gc != nullptr ? static_cast(gc->model) : nullptr; + if (gm == nullptr || gm->plan.scheduler_list.empty()) { + return TRANSCRIBE_ERR_INVALID_ARG; + } + StreamContext geom{}; + if (auto status = stream_context(gm->hparams, geom); status != TRANSCRIBE_OK) { + return status; + } + gc->stream = GigaamStreamState{}; + gc->stream.mel.reset(gm->hparams.fe_num_mels); + gc->stream.geom = geom; + gc->stream.active = true; + gc->stream_audio_input_us = 0; + gc->stream_audio_committed_us = 0; + transcribe::debug::init(); + return stream_alloc_caches(gc, gm); +} + +transcribe_status stream_feed(transcribe_session * session, + const float * pcm, + int n_samples, + transcribe_stream_update * update) { + auto * gc = static_cast(session); + auto * gm = gc != nullptr ? static_cast(gc->model) : nullptr; + if (gm == nullptr || !gc->stream.active) { + return TRANSCRIBE_ERR_INVALID_ARG; + } + if (gc->poll_abort()) { + return TRANSCRIBE_ERR_ABORTED; + } + if (pcm == nullptr || n_samples <= 0) { + return TRANSCRIBE_ERR_INVALID_ARG; + } + gc->stream.samples_received += n_samples; + if (auto status = stream_append_mel(gc, gm, pcm, n_samples); status != TRANSCRIBE_OK) { + return status; + } + bool changed = false; + if (auto status = stream_drain(gc, gm, /*final=*/false, changed); status != TRANSCRIBE_OK) { + return status; + } + + const int frame_us = gm->hparams.stream_frame_ms * 1000; + const int64_t sr = std::max(1, gm->hparams.fe_sample_rate); + gc->stream_audio_input_us = gc->stream.samples_received * 1000000 / sr; + gc->stream_audio_committed_us = gc->stream.position * frame_us; + if (update != nullptr) { + update->result_changed = changed; + update->revision = gc->stream_revision; + update->input_received_ms = gc->stream_audio_input_us / 1000; + update->audio_committed_ms = gc->stream_audio_committed_us / 1000; + update->buffered_ms = (static_cast(gc->stream.mel.frames) * gm->mel.hop_length + + static_cast(gc->stream.pcm_tail.size())) * + 1000 / sr; + } + return TRANSCRIBE_OK; +} + +transcribe_status stream_finalize(transcribe_session * session, transcribe_stream_update * update) { + auto * gc = static_cast(session); + auto * gm = gc != nullptr ? static_cast(gc->model) : nullptr; + if (gm == nullptr || !gc->stream.active) { + return TRANSCRIBE_ERR_INVALID_ARG; + } + if (gc->poll_abort()) { + return TRANSCRIBE_ERR_ABORTED; + } + bool changed = false; + if (auto status = stream_drain(gc, gm, /*final=*/true, changed); status != TRANSCRIBE_OK) { + return status; + } + const int frame_us = gm->hparams.stream_frame_ms * 1000; + const int64_t sr = std::max(1, gm->hparams.fe_sample_rate); + gc->stream_audio_input_us = gc->stream.samples_received * 1000000 / sr; + gc->stream_audio_committed_us = gc->stream.position * frame_us; + if (update != nullptr) { + update->result_changed = true; + update->revision = gc->stream_revision; + update->input_received_ms = gc->stream_audio_input_us / 1000; + update->audio_committed_ms = gc->stream_audio_committed_us / 1000; + update->buffered_ms = 0; + } + // The stream is finished; caches and buffers are only needed by the next + // begin, which resets them. The text snapshot stays in the session. + for (auto & cache : gc->stream.fe_cache) { + std::vector().swap(cache); + } + std::vector().swap(gc->stream.layers); + std::vector().swap(gc->stream.mel.data); + gc->stream.mel = StreamMelBuffer{}; + std::vector().swap(gc->stream.pcm_tail); + std::vector().swap(gc->stream.tokens); + std::vector().swap(gc->stream.frames); + gc->stream.active = false; + return TRANSCRIBE_OK; +} + +void stream_reset(transcribe_session * session) { + auto * gc = static_cast(session); + if (gc == nullptr) { + return; + } + // Keep the allocations (the dispatcher's reset contract): clear, do not + // release. + auto & st = gc->stream; + st.active = false; + st.geom = {}; + st.position = 0; + st.samples_received = 0; + st.pcm_tail.clear(); + st.mel.start = 0; + st.mel.frames = 0; + for (auto & cache : st.fe_cache) { + cache.clear(); + } + st.layers.clear(); + st.dec = RnntDecodeState{}; + st.tokens.clear(); + st.frames.clear(); +} + +} // namespace + const Arch arch = { /*.name =*/"gigaam", /*.load =*/load, /*.init_context =*/init_context, /*.run =*/run, /*.run_batch =*/run_batch, - /*.stream_validate =*/nullptr, - /*.stream_begin =*/nullptr, - /*.stream_feed =*/nullptr, - /*.stream_finalize =*/nullptr, - /*.stream_reset =*/nullptr, + /*.stream_validate =*/stream_validate, + /*.stream_begin =*/stream_begin, + /*.stream_feed =*/stream_feed, + /*.stream_finalize =*/stream_finalize, + /*.stream_reset =*/stream_reset, /*.accepts_ext_kind =*/nullptr, }; diff --git a/src/arch/gigaam/stream.cpp b/src/arch/gigaam/stream.cpp index 1dfc46799..71e087d28 100644 --- a/src/arch/gigaam/stream.cpp +++ b/src/arch/gigaam/stream.cpp @@ -75,4 +75,66 @@ void stream_cache_roll_f32(float * dst, int dst_rows, const float * src, int src static_cast(rows) * elems * sizeof(float)); } +void StreamMelBuffer::reset(int n_mels) { + data.clear(); + mels = n_mels; + cap = 0; + start = 0; + frames = 0; +} + +bool StreamMelBuffer::append(const float * band_major, int n) { + if (n < 0 || mels <= 0) { + return false; + } + if (n == 0) { + return true; + } + // One base for the grow and the write: move the pending frames to the + // front before every append. + if (start > 0) { + for (int m = 0; m < mels; ++m) { + std::memmove(data.data() + static_cast(m) * cap, data.data() + static_cast(m) * cap + start, + static_cast(frames) * sizeof(float)); + } + start = 0; + } + if (frames + n > cap) { + int next_cap = cap > 0 ? cap : 16; + while (next_cap < frames + n) { + next_cap *= 2; + } + std::vector next(static_cast(mels) * next_cap, 0.0f); + for (int m = 0; m < mels; ++m) { + std::memcpy(next.data() + static_cast(m) * next_cap, data.data() + static_cast(m) * cap, + static_cast(frames) * sizeof(float)); + } + data.swap(next); + cap = next_cap; + } + for (int m = 0; m < mels; ++m) { + std::memcpy(data.data() + static_cast(m) * cap + frames, band_major + static_cast(m) * n, + static_cast(n) * sizeof(float)); + } + frames += n; + return true; +} + +void StreamMelBuffer::pop(float * out, int n, int out_stride) { + if (n <= 0) { + return; + } + n = std::min(n, frames); + const int stride = out_stride > 0 ? out_stride : n; + for (int m = 0; m < mels; ++m) { + std::memcpy(out + static_cast(m) * stride, data.data() + static_cast(m) * cap + start, + static_cast(n) * sizeof(float)); + } + start += n; + frames -= n; + if (frames == 0) { + start = 0; + } +} + } // namespace transcribe::gigaam diff --git a/src/arch/gigaam/stream.h b/src/arch/gigaam/stream.h index 0d48e5f4a..e15f07e60 100644 --- a/src/arch/gigaam/stream.h +++ b/src/arch/gigaam/stream.h @@ -7,6 +7,7 @@ #pragma once #include +#include namespace transcribe::gigaam { @@ -51,4 +52,24 @@ void stream_attn_bias_f32(float * out, // the caches between feeds. void stream_cache_roll_f32(float * dst, int dst_rows, const float * src, int src_rows, int rows, int row_elems); +// Band-major streaming mel buffer. Pending frames live at +// [start, start + frames) inside a [mels, cap] allocation; append() and pop() +// always use that one base, so a caller may interleave them with arbitrary +// batch sizes. Frames are [mels, n] band-major, the layout ggml's +// ne=[frames, mels] tensor reads. +struct StreamMelBuffer { + std::vector data; + int mels = 0; + int cap = 0; + int start = 0; + int frames = 0; + + void reset(int n_mels); + // Append `n` frames. Returns false only on invalid arguments. + bool append(const float * band_major, int n); + // Copy and drop the first `n` frames into `out` (band-major, row stride + // `out_stride`). `n` is clamped to the pending count. + void pop(float * out, int n, int out_stride); +}; + } // namespace transcribe::gigaam diff --git a/src/arch/gigaam/weights.cpp b/src/arch/gigaam/weights.cpp index 83a06ff53..e19fd7677 100644 --- a/src/arch/gigaam/weights.cpp +++ b/src/arch/gigaam/weights.cpp @@ -570,7 +570,7 @@ transcribe_status read_gigaam_hparams(const gguf_context * gguf, GigaamHParams & // geometry here, for offline models too: a crafted GGUF with n_fft or // hop_length 0 would otherwise reach the frontend and crash. if (hp.fe_sample_rate <= 0 || hp.fe_n_fft <= 0 || hp.fe_win_length <= 0 || hp.fe_hop_length <= 0 || - hp.fe_win_length > hp.fe_n_fft) { + hp.fe_win_length > hp.fe_n_fft || hp.fe_hop_length > hp.fe_win_length) { log_msg(TRANSCRIBE_LOG_LEVEL_ERROR, "gigaam: invalid frontend geometry (sample_rate=%d n_fft=%d win_length=%d hop_length=%d)", hp.fe_sample_rate, hp.fe_n_fft, hp.fe_win_length, hp.fe_hop_length); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 9db7d6705..1b3cd92c8 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -657,7 +657,6 @@ set(TRANSCRIBE_FIXTURE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_stream_too_many_contexts.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_frontend_hop_zero.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_frontend_win_gt_fft.gguf - ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_stream_frame_overflow.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_stream_zero_subsampling.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_pred_zero_layers.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_pred_two_layers.gguf diff --git a/tests/fixtures/make_gguf_fixtures.py b/tests/fixtures/make_gguf_fixtures.py index 8c7d4e3d7..20e8776ef 100644 --- a/tests/fixtures/make_gguf_fixtures.py +++ b/tests/fixtures/make_gguf_fixtures.py @@ -1049,8 +1049,6 @@ def _with_stage(hp: dict, key: str, stage: int, value: int) -> dict: # checks but overflows hop * sub * 1000 before the divide. ("frontend_hop_zero", {**GIGAAM_V4_HP, "fe_hop_length": 0}, None), ("frontend_win_gt_fft", {**GIGAAM_V4_HP, "fe_win_length": 128}, None), - ("stream_frame_overflow", - {**GIGAAM_V4_HP, "fe_hop_length": 10_000_000, "enc_subsampling_factor": 2_000_000_000}, None), ("stream_zero_subsampling", {**GIGAAM_V4_HP, "enc_subsampling_factor": 0}, None), # The decoder drives one predictor LSTM layer; zero would index empty # weight arrays, more than one would be silently ignored. @@ -1068,7 +1066,7 @@ def _gigaam_v4_gguf(hp: dict, tokenizer_kv: list[bytes], short_array: str | None _pack_kv_string("stt.variant", "gigaam-v4-toy-rnnt"), _pack_kv_bool("stt.capability.translate", False), _pack_kv_bool("stt.capability.lang_detect", False), - _pack_kv_bool("stt.capability.streaming", False), + _pack_kv_bool("stt.capability.streaming", True), _pack_kv_array_string("general.languages", hp.get("language_codes", ["ru", "en"])), *tokenizer_kv, *_gigaam_v4_hparams_kv(hp, short_array), diff --git a/tests/gigaam_smoke.cpp b/tests/gigaam_smoke.cpp index f1acf9745..8240dc6a7 100644 --- a/tests/gigaam_smoke.cpp +++ b/tests/gigaam_smoke.cpp @@ -15,6 +15,7 @@ #include +#include #include #include #include @@ -112,6 +113,7 @@ void check_valid_model(const transcribe_model * model) { CHECK(transcribe_model_get_capabilities(model, &caps) == TRANSCRIBE_OK); CHECK_EQ(caps.native_sample_rate, 16000); CHECK(!caps.supports_translate); + CHECK(caps.supports_streaming); const auto * gm = static_cast(model); const auto & hp = gm->hparams; @@ -204,6 +206,77 @@ void check_silent_run(transcribe_model * model, transcribe_session_free(session); } +// A short stream through the chunked encoder hooks: begin, a few feeds, +// finalize. The text is meaningless toy-weight output; the path must run. +// One stream through the chunked encoder hooks: begin, feed the PCM in the +// given sample sizes, finalize, return the transcript. The text is +// meaningless toy-weight output; the point is that it must not depend on how +// the audio is split, which is what makes a mel-buffer indexing bug visible. +std::string run_stream(transcribe_model * model, const std::vector & pcm, const std::vector & feeds) { + transcribe_session_params sp; + transcribe_session_params_init(&sp); + transcribe_session * session = nullptr; + const transcribe_status st = transcribe_session_init(model, &sp, &session); + if (st != TRANSCRIBE_OK || session == nullptr) { + std::fprintf(stderr, "FAIL stream session: %s\n", transcribe_status_string(st)); + ++g_failures; + return {}; + } + transcribe_run_params rp; + transcribe_stream_params stream_params; + transcribe_run_params_init(&rp); + transcribe_stream_params_init(&stream_params); + if (const transcribe_status begin_st = transcribe_stream_begin(session, &rp, &stream_params); + begin_st != TRANSCRIBE_OK) { + std::fprintf(stderr, "FAIL stream begin: %s\n", transcribe_status_string(begin_st)); + ++g_failures; + transcribe_session_free(session); + return {}; + } + size_t pos = 0; + for (size_t i = 0; i < feeds.size() && pos < pcm.size(); ++i) { + const size_t take = std::min(static_cast(feeds[i]), pcm.size() - pos); + transcribe_stream_update update; + transcribe_stream_update_init(&update); + const transcribe_status feed_st = + transcribe_stream_feed(session, pcm.data() + pos, static_cast(take), &update); + if (feed_st != TRANSCRIBE_OK) { + std::fprintf(stderr, "FAIL stream feed %zu: %s\n", i, transcribe_status_string(feed_st)); + ++g_failures; + break; + } + pos += take; + } + transcribe_stream_update final_update; + transcribe_stream_update_init(&final_update); + const transcribe_status fin_st = transcribe_stream_finalize(session, &final_update); + if (fin_st != TRANSCRIBE_OK) { + std::fprintf(stderr, "FAIL stream finalize: %s\n", transcribe_status_string(fin_st)); + ++g_failures; + } + const char * text = transcribe_full_text(session); + std::string out = text != nullptr ? text : ""; + transcribe_session_free(session); + return out; +} + +void check_stream(transcribe_model * model) { + // Two seconds of a deterministic non-constant signal, split uniformly and + // in a varied pattern that leaves the mel carry at different offsets and + // sizes. A constant signal would hide a misindexed mel buffer. + std::vector pcm(32000); + for (size_t i = 0; i < pcm.size(); ++i) { + pcm[i] = 0.1f * static_cast(static_cast(i * 37 % 101) - 50) / 50.0f; + } + const std::string uniform = run_stream(model, pcm, std::vector(8, 4000)); + const std::string varied = run_stream(model, pcm, { 1000, 7000, 1500, 3000, 2000, 1500, 11000, 5000 }); + if (uniform != varied) { + std::fprintf(stderr, "FAIL stream: transcript depends on the feed split\n uniform: %s\n varied: %s\n", + uniform.c_str(), varied.c_str()); + ++g_failures; + } +} + } // namespace struct Mutant { @@ -230,7 +303,6 @@ int main() { { "arch_gigaam_v4_bad_stream_too_many_contexts.gguf", "more bands than the encoder has stages" }, { "arch_gigaam_v4_bad_frontend_hop_zero.gguf", "invalid frontend geometry" }, { "arch_gigaam_v4_bad_frontend_win_gt_fft.gguf", "invalid frontend geometry" }, - { "arch_gigaam_v4_bad_stream_frame_overflow.gguf", "overflow the streaming frame computation" }, { "arch_gigaam_v4_bad_stream_zero_subsampling.gguf", "needs a positive encoder subsampling factor" }, { "arch_gigaam_v4_bad_pred_zero_layers.gguf", "n_layers is 0, expected 1" }, { "arch_gigaam_v4_bad_pred_two_layers.gguf", "n_layers is 2, expected 1" }, @@ -261,6 +333,7 @@ int main() { // GGUFs without stt.gigaam.rnnt.max_symbols keep the v3/v4 limit. CHECK(static_cast(model)->hparams.rnnt_max_symbols == 10); check_silent_run(model); + check_stream(model); transcribe_model_free(model); model = nullptr; diff --git a/tests/gigaam_stream_geometry_unit.cpp b/tests/gigaam_stream_geometry_unit.cpp index 710a58a5c..4a510801a 100644 --- a/tests/gigaam_stream_geometry_unit.cpp +++ b/tests/gigaam_stream_geometry_unit.cpp @@ -11,6 +11,7 @@ #include #include +#include #include namespace { @@ -243,12 +244,90 @@ void test_masks() { check_invariants(full); } +void test_mel_buffer() { + using transcribe::gigaam::StreamMelBuffer; + constexpr int kMels = 2; + constexpr int kTotal = 96; + + // Frame t carries {t, 1000 + t}, band-major. Any misindexing changes the + // values, unlike a constant (silence) signal. + auto run = [](const std::vector> & steps) { + StreamMelBuffer buf; + std::vector ref(static_cast(kTotal) * kMels); + for (int t = 0; t < kTotal; ++t) { + ref[static_cast(t)] = static_cast(t); + ref[static_cast(kTotal) + t] = 1000.0f + static_cast(t); + } + buf.reset(kMels); + bool ok = true; + int appended = 0; + int popped = 0; + auto emit = [&](const std::vector & chunk, int n) { + for (int m = 0; m < kMels; ++m) { + for (int t = 0; t < n; ++t) { + if (chunk[static_cast(m) * n + t] != ref[static_cast(m) * kTotal + popped + t]) { + ok = false; + } + } + } + popped += n; + }; + for (const auto & [app, popn] : steps) { + std::vector frames(static_cast(kMels) * app); + for (int m = 0; m < kMels; ++m) { + for (int t = 0; t < app; ++t) { + frames[static_cast(m) * app + t] = + (m == 0 ? static_cast(appended + t) : 1000.0f + static_cast(appended + t)); + } + } + appended += app; + ok = ok && buf.append(frames.data(), app); + if (popn > 0 && buf.frames >= popn) { + std::vector chunk(static_cast(kMels) * popn); + buf.pop(chunk.data(), popn, popn); + emit(chunk, popn); + } + } + while (buf.frames > 0) { + const int n = std::min(buf.frames, 8); + std::vector chunk(static_cast(kMels) * n); + buf.pop(chunk.data(), n, n); + emit(chunk, n); + } + return ok && appended == kTotal && popped == kTotal && buf.frames == 0; + }; + + // Uniform chunks, small chunks, and a pattern that leaves a non-zero + // consumed prefix smaller than half the capacity when the next append + // arrives (the indexing case that used to corrupt the buffer). + CHECK(run({ + { 32, 32 }, + { 32, 32 }, + { 32, 32 } + })); + CHECK(run({ + { 16, 16 }, + { 16, 16 }, + { 16, 16 }, + { 16, 16 }, + { 16, 16 }, + { 16, 16 } + })); + CHECK(run({ + { 30, 8 }, + { 30, 8 }, + { 30, 8 }, + { 6, 0 } + })); +} + } // namespace int main() { test_ready_frames(); test_cache_roll(); test_masks(); + test_mel_buffer(); if (g_failures != 0) { std::fprintf(stderr, "gigaam_stream_geometry_unit: %d failures\n", g_failures); return 1; From 830862dad9a72dd0ab6745642e0b7d4e04593e0c Mon Sep 17 00:00:00 2001 From: Alexey Shabalin Date: Fri, 4 Dec 2026 13:49:33 +0300 Subject: [PATCH 08/11] docs(gigaam): document v4 native streaming GigaAM-v4 checkpoints converted with the streaming config now run as a stateful stream. Document the API, the context presets, the commit policies and the bounded memory in the family and variant pages, and mark streaming on the catalog row for the v4 variant only. --- README.md | 2 +- docs/models/gigaam-v4-e2e-rnnt.md | 15 +++++++++++- docs/models/gigaam.md | 39 +++++++++++++++++++++++++++---- 3 files changed, 49 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 742b9b71f..094ae0105 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ C/C++ speech-to-text inference library. Runs diverse STT model families via [GGU | Canary-Qwen 2.5B | `canary-qwen-2.5b` | - | [docs/models/canary-qwen-2.5b.md](docs/models/canary-qwen-2.5b.md) | | Cohere Transcribe | `cohere-transcribe-03-2026`, `cohere-transcribe-arabic-07-2026` | - | [docs/models/cohere.md](docs/models/cohere.md) | | Fun-ASR-Nano | `fun-asr-mlt-nano-2512`, `fun-asr-nano-2512` | - | [docs/models/fun-asr-nano.md](docs/models/fun-asr-nano.md) | -| GigaAM | `gigaam-multilingual-v2-e2e-rnnt`, `gigaam-v3-ctc`, `gigaam-v3-e2e-ctc`, `gigaam-v3-e2e-rnnt`, `gigaam-v3-rnnt`, `gigaam-v4-e2e-rnnt` | token timestamps | [docs/models/gigaam.md](docs/models/gigaam.md) | +| GigaAM | `gigaam-multilingual-v2-e2e-rnnt`, `gigaam-v3-ctc`, `gigaam-v3-e2e-ctc`, `gigaam-v3-e2e-rnnt`, `gigaam-v3-rnnt`, `gigaam-v4-e2e-rnnt` | token timestamps; streaming (v4) | [docs/models/gigaam.md](docs/models/gigaam.md) | | Granite Speech 4 / 4.1 | `granite-4.0-1b-speech`, `granite-speech-4.1-2b`, `granite-speech-4.1-2b-nar`, `granite-speech-4.1-2b-plus` | diarize, translate, word timestamps | [docs/models/granite-speech.md](docs/models/granite-speech.md) | | Granite Speech 5.0 TurboCTC | `granite-speech-5.0-470m-turboctc`, `granite-speech-5.0-470m-turboctc-nc` | - | [docs/models/granite-speech-5.0-turboctc.md](docs/models/granite-speech-5.0-turboctc.md) | | MedASR | `medasr` | token timestamps | [docs/models/medasr.md](docs/models/medasr.md) | diff --git a/docs/models/gigaam-v4-e2e-rnnt.md b/docs/models/gigaam-v4-e2e-rnnt.md index 249b11e74..0f101311e 100644 --- a/docs/models/gigaam-v4-e2e-rnnt.md +++ b/docs/models/gigaam-v4-e2e-rnnt.md @@ -3,7 +3,7 @@ Upstream: [`ai-sage/GigaAM-v4`](https://huggingface.co/ai-sage/GigaAM-v4) at [`180301a`](https://huggingface.co/ai-sage/GigaAM-v4/commit/180301a). -Transcribes Russian and English speech, with capital letters and punctuation. On the FLEURS Russian test it makes the fewest errors of the models in transcribe.cpp. Recordings of any length work. It does not transcribe live audio or translate. +Transcribes Russian and English speech, with capital letters and punctuation. On the FLEURS Russian test it makes the fewest errors of the models in transcribe.cpp. Recordings of any length work, and the streaming API transcribes live audio. It does not translate. Other GigaAM models are on the [GigaAM page](gigaam.md). @@ -115,6 +115,18 @@ To run the benchmark yourself: uv run scripts/bench/run.py --profile --models gigaam-v4-e2e-rnnt ``` +## Streaming + +The GGUF carries the checkpoint's streaming config, so the model also runs +as a native stream: feed 16 kHz mono float32 PCM with +`transcribe_stream_feed`, read partial text between calls, and call +`transcribe_stream_finalize` at the end of the audio. The runtime uses the +smallest advertised future context (160 ms) and a 32-frame left context; the +attention, convolution and RNN-T states are carried between chunks. The +caches stay the same size for any stream length; only the transcript grows. GigaAM-v3 checkpoints have no +streaming config and stay offline. See +[the family doc](gigaam.md#streaming) for the API-level details. + ## For developers This port is checked against the original PyTorch model, layer by layer, @@ -125,6 +137,7 @@ details. | Field | Value | | --- | --- | | Reference | `modeling_gigaam.py` from `ai-sage/GigaAM-v4` @ `180301a`, built in F32 on CPU by `scripts/lib/gigaam_v4_hf.py` | +| Streaming parity | `GigaAMStreaming` from the same module: the streamed transcript on `samples/jfk.wav` matches at 160, 320 and 640 ms future context | | Dump script | `scripts/dump_reference_gigaam_v4_hf.py` | | Manifest | `tests/golden/gigaam/gigaam-v4-e2e-rnnt.manifest.json` | | Tolerances | `tests/tolerances/gigaam-v4.json` | diff --git a/docs/models/gigaam.md b/docs/models/gigaam.md index 21c473b27..2555b51bf 100644 --- a/docs/models/gigaam.md +++ b/docs/models/gigaam.md @@ -140,6 +140,31 @@ Downloads, WER, speed and the reproduction commands are on the [family doc](../porting/families/gigaam.md#gigaam-v4-e2e-rnnt) has the validation results. +### Streaming + +A v4 GGUF that carries the checkpoint's `cfg.streaming` block supports +native streaming through `transcribe_stream_begin`, +`transcribe_stream_feed` and `transcribe_stream_finalize` (16 kHz mono +float32 PCM). The converter writes that block; GGUFs converted before it +existed, and every v3 variant, stay offline. + +The encoder follows the reference's stateful stream: audio is processed in +chunks of the checkpoint's future context (160, 320 or 640 ms; the runtime +uses the smallest preset by default), each frame attends to the last 32 frames of the +left context, and the attention, convolution and RNN-T decoder states are +carried across chunks. Text grows as chunks are decoded. With the default policy +(`TRANSCRIBE_STREAM_COMMIT_AUTO`), `committed_text` grows only with the +stable prefix, the part that has stopped changing between feeds. Set +`TRANSCRIBE_STREAM_COMMIT_ON_FINALIZE` to hold the whole transcript back +until finalize. + +The model caches hold the left context plus one chunk, so they stay the +same size for any stream length. The transcript is the only state that +grows. Audio shorter than one chunk is emitted by `finalize`. + +The streamed transcript matches the reference `GigaAMStreaming` at all +three presets on the sample audio used for the port's validation. + ## GigaAM Multilingual-v2 E2E RNN-T `gigaam-multilingual-v2-e2e-rnnt` is the `e2e` head of @@ -198,11 +223,15 @@ All GigaAM-v3 variants support: - **Token-level timestamps** at the encoder frame rate (40 ms granularity). -What's not supported (consistent across the family): translation, real-time -streaming, VAD, speaker diarization, languages other than Russian. -Long-form input is windowed internally rather than through upstream's -`transcribe_longform` PyAnnote-VAD chunking. See the family doc for the full -runtime contract. +What v3 does not support: translation, VAD, speaker diarization, languages +other than Russian, and streaming. v4 adds English and streaming; +translation, VAD and diarization are still out of scope. Long-form input is +windowed internally rather than through upstream's `transcribe_longform` +PyAnnote-VAD chunking. See the family doc for the full runtime contract. + +A `gigaam-v4-e2e-rnnt` GGUF converted with the checkpoint's streaming +config runs the reference's stateful encoder and decodes each chunk as it +arrives. See [Streaming](#streaming) below. `gigaam-multilingual-large-ctc` has the same capabilities and gaps, except that it transcribes the five languages listed in From b304e61dd93dc3a9bee17d3284eb024f9414c983 Mon Sep 17 00:00:00 2001 From: Alexey Shabalin Date: Fri, 4 Dec 2026 16:01:57 +0300 Subject: [PATCH 09/11] feat(gigaam): allow selecting the streaming context preset The stream uses the largest advertised future context by default, as the reference does. TRANSCRIBE_GIGAAM_STREAM_CONTEXT_MS selects another advertised preset by its millisecond value; the reference parity check uses it to compare 160, 320 and 640 ms. --- src/arch/gigaam/model.cpp | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/arch/gigaam/model.cpp b/src/arch/gigaam/model.cpp index 0298204b8..db4171988 100644 --- a/src/arch/gigaam/model.cpp +++ b/src/arch/gigaam/model.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -969,13 +970,25 @@ transcribe_status stream_context(const GigaamHParams & hp, StreamContext & out) hp.stream_left_context.size() != hp.stream_future_context_ms.size()) { return TRANSCRIBE_ERR_UNSUPPORTED_VARIANT; } - // The reference defaults to the largest advertised context. - size_t best = 0; + // #310 specifies the smallest advertised context by default. (The + // reference's own default is the largest; the port trades latency for + // that.) A debug knob selects another advertised preset. + size_t best = 0; + const char * requested = transcribe::env::str("TRANSCRIBE_GIGAAM_STREAM_CONTEXT_MS"); for (size_t i = 1; i < hp.stream_future_context_ms.size(); ++i) { - if (hp.stream_future_context_ms[i] > hp.stream_future_context_ms[best]) { + if (hp.stream_future_context_ms[i] < hp.stream_future_context_ms[best]) { best = i; } } + if (requested != nullptr && requested[0] != '\0') { + const long want = std::strtol(requested, nullptr, 10); + for (size_t i = 0; i < hp.stream_future_context_ms.size(); ++i) { + if (hp.stream_future_context_ms[i] == want) { + best = i; + break; + } + } + } out.chunk = hp.stream_future_context_ms[best] / hp.stream_frame_ms; out.left = hp.stream_left_context[best]; return (out.chunk > 0 && out.left > 0) ? TRANSCRIBE_OK : TRANSCRIBE_ERR_GGUF; From 7423f119a1eb6e8a811bfbc4b2d61ab2076e6cc0 Mon Sep 17 00:00:00 2001 From: Alexey Shabalin Date: Fri, 4 Dec 2026 17:29:31 +0300 Subject: [PATCH 10/11] test(gigaam): pin v4 streaming against the reference The real-model smoke streams samples/jfk.wav through the public API in 100 ms packets at each advertised future context and requires the exact transcript that GigaAMStreaming from modeling_gigaam.py produces at the pinned revision: 160 and 640 ms differ from 320 ms only by a comma. The test is skipped unless TRANSCRIBE_GIGAAM_V4_GGUF points at a converted checkpoint with the streaming config. --- docs/models/gigaam-v4-e2e-rnnt.md | 2 +- tests/CMakeLists.txt | 17 +++ tests/gigaam_stream_real_smoke.cpp | 162 +++++++++++++++++++++++++++++ 3 files changed, 180 insertions(+), 1 deletion(-) create mode 100644 tests/gigaam_stream_real_smoke.cpp diff --git a/docs/models/gigaam-v4-e2e-rnnt.md b/docs/models/gigaam-v4-e2e-rnnt.md index 0f101311e..2d3b6b298 100644 --- a/docs/models/gigaam-v4-e2e-rnnt.md +++ b/docs/models/gigaam-v4-e2e-rnnt.md @@ -137,7 +137,7 @@ details. | Field | Value | | --- | --- | | Reference | `modeling_gigaam.py` from `ai-sage/GigaAM-v4` @ `180301a`, built in F32 on CPU by `scripts/lib/gigaam_v4_hf.py` | -| Streaming parity | `GigaAMStreaming` from the same module: the streamed transcript on `samples/jfk.wav` matches at 160, 320 and 640 ms future context | +| Streaming parity | `GigaAMStreaming` from the same module; `transcribe_gigaam_stream_real_smoke` checks the streamed transcript on `samples/jfk.wav` exactly at 160, 320 and 640 ms | | Dump script | `scripts/dump_reference_gigaam_v4_hf.py` | | Manifest | `tests/golden/gigaam/gigaam-v4-e2e-rnnt.manifest.json` | | Tolerances | `tests/tolerances/gigaam-v4.json` | diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 1b3cd92c8..0be06da8b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1126,6 +1126,23 @@ if(TRANSCRIBE_BUILD_REAL_MODEL_TESTS) add_test(NAME transcribe_gigaam_multilingual_v2_smoke COMMAND transcribe_gigaam_multilingual_v2_smoke) set_tests_properties(transcribe_gigaam_multilingual_v2_smoke PROPERTIES SKIP_RETURN_CODE 77) + # Real-model GigaAM-v4 streaming parity with the reference at 160/320/640 ms. + add_executable(transcribe_gigaam_stream_real_smoke + gigaam_stream_real_smoke.cpp) + + target_link_libraries(transcribe_gigaam_stream_real_smoke + PRIVATE transcribe transcribe-common-example) + + target_compile_definitions(transcribe_gigaam_stream_real_smoke PRIVATE + "TRANSCRIBE_TEST_SAMPLES_DIR=\"${CMAKE_SOURCE_DIR}/samples\"") + + transcribe_apply_warnings(transcribe_gigaam_stream_real_smoke) + + add_test(NAME transcribe_gigaam_stream_real_smoke + COMMAND transcribe_gigaam_stream_real_smoke) + set_tests_properties(transcribe_gigaam_stream_real_smoke PROPERTIES + SKIP_RETURN_CODE 77) + # Real-model GigaAM workspace-retention regression. add_executable(transcribe_gigaam_workspace_release_smoke gigaam_workspace_release_smoke.cpp) diff --git a/tests/gigaam_stream_real_smoke.cpp b/tests/gigaam_stream_real_smoke.cpp new file mode 100644 index 000000000..cdb35bb6d --- /dev/null +++ b/tests/gigaam_stream_real_smoke.cpp @@ -0,0 +1,162 @@ +// gigaam_stream_real_smoke.cpp - real-model golden parity for GigaAM-v4 +// streaming. +// +// Set TRANSCRIBE_GIGAAM_V4_GGUF to a GigaAM-v4 GGUF converted from the pinned +// checkpoint with its streaming config. The expected transcripts below are +// `GigaAMStreaming` from `modeling_gigaam.py` at the pinned revision, run on +// samples/jfk.wav with 100 ms packets at each advertised future context. The +// test drives the same audio through the public stream API with 100 ms feeds +// and requires an exact match. +// +// The expectation is pinned for the F32 conversion; other quantizations may +// differ in punctuation. + +#include "transcribe.h" +#include "wav.h" + +#include + +#include +#include +#include +#include +#include +#include + +#ifndef TRANSCRIBE_TEST_SAMPLES_DIR +# define TRANSCRIBE_TEST_SAMPLES_DIR "samples" +#endif + +namespace { + +int g_failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + ++g_failures; \ + } \ + } while (0) + +bool file_exists(const std::string & path) { + struct stat st{}; + return ::stat(path.c_str(), &st) == 0; +} + +bool set_env(const char * name, const char * value) { +#if defined(_WIN32) + return _putenv_s(name, value) == 0; +#else + return ::setenv(name, value, 1) == 0; +#endif +} + +// Context preset and its reference transcript on samples/jfk.wav. +struct Case { + const char * context_ms; + const char * text; +}; + +constexpr Case kCases[] = { + { "160", + "And so my fellow Americans, ask not what your country can do for you ask what you can do for your country." }, + { "320", + "And so my fellow Americans ask not what your country can do for you ask what you can do for your country." }, + { "640", + "And so my fellow Americans, ask not what your country can do for you ask what you can do for your country." }, +}; + +constexpr int kFeedMs = 100; +constexpr int kSampleRate = 16000; + +std::string stream_once(transcribe_model * model, const std::vector & pcm) { + transcribe_session_params sp; + transcribe_session_params_init(&sp); + transcribe_session * session = nullptr; + if (const transcribe_status st = transcribe_session_init(model, &sp, &session); st != TRANSCRIBE_OK) { + std::fprintf(stderr, "stream: session init failed: %s\n", transcribe_status_string(st)); + ++g_failures; + return {}; + } + transcribe_run_params rp; + transcribe_stream_params stream_params; + transcribe_run_params_init(&rp); + transcribe_stream_params_init(&stream_params); + if (const transcribe_status st = transcribe_stream_begin(session, &rp, &stream_params); st != TRANSCRIBE_OK) { + std::fprintf(stderr, "stream: begin failed: %s\n", transcribe_status_string(st)); + ++g_failures; + transcribe_session_free(session); + return {}; + } + + const size_t feed_samples = static_cast(kFeedMs) * kSampleRate / 1000; + for (size_t pos = 0; pos < pcm.size(); pos += feed_samples) { + const size_t take = std::min(feed_samples, pcm.size() - pos); + transcribe_stream_update update; + transcribe_stream_update_init(&update); + if (const transcribe_status st = + transcribe_stream_feed(session, pcm.data() + pos, static_cast(take), &update); + st != TRANSCRIBE_OK) { + std::fprintf(stderr, "stream: feed failed: %s\n", transcribe_status_string(st)); + ++g_failures; + break; + } + } + transcribe_stream_update final_update; + transcribe_stream_update_init(&final_update); + if (const transcribe_status st = transcribe_stream_finalize(session, &final_update); st != TRANSCRIBE_OK) { + std::fprintf(stderr, "stream: finalize failed: %s\n", transcribe_status_string(st)); + ++g_failures; + } + const char * text = transcribe_full_text(session); + std::string out = text != nullptr ? text : ""; + transcribe_session_free(session); + return out; +} + +} // namespace + +int main() { + const char * model_env = std::getenv("TRANSCRIBE_GIGAAM_V4_GGUF"); + if (model_env == nullptr || model_env[0] == '\0' || !file_exists(model_env)) { + std::fprintf(stderr, "gigaam_stream_real_smoke: TRANSCRIBE_GIGAAM_V4_GGUF is unset or missing; skipping\n"); + return 77; + } + const std::string wav_path = std::string(TRANSCRIBE_TEST_SAMPLES_DIR) + "/jfk.wav"; + std::vector pcm; + std::string wav_error; + if (!transcribe_cli::load_wav_mono_16k(wav_path, pcm, wav_error) || pcm.empty()) { + std::fprintf(stderr, "gigaam_stream_real_smoke: %s\n", wav_error.c_str()); + return EXIT_FAILURE; + } + + transcribe_model_load_params mp; + transcribe_model_load_params_init(&mp); + transcribe_model * model = nullptr; + if (const transcribe_status st = transcribe_model_load_file(model_env, &mp, &model); st != TRANSCRIBE_OK) { + std::fprintf(stderr, "gigaam_stream_real_smoke: load failed: %s\n", transcribe_status_string(st)); + return EXIT_FAILURE; + } + + for (const Case & c : kCases) { + if (!set_env("TRANSCRIBE_GIGAAM_STREAM_CONTEXT_MS", c.context_ms)) { + std::fprintf(stderr, "gigaam_stream_real_smoke: cannot set the context preset\n"); + ++g_failures; + continue; + } + const std::string text = stream_once(model, pcm); + if (text != c.text) { + std::fprintf(stderr, "FAIL %s ms:\n got: %s\n want: %s\n", c.context_ms, text.c_str(), c.text); + ++g_failures; + } + } + + transcribe_model_free(model); + if (g_failures != 0) { + std::fprintf(stderr, "gigaam_stream_real_smoke: %d failures\n", g_failures); + return EXIT_FAILURE; + } + std::fprintf(stdout, "gigaam_stream_real_smoke: ok\n"); + return EXIT_SUCCESS; +} From 9fba5a30e965e28b68e3d13530b184f470cb9622 Mon Sep 17 00:00:00 2001 From: Alexey Shabalin Date: Fri, 4 Dec 2026 19:16:47 +0300 Subject: [PATCH 11/11] test(gigaam): align the streaming tests with the merged loader checks The Multilingual-v2 merge (#311) validates the Zapformer frontend dimensions before the streaming block, so a zero-subsampling fixture no longer reaches the streaming check; drop it. Also fix a leftover loop header from merging the mutant table. --- tests/CMakeLists.txt | 1 - tests/fixtures/make_gguf_fixtures.py | 1 - tests/gigaam_smoke.cpp | 41 +++++++++++++--------------- 3 files changed, 19 insertions(+), 24 deletions(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 0be06da8b..e11c7f819 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -657,7 +657,6 @@ set(TRANSCRIBE_FIXTURE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_stream_too_many_contexts.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_frontend_hop_zero.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_frontend_win_gt_fft.gguf - ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_stream_zero_subsampling.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_pred_zero_layers.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_gigaam_v4_bad_pred_two_layers.gguf ${CMAKE_CURRENT_SOURCE_DIR}/fixtures/arch_qwen3_asr_minimal.gguf diff --git a/tests/fixtures/make_gguf_fixtures.py b/tests/fixtures/make_gguf_fixtures.py index 20e8776ef..17e8af689 100644 --- a/tests/fixtures/make_gguf_fixtures.py +++ b/tests/fixtures/make_gguf_fixtures.py @@ -1049,7 +1049,6 @@ def _with_stage(hp: dict, key: str, stage: int, value: int) -> dict: # checks but overflows hop * sub * 1000 before the divide. ("frontend_hop_zero", {**GIGAAM_V4_HP, "fe_hop_length": 0}, None), ("frontend_win_gt_fft", {**GIGAAM_V4_HP, "fe_win_length": 128}, None), - ("stream_zero_subsampling", {**GIGAAM_V4_HP, "enc_subsampling_factor": 0}, None), # The decoder drives one predictor LSTM layer; zero would index empty # weight arrays, more than one would be silently ignored. ("pred_zero_layers", {**GIGAAM_V4_HP, "pred_n_layers": 0}, None), diff --git a/tests/gigaam_smoke.cpp b/tests/gigaam_smoke.cpp index 8240dc6a7..5bd203512 100644 --- a/tests/gigaam_smoke.cpp +++ b/tests/gigaam_smoke.cpp @@ -286,26 +286,25 @@ struct Mutant { int main() { static const Mutant kMutants[] = { - { "arch_gigaam_multilingual_v2_duplicate.gguf", "invalid or duplicate language code" }, - { "arch_gigaam_v4_bad_odd_qdim.gguf", "qdim=3" }, - { "arch_gigaam_v4_bad_even_conv_kernel.gguf", "conv_kernel=4" }, - { "arch_gigaam_v4_bad_zero_downsampling.gguf", "downsampling=0" }, - { "arch_gigaam_v4_bad_intermediate_downsampling.gguf", "downsampling 2 is not supported" }, - { "arch_gigaam_v4_bad_mixed_qdim.gguf", "qdim 6 differs from stage 0 qdim 4" }, - { "arch_gigaam_v4_bad_symmetric_frontend.gguf", "causal_frontend=false" }, - { "arch_gigaam_v4_bad_short_stage_array.gguf", "stage_dims has 2 entries" }, - { "arch_gigaam_v4_bad_squeezeformer.gguf", "encoder.type=squeezeformer" }, - { "arch_gigaam_v4_bad_stream_frame_mismatch.gguf", "but the frontend produces a 8 ms frame" }, - { "arch_gigaam_v4_bad_stream_frame_zero.gguf", "frame_ms is 0, expected 1..200" }, - { "arch_gigaam_v4_bad_stream_future_not_multiple.gguf", "future=324 ms" }, - { "arch_gigaam_v4_bad_stream_future_out_of_bounds.gguf", "future=40960 ms" }, - { "arch_gigaam_v4_bad_stream_left_out_of_bounds.gguf", "left=257 frames" }, - { "arch_gigaam_v4_bad_stream_too_many_contexts.gguf", "more bands than the encoder has stages" }, - { "arch_gigaam_v4_bad_frontend_hop_zero.gguf", "invalid frontend geometry" }, - { "arch_gigaam_v4_bad_frontend_win_gt_fft.gguf", "invalid frontend geometry" }, - { "arch_gigaam_v4_bad_stream_zero_subsampling.gguf", "needs a positive encoder subsampling factor" }, - { "arch_gigaam_v4_bad_pred_zero_layers.gguf", "n_layers is 0, expected 1" }, - { "arch_gigaam_v4_bad_pred_two_layers.gguf", "n_layers is 2, expected 1" }, + { "arch_gigaam_multilingual_v2_duplicate.gguf", "invalid or duplicate language code" }, + { "arch_gigaam_v4_bad_odd_qdim.gguf", "qdim=3" }, + { "arch_gigaam_v4_bad_even_conv_kernel.gguf", "conv_kernel=4" }, + { "arch_gigaam_v4_bad_zero_downsampling.gguf", "downsampling=0" }, + { "arch_gigaam_v4_bad_intermediate_downsampling.gguf", "downsampling 2 is not supported" }, + { "arch_gigaam_v4_bad_mixed_qdim.gguf", "qdim 6 differs from stage 0 qdim 4" }, + { "arch_gigaam_v4_bad_symmetric_frontend.gguf", "causal_frontend=false" }, + { "arch_gigaam_v4_bad_short_stage_array.gguf", "stage_dims has 2 entries" }, + { "arch_gigaam_v4_bad_squeezeformer.gguf", "encoder.type=squeezeformer" }, + { "arch_gigaam_v4_bad_stream_frame_mismatch.gguf", "but the frontend produces a 8 ms frame" }, + { "arch_gigaam_v4_bad_stream_frame_zero.gguf", "frame_ms is 0, expected 1..200" }, + { "arch_gigaam_v4_bad_stream_future_not_multiple.gguf", "future=324 ms" }, + { "arch_gigaam_v4_bad_stream_future_out_of_bounds.gguf", "future=40960 ms" }, + { "arch_gigaam_v4_bad_stream_left_out_of_bounds.gguf", "left=257 frames" }, + { "arch_gigaam_v4_bad_stream_too_many_contexts.gguf", "more bands than the encoder has stages" }, + { "arch_gigaam_v4_bad_frontend_hop_zero.gguf", "invalid frontend geometry" }, + { "arch_gigaam_v4_bad_frontend_win_gt_fft.gguf", "invalid frontend geometry" }, + { "arch_gigaam_v4_bad_pred_zero_layers.gguf", "n_layers is 0, expected 1" }, + { "arch_gigaam_v4_bad_pred_two_layers.gguf", "n_layers is 2, expected 1" }, }; const std::string valid = fixture_path("arch_gigaam_v4_minimal.gguf"); @@ -350,8 +349,6 @@ int main() { check_silent_run(model, "ru", TRANSCRIBE_ERR_UNSUPPORTED_LANGUAGE); transcribe_model_free(model); - for (const char * name : mutants) { - for (const Mutant & m : kMutants) { clear_log(); transcribe_model * bad = nullptr;