File size: 6,647 Bytes
d353048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using Unity.InferenceEngine;
using Unity.MLAgents.Inference.Utils;
using Unity.MLAgents.Policies;

namespace Unity.MLAgents.Inference
{
    /// <summary>
    /// Tensor - A class to encapsulate a Tensor used for inference.
    ///
    /// This class contains the Array that holds the data array, the shapes, type and the
    /// placeholder in the execution graph. All the fields are editable in the inspector,
    /// allowing the user to specify everything but the data in a graphical way.
    /// </summary>
    [Serializable]
    internal class TensorProxy
    {
        public enum TensorType
        {
            Integer,
            FloatingPoint
        };

        static readonly Dictionary<TensorType, Type> k_TypeMap =
            new Dictionary<TensorType, Type>()
            {
                { TensorType.FloatingPoint, typeof(float) },
                { TensorType.Integer, typeof(int) }
            };

        static readonly Dictionary<TensorType, DataType> k_DTypeMap =
            new Dictionary<TensorType, DataType>()
            {
                { TensorType.FloatingPoint, InferenceEngine.DataType.Float },
                { TensorType.Integer, InferenceEngine.DataType.Int }
            };

        public string name;
        public TensorType valueType;

        // Since Type is not serializable, we use the DisplayType for the Inspector
        public Type DataType => k_TypeMap[valueType];
        public DataType DType => k_DTypeMap[valueType];
        public int[] shape;
        [NonSerialized]
        public Tensor data;
        public BackendType Device => data.dataOnBackend.backendType;

        public long Height
        {
            get { return shape.Length >= 4 ? shape[^2] : 1; }
        }

        public long Width
        {
            get { return shape.Length >= 3 ? shape[^1] : 1; }
        }

        public long Channels
        {
            get
            {
                return shape.Length >= 4 ? shape[^3] :
                    shape.Length == 3 ? shape[^2] :
                    shape.Length == 2 ? shape[^1] : 1;
            }
        }

        ~TensorProxy()
        {
            Dispose();
        }

        void Dispose()
        {
            if (data.dataOnBackend.backendType != BackendType.CPU)
            {
                data?.Dispose();
            }
        }
    }

    internal static class TensorUtils
    {
        public static void ResizeTensor(TensorProxy tensor, int batch)
        {
            if (tensor.shape[0] == batch &&
                tensor.data != null && tensor.data.Batch() == batch)
            {
                return;
            }

            tensor.data?.Dispose();
            tensor.shape[0] = batch;
            var newTensorShape = new TensorShape(tensor.shape.Select(i => (int)i).ToArray());
            tensor.data = CreateEmptyTensor(newTensorShape, tensor.DType);
        }

        public static Tensor CreateEmptyTensor(TensorShape shape, DataType dataType)
        {
            Tensor tensor = null;
            switch (dataType)
            {
                case DataType.Float:
                    tensor = new Tensor<float>(shape);
                    break;
                case DataType.Int:
                    tensor = new Tensor<int>(shape);
                    break;
            }

            return tensor;
        }

        internal static int[] TensorShapeFromSentis(TensorShape src)
        {
            if (src.rank == 2)
            {
                return new int[] { src.Batch(), src.Channels() };
            }

            if (src.Height() == 1 && src.Width() == 1)
            {
                return new int[] { src.Batch(), src.Channels() };
            }

            return new int[] { src.Batch(), src.Channels(), src.Height(), src.Width() };
        }

        public static TensorProxy TensorProxyFromSentis(Tensor src, string nameOverride = null)
        {
            var shape = TensorShapeFromSentis(src.shape);
            return new TensorProxy
            {
                // name = nameOverride ?? src.name,
                name = nameOverride ?? "",
                valueType = src.dataType == DataType.Float
                    ? TensorProxy.TensorType.FloatingPoint
                    : TensorProxy.TensorType.Integer,
                shape = shape,
                data = src
            };
        }

        /// <summary>
        /// Fill a specific batch of a TensorProxy with a given value
        /// </summary>
        /// <param name="tensorProxy"></param>
        /// <param name="batch">The batch index to fill.</param>
        /// <param name="fillValue"></param>
        public static void FillTensorBatch(TensorProxy tensorProxy, int batch, float fillValue)
        {
            var height = tensorProxy.data.Height();
            var width = tensorProxy.data.Width();
            var channels = tensorProxy.data.Channels();

            tensorProxy.data.CompleteAllPendingOperations();

            for (var h = 0; h < height; h++)
            {
                for (var w = 0; w < width; w++)
                {
                    for (var c = 0; c < channels; c++)
                    {
                        ((Tensor<float>)tensorProxy.data)[batch, c, h, w] = fillValue;
                    }
                }
            }
        }

        /// <summary>
        /// Fill a pre-allocated Tensor with random numbers
        /// </summary>
        /// <param name="tensorProxy">The pre-allocated Tensor to fill</param>
        /// <param name="randomNormal">RandomNormal object used to populate tensor</param>
        /// <exception cref="NotImplementedException">
        /// Throws when trying to fill a Tensor of type other than float
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// Throws when the Tensor is not allocated
        /// </exception>
        public static void FillTensorWithRandomNormal(
            TensorProxy tensorProxy, RandomNormal randomNormal)
        {
            if (tensorProxy.DataType != typeof(float))
            {
                throw new NotImplementedException("Only float data types are currently supported");
            }

            if (tensorProxy.data == null)
            {
                throw new ArgumentNullException();
            }

            tensorProxy.data.CompleteAllPendingOperations();

            for (var i = 0; i < tensorProxy.data.Length(); i++)
            {
                ((Tensor<float>)tensorProxy.data)[i] = (float)randomNormal.NextDouble();
            }
        }
    }
}