main
py 249 lines 8.81 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4 from types import SimpleNamespace
5
6 import pytest
7 import torch
8
9 from vllm.lora.utils import get_supported_lora_modules
10 from vllm.model_executor.layers.quantization.modelopt import ModelOptNvFp4Config
11 from vllm.models.inkling.nvidia import moe
12 from vllm.models.inkling.nvidia.model import _TmlForCausalLMBase
13 from vllm.platforms import current_platform
14
15
16 def test_gate_loads_directly_into_padded_runtime_weight() -> None:
17 gate = moe.InklingGate(
18 d_model=4,
19 n_routed_experts=5,
20 n_shared_experts=2,
21 experts_per_token=2,
22 route_scale=1.0,
23 )
24 loaded = torch.arange(28, dtype=gate.weight.dtype).reshape(7, 4)
25
26 gate.weight.weight_loader(gate.weight, loaded)
27
28 assert gate.weight.shape == (8, 4)
29 torch.testing.assert_close(gate.weight[:7], loaded)
30 torch.testing.assert_close(gate.weight[7], torch.zeros(4))
31
32
33 @pytest.mark.skipif(not current_platform.is_cuda(), reason="requires CUDA")
34 @pytest.mark.parametrize(("num_tokens", "expected_calls"), [(1, 1), (64, 1), (65, 0)])
35 def test_gate_uses_ll_bf16_gemm_through_token_limit(
36 monkeypatch, num_tokens, expected_calls
37 ) -> None:
38 gate = moe.InklingGate(
39 d_model=8,
40 n_routed_experts=5,
41 n_shared_experts=2,
42 experts_per_token=2,
43 route_scale=1.0,
44 ).to(device="cuda", dtype=torch.bfloat16)
45 hidden_states = torch.randn(num_tokens, 8, device="cuda", dtype=torch.bfloat16)
46 calls = []
47
48 def fake_ll_bf16_gemm(x, weight):
49 calls.append((x, weight))
50 return torch.ones(num_tokens, 8, device="cuda", dtype=torch.float32)
51
52 monkeypatch.setattr(
53 moe.current_platform, "has_device_capability", lambda capability: True
54 )
55 monkeypatch.setattr(moe.ll_bf16, "is_available", lambda: True)
56 monkeypatch.setattr(moe.ll_bf16, "ll_bf16_gemm", fake_ll_bf16_gemm)
57
58 logits = gate.compute_logits(hidden_states)
59
60 assert len(calls) == expected_calls
61 if calls:
62 assert calls[0][0] is hidden_states
63 assert calls[0][1] is gate.weight
64 assert logits.shape == (num_tokens, 8)
65 assert logits.dtype == torch.float32
66
67
68 def test_gate_is_not_a_lora_target() -> None:
69 model = torch.nn.Module()
70 model.gate = moe.InklingGate(
71 d_model=4,
72 n_routed_experts=5,
73 n_shared_experts=2,
74 experts_per_token=2,
75 route_scale=1.0,
76 )
77
78 assert "gate" not in get_supported_lora_modules(model)
79
80
81 def test_custom_embedding_is_not_a_lora_target() -> None:
82 model = torch.nn.Module()
83 model.embedding_modules = _TmlForCausalLMBase.embedding_modules
84
85 supported = get_supported_lora_modules(model)
86
87 assert "embed_tokens" not in supported
88 assert "lm_head" in supported
89
90
91 def test_inkling_mapper_maps_modelopt_exclusions() -> None:
92 quant_config = ModelOptNvFp4Config.from_config(
93 {
94 "quantization": {
95 "quant_algo": "NVFP4",
96 "group_size": 16,
97 "kv_cache_quant_algo": None,
98 "exclude_modules": [
99 "model.llm.layers.2.mlp.experts",
100 "model.llm.layers.2.mlp.shared_experts",
101 ],
102 }
103 }
104 )
105
106 quant_config.apply_vllm_mapper(
107 _TmlForCausalLMBase.hf_to_vllm_mapper.get_rename_mapper()
108 )
109
110 assert quant_config.is_layer_excluded("model.layers.2.mlp.experts")
111 assert quant_config.is_layer_excluded("model.layers.2.mlp.shared_experts")
112 assert not quant_config.is_layer_excluded("model.layers.3.mlp.experts")
113
114
115 @pytest.mark.parametrize("projection", ["w13", "w2"])
116 @pytest.mark.parametrize("nested", [False, True])
117 @pytest.mark.parametrize(
118 "suffix",
119 [
120 "input_global_scale",
121 "weight_global_scale",
122 "weight_packed",
123 "weight_scale",
124 ],
125 )
126 def test_inkling_mapper_maps_compressed_tensors_expert_params(
127 projection: str, suffix: str, nested: bool
128 ) -> None:
129 projection_param = (
130 f"{projection}_weight.{suffix}" if nested else f"{projection}_{suffix}"
131 )
132 source = f"model.llm.layers.2.mlp.experts.{projection_param}"
133
134 mapped = _TmlForCausalLMBase.hf_to_vllm_mapper.apply_list([source])
135
136 assert mapped == [f"model.layers.2.mlp.experts.{projection}_{suffix}"]
137
138
139 @pytest.mark.parametrize(("projection", "amax"), [("w13", 4.375), ("w2", 2960.0)])
140 def test_moe_loads_calibrated_input_scale(projection: str, amax: float) -> None:
141 experts = SimpleNamespace(
142 w13_input_scale=torch.nn.Parameter(torch.empty(3, 2)),
143 w2_input_scale=torch.nn.Parameter(torch.empty(3)),
144 )
145 layer = SimpleNamespace(experts=SimpleNamespace(routed_experts=experts))
146
147 loaded = moe.InklingMoE.load_expert_weight(
148 layer,
149 f"experts.{projection}_weight.input_amax",
150 torch.tensor([amax]),
151 )
152
153 scale = getattr(experts, f"{projection}_input_scale")
154 expected = torch.full_like(scale, amax / (448.0 * 6.0))
155 torch.testing.assert_close(scale, expected)
156 assert loaded == [f"experts.routed_experts.{projection}_input_scale"]
157
158
159 @pytest.mark.parametrize("projection", ["w13", "w2"])
160 @pytest.mark.parametrize("scale_kind", ["input", "weight"])
161 def test_moe_loads_compressed_tensors_global_scale(
162 projection: str, scale_kind: str
163 ) -> None:
164 param = torch.nn.Parameter(torch.empty(3, 2 if projection == "w13" else 1))
165 if projection == "w2":
166 param = torch.nn.Parameter(param.squeeze(1))
167 experts = SimpleNamespace(
168 **{f"{projection}_{scale_kind}_global_scale": param},
169 moe_config=SimpleNamespace(moe_parallel_config=SimpleNamespace(tp_rank=0)),
170 )
171 layer = SimpleNamespace(
172 experts=SimpleNamespace(routed_experts=experts),
173 _local_expert_slots=lambda: {0: 0, 1: 1, 2: 2},
174 )
175 checkpoint_scale = torch.tensor([[1.0], [2.0], [3.0]])
176
177 loaded = moe.InklingMoE.load_expert_weight(
178 layer,
179 f"experts.{projection}_{scale_kind}_global_scale",
180 checkpoint_scale,
181 )
182
183 expected = (
184 checkpoint_scale.expand_as(param) if param.ndim == 2 else checkpoint_scale[:, 0]
185 )
186 torch.testing.assert_close(param, expected)
187 assert loaded == [f"experts.routed_experts.{projection}_{scale_kind}_global_scale"]
188
189
190 @pytest.mark.parametrize(("projection", "checkpoint_rows"), [("w13", 8), ("w2", 4)])
191 def test_moe_loads_channelwise_scale_for_tp(
192 projection: str, checkpoint_rows: int
193 ) -> None:
194 param = torch.nn.Parameter(torch.empty(2, 4, 1))
195 experts = SimpleNamespace(
196 **{f"{projection}_weight_scale": param},
197 moe_config=SimpleNamespace(moe_parallel_config=SimpleNamespace(tp_rank=1)),
198 )
199 layer = SimpleNamespace(
200 experts=SimpleNamespace(routed_experts=experts),
201 _local_expert_slots=lambda: {0: 0, 2: 1},
202 )
203 checkpoint_scale = torch.arange(3 * checkpoint_rows).reshape(3, checkpoint_rows, 1)
204
205 loaded = moe.InklingMoE.load_expert_weight(
206 layer, f"experts.{projection}_weight_scale", checkpoint_scale
207 )
208
209 expected = checkpoint_scale[[0, 2]]
210 if projection == "w13":
211 expected = expected[:, 4:].reshape(2, 2, 2, 1).transpose(1, 2).flatten(1, 2)
212 torch.testing.assert_close(param, expected.float())
213 assert loaded == [f"experts.routed_experts.{projection}_weight_scale"]
214
215
216 def test_sink_down_projection_is_packed_during_load(monkeypatch) -> None:
217 monkeypatch.setattr(moe, "get_tensor_model_parallel_world_size", lambda: 2)
218 monkeypatch.setattr(moe, "get_tensor_model_parallel_rank", lambda: 1)
219 sink = moe.InklingSinkExperts(n_experts=2, d_model=3, d_mlp=8)
220 loaded = torch.arange(48, dtype=sink.w2_weight.dtype).reshape(2, 3, 8)
221
222 sink.load_weight("w2_weight", loaded)
223
224 expected = loaded[:, :, 4:].permute(1, 0, 2).reshape(3, 8)
225 torch.testing.assert_close(sink.w2_weight, expected)
226
227
228 @pytest.mark.skipif(not current_platform.is_cuda(), reason="requires CUDA")
229 def test_sink_packed_weight_forward_matches_expert_sum(monkeypatch) -> None:
230 monkeypatch.setattr(moe, "get_tensor_model_parallel_world_size", lambda: 2)
231 monkeypatch.setattr(moe, "get_tensor_model_parallel_rank", lambda: 1)
232 sink = moe.InklingSinkExperts(n_experts=2, d_model=3, d_mlp=8).to(
233 device="cuda", dtype=torch.bfloat16
234 )
235 torch.manual_seed(1)
236 w13 = torch.randn(2, 16, 3, dtype=torch.bfloat16)
237 w2 = torch.randn(2, 3, 8, dtype=torch.bfloat16)
238 sink.load_weight("w13_weight", w13)
239 sink.load_weight("w2_weight", w2)
240 x = torch.randn(5, 3, device="cuda", dtype=torch.bfloat16)
241 gammas = torch.randn(5, 2, device="cuda")
242
243 output = sink(x, gammas)
244
245 raw = torch.einsum("td,efd->tef", x, w13[:, 8:].to("cuda"))
246 hidden = torch.nn.functional.silu(raw[:, :, 0::2].float())
247 hidden = (hidden * raw[:, :, 1::2] * gammas[:, :, None]).to(torch.bfloat16)
248 expected = torch.einsum("tef,edf->td", hidden, w2[:, :, 4:].to("cuda"))
249 torch.testing.assert_close(output, expected, rtol=0, atol=0)