|
| 1 | +import pytest |
| 2 | + |
| 3 | +import torch |
| 4 | +from torch import nn |
| 5 | +from torch.nn import functional as F |
| 6 | + |
| 7 | +from torchao.quantization.quant_api import quantize_ |
| 8 | +from torchao.prototype.scaled_grouped_mm.conversion_utils import MoETrainingConfig |
| 9 | +from torchao.float8.float8_utils import compute_error |
| 10 | + |
| 11 | +# model definition from torchtitan: |
| 12 | +# https://github.com/pytorch/torchtitan/blob/768cde131105bde624160029d808e94649faf0f4/torchtitan/experiments/llama4/model/moe.py#L14 |
| 13 | +class GroupedExperts(nn.Module): |
| 14 | + def __init__( |
| 15 | + self, |
| 16 | + dim: int, |
| 17 | + hidden_dim: int, |
| 18 | + num_experts: int, |
| 19 | + use_grouped_mm: bool, |
| 20 | + ): |
| 21 | + super().__init__() |
| 22 | + self.num_experts = num_experts |
| 23 | + self.w1 = nn.Parameter(torch.empty(num_experts, dim, hidden_dim)) |
| 24 | + self.w2 = nn.Parameter(torch.empty(num_experts, hidden_dim, dim)) |
| 25 | + self.w3 = nn.Parameter(torch.empty(num_experts, dim, hidden_dim)) |
| 26 | + self.use_grouped_mm = use_grouped_mm |
| 27 | + self.init_weights() |
| 28 | + |
| 29 | + def forward( |
| 30 | + self, |
| 31 | + x: torch.Tensor, |
| 32 | + num_local_tokens_per_expert: torch.Tensor | list[int] | None = None, |
| 33 | + ) -> torch.Tensor: |
| 34 | + # TODO: keeping this for loop implementation for comparison |
| 35 | + # and readability, will remove later |
| 36 | + if not self.use_grouped_mm: |
| 37 | + if num_local_tokens_per_expert is not None: |
| 38 | + # a tuple of tensors indexed by experts |
| 39 | + # each with shape (tokens_per_expert(varying), dim) |
| 40 | + x = torch.split( |
| 41 | + x, |
| 42 | + split_size_or_sections=num_local_tokens_per_expert, |
| 43 | + dim=0, |
| 44 | + ) |
| 45 | + out_experts_splits = [] |
| 46 | + for expert_idx, x_expert in enumerate(x): |
| 47 | + w1, w2, w3 = ( |
| 48 | + self.w1[expert_idx], |
| 49 | + self.w2[expert_idx], |
| 50 | + self.w3[expert_idx], |
| 51 | + ) |
| 52 | + h = F.silu(torch.matmul(x_expert, w1)) |
| 53 | + h = h * torch.matmul(x_expert, w3) |
| 54 | + h = torch.matmul(h, w2) |
| 55 | + # h shape (tokens_per_expert(varying), dim) |
| 56 | + out_experts_splits.append(h) |
| 57 | + out = torch.cat(out_experts_splits, dim=0) |
| 58 | + else: |
| 59 | + # x shape (num_experts, tokens_per_expert, dim) |
| 60 | + h = F.silu(torch.bmm(x, self.w1)) |
| 61 | + h = h * torch.bmm(x, self.w3) |
| 62 | + # out shape (num_experts, tokens_per_expert, dim) |
| 63 | + out = torch.bmm(h, self.w2) |
| 64 | + |
| 65 | + return out |
| 66 | + |
| 67 | + # grouped mm implementation |
| 68 | + if num_local_tokens_per_expert is not None: |
| 69 | + # https://github.com/pytorch/pytorch/pull/150374 |
| 70 | + # NOTE: torch._gouped_mm requires bf16 dtypes |
| 71 | + # and shapes to be multiple of 8 |
| 72 | + offsets = torch.cumsum( |
| 73 | + num_local_tokens_per_expert, dim=0, dtype=torch.int32 |
| 74 | + ) |
| 75 | + # grouped mm between a 2D tensor and a 3D tensor |
| 76 | + assert x.dim() == 2 |
| 77 | + else: |
| 78 | + offsets = None |
| 79 | + # fall back to regular bmm between 3D tensors |
| 80 | + assert x.dim() == 3 |
| 81 | + |
| 82 | + assert ( |
| 83 | + x.dtype == self.w1.dtype == self.w2.dtype == self.w3.dtype == torch.bfloat16 |
| 84 | + ), "torch._grouped_mm only supports bf16 dtypes" |
| 85 | + |
| 86 | + h = F.silu(torch._grouped_mm(x, self.w1, offs=offsets)) |
| 87 | + h = h * torch._grouped_mm(x, self.w3, offs=offsets) |
| 88 | + out = torch._grouped_mm(h, self.w2, offs=offsets) |
| 89 | + |
| 90 | + return out |
| 91 | + |
| 92 | + def init_weights(self, init_std: float = 0.02): |
| 93 | + nn.init.trunc_normal_(self.w1, mean=0.0, std=0.02) |
| 94 | + nn.init.trunc_normal_(self.w2, mean=0.0, std=init_std) |
| 95 | + nn.init.trunc_normal_(self.w3, mean=0.0, std=init_std) |
| 96 | + |
| 97 | +class MoE(nn.Module): |
| 98 | + """Toy MoE for testing. Not a complete implementation.""" |
| 99 | + def __init__(self, |
| 100 | + dim: int, |
| 101 | + hidden_dim: int, |
| 102 | + num_experts: int, |
| 103 | + use_grouped_mm: bool |
| 104 | + ): |
| 105 | + super().__init__() |
| 106 | + self.gate = nn.Linear(dim, num_experts) |
| 107 | + self.experts = GroupedExperts( |
| 108 | + dim, |
| 109 | + hidden_dim, |
| 110 | + num_experts, |
| 111 | + use_grouped_mm, |
| 112 | + ) |
| 113 | + self.init_weights() |
| 114 | + |
| 115 | + def forward(self, x: torch.Tensor, num_local_tokens_per_expert: torch.Tensor) -> torch.Tensor: |
| 116 | + return self.experts(x, num_local_tokens_per_expert=num_local_tokens_per_expert) |
| 117 | + |
| 118 | + def init_weights(self, init_std: float = 0.02): |
| 119 | + nn.init.trunc_normal_(self.gate.weight, mean=0.0, std=init_std) |
| 120 | + |
| 121 | +@pytest.mark.parametrize( |
| 122 | + "model_class,target_fqns", [ |
| 123 | + # (MoE, ["experts"]), # calling quantize_ on higher level module |
| 124 | + (GroupedExperts, [""]), # calling quantize_ on experts directly |
| 125 | + ]) |
| 126 | +def test_moe_float8_training(model_class: nn.Module, target_fqns: list[str]): |
| 127 | + batch, seq, dim = 1, 8192, 4096 |
| 128 | + num_experts, top_k = 2, 1 |
| 129 | + |
| 130 | + def moe_module_filter_fn(mod: nn.Module, cur_fqn: str) -> bool: |
| 131 | + for target_fqn in target_fqns: |
| 132 | + if target_fqn in cur_fqn: |
| 133 | + return True |
| 134 | + return False |
| 135 | + |
| 136 | + # define MoE layer |
| 137 | + torch.manual_seed(42) |
| 138 | + model = model_class(dim=dim, hidden_dim=4*dim, num_experts=num_experts, use_grouped_mm=True).to(torch.bfloat16).cuda() |
| 139 | + torch.manual_seed(42) |
| 140 | + ref_model = model_class(dim=dim, hidden_dim=4*dim, num_experts=num_experts, use_grouped_mm=True).to(torch.bfloat16).cuda() |
| 141 | + for param1, param2 in zip(model.parameters(), ref_model.parameters()): |
| 142 | + assert torch.equal(param1, param2) |
| 143 | + |
| 144 | + # convert MoE to float8 training |
| 145 | + config = MoETrainingConfig() |
| 146 | + quantize_(model, config=config, filter_fn=moe_module_filter_fn) |
| 147 | + |
| 148 | + # inputs |
| 149 | + torch.manual_seed(42) |
| 150 | + x = torch.randn(batch*seq*top_k, dim, dtype=torch.bfloat16, requires_grad=True).cuda() |
| 151 | + torch.manual_seed(42) |
| 152 | + ref_x = torch.randn(batch*seq*top_k, dim, dtype=torch.bfloat16, requires_grad=True).cuda() |
| 153 | + |
| 154 | + # offsets |
| 155 | + num_tokens_per_expert = (batch * seq * top_k) // num_experts |
| 156 | + tokens_per_expert_tensor = torch.tensor([num_tokens_per_expert], dtype=torch.int32).repeat(num_experts).cuda() |
| 157 | + ref_tokens_per_expert_tensor = tokens_per_expert_tensor.clone() |
| 158 | + |
| 159 | + # forward pass |
| 160 | + out = model(x, num_local_tokens_per_expert=tokens_per_expert_tensor) |
| 161 | + ref_out = ref_model(ref_x, num_local_tokens_per_expert=ref_tokens_per_expert_tensor) |
| 162 | + |
| 163 | + # validate SQNR is acceptable. |
| 164 | + # a single fp8 gemm uses SQNR >= 25.0 for testing, so for a full MoE layer |
| 165 | + # we'll use a slightly lower threshold. |
| 166 | + out_sqnr = compute_error(out, ref_out) |
| 167 | + assert out_sqnr.item() >= 23.0, f"SQNR must be >= 23.0, got {out_sqnr.item()}." |
| 168 | + |
| 169 | + # backward pass |
| 170 | + out.sum().backward() |
| 171 | + ref_out.sum().backward() |
| 172 | + |
| 173 | + # validate input gradients |
| 174 | + assert torch.allclose(x.grad, ref_x.grad) |
| 175 | + |
| 176 | + # validate param gradients |
| 177 | + for param1, param2 in zip(model.parameters(), ref_model.parameters()): |
| 178 | + assert torch.allclose(param1.grad, param2.grad) |
0 commit comments