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
use std::{
    collections::{hash_map::RandomState, BTreeMap, HashMap, HashSet},
    fmt::Debug,
    ops::Deref,
};

use crate::{Shape, Tensor};

pub trait TensorIter: Debug {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor>;
}

impl TensorIter for Tensor {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        std::iter::once(self)
    }
}

impl TensorIter for &Tensor {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        std::iter::once(*self)
    }
}

impl<const N: usize> TensorIter for [Tensor; N] {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.iter()
    }
}

impl<const N: usize> TensorIter for [&Tensor; N] {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.iter().map(Deref::deref)
    }
}

impl<const N: usize> TensorIter for &[Tensor; N] {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.iter()
    }
}

impl<const N: usize> TensorIter for &[&Tensor; N] {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.iter().map(Deref::deref)
    }
}

impl TensorIter for Vec<Tensor> {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.iter()
    }
}

impl TensorIter for &Vec<Tensor> {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.iter()
    }
}

impl TensorIter for &[Tensor] {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.iter()
    }
}

impl TensorIter for &[&Tensor] {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.iter().map(Deref::deref)
    }
}

impl TensorIter for HashMap<usize, Tensor> {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.values()
    }
}

impl TensorIter for BTreeMap<usize, Tensor> {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.values()
    }
}

impl TensorIter for &HashMap<usize, Tensor> {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.values()
    }
}

impl TensorIter for &BTreeMap<usize, Tensor> {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.values()
    }
}

impl<const N: usize, const M: usize> TensorIter for ([Tensor; N], [Tensor; M]) {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.0.iter().chain(self.1.iter())
    }
}

impl<const N: usize, const M: usize> TensorIter for (&[Tensor; N], &[Tensor; M]) {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.0.iter().chain(self.1.iter())
    }
}

impl<const N: usize, const M: usize, const R: usize> TensorIter
    for (&[Tensor; N], [&[Tensor; M]; R])
{
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.0.iter().chain(self.1.iter().flat_map(|v| v.iter()))
    }
}

impl<const N: usize, const M: usize> TensorIter for (&[Tensor; N], &[&[Tensor; M]]) {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.0.iter().chain(self.1.iter().flat_map(|v| v.iter()))
    }
}

impl<const N: usize, const R: usize> TensorIter for [&[Tensor; N]; R] {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.iter().flat_map(|v| v.iter())
    }
}

impl<const N: usize> TensorIter for &[&[Tensor; N]] {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        self.iter().flat_map(|v| v.iter())
    }
}

impl TensorIter for (Tensor, Vec<Tensor>) {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        std::iter::once(&self.0).chain(self.1.iter())
    }
}

impl<const N: usize> TensorIter for (Tensor, [Tensor; N]) {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        std::iter::once(&self.0).chain(self.1.iter())
    }
}

impl TensorIter for (Tensor, BTreeMap<usize, Tensor>) {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        std::iter::once(&self.0).chain(self.1.values())
    }
}

impl TensorIter for (Tensor, HashMap<usize, Tensor>) {
    fn tensor_iter(&self) -> impl Iterator<Item = &Tensor> {
        std::iter::once(&self.0).chain(self.1.values())
    }
}

pub fn dot_graph<T: TensorIter>(args: T) -> String {
    let mut tape = Vec::new();
    for output in args.tensor_iter() {
        depth_first_traversal(&mut tape, output);
    }

    let nodes: HashSet<String, RandomState> = HashSet::from_iter(tape.iter().map(|tensor| {
        format!(
            "{} [label=\"{}: {}|{{dtype:|shape:|inputs:}}|{{{{{:?}}}|{{{:?}}}|{{{:?}}}}}\"];",
            tensor.id(),
            tensor.id(),
            tensor.primitive().dot_label(),
            tensor.dtype(),
            tensor.shape(),
            tensor.inputs().iter().map(|t| t.id()).collect::<Vec<_>>(),
        )
    }));

    let mut dot = String::new();
    dot.push_str("digraph {\n");
    dot.push_str("  node [shape=record];\n");

    for node in nodes {
        dot.push_str(&format!("  {}\n", node));
    }

    for tensor in tape.iter() {
        for input in tensor.inputs().iter() {
            dot.push_str(&format!("  {:?} -> {:?};\n", input.id(), tensor.id(),));
        }
    }

    dot.push('}');
    dot
}

fn depth_first_traversal(tape: &mut Vec<Tensor>, tensor: &Tensor) {
    for input in tensor.inputs().iter() {
        depth_first_traversal(tape, input);
    }
    if tape.contains(tensor) {
        return;
    }
    tape.push(tensor.clone());
}