library:ml: move erf beside Act::Gelu, which outlives post::duration
- Commit
a378edebb494bb28b5f3ac1fcb455c9f116722b3- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 16:39 UTC (3 months ago)
- Parents
4138572
Diff
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex 61873a94a4..645d33587a 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -117,9 +117,9 @@ pub enum Act { /// 4.7e-4 (at `x = 2.699`), and fp16's step there is 2.0e-3, so the difference is four /// times finer than the arena can represent. `erf` is used anyway for two reasons that are /// about agreement rather than accuracy — it is what the export computes, and- /// [`crate::post::duration::erf`] already implements the same Abramowitz and Stegun 7.1.26- /// series for the CPU duration predictor, so the host reference and the shader are the same- /// function by construction rather than by coincidence. The cost is comparable either way.+ /// [`crate::nets::erf`] implements the same Abramowitz and Stegun 7.1.26 series for the host+ /// interpreter, so the reference and the shader are the same function by construction rather+ /// than by coincidence. The cost is comparable either way. Gelu, /// `tanh(x)`. ///@@ -692,6 +692,28 @@ pub struct Builder<'a> { /// boundary `.maml` aligns its tensors to. const ALIGN_ELEMS: u32 = 8; +/// `erf`, to about 1.5e-7 — Abramowitz and Stegun 7.1.26.+///+/// Rust has no `erf`, and [`Act::Gelu`] is the exact form rather than the tanh approximation, so+/// approximating the *activation* would be a different function. This approximates `erf` itself+/// instead, well below fp16's resolution.+///+/// It lives beside `Act` rather than in `nets::reference` because that module is `#[cfg(test)]`,+/// and it began in `post::duration` for VITS's separable stacks — which is why it is here and not+/// there: `post::duration` goes when Piper does, and `Act::Gelu` does not.+pub(crate) fn erf(x: f32) -> f32 {+ const A: [f32; 5] = [0.254_829_6, -0.284_496_74, 1.421_413_7, -1.453_152, 1.061_405_4];+ const P: f32 = 0.327_591_1;+ let sign = if x < 0.0 { -1.0 } else { 1.0 };+ let x = x.abs();+ let t = 1.0 / (1.0 + P * x);+ let mut poly = 0.0;+ for coefficient in A.iter().rev() {+ poly = (poly + coefficient) * t;+ }+ sign * (1.0 - poly * (-x * x).exp())+}+ /// The largest integer fp16 holds exactly, and so the width of one embedding id lane. /// /// Every integer below this has an exact fp16 representation; at 2049 the gaps open to 2 and
library/ml/src/main/rust/src/nets/reference.rs
diff --git a/library/ml/src/main/rust/src/nets/reference.rs b/library/ml/src/main/rust/src/nets/reference.rsindex b2f3ed2080..c56a01e263 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -84,9 +84,9 @@ fn activate(x: f32, kind: u32, slope: f32) -> f32 { act::CLIP01 => x.clamp(0.0, 1.0), act::SWISH => x / (1.0 + (-x).exp()), act::TANH => x.tanh(),- // The exact GELU. crate::post::duration::erf is the same A&S 7.1.26 series the- // shader uses, so the two agree well inside fp16.- act::GELU => 0.5 * x * (1.0 + crate::post::duration::erf(x * std::f32::consts::FRAC_1_SQRT_2)),+ // The exact GELU, not the tanh approximation: [`super::erf`] is the same A&S 7.1.26+ // series the shader uses, so the two agree well inside fp16.+ act::GELU => 0.5 * x * (1.0 + super::erf(x * std::f32::consts::FRAC_1_SQRT_2)), _ => x, } }@@ -1181,6 +1181,25 @@ mod tests { } } + #[test]+ fn erf_matches_its_known_values() {+ // A&S 7.1.26, good to 1.5e-7, pinned at values with published digits — a wrong+ // coefficient would still look like a sigmoid. `Act::Gelu` is the exact erf form rather+ // than the tanh approximation, and `shaders/conv.comp` carries the same series, so this+ // is what keeps the interpreter and the device agreeing.+ for (x, want) in [+ (0.0f32, 0.0f32),+ (0.5, 0.5204999),+ (1.0, 0.8427008),+ (2.0, 0.9953223),+ (-1.0, -0.8427008),+ (3.0, 0.9999779),+ ] {+ let got = super::super::erf(x);+ assert!((got - want).abs() < 2e-6, "erf({x}) = {got} not {want}");+ }+ }+ #[test] fn a_dense_convolution_matches_a_hand_summed_window() { // 2x2 of ones over 1..9, bias 0.5. Each output is the sum of its window.
library/ml/src/main/rust/src/nets/supertonic_sampler.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_sampler.rs b/library/ml/src/main/rust/src/nets/supertonic_sampler.rsindex 0bff6c66ad..99ec44b7c7 100644--- a/library/ml/src/main/rust/src/nets/supertonic_sampler.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_sampler.rs@@ -36,7 +36,7 @@ //! So the ONNX is not a velocity field but a whole **Euler step**, guidance scale 4 baked in. //! This runtime has no batch axis and cannot fake one — putting the two branches side by side //! along the sequence would let the depthwise convolutions mix them — so the plan is one branch-//! and [`post::supertonic`] runs it twice. That is a real doubling of the sampler's cost against+//! and [`crate::post::supertonic`] runs it twice. That is a real doubling of the sampler's cost against //! any measurement taken of a single branch. //! //! Both branches are the same plan with different **inputs**: the unconditional one passes
library/ml/src/main/rust/src/post/duration.rs
diff --git a/library/ml/src/main/rust/src/post/duration.rs b/library/ml/src/main/rust/src/post/duration.rsindex 0944e74286..89b5416479 100644--- a/library/ml/src/main/rust/src/post/duration.rs+++ b/library/ml/src/main/rust/src/post/duration.rs@@ -79,23 +79,9 @@ fn tensor(weights: &Weights, index: usize, dims: &[u32]) -> Result<Vec<f32>, Str Ok(raw.chunks_exact(2).map(|c| f16_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect()) } -/// `erf`, to about 1.5e-7 — Abramowitz and Stegun 7.1.26.-///-/// Rust has no `erf`, and the export's GELU is the exact one rather than the tanh-/// approximation, so approximating the *activation* would be a different function. This-/// approximates `erf` itself instead, well below fp16's resolution.-pub(crate) fn erf(x: f32) -> f32 {- const A: [f32; 5] = [0.254_829_6, -0.284_496_74, 1.421_413_7, -1.453_152, 1.061_405_4];- const P: f32 = 0.327_591_1;- let sign = if x < 0.0 { -1.0 } else { 1.0 };- let x = x.abs();- let t = 1.0 / (1.0 + P * x);- let mut poly = 0.0;- for coefficient in A.iter().rev() {- poly = (poly + coefficient) * t;- }- sign * (1.0 - poly * (-x * x).exp())-}+/// `erf` now lives beside [`crate::nets::Act::Gelu`], which outlives this module: it goes when+/// Piper does, and the activation does not.+use crate::nets::erf; /// The exact GELU, `0.5 x (1 + erf(x / sqrt(2)))`. fn gelu(x: f32) -> f32 {@@ -340,22 +326,6 @@ pub fn frames(log_durations: &[f32], length_scale: f32) -> Vec<u32> { mod tests { use super::*; - #[test]- fn erf_matches_its_known_values() {- // The approximation is A&S 7.1.26, good to 1.5e-7. Pinned at values with published- // digits, because a wrong coefficient would still look like a sigmoid.- for (x, want) in [- (0.0f32, 0.0f32),- (0.5, 0.5204999),- (1.0, 0.8427008),- (2.0, 0.9953223),- (-1.0, -0.8427008),- (3.0, 0.9999779),- ] {- assert!((erf(x) - want).abs() < 2e-6, "erf({x}) = {} not {want}", erf(x));- }- }- #[test] fn gelu_matches_the_exact_erf_form() { // The tanh approximation differs by at most 4.7e-4, which is below fp16's 2.0e-3 step
library/ml/src/main/rust/src/post/sentencepiece.rs
diff --git a/library/ml/src/main/rust/src/post/sentencepiece.rs b/library/ml/src/main/rust/src/post/sentencepiece.rsindex d2a3e2ae4f..137e580b2d 100644--- a/library/ml/src/main/rust/src/post/sentencepiece.rs+++ b/library/ml/src/main/rust/src/post/sentencepiece.rs@@ -117,7 +117,7 @@ impl<'a> Table<'a> { /// Token ids for text that is **already NFKC-normalised**. ///- /// Does not append [`EOS`] or prepend a language token: [`crate::post::translate`] owns the+ /// Does not append [`EOS`] or prepend a language token: the decode loop owns the /// sequence, because SMaLL-100 puts the *target* language token on the **source** side and /// that is easy to get backwards. pub fn encode(&self, normalised: &str) -> Vec<u32> {