Skip to main content

logit_loom_diffusion/
contract.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Serializable diffusion-state contracts and receipts.
4
5use std::collections::{BTreeMap, HashSet};
6
7use logit_loom_core::{CoreError, Digest};
8use serde::{Deserialize, Serialize};
9
10/// Maximum tensor rank accepted at the public boundary.
11pub const MAX_TENSOR_DIMENSIONS: usize = 8;
12/// Maximum contiguous `f32` elements copied transactionally.
13pub const MAX_TENSOR_ELEMENTS: u64 = 16 * 1024 * 1024;
14/// Maximum scheduler steps in one plan.
15pub const MAX_DIFFUSION_STEPS: usize = 4_096;
16/// Maximum identified model components in one plan.
17pub const MAX_COMPONENTS: usize = 32;
18/// Maximum UTF-8 bytes in one device label.
19pub const MAX_DEVICE_LABEL_BYTES: usize = 256;
20/// Maximum stages in one intervention pipeline.
21pub const MAX_INTERVENTION_STAGES: usize = 32;
22
23/// Tensor scalar representation at the intervention boundary.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum TensorDType {
27    /// IEEE 754 binary32 values exposed directly to Rust.
28    F32,
29    /// IEEE 754 binary16 native state, converted exactly at the adapter boundary.
30    F16,
31    /// Brain floating-point native state, converted exactly at the adapter boundary.
32    Bf16,
33}
34
35/// Contiguous element ordering at the intervention boundary.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum TensorLayout {
39    /// Dimension zero is contiguous and changes fastest.
40    DimensionZeroFastest,
41}
42
43/// Exact shape, scalar, layout, and device of one diffusion state.
44#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(deny_unknown_fields)]
46pub struct TensorSpec {
47    /// Positive dimensions in native order.
48    pub shape: Vec<u64>,
49    /// Native scalar representation.
50    pub dtype: TensorDType,
51    /// Contiguous layout exposed to callbacks.
52    pub layout: TensorLayout,
53    /// Adapter-reported device identity.
54    pub device: String,
55}
56
57impl TensorSpec {
58    /// Constructs and validates a tensor contract.
59    ///
60    /// # Errors
61    ///
62    /// Returns an error for invalid rank, dimensions, element count, or device.
63    pub fn new(
64        shape: Vec<u64>,
65        dtype: TensorDType,
66        layout: TensorLayout,
67        device: impl Into<String>,
68    ) -> Result<Self, CoreError> {
69        let specification = Self {
70            shape,
71            dtype,
72            layout,
73            device: device.into(),
74        };
75        specification.validate()?;
76        Ok(specification)
77    }
78
79    /// Validates rank, dimensions, element count, and device identity.
80    ///
81    /// # Errors
82    ///
83    /// Returns the first invalid tensor invariant.
84    pub fn validate(&self) -> Result<(), CoreError> {
85        if !(1..=MAX_TENSOR_DIMENSIONS).contains(&self.shape.len()) {
86            return Err(CoreError::invalid(
87                "diffusion tensor shape",
88                format!("requires 1..={MAX_TENSOR_DIMENSIONS} dimensions"),
89            ));
90        }
91        if self.shape.contains(&0) {
92            return Err(CoreError::invalid(
93                "diffusion tensor shape",
94                "dimensions must be positive",
95            ));
96        }
97        let elements = self.elements()?;
98        if elements > MAX_TENSOR_ELEMENTS {
99            return Err(CoreError::invalid(
100                "diffusion tensor shape",
101                format!("exceeds the {MAX_TENSOR_ELEMENTS}-element bound"),
102            ));
103        }
104        if self.device.is_empty()
105            || self.device.len() > MAX_DEVICE_LABEL_BYTES
106            || self.device.contains('\0')
107        {
108            return Err(CoreError::invalid(
109                "diffusion tensor device",
110                "must be a nonempty bounded label without NUL",
111            ));
112        }
113        Ok(())
114    }
115
116    /// Returns the checked product of all dimensions.
117    ///
118    /// # Errors
119    ///
120    /// Returns an error when the shape is empty or its product overflows.
121    pub fn elements(&self) -> Result<u64, CoreError> {
122        if self.shape.is_empty() {
123            return Err(CoreError::Empty {
124                field: "diffusion tensor shape",
125            });
126        }
127        self.shape.iter().try_fold(1_u64, |product, dimension| {
128            product.checked_mul(*dimension).ok_or_else(|| {
129                CoreError::invalid("diffusion tensor shape", "element count overflowed")
130            })
131        })
132    }
133
134    /// Returns the content identity of this exact tensor contract.
135    ///
136    /// # Errors
137    ///
138    /// Returns a validation or serialization error.
139    pub fn digest(&self) -> Result<Digest, CoreError> {
140        self.validate()?;
141        Digest::of_serializable("diffusion-tensor-spec-v1", self)
142    }
143}
144
145/// Exact scheduler implementation and descending sigma sequence.
146#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
147#[serde(deny_unknown_fields)]
148pub struct DiffusionSchedule {
149    /// Caller-defined scheduler implementation identity.
150    pub implementation: Digest,
151    /// Sigma at each state boundary; `len() - 1` is the step count.
152    pub sigmas: Vec<f32>,
153}
154
155impl DiffusionSchedule {
156    /// Constructs and validates a scheduler contract.
157    ///
158    /// # Errors
159    ///
160    /// Returns an error for an empty, oversized, non-finite, negative, or
161    /// increasing sigma sequence.
162    pub fn new(implementation: Digest, sigmas: Vec<f32>) -> Result<Self, CoreError> {
163        let schedule = Self {
164            implementation,
165            sigmas,
166        };
167        schedule.validate()?;
168        Ok(schedule)
169    }
170
171    /// Validates bounds and descending finite sigma ordering.
172    ///
173    /// # Errors
174    ///
175    /// Returns the first invalid schedule invariant.
176    pub fn validate(&self) -> Result<(), CoreError> {
177        if !(2..=MAX_DIFFUSION_STEPS + 1).contains(&self.sigmas.len()) {
178            return Err(CoreError::invalid(
179                "diffusion schedule",
180                format!("requires 1..={MAX_DIFFUSION_STEPS} steps"),
181            ));
182        }
183        if self
184            .sigmas
185            .iter()
186            .any(|sigma| !sigma.is_finite() || *sigma < 0.0)
187        {
188            return Err(CoreError::invalid(
189                "diffusion schedule",
190                "sigmas must be finite and non-negative",
191            ));
192        }
193        if self.sigmas.windows(2).any(|pair| pair[0] < pair[1]) {
194            return Err(CoreError::invalid(
195                "diffusion schedule",
196                "sigmas must be non-increasing",
197            ));
198        }
199        Ok(())
200    }
201
202    /// Returns the number of state transitions.
203    pub fn steps(&self) -> usize {
204        self.sigmas.len().saturating_sub(1)
205    }
206
207    /// Returns the content identity of this exact schedule.
208    ///
209    /// # Errors
210    ///
211    /// Returns a validation or serialization error.
212    pub fn digest(&self) -> Result<Digest, CoreError> {
213        self.validate()?;
214        Digest::of_serializable("diffusion-schedule-v1", self)
215    }
216}
217
218/// Exact model, conditioning, random-state, tensor, and schedule contract.
219#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
220#[serde(deny_unknown_fields)]
221pub struct DiffusionPlan {
222    /// Named component artifact identities in deterministic key order.
223    pub components: BTreeMap<String, Digest>,
224    /// Identity of exact tokenization and conditioning output.
225    pub conditioning: Digest,
226    /// Random-number-generator implementation identity.
227    pub rng: Digest,
228    /// Exact random seed interpreted by the identified RNG.
229    pub seed: u64,
230    /// Iterative state exposed at step boundaries.
231    pub tensor: TensorSpec,
232    /// Exact schedule.
233    pub schedule: DiffusionSchedule,
234}
235
236impl DiffusionPlan {
237    /// Constructs and validates an exact diffusion execution plan.
238    ///
239    /// # Errors
240    ///
241    /// Returns an error for invalid components, tensor, or schedule.
242    pub fn new(
243        components: BTreeMap<String, Digest>,
244        conditioning: Digest,
245        rng: Digest,
246        seed: u64,
247        tensor: TensorSpec,
248        schedule: DiffusionSchedule,
249    ) -> Result<Self, CoreError> {
250        let plan = Self {
251            components,
252            conditioning,
253            rng,
254            seed,
255            tensor,
256            schedule,
257        };
258        plan.validate()?;
259        Ok(plan)
260    }
261
262    /// Validates component names and nested contracts.
263    ///
264    /// # Errors
265    ///
266    /// Returns the first invalid plan invariant.
267    pub fn validate(&self) -> Result<(), CoreError> {
268        if self.components.is_empty() || self.components.len() > MAX_COMPONENTS {
269            return Err(CoreError::invalid(
270                "diffusion components",
271                format!("requires 1..={MAX_COMPONENTS} entries"),
272            ));
273        }
274        for name in self.components.keys() {
275            if name.is_empty()
276                || name.len() > 64
277                || !name.bytes().all(|byte| {
278                    byte.is_ascii_lowercase()
279                        || byte.is_ascii_digit()
280                        || matches!(byte, b'-' | b'_' | b'.')
281                })
282            {
283                return Err(CoreError::invalid(
284                    "diffusion component name",
285                    "must be a bounded lowercase identifier",
286                ));
287            }
288        }
289        self.tensor.validate()?;
290        self.schedule.validate()
291    }
292
293    /// Returns the identity of this exact execution plan.
294    ///
295    /// # Errors
296    ///
297    /// Returns a validation or serialization error.
298    pub fn digest(&self) -> Result<Digest, CoreError> {
299        self.validate()?;
300        Digest::of_serializable("diffusion-plan-v1", self)
301    }
302}
303
304/// Exact post-step state boundary presented to Rust.
305#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
306#[serde(deny_unknown_fields)]
307pub struct StepContext {
308    /// Exact execution-plan identity.
309    pub plan: Digest,
310    /// Zero-based transition that just completed.
311    pub step_index: u32,
312    /// Sigma before the transition.
313    pub sigma_from: f32,
314    /// Sigma after the transition.
315    pub sigma_to: f32,
316    /// Tensor contract at this boundary.
317    pub tensor: TensorSpec,
318}
319
320impl StepContext {
321    /// Creates the exact post-step context for one plan transition.
322    ///
323    /// # Errors
324    ///
325    /// Returns an error when the plan or index is invalid.
326    pub fn for_plan(plan: &DiffusionPlan, step_index: usize) -> Result<Self, CoreError> {
327        plan.validate()?;
328        if step_index >= plan.schedule.steps() {
329            return Err(CoreError::invalid(
330                "diffusion step",
331                "index is outside the schedule",
332            ));
333        }
334        let step_index_u32 = u32::try_from(step_index)
335            .map_err(|_| CoreError::invalid("diffusion step", "index exceeds u32"))?;
336        Ok(Self {
337            plan: plan.digest()?,
338            step_index: step_index_u32,
339            sigma_from: plan.schedule.sigmas[step_index],
340            sigma_to: plan.schedule.sigmas[step_index + 1],
341            tensor: plan.tensor.clone(),
342        })
343    }
344
345    /// Validates this boundary against its complete execution plan.
346    ///
347    /// # Errors
348    ///
349    /// Returns an error for an identity, index, sigma, or tensor mismatch.
350    pub fn validate_for(&self, plan: &DiffusionPlan) -> Result<(), CoreError> {
351        let expected = Self::for_plan(
352            plan,
353            usize::try_from(self.step_index)
354                .map_err(|_| CoreError::invalid("diffusion step", "index exceeds usize"))?,
355        )?;
356        if *self != expected {
357            return Err(CoreError::invalid(
358                "diffusion step",
359                "context does not match the execution plan",
360            ));
361        }
362        Ok(())
363    }
364}
365
366/// Exact contract for one ordered state intervention.
367#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
368#[serde(deny_unknown_fields)]
369pub struct InterventionSpec {
370    /// Caller-defined implementation and configuration identity.
371    pub implementation: Digest,
372    /// Exact tensor contract accepted by the stage.
373    pub tensor: Digest,
374    /// Maximum invocations in one pipeline run.
375    pub max_invocations: u32,
376}
377
378impl InterventionSpec {
379    /// Validates a bounded stage contract.
380    ///
381    /// # Errors
382    ///
383    /// Returns an error when the invocation bound is zero.
384    pub fn validate(&self) -> Result<(), CoreError> {
385        if self.max_invocations == 0 {
386            return Err(CoreError::invalid(
387                "diffusion intervention",
388                "maximum invocations must be positive",
389            ));
390        }
391        Ok(())
392    }
393
394    /// Returns the identity of this exact stage contract.
395    ///
396    /// # Errors
397    ///
398    /// Returns a validation or serialization error.
399    pub fn digest(&self) -> Result<Digest, CoreError> {
400        self.validate()?;
401        Digest::of_serializable("diffusion-intervention-spec-v1", self)
402    }
403}
404
405/// Ordered diffusion intervention contracts.
406#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
407#[serde(deny_unknown_fields)]
408pub struct PipelineSpec {
409    /// Stages in exact execution order.
410    pub stages: Vec<InterventionSpec>,
411}
412
413impl PipelineSpec {
414    /// Validates stage bounds and their common tensor identity.
415    ///
416    /// # Errors
417    ///
418    /// Returns an error unless one to 32 compatible stages are present.
419    pub fn validate(&self) -> Result<(), CoreError> {
420        if !(1..=MAX_INTERVENTION_STAGES).contains(&self.stages.len()) {
421            return Err(CoreError::invalid(
422                "diffusion pipeline stages",
423                format!("requires 1..={MAX_INTERVENTION_STAGES} entries"),
424            ));
425        }
426        let tensor = &self.stages[0].tensor;
427        for stage in &self.stages {
428            stage.validate()?;
429            if &stage.tensor != tensor {
430                return Err(CoreError::invalid(
431                    "diffusion pipeline stages",
432                    "all stages must accept the same tensor contract",
433                ));
434            }
435        }
436        Ok(())
437    }
438
439    /// Returns the identity of this exact ordered pipeline.
440    ///
441    /// # Errors
442    ///
443    /// Returns a validation or serialization error.
444    pub fn digest(&self) -> Result<Digest, CoreError> {
445        self.validate()?;
446        Digest::of_serializable("diffusion-pipeline-spec-v1", self)
447    }
448}
449
450/// Complete callback error or contained panic.
451#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
452#[serde(deny_unknown_fields)]
453pub struct InterventionFailure {
454    /// Whether the callback unwound.
455    pub panicked: bool,
456    /// Complete human-readable detail.
457    pub message: String,
458}
459
460impl InterventionFailure {
461    /// Constructs a failure without discarding any detail.
462    pub fn new(panicked: bool, message: impl Into<String>) -> Self {
463        Self {
464            panicked,
465            message: message.into(),
466        }
467    }
468}
469
470/// Mechanical accounting for one intervention stage.
471#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
472#[serde(deny_unknown_fields)]
473pub struct StageReceipt {
474    /// Exact stage contract.
475    pub specification: InterventionSpec,
476    /// Reset calls.
477    pub resets: u32,
478    /// Apply calls, including a failed call.
479    pub invocations: u32,
480    /// State elements presented across calls.
481    pub elements_seen: u64,
482    /// Elements whose bit pattern changed.
483    pub elements_changed: u64,
484    /// First contained failure.
485    #[serde(default, skip_serializing_if = "Option::is_none")]
486    pub failure: Option<InterventionFailure>,
487}
488
489/// Aggregate transactional pipeline accounting.
490#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
491#[serde(deny_unknown_fields)]
492pub struct PipelineReceipt {
493    /// Exact ordered stage contract.
494    pub specification: PipelineSpec,
495    /// Pipeline identity.
496    pub pipeline: Digest,
497    /// Begin/reset operations.
498    pub begins: u32,
499    /// Complete committed invocations.
500    pub invocations: u32,
501    /// Elements copied into the transactional boundary.
502    pub elements_copied: u64,
503    /// Elements committed after every stage succeeded.
504    pub elements_committed: u64,
505    /// First failed stage index.
506    #[serde(default, skip_serializing_if = "Option::is_none")]
507    pub failed_stage: Option<u32>,
508    /// Per-stage accounting in execution order.
509    pub stages: Vec<StageReceipt>,
510}
511
512impl PipelineReceipt {
513    /// Validates aggregate and per-stage accounting.
514    ///
515    /// # Errors
516    ///
517    /// Returns an error for inconsistent identity, bounds, or attribution.
518    pub fn validate(&self) -> Result<(), CoreError> {
519        self.specification.validate()?;
520        if self.pipeline != self.specification.digest()?
521            || self.begins > 1
522            || self.elements_committed > self.elements_copied
523            || self.stages.len() != self.specification.stages.len()
524        {
525            return Err(CoreError::invalid(
526                "diffusion pipeline receipt",
527                "aggregate accounting is inconsistent",
528            ));
529        }
530        let failed = self
531            .failed_stage
532            .map(usize::try_from)
533            .transpose()
534            .map_err(|_| {
535                CoreError::invalid("diffusion pipeline receipt", "failed stage exceeds usize")
536            })?;
537        if failed.is_some_and(|index| index >= self.stages.len()) {
538            return Err(CoreError::invalid(
539                "diffusion pipeline receipt",
540                "failed stage is outside the pipeline",
541            ));
542        }
543        let mut failures = HashSet::new();
544        for (index, (stage, specification)) in self
545            .stages
546            .iter()
547            .zip(&self.specification.stages)
548            .enumerate()
549        {
550            if stage.specification != *specification
551                || stage.resets > self.begins
552                || stage.invocations > stage.specification.max_invocations
553                || stage.elements_changed > stage.elements_seen
554            {
555                return Err(CoreError::invalid(
556                    "diffusion pipeline receipt",
557                    "stage accounting is inconsistent",
558                ));
559            }
560            if stage.failure.is_some() {
561                failures.insert(index);
562            }
563        }
564        if failures.len() > 1 || failures.iter().next().copied() != failed {
565            return Err(CoreError::invalid(
566                "diffusion pipeline receipt",
567                "failure attribution is inconsistent",
568            ));
569        }
570        Ok(())
571    }
572
573    /// Returns the identity of this exact mechanical receipt.
574    ///
575    /// # Errors
576    ///
577    /// Returns a validation or serialization error.
578    pub fn digest(&self) -> Result<Digest, CoreError> {
579        self.validate()?;
580        Digest::of_serializable("diffusion-pipeline-receipt-v1", self)
581    }
582}
583
584/// Conservative lineage for opaque adapter checkpoint bytes.
585#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
586#[serde(deny_unknown_fields)]
587pub struct DiffusionCheckpointReceipt {
588    /// Exact diffusion plan identity.
589    pub plan: Digest,
590    /// Adapter build identity.
591    pub backend: Digest,
592    /// Next zero-based schedule step after restore.
593    pub next_step: u32,
594    /// Identity of exact tensor state bytes.
595    pub state: Digest,
596    /// Identity of exact scheduler and RNG continuation state.
597    pub continuation: Digest,
598}
599
600impl DiffusionCheckpointReceipt {
601    /// Validates checkpoint identity and position against a plan.
602    ///
603    /// # Errors
604    ///
605    /// Returns an error when the plan differs or the position is out of bounds.
606    pub fn validate_for(&self, plan: &DiffusionPlan) -> Result<(), CoreError> {
607        plan.validate()?;
608        if self.plan != plan.digest()?
609            || usize::try_from(self.next_step).map_or(true, |step| step > plan.schedule.steps())
610        {
611            return Err(CoreError::invalid(
612                "diffusion checkpoint",
613                "plan identity or step position is incompatible",
614            ));
615        }
616        Ok(())
617    }
618
619    /// Returns the identity of this exact checkpoint lineage.
620    ///
621    /// # Errors
622    ///
623    /// Returns a validation or serialization error.
624    pub fn digest_for(&self, plan: &DiffusionPlan) -> Result<Digest, CoreError> {
625        self.validate_for(plan)?;
626        Digest::of_serializable("diffusion-checkpoint-receipt-v1", self)
627    }
628}
629
630#[cfg(test)]
631mod tests {
632    use super::*;
633
634    fn tensor() -> TensorSpec {
635        TensorSpec::new(
636            vec![8, 8, 3, 1],
637            TensorDType::F32,
638            TensorLayout::DimensionZeroFastest,
639            "test0",
640        )
641        .unwrap()
642    }
643
644    #[test]
645    fn tensor_bounds_reject_zero_and_overflow() {
646        assert!(
647            TensorSpec::new(
648                vec![1, 0],
649                TensorDType::F32,
650                TensorLayout::DimensionZeroFastest,
651                "test0"
652            )
653            .is_err()
654        );
655        assert!(
656            TensorSpec::new(
657                vec![u64::MAX, 2],
658                TensorDType::F32,
659                TensorLayout::DimensionZeroFastest,
660                "test0"
661            )
662            .is_err()
663        );
664    }
665
666    #[test]
667    fn schedules_reject_nonfinite_and_increasing_values() {
668        let implementation = Digest::of_bytes("test-scheduler", b"v1");
669        assert!(DiffusionSchedule::new(implementation.clone(), vec![1.0, f32::NAN]).is_err());
670        assert!(DiffusionSchedule::new(implementation, vec![0.0, 1.0]).is_err());
671    }
672
673    #[test]
674    fn component_names_accept_catalog_periods_but_reject_uppercase() {
675        let schedule =
676            DiffusionSchedule::new(Digest::of_bytes("scheduler", b"v1"), vec![1.0, 0.0]).unwrap();
677        let mut components = BTreeMap::new();
678        components.insert(
679            "wan-2.1-vae".to_owned(),
680            Digest::of_bytes("artifact", b"vae"),
681        );
682        assert!(
683            DiffusionPlan::new(
684                components.clone(),
685                Digest::of_bytes("conditioning", b"input"),
686                Digest::of_bytes("rng", b"v1"),
687                7,
688                tensor(),
689                schedule.clone(),
690            )
691            .is_ok()
692        );
693        components.insert(
694            "Invalid".to_owned(),
695            Digest::of_bytes("artifact", b"invalid"),
696        );
697        assert!(
698            DiffusionPlan::new(
699                components,
700                Digest::of_bytes("conditioning", b"input"),
701                Digest::of_bytes("rng", b"v1"),
702                7,
703                tensor(),
704                schedule,
705            )
706            .is_err()
707        );
708    }
709
710    #[test]
711    fn step_context_binds_exact_tensor_and_sigmas() {
712        let schedule =
713            DiffusionSchedule::new(Digest::of_bytes("scheduler", b"v1"), vec![1.0, 0.0]).unwrap();
714        let mut components = BTreeMap::new();
715        components.insert("model".to_owned(), Digest::of_bytes("artifact", b"model"));
716        let plan = DiffusionPlan::new(
717            components,
718            Digest::of_bytes("conditioning", b"input"),
719            Digest::of_bytes("rng", b"v1"),
720            7,
721            tensor(),
722            schedule,
723        )
724        .unwrap();
725        let mut context = StepContext::for_plan(&plan, 0).unwrap();
726        context.tensor.device = "other0".to_owned();
727        assert!(context.validate_for(&plan).is_err());
728    }
729}