use crate::shapes::{ProofLevel, Shape};
use core::fmt;
#[cfg(feature = "paranoid-validation")]
use crate::shapes::error::ShapeError;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ShapeEvidence {
pub(crate) proof: ProofLevel,
pub(crate) static_rank: Option<usize>,
pub(crate) static_numel: Option<usize>,
}
impl ShapeEvidence {
pub(crate) const fn dynamic() -> Self {
Self {
proof: ProofLevel::Dynamic,
static_rank: None,
static_numel: None,
}
}
pub(crate) const fn of<S: Shape>() -> Self {
Self {
proof: S::PROOF,
static_rank: S::RANK,
static_numel: S::STATIC_NUMEL,
}
}
#[must_use]
pub const fn proof(self) -> ProofLevel {
self.proof
}
pub const fn static_rank(self) -> Option<usize> {
self.static_rank
}
pub const fn static_numel(self) -> Option<usize> {
self.static_numel
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Validated<O> {
descriptor: O,
proof: ProofLevel,
evidence: ShapeEvidence,
}
impl<O> Validated<O> {
pub(crate) const fn new(descriptor: O, proof: ProofLevel) -> Self {
Self {
descriptor,
proof,
evidence: ShapeEvidence {
proof,
..ShapeEvidence::dynamic()
},
}
}
pub(crate) const fn new_with_evidence(descriptor: O, evidence: ShapeEvidence) -> Self {
Self {
descriptor,
proof: evidence.proof,
evidence,
}
}
#[must_use]
pub const fn descriptor(&self) -> &O {
&self.descriptor
}
#[must_use]
pub const fn proof_level(&self) -> ProofLevel {
self.proof
}
#[must_use]
pub const fn shape_evidence(&self) -> ShapeEvidence {
self.evidence
}
#[must_use]
pub fn into_descriptor(self) -> O {
self.descriptor
}
}
impl<O: fmt::Debug> fmt::Display for Validated<O> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?} [{} proof]", self.descriptor, self.proof)
}
}
#[cfg(feature = "paranoid-validation")]
impl<O: super::spec::ExecutionDescriptor> Validated<O> {
pub fn audit(&self) -> Result<(), ShapeError> {
self.descriptor.output_shape().map_or(Ok(()), |shape| {
shape
.checked_numel(crate::shapes::error::OperationKind::Storage)
.map(|_| ())
})
}
}
#[macro_export]
macro_rules! paranoid_audit {
($validated:expr) => {{
#[cfg(feature = "paranoid-validation")]
{
$crate::exec::proof::__audit_or_panic(&$validated);
}
#[cfg(not(feature = "paranoid-validation"))]
{
let _ = &$validated;
}
}};
}
#[cfg(feature = "paranoid-validation")]
#[doc(hidden)]
pub fn __audit_or_panic<O: super::spec::ExecutionDescriptor>(validated: &Validated<O>) {
if let Err(error) = validated.audit() {
panic!("paranoid-validation: descriptor failed its own invariants: {error:?}");
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::exec::catalog::NoAttributes;
use crate::exec::{Descriptor, LogicalTensorMeta, op};
use crate::shapes::{Dyn, ShapeBuf};
use typenum::{U2, U3};
type Static23 = crate::shapes::DimCons<U2, crate::shapes::DimCons<U3, crate::shapes::Nil>>;
type Mixed23 = crate::shapes::DimCons<U2, crate::shapes::DimCons<usize, crate::shapes::Nil>>;
type Mixed32 = crate::shapes::DimCons<usize, crate::shapes::DimCons<U3, crate::shapes::Nil>>;
type MixedDyn =
crate::shapes::DimCons<usize, crate::shapes::DimCons<usize, crate::shapes::Nil>>;
#[test]
fn a_fully_typed_shape_proves_itself_statically() {
assert_eq!(ProofLevel::of::<Static23>(), ProofLevel::Static);
assert_eq!(ProofLevel::of::<crate::shapes::Nil>(), ProofLevel::Static);
}
#[test]
fn one_runtime_axis_weakens_the_whole_shape() {
assert_eq!(ProofLevel::of::<Mixed23>(), ProofLevel::Mixed);
assert_eq!(ProofLevel::of::<Mixed32>(), ProofLevel::Mixed);
assert_eq!(ProofLevel::of::<MixedDyn>(), ProofLevel::Mixed);
}
#[test]
fn a_ranked_shape_knows_its_rank_but_not_its_extents() {
assert_eq!(
ProofLevel::of::<crate::shapes::Ranked<typenum::U3>>(),
ProofLevel::Mixed
);
assert!(ProofLevel::of::<crate::shapes::Ranked<typenum::U3>>().has_static_rank());
assert!(!ProofLevel::of::<crate::shapes::Ranked<typenum::U3>>().is_static());
}
#[test]
fn an_unranked_shape_proves_nothing_before_it_exists() {
assert_eq!(ProofLevel::of::<Dyn>(), ProofLevel::Dynamic);
assert!(!ProofLevel::of::<Dyn>().has_static_rank());
}
#[test]
fn a_named_axis_is_typed_but_not_statically_sized() {
crate::dim!(Batch);
assert_eq!(
ProofLevel::of::<
crate::shapes::DimCons<
crate::shapes::dim::NamedDim<Batch, usize>,
crate::shapes::DimCons<U3, crate::shapes::Nil>,
>,
>(),
ProofLevel::Mixed
);
}
#[test]
fn meet_takes_the_weaker_operand() {
assert_eq!(
ProofLevel::Static.meet(ProofLevel::Mixed),
ProofLevel::Mixed
);
assert_eq!(
ProofLevel::Mixed.meet(ProofLevel::Dynamic),
ProofLevel::Dynamic
);
assert_eq!(
ProofLevel::Static.meet(ProofLevel::Static),
ProofLevel::Static
);
}
#[test]
fn meet_is_commutative_idempotent_and_topped_by_static() {
let levels = [ProofLevel::Static, ProofLevel::Mixed, ProofLevel::Dynamic];
for a in levels {
assert_eq!(a.meet(a), a, "idempotent");
assert_eq!(ProofLevel::Static.meet(a), a, "Static is the identity");
for b in levels {
assert_eq!(a.meet(b), b.meet(a), "commutative");
for c in levels {
assert_eq!(
a.meet(b).meet(c),
a.meet(b.meet(c)),
"associative, so folding N operands is order-independent"
);
}
}
}
}
#[test]
fn a_sealed_descriptor_still_reads_back_exactly() {
let spec = Descriptor::<op::Add>::infer_runtime(
NoAttributes,
vec![
LogicalTensorMeta {
shape: Some(ShapeBuf::from_slice(&[2, 3])),
dtype: None,
device: None,
},
LogicalTensorMeta {
shape: Some(ShapeBuf::from_slice(&[1, 3])),
dtype: None,
device: None,
},
],
)
.unwrap()
.into_descriptor();
let validated = Validated::new(spec.clone(), ProofLevel::Mixed);
assert_eq!(validated.descriptor(), &spec);
assert_eq!(validated.proof_level(), ProofLevel::Mixed);
assert_eq!(validated.into_descriptor(), spec);
}
#[test]
fn the_proof_is_carried_not_recomputed() {
let spec = Descriptor::<op::Add>::infer_runtime(
NoAttributes,
vec![
LogicalTensorMeta {
shape: Some(ShapeBuf::from_slice(&[2, 3])),
dtype: None,
device: None,
},
LogicalTensorMeta {
shape: Some(ShapeBuf::from_slice(&[2, 3])),
dtype: None,
device: None,
},
],
)
.unwrap()
.into_descriptor();
let validated = Validated::new(spec, ProofLevel::of::<Static23>());
assert!(validated.proof_level().is_static());
}
#[cfg(feature = "paranoid-validation")]
#[test]
fn audit_passes_for_a_descriptor_from_a_checked_constructor() {
let spec = Descriptor::<op::Add>::infer_runtime(
NoAttributes,
vec![
LogicalTensorMeta {
shape: Some(ShapeBuf::from_slice(&[2, 3])),
dtype: None,
device: None,
},
LogicalTensorMeta {
shape: Some(ShapeBuf::from_slice(&[1, 3])),
dtype: None,
device: None,
},
],
)
.unwrap()
.into_descriptor();
let validated = Validated::new(spec, ProofLevel::Mixed);
assert!(validated.audit().is_ok());
}
}