|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +import unittest |
| 8 | + |
| 9 | +import torch |
| 10 | +import torch.nn as nn |
| 11 | + |
| 12 | +from torchtitan.config.job_config import Compile as CompileConfig |
| 13 | +from torchtitan.models.llama4.infra.parallelize import apply_compile |
| 14 | + |
| 15 | + |
| 16 | +class TransformerBlock(nn.Module): |
| 17 | + def __init__(self, dim=512): |
| 18 | + super().__init__() |
| 19 | + self.attention = nn.Linear(dim, dim, bias=False) |
| 20 | + self.mlp = nn.Linear(dim, dim, bias=False) |
| 21 | + self.moe_enabled = False |
| 22 | + |
| 23 | + def forward(self, x): |
| 24 | + x = self.attention(x) |
| 25 | + x = self.mlp(x) |
| 26 | + return x |
| 27 | + |
| 28 | + |
| 29 | +class TinyModel(nn.Module): |
| 30 | + def __init__(self, num_layers=2, dim=512): |
| 31 | + super().__init__() |
| 32 | + self.layers = nn.ModuleDict( |
| 33 | + {str(i): TransformerBlock(dim) for i in range(num_layers)} |
| 34 | + ) |
| 35 | + |
| 36 | + def forward(self, x): |
| 37 | + for layer in self.layers.values(): |
| 38 | + x = layer(x) |
| 39 | + return x |
| 40 | + |
| 41 | + |
| 42 | +class TestApplyCompile(unittest.TestCase): |
| 43 | + def test_patched_once(self): |
| 44 | + """ |
| 45 | + Calls apply_compile multiple times, as in the case with PP. |
| 46 | + But patches should only happen once |
| 47 | + """ |
| 48 | + unused_model1 = TinyModel(num_layers=2, dim=128) |
| 49 | + unused_model2 = TinyModel(num_layers=2, dim=128) |
| 50 | + compile_config = CompileConfig(backend="eager") |
| 51 | + |
| 52 | + apply_compile(unused_model1, compile_config, ep_enabled=True) |
| 53 | + apply_compile(unused_model2, compile_config, ep_enabled=True) |
| 54 | + |
| 55 | + from torchtitan.models.moe import moe as moe_module |
| 56 | + |
| 57 | + # Generate sample inputs for _run_experts_grouped_mm |
| 58 | + num_experts = 8 |
| 59 | + dim = 128 |
| 60 | + hidden_dim = 256 |
| 61 | + w1 = torch.randn(num_experts, hidden_dim, dim) |
| 62 | + w2 = torch.randn(num_experts, dim, hidden_dim) |
| 63 | + w3 = torch.randn(num_experts, hidden_dim, dim) |
| 64 | + num_tokens_per_expert = torch.tensor([10, 8, 12, 9, 11, 7, 10, 13], dtype=torch.int32) |
| 65 | + total_tokens = num_tokens_per_expert.sum().item() |
| 66 | + x = torch.randn(total_tokens, dim) |
| 67 | + |
| 68 | + # Call the function, should not error |
| 69 | + output = moe_module._run_experts_grouped_mm(w1, w2, w3, x, num_tokens_per_expert) |
| 70 | + |
| 71 | + print(f"Input shape: {x.shape}") |
| 72 | + print(f"Output shape: {output.shape}") |
| 73 | + print(f"Num tokens per expert: {num_tokens_per_expert}") |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == "__main__": |
| 77 | + unittest.main() |
0 commit comments