This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.8k
standard update for sparse sgd_mom_update #9189
Merged
Merged
Changes from 5 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
ef0484f
standard sparse sgd mom update
ZiyueHuang f660d37
update
ZiyueHuang f90c450
update comments
ZiyueHuang 54c901c
address comments
ZiyueHuang 66c87b8
Merge remote-tracking branch 'upstream/master' into std_sparse_sgd
ZiyueHuang 9ed9563
revise
ZiyueHuang 37d57d6
more general infer stype
ZiyueHuang a944b76
fix
ZiyueHuang 70596d2
fix
ZiyueHuang 703db8f
resolve conflict
ZiyueHuang 96de6c5
add comments for stype inference func
ZiyueHuang 1807ca4
update
ZiyueHuang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -38,6 +38,7 @@ | |
#include "./elemwise_op_common.h" | ||
#include "mxnet_op.h" | ||
#include "./tensor/init_op.h" | ||
#include "./tensor/util/tensor_util-inl.h" | ||
|
||
namespace mxnet { | ||
namespace op { | ||
|
@@ -460,6 +461,95 @@ inline void SGDMomUpdateRspRspRspImpl(const SGDMomParam& param, | |
mom.data(), req, &out_blob); | ||
} | ||
|
||
inline bool SGDMomStorageType(const nnvm::NodeAttrs& attrs, | ||
const int dev_mask, | ||
DispatchMode* dispatch_mode, | ||
std::vector<int>* in_attrs, | ||
std::vector<int>* out_attrs) { | ||
CHECK_EQ(in_attrs->size(), 3U); | ||
CHECK_EQ(out_attrs->size(), 1U); | ||
bool dispatched = false; | ||
const NDArrayStorageType weight_stype = static_cast<NDArrayStorageType>(in_attrs->at(0)); | ||
const NDArrayStorageType grad_stype = static_cast<NDArrayStorageType>(in_attrs->at(1)); | ||
const NDArrayStorageType mom_stype = static_cast<NDArrayStorageType>(in_attrs->at(2)); | ||
if (!dispatched && common::ContainsOnlyStorage(*in_attrs, kDefaultStorage)) { | ||
// dns, dns, dns -> dns | ||
dispatched = storage_type_assign(out_attrs, kDefaultStorage, | ||
dispatch_mode, DispatchMode::kFCompute); | ||
} | ||
if (!dispatched && weight_stype == kRowSparseStorage && | ||
grad_stype == kRowSparseStorage && | ||
(mom_stype == kRowSparseStorage || mom_stype == kDefaultStorage)) { | ||
// rsp, rsp, rsp/dns -> rsp | ||
dispatched = storage_type_assign(out_attrs, kRowSparseStorage, | ||
dispatch_mode, DispatchMode::kFComputeEx); | ||
} | ||
if (!dispatched) { | ||
dispatch_fallback(out_attrs, dispatch_mode); | ||
LogStorageFallback(attrs, dev_mask, in_attrs, out_attrs); | ||
} | ||
return true; | ||
} | ||
|
||
template<int req> | ||
struct SGDMomStdDnsRspDnsKernel { | ||
template<typename DType, typename IType, typename RType> | ||
MSHADOW_XINLINE static void Map(int i, index_t row_length, DType* out_data, | ||
DType* mom_data, const DType* weight_data, const IType* grad_idx, | ||
const DType* grad_data, const RType* prefix_sum, const DType clip_gradient, | ||
const DType momentum, const DType lr, const DType wd, const DType rescale_grad) { | ||
const DType rate = lr * wd; | ||
const bool non_zero = (i == 0) ? prefix_sum[0] > 0 | ||
: prefix_sum[i] > prefix_sum[i-1]; | ||
|
||
for (index_t j = 0; j < row_length; j++) { | ||
const index_t data_i = i * row_length + j; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
const DType grad = non_zero ? grad_data[(prefix_sum[i]-1) * row_length + j] | ||
: static_cast<DType>(0); | ||
if (clip_gradient >= 0.0f) { | ||
mom_data[data_i] = momentum * mom_data[data_i] | ||
- rate * weight_data[data_i] | ||
- lr * | ||
mshadow_op::clip::Map(rescale_grad * grad, | ||
clip_gradient); | ||
} else { | ||
mom_data[data_i] = momentum * mom_data[data_i] | ||
- rate * weight_data[data_i] | ||
- lr * rescale_grad * grad; | ||
} | ||
KERNEL_ASSIGN(out_data[data_i], req, weight_data[data_i] + mom_data[data_i]); | ||
} | ||
} | ||
}; | ||
|
||
template<typename xpu> | ||
void SGDMomStdUpdateDnsRspDnsImpl(const SGDMomParam& param, | ||
const OpContext& ctx, | ||
const TBlob& weight, | ||
const NDArray& grad, | ||
const TBlob& mom, | ||
const OpReqType& req, | ||
TBlob *out); | ||
|
||
template<typename xpu> | ||
inline void SGDMomStdUpdateRspRspDnsImpl(const SGDMomParam& param, | ||
const OpContext& ctx, | ||
const NDArray& weight, | ||
const NDArray& grad, | ||
const NDArray& mom, | ||
const OpReqType& req, | ||
NDArray *out) { | ||
using namespace mshadow; | ||
using namespace mshadow::expr; | ||
using namespace mxnet_op; | ||
using namespace rowsparse; | ||
CHECK_RSP_ALL_ROWS_NON_ZERO(weight, "SGDMomUpdate", "weights"); | ||
Stream<xpu>* s = ctx.get_stream<xpu>(); | ||
TBlob out_blob = out->data(); | ||
SGDMomStdUpdateDnsRspDnsImpl<xpu>(param, ctx, weight.data(), grad, | ||
mom.data(), req, &out_blob); | ||
} | ||
|
||
template<typename xpu> | ||
inline void SGDMomUpdateEx(const nnvm::NodeAttrs& attrs, | ||
const OpContext &ctx, | ||
|
@@ -474,12 +564,15 @@ inline void SGDMomUpdateEx(const nnvm::NodeAttrs& attrs, | |
const auto weight_stype = weight.storage_type(); | ||
const auto mom_stype = mom.storage_type(); | ||
const auto out_stype = outputs[0].storage_type(); | ||
CHECK_EQ(weight_stype, mom_stype) << "Inconsistent storage type detected between mom.stype = " | ||
<< mom_stype << " and weight.stype = " << weight_stype; | ||
NDArray out = outputs[0]; | ||
if (common::ContainsOnlyStorage(inputs, kRowSparseStorage) && | ||
out_stype == kRowSparseStorage) { | ||
NDArray out = outputs[0]; | ||
SGDMomUpdateRspRspRspImpl<xpu>(param, ctx, weight, grad, mom, req[0], &out); | ||
SGDMomUpdateRspRspRspImpl<xpu>(param, ctx, weight, grad, mom, req[0], &out); | ||
} else if (weight.storage_type() == kRowSparseStorage && | ||
grad.storage_type() == kRowSparseStorage && | ||
mom.storage_type() == kDefaultStorage && | ||
out_stype == kRowSparseStorage) { | ||
SGDMomStdUpdateRspRspDnsImpl<xpu>(param, ctx, weight, grad, mom, req[0], &out); | ||
} else { | ||
LOG(FATAL) << "Not implemented: " << operator_string(attrs, ctx, inputs, req, outputs); | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -36,6 +36,57 @@ DMLC_REGISTER_PARAMETER(RMSPropParam); | |
DMLC_REGISTER_PARAMETER(RMSPropAlexParam); | ||
DMLC_REGISTER_PARAMETER(FtrlParam); | ||
|
||
template<> | ||
void SGDMomStdUpdateDnsRspDnsImpl<cpu>(const SGDMomParam& param, | ||
const OpContext& ctx, | ||
const TBlob& weight, | ||
const NDArray& grad, | ||
const TBlob& mom, | ||
const OpReqType& req, | ||
TBlob *out) { | ||
using namespace mxnet_op; | ||
using namespace rowsparse; | ||
using namespace mshadow; | ||
Stream<cpu>* s = ctx.get_stream<cpu>(); | ||
if (req == kNullOp) return; | ||
CHECK_EQ(req, kWriteInplace) << "kWriteInplace is expected for sparse sgd_mom_update"; | ||
CHECK_GT(weight.shape_.Size(), 0); | ||
CHECK_GT(mom.shape_.Size(), 0); | ||
MSHADOW_REAL_TYPE_SWITCH(weight.type_flag_, DType, { | ||
MSHADOW_IDX_TYPE_SWITCH(grad.aux_type(kIdx), IType, { | ||
MXNET_ASSIGN_REQ_SWITCH(req, req_type, { | ||
DType* weight_data = weight.dptr<DType>(); | ||
IType* grad_idx = grad.aux_data(kIdx).dptr<IType>(); | ||
DType* grad_val = grad.data().dptr<DType>(); | ||
DType* mom_data = mom.dptr<DType>(); | ||
DType* out_data = out->dptr<DType>(); | ||
nnvm::dim_t num_rows = weight.shape_[0]; | ||
auto row_length = weight.shape_.ProdShape(1, weight.ndim()); | ||
Tensor<cpu, 1, char> workspace = ctx.requested[0] | ||
.get_space_typed<cpu, 1, char>(Shape1(num_rows * sizeof(nnvm::dim_t)), s); | ||
|
||
nnvm::dim_t* prefix_sum = reinterpret_cast<nnvm::dim_t*>(workspace.dptr_); | ||
// mark row flags | ||
Kernel<set_zero, cpu>::Launch(s, num_rows, prefix_sum); | ||
if (grad.storage_initialized()) { | ||
Kernel<MarkRowFlgKernel, cpu>::Launch(s, grad.aux_shape(kIdx)[0], | ||
prefix_sum, grad_idx); | ||
// calculate inclusive prefix sum | ||
for (nnvm::dim_t i = 1; i < num_rows; i++) { | ||
prefix_sum[i] += prefix_sum[i - 1]; | ||
} | ||
} | ||
Kernel<SGDMomStdDnsRspDnsKernel<req_type>, cpu>::Launch(s, num_rows, row_length, | ||
out_data, mom_data, weight_data, grad_idx, grad_val, prefix_sum, | ||
static_cast<DType>(param.clip_gradient), static_cast<DType>(param.momentum), | ||
static_cast<DType>(param.lr), static_cast<DType>(param.wd), | ||
static_cast<DType>(param.rescale_grad)); | ||
}); | ||
}); | ||
}); | ||
} | ||
|
||
|
||
NNVM_REGISTER_OP(sgd_update) | ||
MXNET_ADD_SPARSE_OP_ALIAS(sgd_update) | ||
.describe(R"code(Update function for Stochastic Gradient Descent (SDG) optimizer. | ||
|
@@ -83,7 +134,10 @@ It updates the weights using:: | |
|
||
Where the parameter ``momentum`` is the decay rate of momentum estimates at each epoch. | ||
|
||
If weight and momentum are both of ``row_sparse`` storage type, | ||
If weight and grad are both of ``row_sparse`` storage type and momentum is of ``default`` storage type, | ||
standard update is applied. | ||
|
||
If weight, grad and momentum are all of ``row_sparse`` storage type, | ||
only the row slices whose indices appear in grad.indices are updated (for both weight and momentum):: | ||
|
||
for row in gradient.indices: | ||
|
@@ -96,11 +150,15 @@ only the row slices whose indices appear in grad.indices are updated (for both w | |
.set_attr_parser(ParamParser<SGDMomParam>) | ||
.set_attr<nnvm::FInferShape>("FInferShape", ElemwiseShape<3, 1>) | ||
.set_attr<nnvm::FInferType>("FInferType", ElemwiseType<3, 1>) | ||
.set_attr<FInferStorageType>("FInferStorageType", ElemwiseStorageType<3, 1, false, true, false>) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Also update the doc here, too? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Updated |
||
.set_attr<FInferStorageType>("FInferStorageType", SGDMomStorageType) | ||
.set_attr<nnvm::FMutateInputs>("FMutateInputs", | ||
[](const nnvm::NodeAttrs& attrs) { | ||
return std::vector<uint32_t>{2}; | ||
}) | ||
.set_attr<FResourceRequest>("FResourceRequest", | ||
[](const NodeAttrs& attrs) { | ||
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace}; | ||
}) | ||
.set_attr<FCompute>("FCompute<cpu>", SGDMomUpdate<cpu>) | ||
.set_attr<FComputeEx>("FComputeEx<cpu>", SGDMomUpdateEx<cpu>) | ||
.add_argument("weight", "NDArray-or-Symbol", "Weight") | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we should reverse the order and mention
lazy_update
, since the users of optimizer don't know how state stypes are created: