-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathtask_interface.cpp
More file actions
629 lines (555 loc) · 23.3 KB
/
task_interface.cpp
File metadata and controls
629 lines (555 loc) · 23.3 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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
/*
* Copyright (c) PyPTO Contributors.
* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
* CANN Open Software License Agreement Version 2.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
* -----------------------------------------------------------------------------------------------------------
*/
/**
* Nanobind Python extension for task_interface headers.
*
* Wraps DataType, ContinuousTensor, ChipStorageTaskArgs, DynamicTaskArgs,
* TaggedTaskArgs, TensorArgType, ArgDirection, CoreCallable, ChipCallable,
* and helper functions from
* data_type.h / tensor_arg.h / task_args.h / arg_direction.h / callable.h.
*/
#include <nanobind/nanobind.h>
#include <nanobind/stl/string.h>
#include <nanobind/stl/tuple.h>
#include <nanobind/stl/vector.h>
#include <cstring>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include "arg_direction.h"
#include "callable.h"
#include "chip_worker.h"
#include "data_type.h"
#include "dist_worker_bind.h"
#include "task_args.h"
#include "tensor_arg.h"
namespace nb = nanobind;
// ============================================================================
// Module definition
// ============================================================================
NB_MODULE(_task_interface, m) {
m.doc() = "Nanobind bindings for task_interface (DataType, ContinuousTensor, TaskArgs variants)";
// --- DataType enum ---
nb::enum_<DataType>(m, "DataType")
.value("FLOAT32", DataType::FLOAT32)
.value("FLOAT16", DataType::FLOAT16)
.value("INT32", DataType::INT32)
.value("INT16", DataType::INT16)
.value("INT8", DataType::INT8)
.value("UINT8", DataType::UINT8)
.value("BFLOAT16", DataType::BFLOAT16)
.value("INT64", DataType::INT64)
.value("UINT64", DataType::UINT64);
// --- Free functions ---
m.def(
"get_element_size", &get_element_size, nb::arg("dtype"),
"Return the byte size of a single element of the given DataType."
);
m.def(
"get_dtype_name",
[](DataType dt) -> std::string {
return get_dtype_name(dt);
},
nb::arg("dtype"), "Return the string name of a DataType."
);
// --- Constants ---
m.attr("CONTINUOUS_TENSOR_MAX_DIMS") = CONTINUOUS_TENSOR_MAX_DIMS;
// --- ContinuousTensor ---
nb::class_<ContinuousTensor>(m, "ContinuousTensor")
.def(nb::init<>())
.def_static(
"make",
[](uint64_t data, nb::tuple shapes, DataType dtype) -> ContinuousTensor {
size_t n = nb::len(shapes);
if (n > CONTINUOUS_TENSOR_MAX_DIMS)
throw std::invalid_argument("shapes length exceeds CONTINUOUS_TENSOR_MAX_DIMS");
ContinuousTensor arg{};
arg.data = data;
arg.dtype = dtype;
arg.ndims = static_cast<uint32_t>(n);
for (size_t i = 0; i < n; ++i)
arg.shapes[i] = nb::cast<uint32_t>(shapes[i]);
return arg;
},
nb::arg("data"), nb::arg("shapes"), nb::arg("dtype"),
"Create a ContinuousTensor from a data pointer, shape tuple, and dtype."
)
.def_prop_rw(
"data",
[](const ContinuousTensor &self) -> uint64_t {
return self.data;
},
[](ContinuousTensor &self, uint64_t v) {
self.data = v;
}
)
.def_prop_rw(
"shapes",
[](const ContinuousTensor &self) -> nb::tuple {
uint32_t n = self.ndims;
if (n > CONTINUOUS_TENSOR_MAX_DIMS) n = CONTINUOUS_TENSOR_MAX_DIMS;
nb::list lst;
for (uint32_t i = 0; i < n; ++i)
lst.append(self.shapes[i]);
return nb::tuple(lst);
},
[](ContinuousTensor &self, nb::tuple t) {
size_t n = nb::len(t);
if (n > CONTINUOUS_TENSOR_MAX_DIMS)
throw std::invalid_argument(
"shapes tuple length exceeds CONTINUOUS_TENSOR_MAX_DIMS (" +
std::to_string(CONTINUOUS_TENSOR_MAX_DIMS) + ")"
);
for (size_t i = 0; i < n; ++i)
self.shapes[i] = nb::cast<uint32_t>(t[i]);
self.ndims = static_cast<uint32_t>(n);
}
)
.def_prop_rw(
"ndims",
[](const ContinuousTensor &self) -> uint32_t {
return self.ndims;
},
[](ContinuousTensor &self, uint32_t v) {
self.ndims = v;
}
)
.def_prop_rw(
"dtype",
[](const ContinuousTensor &self) -> DataType {
return self.dtype;
},
[](ContinuousTensor &self, DataType dt) {
self.dtype = dt;
}
)
.def(
"nbytes",
[](const ContinuousTensor &self) -> uint64_t {
return self.nbytes();
},
"Compute total bytes (product of shapes * element_size)."
)
.def("__repr__", [](const ContinuousTensor &self) -> std::string {
std::ostringstream os;
os << "ContinuousTensor(data=0x" << std::hex << self.data << std::dec << ", shapes=(";
for (uint32_t i = 0; i < self.ndims; ++i) {
if (i) os << ", ";
os << self.shapes[i];
}
os << "), dtype=" << get_dtype_name(self.dtype) << ")";
return os.str();
});
// --- ChipStorageTaskArgs (fixed-size TaskArgs) ---
nb::class_<ChipStorageTaskArgs>(m, "ChipStorageTaskArgs")
.def(nb::init<>())
.def(
"add_tensor", &ChipStorageTaskArgs::add_tensor, nb::arg("t"),
"Add a ContinuousTensor. Must be called before any add_scalar()."
)
.def(
"add_scalar", &ChipStorageTaskArgs::add_scalar, nb::arg("s"),
"Add a uint64_t scalar. After this, add_tensor() is no longer allowed."
)
.def(
"tensor",
[](const ChipStorageTaskArgs &self, int32_t i) -> const ContinuousTensor & {
if (i < 0 || i >= self.tensor_count())
throw std::out_of_range("ChipStorageTaskArgs tensor index out of range");
return self.tensor(i);
},
nb::arg("i"), nb::rv_policy::reference_internal, "Return the ContinuousTensor at index i."
)
.def(
"scalar",
[](const ChipStorageTaskArgs &self, int32_t i) -> uint64_t {
if (i < 0 || i >= self.scalar_count())
throw std::out_of_range("ChipStorageTaskArgs scalar index out of range");
return self.scalar(i);
},
nb::arg("i"), "Return the scalar at index i."
)
.def("tensor_count", &ChipStorageTaskArgs::tensor_count)
.def("scalar_count", &ChipStorageTaskArgs::scalar_count)
.def("clear", &ChipStorageTaskArgs::clear)
.def(
"__len__",
[](const ChipStorageTaskArgs &self) {
return self.tensor_count() + self.scalar_count();
},
"Return total number of arguments (tensors + scalars)."
)
.def(
"__ptr__",
[](const ChipStorageTaskArgs &self) -> uint64_t {
return reinterpret_cast<uint64_t>(&self);
},
"Return the memory address of the underlying C++ object."
);
// --- TensorArgType enum ---
nb::enum_<TensorArgType>(m, "TensorArgType")
.value("INPUT", TensorArgType::INPUT)
.value("OUTPUT", TensorArgType::OUTPUT)
.value("INOUT", TensorArgType::INOUT);
// --- DynamicTaskArgs (vector-backed, no capacity limit) ---
nb::class_<DynamicTaskArgs>(m, "DynamicTaskArgs")
.def(nb::init<>())
.def(
"add_tensor", &DynamicTaskArgs::add_tensor, nb::arg("t"),
"Add a ContinuousTensor. Must be called before any add_scalar()."
)
.def(
"add_scalar", &DynamicTaskArgs::add_scalar, nb::arg("s"),
"Add a uint64_t scalar. After this, add_tensor() is no longer allowed."
)
.def(
"tensor",
[](const DynamicTaskArgs &self, int32_t i) -> const ContinuousTensor & {
if (i < 0 || i >= self.tensor_count())
throw std::out_of_range("DynamicTaskArgs tensor index out of range");
return self.tensor(i);
},
nb::arg("i"), nb::rv_policy::reference_internal, "Return the ContinuousTensor at index i."
)
.def(
"scalar",
[](const DynamicTaskArgs &self, int32_t i) -> uint64_t {
if (i < 0 || i >= self.scalar_count())
throw std::out_of_range("DynamicTaskArgs scalar index out of range");
return self.scalar(i);
},
nb::arg("i"), "Return the scalar at index i."
)
.def("tensor_count", &DynamicTaskArgs::tensor_count)
.def("scalar_count", &DynamicTaskArgs::scalar_count)
.def("clear", &DynamicTaskArgs::clear)
.def(
"__len__",
[](const DynamicTaskArgs &self) {
return self.tensor_count() + self.scalar_count();
},
"Return total number of arguments (tensors + scalars)."
);
// --- TaggedTaskArgs (fixed-size with per-tensor TensorArgType tags) ---
nb::class_<TaggedTaskArgs>(m, "TaggedTaskArgs")
.def(nb::init<>())
.def(
"add_tensor",
[](TaggedTaskArgs &self, const ContinuousTensor &t, TensorArgType tag) {
self.add_tensor(t);
self.tag(self.tensor_count() - 1) = tag;
},
nb::arg("t"), nb::arg("tag") = TensorArgType::INPUT,
"Add a ContinuousTensor with an optional TensorArgType tag (default INPUT)."
)
.def(
"add_scalar", &TaggedTaskArgs::add_scalar, nb::arg("s"),
"Add a uint64_t scalar. After this, add_tensor() is no longer allowed."
)
.def(
"tensor",
[](const TaggedTaskArgs &self, int32_t i) -> const ContinuousTensor & {
if (i < 0 || i >= self.tensor_count())
throw std::out_of_range("TaggedTaskArgs tensor index out of range");
return self.tensor(i);
},
nb::arg("i"), nb::rv_policy::reference_internal, "Return the ContinuousTensor at index i."
)
.def(
"scalar",
[](const TaggedTaskArgs &self, int32_t i) -> uint64_t {
if (i < 0 || i >= self.scalar_count())
throw std::out_of_range("TaggedTaskArgs scalar index out of range");
return self.scalar(i);
},
nb::arg("i"), "Return the scalar at index i."
)
.def(
"tag",
[](const TaggedTaskArgs &self, int32_t i) -> TensorArgType {
if (i < 0 || i >= self.tensor_count()) throw std::out_of_range("TaggedTaskArgs tag index out of range");
return self.tag(i);
},
nb::arg("i"), "Return the TensorArgType tag for the tensor at index i."
)
.def(
"set_tag",
[](TaggedTaskArgs &self, int32_t i, TensorArgType tag) {
if (i < 0 || i >= self.tensor_count())
throw std::out_of_range("TaggedTaskArgs set_tag index out of range");
self.tag(i) = tag;
},
nb::arg("i"), nb::arg("tag"), "Set the TensorArgType tag for the tensor at index i."
)
.def("tensor_count", &TaggedTaskArgs::tensor_count)
.def("scalar_count", &TaggedTaskArgs::scalar_count)
.def("clear", &TaggedTaskArgs::clear)
.def(
"__len__",
[](const TaggedTaskArgs &self) {
return self.tensor_count() + self.scalar_count();
},
"Return total number of arguments (tensors + scalars)."
);
// --- ArgDirection enum ---
nb::enum_<ArgDirection>(m, "ArgDirection")
.value("SCALAR", ArgDirection::SCALAR)
.value("IN", ArgDirection::IN)
.value("OUT", ArgDirection::OUT)
.value("INOUT", ArgDirection::INOUT);
m.def(
"arg_direction_name",
[](ArgDirection d) -> std::string {
return arg_direction_name(d);
},
nb::arg("direction"), "Return the string name of an ArgDirection."
);
// --- PyCoreCallable wrapper ---
struct PyCoreCallable {
std::vector<uint8_t> buffer_;
const CoreCallable &get() const { return *reinterpret_cast<const CoreCallable *>(buffer_.data()); }
};
nb::class_<PyCoreCallable>(m, "CoreCallable")
.def_static(
"build",
[](std::vector<ArgDirection> signature, nb::bytes binary) -> PyCoreCallable {
auto bin_ptr = reinterpret_cast<const void *>(binary.c_str());
auto bin_size = static_cast<uint32_t>(binary.size());
auto buf = make_callable<CORE_MAX_TENSOR_ARGS>(
signature.data(), static_cast<int32_t>(signature.size()), bin_ptr, bin_size
);
return PyCoreCallable{std::move(buf)};
},
nb::arg("signature"), nb::arg("binary"), "Build a CoreCallable from a signature list and binary bytes."
)
.def(
"sig",
[](const PyCoreCallable &self, int32_t i) -> ArgDirection {
return self.get().sig(i);
},
nb::arg("i"), "Return the ArgDirection at signature index i."
)
.def_prop_ro(
"sig_count",
[](const PyCoreCallable &self) -> int32_t {
return self.get().sig_count();
},
"Number of signature entries."
)
.def_prop_ro(
"binary_size",
[](const PyCoreCallable &self) -> uint32_t {
return self.get().binary_size();
},
"Size of the binary payload in bytes."
)
.def(
"buffer_ptr",
[](const PyCoreCallable &self) -> uint64_t {
return reinterpret_cast<uint64_t>(self.buffer_.data());
},
"Return the memory address of the underlying buffer."
)
.def(
"buffer_size",
[](const PyCoreCallable &self) -> size_t {
return self.buffer_.size();
},
"Return the total size of the underlying buffer in bytes."
)
.def("__repr__", [](const PyCoreCallable &self) -> std::string {
const auto &c = self.get();
std::ostringstream os;
os << "CoreCallable(sig_count=" << c.sig_count() << ", binary_size=" << c.binary_size() << ")";
return os.str();
});
// --- PyChipCallable wrapper ---
struct PyChipCallable {
std::vector<uint8_t> buffer_;
const ChipCallable &get() const { return *reinterpret_cast<const ChipCallable *>(buffer_.data()); }
};
nb::class_<PyChipCallable>(m, "ChipCallable")
.def_static(
"build",
[](std::vector<ArgDirection> signature, std::string func_name, nb::bytes binary,
std::vector<std::tuple<int32_t, PyCoreCallable>> children) -> PyChipCallable {
auto bin_ptr = reinterpret_cast<const void *>(binary.c_str());
auto bin_size = static_cast<uint32_t>(binary.size());
auto child_count = static_cast<int32_t>(children.size());
std::vector<int32_t> func_ids(children.size());
std::vector<std::vector<uint8_t>> child_bufs(children.size());
for (size_t i = 0; i < children.size(); ++i) {
func_ids[i] = std::get<0>(children[i]);
child_bufs[i] = std::get<1>(children[i]).buffer_;
}
auto buf = make_callable<CoreCallable, CHIP_MAX_TENSOR_ARGS, 32>(
signature.data(), static_cast<int32_t>(signature.size()), func_name.c_str(), bin_ptr, bin_size,
func_ids.data(), child_bufs.data(), child_count
);
return PyChipCallable{std::move(buf)};
},
nb::arg("signature"), nb::arg("func_name"), nb::arg("binary"), nb::arg("children"),
"Build a ChipCallable from signature, func_name, binary, and list of (func_id, CoreCallable) children."
)
.def(
"sig",
[](const PyChipCallable &self, int32_t i) -> ArgDirection {
return self.get().sig(i);
},
nb::arg("i"), "Return the ArgDirection at signature index i."
)
.def_prop_ro(
"sig_count",
[](const PyChipCallable &self) -> int32_t {
return self.get().sig_count();
},
"Number of signature entries."
)
.def_prop_ro(
"binary_size",
[](const PyChipCallable &self) -> uint32_t {
return self.get().binary_size();
},
"Size of the binary payload in bytes."
)
.def_prop_ro(
"func_name",
[](const PyChipCallable &self) -> std::string {
const auto &c = self.get();
return std::string(c.func_name(), c.func_name_len());
},
"The orchestration function name."
)
.def_prop_ro(
"child_count",
[](const PyChipCallable &self) -> int32_t {
return self.get().child_count();
},
"Number of child callables."
)
.def(
"child_func_id",
[](const PyChipCallable &self, int32_t i) -> int32_t {
return self.get().child_func_id(i);
},
nb::arg("i"), "Return the func_id for child at index i."
)
.def(
"child",
[](const PyChipCallable &self, int32_t i) -> PyCoreCallable {
const auto &parent = self.get();
const auto &c = parent.child(i);
// Reconstruct a PyCoreCallable by copying the child's raw bytes
auto offset = parent.child_offset(i);
const uint8_t *child_start = reinterpret_cast<const uint8_t *>(parent.storage_ + offset);
// Determine child size: from offset to next child or end of buffer
size_t child_size;
if (i + 1 < parent.child_count()) {
child_size = parent.child_offset(i + 1) - offset;
} else {
size_t header_size = offsetof(ChipCallable, storage_);
child_size = self.buffer_.size() - header_size - offset;
}
std::vector<uint8_t> child_buf(child_start, child_start + child_size);
return PyCoreCallable{std::move(child_buf)};
},
nb::arg("i"), "Return the CoreCallable child at index i."
)
.def(
"child_offset",
[](const PyChipCallable &self, int32_t i) -> uint32_t {
return self.get().child_offset(i);
},
nb::arg("i"), "Return the byte offset of child i within storage (must be multiple of 64)."
)
.def(
"buffer_ptr",
[](const PyChipCallable &self) -> uint64_t {
return reinterpret_cast<uint64_t>(self.buffer_.data());
},
"Return the memory address of the underlying buffer."
)
.def(
"buffer_size",
[](const PyChipCallable &self) -> size_t {
return self.buffer_.size();
},
"Return the total size of the underlying buffer in bytes."
)
.def("__repr__", [](const PyChipCallable &self) -> std::string {
const auto &c = self.get();
std::ostringstream os;
os << "ChipCallable(func_name=\"" << std::string(c.func_name(), c.func_name_len())
<< "\", sig_count=" << c.sig_count() << ", binary_size=" << c.binary_size()
<< ", child_count=" << c.child_count() << ")";
return os.str();
});
// --- CallConfig ---
nb::class_<CallConfig>(m, "CallConfig")
.def(nb::init<>())
.def_rw("block_dim", &CallConfig::block_dim)
.def_rw("aicpu_thread_num", &CallConfig::aicpu_thread_num)
.def_prop_rw(
"enable_profiling",
[](const CallConfig &self) {
return self.perf_level;
},
[](CallConfig &self, nb::object v) {
if (nb::isinstance<nb::bool_>(v)) {
self.perf_level = nb::cast<bool>(v) ? 3 : 0;
} else {
self.perf_level = nb::cast<int>(v);
}
}
)
.def("__repr__", [](const CallConfig &self) -> std::string {
std::ostringstream os;
os << "CallConfig(block_dim=" << self.block_dim << ", aicpu_thread_num=" << self.aicpu_thread_num
<< ", enable_profiling=" << self.perf_level << ")";
return os.str();
});
// --- ChipWorker ---
nb::class_<ChipWorker>(m, "_ChipWorker")
.def(nb::init<>())
.def(
"init", &ChipWorker::init, nb::arg("host_lib_path"), nb::arg("aicpu_path"), nb::arg("aicore_path"),
nb::arg("sim_context_lib_path") = ""
)
.def("set_device", &ChipWorker::set_device, nb::arg("device_id"))
.def("reset_device", &ChipWorker::reset_device)
.def("finalize", &ChipWorker::finalize)
.def(
"run",
[](ChipWorker &self, const PyChipCallable &callable, ChipStorageTaskArgs &args, const CallConfig &config) {
self.run(callable.buffer_.data(), &args, config);
},
nb::arg("callable"), nb::arg("args"), nb::arg("config")
)
.def(
"run_raw",
[](ChipWorker &self, uint64_t callable, uint64_t args, int block_dim, int aicpu_thread_num,
int perf_level) {
CallConfig config;
config.block_dim = block_dim;
config.aicpu_thread_num = aicpu_thread_num;
config.perf_level = perf_level;
self.run(reinterpret_cast<const void *>(callable), reinterpret_cast<const void *>(args), config);
},
nb::arg("callable"), nb::arg("args"), nb::arg("block_dim") = 1, nb::arg("aicpu_thread_num") = 3,
nb::arg("perf_level") = 0, "Run with raw pointer arguments (used from forked chip process)."
)
.def_prop_ro("device_id", &ChipWorker::device_id)
.def_prop_ro("initialized", &ChipWorker::initialized)
.def_prop_ro("device_set", &ChipWorker::device_set);
bind_dist_worker(m);
}