# Param2Moe

Param2Moeは、[BharatGen AI](https://huggingface.co/bharatgenai)が開発したMixture of Experts (MoE) 言語モデルである[Param-2-17B-MoE-A2.4B](https://huggingface.co/bharatgenai/Param2-17B-A2.4B-Thinking)のアーキテクチャです。総パラメータ数は17B、トークンあたりのアクティブパラメータ数は2.4Bです。英語、ヒンディー語、およびインドの21言語に対応しています。

主要なアーキテクチャ上の機能:

- **グループクエリアテンション**（クエリヘッド32、キー/バリューヘッド8）にQK正規化と完全なロータリー位置埋め込みを適用。
- **ハイブリッド Mixture of Experts**: 最初の層では dense な MLP を使用し、残りの層では各トークンを 64 個のエクスパートのうち 6 個にルーティングし、常にアクティブな 2 個の共有エクスパートを追加します。
- **Sigmoid routing**は、エキスパートバイアス補正とルーティングスケーリング係数を使用します。

アーキテクチャは[GLM-4-MoE](./glm4_moe)と同じですが、パラメータ名と設定名が異なります。auto クラスは GLM-4-MoE の実装（[Glm4MoeModel](/docs/transformers/main/ja/model_doc/glm4_moe#transformers.Glm4MoeModel) および [Glm4MoeForCausalLM](/docs/transformers/main/ja/model_doc/glm4_moe#transformers.Glm4MoeForCausalLM)）で読み込むため、[Param2MoeConfig](/docs/transformers/main/ja/model_doc/param2moe#transformers.Param2MoeConfig) だけが Param2Moe に固有です。公開されているチェックポイントは、読み込み時に GLM-4-MoE の名前に変換され、保存時に元の名前に戻されます。

以下の例は、[AutoModelForCausalLM](/docs/transformers/main/ja/model_doc/auto#transformers.AutoModelForCausalLM) クラスを使用してテキストを生成する方法を示しています。

```python
from transformers import AutoModelForCausalLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("bharatgenai/Param2-17B-A2.4B-Thinking")
model = AutoModelForCausalLM.from_pretrained("bharatgenai/Param2-17B-A2.4B-Thinking", device_map="auto")

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is the BharatGen Mission?"},
]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True)
output = model.generate(**inputs.to(model.device), max_new_tokens=300, do_sample=False)
print(tokenizer.decode(output[0][inputs["input_ids"].shape[1] :], skip_special_tokens=False))
```

## Param2MoeConfig[[transformers.Param2MoeConfig]]

#### transformers.Param2MoeConfig[[transformers.Param2MoeConfig]]

```python
transformers.Param2MoeConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vocab_size: int = 128000, hidden_size: int = 2048, intermediate_size: int = 9216, num_hidden_layers: int = 21, num_attention_heads: int = 32, num_key_value_heads: int = 8, hidden_act: str = 'silu', max_position_embeddings: int = 32768, initializer_range: float = 0.02, rms_norm_eps: float = 1e-06, use_cache: bool = True, tie_word_embeddings: bool = True, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, attention_bias: bool = False, attention_dropout: float | int = 0.0, moe_intermediate_size: int = 2048, num_experts_per_tok: int = 6, output_router_logits: bool = False, n_shared_experts: int = 2, n_routed_experts: int = 64, routed_scaling_factor: float = 2.5, n_group: int = 1, topk_group: int = 1, first_k_dense_replace: int = 1, norm_topk_prob: bool = True, use_qk_norm: bool = True, bos_token_id: int | None = None, eos_token_id: int | list[int] | None = 3, pad_token_id: int | None = 0, num_mtp_layers: int = 0, head_dim: int = 64)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/param2moe/configuration_param2moe.py#L30)

**パラメータ:**

vocab_size (`int`、*任意*、デフォルトは`128000`) : モデルの語彙サイズ。`input_ids`で表現できるトークンの種類数を定義します。

hidden_size (`int`、*任意*、デフォルトは`2048`) : 隠れ表現の次元数。

intermediate_size (`int`, *任意*, デフォルトは `9216`) : MLP 表現の次元数。

num_hidden_layers (`int`, *任意*, デフォルトは `21`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは `32`) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

num_key_value_heads (`int`, *optional*, デフォルトは `8`) : Grouped Query Attention を実装するために使用する key_value ヘッドの数です。`num_key_value_heads=num_attention_heads` の場合、モデルは Multi Head Attention (MHA) を使用し、`num_key_value_heads=1` の場合は Multi Query Attention (MQA) を使用し、それ以外の場合は GQA が使用されます。マルチヘッドのチェックポイントを GQA のチェックポイントに変換する際は、各グループの key ヘッドと value ヘッドは、そのグループ内の元のすべてのヘッドを平均プーリングして構築する必要があります。詳細については、[この論文](https://huggingface.co/papers/2305.13245)を参照してください。指定されない場合、デフォルトで `num_attention_heads` が使用されます。

hidden_act (`str`、*任意*、デフォルトは`silu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

max_position_embeddings (`int`、*任意*、デフォルトは`32768`) : このモデルが使用される可能性のある最大シーケンス長です。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

rms_norm_eps (`float`、*任意*、デフォルトは`1e-06`) : rms 正規化レイヤーで使用する epsilon。

use_cache (`bool`、*任意*、デフォルトは `True`) : モデルが最後のキー/バリューアテンションを返すかどうか（すべてのモデルで利用されるわけではありません）。`config.is_decoder=True` の場合、またはモデルがデコーダー専用の生成モデルである場合にのみ関連します。

tie_word_embeddings (`bool`、*任意*、デフォルトは`True`) : モデルの`tied_weights_keys`マッピングに従って重み埋め込みを共有するかどうか。

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *optional*) : RoPE 埋め込みの設定パラメータを含む辞書です。この辞書には `rope_theta` の値が含まれていなければならず、より長い `max_position_embeddings` で RoPE を使用する場合、スケーリングに使用されるパラメータが任意で含まれます。

attention_bias (`bool`、*任意*、デフォルトは`False`) : セルフアテンションにおけるクエリ、キー、バリュー、出力の投影層でバイアスを使用するかどうか。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

moe_intermediate_size (`int`、*optional*、デフォルトは`2048`) : ルーティングされたエキスパートの MLP の中間サイズ。

num_experts_per_tok (`int`、*任意*、デフォルトは`6`) : 各トークンをルーティングするエキスパートの数です。これは、トークン選択ルーティングにおけるtop-kの値です。

output_router_logits (`bool`, *任意*, デフォルトは `False`) : モデルがルーターのロジスティック値を返すかどうかを指定します。これを有効にすると、モデルはロードバランシングロスやルーターのzロスを含む補助ロスの出力も可能になります。

n_shared_experts (`int`、*任意*、デフォルトは`2`) : 共有エキスパートの数。

n_routed_experts (`int`、*任意*、デフォルトは`64`) : ルーティング対象のエクスパート数。

routed_scaling_factor (`float`、*任意*、デフォルトは `2.5`) : スケーリング係数またはルーティングされたエキスパート。

n_group (`int`、*optional*、デフォルトは 1) : ルーティングされたエキスパートのグループ数。

topk_group (`int`, *任意*, デフォルトは `1`) : トークンごとに選択されるグループの数（各トークンについて、選択されるエキスパートが `topk_group` 個のグループの範囲内にのみ存在することを保証します）。

first_k_dense_replace (`int`, *optional*, デフォルトは 1) : 浅い層(embed->dense->moe->moe...->lm_head)における dense 層の数。 \--k dense 層--/

norm_topk_prob (`bool`、*任意*、デフォルトは`True`) : ルーティングされたエキスパートの重みを正規化するかどうかを指定します。

use_qk_norm (`bool`、*任意*、デフォルトは`True`) : アテンションでクエリ・キーの正規化を使用するかどうか。

bos_token_id (`int`, *任意*) : 語彙内でストリームの開始に使用されるトークン ID。

eos_token_id (`Union[int, list[int]]`、*任意*、デフォルトは`3`) : 語彙内でストリーム終了に使用されるトークン ID。

pad_token_id (`int`, *任意*, デフォルトは `0`) : 語彙内でパディングに使用されるトークン ID。

num_mtp_layers (`int`、*optional*、デフォルトは 0) : ベースの Transformer モデルの後に追加できる Multi-Token Prediction (MTP) モジュールの数です。公開されているチェックポイントには MTP の重みは含まれていません。

head_dim (`int`、*任意*、デフォルトは`64`) : アテンションヘッドの次元数。None の場合、hidden_size // num_attention_heads がデフォルトとして使用されます。

これは Glm4MoeModel の設定を保存するための設定クラスです。指定された引数に基づいて Param2Moe モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[bharatgenai/Param2-17B-A2.4B-Thinking](https://huggingface.co/bharatgenai/Param2-17B-A2.4B-Thinking) と同様の設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:

```python
>>> from transformers import AutoModelForCausalLM, Param2MoeConfig

>>> # Initializing a Param2-17B-A2.4B style configuration
>>> configuration = Param2MoeConfig()

>>> # Initializing a model (which uses the GLM-4-MoE implementation) from that configuration
>>> model = AutoModelForCausalLM.from_config(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

