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
use std::collections::HashMap;
use crate::autograd::Variable;
use crate::nn::{Module, NamedInputModule};
use crate::tensor::Result;
/// Additive state cell for forward references (Using before Tag).
///
/// On the first forward call, the graph auto-zeros the state, so
/// stream + zeros = stream (pass-through). On subsequent calls,
/// the accumulated state is added to the current stream.
///
/// ```ignore
/// FlowBuilder::from(embed)
/// .through(StateAdd)
/// .using(&["memory"])
/// .tag("memory")
/// .build()
/// ```
pub struct StateAdd;
impl Module for StateAdd {
fn name(&self) -> &str { "state_add" }
fn forward(&self, input: &Variable) -> Result<Variable> {
Ok(input.clone())
}
fn as_named_input(&self) -> Option<&dyn crate::nn::NamedInputModule> {
Some(self)
}
}
impl NamedInputModule for StateAdd {
fn forward_named(
&self,
input: &Variable,
refs: &HashMap<String, Variable>,
) -> Result<Variable> {
let mut result = input.clone();
for v in refs.values() {
result = result.add(v)?;
}
Ok(result)
}
}