forked from SciSharp/TensorFlow.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConcreteFunction.cs
More file actions
329 lines (288 loc) · 11.8 KB
/
Copy pathConcreteFunction.cs
File metadata and controls
329 lines (288 loc) · 11.8 KB
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Tensorflow.Eager;
using Tensorflow.Framework.Models;
using Tensorflow.Gradients;
using Tensorflow.Graphs;
using Tensorflow.Train;
using Tensorflow.Util;
using Tensorflow.Common.Extensions;
using static Tensorflow.Binding;
namespace Tensorflow.Functions
{
/// <summary>
///
/// </summary>
public class ConcreteFunction: Trackable
{
protected IEnumerable<Tensor> _captured_inputs;
protected DelayedRewriteGradientFunctions _delayed_rewrite_functions;
protected Dictionary<string, AttrValue> _attrs;
protected FunctionSpec _function_spec;
protected FunctionSpec _pre_initialized_function_spec = null;
protected EagerDefinedFunction _inference_function;
protected Dictionary<string, TapeGradientFunctions> _tape_functions_cache = new();
internal FuncGraph func_graph;
internal ForwardBackwardCall forward_backward;
public Tensor[] Inputs => func_graph.Inputs;
public Tensor[] CapturedInputs => func_graph.external_captures;
public string Name => _delayed_rewrite_functions.Forward().Name;
public Tensor[] Outputs => func_graph.Outputs;
public Type ReturnType;
public TensorSpec[] OutputStructure;
public IEnumerable<string> ArgKeywords { get; set; }
public long NumPositionArgs { get; set; }
public FunctionDef FunctionDef => _delayed_rewrite_functions.Forward().Definition;
public Tensor[] FlatStructuredOutputs => func_graph.FlatStructuredOutputs;
public IEnumerable<IVariableV1> Variables => func_graph.Variables;
public IEnumerable<IVariableV1> TrainableVariables => func_graph.TrainableVariables;
internal NameAttrList AsNameAttrList
{
get
{
NameAttrList ret = new() { Name = this.Name };
foreach (var (name, value) in _attrs)
{
ret.Attr[name] = value;
}
return ret;
}
}
public ConcreteFunction(string name)
{
func_graph = new FuncGraph(name);
_captured_inputs = func_graph.external_captures;
_attrs= new Dictionary<string, AttrValue>();
_set_infer_function();
}
public ConcreteFunction(FuncGraph graph, Dictionary<string, AttrValue> attrs = null)
{
func_graph = graph;
_captured_inputs = func_graph.external_captures;
//ToGraph(graph.Inputs, graph.Outputs.Where(x => x != null).ToArray());
_attrs = attrs;
_set_infer_function();
}
public ConcreteFunction(Func<Tensor, Tensor> func, TF_DataType dtype)
{
string func_name = $"{func.Method.Name}_{ops.uid_function()}";
func_graph = new FuncGraph(func_name);
func_graph.as_default();
var input = tf.placeholder(dtype);
var output = func(input);
var opers = func_graph._nodes_by_name.Values.Select(x => x as Operation).ToArray();
func_graph.ToGraph(opers,
new[] { input },
new[] { output },
null);
func_graph.Exit();
_captured_inputs = func_graph.external_captures;
_attrs = new Dictionary<string, AttrValue>();
_set_infer_function();
}
public ConcreteFunction(Func<Tensor, IDatasetV2> func, TF_DataType dtype)
{
string func_name = $"{func.Method.Name}_{ops.uid_function()}";
func_graph = new FuncGraph(func_name);
func_graph.as_default();
var input = tf.placeholder(dtype);
var output = func(input);
OutputStructure = output.structure;
var opers = func_graph._nodes_by_name.Values.Select(x => x as Operation).ToArray();
func_graph.ToGraph(opers,
new[] { input },
new[] { output.variant_tensor },
null);
func_graph.Exit();
_captured_inputs = func_graph.external_captures;
_attrs = new Dictionary<string, AttrValue>();
_set_infer_function();
}
/*public ConcreteFunction(Func<Tensors, Tensors> func,
TF_DataType[] dtypes, Shape[] shapes)
{
string func_name = $"{func.Method.Name}_{ops.uid_function()}";
// IntPtr func_handle;
func_graph = new FuncGraph(func_name);
func_graph.as_default();
var inputs = new Tensors();
foreach(var (i, dtype) in enumerate(dtypes))
inputs.Add(tf.placeholder(dtypes[i], shape: shapes[i], name: "args"));
Outputs = func(inputs);
OutputStructure = Outputs.Select(x => x.ToTensorSpec()).ToArray();
var opers = func_graph._nodes_by_name.Values.Select(x => x as Operation).ToArray();
func_graph.ToGraph(opers, inputs, Outputs, null);
func_graph.Exit();
}*/
public void ToGraph(Tensors inputs, Tensors outputs)
{
var opers = func_graph._nodes_by_name.Values.Select(x => x as Operation).ToArray();
func_graph.ToGraph(opers,
inputs,
outputs,
null);
OutputStructure = outputs.Select(x => x.ToTensorSpec()).ToArray();
}
public void Enter()
{
func_graph.as_default();
}
public void Exit()
{
func_graph.Exit();
}
public Tensors FilteredCall(Tensors inputs)
{
return CallFlat(inputs, CapturedInputs);
}
/// <summary>
/// Executes the wrapped function.
/// </summary>
/// <param name="args"></param>
/// <param name="captured_inputs"></param>
/// <returns></returns>
public Tensors CallFlat(Tensor[] args, Tensor[] captured_inputs)
{
var executing_eagerly = tf.Context.executing_eagerly();
var default_graph = ops.get_default_graph();
// TODO(Rinne): deal with `default_graph.building_function`
var tempvv = func_graph.Variables;
if(tf.GetTapeSet().Count > 0 || default_graph is FuncGraph)
{
foreach(var v in this.func_graph.Variables)
{
resource_variable_ops.variable_accessed(v);
}
}
var tensor_inputs = new Tensors();
foreach (var (i, arg) in enumerate(args))
{
tensor_inputs.Add(arg);
// If we're graph building, shape inference is on.
}
if (!executing_eagerly)
{
// TODO(Rinne): add the check
}
tensor_inputs.AddRange(captured_inputs);
args = tensor_inputs.ToArray();
var possible_gradient_type = gradients_util.PossibleTapeGradientTypes(args);
// No tape is watching; skip to running the function.
if (possible_gradient_type == gradients_util.POSSIBLE_GRADIENT_TYPES_NONE && executing_eagerly)
{
return _build_call_outputs(_inference_function.Call(args));
}
forward_backward = SelectForwardAndBackwardFunctions(args, possible_gradient_type, executing_eagerly);
var (forward_function, args_with_tangents) = forward_backward.Forward();
Tensors flat_outputs = null;
if (executing_eagerly)
{
flat_outputs = forward_function.Call(args_with_tangents);
}
else
{
tf_with(default_graph._override_gradient_function(new Dictionary<string, Func<Operation, object[], Tensor[]>>(){
{ "PartitionedCall", _get_gradient_function() }, { "StatefulPartitionedCall", _get_gradient_function() }
}), _ =>
{
flat_outputs = forward_function.Call(args_with_tangents);
});
}
forward_backward.Record(flat_outputs);
return _build_call_outputs(flat_outputs);
}
public void AddTograph(Graph? g = null)
{
if(!tf.Context.executing_eagerly() && g is null)
{
g = ops.get_default_graph();
}
_delayed_rewrite_functions.Forward().AddToGraph(g);
}
public void SetExternalCaptures(IEnumerable<Tensor> captures)
{
_captured_inputs = captures;
}
ForwardBackwardCall SelectForwardAndBackwardFunctions(Tensors args, int possible_gradient_type, bool executing_eagerly)
{
TangentInfo input_tangents;
if (executing_eagerly)
{
// TODO(Rinne): check if it needs to be implemented.
input_tangents = new TangentInfo();
}
else
{
input_tangents = new TangentInfo();
}
if(possible_gradient_type == gradients_util.POSSIBLE_GRADIENT_TYPES_FIRST_ORDER)
{
if(input_tangents.Indices is not null || executing_eagerly)
{
string cache_key = "first_order";
if(!_tape_functions_cache.TryGetValue(cache_key, out var functions))
{
functions = new FirstOrderTapeGradientFunctions(func_graph, false);
_tape_functions_cache[cache_key] = functions;
}
return new ForwardBackwardCall(functions, args, tape_watching: true);
}
else
{
return new ForwardBackwardCall(_delayed_rewrite_functions, args, tape_watching: true);
}
}
else if(possible_gradient_type == gradients_util.POSSIBLE_GRADIENT_TYPES_HIGHER_ORDER)
{
throw new NotImplementedException();
}
// TODO(Rinne): add arg "input_tagents" for ForwardBackwardCall.
return new ForwardBackwardCall(_delayed_rewrite_functions, args, tape_watching: false);
}
internal void set_variables(IEnumerable<IVariableV1> variables)
{
func_graph.Variables = variables;
}
internal void _set_infer_function()
{
_delayed_rewrite_functions = new DelayedRewriteGradientFunctions(func_graph, _attrs);
_inference_function = _delayed_rewrite_functions.Forward();
}
internal void _set_function_spec(FunctionSpec spec)
{
_function_spec = null;
_pre_initialized_function_spec = spec;
_initialize_function_spec();
}
internal void _initialize_function_spec()
{
if(_pre_initialized_function_spec is null)
{
return;
}
Debug.Assert(_function_spec is null, "already initialized");
var spec = _pre_initialized_function_spec;
//var args = spec.Fullargspec.DictValue.Fields["args"];
// TODO(Rinne): self.structured_input_signature
_function_spec = new FunctionSpec()
{
Fullargspec = spec.Fullargspec,
IsMethod = spec.IsMethod,
InputSignature = spec.InputSignature
};
}
internal Func<Operation, object[], Tensor[]> _get_gradient_function()
{
return _delayed_rewrite_functions._rewrite_forward_and_call_backward;
}
private Tensors _build_call_outputs(Tensors result)
{
// TODO(Rinne): deal with `func_graph.structured_outputs`
return result;
}
public override string ToString()
=> Name;
}
}