Reciprocal

y = 1 / x

struct Reciprocal (
T
size_t dim
) {
Variable!(T, dim, HostStorage) hy;
Variable!(T, dim, DeviceStorage) dy;
}

Examples

test reciprocal simple case, gradcheck and cpu/cuda equality

1 import grain.testing;
2 import std.typecons;
3 import numir;
4 import mir.ndslice;
5 
6 // simple case
7 auto e = [[-1.0f, 1f / 2f, 1f / 3f], [1f, 10f, 1f / 3f]].nparray;
8 auto xs = [[-1.0f, 2.0f, 3.0f], [1.0f, 0.1f, 3.0f]].nparray;
9 Reciprocal!(float, 2) hfunc;
10 auto _hx = xs.variable;
11 auto _hy = hfunc.forward(_hx);
12 assert(approxEqual(_hy.sliced, e));
13 
14 auto hx = uniform!float(2, 2).slice.variable;
15 auto hy = hfunc.forward(hx);
16 auto hgy = uniform!float(2, 2).slice.variable;
17 auto hgx = hfunc.backward(hgy);
18 gradCheck(hfunc, hx, hgy, 1e-3, 5e-2, 5e-2);
19 
20 version (grain_cuda) {
21     Reciprocal!(float, 2) dfunc;
22     auto dy = dfunc.forward(hx.to!DeviceStorage);
23     assert(approxEqual(dy.to!HostStorage.sliced, hy.sliced));
24     auto dgx = dfunc.backward(hgy.to!DeviceStorage);
25     assert(approxEqual(dgx.to!HostStorage.sliced, hgx.sliced));
26 }

Meta