leezu commented on a change in pull request #17841: Gluon data 2.0: c++ dataloader and built-in image/bbox transforms URL: https://github.com/apache/incubator-mxnet/pull/17841#discussion_r395921200
########## File path: python/mxnet/gluon/data/_internal.py ########## @@ -0,0 +1,348 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# coding: utf-8 +# pylint: disable=unnecessary-pass +"""C++ Datasets for common data formats.""" +from __future__ import absolute_import + +import sys +import ctypes +import numpy as np + +from .dataset import Dataset +from .sampler import Sampler +from ...base import _LIB +from ...base import c_str_array, mx_uint, py_str +from ...base import DatasetHandle, NDArrayHandle, BatchifyFunctionhandle +from ...base import mx_real_t +from ...base import check_call, build_param_doc as _build_param_doc +from ...ndarray import NDArray +from ...ndarray.ndarray import NDArrayBase +from ...ndarray.sparse import CSRNDArray +from ...ndarray import _ndarray_cls +from ...numpy.multiarray import _np_ndarray_cls +from ...ndarray import concat, tile +from ...util import is_np_array, default_array +from ...io import io as _io + + +class MXDataset(Dataset): + """A python wrapper a C++ dataset. + + Parameters + ---------- + handle : DatasetHandle, required + The handle to the underlying C++ Dataset. + + """ + def __init__(self, handle, **kwargs): + super(MXDataset, self).__init__() + self.handle = handle + self._kwargs = kwargs + # get dataset size + length = ctypes.c_uint64(0) + check_call(_LIB.MXDatasetGetLen(self.handle, ctypes.byref(length))) + self._len = length.value + + def __del__(self): + check_call(_LIB.MXDatasetFree(self.handle)) + + def __len__(self): + return self._len + + def __getitem__(self, idx): + orig_idx = idx + if idx < 0: + idx += self._len + # check bound + if idx < 0 or idx >= self._len: + raise IndexError("Index {} out of bound: (0, {})".format(orig_idx, self._len)) + create_ndarray_fn = _np_ndarray_cls if is_np_array() else _ndarray_cls + output_vars = ctypes.POINTER(NDArrayHandle)() + num_output = ctypes.c_int(0) + check_call(_LIB.MXDatasetGetItems(self.handle, + ctypes.c_uint64(idx), + ctypes.byref(num_output), + ctypes.byref(output_vars))) + out = [create_ndarray_fn(ctypes.cast(output_vars[i], NDArrayHandle), + False) for i in range(num_output.value)] + for i in range(num_output.value): + if out[i].size == 1: + out[i] = out[i].asnumpy() + if len(out) > 1: + return tuple(out) + return out[0] + + +class MXSampler(Sampler): + def __init__(self, name, **kwargs): + try: + creator = getattr(_io, name) + except AttributeError: + raise ValueError('{} is not a valid MXDataIter class'.format(name)) + self._iter = creator(**kwargs) + + def __len__(self): + try: + size = len(self._iter) + except TypeError: + raise TypeError('Iterator {} does not provide length info'.format(self._iter)) + return size + + def __iter__(self): + for item in self._iter: + ret = item.data[0].asnumpy().flatten().tolist() + pad = item.pad + if pad > 0: + # remove padded values + ret = ret[:-pad] + elif len(ret) == 1: + ret = ret[0] + yield ret + self._iter.reset() + + +class MXBatchifyFunction(object): + def __init__(self, handle, **kwargs): + self._kwargs = kwargs + self.handle = handle + + def __del__(self): + if self.handle is not None: + check_call(_LIB.MXBatchifyFunctionFree(self.handle)) + + def __getstate__(self): + """Override pickling behavior.""" + # pickling pointer is not allowed + d = dict({'creator_name': self._kwargs['creator_name'], + '_kwargs': self._kwargs}) + return d + + def __setstate__(self, d): + """Restore from pickled.""" + creator = d['_kwargs']['creator_name'] + d['_kwargs'].pop('creator_name') + other = getattr(sys.modules[__name__], creator)(**d['_kwargs']) + self.handle = other.handle + self._kwargs = other._kwargs + other.handle = None + + Review comment: inconsistent whitespace ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] With regards, Apache Git Services
