Upload 9 files
Browse files- config.json +1 -0
 - configuration_moe_plus_plus.py +104 -0
 - generation_config.json +1 -0
 - modeling_moe_plus_plus.py +960 -0
 - moe_plus_plus_layer.py +224 -0
 - pytorch_model.bin.index.json +0 -0
 - special_tokens_map.json +1 -0
 - tokenizer.model +3 -0
 - tokenizer_config.json +1 -0
 
    	
        config.json
    ADDED
    
    | 
         @@ -0,0 +1 @@ 
     | 
|
| 
         | 
| 
         | 
|
| 1 | 
         
            +
            {"architectures": ["MoeForCausalLM"], "auto_map": {"AutoConfig": "configuration_moe_plus_plus.MoeConfig", "AutoModelForCausalLM": "modeling_moe_plus_plus.MoeForCausalLM"}, "model_type": "MoE++", "vocab_size": 65536, "bos_token_id": 1, "eos_token_id": 2, "pad_token_id": 0, "hidden_act": "silu", "hidden_size": 1536, "initializer_range": 0.01, "intermediate_size": 4096, "max_position_embeddings": 2048, "num_attention_heads": 16, "num_key_value_heads": 16, "num_hidden_layers": 24, "num_experts": [20], "moe_use_mixtral_gating": false, "moe_2layer_gate": false, "moe_use_logits_norm": true, "moe_gate_norm_std": 1.0, "moe_feature_no_mul_topk": true, "sliding_window": null, "moe_expert_interval": 1, "rms_norm_eps": 1e-06, "rotary_percent": 1.0, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "use_cache": true, "transformers_version": "4.33.1", "rope_theta": 10000}
         
     | 
    	
        configuration_moe_plus_plus.py
    ADDED
    
    | 
         @@ -0,0 +1,104 @@ 
     | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
| 
         | 
|
| 1 | 
         
            +
            # Copyright (c) SkyworkAI and the HuggingFace Inc. team. All rights reserved.
         
     | 
| 2 | 
         
            +
            # This code is built upon Huggingface's transformers repository.
         
     | 
| 3 | 
         
            +
             
     | 
| 4 | 
         
            +
             
     | 
| 5 | 
         
            +
            from transformers.configuration_utils import PretrainedConfig
         
     | 
| 6 | 
         
            +
            from transformers.utils import logging
         
     | 
| 7 | 
         
            +
             
     | 
| 8 | 
         
            +
             
     | 
| 9 | 
         
            +
            logger = logging.get_logger(__name__)
         
     | 
| 10 | 
         
            +
             
     | 
| 11 | 
         
            +
            LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
         
     | 
| 12 | 
         
            +
             
     | 
| 13 | 
         
            +
             
     | 
| 14 | 
         
            +
            class MoeConfig(PretrainedConfig):
         
     | 
| 15 | 
         
            +
             
     | 
| 16 | 
         
            +
                model_type = "MoE++"
         
     | 
| 17 | 
         
            +
                keys_to_ignore_at_inference = ["past_key_values"]
         
     | 
| 18 | 
         
            +
             
     | 
| 19 | 
         
            +
                def __init__(
         
     | 
| 20 | 
         
            +
                    self,
         
     | 
| 21 | 
         
            +
                    vocab_size=32000,
         
     | 
| 22 | 
         
            +
                    hidden_size=4096,
         
     | 
| 23 | 
         
            +
                    intermediate_size=11008,
         
     | 
| 24 | 
         
            +
                    num_hidden_layers=32,
         
     | 
| 25 | 
         
            +
                    num_attention_heads=32,
         
     | 
| 26 | 
         
            +
                    num_key_value_heads=None,
         
     | 
| 27 | 
         
            +
                    hidden_act="silu",
         
     | 
| 28 | 
         
            +
                    max_position_embeddings=2048,
         
     | 
| 29 | 
         
            +
                    initializer_range=0.02,
         
     | 
| 30 | 
         
            +
                    rms_norm_eps=1e-6,
         
     | 
| 31 | 
         
            +
                    use_cache=True,
         
     | 
| 32 | 
         
            +
                    pad_token_id=None,
         
     | 
| 33 | 
         
            +
                    bos_token_id=1,
         
     | 
| 34 | 
         
            +
                    eos_token_id=2,
         
     | 
| 35 | 
         
            +
                    pretraining_tp=1,
         
     | 
| 36 | 
         
            +
                    tie_word_embeddings=False,
         
     | 
| 37 | 
         
            +
                    rope_theta=10000.0,
         
     | 
| 38 | 
         
            +
                    rope_scaling=None,
         
     | 
| 39 | 
         
            +
                    num_experts=[32],
         
     | 
| 40 | 
         
            +
                    moe_expert_interval=1,
         
     | 
| 41 | 
         
            +
                    moe_use_mixtral_gating=False,
         
     | 
| 42 | 
         
            +
                    moe_2layer_gate=True,
         
     | 
| 43 | 
         
            +
                    moe_use_logits_norm=False,
         
     | 
| 44 | 
         
            +
                    moe_gate_norm_std=1.0,
         
     | 
| 45 | 
         
            +
                    moe_feature_no_mul_topk=False,
         
     | 
| 46 | 
         
            +
                    
         
     | 
| 47 | 
         
            +
                    **kwargs,
         
     | 
| 48 | 
         
            +
                ):
         
     | 
| 49 | 
         
            +
                    self.vocab_size = vocab_size
         
     | 
| 50 | 
         
            +
                    self.max_position_embeddings = max_position_embeddings
         
     | 
| 51 | 
         
            +
                    self.hidden_size = hidden_size
         
     | 
| 52 | 
         
            +
                    self.intermediate_size = intermediate_size
         
     | 
| 53 | 
         
            +
                    self.num_hidden_layers = num_hidden_layers
         
     | 
| 54 | 
         
            +
                    self.num_attention_heads = num_attention_heads
         
     | 
| 55 | 
         
            +
             
     | 
| 56 | 
         
            +
                    # for backward compatibility
         
     | 
| 57 | 
         
            +
                    if num_key_value_heads is None:
         
     | 
| 58 | 
         
            +
                        num_key_value_heads = num_attention_heads
         
     | 
| 59 | 
         
            +
             
     | 
| 60 | 
         
            +
                    self.num_key_value_heads = num_key_value_heads
         
     | 
| 61 | 
         
            +
                    self.hidden_act = hidden_act
         
     | 
| 62 | 
         
            +
                    self.initializer_range = initializer_range
         
     | 
| 63 | 
         
            +
                    self.rms_norm_eps = rms_norm_eps
         
     | 
| 64 | 
         
            +
                    self.pretraining_tp = pretraining_tp
         
     | 
| 65 | 
         
            +
                    self.use_cache = use_cache
         
     | 
| 66 | 
         
            +
                    self.rope_theta = rope_theta
         
     | 
| 67 | 
         
            +
                    self.rope_scaling = rope_scaling
         
     | 
| 68 | 
         
            +
                    self._rope_scaling_validation()
         
     | 
| 69 | 
         
            +
                    self.num_experts = num_experts
         
     | 
| 70 | 
         
            +
                    self.moe_expert_interval = moe_expert_interval
         
     | 
| 71 | 
         
            +
                    self.moe_use_mixtral_gating = moe_use_mixtral_gating
         
     | 
| 72 | 
         
            +
                    self.moe_2layer_gate = moe_2layer_gate
         
     | 
| 73 | 
         
            +
                    self.moe_use_logits_norm = moe_use_logits_norm
         
     | 
| 74 | 
         
            +
                    self.moe_gate_norm_std = moe_gate_norm_std
         
     | 
| 75 | 
         
            +
                    self.moe_feature_no_mul_topk = moe_feature_no_mul_topk
         
     | 
| 76 | 
         
            +
             
     | 
| 77 | 
         
            +
                    super().__init__(
         
     | 
| 78 | 
         
            +
                        pad_token_id=pad_token_id,
         
     | 
| 79 | 
         
            +
                        bos_token_id=bos_token_id,
         
     | 
| 80 | 
         
            +
                        eos_token_id=eos_token_id,
         
     | 
| 81 | 
         
            +
                        tie_word_embeddings=tie_word_embeddings,
         
     | 
| 82 | 
         
            +
                        **kwargs,
         
     | 
| 83 | 
         
            +
                    )
         
     | 
| 84 | 
         
            +
             
     | 
| 85 | 
         
            +
                def _rope_scaling_validation(self):
         
     | 
| 86 | 
         
            +
                    """
         
     | 
| 87 | 
         
            +
                    Validate the `rope_scaling` configuration.
         
     | 
| 88 | 
         
            +
                    """
         
     | 
| 89 | 
         
            +
                    if self.rope_scaling is None:
         
     | 
| 90 | 
         
            +
                        return
         
     | 
| 91 | 
         
            +
             
     | 
| 92 | 
         
            +
                    if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
         
     | 
| 93 | 
         
            +
                        raise ValueError(
         
     | 
| 94 | 
         
            +
                            "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
         
     | 
| 95 | 
         
            +
                            f"got {self.rope_scaling}"
         
     | 
| 96 | 
         
            +
                        )
         
     | 
| 97 | 
         
            +
                    rope_scaling_type = self.rope_scaling.get("type", None)
         
     | 
| 98 | 
         
            +
                    rope_scaling_factor = self.rope_scaling.get("factor", None)
         
     | 
| 99 | 
         
            +
                    if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic", "ntk"]:
         
     | 
| 100 | 
         
            +
                        raise ValueError(
         
     | 
| 101 | 
         
            +
                            f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
         
     | 
| 102 | 
         
            +
                        )
         
     | 
| 103 | 
         
            +
                    if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
         
     | 
| 104 | 
         
            +
                        raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}")
         
     | 
    	
        generation_config.json
    ADDED
    
    | 
         @@ -0,0 +1 @@ 
     | 
|
| 
         | 
| 
         | 
|
| 1 | 
         
            +
            {"_from_model_config": true, "bos_token_id": 1, "eos_token_id": 2, "pad_token_id": 0, "transformers_version": "4.33.1"}
         
     | 
    	
        modeling_moe_plus_plus.py
    ADDED
    
    | 
         @@ -0,0 +1,960 @@ 
     | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
| 
         | 
|
| 1 | 
         
            +
            # Copyright (c) SkyworkAI and the HuggingFace Inc. team. All rights reserved.
         
     | 
| 2 | 
         
            +
            # This code is built upon Huggingface's transformers repository.
         
     | 
| 3 | 
         
            +
             
     | 
| 4 | 
         
            +
            import math
         
     | 
| 5 | 
         
            +
            from typing import List, Optional, Tuple, Union
         
     | 
| 6 | 
         
            +
             
     | 
| 7 | 
         
            +
            import torch
         
     | 
| 8 | 
         
            +
            import torch.nn.functional as F
         
     | 
| 9 | 
         
            +
            import torch.utils.checkpoint
         
     | 
| 10 | 
         
            +
            from torch import nn
         
     | 
| 11 | 
         
            +
            from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
         
     | 
| 12 | 
         
            +
             
     | 
| 13 | 
         
            +
            from transformers.activations import ACT2FN
         
     | 
| 14 | 
         
            +
            from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
         
     | 
| 15 | 
         
            +
            from transformers.modeling_utils import PreTrainedModel
         
     | 
| 16 | 
         
            +
            from transformers.utils import logging
         
     | 
| 17 | 
         
            +
            from .configuration_moe_plus_plus import MoeConfig
         
     | 
| 18 | 
         
            +
            from .moe_plus_plus_layer import MOE
         
     | 
| 19 | 
         
            +
             
     | 
| 20 | 
         
            +
            logger = logging.get_logger(__name__)
         
     | 
| 21 | 
         
            +
             
     | 
| 22 | 
         
            +
            _CONFIG_FOR_DOC = "MoeConfig"
         
     | 
| 23 | 
         
            +
             
     | 
| 24 | 
         
            +
             
     | 
| 25 | 
         
            +
            # Copied from transformers.models.bart.modeling_bart._make_causal_mask
         
     | 
| 26 | 
         
            +
            def _make_causal_mask(
         
     | 
| 27 | 
         
            +
                input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
         
     | 
| 28 | 
         
            +
            ):
         
     | 
| 29 | 
         
            +
                """
         
     | 
| 30 | 
         
            +
                Make causal mask used for bi-directional self-attention.
         
     | 
| 31 | 
         
            +
                """
         
     | 
| 32 | 
         
            +
                bsz, tgt_len = input_ids_shape
         
     | 
| 33 | 
         
            +
                mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
         
     | 
| 34 | 
         
            +
                mask_cond = torch.arange(mask.size(-1), device=device)
         
     | 
| 35 | 
         
            +
                mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
         
     | 
| 36 | 
         
            +
                mask = mask.to(dtype)
         
     | 
| 37 | 
         
            +
             
     | 
| 38 | 
         
            +
                if past_key_values_length > 0:
         
     | 
| 39 | 
         
            +
                    mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
         
     | 
| 40 | 
         
            +
                return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
         
     | 
| 41 | 
         
            +
             
     | 
| 42 | 
         
            +
             
     | 
| 43 | 
         
            +
            # Copied from transformers.models.bart.modeling_bart._expand_mask
         
     | 
| 44 | 
         
            +
            def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
         
     | 
| 45 | 
         
            +
                """
         
     | 
| 46 | 
         
            +
                Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
         
     | 
| 47 | 
         
            +
                """
         
     | 
| 48 | 
         
            +
                bsz, src_len = mask.size()
         
     | 
| 49 | 
         
            +
                tgt_len = tgt_len if tgt_len is not None else src_len
         
     | 
| 50 | 
         
            +
             
     | 
| 51 | 
         
            +
                expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
         
     | 
| 52 | 
         
            +
             
     | 
| 53 | 
         
            +
                inverted_mask = 1.0 - expanded_mask
         
     | 
| 54 | 
         
            +
             
     | 
| 55 | 
         
            +
                return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
         
     | 
| 56 | 
         
            +
             
     | 
| 57 | 
         
            +
             
     | 
| 58 | 
         
            +
            class RMSNorm(nn.Module):
         
     | 
| 59 | 
         
            +
                def __init__(self, hidden_size, eps=1e-6):
         
     | 
| 60 | 
         
            +
                    """
         
     | 
| 61 | 
         
            +
                    RMSNorm is equivalent to T5LayerNorm
         
     | 
| 62 | 
         
            +
                    """
         
     | 
| 63 | 
         
            +
                    super().__init__()
         
     | 
| 64 | 
         
            +
                    self.weight = nn.Parameter(torch.ones(hidden_size))
         
     | 
| 65 | 
         
            +
                    self.variance_epsilon = eps
         
     | 
| 66 | 
         
            +
             
     | 
| 67 | 
         
            +
                def forward(self, hidden_states):
         
     | 
| 68 | 
         
            +
                    input_dtype = hidden_states.dtype
         
     | 
| 69 | 
         
            +
                    hidden_states = hidden_states.to(torch.float32)
         
     | 
| 70 | 
         
            +
                    variance = hidden_states.pow(2).mean(-1, keepdim=True)
         
     | 
| 71 | 
         
            +
                    hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
         
     | 
| 72 | 
         
            +
                    return self.weight * hidden_states.to(input_dtype)
         
     | 
| 73 | 
         
            +
             
     | 
| 74 | 
         
            +
             
     | 
| 75 | 
         
            +
            class RotaryEmbedding(torch.nn.Module):
         
     | 
| 76 | 
         
            +
                def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
         
     | 
| 77 | 
         
            +
                    super().__init__()
         
     | 
| 78 | 
         
            +
             
     | 
| 79 | 
         
            +
                    self.dim = dim
         
     | 
| 80 | 
         
            +
                    self.max_position_embeddings = max_position_embeddings
         
     | 
| 81 | 
         
            +
                    self.base = base
         
     | 
| 82 | 
         
            +
                    inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
         
     | 
| 83 | 
         
            +
                    self.register_buffer("inv_freq", inv_freq, persistent=False)
         
     | 
| 84 | 
         
            +
             
     | 
| 85 | 
         
            +
                    # Build here to make `torch.jit.trace` work.
         
     | 
| 86 | 
         
            +
                    self._set_cos_sin_cache(
         
     | 
| 87 | 
         
            +
                        seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
         
     | 
| 88 | 
         
            +
                    )
         
     | 
| 89 | 
         
            +
             
     | 
| 90 | 
         
            +
                def _set_cos_sin_cache(self, seq_len, device, dtype):
         
     | 
| 91 | 
         
            +
                    self.max_seq_len_cached = seq_len
         
     | 
| 92 | 
         
            +
                    t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
         
     | 
| 93 | 
         
            +
             
     | 
| 94 | 
         
            +
                    freqs = torch.einsum("i,j->ij", t, self.inv_freq)
         
     | 
| 95 | 
         
            +
                    # Different from paper, but it uses a different permutation in order to obtain the same calculation
         
     | 
| 96 | 
         
            +
                    emb = torch.cat((freqs, freqs), dim=-1)
         
     | 
| 97 | 
         
            +
                    self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
         
     | 
| 98 | 
         
            +
                    self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
         
     | 
| 99 | 
         
            +
             
     | 
| 100 | 
         
            +
                def forward(self, x, seq_len=None):
         
     | 
| 101 | 
         
            +
                    # x: [bs, num_attention_heads, seq_len, head_size]
         
     | 
| 102 | 
         
            +
                    if seq_len > self.max_seq_len_cached:
         
     | 
| 103 | 
         
            +
                        self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
         
     | 
| 104 | 
         
            +
             
     | 
| 105 | 
         
            +
                    return (
         
     | 
| 106 | 
         
            +
                        self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
         
     | 
| 107 | 
         
            +
                        self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
         
     | 
| 108 | 
         
            +
                    )
         
     | 
| 109 | 
         
            +
             
     | 
| 110 | 
         
            +
             
     | 
| 111 | 
         
            +
            class LinearScalingRotaryEmbedding(RotaryEmbedding):
         
     | 
| 112 | 
         
            +
                """RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
         
     | 
| 113 | 
         
            +
             
     | 
| 114 | 
         
            +
                def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
         
     | 
| 115 | 
         
            +
                    self.scaling_factor = scaling_factor
         
     | 
| 116 | 
         
            +
                    super().__init__(dim, max_position_embeddings, base, device)
         
     | 
| 117 | 
         
            +
             
     | 
| 118 | 
         
            +
                def _set_cos_sin_cache(self, seq_len, device, dtype):
         
     | 
| 119 | 
         
            +
                    self.max_seq_len_cached = seq_len
         
     | 
| 120 | 
         
            +
                    t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
         
     | 
| 121 | 
         
            +
                    t = t / self.scaling_factor
         
     | 
| 122 | 
         
            +
             
     | 
| 123 | 
         
            +
                    freqs = torch.einsum("i,j->ij", t, self.inv_freq)
         
     | 
| 124 | 
         
            +
                    # Different from paper, but it uses a different permutation in order to obtain the same calculation
         
     | 
| 125 | 
         
            +
                    emb = torch.cat((freqs, freqs), dim=-1)
         
     | 
| 126 | 
         
            +
                    self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
         
     | 
| 127 | 
         
            +
                    self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
         
     | 
| 128 | 
         
            +
             
     | 
| 129 | 
         
            +
             
     | 
| 130 | 
         
            +
            class DynamicNTKScalingRotaryEmbedding(RotaryEmbedding):
         
     | 
| 131 | 
         
            +
                """RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
         
     | 
| 132 | 
         
            +
             
     | 
| 133 | 
         
            +
                def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
         
     | 
| 134 | 
         
            +
                    self.scaling_factor = scaling_factor
         
     | 
| 135 | 
         
            +
                    super().__init__(dim, max_position_embeddings, base, device)
         
     | 
| 136 | 
         
            +
             
     | 
| 137 | 
         
            +
                def _set_cos_sin_cache(self, seq_len, device, dtype):
         
     | 
| 138 | 
         
            +
                    self.max_seq_len_cached = seq_len
         
     | 
| 139 | 
         
            +
             
     | 
| 140 | 
         
            +
                    if seq_len > self.max_position_embeddings:
         
     | 
| 141 | 
         
            +
                        base = self.base * (
         
     | 
| 142 | 
         
            +
                            (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
         
     | 
| 143 | 
         
            +
                        ) ** (self.dim / (self.dim - 2))
         
     | 
| 144 | 
         
            +
                        inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
         
     | 
| 145 | 
         
            +
                        self.register_buffer("inv_freq", inv_freq, persistent=False)
         
     | 
| 146 | 
         
            +
             
     | 
| 147 | 
         
            +
                    t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
         
     | 
| 148 | 
         
            +
             
     | 
| 149 | 
         
            +
                    freqs = torch.einsum("i,j->ij", t, self.inv_freq)
         
     | 
| 150 | 
         
            +
                    # Different from paper, but it uses a different permutation in order to obtain the same calculation
         
     | 
| 151 | 
         
            +
                    emb = torch.cat((freqs, freqs), dim=-1)
         
     | 
| 152 | 
         
            +
                    self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
         
     | 
| 153 | 
         
            +
                    self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
         
     | 
| 154 | 
         
            +
             
     | 
| 155 | 
         
            +
             
     | 
| 156 | 
         
            +
             
     | 
| 157 | 
         
            +
            class NTKScalingRotaryEmbedding(torch.nn.Module):
         
     | 
| 158 | 
         
            +
                def __init__(self, dim, max_position_embeddings=2048, base=10000, scaling_factor=100, device=None):
         
     | 
| 159 | 
         
            +
                    super().__init__()
         
     | 
| 160 | 
         
            +
             
     | 
| 161 | 
         
            +
                    self.dim = dim
         
     | 
| 162 | 
         
            +
                    self.max_position_embeddings = max_position_embeddings
         
     | 
| 163 | 
         
            +
                    self.base = base * scaling_factor 
         
     | 
| 164 | 
         
            +
                    inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
         
     | 
| 165 | 
         
            +
                    self.register_buffer("inv_freq", inv_freq, persistent=False)
         
     | 
| 166 | 
         
            +
             
     | 
| 167 | 
         
            +
                    # Build here to make `torch.jit.trace` work.
         
     | 
| 168 | 
         
            +
                    self._set_cos_sin_cache(
         
     | 
| 169 | 
         
            +
                        seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
         
     | 
| 170 | 
         
            +
                    )
         
     | 
| 171 | 
         
            +
             
     | 
| 172 | 
         
            +
                def _set_cos_sin_cache(self, seq_len, device, dtype):
         
     | 
| 173 | 
         
            +
                    self.max_seq_len_cached = seq_len
         
     | 
| 174 | 
         
            +
                    t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
         
     | 
| 175 | 
         
            +
                    freqs = torch.einsum("i,j->ij", t, self.inv_freq)
         
     | 
| 176 | 
         
            +
                    emb = torch.cat((freqs, freqs), dim=-1)
         
     | 
| 177 | 
         
            +
                    self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
         
     | 
| 178 | 
         
            +
                    self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
         
     | 
| 179 | 
         
            +
             
     | 
| 180 | 
         
            +
                def forward(self, x, seq_len=None):
         
     | 
| 181 | 
         
            +
                    if seq_len > self.max_seq_len_cached:
         
     | 
| 182 | 
         
            +
                        self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
         
     | 
| 183 | 
         
            +
             
     | 
| 184 | 
         
            +
                    return (
         
     | 
| 185 | 
         
            +
                        self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
         
     | 
| 186 | 
         
            +
                        self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
         
     | 
| 187 | 
         
            +
                    )
         
     | 
| 188 | 
         
            +
             
     | 
| 189 | 
         
            +
            def rotate_half(x):
         
     | 
| 190 | 
         
            +
                """Rotates half the hidden dims of the input."""
         
     | 
| 191 | 
         
            +
                x1 = x[..., : x.shape[-1] // 2]
         
     | 
| 192 | 
         
            +
                x2 = x[..., x.shape[-1] // 2 :]
         
     | 
| 193 | 
         
            +
                return torch.cat((-x2, x1), dim=-1)
         
     | 
| 194 | 
         
            +
             
     | 
| 195 | 
         
            +
             
     | 
| 196 | 
         
            +
            def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
         
     | 
| 197 | 
         
            +
                # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
         
     | 
| 198 | 
         
            +
                cos = cos.squeeze(1).squeeze(0)  # [seq_len, dim]
         
     | 
| 199 | 
         
            +
                sin = sin.squeeze(1).squeeze(0)  # [seq_len, dim]
         
     | 
| 200 | 
         
            +
                cos = cos[position_ids].unsqueeze(1)  # [bs, 1, seq_len, dim]
         
     | 
| 201 | 
         
            +
                sin = sin[position_ids].unsqueeze(1)  # [bs, 1, seq_len, dim]
         
     | 
| 202 | 
         
            +
                q_embed = (q * cos) + (rotate_half(q) * sin)
         
     | 
| 203 | 
         
            +
                k_embed = (k * cos) + (rotate_half(k) * sin)
         
     | 
| 204 | 
         
            +
                return q_embed, k_embed
         
     | 
| 205 | 
         
            +
             
     | 
| 206 | 
         
            +
             
     | 
| 207 | 
         
            +
            class MLP(nn.Module):
         
     | 
| 208 | 
         
            +
                def __init__(self, config):
         
     | 
| 209 | 
         
            +
                    super().__init__()
         
     | 
| 210 | 
         
            +
                    self.config = config
         
     | 
| 211 | 
         
            +
                    self.hidden_size = config.hidden_size
         
     | 
| 212 | 
         
            +
                    self.intermediate_size = config.intermediate_size
         
     | 
| 213 | 
         
            +
                    self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
         
     | 
| 214 | 
         
            +
                    self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
         
     | 
| 215 | 
         
            +
                    self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
         
     | 
| 216 | 
         
            +
                    self.act_fn = ACT2FN[config.hidden_act]
         
     | 
| 217 | 
         
            +
             
     | 
| 218 | 
         
            +
                def forward(self, x):
         
     | 
| 219 | 
         
            +
                    if self.config.pretraining_tp > 1:
         
     | 
| 220 | 
         
            +
                        slice = self.intermediate_size // self.config.pretraining_tp
         
     | 
| 221 | 
         
            +
                        gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
         
     | 
| 222 | 
         
            +
                        up_proj_slices = self.up_proj.weight.split(slice, dim=0)
         
     | 
| 223 | 
         
            +
                        down_proj_slices = self.down_proj.weight.split(slice, dim=1)
         
     | 
| 224 | 
         
            +
             
     | 
| 225 | 
         
            +
                        gate_proj = torch.cat(
         
     | 
| 226 | 
         
            +
                            [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
         
     | 
| 227 | 
         
            +
                        )
         
     | 
| 228 | 
         
            +
                        up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
         
     | 
| 229 | 
         
            +
             
     | 
| 230 | 
         
            +
                        intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
         
     | 
| 231 | 
         
            +
                        down_proj = [
         
     | 
| 232 | 
         
            +
                            F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
         
     | 
| 233 | 
         
            +
                        ]
         
     | 
| 234 | 
         
            +
                        down_proj = sum(down_proj)
         
     | 
| 235 | 
         
            +
                    else:
         
     | 
| 236 | 
         
            +
                        down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
         
     | 
| 237 | 
         
            +
             
     | 
| 238 | 
         
            +
                    return down_proj
         
     | 
| 239 | 
         
            +
             
     | 
| 240 | 
         
            +
             
     | 
| 241 | 
         
            +
            class MLPMoE(nn.Module):
         
     | 
| 242 | 
         
            +
                def __init__(self, config):
         
     | 
| 243 | 
         
            +
                    super().__init__()
         
     | 
| 244 | 
         
            +
                    self.config = config
         
     | 
| 245 | 
         
            +
                    self.hidden_size = config.hidden_size
         
     | 
| 246 | 
         
            +
                    self.intermediate_size = config.intermediate_size
         
     | 
| 247 | 
         
            +
                    self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size * 2, bias=False)
         
     | 
| 248 | 
         
            +
                    self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
         
     | 
| 249 | 
         
            +
                    def swiglu(x):
         
     | 
| 250 | 
         
            +
                        x = torch.chunk(x, 2, dim=-1)
         
     | 
| 251 | 
         
            +
                        return F.silu(x[0]) * x[1]
         
     | 
| 252 | 
         
            +
                    self.act_fn = swiglu
         
     | 
| 253 | 
         
            +
             
     | 
| 254 | 
         
            +
                def forward(self, x):
         
     | 
| 255 | 
         
            +
                    down_proj = self.down_proj(self.act_fn(self.up_proj(x)))
         
     | 
| 256 | 
         
            +
             
     | 
| 257 | 
         
            +
                    return down_proj
         
     | 
| 258 | 
         
            +
             
     | 
| 259 | 
         
            +
             
     | 
| 260 | 
         
            +
            def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
         
     | 
| 261 | 
         
            +
                """
         
     | 
| 262 | 
         
            +
                This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
         
     | 
| 263 | 
         
            +
                num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
         
     | 
| 264 | 
         
            +
                """
         
     | 
| 265 | 
         
            +
                batch, num_key_value_heads, slen, head_dim = hidden_states.shape
         
     | 
| 266 | 
         
            +
                if n_rep == 1:
         
     | 
| 267 | 
         
            +
                    return hidden_states
         
     | 
| 268 | 
         
            +
                hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
         
     | 
| 269 | 
         
            +
                return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
         
     | 
| 270 | 
         
            +
             
     | 
| 271 | 
         
            +
             
     | 
| 272 | 
         
            +
            class Attention(nn.Module):
         
     | 
| 273 | 
         
            +
                """Multi-headed attention from 'Attention Is All You Need' paper"""
         
     | 
| 274 | 
         
            +
             
     | 
| 275 | 
         
            +
                def __init__(self, config: MoeConfig):
         
     | 
| 276 | 
         
            +
                    super().__init__()
         
     | 
| 277 | 
         
            +
                    self.config = config
         
     | 
| 278 | 
         
            +
                    self.hidden_size = config.hidden_size
         
     | 
| 279 | 
         
            +
                    self.num_heads = config.num_attention_heads
         
     | 
| 280 | 
         
            +
                    self.head_dim = self.hidden_size // self.num_heads
         
     | 
| 281 | 
         
            +
                    self.num_key_value_heads = config.num_key_value_heads
         
     | 
| 282 | 
         
            +
                    self.num_key_value_groups = self.num_heads // self.num_key_value_heads
         
     | 
| 283 | 
         
            +
                    self.max_position_embeddings = config.max_position_embeddings
         
     | 
| 284 | 
         
            +
                    self.rope_theta = config.rope_theta
         
     | 
| 285 | 
         
            +
             
     | 
| 286 | 
         
            +
                    if (self.head_dim * self.num_heads) != self.hidden_size:
         
     | 
| 287 | 
         
            +
                        raise ValueError(
         
     | 
| 288 | 
         
            +
                            f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
         
     | 
| 289 | 
         
            +
                            f" and `num_heads`: {self.num_heads})."
         
     | 
| 290 | 
         
            +
                        )
         
     | 
| 291 | 
         
            +
                    self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
         
     | 
| 292 | 
         
            +
                    self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
         
     | 
| 293 | 
         
            +
                    self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
         
     | 
| 294 | 
         
            +
                    self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
         
     | 
| 295 | 
         
            +
                    self._init_rope()
         
     | 
| 296 | 
         
            +
             
     | 
| 297 | 
         
            +
                def _init_rope(self):
         
     | 
| 298 | 
         
            +
                    if self.config.rope_scaling is None:
         
     | 
| 299 | 
         
            +
                        self.rotary_emb = RotaryEmbedding(
         
     | 
| 300 | 
         
            +
                            self.head_dim,
         
     | 
| 301 | 
         
            +
                            max_position_embeddings=self.max_position_embeddings,
         
     | 
| 302 | 
         
            +
                            base=self.rope_theta,
         
     | 
| 303 | 
         
            +
                        )
         
     | 
| 304 | 
         
            +
                    else:
         
     | 
| 305 | 
         
            +
                        scaling_type = self.config.rope_scaling["type"]
         
     | 
| 306 | 
         
            +
                        scaling_factor = self.config.rope_scaling["factor"]
         
     | 
| 307 | 
         
            +
                        if scaling_type == "linear":
         
     | 
| 308 | 
         
            +
                            self.rotary_emb = LinearScalingRotaryEmbedding(
         
     | 
| 309 | 
         
            +
                                self.head_dim,
         
     | 
| 310 | 
         
            +
                                max_position_embeddings=self.max_position_embeddings,
         
     | 
| 311 | 
         
            +
                                scaling_factor=scaling_factor,
         
     | 
| 312 | 
         
            +
                                base=self.rope_theta,
         
     | 
| 313 | 
         
            +
                            )
         
     | 
| 314 | 
         
            +
                        elif scaling_type == "dynamic":
         
     | 
| 315 | 
         
            +
                            self.rotary_emb = DynamicNTKScalingRotaryEmbedding(
         
     | 
| 316 | 
         
            +
                                self.head_dim,
         
     | 
| 317 | 
         
            +
                                max_position_embeddings=self.max_position_embeddings,
         
     | 
| 318 | 
         
            +
                                scaling_factor=scaling_factor,
         
     | 
| 319 | 
         
            +
                                base=self.rope_theta,
         
     | 
| 320 | 
         
            +
                            )
         
     | 
| 321 | 
         
            +
                        elif scaling_type == "ntk":
         
     | 
| 322 | 
         
            +
                            self.rotary_emb = NTKScalingRotaryEmbedding(
         
     | 
| 323 | 
         
            +
                                self.head_dim,
         
     | 
| 324 | 
         
            +
                                max_position_embeddings=self.max_position_embeddings,
         
     | 
| 325 | 
         
            +
                                scaling_factor=scaling_factor,
         
     | 
| 326 | 
         
            +
                                base=self.rope_theta,
         
     | 
| 327 | 
         
            +
                            )
         
     | 
| 328 | 
         
            +
                        else:
         
     | 
| 329 | 
         
            +
                            raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
         
     | 
| 330 | 
         
            +
                        print('-'*80)
         
     | 
| 331 | 
         
            +
                        print(f"USING COSTOM MODELING, scaling_type is {scaling_type}, scaling_factor is {scaling_factor}")
         
     | 
| 332 | 
         
            +
                        
         
     | 
| 333 | 
         
            +
                def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
         
     | 
| 334 | 
         
            +
                    return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
         
     | 
| 335 | 
         
            +
             
     | 
| 336 | 
         
            +
                def forward(
         
     | 
| 337 | 
         
            +
                    self,
         
     | 
| 338 | 
         
            +
                    hidden_states: torch.Tensor,
         
     | 
| 339 | 
         
            +
                    attention_mask: Optional[torch.Tensor] = None,
         
     | 
| 340 | 
         
            +
                    position_ids: Optional[torch.LongTensor] = None,
         
     | 
| 341 | 
         
            +
                    past_key_value: Optional[Tuple[torch.Tensor]] = None,
         
     | 
| 342 | 
         
            +
                    output_attentions: bool = False,
         
     | 
| 343 | 
         
            +
                    use_cache: bool = False,
         
     | 
| 344 | 
         
            +
                ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
         
     | 
| 345 | 
         
            +
                    bsz, q_len, _ = hidden_states.size()
         
     | 
| 346 | 
         
            +
             
     | 
| 347 | 
         
            +
                    if self.config.pretraining_tp > 1:
         
     | 
| 348 | 
         
            +
                        key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
         
     | 
| 349 | 
         
            +
                        query_slices = self.q_proj.weight.split(
         
     | 
| 350 | 
         
            +
                            (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
         
     | 
| 351 | 
         
            +
                        )
         
     | 
| 352 | 
         
            +
                        key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
         
     | 
| 353 | 
         
            +
                        value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
         
     | 
| 354 | 
         
            +
             
     | 
| 355 | 
         
            +
                        query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
         
     | 
| 356 | 
         
            +
                        query_states = torch.cat(query_states, dim=-1)
         
     | 
| 357 | 
         
            +
             
     | 
| 358 | 
         
            +
                        key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
         
     | 
| 359 | 
         
            +
                        key_states = torch.cat(key_states, dim=-1)
         
     | 
| 360 | 
         
            +
             
     | 
| 361 | 
         
            +
                        value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
         
     | 
| 362 | 
         
            +
                        value_states = torch.cat(value_states, dim=-1)
         
     | 
| 363 | 
         
            +
             
     | 
| 364 | 
         
            +
                    else:
         
     | 
| 365 | 
         
            +
                        query_states = self.q_proj(hidden_states)
         
     | 
| 366 | 
         
            +
                        key_states = self.k_proj(hidden_states)
         
     | 
| 367 | 
         
            +
                        value_states = self.v_proj(hidden_states)
         
     | 
| 368 | 
         
            +
             
     | 
| 369 | 
         
            +
                    query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
         
     | 
| 370 | 
         
            +
                    key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
         
     | 
| 371 | 
         
            +
                    value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
         
     | 
| 372 | 
         
            +
             
     | 
| 373 | 
         
            +
                    kv_seq_len = key_states.shape[-2]
         
     | 
| 374 | 
         
            +
                    if past_key_value is not None:
         
     | 
| 375 | 
         
            +
                        kv_seq_len += past_key_value[0].shape[-2]
         
     | 
| 376 | 
         
            +
                    cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
         
     | 
| 377 | 
         
            +
                    query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
         
     | 
| 378 | 
         
            +
             
     | 
| 379 | 
         
            +
                    if past_key_value is not None:
         
     | 
| 380 | 
         
            +
                        # reuse k, v, self_attention
         
     | 
| 381 | 
         
            +
                        key_states = torch.cat([past_key_value[0], key_states], dim=2)
         
     | 
| 382 | 
         
            +
                        value_states = torch.cat([past_key_value[1], value_states], dim=2)
         
     | 
| 383 | 
         
            +
             
     | 
| 384 | 
         
            +
                    past_key_value = (key_states, value_states) if use_cache else None
         
     | 
| 385 | 
         
            +
             
     | 
| 386 | 
         
            +
                    # repeat k/v heads if n_kv_heads < n_heads
         
     | 
| 387 | 
         
            +
                    key_states = repeat_kv(key_states, self.num_key_value_groups)
         
     | 
| 388 | 
         
            +
                    value_states = repeat_kv(value_states, self.num_key_value_groups)
         
     | 
| 389 | 
         
            +
             
     | 
| 390 | 
         
            +
                    attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
         
     | 
| 391 | 
         
            +
             
     | 
| 392 | 
         
            +
                    if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
         
     | 
| 393 | 
         
            +
                        raise ValueError(
         
     | 
| 394 | 
         
            +
                            f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
         
     | 
| 395 | 
         
            +
                            f" {attn_weights.size()}"
         
     | 
| 396 | 
         
            +
                        )
         
     | 
| 397 | 
         
            +
             
     | 
| 398 | 
         
            +
                    if attention_mask is not None:
         
     | 
| 399 | 
         
            +
                        if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
         
     | 
| 400 | 
         
            +
                            raise ValueError(
         
     | 
| 401 | 
         
            +
                                f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
         
     | 
| 402 | 
         
            +
                            )
         
     | 
| 403 | 
         
            +
                        attn_weights = attn_weights + attention_mask
         
     | 
| 404 | 
         
            +
             
     | 
| 405 | 
         
            +
                    # upcast attention to fp32
         
     | 
| 406 | 
         
            +
                    attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
         
     | 
| 407 | 
         
            +
                    attn_output = torch.matmul(attn_weights, value_states)
         
     | 
| 408 | 
         
            +
             
     | 
| 409 | 
         
            +
                    if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
         
     | 
| 410 | 
         
            +
                        raise ValueError(
         
     | 
| 411 | 
         
            +
                            f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
         
     | 
| 412 | 
         
            +
                            f" {attn_output.size()}"
         
     | 
| 413 | 
         
            +
                        )
         
     | 
| 414 | 
         
            +
             
     | 
| 415 | 
         
            +
                    attn_output = attn_output.transpose(1, 2).contiguous()
         
     | 
| 416 | 
         
            +
                    attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
         
     | 
| 417 | 
         
            +
             
     | 
| 418 | 
         
            +
                    if self.config.pretraining_tp > 1:
         
     | 
| 419 | 
         
            +
                        attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
         
     | 
| 420 | 
         
            +
                        o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
         
     | 
| 421 | 
         
            +
                        attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
         
     | 
| 422 | 
         
            +
                    else:
         
     | 
| 423 | 
         
            +
                        attn_output = self.o_proj(attn_output)
         
     | 
| 424 | 
         
            +
             
     | 
| 425 | 
         
            +
                    if not output_attentions:
         
     | 
| 426 | 
         
            +
                        attn_weights = None
         
     | 
| 427 | 
         
            +
             
     | 
| 428 | 
         
            +
                    return attn_output, attn_weights, past_key_value
         
     | 
| 429 | 
         
            +
             
     | 
| 430 | 
         
            +
             
     | 
| 431 | 
         
            +
            class DecoderLayer(nn.Module):
         
     | 
| 432 | 
         
            +
                def __init__(self, config: MoeConfig, layer_id: int):
         
     | 
| 433 | 
         
            +
                    super().__init__()
         
     | 
| 434 | 
         
            +
                    self.hidden_size = config.hidden_size
         
     | 
| 435 | 
         
            +
                    self.self_attn = Attention(config=config)
         
     | 
| 436 | 
         
            +
                    
         
     | 
| 437 | 
         
            +
                    if config.moe_expert_interval == 1:
         
     | 
| 438 | 
         
            +
                        self.mlp = MOE(config.hidden_size,
         
     | 
| 439 | 
         
            +
                                       MLPMoE(config),
         
     | 
| 440 | 
         
            +
                                       num_experts=config.num_experts[0],
         
     | 
| 441 | 
         
            +
                                       moe_use_mixtral_gating=config.moe_use_mixtral_gating,
         
     | 
| 442 | 
         
            +
                                       moe_2layer_gate=config.moe_2layer_gate,
         
     | 
| 443 | 
         
            +
                                       moe_use_logits_norm=config.moe_use_logits_norm,
         
     | 
| 444 | 
         
            +
                                       moe_gate_norm_std=config.moe_gate_norm_std,
         
     | 
| 445 | 
         
            +
                                       moe_feature_no_mul_topk=config.moe_feature_no_mul_topk)
         
     | 
| 446 | 
         
            +
                    else:
         
     | 
| 447 | 
         
            +
                        if (layer_id + 1) % config.moe_expert_interval == 0:
         
     | 
| 448 | 
         
            +
                            self.mlp = MOE(config.hidden_size,
         
     | 
| 449 | 
         
            +
                                           MLPMoE(config),
         
     | 
| 450 | 
         
            +
                                           num_experts=config.num_experts[0],
         
     | 
| 451 | 
         
            +
                                           moe_use_mixtral_gating=config.moe_use_mixtral_gating,
         
     | 
| 452 | 
         
            +
                                           moe_2layer_gate=config.moe_2layer_gate,
         
     | 
| 453 | 
         
            +
                                           moe_use_logits_norm=config.moe_use_logits_norm,
         
     | 
| 454 | 
         
            +
                                           moe_gate_norm_std=config.moe_gate_norm_std,
         
     | 
| 455 | 
         
            +
                                           moe_feature_no_mul_topk=config.moe_feature_no_mul_topk)
         
     | 
| 456 | 
         
            +
                        else:
         
     | 
| 457 | 
         
            +
                            self.mlp = MLP(config)
         
     | 
| 458 | 
         
            +
                    
         
     | 
| 459 | 
         
            +
                    self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
         
     | 
| 460 | 
         
            +
                    self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
         
     | 
| 461 | 
         
            +
             
     | 
| 462 | 
         
            +
                def forward(
         
     | 
| 463 | 
         
            +
                    self,
         
     | 
| 464 | 
         
            +
                    hidden_states: torch.Tensor,
         
     | 
| 465 | 
         
            +
                    attention_mask: Optional[torch.Tensor] = None,
         
     | 
| 466 | 
         
            +
                    position_ids: Optional[torch.LongTensor] = None,
         
     | 
| 467 | 
         
            +
                    past_key_value: Optional[Tuple[torch.Tensor]] = None,
         
     | 
| 468 | 
         
            +
                    output_attentions: Optional[bool] = False,
         
     | 
| 469 | 
         
            +
                    use_cache: Optional[bool] = False,
         
     | 
| 470 | 
         
            +
                    gate_residual = None,
         
     | 
| 471 | 
         
            +
                ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
         
     | 
| 472 | 
         
            +
                    """
         
     | 
| 473 | 
         
            +
                    Args:
         
     | 
| 474 | 
         
            +
                        hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
         
     | 
| 475 | 
         
            +
                        attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
         
     | 
| 476 | 
         
            +
                            `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
         
     | 
| 477 | 
         
            +
                        output_attentions (`bool`, *optional*):
         
     | 
| 478 | 
         
            +
                            Whether or not to return the attentions tensors of all attention layers. See `attentions` under
         
     | 
| 479 | 
         
            +
                            returned tensors for more detail.
         
     | 
| 480 | 
         
            +
                        use_cache (`bool`, *optional*):
         
     | 
| 481 | 
         
            +
                            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
         
     | 
| 482 | 
         
            +
                            (see `past_key_values`).
         
     | 
| 483 | 
         
            +
                        past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
         
     | 
| 484 | 
         
            +
                    """
         
     | 
| 485 | 
         
            +
             
     | 
| 486 | 
         
            +
                    residual = hidden_states
         
     | 
| 487 | 
         
            +
             
     | 
| 488 | 
         
            +
                    hidden_states = self.input_layernorm(hidden_states)
         
     | 
| 489 | 
         
            +
             
     | 
| 490 | 
         
            +
                    # Self Attention
         
     | 
| 491 | 
         
            +
                    hidden_states, self_attn_weights, present_key_value = self.self_attn(
         
     | 
| 492 | 
         
            +
                        hidden_states=hidden_states,
         
     | 
| 493 | 
         
            +
                        attention_mask=attention_mask,
         
     | 
| 494 | 
         
            +
                        position_ids=position_ids,
         
     | 
| 495 | 
         
            +
                        past_key_value=past_key_value,
         
     | 
| 496 | 
         
            +
                        output_attentions=output_attentions,
         
     | 
| 497 | 
         
            +
                        use_cache=use_cache,
         
     | 
| 498 | 
         
            +
                    )
         
     | 
| 499 | 
         
            +
                    hidden_states = residual + hidden_states
         
     | 
| 500 | 
         
            +
             
     | 
| 501 | 
         
            +
                    # Fully Connected
         
     | 
| 502 | 
         
            +
                    residual = hidden_states
         
     | 
| 503 | 
         
            +
                    hidden_states = self.post_attention_layernorm(hidden_states)
         
     | 
| 504 | 
         
            +
                    hidden_states, gate_residual = self.mlp(hidden_states, gate_residual=gate_residual)
         
     | 
| 505 | 
         
            +
                    hidden_states = residual + hidden_states
         
     | 
| 506 | 
         
            +
             
     | 
| 507 | 
         
            +
                    outputs = (hidden_states,)
         
     | 
| 508 | 
         
            +
             
     | 
| 509 | 
         
            +
                    if output_attentions:
         
     | 
| 510 | 
         
            +
                        outputs += (self_attn_weights,)
         
     | 
| 511 | 
         
            +
             
     | 
| 512 | 
         
            +
                    if use_cache:
         
     | 
| 513 | 
         
            +
                        outputs += (present_key_value,)
         
     | 
| 514 | 
         
            +
             
     | 
| 515 | 
         
            +
                    return outputs, gate_residual
         
     | 
| 516 | 
         
            +
             
     | 
| 517 | 
         
            +
            class MoePreTrainedModel(PreTrainedModel):
         
     | 
| 518 | 
         
            +
                config_class = MoeConfig
         
     | 
| 519 | 
         
            +
                base_model_prefix = "model"
         
     | 
| 520 | 
         
            +
                supports_gradient_checkpointing = True
         
     | 
| 521 | 
         
            +
                _no_split_modules = ["DecoderLayer"]
         
     | 
| 522 | 
         
            +
                _skip_keys_device_placement = "past_key_values"
         
     | 
| 523 | 
         
            +
             
     | 
| 524 | 
         
            +
                def _init_weights(self, module):
         
     | 
| 525 | 
         
            +
                    std = self.config.initializer_range
         
     | 
| 526 | 
         
            +
                    if isinstance(module, nn.Linear):
         
     | 
| 527 | 
         
            +
                        module.weight.data.normal_(mean=0.0, std=std)
         
     | 
| 528 | 
         
            +
                        if module.bias is not None:
         
     | 
| 529 | 
         
            +
                            module.bias.data.zero_()
         
     | 
| 530 | 
         
            +
                    elif isinstance(module, nn.Embedding):
         
     | 
| 531 | 
         
            +
                        module.weight.data.normal_(mean=0.0, std=std)
         
     | 
| 532 | 
         
            +
                        if module.padding_idx is not None:
         
     | 
| 533 | 
         
            +
                            module.weight.data[module.padding_idx].zero_()
         
     | 
| 534 | 
         
            +
             
     | 
| 535 | 
         
            +
                def _set_gradient_checkpointing(self, module, value=False):
         
     | 
| 536 | 
         
            +
                    if isinstance(module, MoeModel):
         
     | 
| 537 | 
         
            +
                        module.gradient_checkpointing = value
         
     | 
| 538 | 
         
            +
             
     | 
| 539 | 
         
            +
            class MoeModel(MoePreTrainedModel):
         
     | 
| 540 | 
         
            +
                """
         
     | 
| 541 | 
         
            +
                Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DecoderLayer`]
         
     | 
| 542 | 
         
            +
             
     | 
| 543 | 
         
            +
                Args:
         
     | 
| 544 | 
         
            +
                    config: MoeConfig
         
     | 
| 545 | 
         
            +
                """
         
     | 
| 546 | 
         
            +
             
     | 
| 547 | 
         
            +
                def __init__(self, config: MoeConfig):
         
     | 
| 548 | 
         
            +
                    super().__init__(config)
         
     | 
| 549 | 
         
            +
                    self.padding_idx = config.pad_token_id
         
     | 
| 550 | 
         
            +
                    self.vocab_size = config.vocab_size
         
     | 
| 551 | 
         
            +
             
     | 
| 552 | 
         
            +
                    self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
         
     | 
| 553 | 
         
            +
                    self.layers = nn.ModuleList([DecoderLayer(config, _) for _ in range(config.num_hidden_layers)])
         
     | 
| 554 | 
         
            +
                    self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
         
     | 
| 555 | 
         
            +
             
     | 
| 556 | 
         
            +
                    self.gradient_checkpointing = False
         
     | 
| 557 | 
         
            +
                    # Initialize weights and apply final processing
         
     | 
| 558 | 
         
            +
                    self.post_init()
         
     | 
| 559 | 
         
            +
             
     | 
| 560 | 
         
            +
                def get_input_embeddings(self):
         
     | 
| 561 | 
         
            +
                    return self.embed_tokens
         
     | 
| 562 | 
         
            +
             
     | 
| 563 | 
         
            +
                def set_input_embeddings(self, value):
         
     | 
| 564 | 
         
            +
                    self.embed_tokens = value
         
     | 
| 565 | 
         
            +
             
     | 
| 566 | 
         
            +
                # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
         
     | 
| 567 | 
         
            +
                def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
         
     | 
| 568 | 
         
            +
                    # create causal mask
         
     | 
| 569 | 
         
            +
                    # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
         
     | 
| 570 | 
         
            +
                    combined_attention_mask = None
         
     | 
| 571 | 
         
            +
                    if input_shape[-1] > 1:
         
     | 
| 572 | 
         
            +
                        combined_attention_mask = _make_causal_mask(
         
     | 
| 573 | 
         
            +
                            input_shape,
         
     | 
| 574 | 
         
            +
                            inputs_embeds.dtype,
         
     | 
| 575 | 
         
            +
                            device=inputs_embeds.device,
         
     | 
| 576 | 
         
            +
                            past_key_values_length=past_key_values_length,
         
     | 
| 577 | 
         
            +
                        )
         
     | 
| 578 | 
         
            +
             
     | 
| 579 | 
         
            +
                    if attention_mask is not None:
         
     | 
| 580 | 
         
            +
                        # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
         
     | 
| 581 | 
         
            +
                        expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
         
     | 
| 582 | 
         
            +
                            inputs_embeds.device
         
     | 
| 583 | 
         
            +
                        )
         
     | 
| 584 | 
         
            +
                        combined_attention_mask = (
         
     | 
| 585 | 
         
            +
                            expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
         
     | 
| 586 | 
         
            +
                        )
         
     | 
| 587 | 
         
            +
             
     | 
| 588 | 
         
            +
                    return combined_attention_mask
         
     | 
| 589 | 
         
            +
             
     | 
| 590 | 
         
            +
                def forward(
         
     | 
| 591 | 
         
            +
                    self,
         
     | 
| 592 | 
         
            +
                    input_ids: torch.LongTensor = None,
         
     | 
| 593 | 
         
            +
                    attention_mask: Optional[torch.Tensor] = None,
         
     | 
| 594 | 
         
            +
                    position_ids: Optional[torch.LongTensor] = None,
         
     | 
| 595 | 
         
            +
                    past_key_values: Optional[List[torch.FloatTensor]] = None,
         
     | 
| 596 | 
         
            +
                    inputs_embeds: Optional[torch.FloatTensor] = None,
         
     | 
| 597 | 
         
            +
                    use_cache: Optional[bool] = None,
         
     | 
| 598 | 
         
            +
                    output_attentions: Optional[bool] = None,
         
     | 
| 599 | 
         
            +
                    output_hidden_states: Optional[bool] = None,
         
     | 
| 600 | 
         
            +
                    return_dict: Optional[bool] = None,
         
     | 
| 601 | 
         
            +
                ) -> Union[Tuple, BaseModelOutputWithPast]:
         
     | 
| 602 | 
         
            +
                    output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
         
     | 
| 603 | 
         
            +
                    output_hidden_states = (
         
     | 
| 604 | 
         
            +
                        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         
     | 
| 605 | 
         
            +
                    )
         
     | 
| 606 | 
         
            +
                    use_cache = use_cache if use_cache is not None else self.config.use_cache
         
     | 
| 607 | 
         
            +
             
     | 
| 608 | 
         
            +
                    return_dict = return_dict if return_dict is not None else self.config.use_return_dict
         
     | 
| 609 | 
         
            +
             
     | 
| 610 | 
         
            +
                    # retrieve input_ids and inputs_embeds
         
     | 
| 611 | 
         
            +
                    if input_ids is not None and inputs_embeds is not None:
         
     | 
| 612 | 
         
            +
                        raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
         
     | 
| 613 | 
         
            +
                    elif input_ids is not None:
         
     | 
| 614 | 
         
            +
                        batch_size, seq_length = input_ids.shape
         
     | 
| 615 | 
         
            +
                    elif inputs_embeds is not None:
         
     | 
| 616 | 
         
            +
                        batch_size, seq_length, _ = inputs_embeds.shape
         
     | 
| 617 | 
         
            +
                    else:
         
     | 
| 618 | 
         
            +
                        raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
         
     | 
| 619 | 
         
            +
             
     | 
| 620 | 
         
            +
                    seq_length_with_past = seq_length
         
     | 
| 621 | 
         
            +
                    past_key_values_length = 0
         
     | 
| 622 | 
         
            +
             
     | 
| 623 | 
         
            +
                    if past_key_values is not None:
         
     | 
| 624 | 
         
            +
                        past_key_values_length = past_key_values[0][0].shape[2]
         
     | 
| 625 | 
         
            +
                        seq_length_with_past = seq_length_with_past + past_key_values_length
         
     | 
| 626 | 
         
            +
             
     | 
| 627 | 
         
            +
                    if position_ids is None:
         
     | 
| 628 | 
         
            +
                        device = input_ids.device if input_ids is not None else inputs_embeds.device
         
     | 
| 629 | 
         
            +
                        position_ids = torch.arange(
         
     | 
| 630 | 
         
            +
                            past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
         
     | 
| 631 | 
         
            +
                        )
         
     | 
| 632 | 
         
            +
                        position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
         
     | 
| 633 | 
         
            +
                    else:
         
     | 
| 634 | 
         
            +
                        position_ids = position_ids.view(-1, seq_length).long()
         
     | 
| 635 | 
         
            +
             
     | 
| 636 | 
         
            +
                    if inputs_embeds is None:
         
     | 
| 637 | 
         
            +
                        inputs_embeds = self.embed_tokens(input_ids)
         
     | 
| 638 | 
         
            +
                    # embed positions
         
     | 
| 639 | 
         
            +
                    if attention_mask is None:
         
     | 
| 640 | 
         
            +
                        attention_mask = torch.ones(
         
     | 
| 641 | 
         
            +
                            (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
         
     | 
| 642 | 
         
            +
                        )
         
     | 
| 643 | 
         
            +
                    attention_mask = self._prepare_decoder_attention_mask(
         
     | 
| 644 | 
         
            +
                        attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
         
     | 
| 645 | 
         
            +
                    )
         
     | 
| 646 | 
         
            +
             
     | 
| 647 | 
         
            +
                    hidden_states = inputs_embeds
         
     | 
| 648 | 
         
            +
             
     | 
| 649 | 
         
            +
                    if self.gradient_checkpointing and self.training:
         
     | 
| 650 | 
         
            +
                        if use_cache:
         
     | 
| 651 | 
         
            +
                            logger.warning_once(
         
     | 
| 652 | 
         
            +
                                "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
         
     | 
| 653 | 
         
            +
                            )
         
     | 
| 654 | 
         
            +
                            use_cache = False
         
     | 
| 655 | 
         
            +
             
     | 
| 656 | 
         
            +
                    # decoder layers
         
     | 
| 657 | 
         
            +
                    all_hidden_states = () if output_hidden_states else None
         
     | 
| 658 | 
         
            +
                    all_self_attns = () if output_attentions else None
         
     | 
| 659 | 
         
            +
                    next_decoder_cache = () if use_cache else None
         
     | 
| 660 | 
         
            +
             
     | 
| 661 | 
         
            +
                    gate_residual = None
         
     | 
| 662 | 
         
            +
             
     | 
| 663 | 
         
            +
                    for idx, decoder_layer in enumerate(self.layers):
         
     | 
| 664 | 
         
            +
                        if output_hidden_states:
         
     | 
| 665 | 
         
            +
                            all_hidden_states += (hidden_states,)
         
     | 
| 666 | 
         
            +
             
     | 
| 667 | 
         
            +
                        past_key_value = past_key_values[idx] if past_key_values is not None else None
         
     | 
| 668 | 
         
            +
             
     | 
| 669 | 
         
            +
                        if self.gradient_checkpointing and self.training:
         
     | 
| 670 | 
         
            +
             
     | 
| 671 | 
         
            +
                            def create_custom_forward(module):
         
     | 
| 672 | 
         
            +
                                def custom_forward(*inputs):
         
     | 
| 673 | 
         
            +
                                    # None for past_key_value
         
     | 
| 674 | 
         
            +
                                    return module(*inputs, past_key_value, output_attentions)
         
     | 
| 675 | 
         
            +
             
     | 
| 676 | 
         
            +
                                return custom_forward
         
     | 
| 677 | 
         
            +
             
     | 
| 678 | 
         
            +
                            layer_outputs, gate_residual = torch.utils.checkpoint.checkpoint(
         
     | 
| 679 | 
         
            +
                                create_custom_forward(decoder_layer),
         
     | 
| 680 | 
         
            +
                                hidden_states,
         
     | 
| 681 | 
         
            +
                                attention_mask,
         
     | 
| 682 | 
         
            +
                                position_ids,
         
     | 
| 683 | 
         
            +
                                past_key_value,
         
     | 
| 684 | 
         
            +
                                output_attentions,
         
     | 
| 685 | 
         
            +
                                use_cache,
         
     | 
| 686 | 
         
            +
                                gate_residual,
         
     | 
| 687 | 
         
            +
                            )
         
     | 
| 688 | 
         
            +
                        else:
         
     | 
| 689 | 
         
            +
                            layer_outputs, gate_residual = decoder_layer(
         
     | 
| 690 | 
         
            +
                                hidden_states,
         
     | 
| 691 | 
         
            +
                                attention_mask=attention_mask,
         
     | 
| 692 | 
         
            +
                                position_ids=position_ids,
         
     | 
| 693 | 
         
            +
                                past_key_value=past_key_value,
         
     | 
| 694 | 
         
            +
                                output_attentions=output_attentions,
         
     | 
| 695 | 
         
            +
                                use_cache=use_cache,
         
     | 
| 696 | 
         
            +
                                gate_residual=gate_residual,
         
     | 
| 697 | 
         
            +
                            )
         
     | 
| 698 | 
         
            +
             
     | 
| 699 | 
         
            +
                        hidden_states = layer_outputs[0]
         
     | 
| 700 | 
         
            +
             
     | 
| 701 | 
         
            +
                        if use_cache:
         
     | 
| 702 | 
         
            +
                            next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
         
     | 
| 703 | 
         
            +
             
     | 
| 704 | 
         
            +
                        if output_attentions:
         
     | 
| 705 | 
         
            +
                            all_self_attns += (layer_outputs[1],)
         
     | 
| 706 | 
         
            +
             
     | 
| 707 | 
         
            +
                    hidden_states = self.norm(hidden_states)
         
     | 
| 708 | 
         
            +
             
     | 
| 709 | 
         
            +
                    # add hidden states from the last decoder layer
         
     | 
| 710 | 
         
            +
                    if output_hidden_states:
         
     | 
| 711 | 
         
            +
                        all_hidden_states += (hidden_states,)
         
     | 
| 712 | 
         
            +
             
     | 
| 713 | 
         
            +
                    next_cache = next_decoder_cache if use_cache else None
         
     | 
| 714 | 
         
            +
                    if not return_dict:
         
     | 
| 715 | 
         
            +
                        return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
         
     | 
| 716 | 
         
            +
                    return BaseModelOutputWithPast(
         
     | 
| 717 | 
         
            +
                        last_hidden_state=hidden_states,
         
     | 
| 718 | 
         
            +
                        past_key_values=next_cache,
         
     | 
| 719 | 
         
            +
                        hidden_states=all_hidden_states,
         
     | 
| 720 | 
         
            +
                        attentions=all_self_attns,
         
     | 
| 721 | 
         
            +
                    )
         
     | 
| 722 | 
         
            +
             
     | 
| 723 | 
         
            +
             
     | 
| 724 | 
         
            +
            class MoeForCausalLM(MoePreTrainedModel):
         
     | 
| 725 | 
         
            +
                _tied_weights_keys = ["lm_head.weight"]
         
     | 
| 726 | 
         
            +
             
     | 
| 727 | 
         
            +
                def __init__(self, config):
         
     | 
| 728 | 
         
            +
                    super().__init__(config)
         
     | 
| 729 | 
         
            +
                    self.model = MoeModel(config)
         
     | 
| 730 | 
         
            +
                    self.vocab_size = config.vocab_size
         
     | 
| 731 | 
         
            +
                    self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
         
     | 
| 732 | 
         
            +
             
     | 
| 733 | 
         
            +
                    # Initialize weights and apply final processing
         
     | 
| 734 | 
         
            +
                    self.post_init()
         
     | 
| 735 | 
         
            +
             
     | 
| 736 | 
         
            +
                def get_input_embeddings(self):
         
     | 
| 737 | 
         
            +
                    return self.model.embed_tokens
         
     | 
| 738 | 
         
            +
             
     | 
| 739 | 
         
            +
                def set_input_embeddings(self, value):
         
     | 
| 740 | 
         
            +
                    self.model.embed_tokens = value
         
     | 
| 741 | 
         
            +
             
     | 
| 742 | 
         
            +
                def get_output_embeddings(self):
         
     | 
| 743 | 
         
            +
                    return self.lm_head
         
     | 
| 744 | 
         
            +
             
     | 
| 745 | 
         
            +
                def set_output_embeddings(self, new_embeddings):
         
     | 
| 746 | 
         
            +
                    self.lm_head = new_embeddings
         
     | 
| 747 | 
         
            +
             
     | 
| 748 | 
         
            +
                def set_decoder(self, decoder):
         
     | 
| 749 | 
         
            +
                    self.model = decoder
         
     | 
| 750 | 
         
            +
             
     | 
| 751 | 
         
            +
                def get_decoder(self):
         
     | 
| 752 | 
         
            +
                    return self.model
         
     | 
| 753 | 
         
            +
             
     | 
| 754 | 
         
            +
                def forward(
         
     | 
| 755 | 
         
            +
                    self,
         
     | 
| 756 | 
         
            +
                    input_ids: torch.LongTensor = None,
         
     | 
| 757 | 
         
            +
                    attention_mask: Optional[torch.Tensor] = None,
         
     | 
| 758 | 
         
            +
                    position_ids: Optional[torch.LongTensor] = None,
         
     | 
| 759 | 
         
            +
                    past_key_values: Optional[List[torch.FloatTensor]] = None,
         
     | 
| 760 | 
         
            +
                    inputs_embeds: Optional[torch.FloatTensor] = None,
         
     | 
| 761 | 
         
            +
                    labels: Optional[torch.LongTensor] = None,
         
     | 
| 762 | 
         
            +
                    use_cache: Optional[bool] = None,
         
     | 
| 763 | 
         
            +
                    output_attentions: Optional[bool] = None,
         
     | 
| 764 | 
         
            +
                    output_hidden_states: Optional[bool] = None,
         
     | 
| 765 | 
         
            +
                    return_dict: Optional[bool] = None,
         
     | 
| 766 | 
         
            +
                ) -> Union[Tuple, CausalLMOutputWithPast]:
         
     | 
| 767 | 
         
            +
             
     | 
| 768 | 
         
            +
                    output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
         
     | 
| 769 | 
         
            +
                    output_hidden_states = (
         
     | 
| 770 | 
         
            +
                        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         
     | 
| 771 | 
         
            +
                    )
         
     | 
| 772 | 
         
            +
                    return_dict = return_dict if return_dict is not None else self.config.use_return_dict
         
     | 
| 773 | 
         
            +
             
     | 
| 774 | 
         
            +
                    # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
         
     | 
| 775 | 
         
            +
                    outputs = self.model(
         
     | 
| 776 | 
         
            +
                        input_ids=input_ids,
         
     | 
| 777 | 
         
            +
                        attention_mask=attention_mask,
         
     | 
| 778 | 
         
            +
                        position_ids=position_ids,
         
     | 
| 779 | 
         
            +
                        past_key_values=past_key_values,
         
     | 
| 780 | 
         
            +
                        inputs_embeds=inputs_embeds,
         
     | 
| 781 | 
         
            +
                        use_cache=use_cache,
         
     | 
| 782 | 
         
            +
                        output_attentions=output_attentions,
         
     | 
| 783 | 
         
            +
                        output_hidden_states=output_hidden_states,
         
     | 
| 784 | 
         
            +
                        return_dict=return_dict,
         
     | 
| 785 | 
         
            +
                    )
         
     | 
| 786 | 
         
            +
             
     | 
| 787 | 
         
            +
                    hidden_states = outputs[0]
         
     | 
| 788 | 
         
            +
                    if self.config.pretraining_tp > 1:
         
     | 
| 789 | 
         
            +
                        lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
         
     | 
| 790 | 
         
            +
                        logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
         
     | 
| 791 | 
         
            +
                        logits = torch.cat(logits, dim=-1)
         
     | 
| 792 | 
         
            +
                    else:
         
     | 
| 793 | 
         
            +
                        logits = self.lm_head(hidden_states)
         
     | 
| 794 | 
         
            +
                    logits = logits.float()
         
     | 
| 795 | 
         
            +
             
     | 
| 796 | 
         
            +
                    loss = None
         
     | 
| 797 | 
         
            +
                    if labels is not None:
         
     | 
| 798 | 
         
            +
                        # Shift so that tokens < n predict n
         
     | 
| 799 | 
         
            +
                        shift_logits = logits[..., :-1, :].contiguous()
         
     | 
| 800 | 
         
            +
                        shift_labels = labels[..., 1:].contiguous()
         
     | 
| 801 | 
         
            +
                        # Flatten the tokens
         
     | 
| 802 | 
         
            +
                        loss_fct = CrossEntropyLoss()
         
     | 
| 803 | 
         
            +
                        shift_logits = shift_logits.view(-1, self.config.vocab_size)
         
     | 
| 804 | 
         
            +
                        shift_labels = shift_labels.view(-1)
         
     | 
| 805 | 
         
            +
                        # Enable model parallelism
         
     | 
| 806 | 
         
            +
                        shift_labels = shift_labels.to(shift_logits.device)
         
     | 
| 807 | 
         
            +
                        loss = loss_fct(shift_logits, shift_labels)
         
     | 
| 808 | 
         
            +
             
     | 
| 809 | 
         
            +
                    if not return_dict:
         
     | 
| 810 | 
         
            +
                        output = (logits,) + outputs[1:]
         
     | 
| 811 | 
         
            +
                        return (loss,) + output if loss is not None else output
         
     | 
| 812 | 
         
            +
             
     | 
| 813 | 
         
            +
                    return CausalLMOutputWithPast(
         
     | 
| 814 | 
         
            +
                        loss=loss,
         
     | 
| 815 | 
         
            +
                        logits=logits,
         
     | 
| 816 | 
         
            +
                        past_key_values=outputs.past_key_values,
         
     | 
| 817 | 
         
            +
                        hidden_states=outputs.hidden_states,
         
     | 
| 818 | 
         
            +
                        attentions=outputs.attentions,
         
     | 
| 819 | 
         
            +
                    )
         
     | 
| 820 | 
         
            +
             
     | 
| 821 | 
         
            +
                def prepare_inputs_for_generation(
         
     | 
| 822 | 
         
            +
                    self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
         
     | 
| 823 | 
         
            +
                ):
         
     | 
| 824 | 
         
            +
                    if past_key_values:
         
     | 
| 825 | 
         
            +
                        input_ids = input_ids[:, -1:]
         
     | 
| 826 | 
         
            +
             
     | 
| 827 | 
         
            +
                    position_ids = kwargs.get("position_ids", None)
         
     | 
| 828 | 
         
            +
                    if attention_mask is not None and position_ids is None:
         
     | 
| 829 | 
         
            +
                        # create position_ids on the fly for batch generation
         
     | 
| 830 | 
         
            +
                        position_ids = attention_mask.long().cumsum(-1) - 1
         
     | 
| 831 | 
         
            +
                        position_ids.masked_fill_(attention_mask == 0, 1)
         
     | 
| 832 | 
         
            +
                        if past_key_values:
         
     | 
| 833 | 
         
            +
                            position_ids = position_ids[:, -1].unsqueeze(-1)
         
     | 
| 834 | 
         
            +
             
     | 
| 835 | 
         
            +
                    # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
         
     | 
| 836 | 
         
            +
                    if inputs_embeds is not None and past_key_values is None:
         
     | 
| 837 | 
         
            +
                        model_inputs = {"inputs_embeds": inputs_embeds}
         
     | 
| 838 | 
         
            +
                    else:
         
     | 
| 839 | 
         
            +
                        model_inputs = {"input_ids": input_ids}
         
     | 
| 840 | 
         
            +
             
     | 
| 841 | 
         
            +
                    model_inputs.update(
         
     | 
| 842 | 
         
            +
                        {
         
     | 
| 843 | 
         
            +
                            "position_ids": position_ids,
         
     | 
| 844 | 
         
            +
                            "past_key_values": past_key_values,
         
     | 
| 845 | 
         
            +
                            "use_cache": kwargs.get("use_cache"),
         
     | 
| 846 | 
         
            +
                            "attention_mask": attention_mask,
         
     | 
| 847 | 
         
            +
                        }
         
     | 
| 848 | 
         
            +
                    )
         
     | 
| 849 | 
         
            +
                    return model_inputs
         
     | 
| 850 | 
         
            +
             
     | 
| 851 | 
         
            +
                @staticmethod
         
     | 
| 852 | 
         
            +
                def _reorder_cache(past_key_values, beam_idx):
         
     | 
| 853 | 
         
            +
                    reordered_past = ()
         
     | 
| 854 | 
         
            +
                    for layer_past in past_key_values:
         
     | 
| 855 | 
         
            +
                        reordered_past += (
         
     | 
| 856 | 
         
            +
                            tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
         
     | 
| 857 | 
         
            +
                        )
         
     | 
| 858 | 
         
            +
                    return reordered_past
         
     | 
| 859 | 
         
            +
             
     | 
| 860 | 
         
            +
             
     | 
| 861 | 
         
            +
            class ForSequenceClassification(MoePreTrainedModel):
         
     | 
| 862 | 
         
            +
                def __init__(self, config):
         
     | 
| 863 | 
         
            +
                    super().__init__(config)
         
     | 
| 864 | 
         
            +
                    self.num_labels = config.num_labels
         
     | 
| 865 | 
         
            +
                    self.model = MoeModel(config)
         
     | 
| 866 | 
         
            +
                    self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
         
     | 
| 867 | 
         
            +
             
     | 
| 868 | 
         
            +
                    # Initialize weights and apply final processing
         
     | 
| 869 | 
         
            +
                    self.post_init()
         
     | 
| 870 | 
         
            +
             
     | 
| 871 | 
         
            +
                def get_input_embeddings(self):
         
     | 
| 872 | 
         
            +
                    return self.model.embed_tokens
         
     | 
| 873 | 
         
            +
             
     | 
| 874 | 
         
            +
                def set_input_embeddings(self, value):
         
     | 
| 875 | 
         
            +
                    self.model.embed_tokens = value
         
     | 
| 876 | 
         
            +
             
     | 
| 877 | 
         
            +
                def forward(
         
     | 
| 878 | 
         
            +
                    self,
         
     | 
| 879 | 
         
            +
                    input_ids: torch.LongTensor = None,
         
     | 
| 880 | 
         
            +
                    attention_mask: Optional[torch.Tensor] = None,
         
     | 
| 881 | 
         
            +
                    position_ids: Optional[torch.LongTensor] = None,
         
     | 
| 882 | 
         
            +
                    past_key_values: Optional[List[torch.FloatTensor]] = None,
         
     | 
| 883 | 
         
            +
                    inputs_embeds: Optional[torch.FloatTensor] = None,
         
     | 
| 884 | 
         
            +
                    labels: Optional[torch.LongTensor] = None,
         
     | 
| 885 | 
         
            +
                    use_cache: Optional[bool] = None,
         
     | 
| 886 | 
         
            +
                    output_attentions: Optional[bool] = None,
         
     | 
| 887 | 
         
            +
                    output_hidden_states: Optional[bool] = None,
         
     | 
| 888 | 
         
            +
                    return_dict: Optional[bool] = None,
         
     | 
| 889 | 
         
            +
                ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
         
     | 
| 890 | 
         
            +
             
     | 
| 891 | 
         
            +
             
     | 
| 892 | 
         
            +
                    return_dict = return_dict if return_dict is not None else self.config.use_return_dict
         
     | 
| 893 | 
         
            +
             
     | 
| 894 | 
         
            +
                    transformer_outputs = self.model(
         
     | 
| 895 | 
         
            +
                        input_ids,
         
     | 
| 896 | 
         
            +
                        attention_mask=attention_mask,
         
     | 
| 897 | 
         
            +
                        position_ids=position_ids,
         
     | 
| 898 | 
         
            +
                        past_key_values=past_key_values,
         
     | 
| 899 | 
         
            +
                        inputs_embeds=inputs_embeds,
         
     | 
| 900 | 
         
            +
                        use_cache=use_cache,
         
     | 
| 901 | 
         
            +
                        output_attentions=output_attentions,
         
     | 
| 902 | 
         
            +
                        output_hidden_states=output_hidden_states,
         
     | 
| 903 | 
         
            +
                        return_dict=return_dict,
         
     | 
| 904 | 
         
            +
                    )
         
     | 
| 905 | 
         
            +
                    hidden_states = transformer_outputs[0]
         
     | 
| 906 | 
         
            +
                    logits = self.score(hidden_states)
         
     | 
| 907 | 
         
            +
             
     | 
| 908 | 
         
            +
                    if input_ids is not None:
         
     | 
| 909 | 
         
            +
                        batch_size = input_ids.shape[0]
         
     | 
| 910 | 
         
            +
                    else:
         
     | 
| 911 | 
         
            +
                        batch_size = inputs_embeds.shape[0]
         
     | 
| 912 | 
         
            +
             
     | 
| 913 | 
         
            +
                    if self.config.pad_token_id is None and batch_size != 1:
         
     | 
| 914 | 
         
            +
                        raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
         
     | 
| 915 | 
         
            +
                    if self.config.pad_token_id is None:
         
     | 
| 916 | 
         
            +
                        sequence_lengths = -1
         
     | 
| 917 | 
         
            +
                    else:
         
     | 
| 918 | 
         
            +
                        if input_ids is not None:
         
     | 
| 919 | 
         
            +
                            sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1).to(
         
     | 
| 920 | 
         
            +
                                logits.device
         
     | 
| 921 | 
         
            +
                            )
         
     | 
| 922 | 
         
            +
                        else:
         
     | 
| 923 | 
         
            +
                            sequence_lengths = -1
         
     | 
| 924 | 
         
            +
             
     | 
| 925 | 
         
            +
                    pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
         
     | 
| 926 | 
         
            +
             
     | 
| 927 | 
         
            +
                    loss = None
         
     | 
| 928 | 
         
            +
                    if labels is not None:
         
     | 
| 929 | 
         
            +
                        labels = labels.to(logits.device)
         
     | 
| 930 | 
         
            +
                        if self.config.problem_type is None:
         
     | 
| 931 | 
         
            +
                            if self.num_labels == 1:
         
     | 
| 932 | 
         
            +
                                self.config.problem_type = "regression"
         
     | 
| 933 | 
         
            +
                            elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
         
     | 
| 934 | 
         
            +
                                self.config.problem_type = "single_label_classification"
         
     | 
| 935 | 
         
            +
                            else:
         
     | 
| 936 | 
         
            +
                                self.config.problem_type = "multi_label_classification"
         
     | 
| 937 | 
         
            +
             
     | 
| 938 | 
         
            +
                        if self.config.problem_type == "regression":
         
     | 
| 939 | 
         
            +
                            loss_fct = MSELoss()
         
     | 
| 940 | 
         
            +
                            if self.num_labels == 1:
         
     | 
| 941 | 
         
            +
                                loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
         
     | 
| 942 | 
         
            +
                            else:
         
     | 
| 943 | 
         
            +
                                loss = loss_fct(pooled_logits, labels)
         
     | 
| 944 | 
         
            +
                        elif self.config.problem_type == "single_label_classification":
         
     | 
| 945 | 
         
            +
                            loss_fct = CrossEntropyLoss()
         
     | 
| 946 | 
         
            +
                            loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
         
     | 
| 947 | 
         
            +
                        elif self.config.problem_type == "multi_label_classification":
         
     | 
| 948 | 
         
            +
                            loss_fct = BCEWithLogitsLoss()
         
     | 
| 949 | 
         
            +
                            loss = loss_fct(pooled_logits, labels)
         
     | 
| 950 | 
         
            +
                    if not return_dict:
         
     | 
| 951 | 
         
            +
                        output = (pooled_logits,) + transformer_outputs[1:]
         
     | 
| 952 | 
         
            +
                        return ((loss,) + output) if loss is not None else output
         
     | 
| 953 | 
         
            +
             
     | 
| 954 | 
         
            +
                    return SequenceClassifierOutputWithPast(
         
     | 
| 955 | 
         
            +
                        loss=loss,
         
     | 
| 956 | 
         
            +
                        logits=pooled_logits,
         
     | 
| 957 | 
         
            +
                        past_key_values=transformer_outputs.past_key_values,
         
     | 
| 958 | 
         
            +
                        hidden_states=transformer_outputs.hidden_states,
         
     | 
| 959 | 
         
            +
                        attentions=transformer_outputs.attentions,
         
     | 
| 960 | 
         
            +
                    )
         
     | 
    	
        moe_plus_plus_layer.py
    ADDED
    
    | 
         @@ -0,0 +1,224 @@ 
     | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
| 
         | 
|
| 1 | 
         
            +
            import typing
         
     | 
| 2 | 
         
            +
            from collections.abc import Callable
         
     | 
| 3 | 
         
            +
            from collections import defaultdict
         
     | 
| 4 | 
         
            +
            from typing import Any, Dict, TYPE_CHECKING, Optional, Tuple, List
         
     | 
| 5 | 
         
            +
             
     | 
| 6 | 
         
            +
            import torch
         
     | 
| 7 | 
         
            +
            import copy
         
     | 
| 8 | 
         
            +
             
     | 
| 9 | 
         
            +
            from torch import Tensor
         
     | 
| 10 | 
         
            +
            from torch.nn import Module
         
     | 
| 11 | 
         
            +
            import torch.nn.functional as F
         
     | 
| 12 | 
         
            +
             
     | 
| 13 | 
         
            +
            if TYPE_CHECKING:
         
     | 
| 14 | 
         
            +
                Base = Module[Tensor]
         
     | 
| 15 | 
         
            +
            else:
         
     | 
| 16 | 
         
            +
                Base = Module
         
     | 
| 17 | 
         
            +
             
     | 
| 18 | 
         
            +
             
     | 
| 19 | 
         
            +
            MOE_TOP_K = 2
         
     | 
| 20 | 
         
            +
            Constant = 2
         
     | 
| 21 | 
         
            +
             
     | 
| 22 | 
         
            +
             
     | 
| 23 | 
         
            +
            class CopyExpert(torch.nn.Module):
         
     | 
| 24 | 
         
            +
                def __init__(self, expert):
         
     | 
| 25 | 
         
            +
                    super(CopyExpert, self).__init__()
         
     | 
| 26 | 
         
            +
                    pass
         
     | 
| 27 | 
         
            +
             
     | 
| 28 | 
         
            +
                def forward(self, inputs):
         
     | 
| 29 | 
         
            +
                    return inputs
         
     | 
| 30 | 
         
            +
             
     | 
| 31 | 
         
            +
             
     | 
| 32 | 
         
            +
            class ZeroExpert(torch.nn.Module):
         
     | 
| 33 | 
         
            +
                def __init__(self, expert):
         
     | 
| 34 | 
         
            +
                    super(ZeroExpert, self).__init__()
         
     | 
| 35 | 
         
            +
                    pass
         
     | 
| 36 | 
         
            +
             
     | 
| 37 | 
         
            +
                def forward(self, inputs):
         
     | 
| 38 | 
         
            +
                    return torch.zeros_like(inputs).to(inputs.dtype).to(inputs.device)
         
     | 
| 39 | 
         
            +
             
     | 
| 40 | 
         
            +
             
     | 
| 41 | 
         
            +
            class ConstantExpert(torch.nn.Module):
         
     | 
| 42 | 
         
            +
                def __init__(self, expert):
         
     | 
| 43 | 
         
            +
                    super(ConstantExpert, self).__init__()
         
     | 
| 44 | 
         
            +
                    self.constant = torch.nn.Parameter(
         
     | 
| 45 | 
         
            +
                        torch.empty((expert.hidden_size)))
         
     | 
| 46 | 
         
            +
                    torch.nn.init.normal_(self.constant)
         
     | 
| 47 | 
         
            +
             
     | 
| 48 | 
         
            +
                    self.wg = torch.nn.Linear(expert.hidden_size, 2, bias=False)
         
     | 
| 49 | 
         
            +
                    self.softmax = torch.nn.Softmax(dim=-1)
         
     | 
| 50 | 
         
            +
             
     | 
| 51 | 
         
            +
                def forward(self, inputs):
         
     | 
| 52 | 
         
            +
                    # print(inputs.size())
         
     | 
| 53 | 
         
            +
                    weight = self.wg(inputs)
         
     | 
| 54 | 
         
            +
                    weight = self.softmax(weight)
         
     | 
| 55 | 
         
            +
                    return torch.einsum('b,bd->bd', [weight[:, 0].type_as(inputs), inputs]) + torch.einsum(
         
     | 
| 56 | 
         
            +
                            'b,d->bd', [weight[:, 1].type_as(inputs), self.constant.type_as(inputs)])
         
     | 
| 57 | 
         
            +
             
     | 
| 58 | 
         
            +
             
     | 
| 59 | 
         
            +
            def gating(logits: Tensor, moe_use_mixtral_gating=False, moe_use_logits_norm=False, moe_gate_norm_std=1.0) -> Dict[int, List[Tuple[int, float]]]:
         
     | 
| 60 | 
         
            +
                # gates shape [num_tokens, num_experts]
         
     | 
| 61 | 
         
            +
                num_experts = logits.size(1)
         
     | 
| 62 | 
         
            +
                if moe_use_mixtral_gating:
         
     | 
| 63 | 
         
            +
                    if moe_use_logits_norm:
         
     | 
| 64 | 
         
            +
                        target_std = moe_gate_norm_std
         
     | 
| 65 | 
         
            +
                        logits_std = logits.std(dim=1, keepdim=True)
         
     | 
| 66 | 
         
            +
                        logits = logits / (logits_std / target_std)
         
     | 
| 67 | 
         
            +
                    gates, indices = torch.topk(logits, k=MOE_TOP_K, dim=1)
         
     | 
| 68 | 
         
            +
                    gates = F.softmax(gates, dim=1)
         
     | 
| 69 | 
         
            +
                else:
         
     | 
| 70 | 
         
            +
                    target_std = moe_gate_norm_std
         
     | 
| 71 | 
         
            +
                    if moe_use_logits_norm:
         
     | 
| 72 | 
         
            +
                        logits_std = logits.std(dim=1, keepdim=True)
         
     | 
| 73 | 
         
            +
                        gates = F.softmax(logits / (logits_std / target_std), dim=1)
         
     | 
| 74 | 
         
            +
                    else:
         
     | 
| 75 | 
         
            +
                        gates = F.softmax(logits, dim=1)
         
     | 
| 76 | 
         
            +
                    # gates shape [num_tokens, MOE_TOP_K]
         
     | 
| 77 | 
         
            +
                    # indices shape [num_tokens, MOE_TOP_K]
         
     | 
| 78 | 
         
            +
                    gates, indices = torch.topk(gates, k=MOE_TOP_K, dim=1)
         
     | 
| 79 | 
         
            +
                    gates = torch.where(indices==(num_experts-1), torch.zeros_like(gates).to(gates.dtype).to(gates.device), gates)
         
     | 
| 80 | 
         
            +
                    gates /= torch.sum(gates, dim=1, keepdim=True)
         
     | 
| 81 | 
         
            +
             
     | 
| 82 | 
         
            +
                expert_info = defaultdict(list)
         
     | 
| 83 | 
         
            +
                for expert_id in range(num_experts):
         
     | 
| 84 | 
         
            +
                    token_ids, score_ids = torch.nonzero(indices == expert_id, as_tuple=True)
         
     | 
| 85 | 
         
            +
                    expert_info[expert_id] = [token_ids, gates[token_ids, score_ids]]
         
     | 
| 86 | 
         
            +
             
     | 
| 87 | 
         
            +
                return expert_info
         
     | 
| 88 | 
         
            +
             
     | 
| 89 | 
         
            +
             
     | 
| 90 | 
         
            +
            class Router(Module):
         
     | 
| 91 | 
         
            +
                def __init__(self,
         
     | 
| 92 | 
         
            +
                             model_dim: int,
         
     | 
| 93 | 
         
            +
                             num_experts: int,
         
     | 
| 94 | 
         
            +
                             moe_use_mixtral_gating: bool,
         
     | 
| 95 | 
         
            +
                             moe_2layer_gate: bool,
         
     | 
| 96 | 
         
            +
                             moe_use_logits_norm: bool,
         
     | 
| 97 | 
         
            +
                             moe_gate_norm_std: float,
         
     | 
| 98 | 
         
            +
                             ) -> None:
         
     | 
| 99 | 
         
            +
                    super().__init__()
         
     | 
| 100 | 
         
            +
             
     | 
| 101 | 
         
            +
                    if moe_2layer_gate:
         
     | 
| 102 | 
         
            +
                        self.wg = torch.nn.Sequential(
         
     | 
| 103 | 
         
            +
                            torch.nn.Linear(model_dim, num_experts * 8, bias=False).float(),
         
     | 
| 104 | 
         
            +
                            torch.nn.Tanh(),
         
     | 
| 105 | 
         
            +
                            torch.nn.Linear(num_experts * 8, num_experts, bias=False).float()).float()
         
     | 
| 106 | 
         
            +
                    else:
         
     | 
| 107 | 
         
            +
                        self.wg = torch.nn.Linear(model_dim, num_experts, bias=False).float()
         
     | 
| 108 | 
         
            +
             
     | 
| 109 | 
         
            +
                    self.gate_map = torch.nn.Linear(num_experts, num_experts, bias=False)
         
     | 
| 110 | 
         
            +
             
     | 
| 111 | 
         
            +
                    self.gate = gating
         
     | 
| 112 | 
         
            +
                    self.moe_use_mixtral_gating = moe_use_mixtral_gating
         
     | 
| 113 | 
         
            +
                    self.moe_use_logits_norm = moe_use_logits_norm
         
     | 
| 114 | 
         
            +
                    self.moe_gate_norm_std = moe_gate_norm_std
         
     | 
| 115 | 
         
            +
             
     | 
| 116 | 
         
            +
                def forward(self, input: torch.Tensor, gate_residual=None) -> Dict[int, List[Tuple[int, float]]]:
         
     | 
| 117 | 
         
            +
                    if isinstance(self.wg, torch.nn.Linear):
         
     | 
| 118 | 
         
            +
                        if self.wg.weight.dtype != torch.float32:
         
     | 
| 119 | 
         
            +
                            self.wg = self.wg.float()
         
     | 
| 120 | 
         
            +
                            setattr(self.wg.weight, 'router', True)
         
     | 
| 121 | 
         
            +
                    else:
         
     | 
| 122 | 
         
            +
                        if self.wg[0].weight.dtype != torch.float32:
         
     | 
| 123 | 
         
            +
                            self.wg = self.wg.float()
         
     | 
| 124 | 
         
            +
                            setattr(self.wg[0].weight, "router", True)
         
     | 
| 125 | 
         
            +
                            setattr(self.wg[2].weight, "router", True)
         
     | 
| 126 | 
         
            +
                    input_fp32 = input.float()
         
     | 
| 127 | 
         
            +
                    logits = self.wg(input_fp32)
         
     | 
| 128 | 
         
            +
             
     | 
| 129 | 
         
            +
                    if gate_residual is not None:
         
     | 
| 130 | 
         
            +
                        gate_residual = self.gate_map(gate_residual.to(self.gate_map.weight.dtype))
         
     | 
| 131 | 
         
            +
                        logits += gate_residual
         
     | 
| 132 | 
         
            +
             
     | 
| 133 | 
         
            +
                    gate_output = self.gate(logits, self.moe_use_mixtral_gating, self.moe_use_logits_norm, self.moe_gate_norm_std)
         
     | 
| 134 | 
         
            +
             
     | 
| 135 | 
         
            +
                    return gate_output, logits
         
     | 
| 136 | 
         
            +
             
     | 
| 137 | 
         
            +
             
     | 
| 138 | 
         
            +
            class Experts(torch.nn.Module):
         
     | 
| 139 | 
         
            +
                def __init__(self, expert, num_local_experts=1):
         
     | 
| 140 | 
         
            +
                    super(Experts, self).__init__()
         
     | 
| 141 | 
         
            +
             
     | 
| 142 | 
         
            +
                    self.experts = torch.nn.ModuleList(
         
     | 
| 143 | 
         
            +
                        [copy.deepcopy(expert) for _ in range(num_local_experts - 2 - Constant)] +
         
     | 
| 144 | 
         
            +
                        [ConstantExpert(expert) for _ in range(Constant)] +
         
     | 
| 145 | 
         
            +
                        [CopyExpert(expert), ZeroExpert(expert)])
         
     | 
| 146 | 
         
            +
             
     | 
| 147 | 
         
            +
                def forward(self, inputs):
         
     | 
| 148 | 
         
            +
                    raise NotImplementedError
         
     | 
| 149 | 
         
            +
             
     | 
| 150 | 
         
            +
             
     | 
| 151 | 
         
            +
            class MOELayer(Base):
         
     | 
| 152 | 
         
            +
                def __init__(self,
         
     | 
| 153 | 
         
            +
                             gate: Module,
         
     | 
| 154 | 
         
            +
                             experts: Module,
         
     | 
| 155 | 
         
            +
                             ep_size,
         
     | 
| 156 | 
         
            +
                             num_local_experts: int,
         
     | 
| 157 | 
         
            +
                             moe_use_mixtral_gating: bool,
         
     | 
| 158 | 
         
            +
                             moe_feature_no_mul_topk: bool) -> None:
         
     | 
| 159 | 
         
            +
                    super().__init__()
         
     | 
| 160 | 
         
            +
                    self.gate = gate
         
     | 
| 161 | 
         
            +
                    self.experts = experts
         
     | 
| 162 | 
         
            +
                    self.ep_size = ep_size
         
     | 
| 163 | 
         
            +
                    self.num_local_experts = num_local_experts
         
     | 
| 164 | 
         
            +
                    self.moe_use_mixtral_gating = moe_use_mixtral_gating
         
     | 
| 165 | 
         
            +
                    self.moe_feature_no_mul_topk = moe_feature_no_mul_topk
         
     | 
| 166 | 
         
            +
             
     | 
| 167 | 
         
            +
                def forward(self, *input: Tensor, gate_residual=None, **kwargs: Any) -> Tensor:
         
     | 
| 168 | 
         
            +
                    d_model = input[0].shape[-1]
         
     | 
| 169 | 
         
            +
                    reshaped_input = input[0].reshape(-1, d_model)
         
     | 
| 170 | 
         
            +
                    output = torch.zeros_like(reshaped_input)
         
     | 
| 171 | 
         
            +
                    expert_info, gate_residual = self.gate(reshaped_input, gate_residual)
         
     | 
| 172 | 
         
            +
                    if not (self.moe_use_mixtral_gating or self.moe_feature_no_mul_topk):
         
     | 
| 173 | 
         
            +
                        reshaped_input *= MOE_TOP_K
         
     | 
| 174 | 
         
            +
                    for expert, token_indices_and_gates in expert_info.items():
         
     | 
| 175 | 
         
            +
                        indices, gating = token_indices_and_gates
         
     | 
| 176 | 
         
            +
                        gating = gating.unsqueeze(-1)
         
     | 
| 177 | 
         
            +
                        tokens = reshaped_input.index_select(dim=0, index=indices)
         
     | 
| 178 | 
         
            +
                        expert_output = self.experts.experts[expert](tokens)
         
     | 
| 179 | 
         
            +
                        expert_output *= gating
         
     | 
| 180 | 
         
            +
                        output.index_add_(dim=0, index=indices, source=expert_output)
         
     | 
| 181 | 
         
            +
                    output = output.reshape(input[0].shape)
         
     | 
| 182 | 
         
            +
             
     | 
| 183 | 
         
            +
                    return output, gate_residual
         
     | 
| 184 | 
         
            +
             
     | 
| 185 | 
         
            +
             
     | 
| 186 | 
         
            +
            class MOE(torch.nn.Module):
         
     | 
| 187 | 
         
            +
                def __init__(self,
         
     | 
| 188 | 
         
            +
                             hidden_size,
         
     | 
| 189 | 
         
            +
                             expert,
         
     | 
| 190 | 
         
            +
                             num_experts=1,
         
     | 
| 191 | 
         
            +
                             ep_size=1,
         
     | 
| 192 | 
         
            +
                             moe_use_mixtral_gating=False,
         
     | 
| 193 | 
         
            +
                             moe_2layer_gate=True,
         
     | 
| 194 | 
         
            +
                             moe_use_logits_norm=False,
         
     | 
| 195 | 
         
            +
                             moe_gate_norm_std=1.0,
         
     | 
| 196 | 
         
            +
                             moe_feature_no_mul_topk=False):
         
     | 
| 197 | 
         
            +
                    super(MOE, self).__init__()
         
     | 
| 198 | 
         
            +
             
     | 
| 199 | 
         
            +
                    self.ep_size = ep_size
         
     | 
| 200 | 
         
            +
                    self.num_experts = num_experts
         
     | 
| 201 | 
         
            +
                    self.num_local_experts = num_experts // self.ep_size
         
     | 
| 202 | 
         
            +
                    self.moe_use_mixtral_gating = moe_use_mixtral_gating
         
     | 
| 203 | 
         
            +
                    self.moe_2layer_gate = moe_2layer_gate
         
     | 
| 204 | 
         
            +
                    self.moe_use_logits_norm = moe_use_logits_norm
         
     | 
| 205 | 
         
            +
                    self.moe_gate_norm_std = moe_gate_norm_std
         
     | 
| 206 | 
         
            +
                    self.moe_feature_no_mul_topk = moe_feature_no_mul_topk
         
     | 
| 207 | 
         
            +
             
     | 
| 208 | 
         
            +
                    experts = Experts(expert, self.num_local_experts)
         
     | 
| 209 | 
         
            +
                    self.moe = MOELayer(Router(hidden_size,
         
     | 
| 210 | 
         
            +
                                               num_experts,
         
     | 
| 211 | 
         
            +
                                               self.moe_use_mixtral_gating,
         
     | 
| 212 | 
         
            +
                                               self.moe_2layer_gate,
         
     | 
| 213 | 
         
            +
                                               self.moe_use_logits_norm,
         
     | 
| 214 | 
         
            +
                                               self.moe_gate_norm_std),
         
     | 
| 215 | 
         
            +
                                        experts,
         
     | 
| 216 | 
         
            +
                                        self.ep_size,
         
     | 
| 217 | 
         
            +
                                        self.num_local_experts,
         
     | 
| 218 | 
         
            +
                                        self.moe_use_mixtral_gating,
         
     | 
| 219 | 
         
            +
                                        self.moe_feature_no_mul_topk,
         
     | 
| 220 | 
         
            +
                                        )
         
     | 
| 221 | 
         
            +
             
     | 
| 222 | 
         
            +
                def forward(self, hidden_states, used_token=None, gate_residual=None):
         
     | 
| 223 | 
         
            +
                    output, gate_residual = self.moe(hidden_states, used_token, gate_residual=gate_residual)
         
     | 
| 224 | 
         
            +
                    return output, gate_residual
         
     | 
    	
        pytorch_model.bin.index.json
    ADDED
    
    | 
         The diff for this file is too large to render. 
		See raw diff 
     | 
| 
         | 
    	
        special_tokens_map.json
    ADDED
    
    | 
         @@ -0,0 +1 @@ 
     | 
|
| 
         | 
| 
         | 
|
| 1 | 
         
            +
            {"bos_token": {"__type": "AddedToken", "content": "<s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false}, "eos_token": {"__type": "AddedToken", "content": "</s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false}, "unk_token": {"__type": "AddedToken", "content": "<unk>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false}}
         
     | 
    	
        tokenizer.model
    ADDED
    
    | 
         @@ -0,0 +1,3 @@ 
     | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
| 
         | 
|
| 1 | 
         
            +
            version https://git-lfs.github.com/spec/v1
         
     | 
| 2 | 
         
            +
            oid sha256:36ec9a4d6fd7cc78fbb9e4afd89fb04cba0381b08a842ca0b60826073821f594
         
     | 
| 3 | 
         
            +
            size 994250
         
     | 
    	
        tokenizer_config.json
    ADDED
    
    | 
         @@ -0,0 +1 @@ 
     | 
|
| 
         | 
| 
         | 
|
| 1 | 
         
            +
            {"tokenizer_class": "LlamaTokenizer", "bos_token": {"__type": "AddedToken", "content": "<s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false}, "eos_token": {"__type": "AddedToken", "content": "</s>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false}, "unk_token": {"__type": "AddedToken", "content": "<unk>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false}, "pad_token": null, "add_bos_token": true, "add_eos_token": false, "clean_up_tokenization_spaces": false, "legacy": false, "model_max_length": 1000000000000000019884624838656, "sp_model_kwargs": {}}
         
     |