082a50e3a0475cd0b4f81f74d3deffca98146fc1
62
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
ae53983c03 |
style: cargo fmt --all (18 files)
Auto-merged by ci-doctor. |
||
|
|
7e576e8d69 |
rtx-csm: implement LoRA merge + load-from-path
Closes the LoRA inference path that was previously stubbed. Two new public APIs in rtx-csm: 1. lora::load_lora_set_from_safetensors(path, config) -> LoraSet Reads a trained adapter file (produced by training:: save_lora_adapter[_with_metadata]). Pairs the .lora_a / .lora_b tensors by base-weight prefix into LoraAdapter entries. 2. lora::merge_into_safetensors(base, lora, scale, output) Reads the base CSM safetensors, folds in the LoRA deltas at the given scale (typically alpha/rank from training), writes a merged safetensors. Original dtype preserved (F16 on Metal, BF16 on CUDA, F32 on CPU). Tensors LoRA doesn't target are passed through unchanged. 3. Generator::load_csm_1b_from_path(path, device) Variant of load_csm_1b that takes an explicit weights path instead of going through the HF cache. Mimi + tokenizer still resolve via the hub. This is the path consumers use to load a merged checkpoint. MergeReport struct restructured to expose merged/skipped/passthrough counts so callers can verify the adapter actually targeted weights. The previous typed-error test is replaced with a missing-base-file test that exercises the real code path. Used by zeroclaw-channel-voice's `--lora-adapter` flag to bake a LoRA adapter into a per-process merged checkpoint at boot, with zero per-inference overhead. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
8a50a1efcd |
rtx-csm: pre-sentence hook + streaming-safe post-process
Two additions for downstream voice-channel prosody / quality wiring:
1. Converse::with_pre_sentence_hook
New PreSentenceHook (Box<dyn FnMut(&mut Generator, &str) -> Result<()>>)
that fires before each sentence's synth call. Receives mutable
access to the underlying Generator + the sentence text — lets
callers apply per-sentence steering (e.g. emotion shifts mid-reply)
without touching crate internals. Wired into both `synthesize` and
`synthesize_streaming` paths.
2. PostProcess streaming split
- New StreamingHpfState — stateful biquad whose IIR taps carry
across chunk boundaries so streaming HPF doesn't click at chunk
joins. Identical filter coefficients to the one-shot path.
- PostProcess::apply_chunk_safe(samples, hpf_state) — HPF + declick
per chunk, no LUFS (needs full utterance).
- PostProcess::apply_lufs(samples, sample_rate) -> Result<f32> —
full-utterance loudness gain, returns the linear gain applied
so streaming pipelines can compensate retroactively if needed.
- compute_lufs_gain helper extracted from loudness_normalize.
Used by zeroclaw-channel-voice for the Maya-gap-closure pack.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
bf5e86c549 |
rtx-csm: Converse::with_context for persistent speaker prompt
Without a voice anchor, CSM-1B picks a different speaker each turn
and drifts mid-sentence on longer outputs (high-pitch squeaks,
female/male swap mid-utterance). The fix is the standard CSM
speaker-prompt pattern: pass a Segment with reference audio + its
transcript as context to every generate() call.
Previously Converse::synthesize and synthesize_streaming hardcoded
`&[]` for the context arg. Add a `context: Vec<Segment>` field on
Converse plus a builder method:
let conv = Converse::new(&llm, &mut gen)
.with_context(vec![Segment::new(0, transcript, audio)]);
Both synth paths now pass `&self.context` instead of `&[]`. Empty
context (default) keeps prior behavior.
Verified end-to-end with zeroclaw-channel-voice + macOS `say`-
generated reference: same input now produces deterministic-length
output across turns (2.64s vs. previously varying 6/19/38s) and the
voice matches the seed throughout.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
a5cedfb46a |
rtx-csm: emotional_speech_guide — CREMA-D vs RAVDESS firdhokk verdict
8-gen bench (4 emotions × 2 corpora) at seed=42 against firdhokk Whisper-LV3: target RAVDESS CREMA-D happy happy (0.999) ✓ happy (0.999) ✓ angry neutral (0.92) sad (0.99) fearful happy (0.998) fearful (0.984) ✓ sad angry (0.99) fearful (0.99) CREMA-D 2/4 vs RAVDESS 1/4. Larger / more naturalistic corpus produces more class-pure fearful direction. Neither corpus solves angry or sad — recipe shifts into 'vague expressivity' rather than class-specific corners. Practical: prefer CREMA-D when available; A/B both per emotion if class precision matters. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
6a03aeba61 |
fix(cuda+csm): P0 rtx-backend-cuda compile fix + P2 rtx-csm clippy cleanup (#9)
Co-authored-by: Omar Sobh <[email protected]> Co-committed-by: Omar Sobh <[email protected]> |
||
|
|
99a7e53aa8 |
rtx-csm: decoder activation capture — architectural hypothesis validated
Adds capture_decoder_activations on Model and ModelBackend, plus
--target-module decoder|backbone on examples/steering_extract.
Decoder mode runs a text-only prompt through the backbone (no
capture), Mimi-encodes the audio separately to grab the middle
frame's c0 token, teacher-forces that c0, and captures one mean-
pooled-over-seq vector per decoder layer. Result: 4 layers ×
1024 embed dim per call, much faster than backbone capture
(text-only prompts are short).
A/B with the canonical "Today I want to share..." prompt at seed
7 (the previously-identified low-WER seed):
case cos WER transcript
baseline 0.76 0.36 "And today I want to share something some
funnel distraits" (high baseline at this
seed)
[email protected] 0.75 5.00 "Today, I want to share some needs of my
prey" (backbone destroys content)
[email protected] 0.86 0.93 "I'm not that tall. I'm not that tall."
(fluent but repetitive — biggest cos)
[email protected] 0.61 2.57 over-steered
[email protected] 0.61 2.14 broken
[email protected] is the largest speaker_cosine boost we've measured AND
produces clean English. Backbone steering at the same seed destroyed
content fidelity. This validates the architectural hypothesis: the
backbone carries semantic content (what the model says), the depth
decoder carries acoustic detail (how it sounds). Steering the
decoder shifts voice character without disturbing word content the
way backbone steering does.
Open issues: [email protected] produces repetitive output ("I'm not that
tall" three times). Likely lower scale (~0.5) plus the existing
repetition guard would fix it; left for follow-up.
Decoder vector magnitudes are ~10× smaller than backbone (norm 0.85
at deepest layer vs 14.9), so the appropriate scale is ~10× higher
than the backbone recipe (1.0 vs 0.1-0.3).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
a1fa72d151 |
rtx-csm: depth-decoder steering API
Adds set_decoder_steering on Model + Generator and --decoder-steering-vec / --decoder-steering-scale on examples/generate. The decoder is already a LlamaModel under the hood, so the existing LayerSteering hook in csm_fork::Layer::forward applies as-is — only the public surface needed wiring. Architectural hypothesis being tested: backbone carries semantic content (what the model says), depth decoder carries acoustic detail (how it sounds). Backbone steering shifts character at the cost of text fidelity (Sprint 2 finding); decoder steering should shift prosody/timbre without disturbing word content. Smoke test with random Gaussian decoder vectors (4 layers × 1024 embed_dim, stddev 0.1, scale 0.5): case cos WER transcript baseline 0.72 1.0 "No." backbone 0.83 1.4 "That's for on-beat for bee..." decoder 0.76 1.0 "So" (premature EOT) both 0.81 3.0 "I'm going to go to the next one..." Decoder steering DOES alter output (cosine 0.72 → 0.76, transcript changes) but random vectors trigger premature EOT — same pattern as random backbone vectors. The infrastructure works; getting the real emotion-from-acoustic-codebooks signal needs decoder activation capture, which the current Model::capture_backbone_activations doesn't do (it captures the backbone forward only). Decoder capture is the next-session item. With it we can extract real per-emotion decoder vectors from RAVDESS and test the hypothesis properly. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
af6c246ef6 |
rtx-csm: layer-subset steering — recovers Sprint 2 fluency
EmoSteer-TTS (arXiv 2508.03543) targets only a spaced subset of
middle-to-deep DiT layers (1, 6, 11, 16, 21 of 32) rather than every
layer. Previously our LayerSteering applied all 16 vectors which —
combined with the noisy emotion-label corpus from Phase B — destroyed
output fluency at scale 0.5.
Adds:
- LayerSteering::restrict_to_layers(&[usize]) — clears every vector
whose index isn't in the allowlist. Plus active_layers() inspector
and a unit test.
- examples/generate --steering-layers 8,10,12 — comma-separated CLI
flag that runs restrict_to_layers after load.
A/B with the existing excited-vs-surprised vectors at scale=0.5
across five layer subsets:
case cos WER transcript
baseline 0.45 0.92 "It is a very important thing to do."
all16 0.37 1.00 "© transcript Emily Beynon" (broken)
[8,10,12] 0.63 0.54 "I want to talk about something." ✓
[4,8,12] 0.42 1.00 "Oh, my God." (broken — layer 4 too early)
[12-15] 0.48 0.77 "I want to have fun with that."
The mid-layer subset is the clear winner — highest speaker cosine,
lowest WER, transcript closest to the prompt ("Today I want to talk
about something genuinely important..."). Including layer 4 destroys
output fluency even at scale 0.5, validating the paper's avoidance of
shallow layers. Pure-deep is between mid and broken.
This unblocks Phase B's empirical validation: even with the noisy
auto-tagged corpus, the extracted vectors produce meaningful steering
when applied to the right layers. A real labeled emotion dataset
should compound from here.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
6b69fb68c7 |
rtx-csm: Sprint 3 — Selective CFG schedule (step / linear / const)
Per-frame CFG scale schedule (arXiv 2509.19668, Zheng & Maleki). Pure
inference-time. Standard CFG uses one fixed scale for the whole
sequence; this lets the scale vary across frames so early frames
(speaker character) get full CFG and later frames (text adherence)
get a lower scale.
What lands:
- src/cfg_schedule.rs: CfgSchedule enum (Constant / Step /
LinearRamp), scale_at(frame_idx), parser for CLI form
`step:E:L:T | linear:S:E:R | const:X`. 6 unit tests.
- src/generator.rs: GenerateOptions::cfg_schedule (takes precedence
over legacy cfg_scale; fixed-f64 path is preserved as
Constant(s) for back-compat). Generation loop reads
schedule.scale_at(frame_idx) and passes per-frame to
generate_frame_cfg.
- examples/generate.rs: --cfg-schedule, --cfg-scale, --enable-cfg
flags. Loading via load_csm_1b_with_cfg when --enable-cfg.
A/B with 6s output on Amini context, prompt about Selective CFG:
case cos WER transcript
no-CFG baseline 0.944 1.50 "Okay, the M.U. worked..." (off)
const:2.0 0.854 0.92 "On the right side." (short)
step:3.0:1.5:12 0.938 1.00 "The officer for the selective
C.F.D. paper recommends" (best)
linear:3.0:1.0:25 0.854 1.08 "On the surface..." (off)
Step schedule produces the transcript closest to the input ("the
selective CFG paper recommends..."). WER stays at 1.0 because
Moonshine doesn't know "CFG" as a word, but qualitatively this is
the only one that's coherently following the prompt. Speaker cosine
stays ≈ baseline (0.94) instead of dropping to 0.85 like the
constant and linear cases.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
3a67e4aa50 |
rtx-csm: Sprint 2 Phase B — steering vector extractor
Closes the loop on Phase A (apply hook). Adds:
- LlamaModel capture buffer + start/take_capture API. Pushes one
mean-pooled-over-seq activation per layer into a per-call Vec when
active. Steering apply runs first, so captures reflect post-steering
state when both are on (extractor disables steering for the duration
of the call to capture baseline activations).
- Model::capture_backbone_activations: teacher-forced forward over a
built prompt, returns per-layer (embed_dim,) activation tensors.
- ModelBackend passthrough; FP-only (Quantized errors out).
- examples/steering_extract: reads emotion-labeled JSONL, accumulates
per-emotion sums on CPU f32, writes per-layer
(mean(target) - mean(baseline)) as `layer_<i>_steering` safetensors.
Smoke run on carlini2 manifest (excited vs surprised, 10 samples each):
- Vector norms grow monotonically with depth (layer 0: 2.25, layer 15:
12.61) — consistent with deeper layers carrying richer
emotion/style signal.
- Loaded into examples/generate at scales 0.5/1.0/2.0; quality_eval
shows WER hits 1.0 immediately. This is the EmoSteer paper's warning
("large α may produce unintelligible speech") triggering at small
α — diagnosis: the corpus is the problem, not the infrastructure.
The emotion_tag labels in our existing manifests are noisy
(emotion2vec output on lecture audio collapses to [surprised] /
[excited] without a clean neutral pool), and 10 samples per pool
is well short of the paper's 1000/emotion.
What this validates:
- End-to-end extraction → save → load → apply pathway works.
- quality_eval (Sprint 1) cleanly catches the regression — the metric
foundation does its job.
What's next (a future session):
- Real emotion-labeled dataset (CREMA-D, ESD, RAVDESS) for proper
pools with a true neutral baseline.
- Layer-subset experiments (paper steers layers 1,6,11,16,21 of 32;
for our 16-layer backbone the analogue is roughly 1, 4, 8, 12).
- Listening test alongside the metric numbers.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
aa274f2210 |
rtx-csm: Sprint 2 Phase A — activation steering API
Adds the apply hook for ActAdd-style activation steering on the Llama
backbone. Inspired by EmoSteer-TTS (arXiv 2508.03543), but adapted: the
paper is flow-matching-specific (DiT layers, 32 CFM steps, per-token
attribution search via mel synthesis), none of which apply to CSM's
autoregressive Llama-over-Mimi-tokens. What's portable is the
underlying difference-in-means construction with residual-stream
addition — the standard ActAdd / contrastive-steering pattern.
What lands:
- src/steering.rs: LayerSteering type, per-layer (1, embed_dim) tensors,
global scale, safetensors load with keys `layer_<i>_steering`. Three
unit tests covering empty/no-op, dimension validation, and apply math.
- src/csm_fork.rs LlamaModel: optional `steering: Option<LayerSteering>`
field, applied after every layer's forward inside the for-loop. Adds
~3 LOC to the hot path; gated by the Option so unsteered generation
has zero cost beyond a None check.
- src/csm_fork.rs Model::set_backbone_steering: installs steering only
on the conditional backbone (cfg_backbone is intentionally left
un-steered so CFG correctly subtracts an unsteered baseline).
- src/generator.rs Generator::set_steering: errors on quantized
backend (only FP supported for now).
- examples/generate.rs: --steering-vec / --steering-scale flags.
- examples/steering_random.rs: smoke helper that writes random Gaussian
vectors so the apply path can be exercised end-to-end before the
real corpus extractor lands. Box-Muller via seeded rand to avoid an
extra rand_distr dep.
Smoke test (16-layer random Gaussian, stddev=0.05, scale=0.5):
- baseline (no steering, same seed/text): 3.04 s @ RMS -19.5 dB
- steered (random vectors): 1.84 s @ RMS -16.2 dB,
EOT triggered earlier
Output clearly differs — pathway is wired correctly. Random vectors
aren't musically meaningful; that's Phase B.
Phase B (next session): corpus extractor that runs forward passes over
emotion-labeled audio (we already have audio_to_manifest emitting
emotion_tag rows), captures per-layer post-residual activations, and
computes the difference-in-means between emotion_X and neutral pools.
Then A/B with quality_eval.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
adc9784646 |
rtx-csm: Stt::finish() — drain asr_delay buffer at end-of-stream
Phase 8.1.1 quality fix from the perf plan. Tokens emitted at LM step
`t` correspond to audio frame `t - ASR_DELAY_FRAMES` (6 frames /
0.48 s), so when a caller stops feeding audio without trailing
silence the last few words trail off — they're still inside the
delay pipeline.
finish() now steps ASR_DELAY_FRAMES additional silent frames after
handling any partial sub-frame buffer, giving the LM the chance to
emit those buffered tokens. Cost: 7 extra step_pcm calls per turn.
Verified end-to-end via stt_demo on a mid-utterance trim of the
LibriSpeech reference clip:
pre-flush: 11 words ("...turnips and carrots and bruised")
post-flush: 13 words ("...turnips and carrots and bruised potatoes and")
Also drops the now-redundant 2s silence suffix in stt_demo — the
flush replaces it. Affects converse_server's real-time end-of-turn
path where suffix padding wasn't possible.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
0568dd3653 |
rtx-csm: drop Mimi reload cadence to every-10 clips
Empirical: with 25-clip cadence the cumulative state still tipped over once at position 8102 mid-window during a 167-clip lora_eval load. Drop to 10 — costs ~200ms×(N/10) at load time but eliminates the state-leak panic across every corpus size we've tried up to 1505 clips. Found while running the first successful 3-lecture Amini corpus through the full data-prep + train + eval pipeline. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
d42aba0f1b |
rtx-csm: emotion2vec input normalization + 9-class direct mapping
Three real bugs found while running a YouTube → train → eval pipeline end-to-end on real corpora: 1. emotion2vec was producing near-constant logits regardless of input. Per config.yaml `normalize: true` — data2vec2/emotion2vec expects per-utterance zero-mean unit-variance normalization on the raw waveform before the local_encoder. Added inside the EmotionDetector trait impl so all callers get it. Verified empirically: 4 different audio inputs (Carlini talk, audience question, McConaughey speech) now produce different argmax classes. Before fix: all 4 produced identical logits. 2. The 9→5 emotion fold was collapsing every real-world clip to [excited]. happy / surprised / other all mapped to Excited covered ~95% of natural speech. Replaced with a direct 9-class identity mapping; EmotionLabel gained Disgusted, Fearful, Happy, Surprised, Unk variants. Now: 132 [surprised] + 12 [excited] across the Carlini corpus instead of 144 [excited]. 3. lora_train_emotional --peak-lr / --epochs flags. The canned 3-stage recipe over-fits on small (~100 clip) corpora at extended rank 8; users need to tune. (The recipe stays as defaults; flags are pure overrides.) Plus diagnostic: examples/emotion2vec_probe — feed real audio files into emotion2vec and dump per-class logits. Used to find bug #1. Lib suite still 131/131 (the test that locked the 9→5 fold updated to lock the new identity mapping). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
b4a7133ffb |
rtx-csm: Mimi.reload() — workaround state-leak in cumulative encode loop
Mimi's transformer carries an internal position counter across encode()
calls that the upstream `reset_state()` does NOT fully clear. When
TrainingDataset::load_from_manifest encodes ~80-100 clips back-to-back
during data prep, the counter overflows the 8192-position buffer and
panics with `narrow invalid args [8192, 32]`.
src/mimi.rs:
- cache the safetensors path on Mimi at construction
- new Mimi.reload() drops the inner Model and rebuilds from the
cached path (~200 ms on Metal)
src/training.rs:
- call generator.mimi.reload() every 50 clips during
load_from_manifest. Adds ~1 s overhead on a 200-clip corpus
(4 reloads × ~200 ms) vs the alternative of a hard panic.
- reset_state() before each encode in TrainingExample::from_audio
is kept (still useful to clear streaming chunk state).
Found while running the end-to-end personal-voice training pipeline on
a 20-minute YouTube source: the bug surfaces around clip 86 when
Mimi's transformer hits position 8181+. Filtering to short clips
alone didn't help — the cumulative state grows even with sub-12-second
inputs.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
83654b677b |
rtx-csm: Phase 13.9 — wav2vec2 slice 4 (CTC Viterbi forced alignment)
Word-level forced alignment shipped. Phase 13.9 complete. viterbi_align(log_probs, tokens, blank_id, vocab) — standard CTC forced-alignment trellis: states alternate [blank, t0, blank, t1, ..., tN, blank] (length 2N+1), at each frame stay/advance/ε-skip-blank- between-different-tokens (canonical CTC ε-skip rule correctly forbids skipping blank between SAME tokens), max-likelihood path recovered via backptr table. transcript_to_token_ids — text → CTC token ids; runs of spaces collapse to | separator; unknown chars → <unk>. group_into_words — fold adjacent non-| AlignedToken into AlignedWord with carried frame_start/frame_end. frame_to_ms — 50 Hz frame grid → ms (20 ms/frame at conv stride 320). examples/wav2vec2_smoke --align <target> wires it end-to-end: forced-aligns a known transcript and prints (word, start_ms, end_ms). Verified on Metal: 10.42 s LibriSpeech audio, first 8 words → HE 560-640 HOPED 720-960 THERE 1000-1140 WOULD 1180-1320 BE 1360-2240 STEW 2980-4720 FOR 5300-6000 DINNER 7040-8540 viterbi alignment in 0 ms (39 tokens). Boundaries match audio. 4 new unit tests: - transcript_to_token_ids_handles_spaces_and_unknowns - viterbi_align_recovers_obvious_alignment - group_into_words_splits_on_separator - frame_to_ms_50hz_grid Lib suite 131/131 (was 127, +4). Phase 13.9 complete (slices 1+2+3+4). Crate now ships full English ASR + word-level forced alignment in pure candle — no whisper.cpp, no ort, no Python. Data-prep can cut long audio at exact word boundaries before feeding into the Phase 12.3 curriculum trainer. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
209279c13e |
rtx-csm: Phase 13.9 — wav2vec2 candle port (slices 1+2+3, real ASR working)
Full port of facebook/wav2vec2-base-960h (94.4 M params, MIT) closing
the WhisperX-class word-alignment gap from the audio-ML survey. Same
staged-scaffolding pattern that worked for emotion2vec — but landed
slices 1+2+3 in one session.
src/wav2vec2.rs ships:
- Wav2Vec2Config::base_960h
- FeatureExtractor — 7 Conv1d (1→512, total stride 320). Layer 0
uses GroupNorm with num_groups=num_channels=512 (HF's wav2vec2
feat_extract_norm: "group"). Critical: state-dict key is
layer_norm.* but the OP is GroupNorm — loading as LayerNorm
produces empty CTC output.
- FeatureProjection — LayerNorm(512) + Linear(512→768)
- ConvPosEmbedding — kernel 128 grouped Conv1d, materialized at
load time from upstream weight_g + weight_v (fairseq's weight_norm
on dim=2; eps-guarded division for numerical stability)
- Block — POST-norm transformer with separate Q/K/V (vs emotion2vec's
fused QKV), uses (B*H, T, D) Metal 3D-matmul workaround from
Phase 8.8 Moonshine
- Encoder — pos_conv + initial LayerNorm + 12 Blocks
- Wav2Vec2 top-level — load_from_safetensors via mmap'd VarBuilder
- ctc_greedy_decode + VOCAB_960H constant for the 32-char alphabet
examples/wav2vec2_inspect.rs (slice 1): dumps tensor layout + config
examples/wav2vec2_smoke.rs (slice 3): real-weight load + ASR forward
Verified on Metal:
loaded model in 0.28 s
forward in 9 ms for 10.42 s audio (~1150× realtime)
transcript: "HE HOPED THERE WOULD BE STEW FOR DINNER TURNIPS AND
CARROTS AND BRUISED POTATOES AND FAT MUTTON PIECES TO
BE LADLED OUT IN THICK PEPPERED FLOWER FAT AND SAUCE"
Numerical parity with upstream Python — the FLOWER-for-FLOUR typo is
the known wav2vec2-base-960h failure mode, matches HF reference exactly.
7 new unit tests; lib suite 127/127 (was 120).
Slice 4 remaining: Viterbi forced alignment given known transcript,
to emit (token, frame_start_ms, frame_end_ms) for word-boundary cuts.
The ASR path itself is now production-ready.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
f50233a9cc |
rtx-csm: Phase 13.8 — emotion2vec port, slice 4 (EmotionDetector + integration)
Port complete. The Phase 13.3 prosody-rule placeholder is now
retire-able by setting one CLI flag — the real candle-ported
emotion2vec_plus_base classifier slots in behind the same
EmotionDetector trait the placeholder used.
impl EmotionDetector for Emotion2Vec — builds (1, 1, T) tensor on
stored device, runs forward, argmaxes the 9 logits, maps to the
5-bucket label via Classifier::tag_for_class. Empty input
short-circuits to Neutral.
Emotion2Vec struct gained a `device` field so the trait impl can
build tensors without an out-of-band handle. new() / load_from_pickle()
threaded through; existing tests + smoke binary updated.
audio_to_manifest --use-emotion2vec — pairs with --auto-emotion-tag
to swap ProsodyDetector for Emotion2Vec, boxed as
Box<dyn EmotionDetector> so the call site is unchanged.
converse_server --use-emotion2vec — same pattern; built once at boot
and stored in Shared as Box<dyn EmotionDetector + Send + Sync>.
~150 ms/turn forward cost vs <1 ms for prosody, but actually runs
SOTA SER. Removed redundant reactive_emotion: bool field — the
Option<Box<dyn>> already encodes the same state.
Verified end-to-end on Metal:
- audio_to_manifest --use-emotion2vec on 2-speaker concat → both
tagged [excited] (prosody had said [neutral] on same input)
- converse_server --quantized-gguf … --lora … --reactive-emotion
--use-emotion2vec boots, 1 bench turn 0 errors, /metrics shows
reactive_emotion_total{label="excited"} 1 — same tag
audio_to_manifest produced. Cross-consumer consistency.
Phase 13.8 complete (slices 1+2+3+4 shipped). The emotional-voice
stack now has a real, trained, candle-ported SER classifier with
no Python sidecar, no ort, no whisper.cpp.
Lib suite 120/120.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
9c1894ec73 |
rtx-csm: Phase 13.8 — emotion2vec port, slice 2d (real weights load + forward)
Slice 2 complete + slice 3 collapsed in. The full candle port loads
real upstream weights and runs forward in 160 ms.
RelativePositionalEncoder — 5 grouped Conv1d (kernel 19, groups 16,
same-padding via pad 9) with GELU between. Output is added back to
input as a positional bias. Pickle keys
relative_positional_encoder.{1..=5}.0.weight/bias (1-based indexing,
no .0.*).
Emotion2Vec top-level — wires LocalEncoder → ProjectFeatures →
RelPosEnc → ContextEncoder → MainEncoder → mean-pool → Classifier.
The proj.* classifier head lives at the state-dict root (not under
d2v_model.), so the constructor uses vb directly there.
Emotion2Vec::load_from_pickle uses VarBuilder::from_pth_with_state
to descend into the fairseq-style nested checkpoint via the "model"
key. One-shot loader; all 185 upstream tensor keys must map onto
candle params of matching shape — and they do.
examples/emotion2vec_smoke.rs — full pipeline integration test:
downloads (or reuses cached) emotion2vec_plus_base from HF, loads it
into candle, runs forward on 2 s of synthetic audio, prints all 9
raw logits + argmax + the 9→5 bucket fold.
Verified on Metal:
loaded model in 0.19 s
forward in 160 ms
9 logits all finite (50-290 range, expected for raw classifier)
argmax: class 7 (surprised) → 5-bucket [excited]
Mechanical correctness end-to-end. Semantic accuracy on real
emotional speech lands in slice 4 (EmotionDetector trait impl +
swap into audio_to_manifest + converse_server reactive-emotion path).
2 new unit tests:
- relative_positional_encoder_preserves_shape
- emotion2vec_random_init_end_to_end_shape
Lib suite 120/120 (was 118, +2).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
491f51565a |
rtx-csm: Phase 13.8 — emotion2vec port, slice 2c (Classifier + Encoders)
Three composition wrappers over the Block from slice 2b.
ContextEncoder — 4 Blocks + final LayerNorm
(context_encoder.blocks.0..3 + context_encoder.norm). Acts as a prenet
between ProjectFeatures and the main encoder.
MainEncoder — 8 Blocks, no final LayerNorm. Confirmed via inspector:
all 96 d2v_model.blocks.* tensors live inside numbered blocks; there's
no d2v_model.norm. Pre-norm pattern's per-block norm2 keeps residuals
conditioned without a global tail norm.
Classifier — single Linear 768→9 (proj.weight/proj.bias at the top of
the state dict, NOT under d2v_model.). Includes tag_for_class(idx)
that folds the 9 fine-grained model classes (angry/disgusted/fearful/
happy/neutral/other/sad/surprised/<unk>) into the 5-bucket label set
the Phase 13.3 EmotionDetector trait already uses:
- 0 angry → Angry
- 1 disgusted, 2 fearful,
6 sad → Sad (low valence)
- 3 happy, 5 other,
7 surprised → Excited (high arousal)
- 4 neutral, 8 <unk> → Neutral
4 new tests:
- context_encoder_chains_4_blocks_with_final_norm
- main_encoder_chains_8_blocks_no_final_norm
- classifier_emits_9_logits
- classifier_class_to_emotion_label_mapping (locks the 9→5 fold)
Lib suite 118/118 (was 114, +4 new).
Slice 2 remaining: relative_positional_encoder (5 Conv1d, the conv
positional bias) + top-level Emotion2Vec + .pt pickle loader. Then
slice 3 = forward pass + numerical parity check vs upstream Python.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
90f1b4667c |
rtx-csm: Phase 13.8 — emotion2vec port, slice 2b (ProjectFeatures + Block)
Two more candle modules toward the full port.
ProjectFeatures — LayerNorm(512) → Linear(512→768). Sits between
LocalEncoder and the transformer. Pickle layout matches upstream:
project_features.1.* is the LayerNorm, project_features.2.* is the
Linear. Both have learnable affine params; the .1 LN is NOT just an
eps constant.
Block — pre-norm fused-QKV transformer block, the workhorse for both
ContextEncoder (4 instances) and MainEncoder (8 instances). Pickle
keys per block: norm1, attn.qkv (fused 768→2304), attn.proj,
norm2, mlp.fc1, mlp.fc2. GELU MLP activation. No positional encoding
inside the block — the conv-based positional bias lives at the encoder
boundary.
Attention uses the (B*H, T, D) 3D collapse-before-matmul Metal
workaround we shipped for Phase 8.8 Moonshine — candle's 4D batched
matmul still has the shape-mismatch bug.
2 new unit tests:
- project_features_shape_check: (1, 50, 512) → (1, 50, 768)
- block_residual_shape_check: random (2, 8, 768) → same shape AND
all values finite (catches softmax NaN / attention overflow)
Lib suite 114/114 (was 112, +2 new).
Remaining within slice 2: relative_positional_encoder (5 Conv1d),
ContextEncoder (4 Blocks), MainEncoder (8 Blocks + LN), Classifier
(Linear 768→9), top-level Emotion2Vec + pickle .pt loader.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
ce00e48acb |
rtx-csm: Phase 13.8 — emotion2vec port, slice 2a (LocalEncoder)
First module of the candle port. src/emotion2vec.rs ships:
Emotion2VecConfig::plus_base() — embed_dim=768, depth=8, prenet_depth=4,
num_classes=9, conv_layers spec yielding stride-product 320 (16 kHz →
50 Hz feature frames).
LocalConvBlock — one Conv1d → LayerNorm → GELU block. Weight key layout
matches the upstream pickle exactly: .0.weight for the conv (no bias),
.2.1.weight/bias for the LayerNorm (upstream wraps it as
Sequential(Conv1d, Dropout, Sequential(TransposeLast, LayerNorm,
TransposeLast), GELU); we collapse dropout / transposes since they're
inactive at inference / handled inline via .transpose(1,2)).
LocalEncoder — 7-block stack, channels 1→512, time shrinks by stride
product. Output shape (B, 512, T/320) — for 16 kHz input that's a
50 Hz feature frame rate.
2 unit tests pass:
- config_stride_product_matches_320 (catches future spec drift)
- local_encoder_random_init_shape_check — builds via VarMap+Kaiming,
runs forward on 1 s of zeros, asserts (1, 512, ~50) output
Lib suite 112/112 (was 110, +2 new tests).
Remaining within slice 2: project_features, relative_positional_encoder,
Block (fused-QKV), ContextEncoder (4 prenet blocks), MainEncoder
(8 main blocks), Classifier, and top-level Emotion2Vec with .pt loader.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
ed4e5e4b85 |
rtx-csm: Phase 13.3 — prosody-rule SER baseline + --auto-emotion-tag
Closes the third gap from the audio-ML Rust ecosystem survey:
speech emotion recognition. Honest scope — this is a hand-tuned
placeholder, not a real classifier. The trait makes a future
emotion2vec_plus_base candle port a one-line swap.
src/ser.rs (~330 LOC):
- EmotionDetector trait
- ProsodyDetector impl: autocorrelation F0 (65-400 Hz, voiced via
autocorr peak ratio) + RMS + voiced-ratio aggregation
- 5 buckets compatible with Phase 12.2 emotion-hint format:
[neutral] [calm] [sad] [angry] [excited]
- 6 unit tests (autocorr accuracy on a pure tone, silence handling,
sad/excited/neutral edge cases, tag-format invariant)
audio_to_manifest gains --auto-emotion-tag: classifies each diarized
clip and writes the resolved label into the manifest row's
emotion_tag. Static --emotion-tag stays as a fallback.
End-to-end verified: 2-speaker concat → both clips classified
[neutral] (correct — synthetic CSM samples are prosodically flat).
Manifest round-trips through lora_train_emotional unchanged.
Lib suite 110/110 (6 new SER tests). Pure-DSP, zero ML deps, zero
runtime risk.
The data-prep pipeline is now end-to-end auto-labeled in-crate:
audio_to_manifest --auto-emotion-tag raw.wav → manifest.jsonl
→ lora_train_emotional → lora_eval → converse_server with --lora
Zero Python, zero ort, zero whisper.cpp.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
2feb5c9d67 |
rtx-csm: Phase 13.2 — audio→manifest pipeline (no Python sidecar)
Single command turns raw audio (podcast/audiobook/conversation) into a
training-ready JSONL manifest + per-segment clip wavs.
audio_to_manifest:
1. Diarize (Phase 13.1: Silero V5 + WavLM-SV + clustering)
2. Per segment: slice audio + Moonshine encode/decode → transcript
3. Write `<stem>.spk{N}.{idx:04}.wav` + manifest.jsonl
Manifest rows match ManifestRow exactly (Phase 12.3), so the output
flows directly into lora_train_emotional / load_from_manifest.
Knobs: --segments-json (reuse precomputed diar), --emotion-tag and
--stage applied uniformly, --min-transcript-chars filters ASR failures,
plus all Phase 13.1 diarization knobs.
DiarizedSegment gained serde::Deserialize for the segments-json
reuse path.
Verified end-to-end: 2-speaker concat → 2 segments diarized in 192 ms
→ Moonshine transcribed → 2 manifest rows + 2 clips written → round-
trips through lora_train_emotional cleanly (LoRA injected with extended
coverage, adapter saved with embedded metadata, lib suite 104/104).
The full no-Python data-prep loop now reads:
audio_to_manifest raw.wav → manifest.jsonl
lora_train_emotional manifest.jsonl → voice.safetensors
lora_eval base + lora for A/B
generate / converse_server with --lora voice.safetensors
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
73d38ed290 |
rtx-csm: Phase 13.1 — in-crate diarization (Silero V5 + WavLM-SV + clustering)
Composes existing in-crate parts into a speaker diarizer with zero new
deps. Pipeline: Silero V5 VAD → speech intervals → WavLM-SV x-vector
per ~2s window → agglomerative average-linkage clustering on cosine
distance → merged (start_s, end_s, speaker) segments.
src/diarize.rs (~330 LOC) ships:
- DiarizedSegment + DiarizationConfig
- Diarizer that owns the two backbones
- vad_intervals helper (smooths short silences, drops short speech)
- hand-rolled agglomerative cluster with auto-threshold OR force-k modes
- 5 unit tests (cosine distance edges, clustering, VAD interval extraction)
examples/diarize.rs CLI: --in --out --wavlm-sv-weights, plus knobs
(window/hop/vad-threshold/cluster-threshold/n-speakers/min-segment).
JSON output is consumable by ffmpeg/sox for downstream slicing.
Verified end-to-end on Metal:
- Single-speaker 10.41s → 1 segment, 21× faster than realtime
- Concatenated 2-speaker (CSM spk 0 + spk 1) → correctly identifies
2 speakers, 10× realtime
- Bug fixed in first run: clamp VAD interval bounds before slicing
(Silero V5 pads to whole-chunk multiple, can exceed sample count).
Closes the WhisperX-class "speaker diarization" gap from the personal
voice training guide without a Python/ort sidecar — sidesteps both
runtime conflicts the project hit before (whisper.cpp/ggml in Phase 7.6,
ort/protobuf in Phase 8.1.3). ~80% of pyannote-community-1 fidelity,
which is fine for data prep.
Lib suite 104/104 (5 new tests).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
f7b6deac1a |
rtx-csm: Phase 12.7 — lora_eval held-out quality harness
Closes the train→generate→evaluate cycle. Users can now produce a hard quality number for any adapter without listening manually. evaluate_held_out runs teacher-forced forward_loss over a JSONL manifest (same format as 12.3 trainer). Uses apply_emotion_hint so eval prompts match training prompts. Frame sampling is seed-controlled — identical seeds across runs score the same frames in the same order, which is what makes a base-vs-LoRA A/B fair. EvalRow + EvalSummary types, both serde-Serialize for JSON output. examples/lora_eval.rs wraps it: --eval-manifest --report [--lora]. Documented usage: run twice with the same seed, diff the summary blocks. Verified end-to-end on the existing 3-row curriculum manifest with seed=42, frames-per-example=4: LoRA shifted mean/median/p90 loss directionally in its favor (-0.011/-0.018/-0.007). Tiny because the test adapter only saw ~10 training steps, but the eval signal is real and the A/B path is wired. Lib suite 99/99. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
32a811904a |
rtx-csm: Phase 12.5 — self-describing LoRA adapters
Trained adapters now embed (rank, alpha, target_modules, crate_version) as JSON in safetensors __metadata__["rtx_csm_lora"]. apply_lora_adapter reads it at load time so users no longer have to remember matching --lora-rank/--lora-alpha/--extended-lora flags from training. LoraAdapterMetadata::is_extended() heuristic: target_modules contains any MLP path or output_proj or k_proj. Handles both the canonical extended() preset and future custom configs that overlap it. apply_lora_adapter rank/alpha/extended params became Option<_> (None = use file metadata, Some = override). Both callers updated. save_lora_adapter_with_metadata is the new path used by both trainers; the plain save_lora_adapter still exists for the metadata-less case (per-stage curriculum snapshots). safetensors dep bumped 0.4 → 0.7 to match candle 0.9's transitive pin so candle's Tensor: View impl is in scope for serialize_to_file (candle's own save wrapper hardcodes the metadata arg to None). Backward compat: pre-12.5 adapters load fine when explicit CLI flags are passed; auto-detect path is skipped silently. Verified end-to-end: trained adapter saved with metadata, `generate --lora <path>` (no other flags) auto-detected rank=8 alpha=16 extended=true and applied. Older metadata-less adapter still loaded with explicit flags. 3 new unit tests; lib suite 99/99. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
9d4eabc773 |
rtx-csm: Phase 12.4 — inference-time LoRA loading + extended-lora flag
Closes the train→generate loop the lora_train comment has promised
since Phase 3 ("forthcoming --lora flag on generate").
apply_lora_adapter(generator, path, rank, alpha, extended, device)
shared helper in src/training.rs wraps add_lora_to_backbone +
load_lora_adapter + refresh_lora. Both examples/generate and
examples/converse_server now call it instead of inlining their own
versions, and both now take --extended-lora to opt into Phase 12.1
coverage. Classic q+v adapters still load without the flag.
lora_train.rs now prints the exact `--lora <path> --lora-rank N
--lora-alpha N [--extended-lora]` command-line you need to apply the
trained adapter at inference, replacing the (forthcoming) message.
End-to-end verified: a Phase 12.3 curriculum-trained adapter loaded
into generate with identical seed/text produces different audio
(92KB vs 61KB, EOT @ frame 24 vs 16) — confirming the adapter takes
effect through to the sampled output. The 3-utterance smoke adapter
hasn't learned anything meaningful but the wiring is sound.
Phase 12 emotional voice stack now complete end-to-end:
12.1 capacity → 12.2 control tokens → 12.3 curriculum → 12.4 inference.
Lib suite 96/96.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
510cd7011c |
rtx-csm: Phase 12.3 — curriculum LoRA trainer for emotional fine-tunes
Closes the personal_voice_training_guide.md §4 stack: capacity (12.1) +
control tokens (12.2) + multi-stage curriculum (this).
TrainingExample gains emotion_tag + stage. Trainer::train applies the
tag via the same apply_emotion_hint helper inference uses (now
pub(crate)) — training and inference must use identical prefix
formatting or the adapter won't transfer.
TrainingDataset::load_from_manifest reads JSONL
`{wav, transcript, emotion_tag?, stage?, speaker?}` rows; wav paths
resolve relative to manifest dir.
CurriculumStage + CurriculumTrainer run N stages sequentially against a
shared VarMap. Per stage: filter by ex.stage label, build a transient
sub-dataset, run Trainer, save snapshot if requested. The "*" stage
name is a global catch-all.
examples/lora_train_emotional.rs wraps the canonical 3-stage recipe:
audiobook (3 ep × lr 1e-4) → podcast (1 ep × lr 3e-5) → va (1 ep ×
lr 1e-5). --extended-lora recommended (FFN is the prosodic-style
carrier per the guide).
Verified end-to-end on Metal: 3-row manifest → all 3 stages execute,
checkpoints + final adapter written, prompt-token lengths varied by
emotion-tag length (9 vs 11 for different tags) confirming the tag
flowed through the training tokenization. Lib suite 96/96.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
9023684d38 |
rtx-csm: Phase 12.2 — emotion control token plumbing
GenerateOptions gains emotion_hint: Option<String>. After text normalization, the hint (if Some) is prepended as `<tag> <text>` so the Llama BPE tokenizer encodes it as ordinary tokens. Plumbed through generate, generate_streaming, and generate_with_profile (via delegation), plus a `--emotion-hint` flag on examples/generate and a Shared field + CLI flag on examples/converse_server (per-turn ConverseOptions). GenerateOptions lost Copy because Option<String> isn't Copy; updated the four callers that depended on it (bench, longform, converse synth + stream) to .clone() the opts at the call site. Cheap — the struct is small and clones are per-turn, not per-frame. On the un-adapted base this is a no-op cosmetic prefix. The point is to unlock Phase 12.1-fine-tuned adapters: train with `[whisper] X` paired with whispered audio, and the adapter learns the tag→prosody mapping at inference time. Verified end-to-end: --emotion-hint "[whisper]" --max-audio-ms 3000 produced a valid 24kHz mono WAV through tokenizer → backbone → Mimi with no panics. Lib suite 96/96 (added 4 apply_emotion_hint unit tests). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
5423136bae |
rtx-csm: Phase 12.1 — extend LoRA coverage q+v → full attn + MLP
Both backbones (FP csm_fork + Q8 csm_quantized) now expose 7 LoRA hooks per layer: q/k/v/o on attention plus gate/up/down (Llama w1/w3/w2) on the SwiGLU MLP. LoraConfig::default() still returns q+v only (backward compat for existing trained adapters); LoraConfig::extended() returns the full 7-module set. lora_train + lora_finetune_step take a --extended-lora flag. Verified end-to-end on Metal: injection across all 16 backbone layers × 7 modules = 224 adapter Vars, 5.6M trainable params (~6.6× q+v alone, still tiny vs the 1B base). Step-0 loss matches the q+v baseline exactly (B=0 init is also a no-op for the new hooks). Forward + backward + AdamW + refresh_lora cycle runs without errors. LoRA test suite: 9 pass (added config_extended_targets_full_attn_and_mlp); full lib suite still 92/92. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
237216a31f |
rtx-csm: Phase 11 — Silero V5 VAD pure-candle port (closes 8.1.3 deferred)
Phase 8.1.3 deferred Silero V5 VAD because the only Rust crate path (`voice_activity_detector` via `ort`) collides with `sentencepiece-sys` on protobuf 3.14 vs 3.21 and panics at process startup. This commit closes that gap with a NATIVE candle port. Direct port from `Snakers4/silero-vad/src/silero_vad/tinygrad_model.py` (71 LOC reference). Architecture: stft_conv Conv1d(1, 258, k=256, s=128) no bias conv1 Conv1d(129, 128, k=3, p=1) conv2 Conv1d(128, 64, k=3, s=2, p=1) conv3 Conv1d(64, 64, k=3, s=2, p=1) conv4 Conv1d(64, 128, k=3, p=1) lstm_cell LSTMCell(128, 128) final_conv Conv1d(128, 1, k=1) Forward: reflect-pad input by 64, STFT-as-conv1d, sqrt(real² + imag²), 4-layer Conv1d feature stack with ReLU, single LSTM step (state across chunks), 1x1 conv + sigmoid -> speech probability. Files added: src/silero_vad.rs ~310 LOC (incl. LSTM cell + downloader) docs/silero_vad_port_notes.md architecture + port plan examples/silero_vad_smoke.rs real-audio discrimination test Plus a new `ureq` direct dep (transport already pulled in via hf-hub). Weights ship via download-on-first-run from the upstream GitHub raw URL into `~/.cache/rtx-csm/silero_vad_16k.safetensors` (1.24 MB). No repo bloat; no .gitignore wrestling. End-to-end smoke (synthetic 50/50 silence/speech WAV at 16 kHz): load (cold): download + parse, < 100 ms after first run VAD sweep: 170 ms over 9.99 s of audio = 0.017x realtime (59x faster) unit test: passes (load weights + run one step) Probability output (per 32 ms chunk): 0-1.5 s: p ~ 0.01-0.07 silence 1.5-5 s: p ~ 1.000 speech (clean ramp at speech onset) 5-10 s: p ~ 0.001 silence Speech-chunk fraction 33% on the 50/50 layout — matches expected. Production angle: dramatically better silence/speech discrimination than the Phase 8.1.3b energy VAD (which only catches obvious silence). Silero V5 catches whisper-quiet speech, breath/lip noise, music vs speech distinction. Drop-in candidate for `--vad-gate` in a future iteration. The ort/protobuf conflict that blocked this for two months is now permanently resolved by NOT using ort. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
df89372ad7 |
rtx-csm: Phase 10.4 — SilentCipher detect + Watermarker trait + apply CLI
End-to-end SilentCipher: bit-perfect round-trip on real LibriSpeech
audio. Sesame's actual production watermarker now works in pure
candle 0.9 + Metal.
New components in src/silentcipher.rs:
detect(samples_16k) -> DetectResult
1. RMS-normalize to VCTK baseline (matches embed pre-conditioning)
2. STFT -> magnitude
3. dec_m_0(magnitude) -> (B, message_dim, 1, T) logits
4. argmax along message_dim -> (T,) per-frame predictions
5. Truncate to multiple of message_len
6. Reshape to (n_patches, message_len), per-column mode
7. Find terminator (value 0), rotate so payload follows it
8. Subtract +1 offset -> original codes
encode_bits / decode_bits (Phase 10.4 fix)
Switched from base-4 (2 bits per code) to base-`(message_dim - 1)`.
The 16 kHz model has message_dim=4 = 3 carrier values (1,2,3) +
terminator (0), NOT 4 carrier values. Original base-4 packing
occasionally produced value 3, which Python's
`np.identity(4)[index+1]` would have crashed on. Real capacity:
15 codes x log2(3) ~= 23.78 bits per patch.
SilentCipherWatermark (impl Watermarker)
Wraps a SilentCipherWatermarker with a fixed default_payload so
it satisfies the existing Watermarker trait. Maps confidence ->
DetectionResult.mean_presence and the lower-16-bits of the
decoded payload -> DetectionResult.message (None below confidence
0.7 to suppress false positives).
examples/silentcipher_apply
Mirrors audioseal_apply: --in / --out / --payload / --detect-only.
Loads from sony/silentcipher HF repo, embeds, optionally
resamples back to source rate, optionally re-detects to verify.
Verified end-to-end (LibriSpeech /tmp/asr_test.flac, 10.42 s @ 16 kHz):
Build: 29 ms (3 .ckpt files from HF cache)
Embed: 1213 ms = 0.116x realtime
Detect: 1838 ms = 0.18x realtime
payload: 0x00BC614E (in)
recovered: 0x00BC614E (out)
codes match: 15 / 15
confidence: 1.0000
Clean (un-watermarked) audio: confidence 0.475, codes mostly 0 -
strong signal-vs-noise discrimination at the 0.7 threshold.
This closes the most surprising gap from the Sesame stack analysis:
rtx-csm now has the *literal* Sesame watermarker (not Meta's
AudioSeal) working in pure candle. AudioSeal stays available for
callers that prefer it.
Phase 10.5 (next): wire as a third option in converse_server alongside
AudioSeal, and a 24/16 kHz ResampledWatermarker for the CSM path.
Plus an A/B bench (SilentCipher vs AudioSeal).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
f6bcf0735a |
rtx-csm: Phase 10.3 — SilentCipher embed pipeline end-to-end
End-to-end encode pipeline working: 3 ckpts load from HF, STFT runs,
encoder + carrier-decoder forward, iSTFT reconstructs. Watermarked
audio out preserves length + carries an embedded message.
New components in src/silentcipher.rs (~150 LOC added):
SilentCipherWatermarker bundle of cfg + 3 networks + STFT + device
::from_ckpts(...) load enc_c.ckpt + dec_c.ckpt + dec_m_0.ckpt
pickle files via candle_core::pickle::read_all
::build_message(codes, T) one-hot + tile across time axis to match
n_frames; matches Python letters_encoding
shape semantics
::embed(samples_16k, codes) full encode pipeline:
1. RMS-normalize to VCTK baseline
2. STFT -> magnitude + phase
3. enc_c forward -> 32-channel carrier
4. enc_c.transform_message -> projected msg
5. cat(carrier_enc, mag.repeat(32),
msg_enc.repeat(32)) -> 96 channels
6. dec_c forward + utterance-level
normalization + ensure_negative_message
+ ReLU clamp
7. iSTFT -> watermarked audio
8. de-normalize energy
::encode_bits(payload) pack a u32 into message_len-1 2-bit codes
Smoke test (`examples/silentcipher_smoke`) verified end-to-end:
Build watermarker: 29 ms (loads 3 .ckpt files)
Synthetic sine embed: 187 ms / 1.00 s audio
Real speech embed: 1042 ms / 10.42 s audio = 0.10x realtime
The 0.10x realtime figure is comparable to AudioSeal in Phase 6f.wm
(73 ms per ~6.8 s sentence = ~0.011x realtime, but AudioSeal had
warm-cache benefit). On a fresh cold model, SilentCipher comes in
~10x faster than realtime — order-of-magnitude OK.
SNR vs original: 24.6 dB on the speech sample, target 47 dB per the
released hparams. The watermark is currently more audible than
intended. Likely cause: utterance-level normalization scale factor
needs refinement, OR the ensure_negative_message + ReLU path is
clipping more than the Python path. Will be diagnosed in Phase 10.4
when detection round-trip lands — the real test of correctness is
"can dec_m recover the embedded codes?", not absolute SNR.
Phase 10.4 will:
- Implement detect() to recover the embedded codes via dec_m_0
- Add Watermarker trait impl for SilentCipherWatermarker
- examples/silentcipher_apply CLI mirroring audioseal_apply
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
e7b34abd16 |
rtx-csm: Phase 10.2 — SilentCipher Layer + STFT + scaffolds
Foundation in src/silentcipher.rs (~480 LOC) plus rustfft 6.2 dep.
What works:
Stft windowed framed FFT via rustfft (Hann window,
n_fft + hop_length config). Round-trip unit test
on a 440 Hz sine (16 kHz, 1 s) achieves > 0.95
correlation — overlap-add + epsilon-trick blur
the bit-exact return slightly but the recovered
waveform tracks the original cleanly.
SilentCipherConfig hyperparameters from the released 16 kHz hparams
(N_FFT=2048, HOP=1024, message_dim=4,
message_band_size=512, etc.). Constructor
sixteen_khz() returns the production defaults.
Layer gated conv block: bn(conv(x) * sigmoid(gate(x)))
built from candle_nn::Conv2d + BatchNorm2d.
BatchNorm runs in eval mode (forward_t with
train=false) — released checkpoints carry
running_mean / running_var.
Encoder 3 stacked Layers (1->32, 32->32, 32->32) plus a
Linear(message_dim, message_band_size) for the
transform_message helper that projects bit
payloads onto the freq axis.
CarrierDecoder 4 stacked Layers (96->96 x3, 96->1 with k=1) +
optional ensure_negative_message + freq-band
masking + RMS / SDR scaling.
MsgDecoder 10 stacked Layers (1->128, 128->128 x8,
128->message_dim) + final Linear collapsing
freq -> 1. Slices to message_band_size rows
before processing. Models the PyTorch index
doubling (Dropout interleaved in eval mode is
identity, but stored under index 2i+1).
vb_from_ckpt opens a .ckpt pickle file and exposes a
VarBuilder with the legacy `module.` prefix
stripped, ready for Encoder::new etc.
What doesn't work yet (Phase 10.3):
- End-to-end embed() / detect() pipeline glue (STFT input ->
Encoder + transform_message -> CarrierDecoder -> iSTFT, plus the
decode mirror). Each piece compiles + has a smoke test, but the
pipeline orchestration is the next ship.
- Watermarker trait impl + wiring into Generator.set_watermarker.
- examples/silentcipher_apply (mirror of audioseal_apply).
Tests: 2 new unit tests pass alongside the existing 88. Full lib build
clean on `--features metal`.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
95015c17e1 |
rtx-csm: Phase 8.9 — Moonshine KV cache + profile binary
KV cache for the decoder turns greedy generation from O(T^2) into O(T)
total work. Per-token decode drops modestly on short transcripts
(7.1 -> 6.0 ms/token at 49 tokens) and compounds on longer ones.
New components in src/moonshine.rs:
RotaryCache::apply_at(x, position, t)
Apply RoPE for a window starting at `position`. Replaces
`apply()` for cached step (which always called positions 0..T).
DecoderSelfAttention::forward_step(xs, cache_k, cache_v, rope, position)
Single-token cached self-attn. Appends new K/V to per-layer cache,
attends across full accumulated history. No causal mask needed
(cache only contains positions <= current).
CrossAttention::precompute_kv(enc) -> (K, V)
One-shot encoder K/V projection for cross-attn. Reused every step.
CrossAttention::forward_step(xs, k, v)
Cached cross-attn. Q computed from new token; K/V from precompute.
DecoderCache { self_k: Vec<Option<Tensor>>, self_v, cross_k, cross_v, position }
Decoder::precompute_cross_kv(enc) -> DecoderCache
Decoder::step(token_id, &mut cache) -> logits (1, vocab)
Decoder::generate_cached(enc, cfg, max_tokens) -> Vec<u32>
Greedy loop using the cached step.
Profile (5 steady-state runs on /tmp/asr_test.flac, 10.42 s LibriSpeech):
warm-up: 344 ms
steady-state mean: 307 ms (p50 305, range 298-319)
realtime factor: 0.0294x
Comparison across all STT in rtx-csm:
Backend RTF Notes
Kyutai STT 1B 1.01x hardware-bound, 3 GB
Whisper-tiny 0.020x breaks CSM (in-process ggml conflict)
Moonshine-tiny 0.0294x pure candle, NO runtime conflict
Moonshine is the only fast STT path that integrates cleanly. ~34x
faster than realtime, ~17x faster than Kyutai 1B, no protobuf or
ggml linkage issues.
New `examples/moonshine_profile` mirrors `stt_profile` and
`whisper_profile` so all three STT backends report comparable numbers.
Phase 8.10 (next): wire as a third AsrEngine variant in converse_server
for English-only deploys. Replace the energy-VAD-gated Kyutai path
when --moonshine flag is set.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
b22ff3544e |
rtx-csm: Phase 8.8 — Moonshine end-to-end transcription works
Full encoder-decoder Moonshine v2 transcribing real audio in pure
candle 0.9 + Metal. No ort, no ggml, no protobuf. The path that
whisper-rs (Phase 7.6) and Silero V5 via ort (Phase 8.1.3) couldn't
deliver due to in-process linkage conflicts.
End-to-end on /tmp/asr_test.flac (LibriSpeech, 10.42 s):
encode: 10 ms
decode: 348 ms (49 tokens, 7.1 ms/token greedy, no KV cache)
realtime factor: 0.068x (~14x faster than realtime)
Output transcript:
"He hoped there would be stew for dinner, turnips and carrots and
bruised potatoes, and fat, mutton pieces to be ladled out in thick,
peppered, flour-fat and sauce."
Ground truth:
"He hoped there would be stew for dinner, turnips and carrots and
bruised potatoes and fat mutton pieces to be ladled out in thick
peppered flour-fattened sauce."
Near-perfect (a few punctuation tweaks, "flour-fat and sauce" vs
"flour-fattened sauce"). WER very low.
Compared to other STT backends in this crate:
Kyutai STT 1B : 1.01x realtime (3 GB, hardware-bound)
Whisper-tiny : 0.020x realtime (in-process ggml -> CSM regression)
**Moonshine-tiny: 0.068x realtime (pure candle, no runtime conflict)**
Components shipped this commit:
- Decoder::generate(encoder_output, cfg, max_tokens) — greedy
autoregressive loop. No KV cache yet (each step re-runs the full
growing token sequence — O(T^2) total). For 49-token transcripts
at <500 ms total, KV cache isn't urgent.
- load_tokenizer() — wraps tokenizers::Tokenizer::from_file for
Moonshine's HF tokenizer.json (BPE, vocab 32_768).
- examples/moonshine_transcribe — full pipeline: audio -> 16 kHz
PCM -> encode -> decode -> detokenize -> transcript text.
Critical bug fixed: SwiGLU gate/up split direction. HF
modeling_moonshine.py says:
hidden, gate = fc1(x).chunk(2, dim=-1)
out = silu(gate) * hidden
The FIRST half of the fused fc1 output is `up` (multiplied), the
SECOND half is `gate` (silu-activated). I had it reversed in Phase
8.7 — the symptom was a degenerate "tt tt tt" repetition loop after
the first 2 tokens. Reversing the split unlocked the working
transcription. Captured in the code comment.
Remaining for Moonshine readiness in production:
Phase 8.9 — KV cache for sub-200ms latency on long transcripts,
plus a standalone moonshine_profile binary for the
full A/B against Kyutai/Whisper.
Phase 8.10 — wire as a third AsrEngine variant in converse_server
(gated on English-only acceptance for the deploy).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
b94edca496 |
rtx-csm: Phase 8.7 — Moonshine decoder transformer (encoder+decoder)
Full encoder-decoder Moonshine v2 working end-to-end on candle 0.9 +
Metal. Loads HF safetensors, runs through every transformer block, and
produces real logits.
Components added to src/moonshine.rs:
CrossAttention MHA with K/V from encoder output (no causal mask)
DecoderSelfAttention MHA with causal mask, partial RoPE on q/k
DecoderMlp SwiGLU: fused fc1 [2304, 288] split gate+up,
silu(gate) * up, fc2 [288, 1152] back to hidden
DecoderLayer Pre-LN self-attn + Pre-LN cross-attn + Pre-LN MLP
Decoder token embed -> 6 layers -> final LN -> tied LM head
load_full() convenience: returns (Encoder, Decoder)
Smoke test verifies end-to-end:
encoder forward : 1 ms (cached after warm-up)
decoder forward : 85 ms (1 token, prefill mode)
logits shape : (1, 1, 32768)
logit max abs : 30.66 (real signal, not zeros)
argmax token_id : 379 (non-trivial prediction; eos=2)
Implementation notes:
- Same (B*H, T, D) 3D matmul pattern as encoder to dodge candle's 4D
Metal matmul shape-mismatch bug.
- LM head tied to decoder.embed_tokens.weight (cached on Decoder for
fast forward; logits = hidden @ embed.T).
- Causal mask is a (T, T) -inf upper-triangular added to scores
before softmax.
- Decoder final LN tensor is `decoder.norm.weight` (NOT
`decoder.layer_norm.weight` — encoder uses the latter naming).
- No KV cache yet: this is prefill mode. Phase 8.8 will add the
streaming-generation loop with cache + tokenizer.
NOT yet verified: numerical parity vs HF Python reference. The token
predicted (id=379) looks plausible for silent-mostly audio, but a
parity check is still needed (Phase 8.9). Architecture appears
correct based on shape + signal sanity.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
a8e729a826 |
rtx-csm: Phase 8.6 — Moonshine encoder transformer block
Full encoder forward path: conv stem -> 6 transformer layers -> final
LayerNorm. Loads HF safetensors, runs end-to-end on Metal.
Components added to src/moonshine.rs:
RotaryCache partial RoPE (32 of 36 head_dim, theta=10000)
EncoderAttention MHA (8 heads, no bias), partial RoPE on q/k
EncoderMlp 288 -> 1152 -> 288 with bias, GELU(erf) activation
EncoderLayer Pre-LN attn + Pre-LN MLP (LayerNorm weight-only)
Encoder stem + 6 layers + final LayerNorm
load_encoder() VarBuilder convenience for the standalone smoke
Smoke test (`examples/moonshine_smoke`) verified end-to-end:
input (1, 1, 160000) -> output (1, 415, 288)
forward: 132 ms (10 s of audio at 0.013x realtime)
max abs: 6.67 (signal preserved, not zeros)
Implementation notes captured in the diff:
- candle Metal 4D batched matmul had shape-mismatch issues for our
(B, H, T, D) pattern. Switched to (B*H, T, D) 3D form which is
unambiguous and avoids the kernel bug.
- LayerNorm is weight-only (no bias tensors in safetensors); we
construct LayerNorm with a zeros bias to satisfy candle's API.
- rotary_dim = floor(head_dim * 0.9 / 2) * 2 = 32 (must be even).
The remaining 4 head_dim channels pass through unchanged via
`narrow + cat` on dim 3.
Numerical parity vs HF Python reference is NOT yet verified — that's
the next bounded chunk (Phase 8.7). Shape + signal correctness are
verified by the smoke test.
Next: decoder transformer block (self-attn + cross-attn + SwiGLU).
~3-4 h of focused work.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
0699cdeb45 |
rtx-csm: Phase 8.5 — Moonshine conv stem (verified end-to-end)
First working piece of the Moonshine v2 candle port. New src/moonshine.rs module with: - MoonshineConfig::tiny() — hyperparameters from HF config.json - ConvStem (Conv1d × 3) — audio stem, raw 16 kHz → 288-d hidden - load_conv_stem() — VarBuilder from HF safetensors Conv layout (verified against HF source): conv1: in=1, out=288, k=127, stride=64, no bias conv2: in=288, out=576, k=7, stride=3, bias conv3: in=576, out=288, k=3, stride=2, bias Activations: tanh after conv1, gelu_erf after conv2 / conv3 Smoke test (`examples/moonshine_smoke`): - Downloads UsefulSensors/moonshine-tiny from HF - Synthetic 10 s @ 16 kHz audio (silence + sine pulse) - input (1, 1, 160000) -> output (1, 415, 288) - Expected T_seq=415 ((160000-127)/64+1 -> 2498 -> 831 -> 415) - Output max abs = 23.17 (real signal, weights loaded correctly) Also extends `examples/moonshine_inspect` to dump conv shapes explicitly (was being truncated by the per-prefix `take(8)` cap). Next ship: encoder transformer block (partial RoPE, GELU MLP) and output layer norm. Tracked in Phase 8 plan; ~2-3 hours of work. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
808c9fae54 |
rtx-csm: Phase 8.1.3 — energy-VAD gate (Silero V5 path blocked)
Original plan: gate STT work via Silero V5 VAD using
voice_activity_detector / ort to skip silent chunks. Phase 8.1.2's
ort_conflict_probe initially passed (no Metal regression). But on
first server boot, sentencepiece-sys's protobuf 3.14 collides with
ort's bundled protobuf 3.21 at process startup:
[libprotobuf FATAL ...] This program was compiled against version
3.14.0 of the Protocol Buffer runtime library, which is not
compatible with the installed version (3.21.12) ... in
sentencepiece-sys-0.13.1
Updated the probe binary to also load Kyutai STT (which links
sentencepiece) — now correctly catches the conflict at probe time.
Same risk class as the whisper-rs/ggml issue from Phase 7.6: external
ML runtimes don't always coexist in the same Rust process.
Pivoted to a pure-Rust energy-based VAD: RMS amplitude threshold per
incoming chunk. ~30 LOC, no external runtime, no protobuf risk.
Catches obvious silence (room tone, pauses) — misses quiet speech
(whispering). Acceptable for typical mic-distance voice loops.
Wired into examples/converse_server as `--vad-gate` /
`--vad-gate-threshold 0.01`. The receive loop checks RMS before each
binary chunk's STT call; silence chunks skip step_pcm entirely.
Orthogonal to existing `--vad` (Kyutai semantic-VAD-for-EOT).
Bench (mock LLM, Q8+stream, 10s LibriSpeech in, ~90% speech):
baseline: recv_phase = 4834 ms
--vad-gate: recv_phase = 4509 ms (-7%, matches the ~10% silence
in this audio)
Real-world voice-agent audio is 30-50% silence; expect proportional
savings (~30-50% recv_phase reduction). Larger silence content =
larger VAD win.
Cargo.toml: keeps the optional `vad` feature + voice_activity_detector
dep wired (path remains for a future Silero-via-candle port). The
ort_conflict_probe example continues to require `--features vad` so
the conflict-detection path stays exercised.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
10c0063e46 |
rtx-csm: Phase 7.2 — STT step_pcm in spawn_blocking
Wraps the per-frame Kyutai STT calls in handle_connection's receive loop with tokio::task::spawn_blocking. The async runtime worker is freed during the ~80ms/frame compute so other tasks/connections can run on the same worker pool. Single-connection latency is unchanged (STT is hardware-bound at ~1× realtime). The win is multi-tenant concurrency: with N WebSocket connections, no longer blocks all N on one connection's STT work. Two call sites updated: - carry-over feed (turn-start barge-in audio) - main receive loop (per-binary-chunk step_pcm) Pattern: clone Arc<Shared>, move into spawn_blocking, use tokio::sync::Mutex::blocking_lock() inside the closure (legal there). The blocking_lock requires the Mutex to be reachable via Send + 'static captures — that's why we clone shared rather than borrow. Cannot show the multi-tenant win in the existing single-connection bench harness; bench thermals also confound direct A/B. Functional correctness verified via running bench (transcripts produced, no errors). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
ae400a7bd9 |
rtx-csm: Phase 6f.stream-tts — per-chunk TTS streaming with spawned conv task
Adds Converse::run_streaming using Generator::generate_streaming. Chunks are emitted via a per-chunk callback as they're decoded; per-sentence callback fires once for /metrics + transcript bookkeeping. Skips post-process and watermark — both require full-sentence context. Wires --stream-tts and --stream-chunk-frames into examples/converse_server. Combining --stream-tts with --watermark-* is rejected at boot. Critical architectural fix: tokio::join!(conv_fut, pump_fut) polls cooperatively in ONE task, so the sync TTS gen blocks the runtime worker and prevents pump_fut from draining the chunk channel. Switched to tokio::spawn(conv_fut) + pump_fut.await on the original task — now the runtime can schedule pump_fut on a different worker while conv_fut is mid-synthesize. Without the spawn, chunks pile up and arrive in burst at sentence boundaries (defeating the streaming purpose). A/B (warmed FP, mock LLM, 10.43s LibriSpeech in): Phase Non-stream Stream+spawn Δ llm_to_first_audio 4892ms 1942ms -2950ms total_turn 18408ms 19628ms +1220ms (variance) Client-side TTFA 9345ms 6789ms -2556ms ~3s TTFA reduction is the production win. total_turn is roughly unchanged (chunk delivery overhead exists but is small). For voice-loop deployments where time-to-first-audio dominates UX, this is the right default. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |
||
|
|
c1ce6e388c |
rtx-csm: conv-phase tracing — per-sentence TTFT/llm_buffer/tts_gen logs
Adds info-level logs inside Converse::run with a stable "conv-phase:"
prefix. Three event types per turn:
conv-phase: ttft={ms} LLM first token (TTFT)
conv-phase: sentence[i] llm_buffer={ms} tts_gen={ms} chars={n}
conv-phase: sentence[i] (trailing) llm_buffer={ms} tts_gen={ms} chars={n}
llm_buffer = wall time accumulating tokens since the previous sentence
boundary (or run start, for the first sentence). tts_gen reports the
synthesize() cost (Generator.generate + post + watermark).
Together with the handle_connection turn-timing log shipped earlier,
this gives complete attribution of where voice-loop wall time goes.
Mock LLM measurement (10.43s LibriSpeech in, 4-sentence canned reply):
ttft=50ms
sentence[0] llm_buffer=103ms tts_gen=5679ms chars=12
sentence[1] llm_buffer=1449ms tts_gen=646ms chars=156
sentence[2] llm_buffer=154ms tts_gen=3661ms chars=20
sentence[3] llm_buffer=259ms tts_gen=4894ms chars=22
Surprise: first-sentence TTS gen (5.7s) is the dominant cost — Metal
warm-up + KV cache init on the first generate() call. Subsequent
sentences are 3-5x cheaper. For real LLMs (e.g., Z.AI thinking-disabled),
ttft becomes the dominant cost; this instrumentation distinguishes the
two cleanly.
No API change — pure observability.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
c56cc68cdc |
rtx-csm: GenConfig.extra_body — provider-specific JSON merging
Adds `extra_body: serde_json::Map<String, Value>` to `GenConfig`. The
OpenAiCompatibleClient serializes the typed ChatRequest to a Value, then
merges extra_body's keys at the top level of the request body before
sending. extra_body is empty by default, so existing callers see no
behavioral change.
Use cases:
- **Z.AI thinking-disabled** for voice-AI: glm-4.5/4.6/4.7 default to
reasoning_content traversal which burns tokens before content emits.
Pass `{"thinking":{"type":"disabled"}}` and reasoning_tokens drops to
0. Verified: curl direct = 2.1s vs 30s+ with thinking.
- **vLLM guided decoding**: `{"guided_json": {...}}`.
- **Anthropic-compat thinking budget** (when proxied through an
OpenAI-compat shim).
Wires `--llm-extra-body '<JSON>'` into examples/converse_server: parsed
once at boot, stored in Shared.llm_extra_body, cloned per-turn into
gen_cfg. Boot rejects malformed JSON or non-object payloads.
Smoke test: examples/llm_extra_body_smoke.rs hits Z.AI directly with
and without extra_body, prints ttf_chunk and total stream time. Latest
run on glm-4.5: WITHOUT extra_body 1283ms, WITH thinking-disabled
1385ms — both fast on this prompt; the field is correctly forwarded
either way (other prompts that trigger reasoning_content show the
30s+ delta).
Note: the first end-to-end test through converse_server still showed
~46s wall (vs 1.4s for the LLM call alone), implying the latency
bottleneck is local STT (~12s on this hardware) + TTS gen, not the
LLM. extra_body code path is verified independently via the smoke
test.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
1ac0f97ea2 |
rtx-csm: Phase 6c.3b + 6d.rate-limit — semantic VAD + token bucket
Phase 6d.rate-limit:
Per-connection sliding-window token bucket (60s window) on the
WebSocket. Two limits: --rate-audio-secs-per-min (default 600,
60 of which exhausts the bucket on a 1-minute monologue), and
--rate-turns-per-min (default 60). Excess fires an error event +
closes the connection.
Verified: with --rate-turns-per-min 1, two SEPARATE WS connections
each get a fresh per-connection bucket (by design — defends against
a single misbehaving client; for per-IP, the bucket would need to
live globally on Shared).
Phase 6c.3b: semantic VAD via extra_heads
- Added Stt::load_default_with_vad() which downloads
`kyutai/stt-1b-en_fr-candle` (the VAD-enabled variant: 4 extra
heads × 6-dim categorical, trained for end-of-turn detection).
- config_stt_1b_en_fr_vad() builds the LM config with the
ExtraHeadsConfig that loads `extra_heads.X.weight` from the
checkpoint. The standard 1B en/fr config has extra_heads = None.
- Stt::end_of_turn_probability(&AsrEvent::Step) extracts head index
2's probability (per the Kyutai reference Python script). 2 unit
tests.
- converse_server gains --vad / --vad-threshold / --vad-consecutive
flags. When --vad is set: STT runs incrementally during the WS
receive loop, watches Step events for end-of-turn probability,
and auto-fires EOT when the threshold is exceeded for K
consecutive frames. Sends {"event":"vad_eot"} to the client when
triggered, then proceeds to LLM + TTS without needing a manual
"EOT" text frame.
87 lib tests pass.
Phase 6 status:
6a STT: working
6b LLM client: working
6c.1 text->LLM->TTS: working
6c.2 WebSocket duplex MVP: working
6c.3a streaming TTS chunks: working
6c.3b semantic VAD: shipped (this commit)
6d.{auth,shutdown,metrics,rate-limit}: shipped (this commit)
6c.3c barge-in (interrupt assistant mid-speak): deferred
The Rust Unmute conversational stack is now feature-complete for the
strategic Phase 6 deliverable.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
1dd79d4d10 |
rtx-csm: Phase 6a COMPLETE — STT works on real speech with detok
Python-reference diff revealed the all-pad debugging session was on the
wrong audio source. /tmp/csm_24k.wav (CSM-generated speech) is not
intelligible enough for Kyutai STT — even the Python reference emits
nothing. On a real LibriSpeech-style speech sample the pipeline works
correctly.
Verified end-to-end on Metal (10s FLAC, "He hoped there would be stew
for dinner..."):
Rust port: 23 words, transcript matches Python reference
Python ref: 25 words (last 2 cut off in our run due to asr_delay
off-by-one — cosmetic, fixable by setting delay=7)
Changes:
- Add sentencepiece = "0.13" dep for token detok
- Stt::decode_word_text(tokens) returns the detokenized word text
(filters padding token id 3, calls SentencePieceProcessor::decode_piece_ids)
- examples/stt_demo: pair Word/EndWord events into timed segments,
detokenize each, print transcript + concatenated text
- Update module docs to reflect WORKING status
Phase 6 progress:
6a STT: WORKING (this commit)
6b LLM client: shipped
6c.1 text->LLM->TTS: shipped
6c.2 full duplex: ready to build now that 6a works
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
ec053fcc18 |
rtx-csm: Phase 6c.1 — text -> LLM -> sentence buffer -> CSM TTS
Composable orchestrator stitching the LLM-output side of the
conversational stack:
prompt + history -> LlmClient.generate_stream -> sentence buffer
-> per-sentence Generator.generate -> post-process -> watermark
-> Vec<Utterance> stream of (text, audio, latency)
CSM is sentence-level (best prosody on full sentences), so the buffer
flushes when terminal punctuation appears anywhere in the buffer
(Punctuation policy: . ! ? \n) or at any clause boundary
(Eager policy: + , ; :).
src/converse.rs:
- Converse<L: LlmClient> orchestrator
- Utterance { text, audio, tts_latency_ms } per sentence
- FlushPolicy { Punctuation, Eager }
- find_first_boundary scans the whole buffer (not just the last char)
so "Sentence one. Word two" emits "Sentence one." immediately rather
than waiting for the next terminal mark
- 3 unit tests for boundary detection + policy modes
examples/converse.rs:
- --mock mode: hardcoded 20-token "sleepy turtle" stream, no API key
- live mode: any OpenAI-compatible endpoint via OpenAiCompatibleClient
- writes the concatenated audio to a single WAV
Verified mock end-to-end on Metal: 2 utterances emitted as expected
(sentence 1 hits max_audio_ms cap at 6s; sentence 2 EOTs naturally at
4.88s), total 10.88s of audio in 31.5s wall-clock.
Phase 6c.1 ships the half-duplex (text-in -> voice-out) pipeline. Full
duplex (audio-in -> voice-out) is 6c.2, blocked on 6a's STT word
emission landing.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
||
|
|
af45e1b58e |
rtx-csm: Phase 6b — LlmClient trait + OpenAI-compatible streaming impl
Generic LLM client abstraction for the conversational stack: - LlmClient trait with generate_stream(messages, config) -> TokenStream. Default generate() impl folds the stream for non-streaming callers. - ChatMessage / Role / GenConfig types with sensible defaults. - OpenAiCompatibleClient: HTTP impl with SSE streaming. Works against OpenAI, Z.AI, vLLM, llama.cpp's HTTP server, LiteLLM — any endpoint serving the Chat Completions schema. - examples/llm_chat: demo CLI that prints token-by-token to stdout with TTFT + total-time + char-count metrics. Promotes tokio + reqwest + futures-util to regular dependencies (no longer dev-only) so the trait is part of the public library surface. Adds async-trait + eventsource-stream for the SSE streaming. 3 unit tests (constructors, role serialization, default config); 82 lib tests total green. Phase 6 progress: - 6a Kyutai STT: integration scaffolded; output bridge needs Python reference diff (deferred) - 6b LLM client: shipped (this commit) - 6c session glue (axum WS + duplex audio loop): next - 6d productionization: deferred Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> |