tenferro-ad 0.3.0

Eager runtime, eager tensors, and traced AD extension traits for tenferro.
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Explicit ownership for automatic-differentiation rule sets.

use std::sync::Arc;

use tenferro_runtime::program::FrozenProgram;
use tenferro_runtime::{CacheStats, Result, TracedTensor};

// SemanticCompatDispatcher removed in Unification 7.
// Extension AD is handled exclusively by SemanticExtensionRuleSet.
use crate::semantic_extension::{SemanticExtensionRegistryError, SemanticExtensionRuleSet};
use crate::semantic_transform::{
    semantic_jvp, semantic_vjp, SemanticAdProgram, SemanticAdTransformError,
};
use crate::transform_cache::{
    AdTransformCache, AdTransformCacheLimits, SemanticAdTransformCacheKey,
};

/// Stats for caches owned by an [`AdContext`].
///
/// `retained_bytes` fields are logical payload estimates, not process RSS.
///
/// # Examples
///
/// ```rust
/// use tenferro_ad::AdContext;
///
/// let ad = AdContext::builder().build().unwrap();
/// assert_eq!(ad.cache_stats().unwrap().ad_transforms.entries, 0);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AdContextCacheStats {
    /// AD transform graph memoization cache.
    pub ad_transforms: CacheStats,
}

/// Explicit automatic-differentiation context.
///
/// `AdContext` owns the extension AD rules used by traced AD transforms.
/// It also owns the AD transform cache shared by context-driven traced AD and
/// eager runtimes created from this context.
///
/// # Examples
///
/// ```rust
/// use tenferro_ad::AdContext;
///
/// let ad = AdContext::builder().build().unwrap();
/// assert!(ad
///     .semantic_extension_rules()
///     .lookup_linearize("example.missing.v1")
///     .is_none());
/// ```
#[derive(Clone, Debug)]
pub struct AdContext {
    semantic_extension_rules: SemanticExtensionRuleSet,
    ad_transform_cache: Arc<AdTransformCache>,
}

impl AdContext {
    /// Start building an explicit AD context.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    ///
    /// let _builder = AdContext::builder();
    /// ```
    pub fn builder() -> AdContextBuilder {
        AdContextBuilder::default()
    }

    pub(crate) fn with_rules_and_transform_cache(
        semantic_extension_rules: SemanticExtensionRuleSet,
        ad_transform_cache: Arc<AdTransformCache>,
    ) -> Self {
        Self {
            semantic_extension_rules,
            ad_transform_cache,
        }
    }

    /// Return semantic-program extension AD rules owned by this context.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// assert!(ad
    ///     .semantic_extension_rules()
    ///     .lookup_linearize("example.missing.v1")
    ///     .is_none());
    /// ```
    pub fn semantic_extension_rules(&self) -> &SemanticExtensionRuleSet {
        &self.semantic_extension_rules
    }

    /// Transform a frozen semantic program into its forward-mode derivative.
    ///
    /// `active_inputs` follows source-program input order. Active tangent
    /// seeds are appended after all primal inputs.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticAdTransformError::ActivityArity`] when
    /// `active_inputs` has the wrong length,
    /// [`SemanticAdTransformError::Extension`] when an extension rule rejects
    /// the transform, or the corresponding `Query`, `Build`, `Finish`, or
    /// `Cache` variant when program import, construction, finalization, or
    /// cache access fails.
    pub fn jvp_program(
        &self,
        input: &FrozenProgram,
        active_inputs: &[bool],
    ) -> std::result::Result<SemanticAdProgram, SemanticAdTransformError> {
        let key = SemanticAdTransformCacheKey::jvp(input, active_inputs);
        if let Some(cached) = self
            .ad_transform_cache
            .get_semantic(&key, input)
            .map_err(SemanticAdTransformError::Cache)?
        {
            return cached
                .as_ref()
                .with_input_prefix_bindings_from(input)
                .map_err(SemanticAdTransformError::from);
        }
        let transformed = semantic_jvp(input, active_inputs, &self.semantic_extension_rules)?;
        self.ad_transform_cache
            .put_semantic(key, input, Arc::new(transformed.clone()))
            .map_err(SemanticAdTransformError::Cache)?;
        Ok(transformed)
    }

    /// Transform a frozen semantic program into its reverse-mode derivative.
    ///
    /// `active_inputs` selects requested primal-input cotangents and
    /// `active_outputs` selects primal outputs that receive appended seeds.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticAdTransformError::ActivityArity`] when either activity
    /// mask has the wrong length,
    /// [`SemanticAdTransformError::Extension`] when an extension rule rejects
    /// the transform, or the corresponding `Query`, `Build`, `Finish`, or
    /// `Cache` variant when program import, construction, finalization, or
    /// cache access fails.
    pub fn vjp_program(
        &self,
        input: &FrozenProgram,
        active_inputs: &[bool],
        active_outputs: &[bool],
    ) -> std::result::Result<SemanticAdProgram, SemanticAdTransformError> {
        let key = SemanticAdTransformCacheKey::vjp(input, active_inputs, active_outputs);
        if let Some(cached) = self
            .ad_transform_cache
            .get_semantic(&key, input)
            .map_err(SemanticAdTransformError::Cache)?
        {
            return cached
                .as_ref()
                .with_input_prefix_bindings_from(input)
                .map_err(SemanticAdTransformError::from);
        }
        let transformed = semantic_vjp(
            input,
            active_inputs,
            active_outputs,
            &self.semantic_extension_rules,
        )?;
        self.ad_transform_cache
            .put_semantic(key, input, Arc::new(transformed.clone()))
            .map_err(SemanticAdTransformError::Cache)?;
        Ok(transformed)
    }

    pub(crate) fn ad_transform_cache(&self) -> Arc<AdTransformCache> {
        Arc::clone(&self.ad_transform_cache)
    }

    /// Return AD transform cache retention limits.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// assert!(ad.ad_transform_cache_limits().unwrap().max_entries().get() > 0);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`tenferro_runtime::Error::RuntimeState`] if the cache lock is
    /// poisoned or its state cannot be inspected.
    pub fn ad_transform_cache_limits(&self) -> Result<AdTransformCacheLimits> {
        self.ad_transform_cache.limits()
    }

    /// Replace AD transform cache retention limits.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroUsize;
    /// use tenferro_ad::{AdContext, AdTransformCacheLimits};
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// let limits = AdTransformCacheLimits::new(NonZeroUsize::new(1).unwrap());
    /// ad.set_ad_transform_cache_limits(limits).unwrap();
    /// assert_eq!(ad.ad_transform_cache_limits().unwrap(), limits);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`tenferro_runtime::Error::RuntimeState`] if the cache lock is
    /// poisoned while updating the limits.
    pub fn set_ad_transform_cache_limits(&self, limits: AdTransformCacheLimits) -> Result<()> {
        self.ad_transform_cache.set_limits(limits)
    }

    /// Clear AD transform cache entries owned by this context.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// ad.clear_ad_transform_caches().unwrap();
    /// assert_eq!(ad.ad_transform_cache_stats().unwrap().entries, 0);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`tenferro_runtime::Error::RuntimeState`] if the cache lock is
    /// poisoned while clearing entries.
    pub fn clear_ad_transform_caches(&self) -> Result<()> {
        self.ad_transform_cache.clear()
    }

    /// Return AD transform cache-entry and retained-byte stats.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// assert_eq!(ad.ad_transform_cache_stats().unwrap().entries, 0);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`tenferro_runtime::Error::RuntimeState`] if the cache lock is
    /// poisoned while collecting statistics.
    pub fn ad_transform_cache_stats(&self) -> Result<CacheStats> {
        self.ad_transform_cache.stats()
    }

    /// Clear every cache owned by this AD context.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// ad.clear_caches().unwrap();
    /// assert_eq!(ad.cache_stats().unwrap().ad_transforms.entries, 0);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`tenferro_runtime::Error::RuntimeState`] if either owned cache
    /// cannot be locked because its state is poisoned.
    pub fn clear_caches(&self) -> Result<()> {
        self.clear_ad_transform_caches()
    }

    /// Return aggregate cache-entry and retained-byte stats for this AD context.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// assert_eq!(ad.cache_stats().unwrap().ad_transforms.retained_bytes, 0);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`tenferro_runtime::Error::RuntimeState`] if an owned cache lock
    /// is poisoned while collecting statistics.
    pub fn cache_stats(&self) -> Result<AdContextCacheStats> {
        Ok(AdContextCacheStats {
            ad_transforms: self.ad_transform_cache_stats()?,
        })
    }

    /// Gradient of a scalar traced output with respect to a traced input.
    ///
    /// For complex scalar outputs, tenferro returns the Hermitian-adjoint
    /// cotangent. To compare seed-`1` scalar gradients with JAX's public
    /// `grad` values, use the complex conjugate of this result. See
    /// <https://tensor4all.org/tenferro-rs/guides/complex-ad.html>.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    /// use tenferro_runtime::TracedTensor;
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// let x = TracedTensor::from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
    /// let loss = (&x * &x).unwrap();
    /// let grad = ad.grad(&loss, &x).unwrap();
    /// assert_eq!(grad.rank, 0);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`tenferro_runtime::Error::NonScalarGrad`] when `output` is not
    /// scalar, [`tenferro_runtime::Error::UnsupportedAdRule`] when a graph op
    /// lacks a registered rule, or a typed [`tenferro_runtime::Error::Validation`]
    /// / backend error when graph metadata or execution is invalid.
    pub fn grad(&self, output: &TracedTensor, wrt: &TracedTensor) -> Result<TracedTensor> {
        crate::traced::grad_with_rules_and_cache(
            output,
            wrt,
            &self.semantic_extension_rules,
            Some(self.ad_transform_cache.as_ref()),
        )
    }

    /// Gradient that returns `None` when `wrt` is inactive.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    /// use tenferro_runtime::TracedTensor;
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// let x = TracedTensor::from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
    /// let loss = (&x * &x).unwrap();
    /// assert!(ad.grad_optional(&loss, &x).unwrap().is_some());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`tenferro_runtime::Error::NonScalarGrad`] for a non-scalar
    /// output, [`tenferro_runtime::Error::UnsupportedAdRule`] for an
    /// unregistered AD rule, or a typed [`tenferro_runtime::Error::Validation`]
    /// / backend error from graph construction and
    /// execution.
    pub fn grad_optional(
        &self,
        output: &TracedTensor,
        wrt: &TracedTensor,
    ) -> Result<Option<TracedTensor>> {
        crate::traced::grad_optional_with_rules_and_cache(
            output,
            wrt,
            &self.semantic_extension_rules,
            Some(self.ad_transform_cache.as_ref()),
        )
    }

    /// Forward-mode Jacobian-vector product.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    /// use tenferro_runtime::TracedTensor;
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// let x = TracedTensor::from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
    /// let dx = TracedTensor::from_vec_col_major(vec![], vec![1.0_f64]).unwrap();
    /// let y = (&x * &x).unwrap();
    /// let dy = ad.jvp(&y, &x, &dx).unwrap();
    /// assert_eq!(dy.rank, 0);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`tenferro_runtime::Error::UnsupportedAdRule`] when the graph
    /// has no JVP rule, [`tenferro_runtime::Error::Validation`] for
    /// inconsistent tangent metadata, or a typed backend/runtime-state error
    /// during evaluation.
    pub fn jvp(
        &self,
        output: &TracedTensor,
        wrt: &TracedTensor,
        tangent: &TracedTensor,
    ) -> Result<TracedTensor> {
        crate::traced::jvp_with_rules_and_cache(
            output,
            wrt,
            tangent,
            &self.semantic_extension_rules,
            Some(self.ad_transform_cache.as_ref()),
        )
    }

    /// Forward-mode Jacobian-vector product that returns `None` for inactive output.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    /// use tenferro_runtime::TracedTensor;
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// let x = TracedTensor::from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
    /// let dx = TracedTensor::from_vec_col_major(vec![], vec![1.0_f64]).unwrap();
    /// let y = (&x * &x).unwrap();
    /// assert!(ad.jvp_optional(&y, &x, &dx).unwrap().is_some());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`tenferro_runtime::Error::UnsupportedAdRule`] when the graph
    /// has no JVP rule, [`tenferro_runtime::Error::Validation`] for
    /// inconsistent tangent metadata, or a typed backend/runtime-state error
    /// during evaluation.
    pub fn jvp_optional(
        &self,
        output: &TracedTensor,
        wrt: &TracedTensor,
        tangent: &TracedTensor,
    ) -> Result<Option<TracedTensor>> {
        crate::traced::jvp_optional_with_rules_and_cache(
            output,
            wrt,
            tangent,
            &self.semantic_extension_rules,
            Some(self.ad_transform_cache.as_ref()),
        )
    }

    /// Reverse-mode vector-Jacobian product.
    ///
    /// Complex cotangents use tenferro's Hermitian real-inner-product
    /// convention. Non-real complex cotangent seeds therefore need an explicit
    /// seed-convention comparison when matching JAX. See
    /// <https://tensor4all.org/tenferro-rs/guides/complex-ad.html>.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    /// use tenferro_runtime::TracedTensor;
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// let x = TracedTensor::from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
    /// let dy = TracedTensor::from_vec_col_major(vec![], vec![1.0_f64]).unwrap();
    /// let y = (&x * &x).unwrap();
    /// let dx = ad.vjp(&y, &x, &dy).unwrap();
    /// assert_eq!(dx.rank, 0);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`tenferro_runtime::Error::Validation`] when the cotangent
    /// metadata is incompatible, [`tenferro_runtime::Error::UnsupportedAdRule`]
    /// when a VJP rule is unavailable, or a typed backend/runtime-state error
    /// during execution.
    pub fn vjp(
        &self,
        output: &TracedTensor,
        wrt: &TracedTensor,
        cotangent: &TracedTensor,
    ) -> Result<TracedTensor> {
        crate::traced::vjp_with_rules_and_cache(
            output,
            wrt,
            cotangent,
            &self.semantic_extension_rules,
            Some(self.ad_transform_cache.as_ref()),
        )
    }

    /// Reverse-mode vector-Jacobian product that returns `None` for inactive input.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    /// use tenferro_runtime::TracedTensor;
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// let x = TracedTensor::from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
    /// let dy = TracedTensor::from_vec_col_major(vec![], vec![1.0_f64]).unwrap();
    /// let y = (&x * &x).unwrap();
    /// assert!(ad.vjp_optional(&y, &x, &dy).unwrap().is_some());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`tenferro_runtime::Error::Validation`] when the cotangent
    /// metadata is incompatible, [`tenferro_runtime::Error::UnsupportedAdRule`]
    /// when a VJP rule is unavailable, or a typed backend/runtime-state error
    /// during execution.
    pub fn vjp_optional(
        &self,
        output: &TracedTensor,
        wrt: &TracedTensor,
        cotangent: &TracedTensor,
    ) -> Result<Option<TracedTensor>> {
        crate::traced::vjp_optional_with_rules_and_cache(
            output,
            wrt,
            cotangent,
            &self.semantic_extension_rules,
            Some(self.ad_transform_cache.as_ref()),
        )
    }
}

/// Builder for [`AdContext`].
///
/// # Examples
///
/// ```rust
/// use tenferro_ad::AdContextBuilder;
///
/// let ad = AdContextBuilder::new().build().unwrap();
/// assert!(ad
///     .semantic_extension_rules()
///     .lookup_linearize("example.missing.v1")
///     .is_none());
/// ```
#[derive(Clone, Debug, Default)]
pub struct AdContextBuilder {
    semantic_extension_rules: SemanticExtensionRuleSet,
}

impl AdContextBuilder {
    /// Create an empty builder.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContextBuilder;
    ///
    /// let _builder = AdContextBuilder::new();
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Include an owned semantic-program extension AD rule set.
    ///
    /// # Errors
    ///
    /// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] when a
    /// family identifier is invalid, or
    /// [`SemanticExtensionRegistryError::DuplicateRule`] when the same family
    /// and role were already supplied.
    pub fn with_semantic_extension_rules(
        mut self,
        rules: SemanticExtensionRuleSet,
    ) -> std::result::Result<Self, SemanticExtensionRegistryError> {
        self.semantic_extension_rules.merge(rules)?;
        Ok(self)
    }

    /// Build the context.
    ///
    /// Semantic extension rules have already been validated and merged by
    /// [`Self::with_semantic_extension_rules`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_ad::AdContext;
    ///
    /// let ad = AdContext::builder().build().unwrap();
    /// assert!(ad
    ///     .semantic_extension_rules()
    ///     .lookup_linearize("example.missing.v1")
    ///     .is_none());
    /// ```
    ///
    /// # Errors
    ///
    /// The error type is [`std::convert::Infallible`], so this finalization step
    /// never returns `Err` after semantic rule registration. It retains a
    /// `Result` so callers can compose it with the fallible registration step.
    pub fn build(self) -> std::result::Result<AdContext, std::convert::Infallible> {
        Ok(AdContext {
            semantic_extension_rules: self.semantic_extension_rules,
            ad_transform_cache: Arc::new(AdTransformCache::new()),
        })
    }
}