sarek 0.1.0

A work-in-progress, experimental neural network library utilizing TensorFlow Keras
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
use {
    std::{
        fmt,
        marker::{
            PhantomData
        },
        ops::{
            Deref,
            DerefMut
        },
        slice
    },
    pyo3::{
        prelude::*,
        types::{
            PyDict,
            PyTuple
        },
        ToPyPointer
    },
    crate::{
        backend::{
            keras::{
                ffi
            }
        },
        core::{
            array::{
                ArrayRef,
                ArrayMut,
                ToArrayRef
            },
            data_source::{
                DataSource
            },
            data_type::{
                DataType,
                Type
            },
            indices::{
                ToIndices
            },
            shape::{
                Shape
            },
            type_cast_error::{
                TypeCastError
            }
        }
    }
};

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum ArrayOrder {
    RowMajor,
    #[allow(dead_code)]
    ColumnMajor
}

struct ArrayInit< 'a > {
    order: ArrayOrder,
    shape: Shape,
    kind: &'a str
}

fn dtype( py: Python, obj: &PyObject ) -> String {
    obj
        .getattr( py, "dtype" ).unwrap() // https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.dtype.html
        .getattr( py, "name" ).unwrap()
        .extract( py ).unwrap()
}

pub struct PyArray {
    obj: PyObject,
    shape: Shape,
    ty: Type
}

unsafe fn as_array_object( obj: &PyObject ) -> &ffi::PyArrayObject {
    &*(obj.as_ptr() as *const ffi::PyArrayObject)
}

unsafe fn as_array_object_mut( obj: &mut PyObject ) -> &mut ffi::PyArrayObject {
    &mut *(obj.as_ptr() as *mut ffi::PyArrayObject)
}

impl PyArray {
    pub(crate) unsafe fn from_object_unchecked( py: Python, obj: PyObject ) -> Self {
        let ty = match dtype( py, &obj ).as_str() {
            "float32" => Type::F32,
            "uint32" => Type::U32,
            "uint16" => Type::U16,
            "uint8" => Type::U8,
            "int32" => Type::I32,
            "int16" => Type::I16,
            "int8" => Type::I8,
            ty => unimplemented!( "Unhandled array type: {}", ty )
        };

        let internal = as_array_object( &obj );
        let slice = slice::from_raw_parts( internal.dims, internal.nd as usize );
        let shape = slice.into_iter().cloned().map( |size| size as usize ).collect();

        PyArray { obj, shape, ty }
    }

    fn as_array_object( &self ) -> &ffi::PyArrayObject {
        unsafe { as_array_object( &self.obj ) }
    }

    fn as_array_object_mut( &mut self ) -> &mut ffi::PyArrayObject {
        unsafe { as_array_object_mut( &mut self.obj ) }
    }

    pub(crate) fn new( py: Python, shape: Shape, ty: Type ) -> PyArray {
        PyArray::new_internal( py, ArrayInit {
            order: ArrayOrder::RowMajor,
            shape,
            kind: py_type_name( ty )
        })
    }

    fn new_internal( py: Python, init: ArrayInit ) -> PyArray {
        let np = py.import( "numpy" ).unwrap();

        let kwargs = PyDict::new( py );
        let shape = PyTuple::new( py, &init.shape );
        kwargs.set_item( "shape", shape ).unwrap();

        let order = match init.order {
            ArrayOrder::RowMajor => "C",
            ArrayOrder::ColumnMajor => "F"
        };

        kwargs.set_item( "order", order ).unwrap();
        kwargs.set_item( "dtype", init.kind ).unwrap();
        let obj = np.get( "ndarray" ).unwrap().call( (), Some( &kwargs ) ).unwrap().to_object( py );
        unsafe { PyArray::from_object_unchecked( py, obj ) }
    }

    /// Returns the number of dimensions for this array.
    pub fn dimension_count( &self ) -> usize {
        self.as_array_object().nd as _
    }

    /// Returns the shape of this array.
    pub fn shape( &self ) -> Shape {
        self.shape.clone()
    }

    pub fn reshape< S >( &self, py: Python, shape: S ) -> PyArray where S: Into< Shape > {
        let shape = shape.into();

        let current_shape = self.shape();
        assert_eq!(
            shape.product(),
            current_shape.product(),
            "Tried to reshape an PyArray from {} into {} where their products don't match ({} != {})",
            current_shape,
            shape,
            current_shape.product(),
            shape.product()
        );

        let shape = PyTuple::new( py, &shape );
        let obj = self.obj.getattr( py, "reshape" ).unwrap().call( py, (shape,), None ).unwrap().to_object( py );
        unsafe { PyArray::from_object_unchecked( py, obj ) }
    }

    /// Casts the array into a typed variant.
    pub fn into_typed< T: DataType >( self ) -> Result< TypedPyArray< T >, TypeCastError< Self > > {
        if self.ty == T::TYPE {
            Ok( TypedPyArray( self, PhantomData ) )
        } else {
            Err( TypeCastError {
                source: "an array",
                target: "a typed array",
                source_ty: self.ty.into(),
                target_ty: T::TYPE,
                obj: self
            })
        }
    }

    /// Checks whenever the array's elements are of the given type.
    pub fn data_is< T: DataType >( &self ) -> bool {
        self.ty == T::TYPE
    }

    pub fn data_type( &self ) -> Type {
        self.ty
    }

    /// Extracts a slice containing the whole array.
    pub fn as_bytes( &self ) -> &[u8] {
        unsafe {
            slice::from_raw_parts( self.as_array_object().data as *const u8, self.shape().product() * self.data_type().byte_size() )
        }
    }

    /// Extracts a mutable slice containing the whole array.
    pub fn as_bytes_mut( &mut self ) -> &mut [u8] {
        unsafe {
            slice::from_raw_parts_mut( self.as_array_object().data as *mut u8, self.shape().product() * self.data_type().byte_size() )
        }
    }

    pub(crate) fn as_py_obj( &self ) -> &PyObject {
        &self.obj
    }
}

pub struct PyArraySource {
    pointer: *mut u8,
    length: usize,
    shape: Shape,
    data_type: Type
}

unsafe impl Send for PyArraySource {}
unsafe impl Sync for PyArraySource {}

impl Drop for PyArraySource {
    fn drop( &mut self ) {
        unsafe {
            libc::free( self.pointer as *mut libc::c_void );
        }
    }
}

impl PyArraySource {
    // This is kinda sketchy, but it works I guess.
    pub fn new( mut array: PyArray ) -> Self {
        assert!( array.dimension_count() > 1 );

        let original_shape = array.shape();
        let length = original_shape.into_iter().next().unwrap();
        let shape = original_shape.into_iter().skip( 1 ).collect();
        let data_type = array.data_type();

        let pointer;
        {
            let array_object = array.as_array_object_mut();

            // Make sure the data is actually owned.
            assert_ne!( array_object.flags & ffi::NPY_ARRAY_OWNDATA, 0 );

            // And that the items themselves have no refcounts.
            assert_eq!( unsafe { &*array_object.descr }.flags & ffi::NPY_ITEM_REFCOUNT, 0 );

            {
                // Zero out the dimensions since we're taking its data away.
                let dims = unsafe { slice::from_raw_parts_mut( array_object.dims, array_object.nd as usize ) };
                for dim in dims.iter_mut() {
                    *dim = 0;
                }
            }

            pointer = array_object.data;
            unsafe {
                ffi::PyTraceMalloc_Untrack( ffi::NPY_TRACE_DOMAIN, pointer as libc::uintptr_t );
            }

            array_object.data = 0 as _;
        }

        PyArraySource {
            pointer,
            length,
            shape,
            data_type
        }
    }

    fn as_bytes( &self ) -> &[u8] {
        unsafe { slice::from_raw_parts( self.pointer, self.length * self.shape.product() * self.data_type.byte_size() ) }
    }
}

impl DataSource for PyArraySource {
    fn data_type( &self ) -> Type {
        self.data_type
    }

    fn shape( &self ) -> Shape {
        self.shape.clone()
    }

    fn len( &self ) -> usize {
        self.length
    }

    fn gather_bytes_into< I >( &self, indices: I, output: &mut [u8] ) where I: ToIndices {
        let input = self.as_bytes();
        let input = ArrayRef::new( self.shape(), self.data_type(), input );
        let mut output = ArrayMut::new( self.shape(), self.data_type(), output );
        output.gather_from( indices, &input );
    }
}

impl ToArrayRef for PyArraySource {
    fn to_array_ref( &self ) -> ArrayRef {
        ArrayRef::new( self.shape(), self.data_type(), self.as_bytes() )
    }
}

impl ToPyObject for PyArray {
    fn to_object( &self, py: Python ) -> PyObject {
        self.obj.clone_ref( py )
    }
}

fn py_type_name( ty: Type ) -> &'static str {
    match ty {
        Type::F32 => "float32",
        Type::I32 => "int32",
        Type::I16 => "int16",
        Type::I8 => "int8",
        Type::U32 => "uint32",
        Type::U16 => "uint16",
        Type::U8 => "uint8"
    }
}

pub struct TypedPyArray< T >( PyArray, PhantomData< T > );

impl< T: DataType > TypedPyArray< T > {
    pub fn new( py: Python, shape: Shape ) -> Self {
        let array = PyArray::new( py, shape, T::TYPE );
        TypedPyArray( array, PhantomData )
    }

    /// Converts this array to a `Vec`.
    pub fn to_vec( &self ) -> Vec< T > {
        self.as_slice().to_vec()
    }

    /// Extracts a slice containing the whole array.
    pub fn as_slice( &self ) -> &[T] {
        unsafe {
            slice::from_raw_parts( self.as_array_object().data as *const T, self.shape().product() )
        }
    }

    /// Extracts a mutable slice containing the whole array.
    pub fn as_slice_mut( &mut self ) -> &mut [T] {
        unsafe {
            slice::from_raw_parts_mut( self.as_array_object().data as *mut T, self.shape().product() )
        }
    }
}

impl< T > Deref for TypedPyArray< T > {
    type Target = PyArray;

    #[inline]
    fn deref( &self ) -> &Self::Target {
        &self.0
    }
}

impl< T > DerefMut for TypedPyArray< T > {
    #[inline]
    fn deref_mut( &mut self ) -> &mut Self::Target {
        &mut self.0
    }
}

impl< T: DataType > Into< Vec< T > > for TypedPyArray< T > {
    #[inline]
    fn into( self ) -> Vec< T > {
        self.to_vec()
    }
}

impl< 'a, T: DataType > Into< Vec< T > > for &'a TypedPyArray< T > {
    #[inline]
    fn into( self ) -> Vec< T > {
        self.to_vec()
    }
}

impl< 'a, T: DataType > Into< Vec< T > > for &'a mut TypedPyArray< T > {
    #[inline]
    fn into( self ) -> Vec< T > {
        self.to_vec()
    }
}

impl< T: DataType > Into< PyArray > for TypedPyArray< T > {
    #[inline]
    fn into( self ) -> PyArray {
        self.0
    }
}

impl< T: DataType + fmt::Debug > fmt::Debug for TypedPyArray< T > {
    fn fmt( &self, fmt: &mut fmt::Formatter ) -> fmt::Result {
        fmt.debug_list().entries( self.as_slice().iter() ).finish()
    }
}

impl< T > ToPyObject for TypedPyArray< T > {
    fn to_object( &self, py: Python ) -> PyObject {
        self.0.obj.clone_ref( py )
    }
}