Skip to content
This repository has been archived by the owner on Nov 17, 2023. It is now read-only.

[fix issue#9976] The assignment problem in NDArray #9981

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions include/mxnet/ndarray.h
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,10 @@ class NDArray {
inline Engine::VarHandle var() const {
return ptr_->var;
}
/*! \return byte offset in chunk of the ndarray*/
inline size_t byte_offset() const {
return byte_offset_;
}
/*!
* \brief save the content into binary stream
* \param strm the output stream
Expand Down
2 changes: 1 addition & 1 deletion src/ndarray/ndarray.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1128,7 +1128,7 @@ void CopyFromToImpl(const NDArray& from, const NDArray& to,
}

void CopyFromTo(const NDArray& from, const NDArray& to, int priority) {
if (from.var() == to.var()) {
if (from.var() == to.var() && from.byte_offset() == to.byte_offset()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we also check for size? @reminisce

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@piiswrong There is a shape equality check after this. For CopyFromTo, I think the added condition is sufficient. Agree we should also check sizes if it is for a function of checking if two ndarrays are the same one.

// skip to copy to itself
return;
}
Expand Down
29 changes: 29 additions & 0 deletions tests/python/unittest/test_ndarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -1099,6 +1099,35 @@ def test_assign_float_value_to_ndarray():
b[0] = a[0]
assert same(a, b.asnumpy())

@with_seed()
def test_assign_a_row_to_ndarray():
"""Test case from https://github.com/apache/incubator-mxnet/issues/9976"""
H, W = 10, 10
dtype = np.float32
a_np = np.random.random((H, W)).astype(dtype)
a_nd = mx.nd.array(a_np)

# assign directly
a_np[0] = a_np[1]
a_nd[0] = a_nd[1]
assert same(a_np, a_nd.asnumpy())

# assign a list
v = np.random.random(W).astype(dtype).tolist()
a_np[1] = v
a_nd[1] = v
assert same(a_np, a_nd.asnumpy())

# assign a np.ndarray
v = np.random.random(W).astype(dtype)
a_np[2] = v
a_nd[2] = v
assert same(a_np, a_nd.asnumpy())

# assign by slice
a_np[0, :] = a_np[1]
a_nd[0, :] = a_nd[1]
assert same(a_np, a_nd.asnumpy())

if __name__ == '__main__':
import nose
Expand Down