ort 2.0.0-rc.12

A safe Rust wrapper for ONNX Runtime 1.24 - Optimize and accelerate machine learning inference & training
Documentation
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
use alloc::{ffi::CString, string::String, vec, vec::Vec};
use core::{
	ffi::c_char,
	ptr::{self, NonNull}
};

use crate::{
	AsPointer, Error, Result,
	memory::Allocator,
	ortsys,
	util::{with_cstr, with_cstr_ptr_array},
	value::{DowncastableTarget, DynValue, ValueRef}
};

#[derive(Debug)]
#[repr(transparent)] // required for `editor::Node::new`
pub struct Attribute(NonNull<ort_sys::OrtOpAttr>);

impl Attribute {
	pub fn new(name: impl AsRef<str>, value: impl ToAttribute) -> Result<Self> {
		with_cstr(name.as_ref().as_bytes(), &|name| {
			let ptr = unsafe { value.to_attribute(name.as_ptr()) }?;
			crate::logging::create!(Attribute, ptr);
			Ok(Self(ptr))
		})
	}
}

impl Drop for Attribute {
	fn drop(&mut self) {
		ortsys![unsafe ReleaseOpAttr(self.0.as_ptr())];
		crate::logging::drop!(Attribute, self.0);
	}
}

pub trait FromKernelAttributes<'s> {
	/// Reads the value of the attribute from an [`ort_sys::OrtKernelInfo`] given its C name.
	#[doc(hidden)]
	unsafe fn from_info(info: *mut ort_sys::OrtKernelInfo, name: *const ort_sys::c_char) -> Result<Self>
	where
		Self: Sized;

	private_trait!();
}

pub trait FromOpAttr {
	#[doc(hidden)]
	fn attr_type() -> ort_sys::OrtOpAttrType;

	/// Reads the value of the attribute via [`ort_sys::OrtApi::ReadOpAttr`] using the known `len`gth of the value.
	#[doc(hidden)]
	unsafe fn from_op_attr(attr: *const ort_sys::OrtOpAttr, len: usize) -> Result<Self>
	where
		Self: Sized;

	private_trait!();
}

pub trait ToAttribute {
	#[doc(hidden)]
	unsafe fn to_attribute(&self, name: *const ort_sys::c_char) -> Result<NonNull<ort_sys::OrtOpAttr>>
	where
		Self: Sized;

	private_trait!();
}

impl FromKernelAttributes<'_> for f32 {
	unsafe fn from_info(info: *mut ort_sys::OrtKernelInfo, name: *const ort_sys::c_char) -> Result<Self>
	where
		Self: Sized
	{
		let mut value = Self::default();
		ortsys![unsafe KernelInfoGetAttribute_float(info, name, &mut value)?];
		Ok(value)
	}

	private_impl!();
}

impl FromOpAttr for f32 {
	fn attr_type() -> ort_sys::OrtOpAttrType {
		ort_sys::OrtOpAttrType::ORT_OP_ATTR_FLOAT
	}

	unsafe fn from_op_attr(attr: *const ort_sys::OrtOpAttr, mut len: usize) -> Result<Self>
	where
		Self: Sized
	{
		let mut out = 0.0_f32;
		ortsys![unsafe ReadOpAttr(attr, ort_sys::OrtOpAttrType::ORT_OP_ATTR_FLOAT, (&mut out as *mut f32).cast(), size_of::<f32>(), &mut len)?];
		debug_assert_eq!(len, size_of::<f32>(), "float attribute is smaller/larger than expected");
		Ok(out)
	}

	private_impl!();
}

impl ToAttribute for f32 {
	unsafe fn to_attribute(&self, name: *const ort_sys::c_char) -> Result<NonNull<ort_sys::OrtOpAttr>>
	where
		Self: Sized
	{
		let mut out = ptr::null_mut();
		ortsys![
			unsafe CreateOpAttr(
				name,
				(self as *const f32).cast(),
				1,
				ort_sys::OrtOpAttrType::ORT_OP_ATTR_FLOAT,
				&mut out
			)?;
			nonNull(out)
		];
		Ok(out)
	}

	private_impl!();
}

impl FromKernelAttributes<'_> for i64 {
	unsafe fn from_info(info: *mut ort_sys::OrtKernelInfo, name: *const ort_sys::c_char) -> Result<Self>
	where
		Self: Sized
	{
		let mut value = Self::default();
		ortsys![unsafe KernelInfoGetAttribute_int64(info, name, &mut value)?];
		Ok(value)
	}

	private_impl!();
}

impl FromOpAttr for i64 {
	fn attr_type() -> ort_sys::OrtOpAttrType {
		ort_sys::OrtOpAttrType::ORT_OP_ATTR_INT
	}

	unsafe fn from_op_attr(attr: *const ort_sys::OrtOpAttr, mut len: usize) -> Result<Self>
	where
		Self: Sized
	{
		let mut out = 0_i64;
		ortsys![unsafe ReadOpAttr(attr, ort_sys::OrtOpAttrType::ORT_OP_ATTR_INT, (&mut out as *mut i64).cast(), size_of::<i64>(), &mut len)?];
		debug_assert_eq!(len, size_of::<i64>(), "int attribute is smaller/larger than expected");
		Ok(out)
	}

	private_impl!();
}

impl ToAttribute for i64 {
	unsafe fn to_attribute(&self, name: *const ort_sys::c_char) -> Result<NonNull<ort_sys::OrtOpAttr>>
	where
		Self: Sized
	{
		let mut out = ptr::null_mut();
		ortsys![
			unsafe CreateOpAttr(
				name,
				(self as *const i64).cast(),
				1,
				ort_sys::OrtOpAttrType::ORT_OP_ATTR_INT,
				&mut out
			)?;
			nonNull(out)
		];
		Ok(out)
	}

	private_impl!();
}

impl FromKernelAttributes<'_> for String {
	unsafe fn from_info(info: *mut ort_sys::OrtKernelInfo, name: *const ort_sys::c_char) -> Result<Self>
	where
		Self: Sized
	{
		let mut size = 0;
		ortsys![unsafe KernelInfoGetAttribute_string(info, name, ptr::null_mut(), &mut size)?];
		let mut out = vec![0u8; size];
		ortsys![unsafe KernelInfoGetAttribute_string(info, name, out.as_mut_ptr().cast::<c_char>(), &mut size)?];

		let string = CString::from_vec_with_nul(out)?;
		Ok(string.into_string()?)
	}

	private_impl!();
}

impl FromOpAttr for String {
	fn attr_type() -> ort_sys::OrtOpAttrType {
		ort_sys::OrtOpAttrType::ORT_OP_ATTR_STRING
	}

	unsafe fn from_op_attr(attr: *const ort_sys::OrtOpAttr, mut len: usize) -> Result<Self>
	where
		Self: Sized
	{
		let mut out = vec![0_u8; len];
		ortsys![unsafe ReadOpAttr(attr, ort_sys::OrtOpAttrType::ORT_OP_ATTR_STRING, out.as_mut_ptr().cast(), len, &mut len)?];
		debug_assert_eq!(out.len(), len, "int attribute is smaller/larger than expected");
		CString::from_vec_with_nul(out)
			.map_err(|_| Error::new("invalid string attribute contents"))
			.and_then(|f| f.into_string().map_err(|_| Error::new("invalid string attribute contents")))
	}

	private_impl!();
}

impl ToAttribute for String {
	unsafe fn to_attribute(&self, name: *const ort_sys::c_char) -> Result<NonNull<ort_sys::OrtOpAttr>>
	where
		Self: Sized
	{
		with_cstr(self.as_bytes(), &|contents| {
			let mut out = ptr::null_mut();
			ortsys![
				unsafe CreateOpAttr(
					name,
					contents.as_ptr().cast(),
					1,
					ort_sys::OrtOpAttrType::ORT_OP_ATTR_STRING,
					&mut out
				)?;
				nonNull(out)
			];
			Ok(out)
		})
	}

	private_impl!();
}

impl FromKernelAttributes<'_> for Vec<f32> {
	unsafe fn from_info(info: *mut ort_sys::OrtKernelInfo, name: *const ort_sys::c_char) -> Result<Self>
	where
		Self: Sized
	{
		let mut size = 0;
		ortsys![unsafe KernelInfoGetAttributeArray_float(info, name, ptr::null_mut(), &mut size)?];
		let mut out = vec![0f32; size];
		ortsys![unsafe KernelInfoGetAttributeArray_float(info, name, out.as_mut_ptr(), &mut size)?];
		Ok(out)
	}

	private_impl!();
}

impl FromOpAttr for Vec<f32> {
	fn attr_type() -> ort_sys::OrtOpAttrType {
		ort_sys::OrtOpAttrType::ORT_OP_ATTR_FLOATS
	}

	unsafe fn from_op_attr(attr: *const ort_sys::OrtOpAttr, mut len: usize) -> Result<Self>
	where
		Self: Sized
	{
		let num_els = len / size_of::<f32>();
		let mut out = vec![0.0_f32; num_els];
		ortsys![unsafe ReadOpAttr(attr, ort_sys::OrtOpAttrType::ORT_OP_ATTR_FLOATS, out.as_mut_ptr().cast(), len, &mut len)?];
		debug_assert_eq!(out.len(), num_els, "float array attribute is smaller/larger than expected");
		Ok(out)
	}

	private_impl!();
}

impl ToAttribute for &[f32] {
	unsafe fn to_attribute(&self, name: *const ort_sys::c_char) -> Result<NonNull<ort_sys::OrtOpAttr>>
	where
		Self: Sized
	{
		let mut out = ptr::null_mut();
		ortsys![
			unsafe CreateOpAttr(
				name,
				self.as_ptr().cast(),
				self.len() as _,
				ort_sys::OrtOpAttrType::ORT_OP_ATTR_FLOATS,
				&mut out
			)?;
			nonNull(out)
		];
		Ok(out)
	}

	private_impl!();
}

impl ToAttribute for Vec<f32> {
	unsafe fn to_attribute(&self, name: *const ort_sys::c_char) -> Result<NonNull<ort_sys::OrtOpAttr>>
	where
		Self: Sized
	{
		unsafe { self.as_slice().to_attribute(name) }
	}

	private_impl!();
}

impl FromKernelAttributes<'_> for Vec<i64> {
	unsafe fn from_info(info: *mut ort_sys::OrtKernelInfo, name: *const ort_sys::c_char) -> Result<Self>
	where
		Self: Sized
	{
		let mut size = 0;
		ortsys![unsafe KernelInfoGetAttributeArray_int64(info, name, ptr::null_mut(), &mut size)?];
		let mut out = vec![0i64; size];
		ortsys![unsafe KernelInfoGetAttributeArray_int64(info, name, out.as_mut_ptr(), &mut size)?];
		Ok(out)
	}

	private_impl!();
}

impl FromOpAttr for Vec<i64> {
	fn attr_type() -> ort_sys::OrtOpAttrType {
		ort_sys::OrtOpAttrType::ORT_OP_ATTR_INTS
	}

	unsafe fn from_op_attr(attr: *const ort_sys::OrtOpAttr, mut len: usize) -> Result<Self>
	where
		Self: Sized
	{
		let num_els = len / size_of::<i64>();
		let mut out = vec![0_i64; num_els];
		ortsys![unsafe ReadOpAttr(attr, ort_sys::OrtOpAttrType::ORT_OP_ATTR_INTS, out.as_mut_ptr().cast(), len, &mut len)?];
		debug_assert_eq!(out.len(), num_els, "int array attribute is smaller/larger than expected");
		Ok(out)
	}

	private_impl!();
}

impl ToAttribute for &[i64] {
	unsafe fn to_attribute(&self, name: *const ort_sys::c_char) -> Result<NonNull<ort_sys::OrtOpAttr>>
	where
		Self: Sized
	{
		let mut out = ptr::null_mut();
		ortsys![
			unsafe CreateOpAttr(
				name,
				self.as_ptr().cast(),
				self.len() as _,
				ort_sys::OrtOpAttrType::ORT_OP_ATTR_INTS,
				&mut out
			)?;
			nonNull(out)
		];
		Ok(out)
	}

	private_impl!();
}

impl ToAttribute for Vec<i64> {
	unsafe fn to_attribute(&self, name: *const ort_sys::c_char) -> Result<NonNull<ort_sys::OrtOpAttr>>
	where
		Self: Sized
	{
		unsafe { self.as_slice().to_attribute(name) }
	}

	private_impl!();
}

impl ToAttribute for &[String] {
	unsafe fn to_attribute(&self, name: *const ort_sys::c_char) -> Result<NonNull<ort_sys::OrtOpAttr>>
	where
		Self: Sized
	{
		with_cstr_ptr_array(self, &|strings| {
			let mut out = ptr::null_mut();
			ortsys![
				unsafe CreateOpAttr(
					name,
					strings.as_ptr().cast(),
					strings.len() as _,
					ort_sys::OrtOpAttrType::ORT_OP_ATTR_STRINGS,
					&mut out
				)?;
				nonNull(out)
			];
			Ok(out)
		})
	}

	private_impl!();
}

impl ToAttribute for &[&str] {
	unsafe fn to_attribute(&self, name: *const ort_sys::c_char) -> Result<NonNull<ort_sys::OrtOpAttr>>
	where
		Self: Sized
	{
		with_cstr_ptr_array(self, &|strings| {
			let mut out = ptr::null_mut();
			ortsys![
				unsafe CreateOpAttr(
					name,
					strings.as_ptr().cast(),
					strings.len() as _,
					ort_sys::OrtOpAttrType::ORT_OP_ATTR_STRINGS,
					&mut out
				)?;
				nonNull(out)
			];
			Ok(out)
		})
	}

	private_impl!();
}

impl ToAttribute for Vec<String> {
	unsafe fn to_attribute(&self, name: *const ort_sys::c_char) -> Result<NonNull<ort_sys::OrtOpAttr>>
	where
		Self: Sized
	{
		unsafe { self.as_slice().to_attribute(name) }
	}

	private_impl!();
}

impl ToAttribute for Vec<&str> {
	unsafe fn to_attribute(&self, name: *const ort_sys::c_char) -> Result<NonNull<ort_sys::OrtOpAttr>>
	where
		Self: Sized
	{
		unsafe { self.as_slice().to_attribute(name) }
	}

	private_impl!();
}

impl<'s, T: DowncastableTarget> FromKernelAttributes<'s> for ValueRef<'s, T> {
	unsafe fn from_info(info: *mut ort_sys::OrtKernelInfo, name: *const ort_sys::c_char) -> Result<Self>
	where
		Self: Sized
	{
		// TODO: This should probably be customizable - docs say the allocator is required for "internal tensor state", but it's
		// not clear if this also includes tensor data (and thus it should instead be allocated on an appropriate device).
		let allocator = Allocator::default();

		let mut value_ptr: *mut ort_sys::OrtValue = ptr::null_mut();
		ortsys![unsafe KernelInfoGetAttribute_tensor(info, name, allocator.ptr().cast_mut(), &mut value_ptr)?; nonNull(value_ptr)];
		unsafe { ValueRef::new(DynValue::from_ptr(value_ptr, None)) }.downcast()
	}

	private_impl!();
}