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