|
| 1 | +import math |
| 2 | +import random |
| 3 | + |
| 4 | +import pytest |
| 5 | +import torch |
| 6 | +import torch.nn.functional as F |
| 7 | + |
| 8 | +import ntops |
| 9 | +from tests.skippers import skip_if_cuda_not_available |
| 10 | +from tests.utils import generate_arguments |
| 11 | + |
| 12 | +_ALPHA_P = -1.7580993408473766 |
| 13 | + |
| 14 | + |
| 15 | +@skip_if_cuda_not_available |
| 16 | +@pytest.mark.parametrize(*generate_arguments()) |
| 17 | +def test_alpha_dropout(shape, dtype, device, rtol, atol): |
| 18 | + input = torch.randn(shape, dtype=dtype, device=device) |
| 19 | + p = random.uniform(0.1, 0.5) |
| 20 | + |
| 21 | + ninetoothed_output = ntops.torch.alpha_dropout(input, p=p, training=True) |
| 22 | + reference_output = F.alpha_dropout(input, p=p, training=True) |
| 23 | + |
| 24 | + # 1. Shape must match. |
| 25 | + assert ninetoothed_output.shape == reference_output.shape |
| 26 | + |
| 27 | + # 2. Compute expected affine parameters. |
| 28 | + q = 1.0 - p |
| 29 | + a = 1.0 / math.sqrt(q * (1.0 + p * _ALPHA_P * _ALPHA_P)) |
| 30 | + b = -a * p * _ALPHA_P |
| 31 | + sat = a * _ALPHA_P + b |
| 32 | + |
| 33 | + # 3. Drop ratios should be close to each other. |
| 34 | + ninetoothed_drop_ratio = ( |
| 35 | + torch.isclose( |
| 36 | + ninetoothed_output, torch.full_like(ninetoothed_output, sat), atol=atol |
| 37 | + ) |
| 38 | + .float() |
| 39 | + .mean() |
| 40 | + .item() |
| 41 | + ) |
| 42 | + reference_drop_ratio = ( |
| 43 | + torch.isclose( |
| 44 | + reference_output, torch.full_like(reference_output, sat), atol=atol |
| 45 | + ) |
| 46 | + .float() |
| 47 | + .mean() |
| 48 | + .item() |
| 49 | + ) |
| 50 | + |
| 51 | + assert abs(ninetoothed_drop_ratio - reference_drop_ratio) < 0.1 |
| 52 | + |
| 53 | + # 4. Kept elements should satisfy the same affine transform. |
| 54 | + kept_mask = ~torch.isclose( |
| 55 | + ninetoothed_output, torch.full_like(ninetoothed_output, sat), atol=atol |
| 56 | + ) |
| 57 | + expected_kept = a * input[kept_mask].float() + b |
| 58 | + actual_kept = ninetoothed_output[kept_mask].float() |
| 59 | + |
| 60 | + assert torch.allclose(actual_kept, expected_kept, rtol=rtol, atol=atol) |
| 61 | + |
| 62 | + # 5. training=False should return input unchanged. |
| 63 | + output_eval = ntops.torch.alpha_dropout(input, p=p, training=False) |
| 64 | + assert torch.equal(output_eval, input) |
0 commit comments