|
| 1 | +# Adapted from https://github.com/thinking-machines-lab/batch_invariant_ops/blob/main/batch_invariant_ops/test_batch_invariance.py |
| 2 | + |
| 3 | +import random |
| 4 | +import unittest |
| 5 | + |
| 6 | +import paddle |
| 7 | + |
| 8 | +from custom_ops.batch_invariant_ops import set_batch_invariant_mode |
| 9 | + |
| 10 | + |
| 11 | +class TestBatchInvariantForLogsoftmax(unittest.TestCase): |
| 12 | + def setUp(self): |
| 13 | + """ |
| 14 | + Initialize the test environment |
| 15 | + """ |
| 16 | + device = "gpu" if paddle.is_compiled_with_cuda() else "cpu" |
| 17 | + paddle.set_device(device) |
| 18 | + |
| 19 | + def create_softmax_trap_tensor(self, B, D, dtype): |
| 20 | + """ |
| 21 | + Constructs a "trap" tensor designed to trigger batch-invariance issues in Softmax/LogSoftmax. |
| 22 | + Inspired by https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/ |
| 23 | +
|
| 24 | + Principle: |
| 25 | + The goal is to make the result of `exp(a - max(a))` contain numbers spanning an extremely wide numerical range |
| 26 | + (e.g., 1.0, 1e-5, 1e-10, and many numbers close to 0). |
| 27 | + When summing these numbers using parallel reduction, different summation orders (due to parallelism) |
| 28 | + can produce different accumulated rounding errors, leading to a subtle difference between |
| 29 | + batch (parallel) and single-sample (serial) computation results. |
| 30 | + """ |
| 31 | + # 1. Determine the desired values after `exp` and calculate the required input values using log(). |
| 32 | + max_val = 20.0 |
| 33 | + |
| 34 | + # Offsets relative to max_val. These offsets result in values spanning vastly different orders of magnitude after exp. |
| 35 | + trap_values = [ |
| 36 | + max_val, # Corresponds to exp(a-max) -> 1.0 |
| 37 | + max_val - 4.6, # Corresponds to exp(a-max) -> ~1e-2 |
| 38 | + max_val - 11.5, # Corresponds to exp(a-max) -> ~1e-5 |
| 39 | + max_val - 23.0, # Corresponds to exp(a-max) -> ~1e-10 |
| 40 | + ] |
| 41 | + |
| 42 | + # 2. Create a background tensor filled with a very large negative number. |
| 43 | + background_val = -1000.0 |
| 44 | + a = paddle.full((B, D), background_val, dtype=dtype) |
| 45 | + |
| 46 | + # 3. Scatter these "trap" values at random positions in each row. |
| 47 | + for i in range(B): |
| 48 | + # Randomly shuffle the positions of the trap values for each row to increase non-determinism. |
| 49 | + indices = random.sample(range(D), k=len(trap_values)) |
| 50 | + for j, val in enumerate(trap_values): |
| 51 | + a[i, indices[j]] = val |
| 52 | + |
| 53 | + return a |
| 54 | + |
| 55 | + def test_batch_invariance(self, B: int = 2048, D: int = 4096, dtype=paddle.float32): |
| 56 | + a = self.create_softmax_trap_tensor(B, D, dtype) |
| 57 | + |
| 58 | + # Method 1: Matrix-vector multiplication (batch size 1) |
| 59 | + out1 = paddle.nn.functional.log_softmax(a[:1]) |
| 60 | + |
| 61 | + # Method 2: Matrix-matrix multiplication, then slice (full batch) |
| 62 | + out2 = paddle.nn.functional.log_softmax(a)[:1] |
| 63 | + |
| 64 | + # Check if results are identical |
| 65 | + diff = (out1 - out2).abs().max() |
| 66 | + return diff.item() == 0, diff |
| 67 | + |
| 68 | + def run_iters(self, iters=10, ass=False): |
| 69 | + for dtype in [paddle.float32, paddle.bfloat16, paddle.float16]: |
| 70 | + is_deterministic = True |
| 71 | + difflist = [] |
| 72 | + for i in range(iters): |
| 73 | + isd, df = self.test_batch_invariance(dtype=dtype) |
| 74 | + is_deterministic = is_deterministic and isd |
| 75 | + difflist.append(df) |
| 76 | + print( |
| 77 | + f"Batch Deterministic: {is_deterministic} run-to-run max/min/diff {max(difflist)}/{min(difflist)}/{max(difflist)-min(difflist)} for {dtype} in {iters} iterations" |
| 78 | + ) |
| 79 | + if ass: |
| 80 | + assert max(difflist) == 0 |
| 81 | + |
| 82 | + def test_case(self): |
| 83 | + # Test with standard Paddle (likely to show differences) |
| 84 | + print("Standard Paddle:") |
| 85 | + with set_batch_invariant_mode(False): |
| 86 | + self.run_iters(ass=False) |
| 87 | + # Test with batch-invariant operations |
| 88 | + print("\nBatch-Invariant Mode:") |
| 89 | + with set_batch_invariant_mode(True): |
| 90 | + self.run_iters(ass=True) |
| 91 | + |
| 92 | + |
| 93 | +if __name__ == "__main__": |
| 94 | + unittest.main() |
| 95 | + """ |
| 96 | + Even in Standard Paddle, we can achieve deterministic results, so maybe the standard implementation is already batch-invariant? |
| 97 | +
|
| 98 | + Result: |
| 99 | +
|
| 100 | + Standard Paddle: |
| 101 | + Batch Deterministic: True run-to-run max/min/diff 0.0/0.0/0.0 for paddle.float32 in 10 iterations |
| 102 | + Batch Deterministic: True run-to-run max/min/diff 0.0/0.0/0.0 for paddle.bfloat16 in 10 iterations |
| 103 | + Batch Deterministic: True run-to-run max/min/diff 0.0/0.0/0.0 for paddle.float16 in 10 iterations |
| 104 | +
|
| 105 | + Batch-Invariant Mode: |
| 106 | + Batch Deterministic: True run-to-run max/min/diff 0.0/0.0/0.0 for paddle.float32 in 10 iterations |
| 107 | + Batch Deterministic: True run-to-run max/min/diff 0.0/0.0/0.0 for paddle.bfloat16 in 10 iterations |
| 108 | + Batch Deterministic: True run-to-run max/min/diff 0.0/0.0/0.0 for paddle.float16 in 10 iterations |
| 109 | + """ |
0 commit comments