-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathContiguousTensor.h
355 lines (302 loc) · 12 KB
/
ContiguousTensor.h
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
/*
* Copyright 2024 The DAPHNE Consortium
*
* 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.
*/
#pragma once
#include <cstddef>
#include <cstring>
#include <memory>
#include <optional>
#include <ostream>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
#include <runtime/local/datastructures/DataObjectFactory.h>
#include <runtime/local/datastructures/DenseMatrix.h>
#include <runtime/local/datastructures/Tensor.h>
/**
* @brief An implementation of a tensor with a contiguous, "row-major" memory
* layout
*
* This tensor implementation is backed by a single allocation for its data.
* The elements of the tensor are placed within this in the "higher dimensional
* equivalent of row-major order".
*
*/
template <typename ValueType> class ContiguousTensor : public Tensor<ValueType> {
public:
std::vector<size_t> strides;
std::shared_ptr<ValueType[]> data;
private:
// Grant DataObjectFactory access to the private constructors and
// destructors.
template <class DataType, typename... ArgTypes> friend DataType *DataObjectFactory::create(ArgTypes...);
template <class DataType> friend void DataObjectFactory::destroy(const DataType *obj);
ContiguousTensor(const std::vector<size_t> &tensor_shape, InitCode init_code)
: Tensor<ValueType>::Tensor(tensor_shape),
data(new ValueType[this->total_element_count], std::default_delete<ValueType[]>()) {
strides.resize(this->rank);
if (this->rank > 0) {
strides[0] = 1;
}
for (size_t i = 0; i < this->rank; i++) {
if (tensor_shape[i] == 0) {
throw std::runtime_error("Tensors with dimensions of extend 0 are disallowed.");
}
}
for (size_t i = 1; i < this->rank; i++) {
strides[i] = strides[i - 1] * this->tensor_shape[i - 1];
}
switch (init_code) {
case InitCode::NONE:
break;
case InitCode::ZERO: {
for (size_t i = 0; i < this->total_element_count; i++) {
data.get()[i] = 0;
}
break;
}
case InitCode::MAX: {
for (size_t i = 0; i < this->total_element_count; i++) {
data.get()[i] = std::numeric_limits<ValueType>::max();
}
break;
}
case InitCode::MIN: {
for (size_t i = 0; i < this->total_element_count; i++) {
data.get()[i] = std::numeric_limits<ValueType>::min();
}
break;
}
case InitCode::IOTA: {
for (size_t i = 0; i < this->total_element_count; i++) {
data.get()[i] = i;
}
break;
}
}
};
template <typename VTArg>
ContiguousTensor(const ContiguousTensor<VTArg> *other)
: Tensor<ValueType>::Tensor(other->tensor_shape), strides(other->strides) {
// workarround for old versions of gcc with template specialization bug
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85282
if constexpr (std::is_same<VTArg, ValueType>::value) {
data = other->data;
} else {
data = std::shared_ptr<ValueType[]>(new ValueType[this->total_element_count],
std::default_delete<ValueType[]>());
for (size_t i = 0; i < this->total_element_count; i++) {
data[i] = static_cast<ValueType>(other->data[i]);
}
}
};
ContiguousTensor(const DenseMatrix<ValueType> *other)
: Tensor<ValueType>::Tensor(other->getNumRows(), other->getNumCols()), data(other->getValuesSharedPtr()) {
strides = {1, other->getRowSkip()};
for (size_t i = 0; i < this->rank; i++) {
if (this->tensor_shape[i] == 0) {
throw std::runtime_error("Tensors with dimensions of extend 0 are disallowed.");
}
}
}
// Copies passed data
ContiguousTensor(ValueType *input_data, const std::vector<size_t> &tensor_shape)
: Tensor<ValueType>::Tensor(tensor_shape),
data(new ValueType[this->total_element_count], std::default_delete<ValueType[]>()) {
strides.resize(this->rank);
if (this->rank > 0) {
strides[0] = 1;
}
for (size_t i = 0; i < this->rank; i++) {
if (this->tensor_shape[i] == 0) {
throw std::runtime_error("Tensors with dimensions of extend 0 are disallowed.");
}
}
for (size_t i = 1; i < this->rank; i++) {
strides[i] = strides[i - 1] * this->tensor_shape[i - 1];
}
std::memcpy(data.get(), input_data, this->total_element_count * sizeof(ValueType));
}
ContiguousTensor(std::shared_ptr<ValueType[]> &input_data, const std::vector<size_t> &tensor_shape)
: Tensor<ValueType>::Tensor(tensor_shape) {
data = input_data;
strides.resize(this->rank);
if (this->rank > 0) {
strides[0] = 1;
}
for (size_t i = 0; i < this->rank; i++) {
if (this->tensor_shape[i] == 0) {
throw std::runtime_error("Tensors with dimensions of extend 0 are disallowed.");
}
}
for (size_t i = 1; i < this->rank; i++) {
strides[i] = strides[i - 1] * this->tensor_shape[i - 1];
}
}
// Takes ownership of data
ContiguousTensor(std::unique_ptr<ValueType[]> input_data, const std::vector<size_t> &tensor_shape)
: Tensor<ValueType>::Tensor(tensor_shape), data(std::move(input_data)) {
strides.resize(this->rank);
if (this->rank > 0) {
strides[0] = 1;
}
for (size_t i = 0; i < this->rank; i++) {
if (this->tensor_shape[i] == 0) {
throw std::runtime_error("Tensors with dimensions of extend 0 are disallowed.");
}
}
for (size_t i = 1; i < this->rank; i++) {
strides[i] = strides[i - 1] * this->tensor_shape[i - 1];
}
}
~ContiguousTensor() override = default;
void printValue(std::ostream &os, ValueType val) const;
public:
bool operator==(const ContiguousTensor<ValueType> &rhs) const {
if (this->tensor_shape != rhs.tensor_shape) {
return false;
}
return !static_cast<bool>(
std::memcmp(data.get(), rhs.data.get(), this->total_element_count * sizeof(ValueType)));
}
DenseMatrix<ValueType> *tryToGetDenseMatrix() const {
if (this->rank != 2) {
return nullptr;
}
return DataObjectFactory::create<DenseMatrix<ValueType>>(this->tensor_shape[1], this->tensor_shape[0], data);
}
std::optional<ValueType> tryGet(const std::vector<size_t> &element_indices) const {
if (element_indices.size() != this->rank) {
return std::nullopt;
}
if (this->rank == 0) {
return data.get()[0];
}
for (size_t i = 0; i < this->rank; i++) {
if (element_indices[i] >= this->tensor_shape[i]) {
return std::nullopt;
}
}
size_t linear_id = element_indices[0];
for (size_t i = 1; i < this->rank; i++) {
linear_id += element_indices[i] * strides[i];
}
return data.get()[linear_id];
}
ValueType get(const std::vector<size_t> &element_indices) const {
if (this->rank == 0) {
return data.get()[0];
}
size_t linear_id = element_indices[0];
for (size_t i = 1; i < this->rank; i++) {
linear_id += element_indices[i] * strides[i];
}
return data.get()[linear_id];
}
bool trySet(const std::vector<size_t> &element_indices, ValueType value) {
if (element_indices.size() != this->rank || this->rank == 0) {
return false;
}
for (size_t i = 0; i < this->rank; i++) {
if (element_indices[i] >= this->tensor_shape[i]) {
return false;
}
}
size_t linear_id = element_indices[0];
for (size_t i = 1; i < this->rank; i++) {
linear_id += element_indices[i] * strides[i];
}
data.get()[linear_id] = value;
return true;
}
void set(const std::vector<size_t> &element_indices, ValueType value) {
size_t linear_id = element_indices[0];
for (size_t i = 1; i < this->rank; i++) {
linear_id += element_indices[i] * strides[i];
}
data.get()[linear_id] = value;
}
void print(std::ostream &os) const override {
os << "ContiguousTensor(";
for (size_t i = 0; i < this->rank; i++) {
os << this->tensor_shape[i];
if (i != this->rank - 1) {
os << "x";
}
}
os << ", " << ValueTypeUtils::cppNameFor<ValueType> << ")" << std::endl;
if (this->rank == 0) {
os << data.get()[0] << std::endl;
return;
}
for (size_t i = 0; i < this->total_element_count; i++) {
if (i % this->tensor_shape[0] == 0) {
os << "\n";
}
printValue(os, data.get()[i]);
os << " ";
}
os << std::endl;
}
// Ranges inclusive on lower bound and exclusive on upper bound i.e. [x,y]
// at dsl lvl is in math == [x:y)
ContiguousTensor<ValueType> *tryDice(std::vector<std::pair<size_t, size_t>> index_ranges) const {
if (index_ranges.size() != this->rank) {
return nullptr;
}
for (size_t i = 0; i < this->rank; i++) {
index_ranges[i] = {std::get<0>(index_ranges[i]), std::get<1>(index_ranges[i]) - 1};
if (std::get<0>(index_ranges[i]) >= this->tensor_shape[i] ||
std::get<1>(index_ranges[i]) >= this->tensor_shape[i] ||
std::get<0>(index_ranges[i]) > std::get<1>(index_ranges[i])) {
return nullptr;
}
}
std::vector<size_t> new_tensor_shape;
new_tensor_shape.resize(this->rank);
for (size_t i = 0; i < this->rank; i++) {
new_tensor_shape[i] = std::get<1>(index_ranges[i]) - std::get<0>(index_ranges[i]) + 1;
}
ContiguousTensor<ValueType> *new_tensor =
DataObjectFactory::create<ContiguousTensor<ValueType>>(new_tensor_shape, InitCode::NONE);
std::vector<size_t> current_indices;
current_indices.resize(this->rank);
for (size_t i = 0; i < new_tensor->total_element_count; i++) {
size_t tmp = i;
for (int64_t j = this->rank - 1; j >= 0; j--) {
current_indices[static_cast<size_t>(j)] = (tmp / new_tensor->strides[static_cast<size_t>(j)]) +
std::get<0>(index_ranges[static_cast<size_t>(j)]);
tmp = tmp % new_tensor->strides[static_cast<size_t>(j)];
}
new_tensor->data[i] = get(current_indices);
}
return new_tensor;
}
// Removes all dimensions with a size of 1
void reduceRank() {
for (size_t i = 0; i < this->rank; i++) {
if (this->tensor_shape[i] == 1) {
this->tensor_shape.erase(this->tensor_shape.begin() + i);
strides.erase(strides.begin() + i);
}
}
this->rank = this->tensor_shape.size();
}
size_t getNumItems() const override { return this->total_element_count; }
size_t serialize(std::vector<char> &buf) const override {
throw std::runtime_error("ContiguousTensor::serialize() is not supported (yet)");
}
};