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
// Copyright (c) Facebook, Inc. and its affiliates
// SPDX-License-Identifier: MIT OR Apache-2.0

use crate::{core::CoreAlgebra, error::Result, graph::Value};
use std::collections::BTreeMap;

#[cfg(doc)]
use crate::prelude::*;

/// Index of a computation node tracked in a graph.
/// Note: Offset is non-zero to optimize `std::mem::size_of<Option<Id>>()`
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Id {
    arena_id: u32,
    index: std::num::NonZeroU32,
}

/// A node Id associated with an underlying gradient type `T`.
/// Such an association must assign a unique type to inner Id.
pub struct GradientId<T> {
    pub(crate) inner: Id,
    marker: std::marker::PhantomData<T>,
}

/// Trait for reading gradient values of type `T` given a handle of type `Id`.
/// Value may be converted if needed.
pub trait GradientReader<Id, T> {
    fn read(&self, id: Id) -> Option<&T>;
}

/// Trait for accessing gradient values of type `T` given a handle of type `Id`.
pub trait GradientStore<Id, T>: GradientReader<Id, T> {
    fn insert(&mut self, id: Id, gradient: T);

    fn get(&self, id: Id) -> Option<&T> {
        self.read(id)
    }

    fn get_mut(&mut self, id: Id) -> Option<&mut T>;

    /// Update a gradient during backward propagation. This is used to define operators
    /// together with [`Graph::make_node`].
    /// The parameter `graph` is used for higher-order differentials (see [`GraphN`]).
    fn add_gradient<A, G>(&mut self, graph: &mut G, id: Id, value: &T) -> Result<()>
    where
        G: CoreAlgebra<A, Value = T> + ?Sized,
        Id: Copy,
        T: Clone + 'static,
    {
        match self.get_mut(id) {
            None => self.insert(id, value.clone()),
            Some(current) => *current = graph.add(current, value)?,
        }
        Ok(())
    }
}

/// Gradient store used by [`Graph1`].
/// Indices of type `GradientId<T>` are mapped to values of type `T`.
#[derive(Debug)]
pub struct GenericGradientMap1 {
    values: BTreeMap<Id, Box<dyn std::any::Any>>,
}

impl Default for GenericGradientMap1 {
    fn default() -> Self {
        Self {
            values: BTreeMap::new(),
        }
    }
}

impl<T: 'static> GradientReader<GradientId<T>, T> for GenericGradientMap1 {
    fn read(&self, id: GradientId<T>) -> Option<&T> {
        self.values.get(&id.inner).map(|val| {
            val.downcast_ref::<T>()
                .expect("indices should have a unique type")
        })
    }
}

impl<T: 'static> GradientStore<GradientId<T>, T> for GenericGradientMap1 {
    fn insert(&mut self, id: GradientId<T>, gradient: T) {
        self.values.insert(id.inner, Box::new(gradient));
    }

    fn get_mut(&mut self, id: GradientId<T>) -> Option<&mut T> {
        self.values.get_mut(&id.inner).map(|val| {
            val.downcast_mut::<T>()
                .expect("indices should have a unique type")
        })
    }
}

/// Gradient store used by [`GraphN`].
/// Indices of type `GradientId<T>` are mapped to values of type `Value<T>`.
#[derive(Debug)]
pub struct GenericGradientMapN {
    values: BTreeMap<Id, Box<dyn std::any::Any>>,
}

impl Default for GenericGradientMapN {
    fn default() -> Self {
        Self {
            values: BTreeMap::new(),
        }
    }
}

impl<T: 'static> GradientReader<GradientId<T>, Value<T>> for GenericGradientMapN {
    fn read(&self, id: GradientId<T>) -> Option<&Value<T>> {
        self.values.get(&id.inner).map(|val| {
            val.downcast_ref::<Value<T>>()
                .expect("indices should have a unique type")
        })
    }
}

impl<T: 'static> GradientReader<GradientId<T>, T> for GenericGradientMapN {
    fn read(&self, id: GradientId<T>) -> Option<&T> {
        self.values.get(&id.inner).map(|val| {
            val.downcast_ref::<Value<T>>()
                .expect("indices should have a unique type")
                .data()
        })
    }
}

impl<T: 'static> GradientStore<GradientId<T>, Value<T>> for GenericGradientMapN {
    fn insert(&mut self, id: GradientId<T>, gradient: Value<T>) {
        self.values.insert(id.inner, Box::new(gradient));
    }

    fn get_mut(&mut self, id: GradientId<T>) -> Option<&mut Value<T>> {
        self.values.get_mut(&id.inner).map(|val| {
            val.downcast_mut::<Value<T>>()
                .expect("indices should have a unique type")
        })
    }
}

/// A gradient store that contains no value. This is used as a placeholder
/// when instantiating networks [`Net`] on algebras without backward propagation
/// such as [`Eval`] and [`Check`].
#[derive(Debug, Default)]
pub struct EmptyGradientMap;

impl<T> GradientReader<(), T> for EmptyGradientMap {
    fn read(&self, _id: ()) -> Option<&T> {
        None
    }
}

/// Configuration for id_arena.
#[derive(Clone, Debug, Copy, PartialEq, Eq)]
pub(crate) struct GraphArenaBehavior;

impl id_arena::ArenaBehavior for GraphArenaBehavior {
    type Id = Id;

    #[inline]
    fn new_id(arena_id: u32, idx: usize) -> Self::Id {
        Self::Id {
            arena_id,
            index: std::num::NonZeroU32::new((idx + 1) as u32).expect("Too many nodes"),
        }
    }

    #[inline]
    fn index(id: Self::Id) -> usize {
        u32::from(id.index) as usize - 1
    }

    #[inline]
    fn arena_id(id: Self::Id) -> u32 {
        id.arena_id
    }
}

impl<T> GradientId<T> {
    /// Associate a gradient type with an index.
    pub(crate) fn new(id: Id) -> Self {
        Self {
            inner: id,
            marker: std::marker::PhantomData,
        }
    }
}

impl<T> Clone for GradientId<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner,
            marker: std::marker::PhantomData,
        }
    }
}

impl<T> Copy for GradientId<T> {}

impl<T> PartialEq for GradientId<T> {
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

impl<T> Eq for GradientId<T> {}

impl Id {
    pub(crate) fn next_id(&self) -> Self {
        Self {
            arena_id: self.arena_id,
            index: std::num::NonZeroU32::new((self.index.get() + 1) as u32)
                .expect("Too many nodes"),
        }
    }
}

impl<T> std::hash::Hash for GradientId<T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.inner.hash(state);
    }
}

impl<T> std::fmt::Debug for GradientId<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(f, "{:?}", self.inner)
    }
}

impl std::fmt::Debug for Id {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        if f.alternate() {
            write!(f, "{} @ {}", self.index, self.arena_id)
        } else {
            write!(f, "{}", self.index)
        }
    }
}