"""Tests for conv.py against SciPy. Run: python -m pytest -q""" import numpy as np import pytest from scipy.signal import convolve2d, correlate2d from conv import conv2d, conv_layer, max_pool2d, output_size, relu @pytest.fixture def rng() -> np.random.Generator: return np.random.default_rng(42) def test_conv2d_matches_scipy_correlate_valid(rng: np.random.Generator) -> None: for shape, kshape in [((8, 8), (3, 3)), ((12, 9), (5, 3)), ((7, 7), (1, 1))]: x = rng.normal(size=shape) w = rng.normal(size=kshape) assert np.allclose(conv2d(x, w), correlate2d(x, w, mode="valid")) def test_conv2d_padding_matches_scipy_same(rng: np.random.Generator) -> None: x = rng.normal(size=(10, 10)) w = rng.normal(size=(3, 3)) assert np.allclose(conv2d(x, w, padding=1), correlate2d(x, w, mode="same", boundary="fill")) def test_conv2d_stride_is_subsampled_full_result(rng: np.random.Generator) -> None: x = rng.normal(size=(11, 11)) w = rng.normal(size=(3, 3)) full = correlate2d(x, w, mode="valid") assert np.allclose(conv2d(x, w, stride=2), full[::2, ::2]) def test_cnn_convolution_is_not_flipped(rng: np.random.Generator) -> None: x = rng.normal(size=(6, 6)) w = np.array([[1.0, 2.0], [3.0, 4.0]]) # not symmetric, so flipping matters assert not np.allclose(conv2d(x, w), convolve2d(x, w, mode="valid")) assert np.allclose(conv2d(x, w[::-1, ::-1]), convolve2d(x, w, mode="valid")) def test_output_size_formula() -> None: assert output_size(640, 3, 2, 1) == 320 assert output_size(224, 7, 2, 3) == 112 x = np.zeros((9, 13)) assert conv2d(x, np.ones((3, 3)), stride=2, padding=1).shape == (output_size(9, 3, 2, 1), output_size(13, 3, 2, 1)) def test_conv_layer_sums_channels(rng: np.random.Generator) -> None: x = rng.normal(size=(3, 8, 8)) w = rng.normal(size=(4, 3, 3, 3)) b = rng.normal(size=4) y = conv_layer(x, w, b, padding=1) assert y.shape == (4, 8, 8) for k in range(4): ref = sum(correlate2d(x[c], w[k, c], mode="same") for c in range(3)) + b[k] assert np.allclose(y[k], ref) def test_conv_layer_rejects_channel_mismatch() -> None: with pytest.raises(ValueError): conv_layer(np.zeros((2, 5, 5)), np.zeros((1, 3, 3, 3)), np.zeros(1)) def test_max_pool_known_values() -> None: x = np.arange(16, dtype=float).reshape(4, 4) assert np.array_equal(max_pool2d(x, 2), [[5, 7], [13, 15]]) assert np.array_equal(max_pool2d(x, 3, stride=1), [[10, 11], [14, 15]]) def test_relu() -> None: assert np.array_equal(relu([-1.0, 0.0, 2.5]), [0.0, 0.0, 2.5]) def test_edge_detector_demo() -> None: image = np.zeros((6, 6)) image[:, 3:] = 1.0 sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=float) edges = conv2d(image, sobel_x) # Columns of the 4 x 4 output whose window straddles the edge respond with 4. assert np.allclose(edges, np.tile([0.0, 4.0, 4.0, 0.0], (4, 1)))