forked from SciSharp/TensorFlow.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEagerDefinedFunction.cs
More file actions
232 lines (217 loc) · 7.75 KB
/
Copy pathEagerDefinedFunction.cs
File metadata and controls
232 lines (217 loc) · 7.75 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
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Tensorflow.Contexts;
using Tensorflow.Eager;
using Tensorflow.Graphs;
using Tensorflow.Operations;
using Tensorflow.Util;
using Tensorflow.Common.Extensions;
using static Tensorflow.Binding;
using Tensorflow.Framework;
using System.Buffers;
using Tensorflow.Gradients;
namespace Tensorflow.Functions
{
public class EagerDefinedFunction: IDisposable
{
public int _num_outputs;
FuncGraph _graph;
FunctionDef _definition;
OpDef _signature;
string _name;
internal ScopedTFFunction _c_func;
internal Tensor[] _func_graph_outputs;
internal string _grad_func_name;
internal Func<Operation, Tensor[], Tensor[]> csharp_grad_func;
internal EagerDefinedFunction _grad_func;
internal bool _registered_on_context = false;
public string Name => _name;
public DataType[] OutputTypes { get; protected set; }
public Shape[] OutputShapes { get; protected set; }
public FunctionDef Definition
{
get
{
if(_definition is null)
{
_definition = _get_definition();
}
return _definition;
}
}
public OpDef Signature
{
get
{
if( _signature is null)
{
_signature = Definition.Signature;
}
return _signature;
}
}
public unsafe EagerDefinedFunction(string name, FuncGraph graph,
Tensors inputs, Tensors outputs,
Dictionary<string, AttrValue> attrs)
{
var input_ops = inputs.Select(x => x.op).ToArray();
var operations = graph.get_operations().Where(x => !input_ops.Contains(x.op))
.Select(x => x as Operation).ToArray();
var graph_output_names = graph._output_names;
string[] output_names;
if(graph_output_names is not null && outputs.All(t => graph_output_names.ContainsKey(ops.tensor_id(t))))
{
output_names = outputs.Select(t => graph_output_names[ops.tensor_id(t)]).ToArray();
if(output_names.Distinct().Count() != output_names.Length)
{
output_names = new string[0];
}
}
else
{
output_names = new string[0];
}
Status status = new Status();
var fn = c_api.TF_GraphToFunction(graph.c_graph,
name,
false,
operations.Length,
operations.Length == 0 ? new IntPtr[0] : operations.Select(x => (IntPtr)x).ToArray(),
inputs.Length,
inputs.Select(t => t._as_tf_output()).ToArray(),
outputs.Length,
outputs.Select(t => t._as_tf_output()).ToArray(),
output_names.Length != outputs.Length ? null : output_names,
IntPtr.Zero, // warning: the control output hasbben totally ignored.
null,
status);
status.Check(true);
_c_func = new ScopedTFFunction(fn, name);
foreach(var (attr_name, attr_value) in attrs)
{
var serialized = attr_value.ToByteArray();
c_api.TF_FunctionSetAttrValueProto(fn, attr_name, serialized, serialized.Length, status);
status.Check(true);
}
var signature = _get_definition().Signature;
_name = signature.Name;
tf_with(ops.init_scope(), s =>
{
tf.Context.add_function(fn);
_registered_on_context = true;
});
_num_outputs = signature.OutputArg.Count;
OutputTypes = signature.OutputArg.Select(x => x.Type).ToArray();
OutputShapes = outputs.Select(x => x.shape).ToArray();
_func_graph_outputs = new List<Tensor>(outputs).ToArray();
csharp_grad_func = null;
_graph = graph;
}
public unsafe Tensors Call(Tensors args)
{
// TODO(Rinne): Add arg `CancellationManager`.
// TODO(Rinne): Check the arg length.
var function_call_options = tf.Context.FunctionCallOptions;
string config = ""; // TODO(Rinne): revise it. The following code should work but not, for unclear reasons.
//if (function_call_options.config_proto_serialized().Length == 0)
//{
// config = function_utils.get_disabled_rewriter_config().ToStringUtf8();
//}
//else
//{
// config = function_call_options.config_proto_serialized().ToStringUtf8();
//}
string executor_type = function_call_options.ExecutorType ?? "";
var executing_eagerly = tf.Context.executing_eagerly();
var attrs = new object[]
{
"executor_type", executor_type,
"config_proto", config
};
Tensor[] outputs;
if (executing_eagerly)
{
outputs = _execute.execute(
Signature.Name,
_num_outputs,
args,
attrs,
tf.Context);
}
else
{
if(tf.GetTapeSet().Count == 0)
{
outputs = functional_ops.partitioned_call(args, this, OutputTypes,
executing_eagerly, config, "");
}
else
{
var tape = tf.GetTapeSet().Peek();
tape.StopRecord();
outputs = functional_ops.partitioned_call(args, this, OutputTypes,
executing_eagerly, config, "");
tape.StartRecord();
}
}
foreach(var (i, func_graph_output) in enumerate(_func_graph_outputs))
{
handle_data_util.copy_handle_data(func_graph_output, outputs[i]);
}
if (executing_eagerly)
{
return outputs;
}
else
{
foreach(var (i, shape) in enumerate(OutputShapes))
{
outputs[i].shape = shape;
}
return outputs;
}
}
public void AddToGraph(Graph g = null)
{
if(g is null && tf.Context.executing_eagerly())
{
var ctx = tf.Context;
if (!ctx.has_function(this.Name))
{
ctx.add_function_def(Definition);
}
}
else
{
if (!g.IsFunction(Name))
{
g.AddFunction(this);
}
foreach(var f in _graph.Functions.Values)
{
if (!g.IsFunction(f.Name))
{
g.AddFunction(f);
}
}
}
}
private FunctionDef _get_definition()
{
var buffer = c_api_util.tf_buffer();
Status status = new();
c_api.TF_FunctionToFunctionDef(_c_func.Get(), buffer, status);
status.Check(true);
var proto_data = c_api.TF_GetBuffer(buffer);
return FunctionDef.Parser.ParseFrom(proto_data.AsSpan<byte>());
}
public void Dispose()
{
tf.Context.remove_function(Name);
}
}
}