File size: 5,372 Bytes
a7c2243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Integration tests for MoE implementation.

These tests verify cross-module contracts between:
- Modules (moe_modules.py)
- Losses (moe_loss.py)
- Transformer (transformer_2501.py)
"""

import pytest
import torch

from nemo.collections.tts.losses.moe_loss import MoEAuxiliaryLoss
from nemo.collections.tts.modules.moe_modules import PositionwiseConvFFMoE
from nemo.collections.tts.modules.transformer_2501 import Transformer, TransformerLayer


@pytest.mark.unit
class TestMoEIntegration:
    """Integration tests for MoE pipeline: modules, losses, and config handling."""

    def test_complete_moe_pipeline(self):
        """Test complete flow: Transformer -> routing_info -> Loss computation."""
        transformer = Transformer(
            n_layers=2,
            d_model=64,
            d_ffn=256,
            sa_n_heads=4,
            kernel_size=1,
            use_moe=True,
            num_experts=4,
            top_k_experts=2,
            router_jitter_noise=0.0,
            routing_strategy="top_k",
        )

        loss_module = MoEAuxiliaryLoss(
            num_experts=4,
            load_balancing_loss_scale=0.01,
            router_z_loss_scale=0.001,
        )

        x = torch.randn(2, 10, 64)
        x_mask = torch.ones(2, 10).bool()

        transformer.train()
        output_dict = transformer(x, x_mask)

        # Extract routing info
        moe_routing_info = output_dict['moe_routing_info']
        assert moe_routing_info is not None
        assert len(moe_routing_info) == 2  # n_layers

        all_logits = torch.stack([info['router_logits'] for info in moe_routing_info], dim=0)
        all_probs = torch.stack([info['router_probs'] for info in moe_routing_info], dim=0)

        merged_logits = all_logits.view(-1, all_logits.size(2), all_logits.size(3))
        merged_probs = all_probs.view(-1, all_probs.size(2), all_probs.size(3))

        # Repeat mask for each layer (for mask-aware loss computation)
        n_layers = len(moe_routing_info)
        merged_mask = x_mask.unsqueeze(0).repeat(n_layers, 1, 1).view(-1, x_mask.size(1))

        load_balancing_loss, router_z_loss, total_loss = loss_module(
            router_logits=merged_logits, router_probs=merged_probs, x_mask=merged_mask
        )

        assert load_balancing_loss.item() >= 0
        assert router_z_loss.item() >= 0
        assert total_loss.item() >= 0

    def test_transformer_from_yaml_config(self):
        """Test creating Transformer from YAML-style config dict."""
        config_dict = {
            'n_layers': 2,
            'd_model': 64,
            'd_ffn': 256,
            'sa_n_heads': 4,
            'kernel_size': 1,
            'p_dropout': 0.0,
            'has_xattn': False,
            'is_causal': True,
            'use_moe': True,
            'num_experts': 4,
            'top_k_experts': 2,
            'router_jitter_noise': 0.0,
            'routing_strategy': 'top_k',
        }

        transformer = Transformer(**config_dict)
        assert transformer.use_moe is True

    @pytest.mark.parametrize(
        "cls,kwargs",
        [
            (
                TransformerLayer,
                {
                    'd_model': 64,
                    'd_ffn': 256,
                    'sa_n_heads': 4,
                    'kernel_size': 1,
                    'p_dropout': 0.0,
                    'has_xattn': False,
                    'use_moe': True,
                    'num_experts': 4,
                    'top_k_experts': 2,
                    'router_load_balancing_loss_coeff': 0.01,
                },
            ),
            (
                Transformer,
                {
                    'n_layers': 2,
                    'd_model': 64,
                    'd_ffn': 256,
                    'sa_n_heads': 4,
                    'kernel_size': 1,
                    'use_moe': True,
                    'num_experts': 4,
                    'top_k_experts': 2,
                    'router_z_loss_coeff': 0.001,
                },
            ),
            (
                PositionwiseConvFFMoE,
                {
                    'd_model': 64,
                    'd_ffn': 256,
                    'p_dropout': 0.0,
                    'num_experts': 4,
                    'top_k_experts': 2,
                    'router_load_balancing_loss_coeff': 0.01,
                },
            ),
        ],
        ids=["TransformerLayer", "Transformer", "PositionwiseConvFFMoE"],
    )
    def test_loss_coefficients_rejected_by_modules(self, cls, kwargs):
        """Test that MoE modules reject loss coefficient parameters (they belong at model level)."""
        with pytest.raises(TypeError, match="unexpected keyword argument"):
            cls(**kwargs)