Skip to main content

EncodingResult

Struct EncodingResult 

Source
pub struct EncodingResult {
    pub epochs: Vec<EpochEmbedding>,
    pub ms_load: f64,
    pub ms_encode: f64,
}
Expand description

Collection of per-epoch outputs.

Fields§

§epochs: Vec<EpochEmbedding>§ms_load: f64§ms_encode: f64

Implementations§

Source§

impl EncodingResult

Source

pub fn save_safetensors(&self, path: &str) -> Result<()>

Save to safetensors file.

Examples found in repository?
examples/embed.rs (line 127)
58fn main() -> anyhow::Result<()> {
59    let args = Args::parse();
60    let t0 = Instant::now();
61    let device = backend::device();
62
63    println!("╔══════════════════════════════════════════════════════════════╗");
64    println!("║  OSF — PSG Embedding Extraction                             ║");
65    println!("╚══════════════════════════════════════════════════════════════╝\n");
66
67    // 1. Load model
68    let model_cfg = if let Some(ref cfg_path) = args.config {
69        let cfg_str = std::fs::read_to_string(cfg_path)?;
70        serde_json::from_str(&cfg_str)?
71    } else {
72        osf_rs::ModelConfig::default()
73    };
74
75    println!("▸ Loading OSF model …");
76    let (encoder, ms_load) = osf_rs::OsfEncoder::<B>::load_with_config(
77        model_cfg,
78        Path::new(&args.weights),
79        device.clone(),
80    )?;
81    println!("  {}  ({ms_load:.0} ms)\n", encoder.describe());
82
83    // 2. Generate synthetic PSG epochs
84    let n_channels = osf_rs::NUM_PSG_CHANNELS;
85    let n_samples = osf_rs::EPOCH_SAMPLES;
86    let n_epochs = 3;
87
88    println!("▸ Generating {} synthetic PSG epochs ({} ch × {} samples each)\n",
89        n_epochs, n_channels, n_samples);
90
91    let mut all_outputs = Vec::new();
92
93    for epoch_idx in 0..n_epochs {
94        let signal = generate_synthetic_psg(n_channels, n_samples);
95        let batch = osf_rs::build_batch::<B>(signal, n_channels, n_samples, &device);
96
97        let t = Instant::now();
98        let result = encoder.run_batch(&batch)?;
99        let ms = t.elapsed().as_secs_f64() * 1000.0;
100
101        // Stats
102        let cls = &result.cls_emb;
103        let mean: f64 = cls.iter().map(|&v| v as f64).sum::<f64>() / cls.len() as f64;
104        let std: f64 = (cls.iter().map(|&v| { let d = v as f64 - mean; d * d }).sum::<f64>()
105            / cls.len() as f64).sqrt();
106
107        println!("  Epoch {epoch_idx}: cls=[{}]  patches=[{},{}]  mean={mean:+.4}  std={std:.4}  {ms:.1}ms",
108            result.embed_dim, result.num_patches, result.embed_dim);
109
110        if args.verbose && epoch_idx == 0 {
111            println!("    First 5 CLS values: {:?}", &cls[..5.min(cls.len())]);
112        }
113
114        all_outputs.push(result);
115    }
116
117    // 3. Save
118    let encoding = osf_rs::EncodingResult {
119        epochs: all_outputs,
120        ms_load,
121        ms_encode: t0.elapsed().as_secs_f64() * 1000.0,
122    };
123
124    if let Some(p) = Path::new(&args.output).parent() {
125        std::fs::create_dir_all(p)?;
126    }
127    encoding.save_safetensors(&args.output)?;
128    println!("\n▸ Saved {} epochs → {}", n_epochs, args.output);
129
130    let ms_total = t0.elapsed().as_secs_f64() * 1000.0;
131    println!("\n  Total: {ms_total:.0} ms");
132    Ok(())
133}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V