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
use variable::{Variable, VariableInner};
use variable_set::VariableSet;
use data_map::DataMap;
use replacement_map::ReplacementMap;
use device::DeviceDescriptor;
use std::ptr;
use std::ffi::CStr;
cpp! {{
#include <CNTKLibrary.h>
#include <cstdio>
#include <vector>
using namespace CNTK;
using namespace std;
}}
type BackPropStateInner = [u64; 2usize];
pub(super) type FunctionInner = [u64; 2usize];
#[derive(Debug)]
pub struct Function {
pub(super) payload: FunctionInner
}
pub struct BackPropState {
payload: BackPropStateInner
}
impl Function {
pub fn from_variable<T: Into<Variable>>(var: T) -> Function {
let varv = var.into();
let payload = varv.payload;
Function { payload: unsafe {
cpp!([payload as "Variable"] -> FunctionInner as "FunctionPtr" {
return payload;
})
}}
}
pub fn combine(variables: &[&Variable]) -> Function {
let data: Vec<Variable> = variables.iter().map(|&x| x.clone()).collect();
let data_ptr = data.as_ptr();
let data_size = data.len();
Function { payload: unsafe {
cpp!([data_ptr as "Variable*", data_size as "size_t"] -> FunctionInner as "FunctionPtr" {
return Combine(vector<Variable>(data_ptr, data_ptr + data_size));
})
}}
}
pub fn num_outputs(&self) -> usize {
let payload = self.payload;
unsafe {
cpp!([payload as "FunctionPtr"] -> usize as "size_t" {
return payload->Outputs().size();
})
}
}
pub fn to_variable(&self) -> Result<Variable, &'static str> {
let payload = self.payload;
if self.num_outputs() > 1 {
Err("Cannot convert function with multiple outputs into Variable")
} else {
Ok(Variable { payload: unsafe {
cpp!([payload as "FunctionPtr"] -> VariableInner as "Variable" {
return Variable(payload);
})
}})
}
}
pub fn evaluate(&self, input_data_map: &DataMap, output_data_map: &mut DataMap, device: DeviceDescriptor) {
let payload = self.payload;
let impayload = input_data_map.payload;
let mut ompayload = output_data_map.payload;
let dpayload = device.payload;
unsafe {
let mut error_p: *mut i8 = ptr::null_mut();
cpp!([payload as "FunctionPtr", impayload as "unordered_map<Variable, ValuePtr>*", mut ompayload as "unordered_map<Variable, ValuePtr>*", dpayload as "DeviceDescriptor", mut error_p as "char*"] {
try {
payload->Evaluate(*impayload, *ompayload, dpayload);
} catch (std::exception& e) {
auto what = e.what();
error_p = new char[strlen(what)+1];
strcpy(error_p, what);
}
});
if !error_p.is_null() {
let msg = CStr::from_ptr(error_p).to_str().unwrap();
panic!("{}", msg);
}
};
}
pub fn forward(&self, input_data_map: &DataMap, output_data_map: &mut DataMap, device: DeviceDescriptor,
retain_backward_state_for: &VariableSet, exclude_gradients_for: &VariableSet) -> BackPropState {
let payload = self.payload;
let impayload = input_data_map.payload;
let mut ompayload = output_data_map.payload;
let dpayload = device.payload;
let bspayload = retain_backward_state_for.payload;
let egpayload = exclude_gradients_for.payload;
BackPropState { payload: unsafe {
let mut error_p: *mut i8 = ptr::null_mut();
let payload = cpp!([payload as "FunctionPtr", impayload as "unordered_map<Variable, ValuePtr>*", mut ompayload as "unordered_map<Variable, ValuePtr>*", dpayload as "DeviceDescriptor",
bspayload as "unordered_set<Variable>*", egpayload as "unordered_set<Variable>*", mut error_p as "char*"] -> BackPropStateInner as "BackPropStatePtr" {
try {
return payload->Forward(*impayload, *ompayload, dpayload, *bspayload, *egpayload);
} catch (std::exception& e) {
auto what = e.what();
error_p = new char[strlen(what)+1];
strcpy(error_p, what);
return nullptr;
}
});
if !error_p.is_null() {
let msg = CStr::from_ptr(error_p).to_str().unwrap();
panic!("{}", msg);
}
payload
}}
}
pub fn backward(&self, bpstate: &BackPropState, gradient_values: &DataMap, output_map: &mut DataMap) {
let payload = self.payload;
let bppayload = bpstate.payload;
let gpayload = gradient_values.payload;
let mut opayload = output_map.payload;
unsafe {
let mut error_p: *mut i8 = ptr::null_mut();
cpp!([payload as "FunctionPtr", bppayload as "BackPropStatePtr", gpayload as "unordered_map<Variable, ValuePtr>*", mut opayload as "unordered_map<Variable, ValuePtr>*", mut error_p as "char*"] {
try {
payload->Backward(bppayload, *gpayload, *opayload);
} catch (std::exception& e) {
auto what = e.what();
error_p = new char[strlen(what)+1];
strcpy(error_p, what);
}
});
if !error_p.is_null() {
let msg = CStr::from_ptr(error_p).to_str().unwrap();
panic!("{}", msg);
}
};
}
pub fn save(&self, path: &str) {
let path_ptr = path.as_ptr();
let path_len = path.len();
let payload = self.payload;
unsafe {
let mut error_p: *mut i8 = ptr::null_mut();
cpp!([payload as "FunctionPtr", path_ptr as "char*", path_len as "size_t", mut error_p as "char*"] {
try {
string path(path_ptr, path_ptr + path_len);
wstring wpath;
wpath.assign(path.begin(), path.end());
payload->Save(wpath);
} catch (std::exception& e) {
auto what = e.what();
error_p = new char[strlen(what)+1];
strcpy(error_p, what);
}
});
if !error_p.is_null() {
let msg = CStr::from_ptr(error_p).to_str().unwrap();
panic!("{}", msg);
}
}
}
pub fn load(path: &str, device: DeviceDescriptor) -> Function {
let path_ptr = path.as_ptr();
let path_len = path.len();
let dpayload = device.payload;
Function {payload: unsafe {
let mut error_p: *mut i8 = ptr::null_mut();
let payload = cpp!([path_ptr as "char*", path_len as "size_t", dpayload as "DeviceDescriptor", mut error_p as "char*"] -> FunctionInner as "FunctionPtr" {
try {
string path(path_ptr, path_ptr + path_len);
wstring wpath;
wpath.assign(path.begin(), path.end());
return Function::Load(wpath, dpayload);
} catch (std::exception& e) {
auto what = e.what();
error_p = new char[strlen(what)+1];
strcpy(error_p, what);
return nullptr;
}
});
if !error_p.is_null() {
let msg = CStr::from_ptr(error_p).to_str().unwrap();
panic!("{}", msg);
}
payload
}}
}
pub fn num_inputs(&self) -> usize {
let payload = self.payload;
unsafe {
cpp!([payload as "FunctionPtr"] -> usize as "size_t" {
return payload->Inputs().size();
})
}
}
pub fn inputs(&self) -> Vec<Variable> {
let payload = self.payload;
let num_inputs = self.num_inputs();
let mut output: Vec<VariableInner> = Vec::with_capacity(num_inputs);
unsafe {
output.set_len(num_inputs);
let mut ptr = output.as_mut_ptr();
cpp!([payload as "FunctionPtr", mut ptr as "Variable*"] {
auto outputs = payload->Inputs();
for (size_t i = 0; i < outputs.size(); i++) {
::new (&ptr[i]) Variable(outputs[i]);
}
})
}
output.into_iter().map(|x| Variable {payload: x}).collect::<Vec<Variable>>()
}
pub fn outputs(&self) -> Vec<Variable> {
let payload = self.payload;
let num_outputs = self.num_outputs();
let mut output: Vec<VariableInner> = Vec::with_capacity(num_outputs);
unsafe {
output.set_len(num_outputs);
let mut ptr = output.as_mut_ptr();
cpp!([payload as "FunctionPtr", mut ptr as "Variable*"] {
auto outputs = payload->Outputs();
for (size_t i = 0; i < outputs.size(); i++) {
::new (&ptr[i]) Variable(outputs[i]);
}
})
}
output.into_iter().map(|x| Variable {payload: x}).collect::<Vec<Variable>>()
}
pub fn replace_placeholders(self, placeholder_replacements: &ReplacementMap) -> Function {
let payload = self.payload;
let repl_payload = placeholder_replacements.payload;
Function {payload: unsafe {
let mut error_p: *mut i8 = ptr::null_mut();
let payload = cpp!([payload as "FunctionPtr", repl_payload as "unordered_map<Variable, Variable>*", mut error_p as "char*"] -> FunctionInner as "FunctionPtr" {
try {
return payload->ReplacePlaceholders(*repl_payload);
} catch (std::exception& e) {
auto what = e.what();
error_p = new char[strlen(what)+1];
strcpy(error_p, what);
return nullptr;
}
});
if !error_p.is_null() {
let msg = CStr::from_ptr(error_p).to_str().unwrap();
panic!("{}", msg);
}
payload
}}
}
pub fn num_parameters(&self) -> usize {
let payload = self.payload;
unsafe {
cpp!([payload as "FunctionPtr"] -> usize as "size_t" {
return payload->Parameters().size();
})
}
}
pub fn parameters(&self) -> Vec<Variable> {
let payload = self.payload;
let num_parameters = self.num_parameters();
let mut output: Vec<VariableInner> = Vec::with_capacity(num_parameters);
unsafe {
output.set_len(num_parameters);
let mut ptr = output.as_mut_ptr();
cpp!([payload as "FunctionPtr", mut ptr as "Variable*"] {
auto outputs = payload->Parameters();
for (size_t i = 0; i < outputs.size(); i++) {
::new (&ptr[i]) Variable(outputs[i]);
}
})
}
output.into_iter().map(|x| Variable {payload: x}).collect::<Vec<Variable>>()
}
}
impl Drop for Function {
fn drop(&mut self) {
let payload = self.payload;
unsafe {
cpp!([payload as "FunctionPtr"] {
payload.~FunctionPtr();
})
};
}
}
impl Drop for BackPropState {
fn drop(&mut self) {
let payload = self.payload;
unsafe {
cpp!([payload as "BackPropStatePtr"] {
payload.~BackPropStatePtr();
})
};
}
}