1use std::collections::{BTreeMap, HashSet};
6
7use logit_loom_core::{CoreError, Digest};
8use serde::{Deserialize, Serialize};
9
10pub const MAX_TENSOR_DIMENSIONS: usize = 8;
12pub const MAX_TENSOR_ELEMENTS: u64 = 16 * 1024 * 1024;
14pub const MAX_DIFFUSION_STEPS: usize = 4_096;
16pub const MAX_COMPONENTS: usize = 32;
18pub const MAX_DEVICE_LABEL_BYTES: usize = 256;
20pub const MAX_INTERVENTION_STAGES: usize = 32;
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum TensorDType {
27 F32,
29 F16,
31 Bf16,
33}
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum TensorLayout {
39 DimensionZeroFastest,
41}
42
43#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(deny_unknown_fields)]
46pub struct TensorSpec {
47 pub shape: Vec<u64>,
49 pub dtype: TensorDType,
51 pub layout: TensorLayout,
53 pub device: String,
55}
56
57impl TensorSpec {
58 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 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 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 pub fn digest(&self) -> Result<Digest, CoreError> {
140 self.validate()?;
141 Digest::of_serializable("diffusion-tensor-spec-v1", self)
142 }
143}
144
145#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
147#[serde(deny_unknown_fields)]
148pub struct DiffusionSchedule {
149 pub implementation: Digest,
151 pub sigmas: Vec<f32>,
153}
154
155impl DiffusionSchedule {
156 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 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 pub fn steps(&self) -> usize {
204 self.sigmas.len().saturating_sub(1)
205 }
206
207 pub fn digest(&self) -> Result<Digest, CoreError> {
213 self.validate()?;
214 Digest::of_serializable("diffusion-schedule-v1", self)
215 }
216}
217
218#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
220#[serde(deny_unknown_fields)]
221pub struct DiffusionPlan {
222 pub components: BTreeMap<String, Digest>,
224 pub conditioning: Digest,
226 pub rng: Digest,
228 pub seed: u64,
230 pub tensor: TensorSpec,
232 pub schedule: DiffusionSchedule,
234}
235
236impl DiffusionPlan {
237 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 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 pub fn digest(&self) -> Result<Digest, CoreError> {
299 self.validate()?;
300 Digest::of_serializable("diffusion-plan-v1", self)
301 }
302}
303
304#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
306#[serde(deny_unknown_fields)]
307pub struct StepContext {
308 pub plan: Digest,
310 pub step_index: u32,
312 pub sigma_from: f32,
314 pub sigma_to: f32,
316 pub tensor: TensorSpec,
318}
319
320impl StepContext {
321 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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
368#[serde(deny_unknown_fields)]
369pub struct InterventionSpec {
370 pub implementation: Digest,
372 pub tensor: Digest,
374 pub max_invocations: u32,
376}
377
378impl InterventionSpec {
379 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 pub fn digest(&self) -> Result<Digest, CoreError> {
400 self.validate()?;
401 Digest::of_serializable("diffusion-intervention-spec-v1", self)
402 }
403}
404
405#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
407#[serde(deny_unknown_fields)]
408pub struct PipelineSpec {
409 pub stages: Vec<InterventionSpec>,
411}
412
413impl PipelineSpec {
414 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 pub fn digest(&self) -> Result<Digest, CoreError> {
445 self.validate()?;
446 Digest::of_serializable("diffusion-pipeline-spec-v1", self)
447 }
448}
449
450#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
452#[serde(deny_unknown_fields)]
453pub struct InterventionFailure {
454 pub panicked: bool,
456 pub message: String,
458}
459
460impl InterventionFailure {
461 pub fn new(panicked: bool, message: impl Into<String>) -> Self {
463 Self {
464 panicked,
465 message: message.into(),
466 }
467 }
468}
469
470#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
472#[serde(deny_unknown_fields)]
473pub struct StageReceipt {
474 pub specification: InterventionSpec,
476 pub resets: u32,
478 pub invocations: u32,
480 pub elements_seen: u64,
482 pub elements_changed: u64,
484 #[serde(default, skip_serializing_if = "Option::is_none")]
486 pub failure: Option<InterventionFailure>,
487}
488
489#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
491#[serde(deny_unknown_fields)]
492pub struct PipelineReceipt {
493 pub specification: PipelineSpec,
495 pub pipeline: Digest,
497 pub begins: u32,
499 pub invocations: u32,
501 pub elements_copied: u64,
503 pub elements_committed: u64,
505 #[serde(default, skip_serializing_if = "Option::is_none")]
507 pub failed_stage: Option<u32>,
508 pub stages: Vec<StageReceipt>,
510}
511
512impl PipelineReceipt {
513 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 pub fn digest(&self) -> Result<Digest, CoreError> {
579 self.validate()?;
580 Digest::of_serializable("diffusion-pipeline-receipt-v1", self)
581 }
582}
583
584#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
586#[serde(deny_unknown_fields)]
587pub struct DiffusionCheckpointReceipt {
588 pub plan: Digest,
590 pub backend: Digest,
592 pub next_step: u32,
594 pub state: Digest,
596 pub continuation: Digest,
598}
599
600impl DiffusionCheckpointReceipt {
601 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 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}