Skip to content

Commit 9dbd51b

Browse files
committed
Implement Tape.
1 parent d76eebf commit 9dbd51b

6 files changed

Lines changed: 472 additions & 16 deletions

File tree

208 KB
Loading
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
using Tensorflow.Eager;
5+
using static Tensorflow.tensorflow;
6+
7+
namespace Tensorflow.Gradients
8+
{
9+
public partial class Tape
10+
{
11+
public Tensor[] CallBackwardFunction(BackwardFunction backward_function,
12+
List<long> unneeded_gradients,
13+
List<Tensor> output_gradients)
14+
{
15+
var grads = new Tensor[output_gradients.Count];
16+
var result = backward_function(output_gradients.ToArray(),
17+
unneeded_gradients.ToArray());
18+
19+
return result;
20+
}
21+
}
22+
}
Lines changed: 249 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,249 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using Tensorflow.Util;
6+
using static Tensorflow.tensorflow;
7+
8+
namespace Tensorflow.Gradients
9+
{
10+
public partial class Tape
11+
{
12+
int kMinAggregateCount = 4;
13+
int kMinAggregateBytes = 128 * 1024 * 1024;
14+
15+
public Tensor[] ComputeGradient(long[] target_tensor_ids,
16+
long[] source_tensor_ids,
17+
UnorderedMap<long, TapeTensor> sources_that_are_targets,
18+
Tensor[] output_gradients)
19+
{
20+
var result = new List<Tensor>(source_tensor_ids.Length);
21+
var sources_set = new UnorderedSet<long>(source_tensor_ids);
22+
var gradients_size = new UnorderedMap<long, long>();
23+
24+
var state = PrepareBackprop(
25+
target_tensor_ids, tensor_tape_, op_tape_, sources_set, persistent_);
26+
var op_stack = InitialStack(state.op_tape, state.op_missing_tensor);
27+
var gradients = InitialGradients(target_tensor_ids, sources_that_are_targets,
28+
output_gradients,
29+
tensor_tape_,
30+
state.op_tape);
31+
32+
while (op_stack.Count > 0)
33+
{
34+
var op = op_stack.Dequeue();
35+
if (!state.op_tape.find(op, out var trace))
36+
continue;
37+
38+
state.op_tape.erase(op);
39+
40+
var out_gradients = new List<Tensor>(trace.output_tensor_info.Length);
41+
var unneeded_gradients = new List<long>();
42+
for (int i = 0; i < trace.input_tensor_id.Length; i++)
43+
{
44+
var in_tensor_id = trace.input_tensor_id[i];
45+
if (!tensor_tape_.find(in_tensor_id) &&
46+
!sources_set.find(in_tensor_id))
47+
unneeded_gradients.Add(i);
48+
}
49+
50+
bool any_gradient_nonzero = false;
51+
var zero_indices = new List<int>();
52+
for (int i = 0; i < trace.output_tensor_info.Length; ++i)
53+
{
54+
var id = trace.output_tensor_info[i].GetID();
55+
if (!gradients.find(id, out var grad_it))
56+
{
57+
throw new NotImplementedException("FunctionsAcceptingNoneForIndicesMap");
58+
}
59+
else
60+
{
61+
any_gradient_nonzero = true;
62+
var new_gradients = grad_it.Count == 1 ?
63+
grad_it[0] :
64+
gen_math_ops.add_n(grad_it.ToArray()); // vspace.AggregateGradients
65+
66+
if (!sources_set.find(id))
67+
gradients.Remove(id);
68+
else
69+
{
70+
grad_it.Clear();
71+
grad_it.Add(new_gradients);
72+
// vspace.MarkAsResult(new_gradients);
73+
}
74+
out_gradients.Add(new_gradients);
75+
}
76+
}
77+
78+
Tensor[] in_gradients;
79+
if (any_gradient_nonzero)
80+
{
81+
foreach (var i in zero_indices)
82+
out_gradients[i] = trace.output_tensor_info[i].ZerosLike();
83+
84+
in_gradients = CallBackwardFunction(trace.backward_function,
85+
unneeded_gradients,
86+
out_gradients);
87+
88+
if (in_gradients.Count() != trace.input_tensor_id.Count())
89+
throw new RuntimeError($"Recorded operation '{trace.op_type}' returned too few gradients. Expected {trace.input_tensor_id.Length} but received {in_gradients.Count()}");
90+
if (!persistent_)
91+
{
92+
// trace.backward_function_deleter(trace.backward_function);
93+
}
94+
}
95+
else
96+
{
97+
throw new NotImplementedException("");
98+
}
99+
100+
for (int i = 0; i < in_gradients.Length; ++i)
101+
{
102+
var id = trace.input_tensor_id[i];
103+
if (in_gradients[i] != null)
104+
{
105+
var unaggregated_grads = gradients[id];
106+
unaggregated_grads.Add(in_gradients[i]);
107+
if(unaggregated_grads.Count > kMinAggregateCount)
108+
{
109+
if(!gradients_size.ContainsKey(id))
110+
{
111+
}
112+
else
113+
{
114+
115+
}
116+
117+
throw new NotImplementedException("");
118+
}
119+
}
120+
121+
if (!state.tensor_usage_counts.find(id))
122+
continue;
123+
124+
state.tensor_usage_counts[id]--;
125+
if (state.tensor_usage_counts[id] > 0)
126+
continue;
127+
128+
if (!tensor_tape_.find(id, out var tape_it))
129+
{
130+
if (gradients.find(id, out var grad_it))
131+
{
132+
// foreach (var g in grad_it)
133+
// DeleteGradient(g);
134+
gradients.erase(id);
135+
}
136+
continue;
137+
}
138+
139+
var op_id = tape_it;
140+
if (op_id == -1)
141+
continue;
142+
143+
if(state.op_missing_tensor.find(op_id, out var missing_it))
144+
{
145+
state.op_missing_tensor[op_id]--;
146+
if (state.op_missing_tensor[op_id] == 0)
147+
op_stack.Enqueue(op_id);
148+
}
149+
}
150+
}
151+
152+
if (state.op_tape.Count > 0)
153+
throw new RuntimeError("Invalid tape state.");
154+
155+
var used_gradient_ids = new List<long>(source_tensor_ids.Length);
156+
foreach (var id in source_tensor_ids)
157+
{
158+
if (!gradients.find(id, out var grad_it))
159+
result.Add(null);
160+
else
161+
{
162+
if(grad_it.Count > 1)
163+
{
164+
var grad = gen_math_ops.add_n(grad_it.ToArray());
165+
grad_it.Clear();
166+
grad_it.Add(grad);
167+
}
168+
result.Add(grad_it[0]);
169+
used_gradient_ids.Add(id);
170+
}
171+
}
172+
173+
/*foreach(var grad_pair in gradients)
174+
{
175+
if(!used_gradient_ids.Contains(grad_pair.Key))
176+
{
177+
foreach(var g in grad_pair.Value)
178+
{
179+
vspace.DeleteGradient(g);
180+
}
181+
}
182+
}*/
183+
184+
return result.ToArray();
185+
}
186+
187+
UnorderedMapEnumerable<long, List<Tensor>> InitialGradients(long[] target_tensor_ids,
188+
UnorderedMap<long, TapeTensor> sources_that_are_targets,
189+
Tensor[] output_gradients,
190+
TensorTape tensor_tape,
191+
OpTape<BackwardFunction, TapeTensor> op_tape)
192+
{
193+
var result = new UnorderedMapEnumerable<long, List<Tensor>>();
194+
for (int i = 0; i < target_tensor_ids.Length; ++i)
195+
{
196+
var id = target_tensor_ids[i];
197+
if (output_gradients.Length == 0 || output_gradients[i] == null)
198+
{
199+
if (tensor_tape.find(id, out var tensor_id) && tensor_id != -1)
200+
{
201+
if (!op_tape.find(tensor_tape[id], out var op_it))
202+
throw new RuntimeError("Internal state of the gradient tape is invalid: " +
203+
"failed to find operation producing a tensor");
204+
bool found = false;
205+
for (int j = 0; j < op_it.output_tensor_info.Length; ++j)
206+
{
207+
if (op_it.output_tensor_info[j].GetID() == id)
208+
{
209+
found = true;
210+
var ones = op_it.output_tensor_info[j].OnesLike();
211+
result[id].Add(ones);
212+
break;
213+
}
214+
}
215+
216+
if (!found)
217+
{
218+
throw new ValueError("Internal state of the gradient tape is invalid: " +
219+
"none of operations outputs match expected tensor");
220+
}
221+
}
222+
else
223+
{
224+
if (sources_that_are_targets.find(id, out var source_tensor))
225+
result[id].Add(source_tensor.OnesLike());
226+
}
227+
}
228+
else
229+
{
230+
result[id].Add(output_gradients[i]);
231+
}
232+
}
233+
234+
return result;
235+
}
236+
237+
Queue<long> InitialStack(OpTape<BackwardFunction, TapeTensor> op_tape,
238+
UnorderedMap<long, long> op_missing_tensor)
239+
{
240+
var result = new Queue<long>();
241+
foreach(var op_entry in op_tape)
242+
{
243+
if (!op_missing_tensor.find(op_entry.Key))
244+
result.Enqueue(op_entry.Key);
245+
}
246+
return result;
247+
}
248+
}
249+
}
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using Tensorflow.Util;
6+
using static Tensorflow.tensorflow;
7+
8+
namespace Tensorflow.Gradients
9+
{
10+
public partial class Tape
11+
{
12+
public BackpropInitialState PrepareBackprop(long[] target,
13+
TensorTape tensor_tape,
14+
OpTape<BackwardFunction, TapeTensor> op_tape,
15+
UnorderedSet<long> sources_set,
16+
bool persistent_tape)
17+
{
18+
BackpropInitialState result = new BackpropInitialState();
19+
var tensor_stack = new Queue<long>(target);
20+
while (tensor_stack.Count > 0)
21+
{
22+
var tensor_id = tensor_stack.Dequeue();
23+
24+
if (!tensor_tape.find(tensor_id, out var op_id))
25+
continue;
26+
27+
if (op_id == -1 ||
28+
!op_tape.find(op_id, out var op_it) ||
29+
result.op_tape.find(op_id, out var result_op_it))
30+
continue;
31+
32+
result.op_tape.emplace(op_id, op_it);
33+
34+
foreach (var it in op_it.input_tensor_id)
35+
{
36+
if(result.tensor_usage_counts.find(it))
37+
result.tensor_usage_counts[it]++;
38+
else
39+
{
40+
result.tensor_usage_counts[it] = 1;
41+
if (tensor_tape.find(it))
42+
tensor_stack.Enqueue(it);
43+
}
44+
}
45+
46+
if (!persistent_tape)
47+
op_tape.Remove(op_id);
48+
}
49+
50+
foreach (var pair in result.tensor_usage_counts)
51+
{
52+
if (tensor_tape.find(pair.Key, out var it) && it != -1)
53+
result.op_missing_tensor[it] += 1;
54+
}
55+
56+
if (!persistent_tape)
57+
{
58+
// Call destructors for all unneeded gradient functions and
59+
// clear the op_tape. We can clear the tape because ownership of
60+
// backward functions that will be used for gradient computation
61+
// has been transferred to `result`.
62+
/*for (const auto&op_pair : *op_tape) {
63+
op_pair.second.backward_function_deleter(
64+
op_pair.second.backward_function);
65+
}*/
66+
op_tape.Clear();
67+
}
68+
69+
return result;
70+
}
71+
}
72+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
using Tensorflow.Util;
5+
using static Tensorflow.tensorflow;
6+
7+
namespace Tensorflow.Gradients
8+
{
9+
public partial class Tape
10+
{
11+
long next_op_id_ = 0;
12+
UnorderedMap<long, long> tensor_usage_;
13+
14+
public void RecordOperation(string op_type,
15+
Tensor[] input_tensors,
16+
TapeTensor[] output_tensors,
17+
long[] input_tensor_id,
18+
TF_DataType[] input_dtypes,
19+
Func<BackwardFunction> backward_function_getter)
20+
{
21+
if (!ShouldRecord(input_tensor_id, input_dtypes))
22+
{
23+
return;
24+
}
25+
26+
long op_id = next_op_id_++;
27+
var ids = new List<long>(input_tensor_id.Length);
28+
foreach (var i in input_tensor_id)
29+
{
30+
tensor_usage_[i]++;
31+
ids.Add(i);
32+
}
33+
34+
var tensors = new List<TapeTensor>(output_tensors.Length);
35+
foreach (var o in output_tensors)
36+
{
37+
tensor_tape_[o.GetID()] = op_id;
38+
tensor_usage_[o.GetID()] = 1;
39+
tensors.Add(o);
40+
}
41+
42+
op_tape_[op_id] = new OpTapeEntry<BackwardFunction, TapeTensor>
43+
{
44+
op_type = op_type,
45+
output_tensor_info = tensors.ToArray(),
46+
input_tensor_id = ids.ToArray(),
47+
backward_function = backward_function_getter()
48+
};
49+
}
50+
}
51+
}

0 commit comments

Comments
 (0)