diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/add.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/add.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f32e44233c20e734b293affedbaa30d367231efb Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/add.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/array_getitem.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/array_getitem.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15a1c73a40da780c0160a7c01137b2b79043f006 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/array_getitem.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/clipped_linear.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/clipped_linear.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7005192f3f8624a253c3f2a7290e2ca7b2eaf0a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/clipped_linear.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/clone.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/clone.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcae96a0876a81e63f2309228b7e8796bcd14065 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/clone.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/concatenate.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/concatenate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83bb3cc1fb3e9e1ecdbb54a9564b27007287b248 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/concatenate.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/hard_swish.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/hard_swish.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c75390a5bd674bbe8dcb9e288973c82ebb164e10 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/hard_swish.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/hashembed.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/hashembed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..924b23b37878d7275a489a92e41f57153d180c04 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/hashembed.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/layernorm.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/layernorm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4734bd152a8e56b9be4b31bd6530045a0a2f9c0c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/layernorm.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/list2ragged.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/list2ragged.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36d1fbe41b605b888450e44a093e4f1285317e2c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/list2ragged.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/reduce_mean.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/reduce_mean.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db696ab56d46a557f77324f6ac477ed737b069cf Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/reduce_mean.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/residual.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/residual.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec39809aab7e350d62c133c6f26316710eb9513c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/residual.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/sigmoid.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/sigmoid.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51f448342e70f0aa8d16e9ea36a861d8abbe03c5 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/sigmoid.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/softmax_activation.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/softmax_activation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..738b5dad2cc6c6811ebbb1cfee4793a715805e9f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/softmax_activation.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/swish.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/swish.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..394fff8c07a7bf948abdd0ca2cebcbe634aca34f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/swish.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/tensorflowwrapper.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/tensorflowwrapper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6716483f0fcf565a3c5ac05e9250526ebff1d0f1 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/tensorflowwrapper.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/with_flatten.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/with_flatten.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41dad0cab1340996f9d079039f48b59752d0a154 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/with_flatten.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/with_signpost_interval.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/with_signpost_interval.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d69d760f9635ef8f344620fb336872151ceae06 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/layers/__pycache__/with_signpost_interval.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b437e895db243ca4c7b44b690fe85e7277401a5d Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/mxnet.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/mxnet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2c2f01c90b555cd2e116fb6d4577cedd670e508 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/mxnet.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/pytorch.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/pytorch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22df7da1c5245a9b7e84e49a6058af2f262bcafc Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/pytorch.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/pytorch_grad_scaler.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/pytorch_grad_scaler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ca2662a8a8a5aa238762143872ada50eb9d0f8d Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/pytorch_grad_scaler.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/shim.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/shim.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d6f9853727ab71e176a69faa7344d25ba73d33c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/shim.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/tensorflow.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/tensorflow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca878b43def0d24079780de0fe3f2583cb02dcf4 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/tensorflow.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/torchscript.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/torchscript.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db10568457f8984e126ae93ac0784e3b45d51245 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/shims/__pycache__/torchscript.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9abf4f846473387bbf486cde2d71e16d1cb0f868 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/conftest.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/conftest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8ae0a758e4a483288e418a88c368dc15ac8b594 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/conftest.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/enable_mxnet.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/enable_mxnet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d87720a2a9fe045e772b42a7c5dc6ee4f4df396 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/enable_mxnet.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/enable_tensorflow.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/enable_tensorflow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea705b8ff5c1c57436ec416f9721d6cdc85e5262 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/enable_tensorflow.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/strategies.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/strategies.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd5969b53b4afb2f7dcde4f82d8b45f4a9c6233d Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/strategies.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_config.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0ea10f7f73a6f78c5d63a6f3728db9e6dc12ef1 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_config.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_examples.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_examples.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87bc363b2a229b04c78eec8f1644e1de65ee952b Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_examples.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_import__all__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_import__all__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0b9d4ae56d7a8d5f8ce5680932a3fc3ac8e2a63 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_import__all__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_indexing.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_indexing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca93b59b1a83652efb0d95bc8376bfbd8c02baf9 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_indexing.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_initializers.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_initializers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfedd259068ac16e687bf3e76e2fae3ccdfc161c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_initializers.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_loss.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_loss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4950df695a6abf6e39aecbb48977365be1decfa Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_loss.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_optimizers.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_optimizers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18aee47d04e3c64e5e6dff00d1d6336e96a95df1 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_optimizers.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_schedules.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_schedules.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90a221392a0509fe18946aa65abf1f1976ba3b76 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_schedules.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_serialize.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_serialize.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8e53eeb5de91bb74bf454a38a73203697309c1e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_serialize.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_types_confection.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_types_confection.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18bb5ca07fe64bdedd67eec5f58aa2daa7f3dd1d Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_types_confection.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_util.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad8b28e78c30f5090c79ec9d6ab126ffcbcbdcbd Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/test_util.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/util.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c041b5e34bb111d89b7a1dac86b1c32c054c562 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/__pycache__/util.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/test_mem.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/test_mem.py new file mode 100644 index 0000000000000000000000000000000000000000..bf867726d75817d7058a33b81e1d638682be0fcf --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/test_mem.py @@ -0,0 +1,12 @@ +import numpy + +from thinc.backends._param_server import ParamServer + + +def test_param_server_init(): + array = numpy.zeros((5,), dtype="f") + params = {("a", 1): array, ("b", 2): array} + grads = {("a", 1): array, ("c", 3): array} + ps = ParamServer(params, grads) + assert ps.param_keys == (("a", 1), ("b", 2)) + assert ps.grad_keys == (("a", 1),) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/test_ops.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/test_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..e36cbac7dc2b17877e8b95b6a86982f0d83afe28 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/backends/test_ops.py @@ -0,0 +1,1610 @@ +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)) + print(base_sig) + 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: + # TODO: This used to work, but not longer does in Cython 3. + # We're getting spurious differences. + # Need to check string value to handle TypeVars etc. + # assert str(p1) == str(p2), attr + pass + + +@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.skip(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_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")) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/extra/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/extra/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/extra/test_beam_search.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/extra/test_beam_search.py new file mode 100644 index 0000000000000000000000000000000000000000..ab7ab9f11fe27c6e9dc6b56d99ebb0c4555d2639 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/extra/test_beam_search.py @@ -0,0 +1,5 @@ +from thinc.extra.search import MaxViolation + + +def test_init_violn(): + MaxViolation() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_basic_tagger.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_basic_tagger.py new file mode 100644 index 0000000000000000000000000000000000000000..3131ebb91657e4472dade89e62b687f517c85250 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_basic_tagger.py @@ -0,0 +1,86 @@ +import random + +import pytest + +from thinc.api import ( + Adam, + HashEmbed, + Model, + Relu, + Softmax, + chain, + expand_window, + strings2arrays, + with_array, +) + + +@pytest.fixture(scope="module") +def ancora(): + pytest.importorskip("ml_datasets") + import ml_datasets + + return ml_datasets.ud_ancora_pos_tags() + + +def create_embed_relu_relu_softmax(depth, width, vector_length): + with Model.define_operators({">>": chain}): + model = strings2arrays() >> with_array( + HashEmbed(width, vector_length, column=0) + >> expand_window(window_size=1) + >> Relu(width, width * 3) + >> Relu(width, width) + >> Softmax(17, width) + ) + return model + + +@pytest.fixture(params=[create_embed_relu_relu_softmax]) +def create_model(request): + return request.param + + +def evaluate_tagger(model, dev_X, dev_Y, batch_size): + correct = 0.0 + total = 0.0 + for i in range(0, len(dev_X), batch_size): + Yh = model.predict(dev_X[i : i + batch_size]) + Y = dev_Y[i : i + batch_size] + for j in range(len(Yh)): + correct += (Yh[j].argmax(axis=1) == Y[j].argmax(axis=1)).sum() + total += Yh[j].shape[0] + return correct / total + + +def get_shuffled_batches(Xs, Ys, batch_size): + zipped = list(zip(Xs, Ys)) + random.shuffle(zipped) + for i in range(0, len(zipped), batch_size): + batch_X, batch_Y = zip(*zipped[i : i + batch_size]) + yield list(batch_X), list(batch_Y) + + +@pytest.mark.parametrize( + ("depth", "width", "vector_width", "nb_epoch"), [(2, 32, 16, 5)] +) +@pytest.mark.xfail(reason="Flaky live download from the internet", strict=False) +def test_small_end_to_end(depth, width, vector_width, nb_epoch, create_model, ancora): + (train_X, train_Y), (dev_X, dev_Y) = ancora + batch_size = 8 + model = create_model(depth, width, vector_width).initialize() + optimizer = Adam(0.001) + losses = [] + scores = [] + for _ in range(nb_epoch): + losses.append(0.0) + for X, Y in get_shuffled_batches(train_X, train_Y, batch_size): + Yh, backprop = model.begin_update(X) + d_loss = [] + for i in range(len(Yh)): + d_loss.append(Yh[i] - Y[i]) + losses[-1] += ((Yh[i] - Y[i]) ** 2).sum() + backprop(d_loss) + model.finish_update(optimizer) + scores.append(evaluate_tagger(model, dev_X, dev_Y, batch_size)) + assert losses[-1] < losses[0] + assert scores[-1] > scores[0] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_combinators.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_combinators.py new file mode 100644 index 0000000000000000000000000000000000000000..c7b4fbe9f4633b67d25dd4fc59f9d0037ff2a4ba --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_combinators.py @@ -0,0 +1,298 @@ +import numpy +import pytest +from numpy.testing import assert_allclose + +from thinc.api import ( + Dropout, + Linear, + Model, + NumpyOps, + add, + clone, + concatenate, + map_list, + noop, +) +from thinc.layers import chain, tuplify + + +@pytest.fixture(params=[1, 2, 9]) +def nB(request): + return request.param + + +@pytest.fixture(params=[1, 6]) +def nI(request): + return request.param + + +@pytest.fixture(params=[1, 5, 3]) +def nH(request): + return request.param + + +@pytest.fixture(params=[1, 2, 7, 9]) +def nO(request): + return request.param + + +@pytest.fixture +def model1(nH, nI): + return Linear(nH, nI) + + +@pytest.fixture +def model2(nO, nH): + return Linear(nO, nH) + + +@pytest.fixture +def model3(nO): + return Linear(nO, nO) + + +def test_tuplify_zero(): + with pytest.raises(TypeError): + tuplify() + + +def test_tuplify_one(model1): + with pytest.raises(TypeError): + tuplify(model1) + + +def test_tuplify_two(model1, model2): + model = tuplify(model1, model2) + assert len(model.layers) == 2 + + +def test_tuplify_operator_two(model1, model2): + with Model.define_operators({"&": tuplify}): + model = model1 & model2 + assert len(model.layers) == 2 + + +def test_tuplify_dulicates_input(): + model = tuplify(noop(), noop()) + ones = numpy.ones([10]) + out = model.predict(ones) + assert out == (ones, ones) + + +def test_tuplify_initialize(nI, nO): + linear = Linear(nO) + model = tuplify(linear, linear) + ones = numpy.ones((1, nI), dtype="float") + model.initialize(X=ones) + + +def test_tuplify_three(model1, model2, model3): + model = tuplify(model1, model2, model3) + assert len(model.layers) == 3 + + +def test_tuplify_operator_three(model1, model2, model3): + # Previously we 'flattened' these nested calls. We might opt to do so + # again, especially for the operators. + with Model.define_operators({"&": tuplify}): + model = model1 & model2 & model3 + assert len(model.layers) == 2 + assert len(model.layers[0].layers) == 2 + + +def test_chain_zero(): + with pytest.raises(TypeError): + chain() + + +def test_chain_one(model1): + with pytest.raises(TypeError): + chain(model1) + + +def test_chain_two(model1, model2): + model = chain(model1, model2) + assert len(model.layers) == 2 + + +def test_chain_operator_two(model1, model2): + with Model.define_operators({">>": chain}): + model = model1 >> model2 + assert len(model.layers) == 2 + + +def test_chain_three(model1, model2, model3): + model = chain(model1, model2, model3) + assert len(model.layers) == 3 + + +def test_chain_operator_three(model1, model2, model3): + # Previously we 'flattened' these nested calls. We might opt to do so + # again, especially for the operators. + with Model.define_operators({">>": chain}): + model = model1 >> model2 >> model3 + assert len(model.layers) == 2 + assert len(model.layers[0].layers) == 2 + + +def test_chain_right_branch(model1, model2, model3): + # Previously we 'flattened' these nested calls. We might opt to do so + # again, especially for the operators. + merge1 = chain(model1, model2) + merge2 = chain(merge1, model3) + assert len(merge1.layers) == 2 + assert len(merge2.layers) == 2 + + +@pytest.mark.parametrize("ops", [NumpyOps(), NumpyOps(use_blis=True)]) +def test_chain(ops): + data = numpy.asarray([[1, 2, 3, 4]], dtype="f") + model = chain(Linear(1), Dropout(), Linear(1)) + model.ops = ops + model.initialize(data, data) + Y, backprop = model(data, is_train=True) + backprop(Y) + # Layers with and without nO/nI + model = chain(Linear(1), Dropout(), Linear(1, 1)) + model.initialize(data, data) + # Setting dim on model + model = chain(Linear(1), Dropout(), Linear(1)) + model.set_dim("nO", 1) + model.initialize(data, None) + model = chain(Linear(1, 1), Dropout(), Linear(1, 1)) + model.set_dim("nI", 1) + model.initialize(None, data) + # Not enough arguments + with pytest.raises(TypeError): + chain(Linear()) + with pytest.raises(TypeError): + chain() + + +def test_concatenate_one(model1): + model = concatenate(model1) + assert isinstance(model, Model) + + +def test_concatenate_two(model1, model2): + model = concatenate(model1, model2) + assert len(model.layers) == 2 + + +def test_concatenate_operator_two(model1, model2): + with Model.define_operators({"|": concatenate}): + model = model1 | model2 + assert len(model.layers) == 2 + + +def test_concatenate_three(model1, model2, model3): + model = concatenate(model1, model2, model3) + assert len(model.layers) == 3 + + +def test_concatenate_operator_three(model1, model2, model3): + with Model.define_operators({"|": concatenate}): + model = model1 | model2 | model3 + assert len(model.layers) == 3 + + +def test_clone_changes_predictions(nH, nI): + model1 = Linear(nH) + model = clone(model1, 10) + ones = numpy.ones((10, nI), dtype="f") + model.initialize(X=ones) + output_from_cloned = model.predict(ones) + output_from_orig = model1.predict(ones) + assert output_from_cloned.sum() != output_from_orig.sum() + + +def test_clone_gives_distinct_ids(nH, nI): + model = clone(Linear(nH), 5) + assert len(model.layers) == 5 + seen_ids = set() + for node in model.walk(): + assert node.id not in seen_ids + seen_ids.add(node.id) + assert len(seen_ids) == 6 + + +def test_clone_noop(): + model = clone(Linear(), 0) + assert len(model.layers) == 0 + assert model.name == "noop" + + +def test_concatenate_noop(): + model = concatenate() + assert len(model.layers) == 0 + assert model.name == "noop" + + +def test_noop(): + data = numpy.asarray([1, 2, 3], dtype="f") + model = noop(Linear(), Linear()) + model.initialize(data, data) + Y, backprop = model(data, is_train=True) + assert numpy.array_equal(Y, data) + dX = backprop(Y) + assert numpy.array_equal(dX, data) + + +def test_add(): + data = numpy.asarray([[1, 2, 3, 4]], dtype="f") + model = add(Linear(), Linear()) + model.initialize(data, data) + Y, backprop = model(data, is_train=True) + Y2 = sum(layer.predict(data) for layer in model.layers) + assert numpy.array_equal(Y, Y2) + dX = backprop(Y) + assert dX.shape == data.shape + # Test that nesting works + model2 = add(model, Linear()) + assert len(model2.layers) == 3 + model.initialize(data, data) + Y = model2.predict(data) + Y2 = sum(layer.predict(data) for layer in model2.layers) + assert numpy.array_equal(Y, Y2) + + +def test_add_edge_cases(): + data = numpy.asarray([[1, 2, 3, 4]], dtype="f") + with pytest.raises(TypeError): + add() + model = add(Linear(), Linear()) + model._layers = [] + Y, backprop = model(data, is_train=True) + assert numpy.array_equal(data, Y) + dX = backprop(Y) + assert numpy.array_equal(dX, data) + + +def test_concatenate(): + data = numpy.asarray([[1, 2, 3], [4, 5, 6]], dtype="f") + model = concatenate(Linear(), Linear()) + model.initialize(data, data) + Y, backprop = model(data, is_train=True) + assert Y.shape[1] == sum([layer.predict(data).shape[1] for layer in model.layers]) + dX = backprop(Y) + assert dX.shape == data.shape + + +def test_map_list(): + nI = 4 + nO = 9 + Xs = [numpy.zeros((6, nI), dtype="f"), numpy.ones((3, nI), dtype="f")] + Y_shapes = [(x.shape[0], nO) for x in Xs] + model = map_list(Linear()) + model.initialize(X=Xs, Y=[numpy.zeros(shape, dtype="f") for shape in Y_shapes]) + Ys, backprop = model(Xs, is_train=True) + assert isinstance(Ys, list) + assert len(Ys) == len(Xs) + layer = model.layers[0] + for X, Y in zip(Xs, Ys): + assert_allclose(layer.predict(X), Y) + dXs = backprop(Ys) + assert isinstance(dXs, list) + assert len(dXs) == len(Xs) + assert dXs[0].shape == Xs[0].shape + assert dXs[1].shape == Xs[1].shape diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_feed_forward.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_feed_forward.py new file mode 100644 index 0000000000000000000000000000000000000000..a808bb445541c0753f1ee755b8939bf7cb706b30 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_feed_forward.py @@ -0,0 +1,196 @@ +from functools import partial + +import numpy +import pytest +from numpy.testing import assert_allclose + +from thinc.api import Linear, NumpyOps, Relu, chain + + +@pytest.fixture(params=[1, 2, 9]) +def nB(request): + return request.param + + +@pytest.fixture(params=[1, 6]) +def nI(request): + return request.param + + +@pytest.fixture(params=[1, 5, 3]) +def nH(request): + return request.param + + +@pytest.fixture(params=[1, 2, 7, 9]) +def nO(request): + return request.param + + +@pytest.fixture +def model1(nH, nI): + model = Relu(nH, nI).initialize() + return model + + +@pytest.fixture +def model2(nO, nH): + model = Linear(nO, nH).initialize() + return model + + +@pytest.fixture +def input_data(nB, nI): + return numpy.ones((nB, nI), dtype="f") + 1.0 + + +@pytest.fixture +def gradient_data(nB, nO): + return numpy.zeros((nB, nO), dtype="f") - 1.0 + + +@pytest.fixture +def model(model1, model2): + return chain(model1, model2).initialize() + + +def get_expected_predict(input_data, Ws, bs): + numpy_ops = NumpyOps() + X = input_data + for i, (W, b) in enumerate(zip(Ws, bs)): + X = numpy_ops.asarray(X) + if i > 0: + X *= X > 0 + X = numpy.tensordot(X, W, axes=[[1], [1]]) + b + return X + + +def numeric_gradient(predict, weights, epsilon=1e-4): + out1 = predict(weights + epsilon) + out2 = predict(weights - epsilon) + return (out1 - out2) / (2 * epsilon) + + +def test_models_have_shape(model1, model2, nI, nH, nO): + assert model1.get_param("W").shape == (nH, nI) + assert model1.get_param("b").shape == (nH,) + assert model2.get_param("W").shape == (nO, nH) + assert model2.get_param("b").shape == (nO,) + + +def test_model_shape(model, model1, model2, nI, nH, nO): + assert model.get_dim("nI") == model1.get_dim("nI") + assert model.get_dim("nO") == model2.get_dim("nO") + + +def test_infer_output_shape(): + model = Relu(dropout=0.2) + X = model.ops.alloc2f(4, 5) + Y = model.ops.alloc2f(4, 2) + assert model.has_dim("nI") is None + assert model.has_dim("nO") is None + model.initialize(X=X, Y=Y) + assert model.get_dim("nI") == 5 + assert model.get_dim("nO") == 2 + + +def test_predict_and_begin_update_match(model, model1, model2, input_data): + model = chain(model1, model2) + via_predict = model.predict(input_data) + via_update, _ = model.begin_update(input_data) + assert_allclose(via_predict, via_update) + expected = get_expected_predict( + input_data, + [model1.get_param("W"), model2.get_param("W")], + [model1.get_param("b"), model2.get_param("b")], + ) + assert_allclose(via_update, expected, atol=1e-2, rtol=1e-4) + + +def test_init_functions_are_called(): + init_was_called = {} + + def register_init(name, model, X=None, Y=None): + init_was_called[name] = True + + layer1 = Linear(5) + layer2 = Linear(5) + layer3 = Linear(5) + layer1.init = partial(register_init, "one") + layer2.init = partial(register_init, "two") + layer3.init = partial(register_init, "three") + # This is the nesting we'll get from operators. + model = chain(layer1, chain(layer2, layer3)) + assert not init_was_called + model.initialize() + assert init_was_called["one"] + assert init_was_called["two"] + assert init_was_called["three"] + + +class GradientSpy(object): + def __init__(self): + self.weights = None + self.d_weights = None + + def __call__(self, weights, grad): + self.weights = weights + self.d_weights = grad + + +# I don't know how to get this working properly after the refactor. It's a numeric +# gradient check. I suspect the test is the problem, not the code. +@pytest.mark.skip +# This is the actual definition -- it's just annoying to see tonnes of skips. +# def test_gradient(model, input_data, nB, nH, nI, nO): +def test_gradient(): + truth = numpy.zeros((nB, nO), dtype="float32") + truth[0] = 1.0 + + guess, backprop = model.begin_update(input_data) + backprop(guess - truth) + + for layer in model.layers: + for name in layer.param_names: + agrad = layer.get_grad(name).ravel() # Should have grads for all params. + predict = get_predict(layer, name, input_data) + ngrad = get_numeric_gradient(predict, agrad.size, truth) + assert_allclose(agrad, ngrad, atol=0.2, rtol=0.2) + + +def get_predict(layer, param_name, inputs): + """Helper for gradient check. To do the numeric gradient check, we have + to be able to wiggle one value in a parameter, and check the prediction + before and after. So we need to get a callback that gives an output + given a change to one weight. + """ + + def predict(i, epsilon): + param = layer.get_param(param_name) + shape = param.shape + param = param.ravel() + param[i] += epsilon + layer.set_param(param_name, param.reshape(shape)) + outputs = layer.predict(inputs) + param[i] -= epsilon + layer.set_param(param_name, param.reshape(shape)) + return outputs.reshape(shape) + + return predict + + +def get_numeric_gradient(predict, n, target): + gradient = numpy.zeros(n) + for i in range(n): + out1 = predict(i, 1e-4) + out2 = predict(i, -1e-4) + + err1 = _get_loss(out1, target) + err2 = _get_loss(out2, target) + gradient[i] = (err1 - err2) / (2 * 1e-4) + print("NGrad", i, err1, err2) + return gradient + + +def _get_loss(truth, guess): + return numpy.sum(numpy.sum(0.5 * numpy.square(truth - guess), 1)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_hash_embed.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_hash_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..5b79539faa586ff6e537f72ec96aef1dd7afac23 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_hash_embed.py @@ -0,0 +1,19 @@ +import numpy + +from thinc.api import HashEmbed + + +def test_init(): + model = HashEmbed(64, 1000).initialize() + assert model.get_dim("nV") == 1000 + assert model.get_dim("nO") == 64 + assert model.get_param("E").shape == (1000, 64) + + +def test_seed_changes_bucket(): + model1 = HashEmbed(64, 1000, seed=2).initialize() + model2 = HashEmbed(64, 1000, seed=1).initialize() + arr = numpy.ones((1,), dtype="uint64") + vector1 = model1.predict(arr) + vector2 = model2.predict(arr) + assert vector1.sum() != vector2.sum() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_layers_api.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_layers_api.py new file mode 100644 index 0000000000000000000000000000000000000000..046d98940c26f73aff1882a96c85f165a40d5589 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_layers_api.py @@ -0,0 +1,236 @@ +from typing import List, Optional + +import numpy +import pytest +import srsly +from numpy.testing import assert_almost_equal + +from thinc.api import Dropout, Model, NumpyOps, registry, with_padded +from thinc.backends import NumpyOps +from thinc.compat import has_torch +from thinc.types import Array2d, Floats2d, FloatsXd, Padded, Ragged, Shape +from thinc.util import data_validation, get_width + +OPS = NumpyOps() + + +class NoDropoutOps(NumpyOps): + def get_dropout_mask(self, shape: Shape, drop: Optional[float]) -> FloatsXd: + if drop is None or drop <= 0: + return self.xp.ones(shape, dtype="f") + else: + raise ValueError("During prediction, dropout should not be applied") + + +array1d = OPS.xp.asarray([1, 2, 3], dtype="f") +array1dint = OPS.xp.asarray([1, 2, 3], dtype="i") +array2d = OPS.xp.asarray([[4, 2, 3, 4], [1, 5, 3, 1], [9, 8, 5, 7]], dtype="f") +array2dint = OPS.xp.asarray([[1, 2, 3], [4, 5, 6]], dtype="i") +array3d = OPS.xp.zeros((3, 3, 3), dtype="f") +ragged = Ragged(array2d, OPS.xp.asarray([2, 1], dtype="i")) +padded = Padded( + array3d, array1d, OPS.asarray1i([1, 2, 3, 4]), OPS.asarray1i([1, 2, 3, 4]) +) +width = array2d.shape[1] +vectors = numpy.zeros((array2dint.max(), 1), dtype="f") + + +def assert_data_match(Y, out_data): + assert type(Y) == type(out_data) + if isinstance(out_data, OPS.xp.ndarray): + assert isinstance(Y, OPS.xp.ndarray) + assert out_data.ndim == Y.ndim + elif isinstance(out_data, Ragged): + assert isinstance(Y, Ragged) + assert out_data.data.ndim == Y.data.ndim + assert out_data.lengths.ndim == Y.lengths.ndim + elif isinstance(out_data, Padded): + assert isinstance(Y, Padded) + assert out_data.data.ndim == Y.data.ndim + assert out_data.size_at_t.ndim == Y.size_at_t.ndim + assert len(out_data.lengths) == len(Y.lengths) + assert len(out_data.indices) == len(Y.indices) + elif isinstance(out_data, (list, tuple)): + assert isinstance(Y, (list, tuple)) + assert all(isinstance(x, numpy.ndarray) for x in Y) + else: + pytest.fail(f"wrong output of {type(Y)}: {Y}") + + +TEST_CASES_SUMMABLE = [ + # Array to array + ("Dish.v1", {}, array2d, array2d), + ("Dish.v1", {"nO": 4, "nI": 4}, array2d, array2d), + ("Dropout.v1", {}, array2d, array2d), + ("LayerNorm.v1", {}, array2d, array2d), + ("Linear.v1", {}, array2d, array2d), + ("Logistic.v1", {}, array2d, array2d), + ("Maxout.v1", {}, array2d, array2d), + ("Maxout.v1", {"normalize": True, "dropout": 0.2}, array2d, array2d), + ("Maxout.v1", {"nO": 4, "nI": 4}, array2d, array2d), + ("Mish.v1", {}, array2d, array2d), + ("Mish.v1", {"nO": 4, "nI": 4}, array2d, array2d), + ("Mish.v1", {"normalize": True, "dropout": 0.2}, array2d, array2d), + ("Relu.v1", {}, array2d, array2d), + ("Relu.v1", {"normalize": True, "dropout": 0.2}, array2d, array2d), + ("Sigmoid.v1", {}, array2d, array2d), + ("Sigmoid.v1", {"nO": 4, "nI": 4}, array2d, array2d), + ("ClippedLinear.v1", {}, array2d, array2d), + ("ClippedLinear.v1", {"nO": 4, "nI": 4}, array2d, array2d), + ("ReluK.v1", {}, array2d, array2d), + ("ReluK.v1", {"nO": 4, "nI": 4}, array2d, array2d), + ("HardSigmoid.v1", {}, array2d, array2d), + ("HardSigmoid.v1", {"nO": 4, "nI": 4}, array2d, array2d), + ("HardTanh.v1", {}, array2d, array2d), + ("HardTanh.v1", {"nO": 4, "nI": 4}, array2d, array2d), + ("HardSwish.v1", {}, array2d, array2d), + ("HardSwish.v1", {"nO": 4, "nI": 4}, array2d, array2d), + ("HardSwishMobilenet.v1", {}, array2d, array2d), + ("HardSwishMobilenet.v1", {"nO": 4, "nI": 4}, array2d, array2d), + ("Swish.v1", {}, array2d, array2d), + ("Swish.v1", {"nO": 4, "nI": 4}, array2d, array2d), + ("Gelu.v1", {}, array2d, array2d), + ("Gelu.v1", {"nO": 4, "nI": 4}, array2d, array2d), + ("sigmoid_activation.v1", {}, array2d, array2d), + ("softmax_activation.v1", {}, array2d, array2d), + ("Softmax.v1", {}, array2d, array2d), + ("Softmax.v1", {"nO": 4, "nI": 4}, array2d, array2d), + ("Softmax.v2", {}, array2d, array2d), + ("Softmax.v2", {"nO": 4, "nI": 4}, array2d, array2d), + # fmt: off + # List to list + ("LSTM.v1", {"bi": False}, [array2d, array2d], [array2d, array2d]), + pytest.param("PyTorchLSTM.v1", {"bi": False, "nO": width, "nI": width}, [array2d, array2d], [array2d, array2d], marks=pytest.mark.skipif(not has_torch, reason="needs PyTorch")), + # fmt: on +] + +TEST_CASES = [ + *TEST_CASES_SUMMABLE, + pytest.param( + "PyTorchLSTM.v1", + {"bi": True, "nO": width * 2, "nI": width}, + [array2d, array2d], + [array2d, array2d], + marks=pytest.mark.skipif(not has_torch, reason="needs PyTorch"), + ), + ("LSTM.v1", {"bi": True}, [array2d, array2d], [array2d, array2d]), + # Ragged to array + ("reduce_max.v1", {}, ragged, array2d), + ("reduce_mean.v1", {}, ragged, array2d), + ("reduce_sum.v1", {}, ragged, array2d), + # fmt: off + # Other + ("expand_window.v1", {}, array2d, array2d), + ("expand_window.v1", {}, ragged, ragged), + ("Embed.v1", {"nO": 4, "nV": int(array2dint.max() + 1), "column": 0, "dropout": 0.2}, array2dint, array2d), + ("Embed.v1", {"nO": 4, "nV": int(array1dint.max() + 1)}, array1dint, array2d), + ("HashEmbed.v1", {"nO": 1, "nV": int(array2dint.max()), "column": 0, "dropout": 0.2}, array2dint, array2d), + ("HashEmbed.v1", {"nO": 1, "nV": 2}, array1dint, array2d), + ("MultiSoftmax.v1", {"nOs": (1, 3)}, array2d, array2d), + # ("CauchySimilarity.v1", {}, (array2d, array2d), array1d), + ("ParametricAttention.v1", {}, ragged, ragged), + ("ParametricAttention.v2", {}, ragged, ragged), + ("ParametricAttention.v2", {"key_transform": {"@layers": "Gelu.v1"}}, ragged, ragged), + ("SparseLinear.v1", {}, (numpy.asarray([1, 2, 3], dtype="uint64"), array1d, numpy.asarray([1, 1], dtype="i")), array2d), + ("SparseLinear.v2", {}, (numpy.asarray([1, 2, 3], dtype="uint64"), array1d, numpy.asarray([1, 1], dtype="i")), array2d), + ("remap_ids.v1", {"dtype": "f"}, ["a", 1, 5.0], array2dint), + ("remap_ids.v2", {"mapping_table": {}, "column": 1}, numpy.array([[1, 2, 3], [4, 5, 6]]).T, array2dint), + ("premap_ids.v1", {"mapping_table": {}, "column": 1}, numpy.array([[1, 2, 3], [4, 5, 6]]).T, array2dint), + # fmt: on +] + + +@pytest.mark.parametrize("name,kwargs,in_data,out_data", TEST_CASES) +def test_layers_from_config(name, kwargs, in_data, out_data): + cfg = {"@layers": name, **kwargs} + filled_cfg = registry.fill({"config": cfg}) + assert srsly.is_json_serializable(filled_cfg) + model = registry.resolve({"config": cfg})["config"] + if "LSTM" in name: + model = with_padded(model) + valid = True + with data_validation(valid): + model.initialize(in_data, out_data) + Y, backprop = model(in_data, is_train=True) + if model.has_dim("nO"): + assert get_width(Y) == model.get_dim("nO") + assert_data_match(Y, out_data) + dX = backprop(Y) + assert_data_match(dX, in_data) + # Test that during predictions, no dropout is applied + model._to_ops(NoDropoutOps()) + model.predict(in_data) + + +@pytest.mark.parametrize("name,kwargs,in_data,out_data", TEST_CASES_SUMMABLE) +def test_layers_with_residual(name, kwargs, in_data, out_data): + cfg = {"@layers": "residual.v1", "layer": {"@layers": name, **kwargs}} + model = registry.resolve({"config": cfg})["config"] + if "LSTM" in name: + model = with_padded(model) + model.initialize(in_data, out_data) + Y, backprop = model(in_data, is_train=True) + assert_data_match(Y, out_data) + dX = backprop(Y) + assert_data_match(dX, in_data) + + +@pytest.mark.parametrize("data", [array2d, ragged, padded, [array2d, array2d]]) +def test_dropout(data): + model = Dropout(0.2) + model.initialize(data, data) + Y, backprop = model(data, is_train=False) + assert_data_match(Y, data) + dX = backprop(Y) + assert_data_match(dX, data) + + +@pytest.mark.parametrize("name,kwargs,in_data,out_data", TEST_CASES) +def test_layers_batching_all(name, kwargs, in_data, out_data): + cfg = {"@layers": name, **kwargs} + model = registry.resolve({"config": cfg})["config"] + if "expand_window" in name: + return + if "LSTM" in name: + model = with_padded(model) + util_batch_unbatch_list(model, in_data, out_data) + else: + if isinstance(in_data, OPS.xp.ndarray) and in_data.ndim == 2: + if isinstance(out_data, OPS.xp.ndarray) and out_data.ndim == 2: + util_batch_unbatch_array(model, in_data, out_data) + if isinstance(in_data, Ragged): + if isinstance(out_data, OPS.xp.ndarray) and out_data.ndim == 2: + util_batch_unbatch_ragged(model, in_data, out_data) + + +def util_batch_unbatch_array( + model: Model[Floats2d, Array2d], in_data: Floats2d, out_data: Array2d +): + unbatched = [model.ops.reshape2f(a, 1, -1) for a in in_data] + with data_validation(True): + model.initialize(in_data, out_data) + Y_batched = model.predict(in_data).tolist() + Y_not_batched = [model.predict(u)[0].tolist() for u in unbatched] + assert_almost_equal(Y_batched, Y_not_batched, decimal=4) + + +def util_batch_unbatch_list( + model: Model[List[Array2d], List[Array2d]], + in_data: List[Array2d], + out_data: List[Array2d], +): + with data_validation(True): + model.initialize(in_data, out_data) + Y_batched = model.predict(in_data) + Y_not_batched = [model.predict([u])[0] for u in in_data] + assert_almost_equal(Y_batched, Y_not_batched, decimal=4) # type: ignore + + +def util_batch_unbatch_ragged( + model: Model[Ragged, Array2d], in_data: Ragged, out_data: Array2d +): + with data_validation(True): + model.initialize(in_data, out_data) + Y_batched = model.predict(in_data) + Y_not_batched = [model.predict(in_data[i])[0] for i in range(len(in_data))] + assert_almost_equal(Y_batched, Y_not_batched, decimal=4) # type: ignore diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_linear.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..e51e1dda1f3959e066ef6d4fbb01cc629a446e39 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_linear.py @@ -0,0 +1,246 @@ +from unittest.mock import MagicMock + +import numpy +import pytest +from hypothesis import given, settings +from numpy.testing import assert_allclose + +from thinc.api import SGD, Dropout, Linear, chain + +from ..strategies import arrays_OI_O_BI +from ..util import get_model, get_shape + + +@pytest.fixture +def model(): + model = Linear() + return model + + +def test_linear_default_name(model): + assert model.name == "linear" + + +def test_linear_dimensions_on_data(): + X = MagicMock(shape=(5, 10), spec=numpy.ndarray) + X.ndim = 2 + X.dtype = "float32" + y = MagicMock(shape=(8,), spec=numpy.ndarray) + y.ndim = 2 + y.dtype = "float32" + y.max = MagicMock() + model = Linear() + model.initialize(X, y) + assert model.get_dim("nI") is not None + y.max.assert_called_with() + + +@pytest.mark.skip(reason="Flaky, skip temporarily") +@given(arrays_OI_O_BI(max_batch=8, max_out=8, max_in=8)) +def test_begin_update_matches_predict(W_b_input): + model = get_model(W_b_input) + nr_batch, nr_out, nr_in = get_shape(W_b_input) + W, b, input_ = W_b_input + fwd_via_begin_update, finish_update = model.begin_update(input_) + fwd_via_predict_batch = model.predict(input_) + assert_allclose(fwd_via_begin_update, fwd_via_predict_batch) + + +@pytest.mark.skip(reason="Flaky, skip temporarily") +@given(arrays_OI_O_BI(max_batch=8, max_out=8, max_in=8)) +def test_finish_update_calls_optimizer_with_weights(W_b_input): + model = get_model(W_b_input) + nr_batch, nr_out, nr_in = get_shape(W_b_input) + W, b, input_ = W_b_input + output, finish_update = model.begin_update(input_) + + seen_keys = set() + + def sgd(key, data, gradient, **kwargs): + seen_keys.add(key) + assert data.shape == gradient.shape + return data, gradient + + grad_BO = numpy.ones((nr_batch, nr_out), dtype="f") + grad_BI = finish_update(grad_BO) # noqa: F841 + model.finish_update(sgd) + for name in model.param_names: + assert (model.id, name) in seen_keys + + +@pytest.mark.skip(reason="Flaky, skip temporarily") +@settings(max_examples=100) +@given(arrays_OI_O_BI(max_batch=8, max_out=8, max_in=8)) +def test_predict_small(W_b_input): + W, b, input_ = W_b_input + nr_out, nr_in = W.shape + model = Linear(nr_out, nr_in) + model.set_param("W", W) + model.set_param("b", b) + + einsummed = numpy.einsum( + "oi,bi->bo", + numpy.asarray(W, dtype="float64"), + numpy.asarray(input_, dtype="float64"), + optimize=False, + ) + + expected_output = einsummed + b + + predicted_output = model.predict(input_) + assert_allclose(predicted_output, expected_output, rtol=0.01, atol=0.01) + + +@pytest.mark.skip(reason="Flaky, skip temporarily") +@given(arrays_OI_O_BI(max_batch=20, max_out=30, max_in=30)) +@settings(deadline=None) +def test_predict_extensive(W_b_input): + W, b, input_ = W_b_input + nr_out, nr_in = W.shape + model = Linear(nr_out, nr_in) + model.set_param("W", W) + model.set_param("b", b) + + einsummed = numpy.einsum( + "bi,oi->bo", + numpy.asarray(input_, dtype="float32"), + numpy.asarray(W, dtype="float32"), + optimize=False, + ) + + expected_output = einsummed + b + + predicted_output = model.predict(input_) + assert_allclose(predicted_output, expected_output, rtol=1e-04, atol=0.0001) + + +@pytest.mark.skip(reason="Flaky, skip temporarily") +@given(arrays_OI_O_BI(max_batch=8, max_out=8, max_in=8)) +def test_dropout_gives_zero_activations(W_b_input): + model = chain(get_model(W_b_input), Dropout(1.0)) + nr_batch, nr_out, nr_in = get_shape(W_b_input) + W, b, input_ = W_b_input + fwd_dropped, _ = model.begin_update(input_) + assert all(val == 0.0 for val in fwd_dropped.flatten()) + + +@pytest.mark.skip(reason="Flaky, skip temporarily") +@given(arrays_OI_O_BI(max_batch=8, max_out=8, max_in=8)) +def test_dropout_gives_zero_gradients(W_b_input): + model = chain(get_model(W_b_input), Dropout(1.0)) + nr_batch, nr_out, nr_in = get_shape(W_b_input) + W, b, input_ = W_b_input + for node in model.walk(): + if node.name == "dropout": + node.attrs["dropout_rate"] = 1.0 + fwd_dropped, finish_update = model.begin_update(input_) + grad_BO = numpy.ones((nr_batch, nr_out), dtype="f") + grad_BI = finish_update(grad_BO) + assert all(val == 0.0 for val in grad_BI.flatten()) + + +@pytest.fixture +def model2(): + model = Linear(2, 2).initialize() + return model + + +def test_init(model2): + assert model2.get_dim("nO") == 2 + assert model2.get_dim("nI") == 2 + assert model2.get_param("W") is not None + assert model2.get_param("b") is not None + + +def test_predict_bias(model2): + input_ = model2.ops.alloc2f(1, model2.get_dim("nI")) + target_scores = model2.ops.alloc2f(1, model2.get_dim("nI")) + scores = model2.predict(input_) + assert_allclose(scores[0], target_scores[0]) + # Set bias for class 0 + model2.get_param("b")[0] = 2.0 + target_scores[0, 0] = 2.0 + scores = model2.predict(input_) + assert_allclose(scores, target_scores) + # Set bias for class 1 + model2.get_param("b")[1] = 5.0 + target_scores[0, 1] = 5.0 + scores = model2.predict(input_) + assert_allclose(scores, target_scores) + + +@pytest.mark.parametrize( + "X,expected", + [ + (numpy.asarray([0.0, 0.0], dtype="f"), [0.0, 0.0]), + (numpy.asarray([1.0, 0.0], dtype="f"), [1.0, 0.0]), + (numpy.asarray([0.0, 1.0], dtype="f"), [0.0, 1.0]), + (numpy.asarray([1.0, 1.0], dtype="f"), [1.0, 1.0]), + ], +) +def test_predict_weights(X, expected): + W = numpy.asarray([1.0, 0.0, 0.0, 1.0], dtype="f").reshape((2, 2)) + bias = numpy.asarray([0.0, 0.0], dtype="f") + + model = Linear(W.shape[0], W.shape[1]) + model.set_param("W", W) + model.set_param("b", bias) + + scores = model.predict(X.reshape((1, -1))) + assert_allclose(scores.ravel(), expected) + + +def test_update(): + W = numpy.asarray([1.0, 0.0, 0.0, 1.0], dtype="f").reshape((2, 2)) + bias = numpy.asarray([0.0, 0.0], dtype="f") + + model = Linear(2, 2) + model.set_param("W", W) + model.set_param("b", bias) + sgd = SGD(1.0, L2=0.0, grad_clip=0.0) + sgd.averages = None + + ff = numpy.asarray([[0.0, 0.0]], dtype="f") + tf = numpy.asarray([[1.0, 0.0]], dtype="f") + ft = numpy.asarray([[0.0, 1.0]], dtype="f") # noqa: F841 + tt = numpy.asarray([[1.0, 1.0]], dtype="f") # noqa: F841 + + # ff, i.e. 0, 0 + scores, backprop = model.begin_update(ff) + assert_allclose(scores[0, 0], scores[0, 1]) + # Tell it the answer was 'f' + gradient = numpy.asarray([[-1.0, 0.0]], dtype="f") + backprop(gradient) + for key, (param, d_param) in model.get_gradients().items(): + param, d_param = sgd(key, param, d_param) + model.set_param(key[1], param) + model.set_grad(key[1], d_param) + + b = model.get_param("b") + W = model.get_param("W") + assert b[0] == 1.0 + assert b[1] == 0.0 + # Unchanged -- input was zeros, so can't get gradient for weights. + assert W[0, 0] == 1.0 + assert W[0, 1] == 0.0 + assert W[1, 0] == 0.0 + assert W[1, 1] == 1.0 + + # tf, i.e. 1, 0 + scores, finish_update = model.begin_update(tf) + # Tell it the answer was 'T' + gradient = numpy.asarray([[0.0, -1.0]], dtype="f") + finish_update(gradient) + for key, (W, dW) in model.get_gradients().items(): + sgd(key, W, dW) + b = model.get_param("b") + W = model.get_param("W") + assert b[0] == 1.0 + assert b[1] == 1.0 + # Gradient for weights should have been outer(gradient, input) + # so outer([0, -1.], [1., 0.]) + # = [[0., 0.], [-1., 0.]] + assert W[0, 0] == 1.0 - 0.0 + assert W[0, 1] == 0.0 - 0.0 + assert W[1, 0] == 0.0 - -1.0 + assert W[1, 1] == 1.0 - 0.0 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_lstm.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_lstm.py new file mode 100644 index 0000000000000000000000000000000000000000..44c90ed4c8d243129e4b16659600d77a144900d4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_lstm.py @@ -0,0 +1,178 @@ +import timeit + +import numpy +import pytest + +from thinc.api import LSTM, NumpyOps, Ops, PyTorchLSTM, fix_random_seed, with_padded +from thinc.compat import has_torch + + +@pytest.fixture(params=[1, 6]) +def nI(request): + return request.param + + +@pytest.fixture(params=[1, 2, 7, 9]) +def nO(request): + return request.param + + +def test_list2padded(): + ops = NumpyOps() + seqs = [numpy.zeros((5, 4)), numpy.zeros((8, 4)), numpy.zeros((2, 4))] + padded = ops.list2padded(seqs) + arr = padded.data + size_at_t = padded.size_at_t + assert arr.shape == (8, 3, 4) + assert size_at_t[0] == 3 + assert size_at_t[1] == 3 + assert size_at_t[2] == 2 + assert size_at_t[3] == 2 + assert size_at_t[4] == 2 + assert size_at_t[5] == 1 + assert size_at_t[6] == 1 + assert size_at_t[7] == 1 + unpadded = ops.padded2list(padded) + assert unpadded[0].shape == (5, 4) + assert unpadded[1].shape == (8, 4) + assert unpadded[2].shape == (2, 4) + + +@pytest.mark.parametrize("ops", [Ops(), NumpyOps()]) +@pytest.mark.parametrize("nO,nI", [(1, 2), (2, 2), (100, 200), (9, 6)]) +def test_LSTM_init_with_sizes(ops, nO, nI): + model = with_padded(LSTM(nO, nI, depth=1)).initialize() + for node in model.walk(): + model.ops = ops + # Check no unallocated params. + assert node.has_param("LSTM") is not None + assert node.has_param("HC0") is not None + for node in model.walk(): + # Check param sizes. + if node.has_param("LSTM"): + params = node.get_param("LSTM") + assert params.shape == ( + ((nO * 4 * nI)) + (nO * 4) + (nO * 4 * nO + nO * 4), + ) + if node.has_param("HC0"): + params = node.get_param("HC0") + assert params.shape == (2, 1, 1, nO) + + +@pytest.mark.parametrize("ops", [Ops(), NumpyOps()]) +def test_LSTM_fwd_bwd_shapes_simple(ops, nO, nI): + nO = 1 + nI = 2 + X = numpy.asarray([[0.1, 0.1], [-0.1, -0.1], [1.0, 1.0]], dtype="f") + model = with_padded(LSTM(nO, nI)).initialize(X=[X]) + for node in model.walk(): + node.ops = ops + ys, backprop_ys = model([X], is_train=True) + dXs = backprop_ys(ys) + assert numpy.vstack(dXs).shape == numpy.vstack([X]).shape + + +@pytest.mark.parametrize("ops", [Ops(), NumpyOps()]) +@pytest.mark.parametrize( + "nO,nI,depth,bi,lengths", + [ + (1, 1, 1, False, [1]), + (12, 32, 1, False, [3, 1]), + (2, 2, 1, True, [2, 5, 7]), + (2, 2, 2, False, [7, 2, 4]), + (2, 2, 2, True, [1]), + (32, 16, 1, True, [5, 1, 10, 2]), + (32, 16, 2, True, [3, 3, 5]), + (32, 16, 3, True, [9, 2, 4]), + ], +) +def test_BiLSTM_fwd_bwd_shapes(ops, nO, nI, depth, bi, lengths): + Xs = [numpy.ones((length, nI), dtype="f") for length in lengths] + model = with_padded(LSTM(nO, nI, depth=depth, bi=bi)).initialize(X=Xs) + for node in model.walk(): + node.ops = ops + ys, backprop_ys = model(Xs, is_train=True) + dXs = backprop_ys(ys) + assert numpy.vstack(dXs).shape == numpy.vstack(Xs).shape + + +def test_LSTM_learns(): + fix_random_seed(0) + + nO = 2 + nI = 2 + + def sgd(key, weights, gradient): + weights -= 0.001 * gradient + return weights, gradient * 0 + + model = with_padded(LSTM(nO, nI)) + X = [[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]] + Y = [[0.2, 0.2], [0.3, 0.3], [0.4, 0.4]] + X = [model.ops.asarray(x, dtype="f").reshape((1, -1)) for x in X] + Y = [model.ops.asarray(y, dtype="f").reshape((1, -1)) for y in Y] + model = model.initialize(X, Y) + Yhs, bp_Yhs = model.begin_update(X) + loss1 = sum([((yh - y) ** 2).sum() for yh, y in zip(Yhs, Y)]) + Yhs, bp_Yhs = model.begin_update(X) + dYhs = [yh - y for yh, y in zip(Yhs, Y)] + dXs = bp_Yhs(dYhs) + model.finish_update(sgd) + Yhs, bp_Yhs = model.begin_update(X) + dYhs = [yh - y for yh, y in zip(Yhs, Y)] + dXs = bp_Yhs(dYhs) # noqa: F841 + loss2 = sum([((yh - y) ** 2).sum() for yh, y in zip(Yhs, Y)]) + assert loss1 > loss2, (loss1, loss2) + + +@pytest.mark.skip +def test_benchmark_LSTM_fwd(): + nO = 128 + nI = 128 + n_batch = 1000 + batch_size = 30 + seq_len = 30 + lengths = numpy.random.normal(scale=10, loc=30, size=n_batch * batch_size) + lengths = numpy.maximum(lengths, 1) + batches = [] + uniform_lengths = False + model = with_padded(LSTM(nO, nI)).initialize() + for batch_lengths in model.ops.minibatch(batch_size, lengths): + batch_lengths = list(batch_lengths) + if uniform_lengths: + seq_len = max(batch_lengths) + batch = [ + numpy.asarray( + numpy.random.uniform(0.0, 1.0, (int(seq_len), nI)), dtype="f" + ) + for _ in batch_lengths + ] + else: + batch = [ + numpy.asarray( + numpy.random.uniform(0.0, 1.0, (int(seq_len), nI)), dtype="f" + ) + for seq_len in batch_lengths + ] + batches.append(batch) + start = timeit.default_timer() + for Xs in batches: + ys, bp_ys = model.begin_update(list(Xs)) + # _ = bp_ys(ys) + end = timeit.default_timer() + n_samples = n_batch * batch_size + print( + "--- %i samples in %s seconds (%f samples/s, %.7f s/sample) ---" + % (n_samples, end - start, n_samples / (end - start), (end - start) / n_samples) + ) + + +def test_lstm_init(): + model = with_padded(LSTM(2, 2, bi=True)).initialize() + model.initialize() + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +def test_pytorch_lstm_init(): + model = with_padded(PyTorchLSTM(2, 2, depth=0)).initialize() + assert model.name == "with_padded(noop)" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_mappers.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_mappers.py new file mode 100644 index 0000000000000000000000000000000000000000..85e984bc4def20435bc0cfaf6b6b7e8a9b9ff5d8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_mappers.py @@ -0,0 +1,56 @@ +import numpy +import pytest + +from thinc.layers import premap_ids, remap_ids, remap_ids_v2 + + +@pytest.fixture +def keys(): + return numpy.array([4, 2, 6, 1, 8, 7, 9, 3, 30]) + + +@pytest.fixture +def mapper(keys): + return {int(k): int(v) for v, k in enumerate(keys)} + + +def test_premap(keys, mapper): + premap = premap_ids(mapper, default=99) + values, _ = premap(keys, False) + numpy.testing.assert_equal(values.squeeze(), numpy.asarray(range(len(keys)))) + + +def test_remap(keys, mapper): + remap = remap_ids(mapper, default=99) + values, _ = remap(keys, False) + numpy.testing.assert_equal(values.squeeze(), numpy.asarray(range(len(keys)))) + + +def test_remap_v2(keys, mapper): + remap = remap_ids_v2(mapper, default=99) + values, _ = remap(keys, False) + numpy.testing.assert_equal(values.squeeze(), numpy.asarray(range(len(keys)))) + + +def test_remap_premap_eq(keys, mapper): + remap = remap_ids(mapper, default=99) + remap_v2 = remap_ids_v2(mapper, default=99) + premap = premap_ids(mapper, default=99) + values1, _ = remap(keys, False) + values2, _ = remap_v2(keys, False) + values3, _ = premap(keys, False) + numpy.testing.assert_equal(values1, values2) + numpy.testing.assert_equal(values2, values3) + + +def test_column(keys, mapper): + idx = numpy.zeros((len(keys), 4), dtype="int") + idx[:, 3] = keys + remap_v2 = remap_ids_v2(mapper, column=3) + premap = premap_ids(mapper, column=3) + numpy.testing.assert_equal( + remap_v2(idx, False)[0].squeeze(), numpy.asarray(range(len(keys))) + ) + numpy.testing.assert_equal( + premap(idx, False)[0].squeeze(), numpy.asarray(range(len(keys))) + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_mnist.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_mnist.py new file mode 100644 index 0000000000000000000000000000000000000000..8fdb74fa32f45e2253c68d63565969ab8559d273 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_mnist.py @@ -0,0 +1,123 @@ +import platform + +import pytest + +from thinc.api import ( + Adam, + PyTorchWrapper, + Relu, + Softmax, + TensorFlowWrapper, + chain, + clone, + get_current_ops, +) +from thinc.compat import has_tensorflow, has_torch + + +@pytest.fixture(scope="module") +def mnist(limit=5000): + pytest.importorskip("ml_datasets") + import ml_datasets + + (train_X, train_Y), (dev_X, dev_Y) = ml_datasets.mnist() + return (train_X[:limit], train_Y[:limit]), (dev_X[:limit], dev_Y[:limit]) + + +def create_relu_softmax(width, dropout, nI, nO): + return chain(clone(Relu(nO=width, dropout=dropout), 2), Softmax(10, width)) + + +def create_wrapped_pytorch(width, dropout, nI, nO): + import torch + import torch.nn + import torch.nn.functional as F + + class PyTorchModel(torch.nn.Module): + def __init__(self, width, nO, nI, dropout): + super(PyTorchModel, self).__init__() + self.dropout1 = torch.nn.Dropout2d(dropout) + self.dropout2 = torch.nn.Dropout2d(dropout) + self.fc1 = torch.nn.Linear(nI, width) + self.fc2 = torch.nn.Linear(width, nO) + + def forward(self, x): + x = F.relu(x) + x = self.dropout1(x) + x = self.fc1(x) + x = F.relu(x) + x = self.dropout2(x) + x = self.fc2(x) + output = F.log_softmax(x, dim=1) + return output + + return PyTorchWrapper(PyTorchModel(width, nO, nI, dropout)) + + +def create_wrapped_tensorflow(width, dropout, nI, nO): + from tensorflow.keras.layers import Dense, Dropout + from tensorflow.keras.models import Sequential + + tf_model = Sequential() + tf_model.add(Dense(width, activation="relu", input_shape=(nI,))) + tf_model.add(Dropout(dropout)) + tf_model.add(Dense(width, activation="relu")) + tf_model.add(Dropout(dropout)) + tf_model.add(Dense(nO, activation=None)) + return TensorFlowWrapper(tf_model) + + +@pytest.fixture( + # fmt: off + params=[ + create_relu_softmax, + pytest.param(create_wrapped_pytorch, marks=pytest.mark.skipif(not has_torch, reason="needs PyTorch")), + pytest.param(create_wrapped_tensorflow, marks=pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow")) + ] + # fmt: on +) +def create_model(request): + return request.param + + +@pytest.mark.slow +@pytest.mark.xfail( + platform.system() == "Darwin", + reason="SSL: CERTIFICATE_VERIFY_FAILED", + strict=False, # Works on macos-15-intel Python 3.10, for some reason +) +@pytest.mark.parametrize(("width", "nb_epoch", "min_score"), [(32, 20, 0.8)]) +def test_small_end_to_end(width, nb_epoch, min_score, create_model, mnist): + batch_size = 128 + dropout = 0.2 + (train_X, train_Y), (dev_X, dev_Y) = mnist + model = create_model(width, dropout, nI=train_X.shape[1], nO=train_Y.shape[1]) + model.initialize(X=train_X[:5], Y=train_Y[:5]) + optimizer = Adam(0.001) + losses = [] + scores = [] + ops = get_current_ops() + + for i in range(nb_epoch): + for X, Y in model.ops.multibatch(batch_size, train_X, train_Y, shuffle=True): + Yh, backprop = model.begin_update(X) + # Ensure that the tensor is type-compatible with the current backend. + Yh = ops.asarray(Yh) + + backprop(Yh - Y) + model.finish_update(optimizer) + losses.append(((Yh - Y) ** 2).sum()) + correct = 0 + total = 0 + for X, Y in model.ops.multibatch(batch_size, dev_X, dev_Y): + Yh = model.predict(X) + Yh = ops.asarray(Yh) + + correct += (Yh.argmax(axis=1) == Y.argmax(axis=1)).sum() + total += Yh.shape[0] + score = correct / total + scores.append(score) + assert losses[-1] < losses[0], losses + if scores[0] < 1.0: + assert scores[-1] > scores[0], scores + assert any([score > min_score for score in scores]), scores diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_mxnet_wrapper.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_mxnet_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..8ddf5dfce522c43db99d692e5124b7237d989d76 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_mxnet_wrapper.py @@ -0,0 +1,216 @@ +from typing import cast + +import numpy +import pytest + +from thinc.api import ( + Adam, + ArgsKwargs, + Model, + MXNetWrapper, + Ops, + get_current_ops, + mxnet2xp, + xp2mxnet, +) +from thinc.compat import has_cupy_gpu, has_mxnet +from thinc.types import Array1d, Array2d, IntsXd +from thinc.util import to_categorical + +from ..util import check_input_converters, make_tempdir + + +@pytest.fixture +def n_hidden() -> int: + return 12 + + +@pytest.fixture +def input_size() -> int: + return 784 + + +@pytest.fixture +def n_classes() -> int: + return 10 + + +@pytest.fixture +def answer() -> int: + return 1 + + +@pytest.fixture +def X(input_size: int) -> Array2d: + ops: Ops = get_current_ops() + return cast(Array2d, ops.alloc(shape=(1, input_size))) + + +@pytest.fixture +def Y(answer: int, n_classes: int) -> Array2d: + ops: Ops = get_current_ops() + return cast( + Array2d, + to_categorical(cast(IntsXd, ops.asarray([answer])), n_classes=n_classes), + ) + + +@pytest.fixture +def mx_model(n_hidden: int, input_size: int, X: Array2d): + import mxnet as mx + + mx_model = mx.gluon.nn.Sequential() + mx_model.add( + mx.gluon.nn.Dense(n_hidden), + mx.gluon.nn.LayerNorm(), + mx.gluon.nn.Dense(n_hidden, activation="relu"), + mx.gluon.nn.LayerNorm(), + mx.gluon.nn.Dense(10, activation="softrelu"), + ) + mx_model.initialize() + return mx_model + + +@pytest.fixture +def model(mx_model) -> Model[Array2d, Array2d]: + return MXNetWrapper(mx_model) + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +def test_mxnet_wrapper_roundtrip_conversion(): + import mxnet as mx + + xp_tensor = numpy.zeros((2, 3), dtype="f") + mx_tensor = xp2mxnet(xp_tensor) + assert isinstance(mx_tensor, mx.nd.NDArray) + new_xp_tensor = mxnet2xp(mx_tensor) + assert numpy.array_equal(xp_tensor, new_xp_tensor) + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +def test_mxnet_wrapper_gluon_sequential(): + import mxnet as mx + + mx_model = mx.gluon.nn.Sequential() + mx_model.add(mx.gluon.nn.Dense(12)) + wrapped = MXNetWrapper(mx_model) + assert isinstance(wrapped, Model) + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +def test_mxnet_wrapper_built_model( + model: Model[Array2d, Array2d], X: Array2d, Y: Array1d +): + # built models are validated more and can perform useful operations: + assert model.predict(X) is not None + # They can de/serialized + assert model.from_bytes(model.to_bytes()) is not None + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +def test_mxnet_wrapper_predict(model: Model[Array2d, Array2d], X: Array2d): + model.predict(X) + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +def test_mxnet_wrapper_train_overfits( + model: Model[Array2d, Array2d], X: Array2d, Y: Array1d, answer: int +): + optimizer = Adam() + for i in range(100): + guesses, backprop = model(X, is_train=True) + d_guesses = (guesses - Y) / guesses.shape[0] + backprop(d_guesses) + model.finish_update(optimizer) + predicted = model.predict(X).argmax() + assert predicted == answer + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +def test_mxnet_wrapper_can_copy_model(model: Model[Array2d, Array2d], X: Array2d): + model.predict(X) + copy: Model[Array2d, Array2d] = model.copy() + assert copy is not None + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +def test_mxnet_wrapper_to_bytes(model: Model[Array2d, Array2d], X: Array2d): + model.predict(X) + # And can be serialized + model_bytes = model.to_bytes() + assert model_bytes is not None + model.from_bytes(model_bytes) + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +def test_mxnet_wrapper_to_from_disk(model: Model[Array2d, Array2d], X: Array2d): + model.predict(X) + with make_tempdir() as tmp_path: + model_file = tmp_path / "model.bytes" + model.to_disk(model_file) + another_model = model.from_disk(model_file) + assert another_model is not None + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +def test_mxnet_wrapper_from_bytes(model: Model[Array2d, Array2d], X: Array2d): + model.predict(X) + model_bytes = model.to_bytes() + another_model = model.from_bytes(model_bytes) + assert another_model is not None + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +def test_mxnet_wrapper_to_cpu(mx_model, X: Array2d): + model = MXNetWrapper(mx_model) + model.predict(X) + model.to_cpu() + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +@pytest.mark.skipif(not has_cupy_gpu, reason="needs GPU/cupy") +def test_mxnet_wrapper_to_gpu(model: Model[Array2d, Array2d], X: Array2d): + model.predict(X) + model.to_gpu(0) + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +@pytest.mark.parametrize( + "data,n_args,kwargs_keys", + [ + # fmt: off + (numpy.zeros((2, 3), dtype="f"), 1, []), + ([numpy.zeros((2, 3), dtype="f"), numpy.zeros((2, 3), dtype="f")], 2, []), + ((numpy.zeros((2, 3), dtype="f"), numpy.zeros((2, 3), dtype="f")), 2, []), + ({"a": numpy.zeros((2, 3), dtype="f"), "b": numpy.zeros((2, 3), dtype="f")}, 0, ["a", "b"]), + (ArgsKwargs((numpy.zeros((2, 3), dtype="f"), numpy.zeros((2, 3), dtype="f")), {"c": numpy.zeros((2, 3), dtype="f")}), 2, ["c"]), + # fmt: on + ], +) +def test_mxnet_wrapper_convert_inputs(data, n_args, kwargs_keys): + import mxnet as mx + + mx_model = mx.gluon.nn.Sequential() + mx_model.add(mx.gluon.nn.Dense(12)) + mx_model.initialize() + model = MXNetWrapper(mx_model) + convert_inputs = model.attrs["convert_inputs"] + Y, backprop = convert_inputs(model, data, is_train=True) + check_input_converters(Y, backprop, data, n_args, kwargs_keys, mx.nd.NDArray) + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +def test_mxnet_wrapper_thinc_model_subclass(mx_model): + class CustomModel(Model): + def fn(self) -> int: + return 1337 + + model = MXNetWrapper(mx_model, model_class=CustomModel) + assert isinstance(model, CustomModel) + assert model.fn() == 1337 + + +@pytest.mark.skipif(not has_mxnet, reason="needs MXNet") +def test_mxnet_wrapper_thinc_set_model_name(mx_model): + model = MXNetWrapper(mx_model, model_name="cool") + assert model.name == "cool" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_parametric_attention_v2.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_parametric_attention_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..fd88880f4e0e9b1d6a35f3ac9022ffadb2ed0cb0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_parametric_attention_v2.py @@ -0,0 +1,10 @@ +from thinc.layers.gelu import Gelu +from thinc.layers.parametricattention_v2 import ( + KEY_TRANSFORM_REF, + ParametricAttention_v2, +) + + +def test_key_transform_used(): + attn = ParametricAttention_v2(key_transform=Gelu()) + assert attn.get_ref(KEY_TRANSFORM_REF).name == "gelu" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_pytorch_wrapper.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_pytorch_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..aa40d9044146f5ecedaf516603533f9d0c645719 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_pytorch_wrapper.py @@ -0,0 +1,215 @@ +import numpy +import pytest + +from thinc.api import ( + SGD, + ArgsKwargs, + CupyOps, + Linear, + MPSOps, + NumpyOps, + PyTorchWrapper, + PyTorchWrapper_v2, + PyTorchWrapper_v3, + Relu, + chain, + get_current_ops, + torch2xp, + use_ops, + xp2torch, +) +from thinc.backends import context_pools +from thinc.compat import has_cupy_gpu, has_torch, has_torch_amp, has_torch_mps_gpu +from thinc.layers.pytorchwrapper import PyTorchWrapper_v3 +from thinc.shims.pytorch import ( + default_deserialize_torch_model, + default_serialize_torch_model, +) +from thinc.shims.pytorch_grad_scaler import PyTorchGradScaler +from thinc.util import get_torch_default_device + +from ..util import check_input_converters, make_tempdir + +XP_OPS = [NumpyOps()] +if has_cupy_gpu: + XP_OPS.append(CupyOps()) +if has_torch_mps_gpu: + XP_OPS.append(MPSOps()) + + +if has_torch_amp: + TORCH_MIXED_PRECISION = [False, True] +else: + TORCH_MIXED_PRECISION = [False] + +XP_OPS_MIXED = [ + (ops, mixed) + for ops in XP_OPS + for mixed in TORCH_MIXED_PRECISION + if not mixed or isinstance(ops, CupyOps) +] + + +def check_learns_zero_output(model, sgd, X, Y): + """Check we can learn to output a zero vector""" + Yh, get_dX = model.begin_update(X) + dYh = (Yh - Y) / Yh.shape[0] + dX = get_dX(dYh) + model.finish_update(sgd) + prev = numpy.abs(Yh.sum()) + for i in range(100): + Yh, get_dX = model.begin_update(X) + total = numpy.abs(Yh.sum()) + dX = get_dX(Yh - Y) # noqa: F841 + model.finish_update(sgd) + assert total < prev + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +@pytest.mark.parametrize("nN,nI,nO", [(2, 3, 4)]) +def test_pytorch_unwrapped(nN, nI, nO): + model = Linear(nO, nI).initialize() + X = numpy.zeros((nN, nI), dtype="f") + X += numpy.random.uniform(size=X.size).reshape(X.shape) + sgd = SGD(0.01) + Y = numpy.zeros((nN, nO), dtype="f") + check_learns_zero_output(model, sgd, X, Y) + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +@pytest.mark.parametrize("nN,nI,nO", [(2, 3, 4)]) +def test_pytorch_wrapper(nN, nI, nO): + import torch.nn + + model = PyTorchWrapper(torch.nn.Linear(nI, nO)).initialize() + sgd = SGD(0.001) + X = numpy.zeros((nN, nI), dtype="f") + X += numpy.random.uniform(size=X.size).reshape(X.shape) + Y = numpy.zeros((nN, nO), dtype="f") + Yh, get_dX = model.begin_update(X) + assert isinstance(Yh, numpy.ndarray) + assert Yh.shape == (nN, nO) + dYh = (Yh - Y) / Yh.shape[0] + dX = get_dX(dYh) + model.finish_update(sgd) + assert dX.shape == (nN, nI) + check_learns_zero_output(model, sgd, X, Y) + assert isinstance(model.predict(X), numpy.ndarray) + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +@pytest.mark.parametrize("ops_mixed", XP_OPS_MIXED) +@pytest.mark.parametrize("nN,nI,nO", [(2, 3, 4)]) +def test_pytorch_wrapper_thinc_input(ops_mixed, nN, nI, nO): + import torch.nn + + ops, mixed_precision = ops_mixed + + with use_ops(ops.name): + ops = get_current_ops() + pytorch_layer = torch.nn.Linear(nO, nO) + # Initialize with large weights to trigger overflow of FP16 in + # mixed-precision training. + torch.nn.init.uniform_(pytorch_layer.weight, 9.0, 11.0) + device = get_torch_default_device() + model = chain( + Relu(), + PyTorchWrapper_v2( + pytorch_layer.to(device), + mixed_precision=mixed_precision, + grad_scaler=PyTorchGradScaler( + enabled=mixed_precision, init_scale=2.0**16 + ), + ).initialize(), + ) + # pytorch allocator is set in PyTorchShim + if isinstance(ops, CupyOps): + assert "pytorch" in context_pools.get() + sgd = SGD(0.001) + X = ops.xp.zeros((nN, nI), dtype="f") + X += ops.xp.random.uniform(size=X.size).reshape(X.shape) + Y = ops.xp.zeros((nN, nO), dtype="f") + model.initialize(X, Y) + Yh, get_dX = model.begin_update(X) + assert isinstance(Yh, ops.xp.ndarray) + assert Yh.shape == (nN, nO) + dYh = (Yh - Y) / Yh.shape[0] + dX = get_dX(dYh) + model.finish_update(sgd) + assert dX.shape == (nN, nI) + check_learns_zero_output(model, sgd, X, Y) + assert isinstance(model.predict(X), ops.xp.ndarray) + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +def test_pytorch_roundtrip_conversion(): + import torch + + xp_tensor = numpy.zeros((2, 3), dtype="f") + torch_tensor = xp2torch(xp_tensor) + assert isinstance(torch_tensor, torch.Tensor) + new_xp_tensor = torch2xp(torch_tensor) + assert numpy.array_equal(xp_tensor, new_xp_tensor) + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +def test_pytorch_wrapper_roundtrip(): + import torch.nn + + model = PyTorchWrapper(torch.nn.Linear(2, 3)) + model_bytes = model.to_bytes() + PyTorchWrapper(torch.nn.Linear(2, 3)).from_bytes(model_bytes) + with make_tempdir() as path: + model_path = path / "model" + model.to_disk(model_path) + new_model = PyTorchWrapper(torch.nn.Linear(2, 3)).from_bytes(model_bytes) + new_model.from_disk(model_path) + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +@pytest.mark.parametrize( + "data,n_args,kwargs_keys", + [ + # fmt: off + (numpy.zeros((2, 3), dtype="f"), 1, []), + ([numpy.zeros((2, 3), dtype="f"), numpy.zeros((2, 3), dtype="f")], 2, []), + ((numpy.zeros((2, 3), dtype="f"), numpy.zeros((2, 3), dtype="f")), 2, []), + ({"a": numpy.zeros((2, 3), dtype="f"), "b": numpy.zeros((2, 3), dtype="f")}, 0, ["a", "b"]), + (ArgsKwargs((numpy.zeros((2, 3), dtype="f"), numpy.zeros((2, 3), dtype="f")), {"c": numpy.zeros((2, 3), dtype="f")}), 2, ["c"]), + # fmt: on + ], +) +def test_pytorch_convert_inputs(data, n_args, kwargs_keys): + import torch.nn + + model = PyTorchWrapper(torch.nn.Linear(3, 4)) + convert_inputs = model.attrs["convert_inputs"] + Y, backprop = convert_inputs(model, data, is_train=True) + check_input_converters(Y, backprop, data, n_args, kwargs_keys, torch.Tensor) + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +def test_pytorch_wrapper_custom_serde(): + import torch.nn + + def serialize(model): + return default_serialize_torch_model(model) + + def deserialize(model, state_bytes, device): + return default_deserialize_torch_model(model, state_bytes, device) + + def get_model(): + return PyTorchWrapper_v3( + torch.nn.Linear(2, 3), + serialize_model=serialize, + deserialize_model=deserialize, + ) + + model = get_model() + model_bytes = model.to_bytes() + get_model().from_bytes(model_bytes) + with make_tempdir() as path: + model_path = path / "model" + model.to_disk(model_path) + new_model = get_model().from_bytes(model_bytes) + new_model.from_disk(model_path) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_reduce.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_reduce.py new file mode 100644 index 0000000000000000000000000000000000000000..608561e13f03b43e33630c3c15c3e208cc2eb075 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_reduce.py @@ -0,0 +1,122 @@ +import numpy +import pytest + +from thinc.api import reduce_first, reduce_last, reduce_max, reduce_mean, reduce_sum +from thinc.types import Ragged + + +@pytest.fixture +def Xs(): + seqs = [numpy.zeros((10, 8), dtype="f"), numpy.zeros((4, 8), dtype="f")] + for x in seqs: + x[0] = 1 + x[1] = 2 # so max != first + x[-1] = -1 + return seqs + + +def test_init_reduce_first(): + model = reduce_first() + + +def test_init_reduce_last(): + model = reduce_last() + + +def test_init_reduce_mean(): + model = reduce_mean() + + +def test_init_reduce_max(): + model = reduce_max() + + +def test_init_reduce_sum(): + model = reduce_sum() + + +def test_reduce_first(Xs): + model = reduce_first() + lengths = model.ops.asarray([x.shape[0] for x in Xs], dtype="i") + X = Ragged(model.ops.flatten(Xs), lengths) + Y, backprop = model(X, is_train=True) + assert isinstance(Y, numpy.ndarray) + assert Y.shape == (len(Xs), Xs[0].shape[1]) + assert Y.dtype == Xs[0].dtype + assert list(Y[0]) == list(Xs[0][0]) + assert list(Y[1]) == list(Xs[1][0]) + dX = backprop(Y) + assert dX.dataXd.shape == X.dataXd.shape + + +def test_reduce_last(Xs): + model = reduce_last() + lengths = model.ops.asarray([x.shape[0] for x in Xs], dtype="i") + X = Ragged(model.ops.flatten(Xs), lengths) + Y, backprop = model(X, is_train=True) + assert isinstance(Y, numpy.ndarray) + assert Y.shape == (len(Xs), Xs[0].shape[1]) + assert Y.dtype == Xs[0].dtype + assert list(Y[0]) == list(Xs[0][-1]) + assert list(Y[1]) == list(Xs[1][-1]) + dX = backprop(Y) + assert dX.dataXd.shape == X.dataXd.shape + + +def test_reduce_max(Xs): + model = reduce_max() + lengths = model.ops.asarray([x.shape[0] for x in Xs], dtype="i") + X = Ragged(model.ops.flatten(Xs), lengths) + Y, backprop = model(X, is_train=True) + assert isinstance(Y, numpy.ndarray) + assert Y.shape == (len(Xs), Xs[0].shape[1]) + assert Y.dtype == Xs[0].dtype + assert list(Y[0]) == list(Xs[0][1]) + assert list(Y[1]) == list(Xs[1][1]) + dX = backprop(Y) + assert dX.dataXd.shape == X.dataXd.shape + + +def test_reduce_mean(Xs): + Xs = [x * 1000 for x in Xs] # use large numbers for numeric stability + model = reduce_mean() + lengths = model.ops.asarray([x.shape[0] for x in Xs], dtype="i") + X = Ragged(model.ops.flatten(Xs), lengths) + Y, backprop = model(X, is_train=True) + assert isinstance(Y, numpy.ndarray) + assert Y.shape == (len(Xs), Xs[0].shape[1]) + assert Y.dtype == Xs[0].dtype + assert numpy.all(Y[0] == Y[0][0]) # all values in row should be equal + assert Y[0][0] == Xs[0].mean() + assert numpy.all(Y[1] == Y[1][0]) + assert Y[1][0] == Xs[1].mean() + dX = backprop(Y) + assert dX.dataXd.shape == X.dataXd.shape + + +def test_reduce_sum(Xs): + model = reduce_sum() + lengths = model.ops.asarray([x.shape[0] for x in Xs], dtype="i") + X = Ragged(model.ops.flatten(Xs), lengths) + Y, backprop = model(X, is_train=True) + assert isinstance(Y, numpy.ndarray) + assert Y.shape == (len(Xs), Xs[0].shape[1]) + assert Y.dtype == Xs[0].dtype + assert Y[0][0] == Xs[0][:, 0].sum() + assert numpy.all(Y[0] == Y[0][0]) + assert Y[1][-1] == Xs[1][:, 0].sum() + assert numpy.all(Y[1] == Y[1][0]) + dX = backprop(Y) + assert dX.dataXd.shape == X.dataXd.shape + + +def test_size_mismatch(Xs): + for reduce in [reduce_first, reduce_last, reduce_max, reduce_mean, reduce_sum]: + model = reduce() + lengths = model.ops.asarray([x.shape[0] for x in Xs], dtype="i") + X = Ragged(model.ops.flatten(Xs), lengths) + Y, backprop = model(X, is_train=True) + + Y_bad = Y[:-1] + with pytest.raises(ValueError): + backprop(Y_bad) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_resizable.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_resizable.py new file mode 100644 index 0000000000000000000000000000000000000000..ffa256de55b84c569f9f2e90d62e8cdc144ac77e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_resizable.py @@ -0,0 +1,34 @@ +from functools import partial + +import pytest + +from thinc.api import Linear, resizable +from thinc.layers.resizable import resize_linear_weighted, resize_model + + +@pytest.fixture +def model(): + output_layer = Linear(nO=None, nI=None) + fill_defaults = {"b": 0, "W": 0} + model = resizable( + output_layer, + resize_layer=partial(resize_linear_weighted, fill_defaults=fill_defaults), + ) + return model + + +def test_resizable_linear_default_name(model): + assert model.name == "resizable(linear)" + + +def test_resize_model(model): + """Test that resizing the model doesn't cause an exception.""" + resize_model(model, new_nO=10) + resize_model(model, new_nO=11) + + model.set_dim("nO", 0, force=True) + resize_model(model, new_nO=10) + + model.set_dim("nI", 10, force=True) + model.set_dim("nO", 0, force=True) + resize_model(model, new_nO=10) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_shim.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_shim.py new file mode 100644 index 0000000000000000000000000000000000000000..dcb43ab1e6a0997fc339b5c0673a50541dbe733d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_shim.py @@ -0,0 +1,35 @@ +from typing import List + +from thinc.shims.shim import Shim + +from ..util import make_tempdir + + +class MockShim(Shim): + def __init__(self, data: List[int]): + super().__init__(None, config=None, optimizer=None) + self.data = data + + def to_bytes(self): + return bytes(self.data) + + def from_bytes(self, data: bytes) -> "MockShim": + return MockShim(data=list(data)) + + +def test_shim_can_roundtrip_with_path(): + + with make_tempdir() as path: + shim_path = path / "cool_shim.data" + shim = MockShim([1, 2, 3]) + shim.to_disk(shim_path) + copy_shim = shim.from_disk(shim_path) + assert copy_shim.to_bytes() == shim.to_bytes() + + +def test_shim_can_roundtrip_with_path_subclass(pathy_fixture): + shim_path = pathy_fixture / "cool_shim.data" + shim = MockShim([1, 2, 3]) + shim.to_disk(shim_path) + copy_shim = shim.from_disk(shim_path) + assert copy_shim.to_bytes() == shim.to_bytes() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_softmax.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_softmax.py new file mode 100644 index 0000000000000000000000000000000000000000..95e2f41c78bd4946c44b4f277ebc69151bc8eea1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_softmax.py @@ -0,0 +1,92 @@ +from typing import Tuple, cast + +import numpy +import pytest +from numpy.testing import assert_allclose + +from thinc.api import Model, NumpyOps, Softmax_v2 +from thinc.types import Floats2d, Ints1d +from thinc.util import has_torch, torch2xp, xp2torch + +OPS = NumpyOps() + +inputs = OPS.xp.asarray([[4, 2, 3, 4], [1, 5, 3, 1], [9, 8, 5, 7]], dtype="f") +outputs = OPS.xp.asarray( + [ + [0.39948627, 0.05406459, 0.14696279, 0.39948627], + [0.01562812, 0.8532666, 0.11547707, 0.01562812], + [0.657233, 0.24178252, 0.01203764, 0.08894681], + ], + dtype="f", +) + + +def test_unnormalized_softmax_backprop(): + model = Softmax_v2(normalize_outputs=False) + model.initialize(inputs, outputs) + _, backprop = model(inputs, is_train=False) + with pytest.raises(ValueError, match="backprop is not supported"): + backprop(OPS.xp.zeros_like(outputs)) + + # Backprop should not fail when training. + _, backprop = model(inputs, is_train=True) + dX = backprop(OPS.xp.zeros_like(outputs)) + assert OPS.xp.all(dX == 0.0) + + +def torch_softmax_with_temperature( + model: Model, X: Floats2d, targets: Ints1d +) -> Tuple[Floats2d, Floats2d]: + import torch + + Wt = xp2torch(model.get_param("W")) + bt = xp2torch(model.get_param("b")) + temperature = model.attrs["softmax_temperature"] + + Xt = xp2torch(X, requires_grad=True) + Yt_gold = xp2torch(targets).long() + + XWbt = (Xt @ Wt) + bt + XWbt_temp = XWbt / temperature + + loss = torch.nn.CrossEntropyLoss() + output = loss(XWbt_temp, Yt_gold) + output.backward() + + return cast( + Floats2d, torch2xp(torch.nn.functional.softmax(XWbt_temp, dim=-1)) + ), cast(Floats2d, torch2xp(cast(torch.Tensor, Xt.grad))) + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +@pytest.mark.parametrize("temperature", [0.5, 1.0, 2.0]) +def test_softmax_temperature(temperature): + model = Softmax_v2( + temperature=temperature, + init_W=lambda ops, shape: ops.xp.eye(shape[1], dtype="f"), + init_b=lambda ops, shape: ops.xp.zeros(shape, dtype="f"), + ) + + X = OPS.xp.arange(-1, 1, 0.2, dtype="f").reshape(1, 10) + targets = OPS.asarray1i([4]) + Y_gold = OPS.xp.eye(10, dtype="f")[targets] + model.initialize(X, Y_gold) + + Yt, dXt = torch_softmax_with_temperature(model, X, targets) + + Y, backprop = model(X, is_train=True) + dX = backprop(Y - Y_gold) + + assert_allclose(Y, Yt, atol=1e-4) + assert_allclose(dX, dXt, atol=1e-4) + + +def test_reject_incorrect_temperature(): + with pytest.raises(ValueError, match=r"softmax temperature.*zero"): + Softmax_v2(normalize_outputs=False, temperature=0.0) + + model = Softmax_v2(normalize_outputs=False) + model.attrs["softmax_temperature"] = 0.0 + model.initialize(inputs, outputs) + with pytest.raises(ValueError, match=r"softmax temperature.*zero"): + model(inputs, is_train=False) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_sparse_linear.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_sparse_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..cce0d1023f2230332f37b93a91a954b705886ea2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_sparse_linear.py @@ -0,0 +1,79 @@ +import math + +import numpy +import pytest + +from thinc.api import SGD, SparseLinear, SparseLinear_v2, to_categorical + + +@pytest.fixture +def instances(): + lengths = numpy.asarray([5, 4], dtype="int32") + keys = numpy.arange(9, dtype="uint64") + values = numpy.ones(9, dtype="float32") + X = (keys, values, lengths) + y = numpy.asarray([0, 2], dtype="int32") + return X, to_categorical(y, n_classes=3) + + +@pytest.fixture +def sgd(): + return SGD(0.001) + + +def test_basic(instances, sgd): + X, y = instances + nr_class = 3 + model = SparseLinear(nr_class).initialize() + yh, backprop = model.begin_update(X) + loss1 = ((yh - y) ** 2).sum() + backprop(yh - y) + model.finish_update(sgd) + yh, backprop = model.begin_update(X) + loss2 = ((yh - y) ** 2).sum() + assert loss2 < loss1 + + +def test_init(): + model = SparseLinear(3).initialize() + keys = numpy.ones((5,), dtype="uint64") + values = numpy.ones((5,), dtype="f") + lengths = numpy.zeros((2,), dtype="int32") + lengths[0] = 3 + lengths[1] = 2 + scores, backprop = model.begin_update((keys, values, lengths)) + assert scores.shape == (2, 3) + d_feats = backprop(scores) + assert len(d_feats) == 3 + + +def test_distribution(): + n_class = 10 + length = 2**18 + model = SparseLinear_v2(nO=n_class, length=length).initialize() + + ii64 = numpy.iinfo(numpy.uint64) + lengths = numpy.zeros((2,), dtype="int32") + + for p_nonzero in range(1, 12): + # Clear gradients from the previous iterarion. + model.set_grad("W", 0.0) + + n = 2**p_nonzero + keys = numpy.random.randint(ii64.min, ii64.max, size=(n,), dtype=numpy.uint64) + values = numpy.ones((n,), dtype="f") + lengths[0] = n // 2 + lengths[1] = n // 2 + + # Probability that a bit is set (2 because we use 2 hashes). + p_nonzero = 1 - math.exp(-2 * n / length) + + Y, backprop = model.begin_update((keys, values, lengths)) + backprop(numpy.ones_like(Y)) + + # Check that for each class we have the expected rate of non-zeros. + dW = model.get_grad("W").reshape(n_class, -1) + nonzero_empirical = numpy.count_nonzero(dW, axis=1) / dW.shape[1] + numpy.testing.assert_allclose( + nonzero_empirical, p_nonzero, rtol=1e-4, atol=1e-4 + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_tensorflow_wrapper.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_tensorflow_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..4741f6dc3a4227a86e293a6a5ebe345283f31c45 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_tensorflow_wrapper.py @@ -0,0 +1,414 @@ +import numpy +import pytest + +from thinc.api import ( + Adam, + ArgsKwargs, + Linear, + Model, + TensorFlowWrapper, + get_current_ops, + keras_subclass, + tensorflow2xp, + xp2tensorflow, +) +from thinc.compat import has_cupy_gpu, has_tensorflow +from thinc.util import to_categorical + +from ..util import check_input_converters, make_tempdir + + +@pytest.fixture +def n_hidden(): + return 12 + + +@pytest.fixture +def input_size(): + return 784 + + +@pytest.fixture +def n_classes(): + return 10 + + +@pytest.fixture +def answer(): + return 1 + + +@pytest.fixture +def X(input_size): + ops = get_current_ops() + return ops.alloc(shape=(1, input_size)) + + +@pytest.fixture +def Y(answer, n_classes): + ops = get_current_ops() + return to_categorical(ops.asarray1i([answer]), n_classes=n_classes) + + +@pytest.fixture +def tf_model(n_hidden, input_size): + import tensorflow as tf + + tf_model = tf.keras.Sequential( + [ + tf.keras.layers.Dense(n_hidden, input_shape=(input_size,)), + tf.keras.layers.LayerNormalization(), + tf.keras.layers.Dense(n_hidden, activation="relu"), + tf.keras.layers.LayerNormalization(), + tf.keras.layers.Dense(10, activation="softmax"), + ] + ) + return tf_model + + +@pytest.fixture +def model(tf_model): + return TensorFlowWrapper(tf_model) + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_roundtrip_conversion(): + import tensorflow as tf + + ops = get_current_ops() + xp_tensor = ops.alloc2f(2, 3, zeros=True) + tf_tensor = xp2tensorflow(xp_tensor) + assert isinstance(tf_tensor, tf.Tensor) + new_xp_tensor = tensorflow2xp(tf_tensor, ops=ops) + assert ops.xp.array_equal(xp_tensor, new_xp_tensor) + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_construction_requires_keras_model(): + import tensorflow as tf + + keras_model = tf.keras.Sequential([tf.keras.layers.Dense(12, input_shape=(12,))]) + assert isinstance(TensorFlowWrapper(keras_model), Model) + with pytest.raises(ValueError): + TensorFlowWrapper(Linear(2, 3)) + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_built_model(model, X, Y): + # built models are validated more and can perform useful operations: + assert model.predict(X) is not None + # Can print a keras summary + assert str(model.shims[0]) != "" + # They can de/serialized + assert model.from_bytes(model.to_bytes()) is not None + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_predict(model, X): + model.predict(X) + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_train_overfits(model, X, Y, answer): + optimizer = Adam() + ops = get_current_ops() + for i in range(100): + guesses, backprop = model(X, is_train=True) + # Ensure that the tensor is type-compatible with the current backend. + guesses = ops.asarray(guesses) + + d_guesses = (guesses - Y) / guesses.shape[0] + backprop(d_guesses) + model.finish_update(optimizer) + predicted = model.predict(X).argmax() + assert predicted == answer + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_accumulate_gradients(model, X, Y, answer): + import tensorflow as tf + + optimizer = Adam() + gradients = [] + ops = get_current_ops() + for i in range(3): + guesses, backprop = model(X, is_train=True) + # Ensure that the tensor is type-compatible with the current backend. + guesses = ops.asarray(guesses) + + d_guesses = (guesses - Y) / guesses.shape[0] + backprop(d_guesses) + shim_grads = [tf.identity(var) for var in model.shims[0].gradients] + gradients.append(shim_grads) + + # Apply the gradients + model.finish_update(optimizer) + assert model.shims[0].gradients is None + + # Compare prev/next pairs and ensure their gradients have changed + for i in range(len(gradients)): + # Skip the first one + if i == 0: + continue + found_diff = False + curr_grads = gradients[i] + prev_grads = gradients[i - 1] + for curr, prev in zip(curr_grads, prev_grads): + if (prev != curr).numpy().any(): + found_diff = True + assert found_diff is True + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_serialize_model_subclass( + X, Y, input_size, n_classes, answer +): + import tensorflow as tf + + input_shape = (1, input_size) + ops = get_current_ops() + + @keras_subclass( + "foo.v1", + X=ops.alloc2f(*input_shape), + Y=to_categorical(ops.asarray1i([1]), n_classes=n_classes), + input_shape=input_shape, + ) + class CustomKerasModel(tf.keras.Model): + def __init__(self, **kwargs): + super(CustomKerasModel, self).__init__(**kwargs) + self.in_dense = tf.keras.layers.Dense( + 12, name="in_dense", input_shape=input_shape + ) + self.out_dense = tf.keras.layers.Dense( + n_classes, name="out_dense", activation="softmax" + ) + + def call(self, inputs) -> tf.Tensor: + x = self.in_dense(inputs) + return self.out_dense(x) + + model = TensorFlowWrapper(CustomKerasModel()) + # Train the model to predict the right single answer + optimizer = Adam() + for i in range(50): + guesses, backprop = model(X, is_train=True) + # Ensure that the tensor is type-compatible with the current backend. + guesses = ops.asarray(guesses) + + d_guesses = (guesses - Y) / guesses.shape[0] + backprop(d_guesses) + model.finish_update(optimizer) + predicted = model.predict(X).argmax() + assert predicted == answer + + # Save then Load the model from bytes + model.from_bytes(model.to_bytes()) + + # The from_bytes model gets the same answer + assert model.predict(X).argmax() == answer + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_keras_subclass_decorator_compile_args(): + import tensorflow as tf + + class UndecoratedModel(tf.keras.Model): + def call(self, inputs): + return inputs + + # Can't wrap an undecorated keras subclass model + with pytest.raises(ValueError): + TensorFlowWrapper(UndecoratedModel()) + + @keras_subclass( + "TestModel", + X=numpy.array([0.0, 0.0]), + Y=numpy.array([0.5]), + input_shape=(2,), + compile_args={"loss": "binary_crossentropy"}, + ) + class TestModel(tf.keras.Model): + def call(self, inputs): + return inputs + + model = TensorFlowWrapper(TestModel()) + model = model.from_bytes(model.to_bytes()) + + assert model.shims[0]._model.loss == "binary_crossentropy" + assert isinstance(model, Model) + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_keras_subclass_decorator(): + import tensorflow as tf + + class UndecoratedModel(tf.keras.Model): + def call(self, inputs): + return inputs + + # Can't wrap an undecorated keras subclass model + with pytest.raises(ValueError): + TensorFlowWrapper(UndecoratedModel()) + + @keras_subclass( + "TestModel", X=numpy.array([0.0, 0.0]), Y=numpy.array([0.5]), input_shape=(2,) + ) + class TestModel(tf.keras.Model): + def call(self, inputs): + return inputs + + # Can wrap an decorated keras subclass model + assert isinstance(TensorFlowWrapper(TestModel()), Model) + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_keras_subclass_decorator_capture_args_kwargs( + X, Y, input_size, n_classes, answer +): + import tensorflow as tf + + @keras_subclass( + "TestModel", X=numpy.array([0.0, 0.0]), Y=numpy.array([0.5]), input_shape=(2,) + ) + class TestModel(tf.keras.Model): + def __init__(self, custom=False, **kwargs): + super().__init__(self) + # This is to force the mode to pass the captured arguments + # or fail. + assert custom is True + assert kwargs.get("other", None) is not None + + def call(self, inputs): + return inputs + + # Can wrap an decorated keras subclass model + model = TensorFlowWrapper(TestModel(True, other=1337)) + + assert hasattr(model.shims[0]._model, "eg_args") + args_kwargs = model.shims[0]._model.eg_args + assert True in args_kwargs.args + assert "other" in args_kwargs.kwargs + + # Raises an error if the args/kwargs is not serializable + obj = {} + obj["key"] = obj + with pytest.raises(ValueError): + TensorFlowWrapper(TestModel(True, other=obj)) + + # Provides the same arguments when copying a capture model + model = model.from_bytes(model.to_bytes()) + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_can_copy_model(model): + copy = model.copy() + assert copy is not None + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_print_summary(model, X): + summary = str(model.shims[0]) + # Summary includes the layers of our model + assert "layer_normalization" in summary + assert "dense" in summary + # And counts of params + assert "Total params" in summary + assert "Trainable params" in summary + assert "Non-trainable params" in summary + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_to_bytes(model, X): + # And can be serialized + model_bytes = model.to_bytes() + assert model_bytes is not None + model.from_bytes(model_bytes) + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_to_from_disk(model, X, Y, answer): + with make_tempdir() as tmp_path: + model_file = tmp_path / "model.h5" + model.to_disk(model_file) + another_model = model.from_disk(model_file) + assert another_model is not None + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_from_bytes(model, X): + model.predict(X) + model_bytes = model.to_bytes() + another_model = model.from_bytes(model_bytes) + assert another_model is not None + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_use_params(model, X, Y, answer): + optimizer = Adam() + ops = get_current_ops() + with model.use_params(optimizer.averages): + assert model.predict(X).argmax() is not None + for i in range(10): + guesses, backprop = model.begin_update(X) + # Ensure that the tensor is type-compatible with the current backend. + guesses = ops.asarray(guesses) + + d_guesses = (guesses - Y) / guesses.shape[0] + backprop(d_guesses) + model.finish_update(optimizer) + with model.use_params(optimizer.averages): + predicted = model.predict(X).argmax() + assert predicted == answer + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_to_cpu(tf_model): + model = TensorFlowWrapper(tf_model) + model.to_cpu() + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +@pytest.mark.skipif(not has_cupy_gpu, reason="needs GPU/cupy") +def test_tensorflow_wrapper_to_gpu(model, X): + model.to_gpu(0) + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +@pytest.mark.parametrize( + "data,n_args,kwargs_keys", + [ + # fmt: off + (numpy.zeros((2, 3), dtype="f"), 1, []), + ([numpy.zeros((2, 3), dtype="f"), numpy.zeros((2, 3), dtype="f")], 2, []), + ((numpy.zeros((2, 3), dtype="f"), numpy.zeros((2, 3), dtype="f")), 2, []), + ({"a": numpy.zeros((2, 3), dtype="f"), "b": numpy.zeros((2, 3), dtype="f")}, 0, ["a", "b"]), + (ArgsKwargs((numpy.zeros((2, 3), dtype="f"), numpy.zeros((2, 3), dtype="f")), {"c": numpy.zeros((2, 3), dtype="f")}), 2, ["c"]), + # fmt: on + ], +) +def test_tensorflow_wrapper_convert_inputs(data, n_args, kwargs_keys): + import tensorflow as tf + + keras_model = tf.keras.Sequential([tf.keras.layers.Dense(12, input_shape=(12,))]) + model = TensorFlowWrapper(keras_model) + convert_inputs = model.attrs["convert_inputs"] + Y, backprop = convert_inputs(model, data, is_train=True) + check_input_converters(Y, backprop, data, n_args, kwargs_keys, tf.Tensor) + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_thinc_model_subclass(tf_model): + class CustomModel(Model): + def fn(self): + return 1337 + + model = TensorFlowWrapper(tf_model, model_class=CustomModel) + assert isinstance(model, CustomModel) + assert model.fn() == 1337 + + +@pytest.mark.skipif(not has_tensorflow, reason="needs TensorFlow") +def test_tensorflow_wrapper_thinc_set_model_name(tf_model): + model = TensorFlowWrapper(tf_model, model_name="cool") + assert model.name == "cool" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_torchscriptwrapper.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_torchscriptwrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..b37afa3c3200834e5b640b99f0e1867811cd1378 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_torchscriptwrapper.py @@ -0,0 +1,28 @@ +import numpy +import pytest + +from thinc.api import ( + PyTorchWrapper_v2, + TorchScriptWrapper_v1, + pytorch_to_torchscript_wrapper, +) +from thinc.compat import has_torch, torch + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +@pytest.mark.parametrize("nN,nI,nO", [(2, 3, 4)]) +def test_pytorch_script(nN, nI, nO): + + model = PyTorchWrapper_v2(torch.nn.Linear(nI, nO)).initialize() + script_model = pytorch_to_torchscript_wrapper(model) + + X = numpy.random.randn(nN, nI).astype("f") + Y = model.predict(X) + Y_script = script_model.predict(X) + numpy.testing.assert_allclose(Y, Y_script) + + serialized = script_model.to_bytes() + script_model2 = TorchScriptWrapper_v1() + script_model2.from_bytes(serialized) + + numpy.testing.assert_allclose(Y, script_model2.predict(X)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_transforms.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..3a9a110f17c5992a16ebc5824de6e5aace3b86eb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_transforms.py @@ -0,0 +1,79 @@ +import numpy +import pytest + +from thinc.api import NumpyOps, Ragged, registry, strings2arrays + +from ..util import get_data_checker + + +@pytest.fixture(params=[[], [(10, 2)], [(5, 3), (1, 3)], [(2, 3), (0, 3), (1, 3)]]) +def shapes(request): + return request.param + + +@pytest.fixture +def ops(): + return NumpyOps() + + +@pytest.fixture +def list_data(shapes): + return [numpy.zeros(shape, dtype="f") for shape in shapes] + + +@pytest.fixture +def ragged_data(ops, list_data): + lengths = numpy.array([len(x) for x in list_data], dtype="i") + if not list_data: + return Ragged(ops.alloc2f(0, 0), lengths) + else: + return Ragged(ops.flatten(list_data), lengths) + + +@pytest.fixture +def padded_data(ops, list_data): + return ops.list2padded(list_data) + + +@pytest.fixture +def array_data(ragged_data): + return ragged_data.data + + +def check_transform(transform, in_data, out_data): + model = registry.resolve({"config": {"@layers": transform}})["config"] + input_checker = get_data_checker(in_data) + output_checker = get_data_checker(out_data) + model.initialize(in_data, out_data) + Y, backprop = model(in_data, is_train=True) + output_checker(Y, out_data) + dX = backprop(Y) + input_checker(dX, in_data) + + +def test_list2array(list_data, array_data): + check_transform("list2array.v1", list_data, array_data) + + +def test_list2ragged(list_data, ragged_data): + check_transform("list2ragged.v1", list_data, ragged_data) + + +def test_list2padded(list_data, padded_data): + check_transform("list2padded.v1", list_data, padded_data) + + +def test_ragged2list(ragged_data, list_data): + check_transform("ragged2list.v1", ragged_data, list_data) + + +def test_padded2list(padded_data, list_data): + check_transform("padded2list.v1", padded_data, list_data) + + +def test_strings2arrays(): + strings = ["hello", "world"] + model = strings2arrays() + Y, backprop = model.begin_update(strings) + assert len(Y) == len(strings) + assert backprop([]) == [] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_uniqued.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_uniqued.py new file mode 100644 index 0000000000000000000000000000000000000000..685da1debcf937ccab8d869aaff45f683bd80f34 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_uniqued.py @@ -0,0 +1,66 @@ +import numpy +import pytest +from hypothesis import given, settings +from hypothesis.strategies import composite, integers, lists +from numpy.testing import assert_allclose + +from thinc.layers import Embed +from thinc.layers.uniqued import uniqued + +ROWS = 10 + +# This test uses a newer hypothesis feature than the skanky flatmap-style +# I used previously. This is much nicer, although it still takes some getting +# used to. The key feature is this composite decorator. It injects a function, +# 'draw'. + + +@composite +def lists_of_integers(draw, columns=2, lo=0, hi=ROWS - 1): + # We call draw to get example values, which we can manipulate. + # Here we get a list of integers, where each member of the list + # should be between a min and max value. + int_list = draw(lists(integers(min_value=lo, max_value=hi))) + # Now we can use this int list to make an array, and it'll be the arrays + # that our functions receive. + # We trim the list, so we're of length divisible by columns. + int_list = int_list[len(int_list) % columns :] + # And make the array and reshape it. + array = numpy.array(int_list, dtype="uint64") + return array.reshape((-1, columns)) + + +@pytest.fixture(scope="module") +def model(nO=128): + return Embed(nO, ROWS, column=0).initialize() + + +def test_uniqued_calls_init(): + calls = [] + embed = Embed(5, 5, column=0) + embed.init = lambda *args, **kwargs: calls.append(True) + embed.initialize() + assert calls == [True] + uembed = uniqued(embed) + uembed.initialize() + assert calls == [True, True] + + +@given(X=lists_of_integers(lo=0, hi=ROWS - 1)) +@settings(deadline=None) +def test_uniqued_doesnt_change_result(model, X): + umodel = uniqued(model, column=model.attrs["column"]).initialize() + Y, bp_Y = model(X, is_train=True) + Yu, bp_Yu = umodel(X, is_train=True) + assert_allclose(Y, Yu) + dX = bp_Y(Y) + dXu = bp_Yu(Yu) + assert_allclose(dX, dXu) + if X.size: + pass + # TODO: This test is a problem, because we exceed the embedding table. + # Fix it with a better cap. + # Check that different inputs do give different results + # Z, bp_Z = model(X + 1, is_train=True) + # with pytest.raises(AssertionError): + # assert_allclose(Y, Z) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_with_debug.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_with_debug.py new file mode 100644 index 0000000000000000000000000000000000000000..3e31c71f0d9a62e7e887f2d6f131335bc894eacb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_with_debug.py @@ -0,0 +1,26 @@ +from unittest.mock import MagicMock + +from thinc.api import Linear, with_debug + + +def test_with_debug(): + on_init = MagicMock() + on_forward = MagicMock() + on_backprop = MagicMock() + model = with_debug( + Linear(), on_init=on_init, on_forward=on_forward, on_backprop=on_backprop + ) + on_init.assert_not_called() + on_forward.assert_not_called() + on_backprop.assert_not_called() + X = model.ops.alloc2f(1, 1) + Y = model.ops.alloc2f(1, 1) + model.initialize(X=X, Y=Y) + on_init.assert_called_once_with(model, X, Y) + on_forward.assert_not_called() + on_backprop.assert_not_called() + Yh, backprop = model(X, is_train=True) + on_forward.assert_called_once_with(model, X, True) + on_backprop.assert_not_called() + backprop(Y) + on_backprop.assert_called_once_with(Y) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_with_flatten.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_with_flatten.py new file mode 100644 index 0000000000000000000000000000000000000000..86d18eb674a512c424468e4da8b71c8e6a5f3573 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_with_flatten.py @@ -0,0 +1,31 @@ +from typing import List + +from thinc.api import Model, with_flatten_v2 + +INPUT = [[1, 2, 3], [4, 5], [], [6, 7, 8]] +INPUT_FLAT = [1, 2, 3, 4, 5, 6, 7, 8] +OUTPUT = [[2, 3, 4], [5, 6], [], [7, 8, 9]] +BACKPROP_OUTPUT = [[3, 4, 5], [6, 7], [], [8, 9, 10]] + + +def _memoize_input() -> Model[List[int], List[int]]: + return Model(name="memoize_input", forward=_memoize_input_forward) + + +def _memoize_input_forward( + model: Model[List[int], List[int]], X: List[int], is_train: bool +): + model.attrs["last_input"] = X + + def backprop(dY: List[int]): + return [v + 2 for v in dY] + + return [v + 1 for v in X], backprop + + +def test_with_flatten(): + model = with_flatten_v2(_memoize_input()) + Y, backprop = model(INPUT, is_train=True) + assert Y == OUTPUT + assert model.layers[0].attrs["last_input"] == INPUT_FLAT + assert backprop(INPUT) == BACKPROP_OUTPUT diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_with_transforms.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_with_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..82cdaed36b787066211f0e994e0a0aab71b9e11b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/layers/test_with_transforms.py @@ -0,0 +1,299 @@ +import numpy +import numpy.testing +import pytest + +from thinc.api import ( + Linear, + Model, + NumpyOps, + noop, + with_array, + with_array2d, + with_getitem, + with_list, + with_padded, + with_ragged, +) +from thinc.types import Padded, Ragged + +from ..util import get_data_checker + + +@pytest.fixture(params=[[], [(10, 2)], [(5, 3), (1, 3)], [(2, 3), (0, 3), (1, 3)]]) +def shapes(request): + return request.param + + +@pytest.fixture +def ops(): + return NumpyOps() + + +@pytest.fixture +def list_input(shapes): + data = [numpy.zeros(shape, dtype="f") for shape in shapes] + for i, x in enumerate(data): + # Give values that make it easy to see where rows or columns mismatch. + x += i * 100 + x += numpy.arange(x.shape[0]).reshape((-1, 1)) * 10 + x += numpy.arange(x.shape[1]).reshape((1, -1)) + return data + + +@pytest.fixture +def ragged_input(ops, list_input): + lengths = numpy.array([len(x) for x in list_input], dtype="i") + if not list_input: + return Ragged(ops.alloc2f(0, 0), lengths) + else: + return Ragged(ops.flatten(list_input), lengths) + + +@pytest.fixture +def padded_input(ops, list_input): + return ops.list2padded(list_input) + + +@pytest.fixture +def array_input(ragged_input): + return ragged_input.data + + +@pytest.fixture +def padded_data_input(padded_input): + x = padded_input + return (x.data, x.size_at_t, x.lengths, x.indices) + + +@pytest.fixture +def ragged_data_input(ragged_input): + return (ragged_input.data, ragged_input.lengths) + + +@pytest.fixture +def noop_models(): + return [ + with_padded(noop()), + with_array(noop()), + with_array2d(noop()), + with_list(noop()), + with_ragged(noop()), + ] + + +# As an example operation, lets just trim the last dimension. That +# should catch stuff that confuses the input and output. + + +def get_array_model(): + def _trim_array_forward(model, X, is_train): + def backprop(dY): + return model.ops.alloc2f(dY.shape[0], dY.shape[1] + 1) + + return X[:, :-1], backprop + + return with_array2d(Model("trimarray", _trim_array_forward)) + + +def get_list_model(): + def _trim_list_forward(model, Xs, is_train): + def backprop(dYs): + dXs = [] + for dY in dYs: + dXs.append(model.ops.alloc2f(dY.shape[0], dY.shape[1] + 1)) + return dXs + + Ys = [X[:, :-1] for X in Xs] + return Ys, backprop + + return with_list(Model("trimlist", _trim_list_forward)) + + +def get_padded_model(): + def _trim_padded_forward(model, Xp, is_train): + def backprop(dYp): + dY = dYp.data + dX = model.ops.alloc3f(dY.shape[0], dY.shape[1], dY.shape[2] + 1) + return Padded(dX, dYp.size_at_t, dYp.lengths, dYp.indices) + + assert isinstance(Xp, Padded) + X = Xp.data + X = X.reshape((X.shape[0] * X.shape[1], X.shape[2])) + X = X[:, :-1] + X = X.reshape((Xp.data.shape[0], Xp.data.shape[1], X.shape[1])) + return Padded(X, Xp.size_at_t, Xp.lengths, Xp.indices), backprop + + return with_padded(Model("trimpadded", _trim_padded_forward)) + + +def get_ragged_model(): + def _trim_ragged_forward(model, Xr, is_train): + def backprop(dYr): + dY = dYr.data + dX = model.ops.alloc2f(dY.shape[0], dY.shape[1] + 1) + return Ragged(dX, dYr.lengths) + + return Ragged(Xr.data[:, :-1], Xr.lengths), backprop + + return with_ragged(Model("trimragged", _trim_ragged_forward)) + + +def check_initialize(model, inputs): + # Just check that these run and don't hit errors. I guess we should add a + # spy and check that model.layers[0].initialize gets called, but shrug? + model.initialize() + model.initialize(X=inputs) + model.initialize(X=inputs, Y=model.predict(inputs)) + + +def check_transform_produces_correct_output_type_forward(model, inputs, checker): + # It's pretty redundant to check these three assertions, so if the tests + # get slow this could be removed. I think it should be fine though? + outputs = model.predict(inputs) + assert checker(inputs, outputs) + outputs, _ = model(inputs, is_train=True) + assert checker(inputs, outputs) + outputs, _ = model(inputs, is_train=False) + assert checker(inputs, outputs) + + +def check_transform_produces_correct_output_type_backward(model, inputs, checker): + # It's pretty redundant to check these three assertions, so if the tests + # get slow this could be removed. I think it should be fine though? + outputs, backprop = model.begin_update(inputs) + d_inputs = backprop(outputs) + assert checker(inputs, d_inputs) + + +def check_transform_doesnt_change_noop_values(model, inputs, d_outputs): + # Check that if we're wrapping a noop() layer in the transform, we don't + # change the output values. + outputs, backprop = model.begin_update(inputs) + d_inputs = backprop(d_outputs) + if isinstance(outputs, list): + for i in range(len(outputs)): + numpy.testing.assert_equal(inputs[i], outputs[i]) + numpy.testing.assert_equal(d_outputs[i], d_inputs[i]) + elif isinstance(outputs, numpy.ndarray): + numpy.testing.assert_equal(inputs, outputs) + numpy.testing.assert_equal(d_outputs, d_inputs) + elif isinstance(outputs, Ragged): + numpy.testing.assert_equal(inputs.data, outputs.data) + numpy.testing.assert_equal(d_outputs.data, d_inputs.data) + elif isinstance(outputs, Padded): + numpy.testing.assert_equal(inputs.data, outputs.data) + numpy.testing.assert_equal(d_inputs.data, d_inputs.data) + + +def test_noop_transforms(noop_models, ragged_input, padded_input, list_input): + # Make distinct backprop values, + # to check that the gradients get passed correctly + d_ragged = Ragged(ragged_input.data + 1, ragged_input.lengths) + d_padded = padded_input.copy() + d_padded.data += 1 + d_list = [dx + 1 for dx in list_input] + for model in noop_models: + print(model.name) + check_transform_doesnt_change_noop_values(model, padded_input, d_padded) + check_transform_doesnt_change_noop_values(model, list_input, d_list) + check_transform_doesnt_change_noop_values(model, ragged_input, d_ragged) + + +def test_with_array_initialize(ragged_input, padded_input, list_input, array_input): + for inputs in (ragged_input, padded_input, list_input, array_input): + check_initialize(get_array_model(), inputs) + + +def test_with_padded_initialize( + ragged_input, padded_input, list_input, padded_data_input +): + for inputs in (ragged_input, padded_input, list_input, padded_data_input): + check_initialize(get_padded_model(), inputs) + + +def test_with_list_initialize(ragged_input, padded_input, list_input): + for inputs in (ragged_input, padded_input, list_input): + check_initialize(get_list_model(), inputs) + + +def test_with_ragged_initialize( + ragged_input, padded_input, list_input, ragged_data_input +): + for inputs in (ragged_input, padded_input, list_input, ragged_data_input): + check_initialize(get_ragged_model(), inputs) + + +def test_with_array_forward(ragged_input, padded_input, list_input, array_input): + for inputs in (ragged_input, padded_input, list_input, array_input): + checker = get_data_checker(inputs) + model = get_array_model() + check_transform_produces_correct_output_type_forward(model, inputs, checker) + + +def test_with_list_forward(ragged_input, padded_input, list_input): + for inputs in (ragged_input, padded_input, list_input): + checker = get_data_checker(inputs) + model = get_list_model() + check_transform_produces_correct_output_type_forward(model, inputs, checker) + + +def test_with_padded_forward(ragged_input, padded_input, list_input, padded_data_input): + for inputs in (ragged_input, padded_input, list_input, padded_data_input): + checker = get_data_checker(inputs) + model = get_padded_model() + check_transform_produces_correct_output_type_forward(model, inputs, checker) + + +def test_with_ragged_forward(ragged_input, padded_input, list_input, ragged_data_input): + for inputs in (ragged_input, padded_input, list_input, ragged_data_input): + checker = get_data_checker(inputs) + model = get_ragged_model() + check_transform_produces_correct_output_type_forward(model, inputs, checker) + + +def test_with_array_backward(ragged_input, padded_input, list_input, array_input): + for inputs in (ragged_input, padded_input, list_input, array_input): + checker = get_data_checker(inputs) + model = get_array_model() + check_transform_produces_correct_output_type_backward(model, inputs, checker) + + +def test_with_list_backward(ragged_input, padded_input, list_input): + for inputs in (ragged_input, padded_input, list_input): + checker = get_data_checker(inputs) + model = get_list_model() + check_transform_produces_correct_output_type_backward(model, inputs, checker) + + +def test_with_ragged_backward( + ragged_input, padded_input, list_input, ragged_data_input +): + for inputs in (ragged_input, padded_input, list_input, ragged_data_input): + checker = get_data_checker(inputs) + model = get_ragged_model() + check_transform_produces_correct_output_type_backward(model, inputs, checker) + + +def test_with_padded_backward( + ragged_input, padded_input, list_input, padded_data_input +): + for inputs in (ragged_input, padded_input, list_input, padded_data_input): + checker = get_data_checker(inputs) + model = get_padded_model() + check_transform_produces_correct_output_type_backward(model, inputs, checker) + + +def test_with_getitem(): + data = ( + numpy.asarray([[1, 2, 3, 4]], dtype="f"), + numpy.asarray([[5, 6, 7, 8]], dtype="f"), + ) + model = with_getitem(1, Linear()) + model.initialize(data, data) + Y, backprop = model.begin_update(data) + assert len(Y) == len(data) + assert numpy.array_equal(Y[0], data[0]) # the other item stayed the same + assert not numpy.array_equal(Y[1], data[1]) + dX = backprop(Y) + assert numpy.array_equal(dX[0], data[0]) + assert not numpy.array_equal(dX[1], data[1]) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/model/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/model/test_model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/model/test_model.py new file mode 100644 index 0000000000000000000000000000000000000000..2284e93b280a22d30acbe836b0d27da0425ef476 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/model/test_model.py @@ -0,0 +1,675 @@ +import platform +import threading +import time +from collections import Counter + +import numpy +import pytest + +from thinc.api import ( + Adam, + CupyOps, + Dropout, + Linear, + Model, + Relu, + Shim, + Softmax, + chain, + change_attr_values, + concatenate, + set_dropout_rate, + use_ops, + with_debug, + wrap_model_recursive, +) +from thinc.compat import has_cupy_gpu + +from ..util import make_tempdir + + +@pytest.fixture +def model_with_no_args(): + return Linear() + + +def create_model(name): + return Model(name, lambda X: (X, lambda dY: dY)) + + +def test_model_defaults_to_cpu(model_with_no_args): + assert not isinstance(model_with_no_args.ops, CupyOps) + + +def test_models_get_different_ids(model_with_no_args): + model1 = Linear() + model2 = Linear() + assert model1.id != model2.id + + +def test_model_init(): + class MyShim(Shim): + name = "testshim" + + model_a = create_model("a") + model = Model( + "test", + lambda X: (X, lambda dY: dY), + dims={"nI": 10, "nO": None}, + params={"W": numpy.zeros((10,)), "b": None}, + refs={"a": model_a, "b": None}, + attrs={"foo": "bar"}, + shims=[MyShim(None)], + layers=[model_a, model_a], + ) + assert model.has_param("W") + assert model.get_param("W").shape == (10,) + assert model.has_param("b") is None + with pytest.raises(KeyError): + model.get_param("b") + with pytest.raises(KeyError): + model.get_param("X") + model.set_param("X", numpy.zeros((10,))) + assert model.has_param("X") + assert model.get_param("X").shape == (10,) + with model.use_params({(model.id, "X"): numpy.ones((10,))}): + assert numpy.array_equal(model.get_param("X"), numpy.ones((10,))) + assert numpy.array_equal(model.get_param("X"), numpy.zeros((10,))) + assert not model.has_grad("W") + assert not model.has_grad("xyz") + with pytest.raises(KeyError): + model.get_grad("b") + model.set_param("W", model.ops.alloc1f(10)) + model.set_grad("W", model.ops.alloc1f(10)) + with pytest.raises(ValueError): + model.inc_grad("W", numpy.zeros((5, 0))) + assert model.has_dim("nI") + assert model.get_dim("nI") == 10 + with pytest.raises(KeyError): + model.get_dim("xyz") + with pytest.raises(ValueError): + model.get_dim("nO") + assert model.has_ref("a") + assert model.get_ref("a").name == "a" + assert not model.has_ref("xyz") + with pytest.raises(KeyError): + model.get_ref("xyz") + assert model.has_ref("b") is None + with pytest.raises(ValueError): + model.get_ref("b") + model.set_ref("c", model_a) + assert model.has_ref("c") + assert model.get_ref("c").name == "a" + with pytest.raises(ValueError): + model.set_ref("c", create_model("c")) + assert "foo" in model.attrs + assert "bar" not in model.attrs + assert model.attrs["foo"] == "bar" + with pytest.raises(KeyError): + model.attrs["bar"] + model.attrs["bar"] = "baz" + model_copy = model.copy() + assert model_copy.name == "test" + + +def test_model_set_dim(): + class MyShim(Shim): + name = "testshim" + + model_a = create_model("a") + model = Model( + "test", + lambda X: (X, lambda dY: dY), + dims={"nI": 5, "nO": None}, + params={"W": None, "b": None}, + refs={"a": model_a, "b": None}, + attrs={"foo": "bar"}, + shims=[MyShim(None)], + layers=[model_a, model_a], + ) + with pytest.raises(ValueError): + model.set_dim("nI", 10) + # force can be used before any parameters are set + model.set_dim("nI", 10, force=True) + model.set_param("W", model.ops.alloc1f(10)) + model.set_grad("W", model.ops.alloc1f(10)) + assert model.has_dim("nI") + assert model.get_dim("nI") == 10 + with pytest.raises(KeyError): + model.set_dim("xyz", 20) + with pytest.raises(ValueError): + model.set_dim("nI", 20) + # force can't be used after any parameter is set + with pytest.raises(ValueError): + model.set_dim("nI", 20, force=True) + + +def test_param_names(): + model = create_model("tmp") + assert model.param_names == tuple() + model.set_param("param1", None) + assert model.param_names == ("param1",) + model.set_param("param2", None) + assert model.param_names == ("param1", "param2") + + +def test_grad_names(): + model = create_model("tmp") + assert model.grad_names == tuple() + model.set_param("param1", model.ops.alloc2f(4, 4)) + model.set_grad("param1", model.ops.alloc2f(4, 4) + 1) + assert model.grad_names == ("param1",) + + +def test_dim_names(): + model = Linear(5, 3) + assert model.dim_names == ("nO", "nI") + + +def test_model_set_reference(): + parent = create_model("parent") + child = create_model("child") + grandchild = create_model("child") + parent.layers.append(child) + assert parent.ref_names == tuple() + parent.set_ref("kid", child) + assert parent.ref_names == ("kid",) + assert parent.get_ref("kid") is child + child.layers.append(grandchild) + with pytest.raises(KeyError): + parent.get_ref("grandkid") + parent.set_ref("grandkid", grandchild) + assert parent.get_ref("grandkid") is grandchild + parent.remove_node(grandchild) + assert grandchild not in child.layers + assert not parent.has_ref("grandkind") + + +def test_maybe_methods(): + model = Linear(5) + assert model.maybe_get_dim("nI") is None + model.set_dim("nI", 4) + assert model.maybe_get_dim("nI") == 4 + assert model.maybe_get_ref("boo") is None + assert model.maybe_get_param("W") is None + model.initialize() + assert model.maybe_get_param("W") is not None + + +def test_model_can_save_to_disk(model_with_no_args): + with make_tempdir() as path: + model_with_no_args.to_disk(path / "thinc_model") + + +def test_model_can_load_from_disk(model_with_no_args): + with make_tempdir() as path: + model_with_no_args.to_disk(path / "thinc_model") + m2 = model_with_no_args.from_disk(path / "thinc_model") + assert model_with_no_args.to_bytes() == m2.to_bytes() + + +def test_model_can_roundtrip_with_path_subclass(model_with_no_args, pathy_fixture): + path = pathy_fixture / "thinc_model" + model_with_no_args.to_disk(path) + m2 = model_with_no_args.from_disk(path) + assert model_with_no_args.to_bytes() == m2.to_bytes() + + +def test_change_attr_values(model_with_no_args): + model = model_with_no_args + model.name = "target" + model.attrs["has_var"] = False + change_attr_values(model, {"target": {"has_var": True, "error": True}}) + assert model.attrs["has_var"] is True + assert "error" not in model.attrs + + +def test_set_dropout(): + model = Dropout() + assert model.attrs["dropout_rate"] == 0.0 + set_dropout_rate(model, 0.2) + assert model.attrs["dropout_rate"] == 0.2 + + +def test_set_dropout_2(model_with_no_args): + model = model_with_no_args + model.name = "dropout" + model.attrs["dropout_rate"] = 0.0 + set_dropout_rate(model, 0.2) + assert model.attrs["dropout_rate"] == 0.2 + + +def test_bind_plus(): + with Model.define_operators({"+": lambda a, b: (a.name, b.name)}): + m = create_model(name="a") + create_model(name="b") + assert m == ("a", "b") + + +def test_plus_chain(): + with Model.define_operators({"+": lambda a, b: a}): + m = ( + create_model(name="a") + + create_model(name="b") + + create_model(name="c") + + create_model(name="d") + ) + assert m.name == "a" + + +def test_overload_operators_in_subthread(): + """Test we can create a model in a child thread with overloaded operators.""" + # Worker1 will start and run, while worker 2 sleeps after Model.define_operators. + # Without thread-safety, worker2 will find that its operator definitions + # have been removed, causing an error. + worker1 = threading.Thread(target=_overload_plus, args=("+", 0)) + worker2 = threading.Thread(target=_overload_plus, args=("*", 1)) + worker2.start() + worker1.start() + worker1.join() + worker2.join() + + worker1 = threading.Thread(target=_overload_plus, args=("+", 1)) + worker2 = threading.Thread(target=_overload_plus, args=("*", 0)) + worker2.start() + worker1.start() + worker1.join() + worker2.join() + + +def _overload_plus(operator, sleep): + m1 = create_model(name="a") + m2 = create_model(name="b") + with Model.define_operators({operator: lambda a, b: a.name + b.name}): + time.sleep(sleep) + if operator == "+": + value = m1 + m2 + else: + value = m1 * m2 + assert value == "ab" + assert Model._context_operators.get() == {} + + +def test_nested_operator_contexts(): + m1 = create_model(name="a") + m2 = create_model(name="b") + assert Model._context_operators.get() == {} + with Model.define_operators({"+": lambda a, b: a.name + b.name}): + value = m1 + m2 + with pytest.raises(TypeError): + value = m1 * m2 + with Model.define_operators({"*": lambda a, b: a.name + b.name}): + with pytest.raises(TypeError): + value = m1 + m2 + value = m1 * m2 + with Model.define_operators({"-": lambda a, b: a.name + b.name}): + with pytest.raises(TypeError): + value = m1 + m2 + value = m1 - m2 + with pytest.raises(TypeError): + value = m1 + m2 + value = m1 * m2 + value = m1 + m2 + with pytest.raises(TypeError): + value = m1 * m2 + assert value == "ab" + assert Model._context_operators.get() == {} + + +@pytest.mark.parametrize("op", "+ - * @ / // % ** << >> & ^ |".split()) +def test_all_operators(op): + m1 = Linear() + m2 = Linear() + with Model.define_operators({op: lambda a, b: a.name + b.name}): + if op == "+": + value = m1 + m2 + else: + with pytest.raises(TypeError): + value = m1 + m2 + if op == "-": + value = m1 - m2 + else: + with pytest.raises(TypeError): + value = m1 - m2 + + if op == "*": + value = m1 * m2 + else: + with pytest.raises(TypeError): + value = m1 * m2 + + if op == "@": + value = m1.__matmul__(m2) # Be kind to Python 2... + else: + with pytest.raises(TypeError): + value = m1.__matmul__(m2) + + if op == "/": + value = m1 / m2 + else: + with pytest.raises(TypeError): + value = m1 / m2 + + if op == "//": + value = m1 // m2 + else: + with pytest.raises(TypeError): + value = m1 // m2 + if op == "^": + value = m1 ^ m2 + else: + with pytest.raises(TypeError): + value = m1 ^ m2 + if op == "%": + value = m1 % m2 + else: + with pytest.raises(TypeError): + value = m1 % m2 + if op == "**": + value = m1**m2 + else: + with pytest.raises(TypeError): + value = m1**m2 + if op == "<<": + value = m1 << m2 + else: + with pytest.raises(TypeError): + value = m1 << m2 + if op == ">>": + value = m1 >> m2 + else: + with pytest.raises(TypeError): + value = m1 >> m2 + if op == "&": + value = m1 & m2 + else: + with pytest.raises(TypeError): + value = m1 & m2 + if op == "^": + value = m1 ^ m2 + else: + with pytest.raises(TypeError): + value = m1 ^ m2 + if op == "|": + value = m1 | m2 + else: + with pytest.raises(TypeError): + value = m1 | m2 # noqa: F841 + assert Model._context_operators.get() == {} + + +def test_unique_id_multithreading(): + """Create a bunch of threads and assert they all get unique IDs""" + + list_of_ids = [] + + def get_model_id(id_list, index): + id_list.append(create_model(name=f"worker{index}").id) + + counter = 0 + while len(list_of_ids) < 1000: + workers = [] + for i in range(50): + w = threading.Thread(target=get_model_id, args=(list_of_ids, counter)) + workers.append(w) + counter += 1 + for w in workers: + w.start() + for w in workers: + w.join() + + assert len(list_of_ids) == len(list(set(list_of_ids))) + + +@pytest.mark.skipif(not has_cupy_gpu, reason="needs CuPy GPU") +def test_model_gpu(): + pytest.importorskip("ml_datasets") + import ml_datasets + + with use_ops("cupy"): + n_hidden = 32 + dropout = 0.2 + (train_X, train_Y), (dev_X, dev_Y) = ml_datasets.mnist() + model = chain( + Relu(nO=n_hidden, dropout=dropout), + Relu(nO=n_hidden, dropout=dropout), + Softmax(), + ) + # make sure the data is on the right device + train_X = model.ops.asarray(train_X) + train_Y = model.ops.asarray(train_Y) + dev_X = model.ops.asarray(dev_X) + dev_Y = model.ops.asarray(dev_Y) + + model.initialize(X=train_X[:5], Y=train_Y[:5]) + optimizer = Adam(0.001) + batch_size = 128 + + for i in range(2): + batches = model.ops.multibatch(batch_size, train_X, train_Y, shuffle=True) + for X, Y in batches: + Yh, backprop = model.begin_update(X) + backprop(Yh - Y) + model.finish_update(optimizer) + # Evaluate and print progress + correct = 0 + total = 0 + for X, Y in model.ops.multibatch(batch_size, dev_X, dev_Y): + Yh = model.predict(X) + correct += (Yh.argmax(axis=1) == Y.argmax(axis=1)).sum() + total += Yh.shape[0] + + +def test_replace_node(): + relu1 = Relu(5) + relu2 = Relu(5) + relu_chain = chain(relu1, relu2) + relu1_debug = with_debug(relu1) + debug = Model( + "test", + lambda X: (X, lambda dY: dY), + layers=[relu1, relu2, relu1, relu_chain], + refs={"relu1": relu1, "relu2": relu2, "relu3": relu1}, + ) + debug.replace_node(relu1, relu1_debug) + assert debug.layers[0] == relu1_debug + assert debug.layers[1] == relu2 + assert debug.layers[2] == relu1_debug + assert debug.get_ref("relu1") == relu1_debug + assert debug.get_ref("relu2") == relu2 + assert debug.get_ref("relu3") == relu1_debug + + # Check that nodes are replaced recursively + assert debug.layers[3] == relu_chain + assert debug.layers[3].layers[0] == relu1_debug + assert debug.layers[3].layers[1] == relu2 + + +def test_replace_node_with_indirect_node_ref(): + # a + # / \ + # x b[y=y] + # | | + # y x + # | + # y + + def dummy_model(name, layers): + return Model(name, lambda model, X, is_train: ..., layers=layers) + + y = dummy_model("y", []) + x = dummy_model("x", [y]) + + y_debug = with_debug(y) + + b = dummy_model("b", [x]) + b.set_ref("y", y) + + a = chain(x, b) + a.name = "a" + + a.replace_node(y, y_debug) + + assert a.layers[0].layers[0] == y_debug + assert a.layers[1].layers[0].layers[0] == y_debug + assert a.layers[1].get_ref("y") == y_debug + + +@pytest.mark.xfail( + platform.system() == "Darwin", + reason="SSL: CERTIFICATE_VERIFY_FAILED", + strict=False, # Works on macos-15-intel Python 3.10, for some reason +) +def test_with_debug(): + pytest.importorskip("ml_datasets") + import ml_datasets + + (train_X, train_Y), (dev_X, dev_Y) = ml_datasets.mnist() + + counts = Counter() + + def on_init(*_): + counts["init"] += 1 + + def on_forward(*_): + counts["forward"] += 1 + + def on_backprop(*_): + counts["backprop"] += 1 + + relu = Relu() + relu2 = with_debug( + Relu(), on_init=on_init, on_forward=on_forward, on_backprop=on_backprop + ) + chained = chain(relu, relu2, relu2) + chained.initialize(X=train_X[:5], Y=train_Y[:5]) + _, backprop = chained(X=train_X[:5], is_train=False) + + # Not real loss gradients, but we don't care for testing. + backprop(train_Y[:5]) + + # Four times forward, because initialization also applies forward for + # validation. + assert counts == {"init": 2, "forward": 4, "backprop": 2} + + +def test_recursive_wrap(): + def dummy_model(name, layers): + return Model(name, lambda model, X, is_train: ..., layers=layers) + + # Check: + # + # * Recursion: chain -> relu + # * Multiple sublayers: chain -> [relu, relu] + + relu = Relu(5) + chained = chain(relu, relu) + chained_debug = wrap_model_recursive( + chained, lambda model: dummy_model(f"dummy({model.name})", [model]) + ) + + assert chained_debug.name == "dummy(relu>>relu)" + assert chained_debug.layers[0] is chained + assert chained_debug.layers[0].layers[0].name == "dummy(relu)" + assert chained_debug.layers[0].layers[0].layers[0] is relu + assert chained_debug.layers[0].layers[1].name == "dummy(relu)" + assert chained_debug.layers[0].layers[1].layers[0] is relu + + +def test_recursive_double_wrap(): + def dummy_model(name, layers): + return Model(name, lambda model, X, is_train: ..., layers=layers) + + relu = Relu(5) + chained = chain(relu, relu) + concat = concatenate(chained, chained, relu) + concat_wrapped = wrap_model_recursive( + concat, lambda model: dummy_model(f"dummy({model.name})", [model]) + ) + + n_debug = 0 + for model in concat_wrapped.walk(): + if model.name.startswith("dummy"): + n_debug += 1 + + # There should be 3 unique dummy wrappers: + # * Around concatenate. + # * Around chain. + # * Around relu. + assert n_debug == 3 + + assert concat_wrapped.layers[0].layers[0].layers[0].layers[0].name == "dummy(relu)" + assert concat_wrapped.layers[0].layers[0].layers[0].layers[1].name == "dummy(relu)" + assert concat_wrapped.layers[0].layers[1].layers[0].layers[0].name == "dummy(relu)" + assert concat_wrapped.layers[0].layers[1].layers[0].layers[1].name == "dummy(relu)" + assert concat_wrapped.layers[0].layers[2].name == "dummy(relu)" + + +def test_wrap_non_child_references(): + relu = Relu(5) + relu2 = Relu(5) + chained = chain(relu, relu) + chained2 = chain(relu2, chained) + chained2.set_ref("relu", relu) + # Fails in case non-child references cannot be set. + wrap_model_recursive(chained2, with_debug) + + +def test_walk_dfs(): + relu = Relu(5) + relu2 = Relu(5) + inner_chain = chain(relu, relu2) + chained = chain(inner_chain, inner_chain) + assert list(chained.walk(order="dfs_pre")) == [chained, inner_chain, relu, relu2] + assert list(chained.walk(order="dfs_post")) == [ + relu, + relu2, + inner_chain, + chained, + ] + + +def test_walk_bfs_post_order_fails(): + relu = Relu(5) + with pytest.raises(ValueError, match="Invalid order"): + relu.walk(order="dfs_post_order") + + +def test_model_copy_with_loop(): + class MyShim(Shim): + name = "testshim" + + def to_bytes(self): + return test_replace_node_with_indirect_node_ref + + def from_bytes(self, bytes): + pass + + model_a = create_model("a") + working_shim = MyShim(None) + layer = Model( + "test", + lambda X: (X, lambda dY: dY), + dims={"nI": 5, "nO": 5}, + params={"W": numpy.zeros((10,)), "b": None}, + refs={"a": model_a, "b": None}, + attrs={"foo": "bar"}, + shims=[working_shim], + layers=[model_a, model_a], + ) + layer2 = Model( + "test2", + lambda X: (X, lambda dY: dY), + dims={"nI": 5, "nO": 5}, + params={"W": numpy.zeros((10,)), "b": None}, + refs={"a": model_a, "b": None}, + attrs={"foo": "bar"}, + shims=[working_shim], + layers=[model_a, model_a], + ) + relu = Relu(5) + model = chain(layer, relu, layer, layer2) + model2 = model.copy() + model.from_dict(model2.to_dict()) + assert model2.name == "test>>relu>>test>>test2" + assert model2.layers[0] == model2.layers[2] + assert id(model2.layers[0].shims[0]) == id(model2.layers[3].shims[0]) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/model/test_validation.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/model/test_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..c58efd015df8d5ffc49642de0649811f24029cd0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/model/test_validation.py @@ -0,0 +1,44 @@ +import pytest + +from thinc.api import ( + ParametricAttention, + Relu, + Softmax, + chain, + list2ragged, + reduce_max, + reduce_sum, + with_ragged, +) +from thinc.util import DataValidationError, data_validation + + +def test_validation(): + model = chain(Relu(10), Relu(10), with_ragged(reduce_max()), Softmax()) + with data_validation(True): + with pytest.raises(DataValidationError): + model.initialize(X=model.ops.alloc2f(1, 10), Y=model.ops.alloc2f(1, 10)) + with pytest.raises(DataValidationError): + model.initialize(X=model.ops.alloc3f(1, 10, 1), Y=model.ops.alloc2f(1, 10)) + with pytest.raises(DataValidationError): + model.initialize(X=[model.ops.alloc2f(1, 10)], Y=model.ops.alloc2f(1, 10)) + + +def test_validation_complex(): + good_model = chain(list2ragged(), reduce_sum(), Relu(12, dropout=0.5), Relu(1)) + X = [good_model.ops.xp.zeros((4, 75), dtype="f")] + Y = good_model.ops.xp.zeros((1,), dtype="f") + good_model.initialize(X, Y) + good_model.predict(X) + + bad_model = chain( + list2ragged(), + reduce_sum(), + Relu(12, dropout=0.5), + # ERROR: Why can't I attach a Relu to an attention layer? + ParametricAttention(12), + Relu(1), + ) + with data_validation(True): + with pytest.raises(DataValidationError): + bad_model.initialize(X, Y) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73f7cbc81e092a18c1267180c926c39fc111d4fc Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/__pycache__/test_mypy.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/__pycache__/test_mypy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afec9d4950b72e66a0428faae24bc6aa7f66c520 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/__pycache__/test_mypy.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/configs/mypy-default.ini b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/configs/mypy-default.ini new file mode 100644 index 0000000000000000000000000000000000000000..47ed372d64d47bcea2d9759afda7b78de5021492 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/configs/mypy-default.ini @@ -0,0 +1,8 @@ +[mypy] +follow_imports = silent +strict_optional = True +warn_redundant_casts = True +warn_unused_ignores = True +# disallow_any_generics = True +check_untyped_defs = True +disallow_untyped_defs = True diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/configs/mypy-plugin.ini b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/configs/mypy-plugin.ini new file mode 100644 index 0000000000000000000000000000000000000000..9dfde3726c775d83bdd5232d26854001e8654328 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/configs/mypy-plugin.ini @@ -0,0 +1,10 @@ +[mypy] +plugins = thinc.mypy + +follow_imports = silent +strict_optional = True +warn_redundant_casts = True +warn_unused_ignores = True +# disallow_any_generics = True +check_untyped_defs = True +disallow_untyped_defs = True diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/fail_no_plugin.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/fail_no_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..f53e33ef3e762356a6934aa0329f242d3d17ea26 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/fail_no_plugin.py @@ -0,0 +1,5 @@ +from thinc.api import Relu, Softmax, add, chain, reduce_max + +bad_model = chain(Relu(10), reduce_max(), Softmax()) + +bad_model2 = add(Relu(10), reduce_max(), Softmax()) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/fail_plugin.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/fail_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..6f23c82b146e9964600b8866ea9ac681a92ce5c5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/fail_plugin.py @@ -0,0 +1,20 @@ +from thinc.api import Relu, Softmax, add, chain, concatenate, reduce_max + +bad_model = chain(Relu(10), reduce_max(), Softmax()) + +bad_model2 = add(Relu(10), reduce_max(), Softmax()) + +bad_model_only_plugin = chain( + Relu(10), Relu(10), Relu(10), Relu(10), reduce_max(), Softmax() +) + +bad_model_only_plugin2 = add( + Relu(10), Relu(10), Relu(10), Relu(10), reduce_max(), Softmax() +) +reveal_type(bad_model_only_plugin2) + +bad_model_only_plugin3 = concatenate( + Relu(10), Relu(10), Relu(10), Relu(10), reduce_max(), Softmax() +) + +reveal_type(bad_model_only_plugin3) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/success_no_plugin.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/success_no_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..058573e5bffc14434ddc90a00dbf1c5cd940d0be --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/success_no_plugin.py @@ -0,0 +1,13 @@ +from thinc.api import Relu, Softmax, add, chain, reduce_max + +good_model = chain(Relu(10), Relu(10), Softmax()) +reveal_type(good_model) + +good_model2 = add(Relu(10), Relu(10), Softmax()) +reveal_type(good_model2) + +bad_model_undetected = chain(Relu(10), Relu(10), reduce_max(), Softmax()) +reveal_type(bad_model_undetected) + +bad_model_undetected2 = add(Relu(10), Relu(10), reduce_max(), Softmax()) +reveal_type(bad_model_undetected2) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/success_plugin.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/success_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..3214bdcb7756c0233887aa6951d5d9a8f166cfc9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/modules/success_plugin.py @@ -0,0 +1,34 @@ +from typing import Any, TypeVar + +from thinc.api import Model, Relu, Softmax, add, chain, reduce_max + +good_model = chain(Relu(10), Relu(10), Softmax()) +reveal_type(good_model) + +good_model2 = add(Relu(10), Relu(10), Softmax()) +reveal_type(good_model2) + +bad_model_undetected = chain(Relu(10), Relu(10), Relu(10), Relu(10), Softmax()) +reveal_type(bad_model_undetected) + +bad_model_undetected2 = add(Relu(10), Relu(10), Relu(10), Relu(10), Softmax()) +reveal_type(bad_model_undetected2) + + +def forward() -> None: + pass + + +OtherType = TypeVar("OtherType") + + +def other_function( + layer1: Model, layer2: Model, *layers: Model +) -> Model[Any, OtherType]: + return Model("some_model", forward) + + +non_combinator_model = other_function( + Model("x", forward), Model("y", forward), Model("z", forward) +) +reveal_type(non_combinator_model) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/outputs/success-plugin.txt b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/outputs/success-plugin.txt new file mode 100644 index 0000000000000000000000000000000000000000..e226360090d25f7198531e3562d74bf2fa6a3848 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/outputs/success-plugin.txt @@ -0,0 +1,6 @@ +6: note: Revealed type is "thinc.model.Model[thinc.types.Floats2d, thinc.types.Floats2d]" +9: note: Revealed type is "thinc.model.Model[thinc.types.Floats2d, thinc.types.Floats2d]" +12: note: Revealed type is "thinc.model.Model[thinc.types.Floats2d, thinc.types.Floats2d]" +15: note: Revealed type is "thinc.model.Model[thinc.types.Floats2d, thinc.types.Floats2d]" +31: error: Need type annotation for "non_combinator_model" [var-annotated] +34: note: Revealed type is "thinc.model.Model[Any, Any]" \ No newline at end of file diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/test_mypy.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/test_mypy.py new file mode 100644 index 0000000000000000000000000000000000000000..f144128f4695d67502971d8927f5fc838995d091 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/mypy/test_mypy.py @@ -0,0 +1,91 @@ +import os +import re +import shutil +import sys +from pathlib import Path + +import pytest + +mypy = pytest.importorskip("mypy") + +# You can change the following variable to True during development to overwrite expected output with generated output +GENERATE = False + +cases = [ + ("mypy-plugin.ini", "success_plugin.py", "success-plugin.txt"), + ("mypy-plugin.ini", "fail_plugin.py", "fail-plugin.txt"), + ("mypy-default.ini", "success_no_plugin.py", "success-no-plugin.txt"), + ("mypy-default.ini", "fail_no_plugin.py", "fail-no-plugin.txt"), +] + + +@pytest.mark.skipif( + mypy.__file__.endswith(".py"), reason="Non-compiled mypy is too slow" +) +@pytest.mark.parametrize("config_filename,python_filename,output_filename", cases) +def test_mypy_results( + config_filename, python_filename, output_filename, tmpdir, monkeypatch +): + from mypy import api as mypy_api + + os.chdir(tmpdir) + root_dir = Path(__file__).parent + thinc_root_dir = Path(__file__).parent.parent.parent.parent + if "--pyargs" not in sys.argv: + monkeypatch.setenv("MYPYPATH", str(thinc_root_dir)) + tmpdir_path = Path(tmpdir) + + full_config_path: Path = root_dir / f"configs/{config_filename}" + full_module_path: Path = root_dir / f"modules/{python_filename}" + full_output_path: Path = root_dir / f"outputs/{output_filename}" + + full_tmp_config_path: Path = tmpdir_path / config_filename + full_tmp_module_path: Path = tmpdir_path / python_filename + + shutil.copy(str(full_config_path), tmpdir) + shutil.copy(str(full_module_path), tmpdir) + + expected_out = "" + expected_err = "" + expected_returncode = 1 + expected_out = full_output_path.read_text() + + # Specifying a different cache dir for each configuration dramatically speeds up subsequent execution + # It also prevents cache-invalidation-related bugs in the tests + cache_dir = tmpdir_path / f".mypy_cache/test-{config_filename[:-4]}" + command = [ + str(full_tmp_module_path), + "--config-file", + str(full_tmp_config_path), + "--cache-dir", + str(cache_dir), + "--show-error-codes", + ] + print( + f"\nExecuting: mypy {' '.join(command)}" + ) # makes it easier to debug as necessary + actual_result = mypy_api.run(command) + actual_out, actual_err, actual_returncode = actual_result + # Need to strip filenames due to differences in formatting by OS + actual_out = "\n".join( + [".py:".join(line.split(".py:")[1:]) for line in actual_out.split("\n") if line] + ).strip() + actual_out = re.sub(r"\n\s*\n", r"\n", actual_out) + + if GENERATE and output_filename is not None: + full_output_path.write_text(actual_out) + else: + assert actual_out.strip() == expected_out.strip(), actual_out + + assert actual_err == expected_err + assert actual_returncode == expected_returncode + + +@pytest.mark.skipif( + mypy.__file__.endswith(".py"), reason="Non-compiled mypy is too slow" +) +def test_generation_is_disabled(): + """ + Makes sure we don't accidentally leave generation on + """ + assert not GENERATE diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3109d3c8745c302b29bd6bdf8d636345b0e5a9e4 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/__pycache__/test_issue208.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/__pycache__/test_issue208.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca17c197b6b5e393b827f913f2382d90b655b0ff Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/__pycache__/test_issue208.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/__pycache__/test_issue564.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/__pycache__/test_issue564.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..189f86cd3a979c0f9d54e68db8616918df6bb1a3 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/__pycache__/test_issue564.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..128d2250956479fa40505363e3678be599d21b16 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/__pycache__/program.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/__pycache__/program.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..366bc7d8c1995f73f421083f35473b476a7a6f93 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/__pycache__/program.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/__pycache__/test_issue519.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/__pycache__/test_issue519.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d8392c29fddb58a96106e792cc7203163496cc3 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/__pycache__/test_issue519.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/program.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/program.py new file mode 100644 index 0000000000000000000000000000000000000000..bce5f32349bfe951f7ae277a8f82e7f5714b09de --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/program.py @@ -0,0 +1,16 @@ +from thinc.api import Relu, Softmax, chain, concatenate +from thinc.model import Model +from thinc.types import Floats2d + +n_hidden = 32 +dropout = 0.2 + +model1: Model[Floats2d, Floats2d] = chain( + Relu(nO=n_hidden, dropout=dropout), Relu(nO=n_hidden, dropout=dropout), Softmax() +) + +model2: Model[Floats2d, Floats2d] = chain( + Relu(nO=n_hidden, dropout=dropout), Relu(nO=n_hidden, dropout=dropout), Softmax() +) + +model3: Model[Floats2d, Floats2d] = concatenate(*[model1, model2]) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/test_issue519.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/test_issue519.py new file mode 100644 index 0000000000000000000000000000000000000000..02601f0d7860475f221e68da486f7d110aad108d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/issue519/test_issue519.py @@ -0,0 +1,29 @@ +import subprocess +import sys + +try: + import importlib.resources as importlib_resources +except ImportError: + import importlib_resources # type: ignore + + +import pytest + + +@pytest.mark.slow +def test_issue519(): + """ + Test ability of Thinc mypy plugin to handle variadic arguments. + + This test can take up to 45 seconds, and is thus marked as slow. + """ + # Determine the name of the parent module (which contains the test program) + parent_module_name = __name__[: __name__.rfind(".")] + + # Load test program that calls a Thinc API with variadic arguments + program_text = importlib_resources.read_text(parent_module_name, "program.py") + + # Ask Mypy to type-check the loaded program text + subprocess.run( + [sys.executable, "-m", "mypy", "--command", program_text], check=True + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/test_issue208.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/test_issue208.py new file mode 100644 index 0000000000000000000000000000000000000000..0c574d6d17cb7d2b878ca01b2b5228da7b270816 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/test_issue208.py @@ -0,0 +1,10 @@ +from thinc.api import Linear, chain + + +def test_issue208(): + """Test issue that was caused by trying to flatten nested chains.""" + layer1 = Linear(nO=9, nI=3) + layer2 = Linear(nO=12, nI=9) + layer3 = Linear(nO=5, nI=12) + model = chain(layer1, chain(layer2, layer3)).initialize() + assert model.get_dim("nO") == 5 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/test_issue564.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/test_issue564.py new file mode 100644 index 0000000000000000000000000000000000000000..94ecc6e63b3b0dd5ad7397bf8ddae3646b0174ed --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/regression/test_issue564.py @@ -0,0 +1,21 @@ +import pytest + +from thinc.api import CupyOps +from thinc.compat import has_torch, has_torch_cuda_gpu + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +@pytest.mark.skipif(not has_torch_cuda_gpu, reason="needs a GPU") +def test_issue564(): + import torch + + if CupyOps.xp is not None: + ops = CupyOps() + t = torch.zeros((10, 2)).cuda() + a = ops.asarray(t) + + assert a.shape == t.shape + ops.xp.testing.assert_allclose( + a, + ops.alloc2f(10, 2), + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/shims/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/shims/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/shims/test_pytorch_grad_scaler.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/shims/test_pytorch_grad_scaler.py new file mode 100644 index 0000000000000000000000000000000000000000..d4ac10fec77a85a04be7d23d21967d15a4f6084a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/thinc/tests/shims/test_pytorch_grad_scaler.py @@ -0,0 +1,109 @@ +import pytest +from hypothesis import given, settings +from hypothesis.strategies import lists, one_of, tuples + +from thinc.api import PyTorchGradScaler +from thinc.compat import has_torch, has_torch_amp, has_torch_cuda_gpu, torch +from thinc.util import is_torch_array + +from ..strategies import ndarrays + + +def tensors(): + return ndarrays().map(lambda a: torch.tensor(a).cuda()) + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +@pytest.mark.skipif(not has_torch_cuda_gpu, reason="needs a GPU") +@pytest.mark.skipif( + not has_torch_amp, reason="requires PyTorch with mixed-precision support" +) +@given(X=one_of(tensors(), lists(tensors()), tuples(tensors()))) +@settings(deadline=None) +def test_scale_random_inputs(X): + import torch + + device_id = torch.cuda.current_device() + scaler = PyTorchGradScaler(enabled=True) + scaler.to_(device_id) + + if is_torch_array(X): + assert torch.allclose(scaler.scale(X), X * 2.0**16) + else: + scaled1 = scaler.scale(X) + scaled2 = [t * 2.0**16 for t in X] + for t1, t2 in zip(scaled1, scaled2): + assert torch.allclose(t1, t2) + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +@pytest.mark.skipif(not has_torch_cuda_gpu, reason="needs a GPU") +@pytest.mark.skipif( + not has_torch_amp, reason="requires PyTorch with mixed-precision support" +) +def test_grad_scaler(): + import torch + + device_id = torch.cuda.current_device() + + scaler = PyTorchGradScaler(enabled=True) + scaler.to_(device_id) + + # Test that scaling works as expected. + t = torch.tensor([1.0], device=device_id) + assert scaler.scale([torch.tensor([1.0], device=device_id)]) == [ + torch.tensor([2.0**16], device=device_id) + ] + assert scaler.scale(torch.tensor([1.0], device=device_id)) == torch.tensor( + [2.0**16], device=device_id + ) + with pytest.raises(ValueError): + scaler.scale("bogus") + with pytest.raises(ValueError): + scaler.scale(42) + + # Test infinity detection. + g = [ + torch.tensor([2.0**16], device=device_id), + torch.tensor([float("Inf")], device=device_id), + ] + + # Check that infinity was found. + assert scaler.unscale(g) + + # Check whether unscale was successful. + assert g[0] == torch.tensor([1.0]).cuda() + + scaler.update() + + # Since infinity was found, the scale should be halved from 2**16 + # to 2**15 for the next step. + assert scaler.scale([torch.tensor([1.0], device=device_id)]) == [ + torch.tensor([2.0**15], device=device_id) + ] + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +@pytest.mark.skipif( + has_torch_amp, reason="needs PyTorch without gradient scaling support" +) +def test_raises_on_old_pytorch(): + import torch + + scaler = PyTorchGradScaler(enabled=True) + with pytest.raises(ValueError, match=r"not supported.*1.9.0"): + scaler.scale([torch.tensor([1.0], device="cpu")]) + + +@pytest.mark.skipif(not has_torch, reason="needs PyTorch") +@pytest.mark.skipif( + not has_torch_amp, reason="needs PyTorch with gradient scaling support" +) +def test_raises_with_cpu_tensor(): + import torch + + scaler = PyTorchGradScaler(enabled=True) + with pytest.raises( + ValueError, match=r"Gradient scaling is only supported for CUDA tensors." + ): + scaler.scale([torch.tensor([1.0], device="cpu")])