incin-core 0.1.0

Core tensor operations and static shape checking for incin
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
use super::*;

/// Open operation contract for downstream static execution.
pub trait Operation: Clone + fmt::Debug + 'static {
    /// Typed attribute payload carried by this descriptor.
    type Attributes: Clone
        + fmt::Debug
        + PartialEq
        + core::any::Any
        + serde::Serialize
        + for<'de> serde::Deserialize<'de>;

    /// Stable key identifying this operation across registries.
    const KEY: OperationKey;

    /// Infers output metadata from checked logical input metadata.
    fn infer_outputs(
        attributes: &Self::Attributes,
        inputs: &[LogicalTensorMeta],
    ) -> Result<Vec<LogicalTensorMeta>, DescriptorError>;

    /// Infer a validated invocation through the open operation contract.
    fn infer_invocation(
        attributes: Self::Attributes,
        inputs: Vec<LogicalTensorMeta>,
    ) -> Result<ValidatedInvocation<Self>, DescriptorError>
    where
        Self: Sized,
    {
        ValidatedInvocation::<Self>::infer_custom_runtime(attributes, inputs)
    }

    /// Shape-specialized form of [`Self::infer_invocation`].
    fn infer_invocation_typed<S: crate::shapes::Shape>(
        attributes: Self::Attributes,
        inputs: Vec<LogicalTensorMeta>,
        expected: &crate::shapes::ShapeValue<S>,
    ) -> Result<ValidatedInvocation<Self>, DescriptorError>
    where
        Self: Sized,
    {
        ValidatedInvocation::<Self>::infer_custom_typed(attributes, inputs, expected)
    }
}

mod private {
    pub trait Sealed {}
}

/// A catalog operation with its exact typed attribute set.
pub trait CanonicalOperation: private::Sealed + Operation {
    /// Exact catalog identity of this operation.
    const ID: OperationKind;
}

incin_operation_catalog!(define_catalog);

macro_rules! seal_operations {
    ($(($variant:ident, $name:literal, $family:ident, $profile:ident, $attrs:ident, $min:expr, $max:expr, $legacy:literal),)*) => {$(impl private::Sealed for op::$variant {})*};
}
incin_operation_catalog!(seal_operations);

/// Concrete typed descriptor. `Descriptor<op::Add>` and
/// `Descriptor<op::Softmax>` are different, non-interchangeable Rust types.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(bound(
    serialize = "O::Attributes: serde::Serialize",
    deserialize = "O::Attributes: serde::Deserialize<'de>"
))]
pub struct Descriptor<O: Operation> {
    pub(super) attributes: O::Attributes,
    pub(super) inputs: Vec<LogicalTensorMeta>,
    pub(super) outputs: Vec<LogicalTensorMeta>,
    pub(super) identity: crate::exec::OperationIdentity,
    pub(super) marker: PhantomData<fn() -> O>,
}

impl<O: Operation> crate::exec::spec::ExecutionDescriptor for Descriptor<O> {
    fn output_shape(&self) -> Option<&ShapeBuf> {
        self.outputs
            .first()
            .and_then(|output| output.shape.as_ref())
    }
}

/// Supplies the graph identity used by the tracing execution adapter.
///
/// This is derived from the same canonical operation identity as capability
/// admission and descriptor execution. It is not a second operation catalog.
pub trait TraceDescriptor: crate::exec::spec::ExecutionDescriptor {
    /// Identity recorded into telemetry traces.
    fn trace_identity(&self) -> crate::exec::OperationIdentity;

    #[cfg(feature = "std")]
    /// Renders attributes for telemetry consumption.
    fn trace_attributes(
        &self,
    ) -> core::result::Result<
        alloc::collections::BTreeMap<alloc::string::String, crate::graph::AttributeValue>,
        &'static str,
    >;

    /// Serializes the descriptor body for trace replay.
    fn trace_descriptor_payload(
        &self,
    ) -> core::result::Result<Option<crate::graph::DescriptorPayload>, &'static str>;

    /// Names the output dtype for trace consumers.
    fn trace_output_dtype(
        &self,
        inputs: &[crate::exec::request::TensorHandle<'_>],
    ) -> Option<DTypeDescriptor>;
}

impl<O: Operation> TraceDescriptor for Descriptor<O> {
    fn trace_identity(&self) -> crate::exec::OperationIdentity {
        self.identity.clone()
    }

    #[cfg(feature = "std")]
    fn trace_attributes(
        &self,
    ) -> core::result::Result<
        alloc::collections::BTreeMap<alloc::string::String, crate::graph::AttributeValue>,
        &'static str,
    >
    where
        O::Attributes: serde::Serialize,
    {
        project_trace_attributes(&self.attributes)
    }

    fn trace_descriptor_payload(
        &self,
    ) -> core::result::Result<Option<crate::graph::DescriptorPayload>, &'static str> {
        #[cfg(not(feature = "std"))]
        {
            Err("descriptor capture requires the std serialization feature")
        }
        #[cfg(feature = "std")]
        {
            let payload = postcard::to_allocvec(self)
                .map_err(|_| "canonical descriptor serialization failed")?;
            Ok(Some(crate::graph::DescriptorPayload {
                schema: crate::exec::DescriptorSchemaVersion::CURRENT.get(),
                payload,
            }))
        }
    }

    fn trace_output_dtype(
        &self,
        inputs: &[crate::exec::request::TensorHandle<'_>],
    ) -> Option<DTypeDescriptor> {
        let OperationIdentity::Builtin(operation) = self.identity else {
            return self
                .outputs
                .first()
                .and_then(|output| output.dtype)
                .or_else(|| inputs.first().map(|input| input.metadata().dtype));
        };
        match operation {
            OperationKind::CmpEq
            | OperationKind::CmpNe
            | OperationKind::CmpLt
            | OperationKind::CmpLe
            | OperationKind::CmpGt
            | OperationKind::CmpGe
            | OperationKind::LogicalAnd
            | OperationKind::LogicalOr
            | OperationKind::LogicalNot => Some(DTypeId::Bool.into()),
            _ => self
                .outputs
                .first()
                .and_then(|output| output.dtype)
                .or_else(|| inputs.first().map(|input| input.metadata().dtype)),
        }
    }
}

impl<O: Operation> Descriptor<O> {
    #[must_use]
    /// Stable key of the captured operation.
    pub const fn key(&self) -> OperationKey {
        O::KEY
    }

    #[must_use]
    /// Typed attribute payload.
    pub const fn attributes(&self) -> &O::Attributes {
        &self.attributes
    }

    #[must_use]
    /// Validated output metadata.
    pub fn outputs(&self) -> &[LogicalTensorMeta] {
        &self.outputs
    }

    #[must_use]
    /// Validated input metadata.
    pub fn inputs(&self) -> &[LogicalTensorMeta] {
        &self.inputs
    }

    #[must_use]
    /// Operation identity proven at construction.
    pub const fn identity(&self) -> &crate::exec::OperationIdentity {
        &self.identity
    }
}

impl<O: CanonicalOperation> Descriptor<O>
where
    O::Attributes: AttributeContract,
{
    #[must_use]
    /// Operation this payload belongs to.
    pub const fn operation(&self) -> OperationKind {
        O::ID
    }

    /// Validate a runtime invocation and attach the resulting dynamic proof.
    ///
    /// This is the public construction seam for backend authors and other
    /// framework boundaries that need to execute an exact descriptor without
    /// reaching into frontend shape rules. Typed tensor frontends use their
    /// stronger proof path; this method intentionally records only dynamic
    /// knowledge.
    pub fn infer_runtime(
        attributes: O::Attributes,
        inputs: Vec<LogicalTensorMeta>,
    ) -> Result<crate::exec::Validated<Self>, DescriptorError> {
        attributes.validate(O::ID, &inputs)?;
        let outputs = O::infer_outputs(&attributes, &inputs)?;
        Ok(crate::exec::Validated::new(
            Self {
                attributes,
                inputs,
                outputs,
                identity: crate::exec::OperationIdentity::Builtin(O::ID),
                marker: PhantomData,
            },
            crate::exec::ProofLevel::Dynamic,
        ))
    }

    /// Revalidate a captured descriptor before execution.
    pub fn revalidate(&self) -> Result<crate::exec::Validated<Self>, DescriptorError> {
        self.attributes.validate(O::ID, &self.inputs)?;
        let outputs = O::infer_outputs(&self.attributes, &self.inputs)?;
        if outputs != self.outputs {
            return Err(DescriptorError::MetadataMismatch {
                operation: O::ID,
                output: 0,
                field: "outputs",
            });
        }
        Ok(crate::exec::Validated::new(
            self.clone(),
            crate::exec::ProofLevel::Dynamic,
        ))
    }
}

/// Storage-free serialized descriptor capture. The exact identity is outside
/// the payload so decoding as the wrong descriptor type fails closed.
#[cfg(feature = "std")]
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CapturedDescriptor {
    operation: OperationKind,
    schema: u32,
    pub(super) payload: Vec<u8>,
}

#[cfg(feature = "std")]
#[derive(Debug)]
/// Failures while capturing or decoding a descriptor payload.
pub enum DescriptorCaptureError {
    /// Descriptor identity disagrees with the requested operation.
    Identity {
        /// Operation the payload claims to be.
        expected: OperationKind,
        /// Operation the caller asked for.
        actual: OperationKind,
    },
    /// A custom-operation key collided with a builtin expectation.
    CustomIdentity {
        /// Operation the payload claims to be.
        expected: OperationKind,
        /// Custom key the payload carries.
        actual: OperationKey,
    },
    /// Descriptor schema version mismatch.
    Schema {
        /// Schema version this build speaks.
        expected: u32,
        /// Schema version found in the payload.
        actual: u32,
    },
    /// Payload failed to serialize.
    Encode(postcard::Error),
    /// Payload failed to deserialize.
    Decode(postcard::Error),
}

#[cfg(feature = "std")]
impl fmt::Display for DescriptorCaptureError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Identity { expected, actual } => write!(
                f,
                "captured descriptor identity {actual} does not match {expected}"
            ),
            Self::CustomIdentity { expected, actual } => write!(
                f,
                "captured descriptor identity {actual:?} does not match builtin {expected}"
            ),
            Self::Schema { expected, actual } => write!(
                f,
                "captured descriptor schema v{actual} does not match v{expected}"
            ),
            Self::Encode(error) => write!(f, "could not encode descriptor capture: {error}"),
            Self::Decode(error) => write!(f, "could not decode descriptor capture: {error}"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for DescriptorCaptureError {}

#[cfg(feature = "std")]
impl CapturedDescriptor {
    /// Wraps raw bytes as a capture for later decoding.
    pub fn from_payload(operation: OperationKind, schema: u32, payload: Vec<u8>) -> Self {
        Self {
            operation,
            schema,
            payload,
        }
    }

    /// Captures a validated descriptor into a portable payload.
    pub fn capture<O: CanonicalOperation>(
        descriptor: &Descriptor<O>,
    ) -> Result<Self, DescriptorCaptureError>
    where
        O::Attributes: AttributeContract,
    {
        let payload = postcard::to_allocvec(descriptor).map_err(DescriptorCaptureError::Encode)?;
        Ok(Self {
            operation: O::ID,
            schema: crate::exec::DescriptorSchemaVersion::CURRENT.get(),
            payload,
        })
    }

    #[must_use]
    /// Operation this payload belongs to.
    pub const fn operation(&self) -> OperationKind {
        self.operation
    }

    #[must_use]
    /// Schema version the payload was encoded with.
    pub const fn schema(&self) -> u32 {
        self.schema
    }

    #[must_use]
    /// Raw encoded descriptor bytes.
    pub fn payload(&self) -> &[u8] {
        &self.payload
    }

    /// Decodes the payload back into a validated descriptor.
    pub fn decode<O: CanonicalOperation>(&self) -> Result<Descriptor<O>, DescriptorCaptureError>
    where
        O::Attributes: AttributeContract,
    {
        if self.operation != O::ID {
            return Err(DescriptorCaptureError::Identity {
                expected: O::ID,
                actual: self.operation,
            });
        }
        let expected = crate::exec::DescriptorSchemaVersion::CURRENT.get();
        if self.schema != expected {
            return Err(DescriptorCaptureError::Schema {
                expected,
                actual: self.schema,
            });
        }
        let descriptor: Descriptor<O> =
            postcard::from_bytes(&self.payload).map_err(DescriptorCaptureError::Decode)?;
        if descriptor.identity != crate::exec::OperationIdentity::Builtin(O::ID) {
            return match descriptor.identity {
                crate::exec::OperationIdentity::Builtin(actual) => {
                    Err(DescriptorCaptureError::Identity {
                        expected: O::ID,
                        actual,
                    })
                }
                crate::exec::OperationIdentity::Custom(actual) => {
                    Err(DescriptorCaptureError::CustomIdentity {
                        expected: O::ID,
                        actual,
                    })
                }
            };
        }
        Ok(descriptor)
    }
}