Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 22 additions & 14 deletions docs/voice-isolation.md
Original file line number Diff line number Diff line change
Expand Up @@ -619,25 +619,33 @@ denses, InstanceNorm, sous-pixel, iSTFT).

## Débruitage multi-cœur (opt-in)

`SARAGOSSA_DENOISE_THREADS=N` (défaut 1 : chemin historique, bit-identique)
découpe le signal en N segments, chacun chauffé sur 1 s de contexte, traités en
parallèle puis recollés par un fondu linéaire de 0,5 s centré sur chaque
frontière. Le fichier entier est gardé en mémoire (pas de flux borné) : environ
0,7 Go par heure en entrée et autant en sortie (f32, 48 kHz), plus les copies par
segment. Seuil de proximité au mono-cœur fixé avant mesure : SNR ≥ 30 dB,
validé seulement sur le modèle synthétique, pas encore mesuré sur le vrai DFN3.
Risque connu : quand le début d'un segment n'est pas multiple de 480, sa grille
STFT est décalée par rapport au mono-cœur (écart borné par le fondu, non mesuré).

Bench de nuit, RTF 1 contre N threads sur le même clip long :
`SARAGOSSA_DENOISE_THREADS=N` (défaut 1 : chemin historique hop par hop)
traite le flux par blocs de 256 trames (2,56 s). Seuls les GRU portent un état
d'une trame à l'autre. L'encodeur (convolutions causales sur des fenêtres
d'entrée connues), les portes d'entrée des GRU et les décodeurs tournent donc
en parallèle sur toutes les trames du bloc (`src/denoise/network/batch.rs`).
La récurrence des GRU reste séquentielle, avec les GRU ERB et DF sur un cœur
chacun. Chaque trame exécute les mêmes fonctions que le chemin hop par hop :
la sortie est identique bit à bit pour tout N. Le traitement reste en flux à
mémoire bornée ; la latence augmente d'un bloc.

Profil mono-cœur (`sample`, 293 s d'audio) : convolutions 61 %, GRU 26 %
(dont environ 40 % de portes d'entrée parallélisables), rééchantillonnage 3 %.
Mesures sur `long.wav` (293 s, M-series 18 cœurs, charge < 2 au lancement),
avec une sortie identique au mono-cœur (`cmp`) pour chaque N :

| N | 1 | 2 | 4 | 8 | 18 |
|---|---|---|---|---|---|
| temps (s) | 13,0 | 7,4 | 4,9 | 3,8 | 3,2 |

Le plafond vient des GRU séquentiels. Pour reproduire :

```bash
for n in 1 2 4 8; do SARAGOSSA_DENOISE_THREADS=$n cargo run --release -- enhance \
for n in 1 2 8; do SARAGOSSA_DENOISE_THREADS=$n cargo run --release -- enhance \
--model $SARAGOSSA_DFN3_DIR/dfn3.safetensors --input long.wav --output out_$n.wav; done
cmp out_1.wav out_2.wav && cmp out_1.wav out_8.wav
```

Chaque run affiche `RTF` ; comparer `out_N.wav` à `out_1.wav` (SNR ≥ 30 dB).

## GPU hors ligne (opt-in)

`SARAGOSSA_DENOISE_GPU=1 saragossa enhance …` calcule le réseau en lot sur
Expand Down
23 changes: 16 additions & 7 deletions src/denoise/layers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,14 +334,23 @@ impl Gru {

/// Met à jour `h` en place à partir de l'entrée `x`.
pub(crate) fn step(&self, x: &[f32], h: &mut [f32], math: Math) {
self.recur(&self.input_gates(x), h, math);
}

/// Portes d'entrée `W_ih · x + b_ih`, indépendantes de l'état : calculables d'avance.
pub(crate) fn input_gates(&self, x: &[f32]) -> Vec<f32> {
let ni = x.len();
(0..3 * self.hidden)
.map(|r| dot(x, &self.w_ih[r * ni..(r + 1) * ni]) + self.b_ih[r])
.collect()
}

/// Partie récurrente du pas, à portes d'entrée `gi` déjà calculées.
pub(crate) fn recur(&self, gi: &[f32], h: &mut [f32], math: Math) {
let n = self.hidden;
let (ni, nh) = (x.len(), n);
let mut gi = vec![0.0_f32; 3 * n];
let mut gh = vec![0.0_f32; 3 * n];
for r in 0..3 * n {
gi[r] = dot(x, &self.w_ih[r * ni..(r + 1) * ni]) + self.b_ih[r];
gh[r] = dot(h, &self.w_hh[r * nh..(r + 1) * nh]) + self.b_hh[r];
}
let gh: Vec<f32> = (0..3 * n)
.map(|r| dot(h, &self.w_hh[r * n..(r + 1) * n]) + self.b_hh[r])
.collect();
for j in 0..n {
let r = math.sigmoid(gi[j] + gh[j]);
let z = math.sigmoid(gi[n + j] + gh[n + j]);
Expand Down
96 changes: 82 additions & 14 deletions src/denoise/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ mod gpu;
mod gpu_probe;
mod layers;
mod network;
mod parallel;
mod resample;
mod stream;
pub use resample::StreamResampler;
Expand Down Expand Up @@ -182,6 +181,7 @@ impl DeepFilterNet3 {
frames: 0,
last_lsnr: 0.0,
steps: Steps::Live,
threads: 1,
}
}
}
Expand Down Expand Up @@ -216,6 +216,8 @@ pub struct DfStream<'a> {
frames: usize,
last_lsnr: f32,
steps: Steps,
/// Cœurs de [`DfStream::process_hops`] ; 1 garde le chemin trame par trame.
threads: usize,
}

impl DfStream<'_> {
Expand Down Expand Up @@ -300,21 +302,87 @@ impl DfStream<'_> {
)
}
};
let center = &self.spec_ring[DF_LOOKAHEAD];
let inv = &self.model.net.erb_inv;
let mut spec = vec![Complex32::default(); FREQ_BINS];
for f in NB_DF..FREQ_BINS {
let gain: f32 = (0..NB_ERB).map(|b| mask[b] * inv[b * FREQ_BINS + f]).sum();
spec[f] = center[f] * gain;
render(
&self.model.net,
&mut self.synthesis,
&self.spec_ring,
(mask, coefs),
output,
);
}

/// Comme `process_hop` sur chaque hop de `input`, le réseau tournant sur
/// `threads` cœurs (voir `network::batch`). Sortie identique bit à bit.
/// L'enregistrement et le rejeu du chemin GPU restent hop par hop.
fn process_hops(&mut self, input: &[f32], output: &mut [f32]) -> Result<()> {
if !matches!(self.steps, Steps::Live) {
let mut pairs = input
.chunks_exact(HOP_SIZE)
.zip(output.chunks_exact_mut(HOP_SIZE));
return pairs.try_for_each(|(i, o)| self.process_hop(i, o));
}
let (mut erbs, mut cplxs, mut rings, mut emits) = (vec![], vec![], vec![], vec![]);
for hop in input.chunks_exact(HOP_SIZE) {
self.spec_ring.rotate_left(1);
let (mut erb, mut cplx) = ([0.0_f32; NB_ERB], [0.0_f32; 2 * NB_DF]);
if let Some(slot) = self.spec_ring.last_mut() {
self.analysis.process(hop, slot);
self.features.process(slot, &mut erb, &mut cplx);
}
self.frames = (self.frames + 1).min(CONV_LOOKAHEAD + 1);
let emit = self.frames > CONV_LOOKAHEAD;
if emit {
erbs.extend(erb);
cplxs.extend(cplx);
rings.push(self.spec_ring.clone());
}
emits.push(emit);
}
for (f, slot) in spec.iter_mut().enumerate().take(NB_DF) {
let mut acc = Complex32::default();
for n in 0..ORDER {
let c = &coefs[(f * ORDER + n) * 2..][..2];
acc += self.spec_ring[n][f] * Complex32::new(c[0], c[1]);
let net = &self.model.net;
let steps = net.step_batch(&mut self.state, &erbs, &cplxs, self.threads);
let mut steps = steps.iter().zip(&rings);
for (out, emit) in output.chunks_exact_mut(HOP_SIZE).zip(emits) {
let next = if emit { steps.next() } else { None };
match next {
Some((step, ring)) => {
self.last_lsnr = step.lsnr;
render(
net,
&mut self.synthesis,
ring,
(&step.mask, &step.coefs),
out,
);
}
None => out.fill(0.0),
}
*slot = acc;
}
self.synthesis.process(&spec, output);
Ok(())
}
}

/// Applique masque ERB et filtre profond au spectre central de `ring`, puis synthétise le hop.
fn render(
net: &Network,
synthesis: &mut Synthesis,
ring: &[Vec<Complex32>],
(mask, coefs): (&[f32], &[f32]),
output: &mut [f32],
) {
let center = &ring[DF_LOOKAHEAD];
let inv = &net.erb_inv;
let mut spec = vec![Complex32::default(); FREQ_BINS];
for f in NB_DF..FREQ_BINS {
let gain: f32 = (0..NB_ERB).map(|b| mask[b] * inv[b * FREQ_BINS + f]).sum();
spec[f] = center[f] * gain;
}
for (f, slot) in spec.iter_mut().enumerate().take(NB_DF) {
let mut acc = Complex32::default();
for (n, frame) in ring.iter().enumerate().take(ORDER) {
let c = &coefs[(f * ORDER + n) * 2..][..2];
acc += frame[f] * Complex32::new(c[0], c[1]);
}
*slot = acc;
}
synthesis.process(&spec, output);
}
111 changes: 83 additions & 28 deletions src/denoise/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use super::dsp::{NB_DF, NB_ERB};
use super::layers::{take_shape, Act, Conv, ConvSpec, GroupedLinear, Gru, Linear1, Math};
use crate::{InferError, Result, Tensor};

mod batch;

pub(super) const CH: usize = 64;
pub(super) const EMB: usize = CH * NB_ERB / 4; // 512
pub(super) const HIDDEN: usize = 256;
Expand Down Expand Up @@ -87,11 +89,26 @@ impl SqueezedGru {
}

fn step(&self, x: &[f32], h: &mut [Vec<f32>], out: &mut Vec<f32>, math: Math) {
self.recur(&self.input_gates(x), h, out, math);
}

/// `linear_in`, ReLU puis portes d'entrée de la première couche : sans état.
fn input_gates(&self, x: &[f32]) -> Vec<f32> {
let mut a = vec![0.0; HIDDEN];
self.lin_in.forward(x, &mut a);
a.iter_mut().for_each(|v| *v = v.max(0.0));
for (layer, state) in self.layers.iter().zip(h.iter_mut()) {
layer.step(&a, state, math);
self.layers[0].input_gates(&a)
}

/// Reste du pas, récurrent, à partir des portes de [`Self::input_gates`].
fn recur(&self, gi0: &[f32], h: &mut [Vec<f32>], out: &mut Vec<f32>, math: Math) {
let mut a = vec![0.0; HIDDEN];
for (l, (layer, state)) in self.layers.iter().zip(h.iter_mut()).enumerate() {
if l == 0 {
layer.recur(gi0, state, math);
} else {
layer.step(&a, state, math);
}
a.copy_from_slice(state);
}
match &self.lin_out {
Expand Down Expand Up @@ -281,17 +298,30 @@ impl Network {

/// Un pas du réseau sur les features décalées `s[τ] = feat[τ + conv_lookahead]`.
pub(crate) fn step(&self, st: &mut NetState, erb: &[f32], cplx: &[f32]) -> StepOut {
let math = st.math;
push(&mut st.erb_hist, erb);
push(&mut st.spec_hist, cplx);
let enc = self.encode(&hist(&st.erb_hist), &hist(&st.spec_hist), math);
let mut emb = Vec::new();
self.enc_gru
.recur(&enc.gates, &mut st.h_enc, &mut emb, math);
let (mut d, mut c) = (Vec::new(), Vec::new());
self.erb_gru.step(&emb, &mut st.h_erb, &mut d, math);
self.df_gru.step(&emb, &mut st.h_df, &mut c, math);
push(&mut st.c0_hist, &enc.c0);
self.decode(&enc, &hist(&st.c0_hist), &emb, (&d, &c), math)
}

/// Encodeur sans état récurrent : `erb` et `spec` sont les fenêtres causales des convolutions.
fn encode(&self, erb: &[&[f32]], spec: &[&[f32]], math: Math) -> Encoded {
let (mut e0, mut e1, mut e2, mut e3) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
self.erb_conv[0].forward(&hist(&st.erb_hist), NB_ERB, &mut e0, st.math);
self.erb_conv[1].forward(&[&e0], NB_ERB, &mut e1, st.math);
self.erb_conv[2].forward(&[&e1], NB_ERB / 2, &mut e2, st.math);
self.erb_conv[3].forward(&[&e2], NB_ERB / 4, &mut e3, st.math);
self.erb_conv[0].forward(erb, NB_ERB, &mut e0, math);
self.erb_conv[1].forward(&[&e0], NB_ERB, &mut e1, math);
self.erb_conv[2].forward(&[&e1], NB_ERB / 2, &mut e2, math);
self.erb_conv[3].forward(&[&e2], NB_ERB / 4, &mut e3, math);
let (mut c0, mut c1) = (Vec::new(), Vec::new());
self.df_conv0
.forward(&hist(&st.spec_hist), NB_DF, &mut c0, st.math);
self.df_conv1.forward(&[&c0], NB_DF, &mut c1, st.math);
self.df_conv0.forward(spec, NB_DF, &mut c0, math);
self.df_conv1.forward(&[&c0], NB_DF, &mut c1, math);

// [C][F] → [F][C] aplati, comme `permute(0, 2, 3, 1).flatten(2)`.
let cemb_in = to_fc(&c1, CH, NB_DF / 2);
Expand All @@ -301,49 +331,74 @@ impl Network {
for (e, c) in emb_in.iter_mut().zip(&cemb) {
*e += c.max(0.0);
}
let mut emb = Vec::new();
self.enc_gru.step(&emb_in, &mut st.h_enc, &mut emb, st.math);
let lsnr = st.math.sigmoid(self.lsnr_fc.forward(&emb)) * (LSNR_MAX - LSNR_MIN) + LSNR_MIN;
// Branches latérales du U-Net ERB : ne dépendent que de l'encodeur.
let f8 = NB_ERB / 4;
let mut skips: [Vec<f32>; 4] = Default::default();
self.convp[0].forward(&[&e0], NB_ERB, &mut skips[0], math);
self.convp[1].forward(&[&e1], NB_ERB / 2, &mut skips[1], math);
self.convp[2].forward(&[&e2], f8, &mut skips[2], math);
self.convp[3].forward(&[&e3], f8, &mut skips[3], math);
Encoded {
gates: self.enc_gru.input_gates(&emb_in),
skips,
c0,
}
}

/// Décodeurs après les GRU : `c0` est la fenêtre causale de `df_convp`.
fn decode(
&self,
enc: &Encoded,
c0: &[&[f32]],
emb: &[f32],
(d, c): (&[f32], &[f32]),
math: Math,
) -> StepOut {
let lsnr = math.sigmoid(self.lsnr_fc.forward(emb)) * (LSNR_MAX - LSNR_MIN) + LSNR_MIN;

// Décodeur ERB (U-Net) → masque [NB_ERB].
let mut d = Vec::new();
self.erb_gru.step(&emb, &mut st.h_erb, &mut d, st.math);
let f8 = NB_ERB / 4;
let mut x = from_fc(&d, CH, f8);
let mut x = from_fc(d, CH, f8);
let mut tmp = Vec::new();
let skips = [(&e3, f8), (&e2, f8), (&e1, NB_ERB / 2)];
for (level, (skip, f)) in skips.into_iter().enumerate() {
self.convp[3 - level].forward(&[skip], f, &mut tmp, st.math);
for (level, f) in [f8, f8, NB_ERB / 2].into_iter().enumerate() {
tmp.clone_from(&enc.skips[3 - level]);
add(&mut tmp, &x);
self.convt[2 - level].forward(&[&tmp], f, &mut x, st.math);
self.convt[2 - level].forward(&[&tmp], f, &mut x, math);
}
self.convp[0].forward(&[&e0], NB_ERB, &mut tmp, st.math);
tmp.clone_from(&enc.skips[0]);
add(&mut tmp, &x);
let mut mask = Vec::new();
self.conv0_out.forward(&[&tmp], NB_ERB, &mut mask, st.math);
self.conv0_out.forward(&[&tmp], NB_ERB, &mut mask, math);

// Décodeur DF → coefficients complexes [NB_DF][ordre][2].
let mut c = Vec::new();
self.df_gru.step(&emb, &mut st.h_df, &mut c, st.math);
let mut c = c.to_vec();
let mut skip = vec![0.0; HIDDEN];
self.df_skip.forward(&emb, &mut skip);
self.df_skip.forward(emb, &mut skip);
add(&mut c, &skip);
let mut coefs = vec![0.0; NB_DF * DF_OUT_CH];
self.df_out.forward(&c, &mut coefs);
push(&mut st.c0_hist, &c0);
let mut pathway = Vec::new();
self.df_convp
.forward(&hist(&st.c0_hist), NB_DF, &mut pathway, st.math);
self.df_convp.forward(c0, NB_DF, &mut pathway, math);
for f in 0..NB_DF {
for o in 0..DF_OUT_CH {
let v = &mut coefs[f * DF_OUT_CH + o];
*v = st.math.tanh(*v) + pathway[o * NB_DF + f];
*v = math.tanh(*v) + pathway[o * NB_DF + f];
}
}
StepOut { mask, coefs, lsnr }
}
}

/// Sorties de l'encodeur d'une trame, avant le GRU.
struct Encoded {
/// Portes d'entrée de la première couche du GRU d'encodeur.
gates: Vec<f32>,
/// `convp[i]` appliquée à la sortie `i` de l'encodeur ERB.
skips: [Vec<f32>; 4],
/// Sortie de `df_conv0`, entrée de `df_convp`.
c0: Vec<f32>,
}

fn hist(h: &[Vec<f32>]) -> Vec<&[f32]> {
h.iter().map(Vec::as_slice).collect()
}
Expand Down
Loading
Loading