Skip to content

Commit

Permalink
ndarray: support modulo operation in macro inplace (#390)
Browse files Browse the repository at this point in the history
* ndarray: inplace modulo operators

```julia
mod_from!(x, y)
mod_from!(x, 2)
rmod_from!(2, x)
```

* ndarray: support modulo operation for macro inplace

Blocker: #389

* update doc
  • Loading branch information
iblislin authored and pluskid committed Jan 4, 2018
1 parent 86ffb5d commit 30852dd
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 10 deletions.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* `context()`
* `empty()`
* `expand_dims()`
* `@inplace`
* `σ()`
* `sigmoid()`
* `relu()`
Expand Down
1 change: 1 addition & 0 deletions docs/src/api/ndarray.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ In the following example `y` can be a `Real` value or another `NDArray`
| `*` | `x .* y` | Elementwise multiplication |
| `/` | `x ./ y` | Elementwise division |
| `^` | `x .^ y` | Elementwise power |
| `%` | `x .% y` | Elementwise modulo |


## Trigonometric Functions
Expand Down
1 change: 1 addition & 0 deletions src/MXNet.jl
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export NDArray,
context,
empty,
expand_dims,
@inplace,
# activation funcs
σ,
sigmoid,
Expand Down
23 changes: 13 additions & 10 deletions src/ndarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -572,18 +572,21 @@ will translate into
which will do inplace adding of the contents of `b` into `a`.
"""
macro inplace(stmt)
if stmt.head == :+= || stmt.head == :.+=
Expr(:call, :add_to!, esc(stmt.args[1]), esc(stmt.args[2]))
elseif stmt.head == :-= || stmt.head == :.-=
Expr(:call, :sub_from!, esc(stmt.args[1]), esc(stmt.args[2]))
elseif stmt.head == :.*=
Expr(:call, :mul_to!, esc(stmt.args[1]), esc(stmt.args[2]))
elseif stmt.head == :./=
Expr(:call, :div_from!, esc(stmt.args[1]), esc(stmt.args[2]))
macro inplace(ex)
f = if ex.head == :+= || ex.head == :.+=
:add_to!
elseif ex.head == :-= || ex.head == :.-=
:sub_from!
elseif ex.head == :.*=
:mul_to!
elseif ex.head == :./=
:div_from!
elseif ex.head == :.%=
:mod_from!
else
error("unsupported inplace translation for $stmt")
error("unsupported inplace translation for $ex")
end
Expr(:call, f, esc(ex.args[1]), esc(ex.args[2]))
end

"""
Expand Down
9 changes: 9 additions & 0 deletions test/unittest/ndarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,15 @@ function test_mod()
@test_throws AssertionError mx.mod_from!(x, 2)
@test_throws AssertionError mx.rmod_from!(2, x)
end

info("NDArray::mod::inplace")
let
x = NDArray(A)
y = NDArray(B)
C = A .% B
@inplace x .%= y
@test copy(x) C
end
end # function test_mod


Expand Down

0 comments on commit 30852dd

Please sign in to comment.