xad-rs 0.1.1

Automatic differentiation library for Rust — forward/reverse mode AD, a Rust port of the C++ XAD library (https://github.com/auto-differentiation/xad)
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
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
//! `AReal` — active real number for reverse-mode (adjoint) AD.
//!
//! An [`AReal<T>`] wraps a scalar value and, when a [`Tape`] is active on
//! the current thread, records every arithmetic and transcendental
//! operation onto that tape. After the forward pass completes, calling
//! [`Tape::compute_adjoints`](crate::tape::Tape::compute_adjoints) walks
//! the recorded trace in reverse and accumulates partial derivatives.
//!
//! # Workflow
//!
//! 1. Create a [`Tape`] and call [`Tape::activate`] to install it as the
//!    thread-local active tape.
//! 2. Wrap your input scalars in [`AReal::new`] and register them with
//!    [`AReal::register_input`]; this hands out tape slots for the inputs
//!    without emitting any statements (they only accumulate adjoints, never
//!    appear as an LHS in the trace).
//! 3. Run your computation normally — every `+`, `-`, `*`, `/`, and
//!    `crate::math::ad::*` call pushes a new statement onto the active tape
//!    via one of [`Tape::push_binary`] / [`Tape::push_unary`].
//! 4. Register outputs with [`AReal::register_output`] (a no-op for values
//!    already on the tape — the common case — and a fresh slot for
//!    constant outputs), seed the starting adjoint via
//!    [`AReal::set_adjoint`], then call
//!    [`Tape::compute_adjoints`](crate::tape::Tape::compute_adjoints).
//! 5. Read back each input's gradient via [`AReal::adjoint`].
//! 6. Call [`Tape::deactivate_all`](crate::tape::Tape::deactivate_all) (or
//!    simply drop the `Tape`) when you're done.
//!
//! # Hot-path design
//!
//! Every binary operator on `AReal` — `+`, `-`, `*`, `/`, and all
//! transcendentals from [`crate::math::ad`] — dispatches through a small,
//! allocation-free helper (`record_binary` / `record_unary`) that reads the
//! thread-local tape pointer, allocates a fresh slot, and pushes the
//! operand(s) via the fixed-arity `Tape::push_*` fast paths. No
//! intermediate `Vec` or slice is constructed per op; the whole tape-
//! recording cost for a single binary op is a thread-local load, a
//! derivatives-buffer `push`, and two `operations`-buffer pushes.

use crate::tape::{Tape, TapeStorage};
use std::fmt;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};

/// Active real number for reverse-mode AD.
///
/// Wraps a scalar value and a tape slot. When a tape is active, all operations
/// involving `AReal` values are recorded for later adjoint computation.
#[derive(Clone)]
pub struct AReal<T: TapeStorage> {
    value: T,
    pub(crate) slot: u32,
}

const INVALID_SLOT: u32 = u32::MAX;

impl<T: TapeStorage> AReal<T> {
    /// Create a new AReal with the given value. Not registered on any tape.
    pub fn new(value: T) -> Self {
        AReal {
            value,
            slot: INVALID_SLOT,
        }
    }

    /// Get the underlying value.
    #[inline]
    pub fn value(&self) -> T {
        self.value
    }

    /// Set the underlying value.
    #[inline]
    pub fn set_value(&mut self, v: T) {
        self.value = v;
    }

    /// Get the tape slot (derivative index).
    #[inline]
    pub fn slot(&self) -> u32 {
        self.slot
    }

    /// Whether this variable is registered on the tape.
    #[inline]
    pub fn should_record(&self) -> bool {
        self.slot != INVALID_SLOT
    }

    /// Get the adjoint (derivative) from the given tape.
    #[inline]
    pub fn adjoint(&self, tape: &Tape<T>) -> T {
        if self.slot == INVALID_SLOT {
            T::zero()
        } else {
            tape.derivative(self.slot)
        }
    }

    /// Set the adjoint (derivative) on the given tape.
    #[inline]
    pub fn set_adjoint(&self, tape: &mut Tape<T>, value: T) {
        if self.slot != INVALID_SLOT {
            tape.set_derivative(self.slot, value);
        }
    }

    /// Register this variable as an input on the tape.
    ///
    /// Input variables are given a fresh slot but **no** tape statement is
    /// emitted for them — inputs never appear on the LHS of any operation,
    /// so there is nothing to record during the reverse sweep. Their
    /// derivatives accumulate in-place in the tape's derivative buffer and
    /// are read back via [`AReal::adjoint`] after `compute_adjoints`.
    pub fn register_input(vars: &mut [AReal<T>], tape: &mut Tape<T>) {
        for v in vars.iter_mut() {
            if !v.should_record() {
                v.slot = tape.register_variable();
            }
        }
    }

    /// Register this variable as an output on the tape.
    ///
    /// In practice the final result of a forward pass is already on the
    /// tape (it was created by the last binary/unary op), so this is a
    /// no-op for most call sites. For constant outputs that never touched
    /// the tape, it allocates a fresh slot — again without emitting a
    /// statement, for the same reason as [`AReal::register_input`].
    pub fn register_output(vars: &mut [AReal<T>], tape: &mut Tape<T>) {
        for v in vars.iter_mut() {
            if !v.should_record() {
                v.slot = tape.register_variable();
            }
        }
    }
}

// Helper to record a binary operation on the active tape.
//
// Hot path: called from every AReal `+`, `-`, `*`, `/`. Uses the fixed-arity
// `Tape::push_binary` fast path so there is no `Vec` allocation and no
// intermediate slice construction per operation.
#[inline]
fn record_binary<T: TapeStorage>(
    result_value: T,
    lhs_slot: u32,
    lhs_mul: T,
    rhs_slot: u32,
    rhs_mul: T,
) -> AReal<T> {
    let tape_ptr = Tape::<T>::get_active();
    if let Some(ptr) = tape_ptr {
        // SAFETY: `ptr` comes from the thread-local active-tape slot, which
        // is only set via `Tape::activate` against a live `&mut Tape` and
        // cleared on drop; the tape cannot be concurrently aliased because
        // the tape pointer is thread-local.
        let tape = unsafe { &mut *ptr };
        let slot = tape.register_variable();
        tape.push_binary(slot, lhs_mul, lhs_slot, rhs_mul, rhs_slot);
        AReal { value: result_value, slot }
    } else {
        AReal::new(result_value)
    }
}

#[inline]
fn record_unary<T: TapeStorage>(result_value: T, input_slot: u32, multiplier: T) -> AReal<T> {
    let tape_ptr = Tape::<T>::get_active();
    if let Some(ptr) = tape_ptr {
        // SAFETY: see `record_binary`.
        let tape = unsafe { &mut *ptr };
        let slot = tape.register_variable();
        tape.push_unary(slot, multiplier, input_slot);
        AReal { value: result_value, slot }
    } else {
        AReal::new(result_value)
    }
}

pub(crate) fn record_unary_op<T: TapeStorage>(
    result_value: T,
    input_slot: u32,
    multiplier: T,
) -> AReal<T> {
    record_unary(result_value, input_slot, multiplier)
}

pub(crate) fn record_binary_op<T: TapeStorage>(
    result_value: T,
    a_slot: u32,
    a_mul: T,
    b_slot: u32,
    b_mul: T,
) -> AReal<T> {
    record_binary(result_value, a_slot, a_mul, b_slot, b_mul)
}

// Assignment from a scalar: create an unrecorded AReal.
impl<T: TapeStorage> From<T> for AReal<T> {
    fn from(value: T) -> Self {
        AReal::new(value)
    }
}

impl From<i32> for AReal<f64> {
    fn from(value: i32) -> Self {
        AReal::new(value as f64)
    }
}

impl From<i32> for AReal<f32> {
    fn from(value: i32) -> Self {
        AReal::new(value as f32)
    }
}

// --- Operator implementations ---

// AReal + AReal
impl<T: TapeStorage> Add for AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn add(self, rhs: AReal<T>) -> AReal<T> {
        record_binary(
            self.value + rhs.value,
            self.slot,
            T::one(),
            rhs.slot,
            T::one(),
        )
    }
}

impl<T: TapeStorage> Add for &AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn add(self, rhs: &AReal<T>) -> AReal<T> {
        record_binary(
            self.value + rhs.value,
            self.slot,
            T::one(),
            rhs.slot,
            T::one(),
        )
    }
}

impl<T: TapeStorage> Add<&AReal<T>> for AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn add(self, rhs: &AReal<T>) -> AReal<T> {
        record_binary(
            self.value + rhs.value,
            self.slot,
            T::one(),
            rhs.slot,
            T::one(),
        )
    }
}

impl<T: TapeStorage> Add<AReal<T>> for &AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn add(self, rhs: AReal<T>) -> AReal<T> {
        record_binary(
            self.value + rhs.value,
            self.slot,
            T::one(),
            rhs.slot,
            T::one(),
        )
    }
}

// AReal + scalar
impl<T: TapeStorage> Add<T> for AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn add(self, rhs: T) -> AReal<T> {
        record_unary(self.value + rhs, self.slot, T::one())
    }
}

impl<T: TapeStorage> Add<T> for &AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn add(self, rhs: T) -> AReal<T> {
        record_unary(self.value + rhs, self.slot, T::one())
    }
}

// scalar + AReal (only for f64 and f32 to avoid orphan rules)
impl Add<AReal<f64>> for f64 {
    type Output = AReal<f64>;
    #[inline]
    fn add(self, rhs: AReal<f64>) -> AReal<f64> {
        record_unary(self + rhs.value, rhs.slot, 1.0)
    }
}

impl Add<&AReal<f64>> for f64 {
    type Output = AReal<f64>;
    #[inline]
    fn add(self, rhs: &AReal<f64>) -> AReal<f64> {
        record_unary(self + rhs.value, rhs.slot, 1.0)
    }
}

impl Add<AReal<f32>> for f32 {
    type Output = AReal<f32>;
    #[inline]
    fn add(self, rhs: AReal<f32>) -> AReal<f32> {
        record_unary(self + rhs.value, rhs.slot, 1.0)
    }
}

impl Add<&AReal<f32>> for f32 {
    type Output = AReal<f32>;
    #[inline]
    fn add(self, rhs: &AReal<f32>) -> AReal<f32> {
        record_unary(self + rhs.value, rhs.slot, 1.0)
    }
}

// AReal - AReal
impl<T: TapeStorage> Sub for AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn sub(self, rhs: AReal<T>) -> AReal<T> {
        record_binary(
            self.value - rhs.value,
            self.slot,
            T::one(),
            rhs.slot,
            -T::one(),
        )
    }
}

impl<T: TapeStorage> Sub for &AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn sub(self, rhs: &AReal<T>) -> AReal<T> {
        record_binary(
            self.value - rhs.value,
            self.slot,
            T::one(),
            rhs.slot,
            -T::one(),
        )
    }
}

impl<T: TapeStorage> Sub<&AReal<T>> for AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn sub(self, rhs: &AReal<T>) -> AReal<T> {
        record_binary(
            self.value - rhs.value,
            self.slot,
            T::one(),
            rhs.slot,
            -T::one(),
        )
    }
}

impl<T: TapeStorage> Sub<AReal<T>> for &AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn sub(self, rhs: AReal<T>) -> AReal<T> {
        record_binary(
            self.value - rhs.value,
            self.slot,
            T::one(),
            rhs.slot,
            -T::one(),
        )
    }
}

// AReal - scalar
impl<T: TapeStorage> Sub<T> for AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn sub(self, rhs: T) -> AReal<T> {
        record_unary(self.value - rhs, self.slot, T::one())
    }
}

impl<T: TapeStorage> Sub<T> for &AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn sub(self, rhs: T) -> AReal<T> {
        record_unary(self.value - rhs, self.slot, T::one())
    }
}

// scalar - AReal
impl Sub<AReal<f64>> for f64 {
    type Output = AReal<f64>;
    #[inline]
    fn sub(self, rhs: AReal<f64>) -> AReal<f64> {
        record_unary(self - rhs.value, rhs.slot, -1.0)
    }
}

impl Sub<&AReal<f64>> for f64 {
    type Output = AReal<f64>;
    #[inline]
    fn sub(self, rhs: &AReal<f64>) -> AReal<f64> {
        record_unary(self - rhs.value, rhs.slot, -1.0)
    }
}

impl Sub<AReal<f32>> for f32 {
    type Output = AReal<f32>;
    #[inline]
    fn sub(self, rhs: AReal<f32>) -> AReal<f32> {
        record_unary(self - rhs.value, rhs.slot, -1.0)
    }
}

impl Sub<&AReal<f32>> for f32 {
    type Output = AReal<f32>;
    #[inline]
    fn sub(self, rhs: &AReal<f32>) -> AReal<f32> {
        record_unary(self - rhs.value, rhs.slot, -1.0)
    }
}

// AReal * AReal
impl<T: TapeStorage> Mul for AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn mul(self, rhs: AReal<T>) -> AReal<T> {
        // d(a*b) = b*da + a*db
        record_binary(
            self.value * rhs.value,
            self.slot,
            rhs.value,
            rhs.slot,
            self.value,
        )
    }
}

impl<T: TapeStorage> Mul for &AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn mul(self, rhs: &AReal<T>) -> AReal<T> {
        record_binary(
            self.value * rhs.value,
            self.slot,
            rhs.value,
            rhs.slot,
            self.value,
        )
    }
}

impl<T: TapeStorage> Mul<&AReal<T>> for AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn mul(self, rhs: &AReal<T>) -> AReal<T> {
        record_binary(
            self.value * rhs.value,
            self.slot,
            rhs.value,
            rhs.slot,
            self.value,
        )
    }
}

impl<T: TapeStorage> Mul<AReal<T>> for &AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn mul(self, rhs: AReal<T>) -> AReal<T> {
        record_binary(
            self.value * rhs.value,
            self.slot,
            rhs.value,
            rhs.slot,
            self.value,
        )
    }
}

// AReal * scalar
impl<T: TapeStorage> Mul<T> for AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn mul(self, rhs: T) -> AReal<T> {
        record_unary(self.value * rhs, self.slot, rhs)
    }
}

impl<T: TapeStorage> Mul<T> for &AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn mul(self, rhs: T) -> AReal<T> {
        record_unary(self.value * rhs, self.slot, rhs)
    }
}

// scalar * AReal
impl Mul<AReal<f64>> for f64 {
    type Output = AReal<f64>;
    #[inline]
    fn mul(self, rhs: AReal<f64>) -> AReal<f64> {
        record_unary(self * rhs.value, rhs.slot, self)
    }
}

impl Mul<&AReal<f64>> for f64 {
    type Output = AReal<f64>;
    #[inline]
    fn mul(self, rhs: &AReal<f64>) -> AReal<f64> {
        record_unary(self * rhs.value, rhs.slot, self)
    }
}

impl Mul<AReal<f32>> for f32 {
    type Output = AReal<f32>;
    #[inline]
    fn mul(self, rhs: AReal<f32>) -> AReal<f32> {
        record_unary(self * rhs.value, rhs.slot, self)
    }
}

impl Mul<&AReal<f32>> for f32 {
    type Output = AReal<f32>;
    #[inline]
    fn mul(self, rhs: &AReal<f32>) -> AReal<f32> {
        record_unary(self * rhs.value, rhs.slot, self)
    }
}

// AReal / AReal
impl<T: TapeStorage> Div for AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn div(self, rhs: AReal<T>) -> AReal<T> {
        // d(a/b) = da/b - a*db/b^2
        let inv_b = T::one() / rhs.value;
        record_binary(
            self.value * inv_b,
            self.slot,
            inv_b,
            rhs.slot,
            -self.value * inv_b * inv_b,
        )
    }
}

impl<T: TapeStorage> Div for &AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn div(self, rhs: &AReal<T>) -> AReal<T> {
        let inv_b = T::one() / rhs.value;
        record_binary(
            self.value * inv_b,
            self.slot,
            inv_b,
            rhs.slot,
            -self.value * inv_b * inv_b,
        )
    }
}

impl<T: TapeStorage> Div<&AReal<T>> for AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn div(self, rhs: &AReal<T>) -> AReal<T> {
        let inv_b = T::one() / rhs.value;
        record_binary(
            self.value * inv_b,
            self.slot,
            inv_b,
            rhs.slot,
            -self.value * inv_b * inv_b,
        )
    }
}

impl<T: TapeStorage> Div<AReal<T>> for &AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn div(self, rhs: AReal<T>) -> AReal<T> {
        let inv_b = T::one() / rhs.value;
        record_binary(
            self.value * inv_b,
            self.slot,
            inv_b,
            rhs.slot,
            -self.value * inv_b * inv_b,
        )
    }
}

// AReal / scalar
impl<T: TapeStorage> Div<T> for AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn div(self, rhs: T) -> AReal<T> {
        let inv = T::one() / rhs;
        record_unary(self.value * inv, self.slot, inv)
    }
}

impl<T: TapeStorage> Div<T> for &AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn div(self, rhs: T) -> AReal<T> {
        let inv = T::one() / rhs;
        record_unary(self.value * inv, self.slot, inv)
    }
}

// scalar / AReal
impl Div<AReal<f64>> for f64 {
    type Output = AReal<f64>;
    #[inline]
    fn div(self, rhs: AReal<f64>) -> AReal<f64> {
        // d(a/x) = -a/x^2 * dx
        let inv = 1.0 / rhs.value;
        record_unary(self * inv, rhs.slot, -self * inv * inv)
    }
}

impl Div<&AReal<f64>> for f64 {
    type Output = AReal<f64>;
    #[inline]
    fn div(self, rhs: &AReal<f64>) -> AReal<f64> {
        let inv = 1.0 / rhs.value;
        record_unary(self * inv, rhs.slot, -self * inv * inv)
    }
}

impl Div<AReal<f32>> for f32 {
    type Output = AReal<f32>;
    #[inline]
    fn div(self, rhs: AReal<f32>) -> AReal<f32> {
        let inv = 1.0 / rhs.value;
        record_unary(self * inv, rhs.slot, -self * inv * inv)
    }
}

impl Div<&AReal<f32>> for f32 {
    type Output = AReal<f32>;
    #[inline]
    fn div(self, rhs: &AReal<f32>) -> AReal<f32> {
        let inv = 1.0 / rhs.value;
        record_unary(self * inv, rhs.slot, -self * inv * inv)
    }
}

// Negation
impl<T: TapeStorage> Neg for AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn neg(self) -> AReal<T> {
        record_unary(-self.value, self.slot, -T::one())
    }
}

impl<T: TapeStorage> Neg for &AReal<T> {
    type Output = AReal<T>;
    #[inline]
    fn neg(self) -> AReal<T> {
        record_unary(-self.value, self.slot, -T::one())
    }
}

// Compound assignment operators
impl<T: TapeStorage> AddAssign for AReal<T> {
    fn add_assign(&mut self, rhs: AReal<T>) {
        *self = self.clone() + rhs;
    }
}

impl<T: TapeStorage> AddAssign<&AReal<T>> for AReal<T> {
    fn add_assign(&mut self, rhs: &AReal<T>) {
        *self = self.clone() + rhs;
    }
}

impl<T: TapeStorage> AddAssign<T> for AReal<T> {
    fn add_assign(&mut self, rhs: T) {
        *self = self.clone() + rhs;
    }
}

impl<T: TapeStorage> SubAssign for AReal<T> {
    fn sub_assign(&mut self, rhs: AReal<T>) {
        *self = self.clone() - rhs;
    }
}

impl<T: TapeStorage> SubAssign<&AReal<T>> for AReal<T> {
    fn sub_assign(&mut self, rhs: &AReal<T>) {
        *self = self.clone() - rhs;
    }
}

impl<T: TapeStorage> SubAssign<T> for AReal<T> {
    fn sub_assign(&mut self, rhs: T) {
        *self = self.clone() - rhs;
    }
}

impl<T: TapeStorage> MulAssign for AReal<T> {
    fn mul_assign(&mut self, rhs: AReal<T>) {
        *self = self.clone() * rhs;
    }
}

impl<T: TapeStorage> MulAssign<&AReal<T>> for AReal<T> {
    fn mul_assign(&mut self, rhs: &AReal<T>) {
        *self = self.clone() * rhs;
    }
}

impl<T: TapeStorage> MulAssign<T> for AReal<T> {
    fn mul_assign(&mut self, rhs: T) {
        *self = self.clone() * rhs;
    }
}

impl<T: TapeStorage> DivAssign for AReal<T> {
    fn div_assign(&mut self, rhs: AReal<T>) {
        *self = self.clone() / rhs;
    }
}

impl<T: TapeStorage> DivAssign<&AReal<T>> for AReal<T> {
    fn div_assign(&mut self, rhs: &AReal<T>) {
        *self = self.clone() / rhs;
    }
}

impl<T: TapeStorage> DivAssign<T> for AReal<T> {
    fn div_assign(&mut self, rhs: T) {
        *self = self.clone() / rhs;
    }
}

// Comparison operators
impl<T: TapeStorage> PartialEq for AReal<T> {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

impl<T: TapeStorage> PartialEq<T> for AReal<T> {
    fn eq(&self, other: &T) -> bool {
        self.value == *other
    }
}

impl<T: TapeStorage> PartialOrd for AReal<T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.value.partial_cmp(&other.value)
    }
}

impl<T: TapeStorage> PartialOrd<T> for AReal<T> {
    fn partial_cmp(&self, other: &T) -> Option<std::cmp::Ordering> {
        self.value.partial_cmp(other)
    }
}

// Display / Debug
impl<T: TapeStorage> fmt::Display for AReal<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.value)
    }
}

impl<T: TapeStorage> fmt::Debug for AReal<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "AReal({}, slot={})", self.value, self.slot)
    }
}

impl<T: TapeStorage> Default for AReal<T> {
    fn default() -> Self {
        AReal::new(T::zero())
    }
}