tenferro-runtime 0.3.0

Concrete tensor helpers, traced tensors, graph execution, and extension runtime support for tenferro.
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
use tenferro_ops::dim_expr::DimExpr;
use tenferro_ops::shape_extent::ShapeExtent;
use tenferro_tensor::DType;

use super::EffectResourceError;

/// Diagnostic origin class of one semantic operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SemanticProvenanceKind {
    /// Operation was added directly through a semantic-program builder.
    Builder,
    /// Operation was preserved by importing another semantic program.
    Imported,
    /// Operation was produced by an internal semantic derivation.
    Derived,
}

#[derive(Clone)]
pub(crate) struct SemanticProvenance {
    kind: SemanticProvenanceKind,
    label: Option<std::sync::Arc<str>>,
}

impl SemanticProvenance {
    pub(crate) fn builder(label: Option<&str>) -> Self {
        Self {
            kind: SemanticProvenanceKind::Builder,
            label: label.map(std::sync::Arc::from),
        }
    }

    pub(crate) fn view(&self) -> SemanticProvenanceView<'_> {
        SemanticProvenanceView {
            kind: self.kind,
            label: self.label.as_deref(),
        }
    }
}

/// Bounded, allocation-free diagnostic provenance view.
#[derive(Clone, Copy)]
pub struct SemanticProvenanceView<'a> {
    kind: SemanticProvenanceKind,
    label: Option<&'a str>,
}

impl<'a> SemanticProvenanceView<'a> {
    /// Return the origin class without exposing source value or operation IDs.
    pub const fn kind(self) -> SemanticProvenanceKind {
        self.kind
    }

    /// Return an optional operation-family or transform label.
    pub const fn label(self) -> Option<&'a str> {
        self.label
    }
}

impl std::fmt::Debug for SemanticProvenanceView<'_> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("SemanticProvenanceView")
            .field("kind", &self.kind)
            .field("has_label", &self.label.is_some())
            .finish()
    }
}

/// Dtype and ordered symbolic extents of one semantic SSA value.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ProgramValueMetadata {
    dtype: DType,
    shape: Box<[ShapeExtent<DimExpr>]>,
}

impl ProgramValueMetadata {
    /// Construct value metadata from a dtype and symbolic shape.
    pub fn new(dtype: DType, shape: impl IntoIterator<Item = DimExpr>) -> Self {
        Self {
            dtype,
            shape: shape.into_iter().map(ShapeExtent::Exact).collect(),
        }
    }

    /// Construct metadata with explicit exact, bounded, or unknown extents.
    pub fn from_extents(
        dtype: DType,
        shape: impl IntoIterator<Item = ShapeExtent<DimExpr>>,
    ) -> Self {
        Self {
            dtype,
            shape: shape.into_iter().collect(),
        }
    }

    /// Return the value dtype.
    pub const fn dtype(&self) -> DType {
        self.dtype
    }

    /// Borrow the ordered symbolic extents without allocation.
    pub fn shape(&self) -> &[ShapeExtent<DimExpr>] {
        &self.shape
    }

    pub(crate) fn logical_retained_bytes(&self) -> Option<usize> {
        checked_sum([
            self.shape
                .len()
                .checked_mul(std::mem::size_of::<ShapeExtent<DimExpr>>())?,
            checked_sum_options(self.shape.iter().map(shape_extent_logical_retained_bytes))?,
        ])
    }
}

/// Metadata for one externally supplied semantic-program input.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ProgramInputSpec {
    metadata: ProgramValueMetadata,
}

impl ProgramInputSpec {
    /// Construct an input specification.
    pub fn new(dtype: DType, shape: impl IntoIterator<Item = DimExpr>) -> Self {
        Self {
            metadata: ProgramValueMetadata::new(dtype, shape),
        }
    }

    /// Construct an input specification with exact, bounded, or unknown extents.
    pub fn from_metadata(metadata: ProgramValueMetadata) -> Self {
        Self { metadata }
    }

    /// Borrow this input's value metadata.
    pub const fn metadata(&self) -> &ProgramValueMetadata {
        &self.metadata
    }
}

/// Relation enforced between two symbolic dimension expressions.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ProgramShapeRelation {
    /// Both expressions must evaluate to the same extent.
    Equal,
    /// The left expression must not exceed the right expression.
    LessEqual,
    /// The left expression must be at least the right expression.
    GreaterEqual,
}

/// A backend-neutral symbolic-shape obligation.
#[derive(Clone, Debug)]
pub struct ShapeGuard {
    relation: ProgramShapeRelation,
    lhs: DimExpr,
    rhs: DimExpr,
    source_family: Option<&'static str>,
}

impl ShapeGuard {
    /// Construct a shape guard.
    pub fn new(relation: ProgramShapeRelation, lhs: DimExpr, rhs: DimExpr) -> Self {
        Self {
            relation,
            lhs,
            rhs,
            source_family: None,
        }
    }

    pub(crate) fn with_source_family(mut self, family: &'static str) -> Self {
        self.source_family = Some(family);
        self
    }

    /// Return the required relation.
    pub const fn relation(&self) -> ProgramShapeRelation {
        self.relation
    }

    /// Borrow the left expression.
    pub const fn lhs(&self) -> &DimExpr {
        &self.lhs
    }

    /// Borrow the right expression.
    pub const fn rhs(&self) -> &DimExpr {
        &self.rhs
    }

    /// Return the diagnostic family that introduced this guard, when known.
    ///
    /// Diagnostic provenance does not participate in semantic equality or the
    /// semantic fingerprint.
    pub const fn source_family(&self) -> Option<&'static str> {
        self.source_family
    }

    pub(crate) fn logical_retained_bytes(&self) -> Option<usize> {
        checked_sum([
            dim_expr_logical_retained_bytes(&self.lhs)?,
            dim_expr_logical_retained_bytes(&self.rhs)?,
        ])
    }
}

impl PartialEq for ShapeGuard {
    fn eq(&self, other: &Self) -> bool {
        self.relation == other.relation && self.lhs == other.lhs && self.rhs == other.rhs
    }
}

impl Eq for ShapeGuard {}

impl std::hash::Hash for ShapeGuard {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.relation.hash(state);
        self.lhs.hash(state);
        self.rhs.hash(state);
    }
}

fn shape_extent_logical_retained_bytes(extent: &ShapeExtent<DimExpr>) -> Option<usize> {
    match extent {
        ShapeExtent::Exact(expression) | ShapeExtent::UpperBound(expression) => {
            dim_expr_logical_retained_bytes(expression)
        }
        ShapeExtent::Unknown => Some(0),
    }
}

fn dim_expr_logical_retained_bytes(expression: &DimExpr) -> Option<usize> {
    match expression {
        DimExpr::Const(_) | DimExpr::InputDim { .. } => Some(0),
        DimExpr::Add(left, right)
        | DimExpr::Sub(left, right)
        | DimExpr::Mul(left, right)
        | DimExpr::FloorDiv(left, right)
        | DimExpr::Min(left, right)
        | DimExpr::Max(left, right) => checked_sum([
            2usize.checked_mul(std::mem::size_of::<DimExpr>())?,
            dim_expr_logical_retained_bytes(left)?,
            dim_expr_logical_retained_bytes(right)?,
        ]),
    }
}

fn checked_sum(values: impl IntoIterator<Item = usize>) -> Option<usize> {
    values
        .into_iter()
        .try_fold(0usize, |sum, value| sum.checked_add(value))
}

fn checked_sum_options(values: impl IntoIterator<Item = Option<usize>>) -> Option<usize> {
    values
        .into_iter()
        .try_fold(0usize, |sum, value| sum.checked_add(value?))
}

/// Typed identity of an observable state resource.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct EffectResource {
    family: &'static str,
    key: u64,
}

impl EffectResource {
    /// Construct a versioned resource identity.
    ///
    /// # Errors
    ///
    /// Returns [`EffectResourceError::InvalidFamily`] when `family` is empty
    /// or has no `.v<version>` suffix.
    pub fn new(family: &'static str, key: u64) -> Result<Self, EffectResourceError> {
        let version = family.rsplit_once(".v").map(|(_, version)| version);
        if family.is_empty()
            || !version.is_some_and(|version| {
                !version.is_empty() && version.bytes().all(|byte| byte.is_ascii_digit())
            })
        {
            return Err(EffectResourceError::InvalidFamily);
        }
        Ok(Self { family, key })
    }

    /// Return the stable resource family.
    pub const fn family(self) -> &'static str {
        self.family
    }

    /// Return the family-local resource key.
    pub const fn key(self) -> u64 {
        self.key
    }
}

/// Access mode of one semantic effect.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EffectAccess {
    /// Read-only access.
    Read,
    /// Mutating access.
    Write,
}

/// One typed observable state access.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Effect {
    resource: EffectResource,
    access: EffectAccess,
}

impl Effect {
    /// Construct a typed effect.
    pub const fn new(resource: EffectResource, access: EffectAccess) -> Self {
        Self { resource, access }
    }

    /// Return the affected resource.
    pub const fn resource(self) -> EffectResource {
        self.resource
    }

    /// Return the access mode.
    pub const fn access(self) -> EffectAccess {
        self.access
    }
}

/// Semantic alias class for one operation output.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AliasKind {
    /// The output has fresh value semantics.
    Fresh,
    /// The output is a view of an input.
    ViewOf,
    /// The output must alias an input.
    MustAlias,
    /// The output aliases an external typed resource.
    ExternalAlias,
}

/// Alias contract for one operation output.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Alias {
    kind: AliasKind,
    output: usize,
    input: Option<usize>,
    resource: Option<EffectResource>,
}

impl Alias {
    /// Declare a semantically fresh output.
    pub const fn fresh(output: usize) -> Self {
        Self {
            kind: AliasKind::Fresh,
            output,
            input: None,
            resource: None,
        }
    }

    /// Declare an output view of an input.
    pub const fn view_of(output: usize, input: usize) -> Self {
        Self {
            kind: AliasKind::ViewOf,
            output,
            input: Some(input),
            resource: None,
        }
    }

    /// Require an output to alias an input.
    pub const fn must_alias(output: usize, input: usize) -> Self {
        Self {
            kind: AliasKind::MustAlias,
            output,
            input: Some(input),
            resource: None,
        }
    }

    /// Declare an alias of an external typed resource.
    pub const fn external(output: usize, resource: EffectResource) -> Self {
        Self {
            kind: AliasKind::ExternalAlias,
            output,
            input: None,
            resource: Some(resource),
        }
    }

    /// Return the alias class.
    pub const fn kind(self) -> AliasKind {
        self.kind
    }

    /// Return the operation-local output index.
    pub const fn output(self) -> usize {
        self.output
    }

    /// Return the aliased input index, when applicable.
    pub const fn input(self) -> Option<usize> {
        self.input
    }

    /// Return the external resource, when applicable.
    pub const fn resource(self) -> Option<EffectResource> {
        self.resource
    }
}

/// Kind of unresolved semantic placement requirement.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SemanticPlacementKind {
    /// No semantic placement restriction.
    Any,
    /// Placement must match one operation input.
    SameAsInput,
}

/// Backend-neutral placement requirement retained for runtime preparation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SemanticPlacementConstraint {
    kind: SemanticPlacementKind,
    input: Option<usize>,
}

impl SemanticPlacementConstraint {
    /// Construct an unrestricted placement constraint.
    pub const fn any() -> Self {
        Self {
            kind: SemanticPlacementKind::Any,
            input: None,
        }
    }

    /// Require placement compatible with one operation input.
    pub const fn same_as_input(input: usize) -> Self {
        Self {
            kind: SemanticPlacementKind::SameAsInput,
            input: Some(input),
        }
    }

    /// Return the placement kind.
    pub const fn kind(self) -> SemanticPlacementKind {
        self.kind
    }

    /// Return the referenced input index, when applicable.
    pub const fn input(self) -> Option<usize> {
        self.input
    }
}