-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathtensor_example.cpp
More file actions
555 lines (462 loc) · 19.7 KB
/
Copy pathtensor_example.cpp
File metadata and controls
555 lines (462 loc) · 19.7 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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
/********************************************************************************
# * Copyright (c) 2025-2026 Advanced Micro Devices, Inc. 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.
# *******************************************************************************/
#include <cstdint>
#include <iostream>
#include <memory>
#include <optional>
#include "tensor_example.hpp"
namespace zendnnl {
namespace examples {
using namespace zendnnl::interface;
int tensor_unaligned_allocation_example() {
testlog_info("Tensor unaligned memory allocation example");
auto tensor = tensor_t()
.set_name("unaligned_tensor")
.set_size({15, 10, 1, 1})
.set_stride({1, 15, 1, 150})
.set_storage()
.create();
if (tensor.check()) {
testlog_info("Tensor creation of ", tensor.get_name(), " successful.");
testlog_info(tensor.get_name(), " elements :", tensor.get_nelem(),
" buffer size :", tensor.get_buffer_sz_bytes(),
" order :", tensor.get_order(), " raw ptr :",
reinterpret_cast<std::uintptr_t>(
tensor.get_raw_handle_unsafe()));
} else {
testlog_error("Tensor creation of ", tensor.get_name(), " failed!");
return NOT_OK;
}
return OK;
}
int tensor_aligned_allocation_example() {
testlog_info("Tensor aligned memory allocation example");
auto tensor = tensor_t()
.set_name("aligned_tensor")
.set_size({MATMUL_ROWS, MATMUL_COLS})
.set_storage(ALIGNMENT_BOUNDARY)
.create();
if (tensor.check()) {
testlog_info("Tensor creation of ", tensor.get_name(), " successful.");
testlog_verbose(tensor.get_name(), " elements :", tensor.get_nelem(),
" buffer size :", tensor.get_buffer_sz_bytes(), " raw ptr :",
reinterpret_cast<std::uintptr_t>(
tensor.get_raw_handle_unsafe()));
} else {
testlog_error("Tensor creation of ", tensor.get_name(), " failed!");
return NOT_OK;
}
return OK;
}
int tensor_strided_aligned_allocation_example() {
testlog_info("Tensor strided aligned memory allocation example");
auto tensor = tensor_t()
.set_name("aligned_strided_tensor")
.set_aligned_size({MATMUL_ROWS, MATMUL_STRIDE_COLS})
.set_size({MATMUL_ROWS, MATMUL_COLS})
.set_storage(ALIGNMENT_BOUNDARY)
.create();
if (tensor.check()) {
testlog_info("Tensor creation of ", tensor.get_name(), " successful.");
testlog_verbose(tensor.get_name(), " elements :", tensor.get_nelem(),
" buffer size :", tensor.get_buffer_sz_bytes(), " raw ptr :",
reinterpret_cast<std::uintptr_t>(
tensor.get_raw_handle_unsafe()));
} else {
testlog_error("Tensor creation of ", tensor.get_name(), " failed!");
return NOT_OK;
}
return OK;
}
int tensor_copy_and_compare_example() {
testlog_info("Tensor copy and compare example");
auto tensor = tensor_t()
.set_name("contiguous_tensor")
.set_size({MATMUL_ROWS, MATMUL_COLS})
.set_data_type(data_type_t::bf16)
.set_storage()
.create();
if (tensor.check()) {
testlog_verbose(
"Tensor creation of ", tensor.get_name(), " successful");
testlog_verbose(tensor.get_name(), " hash :", tensor.hash(),
" elements :", tensor.get_nelem(),
" buffer size :", tensor.get_buffer_sz_bytes(), " raw ptr :",
reinterpret_cast<std::uintptr_t>(
tensor.get_raw_handle_unsafe()));
} else {
testlog_error("Tensor creation of ", tensor.get_name(), " failed!");
return NOT_OK;
}
auto copy_tensor = tensor;
copy_tensor.set_name("copied_bf16_tensor");
testlog_info("copied ", tensor.get_name(), " to ", copy_tensor.get_name());
testlog_info(
"comparing ", tensor.get_name(), " with ", copy_tensor.get_name());
if (copy_tensor == tensor) {
testlog_info("tensor copy of ", copy_tensor.get_name(), " from ",
tensor.get_name(), " is successful");
testlog_verbose(tensor.get_name(),
" storage count : ", tensor.get_storage_count());
} else {
testlog_error("tensor copy failed with original hash:", tensor.hash(),
" copied hash:", copy_tensor.hash(), " mismatch.");
return NOT_OK;
}
return OK;
}
int tensor_move_and_refcount_example() {
testlog_info("Tensor move and refcount example.");
auto tensor = tensor_t()
.set_name("contiguous_tensor")
.set_size({MATMUL_ROWS, MATMUL_COLS})
.set_data_type(data_type_t::s8)
.set_storage()
.create();
if (tensor.check()) {
testlog_verbose(
"Tensor creation of ", tensor.get_name(), " successful");
testlog_verbose(tensor.get_name(), " hash :", tensor.hash(),
" elements :", tensor.get_nelem(),
" buffer size :", tensor.get_buffer_sz_bytes(), " raw ptr :",
reinterpret_cast<std::uintptr_t>(
tensor.get_raw_handle_unsafe()));
} else {
testlog_error("Tensor creation of ", tensor.get_name(), " failed!");
return NOT_OK;
}
// Store the original name before moving
std::string original_name = tensor.get_name();
auto move_tensor = std::move(tensor);
move_tensor.set_name("move_s8_tensor");
testlog_info("moved ", original_name, " to ", move_tensor.get_name());
// After move, tensor is in a valid but unspecified state
// We can only check if move_tensor is valid, not compare with moved tensor
if (move_tensor.check()) {
testlog_info("tensor move of ", original_name, " to ",
move_tensor.get_name(), " is successful");
testlog_info(move_tensor.get_name(), " hash :", move_tensor.hash(),
" storage count : ", move_tensor.get_storage_count());
} else {
testlog_error("move tensor failed.");
return NOT_OK;
}
return OK;
}
int tensor_constness_example() {
testlog_info("Tensor constness example");
//use tensor factor to create a uniform tensor
tensor_factory_t tensor_factory;
auto utensor = tensor_factory.uniform_tensor(
{MATMUL_DEPTH, MATMUL_ROWS, MATMUL_COLS}, data_type_t::f32, 2.5,
"tensor");
//make the tensor const
utensor.set_const(true);
//try to grab its raw pointer
try {
void *ptr = utensor.get_raw_handle_unsafe();
testlog_info("raw pointer of const tensor", ptr);
} catch (const exception_t &ex) {
testlog_info(
"caught exception of attempt to get raw pointer of a const "
"tensor.");
testlog_verbose(ex.what());
}
//try to get const handle
try {
const float *const_ptr
= static_cast<const float *>(utensor.get_raw_handle_const());
//try to modify data
//const_ptr[2] = 3.0;
//read the data
testlog_info("tensor ", utensor.get_name(),
"flat index = 2 : value = ", const_ptr[2]);
//at() works
testlog_info(utensor.get_name(), "[2,2,2] = ", utensor.at({2, 2, 2}));
} catch (const exception_t &ex) {
testlog_error(ex.what());
return NOT_OK;
}
return OK;
}
int tensor_create_alike_example() {
testlog_info("Tensor create alike example");
//use tensor factory to create a uniform tensor
tensor_factory_t tensor_factory;
auto utensor = tensor_factory.uniform_tensor(
{MATMUL_DEPTH, MATMUL_ROWS, MATMUL_COLS}, data_type_t::f32, 2.5,
"tensor");
//make the tensor const
auto tensor_option = utensor.get_tensor_option();
try {
tensor_t atensor = tensor_t()
.set_tensor_option(tensor_option)
.set_storage()
.create();
//check few options
if ((utensor.get_size() == atensor.get_size())
&& (utensor.get_data_type() == atensor.get_data_type())
&& (utensor.get_layout() == atensor.get_layout())) {
testlog_info("Created a tensor with same options");
} else {
testlog_error("Failed to create tensor with same options");
return NOT_OK;
}
} catch (const exception_t &ex) {
testlog_error(ex.what());
return NOT_OK;
}
return OK;
}
int tensor_broadcast_example() {
testlog_info("Tensor broadcast example");
{
//create a 3D tensor broadcasted along depth
auto depth_tensor = tensor_t()
.set_name("depth_broadcast_tensor")
.set_size({10, 4, 6})
.set_stride({0, 6, 1})
.set_data_type(data_type_t::f32)
.set_storage()
.create();
if (!depth_tensor.check()) {
testlog_error("Creation of ", depth_tensor.get_name(), " failed.");
return NOT_OK;
} else {
testlog_info(
"Created detphwise broadcast tensor of size {10,6,4}, "
"stride {0,6,1}");
}
auto nelem = depth_tensor.get_nelem();
float *buf_ptr
= static_cast<float *>(depth_tensor.get_raw_handle_unsafe());
for (uint32_t i = 0; i < nelem; ++i)
buf_ptr[i] = i + 1;
testlog_info(depth_tensor.get_name(), " has ", nelem, " elements.");
//print same row and col element at differet depths
testlog_info(
"Printing elements with same row, col but only depth "
"changing...");
uint32_t r = 2;
uint32_t c = 3;
for (uint32_t d = 0; d < 5; ++d) {
auto val = depth_tensor.at({d, r, c});
testlog_info(depth_tensor.get_name(), "[", d, ",", r, ",", c,
"] = ", val);
}
}
{
//create a 3D tensor broadcasted along row
auto row_tensor = tensor_t()
.set_name("row_broadcast_tensor")
.set_size({10, 4, 6})
.set_stride({6, 0, 1})
.set_data_type(data_type_t::f32)
.set_storage()
.create();
if (!row_tensor.check()) {
testlog_error("Creation of ", row_tensor.get_name(), " failed.");
return NOT_OK;
} else {
testlog_info(
"Created row-wise broadcast tensor of size {10,4,6}, "
"stride {6,0,1}");
}
auto nelem = row_tensor.get_nelem();
float *buf_ptr
= static_cast<float *>(row_tensor.get_raw_handle_unsafe());
for (uint32_t i = 0; i < nelem; ++i)
buf_ptr[i] = i + 1;
testlog_info(row_tensor.get_name(), " has ", nelem, " elements.");
//print same row and col element at differet depths
testlog_info(
"Printing elements with same depth, col but only row "
"changing...");
uint32_t d = 4;
uint32_t c = 3;
for (uint32_t r = 0; r < 4; ++r) {
auto val = row_tensor.at({d, r, c});
testlog_info(
row_tensor.get_name(), "[", d, ",", r, ",", c, "] = ", val);
}
}
{
//create a 4D tensor with 'ac' subtensor broadcasted along 'bd' axes
auto bd_tensor = tensor_t()
.set_name("bd_broadcast_tensor")
.set_size({10, 5, 4, 6})
.set_stride({4, 0, 1, 0})
.set_data_type(data_type_t::f32)
.set_storage()
.create();
if (!bd_tensor.check()) {
testlog_error("Creation of ", bd_tensor.get_name(), " failed.");
return NOT_OK;
} else {
testlog_info(
"Created bd-wise broadcast tensor of size {10,5,4,6}, "
"stride {4,0,1,0}");
}
auto nelem = bd_tensor.get_nelem();
float *buf_ptr
= static_cast<float *>(bd_tensor.get_raw_handle_unsafe());
for (uint32_t i = 0; i < nelem; ++i)
buf_ptr[i] = i + 1;
testlog_info(bd_tensor.get_name(), " has ", nelem, " elements.");
//print same row and col element at differet depths
testlog_info("Printing elements with same a,c, only b,d changing...");
uint32_t a = 2;
uint32_t c = 1;
for (uint32_t b = 0; b < 5; ++b) {
for (uint32_t d = 0; d < 6; ++d) {
auto val = bd_tensor.at({a, b, c, d});
testlog_info(bd_tensor.get_name(), "[", a, ",", b, ",", c, ',',
d, "] = ", val);
}
}
}
return OK;
}
int tensor_axes_permutation_example() {
testlog_info("Tensor axis permutation example");
//create and linearly populate a 4D tensor. stride [120,24,6,1]
auto orig_tensor = tensor_t()
.set_name("orig_tensor")
.set_size({10, 5, 4, 6})
.set_data_type(data_type_t::f32)
.set_storage()
.create();
if (!orig_tensor.check()) {
testlog_error("Creation of ", orig_tensor.get_name(), " failed.");
return NOT_OK;
}
auto nelem = orig_tensor.get_nelem();
float *buf_ptr = static_cast<float *>(orig_tensor.get_raw_handle_unsafe());
for (uint32_t i = 0; i < nelem; ++i)
buf_ptr[i] = i + 1;
//access an element
tensor_t::index_vec_type index = {2, 3, 1, 4};
testlog_info(
orig_tensor.get_name(), " [2,3,1,4] = ", orig_tensor.at(index));
//create another tensor with permuted axes, but same buffer
auto permuted_tensor = tensor_t()
.set_name("permuted_tensor")
.set_size({10, 5, 6, 4})
.set_order("abdc")
.set_data_type(data_type_t::f32)
.set_storage(orig_tensor)
.create();
//access same element with permuted index
index = {2, 3, 4, 1};
testlog_info(permuted_tensor.get_name(),
" [2,3,4,1] = ", permuted_tensor.at(index));
//give strides in place of order
auto stride_tensor = tensor_t()
.set_name("stride_tensor")
.set_size({10, 5, 6, 4})
.set_stride({120, 24, 1, 6})
.set_data_type(data_type_t::f32)
.set_storage(orig_tensor)
.create();
//access same element with permuted index
index = {2, 3, 4, 1};
testlog_info(
stride_tensor.get_name(), " [2,3,4,1] = ", stride_tensor.at(index));
return OK;
}
int tensor_quantization_example() {
testlog_info("Quantizated tensor creation example");
//use tensor factory to create a uniform tensor
tensor_factory_t tensor_factory;
//get a uniformly distributed tensor
auto udtensor = tensor_factory.uniform_dist_strided_tensor(
{MATMUL_ROWS, MATMUL_COLS}, {MATMUL_ROWS, MATMUL_COLS},
data_type_t::f32, 1.0, "udtensor");
//get a scale tensor for row-wise channel quantization
float scale = 1.0 / 127.0;
auto scales = tensor_factory.uniform_tensor(
{MATMUL_ROWS, 1}, data_type_t::f32, scale, "scale tensor");
auto qtensor = tensor_t()
.set_name("quantized tensor")
.set_size({MATMUL_ROWS, MATMUL_COLS})
.set_data_type(data_type_t::s8)
.set_quant_scale(scales)
.set_storage()
.create();
if (!qtensor.check()) {
testlog_error("tensor creation of ", qtensor.get_name(), " failed");
return NOT_OK;
}
//quantize the tensor
const float *udhandle = (const float *)udtensor.get_raw_handle_const();
int8_t *qhandle = (int8_t *)qtensor.get_raw_handle_unsafe();
const float *shandle
= (const float *)qtensor.get_quant_scale_raw_handle_const();
for (uint32_t r = 0; r < MATMUL_ROWS; ++r) {
float scale = shandle[r];
for (uint32_t c = 0; c < MATMUL_COLS; ++c) {
auto udoffset = udtensor.compute_offset({r, c});
auto qoffset = qtensor.compute_offset({r, c});
qhandle[qoffset] = int8_t(udhandle[udoffset] / scale);
}
}
//query quantization parameters
auto quant_type = qtensor.get_quant_type();
if (quant_type == quant_type_t::uniform)
testlog_info(qtensor.get_name(), " quant type : uniform");
else
testlog_info(qtensor.get_name(), " quant type : nonuniform");
auto quant_subtype = qtensor.get_quant_subtype();
if (quant_subtype == quant_subtype_t::symmetric)
testlog_info(qtensor.get_name(), " quant subtype : symmetric");
else
testlog_info(qtensor.get_name(), " quant subtype : asymmetric");
//dequantize the tensor
qtensor.set_const(true);
auto dqtensor = tensor_t()
.set_name("dequantized tensor")
.set_size({MATMUL_ROWS, MATMUL_COLS})
.set_data_type(data_type_t::f32)
.set_storage()
.create();
if (!dqtensor.check()) {
testlog_error("tensor creation of ", dqtensor.get_name(), " failed");
return NOT_OK;
}
float *dqhandle = (float *)dqtensor.get_raw_handle_unsafe();
const int8_t *qchandle = (const int8_t *)qtensor.get_raw_handle_const();
shandle = (const float *)qtensor.get_quant_scale_raw_handle_const();
for (uint32_t r = 0; r < MATMUL_ROWS; ++r) {
float scale = shandle[r];
for (uint32_t c = 0; c < MATMUL_COLS; ++c) {
auto dqoffset = dqtensor.compute_offset({r, c});
auto qoffset = qtensor.compute_offset({r, c});
dqhandle[dqoffset] = qchandle[qoffset] * scale;
}
}
//display results
for (uint32_t r = 0; r < MATMUL_ROWS; ++r) {
for (uint32_t c = 0; c < MATMUL_COLS; ++c) {
auto udval = udtensor.at({r, c});
auto dqval = dqtensor.at({r, c});
testlog_info("orig[", r, ",", c, "]=", udval, " dq[", r, ",", c,
"]=", dqval);
}
}
return OK;
}
} // namespace examples
} // namespace zendnnl