Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/add.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/array_getitem.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/clipped_linear.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/clone.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/concatenate.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/hard_swish.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/hashembed.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/layernorm.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/list2ragged.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/reduce_mean.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/residual.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/sigmoid.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/softmax_activation.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/swish.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/tensorflowwrapper.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/with_flatten.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/with_signpost_interval.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/mxnet.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/pytorch.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/pytorch_grad_scaler.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/shim.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/tensorflow.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/torchscript.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/conftest.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/enable_mxnet.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/enable_tensorflow.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/strategies.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_config.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_examples.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_import__all__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_indexing.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_initializers.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_loss.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_optimizers.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_schedules.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_serialize.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_types_confection.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_util.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/util.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/__init__.py +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/test_mem.py +12 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/test_ops.py +1610 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/extra/__init__.py +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/extra/test_beam_search.py +5 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/__init__.py +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_basic_tagger.py +86 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_combinators.py +298 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_feed_forward.py +196 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/add.cpython-310.pyc
ADDED
|
Binary file (2.46 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/array_getitem.cpython-310.pyc
ADDED
|
Binary file (1.87 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/clipped_linear.cpython-310.pyc
ADDED
|
Binary file (3.82 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/clone.cpython-310.pyc
ADDED
|
Binary file (908 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/concatenate.cpython-310.pyc
ADDED
|
Binary file (6 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/hard_swish.cpython-310.pyc
ADDED
|
Binary file (2.34 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/hashembed.cpython-310.pyc
ADDED
|
Binary file (3.31 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/layernorm.cpython-310.pyc
ADDED
|
Binary file (2.94 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/list2ragged.cpython-310.pyc
ADDED
|
Binary file (1.49 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/reduce_mean.cpython-310.pyc
ADDED
|
Binary file (1.17 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/residual.cpython-310.pyc
ADDED
|
Binary file (2.36 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/sigmoid.cpython-310.pyc
ADDED
|
Binary file (2.22 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/softmax_activation.cpython-310.pyc
ADDED
|
Binary file (1.02 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/swish.cpython-310.pyc
ADDED
|
Binary file (2.32 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/tensorflowwrapper.cpython-310.pyc
ADDED
|
Binary file (6.33 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/with_flatten.cpython-310.pyc
ADDED
|
Binary file (2.14 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/with_signpost_interval.cpython-310.pyc
ADDED
|
Binary file (2.1 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (580 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/mxnet.cpython-310.pyc
ADDED
|
Binary file (4.97 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/pytorch.cpython-310.pyc
ADDED
|
Binary file (8.79 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/pytorch_grad_scaler.cpython-310.pyc
ADDED
|
Binary file (5.3 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/shim.cpython-310.pyc
ADDED
|
Binary file (3.62 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/tensorflow.cpython-310.pyc
ADDED
|
Binary file (9.09 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/torchscript.cpython-310.pyc
ADDED
|
Binary file (2.74 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (185 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/conftest.cpython-310.pyc
ADDED
|
Binary file (1.85 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/enable_mxnet.cpython-310.pyc
ADDED
|
Binary file (291 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/enable_tensorflow.cpython-310.pyc
ADDED
|
Binary file (301 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/strategies.cpython-310.pyc
ADDED
|
Binary file (4.31 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_config.cpython-310.pyc
ADDED
|
Binary file (6.75 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_examples.cpython-310.pyc
ADDED
|
Binary file (2.12 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_import__all__.cpython-310.pyc
ADDED
|
Binary file (2.22 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_indexing.cpython-310.pyc
ADDED
|
Binary file (2.48 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_initializers.cpython-310.pyc
ADDED
|
Binary file (1.25 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_loss.cpython-310.pyc
ADDED
|
Binary file (8.05 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_optimizers.cpython-310.pyc
ADDED
|
Binary file (4.12 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_schedules.cpython-310.pyc
ADDED
|
Binary file (2.17 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_serialize.cpython-310.pyc
ADDED
|
Binary file (7.99 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_types_confection.cpython-310.pyc
ADDED
|
Binary file (1.71 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_util.cpython-310.pyc
ADDED
|
Binary file (5 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/util.cpython-310.pyc
ADDED
|
Binary file (4.22 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/__init__.py
ADDED
|
File without changes
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/test_mem.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy
|
| 2 |
+
|
| 3 |
+
from thinc.backends._param_server import ParamServer
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_param_server_init():
|
| 7 |
+
array = numpy.zeros((5,), dtype="f")
|
| 8 |
+
params = {("a", 1): array, ("b", 2): array}
|
| 9 |
+
grads = {("a", 1): array, ("c", 3): array}
|
| 10 |
+
ps = ParamServer(params, grads)
|
| 11 |
+
assert ps.param_keys == (("a", 1), ("b", 2))
|
| 12 |
+
assert ps.grad_keys == (("a", 1),)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/test_ops.py
ADD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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import platform
|
| 3 |
+
from typing import Tuple, cast
|
| 4 |
+
|
| 5 |
+
import numpy
|
| 6 |
+
import pytest
|
| 7 |
+
from hypothesis import given, settings
|
| 8 |
+
from hypothesis.strategies import composite, integers
|
| 9 |
+
from numpy.testing import assert_allclose
|
| 10 |
+
from packaging.version import Version
|
| 11 |
+
|
| 12 |
+
from thinc.api import (
|
| 13 |
+
LSTM,
|
| 14 |
+
CupyOps,
|
| 15 |
+
NumpyOps,
|
| 16 |
+
Ops,
|
| 17 |
+
fix_random_seed,
|
| 18 |
+
get_current_ops,
|
| 19 |
+
get_ops,
|
| 20 |
+
use_ops,
|
| 21 |
+
)
|
| 22 |
+
from thinc.backends._custom_kernels import KERNELS, KERNELS_LIST, compile_mmh
|
| 23 |
+
from thinc.compat import has_cupy_gpu, has_torch, torch_version
|
| 24 |
+
from thinc.types import Floats2d
|
| 25 |
+
from thinc.util import torch2xp, xp2torch
|
| 26 |
+
|
| 27 |
+
from .. import strategies
|
| 28 |
+
from ..strategies import arrays_BI, ndarrays_of_shape
|
| 29 |
+
|
| 30 |
+
MAX_EXAMPLES = 10
|
| 31 |
+
|
| 32 |
+
VANILLA_OPS = Ops(numpy) # type: ignore
|
| 33 |
+
NUMPY_OPS = NumpyOps()
|
| 34 |
+
BLIS_OPS = NumpyOps(use_blis=True)
|
| 35 |
+
CPU_OPS = [NUMPY_OPS, VANILLA_OPS]
|
| 36 |
+
XP_OPS = [NUMPY_OPS]
|
| 37 |
+
if has_cupy_gpu:
|
| 38 |
+
XP_OPS.append(CupyOps())
|
| 39 |
+
ALL_OPS = XP_OPS + [VANILLA_OPS]
|
| 40 |
+
|
| 41 |
+
FLOAT_TYPES = ["float32", "float64"]
|
| 42 |
+
INT_TYPES = ["int32", "int64"]
|
| 43 |
+
|
| 44 |
+
REDUCTIONS = ["reduce_first", "reduce_last", "reduce_max", "reduce_mean", "reduce_sum"]
|
| 45 |
+
|
| 46 |
+
REDUCE_ZERO_LENGTH_RAISES = [
|
| 47 |
+
("reduce_first", True),
|
| 48 |
+
("reduce_last", True),
|
| 49 |
+
("reduce_max", True),
|
| 50 |
+
# From a mathematical perspective we'd want mean reduction to raise for
|
| 51 |
+
# zero-length sequences, since floating point numbers are not a monoid
|
| 52 |
+
# under averaging. However, floret relies on reduce_mean to return a
|
| 53 |
+
# zero-vector in this case.
|
| 54 |
+
("reduce_mean", False),
|
| 55 |
+
("reduce_sum", False),
|
| 56 |
+
]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def create_pytorch_funcs():
|
| 60 |
+
import math
|
| 61 |
+
|
| 62 |
+
import torch
|
| 63 |
+
|
| 64 |
+
def torch_relu(x):
|
| 65 |
+
return torch.nn.functional.relu(x)
|
| 66 |
+
|
| 67 |
+
def torch_relu_k(x):
|
| 68 |
+
return torch.nn.functional.relu6(x)
|
| 69 |
+
|
| 70 |
+
def torch_hard_sigmoid(x):
|
| 71 |
+
return torch.clip(x * 0.2 + 0.5, 0, 1)
|
| 72 |
+
|
| 73 |
+
def torch_hard_tanh(x):
|
| 74 |
+
return torch.nn.functional.hardtanh(x)
|
| 75 |
+
|
| 76 |
+
def torch_mish(x):
|
| 77 |
+
return torch.nn.functional.mish(x)
|
| 78 |
+
|
| 79 |
+
def torch_swish(x):
|
| 80 |
+
return torch.nn.functional.silu(x)
|
| 81 |
+
|
| 82 |
+
def torch_hard_swish(x):
|
| 83 |
+
return x * torch_hard_sigmoid(x)
|
| 84 |
+
|
| 85 |
+
def torch_hard_swish_mobilenet(x):
|
| 86 |
+
return torch.nn.functional.hardswish(x)
|
| 87 |
+
|
| 88 |
+
def torch_sigmoid(x):
|
| 89 |
+
return torch.sigmoid(x)
|
| 90 |
+
|
| 91 |
+
def torch_dish(x):
|
| 92 |
+
return 0.5 * x * (x / (1 + x * x).sqrt() + 1)
|
| 93 |
+
|
| 94 |
+
# https://github.com/huggingface/transformers/blob/master/src/transformers/activations.py#L37
|
| 95 |
+
def torch_gelu_approx(x):
|
| 96 |
+
return (
|
| 97 |
+
0.5
|
| 98 |
+
* x
|
| 99 |
+
* (
|
| 100 |
+
1.0
|
| 101 |
+
+ torch.tanh(
|
| 102 |
+
math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))
|
| 103 |
+
)
|
| 104 |
+
)
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
def torch_gelu(x):
|
| 108 |
+
return torch.nn.functional.gelu(x)
|
| 109 |
+
|
| 110 |
+
return [
|
| 111 |
+
("relu", torch_relu),
|
| 112 |
+
("relu_k", torch_relu_k),
|
| 113 |
+
("hard_sigmoid", torch_hard_sigmoid),
|
| 114 |
+
("hard_tanh", torch_hard_tanh),
|
| 115 |
+
("mish", torch_mish),
|
| 116 |
+
("swish", torch_swish),
|
| 117 |
+
("hard_swish", torch_hard_swish),
|
| 118 |
+
("hard_swish_mobilenet", torch_hard_swish_mobilenet),
|
| 119 |
+
("dish", torch_dish),
|
| 120 |
+
("gelu_approx", torch_gelu_approx),
|
| 121 |
+
("gelu", torch_gelu),
|
| 122 |
+
("sigmoid", torch_sigmoid),
|
| 123 |
+
]
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
if has_torch:
|
| 127 |
+
TORCH_FUNCS = create_pytorch_funcs()
|
| 128 |
+
else:
|
| 129 |
+
TORCH_FUNCS = []
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@pytest.mark.parametrize("op", [NumpyOps, CupyOps])
|
| 133 |
+
def test_ops_consistency(op):
|
| 134 |
+
"""Test that specific ops don't define any methods that are not on the
|
| 135 |
+
Ops base class and that all ops methods define the exact same arguments."""
|
| 136 |
+
attrs = [m for m in dir(op) if not m.startswith("_")]
|
| 137 |
+
for attr in attrs:
|
| 138 |
+
assert hasattr(Ops, attr)
|
| 139 |
+
method = getattr(op, attr)
|
| 140 |
+
if hasattr(method, "__call__"):
|
| 141 |
+
sig = inspect.signature(method)
|
| 142 |
+
params = [p for p in sig.parameters][1:]
|
| 143 |
+
base_sig = inspect.signature(getattr(Ops, attr))
|
| 144 |
+
print(base_sig)
|
| 145 |
+
base_params = [p for p in base_sig.parameters][1:]
|
| 146 |
+
assert params == base_params, attr
|
| 147 |
+
defaults = [p.default for p in sig.parameters.values()][1:]
|
| 148 |
+
base_defaults = [p.default for p in base_sig.parameters.values()][1:]
|
| 149 |
+
assert defaults == base_defaults, attr
|
| 150 |
+
# If args are type annotated, their types should be the same
|
| 151 |
+
annots = [p.annotation for p in sig.parameters.values()][1:]
|
| 152 |
+
base_annots = [p.annotation for p in base_sig.parameters.values()][1:]
|
| 153 |
+
for i, (p1, p2) in enumerate(zip(annots, base_annots)):
|
| 154 |
+
if p1 != inspect.Parameter.empty and p2 != inspect.Parameter.empty:
|
| 155 |
+
# TODO: This used to work, but not longer does in Cython 3.
|
| 156 |
+
# We're getting spurious differences.
|
| 157 |
+
# Need to check string value to handle TypeVars etc.
|
| 158 |
+
# assert str(p1) == str(p2), attr
|
| 159 |
+
pass
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 163 |
+
@pytest.mark.filterwarnings("ignore::RuntimeWarning")
|
| 164 |
+
def test_adam_incorrect_inputs(ops):
|
| 165 |
+
one = ops.xp.zeros(1, dtype="f")
|
| 166 |
+
two = ops.xp.zeros(2, dtype="f")
|
| 167 |
+
|
| 168 |
+
ops.adam(one, one, one, one, 0.0, 0.0, 0.0, 0.0)
|
| 169 |
+
with pytest.raises(ValueError):
|
| 170 |
+
ops.adam(two, one, one, one, 0.0, 0.0, 0.0, 0.0)
|
| 171 |
+
with pytest.raises(ValueError):
|
| 172 |
+
ops.adam(one, two, one, one, 0.0, 0.0, 0.0, 0.0)
|
| 173 |
+
with pytest.raises(ValueError):
|
| 174 |
+
ops.adam(one, one, two, one, 0.0, 0.0, 0.0, 0.0)
|
| 175 |
+
with pytest.raises(ValueError):
|
| 176 |
+
ops.adam(one, one, one, two, 0.0, 0.0, 0.0, 0.0)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 180 |
+
def test_alloc(ops):
|
| 181 |
+
float_methods = (ops.alloc1f, ops.alloc2f, ops.alloc3f, ops.alloc4f)
|
| 182 |
+
for i, method in enumerate(float_methods):
|
| 183 |
+
shape = (1,) * (i + 1)
|
| 184 |
+
arr = method(*shape)
|
| 185 |
+
assert arr.dtype == numpy.float32
|
| 186 |
+
assert arr.ndim == len(shape)
|
| 187 |
+
arr = ops.alloc_f(shape)
|
| 188 |
+
assert arr.dtype == numpy.float32
|
| 189 |
+
assert arr.ndim == len(shape)
|
| 190 |
+
int_methods = (ops.alloc1i, ops.alloc2i, ops.alloc3i, ops.alloc4i)
|
| 191 |
+
for i, method in enumerate(int_methods):
|
| 192 |
+
shape = (1,) * (i + 1)
|
| 193 |
+
arr = method(*shape)
|
| 194 |
+
assert arr.dtype == numpy.int32
|
| 195 |
+
assert arr.ndim == len(shape)
|
| 196 |
+
arr = ops.alloc_i(shape)
|
| 197 |
+
assert arr.dtype == numpy.int32
|
| 198 |
+
assert arr.ndim == len(shape)
|
| 199 |
+
assert ops.alloc(1).ndim == 1
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 203 |
+
def test_hash_gives_distinct_keys(ops):
|
| 204 |
+
ids = ops.alloc1f(5, dtype="uint64")
|
| 205 |
+
keys = ops.hash(ids, 0)
|
| 206 |
+
assert keys.shape == (5, 4)
|
| 207 |
+
assert keys.dtype == "uint32"
|
| 208 |
+
for i in range(len(ids)):
|
| 209 |
+
for j in range(keys.shape[1]):
|
| 210 |
+
assert keys[i, j] != 0
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 214 |
+
def test_get_dropout_empty(ops):
|
| 215 |
+
shape = (2, 2)
|
| 216 |
+
drop = 0.0
|
| 217 |
+
mask = ops.get_dropout_mask(shape, drop)
|
| 218 |
+
if drop <= 0.0:
|
| 219 |
+
assert mask[mask == 1.0].all()
|
| 220 |
+
else:
|
| 221 |
+
assert mask[mask != 1.0].all()
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 225 |
+
def test_get_dropout_not_empty(ops):
|
| 226 |
+
shape = (200, 200)
|
| 227 |
+
drop = 0.5
|
| 228 |
+
mask = ops.get_dropout_mask(shape, drop)
|
| 229 |
+
assert (mask > 1.0).any()
|
| 230 |
+
assert (mask == 0.0).any()
|
| 231 |
+
assert mask.shape == shape
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 235 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 236 |
+
@pytest.mark.parametrize("index_dtype", ["int32", "uint32"])
|
| 237 |
+
def test_gather_add(ops, dtype, index_dtype):
|
| 238 |
+
table = ops.xp.arange(12, dtype=dtype).reshape(4, 3)
|
| 239 |
+
indices = ops.xp.array([[0, 2], [3, 1], [0, 1]], dtype=index_dtype)
|
| 240 |
+
gathered = ops.gather_add(table, indices)
|
| 241 |
+
ops.xp.testing.assert_allclose(
|
| 242 |
+
gathered, [[6.0, 8.0, 10.0], [12.0, 14.0, 16.0], [3.0, 5.0, 7.0]]
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 247 |
+
@given(table=strategies.arrays_BI())
|
| 248 |
+
def test_gather_add_against_numpy(ops, table):
|
| 249 |
+
table = ops.asarray(table)
|
| 250 |
+
indices = ops.xp.arange(100, dtype="i").reshape(25, 4) % table.shape[0]
|
| 251 |
+
ops.xp.testing.assert_allclose(
|
| 252 |
+
ops.gather_add(table, indices),
|
| 253 |
+
table[indices].sum(1),
|
| 254 |
+
atol=1e-5,
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 259 |
+
def test_gather_add_oob_raises(ops):
|
| 260 |
+
table = ops.xp.arange(12, dtype="f").reshape(4, 3)
|
| 261 |
+
indices = ops.xp.array([[0, 2], [3, 1], [5, 1]], dtype="i")
|
| 262 |
+
with pytest.raises(IndexError):
|
| 263 |
+
ops.gather_add(table, indices)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@pytest.mark.parametrize("ops", CPU_OPS)
|
| 267 |
+
def test_seq2col_window_one_small(ops):
|
| 268 |
+
seq = ops.asarray([[1.0], [3.0], [4.0], [5]], dtype="float32")
|
| 269 |
+
cols = ops.seq2col(seq, 1)
|
| 270 |
+
if hasattr(cols, "get"):
|
| 271 |
+
cols = cols.get()
|
| 272 |
+
assert_allclose(cols[0], [0.0, 1.0, 3.0])
|
| 273 |
+
assert_allclose(cols[1], [1.0, 3.0, 4.0])
|
| 274 |
+
assert_allclose(cols[2], [3.0, 4.0, 5.0])
|
| 275 |
+
assert_allclose(cols[3], [4.0, 5.0, 0.0])
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 279 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 280 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 281 |
+
@given(X=strategies.arrays_BOP())
|
| 282 |
+
def test_maxout(ops, dtype, X):
|
| 283 |
+
X = ops.asarray(X, dtype=dtype)
|
| 284 |
+
expected_best = X.max(axis=-1).astype(dtype)
|
| 285 |
+
predicted_best, which = ops.maxout(X)
|
| 286 |
+
assert predicted_best.dtype == dtype
|
| 287 |
+
ops.xp.testing.assert_allclose(
|
| 288 |
+
expected_best, predicted_best, rtol=0.001, atol=0.001
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
# Can't compare 'which' directly, as sort order might be different.
|
| 292 |
+
# So, instead we use 'which' to extract elements from X and then
|
| 293 |
+
# check the result against the expected output.
|
| 294 |
+
ops.xp.testing.assert_allclose(
|
| 295 |
+
ops.xp.take_along_axis(X, ops.xp.expand_dims(which, -1), axis=-1),
|
| 296 |
+
ops.xp.expand_dims(expected_best, -1),
|
| 297 |
+
atol=1e-10,
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 302 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 303 |
+
def test_backprop_maxout(ops, dtype):
|
| 304 |
+
dX = ops.backprop_maxout(
|
| 305 |
+
ops.asarray2f([[1.0, 2.0], [3.0, 4.0]], dtype=dtype),
|
| 306 |
+
ops.asarray2i([[1, 0], [2, 1]]),
|
| 307 |
+
3,
|
| 308 |
+
)
|
| 309 |
+
assert dX.dtype == dtype
|
| 310 |
+
ops.xp.testing.assert_allclose(
|
| 311 |
+
dX,
|
| 312 |
+
[[[0.0, 1.0, 0.0], [2.0, 0.0, 0.0]], [[0.0, 0.0, 3.0], [0.0, 4.0, 0.0]]],
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
with pytest.raises(IndexError):
|
| 316 |
+
ops.backprop_maxout(
|
| 317 |
+
ops.asarray2f([[1.0, 2.0], [3.0, 4.0]]), ops.asarray2i([[1, 0], [3, 1]]), 3
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 322 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 323 |
+
@given(X=strategies.arrays_BI())
|
| 324 |
+
def test_seq2col_window_one(ops, X):
|
| 325 |
+
X = ops.asarray(X)
|
| 326 |
+
base_ops = Ops()
|
| 327 |
+
base_ops.xp = ops.xp
|
| 328 |
+
baseX = base_ops.alloc(X.shape) + X
|
| 329 |
+
target = base_ops.seq2col(base_ops.asarray(baseX), nW=1)
|
| 330 |
+
predicted = ops.seq2col(X, nW=1)
|
| 331 |
+
ops.xp.testing.assert_allclose(target, predicted, atol=0.001, rtol=0.001)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 335 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 336 |
+
def test_seq2col_lengths_all_zero(ops, dtype):
|
| 337 |
+
# Empty batch
|
| 338 |
+
ops.xp.testing.assert_allclose(
|
| 339 |
+
ops.alloc((0, 0), dtype=dtype),
|
| 340 |
+
ops.seq2col(
|
| 341 |
+
ops.alloc((0, 0), dtype=dtype), 1, lengths=ops.xp.zeros((0,), dtype="int32")
|
| 342 |
+
),
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
ops.xp.testing.assert_allclose(
|
| 346 |
+
ops.alloc((0, 0), dtype=dtype),
|
| 347 |
+
ops.backprop_seq2col(
|
| 348 |
+
ops.alloc((0, 0), dtype=dtype), 1, lengths=ops.xp.zeros((0,), dtype="int32")
|
| 349 |
+
),
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
# Zero-length sequence
|
| 353 |
+
ops.xp.testing.assert_allclose(
|
| 354 |
+
ops.alloc((0, 0), dtype=dtype),
|
| 355 |
+
ops.seq2col(ops.alloc((0, 0), dtype=dtype), 1, lengths=ops.asarray1i([0])),
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
ops.xp.testing.assert_allclose(
|
| 359 |
+
ops.alloc((0, 0), dtype=dtype),
|
| 360 |
+
ops.backprop_seq2col(
|
| 361 |
+
ops.alloc((0, 0), dtype=dtype), 1, lengths=ops.asarray1i([0])
|
| 362 |
+
),
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
# Multiple zero-length sequences
|
| 366 |
+
ops.xp.testing.assert_allclose(
|
| 367 |
+
ops.alloc((0, 0), dtype=dtype),
|
| 368 |
+
ops.seq2col(ops.alloc((0, 0), dtype=dtype), 1, lengths=ops.asarray1i([0, 0])),
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
ops.xp.testing.assert_allclose(
|
| 372 |
+
ops.alloc((0, 0), dtype=dtype),
|
| 373 |
+
ops.backprop_seq2col(
|
| 374 |
+
ops.alloc((0, 0), dtype=dtype), 1, lengths=ops.asarray1i([0, 0])
|
| 375 |
+
),
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 380 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 381 |
+
def test_seq2col_lengths_zero_first_last(ops, dtype):
|
| 382 |
+
cols_check = ops.asarray2f(
|
| 383 |
+
[
|
| 384 |
+
[0, 0, 0, 1, 2, 3, 4, 5, 6],
|
| 385 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9],
|
| 386 |
+
[4, 5, 6, 7, 8, 9, 10, 11, 12],
|
| 387 |
+
[7, 8, 9, 10, 11, 12, 13, 14, 15],
|
| 388 |
+
[10, 11, 12, 13, 14, 15, 0, 0, 0],
|
| 389 |
+
],
|
| 390 |
+
dtype=dtype,
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
grad_check = ops.asarray2f(
|
| 394 |
+
[[2, 4, 6], [12, 15, 18], [21, 24, 27], [30, 33, 36], [26, 28, 30]], dtype=dtype
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
# Initial zero-length sequence
|
| 398 |
+
ops.xp.testing.assert_allclose(
|
| 399 |
+
cols_check,
|
| 400 |
+
ops.seq2col(
|
| 401 |
+
ops.xp.arange(1.0, 16.0, dtype=dtype).reshape(5, 3),
|
| 402 |
+
1,
|
| 403 |
+
lengths=ops.asarray1i([0, 5]),
|
| 404 |
+
),
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
ops.xp.testing.assert_allclose(
|
| 408 |
+
grad_check,
|
| 409 |
+
ops.backprop_seq2col(
|
| 410 |
+
cols_check,
|
| 411 |
+
1,
|
| 412 |
+
lengths=ops.asarray1i([0, 5]),
|
| 413 |
+
),
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
# Final zero-length sequence.
|
| 417 |
+
ops.xp.testing.assert_allclose(
|
| 418 |
+
cols_check,
|
| 419 |
+
ops.seq2col(
|
| 420 |
+
ops.xp.arange(1.0, 16.0, dtype=dtype).reshape(5, 3),
|
| 421 |
+
1,
|
| 422 |
+
lengths=ops.asarray1i([5, 0]),
|
| 423 |
+
),
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 428 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 429 |
+
def test_seq2col_lengths_zero_between(ops, dtype):
|
| 430 |
+
cols_check = ops.asarray2f(
|
| 431 |
+
[
|
| 432 |
+
[0, 0, 0, 1, 2, 3, 4, 5, 6],
|
| 433 |
+
[1, 2, 3, 4, 5, 6, 7, 8, 9],
|
| 434 |
+
[4, 5, 6, 7, 8, 9, 10, 11, 12],
|
| 435 |
+
[7, 8, 9, 10, 11, 12, 13, 14, 15],
|
| 436 |
+
[10, 11, 12, 13, 14, 15, 0, 0, 0],
|
| 437 |
+
[0, 0, 0, 16, 17, 18, 19, 20, 21],
|
| 438 |
+
[16, 17, 18, 19, 20, 21, 0, 0, 0],
|
| 439 |
+
],
|
| 440 |
+
dtype=dtype,
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
grad_check = ops.asarray2f(
|
| 444 |
+
[
|
| 445 |
+
[2, 4, 6],
|
| 446 |
+
[12, 15, 18],
|
| 447 |
+
[21, 24, 27],
|
| 448 |
+
[30, 33, 36],
|
| 449 |
+
[26, 28, 30],
|
| 450 |
+
[32, 34, 36],
|
| 451 |
+
[38, 40, 42],
|
| 452 |
+
],
|
| 453 |
+
dtype=dtype,
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
# Zero-length between.
|
| 457 |
+
ops.xp.testing.assert_allclose(
|
| 458 |
+
cols_check,
|
| 459 |
+
ops.seq2col(
|
| 460 |
+
ops.xp.arange(1.0, 22.0, dtype=dtype).reshape(7, 3),
|
| 461 |
+
1,
|
| 462 |
+
lengths=ops.asarray1i([5, 0, 2]),
|
| 463 |
+
),
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
ops.xp.testing.assert_allclose(
|
| 467 |
+
grad_check,
|
| 468 |
+
ops.backprop_seq2col(
|
| 469 |
+
cols_check,
|
| 470 |
+
1,
|
| 471 |
+
lengths=ops.asarray1i([5, 0, 2]),
|
| 472 |
+
),
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
# Zero-length between twice.
|
| 476 |
+
ops.xp.testing.assert_allclose(
|
| 477 |
+
cols_check,
|
| 478 |
+
ops.seq2col(
|
| 479 |
+
ops.xp.arange(1.0, 22.0, dtype=dtype).reshape(7, 3),
|
| 480 |
+
1,
|
| 481 |
+
lengths=ops.asarray1i([5, 0, 0, 2]),
|
| 482 |
+
),
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
ops.xp.testing.assert_allclose(
|
| 486 |
+
grad_check,
|
| 487 |
+
ops.backprop_seq2col(
|
| 488 |
+
cols_check,
|
| 489 |
+
1,
|
| 490 |
+
lengths=ops.asarray1i([5, 0, 0, 2]),
|
| 491 |
+
),
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 496 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 497 |
+
def test_seq2col_window_one_lengths(ops, dtype):
|
| 498 |
+
X = ops.xp.arange(1.0, 16.0, dtype=dtype).reshape(5, 3)
|
| 499 |
+
lengths = ops.asarray1i([1, 3, 1])
|
| 500 |
+
cols = ops.seq2col(X, 1, lengths=lengths)
|
| 501 |
+
ops.xp.testing.assert_allclose(
|
| 502 |
+
ops.asarray2f(
|
| 503 |
+
[
|
| 504 |
+
[0, 0, 0, 1, 2, 3, 0, 0, 0],
|
| 505 |
+
[0, 0, 0, 4, 5, 6, 7, 8, 9],
|
| 506 |
+
[4, 5, 6, 7, 8, 9, 10, 11, 12],
|
| 507 |
+
[7, 8, 9, 10, 11, 12, 0, 0, 0],
|
| 508 |
+
[0, 0, 0, 13, 14, 15, 0, 0, 0],
|
| 509 |
+
],
|
| 510 |
+
dtype=dtype,
|
| 511 |
+
),
|
| 512 |
+
cols,
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 517 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 518 |
+
def test_seq2col_window_two_lengths(ops, dtype):
|
| 519 |
+
X = ops.xp.arange(1.0, 16.0, dtype=dtype).reshape(5, 3)
|
| 520 |
+
lengths = ops.asarray1i([1, 3, 1])
|
| 521 |
+
cols = ops.seq2col(X, 2, lengths=lengths)
|
| 522 |
+
ops.xp.testing.assert_allclose(
|
| 523 |
+
ops.asarray2f(
|
| 524 |
+
[
|
| 525 |
+
[0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0],
|
| 526 |
+
[0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 8, 9, 10, 11, 12],
|
| 527 |
+
[0, 0, 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0],
|
| 528 |
+
[4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 0, 0, 0],
|
| 529 |
+
[0, 0, 0, 0, 0, 0, 13, 14, 15, 0, 0, 0, 0, 0, 0],
|
| 530 |
+
],
|
| 531 |
+
dtype=dtype,
|
| 532 |
+
),
|
| 533 |
+
cols,
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 538 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 539 |
+
def test_backprop_seq2col_window_one_small(ops, dtype):
|
| 540 |
+
cols = ops.asarray(
|
| 541 |
+
[[0.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [2.0, 0.0, 0.0]], dtype=dtype
|
| 542 |
+
)
|
| 543 |
+
expected = [[-1.0], [2.0], [1.0]]
|
| 544 |
+
seq = ops.backprop_seq2col(cols, 1)
|
| 545 |
+
if not isinstance(seq, numpy.ndarray):
|
| 546 |
+
seq = seq.get()
|
| 547 |
+
assert_allclose(seq, expected, atol=0.001, rtol=0.001)
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 551 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 552 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 553 |
+
@given(X=strategies.arrays_BI())
|
| 554 |
+
def test_backprop_seq2col_window_one(ops, dtype, X):
|
| 555 |
+
if X.shape[1] % 3:
|
| 556 |
+
return None
|
| 557 |
+
X = ops.asarray(X, dtype=dtype)
|
| 558 |
+
if ops.xp.abs(X).max() >= 30:
|
| 559 |
+
return None
|
| 560 |
+
base_ops = Ops()
|
| 561 |
+
base_ops.xp = ops.xp
|
| 562 |
+
target = base_ops.backprop_seq2col(X, nW=1)
|
| 563 |
+
predicted = ops.backprop_seq2col(X, nW=1)
|
| 564 |
+
for row in range(target.shape[0]):
|
| 565 |
+
diff = target[row].sum() - predicted[row].sum()
|
| 566 |
+
if diff < -0.1 or diff > 0.1:
|
| 567 |
+
print(row, diff)
|
| 568 |
+
print(target[row])
|
| 569 |
+
print(predicted[row])
|
| 570 |
+
ops.xp.testing.assert_allclose(target, predicted, atol=0.001, rtol=0.001)
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 574 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 575 |
+
def test_backprop_seq2col_window_one_lengths(ops, dtype):
|
| 576 |
+
d_y = ops.xp.arange(0.1, 4.6, step=0.1, dtype=dtype).reshape(5, 9)
|
| 577 |
+
lengths = ops.asarray1i([1, 3, 1])
|
| 578 |
+
d_seqs = ops.backprop_seq2col(d_y, 1, lengths=lengths)
|
| 579 |
+
|
| 580 |
+
ops.xp.testing.assert_allclose(
|
| 581 |
+
ops.asarray2f(
|
| 582 |
+
[
|
| 583 |
+
[0.4, 0.5, 0.6],
|
| 584 |
+
[3.2, 3.4, 3.6],
|
| 585 |
+
[6.6, 6.9, 7.2],
|
| 586 |
+
[5.6, 5.8, 6.0],
|
| 587 |
+
[4.0, 4.1, 4.2],
|
| 588 |
+
],
|
| 589 |
+
dtype=dtype,
|
| 590 |
+
),
|
| 591 |
+
d_seqs,
|
| 592 |
+
atol=1e-6,
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 597 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 598 |
+
def test_seq2col_window_two(ops, dtype):
|
| 599 |
+
seq = ops.asarray([[1.0], [2.0], [3.0], [4]], dtype=dtype)
|
| 600 |
+
cols = ops.seq2col(seq, 2)
|
| 601 |
+
if not isinstance(cols, numpy.ndarray):
|
| 602 |
+
cols = cols.get()
|
| 603 |
+
assert_allclose(cols[0], [0.0, 0.0, 1.0, 2.0, 3.0])
|
| 604 |
+
assert_allclose(cols[1], [0.0, 1.0, 2.0, 3.0, 4.0])
|
| 605 |
+
assert_allclose(cols[2], [1.0, 2.0, 3.0, 4.0, 0.0])
|
| 606 |
+
assert_allclose(cols[3], [2.0, 3.0, 4.0, 0.0, 0.0])
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 610 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 611 |
+
def test_backprop_seq2col_window_two_lengths(ops, dtype):
|
| 612 |
+
d_y = ops.xp.arange(0.1, 7.6, step=0.1, dtype=dtype).reshape(5, 15)
|
| 613 |
+
lengths = ops.asarray1i([1, 3, 1])
|
| 614 |
+
d_seqs = ops.backprop_seq2col(d_y, 2, lengths=lengths)
|
| 615 |
+
|
| 616 |
+
ops.xp.testing.assert_allclose(
|
| 617 |
+
ops.asarray2f(
|
| 618 |
+
[
|
| 619 |
+
[0.7, 0.8, 0.9],
|
| 620 |
+
[10.2, 10.5, 10.8],
|
| 621 |
+
[11.1, 11.4, 11.7],
|
| 622 |
+
[12.0, 12.3, 12.6],
|
| 623 |
+
[6.7, 6.8, 6.9],
|
| 624 |
+
],
|
| 625 |
+
dtype=dtype,
|
| 626 |
+
),
|
| 627 |
+
d_seqs,
|
| 628 |
+
)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 632 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 633 |
+
def test_backprop_seq2col_window_two(ops, dtype):
|
| 634 |
+
cols = ops.asarray(
|
| 635 |
+
[
|
| 636 |
+
[0.0, 0.0, 1.0, 2.0, 3.0],
|
| 637 |
+
[0.0, 1.0, 2.0, 3.0, 4.0],
|
| 638 |
+
[1.0, 2.0, 3.0, 4.0, 0.0],
|
| 639 |
+
[2.0, 3.0, 4.0, 0.0, 0.0],
|
| 640 |
+
],
|
| 641 |
+
dtype=dtype,
|
| 642 |
+
)
|
| 643 |
+
# We're summing the values that each row
|
| 644 |
+
# was used as a feature. So row 0 had a
|
| 645 |
+
# gradient of 1 in row 0, 1 in row 2, and
|
| 646 |
+
# 1 in row 3.
|
| 647 |
+
expected = ops.asarray(
|
| 648 |
+
[
|
| 649 |
+
[1 + 1 + 1.0 + 0.0],
|
| 650 |
+
[2.0 + 2.0 + 2.0 + 2.0],
|
| 651 |
+
[3.0 + 3.0 + 3.0 + 3.0],
|
| 652 |
+
[0.0 + 4.0 + 4.0 + 4.0],
|
| 653 |
+
],
|
| 654 |
+
dtype=dtype,
|
| 655 |
+
)
|
| 656 |
+
seq = ops.backprop_seq2col(cols, 2)
|
| 657 |
+
ops.xp.testing.assert_allclose(seq, expected, atol=0.001, rtol=0.001)
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
@pytest.mark.skipif(not has_cupy_gpu, reason="needs GPU/CuPy")
|
| 661 |
+
@pytest.mark.parametrize("nW", [1, 2])
|
| 662 |
+
def test_large_seq2col_gpu_against_cpu(nW):
|
| 663 |
+
cupy_ops = CupyOps()
|
| 664 |
+
numpy_ops = NumpyOps()
|
| 665 |
+
|
| 666 |
+
# Use array with a large enough batch to require multiple
|
| 667 |
+
# CUDA grids.
|
| 668 |
+
batch_size = 128 * 128 * 2 # threads per block * blocks * 2
|
| 669 |
+
X = numpy_ops.xp.random.randn(batch_size * 2).astype("float32").reshape(-1, 2)
|
| 670 |
+
X_gpu = cupy_ops.asarray2f(X)
|
| 671 |
+
|
| 672 |
+
# Use somewhat interesting sequence lengths.
|
| 673 |
+
lengths = numpy_ops.asarray1i([1, 4, 2, 1] * (batch_size // 8))
|
| 674 |
+
lengths_gpu = cupy_ops.asarray1i(lengths)
|
| 675 |
+
|
| 676 |
+
cols = numpy_ops.seq2col(X, nW=nW, lengths=lengths)
|
| 677 |
+
cols_gpu = cupy_ops.seq2col(X_gpu, nW=nW, lengths=lengths_gpu)
|
| 678 |
+
|
| 679 |
+
assert_allclose(cols, cols_gpu.get())
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
@pytest.mark.skipif(not has_cupy_gpu, reason="needs GPU/CuPy")
|
| 683 |
+
@pytest.mark.parametrize("nW", [1, 2])
|
| 684 |
+
def test_large_backprop_seq2col_gpu_against_cpu(nW):
|
| 685 |
+
cupy_ops = CupyOps()
|
| 686 |
+
numpy_ops = NumpyOps()
|
| 687 |
+
|
| 688 |
+
# Use array with a large enough batch to require multiple
|
| 689 |
+
# CUDA grids.
|
| 690 |
+
batch_size = 128 * 128 * 2 # threads per block * blocks * 2
|
| 691 |
+
nF = 2 * nW + 1
|
| 692 |
+
d_cols = (
|
| 693 |
+
numpy_ops.xp.random.randn(batch_size * nF).astype("float32").reshape(-1, nF)
|
| 694 |
+
)
|
| 695 |
+
d_cols_gpu = cupy_ops.asarray2f(d_cols)
|
| 696 |
+
|
| 697 |
+
# Use somewhat interesting sequence lengths.
|
| 698 |
+
lengths = numpy_ops.asarray1i([1, 4, 2, 1] * (batch_size // 8))
|
| 699 |
+
lengths_gpu = cupy_ops.asarray1i(lengths)
|
| 700 |
+
|
| 701 |
+
d_seqs = numpy_ops.backprop_seq2col(d_cols, nW=nW, lengths=lengths)
|
| 702 |
+
d_seqs_gpu = cupy_ops.backprop_seq2col(d_cols_gpu, nW=nW, lengths=lengths_gpu)
|
| 703 |
+
|
| 704 |
+
assert_allclose(d_seqs, d_seqs_gpu.get())
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 708 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 709 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 710 |
+
@given(X=strategies.arrays_BI())
|
| 711 |
+
def test_backprop_reduce_sum(ops, dtype, X):
|
| 712 |
+
X = ops.asarray(X, dtype=dtype)
|
| 713 |
+
if ops.xp.abs(X).max() >= 5:
|
| 714 |
+
return None
|
| 715 |
+
lengths = ops.asarray([3] * len(X), dtype="i")
|
| 716 |
+
out = ops.backprop_reduce_sum(X, lengths)
|
| 717 |
+
assert out.dtype == dtype
|
| 718 |
+
assert out.shape == (sum(lengths), X.shape[1])
|
| 719 |
+
start = 0
|
| 720 |
+
for i, length in enumerate(lengths):
|
| 721 |
+
ops.xp.testing.assert_allclose(
|
| 722 |
+
out[start : start + length].sum(axis=0), X[i] * length, rtol=0.01, atol=0.01
|
| 723 |
+
)
|
| 724 |
+
start += length
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 728 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 729 |
+
@given(X=strategies.arrays_BI())
|
| 730 |
+
def test_softmax_sums_to_one(ops, X):
|
| 731 |
+
y = ops.softmax(ops.asarray(X))
|
| 732 |
+
for row in y:
|
| 733 |
+
assert 0.99999 <= row.sum() <= 1.0001
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 737 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 738 |
+
@given(X=strategies.arrays_BI())
|
| 739 |
+
def test_softmax_works_inplace(ops, X):
|
| 740 |
+
X = ops.asarray(X)
|
| 741 |
+
X = ops.softmax(X, inplace=True)
|
| 742 |
+
for row in X:
|
| 743 |
+
assert 0.99999 <= row.sum() <= 1.00001
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
def torch_softmax_with_temperature(
|
| 747 |
+
X: Floats2d, dY: Floats2d, temperature: float
|
| 748 |
+
) -> Tuple[Floats2d, Floats2d]:
|
| 749 |
+
import torch
|
| 750 |
+
|
| 751 |
+
Xt = xp2torch(X, requires_grad=True)
|
| 752 |
+
dYt = xp2torch(dY)
|
| 753 |
+
|
| 754 |
+
Xt_temp = Xt / temperature
|
| 755 |
+
|
| 756 |
+
Yt = torch.nn.functional.softmax(Xt_temp, dim=-1)
|
| 757 |
+
Yt.backward(dYt)
|
| 758 |
+
|
| 759 |
+
return cast(Floats2d, torch2xp(Yt)), cast(
|
| 760 |
+
Floats2d, torch2xp(cast(torch.Tensor, Xt.grad))
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
@pytest.mark.skipif(not has_torch, reason="needs PyTorch")
|
| 765 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 766 |
+
@pytest.mark.parametrize("temperature", [0.5, 1.0, 2.0])
|
| 767 |
+
def test_softmax_temperature(ops, temperature):
|
| 768 |
+
X = ops.xp.arange(-10, 10, 0.2, dtype="f").reshape(10, 10)
|
| 769 |
+
dY = ops.xp.eye(10, dtype="f")
|
| 770 |
+
|
| 771 |
+
Y = ops.softmax(X, temperature=temperature)
|
| 772 |
+
dX = ops.backprop_softmax(Y, dY, temperature=temperature)
|
| 773 |
+
|
| 774 |
+
Yt, dXt = torch_softmax_with_temperature(X, dY, temperature)
|
| 775 |
+
|
| 776 |
+
ops.xp.testing.assert_allclose(Y, Yt, atol=1e-6)
|
| 777 |
+
ops.xp.testing.assert_allclose(dX, dXt, atol=1e-6)
|
| 778 |
+
|
| 779 |
+
|
| 780 |
+
@pytest.mark.parametrize("cpu_ops", [*CPU_OPS, BLIS_OPS])
|
| 781 |
+
def test_gemm_computes_correctly(cpu_ops):
|
| 782 |
+
W = numpy.zeros((3, 2), dtype="f")
|
| 783 |
+
X = numpy.zeros((4, 2), dtype="f")
|
| 784 |
+
W += numpy.random.uniform(size=W.size).reshape(W.shape)
|
| 785 |
+
X += numpy.random.uniform(size=X.size).reshape(X.shape)
|
| 786 |
+
Y = cpu_ops.gemm(X, W, trans2=True)
|
| 787 |
+
expected = numpy.dot(X, W.T)
|
| 788 |
+
assert_allclose(expected, Y, atol=1e-4, rtol=1e-4)
|
| 789 |
+
W = numpy.zeros((2, 3), dtype="f")
|
| 790 |
+
X = numpy.zeros((2, 4), dtype="f")
|
| 791 |
+
W += numpy.random.uniform(size=W.size).reshape(W.shape)
|
| 792 |
+
X += numpy.random.uniform(size=X.size).reshape(X.shape)
|
| 793 |
+
Y = cpu_ops.gemm(X, W, trans1=True)
|
| 794 |
+
expected = numpy.dot(X.T, W)
|
| 795 |
+
assert_allclose(expected, Y, atol=1e-4, rtol=1e-4)
|
| 796 |
+
cpu_ops.gemm(X, W, trans1=True, out=Y)
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
@pytest.mark.parametrize("cpu_ops", [*CPU_OPS, BLIS_OPS])
|
| 800 |
+
def test_gemm_out_used(cpu_ops):
|
| 801 |
+
a = b = numpy.zeros((2, 2), dtype="f")
|
| 802 |
+
c = numpy.ones((2, 2), dtype="f")
|
| 803 |
+
cpu_ops.gemm(a, b, out=c)
|
| 804 |
+
assert numpy.array_equal(c, numpy.zeros((2, 2)))
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
@pytest.mark.parametrize("cpu_ops", CPU_OPS)
|
| 808 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 809 |
+
@given(X=strategies.arrays_BI())
|
| 810 |
+
def test_flatten_unflatten_roundtrip(cpu_ops, X):
|
| 811 |
+
flat = cpu_ops.flatten([x for x in X])
|
| 812 |
+
assert flat.ndim == 1
|
| 813 |
+
unflat = cpu_ops.unflatten(flat, [len(x) for x in X])
|
| 814 |
+
assert_allclose(X, unflat)
|
| 815 |
+
flat2 = cpu_ops.flatten([x for x in X], pad=1, dtype="f")
|
| 816 |
+
assert len(flat2) > len(flat)
|
| 817 |
+
unflat2 = cpu_ops.unflatten(flat2, [len(x) for x in X], pad=1)
|
| 818 |
+
assert_allclose(X, unflat2)
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 822 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES + INT_TYPES)
|
| 823 |
+
def test_pad(ops, dtype):
|
| 824 |
+
X = [ops.xp.arange(1, 3, dtype=dtype), ops.xp.arange(1, 5, dtype=dtype)]
|
| 825 |
+
ops.xp.testing.assert_allclose(ops.pad(X), [[1, 2, 0, 0], [1, 2, 3, 4]])
|
| 826 |
+
ops.xp.testing.assert_allclose(
|
| 827 |
+
ops.pad(X, round_to=8), [[1, 2, 0, 0, 0, 0, 0, 0], [1, 2, 3, 4, 0, 0, 0, 0]]
|
| 828 |
+
)
|
| 829 |
+
|
| 830 |
+
X = [
|
| 831 |
+
ops.xp.arange(1, 5, dtype=dtype).reshape(2, 2),
|
| 832 |
+
ops.xp.arange(1, 9, dtype=dtype).reshape(4, 2),
|
| 833 |
+
]
|
| 834 |
+
ops.xp.testing.assert_allclose(
|
| 835 |
+
ops.pad(X),
|
| 836 |
+
[
|
| 837 |
+
[[1, 2], [3, 4], [0, 0], [0, 0]],
|
| 838 |
+
[[1, 2], [3, 4], [5, 6], [7, 8]],
|
| 839 |
+
],
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
ops.xp.testing.assert_allclose(
|
| 843 |
+
ops.pad(X, round_to=5),
|
| 844 |
+
[
|
| 845 |
+
[[1, 2], [3, 4], [0, 0], [0, 0], [0, 0]],
|
| 846 |
+
[[1, 2], [3, 4], [5, 6], [7, 8], [0, 0]],
|
| 847 |
+
],
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
with pytest.raises(ValueError, match=r"Rounding for padding must at least be 1"):
|
| 851 |
+
ops.pad(X, round_to=0)
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 855 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 856 |
+
def test_reduce_sum(ops, dtype):
|
| 857 |
+
X = ops.asarray2f(
|
| 858 |
+
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [1.0, 2.0], [3.0, 4.0]], dtype=dtype
|
| 859 |
+
)
|
| 860 |
+
lengths = ops.asarray1i([3, 2])
|
| 861 |
+
ops.xp.testing.assert_allclose(
|
| 862 |
+
ops.reduce_sum(X, lengths), [[9.0, 12.0], [4.0, 6.0]]
|
| 863 |
+
)
|
| 864 |
+
|
| 865 |
+
# Zero-length array
|
| 866 |
+
lengths = ops.asarray1i([3, 0, 2])
|
| 867 |
+
ops.xp.testing.assert_allclose(
|
| 868 |
+
ops.reduce_sum(X, lengths), [[9.0, 12.0], [0.0, 0.0], [4.0, 6.0]]
|
| 869 |
+
)
|
| 870 |
+
|
| 871 |
+
with pytest.raises(IndexError):
|
| 872 |
+
ops.reduce_sum(X, ops.xp.array([5, 5, 5, 5], dtype="i"))
|
| 873 |
+
|
| 874 |
+
with pytest.raises(ValueError):
|
| 875 |
+
ops.reduce_sum(X, ops.xp.array([-1, 10, 5, 5], dtype="i"))
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 879 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 880 |
+
def test_backprop_fails_with_incorrect_length(ops, dtype):
|
| 881 |
+
with pytest.raises(ValueError, match=r"lengths must be"):
|
| 882 |
+
ops.backprop_reduce_sum(
|
| 883 |
+
ops.xp.arange(1, 7, dtype=dtype).reshape(2, 3),
|
| 884 |
+
ops.xp.array([-1, 2], dtype="int32"),
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 889 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 890 |
+
def test_reduce_first(ops, dtype):
|
| 891 |
+
X = ops.asarray2f(
|
| 892 |
+
[[1.0, 6.0], [2.0, 7.0], [3.0, 8.0], [4.0, 9.0], [5.0, 10.0]], dtype=dtype
|
| 893 |
+
)
|
| 894 |
+
lengths = ops.asarray1i([3, 2])
|
| 895 |
+
Y, starts_ends = ops.reduce_first(X, lengths)
|
| 896 |
+
ops.xp.testing.assert_array_equal(starts_ends, ops.asarray1i([0, 3, 5]))
|
| 897 |
+
ops.xp.testing.assert_allclose(Y, [[1.0, 6.0], [4.0, 9.0]])
|
| 898 |
+
|
| 899 |
+
lengths = ops.asarray1i([3, 0, 2])
|
| 900 |
+
with pytest.raises(ValueError, match=r"all sequence lengths must be > 0"):
|
| 901 |
+
ops.reduce_last(X, lengths)
|
| 902 |
+
|
| 903 |
+
lengths = ops.asarray1i([3, 2, 1])
|
| 904 |
+
with pytest.raises(IndexError, match=r"lengths must sum up to the number of rows"):
|
| 905 |
+
ops.reduce_last(X, lengths)
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 909 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 910 |
+
def test_backprop_reduce_first(ops, dtype):
|
| 911 |
+
dY = ops.asarray2f([[1.0, 3.0], [2.0, 4.0]], dtype=dtype)
|
| 912 |
+
starts_ends = ops.asarray1i([0, 3, 5])
|
| 913 |
+
dX = ops.backprop_reduce_first(dY, starts_ends)
|
| 914 |
+
ops.xp.testing.assert_allclose(
|
| 915 |
+
dX, [[1.0, 3.0], [0.0, 0.0], [0.0, 0.0], [2.0, 4.0], [0.0, 0.0]]
|
| 916 |
+
)
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 920 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 921 |
+
def test_reduce_last(ops, dtype):
|
| 922 |
+
X = ops.asarray2f(
|
| 923 |
+
[[1.0, 6.0], [2.0, 7.0], [3.0, 8.0], [4.0, 9.0], [5.0, 10.0]], dtype=dtype
|
| 924 |
+
)
|
| 925 |
+
lengths = ops.asarray1i([3, 2])
|
| 926 |
+
Y, lasts = ops.reduce_last(X, lengths)
|
| 927 |
+
ops.xp.testing.assert_array_equal(lasts, ops.asarray1i([2, 4]))
|
| 928 |
+
ops.xp.testing.assert_allclose(Y, [[3.0, 8.0], [5.0, 10.0]])
|
| 929 |
+
|
| 930 |
+
lengths = ops.asarray1i([3, 0, 2])
|
| 931 |
+
with pytest.raises(ValueError, match=r"all sequence lengths must be > 0"):
|
| 932 |
+
ops.reduce_last(X, lengths)
|
| 933 |
+
|
| 934 |
+
lengths = ops.asarray1i([3, 2, 1])
|
| 935 |
+
with pytest.raises(IndexError, match=r"lengths must sum up to the number of rows"):
|
| 936 |
+
ops.reduce_last(X, lengths)
|
| 937 |
+
|
| 938 |
+
|
| 939 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 940 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 941 |
+
def test_backprop_reduce_last(ops, dtype):
|
| 942 |
+
dY = ops.asarray2f([[1.0, 3.0], [2.0, 4.0]], dtype=dtype)
|
| 943 |
+
lasts = ops.asarray1i([2, 4])
|
| 944 |
+
dX = ops.backprop_reduce_last(dY, lasts)
|
| 945 |
+
ops.xp.testing.assert_allclose(
|
| 946 |
+
dX, [[0.0, 0.0], [0.0, 0.0], [1.0, 3.0], [0.0, 0.0], [2.0, 4.0]]
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 951 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 952 |
+
def test_reduce_max_sm(ops, dtype):
|
| 953 |
+
X = ops.xp.zeros((6, 3), dtype=dtype)
|
| 954 |
+
X += ops.xp.random.uniform(-1, 1, X.shape)
|
| 955 |
+
lengths = ops.xp.array([2, 2, 2], dtype="i")
|
| 956 |
+
maxes, which = ops.reduce_max(X, lengths)
|
| 957 |
+
assert maxes.dtype == dtype
|
| 958 |
+
assert ops.xp.all(which >= 0)
|
| 959 |
+
assert ops.xp.all(which < X.shape[0])
|
| 960 |
+
|
| 961 |
+
start = 0
|
| 962 |
+
for i, length in enumerate(lengths):
|
| 963 |
+
truth = X[start : start + length].max(axis=0)
|
| 964 |
+
ops.xp.testing.assert_allclose(maxes[i], truth)
|
| 965 |
+
start += length
|
| 966 |
+
|
| 967 |
+
|
| 968 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 969 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 970 |
+
def test_reduce_max(ops, dtype):
|
| 971 |
+
m = ops.xp.zeros((19, 5), dtype=dtype)
|
| 972 |
+
m += ops.xp.random.uniform(-1, 1, m.shape)
|
| 973 |
+
lengths = ops.xp.array([5, 5, 3, 6], dtype="i")
|
| 974 |
+
# m[4, 0] = 1
|
| 975 |
+
# m[0, 1] = 2
|
| 976 |
+
# m[1, 3] = 3
|
| 977 |
+
maxes, which = ops.reduce_max(m, lengths)
|
| 978 |
+
assert maxes.dtype == dtype
|
| 979 |
+
assert ops.xp.all(which >= 0)
|
| 980 |
+
assert ops.xp.all(which < m.shape[0])
|
| 981 |
+
|
| 982 |
+
start = 0
|
| 983 |
+
for i, length in enumerate(lengths):
|
| 984 |
+
truth = m[start : start + length].max(axis=0)
|
| 985 |
+
ops.xp.testing.assert_allclose(maxes[i], truth)
|
| 986 |
+
start += length
|
| 987 |
+
|
| 988 |
+
with pytest.raises(IndexError):
|
| 989 |
+
ops.reduce_max(m, ops.xp.array([5, 5, 5, 5], dtype="i"))
|
| 990 |
+
|
| 991 |
+
with pytest.raises(ValueError):
|
| 992 |
+
ops.reduce_max(m, ops.xp.array([-1, 10, 5, 5], dtype="i"))
|
| 993 |
+
|
| 994 |
+
with pytest.raises(ValueError):
|
| 995 |
+
ops.reduce_max(m, ops.xp.array([5, 5, 0, 3, 6], dtype="i"))
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 999 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 1000 |
+
def test_backprop_reduce_max(ops, dtype):
|
| 1001 |
+
dX = ops.backprop_reduce_max(
|
| 1002 |
+
ops.xp.arange(1, 7, dtype=dtype).reshape(2, 3),
|
| 1003 |
+
ops.xp.array([[2, 1, 0], [1, 0, 1]]).astype("int32"),
|
| 1004 |
+
ops.xp.array([3, 2], dtype="int32"),
|
| 1005 |
+
)
|
| 1006 |
+
assert dX.dtype == dtype
|
| 1007 |
+
ops.xp.testing.assert_allclose(
|
| 1008 |
+
dX,
|
| 1009 |
+
[
|
| 1010 |
+
[0.0, 0.0, 3.0],
|
| 1011 |
+
[0.0, 2.0, 0.0],
|
| 1012 |
+
[1.0, 0.0, 0.0],
|
| 1013 |
+
[0.0, 5.0, 0.0],
|
| 1014 |
+
[4.0, 0.0, 6.0],
|
| 1015 |
+
],
|
| 1016 |
+
)
|
| 1017 |
+
|
| 1018 |
+
with pytest.raises(IndexError):
|
| 1019 |
+
ops.backprop_reduce_max(
|
| 1020 |
+
ops.xp.arange(1, 7, dtype="f").reshape(2, 3),
|
| 1021 |
+
ops.xp.array([[2, 3, 0], [1, 0, 1]]).astype("int32"),
|
| 1022 |
+
ops.xp.array([3, 2], dtype="int32"),
|
| 1023 |
+
)
|
| 1024 |
+
|
| 1025 |
+
with pytest.raises(ValueError):
|
| 1026 |
+
ops.backprop_reduce_max(
|
| 1027 |
+
ops.xp.arange(1, 7, dtype=dtype).reshape(2, 3),
|
| 1028 |
+
ops.xp.array([[2, 1, 0], [1, 0, 1]]).astype("int32"),
|
| 1029 |
+
ops.xp.array([-3, 2], dtype="int32"),
|
| 1030 |
+
)
|
| 1031 |
+
|
| 1032 |
+
with pytest.raises(ValueError):
|
| 1033 |
+
ops.backprop_reduce_max(
|
| 1034 |
+
ops.xp.arange(1, 7, dtype=dtype).reshape(2, 3),
|
| 1035 |
+
ops.xp.array([[2, 1, 0], [1, 0, 1], [1, 0, 1]]).astype("int32"),
|
| 1036 |
+
ops.xp.array([3, 0, 2], dtype="int32"),
|
| 1037 |
+
)
|
| 1038 |
+
|
| 1039 |
+
|
| 1040 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1041 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 1042 |
+
def test_reduce_mean(ops, dtype):
|
| 1043 |
+
X = ops.asarray2f(
|
| 1044 |
+
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [1.0, 2.0], [3.0, 4.0]], dtype=dtype
|
| 1045 |
+
)
|
| 1046 |
+
lengths = ops.asarray1i([3, 2])
|
| 1047 |
+
ops.xp.testing.assert_allclose(
|
| 1048 |
+
ops.reduce_mean(X, lengths), [[3.0, 4.0], [2.0, 3.0]]
|
| 1049 |
+
)
|
| 1050 |
+
|
| 1051 |
+
# Zero-length array
|
| 1052 |
+
lengths = ops.asarray1i([3, 0, 2])
|
| 1053 |
+
ops.xp.testing.assert_allclose(
|
| 1054 |
+
ops.reduce_mean(X, lengths), [[3.0, 4.0], [0.0, 0.0], [2.0, 3.0]]
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
# Zero-length array last.
|
| 1058 |
+
X = ops.asarray2f([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=dtype)
|
| 1059 |
+
lengths = ops.asarray1i([3, 0])
|
| 1060 |
+
ops.xp.testing.assert_allclose(
|
| 1061 |
+
ops.reduce_mean(X, lengths), [[3.0, 4.0], [0.0, 0.0]]
|
| 1062 |
+
)
|
| 1063 |
+
|
| 1064 |
+
with pytest.raises(IndexError):
|
| 1065 |
+
ops.reduce_mean(X, ops.xp.array([3, 3], dtype="i"))
|
| 1066 |
+
|
| 1067 |
+
with pytest.raises(ValueError):
|
| 1068 |
+
ops.reduce_mean(X, ops.xp.array([-1, 5], dtype="i"))
|
| 1069 |
+
|
| 1070 |
+
|
| 1071 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1072 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 1073 |
+
def test_backprop_reduce_mean(ops, dtype):
|
| 1074 |
+
dX = ops.backprop_reduce_mean(
|
| 1075 |
+
ops.xp.arange(1, 7, dtype=dtype).reshape(2, 3),
|
| 1076 |
+
ops.xp.array([4, 2], dtype="int32"),
|
| 1077 |
+
)
|
| 1078 |
+
assert dX.dtype == dtype
|
| 1079 |
+
ops.xp.testing.assert_allclose(
|
| 1080 |
+
dX,
|
| 1081 |
+
[
|
| 1082 |
+
[0.25, 0.5, 0.75],
|
| 1083 |
+
[0.25, 0.5, 0.75],
|
| 1084 |
+
[0.25, 0.5, 0.75],
|
| 1085 |
+
[0.25, 0.5, 0.75],
|
| 1086 |
+
[2.0, 2.5, 3.0],
|
| 1087 |
+
[2.0, 2.5, 3.0],
|
| 1088 |
+
],
|
| 1089 |
+
)
|
| 1090 |
+
|
| 1091 |
+
with pytest.raises(ValueError, match=r"lengths must be"):
|
| 1092 |
+
ops.backprop_reduce_mean(
|
| 1093 |
+
ops.xp.arange(1, 7, dtype=dtype).reshape(2, 3),
|
| 1094 |
+
ops.xp.array([-1, 2], dtype="int32"),
|
| 1095 |
+
)
|
| 1096 |
+
|
| 1097 |
+
|
| 1098 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1099 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 1100 |
+
@pytest.mark.parametrize("reduction", REDUCTIONS)
|
| 1101 |
+
def test_reduce_empty_batch(ops, dtype, reduction):
|
| 1102 |
+
func = getattr(ops, reduction)
|
| 1103 |
+
backprop_func = getattr(ops, f"backprop_{reduction}")
|
| 1104 |
+
|
| 1105 |
+
lengths = ops.asarray1i([])
|
| 1106 |
+
Y = func(ops.alloc((0, 10), dtype=dtype), lengths)
|
| 1107 |
+
|
| 1108 |
+
if reduction == "reduce_max":
|
| 1109 |
+
Y, which = Y
|
| 1110 |
+
dX = backprop_func(Y, which, lengths)
|
| 1111 |
+
elif isinstance(Y, tuple):
|
| 1112 |
+
Y, extra = Y
|
| 1113 |
+
dX = backprop_func(Y, extra)
|
| 1114 |
+
else:
|
| 1115 |
+
dX = backprop_func(Y, lengths)
|
| 1116 |
+
|
| 1117 |
+
assert Y.shape == (0, 10)
|
| 1118 |
+
assert dX.shape == (0, 10)
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1122 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 1123 |
+
@pytest.mark.parametrize("reduction", REDUCTIONS)
|
| 1124 |
+
def test_reduce_empty_hidden(ops, dtype, reduction):
|
| 1125 |
+
func = getattr(ops, reduction)
|
| 1126 |
+
backprop_func = getattr(ops, f"backprop_{reduction}")
|
| 1127 |
+
|
| 1128 |
+
lengths = ops.asarray1i([2, 3])
|
| 1129 |
+
Y = func(ops.alloc((5, 0), dtype=dtype), lengths)
|
| 1130 |
+
|
| 1131 |
+
if reduction == "reduce_max":
|
| 1132 |
+
Y, which = Y
|
| 1133 |
+
dX = backprop_func(Y, which, lengths)
|
| 1134 |
+
elif isinstance(Y, tuple):
|
| 1135 |
+
Y, extra = Y
|
| 1136 |
+
dX = backprop_func(Y, extra)
|
| 1137 |
+
else:
|
| 1138 |
+
dX = backprop_func(Y, lengths)
|
| 1139 |
+
|
| 1140 |
+
assert Y.shape == (2, 0)
|
| 1141 |
+
assert dX.shape == (5, 0)
|
| 1142 |
+
|
| 1143 |
+
|
| 1144 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1145 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 1146 |
+
@pytest.mark.parametrize("reduction_raises", REDUCE_ZERO_LENGTH_RAISES)
|
| 1147 |
+
def test_reduce_zero_seq_length(ops, dtype, reduction_raises):
|
| 1148 |
+
reduction_str, raises = reduction_raises
|
| 1149 |
+
reduction = getattr(ops, reduction_str)
|
| 1150 |
+
X = ops.asarray2f(
|
| 1151 |
+
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [1.0, 2.0], [3.0, 4.0]], dtype=dtype
|
| 1152 |
+
)
|
| 1153 |
+
lengths = ops.asarray1i([3, 0, 2])
|
| 1154 |
+
|
| 1155 |
+
if raises:
|
| 1156 |
+
with pytest.raises(ValueError):
|
| 1157 |
+
reduction(X, lengths)
|
| 1158 |
+
else:
|
| 1159 |
+
# All non-raising reductions have zero as their identity element.
|
| 1160 |
+
ops.xp.testing.assert_allclose(reduction(X, lengths)[1], [0.0, 0.0])
|
| 1161 |
+
|
| 1162 |
+
|
| 1163 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1164 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1165 |
+
@given(X=strategies.arrays_BI())
|
| 1166 |
+
def test_mish(ops, X):
|
| 1167 |
+
X = ops.asarray(X)
|
| 1168 |
+
Y = ops.mish(X)
|
| 1169 |
+
assert Y.shape == X.shape
|
| 1170 |
+
assert not ops.xp.isnan(Y).any()
|
| 1171 |
+
|
| 1172 |
+
|
| 1173 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 1174 |
+
@pytest.mark.parametrize("dtype", FLOAT_TYPES)
|
| 1175 |
+
@pytest.mark.parametrize(
|
| 1176 |
+
"op",
|
| 1177 |
+
[
|
| 1178 |
+
"backprop_clipped_linear",
|
| 1179 |
+
"backprop_dish",
|
| 1180 |
+
"backprop_gelu",
|
| 1181 |
+
"backprop_gelu_approx",
|
| 1182 |
+
"backprop_hard_sigmoid",
|
| 1183 |
+
"backprop_hard_swish",
|
| 1184 |
+
"backprop_hard_swish_mobilenet",
|
| 1185 |
+
"backprop_hard_tanh",
|
| 1186 |
+
"backprop_mish",
|
| 1187 |
+
"backprop_relu",
|
| 1188 |
+
"backprop_relu_k",
|
| 1189 |
+
"backprop_softmax",
|
| 1190 |
+
"backprop_swish",
|
| 1191 |
+
],
|
| 1192 |
+
)
|
| 1193 |
+
def test_eltwise_backprop_rejects_incorrect_shapes(ops, dtype, op):
|
| 1194 |
+
backprop = getattr(ops, op)
|
| 1195 |
+
positional_args = [
|
| 1196 |
+
p
|
| 1197 |
+
for p in inspect.signature(backprop).parameters.values()
|
| 1198 |
+
if p.default == inspect.Parameter.empty
|
| 1199 |
+
]
|
| 1200 |
+
if len(positional_args) == 3:
|
| 1201 |
+
with pytest.raises(ValueError):
|
| 1202 |
+
backprop(
|
| 1203 |
+
ops.xp.zeros(10, dtype=dtype),
|
| 1204 |
+
ops.xp.zeros(5, dtype=dtype),
|
| 1205 |
+
ops.xp.zeros(10, dtype=dtype),
|
| 1206 |
+
)
|
| 1207 |
+
with pytest.raises(ValueError):
|
| 1208 |
+
backprop(
|
| 1209 |
+
ops.xp.zeros(10, dtype=dtype),
|
| 1210 |
+
ops.xp.zeros(10, dtype=dtype),
|
| 1211 |
+
ops.xp.zeros(5, dtype=dtype),
|
| 1212 |
+
)
|
| 1213 |
+
else:
|
| 1214 |
+
with pytest.raises(ValueError):
|
| 1215 |
+
backprop(
|
| 1216 |
+
ops.xp.arange(-10, 10, dtype=dtype),
|
| 1217 |
+
ops.xp.arange(5, -5, -1, dtype=dtype),
|
| 1218 |
+
)
|
| 1219 |
+
|
| 1220 |
+
|
| 1221 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1222 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1223 |
+
@given(X=strategies.arrays_BI())
|
| 1224 |
+
def test_relu_k(ops, X):
|
| 1225 |
+
X = ops.asarray(X)
|
| 1226 |
+
Y = ops.relu_k(X)
|
| 1227 |
+
assert Y.shape == X.shape
|
| 1228 |
+
assert not ops.xp.isnan(Y).any()
|
| 1229 |
+
assert (Y >= 0).sum() == Y.size
|
| 1230 |
+
assert (Y <= 6.0).sum() == Y.size
|
| 1231 |
+
|
| 1232 |
+
|
| 1233 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1234 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1235 |
+
@given(X=strategies.arrays_BI())
|
| 1236 |
+
def test_swish(ops, X):
|
| 1237 |
+
X = ops.asarray(X)
|
| 1238 |
+
Y = ops.swish(X)
|
| 1239 |
+
assert Y.shape == X.shape
|
| 1240 |
+
assert not ops.xp.isnan(Y).any()
|
| 1241 |
+
|
| 1242 |
+
|
| 1243 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1244 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1245 |
+
@given(X=strategies.arrays_BI())
|
| 1246 |
+
def test_hard_sigmoid(ops, X):
|
| 1247 |
+
X = ops.asarray(X)
|
| 1248 |
+
Y = ops.hard_sigmoid(X)
|
| 1249 |
+
assert Y.shape == X.shape
|
| 1250 |
+
assert not ops.xp.isnan(Y).any()
|
| 1251 |
+
assert (Y >= 0).sum() == Y.size
|
| 1252 |
+
assert (Y <= 1.0).sum() == Y.size
|
| 1253 |
+
|
| 1254 |
+
|
| 1255 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1256 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1257 |
+
@given(X=strategies.arrays_BI())
|
| 1258 |
+
def test_hard_tanh(ops, X):
|
| 1259 |
+
X = ops.asarray(X)
|
| 1260 |
+
Y = ops.hard_tanh(X)
|
| 1261 |
+
assert Y.shape == X.shape
|
| 1262 |
+
assert not ops.xp.isnan(Y).any()
|
| 1263 |
+
assert (Y >= -1.0).sum() == Y.size
|
| 1264 |
+
assert (Y <= 1.0).sum() == Y.size
|
| 1265 |
+
|
| 1266 |
+
|
| 1267 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1268 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1269 |
+
@given(X=strategies.arrays_BI())
|
| 1270 |
+
def test_hard_swish(ops, X):
|
| 1271 |
+
X = ops.asarray(X)
|
| 1272 |
+
Y = ops.hard_swish(X)
|
| 1273 |
+
assert Y.shape == X.shape
|
| 1274 |
+
assert not ops.xp.isnan(Y).any()
|
| 1275 |
+
|
| 1276 |
+
|
| 1277 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1278 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1279 |
+
@given(X=strategies.arrays_BI())
|
| 1280 |
+
def test_hard_swish_mobilenet(ops, X):
|
| 1281 |
+
X = ops.asarray(X)
|
| 1282 |
+
Y = ops.hard_swish_mobilenet(X)
|
| 1283 |
+
assert Y.shape == X.shape
|
| 1284 |
+
assert not ops.xp.isnan(Y).any()
|
| 1285 |
+
|
| 1286 |
+
|
| 1287 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1288 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1289 |
+
@given(X=strategies.arrays_BI())
|
| 1290 |
+
def test_gelu_approx(ops, X):
|
| 1291 |
+
X = ops.asarray(X)
|
| 1292 |
+
Y = ops.gelu_approx(X)
|
| 1293 |
+
assert Y.shape == X.shape
|
| 1294 |
+
assert not ops.xp.isnan(Y).any()
|
| 1295 |
+
|
| 1296 |
+
|
| 1297 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1298 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1299 |
+
@given(X=strategies.arrays_BI())
|
| 1300 |
+
def test_dish(ops, X):
|
| 1301 |
+
X = ops.asarray(X)
|
| 1302 |
+
Y = ops.dish(X)
|
| 1303 |
+
assert Y.shape == X.shape
|
| 1304 |
+
assert not ops.xp.isnan(Y).any()
|
| 1305 |
+
|
| 1306 |
+
|
| 1307 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1308 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1309 |
+
@given(X=strategies.arrays_BI())
|
| 1310 |
+
def test_gelu(ops, X):
|
| 1311 |
+
X = ops.asarray(X)
|
| 1312 |
+
Y = ops.gelu(X)
|
| 1313 |
+
assert Y.shape == X.shape
|
| 1314 |
+
assert not ops.xp.isnan(Y).any()
|
| 1315 |
+
|
| 1316 |
+
|
| 1317 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1318 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1319 |
+
@given(X=strategies.arrays_BI())
|
| 1320 |
+
def test_backprop_mish(ops, X):
|
| 1321 |
+
X = ops.asarray(X)
|
| 1322 |
+
# Test zero gradients result in 0 dX
|
| 1323 |
+
zeros = ops.alloc(X.shape)
|
| 1324 |
+
dX = ops.backprop_mish(zeros, X)
|
| 1325 |
+
assert dX.shape == X.shape
|
| 1326 |
+
assert (dX == 0).all()
|
| 1327 |
+
|
| 1328 |
+
|
| 1329 |
+
def get_lstm_args(depth, dirs, nO, batch_size, nI, draw=None):
|
| 1330 |
+
|
| 1331 |
+
if dirs == 1:
|
| 1332 |
+
n_params = (nO * 4) * nI + nO * 4 + nO * 4 * nO + nO * 4
|
| 1333 |
+
for _ in range(1, depth):
|
| 1334 |
+
n_params += nO * 4 * nO + nO * 4 + nO * 4 * nO + nO * 4
|
| 1335 |
+
else:
|
| 1336 |
+
n_params = (nO * 2) * nI + nO * 2 + nO * 2 * (nO // 2) + nO * 2
|
| 1337 |
+
for _ in range(1, depth):
|
| 1338 |
+
n_params += nO * 2 * nO + nO * 2 + nO * 2 * (nO // 2) + nO * 2
|
| 1339 |
+
n_params *= 2
|
| 1340 |
+
lstm = LSTM(nO, nI, depth=depth, bi=dirs >= 2).initialize()
|
| 1341 |
+
assert lstm.get_param("LSTM").size == n_params
|
| 1342 |
+
if draw:
|
| 1343 |
+
params = draw(ndarrays_of_shape(n_params))
|
| 1344 |
+
# For some reason this is crashing hypothesis?
|
| 1345 |
+
# size_at_t = draw(ndarrays_of_shape(shape=(batch_size,), lo=1, dtype="int32"))
|
| 1346 |
+
size_at_t = numpy.ones(shape=(batch_size,), dtype="int32")
|
| 1347 |
+
X = draw(ndarrays_of_shape((int(size_at_t.sum()), nI)))
|
| 1348 |
+
else:
|
| 1349 |
+
params = numpy.ones((n_params,), dtype="f")
|
| 1350 |
+
size_at_t = numpy.ones(shape=(batch_size,), dtype="int32")
|
| 1351 |
+
X = numpy.zeros(((int(size_at_t.sum()), nI)))
|
| 1352 |
+
H0 = numpy.zeros((depth, dirs, nO // dirs))
|
| 1353 |
+
C0 = numpy.zeros((depth, dirs, nO // dirs))
|
| 1354 |
+
return (params, H0, C0, X, size_at_t)
|
| 1355 |
+
|
| 1356 |
+
|
| 1357 |
+
@composite
|
| 1358 |
+
def draw_lstm_args(draw):
|
| 1359 |
+
depth = draw(integers(1, 4))
|
| 1360 |
+
dirs = draw(integers(1, 2))
|
| 1361 |
+
nO = draw(integers(1, 16)) * dirs
|
| 1362 |
+
batch_size = draw(integers(1, 6))
|
| 1363 |
+
nI = draw(integers(1, 16))
|
| 1364 |
+
return get_lstm_args(depth, dirs, nO, batch_size, nI, draw=draw)
|
| 1365 |
+
|
| 1366 |
+
|
| 1367 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 1368 |
+
@pytest.mark.parametrize(
|
| 1369 |
+
"depth,dirs,nO,batch_size,nI",
|
| 1370 |
+
[
|
| 1371 |
+
(1, 1, 1, 1, 1),
|
| 1372 |
+
(1, 1, 2, 1, 1),
|
| 1373 |
+
(1, 1, 2, 1, 2),
|
| 1374 |
+
(2, 1, 1, 1, 1),
|
| 1375 |
+
(2, 1, 2, 2, 2),
|
| 1376 |
+
(1, 2, 2, 1, 1),
|
| 1377 |
+
(2, 2, 2, 2, 2),
|
| 1378 |
+
],
|
| 1379 |
+
)
|
| 1380 |
+
def test_lstm_forward_training(ops, depth, dirs, nO, batch_size, nI):
|
| 1381 |
+
reference_ops = Ops()
|
| 1382 |
+
params, H0, C0, X, size_at_t = get_lstm_args(depth, dirs, nO, batch_size, nI)
|
| 1383 |
+
reference = reference_ops.lstm_forward_training(params, H0, C0, X, size_at_t)
|
| 1384 |
+
Y, fwd_state = ops.lstm_forward_training(params, H0, C0, X, size_at_t)
|
| 1385 |
+
assert_allclose(fwd_state[2], reference[1][2], atol=1e-4, rtol=1e-3)
|
| 1386 |
+
assert_allclose(fwd_state[1], reference[1][1], atol=1e-4, rtol=1e-3)
|
| 1387 |
+
assert_allclose(Y, reference[0], atol=1e-4, rtol=1e-3)
|
| 1388 |
+
|
| 1389 |
+
|
| 1390 |
+
@pytest.mark.skip(reason="Flaky, skip temporarily")
|
| 1391 |
+
@pytest.mark.parametrize("ops", XP_OPS)
|
| 1392 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1393 |
+
@given(args=draw_lstm_args())
|
| 1394 |
+
def test_lstm_forward_training_fuzz(ops, args):
|
| 1395 |
+
params, H0, C0, X, size_at_t = args
|
| 1396 |
+
reference_ops = Ops()
|
| 1397 |
+
reference = reference_ops.lstm_forward_training(params, H0, C0, X, size_at_t)
|
| 1398 |
+
Y, fwd_state = ops.lstm_forward_training(params, H0, C0, X, size_at_t)
|
| 1399 |
+
assert_allclose(fwd_state[2], reference[1][2], atol=1e-4, rtol=1e-3)
|
| 1400 |
+
assert_allclose(fwd_state[1], reference[1][1], atol=1e-4, rtol=1e-3)
|
| 1401 |
+
assert_allclose(Y, reference[0], atol=1e-4, rtol=1e-3)
|
| 1402 |
+
|
| 1403 |
+
|
| 1404 |
+
def test_get_ops():
|
| 1405 |
+
assert isinstance(get_ops("numpy"), NumpyOps)
|
| 1406 |
+
assert isinstance(get_ops("cupy"), CupyOps)
|
| 1407 |
+
# If Apple ops are available, "cpu" should return AppleOps or
|
| 1408 |
+
# NumpyOps otherwise.
|
| 1409 |
+
try:
|
| 1410 |
+
from thinc_apple_ops import AppleOps
|
| 1411 |
+
|
| 1412 |
+
assert isinstance(get_ops("cpu"), AppleOps)
|
| 1413 |
+
except ImportError:
|
| 1414 |
+
assert isinstance(get_ops("cpu"), NumpyOps)
|
| 1415 |
+
# If BigEndian ops are available, "cpu" should return BigEndianOps or
|
| 1416 |
+
# NumpyOps otherwise.
|
| 1417 |
+
try:
|
| 1418 |
+
from thinc_bigendian_ops import BigEndianOps
|
| 1419 |
+
|
| 1420 |
+
assert isinstance(get_ops("cpu"), BigEndianOps)
|
| 1421 |
+
except ImportError:
|
| 1422 |
+
assert isinstance(get_ops("cpu"), NumpyOps)
|
| 1423 |
+
with pytest.raises(ValueError):
|
| 1424 |
+
get_ops("blah")
|
| 1425 |
+
ops = Ops(numpy)
|
| 1426 |
+
assert ops.xp == numpy
|
| 1427 |
+
|
| 1428 |
+
|
| 1429 |
+
def test_use_ops():
|
| 1430 |
+
class_ops = get_current_ops()
|
| 1431 |
+
with use_ops("numpy"):
|
| 1432 |
+
new_ops = get_current_ops()
|
| 1433 |
+
assert new_ops.name == "numpy"
|
| 1434 |
+
with use_ops("cupy"):
|
| 1435 |
+
new_ops = get_current_ops()
|
| 1436 |
+
assert new_ops.name == "cupy"
|
| 1437 |
+
new_ops = get_current_ops()
|
| 1438 |
+
assert class_ops.name == new_ops.name
|
| 1439 |
+
|
| 1440 |
+
|
| 1441 |
+
def test_minibatch():
|
| 1442 |
+
fix_random_seed(0)
|
| 1443 |
+
ops = get_current_ops()
|
| 1444 |
+
items = [1, 2, 3, 4, 5, 6]
|
| 1445 |
+
batches = ops.minibatch(3, items)
|
| 1446 |
+
assert list(batches) == [[1, 2, 3], [4, 5, 6]]
|
| 1447 |
+
batches = ops.minibatch((i for i in (3, 2, 1)), items)
|
| 1448 |
+
assert list(batches) == [[1, 2, 3], [4, 5], [6]]
|
| 1449 |
+
batches = list(ops.minibatch(3, numpy.asarray(items)))
|
| 1450 |
+
assert isinstance(batches[0], numpy.ndarray)
|
| 1451 |
+
assert numpy.array_equal(batches[0], numpy.asarray([1, 2, 3]))
|
| 1452 |
+
assert numpy.array_equal(batches[1], numpy.asarray([4, 5, 6]))
|
| 1453 |
+
batches = list(ops.minibatch((i for i in (3, 2, 1)), items, shuffle=True))
|
| 1454 |
+
assert batches != [[1, 2, 3], [4, 5], [6]]
|
| 1455 |
+
assert len(batches[0]) == 3
|
| 1456 |
+
assert len(batches[1]) == 2
|
| 1457 |
+
assert len(batches[2]) == 1
|
| 1458 |
+
with pytest.raises(ValueError):
|
| 1459 |
+
ops.minibatch(10, (i for i in range(100)))
|
| 1460 |
+
with pytest.raises(ValueError):
|
| 1461 |
+
ops.minibatch(10, True)
|
| 1462 |
+
|
| 1463 |
+
|
| 1464 |
+
def test_multibatch():
|
| 1465 |
+
fix_random_seed(0)
|
| 1466 |
+
ops = get_current_ops()
|
| 1467 |
+
arr1 = numpy.asarray([1, 2, 3, 4])
|
| 1468 |
+
arr2 = numpy.asarray([5, 6, 7, 8])
|
| 1469 |
+
batches = list(ops.multibatch(2, arr1, arr2))
|
| 1470 |
+
assert numpy.concatenate(batches).tolist() == [[1, 2], [5, 6], [3, 4], [7, 8]]
|
| 1471 |
+
batches = list(ops.multibatch(2, arr1, arr2, shuffle=True))
|
| 1472 |
+
assert len(batches) == 2
|
| 1473 |
+
assert len(batches[0]) == 2
|
| 1474 |
+
assert len(batches[1]) == 2
|
| 1475 |
+
batches = list(ops.multibatch(2, [1, 2, 3, 4], [5, 6, 7, 8]))
|
| 1476 |
+
assert batches == [[[1, 2], [5, 6]], [[3, 4], [7, 8]]]
|
| 1477 |
+
with pytest.raises(ValueError):
|
| 1478 |
+
ops.multibatch(10, (i for i in range(100)), (i for i in range(100)))
|
| 1479 |
+
with pytest.raises(ValueError):
|
| 1480 |
+
ops.multibatch(10, arr1, (i for i in range(100)), arr2)
|
| 1481 |
+
|
| 1482 |
+
|
| 1483 |
+
def test_ngrams():
|
| 1484 |
+
ops = get_current_ops()
|
| 1485 |
+
arr1 = numpy.asarray([1, 2, 3, 4, 5], dtype=numpy.uint64)
|
| 1486 |
+
for n in range(1, 10):
|
| 1487 |
+
assert len(ops.ngrams(n, arr1)) == max(0, arr1.shape[0] - (n - 1))
|
| 1488 |
+
assert len(ops.ngrams(-1, arr1)) == 0
|
| 1489 |
+
assert len(ops.ngrams(arr1.shape[0] + 1, arr1)) == 0
|
| 1490 |
+
|
| 1491 |
+
|
| 1492 |
+
@pytest.mark.skipif(not has_torch, reason="needs PyTorch")
|
| 1493 |
+
@pytest.mark.skipif(torch_version < Version("1.9.0"), reason="needs PyTorch 1.9.0")
|
| 1494 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1495 |
+
@pytest.mark.parametrize("dtype", ["float32", "float64"])
|
| 1496 |
+
@pytest.mark.parametrize("torch_func", TORCH_FUNCS)
|
| 1497 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1498 |
+
@given(
|
| 1499 |
+
x=strategies.floats(min_value=-30, max_value=30),
|
| 1500 |
+
dY=strategies.floats(min_value=-1, max_value=1),
|
| 1501 |
+
)
|
| 1502 |
+
def test_compare_activations_to_torch(ops, dtype, x, dY, torch_func):
|
| 1503 |
+
import torch
|
| 1504 |
+
|
| 1505 |
+
func_name, pytorch_func = torch_func
|
| 1506 |
+
forward = getattr(ops, func_name)
|
| 1507 |
+
backward = getattr(ops, "backprop_" + func_name)
|
| 1508 |
+
# The tolerance of isclose is set to 1e-06 instead of
|
| 1509 |
+
# the default 1e-08 due to the GELU
|
| 1510 |
+
x_thinc = ops.asarray([x], dtype=dtype)
|
| 1511 |
+
x_torch = xp2torch(x_thinc, requires_grad=True)
|
| 1512 |
+
y = pytorch_func(x_torch)
|
| 1513 |
+
y_thinc = forward(x_thinc)
|
| 1514 |
+
y.backward()
|
| 1515 |
+
assert x_thinc.dtype == y_thinc.dtype
|
| 1516 |
+
assert y_thinc is not x_thinc
|
| 1517 |
+
y_think_inplace = forward(x_thinc, inplace=True)
|
| 1518 |
+
assert y_think_inplace is x_thinc
|
| 1519 |
+
assert ops.xp.isclose(y_thinc, y_think_inplace, atol=1e-06)
|
| 1520 |
+
assert ops.xp.isclose(y_thinc, y.detach(), atol=1e-05)
|
| 1521 |
+
x_thinc = ops.asarray([x], dtype=dtype)
|
| 1522 |
+
dY_thinc = ops.asarray([dY], dtype=dtype)
|
| 1523 |
+
dY_thinc_inplace = dY_thinc.copy()
|
| 1524 |
+
|
| 1525 |
+
s = inspect.signature(backward)
|
| 1526 |
+
params = {p for p in s.parameters if p in ["dY", "X", "Y"]}
|
| 1527 |
+
|
| 1528 |
+
if params == {"dY", "X", "Y"}:
|
| 1529 |
+
dx_thinc = backward(dY_thinc, Y=y_thinc, X=x_thinc)
|
| 1530 |
+
assert dx_thinc.dtype == x_thinc.dtype
|
| 1531 |
+
assert dx_thinc is not dY_thinc
|
| 1532 |
+
dx_thinc_inplace = backward(
|
| 1533 |
+
dY=dY_thinc_inplace, Y=y_thinc, X=x_thinc, inplace=True
|
| 1534 |
+
)
|
| 1535 |
+
assert dx_thinc_inplace is dY_thinc_inplace
|
| 1536 |
+
assert ops.xp.isclose(dx_thinc, dx_thinc_inplace)
|
| 1537 |
+
assert ops.xp.isclose(x_torch.grad.item() * dY, float(dx_thinc), atol=1e-06)
|
| 1538 |
+
elif params == {"Y", "dY"}:
|
| 1539 |
+
dx_thinc = backward(dY_thinc, Y=y_thinc)
|
| 1540 |
+
assert dx_thinc.dtype == x_thinc.dtype
|
| 1541 |
+
assert ops.xp.isclose(
|
| 1542 |
+
dx_thinc,
|
| 1543 |
+
backward(dY=dY_thinc_inplace, Y=y_thinc, inplace=True),
|
| 1544 |
+
)
|
| 1545 |
+
assert ops.xp.isclose(x_torch.grad.item() * dY, float(dx_thinc), atol=1e-06)
|
| 1546 |
+
elif params == {"dY", "X"}:
|
| 1547 |
+
dx_thinc = backward(dY_thinc, X=x_thinc)
|
| 1548 |
+
assert dx_thinc.dtype == x_thinc.dtype
|
| 1549 |
+
assert ops.xp.isclose(
|
| 1550 |
+
dx_thinc, backward(dY=dY_thinc_inplace, X=x_thinc, inplace=True)
|
| 1551 |
+
)
|
| 1552 |
+
assert ops.xp.isclose(
|
| 1553 |
+
x_torch.grad.item() * dY, float(backward(dY_thinc, X=x_thinc)), atol=1e-06
|
| 1554 |
+
)
|
| 1555 |
+
else:
|
| 1556 |
+
raise NotImplementedError(
|
| 1557 |
+
f"No PyTorch comparison implemented for parameter set: {params}"
|
| 1558 |
+
)
|
| 1559 |
+
|
| 1560 |
+
|
| 1561 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1562 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1563 |
+
@given(x=strategies.floats(min_value=-10, max_value=10))
|
| 1564 |
+
def test_clipped_linear(ops, x):
|
| 1565 |
+
x_thinc = ops.xp.asarray([x])
|
| 1566 |
+
assert ops.xp.isclose(ops.clipped_linear(x_thinc, max_val=6.0), ops.relu_k(x_thinc))
|
| 1567 |
+
assert ops.xp.isclose(
|
| 1568 |
+
ops.backprop_clipped_linear(ops.asarray1f([1.0]), x_thinc, max_val=6.0),
|
| 1569 |
+
ops.backprop_relu_k(ops.asarray1f([1.0]), x_thinc),
|
| 1570 |
+
)
|
| 1571 |
+
assert ops.xp.isclose(
|
| 1572 |
+
ops.clipped_linear(x_thinc, slope=0.2, offset=0.5), ops.hard_sigmoid(x_thinc)
|
| 1573 |
+
)
|
| 1574 |
+
assert ops.xp.isclose(
|
| 1575 |
+
ops.backprop_clipped_linear(
|
| 1576 |
+
ops.asarray1f([1.0]), x_thinc, slope=0.2, offset=0.5
|
| 1577 |
+
),
|
| 1578 |
+
ops.backprop_hard_sigmoid(ops.asarray1f([1.0]), x_thinc),
|
| 1579 |
+
)
|
| 1580 |
+
|
| 1581 |
+
|
| 1582 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1583 |
+
@pytest.mark.parametrize("byte_order", (">", "<", "=", "|"))
|
| 1584 |
+
@settings(max_examples=MAX_EXAMPLES, deadline=None)
|
| 1585 |
+
@given(x=strategies.floats(min_value=-10, max_value=10))
|
| 1586 |
+
def test_to_numpy_byteorder(ops, byte_order, x):
|
| 1587 |
+
x = ops.xp.asarray([x])
|
| 1588 |
+
y = ops.to_numpy(x, byte_order=byte_order)
|
| 1589 |
+
assert numpy.array_equal(ops.to_numpy(x), ops.to_numpy(y))
|
| 1590 |
+
if byte_order in (">", "<"):
|
| 1591 |
+
# hack from: https://stackoverflow.com/a/49740663
|
| 1592 |
+
assert y.dtype.newbyteorder("S").newbyteorder("S").byteorder == byte_order
|
| 1593 |
+
else:
|
| 1594 |
+
assert x.dtype.byteorder == y.dtype.byteorder
|
| 1595 |
+
|
| 1596 |
+
|
| 1597 |
+
@pytest.mark.skipif(not has_cupy_gpu, reason="needs GPU/CuPy")
|
| 1598 |
+
def test_custom_kernel_compilation():
|
| 1599 |
+
for kernel_name in KERNELS_LIST:
|
| 1600 |
+
compiled_kernel = KERNELS.get_function(kernel_name)
|
| 1601 |
+
assert compiled_kernel is not None
|
| 1602 |
+
|
| 1603 |
+
assert compile_mmh() is not None
|
| 1604 |
+
|
| 1605 |
+
|
| 1606 |
+
@pytest.mark.parametrize("ops", ALL_OPS)
|
| 1607 |
+
def test_asarray_from_list_uint64(ops):
|
| 1608 |
+
# list contains int values both above and below int64.max
|
| 1609 |
+
uint64_list = [16, 11648197037703959513]
|
| 1610 |
+
assert uint64_list == list(ops.asarray(uint64_list, dtype="uint64"))
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/extra/__init__.py
ADDED
|
File without changes
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/extra/test_beam_search.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from thinc.extra.search import MaxViolation
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def test_init_violn():
|
| 5 |
+
MaxViolation()
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/__init__.py
ADDED
|
File without changes
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_basic_tagger.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from thinc.api import (
|
| 6 |
+
Adam,
|
| 7 |
+
HashEmbed,
|
| 8 |
+
Model,
|
| 9 |
+
Relu,
|
| 10 |
+
Softmax,
|
| 11 |
+
chain,
|
| 12 |
+
expand_window,
|
| 13 |
+
strings2arrays,
|
| 14 |
+
with_array,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.fixture(scope="module")
|
| 19 |
+
def ancora():
|
| 20 |
+
pytest.importorskip("ml_datasets")
|
| 21 |
+
import ml_datasets
|
| 22 |
+
|
| 23 |
+
return ml_datasets.ud_ancora_pos_tags()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def create_embed_relu_relu_softmax(depth, width, vector_length):
|
| 27 |
+
with Model.define_operators({">>": chain}):
|
| 28 |
+
model = strings2arrays() >> with_array(
|
| 29 |
+
HashEmbed(width, vector_length, column=0)
|
| 30 |
+
>> expand_window(window_size=1)
|
| 31 |
+
>> Relu(width, width * 3)
|
| 32 |
+
>> Relu(width, width)
|
| 33 |
+
>> Softmax(17, width)
|
| 34 |
+
)
|
| 35 |
+
return model
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@pytest.fixture(params=[create_embed_relu_relu_softmax])
|
| 39 |
+
def create_model(request):
|
| 40 |
+
return request.param
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def evaluate_tagger(model, dev_X, dev_Y, batch_size):
|
| 44 |
+
correct = 0.0
|
| 45 |
+
total = 0.0
|
| 46 |
+
for i in range(0, len(dev_X), batch_size):
|
| 47 |
+
Yh = model.predict(dev_X[i : i + batch_size])
|
| 48 |
+
Y = dev_Y[i : i + batch_size]
|
| 49 |
+
for j in range(len(Yh)):
|
| 50 |
+
correct += (Yh[j].argmax(axis=1) == Y[j].argmax(axis=1)).sum()
|
| 51 |
+
total += Yh[j].shape[0]
|
| 52 |
+
return correct / total
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def get_shuffled_batches(Xs, Ys, batch_size):
|
| 56 |
+
zipped = list(zip(Xs, Ys))
|
| 57 |
+
random.shuffle(zipped)
|
| 58 |
+
for i in range(0, len(zipped), batch_size):
|
| 59 |
+
batch_X, batch_Y = zip(*zipped[i : i + batch_size])
|
| 60 |
+
yield list(batch_X), list(batch_Y)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@pytest.mark.parametrize(
|
| 64 |
+
("depth", "width", "vector_width", "nb_epoch"), [(2, 32, 16, 5)]
|
| 65 |
+
)
|
| 66 |
+
@pytest.mark.xfail(reason="Flaky live download from the internet", strict=False)
|
| 67 |
+
def test_small_end_to_end(depth, width, vector_width, nb_epoch, create_model, ancora):
|
| 68 |
+
(train_X, train_Y), (dev_X, dev_Y) = ancora
|
| 69 |
+
batch_size = 8
|
| 70 |
+
model = create_model(depth, width, vector_width).initialize()
|
| 71 |
+
optimizer = Adam(0.001)
|
| 72 |
+
losses = []
|
| 73 |
+
scores = []
|
| 74 |
+
for _ in range(nb_epoch):
|
| 75 |
+
losses.append(0.0)
|
| 76 |
+
for X, Y in get_shuffled_batches(train_X, train_Y, batch_size):
|
| 77 |
+
Yh, backprop = model.begin_update(X)
|
| 78 |
+
d_loss = []
|
| 79 |
+
for i in range(len(Yh)):
|
| 80 |
+
d_loss.append(Yh[i] - Y[i])
|
| 81 |
+
losses[-1] += ((Yh[i] - Y[i]) ** 2).sum()
|
| 82 |
+
backprop(d_loss)
|
| 83 |
+
model.finish_update(optimizer)
|
| 84 |
+
scores.append(evaluate_tagger(model, dev_X, dev_Y, batch_size))
|
| 85 |
+
assert losses[-1] < losses[0]
|
| 86 |
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 |
+
clone,
|
| 12 |
+
concatenate,
|
| 13 |
+
map_list,
|
| 14 |
+
noop,
|
| 15 |
+
)
|
| 16 |
+
from thinc.layers import chain, tuplify
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@pytest.fixture(params=[1, 2, 9])
|
| 20 |
+
def nB(request):
|
| 21 |
+
return request.param
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.fixture(params=[1, 6])
|
| 25 |
+
def nI(request):
|
| 26 |
+
return request.param
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@pytest.fixture(params=[1, 5, 3])
|
| 30 |
+
def nH(request):
|
| 31 |
+
return request.param
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@pytest.fixture(params=[1, 2, 7, 9])
|
| 35 |
+
def nO(request):
|
| 36 |
+
return request.param
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.fixture
|
| 40 |
+
def model1(nH, nI):
|
| 41 |
+
return Linear(nH, nI)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@pytest.fixture
|
| 45 |
+
def model2(nO, nH):
|
| 46 |
+
return Linear(nO, nH)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@pytest.fixture
|
| 50 |
+
def model3(nO):
|
| 51 |
+
return Linear(nO, nO)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_tuplify_zero():
|
| 55 |
+
with pytest.raises(TypeError):
|
| 56 |
+
tuplify()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_tuplify_one(model1):
|
| 60 |
+
with pytest.raises(TypeError):
|
| 61 |
+
tuplify(model1)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_tuplify_two(model1, model2):
|
| 65 |
+
model = tuplify(model1, model2)
|
| 66 |
+
assert len(model.layers) == 2
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_tuplify_operator_two(model1, model2):
|
| 70 |
+
with Model.define_operators({"&": tuplify}):
|
| 71 |
+
model = model1 & model2
|
| 72 |
+
assert len(model.layers) == 2
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_tuplify_dulicates_input():
|
| 76 |
+
model = tuplify(noop(), noop())
|
| 77 |
+
ones = numpy.ones([10])
|
| 78 |
+
out = model.predict(ones)
|
| 79 |
+
assert out == (ones, ones)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_tuplify_initialize(nI, nO):
|
| 83 |
+
linear = Linear(nO)
|
| 84 |
+
model = tuplify(linear, linear)
|
| 85 |
+
ones = numpy.ones((1, nI), dtype="float")
|
| 86 |
+
model.initialize(X=ones)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_tuplify_three(model1, model2, model3):
|
| 90 |
+
model = tuplify(model1, model2, model3)
|
| 91 |
+
assert len(model.layers) == 3
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_tuplify_operator_three(model1, model2, model3):
|
| 95 |
+
# Previously we 'flattened' these nested calls. We might opt to do so
|
| 96 |
+
# again, especially for the operators.
|
| 97 |
+
with Model.define_operators({"&": tuplify}):
|
| 98 |
+
model = model1 & model2 & model3
|
| 99 |
+
assert len(model.layers) == 2
|
| 100 |
+
assert len(model.layers[0].layers) == 2
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_chain_zero():
|
| 104 |
+
with pytest.raises(TypeError):
|
| 105 |
+
chain()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_chain_one(model1):
|
| 109 |
+
with pytest.raises(TypeError):
|
| 110 |
+
chain(model1)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def test_chain_two(model1, model2):
|
| 114 |
+
model = chain(model1, model2)
|
| 115 |
+
assert len(model.layers) == 2
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def test_chain_operator_two(model1, model2):
|
| 119 |
+
with Model.define_operators({">>": chain}):
|
| 120 |
+
model = model1 >> model2
|
| 121 |
+
assert len(model.layers) == 2
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def test_chain_three(model1, model2, model3):
|
| 125 |
+
model = chain(model1, model2, model3)
|
| 126 |
+
assert len(model.layers) == 3
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def test_chain_operator_three(model1, model2, model3):
|
| 130 |
+
# Previously we 'flattened' these nested calls. We might opt to do so
|
| 131 |
+
# again, especially for the operators.
|
| 132 |
+
with Model.define_operators({">>": chain}):
|
| 133 |
+
model = model1 >> model2 >> model3
|
| 134 |
+
assert len(model.layers) == 2
|
| 135 |
+
assert len(model.layers[0].layers) == 2
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def test_chain_right_branch(model1, model2, model3):
|
| 139 |
+
# Previously we 'flattened' these nested calls. We might opt to do so
|
| 140 |
+
# again, especially for the operators.
|
| 141 |
+
merge1 = chain(model1, model2)
|
| 142 |
+
merge2 = chain(merge1, model3)
|
| 143 |
+
assert len(merge1.layers) == 2
|
| 144 |
+
assert len(merge2.layers) == 2
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@pytest.mark.parametrize("ops", [NumpyOps(), NumpyOps(use_blis=True)])
|
| 148 |
+
def test_chain(ops):
|
| 149 |
+
data = numpy.asarray([[1, 2, 3, 4]], dtype="f")
|
| 150 |
+
model = chain(Linear(1), Dropout(), Linear(1))
|
| 151 |
+
model.ops = ops
|
| 152 |
+
model.initialize(data, data)
|
| 153 |
+
Y, backprop = model(data, is_train=True)
|
| 154 |
+
backprop(Y)
|
| 155 |
+
# Layers with and without nO/nI
|
| 156 |
+
model = chain(Linear(1), Dropout(), Linear(1, 1))
|
| 157 |
+
model.initialize(data, data)
|
| 158 |
+
# Setting dim on model
|
| 159 |
+
model = chain(Linear(1), Dropout(), Linear(1))
|
| 160 |
+
model.set_dim("nO", 1)
|
| 161 |
+
model.initialize(data, None)
|
| 162 |
+
model = chain(Linear(1, 1), Dropout(), Linear(1, 1))
|
| 163 |
+
model.set_dim("nI", 1)
|
| 164 |
+
model.initialize(None, data)
|
| 165 |
+
# Not enough arguments
|
| 166 |
+
with pytest.raises(TypeError):
|
| 167 |
+
chain(Linear())
|
| 168 |
+
with pytest.raises(TypeError):
|
| 169 |
+
chain()
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def test_concatenate_one(model1):
|
| 173 |
+
model = concatenate(model1)
|
| 174 |
+
assert isinstance(model, Model)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def test_concatenate_two(model1, model2):
|
| 178 |
+
model = concatenate(model1, model2)
|
| 179 |
+
assert len(model.layers) == 2
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def test_concatenate_operator_two(model1, model2):
|
| 183 |
+
with Model.define_operators({"|": concatenate}):
|
| 184 |
+
model = model1 | model2
|
| 185 |
+
assert len(model.layers) == 2
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def test_concatenate_three(model1, model2, model3):
|
| 189 |
+
model = concatenate(model1, model2, model3)
|
| 190 |
+
assert len(model.layers) == 3
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_concatenate_operator_three(model1, model2, model3):
|
| 194 |
+
with Model.define_operators({"|": concatenate}):
|
| 195 |
+
model = model1 | model2 | model3
|
| 196 |
+
assert len(model.layers) == 3
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def test_clone_changes_predictions(nH, nI):
|
| 200 |
+
model1 = Linear(nH)
|
| 201 |
+
model = clone(model1, 10)
|
| 202 |
+
ones = numpy.ones((10, nI), dtype="f")
|
| 203 |
+
model.initialize(X=ones)
|
| 204 |
+
output_from_cloned = model.predict(ones)
|
| 205 |
+
output_from_orig = model1.predict(ones)
|
| 206 |
+
assert output_from_cloned.sum() != output_from_orig.sum()
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def test_clone_gives_distinct_ids(nH, nI):
|
| 210 |
+
model = clone(Linear(nH), 5)
|
| 211 |
+
assert len(model.layers) == 5
|
| 212 |
+
seen_ids = set()
|
| 213 |
+
for node in model.walk():
|
| 214 |
+
assert node.id not in seen_ids
|
| 215 |
+
seen_ids.add(node.id)
|
| 216 |
+
assert len(seen_ids) == 6
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def test_clone_noop():
|
| 220 |
+
model = clone(Linear(), 0)
|
| 221 |
+
assert len(model.layers) == 0
|
| 222 |
+
assert model.name == "noop"
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def test_concatenate_noop():
|
| 226 |
+
model = concatenate()
|
| 227 |
+
assert len(model.layers) == 0
|
| 228 |
+
assert model.name == "noop"
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def test_noop():
|
| 232 |
+
data = numpy.asarray([1, 2, 3], dtype="f")
|
| 233 |
+
model = noop(Linear(), Linear())
|
| 234 |
+
model.initialize(data, data)
|
| 235 |
+
Y, backprop = model(data, is_train=True)
|
| 236 |
+
assert numpy.array_equal(Y, data)
|
| 237 |
+
dX = backprop(Y)
|
| 238 |
+
assert numpy.array_equal(dX, data)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def test_add():
|
| 242 |
+
data = numpy.asarray([[1, 2, 3, 4]], dtype="f")
|
| 243 |
+
model = add(Linear(), Linear())
|
| 244 |
+
model.initialize(data, data)
|
| 245 |
+
Y, backprop = model(data, is_train=True)
|
| 246 |
+
Y2 = sum(layer.predict(data) for layer in model.layers)
|
| 247 |
+
assert numpy.array_equal(Y, Y2)
|
| 248 |
+
dX = backprop(Y)
|
| 249 |
+
assert dX.shape == data.shape
|
| 250 |
+
# Test that nesting works
|
| 251 |
+
model2 = add(model, Linear())
|
| 252 |
+
assert len(model2.layers) == 3
|
| 253 |
+
model.initialize(data, data)
|
| 254 |
+
Y = model2.predict(data)
|
| 255 |
+
Y2 = sum(layer.predict(data) for layer in model2.layers)
|
| 256 |
+
assert numpy.array_equal(Y, Y2)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def test_add_edge_cases():
|
| 260 |
+
data = numpy.asarray([[1, 2, 3, 4]], dtype="f")
|
| 261 |
+
with pytest.raises(TypeError):
|
| 262 |
+
add()
|
| 263 |
+
model = add(Linear(), Linear())
|
| 264 |
+
model._layers = []
|
| 265 |
+
Y, backprop = model(data, is_train=True)
|
| 266 |
+
assert numpy.array_equal(data, Y)
|
| 267 |
+
dX = backprop(Y)
|
| 268 |
+
assert numpy.array_equal(dX, data)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def test_concatenate():
|
| 272 |
+
data = numpy.asarray([[1, 2, 3], [4, 5, 6]], dtype="f")
|
| 273 |
+
model = concatenate(Linear(), Linear())
|
| 274 |
+
model.initialize(data, data)
|
| 275 |
+
Y, backprop = model(data, is_train=True)
|
| 276 |
+
assert Y.shape[1] == sum([layer.predict(data).shape[1] for layer in model.layers])
|
| 277 |
+
dX = backprop(Y)
|
| 278 |
+
assert dX.shape == data.shape
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def test_map_list():
|
| 282 |
+
nI = 4
|
| 283 |
+
nO = 9
|
| 284 |
+
Xs = [numpy.zeros((6, nI), dtype="f"), numpy.ones((3, nI), dtype="f")]
|
| 285 |
+
Y_shapes = [(x.shape[0], nO) for x in Xs]
|
| 286 |
+
model = map_list(Linear())
|
| 287 |
+
model.initialize(X=Xs, Y=[numpy.zeros(shape, dtype="f") for shape in Y_shapes])
|
| 288 |
+
Ys, backprop = model(Xs, is_train=True)
|
| 289 |
+
assert isinstance(Ys, list)
|
| 290 |
+
assert len(Ys) == len(Xs)
|
| 291 |
+
layer = model.layers[0]
|
| 292 |
+
for X, Y in zip(Xs, Ys):
|
| 293 |
+
assert_allclose(layer.predict(X), Y)
|
| 294 |
+
dXs = backprop(Ys)
|
| 295 |
+
assert isinstance(dXs, list)
|
| 296 |
+
assert len(dXs) == len(Xs)
|
| 297 |
+
assert dXs[0].shape == Xs[0].shape
|
| 298 |
+
assert dXs[1].shape == Xs[1].shape
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_feed_forward.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import partial
|
| 2 |
+
|
| 3 |
+
import numpy
|
| 4 |
+
import pytest
|
| 5 |
+
from numpy.testing import assert_allclose
|
| 6 |
+
|
| 7 |
+
from thinc.api import Linear, NumpyOps, Relu, chain
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@pytest.fixture(params=[1, 2, 9])
|
| 11 |
+
def nB(request):
|
| 12 |
+
return request.param
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.fixture(params=[1, 6])
|
| 16 |
+
def nI(request):
|
| 17 |
+
return request.param
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@pytest.fixture(params=[1, 5, 3])
|
| 21 |
+
def nH(request):
|
| 22 |
+
return request.param
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@pytest.fixture(params=[1, 2, 7, 9])
|
| 26 |
+
def nO(request):
|
| 27 |
+
return request.param
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.fixture
|
| 31 |
+
def model1(nH, nI):
|
| 32 |
+
model = Relu(nH, nI).initialize()
|
| 33 |
+
return model
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@pytest.fixture
|
| 37 |
+
def model2(nO, nH):
|
| 38 |
+
model = Linear(nO, nH).initialize()
|
| 39 |
+
return model
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@pytest.fixture
|
| 43 |
+
def input_data(nB, nI):
|
| 44 |
+
return numpy.ones((nB, nI), dtype="f") + 1.0
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@pytest.fixture
|
| 48 |
+
def gradient_data(nB, nO):
|
| 49 |
+
return numpy.zeros((nB, nO), dtype="f") - 1.0
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@pytest.fixture
|
| 53 |
+
def model(model1, model2):
|
| 54 |
+
return chain(model1, model2).initialize()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def get_expected_predict(input_data, Ws, bs):
|
| 58 |
+
numpy_ops = NumpyOps()
|
| 59 |
+
X = input_data
|
| 60 |
+
for i, (W, b) in enumerate(zip(Ws, bs)):
|
| 61 |
+
X = numpy_ops.asarray(X)
|
| 62 |
+
if i > 0:
|
| 63 |
+
X *= X > 0
|
| 64 |
+
X = numpy.tensordot(X, W, axes=[[1], [1]]) + b
|
| 65 |
+
return X
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def numeric_gradient(predict, weights, epsilon=1e-4):
|
| 69 |
+
out1 = predict(weights + epsilon)
|
| 70 |
+
out2 = predict(weights - epsilon)
|
| 71 |
+
return (out1 - out2) / (2 * epsilon)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_models_have_shape(model1, model2, nI, nH, nO):
|
| 75 |
+
assert model1.get_param("W").shape == (nH, nI)
|
| 76 |
+
assert model1.get_param("b").shape == (nH,)
|
| 77 |
+
assert model2.get_param("W").shape == (nO, nH)
|
| 78 |
+
assert model2.get_param("b").shape == (nO,)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_model_shape(model, model1, model2, nI, nH, nO):
|
| 82 |
+
assert model.get_dim("nI") == model1.get_dim("nI")
|
| 83 |
+
assert model.get_dim("nO") == model2.get_dim("nO")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_infer_output_shape():
|
| 87 |
+
model = Relu(dropout=0.2)
|
| 88 |
+
X = model.ops.alloc2f(4, 5)
|
| 89 |
+
Y = model.ops.alloc2f(4, 2)
|
| 90 |
+
assert model.has_dim("nI") is None
|
| 91 |
+
assert model.has_dim("nO") is None
|
| 92 |
+
model.initialize(X=X, Y=Y)
|
| 93 |
+
assert model.get_dim("nI") == 5
|
| 94 |
+
assert model.get_dim("nO") == 2
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_predict_and_begin_update_match(model, model1, model2, input_data):
|
| 98 |
+
model = chain(model1, model2)
|
| 99 |
+
via_predict = model.predict(input_data)
|
| 100 |
+
via_update, _ = model.begin_update(input_data)
|
| 101 |
+
assert_allclose(via_predict, via_update)
|
| 102 |
+
expected = get_expected_predict(
|
| 103 |
+
input_data,
|
| 104 |
+
[model1.get_param("W"), model2.get_param("W")],
|
| 105 |
+
[model1.get_param("b"), model2.get_param("b")],
|
| 106 |
+
)
|
| 107 |
+
assert_allclose(via_update, expected, atol=1e-2, rtol=1e-4)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_init_functions_are_called():
|
| 111 |
+
init_was_called = {}
|
| 112 |
+
|
| 113 |
+
def register_init(name, model, X=None, Y=None):
|
| 114 |
+
init_was_called[name] = True
|
| 115 |
+
|
| 116 |
+
layer1 = Linear(5)
|
| 117 |
+
layer2 = Linear(5)
|
| 118 |
+
layer3 = Linear(5)
|
| 119 |
+
layer1.init = partial(register_init, "one")
|
| 120 |
+
layer2.init = partial(register_init, "two")
|
| 121 |
+
layer3.init = partial(register_init, "three")
|
| 122 |
+
# This is the nesting we'll get from operators.
|
| 123 |
+
model = chain(layer1, chain(layer2, layer3))
|
| 124 |
+
assert not init_was_called
|
| 125 |
+
model.initialize()
|
| 126 |
+
assert init_was_called["one"]
|
| 127 |
+
assert init_was_called["two"]
|
| 128 |
+
assert init_was_called["three"]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class GradientSpy(object):
|
| 132 |
+
def __init__(self):
|
| 133 |
+
self.weights = None
|
| 134 |
+
self.d_weights = None
|
| 135 |
+
|
| 136 |
+
def __call__(self, weights, grad):
|
| 137 |
+
self.weights = weights
|
| 138 |
+
self.d_weights = grad
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# I don't know how to get this working properly after the refactor. It's a numeric
|
| 142 |
+
# gradient check. I suspect the test is the problem, not the code.
|
| 143 |
+
@pytest.mark.skip
|
| 144 |
+
# This is the actual definition -- it's just annoying to see tonnes of skips.
|
| 145 |
+
# def test_gradient(model, input_data, nB, nH, nI, nO):
|
| 146 |
+
def test_gradient():
|
| 147 |
+
truth = numpy.zeros((nB, nO), dtype="float32")
|
| 148 |
+
truth[0] = 1.0
|
| 149 |
+
|
| 150 |
+
guess, backprop = model.begin_update(input_data)
|
| 151 |
+
backprop(guess - truth)
|
| 152 |
+
|
| 153 |
+
for layer in model.layers:
|
| 154 |
+
for name in layer.param_names:
|
| 155 |
+
agrad = layer.get_grad(name).ravel() # Should have grads for all params.
|
| 156 |
+
predict = get_predict(layer, name, input_data)
|
| 157 |
+
ngrad = get_numeric_gradient(predict, agrad.size, truth)
|
| 158 |
+
assert_allclose(agrad, ngrad, atol=0.2, rtol=0.2)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def get_predict(layer, param_name, inputs):
|
| 162 |
+
"""Helper for gradient check. To do the numeric gradient check, we have
|
| 163 |
+
to be able to wiggle one value in a parameter, and check the prediction
|
| 164 |
+
before and after. So we need to get a callback that gives an output
|
| 165 |
+
given a change to one weight.
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
def predict(i, epsilon):
|
| 169 |
+
param = layer.get_param(param_name)
|
| 170 |
+
shape = param.shape
|
| 171 |
+
param = param.ravel()
|
| 172 |
+
param[i] += epsilon
|
| 173 |
+
layer.set_param(param_name, param.reshape(shape))
|
| 174 |
+
outputs = layer.predict(inputs)
|
| 175 |
+
param[i] -= epsilon
|
| 176 |
+
layer.set_param(param_name, param.reshape(shape))
|
| 177 |
+
return outputs.reshape(shape)
|
| 178 |
+
|
| 179 |
+
return predict
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def get_numeric_gradient(predict, n, target):
|
| 183 |
+
gradient = numpy.zeros(n)
|
| 184 |
+
for i in range(n):
|
| 185 |
+
out1 = predict(i, 1e-4)
|
| 186 |
+
out2 = predict(i, -1e-4)
|
| 187 |
+
|
| 188 |
+
err1 = _get_loss(out1, target)
|
| 189 |
+
err2 = _get_loss(out2, target)
|
| 190 |
+
gradient[i] = (err1 - err2) / (2 * 1e-4)
|
| 191 |
+
print("NGrad", i, err1, err2)
|
| 192 |
+
return gradient
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _get_loss(truth, guess):
|
| 196 |
+
return numpy.sum(numpy.sum(0.5 * numpy.square(truth - guess), 1))
|