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
use linear_map::LinearMap;
use device::{IDevice, DeviceType};
use memory::MemoryType;
use std::marker::PhantomData;
use std::{fmt, mem, error};
pub type TensorDesc = Vec<usize>;
#[derive(Debug)]
pub struct SharedTensor<T> {
desc: TensorDesc,
latest_location: DeviceType,
latest_copy: MemoryType,
copies: LinearMap<DeviceType, MemoryType>,
phantom: PhantomData<T>,
}
pub trait ITensorDesc {
fn rank(&self) -> usize;
fn size(&self) -> usize;
fn dims(&self) -> &Vec<usize>;
fn dims_i32(&self) -> Vec<i32>;
fn default_stride(&self) -> Vec<usize> {
let mut strides: Vec<usize> = Vec::with_capacity(self.rank());
let dim_length = self.dims().len();
match dim_length {
0 => strides,
1 => {
strides.push(1);
strides
},
_ => {
let imp_dims = &self.dims()[1..dim_length];
for (i, _) in imp_dims.iter().enumerate() {
strides.push(imp_dims[i..imp_dims.len()].iter().fold(1, |prod, &x| prod * x))
}
strides.push(1);
strides
}
}
}
fn default_stride_i32(&self) -> Vec<i32> {
self.default_stride().iter().map(|&e| e as i32).collect()
}
}
pub trait IntoTensorDesc {
fn into(&self) -> TensorDesc;
}
impl IntoTensorDesc for () {
fn into(&self) -> TensorDesc {
Vec::with_capacity(1)
}
}
impl IntoTensorDesc for usize {
fn into(&self) -> TensorDesc {
vec![*self]
}
}
impl IntoTensorDesc for u32 {
fn into(&self) -> TensorDesc {
vec![*self as usize]
}
}
impl IntoTensorDesc for isize {
fn into(&self) -> TensorDesc {
vec![*self as usize]
}
}
impl IntoTensorDesc for i32 {
fn into(&self) -> TensorDesc {
vec![*self as usize]
}
}
impl IntoTensorDesc for Vec<usize> {
fn into(&self) -> TensorDesc {
self.clone()
}
}
impl<'a> IntoTensorDesc for &'a [usize] {
fn into(&self) -> TensorDesc {
From::from(self.to_owned())
}
}
impl IntoTensorDesc for (usize, usize) {
fn into(&self) -> TensorDesc {
vec![self.0, self.1]
}
}
impl IntoTensorDesc for (usize, usize, usize) {
fn into(&self) -> TensorDesc {
vec![self.0, self.1, self.2]
}
}
impl IntoTensorDesc for (usize, usize, usize, usize) {
fn into(&self) -> TensorDesc {
vec![self.0, self.1, self.2, self.3]
}
}
impl IntoTensorDesc for (usize, usize, usize, usize, usize) {
fn into(&self) -> TensorDesc {
vec![self.0, self.1, self.2, self.3, self.4]
}
}
impl IntoTensorDesc for (usize, usize, usize, usize, usize, usize) {
fn into(&self) -> TensorDesc {
vec![self.0, self.1, self.2, self.3, self.4, self.5]
}
}
impl ITensorDesc for TensorDesc {
fn rank(&self) -> usize {
self.len()
}
fn size(&self) -> usize {
match self.rank() {
0 => 1,
_ => self.iter().fold(1, |s, &a| s * a)
}
}
fn dims(&self) -> &Vec<usize> {
self
}
fn dims_i32(&self) -> Vec<i32> {
self.iter().map(|&e| e as i32).collect()
}
}
impl<T> SharedTensor<T> {
pub fn new<D: IntoTensorDesc>(dev: &DeviceType, desc: &D) -> Result<SharedTensor<T>, Error> {
let copies = LinearMap::<DeviceType, MemoryType>::new();
let copy = try!(Self::alloc_on_device(dev, desc));
let tensor_desc: TensorDesc = desc.into();
Ok(SharedTensor {
desc: tensor_desc,
latest_location: dev.clone(),
latest_copy: copy,
copies: copies,
phantom: PhantomData,
})
}
pub fn reshape<D: IntoTensorDesc>(&mut self, desc: &D) -> Result<(), Error> {
let new_desc: TensorDesc = desc.into();
if new_desc.size() == self.desc().size() {
self.desc = new_desc;
Ok(())
} else {
Err(Error::InvalidShape("Size of the provided shape is not equal to the old shape."))
}
}
pub fn resize<D: IntoTensorDesc>(&mut self, desc: &D) -> Result<(), Error> {
self.copies.clear();
self.latest_copy = try!(Self::alloc_on_device(self.latest_device(), desc));
let new_desc: TensorDesc = desc.into();
self.desc = new_desc;
Ok(())
}
fn alloc_on_device<D: IntoTensorDesc>(dev: &DeviceType, desc: &D) -> Result<MemoryType, Error> {
let tensor_desc: TensorDesc = desc.into();
let alloc_size = Self::mem_size(tensor_desc.size());
let copy = match *dev {
#[cfg(feature = "native")]
DeviceType::Native(ref cpu) => MemoryType::Native(try!(cpu.alloc_memory(alloc_size))),
#[cfg(feature = "opencl")]
DeviceType::OpenCL(ref context) => MemoryType::OpenCL(try!(context.alloc_memory(alloc_size))),
#[cfg(feature = "cuda")]
DeviceType::Cuda(ref context) => MemoryType::Cuda(try!(context.alloc_memory(alloc_size))),
};
Ok(copy)
}
pub fn sync(&mut self, destination: &DeviceType) -> Result<(), Error> {
if &self.latest_location != destination {
let latest = self.latest_location.clone();
try!(self.sync_from_to(&latest, &destination));
let mut swap_location = destination.clone();
let mut swap_copy = try!(self.copies.remove(destination).ok_or(Error::MissingDestination("Tensor does not hold a copy on destination device.")));
mem::swap(&mut self.latest_location, &mut swap_location);
mem::swap(&mut self.latest_copy, &mut swap_copy);
self.copies.insert(swap_location, swap_copy);
}
Ok(())
}
pub fn get(&self, device: &DeviceType) -> Option<&MemoryType> {
if &self.latest_location == device {
return Some(&self.latest_copy)
}
self.copies.get(device)
}
pub fn get_mut(&mut self, device: &DeviceType) -> Option<&mut MemoryType> {
if &self.latest_location == device {
return Some(&mut self.latest_copy)
}
self.copies.get_mut(device)
}
fn sync_from_to(&mut self, source: &DeviceType, destination: &DeviceType) -> Result<(), Error> {
if source != destination {
match self.copies.get_mut(destination) {
Some(mut destination_copy) => {
match destination {
#[cfg(feature = "native")]
&DeviceType::Native(ref cpu) => {
match destination_copy.as_mut_native() {
Some(ref mut mem) => try!(cpu.sync_in(&self.latest_location, &self.latest_copy, mem)),
None => return Err(Error::InvalidMemory("Expected Native Memory (FlatBox)"))
}
},
#[cfg(feature = "cuda")]
&DeviceType::Cuda(ref context) => {
match destination_copy.as_mut_cuda() {
Some(ref mut mem) => try!(context.sync_in(&self.latest_location, &self.latest_copy, mem)),
None => return Err(Error::InvalidMemory("Expected CUDA Memory."))
}
},
#[cfg(feature = "opencl")]
&DeviceType::OpenCL(ref context) => {
match destination_copy.as_mut_opencl() {
Some(ref mut mem) => try!(context.sync_in(&self.latest_location, &self.latest_copy, mem)),
None => return Err(Error::InvalidMemory("Expected OpenCL Memory."))
}
}
}
Ok(())
},
None => Err(Error::MissingDestination("Tensor does not hold a copy on destination device."))
}
} else {
Ok(())
}
}
pub fn remove_copy(&mut self, destination: &DeviceType) -> Result<(MemoryType), Error> {
if &self.latest_location == destination {
let first = self.copies.keys().nth(0).unwrap().clone();
try!(self.sync(&first));
}
match self.copies.remove(destination) {
Some(destination_cpy) => Ok(destination_cpy),
None => Err(Error::MissingDestination("Tensor does not hold a copy on destination device."))
}
}
fn return_copy(&mut self, dest: &DeviceType, dest_mem: MemoryType) {
self.copies.insert(dest.clone(), dest_mem);
}
pub fn add_device(&mut self, device: &DeviceType) -> Result<&mut Self, Error> {
if &self.latest_location == device {
return Err(Error::InvalidMemoryAllocation("Tensor already tracks memory for this device. No memory allocation."))
}
match self.copies.get(device) {
Some(_) => Err(Error::InvalidMemoryAllocation("Tensor already tracks memory for this device. No memory allocation.")),
None => {
let copy: MemoryType;
match *device {
#[cfg(feature = "native")]
DeviceType::Native(ref cpu) => copy = MemoryType::Native(try!(cpu.alloc_memory(Self::mem_size(self.capacity())))),
#[cfg(feature = "opencl")]
DeviceType::OpenCL(ref context) => copy = MemoryType::OpenCL(try!(context.alloc_memory(Self::mem_size(self.capacity())))),
#[cfg(feature = "cuda")]
DeviceType::Cuda(ref context) => copy = MemoryType::Cuda(try!(context.alloc_memory(Self::mem_size(self.capacity())))),
};
self.copies.insert(device.clone(), copy);
Ok(self)
}
}
}
pub fn latest_device(&self) -> &DeviceType {
&self.latest_location
}
pub fn capacity(&self) -> usize {
self.desc.size()
}
pub fn desc(&self) -> &TensorDesc {
&self.desc
}
pub fn mem_size(capacity: usize) -> usize {
mem::size_of::<T>() * capacity
}
}
#[derive(Debug, Copy, Clone)]
pub enum Error {
MissingSource(&'static str),
MissingDestination(&'static str),
InvalidMemory(&'static str),
InvalidMemoryAllocation(&'static str),
InvalidRemove(&'static str),
MemoryAllocationError(::device::Error),
MemorySynchronizationError(::device::Error),
InvalidShape(&'static str)
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::MissingSource(ref err) => write!(f, "{:?}", err),
Error::MissingDestination(ref err) => write!(f, "{:?}", err),
Error::InvalidMemory(ref err) => write!(f, "{:?}", err),
Error::InvalidMemoryAllocation(ref err) => write!(f, "{:?}", err),
Error::InvalidRemove(ref err) => write!(f, "{:?}", err),
Error::MemoryAllocationError(ref err) => write!(f, "{}", err),
Error::MemorySynchronizationError(ref err) => write!(f, "{}", err),
Error::InvalidShape(ref err) => write!(f, "{}", err),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::MissingSource(ref err) => err,
Error::MissingDestination(ref err) => err,
Error::InvalidMemory(ref err) => err,
Error::InvalidMemoryAllocation(ref err) => err,
Error::InvalidRemove(ref err) => err,
Error::MemoryAllocationError(ref err) => err.description(),
Error::MemorySynchronizationError(ref err) => err.description(),
Error::InvalidShape(ref err) => err,
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::MissingSource(_) => None,
Error::MissingDestination(_) => None,
Error::InvalidMemory(_) => None,
Error::InvalidMemoryAllocation(_) => None,
Error::InvalidRemove(_) => None,
Error::MemoryAllocationError(ref err) => Some(err),
Error::MemorySynchronizationError(ref err) => Some(err),
Error::InvalidShape(_) => None,
}
}
}
impl From<Error> for ::error::Error {
fn from(err: Error) -> ::error::Error {
::error::Error::Tensor(err)
}
}