Skip to content

Commit

Permalink
fix mixtral moe
Browse files Browse the repository at this point in the history
  • Loading branch information
DesmonDay committed Feb 27, 2024
1 parent b50e5f7 commit 1627c85
Show file tree
Hide file tree
Showing 3 changed files with 744 additions and 387 deletions.
6 changes: 3 additions & 3 deletions llm/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,11 @@ def get_convert_example(model):

if base_model_prefix == "chatglm":
return convert_example_chatglm
elif base_model_prefix in ["chatglm_v2", "llama", "bloom", "opt", "qwen"]:
elif base_model_prefix in ["chatglm_v2", "llama", "bloom", "opt", "qwen", "mixtral"]:
return convert_example_common
else:
raise ValueError(
f"Unknown base_model_prefix: {model.base_model_prefix}. Supported base_model_prefix list: chatglm, bloom, llama."
f"Unknown base_model_prefix: {model.base_model_prefix}. Supported base_model_prefix list: chatglm, bloom, llama, qwen, mixtral"
)


Expand Down Expand Up @@ -107,7 +107,7 @@ def tokenize_rounds_example(tokenizer, example, data_args):
# 0. prepare data
context_data = example.get("context", {})
context_data["is_training"] = True

example["src"] = example["src"] if isinstance(example["src"], list) else [example["src"]]
example["tgt"] = example["tgt"] if isinstance(example["tgt"], list) else [example["tgt"]]

Expand Down
110 changes: 73 additions & 37 deletions paddlenlp/transformers/mixtral/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,28 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Mixtral model configuration"""

from paddlenlp.transformers import PretrainedConfig
from paddlenlp.transformers.configuration_utils import PretrainedConfig

__all__ = ["MixtralConfig"]
__all__ = [
"MixtralConfig",
]


class MixtralConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`MixtralModel`]. It is used to instantiate an
Mixtral model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the Mixtral-7B-v0.1 or Mixtral-7B-Instruct-v0.1.
This is the configuration class to store the configuration of a [`~MixtralModel`]. It is used to instantiate an Mixtral
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the Mixtral-7B-v0.1 or Mixtral-7B-Instruct-v0.1.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 32000):
Vocabulary size of the Mixtral model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`MixtralModel`]
`inputs_ids` passed when calling [`~MixtralModel`]
hidden_size (`int`, *optional*, defaults to 4096):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 14336):
Expand All @@ -39,13 +42,6 @@ class MixtralConfig(PretrainedConfig):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 32):
Number of attention heads for each attention layer in the Transformer encoder.
num_key_value_heads (`int`, *optional*, defaults to 8):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details checkout [this
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
The non-linear activation function (function or string) in the decoder.
max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
Expand All @@ -64,25 +60,47 @@ class MixtralConfig(PretrainedConfig):
The id of the "beginning-of-sequence" token.
eos_token_id (`int`, *optional*, defaults to 2):
The id of the "end-of-sequence" token.
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether the model's input and output word embeddings should be tied.
tie_word_embeddings(`bool`, *optional*, defaults to `False`):
Whether to tie weight embeddings.
rope_theta (`float`, *optional*, defaults to 1000000.0):
The base period of the RoPE embeddings.
sliding_window (`int`, *optional*):
Sliding window attention window size. If not specified, will default to `4096`.
Sliding window attention window size.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
num_experts_per_tok (`int`, *optional*, defaults to 2):
The number of experts to root per-token, can be also interpreted as the `top-p` routing
parameter.
parameter
num_local_experts (`int`, *optional*, defaults to 8):
Number of experts per Sparse MLP layer.
output_router_logits (`bool`, *optional*, defaults to `False`):
Whether or not the router logits should be returned by the model. Enabeling this will also
allow the model to output the auxiliary loss. See [here]() for more details
router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
The aux loss factor for the total loss.
"""
use_fused_rope(`bool`, *optional*, defaults to False):
Enable rope fusion or not.
num_key_value_heads (`int`, *optional*, defaults to 8):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details checkout [this
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
`num_attention_heads`.
Example:
```python
>>> from paddlenlp.transformer import MixtralModel, MixtralConfig
>>> # Initializing a Mixtral mixtral-7b style configuration
>>> configuration = MixtralConfig()
>>> # Initializing a model from the mixtral-7b style configuration
>>> model = MixtralModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""

model_type = "mixtral"
keys_to_ignore_at_inference = ["past_key_values"]
Expand All @@ -92,64 +110,82 @@ def __init__(
vocab_size=32000,
hidden_size=4096,
intermediate_size=14336,
max_position_embeddings=4096 * 32,
seq_length=2048,
num_hidden_layers=32,
num_attention_heads=32,
num_key_value_heads=8,
hidden_act="silu",
max_position_embeddings=4096 * 32,
initializer_range=0.02,
rms_norm_eps=1e-5,
use_cache=True,
use_recompute=False,
recompute_granularity="full",
no_recompute_layers=None,
use_flash_attention=False,
attention_dropout=0.0,
use_fused_rope=False,
rope_theta=1e6,
tensor_parallel_output=True,
sequence_parallel=False,
fuse_sequence_parallel_allreduce=False,
pad_token_id=None,
bos_token_id=1,
eos_token_id=2,
tie_word_embeddings=False,
rope_theta=1e6,
sliding_window=None,
attention_dropout=0.0,
num_experts_per_tok=2,
num_local_experts=8,
output_router_logits=False,
router_aux_loss_coef=0.001,
use_flash_attention=False,
use_fused_rope=False,
use_recompute=False,
recompute_granularity="full",
output_router_logits=False,
sliding_window=None,
**kwargs,
):
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.max_position_embeddings = max_position_embeddings
self.seq_length = seq_length
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.attention_dropout = attention_dropout

Check warning on line 150 in paddlenlp/transformers/mixtral/configuration.py

View check run for this annotation

Codecov / codecov/patch

paddlenlp/transformers/mixtral/configuration.py#L143-L150

Added lines #L143 - L150 were not covered by tests

# for backward compatibility
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads

self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act

Check warning on line 155 in paddlenlp/transformers/mixtral/configuration.py

View check run for this annotation

Codecov / codecov/patch

paddlenlp/transformers/mixtral/configuration.py#L152-L155

Added lines #L152 - L155 were not covered by tests
self.max_position_embeddings = max_position_embeddings

self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps

Check warning on line 158 in paddlenlp/transformers/mixtral/configuration.py

View check run for this annotation

Codecov / codecov/patch

paddlenlp/transformers/mixtral/configuration.py#L157-L158

Added lines #L157 - L158 were not covered by tests

self.use_cache = use_cache
self.use_recompute = use_recompute
self.recompute_granularity = recompute_granularity
self.no_recompute_layers = no_recompute_layers
self.use_flash_attention = use_flash_attention
self.tensor_parallel_output = tensor_parallel_output
self.sequence_parallel = sequence_parallel
self.fuse_sequence_parallel_allreduce = fuse_sequence_parallel_allreduce

Check warning on line 167 in paddlenlp/transformers/mixtral/configuration.py

View check run for this annotation

Codecov / codecov/patch

paddlenlp/transformers/mixtral/configuration.py#L160-L167

Added lines #L160 - L167 were not covered by tests

self.pad_token_id = pad_token_id
self.bos_token_id = bos_token_id
self.eos_token_id = eos_token_id

Check warning on line 171 in paddlenlp/transformers/mixtral/configuration.py

View check run for this annotation

Codecov / codecov/patch

paddlenlp/transformers/mixtral/configuration.py#L169-L171

Added lines #L169 - L171 were not covered by tests

self.use_fused_rope = use_fused_rope
self.rope_theta = rope_theta

Check warning on line 174 in paddlenlp/transformers/mixtral/configuration.py

View check run for this annotation

Codecov / codecov/patch

paddlenlp/transformers/mixtral/configuration.py#L173-L174

Added lines #L173 - L174 were not covered by tests
self.sliding_window = sliding_window
self.attention_dropout = attention_dropout

# ----------------- Experts -------------------- #
self.num_experts_per_tok = num_experts_per_tok
self.num_local_experts = num_local_experts
self.output_router_logits = output_router_logits
self.router_aux_loss_coef = router_aux_loss_coef
self.output_router_logits = output_router_logits

Check warning on line 180 in paddlenlp/transformers/mixtral/configuration.py

View check run for this annotation

Codecov / codecov/patch

paddlenlp/transformers/mixtral/configuration.py#L177-L180

Added lines #L177 - L180 were not covered by tests

self.use_flash_attention = use_flash_attention
self.use_fused_rope = use_fused_rope
self.use_recompute = use_recompute
self.recompute_granularity = recompute_granularity
self.sliding_window = sliding_window

Check warning on line 182 in paddlenlp/transformers/mixtral/configuration.py

View check run for this annotation

Codecov / codecov/patch

paddlenlp/transformers/mixtral/configuration.py#L182

Added line #L182 was not covered by tests

super().__init__(

Check warning on line 184 in paddlenlp/transformers/mixtral/configuration.py

View check run for this annotation

Codecov / codecov/patch

paddlenlp/transformers/mixtral/configuration.py#L184

Added line #L184 was not covered by tests
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
tensor_parallel_output=tensor_parallel_output,
**kwargs,
)
Loading

0 comments on commit 1627c85

Please sign in to comment.