helena 0.1.0

Core types and component interfaces for helena, a latent data-to-waveform generation platform.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//! The validated experiment spec: raw document resolved into domain types.
//!
//! [`ExperimentSpec`] is obtainable only through
//! [`RawExperimentConfig::resolve`], so holding one is proof its invariants
//! hold. Where the raw document carried primitives that could be nonsensical (a
//! zero sample rate, a zero latent dim, a `0.0` temperature entangled with a
//! seed), the spec carries the domain vocabulary that makes those states
//! unrepresentable: [`SampleRate`], `NonZero` dims, a validated
//! [`Segmentation`], and [`GenerationDefaults`] whose optional temperature *is*
//! the determinism decision.

use std::num::{NonZeroU64, NonZeroUsize};

use serde::Serialize;

use crate::error::{Error, Result};
use crate::latent::KindTag;
use crate::manifest::SourceKind;
use crate::seams::{GuidanceScale, Temperature};
use crate::time::SampleRate;

use super::raw::{
    Alignment, RawAudioCodec, RawDataEncoder, RawExperimentConfig, RawGenerator, RawSegmentation,
    RawSourceData, RawTargetAudio, RawTraining,
};

impl RawExperimentConfig {
    /// Resolve a parsed config into a validated [`ExperimentSpec`] (PRD FR-004).
    ///
    /// The only path from a raw document to the validated spec. Proves: a
    /// nonzero [`SampleRate`], a positive finite clip duration, non-empty
    /// component keys, positive optimizer settings, a segmentation that
    /// advances at frame resolution, and a positive candidate count. Consumes
    /// `self`, but *retains* the raw document inside the spec so the
    /// [`Recipe`](super::Recipe) can be minted deterministically across
    /// load/save cycles. Returns [`Error::Validation`] describing the first
    /// problem found.
    pub fn resolve(self) -> Result<ExperimentSpec> {
        require_non_empty(&self.project, "project")?;
        require_non_empty(&self.experiment_name, "experiment_name")?;
        let sample_rate = SampleRate::try_from(self.sample_rate)?;
        let clip_duration_seconds =
            require_positive_finite(self.clip_duration_seconds, "clip_duration_seconds")?;

        let source_data = self.source_data.resolve()?;
        let target_audio = self.target_audio.resolve(sample_rate)?;
        let data_encoder = self.data_encoder.resolve()?;
        let audio_codec = self.audio_codec.resolve()?;
        let generator = self.conditional_generator.resolve()?;
        let training = self.training.resolve()?;
        let generation = GenerationDefaults::resolve(&self.generation)?;

        Ok(ExperimentSpec {
            sample_rate,
            clip_duration_seconds,
            source_data,
            target_audio,
            data_encoder,
            audio_codec,
            generator,
            training,
            generation,
            raw: self,
        })
    }
}

/// A validated experiment specification.
///
/// Constructed only by [`RawExperimentConfig::resolve`]. Fields are private;
/// accessors return domain-typed, proven values. The originating raw document
/// is retained (private) so [`recipe`](Self::recipe) is a byte-stable
/// projection across load/save cycles.
#[derive(Clone, Debug)]
pub struct ExperimentSpec {
    sample_rate: SampleRate,
    clip_duration_seconds: f32,
    source_data: SourceDataSpec,
    target_audio: TargetAudioSpec,
    data_encoder: DataEncoderSpec,
    audio_codec: AudioCodecSpec,
    generator: GeneratorSpec,
    training: TrainingSpec,
    generation: GenerationDefaults,
    raw: RawExperimentConfig,
}

impl ExperimentSpec {
    /// Project namespace the experiment belongs to.
    pub fn project(&self) -> &str {
        &self.raw.project
    }

    /// Experiment name, unique within the project.
    pub fn experiment_name(&self) -> &str {
        &self.raw.experiment_name
    }

    /// The validated (nonzero) target sample rate.
    pub fn sample_rate(&self) -> SampleRate {
        self.sample_rate
    }

    /// The nominal clip length (strictly positive, finite).
    pub fn clip_duration_seconds(&self) -> f32 {
        self.clip_duration_seconds
    }

    /// Source-data section.
    pub fn source_data(&self) -> &SourceDataSpec {
        &self.source_data
    }

    /// Target-audio section, including validated segmentation.
    pub fn target_audio(&self) -> &TargetAudioSpec {
        &self.target_audio
    }

    /// Data-encoder section.
    pub fn data_encoder(&self) -> &DataEncoderSpec {
        &self.data_encoder
    }

    /// Audio-codec section.
    pub fn audio_codec(&self) -> &AudioCodecSpec {
        &self.audio_codec
    }

    /// Conditional-generator section.
    pub fn generator(&self) -> &GeneratorSpec {
        &self.generator
    }

    /// Training section.
    pub fn training(&self) -> &TrainingSpec {
        &self.training
    }

    /// Default generation knobs recorded with the config.
    pub fn generation(&self) -> &GenerationDefaults {
        &self.generation
    }

    /// The training-determining projection of this spec (refoundation A6).
    ///
    /// A borrow of the raw document *minus* its generation section, so the two
    /// invariants of the recipe hold by construction: editing an inference-only
    /// `generation.*` knob leaves the recipe unchanged (a checkpoint stays
    /// loadable across sampling settings — the GEN-14 contract), while any
    /// training-determining field moves it. Basing the projection on the raw
    /// document keeps the derived
    /// [`RecipeFingerprint`](super::RecipeFingerprint) byte-stable across
    /// load/save cycles.
    pub fn recipe(&self) -> super::Recipe<'_> {
        super::Recipe::new(&self.raw)
    }

    /// The full-provenance fingerprint of the originating config (PRD
    /// NFR-010): the [`ConfigFingerprint`](super::ConfigFingerprint) over the
    /// retained raw document, generation section included. The provenance-side
    /// counterpart to [`recipe_fingerprint`](Self::recipe_fingerprint), reached
    /// without a consumer having to hold the raw document separately.
    pub fn config_fingerprint(&self) -> Result<super::ConfigFingerprint> {
        super::ConfigFingerprint::of(&self.raw)
    }

    /// The recipe fingerprint that gates checkpoint reload (GEN-14): the
    /// [`RecipeFingerprint`](super::RecipeFingerprint) over
    /// [`recipe`](Self::recipe), so it is invariant under inference-knob edits.
    pub fn recipe_fingerprint(&self) -> Result<super::RecipeFingerprint> {
        super::RecipeFingerprint::of(&self.recipe())
    }
}

impl RawSourceData {
    fn resolve(&self) -> Result<SourceDataSpec> {
        require_non_empty(&self.path, "source_data.path")?;
        Ok(SourceDataSpec {
            kind: self.kind,
            path: self.path.clone(),
            alignment: self.alignment,
        })
    }
}

/// Validated source-data section.
#[derive(Clone, Debug)]
pub struct SourceDataSpec {
    kind: SourceKind,
    path: String,
    alignment: Alignment,
}

impl SourceDataSpec {
    /// Source modality, parsed once.
    pub fn kind(&self) -> SourceKind {
        self.kind
    }

    /// Filesystem path to the source dataset (non-empty).
    pub fn path(&self) -> &str {
        &self.path
    }

    /// How source items correspond to target audio.
    pub fn alignment(&self) -> Alignment {
        self.alignment
    }
}

impl RawTargetAudio {
    fn resolve(&self, sample_rate: SampleRate) -> Result<TargetAudioSpec> {
        require_non_empty(&self.path, "target_audio.path")?;
        let segmentation = Segmentation::resolve(&self.segmentation, sample_rate)?;
        Ok(TargetAudioSpec {
            path: self.path.clone(),
            segmentation,
        })
    }
}

/// Validated target-audio section.
#[derive(Clone, Debug)]
pub struct TargetAudioSpec {
    path: String,
    segmentation: Segmentation,
}

impl TargetAudioSpec {
    /// Filesystem path to the target-audio dataset (non-empty).
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Validated windowing for training.
    pub fn segmentation(&self) -> &Segmentation {
        &self.segmentation
    }
}

/// Validated audio windowing.
///
/// Constructed only as part of [`RawExperimentConfig::resolve`], which proves
/// its invariants: both durations finite, window strictly positive, overlap
/// non-negative and strictly less than the window, and — at the section's
/// sample rate — a window that rounds to at least one frame with an overlap
/// rounding to strictly fewer frames than the window. The frame arithmetic is
/// carried alongside the seconds so a consumer need not re-derive it.
#[derive(Clone, Copy, Debug)]
pub struct Segmentation {
    window_seconds: f32,
    overlap_seconds: f32,
    window_frames: NonZeroU64,
    overlap_frames: u64,
}

impl Segmentation {
    fn resolve(raw: &RawSegmentation, sample_rate: SampleRate) -> Result<Self> {
        let window_seconds =
            require_positive_finite(raw.window_seconds, "segmentation.window_seconds")?;
        let overlap_seconds =
            require_non_negative_finite(raw.overlap_seconds, "segmentation.overlap_seconds")?;
        if overlap_seconds >= window_seconds {
            return Err(Error::validation(
                "segmentation.overlap_seconds must be smaller than window_seconds",
            ));
        }

        let sr = sample_rate.get() as f32;
        let window_frames = (window_seconds * sr).round() as u64;
        let overlap_frames = (overlap_seconds * sr).round() as u64;
        let window_frames = NonZeroU64::new(window_frames).ok_or_else(|| {
            Error::validation(
                "segmentation.window_seconds is too small for the sample rate (rounds to zero frames)",
            )
        })?;
        if overlap_frames >= window_frames.get() {
            return Err(Error::validation(
                "segmentation.overlap_seconds rounds to at least a full window at this sample rate",
            ));
        }
        Ok(Self {
            window_seconds,
            overlap_seconds,
            window_frames,
            overlap_frames,
        })
    }

    /// Window length in seconds (strictly positive).
    pub fn window_seconds(&self) -> f32 {
        self.window_seconds
    }

    /// Overlap in seconds (non-negative, below the window).
    pub fn overlap_seconds(&self) -> f32 {
        self.overlap_seconds
    }

    /// Window length in samples at the section's sample rate (nonzero).
    pub fn window_frames(&self) -> NonZeroU64 {
        self.window_frames
    }

    /// Overlap in samples at the section's sample rate (below the window).
    pub fn overlap_frames(&self) -> u64 {
        self.overlap_frames
    }
}

impl RawDataEncoder {
    fn resolve(&self) -> Result<DataEncoderSpec> {
        require_non_empty(&self.kind, "data_encoder.type")?;
        let latent_dim = NonZeroUsize::new(self.latent_dim).ok_or_else(|| {
            Error::validation("data_encoder.latent_dim must be greater than zero")
        })?;
        Ok(DataEncoderSpec {
            kind: self.kind.clone(),
            latent_dim,
            extra: self.extra.clone(),
        })
    }
}

/// Validated data-encoder section.
///
/// `extra` is carried verbatim; the resolver that builds the concrete encoder
/// vets it against its recognized keys with
/// [`reject_unknown_extra`](super::reject_unknown_extra).
#[derive(Clone, Debug)]
pub struct DataEncoderSpec {
    kind: String,
    latent_dim: NonZeroUsize,
    extra: crate::latent::Metadata,
}

impl DataEncoderSpec {
    /// Encoder plugin key (non-empty).
    pub fn kind(&self) -> &str {
        &self.kind
    }

    /// Width of each conditioning latent the encoder emits (nonzero).
    pub fn latent_dim(&self) -> NonZeroUsize {
        self.latent_dim
    }

    /// Encoder-specific extra settings, for the resolver to interpret.
    pub fn extra(&self) -> &crate::latent::Metadata {
        &self.extra
    }
}

impl RawAudioCodec {
    fn resolve(&self) -> Result<AudioCodecSpec> {
        require_non_empty(&self.kind, "audio_codec.type")?;
        Ok(AudioCodecSpec {
            kind: self.kind.clone(),
            latent_kind: self.latent_type,
            freeze: self.freeze,
            extra: self.extra.clone(),
        })
    }
}

/// Validated audio-codec section.
///
/// The latent kind is a [`KindTag`] (parsed once, threaded thereafter), not a
/// free string.
#[derive(Clone, Debug)]
pub struct AudioCodecSpec {
    kind: String,
    latent_kind: KindTag,
    freeze: bool,
    extra: crate::latent::Metadata,
}

impl AudioCodecSpec {
    /// Codec plugin key (non-empty).
    pub fn kind(&self) -> &str {
        &self.kind
    }

    /// Latent kind the codec produces.
    pub fn latent_kind(&self) -> KindTag {
        self.latent_kind
    }

    /// Whether the codec is frozen during training.
    pub fn freeze(&self) -> bool {
        self.freeze
    }

    /// Codec-specific extra settings, for the resolver to interpret.
    pub fn extra(&self) -> &crate::latent::Metadata {
        &self.extra
    }
}

impl RawGenerator {
    fn resolve(&self) -> Result<GeneratorSpec> {
        require_non_empty(&self.kind, "conditional_generator.type")?;
        Ok(GeneratorSpec {
            kind: self.kind.clone(),
            extra: self.extra.clone(),
        })
    }
}

/// Validated conditional-generator section.
#[derive(Clone, Debug)]
pub struct GeneratorSpec {
    kind: String,
    extra: crate::latent::Metadata,
}

impl GeneratorSpec {
    /// Generator plugin key (non-empty).
    pub fn kind(&self) -> &str {
        &self.kind
    }

    /// Architecture-specific settings, for the resolver to interpret.
    pub fn extra(&self) -> &crate::latent::Metadata {
        &self.extra
    }
}

impl RawTraining {
    fn resolve(&self) -> Result<TrainingSpec> {
        let batch_size = NonZeroUsize::new(self.batch_size)
            .ok_or_else(|| Error::validation("training.batch_size must be greater than zero"))?;
        let max_steps = NonZeroU64::new(self.max_steps)
            .ok_or_else(|| Error::validation("training.max_steps must be greater than zero"))?;
        if !self.learning_rate.is_finite() || self.learning_rate <= 0.0 {
            return Err(Error::validation(format!(
                "training.learning_rate must be finite and positive, got {}",
                self.learning_rate
            )));
        }
        Ok(TrainingSpec {
            batch_size,
            learning_rate: self.learning_rate,
            max_steps,
            seed: self.seed,
        })
    }
}

/// Validated training section.
#[derive(Clone, Debug)]
pub struct TrainingSpec {
    batch_size: NonZeroUsize,
    learning_rate: f64,
    max_steps: NonZeroU64,
    seed: u64,
}

impl TrainingSpec {
    /// Number of items per optimizer step (nonzero).
    pub fn batch_size(&self) -> NonZeroUsize {
        self.batch_size
    }

    /// Optimizer learning rate (finite, positive).
    pub fn learning_rate(&self) -> f64 {
        self.learning_rate
    }

    /// Total optimizer steps to run (nonzero).
    pub fn max_steps(&self) -> NonZeroU64 {
        self.max_steps
    }

    /// Seed for reproducible training.
    pub fn seed(&self) -> u64 {
        self.seed
    }
}

/// Validated default generation knobs.
///
/// The old `GenerationConfig { temperature, guidance_scale, num_candidates }`
/// mapped onto the domain vocabulary. A `0.0` temperature *is* determinism, so
/// it becomes `temperature: None` rather than a `Temperature` — the old
/// "seeded but temperature zero" ambiguity is unrepresentable (mirroring
/// [`SeedPolicy`](crate::seams::SeedPolicy)). A positive temperature resolves to
/// `Some(Temperature)`.
#[derive(Clone, Copy, Debug)]
pub struct GenerationDefaults {
    temperature: Option<Temperature>,
    guidance: GuidanceScale,
    candidates: NonZeroUsize,
}

impl GenerationDefaults {
    fn resolve(raw: &super::raw::RawGeneration) -> Result<Self> {
        // 0.0 (and only 0.0) is the deterministic sentinel; negatives and
        // non-finite values are still rejected. A positive value must satisfy
        // `Temperature`'s own invariant.
        let temperature = if raw.temperature == 0.0 {
            None
        } else if !raw.temperature.is_finite() || raw.temperature < 0.0 {
            return Err(Error::validation(format!(
                "generation.temperature must be finite and non-negative, got {}",
                raw.temperature
            )));
        } else {
            Some(Temperature::new(raw.temperature)?)
        };
        let guidance = GuidanceScale::new(raw.guidance_scale).map_err(|_| {
            Error::validation(format!(
                "generation.guidance_scale must be finite and non-negative, got {}",
                raw.guidance_scale
            ))
        })?;
        let candidates = usize::try_from(raw.num_candidates)
            .ok()
            .and_then(NonZeroUsize::new)
            .ok_or_else(|| Error::validation("generation.num_candidates must be at least one"))?;
        Ok(Self {
            temperature,
            guidance,
            candidates,
        })
    }

    /// Default sampling temperature, or `None` for the deterministic path.
    pub fn temperature(&self) -> Option<Temperature> {
        self.temperature
    }

    /// Default classifier-free guidance strength.
    pub fn guidance(&self) -> GuidanceScale {
        self.guidance
    }

    /// Default candidate count per request (at least one).
    pub fn candidates(&self) -> NonZeroUsize {
        self.candidates
    }
}

fn require_non_empty(value: &str, field: &str) -> Result<()> {
    if value.trim().is_empty() {
        return Err(Error::validation(format!("{field} must not be empty")));
    }
    Ok(())
}

fn require_positive_finite(value: f32, field: &str) -> Result<f32> {
    if !value.is_finite() || value <= 0.0 {
        return Err(Error::validation(format!(
            "{field} must be finite and positive, got {value}"
        )));
    }
    Ok(value)
}

fn require_non_negative_finite(value: f32, field: &str) -> Result<f32> {
    if !value.is_finite() || value < 0.0 {
        return Err(Error::validation(format!(
            "{field} must be finite and non-negative, got {value}"
        )));
    }
    Ok(value)
}

/// A `Serialize`-only view of a raw config, the recipe projection.
///
/// Excludes the `generation` section: inference knobs never invalidate trained
/// weights (refoundation A6). Held as a borrow of the raw document so the
/// derived fingerprint is byte-stable across load/save cycles.
#[derive(Debug, Serialize)]
pub struct Recipe<'a> {
    project: &'a str,
    experiment_name: &'a str,
    sample_rate: u32,
    clip_duration_seconds: f32,
    source_data: &'a RawSourceData,
    target_audio: &'a RawTargetAudio,
    data_encoder: &'a RawDataEncoder,
    audio_codec: &'a RawAudioCodec,
    conditional_generator: &'a RawGenerator,
    training: &'a RawTraining,
    // `generation` is deliberately absent.
}

impl<'a> Recipe<'a> {
    pub(super) fn new(raw: &'a RawExperimentConfig) -> Self {
        Self {
            project: &raw.project,
            experiment_name: &raw.experiment_name,
            sample_rate: raw.sample_rate,
            clip_duration_seconds: raw.clip_duration_seconds,
            source_data: &raw.source_data,
            target_audio: &raw.target_audio,
            data_encoder: &raw.data_encoder,
            audio_codec: &raw.audio_codec,
            conditional_generator: &raw.conditional_generator,
            training: &raw.training,
        }
    }
}