Skip to main content

ftts_artifacts/
enhance_loader.rs

1//! Hydrates the FastEnhancer denoiser ([`ftts_kernels::enhance::Enhancer`]) from a
2//! safetensors artifact holding the inference-form weights.
3//!
4//! The artifact is `fastenhancer_s_48k_inference.safetensors`: the pinned upstream
5//! checkpoint after the reference's own `remove_weight_reparameterizations()` fold,
6//! re-serialized as F32 safetensors (see `docs/DENOISER.md` for the pin and recipe).
7
8use std::collections::BTreeMap;
9
10use ftts_kernels::enhance::{EnhanceError, Enhancer};
11
12use crate::safetensors::SafetensorsFile;
13
14/// Why hydration failed.
15#[derive(Debug)]
16pub enum EnhancerLoadError {
17    /// The file could not be opened or its directory parsed.
18    Open(crate::safetensors::OpenError),
19    /// The tensor set does not describe the expected model geometry.
20    Model(EnhanceError),
21}
22
23impl std::fmt::Display for EnhancerLoadError {
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        match self {
26            Self::Open(error) => write!(f, "cannot open denoiser artifact: {error:?}"),
27            Self::Model(error) => write!(f, "denoiser artifact is malformed: {error}"),
28        }
29    }
30}
31
32impl std::error::Error for EnhancerLoadError {}
33
34/// Materialize every tensor to `f32` and build the engine.
35///
36/// The whole artifact is ~830 KB, so whole-tensor materialization is the right shape here —
37/// no cold-row machinery.
38pub fn enhancer_from_safetensors(file: &SafetensorsFile) -> Result<Enhancer, EnhancerLoadError> {
39    let mut tensors = BTreeMap::new();
40    for entry in file.index().entries() {
41        let view = file
42            .view(&entry.name)
43            .expect("index entries always resolve against their own file");
44        let mut data = vec![0.0f32; view.len()];
45        for (i, slot) in data.iter_mut().enumerate() {
46            *slot = view
47                .get_f32(i)
48                .expect("index bounds were validated at parse");
49        }
50        tensors.insert(entry.name.clone(), (entry.shape.clone(), data));
51    }
52    Enhancer::load(tensors).map_err(EnhancerLoadError::Model)
53}
54
55/// Open a denoiser artifact from disk and build the engine.
56pub fn open_enhancer(path: impl AsRef<std::path::Path>) -> Result<Enhancer, EnhancerLoadError> {
57    let file = SafetensorsFile::open(path).map_err(EnhancerLoadError::Open)?;
58    enhancer_from_safetensors(&file)
59}