|
| 1 | +"""E7-13 tests: extended activations (mish/geglu/reglu/xielu).""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import mlx.core as mx |
| 6 | +import mlx.nn as nn |
| 7 | +import pytest |
| 8 | + |
| 9 | +from cppmega_mlx.nn.activations import ( |
| 10 | + ACTIVATION_NAMES, IS_GATED, apply_activation, is_gated, |
| 11 | +) |
| 12 | +from cppmega_v4.explain import get_entry |
| 13 | + |
| 14 | + |
| 15 | +def test_activation_names_have_ten_entries(): |
| 16 | + assert set(ACTIVATION_NAMES) == { |
| 17 | + "gelu", "relu", "relu2", "sqrelu", "silu", "mish", |
| 18 | + "swiglu", "geglu", "reglu", "xielu", |
| 19 | + } |
| 20 | + |
| 21 | + |
| 22 | +def test_gated_set_has_four_entries(): |
| 23 | + gated = {n for n, g in IS_GATED.items() if g} |
| 24 | + assert gated == {"swiglu", "geglu", "reglu", "xielu"} |
| 25 | + |
| 26 | + |
| 27 | +def test_mish_is_dense(): |
| 28 | + assert not is_gated("mish") |
| 29 | + |
| 30 | + |
| 31 | +@pytest.mark.parametrize("name", ["geglu", "reglu", "xielu"]) |
| 32 | +def test_new_gated_activations_require_gate(name): |
| 33 | + x = mx.random.normal((2, 4)) |
| 34 | + with pytest.raises(ValueError, match="is gated"): |
| 35 | + apply_activation(name, x) |
| 36 | + |
| 37 | + |
| 38 | +def test_mish_forward_matches_reference(): |
| 39 | + """Mish = x * tanh(softplus(x)).""" |
| 40 | + x = mx.random.normal((4, 8), key=mx.random.key(0)) |
| 41 | + got = apply_activation("mish", x) |
| 42 | + expected = x * mx.tanh(mx.log1p(mx.exp(x))) |
| 43 | + assert mx.allclose(got, expected).item() |
| 44 | + |
| 45 | + |
| 46 | +def test_geglu_uses_gelu_on_gate(): |
| 47 | + x = mx.random.normal((2, 4), key=mx.random.key(0)) |
| 48 | + g = mx.random.normal((2, 4), key=mx.random.key(1)) |
| 49 | + got = apply_activation("geglu", x, gate=g) |
| 50 | + expected = nn.gelu_approx(g) * x |
| 51 | + assert mx.allclose(got, expected).item() |
| 52 | + |
| 53 | + |
| 54 | +def test_reglu_uses_relu_on_gate(): |
| 55 | + x = mx.random.normal((2, 4), key=mx.random.key(0)) |
| 56 | + g = mx.random.normal((2, 4), key=mx.random.key(1)) |
| 57 | + got = apply_activation("reglu", x, gate=g) |
| 58 | + expected = mx.maximum(g, 0) * x |
| 59 | + assert mx.allclose(got, expected).item() |
| 60 | + |
| 61 | + |
| 62 | +def test_xielu_uses_gelu_gate_silu_value(): |
| 63 | + x = mx.random.normal((2, 4), key=mx.random.key(0)) |
| 64 | + g = mx.random.normal((2, 4), key=mx.random.key(1)) |
| 65 | + got = apply_activation("xielu", x, gate=g) |
| 66 | + expected = nn.gelu_approx(g) * nn.silu(x) |
| 67 | + assert mx.allclose(got, expected).item() |
| 68 | + |
| 69 | + |
| 70 | +@pytest.mark.parametrize("name", ACTIVATION_NAMES) |
| 71 | +def test_every_activation_has_catalog_entry(name): |
| 72 | + entry = get_entry("activation", name) |
| 73 | + assert entry is not None, f"missing catalog entry for {name}" |
| 74 | + assert entry.summary |
0 commit comments