diff --git a/Model_Architecture_Discussions/MiniCPM/MiniCPM.ipynb b/Model_Architecture_Discussions/MiniCPM/MiniCPM.ipynb
new file mode 100644
index 0000000..584f946
--- /dev/null
+++ b/Model_Architecture_Discussions/MiniCPM/MiniCPM.ipynb
@@ -0,0 +1,1176 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "/home/jeeves/.local/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
+ " from .autonotebook import tqdm as notebook_tqdm\n"
+ ]
+ }
+ ],
+ "source": [
+ "import math\n",
+ "import warnings\n",
+ "from typing import List, Optional, Tuple, Union, Dict\n",
+ "from collections import OrderedDict\n",
+ "\n",
+ "import torch\n",
+ "import torch.nn.functional as F\n",
+ "from torch import nn\n",
+ "from torch.nn import CrossEntropyLoss\n",
+ "import re\n",
+ "from dataclasses import dataclass\n",
+ "\n",
+ "\n",
+ "import logging\n",
+ "from configuration_minicpm import MiniCPMConfig # 直接导入\n",
+ "\n",
+ "logger = logging.getLogger(__name__)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "MiniCPM 采用标准的 Decoder 作为其架构,主要包括三个部分:Embedding, Attention 和 MLP 层。我们对每一部分进行拆解,以便更好地理解其工作原理。整体代码源自于 [MiniCPM 官方仓库](https://github.com/OpenBMB/MiniCPM),这里逐步搭建模型,以便更好地理解其工作原理。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "config = MiniCPMConfig(**json.load(open(\"config.json\")))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "@dataclass\n",
+ "class BaseModelOutputWithPast(OrderedDict):\n",
+ " last_hidden_state: torch.FloatTensor = None\n",
+ " past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None\n",
+ " hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None\n",
+ " attentions: Optional[Tuple[torch.FloatTensor, ...]] = None\n",
+ " \n",
+ "@dataclass\n",
+ "class CausalLMOutputWithPast(OrderedDict):\n",
+ " loss: Optional[torch.FloatTensor] = None\n",
+ " logits: torch.FloatTensor = None\n",
+ " past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None\n",
+ " hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None\n",
+ " attentions: Optional[Tuple[torch.FloatTensor, ...]] = None\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### RoPE"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "在计算 Embedding 时,采用了 RoPE(Rotary Positional Embedding)的相对位置编码方式,帮助模型更好地理解序列中的位置信息。RoPE 的核心思想是将位置编码的计算转换为旋转矩阵的计算,从而减少计算量。RoPE 的计算公式如下:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "`MiniCPMRotaryEmbedding` 实现了旋转位置嵌入(Rotary Position Embedding)。它计算并缓存旋转位置编码的余弦和正弦值,以便在前向传播过程中快速获取。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class MiniCPMRotaryEmbedding(nn.Module):\n",
+ " def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):\n",
+ " super().__init__()\n",
+ "\n",
+ " self.dim = dim\n",
+ " self.max_position_embeddings = max_position_embeddings\n",
+ " self.base = base\n",
+ " # 计算了逆频率inv_freq并使用register_buffer方法将其注册为一个缓冲区\n",
+ " inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))\n",
+ " self.register_buffer(\"inv_freq\", inv_freq, persistent=False)\n",
+ "\n",
+ " # 构建缓存\n",
+ " self._set_cos_sin_cache(\n",
+ " seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.float32\n",
+ " )\n",
+ "\n",
+ " def _set_cos_sin_cache(self, seq_len, device, dtype):\n",
+ " # 计算并缓存余弦和正弦值\n",
+ " self.max_seq_len_cached = seq_len\n",
+ " t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)\n",
+ " freqs = torch.outer(t, self.inv_freq)\n",
+ "\n",
+ " # 将频率扩展到维度上\n",
+ " emb = torch.cat((freqs, freqs), dim=-1)\n",
+ "\n",
+ " # 缓存余弦值和正弦值\n",
+ " self.register_buffer(\"cos_cached\", emb.cos().to(dtype), persistent=False)\n",
+ " self.register_buffer(\"sin_cached\", emb.sin().to(dtype), persistent=False)\n",
+ "\n",
+ " def forward(self, x, seq_len=None):\n",
+ " # 首先检查输入序列的长度是否超过了缓存的最大长度,如果超过了,则重新计算并缓存余弦和正弦值\n",
+ " # x: [bs, num_attention_heads, seq_len, head_size]\n",
+ " if seq_len > self.max_seq_len_cached:\n",
+ " self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)\n",
+ "\n",
+ " # 返回对应序列长度的余弦和正弦值\n",
+ " return (\n",
+ " self.cos_cached[:seq_len].to(dtype=x.dtype),\n",
+ " self.sin_cached[:seq_len].to(dtype=x.dtype),\n",
+ " )"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "此段代码的功能是对输入数据的一半隐藏维度进行旋转操作。将原本的后半部分旋转到前面,将原本的前半部分旋转到后面。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def rotate_half(x):\n",
+ " # 将输入张量 x 沿 emb 维度一分为二\n",
+ " x1 = x[..., : x.shape[-1] // 2]\n",
+ " x2 = x[..., x.shape[-1] // 2 :]\n",
+ " # 将后半部分取负号,然后与前半部分拼接,对输入张量的隐藏维度进行旋转\n",
+ " return torch.cat((-x2, x1), dim=-1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "此函数将旋转位置嵌入(Rotary Position Embedding)应用于查询和键张量。首先,函数获取键张量的数据类型,然后根据位置索引提取旋转嵌入的余弦和正弦部分,并在指定维度上进行扩展。为了提高计算的精度,在进行 embedding 计算时,从 bfloat16 数据类型转换为 float32 数据类型。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):\n",
+ " # 保存原始数据类型\n",
+ " orig_dtype = k.dtype # torch.bfloat16\n",
+ " \n",
+ " # 根据 position_ids 选择 cos 和 sin,并在指定维度上扩展\n",
+ " cos = cos[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim] 便于和[bs, num_heads, q_len, head_dim] 维度的 q,k 进行矩阵乘法\n",
+ " sin = sin[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]\n",
+ " \n",
+ " # 将 q 和 k 转换为 float32 类型,以便进行精确的计算\n",
+ " q_fp32 = q.to(dtype=torch.float32, device=q.device)\n",
+ " k_fp32 = k.to(dtype=torch.float32, device=k.device)\n",
+ " \n",
+ " # 计算 q 和 k 的旋转位置嵌入\n",
+ " q_embed = (q_fp32 * cos) + (rotate_half(q_fp32) * sin)\n",
+ " k_embed = (k_fp32 * cos) + (rotate_half(k_fp32) * sin)\n",
+ " \n",
+ " # 将结果转换回原始数据类型并返回\n",
+ " return q_embed.to(dtype=orig_dtype), k_embed.to(dtype=orig_dtype) # [bs, num_heads, q_len, head_dim]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Attention"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "在语言模型中,未来的 token 在当前时间步骤中是不可见的。因此,我们构造一个上三角矩阵来屏蔽未来的信息。在此矩阵中,对角线以上的部分(即未来的元素)被设置为极小的浮点数值(通常为负无穷大),这样做的目的是在自注意力机制的计算过程中,使这些部分被忽略或仅被赋予极小的权重,从而确保模型仅能“感知”到之前的元素。若存在缓存,则需要将过去的缓存纳入考虑范围。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def create_causal_mask(input_shape, dtype, device, past_length=0):\n",
+ " batch_size, query_length = input_shape\n",
+ " # 创建一个上三角矩阵,填充最小浮点值,表示未来的token不能看到\n",
+ " causal_mask = torch.triu(torch.full((query_length, query_length), torch.finfo(dtype).min, dtype=dtype, device=device), diagonal=1)\n",
+ " # 如果有过去的key-value长度,则在mask前面添加零矩阵\n",
+ " if past_length > 0:\n",
+ " causal_mask = torch.cat([torch.zeros(query_length, past_length, dtype=dtype, device=device), causal_mask], dim=-1)\n",
+ " # 扩展mask的维度以匹配批次大小,并返回\n",
+ " return causal_mask[None, None, :, :].expand(batch_size, 1, query_length, query_length + past_length)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "在 MiniCPM 模型中,原始的分词器(tokenizer)生成的掩码(mask)矩阵是一个二维矩阵,其中0表示填充(padding)位置,1表示真实令牌(token)位置。在注意力(attention)层中,我们需要将这个掩码矩阵扩展到四维,以便它能够与注意力矩阵进行逐元素相乘。这一步骤是为了确保模型在计算注意力权重时,只考虑真实令牌的位置,而忽略填充位置,从而提高模型处理不同长度输入序列的能力。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def expand_attention_mask(mask, dtype, target_length = None):\n",
+ " batch_size, source_length = mask.shape\n",
+ " target_length = target_length if target_length is not None else source_length\n",
+ "\n",
+ " # 扩展mask的维度以匹配目标长度和批次大小\n",
+ " expanded_mask = mask[:, None, None, :].expand(batch_size, 1, target_length, source_length).to(dtype)\n",
+ " # 反转mask,将1变为0,0变为1\n",
+ " inverted_mask = 1.0 - expanded_mask\n",
+ " # 将反转后的mask中为True的位置填充为最小浮点值\n",
+ " return inverted_mask.masked_fill(inverted_mask.bool(), torch.finfo(dtype).min)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "组合我们设计好的用于因果语言模型的 mask 和 padding mask,得到最终的 mask 矩阵。这个矩阵的作用是在自注意力机制中,屏蔽未来的信息,确保模型只能“感知”到之前的元素。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n",
+ "def prepare_4d_causal_attention_mask(\n",
+ " attention_mask: Optional[torch.Tensor],\n",
+ " query_length: int,\n",
+ " past_length: int,\n",
+ " dtype: torch.dtype,\n",
+ " device: Union[torch.device, \"str\"] = \"cpu\",\n",
+ "):\n",
+ "\n",
+ " # 如果attention_mask存在且是2维的\n",
+ " if attention_mask is not None and attention_mask.dim() == 2:\n",
+ " # 获取批次大小和查询长度\n",
+ " batch_size = attention_mask.shape[0]\n",
+ " query_length = query_length\n",
+ " # 更新input_shape和past_length\n",
+ " input_shape = (batch_size, query_length)\n",
+ " causal_mask = None\n",
+ " if query_length > 1:\n",
+ " # 创建4维的causal mask\n",
+ " causal_mask = create_causal_mask(input_shape, dtype, device, past_length)\n",
+ " # 扩展attention mask\n",
+ " expanded_mask = expand_attention_mask(attention_mask, dtype, query_length)\n",
+ " if causal_mask is not None:\n",
+ " # 将causal mask中对应expanded mask为True的位置填充为最小浮点值\n",
+ " expanded_attn_mask = causal_mask.masked_fill(expanded_mask.bool(), torch.finfo(dtype).min)\n",
+ " expanded_attn_mask = expanded_mask\n",
+ " return expanded_attn_mask\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "`MiniCPMAttention` 通过多头注意力机制高效处理长序列数据。它融合了动态头维度分配、旋转式位置编码(RoPE)、以及键值对缓存机制等多项技术,以提高模型的性能和灵活性。\n",
+ "\n",
+ "- **动态头维度分配**:通过将隐藏层的维度均匀分配给多个注意力头,实现了并行处理的优化,从而提高了计算效率。\n",
+ "- **RoPE 位置编码**:引入了旋转式位置编码,以增强模型对序列位置信息的捕捉能力。这在处理长序列时尤其重要,因为它能够有效地保持位置信息的连续性和一致性。\n",
+ "- **键值对缓存机制**:在自回归解码过程中,支持缓存先前计算的键值对,这一机制显著加速了连续解码任务的处理速度。\n",
+ "\n",
+ "相比如原始的 Attention,MiniCPMAttention 在计算 Embeddig 时采用 RoPE Embedding,这样可以更好地处理长序列。另外,MiniCPMAttention 支持键值对的缓存,这在自回归解码中非常有用,可以大大提高解码速度。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class MiniCPMAttention(nn.Module):\n",
+ " def __init__(self, config: MiniCPMConfig, layer_idx: Optional[int] = None):\n",
+ " super().__init__()\n",
+ " self.config = config\n",
+ " self.layer_idx = layer_idx\n",
+ " if layer_idx is None:\n",
+ " layer_idx.warn_once(\n",
+ " f\"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will \"\n",
+ " \"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` \"\n",
+ " \"when creating this class.\"\n",
+ " )\n",
+ "\n",
+ " self.attention_dropout = config.attention_dropout # 0.0\n",
+ " self.hidden_size = config.hidden_size # 2304\n",
+ " self.num_heads = config.num_attention_heads # 36\n",
+ " self.head_dim = self.hidden_size // self.num_heads # 64\n",
+ " self.num_key_value_heads = config.num_key_value_heads # 36\n",
+ " self.num_key_value_groups = self.num_heads // self.num_key_value_heads # 1\n",
+ " self.max_position_embeddings = config.max_position_embeddings # 2048\n",
+ " self.rope_theta = config.rope_theta # 10000.0\n",
+ " self.is_causal = True\n",
+ "\n",
+ " if (self.head_dim * self.num_heads) != self.hidden_size:\n",
+ " raise ValueError(\n",
+ " f\"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}\"\n",
+ " f\" and `num_heads`: {self.num_heads}).\"\n",
+ " )\n",
+ "\n",
+ " self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias) # (2304, 36*64=2304)\n",
+ " self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)\n",
+ " self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)\n",
+ " self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)\n",
+ " self._init_rope()\n",
+ "\n",
+ " def _init_rope(self):\n",
+ " self.rotary_emb = MiniCPMRotaryEmbedding(\n",
+ " self.head_dim,\n",
+ " max_position_embeddings=self.max_position_embeddings,\n",
+ " base=self.rope_theta,\n",
+ " )\n",
+ "\n",
+ " def forward(\n",
+ " self,\n",
+ " hidden_states: torch.Tensor,\n",
+ " attention_mask: Optional[torch.Tensor] = None,\n",
+ " position_ids: Optional[torch.LongTensor] = None,\n",
+ " past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n",
+ " output_attentions: bool = False,\n",
+ " use_cache: bool = False,\n",
+ " **kwargs,\n",
+ " ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n",
+ "\n",
+ " bsz, q_len, _ = hidden_states.size()\n",
+ "\n",
+ " # q,k,v 矩阵\n",
+ " query_states = self.q_proj(hidden_states)\n",
+ " key_states = self.k_proj(hidden_states)\n",
+ " value_states = self.v_proj(hidden_states)\n",
+ " \n",
+ " # 拆成 num_heads 个头 (bsz, num_heads, q_len, self.head_dim)\n",
+ " query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)\n",
+ " key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)\n",
+ " value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)\n",
+ "\n",
+ " kv_seq_len = key_states.shape[-2]\n",
+ " if past_key_value is not None and len(past_key_value) > 0 and len(past_key_value[0]) > self.layer_idx and len(past_key_value[0][self.layer_idx].shape) > 1:\n",
+ " # 如果有 kv-cache 缓存,需要加上缓存的长度\n",
+ " kv_seq_len += past_key_value[0][self.layer_idx].shape[0] \n",
+ " \n",
+ " # 获取 RoPE Embedding 对应位置的 cos 和 sin 值 ( 这里传入的 value_states 不会参与计算,只是确保类型和设备)\n",
+ " cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)\n",
+ " \n",
+ " # 对 q 和 k 向量应用 RoPE 位置编码\n",
+ " query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)\n",
+ " # 如果存在先前的 k-v 缓存\n",
+ " if past_key_value is not None:\n",
+ " # 若当前层缓存未初始化,则进行初始化\n",
+ " if len(past_key_value[0]) <= self.layer_idx:\n",
+ " # 为当前层新增 k-v 的缓存\n",
+ " past_key_value[0].append(key_states)\n",
+ " past_key_value[1].append(value_states)\n",
+ " else:\n",
+ " # 若当前层缓存已存在,通过在序列长度维度上进行拼接更新缓存\n",
+ " past_key_value[0][self.layer_idx] = torch.cat([past_key_value[0][self.layer_idx], key_states], dim=-2)\n",
+ " past_key_value[1][self.layer_idx] = torch.cat([past_key_value[1][self.layer_idx], value_states], dim=-2)\n",
+ "\n",
+ " key_states, value_states = past_key_value[0][self.layer_idx], past_key_value[1][self.layer_idx] \n",
+ " \n",
+ " attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)\n",
+ " \n",
+ " if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):\n",
+ " raise ValueError(\n",
+ " f\"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is\"\n",
+ " f\" {attn_weights.size()}\"\n",
+ " )\n",
+ "\n",
+ " if attention_mask is not None:\n",
+ " if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):\n",
+ " raise ValueError(\n",
+ " f\"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}\"\n",
+ " )\n",
+ " attn_weights = attn_weights + attention_mask\n",
+ "\n",
+ " # 使用32位浮点数精度以提高计算精度\n",
+ " attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)\n",
+ " attn_weights = F.dropout(attn_weights, p=self.attention_dropout, training=self.training)\n",
+ " attn_output = torch.matmul(attn_weights, value_states)\n",
+ "\n",
+ " if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):\n",
+ " raise ValueError(\n",
+ " f\"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is\"\n",
+ " f\" {attn_output.size()}\"\n",
+ " )\n",
+ " \n",
+ " attn_output = attn_output.transpose(1, 2).contiguous()\n",
+ "\n",
+ " attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)\n",
+ "\n",
+ " attn_output = self.o_proj(attn_output)\n",
+ "\n",
+ " if not output_attentions:\n",
+ " attn_weights = None\n",
+ " \n",
+ " return attn_output, attn_weights, past_key_value"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "在模型中,注意力层(attention layer)占据了大部分的参数量,这主要归因于多个注意力头(attention heads)的参数。其中,查询(Q)、键(K)、值(V)三个矩阵的参数量相同。给定隐藏层大小(hidden_size)为 2304,并使用 64 个注意力头,每个头的维度设置为 36,那么这三个矩阵的总参数量计算为 `3*2304*36*64=15,925,248`。\n",
+ "\n",
+ "此外,还需要一个映射矩阵将这 64 个头的输出重新映射回输入的维度,该映射矩阵的参数量为 `2304*2304=5,308,416`。\n",
+ "\n",
+ "因此,注意力层的总参数量为 `15,925,248 + 5,308,416 = 21,233,664` 约 21M。"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### RMSNorm"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "`rms_layernorm` 是一种归一化层,它结合了 RMSProp 优化器和 Layer Normalization 的概念。可以对输入进行归一化处理,使得网络在训练过程中更加稳定。\n",
+ "\n",
+ "$$ y = W \\times \\left(\\frac{H}{\\sqrt{mean(H^2) + \\epsilon}}\\right) $$\n",
+ "\n",
+ "`rms_layernorm`层首先计算输入的平方的均值,然后用输入除以这个均值的平方根(加上一个很小的常数以防止除以零),从而确保输入的每个元素都在一个相对稳定的范围内。然后,这个层会乘以一个可学习的权重参数。\n",
+ "\n",
+ "这种归一化策略有助于减少训练过程中的内部协变量偏移,降低模型对初始化的敏感度,同时也能加速训练过程。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n",
+ "class MiniCPMRMSNorm(nn.Module):\n",
+ " def __init__(self, hidden_size, eps=1e-6):\n",
+ " super().__init__()\n",
+ " # 初始化权重参数为1,形状由hidden_size决定\n",
+ " self.weight = nn.Parameter(torch.ones(hidden_size)) \n",
+ " # 设置方差的epsilon值,防止除以0\n",
+ " self.variance_epsilon = eps\n",
+ "\n",
+ " def forward(self, hidden_states):\n",
+ " # 保存输入的数据类型,以便后续恢复\n",
+ " old_dtype = hidden_states.dtype\n",
+ " # 计算方差,先转换数据类型以提高精度,然后计算平方的均值\n",
+ " variance = hidden_states.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)\n",
+ " # 标准化隐藏状态,使用rsqrt(方差+epsilon的倒数根)进行缩放,并恢复原数据类型\n",
+ " hidden_states = (hidden_states * torch.rsqrt(variance + self.variance_epsilon)).to(old_dtype)\n",
+ " # 应用权重参数,进行缩放\n",
+ " return hidden_states * self.weight\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### SwiGLU 的 MLP"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "MiniCPM 的 MLP(多层感知器)结构采用 SwiGLU 激活层。该结构包含三个线性层:gate_proj、up_proj 和 down_proj,以及一个 SiLU 激活函数。将 gate_proj 层的结果通过 SiLU 激活函数转化,控制 up_proj 层的激活权重,对输入 x 进行特征提取和转换,然后通过 down_proj 层将转换后的特征映射回原始维度,从而实现一次前向传播。这种设计策略使得模型在保持输出维度不变的同时,能够有效地提取和转换输入特征。"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "SiLU(Sigmoid Linear Unit)激活函数是一种非线性函数,其公式为 $$ f(x) = x \\cdot \\sigma(x) $$当输入值为负时,该函数的输出接近于0;而当输入值为正时,输出则接近于输入值本身。这种特性使得 SiLU 函数具有无上界、有下界、平滑且非单调的特征。在深度学习模型的众多实践中,SiLU 函数已被证明在性能上超越了 ReLU 及其他激活函数。SiLU 函数不仅继承了 ReLU 激活函数的优点(例如,能够有效缓解梯度消失问题),同时也克服了 ReLU 函数的一些不足(例如,ReLU 函数在负数部分梯度为零,且非零中心)。此外,SiLU 函数是一种平滑函数,这意味着在其整个定义域内都存在导数,这对于优化过程是极其有利的。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ " \n",
+ "class MiniCPMMLP(nn.Module):\n",
+ " def __init__(self, config):\n",
+ " super().__init__()\n",
+ " self.config = config\n",
+ " self.hidden_size = config.hidden_size # 2304\n",
+ " self.intermediate_size = config.intermediate_size # 5760\n",
+ " self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)\n",
+ " self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)\n",
+ " self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)\n",
+ " self.act_fn = nn.SiLU()\n",
+ "\n",
+ " def forward(self, x): \n",
+ " down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))\n",
+ " return down_proj"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "MLP 层是模型参数量的另一个重要来源。在 MiniCPM 模型中,MLP 层的参数量主要来自于三个线性层(gate_proj、up_proj 和 down_proj)的参数。给定隐藏层大小(hidden_size)为 2304,up_proj 和 gate_proj 将均数据升维到 5760,down_proj 再降维到 2304,那么这三个线性层的参数量分别为 `2304*5760=13,276,160`,`2304*5760=13,276,160`,`5760*2304=13,276,160`。\n",
+ "\n",
+ "MLP 层的总参数量为 `13,276,160 + 13,276,160 + 13,276,160 = 39,828,480`,约 39M。"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### DecoderLayer"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "在构建 MiniCPM 模型的解码器层 `MiniCPMDecoderLayer` 时,我们将充分利用已经构建的关键组件:`MiniCPMAttention` 类负责执行注意力计算,`MiniCPMMLP` 类处理全连接层的运算,而 `MiniCPMRMSNorm` 类则负责执行层归一化操作,这包括对输入的隐藏状态进行归一化以及在注意力计算之后进行归一化处理。\n",
+ "\n",
+ "解码器层的处理流程遵循了解码器层设计的通用模式。首先,对输入的隐藏状态进行层归一化处理,接着通过自注意力机制对其进行加工处理。处理后的隐藏状态会与原始的隐藏状态进行残差连接,然后进行比例缩放。之后,对这个经过残差连接和比例缩放处理的隐藏状态再次进行层归一化处理,并通过全连接层进行加工处理。处理后的隐藏状态再次与原始的隐藏状态进行残差连接,并进行比例缩放。\n",
+ "\n",
+ "\n",
+ "在深层神经网络中,随着层数的增加,残差连接的累积可能导致梯度爆炸或梯度消失的问题。通过引入缩放机制,可以确保每一层的输出保持在一个合理的范围内,从而提升训练过程的稳定性和模型的整体性能。通过缩放因子 `self.scale_depth / math.sqrt(self.num_hidden_layers)` 调整残差连接的贡献度,以确保每一层的输出既不会因层数增加而过大,也不会过小。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n",
+ "class MiniCPMDecoderLayer(nn.Module):\n",
+ " def __init__(self, config: MiniCPMConfig, layer_idx: int):\n",
+ " super().__init__()\n",
+ " self.hidden_size = config.hidden_size\n",
+ " self.self_attn = MiniCPMAttention(config=config, layer_idx=layer_idx)\n",
+ "\n",
+ " self.mlp = MiniCPMMLP(config)\n",
+ " self.input_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)\n",
+ " self.post_attention_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)\n",
+ "\n",
+ " self.scale_depth = config.scale_depth\n",
+ " self.num_hidden_layers = config.num_hidden_layers\n",
+ "\n",
+ " def forward(\n",
+ " self,\n",
+ " hidden_states: torch.Tensor,\n",
+ " attention_mask: Optional[torch.Tensor] = None,\n",
+ " position_ids: Optional[torch.LongTensor] = None,\n",
+ " past_key_value: Optional[Tuple[torch.Tensor]] = None,\n",
+ " output_attentions: Optional[bool] = False,\n",
+ " use_cache: Optional[bool] = False,\n",
+ " **kwargs,\n",
+ " ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:\n",
+ " \n",
+ " residual = hidden_states\n",
+ " # 对输入归一化\n",
+ " hidden_states = self.input_layernorm(hidden_states)\n",
+ " # Self Attention 计算\n",
+ " hidden_states, self_attn_weights, present_key_value = self.self_attn(\n",
+ " hidden_states=hidden_states,\n",
+ " attention_mask=attention_mask,\n",
+ " position_ids=position_ids,\n",
+ " past_key_value=past_key_value,\n",
+ " output_attentions=output_attentions,\n",
+ " use_cache=use_cache,\n",
+ " **kwargs,\n",
+ " )\n",
+ " # 应用残差连接并缩放\n",
+ " hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))\n",
+ "\n",
+ " residual = hidden_states\n",
+ " # 对 attention 结果归一化\n",
+ " hidden_states = self.post_attention_layernorm(hidden_states)\n",
+ "\n",
+ " hidden_states = self.mlp(hidden_states)\n",
+ " # 应用残差连接并缩放\n",
+ " hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))\n",
+ "\n",
+ " outputs = (hidden_states,)\n",
+ "\n",
+ " if output_attentions:\n",
+ " outputs += (self_attn_weights,)\n",
+ "\n",
+ " if use_cache:\n",
+ " outputs += (present_key_value,)\n",
+ "\n",
+ " return outputs\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "每个解码层都由 attention 层和 MLP 层组成,所以一个解码器的参数量为 `21,233,664 + 39,828,480 = 61,062,144` 约 61M。"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Model"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "用一个 Model 类进行所有 MiniCPM 的基本配置"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ " \n",
+ "class MiniCPMPreTrainedModel(nn.Module):\n",
+ " def __init__(self, *args, **kwargs):\n",
+ " self.config = args[0]\n",
+ "\n",
+ " super().__init__()\n",
+ "\n",
+ " def _init_weights(self, module):\n",
+ " std = self.config.initializer_range\n",
+ " if isinstance(module, nn.Linear):\n",
+ " module.weight.data.normal_(mean=0.0, std=std)\n",
+ " if module.bias is not None:\n",
+ " module.bias.data.zero_()\n",
+ " elif isinstance(module, nn.Embedding):\n",
+ " module.weight.data.normal_(mean=0.0, std=std)\n",
+ " if module.padding_idx is not None:\n",
+ " module.weight.data[module.padding_idx].zero_()\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "MiniCPMModel 使整个模型的核心部分,它负责整个模型的前向计算过程。包括以下几个关键步骤:\n",
+ "\n",
+ "1. **参数校验**:确保`input_ids`和`inputs_embeds`不会同时指定。\n",
+ "2. **位置ID处理**:若未提供`position_ids`,则自动创建一个序列。\n",
+ "3. **词嵌入生成**:基于`input_ids`生成词嵌入,或直接采用`inputs_embeds`。\n",
+ "4. **注意力掩码准备**:构造一个四维的因果注意力掩码。\n",
+ "5. **隐藏状态初始化**:以词嵌入向量初始化隐藏状态。\n",
+ "\n",
+ "在完成隐藏状态的初始化后,模型通过若干解码器层对隐藏状态进行加工处理。在此过程中,根据需求,模型能够输出隐藏状态和注意力机制的详细信息。这包括对最终层隐藏状态的归一化处理,以及对所有隐藏状态和自注意力机制输出的汇总。此外,还涉及到批次大小和序列长度的计算、缓存机制的管理、位置索引的生成、词嵌入层的操作、解码器层的加工处理,以及最终输出层的归一化处理。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n",
+ "class MiniCPMModel(MiniCPMPreTrainedModel):\n",
+ "\n",
+ " def __init__(self, config: MiniCPMConfig):\n",
+ " super().__init__(config)\n",
+ "\n",
+ " self.padding_idx = config.pad_token_id\n",
+ " self.vocab_size = config.vocab_size\n",
+ "\n",
+ " self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)\n",
+ " self.layers = nn.ModuleList(\n",
+ " [MiniCPMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]\n",
+ " )\n",
+ "\n",
+ " self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)\n",
+ "\n",
+ " self.gradient_checkpointing = False\n",
+ " # self._init_weights()\n",
+ " \n",
+ " def _init_weights(self, module):\n",
+ " std = self.config.initializer_range\n",
+ " if isinstance(module, nn.Linear):\n",
+ " module.weight.data.normal_(mean=0.0, std=std)\n",
+ " if module.bias is not None:\n",
+ " module.bias.data.zero_()\n",
+ " elif isinstance(module, nn.Embedding):\n",
+ " module.weight.data.normal_(mean=0.0, std=std)\n",
+ " if module.padding_idx is not None:\n",
+ " module.weight.data[module.padding_idx].zero_()\n",
+ " \n",
+ " def get_input_embeddings(self):\n",
+ " return self.embed_tokens\n",
+ "\n",
+ " def set_input_embeddings(self, value):\n",
+ " self.embed_tokens = value\n",
+ "\n",
+ " def forward(\n",
+ " self,\n",
+ " input_ids: torch.LongTensor = None,\n",
+ " attention_mask: Optional[torch.Tensor] = None,\n",
+ " position_ids: Optional[torch.LongTensor] = None,\n",
+ " past_key_values: Optional[List[torch.FloatTensor]] = None,\n",
+ " inputs_embeds: Optional[torch.FloatTensor] = None,\n",
+ " use_cache: Optional[bool] = None,\n",
+ " output_attentions: Optional[bool] = None,\n",
+ " output_hidden_states: Optional[bool] = None,\n",
+ " return_dict: Optional[bool] = None,\n",
+ " ) -> Union[Tuple, BaseModelOutputWithPast]:\n",
+ " output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n",
+ " output_hidden_states = (\n",
+ " output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n",
+ " )\n",
+ " use_cache = use_cache if use_cache is not None else self.config.use_cache\n",
+ "\n",
+ " return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n",
+ "\n",
+ " if input_ids is not None and inputs_embeds is not None:\n",
+ " raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n",
+ " elif input_ids is not None:\n",
+ " batch_size, seq_length = input_ids.shape[:2]\n",
+ " elif inputs_embeds is not None:\n",
+ " batch_size, seq_length = inputs_embeds.shape[:2]\n",
+ " else:\n",
+ " raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n",
+ "\n",
+ " past_key_values_length = 0\n",
+ " \n",
+ " if use_cache:\n",
+ " if past_key_values is not None and len(past_key_values) > 0 and len(past_key_values[0]) > 0 and len(past_key_values[0][0].shape) > 2:\n",
+ " past_key_values_length = past_key_values[0][0].shape[-2]\n",
+ "\n",
+ " if position_ids is None:\n",
+ " device = input_ids.device if input_ids is not None else inputs_embeds.device\n",
+ " position_ids = torch.arange(\n",
+ " past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device\n",
+ " )\n",
+ " position_ids = position_ids.unsqueeze(0)\n",
+ "\n",
+ " if inputs_embeds is None:\n",
+ " inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb\n",
+ "\n",
+ " attention_mask = prepare_4d_causal_attention_mask(attention_mask, seq_length, past_key_values_length, inputs_embeds.dtype, inputs_embeds.device)\n",
+ " \n",
+ " # embed positions\n",
+ " hidden_states = inputs_embeds\n",
+ "\n",
+ " # decoder layers\n",
+ " all_hidden_states = () if output_hidden_states else None\n",
+ " all_self_attns = () if output_attentions else None\n",
+ " next_decoder_cache = None\n",
+ "\n",
+ " for decoder_layer in self.layers:\n",
+ " if output_hidden_states:\n",
+ " all_hidden_states += (hidden_states,)\n",
+ "\n",
+ " layer_outputs = decoder_layer(\n",
+ " hidden_states,\n",
+ " attention_mask=attention_mask,\n",
+ " position_ids=position_ids,\n",
+ " past_key_value=past_key_values,\n",
+ " output_attentions=output_attentions,\n",
+ " use_cache=use_cache,\n",
+ " )\n",
+ "\n",
+ " hidden_states = layer_outputs[0]\n",
+ "\n",
+ " if use_cache:\n",
+ " next_decoder_cache = layer_outputs[2 if output_attentions else 1]\n",
+ "\n",
+ " if output_attentions:\n",
+ " all_self_attns += (layer_outputs[1],)\n",
+ " # 对最终的结果归一化\n",
+ " hidden_states = self.norm(hidden_states)\n",
+ "\n",
+ " # 添加最后一个解码器层的隐藏状态\n",
+ " if output_hidden_states:\n",
+ " all_hidden_states += (hidden_states,)\n",
+ "\n",
+ " next_cache = None\n",
+ " if use_cache:\n",
+ " next_cache = next_decoder_cache\n",
+ " if not return_dict:\n",
+ " return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)\n",
+ " return BaseModelOutputWithPast(\n",
+ " last_hidden_state=hidden_states,\n",
+ " past_key_values=next_cache,\n",
+ " hidden_states=all_hidden_states,\n",
+ " attentions=all_self_attns,\n",
+ " )"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Embedding 占模型中非常大的一个参数量,这里的为 `122753 * 2304 = 282,822,912`,即约 282M 参数。"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### CausalLM"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "首先定义一个 `CausalLMOutputWithPast`类,主要用于因果语言模型(或自回归模型)的输出。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class CausalLMOutputWithPast(OrderedDict):\n",
+ " loss: Optional[torch.FloatTensor] = None\n",
+ " logits: torch.FloatTensor = None\n",
+ " past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None\n",
+ " hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None\n",
+ " attentions: Optional[Tuple[torch.FloatTensor, ...]] = None"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "我们来看一下如何准备输入数据的步骤。\n",
+ "\n",
+ "1. **调整输入数据**:利用`adjust_input_ids`函数,根据提供的注意力掩码或之前计算出的键值对长度,调整`input_ids`的长度,以确保其符合模型所期望的长度,从而能够正确地应用注意力机制。\n",
+ "\n",
+ "2. **处理先前的键值对**:计算先前键值对的长度,并基于此调整`input_ids`和`attention_mask`。\n",
+ "\n",
+ "3. **生成位置ID**:对于Transformer模型而言,位置ID极为关键,它为模型提供了序列中各个元素的位置信息。如果没有直接提供位置ID但提供了注意力掩码,该函数将依据注意力掩码来生成位置ID。\n",
+ "\n",
+ "4. **更新模型输入**:根据是否提供了`inputs_embeds`以及是否利用了先前的键值对,该函数决定使用哪种类型的输入,并将位置ID、先前的键值对、是否使用缓存以及注意力掩码等信息综合到模型输入中。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ " def prepare_inputs_for_generation(\n",
+ " self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs\n",
+ " ):\n",
+ " # 调整输入以匹配注意力掩码或过去的键值长度\n",
+ " def adjust_input_ids(input_ids, attention_mask, past_length):\n",
+ " if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:\n",
+ " return input_ids[:, -(attention_mask.shape[1] - past_length):]\n",
+ " elif past_length < input_ids.shape[1]:\n",
+ " return input_ids[:, past_length:]\n",
+ " return input_ids\n",
+ "\n",
+ " # 根据 kv 缓存的长度调整输入\n",
+ " if past_key_values is not None and len(past_key_values) > 0 and len(past_key_values[0]) > 0 and len(past_key_values[0][0].shape) > 2:\n",
+ " cache_length = past_length = past_key_values[0][0].shape[2]\n",
+ " max_cache_length = None\n",
+ "\n",
+ " input_ids = adjust_input_ids(input_ids, attention_mask, past_length)\n",
+ "\n",
+ " if max_cache_length is not None and attention_mask is not None and cache_length + input_ids.shape[1] > max_cache_length:\n",
+ " attention_mask = attention_mask[:, -max_cache_length:]\n",
+ " \n",
+ " # 按照注意力掩码生成位置ID\n",
+ " position_ids = kwargs.get(\"position_ids\", None)\n",
+ " if attention_mask is not None and position_ids is None:\n",
+ " position_ids = attention_mask.long().cumsum(-1) - 1\n",
+ " position_ids.masked_fill_(attention_mask == 0, 1)\n",
+ " if past_key_values:\n",
+ " position_ids = position_ids[:, -input_ids.shape[1]:]\n",
+ " \n",
+ " # 更新模型输入\n",
+ " model_inputs = {\"inputs_embeds\": inputs_embeds} if inputs_embeds is not None and past_key_values is None else {\"input_ids\": input_ids}\n",
+ " \n",
+ " model_inputs.update(\n",
+ " {\n",
+ " \"position_ids\": position_ids,\n",
+ " \"past_key_values\": past_key_values,\n",
+ " \"use_cache\": kwargs.get(\"use_cache\"),\n",
+ " \"attention_mask\": attention_mask,\n",
+ " }\n",
+ " )\n",
+ " return model_inputs "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "MiniCPM 采用了 tie-Embedding 的方式,即词嵌入层和输出层共享参数。这种方式可以减少模型的参数量,提高模型的训练效率。所以需要有获取和设置输入输出词嵌入层的方法。"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "`MiniCPMForCausalLM`类通过继承`MiniCPMPreTrainedModel`继承了基础属性。在其构造函数`__init__`中,执行了以下几个关键步骤:\n",
+ "\n",
+ "1. **初始化父类**:通过`super().__init__(config)`调用父类构造函数,确保 config 被正确初始化。\n",
+ "2. **构建模型核心**:实例化`MiniCPMModel`作为模型的核心组件。\n",
+ "3. **定义线性层**:根据配置中的`vocab_size`确定词汇表的大小,并定义一个线性层`lm_head`。该线性层负责将隐藏层状态映射到词汇表上的得分(即logits),并明确指出不使用偏置项(`bias=False`),直接复用输入 Emb 层(读取权重时手动实现)。\n",
+ "\n",
+ "在`forward`方法中,执行了以下几个关键步骤:\n",
+ "\n",
+ "1. **确定输出内容**:依据配置来决定是否输出注意力权重和隐藏层状态。\n",
+ "2. **执行前向传播**:调用`self.model`进行实际的前向传播计算,获取最后一层的隐藏层状态。\n",
+ "3. **转换为logits**:通过`lm_head`将隐藏层状态转换为logits。\n",
+ "4. **计算损失**:如果提供了标签,则根据这些标签计算交叉熵损失,这一步骤对模型的训练至关重要。\n",
+ "5. **返回结果**:根据`return_dict`的设置,决定是返回一个包含所有输出的元组,还是返回一个命名的输出对象`CausalLMOutputWithPast`。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ " \n",
+ "class MiniCPMForCausalLM(MiniCPMPreTrainedModel):\n",
+ " _tied_weights_keys = [\"lm_head.weight\"]\n",
+ "\n",
+ " def __init__(self, config):\n",
+ " super().__init__(config)\n",
+ " self.model = MiniCPMModel(config)\n",
+ " self.vocab_size = config.vocab_size\n",
+ " self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n",
+ "\n",
+ " # Initialize weights and apply final processing\n",
+ " # self.post_init()\n",
+ "\n",
+ " def get_input_embeddings(self):\n",
+ " return self.model.embed_tokens\n",
+ "\n",
+ " def set_input_embeddings(self, value):\n",
+ " self.model.embed_tokens = value\n",
+ "\n",
+ " def get_output_embeddings(self):\n",
+ " return self.lm_head\n",
+ "\n",
+ " def set_output_embeddings(self, new_embeddings):\n",
+ " self.lm_head = new_embeddings\n",
+ "\n",
+ " def set_decoder(self, decoder):\n",
+ " self.model = decoder\n",
+ "\n",
+ " def get_decoder(self):\n",
+ " return self.model\n",
+ "\n",
+ " def forward(\n",
+ " self,\n",
+ " input_ids: torch.LongTensor = None,\n",
+ " attention_mask: Optional[torch.Tensor] = None,\n",
+ " position_ids: Optional[torch.LongTensor] = None,\n",
+ " past_key_values: Optional[List[torch.FloatTensor]] = None,\n",
+ " inputs_embeds: Optional[torch.FloatTensor] = None,\n",
+ " labels: Optional[torch.LongTensor] = None,\n",
+ " use_cache: Optional[bool] = None,\n",
+ " output_attentions: Optional[bool] = None,\n",
+ " output_hidden_states: Optional[bool] = None,\n",
+ " return_dict: Optional[bool] = None,\n",
+ " ) -> Union[Tuple, CausalLMOutputWithPast]:\n",
+ "\n",
+ " output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n",
+ " output_hidden_states = (\n",
+ " output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n",
+ " )\n",
+ " return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n",
+ "\n",
+ " # 调用模型\n",
+ " outputs = self.model(\n",
+ " input_ids=input_ids,\n",
+ " attention_mask=attention_mask,\n",
+ " position_ids=position_ids,\n",
+ " past_key_values=past_key_values,\n",
+ " inputs_embeds=inputs_embeds,\n",
+ " use_cache=use_cache,\n",
+ " output_attentions=output_attentions,\n",
+ " output_hidden_states=output_hidden_states,\n",
+ " return_dict=return_dict,\n",
+ " )\n",
+ " \n",
+ " # 获取最后一层隐藏状态,并通过线性层(lm_head)转换为logits\n",
+ " hidden_states = outputs.last_hidden_state\n",
+ " logits = self.lm_head(hidden_states / (self.config.hidden_size / self.config.dim_model_base))\n",
+ " logits = logits.float()\n",
+ " \n",
+ " loss = None\n",
+ " # 如果存在标签,则进行损失计算\n",
+ " if labels is not None:\n",
+ " # 对logits和labels进行错位,以便预测下一个token\n",
+ " shift_logits = logits[..., :-1, :].contiguous()\n",
+ " shift_labels = labels[..., 1:].contiguous()\n",
+ " # 为交叉熵损失计算准备,将tokens展平\n",
+ " loss_fct = CrossEntropyLoss()\n",
+ " shift_logits = shift_logits.view(-1, self.config.vocab_size)\n",
+ " shift_labels = shift_labels.view(-1)\n",
+ " shift_labels = shift_labels.to(shift_logits.device)\n",
+ " # 计算交叉熵损失\n",
+ " loss = loss_fct(shift_logits, shift_labels)\n",
+ "\n",
+ " if not return_dict:\n",
+ " output = (logits,) + outputs[1:]\n",
+ " return (loss,) + output if loss is not None else output\n",
+ "\n",
+ " return CausalLMOutputWithPast(\n",
+ " loss=loss,\n",
+ " logits=logits,\n",
+ " past_key_values=outputs.past_key_values,\n",
+ " hidden_states=outputs.hidden_states,\n",
+ " attentions=outputs.attentions,\n",
+ " )"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "定义一个名为 `generate` 的方法,用于生成文本序列。该方法设计灵活,既能进行确定性的最大概率生成,也能通过随机采样产生更加多样化的输出。通过调整方法参数,用户可以在生成的质量与多样性之间做出权衡。\n",
+ "\n",
+ "1. **初始化缓存**:若启用缓存且未提供过去的键值对,则该方法会初始化一个空的键值对缓存。\n",
+ "\n",
+ "2. **准备输入**:计算批次大小,并初始化两个标志变量:`finished` 用于标记每个序列是否完成生成,`unfinished_sequences` 用于标记每个序列是否尚未完成。\n",
+ "\n",
+ "3. **获取 pad_token_id**:从 tokenizer 中获取 pad token 的 ID,该 ID 将用于后续填充生成的序列。\n",
+ "\n",
+ "4. **生成循环**:最多循环 `max_new_tokens` 次,每次循环生成一个新的 token。循环内部操作如下:\n",
+ " - 准备当前步骤的输入,并通过模型获取 logits。\n",
+ " - 若指定了 `top_k`,则将 logits 中非 top_k 的值设置为负无穷大,以便在采样时忽略它们。\n",
+ " - 根据 `do_sample` 参数决定是通过采样还是选择最大概率的 token 作为下一个 token。\n",
+ " - 更新输入序列,将新生成的 token 添加到输入序列中。\n",
+ " - 若提供了 `attention_mask`,则更新它以包括新的 token。\n",
+ " - 更新 `finished` 和 `unfinished_sequences` 标志,以标记哪些序列已完成或仍未完成。\n",
+ " - 检查是否所有序列都已完成,若是,则终止循环。\n",
+ "\n",
+ "5. **返回生成的序列**:最终,该方法返回包含原始及新生成 token 的输入序列。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ " @torch.no_grad()\n",
+ " def generate(self, input_ids, max_new_tokens=1024, temperature=1.0, top_k=None, use_cache=False, past_key_values=None, tokenizer=None, do_sample=False, **model_kwargs):\n",
+ " if use_cache and past_key_values is None:\n",
+ " # 初始化 kv 缓存\n",
+ " past_key_values = ([], [])\n",
+ " model_kwargs[\"past_key_values\"] = past_key_values\n",
+ " batch_size = input_ids.size(0)\n",
+ " # 初始化完成标志和未完成序列标志\n",
+ " finished = torch.zeros(batch_size, dtype=torch.bool).to(input_ids.device)\n",
+ " unfinished_sequences = torch.ones(batch_size, dtype=torch.bool).to(input_ids.device)\n",
+ " # 获取 pad_token_id 用于填充\n",
+ " pad_token_id = tokenizer.pad_token_id # 提前获取 pad_token_id\n",
+ "\n",
+ " for _ in range(max_new_tokens):\n",
+ " # 准备生成的输入\n",
+ " model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)\n",
+ "\n",
+ " logits = self(**model_inputs).logits[:, -1, :] / temperature # Apply temperature\n",
+ " \n",
+ " if top_k is not None:\n",
+ " indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]\n",
+ " logits[indices_to_remove] = -float('Inf')\n",
+ " \n",
+ " if do_sample:\n",
+ " probs = F.softmax(logits, dim=-1)\n",
+ " next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)\n",
+ " else:\n",
+ " next_tokens = torch.argmax(logits, dim=-1)\n",
+ " \n",
+ " # 更新未完成序列的 next_tokens \n",
+ " next_tokens = next_tokens * unfinished_sequences + pad_token_id * (~unfinished_sequences) \n",
+ " input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)\n",
+ " if \"attention_mask\" in model_kwargs:\n",
+ " # 更新 attention_mask\n",
+ " attention_mask = model_kwargs[\"attention_mask\"]\n",
+ " model_kwargs[\"attention_mask\"] = torch.cat(\n",
+ " [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1\n",
+ " )\n",
+ " # 更新完成和未完成的序列标志\n",
+ " finished |= (next_tokens.squeeze(-1) == tokenizer.eos_token_id)\n",
+ " unfinished_sequences &= ~finished\n",
+ " \n",
+ " # 如果所有序列都完成,则停止生成\n",
+ " if finished.all():\n",
+ " break\n",
+ "\n",
+ " return input_ids"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "所以整个 MiniCPM 的非 Embedding 参数量为:\n",
+ "\n",
+ "整个模型有 40 个 decoder 层,每个 decoder 层由一个 21M 参数的 attention 层和一个 39M 参数的 MLP 层组成,共约 61M 参数。\n",
+ "所以总参数量为 `61,062,144 * 40 = 2,442,485,760`,约 2.4B。\n",
+ "\n",
+ "Embedding 层后的参数为:`122753 * 2304 = 282,822,912`, 约 282M。\n",
+ "\n",
+ "考虑 Embedding 层后的总参数为: `2,442,485,760 + 282,822,912 = 2,725,308,672`,约 2.7B 参数。"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "aiLLM",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.12"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Model_Architecture_Discussions/MiniCPM/MiniCPM.py b/Model_Architecture_Discussions/MiniCPM/MiniCPM.py
new file mode 100644
index 0000000..bf98f65
--- /dev/null
+++ b/Model_Architecture_Discussions/MiniCPM/MiniCPM.py
@@ -0,0 +1,726 @@
+import math
+import warnings
+from typing import List, Optional, Tuple, Union, Dict
+from collections import OrderedDict
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+from torch.nn import CrossEntropyLoss
+import re
+from dataclasses import dataclass
+
+
+import logging
+from configuration_minicpm import MiniCPMConfig # 直接导入
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class BaseModelOutputWithPast(OrderedDict):
+ last_hidden_state: torch.FloatTensor = None
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
+
+@dataclass
+class CausalLMOutputWithPast(OrderedDict):
+ loss: Optional[torch.FloatTensor] = None
+ logits: torch.FloatTensor = None
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
+
+
+class MiniCPMRotaryEmbedding(nn.Module):
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
+ super().__init__()
+
+ self.dim = dim
+ self.max_position_embeddings = max_position_embeddings
+ self.base = base
+ # 计算了逆频率inv_freq并使用register_buffer方法将其注册为一个缓冲区
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+
+ # 构建缓存
+ self._set_cos_sin_cache(
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.float32
+ )
+
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
+ # 计算并缓存余弦和正弦值
+ self.max_seq_len_cached = seq_len
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
+ freqs = torch.outer(t, self.inv_freq)
+
+ # 将频率扩展到维度上
+ emb = torch.cat((freqs, freqs), dim=-1)
+
+ # 缓存余弦值和正弦值
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
+
+ def forward(self, x, seq_len=None):
+ # 首先检查输入序列的长度是否超过了缓存的最大长度,如果超过了,则重新计算并缓存余弦和正弦值
+ # x: [bs, num_attention_heads, seq_len, head_size]
+ if seq_len > self.max_seq_len_cached:
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
+
+ # 返回对应序列长度的余弦和正弦值
+ return (
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
+ )
+
+def rotate_half(x):
+ # 将输入张量 x 沿 emb 维度一分为二
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ # 将后半部分取负号,然后与前半部分拼接,对输入张量的隐藏维度进行旋转
+ return torch.cat((-x2, x1), dim=-1)
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
+ # 保存原始数据类型
+ orig_dtype = k.dtype # torch.bfloat16
+
+ # 根据 position_ids 选择 cos 和 sin,并在指定维度上扩展
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim] 便于和[bs, num_heads, q_len, head_dim] 维度的 q,k 进行矩阵乘法
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
+
+ # 将 q 和 k 转换为 float32 类型,以便进行精确的计算
+ q_fp32 = q.to(dtype=torch.float32, device=q.device)
+ k_fp32 = k.to(dtype=torch.float32, device=k.device)
+
+ # 计算 q 和 k 的旋转位置嵌入
+ q_embed = (q_fp32 * cos) + (rotate_half(q_fp32) * sin)
+ k_embed = (k_fp32 * cos) + (rotate_half(k_fp32) * sin)
+
+ # 将结果转换回原始数据类型并返回
+ return q_embed.to(dtype=orig_dtype), k_embed.to(dtype=orig_dtype) # [bs, num_heads, q_len, head_dim]
+
+
+def create_causal_mask(input_shape, dtype, device, past_length=0):
+ batch_size, query_length = input_shape
+ # 创建一个上三角矩阵,填充最小浮点值,表示未来的token不能看到
+ causal_mask = torch.triu(torch.full((query_length, query_length), torch.finfo(dtype).min, dtype=dtype, device=device), diagonal=1)
+ # 如果有过去的key-value长度,则在mask前面添加零矩阵
+ if past_length > 0:
+ causal_mask = torch.cat([torch.zeros(query_length, past_length, dtype=dtype, device=device), causal_mask], dim=-1)
+ # 扩展mask的维度以匹配批次大小,并返回
+ return causal_mask[None, None, :, :].expand(batch_size, 1, query_length, query_length + past_length)
+
+def expand_attention_mask(mask, dtype, target_length = None):
+ batch_size, source_length = mask.shape
+ target_length = target_length if target_length is not None else source_length
+
+ # 扩展mask的维度以匹配目标长度和批次大小
+ expanded_mask = mask[:, None, None, :].expand(batch_size, 1, target_length, source_length).to(dtype)
+ # 反转mask,将1变为0,0变为1
+ inverted_mask = 1.0 - expanded_mask
+ # 将反转后的mask中为True的位置填充为最小浮点值
+ return inverted_mask.masked_fill(inverted_mask.bool(), torch.finfo(dtype).min)
+
+def prepare_4d_causal_attention_mask(
+ attention_mask: Optional[torch.Tensor],
+ query_length: int,
+ past_length: int,
+ dtype: torch.dtype,
+ device: Union[torch.device, "str"] = "cpu",
+):
+
+ # 如果attention_mask存在且是2维的
+ if attention_mask is not None and attention_mask.dim() == 2:
+ # 获取批次大小和查询长度
+ batch_size = attention_mask.shape[0]
+ query_length = query_length
+ # 更新input_shape和past_length
+ input_shape = (batch_size, query_length)
+ causal_mask = None
+ if query_length > 1:
+ # 创建4维的causal mask
+ causal_mask = create_causal_mask(input_shape, dtype, device, past_length)
+ # 扩展attention mask
+ expanded_mask = expand_attention_mask(attention_mask, dtype, query_length)
+ if causal_mask is not None:
+ # 将causal mask中对应expanded mask为True的位置填充为最小浮点值
+ expanded_attn_mask = causal_mask.masked_fill(expanded_mask.bool(), torch.finfo(dtype).min)
+ expanded_attn_mask = expanded_mask
+ return expanded_attn_mask
+
+class MiniCPMAttention(nn.Module):
+ def __init__(self, config: MiniCPMConfig, layer_idx: Optional[int] = None):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ if layer_idx is None:
+ layer_idx.warn_once(
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
+ "when creating this class."
+ )
+
+ self.attention_dropout = config.attention_dropout # 0.0
+ self.hidden_size = config.hidden_size # 2304
+ self.num_heads = config.num_attention_heads # 36
+ self.head_dim = self.hidden_size // self.num_heads # 64
+ self.num_key_value_heads = config.num_key_value_heads # 36
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads # 1
+ self.max_position_embeddings = config.max_position_embeddings # 2048
+ self.rope_theta = config.rope_theta # 10000.0
+ self.is_causal = True
+
+ if (self.head_dim * self.num_heads) != self.hidden_size:
+ raise ValueError(
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
+ f" and `num_heads`: {self.num_heads})."
+ )
+
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias) # (2304, 36*64=2304)
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
+ self._init_rope()
+
+ def _init_rope(self):
+ self.rotary_emb = MiniCPMRotaryEmbedding(
+ self.head_dim,
+ max_position_embeddings=self.max_position_embeddings,
+ base=self.rope_theta,
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
+ output_attentions: bool = False,
+ use_cache: bool = False,
+ **kwargs,
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
+
+ bsz, q_len, _ = hidden_states.size()
+
+ # q,k,v 矩阵
+ query_states = self.q_proj(hidden_states)
+ key_states = self.k_proj(hidden_states)
+ value_states = self.v_proj(hidden_states)
+
+ # 拆成 num_heads 个头 (bsz, num_heads, q_len, self.head_dim)
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
+
+ kv_seq_len = key_states.shape[-2]
+ if past_key_value is not None and len(past_key_value) > 0 and len(past_key_value[0]) > self.layer_idx and len(past_key_value[0][self.layer_idx].shape) > 1:
+ # 如果有 kv-cache 缓存,需要加上缓存的长度
+ kv_seq_len += past_key_value[0][self.layer_idx].shape[0]
+
+ # 获取 RoPE Embedding 对应位置的 cos 和 sin 值 ( 这里传入的 value_states 不会参与计算,只是确保类型和设备)
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
+
+ # 对 q 和 k 向量应用 RoPE 位置编码
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
+ # 如果存在先前的 k-v 缓存
+ if past_key_value is not None:
+ # 若当前层缓存未初始化,则进行初始化
+ if len(past_key_value[0]) <= self.layer_idx:
+ # 为当前层新增 k-v 的缓存
+ past_key_value[0].append(key_states)
+ past_key_value[1].append(value_states)
+ else:
+ # 若当前层缓存已存在,通过在序列长度维度上进行拼接更新缓存
+ past_key_value[0][self.layer_idx] = torch.cat([past_key_value[0][self.layer_idx], key_states], dim=-2)
+ past_key_value[1][self.layer_idx] = torch.cat([past_key_value[1][self.layer_idx], value_states], dim=-2)
+
+ key_states, value_states = past_key_value[0][self.layer_idx], past_key_value[1][self.layer_idx]
+
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
+
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
+ raise ValueError(
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
+ f" {attn_weights.size()}"
+ )
+
+ if attention_mask is not None:
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
+ raise ValueError(
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
+ )
+ attn_weights = attn_weights + attention_mask
+
+ # 使用32位浮点数精度以提高计算精度
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
+ attn_weights = F.dropout(attn_weights, p=self.attention_dropout, training=self.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
+ raise ValueError(
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
+ f" {attn_output.size()}"
+ )
+
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
+
+ attn_output = self.o_proj(attn_output)
+
+ if not output_attentions:
+ attn_weights = None
+
+ return attn_output, attn_weights, past_key_value
+
+class MiniCPMRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps=1e-6):
+ super().__init__()
+ # 初始化权重参数为1,形状由hidden_size决定
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ # 设置方差的epsilon值,防止除以0
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states):
+ # 保存输入的数据类型,以便后续恢复
+ old_dtype = hidden_states.dtype
+ # 计算方差,先转换数据类型以提高精度,然后计算平方的均值
+ variance = hidden_states.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
+ # 标准化隐藏状态,使用rsqrt(方差+epsilon的倒数根)进行缩放,并恢复原数据类型
+ hidden_states = (hidden_states * torch.rsqrt(variance + self.variance_epsilon)).to(old_dtype)
+ # 应用权重参数,进行缩放
+ return hidden_states * self.weight
+
+class MiniCPMMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size # 2304
+ self.intermediate_size = config.intermediate_size # 5760
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = nn.SiLU()
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+class MiniCPMPreTrainedModel(nn.Module):
+ def __init__(self, *args, **kwargs):
+ self.config = args[0]
+
+ super().__init__()
+
+ def _init_weights(self, module):
+ std = self.config.initializer_range
+ if isinstance(module, nn.Linear):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+
+
+class MiniCPMDecoderLayer(nn.Module):
+ def __init__(self, config: MiniCPMConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.self_attn = MiniCPMAttention(config=config, layer_idx=layer_idx)
+
+ self.mlp = MiniCPMMLP(config)
+ self.input_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ self.scale_depth = config.scale_depth
+ self.num_hidden_layers = config.num_hidden_layers
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: Optional[bool] = False,
+ **kwargs,
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
+
+ residual = hidden_states
+ # 对输入归一化
+ hidden_states = self.input_layernorm(hidden_states)
+ # Self Attention 计算
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_value=past_key_value,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ # 应用残差连接并缩放
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
+
+ residual = hidden_states
+ # 对 attention 结果归一化
+ hidden_states = self.post_attention_layernorm(hidden_states)
+
+ hidden_states = self.mlp(hidden_states)
+ # 应用残差连接并缩放
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (self_attn_weights,)
+
+ if use_cache:
+ outputs += (present_key_value,)
+
+ return outputs
+
+
+class MiniCPMModel(MiniCPMPreTrainedModel):
+
+ def __init__(self, config: MiniCPMConfig):
+ super().__init__(config)
+
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [MiniCPMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+
+ self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ self.gradient_checkpointing = False
+ # self._init_weights()
+
+ def _init_weights(self, module):
+ std = self.config.initializer_range
+ if isinstance(module, nn.Linear):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+
+ def get_input_embeddings(self):
+ return self.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.embed_tokens = value
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ batch_size, seq_length = input_ids.shape[:2]
+ elif inputs_embeds is not None:
+ batch_size, seq_length = inputs_embeds.shape[:2]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ past_key_values_length = 0
+
+ if use_cache:
+ if past_key_values is not None and len(past_key_values) > 0 and len(past_key_values[0]) > 0 and len(past_key_values[0][0].shape) > 2:
+ past_key_values_length = past_key_values[0][0].shape[-2]
+
+ if position_ids is None:
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+ position_ids = torch.arange(
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
+ )
+ position_ids = position_ids.unsqueeze(0)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb
+
+ attention_mask = prepare_4d_causal_attention_mask(attention_mask, seq_length, past_key_values_length, inputs_embeds.dtype, inputs_embeds.device)
+
+ # embed positions
+ hidden_states = inputs_embeds
+
+ # decoder layers
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+ next_decoder_cache = None
+
+ for decoder_layer in self.layers:
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ layer_outputs = decoder_layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_value=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ if use_cache:
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
+
+ if output_attentions:
+ all_self_attns += (layer_outputs[1],)
+ # 对最终的结果归一化
+ hidden_states = self.norm(hidden_states)
+
+ # 添加最后一个解码器层的隐藏状态
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ next_cache = None
+ if use_cache:
+ next_cache = next_decoder_cache
+ if not return_dict:
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=next_cache,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attns,
+ )
+
+class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
+ _tied_weights_keys = ["lm_head.weight"]
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = MiniCPMModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ # self.post_init()
+
+ def get_input_embeddings(self):
+ return self.model.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.model.embed_tokens = value
+
+ def get_output_embeddings(self):
+ return self.lm_head
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head = new_embeddings
+
+ def set_decoder(self, decoder):
+ self.model = decoder
+
+ def get_decoder(self):
+ return self.model
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # 调用模型
+ outputs = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ # 获取最后一层隐藏状态,并通过线性层(lm_head)转换为logits
+ hidden_states = outputs.last_hidden_state
+ logits = self.lm_head(hidden_states / (self.config.hidden_size / self.config.dim_model_base))
+ logits = logits.float()
+
+ loss = None
+ # 如果存在标签,则进行损失计算
+ if labels is not None:
+ # 对logits和labels进行错位,以便预测下一个token
+ shift_logits = logits[..., :-1, :].contiguous()
+ shift_labels = labels[..., 1:].contiguous()
+ # 为交叉熵损失计算准备,将tokens展平
+ loss_fct = CrossEntropyLoss()
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
+ shift_labels = shift_labels.view(-1)
+ shift_labels = shift_labels.to(shift_logits.device)
+ # 计算交叉熵损失
+ loss = loss_fct(shift_logits, shift_labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return (loss,) + output if loss is not None else output
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
+ ):
+ # 调整输入以匹配注意力掩码或过去的键值长度
+ def adjust_input_ids(input_ids, attention_mask, past_length):
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
+ return input_ids[:, -(attention_mask.shape[1] - past_length):]
+ elif past_length < input_ids.shape[1]:
+ return input_ids[:, past_length:]
+ return input_ids
+
+ # 根据 kv 缓存的长度调整输入
+ if past_key_values is not None and len(past_key_values) > 0 and len(past_key_values[0]) > 0 and len(past_key_values[0][0].shape) > 2:
+ cache_length = past_length = past_key_values[0][0].shape[2]
+ max_cache_length = None
+
+ input_ids = adjust_input_ids(input_ids, attention_mask, past_length)
+
+ if max_cache_length is not None and attention_mask is not None and cache_length + input_ids.shape[1] > max_cache_length:
+ attention_mask = attention_mask[:, -max_cache_length:]
+
+ # 按照注意力掩码生成位置ID
+ position_ids = kwargs.get("position_ids", None)
+ if attention_mask is not None and position_ids is None:
+ position_ids = attention_mask.long().cumsum(-1) - 1
+ position_ids.masked_fill_(attention_mask == 0, 1)
+ if past_key_values:
+ position_ids = position_ids[:, -input_ids.shape[1]:]
+
+ # 更新模型输入
+ model_inputs = {"inputs_embeds": inputs_embeds} if inputs_embeds is not None and past_key_values is None else {"input_ids": input_ids}
+
+ model_inputs.update(
+ {
+ "position_ids": position_ids,
+ "past_key_values": past_key_values,
+ "use_cache": kwargs.get("use_cache"),
+ "attention_mask": attention_mask,
+ }
+ )
+ return model_inputs
+
+ @torch.inference_mode()
+ def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user",
+ max_length: int = 4096, num_beams=1, do_sample=True, top_p=0.8, temperature=0.3, logits_processor=None,
+ **kwargs):
+ if history is None:
+ history = []
+ if logits_processor:
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
+ else:
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
+ "temperature": temperature, "logits_processor": logits_processor, **kwargs}
+
+ history.append({"role": role, "content": query})
+ history_str = tokenizer.apply_chat_template(history, tokenize=False, add_generation_prompt=False)
+ inputs = tokenizer(history_str, return_tensors='pt').to(self.device)
+ outputs = self.generate(**inputs, **gen_kwargs)
+ outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
+ response = tokenizer.decode(outputs)
+ pattern = re.compile(r".*?(?=|<用户>)", re.DOTALL)
+ matches = pattern.findall(response)
+ if len(matches) > 0:
+ response = matches[0]
+ history.append({"role": "assistant", "content": response})
+ return response, history
+
+ '''进行推理'''
+ @torch.no_grad()
+ def generate(self, input_ids, max_new_tokens=1024, temperature=1.0, top_k=None, use_cache=False, past_key_values=None, tokenizer=None, do_sample=False, **model_kwargs):
+ if use_cache and past_key_values is None:
+ # 初始化 kv 缓存
+ past_key_values = ([], [])
+ model_kwargs["past_key_values"] = past_key_values
+ batch_size = input_ids.size(0)
+ # 初始化完成标志和未完成序列标志
+ finished = torch.zeros(batch_size, dtype=torch.bool).to(input_ids.device)
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.bool).to(input_ids.device)
+ # 获取 pad_token_id 用于填充
+ pad_token_id = tokenizer.pad_token_id # 提前获取 pad_token_id
+
+ for _ in range(max_new_tokens):
+ # 准备生成的输入
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
+
+ logits = self(**model_inputs).logits[:, -1, :] / temperature # Apply temperature
+
+ if top_k is not None:
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
+ logits[indices_to_remove] = -float('Inf')
+
+ if do_sample:
+ probs = F.softmax(logits, dim=-1)
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
+ else:
+ next_tokens = torch.argmax(logits, dim=-1)
+
+ # 更新未完成序列的 next_tokens
+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (~unfinished_sequences)
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
+ if "attention_mask" in model_kwargs:
+ # 更新 attention_mask
+ attention_mask = model_kwargs["attention_mask"]
+ model_kwargs["attention_mask"] = torch.cat(
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
+ )
+ # 更新完成和未完成的序列标志
+ finished |= (next_tokens.squeeze(-1) == tokenizer.eos_token_id)
+ unfinished_sequences &= ~finished
+
+ # 如果所有序列都完成,则停止生成
+ if finished.all():
+ break
+
+ return input_ids
\ No newline at end of file
diff --git a/Model_Architecture_Discussions/MiniCPM/MiniCPMTest.ipynb b/Model_Architecture_Discussions/MiniCPM/MiniCPMTest.ipynb
new file mode 100644
index 0000000..f794a99
--- /dev/null
+++ b/Model_Architecture_Discussions/MiniCPM/MiniCPMTest.ipynb
@@ -0,0 +1,308 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "用我们搭建的模型尝试读取官方权重并预测"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "/home/jeeves/.local/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
+ " from .autonotebook import tqdm as notebook_tqdm\n"
+ ]
+ }
+ ],
+ "source": [
+ "import json\n",
+ "import torch\n",
+ "from transformers import AutoTokenizer, AutoModelForCausalLM\n",
+ "from configuration_minicpm import MiniCPMConfig\n",
+ "from MiniCPM import MiniCPMForCausalLM\n",
+ "import logging\n",
+ "import gc\n",
+ "\n",
+ "# 配置日志\n",
+ "logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "加载模型 config"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "config_json = json.load(open(\"/data/workspace/llms-from-scratch-cn/Model_Architecture_Discussions/MiniCPM/config.json\"))\n",
+ "config = MiniCPMConfig(**config_json)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "按照 config 初始化模型,并查看模型结构"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "2024-07-25 15:57:28,490 - INFO - 初始化模型\n",
+ "2024-07-25 15:57:50,064 - INFO - 模型:\n",
+ ": MiniCPMForCausalLM(\n",
+ " (model): MiniCPMModel(\n",
+ " (embed_tokens): Embedding(122753, 2304)\n",
+ " (layers): ModuleList(\n",
+ " (0-39): 40 x MiniCPMDecoderLayer(\n",
+ " (self_attn): MiniCPMAttention(\n",
+ " (q_proj): Linear(in_features=2304, out_features=2304, bias=False)\n",
+ " (k_proj): Linear(in_features=2304, out_features=2304, bias=False)\n",
+ " (v_proj): Linear(in_features=2304, out_features=2304, bias=False)\n",
+ " (o_proj): Linear(in_features=2304, out_features=2304, bias=False)\n",
+ " (rotary_emb): MiniCPMRotaryEmbedding()\n",
+ " )\n",
+ " (mlp): MiniCPMMLP(\n",
+ " (gate_proj): Linear(in_features=2304, out_features=5760, bias=False)\n",
+ " (up_proj): Linear(in_features=2304, out_features=5760, bias=False)\n",
+ " (down_proj): Linear(in_features=5760, out_features=2304, bias=False)\n",
+ " (act_fn): SiLU()\n",
+ " )\n",
+ " (input_layernorm): MiniCPMRMSNorm()\n",
+ " (post_attention_layernorm): MiniCPMRMSNorm()\n",
+ " )\n",
+ " )\n",
+ " (norm): MiniCPMRMSNorm()\n",
+ " )\n",
+ " (lm_head): Linear(in_features=2304, out_features=122753, bias=False)\n",
+ ")\n"
+ ]
+ }
+ ],
+ "source": [
+ "\n",
+ "try:\n",
+ " logging.info(\"初始化模型\")\n",
+ " model = MiniCPMForCausalLM(config=config).to('cuda')\n",
+ " logging.info(\"模型:\\n: %s\", model)\n",
+ "except Exception as e:\n",
+ " logging.error(f\"初始化模型时发生错误: {e}\")\n",
+ " raise"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "读取模型权重"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "2024-07-25 15:57:50,086 - INFO - 加载模型权重\n",
+ "2024-07-25 15:57:52,515 - INFO - 加载模型权重完成。\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "缺失的参数名: ['lm_head.weight']\n"
+ ]
+ }
+ ],
+ "source": [
+ "\n",
+ "path = \"/data/model/OpenBMB/MiniCPM-2B-dpo-bf16\"\n",
+ "\n",
+ "try:\n",
+ " logging.info(\"加载模型权重\")\n",
+ " params = torch.load(\n",
+ " f=path + \"/pytorch_model.bin\",\n",
+ " map_location=torch.device('cuda'),\n",
+ " weights_only=True, # 设置为True表示仅加载模型的权重。这通常用于加载预训练权重进行微调或预测,而不需要完整的模型结构\n",
+ " mmap=True # 使用内存映射方式加载模型文件,这可以提高加载大型模型文件的效率,特别是在有限的内存资源下\n",
+ " )\n",
+ " # 打印出模型参数和params中不一致的参数名\n",
+ " missing_keys, unexpected_keys = model.load_state_dict(params, strict=False)\n",
+ " # 打印缺失的参数名\n",
+ " if missing_keys:\n",
+ " print(\"缺失的参数名:\", missing_keys)\n",
+ "\n",
+ " # 打印多余的参数名\n",
+ " if unexpected_keys:\n",
+ " print(\"多余的参数名:\", unexpected_keys)\n",
+ " # modelV1 = AutoModelForCausalLM.from_pretrained(path, torch_dtype=torch.bfloat16, device_map='cuda', trust_remote_code=True)\n",
+ " # 手动实现 tie embedding 即输入输出共享一个 Embedding\n",
+ " model.get_output_embeddings().weight = model.get_input_embeddings().weight\n",
+ " del params\n",
+ " gc.collect()\n",
+ " logging.info(\"加载模型权重完成。\")\n",
+ "except Exception as e:\n",
+ " logging.error(f\"加载模型权重时发生错误: {e}\")\n",
+ " raise"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "MiniCPM 采用了 tie-Embedding 的方式,即词嵌入层和输出层共享参数。这种方式可以减少模型的参数量,提高模型的训练效率。所以需要有获取和设置输入输出词嵌入层的方法。\n",
+ "我们可以看到在加载权重时缺失 `lm_head.weight` 的参数,这里我们通过手动设置 `model.get_output_embeddings().weight = model.get_input_embeddings().weight` 来共享参数。"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "使用默认的 tokenizer 分词"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "2024-07-25 16:01:12,360 - INFO - 初始化分词器\n",
+ "2024-07-25 16:01:12,557 - INFO - 生成文本\n"
+ ]
+ }
+ ],
+ "source": [
+ "logging.info(\"初始化分词器\")\n",
+ "tokenizer = AutoTokenizer.from_pretrained(\"/data/model/OpenBMB/MiniCPM-2B-dpo-bf16/\")\n",
+ "\n",
+ "logging.info(\"生成文本\")\n",
+ "input_texts = [\"北京最高的山是哪座山?\", \"山东省最长的山是哪座山?\" ]\n",
+ "\n",
+ "tokenizer.pad_token_id=tokenizer.eos_token_id\n",
+ "\n",
+ "inputs = tokenizer(input_texts, padding=True, return_tensors=\"pt\").to('cuda')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "可以看出 MiniCPM 采用 tokenizer 为 `LlamaTokenizerFast`, 词表大小为 122753 个 token。"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "LlamaTokenizerFast(name_or_path='/data/model/OpenBMB/MiniCPM-2B-dpo-bf16/', vocab_size=122753, model_max_length=1000000000000000019884624838656, is_fast=True, padding_side='left', truncation_side='right', special_tokens={'bos_token': '', 'eos_token': '', 'unk_token': '', 'pad_token': ''}, clean_up_tokenization_spaces=False), added_tokens_decoder={\n",
+ "\t0: AddedToken(\"\", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),\n",
+ "\t1: AddedToken(\"\", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),\n",
+ "\t2: AddedToken(\"\", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),\n",
+ "}\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(tokenizer)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "我们让模型输出结果看看"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "2024-07-25 16:01:36,687 - INFO - 生成结果: 北京最高的山是哪座山?\n",
+ " 北京最高的山是香山。香山位于北京市海淀区,距离北京市中心约25公里,海拔572米。香山是北京市内最高峰\n",
+ "2024-07-25 16:01:36,687 - INFO - 生成结果: 山东省最长的山是哪座山?\n",
+ " 目前,山东省最长的山是泰山。泰山,位于山东省中部,是五岳之一,也是中国著名的山脉之一。泰山是中国著名的山脉之一\n"
+ ]
+ }
+ ],
+ "source": [
+ "generate_input = {\n",
+ " \"input_ids\": inputs.input_ids,\n",
+ " \"attention_mask\": inputs.attention_mask,\n",
+ " \"max_new_tokens\": 32,\n",
+ " \"temperature\": 1,\n",
+ " \"tokenizer\": tokenizer,\n",
+ "}\n",
+ "model.eval()\n",
+ "outputs = model.generate(**generate_input)\n",
+ "for output in outputs:\n",
+ " result = tokenizer.decode(output, skip_special_tokens=True)\n",
+ " logging.info(f\"生成结果: {result}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "可以看出输出的结果还可以"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.12"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Model_Architecture_Discussions/MiniCPM/README.md b/Model_Architecture_Discussions/MiniCPM/README.md
new file mode 100644
index 0000000..cce4daf
--- /dev/null
+++ b/Model_Architecture_Discussions/MiniCPM/README.md
@@ -0,0 +1,151 @@
+---
+language:
+- en
+- zh
+tags:
+- MiniCPM
+- ModelBest
+- THUNLP
+---
+
+
+
+
+ MiniCPM
+
+
+
+
+MiniCPM 技术报告 Technical Report |
+OmniLMM 多模态模型 Multi-modal Model |
+CPM-C 千亿模型试用 ~100B Model Trial
+
+
+MiniCPM 是面壁与清华大学自然语言处理实验室共同开源的系列端侧语言大模型,主体语言模型 MiniCPM-2B 仅有 24亿(2.4B)的非词嵌入参数量。
+- 经过 SFT 后,MiniCPM 在公开综合性评测集上,MiniCPM 与 Mistral-7B相近(中文、数学、代码能力更优),整体性能超越 Llama2-13B、MPT-30B、Falcon-40B 等模型。
+- 经过 DPO 后,MiniCPM 在当前最接近用户体感的评测集 MTBench上,MiniCPM-2B 也超越了 Llama2-70B-Chat、Vicuna-33B、Mistral-7B-Instruct-v0.1、Zephyr-7B-alpha 等众多代表性开源大模型。
+- 以 MiniCPM-2B 为基础构建端侧多模态大模型 MiniCPM-V,整体性能在同规模模型中实现最佳,超越基于 Phi-2 构建的现有多模态大模型,在部分评测集上达到与 9.6B Qwen-VL-Chat 相当甚至更好的性能。
+- 经过 Int4 量化后,MiniCPM 可在手机上进行部署推理,流式输出速度略高于人类说话速度。MiniCPM-V 也首次跑通了多模态大模型在手机上的部署。
+- 一张1080/2080可高效参数微调,一张3090/4090可全参数微调,一台机器可持续训练 MiniCPM,二次开发成本较低。
+
+我们将完全开源MiniCPM-2B的模型参数供学术研究和有限商用,以及训练过程中的所有Checkpoint和大部分非专有数据供模型机理研究。
+
+- 基于MiniCPM-2B的指令微调与人类偏好对**MiniCPM-2B-SFT/DPO。**
+- 基于MiniCPM-2B的多模态模型**MiniCPM-V**,能力超越基于Phi-2的同参数级别多模态模型**。**
+- MiniCPM-2B-SFT/DPO的Int4量化版**MiniCPM-2B-SFT/DPO-Int4。**
+- 基于MLC-LLM、LLMFarm开发的MiniCPM手机端程序,**文本及多模态模型均可在手机端进行推理。**
+
+
+MiniCPM is an End-Size LLM developed by ModelBest Inc. and TsinghuaNLP, with only 2.4B parameters excluding embeddings.
+
+- MiniCPM has very close performance compared with Mistral-7B on open-sourced general benchmarks with better ability on Chinese, Mathmetics and Coding after SFT. The overall performance exceeds Llama2-13B, MPT-30B, Falcon-40B, etc.
+- After DPO, MiniCPM outperforms Llama2-70B-Chat, Vicuna-33B, Mistral-7B-Instruct-v0.1, Zephyr-7B-alpha, etc. on MTBench.
+- MiniCPM-V, based on MiniCPM-2B, achieves the best overall performance among multimodel models of the same scale, surpassing existing multimodal large models built on Phi-2 and achieving performance comparable to or even better than 9.6B Qwen-VL-Chat on some tasks.
+- MiniCPM can be deployed and infer on smartphones, and the speed of streaming output is relatively higher than the verbal speed of human. MiniCPM-V is the first multi-modal models that can be deployed on smartphones.
+- The cost of developing based on MiniCPM is low. Parameter efficient finetuning can be conducted with a single 1080/2080 GPU and full parameter finetuning can be conducted with a 3090/4090 GPU.
+
+We release all model parameters for research and limited commercial use. We also release all the checkpoint during training and most public training data for research on model mechanism.
+
+- SFT and DPO version based on MiniCPM-2B and human preference: **MiniCPM-2B-SFT/DPO**
+- The multi-modal model **MiniCPM-V** based on MiniCPM-2B, which outperforms models with similar size, i.e., Phi-2
+- The INT4 quantized version **MiniCPM-2B-SFT/DPO-Int4** based on MiniCPM-2B-SFT/DPO
+- Mobile phone application based on MLC-LLM and LLMFarm. Both language model and multimodel model can conduct inference on smartphones.
+
+### 评测结果 Evaluation Results
+
+ 详细的评测结果位于[github仓库](https://github.com/OpenBMB/MiniCPM?tab=readme-ov-file#%E8%AF%84%E6%B5%8B%E7%BB%93%E6%9E%9C)
+
+ Detailed evaluation results are in [github repo](https://github.com/OpenBMB/MiniCPM/blob/main/README-en.md#evaluation-results)
+
+ 注意:我们发现使用Huggingface生成质量略差于vLLM,因此推荐使用vLLM进行测试。我们正在排查原因。
+
+ Notice: We discovered that the quality of Huggingface generation is slightly lower than vLLM, thus benchmarking using vLLM is recommended.
+ We are investigating the cause now.
+
+### 局限性 Limitations
+
+- 受限于模型规模,模型可能出现幻觉性问题。其中由于DPO模型生成的回复内容更长,更容易出现幻觉。我们也将持续进行MiniCPM模型的迭代改进;
+- 为了保证在学术研究用途上模型的通用性,我们未对模型进行任何身份认同训练。同时由于我们用ShareGPT开源语料作为部分训练数据,模型可能会输出类似GPT系列模型的身份认同信息;
+- 受限于模型规模,模型的输出受到提示词(prompt)的影响较大,可能多次尝试产生不一致的结果;
+- 受限于模型容量,模型的知识记忆较不准确,后续我们将结合RAG方法来增强模型的知识记忆能力。
+
+- Due to limitations in model size, the model may experience hallucinatory issues. As DPO model tend to generate longer response, hallucinations are more likely to occur. We will also continue to iterate and improve the MiniCPM model.
+- To ensure the universality of the model for academic research purposes, we did not conduct any identity training on the model. Meanwhile, as we use ShareGPT open-source corpus as part of the training data, the model may output identity information similar to the GPT series models.
+- Due to the limitation of model size, the output of the model is greatly influenced by prompt words, which may result in inconsistent results from multiple attempts.
+- Due to limited model capacity, the model's knowledge memory is not accurate. In the future, we will combine the RAG method to enhance the model's knowledge memory ability.
+
+## 模型下载 Download
+
+ | HuggingFace | ModelScope | WiseModel |
+ |-------------|------------|-----------|
+ |[sft-bf16](https://huggingface.co/openbmb/MiniCPM-2B-sft-bf16)|[sft-bf16](https://modelscope.cn/models/OpenBMB/miniCPM-bf16)|[sft-bf16](https://wisemodel.cn/models/OpenBMB/miniCPM-bf16)
+ |[sft-fp32](https://huggingface.co/openbmb/MiniCPM-2B-sft-fp32)|[sft-fp32](https://modelscope.cn/models/OpenBMB/MiniCPM-2B-sft-fp32)|[sft-fp32](https://wisemodel.cn/models/OpenBMB/miniCPM-dpo-fp32)
+ |[dpo-bf16](https://huggingface.co/openbmb/MiniCPM-2B-dpo-bf16)|[dpo-bf16](https://modelscope.cn/models/OpenBMB/MiniCPM-2B-dpo-bf16/summary)|[dpo-bf16](https://wisemodel.cn/models/OpenBMB/MiniCPM-2B-dpo-bf16)
+ |[dpo-fp16](https://huggingface.co/openbmb/MiniCPM-2B-dpo-fp16)|[dpo-fp16](https://modelscope.cn/models/OpenBMB/MiniCPM-2B-dpo-fp16/)|[dpo-fp16](https://wisemodel.cn/models/OpenBMB/MiniCPM-2B-dpo-fp16)
+ |[dpo-fp32](https://huggingface.co/openbmb/MiniCPM-2B-dpo-fp32)|[dpo-fp32](https://modelscope.cn/models/OpenBMB/MiniCPM-2B-dpo-fp32)|[dpo-fp32](https://wisemodel.cn/models/OpenBMB/miniCPM-dpo-fp32)
+
+## 模型使用 Usage
+
+* 安装`transformers>=4.36.0`以及`accelerate`后,运行以下代码
+* 注意:需要在`from_pretrained`中明确指明模型的数据类型,否则会引起较大计算误差
+* Run the following code after install `transformers>=4.36.0` and `accelerate`
+* Warning: It is necessary to specify the data type of the model clearly in 'from_pretrained', otherwise large calculation errors will be caused
+```python
+from modelscope import AutoModelForCausalLM, AutoTokenizer
+import torch
+torch.manual_seed(0)
+
+path = 'OpenBMB/MiniCPM-2B-dpo-bf16'
+tokenizer = AutoTokenizer.from_pretrained(path)
+model = AutoModelForCausalLM.from_pretrained(path, torch_dtype=torch.bfloat16, device_map='cuda', trust_remote_code=True)
+
+responds, history = model.chat(tokenizer, "山东省最高的山是哪座山, 它比黄山高还是矮?差距多少?", temperature=0.8, top_p=0.8)
+print(responds)
+```
+
+* 期望输出 Expected Output
+```shell
+山东省最高的山是泰山,海拔1545米。
+
+相对于黄山(海拔1864米),泰山海拔较低,相差约319米。
+```
+
+## 开源协议 LICENSE
+
+#### 模型协议 Model LICENSE
+
+* 本仓库中代码依照 [Apache-2.0](https://github.com/OpenBMB/MiniCPM/blob/main/LICENSE) 协议开源
+* MiniCPM 模型权重的使用则需要遵循 [“通用模型许可协议-来源说明-宣传限制-商业授权”](https://github.com/OpenBMB/General-Model-License/blob/main/%E9%80%9A%E7%94%A8%E6%A8%A1%E5%9E%8B%E8%AE%B8%E5%8F%AF%E5%8D%8F%E8%AE%AE-%E6%9D%A5%E6%BA%90%E8%AF%B4%E6%98%8E-%E5%AE%A3%E4%BC%A0%E9%99%90%E5%88%B6-%E5%95%86%E4%B8%9A%E6%8E%88%E6%9D%83.md)。
+* MiniCPM 模型权重对学术研究完全开放。
+* 如需将模型用于商业用途,请联系cpm@modelbest.cn来获取书面授权,在登记后亦允许免费商业使用。
+
+* This repository is released under the [Apache-2.0](https://github.com/OpenBMB/MiniCPM/blob/main/LICENSE) License.
+* The usage of MiniCPM model weights must strictly follow [the General Model License (GML)](https://github.com/OpenBMB/General-Model-License/blob/main/%E9%80%9A%E7%94%A8%E6%A8%A1%E5%9E%8B%E8%AE%B8%E5%8F%AF%E5%8D%8F%E8%AE%AE-%E6%9D%A5%E6%BA%90%E8%AF%B4%E6%98%8E-%E5%AE%A3%E4%BC%A0%E9%99%90%E5%88%B6-%E5%95%86%E4%B8%9A%E6%8E%88%E6%9D%83.md).
+* The models and weights of MiniCPM are completely free for academic research.
+* If you intend to utilize the model for commercial purposes, please reach out to cpm@modelbest.cn to obtain the certificate of authorization.
+
+#### 声明 Statement
+
+* 作为一个语言模型,MiniCPM 通过学习大量的文本来生成内容,但它无法理解、表达个人观点或价值判断,它所输出的任何内容都不代表模型开发者的观点和立场。
+* 因此用户在使用 MiniCPM 生成的内容时,应自行负责对其进行评估和验证。
+* 如果由于使用 MinCPM 开源模型而导致的任何问题,包括但不限于数据安全问题、公共舆论风险,或模型被误导、滥用、传播或不当利用所带来的任何风险和问题,我们将不承担任何责任。
+
+* As a language model, MiniCPM generates content by learning from a vast amount of text.
+* However, it does not possess the ability to comprehend or express personal opinions or value judgments.
+* Any content generated by MiniCPM does not represent the viewpoints or positions of the model developers.
+* Therefore, when using content generated by MiniCPM, users should take full responsibility for evaluating and verifying it on their own.
+
+
+
+## 工作引用 Citation
+
+* 如果觉得MiniCPM有助于您的工作,请考虑引用下列[技术报告](https://shengdinghu.notion.site/MiniCPM-c805a17c5c8046398914e47f0542095a?pvs=4)
+* Please cite our [techinical report](https://shengdinghu.notion.site/MiniCPM-Unveiling-the-Potential-of-End-side-Large-Language-Models-d4d3a8c426424654a4e80e42a711cb20?pvs=4) if you find our work valuable.
+
+```
+@inproceedings{minicpm2024,
+ title={MiniCPM:Unveiling the Potential of End-side Large Language Models},
+ booktitle={OpenBMB Blog},
+ year={2024}
+}
+```
diff --git a/Model_Architecture_Discussions/MiniCPM/config.json b/Model_Architecture_Discussions/MiniCPM/config.json
new file mode 100644
index 0000000..1fa7878
--- /dev/null
+++ b/Model_Architecture_Discussions/MiniCPM/config.json
@@ -0,0 +1,28 @@
+{
+ "_name_or_path": "openbmb/CPM-2B",
+ "architectures": [
+ "MiniCPMForCausalLM"
+ ],
+ "do_sample": false,
+ "temperature": 1,
+ "bos_token_id": 1,
+ "eos_token_id": 2,
+ "hidden_act": "silu",
+ "hidden_size": 2304,
+ "initializer_range": 0.1,
+ "intermediate_size": 5760,
+ "max_position_embeddings": 2048,
+ "num_attention_heads": 36,
+ "num_hidden_layers": 40,
+ "num_key_value_heads": 36,
+ "rms_norm_eps": 1e-05,
+ "rope_scaling": null,
+ "torch_dtype": "bfloat16",
+ "transformers_version": "4.36.0",
+ "use_cache": true,
+ "vocab_size": 122753,
+ "scale_emb": 12,
+ "dim_model_base": 256,
+ "scale_depth": 1.4,
+ "_attn_implementation": "eager"
+}
\ No newline at end of file
diff --git a/Model_Architecture_Discussions/MiniCPM/configuration_minicpm.py b/Model_Architecture_Discussions/MiniCPM/configuration_minicpm.py
new file mode 100644
index 0000000..3ffff72
--- /dev/null
+++ b/Model_Architecture_Discussions/MiniCPM/configuration_minicpm.py
@@ -0,0 +1,75 @@
+import logging
+import json
+
+logger = logging.getLogger(__name__)
+
+class MiniCPMConfig():
+
+ model_type = "minicpm"
+ keys_to_ignore_at_inference = ["past_key_values"]
+
+ def __init__(
+ self,
+ vocab_size=32000,
+ hidden_size=4096,
+ intermediate_size=11008,
+ num_hidden_layers=32,
+ num_attention_heads=32,
+ num_key_value_heads=None,
+ hidden_act="silu",
+ max_position_embeddings=2048,
+ initializer_range=0.02,
+ rms_norm_eps=1e-6,
+ use_cache=False,
+ pad_token_id=None,
+ bos_token_id=1,
+ eos_token_id=2,
+ pretraining_tp=1,
+ tie_word_embeddings=True,
+ rope_theta=10000.0,
+ rope_scaling=None,
+ attention_bias=False,
+ attention_dropout=0.0,
+ scale_emb=1,
+ dim_model_base=1,
+ scale_depth=1,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ use_return_dict=True,
+ **kwargs,
+ ):
+ self.vocab_size = vocab_size
+ self.max_position_embeddings = max_position_embeddings
+ self.hidden_size = hidden_size
+ self.intermediate_size = intermediate_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.num_key_value_heads = num_key_value_heads
+ self.hidden_act = hidden_act
+ self.initializer_range = initializer_range
+ self.rms_norm_eps = rms_norm_eps
+ self.pretraining_tp = pretraining_tp
+ self.use_cache = use_cache
+ self.rope_theta = rope_theta
+ self.rope_scaling = rope_scaling
+ self.attention_bias = attention_bias
+ self.attention_dropout = attention_dropout
+ self.scale_emb = scale_emb
+ self.dim_model_base = dim_model_base
+ self.scale_depth = scale_depth
+ self.pad_token_id=pad_token_id
+ self.bos_token_id=bos_token_id
+ self.eos_token_id=eos_token_id
+ self.tie_word_embeddings=tie_word_embeddings
+ self.output_attentions=output_attentions
+ self.output_hidden_states=output_hidden_states
+ self.return_dict=return_dict
+ self.use_return_dict=use_return_dict
+
+ def to_json_string(self) -> str:
+ config_dict = self.__dict__
+ return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
+
+ def __repr__(self):
+ return f"{self.__class__.__name__} {self.to_json_string()}"
diff --git a/Model_Architecture_Discussions/MiniCPM/generation_config.json b/Model_Architecture_Discussions/MiniCPM/generation_config.json
new file mode 100644
index 0000000..4881cde
--- /dev/null
+++ b/Model_Architecture_Discussions/MiniCPM/generation_config.json
@@ -0,0 +1,7 @@
+{
+ "do_sample": true,
+ "top_p": 0.8,
+ "temperature": 0.8,
+ "bos_token_id": 1,
+ "eos_token_id": 2
+}
\ No newline at end of file
diff --git a/Model_Architecture_Discussions/MiniCPM/gitattributes b/Model_Architecture_Discussions/MiniCPM/gitattributes
new file mode 100644
index 0000000..0c72ca2
--- /dev/null
+++ b/Model_Architecture_Discussions/MiniCPM/gitattributes
@@ -0,0 +1,35 @@
+*.7z filter=lfs diff=lfs merge=lfs -text
+*.arrow filter=lfs diff=lfs merge=lfs -text
+*.bin filter=lfs diff=lfs merge=lfs -text
+*.bin.* filter=lfs diff=lfs merge=lfs -text
+*.bz2 filter=lfs diff=lfs merge=lfs -text
+*.ftz filter=lfs diff=lfs merge=lfs -text
+*.gz filter=lfs diff=lfs merge=lfs -text
+*.h5 filter=lfs diff=lfs merge=lfs -text
+*.joblib filter=lfs diff=lfs merge=lfs -text
+*.lfs.* filter=lfs diff=lfs merge=lfs -text
+*.model filter=lfs diff=lfs merge=lfs -text
+*.msgpack filter=lfs diff=lfs merge=lfs -text
+*.onnx filter=lfs diff=lfs merge=lfs -text
+*.ot filter=lfs diff=lfs merge=lfs -text
+*.parquet filter=lfs diff=lfs merge=lfs -text
+*.pb filter=lfs diff=lfs merge=lfs -text
+*.pt filter=lfs diff=lfs merge=lfs -text
+*.pth filter=lfs diff=lfs merge=lfs -text
+*.rar filter=lfs diff=lfs merge=lfs -text
+saved_model/**/* filter=lfs diff=lfs merge=lfs -text
+*.tar.* filter=lfs diff=lfs merge=lfs -text
+*.tflite filter=lfs diff=lfs merge=lfs -text
+*.tgz filter=lfs diff=lfs merge=lfs -text
+*.xz filter=lfs diff=lfs merge=lfs -text
+*.zip filter=lfs diff=lfs merge=lfs -text
+*.zstandard filter=lfs diff=lfs merge=lfs -text
+*.tfevents* filter=lfs diff=lfs merge=lfs -text
+*.db* filter=lfs diff=lfs merge=lfs -text
+*.ark* filter=lfs diff=lfs merge=lfs -text
+**/*ckpt*data* filter=lfs diff=lfs merge=lfs -text
+**/*ckpt*.meta filter=lfs diff=lfs merge=lfs -text
+**/*ckpt*.index filter=lfs diff=lfs merge=lfs -text
+*.safetensors filter=lfs diff=lfs merge=lfs -text
+*.ckpt filter=lfs diff=lfs merge=lfs -text
+pytorch_model.bin filter=lfs diff=lfs merge=lfs -text
diff --git a/Model_Architecture_Discussions/MiniCPM/special_tokens_map.json b/Model_Architecture_Discussions/MiniCPM/special_tokens_map.json
new file mode 100644
index 0000000..451134b
--- /dev/null
+++ b/Model_Architecture_Discussions/MiniCPM/special_tokens_map.json
@@ -0,0 +1,23 @@
+{
+ "bos_token": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false
+ },
+ "eos_token": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false
+ },
+ "unk_token": {
+ "content": "",
+ "lstrip": false,
+ "normalized": false,
+ "rstrip": false,
+ "single_word": false
+ }
+}
diff --git a/Model_Architecture_Discussions/MiniCPM/tokenizer.json b/Model_Architecture_Discussions/MiniCPM/tokenizer.json
new file mode 100644
index 0000000..209e947
--- /dev/null
+++ b/Model_Architecture_Discussions/MiniCPM/tokenizer.json
@@ -0,0 +1,294435 @@
+{
+ "version": "1.0",
+ "truncation": null,
+ "padding": null,
+ "added_tokens": [
+ {
+ "id": 0,
+ "content": "",
+ "single_word": false,
+ "lstrip": false,
+ "rstrip": false,
+ "normalized": false,
+ "special": true
+ },
+ {
+ "id": 1,
+ "content": "",
+ "single_word": false,
+ "lstrip": false,
+ "rstrip": false,
+ "normalized": false,
+ "special": true
+ },
+ {
+ "id": 2,
+ "content": "",
+ "single_word": false,
+ "lstrip": false,
+ "rstrip": false,
+ "normalized": false,
+ "special": true
+ }
+ ],
+ "normalizer": {
+ "type": "Sequence",
+ "normalizers": [
+ {
+ "type": "Prepend",
+ "prepend": "▁"
+ },
+ {
+ "type": "Replace",
+ "pattern": {
+ "String": " "
+ },
+ "content": "▁"
+ }
+ ]
+ },
+ "pre_tokenizer": null,
+ "post_processor": {
+ "type": "TemplateProcessing",
+ "single": [
+ {
+ "SpecialToken": {
+ "id": "",
+ "type_id": 0
+ }
+ },
+ {
+ "Sequence": {
+ "id": "A",
+ "type_id": 0
+ }
+ }
+ ],
+ "pair": [
+ {
+ "SpecialToken": {
+ "id": "",
+ "type_id": 0
+ }
+ },
+ {
+ "Sequence": {
+ "id": "A",
+ "type_id": 0
+ }
+ },
+ {
+ "SpecialToken": {
+ "id": "",
+ "type_id": 1
+ }
+ },
+ {
+ "Sequence": {
+ "id": "B",
+ "type_id": 1
+ }
+ }
+ ],
+ "special_tokens": {
+ "": {
+ "id": "",
+ "ids": [
+ 1
+ ],
+ "tokens": [
+ ""
+ ]
+ }
+ }
+ },
+ "decoder": {
+ "type": "Sequence",
+ "decoders": [
+ {
+ "type": "Replace",
+ "pattern": {
+ "String": "▁"
+ },
+ "content": " "
+ },
+ {
+ "type": "ByteFallback"
+ },
+ {
+ "type": "Fuse"
+ },
+ {
+ "type": "Strip",
+ "content": " ",
+ "start": 1,
+ "stop": 0
+ }
+ ]
+ },
+ "model": {
+ "type": "BPE",
+ "dropout": null,
+ "unk_token": "",
+ "continuing_subword_prefix": null,
+ "end_of_word_suffix": null,
+ "fuse_unk": true,
+ "byte_fallback": true,
+ "vocab": {
+ "": 0,
+ "": 1,
+ "": 2,
+ "": 3,
+ "": 4,
+ "\n": 5,
+ "\t": 6,
+ "
": 7,
+ "
": 8,
+ "": 9,
+ "": 10,
+ "": 11,
+ "
": 12,
+ "": 13,
+ " | | ": 14,
+ "": 15,
+ "": 16,
+ "": 17,
+ "": 18,
+ "": 21,
+ "": 22,
+ "
": 23,
+ "": 24,
+ "": 25,
+ "": 26,
+ "": 27,
+ "": 28,
+ "": 29,
+ "": 30,
+ "": 31,
+ "": 32,
+ "
": 33,
+ "
": 34,
+ "
": 35,
+ "": 36,
+ "": 37,
+ "": 38,
+ "
": 39,
+ "": 40,
+ "": 41,
+ "
": 42,
+ "": 43,
+ "
": 44,
+ "": 45,
+ "": 46,
+ "": 47,
+ "
": 48,
+ "": 49,
+ "": 50,
+ "": 51,
+ "0": 52,
+ "1": 53,
+ "2": 54,
+ "3": 55,
+ "4": 56,
+ "5": 57,
+ "6": 58,
+ "7": 59,
+ "8": 60,
+ "9": 61,
+ "+": 62,
+ "-": 63,
+ "=": 64,
+ ",": 65,
+ "。": 66,
+ "!": 67,
+ "?": 68,
+ "、": 69,
+ ":": 70,
+ "¥": 71,
+ ".": 72,
+ "!": 73,
+ "?": 74,
+ "...": 75,
+ "。。。": 76,
+ "。。。。。。": 77,
+ "《": 78,
+ "》": 79,
+ "【": 80,
+ "】": 81,
+ "『": 82,
+ "』": 83,
+ "```": 84,
+ "": 86,
+ "---": 87,
+ "": 88,
+ ";": 89,
+ ".": 90,
+ "=": 91,
+ "<": 92,
+ ">": 93,
+ "-": 94,
+ "+": 95,
+ "%": 96,
+ "‼": 97,
+ "㊣": 98,
+ "/": 99,
+ "|": 100,
+ "": 101,
+ "": 102,
+ "": 103,
+ "": 104,
+ "": 105,
+ "": 106,
+ "": 107,
+ "": 108,
+ "": 109,
+ "": 110,
+ "": 111,
+ "": 112,
+ "": 113,
+ "": 114,
+ "": 115,
+ "": 116,
+ "": 117,
+ "": 118,
+ "": 119,
+ "": 120,
+ "": 121,
+ "": 122,
+ "": 123,
+ "": 124,
+ "": 125,
+ "": 126,
+ "": 127,
+ "": 128,
+ "": 129,
+ "": 130,
+ "": 131,
+ "": 132,
+ "": 133,
+ "": 134,
+ "": 135,
+ "": 136,
+ "": 137,
+ "": 138,
+ "": 139,
+ "": 140,
+ "": 141,
+ "": 142,
+ "": 143,
+ "": 144,
+ "": 145,
+ "": 146,
+ "": 147,
+ "": 148,
+ "": 149,
+ "": 150,
+ "": 151,
+ "": 152,
+ "": 153,
+ "": 154,
+ "": 155,
+ "": 156,
+ "": 157,
+ "": 158,
+ "": 159,
+ "": 160,
+ "": 161,
+ "": 162,
+ "": 163,
+ "": 164,
+ "": 165,
+ "": 166,
+ "": 167,
+ "": 168,
+ "": 169,
+ "": 170,
+ "": 171,
+ "": 172,
+ "": 173,
+ "": 174,
+ "": 175,
+ "": 176,
+ "": 177,
+ "": 178,
+ "": 179,
+ "": 180,
+ "": 181,
+ "": 182,
+ "": 183,
+ "": 184,
+ "": 185,
+ "": 186,
+ "": 187,
+ "": 188,
+ "": 189,
+ "": 190,
+ "": 191,
+ "": 192,
+ "": 193,
+ "": 194,
+ "": 195,
+ "": 196,
+ "": 197,
+ "": 198,
+ "": 199,
+ "": 200,
+ "": 201,
+ "": 202,
+ "": 203,
+ "": 204,
+ "": 205,
+ "": 206,
+ "": 207,
+ "": 208,
+ "": 209,
+ "": 210,
+ "": 211,
+ "": 212,
+ "": 213,
+ "": 214,
+ "": 215,
+ "": 216,
+ "": 217,
+ "": 218,
+ "": 219,
+ "": 220,
+ "": 221,
+ "": 222,
+ "": 223,
+ "": 224,
+ "": 225,
+ "": 226,
+ "": 227,
+ "": 228,
+ "": 229,
+ "": 230,
+ "": 231,
+ "": 232,
+ "": 233,
+ "": 234,
+ "": 235,
+ "": 236,
+ "": 237,
+ "": 238,
+ "": 239,
+ "": 240,
+ "": 241,
+ "": 242,
+ "": 243,
+ "": 244,
+ "": 245,
+ "": 246,
+ "": 247,
+ "": 248,
+ "": 249,
+ "": 250,
+ "": 251,
+ "": 252,
+ "": 253,
+ "": 254,
+ "": 255,
+ "": 256,
+ "": 257,
+ "": 258,
+ "": 259,
+ "": 260,
+ "": 261,
+ "": 262,
+ "": 263,
+ "": 264,
+ "": 265,
+ "": 266,
+ "": 267,
+ "": 268,
+ "": 269,
+ "": 270,
+ "": 271,
+ "": 272,
+ "": 273,
+ "": 274,
+ "": 275,
+ "": 276,
+ "": 277,
+ "": 278,
+ "": 279,
+ "": 280,
+ "": 281,
+ "": 282,
+ "": 283,
+ "": 284,
+ "": 285,
+ "": 286,
+ "": 287,
+ "": 288,
+ "": 289,
+ "": 290,
+ "": 291,
+ "": 292,
+ "": 293,
+ "": 294,
+ "": 295,
+ "": 296,
+ "": 297,
+ "": 298,
+ "": 299,
+ "": 300,
+ "": 301,
+ "": 302,
+ "": 303,
+ "": 304,
+ "": 305,
+ "": 306,
+ "": 307,
+ "": 308,
+ "": 309,
+ "": 310,
+ "": 311,
+ "": 312,
+ "": 313,
+ "": 314,
+ "": 315,
+ "": 316,
+ "": 317,
+ "": 318,
+ "": 319,
+ "": 320,
+ "": 321,
+ "": 322,
+ "": 323,
+ "": 324,
+ "": 325,
+ "": 326,
+ "": 327,
+ "": 328,
+ "": 329,
+ "": 330,
+ "": 331,
+ "": 332,
+ "": 333,
+ "": 334,
+ "": 335,
+ "": 336,
+ "": 337,
+ "": 338,
+ "": 339,
+ "": 340,
+ "": 341,
+ "": 342,
+ "": 343,
+ "": 344,
+ "": 345,
+ "": 346,
+ "": 347,
+ "": 348,
+ "": 349,
+ "": 350,
+ "": 351,
+ "": 352,
+ "": 353,
+ "