asitstands closed pull request #9991: Random shuffle implementation URL: https://github.com/apache/incubator-mxnet/pull/9991
This is a PR merged from a forked repository. As GitHub hides the original diff on merge, it is displayed below for the sake of provenance: As this is a foreign pull request (from a fork), the diff is supplied below (as it won't show otherwise due to GitHub magic): diff --git a/docs/api/python/ndarray/random.md b/docs/api/python/ndarray/random.md index ae9e69f758f..4341a3ce2cd 100644 --- a/docs/api/python/ndarray/random.md +++ b/docs/api/python/ndarray/random.md @@ -35,6 +35,8 @@ In the rest of this document, we list routines provided by the `ndarray.random` normal poisson uniform + multinomial + shuffle mxnet.random.seed ``` diff --git a/docs/api/python/symbol/random.md b/docs/api/python/symbol/random.md index a3492f6f840..22c686ff2fd 100644 --- a/docs/api/python/symbol/random.md +++ b/docs/api/python/symbol/random.md @@ -35,6 +35,8 @@ In the rest of this document, we list routines provided by the `symbol.random` p normal poisson uniform + multinomial + shuffle mxnet.random.seed ``` diff --git a/python/mxnet/ndarray/random.py b/python/mxnet/ndarray/random.py index af125753e5e..49e32d6fd42 100644 --- a/python/mxnet/ndarray/random.py +++ b/python/mxnet/ndarray/random.py @@ -24,7 +24,7 @@ __all__ = ['uniform', 'normal', 'poisson', 'exponential', 'gamma', 'multinomial', - 'negative_binomial', 'generalized_negative_binomial'] + 'negative_binomial', 'generalized_negative_binomial', 'shuffle'] def _random_helper(random, sampler, params, shape, dtype, ctx, out, kwargs): @@ -431,3 +431,32 @@ def multinomial(data, shape=_Null, get_prob=False, out=None, **kwargs): <NDArray 2 @cpu(0)> """ return _internal._sample_multinomial(data, shape, get_prob, out=out, **kwargs) + + +def shuffle(data, out=None, **kwargs): + """Shuffle the elements randomly. + + This shuffles the elements along the last axis, i.e., for each element, + all indices except the last one are preserved but the last one changes randomly. + + Parameters + ---------- + data : NDArray + Input data array. + out : NDArray + Array to store the result. + For in-place shuffle, set this to the same array assigned to `data`. + + Examples + -------- + >>> data = mx.nd.array([[0, 1, 2], [3, 4, 5]]) + >>> mx.nd.random.shuffle(data) + [[ 0. 2. 1.] + [ 5. 4. 3.]] + <NDArray 2x3 @cpu(0)> + >>> mx.nd.random.shuffle(data) + [[ 1. 2. 0.] + [ 3. 5. 4.]] + <NDArray 2x3 @cpu(0)> + """ + return _internal._shuffle(data, out, **kwargs) diff --git a/python/mxnet/symbol/random.py b/python/mxnet/symbol/random.py index f0d05ad0561..76b28900b60 100644 --- a/python/mxnet/symbol/random.py +++ b/python/mxnet/symbol/random.py @@ -247,3 +247,30 @@ def multinomial(data, shape=_Null, get_prob=True, **kwargs): reward as head gradient w.r.t. this array to estimate gradient. """ return _internal._sample_multinomial(data, shape, get_prob, **kwargs) + +def shuffle(data, **kwargs): + """Shuffle the elements randomly. + + This shuffles the elements along the last axis, i.e., for each element, + all indices except the last one are preserved but the last one changes randomly. + + Parameters + ---------- + data : NDArray + Input data array. + + Examples + -------- + >>> data = mx.nd.array([[0, 1, 2], [3, 4, 5]]) + >>> a = mx.sym.Variable('a') + >>> b = mx.sym.random.shuffle(a) + >>> b.eval(a=data) + [[ 0. 2. 1.] + [ 5. 4. 3.]] + <NDArray 2x3 @cpu(0)> + >>> b.eval(a=data) + [[ 1. 2. 0.] + [ 3. 5. 4.]] + <NDArray 2x3 @cpu(0)> + """ + return _internal._shuffle(data, **kwargs) diff --git a/src/operator/random/shuffle_op.cc b/src/operator/random/shuffle_op.cc new file mode 100644 index 00000000000..073797a88b9 --- /dev/null +++ b/src/operator/random/shuffle_op.cc @@ -0,0 +1,90 @@ +/* + * 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. + */ + +/*! + * Copyright (c) 2018 by Contributors + * \file shuffle_op.cc + * \brief Operator to shuffle elements of an NDArray + */ +#if (__GNUC__ > 4 && !defined(__clang__major__)) || (__clang_major__ > 4 && __linux__) + #define USE_GNU_PARALLEL_SHUFFLE +#endif + +#include <random> +#include <algorithm> +#ifdef USE_GNU_PARALLEL_SHUFFLE + #include <parallel/algorithm> +#endif +#include "./shuffle_op.h" + +namespace mxnet { +namespace op { + +struct ShuffleCPUImpl { + template<typename DType> + static void shuffle(const OpContext& ctx, + mshadow::Tensor<cpu, 1, DType> out, + size_t n_batches, + size_t n_elements) { + using namespace mxnet_op; + auto& prnd = ctx.requested[0].get_random<cpu, size_t>(ctx.get_stream<cpu>())->GetRndEngine(); + for (size_t i = 0; i < n_batches; ++i) { + #ifdef USE_GNU_PARALLEL_SHUFFLE + __gnu_parallel::random_shuffle(out.dptr_ + i * n_elements, + out.dptr_ + (i + 1) * n_elements, + [&prnd](size_t n) { + std::uniform_int_distribution<size_t> dist(0, n - 1); + return dist(prnd); + }); + #else + std::shuffle(out.dptr_ + i * n_elements, + out.dptr_ + (i + 1) * n_elements, + prnd); + #endif + } + } +}; + +// No parameter is declared. +// No backward computation is registered. Shuffling is not differentiable. + +NNVM_REGISTER_OP(_shuffle) +.add_alias("shuffle") +.describe(R"code(Randomly shuffle the elements. + +This shuffles the elements along the last axis, i.e., for each element, +all indices except the last one are preserved but the last one changes randomly. +)code") +.set_num_inputs(1) +.set_num_outputs(1) +.set_attr<nnvm::FInferShape>("FInferShape", ElemwiseShape<1, 1>) +.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<1, 1>) +.set_attr<FResourceRequest>("FResourceRequest", + [](const nnvm::NodeAttrs& attrs) { + return std::vector<ResourceRequest>{ResourceRequest::kRandom, ResourceRequest::kTempSpace}; + }) +.set_attr<nnvm::FInplaceOption>("FInplaceOption", + [](const NodeAttrs& attrs) { + return std::vector<std::pair<int, int>>{{0, 0}}; + }) +.set_attr<FCompute>("FCompute<cpu>", ShuffleForward<cpu, ShuffleCPUImpl>) +.add_argument("data", "NDArray-or-Symbol", "Data to be shuffled."); + +} // namespace op +} // namespace mxnet diff --git a/src/operator/random/shuffle_op.cu b/src/operator/random/shuffle_op.cu new file mode 100644 index 00000000000..f284083dd20 --- /dev/null +++ b/src/operator/random/shuffle_op.cu @@ -0,0 +1,66 @@ +/* + * 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. + */ + +/*! + * Copyright (c) 2018 by Contributors + * \file shuffle_op.cu + * \brief Operator to shuffle elements of an NDArray + */ +#include "./shuffle_op.h" + +namespace mxnet { +namespace op { + +// Note that the outcomes may not be distributed uniformly if both of the the batch size +// and the length of the last axis are very large. It is because the probability that +// there are duplicated keys is not negligible in that case. +struct ShuffleGPUImpl { + using KeyType = double; // `float` does not provide enough precision + + struct AddBatchIndexKernel { + template<typename DType> + MSHADOW_XINLINE static void Map(int i, DType* keys, size_t n_elements) { + keys[i] += i / n_elements; + } + }; + + template<typename DType> + static void shuffle(const OpContext& ctx, + mshadow::Tensor<gpu, 1, DType> out, + size_t n_batches, + size_t n_elements) { + using namespace mxnet_op; + Stream<gpu> *s = ctx.get_stream<gpu>(); + size_t size = n_batches * n_elements; + Random<gpu, KeyType> *prnd = ctx.requested[0].get_random<gpu, KeyType>(s); + Tensor<gpu, 1, KeyType> keys = + ctx.requested[1].get_space_typed<gpu, 1, KeyType>(Shape1(size), s); + prnd->SampleUniform(&keys, 0, 1); + if (n_batches > 1) { + Kernel<AddBatchIndexKernel, gpu>::Launch(s, size, keys.dptr_, n_elements); + } + SortByKey(keys, out, true); + } +}; + +NNVM_REGISTER_OP(_shuffle) +.set_attr<FCompute>("FCompute<gpu>", ShuffleForward<gpu, ShuffleGPUImpl>); + +} // namespace op +} // namespace mxnet diff --git a/src/operator/random/shuffle_op.h b/src/operator/random/shuffle_op.h new file mode 100644 index 00000000000..4223203f6b6 --- /dev/null +++ b/src/operator/random/shuffle_op.h @@ -0,0 +1,64 @@ +/* + * 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. + */ + +/*! + * Copyright (c) 2018 by Contributors + * \file shuffle_op.h + * \brief Operator to shuffle elements of an NDArray + */ +#ifndef MXNET_OPERATOR_RANDOM_SHUFFLE_OP_H_ +#define MXNET_OPERATOR_RANDOM_SHUFFLE_OP_H_ + +#include <mxnet/operator_util.h> +#include <vector> +#include "../elemwise_op_common.h" + +namespace mxnet { +namespace op { + +template<typename xpu, typename ShuffleImpl> +void ShuffleForward(const nnvm::NodeAttrs& attrs, + const OpContext& ctx, + const std::vector<TBlob>& inputs, + const std::vector<OpReqType>& req, + const std::vector<TBlob>& outputs) { + using namespace mxnet_op; + if (req[0] == kNullOp) { + return; + } + CHECK_NE(req[0], kAddTo) << "Shuffle does not support AddTo"; + Stream<xpu> *s = ctx.get_stream<xpu>(); + const TShape input_shape = inputs[0].shape_; + const size_t n_elements = input_shape[input_shape.ndim() - 1]; + const size_t n_batches = inputs[0].Size() / n_elements; + const size_t size = inputs[0].Size(); + MSHADOW_REAL_TYPE_SWITCH(inputs[0].type_flag_, DType, { + Tensor<xpu, 1, DType> in = inputs[0].get_with_shape<xpu, 1, DType>(Shape1(size), s); + Tensor<xpu, 1, DType> out = outputs[0].get_with_shape<xpu, 1, DType>(Shape1(size), s); + if (req[0] != kWriteInplace) { + Copy(out, in, s); + } + ShuffleImpl::shuffle(ctx, out, n_batches, n_elements); + }); +} + +} // namespace op +} // namespace mxnet + +#endif // MXNET_OPERATOR_RANDOM_SHUFFLE_OP_H_ diff --git a/tests/python/unittest/test_random.py b/tests/python/unittest/test_random.py index f042f57c4e9..55c32a50219 100644 --- a/tests/python/unittest/test_random.py +++ b/tests/python/unittest/test_random.py @@ -16,6 +16,8 @@ # under the License. import os +import itertools +import math import mxnet as mx from mxnet.test_utils import verify_generator, gen_buckets_probs_with_ppf import numpy as np @@ -552,6 +554,37 @@ def compute_expected_prob(): mx.test_utils.assert_almost_equal(exp_cnt_sampled.asnumpy(), exp_cnt[sampled_classes].asnumpy(), rtol=1e-1, atol=1e-2) mx.test_utils.assert_almost_equal(exp_cnt_true.asnumpy(), exp_cnt[true_classes].asnumpy(), rtol=1e-1, atol=1e-2) +@with_seed() +def test_shuffle(): + def hash(arr): + ret = 0 + for i, n in enumerate(arr): + ret += int(n.asscalar()) * (10 ** i) + return ret + + data = mx.nd.arange(0, 9).reshape((3, 3)) + repeat = 100000 + lastDim = data.shape[len(data.shape) - 1] + count = {} + # Count the number of each outcome in `repeat` iterations + for i in range(repeat): + ret = mx.nd.random.shuffle(data) + for j in range(lastDim): + c = count.get(hash(ret[j]), 0) + count[hash(ret[j])] = c + 1 + # Check the number of different outcomes + assert len(count) == math.factorial(lastDim) * (data.size / lastDim) + # The outcomes must be uniformly distributed + for i in range(lastDim): + for p in itertools.permutations(data[i].asnumpy()): + assert abs(count[hash(mx.nd.array(p))] / repeat - 1 / math.factorial(lastDim)) < 0.01 + # Check symbol interface + a = mx.sym.Variable('a') + b = mx.sym.random.shuffle(a) + c = mx.sym.random.shuffle(data=b, name='c') + d = mx.sym.sort(c) + assert (d.eval(a=data, ctx=mx.current_context())[0] == data).prod() == 1 + if __name__ == '__main__': import nose nose.runmodule() ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org With regards, Apache Git Services