1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
|
import numpy as np
from hypothesis import given, assume, settings
import hypothesis.strategies as st
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.mkl_test_util as mu
import caffe2.python.serialized_test.serialized_test_util as serial
from scipy.stats import norm
import unittest
class TestActivations(serial.SerializedTestCase):
@given(X=hu.tensor(), in_place=st.booleans(),
engine=st.sampled_from(["", "CUDNN"]), **mu.gcs)
@settings(deadline=10000)
def test_relu(self, X, in_place, engine, gc, dc):
if gc == mu.mkl_do:
in_place = False
op = core.CreateOperator(
"Relu",
["X"],
["X"] if in_place else ["Y"],
engine=engine,
)
def relu_ref(X):
return [np.maximum(X, 0.0)]
# go away from the origin point to avoid kink problems
X += 0.02 * np.sign(X)
X[X == 0.0] += 0.02
self.assertReferenceChecks(gc, op, [X], relu_ref, ensure_outputs_are_inferred=True)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0], ensure_outputs_are_inferred=True)
@given(N=st.integers(1, 10), M=st.integers(1, 10), in_place=st.booleans(),
**hu.gcs)
def test_relu_empty_input(self, N, M, in_place, gc, dc):
op = core.CreateOperator(
"Relu",
["X"],
["X"] if in_place else ["Y"],
)
def relu_ref(X):
return [np.maximum(X, 0.0)]
X = np.random.randn(0, N, M).astype(np.float32)
self.assertReferenceChecks(gc, op, [X], relu_ref, ensure_outputs_are_inferred=True)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0], ensure_outputs_are_inferred=True)
@unittest.skipIf(not workspace.has_gpu_support,
"Relu for float16 can only run on GPU now.")
@given(X=hu.tensor(dtype=np.float16), in_place=st.booleans(),
engine=st.sampled_from(["", "CUDNN"]), **hu.gcs)
def test_relu_fp16(self, X, in_place, engine, gc, dc):
# fp16 is only supported on CUDA/HIP
assume(core.IsGPUDeviceType(gc.device_type))
op = core.CreateOperator(
"Relu",
["X"],
["X"] if in_place else ["Y"],
engine=engine,
)
def relu_ref(X):
return [np.maximum(X, 0.0)]
def relu_grad_ref(g_out, outputs, fwd_inputs):
dY = g_out
[Y] = outputs
dX = dY
dX[Y == 0] = 0
return [dX]
# go away from the origin point to avoid kink problems
X += 0.02 * np.sign(X)
X[X == 0.0] += 0.02
self.assertReferenceChecks(
gc,
op,
[X],
relu_ref,
output_to_grad="X" if in_place else "Y",
grad_reference=relu_grad_ref)
@serial.given(X=hu.tensor(elements=hu.floats(-3.0, 3.0)),
n=hu.floats(min_value=0.5, max_value=2.0),
in_place=st.booleans(), **hu.gcs)
def test_relu_n(self, X, n, in_place, gc, dc):
op = core.CreateOperator(
"ReluN",
["X"],
["X"] if in_place else ["Y"],
n=n,
)
def relu_n_ref(X):
return [np.minimum(np.maximum(X, 0.0), n)]
# go away from 0 and n to avoid kink problems
X += 0.04 * np.sign(X)
X[X == 0.0] += 0.04
X -= n
X += 0.02 * np.sign(X)
X[X == 0.0] -= 0.02
X += n
self.assertReferenceChecks(gc, op, [X], relu_n_ref, ensure_outputs_are_inferred=True)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=0.005,
ensure_outputs_are_inferred=True)
@serial.given(X=hu.tensor(),
alpha=hu.floats(min_value=0.1, max_value=2.0),
in_place=st.booleans(), engine=st.sampled_from(["", "CUDNN"]),
**hu.gcs)
def test_elu(self, X, alpha, in_place, engine, gc, dc):
op = core.CreateOperator(
"Elu",
["X"],
["X"] if in_place else ["Y"],
alpha=alpha,
engine=engine,
)
def elu_ref(X):
Y = X
Y[X < 0] = alpha * (np.exp(X[X < 0]) - 1.0)
return [Y]
# go away from the origin point to avoid kink problems
X += 0.04 * np.sign(X)
X[X == 0.0] += 0.04
self.assertReferenceChecks(gc, op, [X], elu_ref, ensure_outputs_are_inferred=True)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=1e-2, ensure_outputs_are_inferred=True)
@given(X=hu.tensor(min_dim=4, max_dim=4),
alpha=hu.floats(min_value=0.1, max_value=2.0),
inplace=st.booleans(),
shared=st.booleans(),
order=st.sampled_from(["NCHW", "NHWC"]),
seed=st.sampled_from([20, 100]),
**hu.gcs)
@settings(deadline=10000)
def test_prelu(self, X, alpha, inplace, shared, order, seed, gc, dc):
np.random.seed(seed)
W = np.random.randn(
X.shape[1] if order == "NCHW" else X.shape[3]).astype(np.float32)
if shared:
W = np.random.randn(1).astype(np.float32)
# go away from the origin point to avoid kink problems
X += 0.04 * np.sign(X)
X[X == 0.0] += 0.04
def prelu_ref(X, W):
Y = X.copy()
W = W.reshape(1, -1, 1, 1) if order == "NCHW" \
else W.reshape(1, 1, 1, -1)
assert len(X.shape) == 4
neg_indices = X <= 0
assert len(neg_indices.shape) == 4
assert X.shape == neg_indices.shape
Y[neg_indices] = (Y * W)[neg_indices]
return (Y,)
op = core.CreateOperator(
"PRelu", ["X", "W"], ["Y" if not inplace else "X"],
alpha=alpha, order=order)
self.assertReferenceChecks(gc, op, [X, W], prelu_ref, ensure_outputs_are_inferred=True)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [X, W], [0])
if not inplace:
# Gradient check wrt X
self.assertGradientChecks(gc, op, [X, W], 0, [0], stepsize=1e-2, ensure_outputs_are_inferred=True)
# Gradient check wrt W
self.assertGradientChecks(gc, op, [X, W], 1, [0], stepsize=1e-2, ensure_outputs_are_inferred=True)
@serial.given(X=hu.tensor(),
alpha=hu.floats(min_value=0.1, max_value=2.0),
inplace=st.booleans(),
**hu.gcs)
def test_leaky_relu(self, X, alpha, inplace, gc, dc):
# go away from the origin point to avoid kink problems
X += 0.04 * np.sign(X)
X[X == 0.0] += 0.04
def leaky_relu_ref(X):
Y = X.copy()
neg_indices = X <= 0
Y[neg_indices] = Y[neg_indices] * alpha
return (Y,)
op = core.CreateOperator(
"LeakyRelu",
["X"], ["Y" if not inplace else "X"],
alpha=alpha)
self.assertReferenceChecks(gc, op, [X], leaky_relu_ref,
ensure_outputs_are_inferred=True)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [X], [0])
@given(X=hu.tensor(),
inplace=st.booleans(),
**hu.gcs)
def test_leaky_relu_default(self, X, inplace, gc, dc):
# go away from the origin point to avoid kink problems
X += 0.04 * np.sign(X)
X[X == 0.0] += 0.04
def leaky_relu_ref(X):
Y = X.copy()
neg_indices = X <= 0
Y[neg_indices] = Y[neg_indices] * 0.01
return (Y,)
op = core.CreateOperator(
"LeakyRelu",
["X"], ["Y" if not inplace else "X"])
self.assertReferenceChecks(gc, op, [X], leaky_relu_ref)
# Check over multiple devices
self.assertDeviceChecks(dc, op, [X], [0])
@given(X=hu.tensor(),
fast_gelu=st.booleans(),
**hu.gcs)
@settings(deadline=10000)
def test_gelu(self, X, fast_gelu, gc, dc):
op = core.CreateOperator(
"Gelu",
["X"],
["Y"],
fast_gelu=fast_gelu,
)
def gelu_ref(X):
return (X * norm.cdf(X),)
tol = 1e-3 if fast_gelu else 1e-4
self.assertReferenceChecks(gc, op, [X], gelu_ref, threshold=tol,
ensure_outputs_are_inferred=True)
self.assertDeviceChecks(dc, op, [X], [0])
self.assertGradientChecks(gc, op, [X], 0, [0],
ensure_outputs_are_inferred=True)
@given(n=st.integers(0, 6), m=st.integers(4, 6),
seed=st.integers(0, 1000), **hu.gcs_cpu_only)
def test_mish(self, n, m, gc, dc, seed):
np.random.seed(seed)
X = np.random.rand(n, m).astype(np.float32)
def mish_ref(X):
return (X * np.tanh(np.log1p(np.exp(X))),)
op = core.CreateOperator(
"Mish",
["X"],
["Y"]
)
self.assertReferenceChecks(
device_option=gc,
op=op,
inputs=[X],
reference=mish_ref,
ensure_outputs_are_inferred=True,
)
self.assertGradientChecks(
gc, op, [X], 0, [0], ensure_outputs_are_inferred=True)
if __name__ == "__main__":
unittest.main()
|