forked from SciSharp/TensorFlow.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTensor.cs
More file actions
487 lines (429 loc) · 19.5 KB
/
Tensor.cs
File metadata and controls
487 lines (429 loc) · 19.5 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/*****************************************************************************
Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
using NumSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using NumSharp.Backends;
using NumSharp.Backends.Unmanaged;
using NumSharp.Utilities;
using Tensorflow.Framework;
namespace Tensorflow
{
/// <summary>
/// A tensor is a generalization of vectors and matrices to potentially higher dimensions.
/// Internally, TensorFlow represents tensors as n-dimensional arrays of base datatypes.
/// </summary>
[SuppressMessage("ReSharper", "ConvertToAutoProperty")]
public partial class Tensor : DisposableObject, ITensorOrOperation, _TensorLike
{
private readonly int _id;
private readonly Operation _op;
private readonly int _value_index;
private TF_Output? _tf_output;
private readonly TF_DataType _override_dtype;
public int Id => _id;
/// <summary>
/// The Graph that contains this tensor.
/// </summary>
public Graph graph => op?.graph;
/// <summary>
/// The Operation that produces this tensor as an output.
/// </summary>
public Operation op => _op;
public Tensor[] outputs => op.outputs;
/// <summary>
/// The string name of this tensor.
/// </summary>
public string name => $"{(op == null ? "<unnamed Operation>" : $"{op.name}:{_value_index}")}";
/// <summary>
/// The index of this tensor in the outputs of its Operation.
/// </summary>
public int value_index => _value_index;
/// <summary>
/// The DType of elements in this tensor.
/// </summary>
public TF_DataType dtype => _handle == IntPtr.Zero ? _override_dtype : c_api.TF_TensorType(_handle);
public ulong bytesize => _handle == IntPtr.Zero ? 0 : c_api.TF_TensorByteSize(_handle);
public ulong itemsize => _handle == IntPtr.Zero ? 0 : c_api.TF_DataTypeSize(dtype);
public ulong size => _handle == IntPtr.Zero ? 0 : bytesize / itemsize;
public IntPtr buffer => _handle == IntPtr.Zero ? IntPtr.Zero : c_api.TF_TensorData(_handle);
public int num_consumers(TF_Output oper_out) => _handle == IntPtr.Zero ? 0 : c_api.TF_OperationOutputNumConsumers(oper_out);
public int NDims => rank;
/// <summary>
/// The name of the device on which this tensor will be produced, or null.
/// </summary>
public string Device => op.Device;
public int[] dims => shape;
/// <summary>
/// Used for keep other pointer when do implicit operating
/// </summary>
public object Tag { get; set; }
/// <summary>
/// Returns the shape of a tensor.
/// </summary>
/// <remarks>https://www.tensorflow.org/api_docs/python/tf/shape</remarks>
public int[] shape
{
get
{
var dims = new long[rank < 0 ? 0 : rank];
if (_handle == IntPtr.Zero)
{
using (var status = new Status())
{
c_api.TF_GraphGetTensorShape(op.graph, _as_tf_output(), dims, rank, status);
status.Check();
}
}
else
{
for (int i = 0; i < rank; i++)
dims[i] = c_api.TF_Dim(_handle, i);
}
return dims.Select(x => ((IConvertible) x).ToInt32(CultureInfo.InvariantCulture)).ToArray();
}
set
{
using (var status = new Status())
{
if (value == null)
c_api.TF_GraphSetTensorShape(this.graph, this._as_tf_output(), null, -1, status);
else
c_api.TF_GraphSetTensorShape(this.graph, this._as_tf_output(), value.Select(Convert.ToInt64).ToArray(), value.Length, status);
status.Check(true);
}
}
}
public int[] _shape_tuple()
{
return rank < 0 ? null : shape;
}
public TensorShape TensorShape => rank < 0 ? new TensorShape() : tensor_util.to_shape(shape);
/// <summary>
/// Updates the shape of this tensor.
/// </summary>
public void set_shape(TensorShape shape)
{
this.shape = shape.rank > 0 ? shape.dims : null;
}
/// <summary>
/// Updates the shape of this tensor.
/// </summary>
public void set_shape(Tensor shape)
{
// ReSharper disable once MergeConditionalExpression
this.shape = shape is null ? null : shape.shape;
}
/// <summary>
/// number of dimensions <br></br>
/// -1 Unknown <br></br>
/// 0 Scalar (magnitude only) <br></br>
/// 1 Vector (magnitude and direction) <br></br>
/// 2 Matrix (table of numbers) <br></br>
/// 3 3-Tensor (cube of numbers) <br></br>
/// n n-Tensor (you get the idea)
/// </summary>
/// <remarks>https://www.tensorflow.org/api_docs/python/tf/rank</remarks>
public int rank
{
get
{
if (_handle == IntPtr.Zero)
{
using (var status = new Status())
{
var output = _as_tf_output();
int ndim = c_api.TF_GraphGetTensorNumDims(op.graph, output, status);
status.Check();
return ndim;
}
}
return c_api.TF_NumDims(_handle);
}
}
/// <summary>
/// Returns a list of Operations that consume this tensor.
/// </summary>
/// <returns></returns>
public Operation[] consumers()
{
var output = _as_tf_output();
var consumer_names = c_api.TF_OperationOutputConsumers_wrapper(output);
return consumer_names.Select(x => graph.OperationByName(x)).ToArray();
}
public TF_Output _as_tf_output()
{
if (!_tf_output.HasValue)
_tf_output = new TF_Output(op, value_index);
return _tf_output.Value;
}
[Obsolete("Please use ToArray<T>() instead.", false)]
public T[] Data<T>() where T : unmanaged
{
return ToArray<T>();
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
/// <exception cref="ArgumentException">When <typeparam name="T"> is string </typeparam></exception>
public T[] ToArray<T>() where T : unmanaged
{
//Are the types matching?
if (typeof(T).as_dtype() == dtype)
{
if (NDims == 0 && size == 1) //is it a scalar?
{
unsafe
{
return new T[] {*(T*) buffer};
}
}
//types match, no need to perform cast
var ret = new T[size];
unsafe
{
var len = (long) size;
fixed (T* dst = ret)
{
//T can only be unmanaged, I believe it is safe to say that MemoryCopy is valid for all cases this method can be called.
var src = (T*) buffer;
len *= ((long) itemsize);
System.Buffer.MemoryCopy(src, dst, len, len);
}
}
return ret;
} else
{
//types do not match, need to perform cast
if (NDims == 0 && size == 1) //is it a scalar?
{
unsafe
{
#if _REGEN
#region Compute
switch (dtype.as_numpy_dtype().GetTypeCode())
{
%foreach supported_dtypes,supported_dtypes_lowercase%
case NPTypeCode.#1: return new T[] {Converts.ChangeType<T>(*(#2*) buffer)};
%
case NPTypeCode.String: return new T[] {Converts.ChangeType<T>((string)this)};
default:
throw new NotSupportedException();
}
#endregion
#else
#region Compute
switch (dtype.as_numpy_dtype().GetTypeCode())
{
case NPTypeCode.Boolean: return new T[] {Converts.ChangeType<T>(*(bool*) buffer)};
case NPTypeCode.Byte: return new T[] {Converts.ChangeType<T>(*(byte*) buffer)};
case NPTypeCode.Int16: return new T[] {Converts.ChangeType<T>(*(short*) buffer)};
case NPTypeCode.UInt16: return new T[] {Converts.ChangeType<T>(*(ushort*) buffer)};
case NPTypeCode.Int32: return new T[] {Converts.ChangeType<T>(*(int*) buffer)};
case NPTypeCode.UInt32: return new T[] {Converts.ChangeType<T>(*(uint*) buffer)};
case NPTypeCode.Int64: return new T[] {Converts.ChangeType<T>(*(long*) buffer)};
case NPTypeCode.UInt64: return new T[] {Converts.ChangeType<T>(*(ulong*) buffer)};
case NPTypeCode.Char: return new T[] {Converts.ChangeType<T>(*(char*) buffer)};
case NPTypeCode.Double: return new T[] {Converts.ChangeType<T>(*(double*) buffer)};
case NPTypeCode.Single: return new T[] {Converts.ChangeType<T>(*(float*) buffer)};
case NPTypeCode.String: return new T[] {Converts.ChangeType<T>((string)this)};
default:
throw new NotSupportedException();
}
#endregion
#endif
}
}
var ret = new T[size];
unsafe
{
var len = (long) size;
fixed (T* dstRet = ret)
{
T* dst = dstRet; //local stack copy
#if _REGEN
#region Compute
switch (dtype.as_numpy_dtype().GetTypeCode())
{
%foreach supported_dtypes,supported_dtypes_lowercase%
case NPTypeCode.#1: new UnmanagedMemoryBlock<#2>((#2*) buffer, len).CastTo(new UnmanagedMemoryBlock<T>(dst, len), null, null); break;
%
default:
throw new NotSupportedException();
}
#endregion
#else
#region Compute
switch (dtype.as_numpy_dtype().GetTypeCode())
{
case NPTypeCode.Boolean: new UnmanagedMemoryBlock<bool>((bool*) buffer, len).CastTo(new UnmanagedMemoryBlock<T>(dst, len), null, null); break;
case NPTypeCode.Byte: new UnmanagedMemoryBlock<byte>((byte*) buffer, len).CastTo(new UnmanagedMemoryBlock<T>(dst, len), null, null); break;
case NPTypeCode.Int16: new UnmanagedMemoryBlock<short>((short*) buffer, len).CastTo(new UnmanagedMemoryBlock<T>(dst, len), null, null); break;
case NPTypeCode.UInt16: new UnmanagedMemoryBlock<ushort>((ushort*) buffer, len).CastTo(new UnmanagedMemoryBlock<T>(dst, len), null, null); break;
case NPTypeCode.Int32: new UnmanagedMemoryBlock<int>((int*) buffer, len).CastTo(new UnmanagedMemoryBlock<T>(dst, len), null, null); break;
case NPTypeCode.UInt32: new UnmanagedMemoryBlock<uint>((uint*) buffer, len).CastTo(new UnmanagedMemoryBlock<T>(dst, len), null, null); break;
case NPTypeCode.Int64: new UnmanagedMemoryBlock<long>((long*) buffer, len).CastTo(new UnmanagedMemoryBlock<T>(dst, len), null, null); break;
case NPTypeCode.UInt64: new UnmanagedMemoryBlock<ulong>((ulong*) buffer, len).CastTo(new UnmanagedMemoryBlock<T>(dst, len), null, null); break;
case NPTypeCode.Char: new UnmanagedMemoryBlock<char>((char*) buffer, len).CastTo(new UnmanagedMemoryBlock<T>(dst, len), null, null); break;
case NPTypeCode.Double: new UnmanagedMemoryBlock<double>((double*) buffer, len).CastTo(new UnmanagedMemoryBlock<T>(dst, len), null, null); break;
case NPTypeCode.Single: new UnmanagedMemoryBlock<float>((float*) buffer, len).CastTo(new UnmanagedMemoryBlock<T>(dst, len), null, null); break;
case NPTypeCode.String: throw new NotSupportedException("Unable to convert from string to other dtypes"); //TODO! this should call Converts.To<T>
default:
throw new NotSupportedException();
}
#endregion
#endif
}
}
return ret;
}
}
/// <summary>
/// Copies the memory of current buffer onto newly allocated array.
/// </summary>
/// <returns></returns>
[Obsolete("Please use set_shape(TensorShape shape) instead.", false)]
public byte[] Data()
{
return BufferToArray();
}
/// <summary>
/// Copies the memory of current buffer onto newly allocated array.
/// </summary>
/// <returns></returns>
public byte[] BufferToArray()
{
unsafe
{
// ReSharper disable once LocalVariableHidesMember
var bytesize = (long) this.bytesize;
var data = new byte[bytesize];
fixed (byte* dst = data)
System.Buffer.MemoryCopy(buffer.ToPointer(), dst, bytesize, bytesize);
return data;
}
}
/// <summary>
/// Extracts string array from current Tensor.
/// </summary>
/// <exception cref="InvalidOperationException">When <see cref="dtype"/> != TF_DataType.TF_STRING</exception>
public unsafe string[] StringData()
{
if (dtype != TF_DataType.TF_STRING)
throw new InvalidOperationException($"Unable to call StringData when dtype != TF_DataType.TF_STRING (dtype is {dtype})");
//
// TF_STRING tensors are encoded with a table of 8-byte offsets followed by TF_StringEncode-encoded bytes.
// [offset1, offset2,...,offsetn, s1size, s1bytes, s2size, s2bytes,...,snsize,snbytes]
//
long size = 1;
foreach (var s in TensorShape.dims)
size *= s;
var buffer = new byte[size][];
var src = c_api.TF_TensorData(_handle);
var srcLen = (IntPtr) (src.ToInt64() + (long) bytesize);
src += (int) (size * 8);
for (int i = 0; i < buffer.Length; i++)
{
using (var status = new Status())
{
IntPtr dst = IntPtr.Zero;
UIntPtr dstLen = UIntPtr.Zero;
var read = c_api.TF_StringDecode((byte*) src, (UIntPtr) (srcLen.ToInt64() - src.ToInt64()), (byte**) &dst, &dstLen, status);
status.Check(true);
buffer[i] = new byte[(int) dstLen];
Marshal.Copy(dst, buffer[i], 0, buffer[i].Length);
src += (int) read;
}
}
var _str = new string[buffer.Length];
for (int i = 0; i < _str.Length; i++)
_str[i] = Encoding.UTF8.GetString(buffer[i]);
return _str;
}
public Tensor MaybeMove()
{
var tensor = c_api.TF_TensorMaybeMove(_handle);
return tensor;
}
/// <summary>
/// Evaluates this tensor in a `Session`.
/// </summary>
/// <param name="feed_dict">A dictionary that maps `Tensor` objects to feed values.</param>
/// <returns>A <see cref="NumSharp"/> array corresponding to the value of this tensor.</returns>
public NDArray eval(params FeedItem[] feed_dict)
{
return ops._eval_using_default_session(this, feed_dict, graph);
}
/// <summary>
/// Evaluates this tensor in a `Session`.
/// </summary>
/// <param name="feed_dict">A dictionary that maps `Tensor` objects to feed values.</param>
/// <param name="session">The `Session` to be used to evaluate this tensor.</param>
/// <returns>A <see cref="NumSharp"/> array corresponding to the value of this tensor.</returns>
public NDArray eval(Session session, params FeedItem[] feed_dict)
{
return ops._eval_using_default_session(this, feed_dict, graph, session);
}
public override string ToString()
{
// this can throw IndexOutOfRangeException
switch (rank)
{
case -1:
return $"tf.Tensor '{name}' shape=<unknown> dtype={dtype}";
case 0:
return $"tf.Tensor '{name}' shape=() dtype={dtype}";
default:
return $"tf.Tensor '{name}' shape=({string.Join(",", shape)}) dtype={dtype}";
}
}
/// <summary>
/// Dispose any managed resources.
/// </summary>
/// <remarks>Equivalent to what you would perform inside <see cref="DisposableObject.Dispose"/></remarks>
protected override void DisposeManagedResources()
{
AllocationReferenceHolder = null;
}
[SuppressMessage("ReSharper", "ConvertIfStatementToSwitchStatement")]
protected override void DisposeUnmanagedResources(IntPtr handle)
{
c_api.TF_DeleteTensor(handle);
if (AllocationHandle == null)
return;
if (AllocationType == AllocationType.GCHandle)
{
((GCHandle) AllocationHandle).Free();
AllocationHandle = null;
AllocationType = AllocationType.None;
} else if (AllocationType == AllocationType.Marshal)
{
Marshal.FreeHGlobal((IntPtr) AllocationHandle);
AllocationHandle = null;
AllocationType = AllocationType.None;
} else
throw new InvalidOperationException($"Tensor.AllocationHandle is not null ({AllocationHandle}) but AllocationType is not matched to a C# allocation type ({AllocationType}).");
}
public bool IsDisposed => _disposed;
public int tensor_int_val { get; set; }
}
}