Upload Transformer
Browse files- LMConfig.py +58 -0
- README.md +199 -0
- config.json +32 -0
- generation_config.json +4 -0
- model.py +428 -0
- pytorch_model.bin +3 -0
LMConfig.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
from typing import List
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class LMConfig(PretrainedConfig):
|
| 6 |
+
model_type = "minimind"
|
| 7 |
+
|
| 8 |
+
def __init__(
|
| 9 |
+
self,
|
| 10 |
+
dim: int = 512,
|
| 11 |
+
n_layers: int = 8,
|
| 12 |
+
n_heads: int = 16,
|
| 13 |
+
n_kv_heads: int = 8,
|
| 14 |
+
vocab_size: int = 6400,
|
| 15 |
+
hidden_dim: int = None,
|
| 16 |
+
multiple_of: int = 64,
|
| 17 |
+
norm_eps: float = 1e-5,
|
| 18 |
+
max_seq_len: int = 512,
|
| 19 |
+
dropout: float = 0.0,
|
| 20 |
+
flash_attn: bool = True,
|
| 21 |
+
####################################################
|
| 22 |
+
# Here are the specific configurations of MOE
|
| 23 |
+
# When use_moe is false, the following is invalid
|
| 24 |
+
####################################################
|
| 25 |
+
use_moe: bool = False,
|
| 26 |
+
num_experts_per_tok=2,
|
| 27 |
+
n_routed_experts=4,
|
| 28 |
+
n_shared_experts: bool = True,
|
| 29 |
+
scoring_func='softmax',
|
| 30 |
+
aux_loss_alpha=0.01,
|
| 31 |
+
seq_aux=True,
|
| 32 |
+
norm_topk_prob=True,
|
| 33 |
+
**kwargs,
|
| 34 |
+
):
|
| 35 |
+
self.dim = dim
|
| 36 |
+
self.n_layers = n_layers
|
| 37 |
+
self.n_heads = n_heads
|
| 38 |
+
self.n_kv_heads = n_kv_heads
|
| 39 |
+
self.vocab_size = vocab_size
|
| 40 |
+
self.hidden_dim = hidden_dim
|
| 41 |
+
self.multiple_of = multiple_of
|
| 42 |
+
self.norm_eps = norm_eps
|
| 43 |
+
self.max_seq_len = max_seq_len
|
| 44 |
+
self.dropout = dropout
|
| 45 |
+
self.flash_attn = flash_attn
|
| 46 |
+
####################################################
|
| 47 |
+
# Here are the specific configurations of MOE
|
| 48 |
+
# When use_moe is false, the following is invalid
|
| 49 |
+
####################################################
|
| 50 |
+
self.use_moe = use_moe
|
| 51 |
+
self.num_experts_per_tok = num_experts_per_tok # 每个token选择的专家数量
|
| 52 |
+
self.n_routed_experts = n_routed_experts # 总的专家数量
|
| 53 |
+
self.n_shared_experts = n_shared_experts # 共享专家
|
| 54 |
+
self.scoring_func = scoring_func # 评分函数,默认为'softmax'
|
| 55 |
+
self.aux_loss_alpha = aux_loss_alpha # 辅助损失的alpha参数
|
| 56 |
+
self.seq_aux = seq_aux # 是否在序列级别上计算辅助损失
|
| 57 |
+
self.norm_topk_prob = norm_topk_prob # 是否标准化top-k概率
|
| 58 |
+
super().__init__(**kwargs)
|
README.md
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 3 |
+
tags: []
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# Model Card for Model ID
|
| 7 |
+
|
| 8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
## Model Details
|
| 13 |
+
|
| 14 |
+
### Model Description
|
| 15 |
+
|
| 16 |
+
<!-- Provide a longer summary of what this model is. -->
|
| 17 |
+
|
| 18 |
+
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
| 19 |
+
|
| 20 |
+
- **Developed by:** [More Information Needed]
|
| 21 |
+
- **Funded by [optional]:** [More Information Needed]
|
| 22 |
+
- **Shared by [optional]:** [More Information Needed]
|
| 23 |
+
- **Model type:** [More Information Needed]
|
| 24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
| 25 |
+
- **License:** [More Information Needed]
|
| 26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
| 27 |
+
|
| 28 |
+
### Model Sources [optional]
|
| 29 |
+
|
| 30 |
+
<!-- Provide the basic links for the model. -->
|
| 31 |
+
|
| 32 |
+
- **Repository:** [More Information Needed]
|
| 33 |
+
- **Paper [optional]:** [More Information Needed]
|
| 34 |
+
- **Demo [optional]:** [More Information Needed]
|
| 35 |
+
|
| 36 |
+
## Uses
|
| 37 |
+
|
| 38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
| 39 |
+
|
| 40 |
+
### Direct Use
|
| 41 |
+
|
| 42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
| 43 |
+
|
| 44 |
+
[More Information Needed]
|
| 45 |
+
|
| 46 |
+
### Downstream Use [optional]
|
| 47 |
+
|
| 48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
| 49 |
+
|
| 50 |
+
[More Information Needed]
|
| 51 |
+
|
| 52 |
+
### Out-of-Scope Use
|
| 53 |
+
|
| 54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
| 55 |
+
|
| 56 |
+
[More Information Needed]
|
| 57 |
+
|
| 58 |
+
## Bias, Risks, and Limitations
|
| 59 |
+
|
| 60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
| 61 |
+
|
| 62 |
+
[More Information Needed]
|
| 63 |
+
|
| 64 |
+
### Recommendations
|
| 65 |
+
|
| 66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
| 67 |
+
|
| 68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
| 69 |
+
|
| 70 |
+
## How to Get Started with the Model
|
| 71 |
+
|
| 72 |
+
Use the code below to get started with the model.
|
| 73 |
+
|
| 74 |
+
[More Information Needed]
|
| 75 |
+
|
| 76 |
+
## Training Details
|
| 77 |
+
|
| 78 |
+
### Training Data
|
| 79 |
+
|
| 80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
| 81 |
+
|
| 82 |
+
[More Information Needed]
|
| 83 |
+
|
| 84 |
+
### Training Procedure
|
| 85 |
+
|
| 86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
| 87 |
+
|
| 88 |
+
#### Preprocessing [optional]
|
| 89 |
+
|
| 90 |
+
[More Information Needed]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
#### Training Hyperparameters
|
| 94 |
+
|
| 95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
| 96 |
+
|
| 97 |
+
#### Speeds, Sizes, Times [optional]
|
| 98 |
+
|
| 99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
| 100 |
+
|
| 101 |
+
[More Information Needed]
|
| 102 |
+
|
| 103 |
+
## Evaluation
|
| 104 |
+
|
| 105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
| 106 |
+
|
| 107 |
+
### Testing Data, Factors & Metrics
|
| 108 |
+
|
| 109 |
+
#### Testing Data
|
| 110 |
+
|
| 111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
| 112 |
+
|
| 113 |
+
[More Information Needed]
|
| 114 |
+
|
| 115 |
+
#### Factors
|
| 116 |
+
|
| 117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
| 118 |
+
|
| 119 |
+
[More Information Needed]
|
| 120 |
+
|
| 121 |
+
#### Metrics
|
| 122 |
+
|
| 123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
| 124 |
+
|
| 125 |
+
[More Information Needed]
|
| 126 |
+
|
| 127 |
+
### Results
|
| 128 |
+
|
| 129 |
+
[More Information Needed]
|
| 130 |
+
|
| 131 |
+
#### Summary
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
## Model Examination [optional]
|
| 136 |
+
|
| 137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
| 138 |
+
|
| 139 |
+
[More Information Needed]
|
| 140 |
+
|
| 141 |
+
## Environmental Impact
|
| 142 |
+
|
| 143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
| 144 |
+
|
| 145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
| 146 |
+
|
| 147 |
+
- **Hardware Type:** [More Information Needed]
|
| 148 |
+
- **Hours used:** [More Information Needed]
|
| 149 |
+
- **Cloud Provider:** [More Information Needed]
|
| 150 |
+
- **Compute Region:** [More Information Needed]
|
| 151 |
+
- **Carbon Emitted:** [More Information Needed]
|
| 152 |
+
|
| 153 |
+
## Technical Specifications [optional]
|
| 154 |
+
|
| 155 |
+
### Model Architecture and Objective
|
| 156 |
+
|
| 157 |
+
[More Information Needed]
|
| 158 |
+
|
| 159 |
+
### Compute Infrastructure
|
| 160 |
+
|
| 161 |
+
[More Information Needed]
|
| 162 |
+
|
| 163 |
+
#### Hardware
|
| 164 |
+
|
| 165 |
+
[More Information Needed]
|
| 166 |
+
|
| 167 |
+
#### Software
|
| 168 |
+
|
| 169 |
+
[More Information Needed]
|
| 170 |
+
|
| 171 |
+
## Citation [optional]
|
| 172 |
+
|
| 173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
| 174 |
+
|
| 175 |
+
**BibTeX:**
|
| 176 |
+
|
| 177 |
+
[More Information Needed]
|
| 178 |
+
|
| 179 |
+
**APA:**
|
| 180 |
+
|
| 181 |
+
[More Information Needed]
|
| 182 |
+
|
| 183 |
+
## Glossary [optional]
|
| 184 |
+
|
| 185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
| 186 |
+
|
| 187 |
+
[More Information Needed]
|
| 188 |
+
|
| 189 |
+
## More Information [optional]
|
| 190 |
+
|
| 191 |
+
[More Information Needed]
|
| 192 |
+
|
| 193 |
+
## Model Card Authors [optional]
|
| 194 |
+
|
| 195 |
+
[More Information Needed]
|
| 196 |
+
|
| 197 |
+
## Model Card Contact
|
| 198 |
+
|
| 199 |
+
[More Information Needed]
|
config.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "./save_models/minimind-v1-small",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"Transformer"
|
| 5 |
+
],
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "LMConfig.LMConfig",
|
| 8 |
+
"AutoModelForCausalLM": "model.Transformer"
|
| 9 |
+
},
|
| 10 |
+
"aux_loss_alpha": 0.01,
|
| 11 |
+
"dim": 512,
|
| 12 |
+
"dropout": 0.0,
|
| 13 |
+
"flash_attn": true,
|
| 14 |
+
"hidden_dim": null,
|
| 15 |
+
"max_seq_len": 512,
|
| 16 |
+
"model_type": "minimind",
|
| 17 |
+
"multiple_of": 64,
|
| 18 |
+
"n_heads": 16,
|
| 19 |
+
"n_kv_heads": 8,
|
| 20 |
+
"n_layers": 8,
|
| 21 |
+
"n_routed_experts": 4,
|
| 22 |
+
"n_shared_experts": true,
|
| 23 |
+
"norm_eps": 1e-05,
|
| 24 |
+
"norm_topk_prob": true,
|
| 25 |
+
"num_experts_per_tok": 2,
|
| 26 |
+
"scoring_func": "softmax",
|
| 27 |
+
"seq_aux": true,
|
| 28 |
+
"torch_dtype": "float32",
|
| 29 |
+
"transformers_version": "4.44.0",
|
| 30 |
+
"use_moe": false,
|
| 31 |
+
"vocab_size": 6400
|
| 32 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"transformers_version": "4.44.0"
|
| 4 |
+
}
|
model.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import struct
|
| 3 |
+
import inspect
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
from .LMConfig import LMConfig
|
| 7 |
+
from typing import Any, Optional, Tuple
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from torch import nn
|
| 12 |
+
from transformers import PreTrainedModel
|
| 13 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class RMSNorm(torch.nn.Module):
|
| 17 |
+
def __init__(self, dim: int, eps: float):
|
| 18 |
+
super().__init__()
|
| 19 |
+
self.eps = eps
|
| 20 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 21 |
+
|
| 22 |
+
def _norm(self, x):
|
| 23 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 24 |
+
|
| 25 |
+
def forward(self, x):
|
| 26 |
+
output = self._norm(x.float()).type_as(x)
|
| 27 |
+
return output * self.weight
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def precompute_pos_cis(dim: int, end: int, theta: float = 10000.0):
|
| 31 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
|
| 32 |
+
t = torch.arange(end, device=freqs.device) # type: ignore
|
| 33 |
+
freqs = torch.outer(t, freqs).float() # type: ignore
|
| 34 |
+
pos_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
|
| 35 |
+
return pos_cis
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# 旋转位置编码 RoPE(Rotary Position Embedding)
|
| 39 |
+
# 参考 https://github.com/meta-llama/llama/blob/main/llama/model.py#L132
|
| 40 |
+
def apply_rotary_emb(xq, xk, pos_cis):
|
| 41 |
+
def unite_shape(pos_cis, x):
|
| 42 |
+
ndim = x.ndim
|
| 43 |
+
assert 0 <= 1 < ndim
|
| 44 |
+
assert pos_cis.shape == (x.shape[1], x.shape[-1])
|
| 45 |
+
shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
|
| 46 |
+
return pos_cis.view(*shape)
|
| 47 |
+
|
| 48 |
+
xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
|
| 49 |
+
xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
|
| 50 |
+
pos_cis = unite_shape(pos_cis, xq_)
|
| 51 |
+
xq_out = torch.view_as_real(xq_ * pos_cis).flatten(3)
|
| 52 |
+
xk_out = torch.view_as_real(xk_ * pos_cis).flatten(3)
|
| 53 |
+
return xq_out.type_as(xq), xk_out.type_as(xk)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 57 |
+
"""torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
|
| 58 |
+
bs, slen, n_kv_heads, head_dim = x.shape
|
| 59 |
+
if n_rep == 1:
|
| 60 |
+
return x
|
| 61 |
+
return (
|
| 62 |
+
x[:, :, :, None, :]
|
| 63 |
+
.expand(bs, slen, n_kv_heads, n_rep, head_dim)
|
| 64 |
+
.reshape(bs, slen, n_kv_heads * n_rep, head_dim)
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class Attention(nn.Module):
|
| 69 |
+
def __init__(self, args: LMConfig):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
|
| 72 |
+
assert args.n_heads % self.n_kv_heads == 0
|
| 73 |
+
self.n_local_heads = args.n_heads
|
| 74 |
+
self.n_local_kv_heads = self.n_kv_heads
|
| 75 |
+
self.n_rep = self.n_local_heads // self.n_local_kv_heads
|
| 76 |
+
self.head_dim = args.dim // args.n_heads
|
| 77 |
+
self.wq = nn.Linear(args.dim, args.n_heads * self.head_dim, bias=False)
|
| 78 |
+
self.wk = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
|
| 79 |
+
self.wv = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
|
| 80 |
+
self.wo = nn.Linear(args.n_heads * self.head_dim, args.dim, bias=False)
|
| 81 |
+
self.k_cache, self.v_cache = None, None
|
| 82 |
+
self.attn_dropout = nn.Dropout(args.dropout)
|
| 83 |
+
self.resid_dropout = nn.Dropout(args.dropout)
|
| 84 |
+
self.dropout = args.dropout
|
| 85 |
+
self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn
|
| 86 |
+
|
| 87 |
+
# print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
|
| 88 |
+
mask = torch.full((1, 1, args.max_seq_len, args.max_seq_len), float("-inf"))
|
| 89 |
+
mask = torch.triu(mask, diagonal=1)
|
| 90 |
+
self.register_buffer("mask", mask, persistent=False)
|
| 91 |
+
|
| 92 |
+
def forward(self, x: torch.Tensor, pos_cis: torch.Tensor, kv_cache=False):
|
| 93 |
+
bsz, seqlen, _ = x.shape
|
| 94 |
+
|
| 95 |
+
xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
|
| 96 |
+
|
| 97 |
+
xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
|
| 98 |
+
xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
|
| 99 |
+
xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
|
| 100 |
+
|
| 101 |
+
xq, xk = apply_rotary_emb(xq, xk, pos_cis)
|
| 102 |
+
|
| 103 |
+
# 更高效的kv_cache实现
|
| 104 |
+
if kv_cache and self.eval():
|
| 105 |
+
if seqlen == 1 and all(cache is not None for cache in (self.k_cache, self.v_cache)):
|
| 106 |
+
xk = torch.cat((self.k_cache, xk), dim=1)
|
| 107 |
+
xv = torch.cat((self.v_cache, xv), dim=1)
|
| 108 |
+
self.k_cache, self.v_cache = xk, xv
|
| 109 |
+
|
| 110 |
+
xk = repeat_kv(xk, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
|
| 111 |
+
xv = repeat_kv(xv, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
|
| 112 |
+
|
| 113 |
+
xq = xq.transpose(1, 2)
|
| 114 |
+
xk = xk.transpose(1, 2)
|
| 115 |
+
xv = xv.transpose(1, 2)
|
| 116 |
+
|
| 117 |
+
if self.flash and seqlen != 1:
|
| 118 |
+
output = torch.nn.functional.scaled_dot_product_attention(xq, xk, xv, attn_mask=None,
|
| 119 |
+
dropout_p=self.dropout if self.training else 0.0,
|
| 120 |
+
is_causal=True)
|
| 121 |
+
else:
|
| 122 |
+
scores = torch.matmul(xq, xk.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 123 |
+
scores = scores + self.mask[:, :, :seqlen, :seqlen] # (bs, n_local_heads, seqlen, cache_len + seqlen)
|
| 124 |
+
scores = F.softmax(scores.float(), dim=-1).type_as(xq)
|
| 125 |
+
scores = self.attn_dropout(scores)
|
| 126 |
+
output = torch.matmul(scores, xv) # (bs, n_local_heads, seqlen, head_dim)
|
| 127 |
+
|
| 128 |
+
output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
|
| 129 |
+
|
| 130 |
+
output = self.wo(output)
|
| 131 |
+
output = self.resid_dropout(output)
|
| 132 |
+
return output
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class FeedForward(nn.Module):
|
| 136 |
+
def __init__(self, dim: int, hidden_dim: int, multiple_of: int, dropout: float):
|
| 137 |
+
super().__init__()
|
| 138 |
+
if hidden_dim is None:
|
| 139 |
+
hidden_dim = 4 * dim
|
| 140 |
+
hidden_dim = int(2 * hidden_dim / 3)
|
| 141 |
+
hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
|
| 142 |
+
self.w1 = nn.Linear(dim, hidden_dim, bias=False)
|
| 143 |
+
self.w2 = nn.Linear(hidden_dim, dim, bias=False)
|
| 144 |
+
self.w3 = nn.Linear(dim, hidden_dim, bias=False)
|
| 145 |
+
self.dropout = nn.Dropout(dropout)
|
| 146 |
+
|
| 147 |
+
def forward(self, x):
|
| 148 |
+
return self.dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class MoEGate(nn.Module):
|
| 152 |
+
def __init__(self, config: LMConfig):
|
| 153 |
+
super().__init__()
|
| 154 |
+
self.config = config
|
| 155 |
+
self.top_k = config.num_experts_per_tok
|
| 156 |
+
self.n_routed_experts = config.n_routed_experts
|
| 157 |
+
|
| 158 |
+
self.scoring_func = config.scoring_func
|
| 159 |
+
self.alpha = config.aux_loss_alpha
|
| 160 |
+
self.seq_aux = config.seq_aux
|
| 161 |
+
|
| 162 |
+
self.norm_topk_prob = config.norm_topk_prob
|
| 163 |
+
self.gating_dim = config.dim
|
| 164 |
+
self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
|
| 165 |
+
self.reset_parameters()
|
| 166 |
+
|
| 167 |
+
def reset_parameters(self) -> None:
|
| 168 |
+
import torch.nn.init as init
|
| 169 |
+
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
|
| 170 |
+
|
| 171 |
+
def forward(self, hidden_states):
|
| 172 |
+
bsz, seq_len, h = hidden_states.shape
|
| 173 |
+
|
| 174 |
+
hidden_states = hidden_states.view(-1, h)
|
| 175 |
+
logits = F.linear(hidden_states, self.weight, None)
|
| 176 |
+
if self.scoring_func == 'softmax':
|
| 177 |
+
scores = logits.softmax(dim=-1)
|
| 178 |
+
else:
|
| 179 |
+
raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
|
| 180 |
+
|
| 181 |
+
topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
|
| 182 |
+
|
| 183 |
+
if self.top_k > 1 and self.norm_topk_prob:
|
| 184 |
+
denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
|
| 185 |
+
topk_weight = topk_weight / denominator
|
| 186 |
+
|
| 187 |
+
if self.training and self.alpha > 0.0:
|
| 188 |
+
scores_for_aux = scores
|
| 189 |
+
aux_topk = self.top_k
|
| 190 |
+
topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
|
| 191 |
+
if self.seq_aux:
|
| 192 |
+
scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
|
| 193 |
+
ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
|
| 194 |
+
ce.scatter_add_(1, topk_idx_for_aux_loss,
|
| 195 |
+
torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)).div_(
|
| 196 |
+
seq_len * aux_topk / self.n_routed_experts)
|
| 197 |
+
aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
|
| 198 |
+
else:
|
| 199 |
+
mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
|
| 200 |
+
ce = mask_ce.float().mean(0)
|
| 201 |
+
Pi = scores_for_aux.mean(0)
|
| 202 |
+
fi = ce * self.n_routed_experts
|
| 203 |
+
aux_loss = (Pi * fi).sum() * self.alpha
|
| 204 |
+
else:
|
| 205 |
+
aux_loss = None
|
| 206 |
+
return topk_idx, topk_weight, aux_loss
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class MOEFeedForward(nn.Module):
|
| 210 |
+
def __init__(self, config: LMConfig):
|
| 211 |
+
super().__init__()
|
| 212 |
+
self.config = config
|
| 213 |
+
self.experts = nn.ModuleList([
|
| 214 |
+
FeedForward(
|
| 215 |
+
dim=config.dim,
|
| 216 |
+
hidden_dim=config.hidden_dim,
|
| 217 |
+
multiple_of=config.multiple_of,
|
| 218 |
+
dropout=config.dropout,
|
| 219 |
+
)
|
| 220 |
+
for _ in range(config.n_routed_experts)
|
| 221 |
+
])
|
| 222 |
+
|
| 223 |
+
self.gate = MoEGate(config)
|
| 224 |
+
if config.n_shared_experts is not None:
|
| 225 |
+
self.shared_experts = FeedForward(
|
| 226 |
+
dim=config.dim,
|
| 227 |
+
hidden_dim=config.hidden_dim,
|
| 228 |
+
multiple_of=config.multiple_of,
|
| 229 |
+
dropout=config.dropout,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
def forward(self, x):
|
| 233 |
+
identity = x
|
| 234 |
+
orig_shape = x.shape
|
| 235 |
+
bsz, seq_len, _ = x.shape
|
| 236 |
+
|
| 237 |
+
# 使用门控机制选择专家
|
| 238 |
+
topk_idx, topk_weight, aux_loss = self.gate(x)
|
| 239 |
+
|
| 240 |
+
x = x.view(-1, x.shape[-1])
|
| 241 |
+
flat_topk_idx = topk_idx.view(-1)
|
| 242 |
+
|
| 243 |
+
if self.training:
|
| 244 |
+
# 训练模式下,重复输入数据
|
| 245 |
+
x = x.repeat_interleave(self.config.num_experts_per_tok, dim=0)
|
| 246 |
+
y = torch.empty_like(x, dtype=torch.float16)
|
| 247 |
+
for i, expert in enumerate(self.experts):
|
| 248 |
+
y[flat_topk_idx == i] = expert(x[flat_topk_idx == i])
|
| 249 |
+
y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
|
| 250 |
+
y = y.view(*orig_shape)
|
| 251 |
+
else:
|
| 252 |
+
# 推理模式下,只选择最优专家
|
| 253 |
+
y = self.moe_infer(x, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
|
| 254 |
+
|
| 255 |
+
if self.config.n_shared_experts is not None:
|
| 256 |
+
y = y + self.shared_experts(identity)
|
| 257 |
+
|
| 258 |
+
return y
|
| 259 |
+
|
| 260 |
+
@torch.no_grad()
|
| 261 |
+
def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
|
| 262 |
+
expert_cache = torch.zeros_like(x)
|
| 263 |
+
idxs = flat_expert_indices.argsort()
|
| 264 |
+
tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
|
| 265 |
+
token_idxs = idxs // self.config.num_experts_per_tok
|
| 266 |
+
# 例如当tokens_per_expert=[6, 15, 20, 26, 33, 38, 46, 52]
|
| 267 |
+
# 当token_idxs=[3, 7, 19, 21, 24, 25, 4, 5, 6, 10, 11, 12...]
|
| 268 |
+
# 意味着当token_idxs[:6] -> [3, 7, 19, 21, 24, 25, 4]位置的token都由专家0处理,token_idxs[6:15]位置的token都由专家1处理......
|
| 269 |
+
for i, end_idx in enumerate(tokens_per_expert):
|
| 270 |
+
start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
|
| 271 |
+
if start_idx == end_idx:
|
| 272 |
+
continue
|
| 273 |
+
expert = self.experts[i]
|
| 274 |
+
exp_token_idx = token_idxs[start_idx:end_idx]
|
| 275 |
+
expert_tokens = x[exp_token_idx]
|
| 276 |
+
expert_out = expert(expert_tokens)
|
| 277 |
+
expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
|
| 278 |
+
# 使用 scatter_add_ 进行 sum 操作
|
| 279 |
+
expert_cache.scatter_add_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out)
|
| 280 |
+
|
| 281 |
+
return expert_cache
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class TransformerBlock(nn.Module):
|
| 285 |
+
def __init__(self, layer_id: int, args: LMConfig):
|
| 286 |
+
super().__init__()
|
| 287 |
+
self.n_heads = args.n_heads
|
| 288 |
+
self.dim = args.dim
|
| 289 |
+
self.head_dim = args.dim // args.n_heads
|
| 290 |
+
self.attention = Attention(args)
|
| 291 |
+
|
| 292 |
+
self.layer_id = layer_id
|
| 293 |
+
self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
|
| 294 |
+
self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)
|
| 295 |
+
|
| 296 |
+
if args.use_moe:
|
| 297 |
+
self.feed_forward = MOEFeedForward(args)
|
| 298 |
+
else:
|
| 299 |
+
self.feed_forward = FeedForward(
|
| 300 |
+
dim=args.dim,
|
| 301 |
+
hidden_dim=args.hidden_dim,
|
| 302 |
+
multiple_of=args.multiple_of,
|
| 303 |
+
dropout=args.dropout,
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
def forward(self, x, pos_cis, kv_cache=False):
|
| 307 |
+
h = x + self.attention(self.attention_norm(x), pos_cis, kv_cache)
|
| 308 |
+
out = h + self.feed_forward(self.ffn_norm(h))
|
| 309 |
+
return out
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
class Transformer(PreTrainedModel):
|
| 313 |
+
config_class = LMConfig
|
| 314 |
+
last_loss: Optional[torch.Tensor]
|
| 315 |
+
|
| 316 |
+
def __init__(self, params: LMConfig = None):
|
| 317 |
+
super().__init__(params)
|
| 318 |
+
if not params:
|
| 319 |
+
params = LMConfig()
|
| 320 |
+
self.params = params
|
| 321 |
+
self.vocab_size = params.vocab_size
|
| 322 |
+
self.n_layers = params.n_layers
|
| 323 |
+
|
| 324 |
+
self.tok_embeddings = nn.Embedding(params.vocab_size, params.dim)
|
| 325 |
+
self.dropout = nn.Dropout(params.dropout)
|
| 326 |
+
self.layers = torch.nn.ModuleList()
|
| 327 |
+
for layer_id in range(self.n_layers):
|
| 328 |
+
self.layers.append(TransformerBlock(layer_id, params))
|
| 329 |
+
self.norm = RMSNorm(params.dim, eps=params.norm_eps)
|
| 330 |
+
self.output = nn.Linear(params.dim, params.vocab_size, bias=False)
|
| 331 |
+
self.tok_embeddings.weight = self.output.weight
|
| 332 |
+
pos_cis = precompute_pos_cis(self.params.dim // self.params.n_heads, self.params.max_seq_len)
|
| 333 |
+
self.register_buffer("pos_cis", pos_cis, persistent=False)
|
| 334 |
+
|
| 335 |
+
self.apply(self._init_weights)
|
| 336 |
+
|
| 337 |
+
for pn, p in self.named_parameters():
|
| 338 |
+
if pn.endswith('w3.weight') or pn.endswith('wo.weight'):
|
| 339 |
+
torch.nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * params.n_layers))
|
| 340 |
+
|
| 341 |
+
self.last_loss = None
|
| 342 |
+
self.OUT = CausalLMOutputWithPast()
|
| 343 |
+
self._no_split_modules = [name for name, _ in self.named_modules()]
|
| 344 |
+
|
| 345 |
+
def _init_weights(self, module):
|
| 346 |
+
if isinstance(module, nn.Linear):
|
| 347 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 348 |
+
if module.bias is not None:
|
| 349 |
+
torch.nn.init.zeros_(module.bias)
|
| 350 |
+
elif isinstance(module, nn.Embedding):
|
| 351 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 352 |
+
|
| 353 |
+
def forward(self, tokens: Optional[torch.Tensor] = None, targets: Optional[torch.Tensor] = None,
|
| 354 |
+
kv_cache=False, **keyargs):
|
| 355 |
+
current_idx = 0
|
| 356 |
+
if 'input_ids' in keyargs:
|
| 357 |
+
tokens = keyargs['input_ids']
|
| 358 |
+
if 'attention_mask' in keyargs:
|
| 359 |
+
targets = keyargs['attention_mask']
|
| 360 |
+
if 'current_idx' in keyargs:
|
| 361 |
+
current_idx = int(keyargs['current_idx'])
|
| 362 |
+
|
| 363 |
+
_bsz, seqlen = tokens.shape
|
| 364 |
+
h = self.tok_embeddings(tokens)
|
| 365 |
+
h = self.dropout(h)
|
| 366 |
+
pos_cis = self.pos_cis[current_idx:current_idx + seqlen]
|
| 367 |
+
for idx, layer in enumerate(self.layers):
|
| 368 |
+
h = layer(h, pos_cis, kv_cache)
|
| 369 |
+
|
| 370 |
+
h = self.norm(h)
|
| 371 |
+
|
| 372 |
+
if targets is not None:
|
| 373 |
+
logits = self.output(h)
|
| 374 |
+
self.last_loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1),
|
| 375 |
+
ignore_index=0, reduction='none')
|
| 376 |
+
else:
|
| 377 |
+
logits = self.output(h[:, [-1], :])
|
| 378 |
+
self.last_loss = None
|
| 379 |
+
|
| 380 |
+
self.OUT.__setitem__('logits', logits)
|
| 381 |
+
self.OUT.__setitem__('last_loss', self.last_loss)
|
| 382 |
+
return self.OUT
|
| 383 |
+
|
| 384 |
+
@torch.inference_mode()
|
| 385 |
+
def generate(self, idx, eos, max_new_tokens, temperature=0.7, top_k=8, stream=True, rp=1., kv_cache=True):
|
| 386 |
+
# rp: repetition_penalty
|
| 387 |
+
index = idx.shape[1]
|
| 388 |
+
init_inference = True
|
| 389 |
+
while idx.shape[1] < max_new_tokens - 1:
|
| 390 |
+
if init_inference or not kv_cache:
|
| 391 |
+
inference_res, init_inference = self(idx, kv_cache=kv_cache), False
|
| 392 |
+
else:
|
| 393 |
+
inference_res = self(idx[:, -1:], kv_cache=kv_cache, current_idx=idx.shape[1] - 1)
|
| 394 |
+
|
| 395 |
+
logits = inference_res.logits
|
| 396 |
+
logits = logits[:, -1, :]
|
| 397 |
+
|
| 398 |
+
for token in set(idx.tolist()[0]):
|
| 399 |
+
logits[:, token] /= rp
|
| 400 |
+
|
| 401 |
+
if temperature == 0.0:
|
| 402 |
+
_, idx_next = torch.topk(logits, k=1, dim=-1)
|
| 403 |
+
else:
|
| 404 |
+
logits = logits / temperature
|
| 405 |
+
if top_k is not None:
|
| 406 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| 407 |
+
logits[logits < v[:, [-1]]] = -float('Inf')
|
| 408 |
+
|
| 409 |
+
probs = F.softmax(logits, dim=-1)
|
| 410 |
+
idx_next = torch.multinomial(probs, num_samples=1, generator=None)
|
| 411 |
+
|
| 412 |
+
if idx_next == eos:
|
| 413 |
+
break
|
| 414 |
+
|
| 415 |
+
idx = torch.cat((idx, idx_next), dim=1)
|
| 416 |
+
if stream:
|
| 417 |
+
yield idx[:, index:]
|
| 418 |
+
|
| 419 |
+
if not stream:
|
| 420 |
+
yield idx[:, index:]
|
| 421 |
+
|
| 422 |
+
@torch.inference_mode()
|
| 423 |
+
def eval_answer(self, idx):
|
| 424 |
+
idx_cond = idx if idx.size(1) <= self.params.max_seq_len else idx[:, -self.params.max_seq_len:]
|
| 425 |
+
inference_res = self(idx_cond)
|
| 426 |
+
logits = inference_res.logits
|
| 427 |
+
logits = logits[:, -1, :]
|
| 428 |
+
return logits
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cd5b25253c9dff3220290f1eeecdf263109a90e065a6d4809b78f6f6113367e0
|
| 3 |
+
size 107537292
|