|
| 1 | +import pytest |
| 2 | +import torch |
| 3 | +import torch.distributed as dist |
| 4 | +import torch.multiprocessing as mp |
| 5 | +import os |
| 6 | +from typing import cast |
| 7 | + |
| 8 | +from clt.config import CLTConfig |
| 9 | +from clt.models.clt import CrossLayerTranscoder |
| 10 | + |
| 11 | + |
| 12 | +def setup_distributed_environment(rank, world_size, port="12356"): |
| 13 | + """Initializes the distributed process group.""" |
| 14 | + os.environ["MASTER_ADDR"] = "localhost" |
| 15 | + os.environ["MASTER_PORT"] = port |
| 16 | + dist.init_process_group("gloo", rank=rank, world_size=world_size) |
| 17 | + |
| 18 | + |
| 19 | +def cleanup_distributed_environment(): |
| 20 | + """Cleans up the distributed process group.""" |
| 21 | + dist.destroy_process_group() |
| 22 | + |
| 23 | + |
| 24 | +def distributed_test_runner(rank, world_size, test_fn, *args): |
| 25 | + """A wrapper to run a distributed test function.""" |
| 26 | + setup_distributed_environment(rank, world_size) |
| 27 | + try: |
| 28 | + test_fn(rank, world_size, *args) |
| 29 | + finally: |
| 30 | + cleanup_distributed_environment() |
| 31 | + |
| 32 | + |
| 33 | +# --- Test Functions (to be run in separate processes) --- |
| 34 | + |
| 35 | + |
| 36 | +def _test_forward_pass_distributed(rank, world_size): |
| 37 | + """ |
| 38 | + Tests that the forward pass produces identical results on all ranks. |
| 39 | + """ |
| 40 | + device = torch.device("cpu") |
| 41 | + torch.manual_seed(42) # Ensure same model initialization |
| 42 | + |
| 43 | + clt_config = CLTConfig(num_layers=2, d_model=8, num_features=16, activation_fn="relu") |
| 44 | + model = CrossLayerTranscoder(config=clt_config, process_group=dist.group.WORLD, device=device) |
| 45 | + |
| 46 | + # All ranks get the same input |
| 47 | + torch.manual_seed(123) |
| 48 | + sample_inputs = { |
| 49 | + 0: torch.randn(20, clt_config.d_model, device=device), |
| 50 | + 1: torch.randn(20, clt_config.d_model, device=device), |
| 51 | + } |
| 52 | + |
| 53 | + reconstructions = model.forward(sample_inputs) |
| 54 | + loss = torch.mean(reconstructions[0]) # A simple, deterministic loss |
| 55 | + |
| 56 | + # Gather the loss from all ranks |
| 57 | + loss_list = [torch.zeros_like(loss) for _ in range(world_size)] |
| 58 | + dist.all_gather(loss_list, loss) |
| 59 | + |
| 60 | + # The loss, and therefore the forward pass result, should be identical on all ranks |
| 61 | + for other_loss in loss_list: |
| 62 | + assert torch.allclose(loss, other_loss), "Forward pass results (losses) differ across ranks" |
| 63 | + |
| 64 | + |
| 65 | +def _test_sharded_gradient(rank, world_size): |
| 66 | + """ |
| 67 | + Tests that sharded parameters receive different gradients on each rank. |
| 68 | + """ |
| 69 | + device = torch.device("cpu") |
| 70 | + # Use rank-specific seed for weight initialization to ensure different weights |
| 71 | + torch.manual_seed(42 + rank) |
| 72 | + |
| 73 | + clt_config = CLTConfig(num_layers=2, d_model=8, num_features=16, activation_fn="relu") |
| 74 | + model = CrossLayerTranscoder(config=clt_config, process_group=dist.group.WORLD, device=device) |
| 75 | + |
| 76 | + # All ranks get the same input |
| 77 | + torch.manual_seed(123) |
| 78 | + sample_inputs = {0: torch.randn(5, clt_config.d_model, device=device)} |
| 79 | + |
| 80 | + # Forward pass |
| 81 | + reconstructions = model.forward(sample_inputs) |
| 82 | + |
| 83 | + # Create a loss that depends on the actual output values |
| 84 | + # This will produce different gradients for different weight values |
| 85 | + target = torch.randn_like(reconstructions[0]) |
| 86 | + loss = torch.nn.functional.mse_loss(reconstructions[0], target) |
| 87 | + |
| 88 | + # Backward pass |
| 89 | + loss.backward() |
| 90 | + |
| 91 | + # Test gradients of a SHARDED parameter (e.g., Encoder weights) |
| 92 | + sharded_grad_optional = model.encoder_module.encoders[0].weight.grad |
| 93 | + assert sharded_grad_optional is not None, "Gradient for sharded parameter should exist" |
| 94 | + sharded_grad = cast(torch.Tensor, sharded_grad_optional) |
| 95 | + |
| 96 | + # Gather all gradients to compare |
| 97 | + grad_list = [torch.zeros_like(sharded_grad) for _ in range(world_size)] |
| 98 | + dist.all_gather(grad_list, sharded_grad) |
| 99 | + |
| 100 | + # The gradients for a sharded parameter should be DIFFERENT on each rank |
| 101 | + # because each rank has different weights and computes different outputs |
| 102 | + assert not torch.allclose( |
| 103 | + grad_list[0], grad_list[1], rtol=1e-5, atol=1e-8 |
| 104 | + ), "Gradients for sharded parameters should be different across ranks" |
| 105 | + |
| 106 | + |
| 107 | +# --- Pytest Test Class --- |
| 108 | + |
| 109 | + |
| 110 | +@pytest.mark.integration |
| 111 | +@pytest.mark.distributed |
| 112 | +@pytest.mark.skipif(not dist.is_available(), reason="torch.distributed not available") |
| 113 | +class TestCLTDistributed: |
| 114 | + def test_forward_pass(self): |
| 115 | + world_size = 2 |
| 116 | + mp.spawn( # type: ignore[attr-defined] |
| 117 | + distributed_test_runner, |
| 118 | + args=(world_size, _test_forward_pass_distributed), |
| 119 | + nprocs=world_size, |
| 120 | + join=True, |
| 121 | + ) |
| 122 | + |
| 123 | + def test_gradient_sharding(self): |
| 124 | + world_size = 2 |
| 125 | + mp.spawn( # type: ignore[attr-defined] |
| 126 | + distributed_test_runner, |
| 127 | + args=(world_size, _test_sharded_gradient), |
| 128 | + nprocs=world_size, |
| 129 | + join=True, |
| 130 | + ) |
0 commit comments