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
use tf;
use libc::{c_char, c_int};
use std::ffi::CStr;
use std::ffi::CString;
use std::marker;
use std::path::Path;
use std::ptr;
use super::AnyTensor;
use super::{Buffer, BufferTrait};
use super::Code;
use super::DataType;
use super::Graph;
use super::GraphTrait;
use super::Operation;
use super::OperationTrait;
use super::Result;
use super::SessionOptions;
use super::Status;
use super::Tensor;
use super::TensorType;
#[derive(Debug)]
pub struct SavedModelBundle {
pub session: Session,
pub meta_graph_def: Vec<u8>,
}
impl SavedModelBundle {
pub fn load<P: AsRef<Path>, Tag: AsRef<str>, Tags: IntoIterator<Item = Tag>>
(options: &SessionOptions,
tags: Tags,
graph: &mut Graph,
export_dir: P)
-> Result<SavedModelBundle> {
let mut status = Status::new();
let export_dir_cstr =
export_dir.as_ref()
.to_str()
.and_then(|s| CString::new(s.as_bytes()).ok())
.ok_or_else(|| invalid_arg!("Invalid export directory path"))?;
let tags_cstr: Vec<_> = tags.into_iter()
.map(|t| CString::new(t.as_ref()))
.collect::<::std::result::Result<_, _>>()
.map_err(|_| invalid_arg!("Invalid tag name"))?;
let tags_ptr: Vec<*const c_char> = tags_cstr.iter().map(|t| t.as_ptr()).collect();
let mut meta = unsafe { Buffer::<u8>::from_ptr(ptr::null_mut(), 0) };
let inner = unsafe {
tf::TF_LoadSessionFromSavedModel(options.inner,
ptr::null(),
export_dir_cstr.as_ptr(),
tags_ptr.as_ptr(),
tags_ptr.len() as c_int,
graph.inner(),
meta.inner_mut(),
status.inner())
};
if inner.is_null() {
Err(status)
} else {
let session = Session { inner: inner };
Ok(SavedModelBundle {
session: session,
meta_graph_def: Vec::from(meta.as_ref())
})
}
}
}
#[derive(Debug)]
pub struct Session {
inner: *mut tf::TF_Session,
}
impl Session {
pub fn new(options: &SessionOptions, graph: &Graph) -> Result<Self> {
let mut status = Status::new();
let inner = unsafe { tf::TF_NewSession(graph.inner(), options.inner, status.inner()) };
if inner.is_null() {
Err(status)
} else {
Ok(Session { inner: inner })
}
}
pub fn from_saved_model<P: AsRef<Path>, Tag: AsRef<str>, Tags: IntoIterator<Item = Tag>>
(options: &SessionOptions,
tags: Tags,
graph: &mut Graph,
export_dir: P)
-> Result<Self> {
let mut status = Status::new();
let export_dir_cstr = export_dir.as_ref()
.to_str()
.and_then(|s| CString::new(s.as_bytes()).ok())
.ok_or_else(|| invalid_arg!("Invalid export directory path"))?;
let tags_cstr: Vec<_> = tags.into_iter()
.map(|t| CString::new(t.as_ref()))
.collect::<::std::result::Result<_, _>>()
.map_err(|_| invalid_arg!("Invalid tag name"))?;
let tags_ptr: Vec<*const c_char> = tags_cstr.iter().map(|t| t.as_ptr()).collect();
let inner = unsafe {
tf::TF_LoadSessionFromSavedModel(options.inner,
ptr::null(),
export_dir_cstr.as_ptr(),
tags_ptr.as_ptr(),
tags_ptr.len() as c_int,
graph.inner(),
ptr::null_mut(),
status.inner())
};
if inner.is_null() {
Err(status)
} else {
Ok(Session { inner: inner })
}
}
pub fn close(&mut self) -> Result<()> {
let mut status = Status::new();
unsafe {
tf::TF_CloseSession(self.inner, status.inner());
}
status.into_result()
}
pub fn run(&mut self, step: &mut StepWithGraph) -> Result<()> {
step.drop_output_tensors();
let mut status = Status::new();
let maybe_tensors: Result<_> = step.input_tensors.iter().map(|t| t.inner()).collect();
let input_tensors: Vec<_> = maybe_tensors?;
unsafe {
tf::TF_SessionRun(self.inner,
ptr::null(),
step.input_ports.as_ptr(),
input_tensors.as_ptr() as *const *const tf::TF_Tensor,
input_tensors.len() as c_int,
step.output_ports.as_ptr(),
step.output_tensors.as_mut_ptr(),
step.output_tensors.len() as c_int,
step.target_operations.as_mut_ptr(),
step.target_operations.len() as c_int,
ptr::null_mut(),
status.inner());
};
status.into_result()
}
pub fn device_list(&self) -> Result<Vec<Device>> {
let status = Status::new();
unsafe {
let list = tf::TF_SessionListDevices(self.inner, status.inner);
if !status.is_ok() {
return Err(status);
}
let result = (|| {
let n = tf::TF_DeviceListCount(list);
let mut devices = Vec::with_capacity(n as usize);
for i in 0..n {
let c_name = tf::TF_DeviceListName(list, i, status.inner);
if !status.is_ok() {
return Err(status);
}
let c_type = tf::TF_DeviceListType(list, i, status.inner);
if !status.is_ok() {
return Err(status);
}
let bytes = tf::TF_DeviceListMemoryBytes(list, i, status.inner);
if !status.is_ok() {
return Err(status);
}
devices.push(Device {
name: CStr::from_ptr(c_name).to_str()?.to_string(),
device_type: CStr::from_ptr(c_type).to_str()?.to_string(),
memory_bytes: bytes,
});
}
Ok(devices)
})();
tf::TF_DeleteDeviceList(list);
result
}
}
}
impl Drop for Session {
fn drop(&mut self) {
let mut status = Status::new();
unsafe {
tf::TF_DeleteSession(self.inner, status.inner());
}
}
}
#[derive(Copy,Clone,Debug)]
pub struct OutputToken {
index: usize,
}
#[derive(Debug)]
pub struct StepWithGraph<'l> {
input_ports: Vec<tf::TF_Output>,
input_tensors: Vec<&'l AnyTensor>,
output_ports: Vec<tf::TF_Output>,
output_tensors: Vec<*mut tf::TF_Tensor>,
target_operations: Vec<*const tf::TF_Operation>,
phantom: marker::PhantomData<&'l ()>,
}
impl<'l> StepWithGraph<'l> {
pub fn new() -> Self {
StepWithGraph {
input_ports: vec![],
input_tensors: vec![],
output_ports: vec![],
output_tensors: vec![],
target_operations: vec![],
phantom: marker::PhantomData,
}
}
pub fn add_input<T: TensorType>(&mut self,
operation: &Operation,
index: c_int,
tensor: &'l Tensor<T>) {
self.input_ports.push(tf::TF_Output {
oper: operation.inner(),
index: index,
});
self.input_tensors.push(tensor);
}
pub fn request_output(&mut self, operation: &Operation, index: c_int) -> OutputToken {
self.output_ports.push(tf::TF_Output {
oper: operation.inner(),
index: index,
});
self.output_tensors.push(ptr::null_mut());
OutputToken { index: self.output_tensors.len() - 1 }
}
pub fn take_output<T: TensorType>(&mut self, token: OutputToken) -> Result<Tensor<T>> {
let output_idx = token.index;
if output_idx >= self.output_tensors.len() {
return Err(Status::new_set(Code::OutOfRange,
&format!("Requested output index is out of range: {} vs \
{}",
output_idx,
self.output_tensors.len()))
.unwrap());
}
if self.output_tensors[output_idx].is_null() {
return Err(Status::new_set(Code::Unavailable,
"Output not available. Either it was already taken, or \
this step has not been sucessfully run yet.")
.unwrap());
}
let actual_data_type = self.output_data_type(output_idx).unwrap();
if actual_data_type != T::data_type() {
return Err(invalid_arg!("Requested tensor type does not match actual tensor type: \
{} vs {}",
actual_data_type,
T::data_type()));
}
let tensor = unsafe { Tensor::from_tf_tensor(self.output_tensors[output_idx]).unwrap() };
self.output_tensors[output_idx] = ptr::null_mut();
Ok(tensor)
}
pub fn add_target(&mut self, operation: &Operation) {
self.target_operations.push(operation.inner());
}
pub fn output_data_type(&self, output_idx: usize) -> Option<DataType> {
if output_idx >= self.output_tensors.len() {
return None;
}
if self.output_tensors[output_idx].is_null() {
return None;
}
unsafe { Some(DataType::from_c(tf::TF_TensorType(self.output_tensors[output_idx]))) }
}
fn drop_output_tensors(&mut self) {
for mut tensor in &mut self.output_tensors {
if !tensor.is_null() {
unsafe {
tf::TF_DeleteTensor(*tensor);
}
}
*tensor = ptr::null_mut();
}
}
}
impl<'l> Drop for StepWithGraph<'l> {
fn drop(&mut self) {
self.drop_output_tensors();
}
}
#[derive(Debug,Eq,PartialEq,Clone,Hash)]
pub struct Device {
pub name: String,
pub device_type: String,
pub memory_bytes: i64,
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::DataType;
use super::super::Graph;
use super::super::Operation;
use super::super::Output;
use super::super::SessionOptions;
use super::super::Shape;
use super::super::Tensor;
fn create_session() -> (Session, Operation, Operation) {
let mut g = Graph::new();
let two = {
let mut nd = g.new_operation("Const", "two").unwrap();
nd.set_attr_type("dtype", DataType::Float).unwrap();
let mut value = Tensor::new(&[1]);
value[0] = 2.0f32;
nd.set_attr_tensor("value", value).unwrap();
nd.finish().unwrap()
};
let x = {
let mut nd = g.new_operation("Placeholder", "x").unwrap();
nd.set_attr_type("dtype", DataType::Float).unwrap();
nd.set_attr_shape("shape", &Shape(Some(vec![]))).unwrap();
nd.finish().unwrap()
};
let y = {
let mut nd = g.new_operation("Mul", "y").unwrap();
nd.add_input(Output {
operation: two,
index: 0,
});
nd.add_input(Output {
operation: x.clone(),
index: 0,
});
nd.finish().unwrap()
};
let options = SessionOptions::new();
match Session::new(&options, &g) {
Ok(session) => (session, x, y),
Err(status) => panic!("Creating session failed with status: {}", status),
}
}
#[test]
fn smoke() {
create_session();
}
#[test]
fn test_close() {
let (mut session, _, _) = create_session();
let status = session.close();
assert!(status.is_ok());
}
#[test]
fn test_run() {
let (mut session, x_operation, y_operation) = create_session();
let mut x = <Tensor<f32>>::new(&[2]);
x[0] = 2.0;
x[1] = 3.0;
let mut step = StepWithGraph::new();
step.add_input(&x_operation, 0, &x);
let output_token = step.request_output(&y_operation, 0);
session.run(&mut step).unwrap();
let output_tensor = step.take_output::<f32>(output_token).unwrap();
assert_eq!(output_tensor.len(), 2);
assert_eq!(output_tensor[0], 4.0);
assert_eq!(output_tensor[1], 6.0);
}
#[test]
fn test_savedmodelbundle() {
let mut graph = Graph::new();
let bundle = SavedModelBundle::load(
&SessionOptions::new(),
&["train", "serve"],
&mut graph,
"test_resources/regression-model",
).unwrap();
let x_op = graph.operation_by_name_required("x").unwrap();
let y_op = graph.operation_by_name_required("y").unwrap();
let y_hat_op = graph.operation_by_name_required("y_hat").unwrap();
let _train_op = graph.operation_by_name_required("train").unwrap();
let SavedModelBundle {
mut session,
meta_graph_def,
} = bundle;
assert!(!meta_graph_def.is_empty());
let mut x = <Tensor<f32>>::new(&[1]);
x[0] = 2.0;
let mut y = <Tensor<f32>>::new(&[1]);
y[0] = 4.0;
let mut step = StepWithGraph::new();
step.add_input(&x_op, 0, &x);
step.add_input(&y_op, 0, &y);
let output_token = step.request_output(&y_hat_op, 0);
session.run(&mut step).unwrap();
let output_tensor = step.take_output::<f32>(output_token).unwrap();
assert_eq!(output_tensor.len(), 1);
}
#[test]
fn test_device_list() {
let (session, _, _) = create_session();
let devices = session.device_list().unwrap();
assert!(devices.iter().any(|d| d.device_type == "CPU"), "devices: {:?}", devices);
}
}