mirror of
https://github.com/RustyRaptor/incubator-mxnet.git
synced 2026-12-04 00:05:18 -07:00
* [WIP] Sparse Tensor (#5800)
* squash
merge with 38f7c55840
compiles on GPU
update check alloc:
Checkpoint. Pass elem-sum gpu test
bug fix for copyfromto. sparse sgd test pass on gpu
inefficient implementation for csr copy
update submodule
fix lint
Simple bind with infer storage type (#32)
* Symbol binding for sparse tensor development. (#31)
* Initial checkin
* Add init functions for simple bind in graph_executor
* Add simple_bind c_api
* Add simple bind c-api
* Assign zeros to in_args, arg_grads, and aux_states
* Add simple_bind2 python interface
* Fix python interface bugs
* Interface changes
* Fix
* Fix core dump
* Add bind_ith_exec c_api
* Change simple_bind2
* Fix seg fault
* Finish simple_bind
* Change _bind_ith_exec
* Refactor simple_bind initialization flow for bind
* Consolidate bind and simple_bind graph init flow
* Fix bug
* Clean up
* Add comments
* Clean up
* Clean up
* Minor correction
* Rename APIs in graph executor
* Refactor
* Rebase
* Delete deprecated functions
* Move more front-end work to backend
* Bug fix
* Fix failed tests
* Minor fix
* Fix lint
* Fix lint
* Revert unnecessary changes
* Revert
* Revert
* Clean up
* Fix lint
Conflicts:
python/mxnet/symbol.py
src/executor/graph_executor.cc
* Add inferstorage to graph executor
* re-enable tests for sparse embedding with simple_bind
* type switch fix in sparse embedding"
;
change `default` to `default_storage` for cast storage op (#33)
* change default to default_storage
* disable cpp test build temporarily
attempt to fix windows build error, and fix lint (#34)
update nnvm submodule (#37)
Scipy build (#38)
* update nnvm submodule
* add scipy pip install for dockerfile
Python3 unit tests (#39)
* change xrange to range for python3 compatiblity"
* remove more xrange from tests
replace long with int for python3 (#40)
fix the rest of TShape constructor errors (#41)
fix lint (#42)
fix wrong usage of mshadow::Shape1" (#43)
implementation for Csr slice on cpu (#36)
* CPU implementation for CSR
remove seg_len from csr slice
add some docs for slice csr
change indptr, values, etc to be private member
bug fix in sparse embedding
update nnvm submoduel
fix lint
update unit test for sparse nd"
* add const for SliceCsrIndPtr kernel
Fix sparse dot according to the new RSP definition (#35)
* Fix csr dot dns
* Fix sparse dot
* Add fallback and test cases for dot(csr, dns)=dns
* Add int type switch
* Fix
* Fix
* Fix
update mshadow submodule (#44)
Fix dns to rsp (#46)
fix lint (#47)
add runtime storage fallback detection" (#48)
* add runtime storage fallback detection"
* replace cast storage ex with cast storage impl
Fm example (#45)
* update csr slice logic to avoid confusion. add more exmaples.
* add hint to module.update
* more testcases(fallback) for sparse_nd
* add to_csr() and to_rsp() method. More unit test (fallback now)
* add fm test. fix lint
* register sparse sgd under Optim.SGD
* update dmlc-core submoduel
* change indptr to _indptr temporarily. add const ref to fname
fix lint
fix lint; (#51)
Guard gpu cast storage (#50)
* Clean up
* Fix typo
Rearrange unit test files (#52)
fix lint. add scipy for python_test. fix scipy.sparse import error. fix truediv for python3
fix travis test (#54)
* remove pyc files
* add verbose for travis nosetests
cleanup some testing code and enums (#57)
* update Makefile
* refactor test_sparse_operator
* change `default_storage` back to `default`
* remove unused cpp tests
port libsvm parser to mxnet as libsvm iter (#55)
* copied csv iter to libsvm iter
test
libsvm iter draft
handle round batch == false for csr batch loader
code refactoring
add get stype, shape interface to iiter
separate class for sparse iter
add missing file
fix mem corruption'
rename variables
add comments
also read label from libsvm
add test. update docs. update submodule
Conflicts:
python/mxnet/sparse_ndarray.py
* update submodule
* fix lint
* update test
* revert naming change
add benchmark scritp for dot (#59)
* add benchmark scritp for dot
add gpu option for bench
add get_data funciton for benchmark
print t_sparse, too;
add comment
change nnz to dnesity
add backward
* add comment
update fm test (#62)
introduce CSRNDarray and rowsparseNDarray to python frontend api (#58)
* introduce CSRNDarray and rowsparseNDarray to python frontend api
* temporarily disable fm_module test
fix lint (#64)
fix typo. disable libsvm io test (#65)
Improve dot (#61)
* Init checkin
* Fix
* Adjust dot parallelization methods
* Set num_omp_threads for benchmark from command line
* Fix omp thread number
* Clean up
* Add scipy as dot baseline
* Fix format
sparse_retain op (#66)
* Initial checkin
* Fix bugs
* Add unit test for sparse_retain
* Add example and modify test
add storage cast for outputs that have non-default storage (#67)
fix gpu build (#69)
Fix test_sparse_retain python3 issue (#68)
revert nnvm version
* draft for sgd rsp rsp (#75)
support sgd(rsp, rsp)
support dot(csr, rsp) when rsp is full
add ref to const ndarray params
support sparse embedding with rsp weight'
fix lint
modify embedding backward to produce dense grad
remove invalid_rid for rsp->dns
remove previous embedding op changes
pass sparse embedding test
add STORAGE_TYPE_ASSIGN_CHECK
remove backward storage infer
* fix lint (#78)
* fix lint (#79)
* serial elemwise sum impl (#80)
update module kvstore interface
add other missing params and functions
revert some interface changes
revert some more changes
reomve explicit casting for gradients on kvstore
update Comm interface
update fm example
Conflicts:
python/mxnet/model.py
python/mxnet/ndarray.py
* bug fix for initializing module with row_sparse weight (#81)
* bug fix for initializing module with row_sparse weight
* update log message
* Sparse ndarray serialization and deserialization (#77)
* Initial checkin
* Add unit tests
* Fix lint
* Fix lint (#84)
* Sgd with row_sparse weight, dns gradient (#83)
* sgd rsp dns draft
* support sgd_mom(rsp, dns, rsp)
* update doc
* remove cast storage for kv updater
* code refactoring
* update mshadow version (#88)
* csr slice bug fix (#90)
* benchmark dot code refactor (#87)
* q^x6x add some code in benchmark
* refactor
* minor fixes
* fix
* lint fix
* Add unit test (#91)
* add unittest
* minor fix
* remove commented lines
* change test func name
* add test rsp
* kvstore push row sparse (#93)
* Add multi-thread cpu elemwise sum for rsps
* Minor fix
* Add flag to switch between serial and multi-thread kvstore push
* Fix lint in sparse_ndarray.py
* Revert "Fix lint in sparse_ndarray.py"
This reverts commit d7225ec267a1e8c0c3c8074d25af5844ed39a14d.
* Fix ndarray init in copy(ctx)
* Add env var to control the flow of serial/parallel reduce
* Refactor
* Fix copy ndarray bug
* Fix lint
* Refactor
* Fix windows openmp build failure (#94)
* update mshadow submoduel (#95)
* Revert "update mshadow submoduel (#95)" (#96)
This reverts commit 1a129e4cc39514a6c7b3aa1189949969b818aec3.
* Refactor sparse tensor code (#99)
* Initial checkin test_sparse_ndarray passes
* Fix test failure
* Clean up
* Clean up
* Move init backend op to ndarray_utils
* Fix lint
* Eliminate circular dependency on headers
* More refactor
* Fix gpu build and consolidate Slice for dense and sparse
* Clean up
* More refactor
* Clean up
* Fix gpu build
* Fix comment
* fix pylint (#100)
* Fix refactor sparse gpu test (#104)
* Fix gpu build
* Fix
* Fix gpu test failure
* change idx types from int32 to int64 (#101)
Conflicts:
python/mxnet/test_utils.py
tests/python/unittest/test_sparse_operator.py
update mshadow submodule
fix extra quotes in test script
change indptr type to int64
better err message for rsp"
* revert LOG(DEBUG) change (#105)
* fix undefined zeros in optimizer.py (#106)
* move init dns zeros to init_op.h for kvstore to use (#107)
* Refactor cast storage (#109)
* Refactor cast_storage
* Add cast_storage cc and cu files
* Remove redundant comments
* Replace std::accumulate with ParallelAccumulate
* Clean up
* Fix windows build
* Rowsparse kv (#111)
* update kvstore unit test
Conflicts:
tests/python/unittest/test_kvstore.py
update model/module.py
Conflicts:
python/mxnet/model.py
python/mxnet/module/module.py
fix lint
resolve conflict
remove int keys in kvstore
update cast to str function
* fix failed dist_sync_kv test
* bug fix in comm to ensure merged gradient is of the right type
bug fix in comm
* row sparse dist kvstore draft (push only)
row_sparse pull
* add ndarray row sparse shared mem constructor
* code refactoring
* add test for row_sparse weight
bug fix for kv server slicing
add async support
rsolve race condition in kvstore
* resolve error after reb ase
* fix lint (#113)
* rename some python funciton (#114)
* _to_rsp
* _to_csr. raise NotImplementedError
* todense
* fix lint (#115)
enable libsvm uniit test (#6839)
remove shared mem slice for csr
add csr ndarray iter test
make osx nose test verbose
disable libsvm iter test
Move InferAttr to mxnet from nnvm (#6830)
* Move InferAttr to mxnet from nnvm
Replace nnvm infer attr functions in c_api
Initial checkin
Clean up
Remove nnvm namespace for FInferShape, FInferType, and FInferStorageType
Add new interface for InferStorageType
Revert "Remove nnvm namespace for FInferShape, FInferType, and FInferStorageType"
This reverts commit 8aedf054bfe29b076c6fcb6f54d996fd2752e4de.
Fix and clean up
Fix lint
Add nnvm changes
Change infer function interface to accept only rvalue reference of graph
Clean up
Flush commits to show up in PR
Add error handling for storage type inference failure
Update nnvm
* Fix pylint
Change idx type switch for aux data (#6860)
* Change idx type switch for aux data
* Add mshadow commit
Sparse dot enhancement (#6842)
* Initial checkin
Initial checkin
Fix sparse dot test
Fix unitest and add fallback for sparse dot
* Add benchmark code
* Revert "Add benchmark code"
This reverts commit be009fe4c5a2a321aa92e99ac6e9cc511198c742.
* Fix bug
* Fix storage shape
* Remove unnecessary test code
* Use idx type switch
Implement dot(csr, rsp)=dns and dot(csr.T, rsp)=rsp and refactor (#6902)
* Initial checkin
Add dot(csr.T, rsp)=rsp2
Add infer storage for dot(csr, rsp)=dns and dot(csr.T, rsp)=rsp2
* Fix comments
* Replace std::lower_bound with own impl for gpu use too
* Add time profiling
* Revert "Add time profiling"
This reverts commit 8f5bb982867731df0305148b1b150b05661f8529.
* Move dot and batch_dot to a single file
* Move dot gpu impl to a .cuh file
* More refactor
* Fix include error
LibsvmIter fix (#6898)
* fix bug in libsvm iter which causes mem corruption
* add test for news dataset
* fix wrong path in test
* fix import error for urllib
* update url
* replace bz command with bz module
Optimized gpu dot kernels (#6937)
* pulled update to mshadow
* mshadow update
* added optimized gpu kernels for dot(csr,dns)=dns and dot(csr.T,dns)=dns, and unit test
* added __syncwarp to vector kernel and reduced number of writes to shared memory
Refactor sparse tensor code (#6955)
* Save stype in frontend to avoid c-api call for stype
* Change storage_type to stype
* Revert "Change storage_type to stype"
This reverts commit 90db7d18b624f3ee4ffd37bf5680205e77ca2763.
* Revert "Revert "Change storage_type to stype""
This reverts commit 09328382e926b92a42ba5b3df6f169f825975d88.
Move ndarray.py, sparse_ndarray.py, ndarray_utils.py, and _ndarray_internal to ndarrary folder
More refactor
Move elementwise sum for rsp to ndarray_function.cc
Remove unnecessary import in ndarray module
Fix pylint
Remove redundant code
Remove _stype from slots
Fix cpp-package build error caused by the change to imperative invoke interface
Use relative import
Remove print line
Rename _ndarray_internal.py to _internal.py
* Relaunch test...
minor bug fix in warp synchronous code (#7029)
* move storage type vector from nnvm to mxnet (#7054)
* move storage type vector from nnvm to mxnet
* update nnvm
* update nnvm
* Improve copy sparse tensors (#7003)
* Use cast_storage when copying ndarrays of different stypes on same context
* Relaunch test
* fix failed tests. add back 64bit support for dot
fix lint
* bug fix for IdentityComputeRsp
* fix lint
fix lint
fix lint
* add data partition for libsvm iter (#7027)
* remove sparse embedding (#7165)
* fix ndarray namespace
* remove untested gpu operators (#7172)
* skip sparse dot gpu tset. add sparse_nd_zeros gpu test
* remove sparse_retain gpu
Conflicts:
tests/python/gpu/test_operator_gpu.py
* Fix ndarray aux data issue (#7098)
* Fix getting sparse ndarray data/aux_data issues
* Add tests for func csr and row_sparse
* Make get/set data/aux_data thread safe
* Fix a bug
* Fix typo and comment
* More comments
* Correct comment
Conflicts:
tests/python/gpu/test_operator_gpu.py
* Support K-dimensional row-sparse tensor (#7179)
* remove check for k dimensional rowsparse tensor
* change var name for rsp sgd operator
* add checks for sparse dot
* bug fix for kdim rowsparse cast storage cpu
* update IdentityLikeRhsComputeEx interface
* remove set_storage_shape from ndarray. support elemwise_add with kdim row_sparse tensor
* use get_with_shape instead of reshape
* update according to comments
Conflicts:
src/operator/tensor/elemwise_unary_op.h
* Improve sparse ndarray error message (#7181)
* add test for broadcast_to
* add comments
Conflicts:
python/mxnet/base.py
* construct row_sparse ndarray for dist-async
fix bug in rsp add
rsp sync push
race condition for push
fix bug in rsp pull. refactor test
cleanup comments
refactor dist server
fix lint
fix storage shape issue with the new ndarray constructor
data sharding draft;
fix lint. add comment
add support for zeros gradients
use std::upper_bound/lower_bound
remove special init function for rowsparse dist kvstore
temporary support for inplace operators for sparse
add test. fix return type
store kRowSparseNDArray in kv server
remove fcomp_ex sgd with dns weight and rsp gradient
bug fix in sparse retain
sparse pull c_api
revise rowsparse pull api
use engine to compute unique to ensure thread safety
add rowsparse pull to dist-kv
fix lint
add example for rsp_pull
remove name2idx;
add sparse_pull_dict param to module
fix unit test and c rowid conversion
support str key type in kvstore (#6765)
* update kvstore unit test
* update model/module.py
* fix lint
* remove int keys in kvstore
* update cast to str function
* remove _cast_to_str_keys
* fix lint
* always cast to str
Conflicts:
include/mxnet/c_api.h
include/mxnet/kvstore.h
python/mxnet/kvstore.py
python/mxnet/model.py
python/mxnet/module/module.py
src/c_api/c_api.cc
src/kvstore/kvstore_local.h
tests/python/unittest/test_kvstore.py
update module API for other submodules
update stypes in kvstore after refactoring
change type of size from size_t to int64_t
add sparse linear regression example
remove sparse_pull_dict from module
fix init_optim for seq_module. update sparse example
resolve conflict for binary add rsp rsp
Conflicts:
python/mxnet/kvstore.py
tests/python/unittest/test_kvstore.py
* fix DotCsrRspRspImpl error message (#7191)
* GPU implementation of cast_storage (dense to csr) (#7081)
* Added gpu implementation for cast_storage dense to csr, unit tests, and benchmark. Additionally, cast_storage interface change to accommodate the need of temporary storage in cuda kernels.
* fixed whitespace
* minor unittest update
* removed whitespace
* add cast storage benchmark params info
Conflicts:
tests/python/gpu/test_operator_gpu.py
* Sparse square sum (#7206)
* Add square_sum op
* Add unit test and fix check_numeric_gradient
* Add .cu file and example
* Fix lint
* Remove gpu registration
* Use square_sum in test_module_fm
* Modify and Add documentation for mx.nd.zeros (#7197)
* Modify and Add documentation for mx.nd.zeros
* Change context to cpu
* Change stype to optional
* Change ordering and remove optional for _zeros_sparse_ndarray
* Expose kWriteInplace for imperative execution (fcompute_ex and fstatefulcompute_ex) (#133)
* expose kWriteInplace to FComputeEx and FStatefulComputeEx
* refactor ccode
* remove duplicated test
* Operator add_n for row sparse ndarrays (#7244)
* Add add_n op for row-sparse ndarrays and identity FComputeEx
* Fix bug in square_sum
* Remove test_cast_storage_ex from gpu test since it's not implemented yet
* Fix according to the cr
Conflicts:
src/operator/tensor/elemwise_sum.cc
src/operator/tensor/elemwise_unary_op.cc
tests/python/gpu/test_operator_gpu.py
resolve conflict
* GPU implementation of cast_storage (dense to rsp) (#7223)
* CastStorageDnsRsp GPU Implementation
* updating function doc and some variable types and names
* adding cuda_get_device_prop() util function
* added rand_shape function for n-dimensional tensors
* updated cast storage unit test
* added dns_to_rsp to cast storage benchmark script
* removing redundant unit test
* fix lint
* minor change in benchmark script
* fix lint
* correct function description
* change storage_type to stype
* changed scope of using namespaces
* changed variable types from index_t to dim_t
* resolve merge conflict in ndarray.load
* Improve StatefulOp/FCompute storage fallback (#134)
* test for fcomp fallback
add storage fallback test and optimize fallback logic
rename function, add comments
use std size()
* add autograd test with sparse inputs
* update sparse ndarray api (#139)
* support mx.nd.empty for sparse ndarray
Change SparseNDArray to BaseSparseNDArray
support mx.nd.array with BaseSparseNDArray inputs. Update documentation with explicit subclasses of NDArrays
Conflicts:
python/mxnet/ndarray/__init__.py
python/mxnet/ndarray/ndarray.py
python/mxnet/ndarray/sparse_ndarray.py
tests/python/unittest/test_sparse_ndarray.py
* fix print msg in test
* Handle ograd_stype='row_sparse' for square_sum backward (#143)
* Add one kernel for square_sum backward pass to take rsp ograd
* Add kNullOp and change to use type_assign in infer stype fallback
* Sparse retain improvement (#138)
* Add one more kernel for sparse retain
* Fix compile
* Change STORAGE_TYPE_ASSIGN_CHECK to type_assign for fallback
* Fix
* Add gpu compile
* ignoring variables in SimpleBind that is used on python's sparse branch for now. (#135)
* add bias term to fm test (#145)
* update ndarray.nd, remove `invoke` from excluded members (#137)
remove __weakref__ from SparseNDArray
add data indice to doc
revert dlpack update
revert mxdoc changes
move methods from BaseSparseNDarray to csrndarray and rwosparse ndarray
* support storage fallback with mutable inputs (#147)
* include mutatable inputs in storage fallback. refactor executor
add fallback test for rms prop and adam
fix lint
fix lint
fix test in optimizer
* update according to comments
* fix unit tests
* fix gpu compilation err
* Code changes based on reviews (#144)
* code changes according to review comments
remove executor debug. add doc to optimizer
update sparse sgd test
add dtype option to rand_sparse_ndarray
* overhauled reqs for sparse operators
* patch FCompExFallback with mutable inputs. update test_optimizer with more fallback cases
* change executor debug macro to env var
* add comment
* update doc
* change ndarray.aux_shape() to return const reference
* remove todense to_rsp to_csr. replace with tostype
* replace manual calls to cast_storage with tostype
* disable gpu fallback test for optimizer
* fix lint
* add backward pass for cast_storage. refactor cast_storage test
* rand_sparse_ndarray bug fix
* fix cast_storage for gpu
* disable csr test for fp16
* update row sparse ndarray doc
* update doc
* small edits according to reviews (#151)
* fix lint (#152)
* add license to all new files in sparse brnach (#154)
* Allocate temp data on the fly for some casting operations (#149)
* fix utf8 encoding in sparse ndarray
* Extending the GPU dot operator (#7226)
* Added GPU DotCsrRspDnsImpl declaration and TODOs
* cleaning up function doc, variable types, and code-style
* minor bug fixes
* enable GPU dot(csr,rsp)=dns unit test
* extend sparse dot unit test
* adding GPU impl of DotCsrRspDns and its kernels
* add TODO
* changed variable types from index_t to dim_t
* fix function description
* added DotCsrRspRspImpl and its kernels (baseline, functionality)
* added DotCsrDnsRspImpl and its kernels (baseline, functionality); plus code documentation
* refactored dot benchmark
* optimized DotCsrTransDnsRsp GPU kernel
* change of dot impl interface to include OpContext, for temp storage
* removing __device__ flag from CPU kernels
* minor fixes and changing variable data types
* minor fixes based on code reviews
Conflicts:
benchmark/python/sparse_op.py
tests/python/gpu/test_operator_gpu.py
tests/python/unittest/test_sparse_operator.py
* Add get_synthetic_dataset function to util (#146)
* Add get_synthetic_datasets
* Move to test_utils
* Remove _get_uniform_dataset
* Move validation to its own function
* Refactor the validation code for csr generation
* Make test_powerlaw a nested function
* Change SparseNDArray to CSRNDArray
* Merge with dtype specific changes in test_utils
* temporary fix for batch norm storage fallback (#156)
* support random_uniform/normal/gamma with row_sparse output (#155)
* add support for initilazer with rowsparse output
* add scalar assignment to row_sparse
* add setitem test to gpu
* Revert "add scalar assignment to row_sparse"
This reverts commit 8aef7a56c44038f67bbec93811977ea2f9fa3c30.
* Revert "add setitem test to gpu"
This reverts commit 3b969ac0980e8d7166a1cf46878ed2bd457986ed.
* Square sum backward support one more case (#161)
* Add documentation for sparse ops (#148)
* draft doc for sparse op
* add more stype doc for operators
* add doc for cast_storage
* see also cast_storage. remove base sparse ndarray. fix aux_types comemtn
* grammar / spelling fix
* A few fixes (#163)
* fix batch norm gpu kernel. register random operators on gpu
* register sparse random op on gpu, too
* Minor fixes sparse ops (#160)
* change CPU kernel inline directives, data types, and function doc
* update dot dtype switch to use 32 and 64bit floating point only
* use type_assign instead of STORAGE_TYPE_ASSIGN_CHECK
* added tensor_util-inl.cuh file for common tensor operator GPU kernels
* sparse Adam optimizer (#164)
* add sparse adam
* register gpu op
* add comments
* cr comments
* kvstore.row_sparse_pull for GPU and end-to-end benchmark: CPU vs. multi-GPUs (#150)
* Add gpu support for BroadcastRowSparse
* Fix bugs
* Add benchmark script
* Increase output dim size
* Update weight on CPU using single GPU for sparse tensors
* More fix
* Optimize sparse_retain for special case
* Change row sparse pull locations
* Avoid sparse retain on cpu if possible
* Use acc for metric
* Fix misc
* fix bug in adam update (#167)
fix a bug in adam update
* change sparse example from regression to classification (#165)
* fix python import (#166)
* Add waitall to sparse_end2end.py (#169)
* Add waitall()
* Add dummy metric option
* Add header license
* Dot script changes (#159)
* Add get_synthetic_datasets
* Move to test_utils
* Remove _get_uniform_dataset
* Move validation to its own function
* Refactor the validation code for csr generation
* Make test_powerlaw a nested function
* Change SparseNDArray to CSRNDArray
* Refactoring changes to dot.py
* Fix mxnet test_utils changes
* Remove pdb statement
* Add distribution parameter
* Refactor benchmarking script
* Remove unused code
* Make style changes and remove unused code
* Change typo in comment
* Add transpose support
* Change typo
* 4 decimal points needed for density
* Add rsp support for real datasets
* Correct variable name mini_file_name
* Move wait_to_read outside if
* Seperate out scipy and mxnet logic in bench_dot
* Fix lhs_trans issue
* Move transpose outside measure_cost
* Compute transpose inside measure_cost
* Remove unused variables
* Transpose only if trans_lhs (#171)
* fix default val for distribution (#172)
* fix lint (#175)
* avoid cast_storage in dist-kvstore-server (#174)
* avoid cast_storage in dist-kvstore-server
* add stream arg to mshadow;;copy
* fix copy order
* Add sparse namespace to ndarray and symbol (#177)
* Register dot, cast_storage, and sparse_retain under mxnet.ndarray.sparse
* Add sparse to symbol namespace
* Delete commented code
* mv sparse_ndarray.py sparse.py
* Clean up
* Change docstring
* changes based on code reviews (#176)
* remove scipy dependency
* move kvstore checks to backned
* add const to lambda
* temp fix to ndarray.md (#178)
* Fix sparse namespace pylint (#179)
* add comments and error msg (#181)
* add clarification for csr (#182)
* add clarification for csr
* cr comments
* revert change in test util (#183)
* fix amalgamation (#184)
* fix lint
924 lines
33 KiB
Python
924 lines
33 KiB
Python
# 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
|
|
"""Sparse NDArray API of MXNet."""
|
|
|
|
from __future__ import absolute_import
|
|
from __future__ import division
|
|
try:
|
|
from __builtin__ import slice as py_slice
|
|
except ImportError:
|
|
from builtins import slice as py_slice
|
|
|
|
import ctypes
|
|
import warnings
|
|
|
|
import os as _os
|
|
import sys as _sys
|
|
|
|
# import operator
|
|
import numpy as np
|
|
from ..base import NotSupportedForSparseNDArray
|
|
from ..base import _LIB, numeric_types
|
|
from ..base import c_array, mx_real_t
|
|
from ..base import mx_uint, NDArrayHandle, check_call
|
|
from ..context import Context
|
|
from . import _internal
|
|
from .ndarray import _DTYPE_NP_TO_MX, _DTYPE_MX_TO_NP
|
|
from .ndarray import _STORAGE_TYPE_STR_TO_ID
|
|
from .ndarray import NDArray, _storage_type
|
|
from .ndarray import zeros as _zeros_ndarray
|
|
from .ndarray import array as _array
|
|
from . import cast_storage
|
|
from . import slice as nd_slice
|
|
|
|
# Use different verison of SymbolBase
|
|
# When possible, use cython to speedup part of computation.
|
|
# pylint: disable=unused-import
|
|
try:
|
|
if int(_os.environ.get("MXNET_ENABLE_CYTHON", True)) == 0:
|
|
from .._ctypes.ndarray import _set_ndarray_class
|
|
elif _sys.version_info >= (3, 0):
|
|
from .._cy3.ndarray import _set_ndarray_class
|
|
else:
|
|
from .._cy2.ndarray import _set_ndarray_class
|
|
except ImportError:
|
|
if int(_os.environ.get("MXNET_ENFORCE_CYTHON", False)) != 0:
|
|
raise ImportError("Cython Module cannot be loaded but MXNET_ENFORCE_CYTHON=1")
|
|
from .._ctypes.ndarray import _set_ndarray_class
|
|
# pylint: enable=unused-import
|
|
|
|
|
|
__all__ = ["_ndarray_cls", "csr_matrix", "row_sparse_array",
|
|
"BaseSparseNDArray", "CSRNDArray", "RowSparseNDArray"]
|
|
|
|
|
|
_STORAGE_AUX_TYPES = {
|
|
'row_sparse': [np.int64],
|
|
'csr': [np.int64, np.int64]
|
|
}
|
|
|
|
|
|
def _new_alloc_handle(stype, shape, ctx, delay_alloc, dtype, aux_types, aux_shapes=None):
|
|
"""Return a new handle with specified storage type, shape, dtype and context.
|
|
|
|
Empty handle is only used to hold results
|
|
|
|
Returns
|
|
-------
|
|
handle
|
|
A new empty ndarray handle
|
|
"""
|
|
hdl = NDArrayHandle()
|
|
aux_type_ids = [int(_DTYPE_NP_TO_MX[np.dtype(aux_t).type]) for aux_t in aux_types]
|
|
aux_shapes = [(0,) for aux_t in aux_types] if aux_shapes is None else aux_shapes
|
|
aux_shape_lens = [len(aux_shape) for aux_shape in aux_shapes]
|
|
aux_shapes = sum(aux_shapes, ())
|
|
num_aux = mx_uint(len(aux_types))
|
|
check_call(_LIB.MXNDArrayCreateSparseEx(
|
|
ctypes.c_int(int(_STORAGE_TYPE_STR_TO_ID[stype])),
|
|
c_array(mx_uint, shape),
|
|
mx_uint(len(shape)),
|
|
ctypes.c_int(ctx.device_typeid),
|
|
ctypes.c_int(ctx.device_id),
|
|
ctypes.c_int(int(delay_alloc)),
|
|
ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])),
|
|
num_aux,
|
|
c_array(ctypes.c_int, aux_type_ids),
|
|
c_array(mx_uint, aux_shape_lens),
|
|
c_array(mx_uint, aux_shapes),
|
|
ctypes.byref(hdl)))
|
|
return hdl
|
|
|
|
|
|
class BaseSparseNDArray(NDArray):
|
|
"""The base class of an NDArray stored in a sparse storage format.
|
|
|
|
See CSRNDArray and RowSparseNDArray for more details.
|
|
"""
|
|
|
|
def __iadd__(self, other):
|
|
raise NotImplementedError()
|
|
|
|
def __isub__(self, other):
|
|
raise NotImplementedError()
|
|
|
|
def __imul__(self, other):
|
|
raise NotImplementedError()
|
|
|
|
def __idiv__(self, other):
|
|
raise NotImplementedError()
|
|
|
|
def __itruediv__(self, other):
|
|
raise NotImplementedError()
|
|
|
|
def _sync_copyfrom(self, source_array):
|
|
raise NotImplementedError()
|
|
|
|
def _at(self, idx):
|
|
raise NotSupportedForSparseNDArray(self._at, '[idx]', idx)
|
|
|
|
def _slice(self, start, stop):
|
|
raise NotSupportedForSparseNDArray(self._slice, None, start, stop)
|
|
|
|
def reshape(self, shape):
|
|
raise NotSupportedForSparseNDArray(self.reshape, None, shape)
|
|
|
|
def _aux_type(self, i):
|
|
"""Data-type of the array's ith aux data.
|
|
|
|
Returns
|
|
-------
|
|
numpy.dtype
|
|
This BaseSparseNDArray's aux data type.
|
|
"""
|
|
aux_type = ctypes.c_int()
|
|
check_call(_LIB.MXNDArrayGetAuxType(self.handle, i, ctypes.byref(aux_type)))
|
|
return _DTYPE_MX_TO_NP[aux_type.value]
|
|
|
|
@property
|
|
def _num_aux(self):
|
|
"""The number of aux data used to help store the sparse ndarray.
|
|
"""
|
|
return len(_STORAGE_AUX_TYPES[self.stype])
|
|
|
|
@property
|
|
def _aux_types(self):
|
|
"""The data types of the aux data for the BaseSparseNDArray.
|
|
"""
|
|
aux_types = []
|
|
num_aux = self._num_aux
|
|
for i in range(num_aux):
|
|
aux_types.append(self._aux_type(i))
|
|
return aux_types
|
|
|
|
def asnumpy(self):
|
|
"""Return a dense ``numpy.ndarray`` object with value copied from this array
|
|
"""
|
|
return self.tostype('default').asnumpy()
|
|
|
|
def astype(self, dtype):
|
|
"""Returns a copy of the array after casting to a specified type.
|
|
Parameters
|
|
----------
|
|
dtype : numpy.dtype or str
|
|
The type of the returned array.
|
|
Examples
|
|
--------
|
|
>>> x = mx.nd.zeros('row_sparse', (2,3), dtype='float32')
|
|
>>> y = x.astype('int32')
|
|
>>> y.dtype
|
|
<type 'numpy.int32'>
|
|
"""
|
|
res = zeros(shape=self.shape, ctx=self.context,
|
|
dtype=dtype, stype=self.stype)
|
|
self.copyto(res)
|
|
return res
|
|
|
|
def copyto(self, other):
|
|
"""Copies the value of this array to another array.
|
|
|
|
Parameters
|
|
----------
|
|
other : NDArray or CSRNDArray or RowSparseNDArray or Context
|
|
The destination array or context.
|
|
|
|
Returns
|
|
-------
|
|
NDArray or CSRNDArray or RowSparseNDArray
|
|
The copied array.
|
|
"""
|
|
if isinstance(other, NDArray):
|
|
if other.handle is self.handle:
|
|
warnings.warn('You are attempting to copy an array to itself', RuntimeWarning)
|
|
return
|
|
return _internal._copyto(self, out=other)
|
|
elif isinstance(other, Context):
|
|
hret = _ndarray_cls(_new_alloc_handle(self.stype, self.shape, other,
|
|
True, self.dtype, self._aux_types))
|
|
return _internal._copyto(self, out=hret)
|
|
else:
|
|
raise TypeError('copyto does not support type ' + str(type(other)))
|
|
|
|
def _data(self):
|
|
"""A deep copy NDArray of the data array associated with the BaseSparseNDArray.
|
|
|
|
This function blocks. Do not use it in performance critical code.
|
|
"""
|
|
self.wait_to_read()
|
|
hdl = NDArrayHandle()
|
|
check_call(_LIB.MXNDArrayGetDataNDArray(self.handle, ctypes.byref(hdl)))
|
|
return NDArray(hdl)
|
|
|
|
|
|
def _aux_data(self, i):
|
|
""" Get a deep copy NDArray of the i-th aux data array associated with the
|
|
BaseSparseNDArray.
|
|
|
|
This function blocks. Do not use it in performance critical code.
|
|
"""
|
|
self.wait_to_read()
|
|
hdl = NDArrayHandle()
|
|
check_call(_LIB.MXNDArrayGetAuxNDArray(self.handle, i, ctypes.byref(hdl)))
|
|
return NDArray(hdl)
|
|
|
|
|
|
# pylint: disable=abstract-method
|
|
class CSRNDArray(BaseSparseNDArray):
|
|
"""A sparse representation of 2D NDArray in the standard CSR format.
|
|
|
|
A CSRNDArray represents an NDArray as three separate arrays: `data`,
|
|
`indptr` and `indices`. It uses the standard CSR representation where the column indices for
|
|
row i are stored in indices[indptr[i]:indptr[i+1]] and their corresponding values are stored
|
|
in values[indptr[i]:indptr[i+1]].
|
|
|
|
The column indices for a given row are expected to be sorted in ascending order.
|
|
Duplicate column entries for the same row are not allowed.
|
|
|
|
Example
|
|
-------
|
|
>>> a = mx.nd.array([[0, 1, 0], [2, 0, 0], [0, 0, 0], [0, 0, 3]])
|
|
>>> a = a.tostype('csr')
|
|
>>> a.indices.asnumpy()
|
|
array([1, 0, 2])
|
|
>>> a.indptr.asnumpy()
|
|
array([0, 1, 2, 2, 3])
|
|
>>> a.data.asnumpy()
|
|
array([ 1., 2., 3.], dtype=float32)
|
|
"""
|
|
|
|
def __reduce__(self):
|
|
return CSRNDArray, (None,), super(CSRNDArray, self).__getstate__()
|
|
|
|
def __iadd__(self, other):
|
|
(self + other).copyto(self)
|
|
return self
|
|
|
|
def __isub__(self, other):
|
|
(self - other).copyto(self)
|
|
return self
|
|
|
|
def __imul__(self, other):
|
|
(self * other).copyto(self)
|
|
return self
|
|
|
|
def __idiv__(self, other):
|
|
(self / other).copyto(self)
|
|
return self
|
|
|
|
def __itruediv__(self, other):
|
|
(self / other).copyto(self)
|
|
return self
|
|
|
|
def __getitem__(self, key):
|
|
"""x.__getitem__(i) <=> x[i]
|
|
|
|
Returns a sliced view of this array.
|
|
|
|
Parameters
|
|
----------
|
|
key : slice
|
|
Indexing key.
|
|
|
|
Examples
|
|
--------
|
|
>>> indptr = np.array([0, 2, 3, 6])
|
|
>>> indices = np.array([0, 2, 2, 0, 1, 2])
|
|
>>> data = np.array([1, 2, 3, 4, 5, 6])
|
|
>>> a = mx.nd.csr_matrix(data, indptr, indices, (3, 3))
|
|
>>> a.asnumpy()
|
|
array([[1, 0, 2],
|
|
[0, 0, 3],
|
|
[4, 5, 6]])
|
|
>>> a[1:2].asnumpy()
|
|
array([[0, 0, 3]], dtype=float32)
|
|
"""
|
|
if isinstance(key, int):
|
|
raise ValueError("__getitem__ with int key is not implemented for CSRNDArray")
|
|
if isinstance(key, py_slice):
|
|
if key.step is not None:
|
|
raise ValueError('CSRNDArray only supports continuous slicing on axis 0')
|
|
if key.start is not None or key.stop is not None:
|
|
begin = key.start if key.start else 0
|
|
end = key.stop if key.stop else self.shape[0]
|
|
return nd_slice(self, begin=begin, end=end)
|
|
else:
|
|
return self
|
|
if isinstance(key, tuple):
|
|
raise ValueError('Multi-dimension indexing is not supported')
|
|
|
|
def __setitem__(self, key, value):
|
|
"""x.__setitem__(i, y) <=> x[i]=y
|
|
|
|
Set self[key] to value. Only slice key [:] is supported.
|
|
|
|
Parameters
|
|
----------
|
|
key : slice
|
|
The indexing key.
|
|
value : NDArray or CSRNDArray or numpy.ndarray
|
|
The value to set.
|
|
|
|
Examples
|
|
--------
|
|
>>> src = mx.nd.zeros((3,3), stype='csr')
|
|
>>> src.asnumpy()
|
|
array([[ 0., 0., 0.],
|
|
[ 0., 0., 0.],
|
|
[ 0., 0., 0.]], dtype=float32)
|
|
>>> # assign CSRNDArray with same storage type
|
|
>>> x = mx.nd.ones('row_sparse', (3,3)).tostype('csr')
|
|
>>> x[:] = src
|
|
>>> x.asnumpy()
|
|
array([[ 1., 1., 1.],
|
|
[ 1., 1., 1.],
|
|
[ 1., 1., 1.]], dtype=float32)
|
|
>>> # assign NDArray to CSRNDArray
|
|
>>> x[:] = mx.nd.ones((3,3)) * 2
|
|
>>> x.asnumpy()
|
|
array([[ 2., 2., 2.],
|
|
[ 2., 2., 2.],
|
|
[ 2., 2., 2.]], dtype=float32)
|
|
"""
|
|
if not self.writable:
|
|
raise ValueError('Failed to assign to a readonly CSRNDArray')
|
|
if isinstance(key, py_slice):
|
|
if key.step is not None or key.start is not None or key.stop is not None:
|
|
raise ValueError('Assignment with slice for CSRNDArray is not ' \
|
|
'implmented yet.')
|
|
if isinstance(value, NDArray):
|
|
# avoid copying to itself
|
|
if value.handle is not self.handle:
|
|
value.copyto(self)
|
|
elif isinstance(value, numeric_types):
|
|
raise ValueError("Assigning numeric types to CSRNDArray is " \
|
|
"not implemented yet.")
|
|
elif isinstance(value, (np.ndarray, np.generic)):
|
|
# TODO(haibin/anisub) check scipy.sparse and use _sync_copy_from to
|
|
# avoid the temporary copy
|
|
warnings.warn('Assigning non-NDArray object to CSRNDArray is not efficient',
|
|
RuntimeWarning)
|
|
tmp = _array(value)
|
|
tmp.copyto(self)
|
|
else:
|
|
raise TypeError('type %s not supported' % str(type(value)))
|
|
else:
|
|
assert(isinstance(key, (int, tuple)))
|
|
raise Exception('CSRNDArray only supports [:] for assignment')
|
|
|
|
@property
|
|
def indices(self):
|
|
"""A deep copy NDArray of the indices array of the CSRNDArray.
|
|
This generates a deep copy of the column indices of the current `csr` matrix.
|
|
|
|
Returns
|
|
-------
|
|
NDArray
|
|
This CSRNDArray's indices array.
|
|
"""
|
|
return self._aux_data(1)
|
|
|
|
@property
|
|
def indptr(self):
|
|
"""A deep copy NDArray of the indptr array of the CSRNDArray.
|
|
This generates a deep copy of the `indptr` of the current `csr` matrix.
|
|
|
|
Returns
|
|
-------
|
|
NDArray
|
|
This CSRNDArray's indptr array.
|
|
"""
|
|
return self._aux_data(0)
|
|
|
|
@property
|
|
def data(self):
|
|
"""A deep copy NDArray of the data array of the CSRNDArray.
|
|
This generates a deep copy of the `data` of the current `csr` matrix.
|
|
|
|
Returns
|
|
-------
|
|
NDArray
|
|
This CSRNDArray's data array.
|
|
"""
|
|
return self._data()
|
|
|
|
def tostype(self, stype):
|
|
"""Return a copy of the array with chosen storage type.
|
|
|
|
Returns
|
|
-------
|
|
NDArray or CSRNDArray
|
|
A copy of the array with the chosen storage stype
|
|
"""
|
|
if stype == 'row_sparse':
|
|
raise ValueError("cast_storage from csr to row_sparse is not supported")
|
|
return cast_storage(self, stype=stype)
|
|
|
|
def copyto(self, other):
|
|
"""Copies the value of this array to another array.
|
|
|
|
If ``other`` is a ``NDArray`` or ``CSRNDArray`` object, then ``other.shape`` and
|
|
``self.shape`` should be the same. This function copies the value from
|
|
``self`` to ``other``.
|
|
|
|
If ``other`` is a context, a new ``CSRNDArray`` will be first created on
|
|
the target context, and the value of ``self`` is copied.
|
|
|
|
Parameters
|
|
----------
|
|
other : NDArray or CSRNDArray or Context
|
|
The destination array or context.
|
|
|
|
Returns
|
|
-------
|
|
NDArray or CSRNDArray
|
|
The copied array. If ``other`` is an ``NDArray`` or ``CSRNDArray``, then the return
|
|
value and ``other`` will point to the same ``NDArray`` or ``CSRNDArray``.
|
|
"""
|
|
if isinstance(other, Context):
|
|
return super(CSRNDArray, self).copyto(other)
|
|
elif isinstance(other, NDArray):
|
|
stype = other.stype
|
|
if stype == 'default' or stype == 'csr':
|
|
return super(CSRNDArray, self).copyto(other)
|
|
else:
|
|
raise TypeError('copyto does not support destination NDArray stype ' + str(stype))
|
|
else:
|
|
raise TypeError('copyto does not support type ' + str(type(other)))
|
|
|
|
|
|
# pylint: disable=abstract-method
|
|
class RowSparseNDArray(BaseSparseNDArray):
|
|
"""A sparse representation of a set of NDArray row slices at given indices.
|
|
|
|
A RowSparseNDArray represents a multidimensional NDArray using two separate arrays: `data` and
|
|
`indices`.
|
|
|
|
- data: an NDArray of any dtype with shape [D0, D1, ..., Dn].
|
|
- indices: a 1-D int64 NDArray with shape [D0].
|
|
|
|
The `indices` stores the indices of the row slices with non-zeros,
|
|
while the values are stored in `data`. The corresponding NDArray ``dense``
|
|
represented by RowSparseNDArray ``rsp`` has
|
|
|
|
``dense[rsp.indices[i], :, :, :, ...] = rsp.data[i, :, :, :, ...]``
|
|
|
|
>>> dense.asnumpy()
|
|
array([[ 1., 2., 3.],
|
|
[ 0., 0., 0.],
|
|
[ 4., 0., 5.],
|
|
[ 0., 0., 0.],
|
|
[ 0., 0., 0.]], dtype=float32)
|
|
>>> rsp = dense.tostype('row_sparse')
|
|
>>> rsp.indices.asnumpy()
|
|
array([0, 2], dtype=int64)
|
|
>>> rsp.data.asnumpy()
|
|
array([[ 1., 2., 3.],
|
|
[ 4., 0., 5.]], dtype=float32)
|
|
|
|
A RowSparseNDArray is typically used to represent non-zero row-slices of a large NDArray
|
|
of shape [LARGE0, D1, .. , Dn] where LARGE0 >> D0 and most row slices are zeros.
|
|
|
|
The indices are expected to be sorted in ascending order.
|
|
|
|
RowSparseNDArray is used principally in the definition of gradients for operations
|
|
that have sparse gradients (e.g. sparse dot and sparse embedding).
|
|
"""
|
|
def __reduce__(self):
|
|
return RowSparseNDArray, (None,), super(RowSparseNDArray, self).__getstate__()
|
|
|
|
def __iadd__(self, other):
|
|
(self + other).copyto(self)
|
|
return self
|
|
|
|
def __isub__(self, other):
|
|
(self - other).copyto(self)
|
|
return self
|
|
|
|
def __imul__(self, other):
|
|
(self * other).copyto(self)
|
|
return self
|
|
|
|
def __idiv__(self, other):
|
|
(self / other).copyto(self)
|
|
return self
|
|
|
|
def __itruediv__(self, other):
|
|
(self / other).copyto(self)
|
|
return self
|
|
|
|
def __getitem__(self, key):
|
|
"""x.__getitem__(i) <=> x[i]
|
|
|
|
Returns a sliced view of this array.
|
|
|
|
Parameters
|
|
----------
|
|
key : slice
|
|
Indexing key.
|
|
|
|
Examples
|
|
--------
|
|
>>> x = mx.nd.zeros((2, 3), stype='row_sparse')
|
|
>>> x[:].asnumpy()
|
|
array([[ 0., 0., 0.],
|
|
[ 0., 0., 0.]], dtype=float32)
|
|
"""
|
|
if isinstance(key, int):
|
|
raise Exception("__getitem__ with int key is not implemented for RowSparseNDArray yet")
|
|
if isinstance(key, py_slice):
|
|
if key.step is not None or key.start is not None or key.stop is not None:
|
|
raise Exception('RowSparseNDArray only supports [:] for __getitem__')
|
|
else:
|
|
return self
|
|
if isinstance(key, tuple):
|
|
raise ValueError('Multi-dimension indexing is not supported')
|
|
|
|
def __setitem__(self, key, value):
|
|
"""x.__setitem__(i, y) <=> x[i]=y
|
|
|
|
Set self[key] to value. Only slice key [:] is supported.
|
|
|
|
Parameters
|
|
----------
|
|
key : slice
|
|
The indexing key.
|
|
value : NDArray or numpy.ndarray
|
|
The value to set.
|
|
|
|
Examples
|
|
--------
|
|
>>> src = mx.nd.row_sparse([[1, 0, 2], [4, 5, 6]], [0, 2], (3,3))
|
|
>>> src.asnumpy()
|
|
array([[ 1., 0., 2.],
|
|
[ 0., 0., 0.],
|
|
[ 4., 5., 6.]], dtype=float32)
|
|
>>> # assign RowSparseNDArray with same storage type
|
|
>>> x = mx.nd.zeros('row_sparse', (3,3))
|
|
>>> x[:] = src
|
|
>>> x.asnumpy()
|
|
array([[ 1., 0., 2.],
|
|
[ 0., 0., 0.],
|
|
[ 4., 5., 6.]], dtype=float32)
|
|
>>> # assign NDArray to RowSparseNDArray
|
|
>>> x[:] = mx.nd.ones((3,3))
|
|
>>> x.asnumpy()
|
|
array([[ 1., 1., 1.],
|
|
[ 1., 1., 1.],
|
|
[ 1., 1., 1.]], dtype=float32)
|
|
"""
|
|
if not self.writable:
|
|
raise ValueError('Failed to assign to a readonly RowSparseNDArray')
|
|
if isinstance(key, py_slice):
|
|
if key.step is not None or key.start is not None or key.stop is not None:
|
|
raise ValueError('Assignment with slice for RowSparseNDArray ' \
|
|
'is not implmented yet.')
|
|
if isinstance(value, NDArray):
|
|
# avoid copying to itself
|
|
if value.handle is not self.handle:
|
|
value.copyto(self)
|
|
elif isinstance(value, numeric_types):
|
|
raise ValueError("Assigning numeric types to RowSparseNDArray " \
|
|
"is not implemented yet.")
|
|
elif isinstance(value, (np.ndarray, np.generic)):
|
|
warnings.warn('Assigning non-NDArray object to RowSparseNDArray is not efficient',
|
|
RuntimeWarning)
|
|
tmp = _array(value)
|
|
tmp.copyto(self)
|
|
else:
|
|
raise TypeError('type %s not supported' % str(type(value)))
|
|
else:
|
|
assert(isinstance(key, (int, tuple)))
|
|
raise TypeError('RowSparseNDArray only supports [:] for assignment')
|
|
|
|
@property
|
|
def indices(self):
|
|
"""A deep copy NDArray of the indices array of the RowSparseNDArray.
|
|
This generates a deep copy of the row indices of the current `row_sparse` matrix.
|
|
|
|
Returns
|
|
-------
|
|
NDArray
|
|
This RowSparseNDArray's indices array.
|
|
"""
|
|
return self._aux_data(0)
|
|
|
|
@property
|
|
def data(self):
|
|
"""A deep copy NDArray of the data array of the RowSparseNDArray.
|
|
This generates a deep copy of the `data` of the current `row_sparse` matrix.
|
|
|
|
Returns
|
|
-------
|
|
NDArray
|
|
This RowSparseNDArray's data array.
|
|
"""
|
|
return self._data()
|
|
|
|
def tostype(self, stype):
|
|
"""Return a copy of the array with chosen storage type.
|
|
|
|
Returns
|
|
-------
|
|
NDArray or RowSparseNDArray
|
|
A copy of the array with the chosen storage stype
|
|
"""
|
|
if stype == 'csr':
|
|
raise ValueError("cast_storage from row_sparse to csr is not supported")
|
|
return cast_storage(self, stype=stype)
|
|
|
|
def copyto(self, other):
|
|
"""Copies the value of this array to another array.
|
|
|
|
If ``other`` is a ``NDArray`` or ``RowSparseNDArray`` object, then ``other.shape``
|
|
and ``self.shape`` should be the same. This function copies the value from
|
|
``self`` to ``other``.
|
|
|
|
If ``other`` is a context, a new ``RowSparseNDArray`` will be first created on
|
|
the target context, and the value of ``self`` is copied.
|
|
|
|
Parameters
|
|
----------
|
|
other : NDArray or RowSparseNDArray or Context
|
|
The destination array or context.
|
|
|
|
Returns
|
|
-------
|
|
NDArray or RowSparseNDArray
|
|
The copied array. If ``other`` is an ``NDArray`` or ``RowSparseNDArray``, then the
|
|
return value and ``other`` will point to the same ``NDArray`` or ``RowSparseNDArray``.
|
|
"""
|
|
if isinstance(other, Context):
|
|
return super(RowSparseNDArray, self).copyto(other)
|
|
elif isinstance(other, NDArray):
|
|
stype = other.stype
|
|
if stype == 'default' or stype == 'row_sparse':
|
|
return super(RowSparseNDArray, self).copyto(other)
|
|
else:
|
|
raise TypeError('copyto does not support destination NDArray stype ' + str(stype))
|
|
else:
|
|
raise TypeError('copyto does not support type ' + str(type(other)))
|
|
|
|
|
|
def _prepare_src_array(src, dtype, default_dtype):
|
|
"""Prepare `src` and its dtype so that they can be used to construct NDArray.
|
|
`src` is converted to a `np.ndarray` if it's neither an `NDArray` nor an `np.ndarray`.
|
|
"""
|
|
if isinstance(src, NDArray):
|
|
dtype = src.dtype if dtype is None else dtype
|
|
else:
|
|
dtype = default_dtype if dtype is None else dtype
|
|
if not isinstance(src, np.ndarray):
|
|
try:
|
|
src = np.array(src, dtype=dtype)
|
|
except:
|
|
raise TypeError('values must be array like object')
|
|
return src, dtype
|
|
|
|
|
|
def csr_matrix(data, indptr, indices, shape, ctx=None, dtype=None, indptr_type=None,
|
|
indices_type=None):
|
|
"""Creates a 2D array with compressed sparse row(CSR) format.
|
|
|
|
Parameters
|
|
----------
|
|
data: array_like
|
|
An object exposing the array interface, with shape [nnz], where D0 is the number of
|
|
non-zero entries.
|
|
indptr: array_like
|
|
An object exposing the array interface, with shape [D0 + 1]. The first element in indptr
|
|
should always be zero.
|
|
indices: array_like
|
|
An object exposing the array interface, with shape [nnz].
|
|
ctx: Context, optional
|
|
Device context (default is the current default context).
|
|
dtype: str or numpy.dtype, optional
|
|
The data type of the output array. The default dtype is ``values.dtype``
|
|
if `values` is an `NDArray`, `float32` otherwise.
|
|
indptr_type: str or numpy.dtype, optional
|
|
The data type of the indices array. The default dtype is ``indptr.dtype``
|
|
if `indptr` is an `NDArray`, `int64` otherwise.
|
|
indices_type: str or numpy.dtype, optional
|
|
The data type of the indices array. The default dtype is ``indices.dtype``
|
|
if `indicies` is an `NDArray`, `int64` otherwise.
|
|
|
|
Returns
|
|
-------
|
|
CSRNDArray
|
|
A `CSRNDArray` with the `csr` storage representation.
|
|
|
|
Example
|
|
-------
|
|
>>> import mxnet as mx
|
|
>>> a = mx.nd.csr_matrix([1, 2, 3], [0, 1, 2, 2, 3], [1, 0, 2], (4, 3))
|
|
>>> a.asnumpy()
|
|
array([[ 0., 1., 0.],
|
|
[ 2., 0., 0.],
|
|
[ 0., 0., 0.],
|
|
[ 0., 0., 3.]], dtype=float32)
|
|
"""
|
|
storage_type = 'csr'
|
|
# context
|
|
if ctx is None:
|
|
ctx = Context.default_ctx
|
|
# prepare src array and types
|
|
data, dtype = _prepare_src_array(data, dtype, mx_real_t)
|
|
indptr, indptr_type = _prepare_src_array(indptr, indptr_type,
|
|
_STORAGE_AUX_TYPES[storage_type][0])
|
|
indices, indices_type = _prepare_src_array(indices, indices_type,
|
|
_STORAGE_AUX_TYPES[storage_type][1])
|
|
# verify types
|
|
assert('int64' in str(indptr_type)), "expected int64 for indptr"
|
|
assert('int64' in str(indices_type)), "expected int64 for indices"
|
|
# verify shapes
|
|
aux_shapes = [indptr.shape, indices.shape]
|
|
assert(data.ndim == 1)
|
|
assert(indptr.ndim == 1)
|
|
assert(indices.ndim == 1)
|
|
assert(len(shape) == 2)
|
|
result = CSRNDArray(_new_alloc_handle(storage_type, shape, ctx, False, dtype,
|
|
[indptr_type, indices_type], aux_shapes))
|
|
# TODO(junwu): Convert data, indptr, and indices to mxnet NDArrays
|
|
# if they are not for now. In the future, we should provide a c-api
|
|
# to accept np.ndarray types to copy from to result.data and aux_data
|
|
if not isinstance(data, NDArray):
|
|
data = _array(data, ctx, dtype)
|
|
if not isinstance(indptr, NDArray):
|
|
indptr = _array(indptr, ctx, indptr_type)
|
|
if not isinstance(indices, NDArray):
|
|
indices = _array(indices, ctx, indices_type)
|
|
check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, data.handle, ctypes.c_int(-1)))
|
|
check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, indptr.handle, ctypes.c_int(0)))
|
|
check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, indices.handle, ctypes.c_int(1)))
|
|
return result
|
|
|
|
|
|
def row_sparse_array(data, indices, shape, ctx=None, dtype=None, indices_type=None):
|
|
"""Creates a multidimensional row sparse array with a set of tensor slices at given indices.
|
|
|
|
Parameters
|
|
----------
|
|
data: array_like
|
|
An object exposing the array interface, with shape [D0, D1, .. DK], where D0 is
|
|
the number of rows with non-zeros entries.
|
|
indices: array_like
|
|
An object exposing the array interface, with shape [D0].
|
|
ctx : Context, optional
|
|
Device context (default is the current default context).
|
|
dtype : str or numpy.dtype, optional
|
|
The data type of the output array. The default dtype is ``data.dtype``
|
|
if `data` is an `NDArray`, `float32` otherwise.
|
|
indices_type: str or numpy.dtype, optional
|
|
The data type of the indices array. The default dtype is ``indices.dtype``
|
|
if `indicies` is an `NDArray`, `int64` otherwise.
|
|
|
|
Returns
|
|
-------
|
|
RowSparseNDArray
|
|
An `RowSparseNDArray` with the `row_sparse` storage representation.
|
|
|
|
Example
|
|
-------
|
|
>>> a = mx.nd.row_sparse_array([[1, 2], [3, 4]], [1, 4], (6, 2))
|
|
>>> a.asnumpy()
|
|
array([[ 0., 0.],
|
|
[ 1., 2.],
|
|
[ 0., 0.],
|
|
[ 0., 0.],
|
|
[ 3., 4.],
|
|
[ 0., 0.]], dtype=float32)
|
|
"""
|
|
storage_type = 'row_sparse'
|
|
# context
|
|
if ctx is None:
|
|
ctx = Context.default_ctx
|
|
# prepare src array and types
|
|
data, dtype = _prepare_src_array(data, dtype, mx_real_t)
|
|
indices, indices_type = _prepare_src_array(indices, indices_type,
|
|
_STORAGE_AUX_TYPES[storage_type][0])
|
|
# verify types
|
|
assert('int64' in str(indices_type)), "expected int64 for indices"
|
|
# verify shapes
|
|
assert(data.ndim == len(shape))
|
|
assert(indices.ndim == 1)
|
|
result = RowSparseNDArray(_new_alloc_handle(storage_type, shape, ctx, False, dtype,
|
|
[indices_type], [indices.shape]))
|
|
|
|
# TODO(junwu): Convert data, indptr, and indices to mxnet NDArrays
|
|
# if they are not for now. In the future, we should provide a c-api
|
|
# to accept np.ndarray types to copy from to result.data and aux_data
|
|
if not isinstance(data, NDArray):
|
|
data = _array(data, ctx, dtype)
|
|
if not isinstance(indices, NDArray):
|
|
indices = _array(indices, ctx, indices_type)
|
|
check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, data.handle, ctypes.c_int(-1)))
|
|
check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, indices.handle, ctypes.c_int(0)))
|
|
return result
|
|
|
|
|
|
def _ndarray_cls(handle, writable=True, stype=None):
|
|
if stype is None:
|
|
stype = _storage_type(handle)
|
|
if stype == 'default':
|
|
return NDArray(handle, writable=writable)
|
|
elif stype == 'csr':
|
|
return CSRNDArray(handle, writable=writable)
|
|
elif stype == 'row_sparse':
|
|
return RowSparseNDArray(handle, writable=writable)
|
|
else:
|
|
raise Exception("unknown storage type")
|
|
|
|
|
|
_set_ndarray_class(_ndarray_cls)
|
|
|
|
|
|
def zeros(stype, shape, ctx=None, dtype=None, aux_types=None, **kwargs):
|
|
"""Return a new array of given shape and type, filled with zeros.
|
|
|
|
Parameters
|
|
----------
|
|
stype: string
|
|
The storage type of the empty array, such as 'row_sparse', 'csr', etc
|
|
shape : int or tuple of int
|
|
The shape of the empty array
|
|
ctx : Context, optional
|
|
An optional device context (default is the current default context)
|
|
dtype : str or numpy.dtype, optional
|
|
An optional value type (default is `float32`)
|
|
aux_types: list of numpy.dtype, optional
|
|
An optional list of types of the aux data for RowSparseNDArray or CSRNDArray
|
|
(default values depends on the storage type)
|
|
|
|
Returns
|
|
-------
|
|
RowSparseNDArray or CSRNDArray
|
|
A created array
|
|
Examples
|
|
--------
|
|
>>> mx.nd.zeros((1,2), mx.cpu(), stype='csr')
|
|
<CSRNDArray 1x2 @cpu(0)>
|
|
>>> mx.nd.zeros((1,2), mx.cpu(), 'float16', stype='row_sparse').asnumpy()
|
|
array([[ 0., 0.]], dtype=float16)
|
|
"""
|
|
if stype == 'default':
|
|
return _zeros_ndarray(shape, ctx=ctx, dtype=dtype, **kwargs)
|
|
if ctx is None:
|
|
ctx = Context.default_ctx
|
|
dtype = mx_real_t if dtype is None else dtype
|
|
if aux_types is None:
|
|
if stype == 'row_sparse' or stype == 'csr':
|
|
aux_types = _STORAGE_AUX_TYPES[stype]
|
|
else:
|
|
raise Exception("unknown storage type")
|
|
assert(len(aux_types) == len(_STORAGE_AUX_TYPES[stype]))
|
|
out = _ndarray_cls(_new_alloc_handle(stype, shape, ctx, True, dtype, aux_types))
|
|
return _internal._zeros(shape=shape, ctx=ctx, dtype=dtype, out=out, **kwargs)
|
|
|
|
|
|
def empty(stype, shape, ctx=None, dtype=None, aux_types=None):
|
|
"""Returns a new array of given shape and type, without initializing entries.
|
|
"""
|
|
if isinstance(shape, int):
|
|
shape = (shape, )
|
|
if ctx is None:
|
|
ctx = Context.default_ctx
|
|
if dtype is None:
|
|
dtype = mx_real_t
|
|
assert(stype is not None)
|
|
if stype == 'csr' or stype == 'row_sparse':
|
|
return zeros(stype, shape, ctx=ctx, dtype=dtype, aux_types=aux_types)
|
|
else:
|
|
raise Exception("unknown stype : " + str(stype))
|
|
|
|
|
|
def array(source_array, ctx=None, dtype=None, aux_types=None):
|
|
"""Creates a sparse array from any object exposing the array interface.
|
|
"""
|
|
if isinstance(source_array, NDArray):
|
|
assert(source_array.stype != 'default'), \
|
|
"Please use `cast_storage` to create BaseSparseNDArray from an NDArray"
|
|
dtype = source_array.dtype if dtype is None else dtype
|
|
aux_types = source_array._aux_types if aux_types is None else aux_types
|
|
else:
|
|
# TODO(haibin/anisub) support creation from scipy object when `_sync_copy_from` is ready
|
|
raise NotImplementedError('creating BaseSparseNDArray from ' \
|
|
' a non-NDArray object is not implemented.')
|
|
arr = empty(source_array.stype, source_array.shape, ctx, dtype, aux_types)
|
|
arr[:] = source_array
|
|
return arr
|