-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroot.zig
More file actions
6536 lines (5777 loc) · 278 KB
/
root.zig
File metadata and controls
6536 lines (5777 loc) · 278 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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const builtin = @import("builtin");
/// General Utils N stuff
pub const Utils = struct {
pub const PathChar = if (builtin.os.tag == .windows) u16 else u8;
comptime { std.debug.assert(PathChar == Api.c.ORTCHAR_T); }
pub const Path = [*:0]const PathChar;
const VEnum = enum {usize, cstr};
fn OptionsKVLRetvalType(I: type, vEnum: VEnum) type {
return struct {
const T = if (@typeInfo(I) == .pointer) @typeInfo(I).pointer.child else I;
const V = switch (vEnum) {
.usize => usize,
.cstr => [*:0]const u8,
};
const max_len = @typeInfo(T).@"struct".fields.len;
_keys: [max_len][*:0]const u8 = undefined,
_vals: [max_len]V = undefined,
len: usize = 0,
fn add(self: *@This(), options: I, comptime k: [:0]const u8) void {
self._keys[self.len] = k;
const v = @field(options, k);
if (vEnum == .usize) {
self._vals[self.len] = switch (@typeInfo(@TypeOf(v))) {
.optional => |oi| switch (@typeInfo(oi.child)) {
.int => v.?,
else => unreachable,
},
.@"enum" => @intFromEnum(v),
.int => v,
.bool => @intFromBool(v),
else => unreachable,
};
} else {
self._vals[self.len] = switch (@typeInfo(@TypeOf(v))) {
.optional => |oi| switch (@typeInfo(oi.child)) {
.pointer => |pi| switch (pi.size) {
.many => v.?,
.slice => v.?.ptr,
.c, .one => unreachable,
},
else => unreachable,
},
.pointer => |pi| switch (pi.size) {
.many => v,
.slice => v.ptr,
.c, .one => unreachable,
},
else => unreachable,
};
}
self.len += 1;
}
fn fromInstance(instance: I) @This() {
var retval: @This() = .{};
inline for (@typeInfo(T).@"struct".fields) |f| {
if (@field(instance, f.name) != @as(*const @FieldType(T, f.name), @alignCast(@ptrCast(f.default_value_ptr.?))).*)
retval.add(instance, f.name);
}
return retval;
}
pub fn keys(self: *const @This()) [*]const [*:0] const u8 { return (&self._keys).ptr; }
pub fn vals(self: *const @This()) [*]const V { return (&self._vals).ptr; }
};
}
/// Helper function to convert a struct to keys, values array and length, for V2 functions that take string arrays
pub fn createOptionsKVL(instance: anytype, comptime V: VEnum) OptionsKVLRetvalType(@TypeOf(instance), V) {
return .fromInstance(instance);
}
fn CopyPointerAttrs(From: type, size: std.builtin.Type.Pointer.Size, To: type) type {
if (@typeInfo(To) == .@"opaque" and size != .one) {
@compileError(std.fmt.comptimePrint("From: {s}; size: {any}; To: {s}", .{@typeName(From), size, @typeName(To)}));
}
const info = @typeInfo(From).pointer;
return @Type(.{
.pointer = .{
.size = size,
.is_const = info.is_const,
.is_volatile = info.is_volatile,
.is_allowzero = info.is_allowzero,
.alignment = info.alignment,
.address_space = info.address_space,
.child = To,
.sentinel_ptr = null,
},
});
}
fn ApiCast(comptime T: type) type {
return switch (@typeInfo(T)) {
.@"opaque", .@"struct" => T.Underlying,
.@"enum" => @typeInfo(T).@"enum".tag_type,
.pointer => |pi| blk: {
std.debug.assert(pi.size != .slice);
break :blk CopyPointerAttrs(T, if (@typeInfo(pi.child) == .@"opaque") .one else .c, ApiCast(pi.child));
},
.optional => |oi| blk: {
const casted = ApiCast(oi.child);
break :blk switch (@typeInfo(casted)) {
.pointer => |pi| switch (pi.size) {
.one => ?casted,
.slice => unreachable,
else => casted,
},
else => unreachable,
};
},
else => unreachable,
};
}
pub fn apiCast(anyptr: anytype) ApiCast(@TypeOf(anyptr)) {
return @ptrCast(anyptr);
}
// fn ApiCastTo(T: type, To: type) type {
// return switch (@typeInfo(T)) {
// .@"opaque", .@"struct", => blk: {
// std.debug.assert(T == To.Underlying);
// break :blk To.Underlying;
// },
// .@"enum" => blk: {
// std.debug.assert(T == @typeInfo(To).@"enum".tag_type);
// break :blk @typeInfo(To).@"enum".tag_type;
// },
// .pointer => |pi| switch (@typeInfo(To)) {
// .pointer => |topi| CopyPointerAttrs(T, topi.size, ApiCastTo(pi.child, topi.child)),
// .optional => |tooi| ?blk: {
// const topi = @typeInfo(tooi.child);
// break :blk CopyPointerAttrs(T, topi.size, ApiCastTo(pi.child, topi.child));
// },
// else => unreachable,
// },
// else => unreachable,
// };
// }
fn ApiCastTo(From: type, To: type) type {
const CastedFrom = ApiCast(To);
if (CastedFrom != From) @compileError(std.fmt.comptimePrint("From: {s}; Casted: {s}; To: {s}", .{@typeName(From), @typeName(CastedFrom), @typeName(To)}));
return To;
}
pub fn apiCastTo(anyptr: anytype, comptime To: type) ApiCastTo(@TypeOf(anyptr), To) {
return @ptrCast(anyptr);
}
fn SentinelStrCast(Str: type, T: type) type {
if (Str == [*:0]const T) return [*c]const T;
if (Str == [*:0]T) return [*c]T;
return switch (@typeInfo(Str)) {
.pointer => |pi| blk: {
std.debug.assert(pi.size != .slice);
break :blk CopyPointerAttrs(Str, .c, SentinelStrCast(pi.child, T));
},
.optional => |oi| SentinelStrCast(oi.child, T), // c pointers are already optional
else => unreachable,
};
}
fn SentinelStrCastTo(Str: type, T: type, To: type) type {
if (Str == [*c]const T) {
std.debug.assert(To == [*:0]const T or To == ?[*:0]const T);
return To;
}
if (Str == [*c]T) {
std.debug.assert(To == [*:0]T or To == ?[*:0]T);
return To;
}
return switch (@typeInfo(Str)) {
.pointer => |pi| blk: {
std.debug.assert(pi.size != .slice);
break :blk switch (@typeInfo(To)) {
.pointer => |topi| blk2: {
std.debug.assert(topi.size != .slice);
break :blk2 CopyPointerAttrs(Str, topi.size, SentinelStrCastTo(pi.child, T, topi.child));
},
.optional => |tooi| ?blk2: {
const topi = @typeInfo(tooi.child);
break :blk2 CopyPointerAttrs(Str, topi.size, SentinelStrCastTo(pi.child, T, topi.child));
},
else => unreachable,
};
},
else => unreachable,
};
}
pub fn cStr(str: anytype) SentinelStrCast(@TypeOf(str), u8) {
return @ptrCast(str);
}
pub fn cStrTo(str: anytype, comptime To: type) SentinelStrCastTo(@TypeOf(str), u8, To) {
return @ptrCast(str);
}
pub fn pathCast(str: anytype) SentinelStrCast(@TypeOf(str), PathChar) {
return @ptrCast(str);
}
pub fn pathCastTo(str: anytype, comptime To: type) SentinelStrCastTo(@TypeOf(str), PathChar, To) {
return @ptrCast(str);
}
fn CCast(comptime T: type) type {
return switch (@typeInfo(T)) {
.@"enum" => @typeInfo(T).@"enum".tag_type,
.pointer => |pi| blk: {
std.debug.assert(pi.size != .slice);
break :blk CopyPointerAttrs(T, if (@typeInfo(pi.child) == .@"opaque") .one else .c, CCast(pi.child));
},
.optional => |oi| blk: {
const casted = CCast(oi.child);
break :blk switch (@typeInfo(casted)) {
.pointer => |pi| switch (pi.size) {
.one => ?casted,
.slice => unreachable,
else => casted,
},
else => unreachable,
};
},
else => T,
};
}
pub fn cCast(anyptr: anytype) CCast(@TypeOf(anyptr)) {
return @ptrCast(anyptr);
}
pub const empty_string = [_]u8{0};
pub const empty_path = [_]PathChar{0};
pub fn asPath(comptime str: []const u8) [:0]const PathChar {
var retval: [str.len:0]PathChar = undefined;
for (str, 0..) |c, i| retval[i] = c;
retval[str.len] = 0;
const const_retval = retval;
return &const_retval;
}
};
const apiCast = Utils.apiCast;
const apiCastTo = Utils.apiCastTo;
const cStr = Utils.cStr;
const cStrTo = Utils.cStrTo;
const pathCast = Utils.pathCast;
const pathCastTo = Utils.pathCastTo;
const cCast = Utils.cCast;
const empty_string = Utils.empty_string;
const empty_path = Utils.empty_path;
/// This is usually used by vendors
pub const Ep = struct {
pub const api = opaque {
pub var underlying: *const Api.c.OrtEpApi = undefined;
};
/// The Wrapper for OrtEp Struct
pub const Interface = struct {
pub const Underlying = Api.c.OrtEp;
underlying: Underlying,
comptime { std.debug.assert(@bitSizeOf(@This()) == @bitSizeOf(Underlying)); }
// Call the underlying vtable
pub fn getName(self: *const @This()) [*:0]const u8 {
return cStrTo(self.underlying.GetName.?(apiCast(self)), [*:0]const u8);
}
// Call the underlying vtable
pub fn setDynamicOptions(self: *@This(), keys: []const [*:0]const u8, values: []const [*:0]const u8) !void {
if (self.underlying.SetDynamicOptions) |f| {
try Error.check(f(apiCast(self), cStr(keys.ptr), cStr(values.ptr), keys.len));
}
}
// Call the underlying vtable
pub fn getCompiledModelCompatibilityInfo(self: *@This(), graph: *const Graph) [*:0]const u8 {
return self.underlying.GetCompiledModelCompatibilityInfo.?(apiCast(self), apiCast(graph));
}
pub const DataLayout = enum(Api.c.OrtEpDataLayout) {
NCHW = @bitCast(Api.c.OrtEpDataLayout_NCHW),
NHWC = @bitCast(Api.c.OrtEpDataLayout_NHWC),
};
/// Initialize the Ep structure with vtables pointing to the provided Implementer type.
///
/// Requirements for Implementer (T):
/// - Must have a field `ep: Ep.Interface`.
/// - fn getName(self: *const T) [*:0]const u8
/// - fn getCapability(self: *T, graph: *const Graph, support_info: *GraphSupportInfo) !void
/// - fn compile(self: *T, graphs: []const *const Graph, fused_nodes: []const *const Node, node_compute_infos: []*NodeCompute.Info, ep_context_nodes: []*Node) !void
/// - fn releaseNodeComputeInfos(self: *T, node_compute_infos: []*NodeCompute.Info) void
/// - fn getCompiledModelCompatibilityInfo(self: *T, graph: *const Graph) [*:0]const u8
///
/// Optional methods for Implementer (T):
/// - fn getPreferredDataLayout(self: *T) !DataLayout
/// - fn shouldConvertDataLayoutForOp(self: *T, domain: [*:0]const u8, op_type: [*:0]const u8, layout: DataLayout) i32 (1: conv, 0: no, -1: let ORT decide)
/// - fn setDynamicOptions(self: *T, keys: []const [*:0]const u8, values: []const [*:0]const u8) !void
/// - fn onRunStart(self: *T, options: *const RunOptions) !void
/// - fn onRunEnd(self: *T, options: *const RunOptions, sync_stream: bool) !void
/// - fn createAllocator(self: *T, info: *const Allocator.MemoryInfo) !?*Allocator
/// - fn createSyncStreamForDevice(self: *T, device: *const Allocator.MemoryDevice) !?*SyncStreamImpl
pub fn init(comptime T: type) @This() {
const VTable = struct {
fn getSelf(ptr: [*c]const Api.c.OrtEp) *T {
return @constCast(@fieldParentPtr("ep", apiCastTo(ptr.?, *const Ep.Interface)));
}
fn getName(ptr: [*c]const Api.c.OrtEp) callconv(.c) [*c]const u8 {
return cStr(getSelf(ptr).getName());
}
fn getCapability(ptr: [*c]Api.c.OrtEp, graph: ?*const Api.c.OrtGraph, info: ?*Api.c.OrtEpGraphSupportInfo) callconv(.c) ?*Api.c.OrtStatus {
getSelf(ptr).getCapability(apiCastTo(graph.?, *const Graph), apiCastTo(info.?, *GraphSupportInfo)) catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
return null;
}
fn compile(
ptr: [*c]Api.c.OrtEp,
graphs: [*c]?*const Api.c.OrtGraph,
fused: [*c]?*const Api.c.OrtNode,
count: usize,
infos_out: [*c][*c]Api.c.OrtNodeComputeInfo,
context_nodes_out: [*c]?*Api.c.OrtNode,
) callconv(.c) ?*Api.c.OrtStatus {
const g_slice_optional = apiCastTo(graphs, [*]?*const Graph);
const f_slice_optional = apiCastTo(fused, [*]?*const Node);
const i_slice_optional = apiCastTo(infos_out, [*]?*NodeCompute.Info);
const c_slice_optional = apiCastTo(context_nodes_out, [*]?*Node);
const g_slice = @as([*]*const Graph, @ptrCast(g_slice_optional))[0..count];
const f_slice = @as([*]*const Node, @ptrCast(f_slice_optional))[0..count];
const i_slice = @as([*]*NodeCompute.Info, @ptrCast(i_slice_optional))[0..count];
const c_slice = @as([*]*Node, @ptrCast(c_slice_optional))[0..count];
getSelf(ptr).compile(g_slice, f_slice, i_slice, c_slice) catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
return null;
}
fn releaseNodeComputeInfos(ptr: [*c]Api.c.OrtEp, infos: [*c][*c]Api.c.OrtNodeComputeInfo, count: usize) callconv(.c) void {
getSelf(ptr).releaseNodeComputeInfos(apiCastTo(infos, [*]*NodeCompute.Info)[0..count]);
}
fn getPreferredDataLayout(ptr: [*c]Api.c.OrtEp, layout_out: [*c]Api.c.OrtEpDataLayout) callconv(.c) ?*Api.c.OrtStatus {
const layout = getSelf(ptr).getPreferredDataLayout() catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
layout_out.?.* = @intFromEnum(layout);
return null;
}
fn shouldConvertDataLayoutForOp(ptr: [*c]Api.c.OrtEp, domain: [*:0]const u8, op_type: [*:0]const u8, layout: Api.c.OrtEpDataLayout, out: [*c]c_int) callconv(.c) ?*Api.c.OrtStatus {
out.?.* = getSelf(ptr).shouldConvertDataLayoutForOp(domain, op_type, @enumFromInt(layout));
return null;
}
fn setDynamicOptions(ptr: [*c]Api.c.OrtEp, keys: [*c]const [*:0]const u8, vals: [*c]const [*:0]const u8, count: usize) callconv(.c) ?*Api.c.OrtStatus {
getSelf(ptr).setDynamicOptions(keys[0..count], vals[0..count]) catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
return null;
}
fn onRunStart(ptr: [*c]Api.c.OrtEp, options: [*c]const Api.c.OrtRunOptions) callconv(.c) ?*Api.c.OrtStatus {
getSelf(ptr).onRunStart(apiCastTo(options.?, *const RunOptions)) catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
return null;
}
fn onRunEnd(ptr: [*c]Api.c.OrtEp, options: [*c]const Api.c.OrtRunOptions, sync: bool) callconv(.c) ?*Api.c.OrtStatus {
getSelf(ptr).onRunEnd(apiCastTo(options.?, *const RunOptions), sync) catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
return null;
}
fn createAllocator(ptr: [*c]Api.c.OrtEp, info: [*c]const Api.c.OrtMemoryInfo, out: [*c][*c]Api.c.OrtAllocator) callconv(.c) ?*Api.c.OrtStatus {
const alloc = getSelf(ptr).createAllocator(apiCastTo(info.?, *const Allocator.MemoryInfo)) catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
out.?.* = apiCast(alloc);
return null;
}
fn createSyncStreamForDevice(ptr: [*c]Api.c.OrtEp, dev: [*c]const Api.c.OrtMemoryDevice, out: [*c][*c]Api.c.OrtSyncStreamImpl) callconv(.c) ?*Api.c.OrtStatus {
const stream = getSelf(ptr).createSyncStreamForDevice(apiCastTo(dev.?, *const Allocator.MemoryDevice)) catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
out.?.* = apiCast(stream);
return null;
}
fn getCompiledModelCompatibilityInfo(ptr: [*c]Api.c.OrtEp, graph: ?*const Api.c.OrtGraph) callconv(.c) [*:0]const u8 {
return getSelf(ptr).getCompiledModelCompatibilityInfo(apiCastTo(graph.?, *const Graph));
}
};
return .{
.underlying = .{
.ort_version_supported = Api.c.ORT_API_VERSION,
.GetName = VTable.getName,
.GetCapability = VTable.getCapability,
.Compile = VTable.compile,
.ReleaseNodeComputeInfos = VTable.releaseNodeComputeInfos,
.GetPreferredDataLayout = if (@hasDecl(T, "getPreferredDataLayout")) VTable.getPreferredDataLayout else null,
.ShouldConvertDataLayoutForOp = if (@hasDecl(T, "shouldConvertDataLayoutForOp")) VTable.shouldConvertDataLayoutForOp else null,
.SetDynamicOptions = if (@hasDecl(T, "setDynamicOptions")) VTable.setDynamicOptions else null,
.OnRunStart = if (@hasDecl(T, "onRunStart")) VTable.onRunStart else null,
.OnRunEnd = if (@hasDecl(T, "onRunEnd")) VTable.onRunEnd else null,
.CreateAllocator = if (@hasDecl(T, "createAllocator")) VTable.createAllocator else null,
.CreateSyncStreamForDevice = if (@hasDecl(T, "createSyncStreamForDevice")) VTable.createSyncStreamForDevice else null,
.GetCompiledModelCompatibilityInfo = VTable.getCompiledModelCompatibilityInfo,
},
};
}
};
/// Struct that an EP implements for IDataTransfer to copy between devices it uses and CPU
pub const DataTransfer = struct {
pub const Underlying = Api.c.OrtDataTransferImpl;
underlying: Underlying,
comptime { std.debug.assert(@bitSizeOf(@This()) == @bitSizeOf(Underlying)); }
/// Check if the implementation can copy between the source and destination memory devices.
/// returns true if the implementation can copy between the devices.
/// since Version 1.23.
pub fn canCopy(self: *const @This(), src: *const Allocator.MemoryDevice, dst: *const Allocator.MemoryDevice) bool {
return self.underlying.CanCopy.?(apiCast(self), apiCast(src), apiCast(dst));
}
/// Copy tensors from src_tensors to dst_tensors using the provided streams.
///
/// The implementation can use the provided streams to perform asynchronous copies if supported.
/// If a stream is not available, the copy is performed synchronously.
///
/// streams: Array of OrtSyncStream pointers for the copy operations, if the execution provider is stream aware. nullptr if it is not.
///
/// since Version 1.23.
pub fn copy(self: *@This(), src: []*const Value, dst: []*Value, streams: ?[]?*SyncStream) !void {
std.debug.assert(src.len == dst.len);
if (streams) |s| std.debug.assert(src.len == s.len);
const src_ptr: [*]?*const Value = @ptrCast(src.ptr);
const dst_ptr: [*]?*Value = @ptrCast(dst.ptr);
try Error.check(self.underlying.CopyTensors.?(
apiCast(self),
apiCast(src_ptr),
apiCast(dst_ptr),
apiCast(if (streams) |s| s.ptr else null),
src.len,
));
}
/// Release the OrtDataTransferImpl instance.
///
/// This is called by ORT when the OrtDataTransferImpl instance is no longer needed.
/// The implementation should release any resources held by the instance.
///
/// since Version 1.23.
pub fn deinit(self: *@This()) void {
return self.underlying.Release.?(apiCast(self));
}
/// Initialize the DataTransfer structure with vtables pointing to the provided Implementer type.
///
/// Requirements for Implementer:
/// - Must have a field `data_transfer: DataTransfer` as the a member, we use @fieldParentPtr on that member to get actual pointer
/// - fn canCopy(self: *const Implementer, src: *const Allocator.MemoryDevice, dst: *const Allocator.MemoryDevice) bool
/// - fn copyTensors(self: *Implementer, src: []const *const Value, dst: []*Value, streams: ?[]?*SyncStream) !void
/// - (Optional) fn deinit(self: *Implementer) void
pub fn init(comptime T: type) @This() {
const VTable = struct {
fn getSelf(self: [*c]const Api.c.OrtDataTransferImpl) *T {
return @constCast(@fieldParentPtr("data_transfer", apiCastTo(self.?, *const DataTransfer)));
}
fn release(self: [*c]Api.c.OrtDataTransferImpl) callconv(.c) void {
if (@hasDecl(T, "deinit")) getSelf(self).deinit();
}
fn canCopy(
self: [*c]const Api.c.OrtDataTransferImpl,
src: ?*const Api.c.OrtMemoryDevice,
dst: ?*const Api.c.OrtMemoryDevice,
) callconv(.c) bool {
return getSelf(self).canCopy(apiCastTo(src.?, *const Allocator.MemoryDevice), apiCastTo(dst.?, *const Allocator.MemoryDevice));
}
fn copyTensors(
self: [*c]Api.c.OrtDataTransferImpl,
src: [*c]?*const Api.c.OrtValue,
dst: [*c]?*Api.c.OrtValue,
streams: [*c]?*Api.c.OrtSyncStream,
num: usize,
) callconv(.c) ?*Api.c.OrtStatus {
const src_slice_optional = apiCastTo(src, [*]?*const Value);
const dst_slice_optional = apiCastTo(dst, [*]?*Value);
const src_slice = @as([*]const *const Value, @ptrCast(src_slice_optional))[0..num];
const dst_slice = @as([*]*Value, @ptrCast(dst_slice_optional))[0..num];
const streams_slice = apiCastTo(streams, [*]?*SyncStream)[0..num];
getSelf(self).copyTensors(src_slice, dst_slice, streams_slice) catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
return null;
}
};
return .{
.underlying = .{
.ort_version_supported = Api.c.ORT_API_VERSION,
.Release = VTable.release,
.CanCopy = VTable.canCopy,
.CopyTensors = VTable.copyTensors,
},
};
}
};
/// Struct that an EP implements for Stream Notifications.
pub const SyncNotificationImpl = struct {
pub const Underlying = Api.c.OrtSyncNotificationImpl;
underlying: Underlying,
comptime { std.debug.assert(@bitSizeOf(@This()) == @bitSizeOf(Underlying)); }
/// Called by ORT to activate the notification.
///
/// since Version 1.23.
pub fn activate(self: *@This()) !void {
try Error.check(self.underlying.Activate.?(apiCast(self)));
}
/// Wait for a device to device operation to complete.
///
/// this_ptr: Pointer to the OrtSyncNotificationImpl instance.
/// stream: The OrtSyncStream instance that will wait on this notification to be activated.
///
/// since Version 1.23.
pub fn waitOnDevice(self: *@This(), stream: *SyncStream) !void {
try Error.check(self.underlying.WaitOnDevice.?(apiCast(self), apiCast(stream)));
}
/// Wait for a device to host operation to complete.
///
/// since Version 1.23.
pub fn waitOnHost(self: *@This()) !void {
try Error.check(self.underlying.WaitOnHost.?(apiCast(self)));
}
/// Release the OrtSyncNotificationImpl instance.
///
/// This is called by ORT when the OrtSyncNotificationImpl instance is no longer needed.
/// The implementation should release any resources held by the instance.
///
/// since Version 1.23.
pub fn deinit(self: *@This()) void {
self.underlying.Release.?(apiCast(self));
}
/// Initialize the SyncNotification structure with vtables pointing to the provided Implementer type.
///
/// Requirements for Implementer:
/// - Must have a field `sync_notification: SyncNotificationImpl` as a member.
/// - fn activate(self: *Implementer) !void
/// - fn waitOnDevice(self: *Implementer, consumer_stream: *SyncStream) !void
/// - fn waitOnHost(self: *Implementer) !void
/// - (Optional) fn deinit(self: *Implementer) void
pub fn init(comptime T: type) @This() {
const VTable = struct {
fn getSelf(self: [*c]Api.c.OrtSyncNotificationImpl) *T {
return @constCast(@fieldParentPtr("sync_notification", apiCastTo(self.?, *SyncNotificationImpl)));
}
fn release(self: [*c]Api.c.OrtSyncNotificationImpl) callconv(.c) void {
if (@hasDecl(T, "deinit")) getSelf(self).deinit();
}
fn activate(self: [*c]Api.c.OrtSyncNotificationImpl) callconv(.c) ?*Api.c.OrtStatus {
getSelf(self).activate() catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
return null;
}
fn waitOnDevice(self: [*c]Api.c.OrtSyncNotificationImpl, stream: ?*Api.c.OrtSyncStream) callconv(.c) ?*Api.c.OrtStatus {
getSelf(self).waitOnDevice(@as(*SyncStream, apiCastTo(stream.?, *SyncStream))) catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
return null;
}
fn waitOnHost(self: [*c]Api.c.OrtSyncNotificationImpl) callconv(.c) ?*Api.c.OrtStatus {
getSelf(self).waitOnHost() catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
return null;
}
};
return .{
.underlying = .{
.ort_version_supported = Api.c.ORT_API_VERSION,
.Release = VTable.release,
.Activate = VTable.activate,
.WaitOnDevice = VTable.waitOnDevice,
.WaitOnHost = VTable.waitOnHost,
},
};
}
};
/// Used for synchronization and async execution / data transfer etc
pub const SyncStream = opaque {
pub const Underlying = Api.c.OrtSyncStream;
/// Wraps OrtApi::CreateSyncStreamForEpDevice
/// stream_options: Optional KeyValuePairs for stream configuration.
pub fn init(device: *const Ep.Device, stream_options: ?*const KeyValuePairs) !*@This() {
var retval: ?*@This() = null;
try Error.check(Api.ort.CreateSyncStreamForEpDevice.?(apiCast(device), apiCast(stream_options), apiCast(&retval)));
return retval orelse error.OutOfMemory;
}
/// Wraps OrtApi::SyncStream_GetHandle
/// Returns the native handle
pub fn getHandle(self: *@This()) ?*anyopaque {
return Api.ort.SyncStream_GetHandle.?(apiCast(self));
}
/// Wraps OrtApi::ReleaseSyncStream
pub fn deinit(self: *@This()) void {
Api.ort.ReleaseSyncStream.?(apiCast(self));
}
/// Get the OrtSyncStreamImpl associated with an OrtSyncStream instance.
///
/// This allows an the plugin library to connect its OrtSyncStreamImpl instance with an OrtSyncStream if needed.
///
/// stream: The OrtSyncStream instance to find an OrtSyncStreamImpl for.
/// returns The associated OrtSyncStreamImpl if found. nullptr otherwise.
///
/// since Version 1.23.
///
/// Remarks: There should always be an OrtSyncStreamImpl associated with an OrtSyncStream instance that the EP gets.
pub fn getImpl(self: *const @This()) *const Impl {
return apiCastTo(Ep.api.underlying.SyncStream_GetImpl.?(apiCast(self)), *const Impl);
}
/// Get the current sync ID for a stream.
///
/// stream: The OrtSyncStream to get the sync ID for.
/// returns Current sync ID.
///
/// since Version 1.23.
pub fn getSyncId(self: *const @This()) u64 {
return Ep.api.underlying.SyncStream_GetSyncId.?(apiCast(self));
}
/// Get the sync ID for the last time the consumer_stream waited on the producer_stream.
///
/// When two streams are synchronized, the sync id represents the event used in that synchronization.
///
/// producer_stream: The OrtSyncStream that produced the data.
/// consumer_stream: The OrtSyncStream that waited on the producer_stream.
/// returns ID for last sync. 0 if no sync has occurred between the two streams.
///
/// since Version 1.23.
pub fn getSyncIdForLastWaitOnSyncStream(producer: *const @This(), consumer: *const @This()) u64 {
return Ep.api.underlying.GetSyncIdForLastWaitOnSyncStream.?(apiCast(producer), apiCast(consumer));
}
/// Struct that an EP implements if it wishes to implement Stream support.
/// This struct provides the overrides for onnxruntime::Stream's virtual methods.
///
/// since Version 1.23.
pub const Impl = struct {
pub const Underlying = Api.c.OrtSyncStreamImpl;
underlying: @This().Underlying,
comptime { std.debug.assert(@bitSizeOf(@This()) == @bitSizeOf(@This().Underlying)); }
///Get the handle of the stream.
///
/// This returns the native handle for the stream. e.g. cudaStream_t for CUDA streams.
///
/// since Version 1.23.
pub fn handle(self: *@This()) ?*anyopaque {
return self.underlying.GetHandle.?(apiCast(self));
}
/// Create an OrtSyncNotificationImpl for the OrtSyncStreamImpl instance.
///
/// since Version 1.23.
pub fn createNotification(self: *@This()) !*SyncNotificationImpl {
var out: ?*SyncNotificationImpl = null;
try Error.check(self.underlying.CreateNotification.?(apiCast(self), apiCast(&out)));
return out orelse error.OutOfMemory;
}
/// Notify the stream that a session run has ended.
///
/// This is called by ORT to notify the stream that a session run has ended, allowing the stream to perform any
/// necessary cleanup or finalization.
///
/// since Version 1.23.
pub fn endSessionRun(self: *@This()) !void {
try Error.check(self.underlying.OnSessionRunEnd.?(apiCast(self)));
}
/// Flush the stream.
///
/// This is called by ORT to flush the stream, ensuring that all operations submitted to the stream are completed.
///
/// since Version 1.23.
pub fn flush(self: *@This()) !void {
try Error.check(self.underlying.Flush.?(apiCast(self)));
}
/// Release the OrtSyncStreamImpl instance.
///
/// This is called by ORT when the OrtSyncStreamImpl instance is no longer needed.
/// The implementation should release any resources held by the instance.
///
/// since Version 1.23.
pub fn deinit(self: *@This()) void {
self.underlying.Release.?(apiCast(self));
}
/// Requirements for Implementer:
/// - Must have a field `sync_stream: SyncStreamImpl`.
/// - fn getHandle(self: *Implementer) ?*anyopaque
/// - fn createNotification(self: *Implementer, out: **SyncNotificationImpl) !void
/// - fn flush(self: *Implementer) !void
/// - fn onSessionRunEnd(self: *Implementer) !void
pub fn init(comptime T: type) @This() {
const VTable = struct {
fn getSelf(self: [*c]Api.c.OrtSyncStreamImpl) *T {
return @constCast(@fieldParentPtr("sync_stream", apiCastTo(self.?, *Impl)));
}
fn release(self: [*c]Api.c.OrtSyncStreamImpl) callconv(.c) void {
if (@hasDecl(T, "deinit")) getSelf(self).deinit();
}
fn getHandle(self: [*c]Api.c.OrtSyncStreamImpl) callconv(.c) ?*anyopaque {
return getSelf(self).getHandle();
}
fn createNotification(self: [*c]Api.c.OrtSyncStreamImpl, out: [*c][*c]Api.c.OrtSyncNotificationImpl) callconv(.c) ?*Api.c.OrtStatus {
getSelf(self).createNotification(@as(*?*SyncNotificationImpl, apiCastTo(out.?, *?*SyncNotificationImpl))) catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
return null;
}
fn flush(self: [*c]Api.c.OrtSyncStreamImpl) callconv(.c) ?*Api.c.OrtStatus {
getSelf(self).flush() catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
return null;
}
fn onSessionRunEnd(self: [*c]Api.c.OrtSyncStreamImpl) callconv(.c) ?*Api.c.OrtStatus {
getSelf(self).onSessionRunEnd() catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
return null;
}
};
return .{
.underlying = .{
.ort_version_supported = Api.c.ORT_API_VERSION,
.Release = VTable.release,
.GetHandle = VTable.getHandle,
.CreateNotification = VTable.createNotification,
.Flush = VTable.flush,
.OnSessionRunEnd = VTable.onSessionRunEnd,
},
};
}
};
};
pub const NodeFusionOptions = struct {
const Underlying = Api.c.OrtNodeFusionOptions;
underlying: Underlying,
comptime { std.debug.assert(@bitSizeOf(@This()) == @bitSizeOf(Underlying)); }
};
pub const NodeCompute = struct {
/// Opaque to add type to createState
pub const State = opaque {
// This has no underlying type
};
pub const Context = opaque {
pub const Underlying = Api.c.OrtNodeComputeContext;
/// Query a OrtNodeComputeContext for the name of the node that encapsulates the compiled/fused node.
///
/// Used in OrtNodeComputeInfo::CreateComputeState().
///
/// context The OrtNodeComputeContext instance to query.
/// returns The node's name.
///
/// Note: Returned string is owned by ORT and valid only while OrtNodeComputeInfo::CreateComputeState() is called.
///
/// since Version 1.23.
pub fn name(self: *const @This()) [*:0]const u8 {
return cStrTo(api.underlying.NodeComputeContext_NodeName.?(apiCast(self)), [*:0]const u8);
}
};
/// The OrtNodeComputeInfo struct provides functions that an OrtEp implements to specify the compute function for a compiled OrtGraph instance.
/// since Version 1.23.
pub const Info = struct {
pub const Underlying = Api.c.OrtNodeComputeInfo;
underlying: Underlying,
comptime { std.debug.assert(@bitSizeOf(@This()) == @bitSizeOf(Underlying)); }
/// Creates an opaque compute state object that is then passed to the Compute() function during inference.
/// compute_context OrtNodeComputeContext instance that contains compiled/fused node's name and host
/// memory allocation functions. Can optionally be used to build the compute state.
/// returns: compute_state: the opaque computation state. ONNX Runtime calls ReleaseState() (after calling Compute())
/// to allow the implementer to release the compute state.
///
/// since Version 1.23.
pub fn createState(self: *@This(), context: *Context) !*State {
var out: ?*State = null;
// @ptrCast is needed because State has no underlying type
try Error.check(self.underlying.CreateState.?(apiCast(self), apiCast(context), @ptrCast(&out)));
return out orelse error.OutOfMemory;
}
/// Computation function called to execute the fused node compiled by an OrtEp instance.
///
/// compute_state: The opaque computation state returned by CreateState().
/// kernel_context: The OrtKernelContext instance used to access inputs/outputs.
///
/// since Version 1.23.
pub fn compute(self: *@This(), state: *State, kernel_context: *Op.KernelContext) !void {
// @ptrCast is needed because State has no underlying type
try Error.check(self.underlying.Compute.?(apiCast(self), @ptrCast(state), apiCast(kernel_context)));
}
/// Releases the compute state returned by CreateState().
///
/// compute_state: The opaque compute state returned by CreateState().
///
/// since Version 1.23.
pub fn releaseState(self: *@This(), state: *State) void {
// @ptrCast is needed because State has no underlying type
self.underlying.ReleaseState.?(apiCast(self), @ptrCast(state));
}
/// Initialize the NodeCompute.Info structure with vtables pointing to the provided Implementer type.
///
/// Requirements for Implementer:
/// - Must have a field `compute_info: Ep.NodeCompute.Info`.
/// - fn createState(self: *Implementer, context: *Context) !*State
/// - fn compute(self: *Implementer, state: ?*State, kernel_context: *KernelContext) !void
/// - fn releaseState(self: *Implementer, state: ?*State) void
pub fn init(comptime T: type) @This() {
const VTable = struct {
fn getSelf(self: [*c]Api.c.OrtNodeComputeInfo) *T {
return @fieldParentPtr("compute_info", apiCastTo(self.?, *Info));
}
fn createState(
self: [*c]Api.c.OrtNodeComputeInfo,
ctx: ?*Api.c.OrtNodeComputeContext,
state_out: ?*?*anyopaque,
) callconv(.c) ?*Api.c.OrtStatus {
const result = getSelf(self).createState(apiCastTo(ctx.?, *Context)) catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
state_out.?.* = @ptrCast(result);
return null;
}
fn compute(
self: [*c]Api.c.OrtNodeComputeInfo,
state: ?*anyopaque,
kernel_ctx: ?*Api.c.OrtKernelContext,
) callconv(.c) ?*Api.c.OrtStatus {
// @ptrCast is needed because State has no underlying type
getSelf(self).compute(@ptrCast(state), apiCastTo(kernel_ctx.?, *Op.KernelContext)) catch |err|
return apiCast(Error.Status.initInfallible(@intFromEnum(Error.Code.Fail), @errorName(err)));
return null;
}
fn releaseState(self: [*c]Api.c.OrtNodeComputeInfo, state: ?*anyopaque) callconv(.c) void {
// @ptrCast is needed because State has no underlying type
getSelf(self).releaseState(@ptrCast(state));
}
};
return .{
.underlying = .{
.ort_version_supported = Api.c.ORT_API_VERSION,
.CreateState = VTable.createState,
.Compute = VTable.compute,
.ReleaseState = VTable.releaseState,
},
};
}
};
};
/// Holds information about the nodes supported by an Execution Provider.
/// This is passed to the EP's GetCapability function.
/// Wraps OrtEpGraphSupportInfo.
pub const GraphSupportInfo = opaque {
pub const Underlying = Api.c.OrtEpGraphSupportInfo;
/// Specify nodes that are supported by an OrtEp and should be fused into one node.
///
/// Because the nodes will be fused into one "fused node", there must not exist an unsupported node in
/// a path between two of the provided nodes. Otherwise, the graph will become invalid.
///
/// This function can be called multiple times. A subsequent call to this function will force the next set of
/// nodes to be fused into a different node.
///
/// graph_support_info OrtEpGraphSupportInfo instance to which to add the supported nodes.
/// nodes Array of nodes supported by the EP that should be fused/compiled.
/// num_nodes The number of supported nodes.
/// node_fusion_options Optional node fusion options. Ignored if set to NULL.
///
/// since Version 1.23.
pub fn addNodesToFuse(
self: *@This(),
nodes: []const *const Node,
options: ?*const NodeFusionOptions,
) !void {
try Error.check(api.underlying.EpGraphSupportInfo_AddNodesToFuse.?(
apiCast(self),
apiCast(nodes.ptr),
nodes.len,
apiCast(options),
));
}
/// Specify a node that is supported by an OrtEp and should be run with a registered EP kernel.
///
/// graph_support_info OrtEpGraphSupportInfo instance to which to add the supported node.
/// node The supported OrtNode instance.
///
/// since Version 1.23.
pub fn addSingleNode(self: *@This(), node: *const Node) !void {
try Error.check(api.underlying.EpGraphSupportInfo_AddSingleNode.?(
apiCast(self),
apiCast(node),
));
}
};
// this is const everywhere
/// Represents an instance of an Execution Provider mapped to a specific hardware device.
/// Wraps OrtEpDevice.
pub const Device = opaque {
pub const Underlying = Api.c.OrtEpDevice;
/// Create an OrtEpDevice for the EP and an OrtHardwareDevice.
/// ep_factory Execution provider factory that is creating the instance.
/// hardware_device Hardware device that the EP can utilize.
/// ep_metadata (Optional) OrtKeyValuePairs instance for execution provider metadata that may be used
/// during execution provider selection and passed to CreateEp.
/// ep_device will copy this instance and the user should call ReleaseKeyValuePairs.
/// ep_options (Optional) OrtKeyValuePairs instance for execution provider options that will be added
/// to the Session configuration options if the execution provider is selected.
/// ep_device will copy this instance and the user should call ReleaseKeyValuePairs.
/// returns: ep_device OrtExecutionDevice that is created.
///
/// since Version 1.22.
pub fn init(
factory: *Factory,
hw_device: *const HardwareDevice,
ep_metadata: ?*const KeyValuePairs,
ep_options: ?*const KeyValuePairs
) !*@This() {
var out: ?*@This() = null;
try Error.check(api.underlying.CreateEpDevice.?(
apiCast(factory),
apiCast(hw_device),
apiCast(ep_metadata),
apiCast(ep_options),
apiCast(&out)
));
return out orelse error.OutOfMemory;
}
/// Returns the name of the execution provider (e.g., "CUDA", "CPU").
/// Wraps OrtApi::EpDevice_EpName
pub fn getEpName(self: *const @This()) [*:0]const u8 {
return cStrTo(Api.ort.EpDevice_EpName.?(apiCast(self)), [*:0]const u8);
}
/// Returns the name of the execution provider's vendor.
/// Wraps OrtApi::EpDevice_EpVendor
pub fn getEpVendor(self: *const @This()) [*:0]const u8 {
return cStrTo(Api.ort.EpDevice_EpVendor.?(apiCast(self)), [*:0]const u8);
}