Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve F.rsqrt performance in CPU #4538

Merged
merged 1 commit into from Apr 3, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 9 additions & 10 deletions chainer/functions/math/sqrt.py
Expand Up @@ -29,7 +29,7 @@ def backward(self, indexes, grad_outputs):
return gy / (gx * 2.0),


class Rsqrt(function_node.FunctionNode):
class RsqrtGPU(function_node.FunctionNode):

@property
def label(self):
Expand All @@ -41,16 +41,10 @@ def check_type_forward(self, in_types):
in_types[0].dtype.kind == 'f',
)

def forward(self, inputs):
def forward_gpu(self, inputs):
self.retain_inputs((0,))
x, = inputs
xp = cuda.get_array_module(x)
dtype = x.dtype
if xp is numpy:
out = xp.reciprocal(xp.sqrt(x, dtype=dtype), dtype=dtype)
else:
# CuPy provides `rsqrt` which is faster than `1.0 / sqrt(x)`.
out = cuda.cupyx.rsqrt(x, dtype=dtype)
out = cuda.cupyx.rsqrt(x, dtype=x.dtype)
return utils.force_array(out),

def backward(self, indexes, grad_outputs):
Expand Down Expand Up @@ -91,4 +85,9 @@ def rsqrt(x):

.. seealso:: :func:`~chainer.functions.sqrt`
"""
return Rsqrt().apply((x,))[0]
xp = cuda.get_array_module(x)
if xp is numpy:
return 1.0 / sqrt(x)

# CuPy provides `rsqrt` which is faster than `1.0 / sqrt(x)`.
return RsqrtGPU().apply((x,))[0]