first commit

This commit is contained in:
xxl 2024-11-27 10:57:55 +08:00
parent 87b2cf9dc6
commit 4a8687829f
15 changed files with 456457 additions and 2 deletions

BIN
.msc Normal file

Binary file not shown.

1
.mv Normal file
View File

@ -0,0 +1 @@
Revision:master,CreatedAt:1732026261

View File

@ -1,3 +1,95 @@
# Steel-LLM_a13737944229998592552118 ---
license: apache-2.0
---
<div align="center">
Steel-LLM # 开源中文预训练语言模型Steel-LLM
由zhanshijin和lishu14创建
</div>
## 👋 介绍
Steel-LLM是个人发起的利用业余时间从零开始预训练中文大模型的项目。我们使用了1T+的数据预训练一个1B左右参数量的中文LLM耗时8个月。我们分享了数据收集、数据处理、预训练框架修改、模型设计、模型微调等全过程并开源全部代码。让每个人在有8~几十张卡的情况下都能复现我们的工作。得益于开源中文数据Steel LLM在中文benchmark上表现优于一些大几倍的机构发布的LLM最终在ceval达到了38分cmmlu达到了33分。
<p align="center">
🐱 <a href="https://github.com/zhanshijinwat/Steel-LLM">Github</a>&nbsp&nbsp
&nbsp&nbsp 📑 <a href="https://www.zhihu.com/people/zhan-shi-jin-27">Blog</a> &nbsp&nbsp🌐公众号炼钢AI
"Steel(钢)"取名灵感来源于华北平原一只优秀的乐队“万能青年旅店万青”。乐队在做一专的时候条件有限自称是在“土法炼钢”但却是一张神专。我们训练LLM的条件同样有限但也希望能炼出好“钢”来。
## 📖 预训练数据
预训练数据方面Steel-LLM主要使用了wanjuan1.0、Skywork/Skypile-150B数据集、starcoder的python/java/c++数据。另外也加入了中文维基百科、百度百科、知乎问答等数据转换为token id后占用1.7T硬盘空间。Steel-LLM也对问答数据以及代码数据使用data-juicer进行了数据清洗数据收集及数据处理的具体细节见我的博客
https://mp.weixin.qq.com/s/yqmtHLuuNV9075qHgzhcPw
## 🎰 训练框架
训练框架方面我们修改了TinyLlama训练程序兼容Hugginface格式模型、支持了数据断点续训、支持了追加新的数据等能力。训练前20k checkpoint使用8 * A100之后使用的是8 * H800
具体的技术细节见我的博客https://mp.weixin.qq.com/s/KPRir6bK3MZZ-vMFTfhUQQ
## 🤖模型结构
tokenizer方面使用了Qwen/Qwen1.5-MoE-A2.7B-Chat的tokenizer。模型结构方面基于Qwen1.5模型进行了以下的新结构的尝试:
- FFN层使用softmax moe相同参数量下有更高的训练速度
- 使用双层的SwiGLU
具体的技术细节见我的博客https://mp.weixin.qq.com/s/JaZyf1jOEOtNDCcFqSj8TQ
## 💡 微调
微调阶段主要使用了BAAI/Infinity-Instruct、预训练数据中的wanjuan中文选择题部分回炉重造、ruozhiba等数据。尝试了COT/非COT微调、刷榜测试。
具体的实验细节见我的博客https://mp.weixin.qq.com/s/KK0G0spNw0D9rPUESkHMew
## 🏅 评估
Steel-LLM在CEVAL和CMMLU上进行了测试。Steel-LLM旨在训练一个中文LLM80%的训练数据都是中文因此并没有在英文benchmark上进行评测。
其他模型的指标来自于CEVAL论文、MiniCPM技术报告、MAP-Neo技术报告等途径。更多模型的指标可查看之前的<a href=https://mp.weixin.qq.com/s/KK0G0spNw0D9rPUESkHMew>博客</a>
| | CEVAL | CMMLU |
|------------------------------|--------|-------|
| Steel-LLM | 38.57 | 33.48 |
| Tiny-Llama-1.1B | 25.02 | 24.03 |
| Gemma-2b-it | 32.3 | 33.07 |
| Phi2(2B) | 23.37 | 24.18 |
| Deepseek-coder-1.3B-instruct | 28.33 | 27.75 |
| CT-LLM-SFT-2B | 41.54 | 41.48 |
| MiniCPM-2B-sft-fp32 | 49.14 | 51.0 |
| Qwen1.5-1.8B-Chat | 56.84 | 54.11 |
| ChatGLM-6B | 38.9 | - |
| Moss | 33.1 | - |
| LLAMA-65B | 34.7 | - |
| Qwen-7B | 58.96 | 60.35 |
| Gemma-7B | 42.57 | 44.20 |
| OLMo-7B | 35.18 | 35.55 |
| MAP-NEO-7B | 56.97 | 55.01 |
## ⛏️ 快速使用
```python
from modelscope import AutoModelForCausalLM, AutoTokenizer
model_name = "zhanshijin/Steel-LLM"
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype="auto",
device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
prompt = "你是谁开发的"
messages = [
{"role": "user", "content": prompt}
]
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
generated_ids = model.generate(
**model_inputs,
max_new_tokens=512
)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
print(response)
```

5
added_tokens.json Normal file
View File

@ -0,0 +1,5 @@
{
"<|endoftext|>": 151643,
"<|im_end|>": 151645,
"<|im_start|>": 151644
}

38
config.json Normal file
View File

@ -0,0 +1,38 @@
{
"FFN_type": "softmoe_v3",
"_name_or_path": "/data/model/llm/hf_model/steel-llm-step-1060000-ckpt",
"architectures": [
"SteelForCausalLM"
],
"attention_dropout": 0.0,
"auto_map": {
"AutoConfig": "configuration_steel.SteelConfig",
"AutoModel": "modeling_steel.SteelForCausalLM",
"AutoModelForCausalLM": "modeling_steel.SteelForCausalLM"
},
"bos_token_id": 151643,
"eos_token_id": 151645,
"hidden_act": "silu",
"hidden_size": 1792,
"initializer_range": 0.02,
"intermediate_size": 1792,
"max_position_embeddings": 32768,
"max_window_layers": 21,
"mlp_div_ratio": 4,
"mlp_type": "senet",
"model_type": "qwen2",
"n_experts": 6,
"num_attention_heads": 32,
"num_hidden_layers": 18,
"num_key_value_heads": 32,
"rms_norm_eps": 1e-06,
"rope_theta": 1000000.0,
"sliding_window": 32768,
"slots_per_expert": 1,
"tie_word_embeddings": false,
"torch_dtype": "float32",
"transformers_version": "4.43.4",
"use_cache": false,
"use_sliding_window": false,
"vocab_size": 151936
}

131
configuration_steel.py Normal file
View File

@ -0,0 +1,131 @@
# coding=utf-8
# Copyright 2024 zhanshijin and lishu. All rights reserved.
#
# This project copy from qwen1.5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Steel model configuration"""
from transformers.configuration_utils import PretrainedConfig
from transformers.utils import logging
logger = logging.get_logger(__name__)
class SteelConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of
Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 151936):
Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`Qwen2Model`]
hidden_size (`int`, *optional*, defaults to 4096):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 22016):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 32):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 32):
Number of attention heads for each attention layer in the Transformer encoder.
num_key_value_heads (`int`, *optional*, defaults to 32):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details checkout [this
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
The non-linear activation function (function or string) in the decoder.
max_position_embeddings (`int`, *optional*, defaults to 32768):
The maximum sequence length that this model might ever be used with.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the rms normalization layers.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether the model's input and output word embeddings should be tied.
rope_theta (`float`, *optional*, defaults to 10000.0):
The base period of the RoPE embeddings.
use_sliding_window (`bool`, *optional*, defaults to `False`):
Whether to use sliding window attention.
sliding_window (`int`, *optional*, defaults to 4096):
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
max_window_layers (`int`, *optional*, defaults to 28):
The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
"""
model_type = "qwen2"
keys_to_ignore_at_inference = ["past_key_values"]
def __init__(
self,
vocab_size=151936,
hidden_size=4096,
intermediate_size=22016,
num_hidden_layers=32,
num_attention_heads=32,
num_key_value_heads=32,
hidden_act="silu",
max_position_embeddings=32768,
initializer_range=0.02,
rms_norm_eps=1e-6,
use_cache=True,
tie_word_embeddings=False,
rope_theta=10000.0,
use_sliding_window=False,
sliding_window=4096,
max_window_layers=28,
attention_dropout=0.0,
**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.use_sliding_window = use_sliding_window
self.sliding_window = sliding_window
self.max_window_layers = max_window_layers
# for backward compatibility
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.rope_theta = rope_theta
self.attention_dropout = attention_dropout
super().__init__(
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)

6
generation_config.json Normal file
View File

@ -0,0 +1,6 @@
{
"_from_model_config": true,
"bos_token_id": 151643,
"eos_token_id": 151645,
"transformers_version": "4.43.4"
}

151388
merges.txt Normal file

File diff suppressed because it is too large Load Diff

BIN
model.safetensors (Stored with Git LFS) Normal file

Binary file not shown.

1502
modeling_steel.py Normal file

File diff suppressed because it is too large Load Diff

112
softmoe_v3.py Normal file
View File

@ -0,0 +1,112 @@
from typing import Callable
import torch
import torch.nn as nn
import torch.nn.functional as F
def softmax(x: torch.Tensor, dim: int | tuple[int, ...]) -> torch.Tensor:
"""
Compute the softmax along the specified dimensions.
This function adds the option to specify multiple dimensions
Args:
x (torch.Tensor): Input tensor.
dims (int or tuple[int]): The dimension or list of dimensions along which the softmax probabilities are computed.
Returns:
torch.Tensor: Output tensor containing softmax probabilities along the specified dimensions.
"""
dtype = x.dtype
x = x.to(torch.float32)
max_vals = torch.amax(x, dim=dim, keepdim=True)
e_x = torch.exp(x - max_vals)
sum_exp = e_x.sum(dim=dim, keepdim=True)
return (e_x / sum_exp).to(dtype)
# copy from https://github.com/bwconrad/soft-moe
class SteelSoftMoEV3(nn.Module):
"""
A wrapper class to create a Soft Mixture of Experts layer.
From "From Sparse to Soft Mixtures of Experts"
https://arxiv.org/pdf/2308.00951.pdf
"""
def __init__(
self,
config,
layer: Callable,
) -> None:
"""
Args:
dim (int): Dimensionality of input features.
num_experts (int): Number of experts.
slots_per_expert (int): Number of token slots per expert.
layer (Callable): Network layer of the experts.
normalize (bool): Normalize input and phi (sec. 2.3 from paper)
**layer_kwargs: Additional keyword arguments for the layer class.
"""
super().__init__()
self.dim = config.hidden_size
self.num_experts = config.n_experts
self.slots_per_expert = config.slots_per_expert if hasattr(config, "slots_per_expert") else 1
self.normalize = True
# Initialize phi and normalization scaling factor
self.phi = nn.Parameter(torch.zeros(self.dim, self.num_experts, self.slots_per_expert))
if self.normalize:
self.scale = nn.Parameter(torch.ones(1))
# Initialize phi using LeCun normal initialization
# https://github.com/google-research/vmoe/blob/662341d007650d5bbb7c6a2bef7f3c759a20cc7e/vmoe/projects/soft_moe/router.py#L49C1-L49C1
nn.init.normal_(self.phi, mean=0, std=1 / self.dim**0.5)
# Create a list of expert networks
self.experts = nn.ModuleList(
[layer(config) for _ in range(self.num_experts)]
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass through the Soft-MoE layer (algorithm 1 from paper).
Args:
x (torch.Tensor): Input tensor of shape [batch_size, seq_len, input_dim].
Returns:
torch.Tensor: Output tensor of shape [batch_size, seq_len, input_dim].
"""
assert (
x.shape[-1] == self.dim
), f"Input feature dim of {x.shape[-1]} does not match layer dim of {self.dim}"
assert (
len(x.shape) == 3
), f"Input expected to have 3 dimensions but has {len(x.shape)}"
phi = self.phi
# Normalize input and phi
if self.normalize:
x = F.normalize(x, dim=2) # [b, m, d]
phi = self.scale * F.normalize(phi, dim=0) # [d, n, p]
# Compute dispatch and combine weights
logits = torch.einsum("bmd,dnp->bmnp", x, phi)
d = softmax(logits, dim=1)
c = softmax(logits, dim=(2, 3))
# tmp = c[0,:,:,0].reshape([c.shape[1],-1])
# print("num:",tmp, "shape:",tmp.shape, "sum:",tmp.sum(dim=1))
# Compute input slots as weighted average of input tokens using dispatch weights
xs = torch.einsum("bmd,bmnp->bnpd", x, d)
# Apply expert to corresponding slots
ys = torch.stack(
[f_i(xs[:, i, :, :]) for i, f_i in enumerate(self.experts)], dim=1
)
# Compute output tokens as weighted average of output slots using combine weights
y = torch.einsum("bnpd,bmnp->bmd", ys, c)
return y

20
special_tokens_map.json Normal file
View File

@ -0,0 +1,20 @@
{
"additional_special_tokens": [
"<|im_start|>",
"<|im_end|>"
],
"eos_token": {
"content": "<|im_end|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
"pad_token": {
"content": "<|endoftext|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
}
}

303112
tokenizer.json Normal file

File diff suppressed because it is too large Load Diff

44
tokenizer_config.json Normal file
View File

@ -0,0 +1,44 @@
{
"add_prefix_space": false,
"added_tokens_decoder": {
"151643": {
"content": "<|endoftext|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151644": {
"content": "<|im_start|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151645": {
"content": "<|im_end|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
}
},
"additional_special_tokens": [
"<|im_start|>",
"<|im_end|>"
],
"bos_token": null,
"chat_template": "{% set system_message = 'You are a helpful assistant.' %}{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% else %}{% set loop_messages = messages %}{% endif %}{% if system_message is defined %}{{ '<|im_start|>system\n' + system_message + '<|im_end|>\n' }}{% endif %}{% for message in loop_messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|im_start|>user\n' + content + '<|im_end|>\n<|im_start|>assistant\n' }}{% elif message['role'] == 'assistant' %}{{ content + '<|im_end|>' + '\n' }}{% endif %}{% endfor %}",
"clean_up_tokenization_spaces": false,
"eos_token": "<|im_end|>",
"errors": "replace",
"model_max_length": 32768,
"pad_token": "<|endoftext|>",
"padding_side": "right",
"split_special_tokens": false,
"tokenizer_class": "Qwen2Tokenizer",
"unk_token": null
}

1
vocab.json Normal file

File diff suppressed because one or more lines are too long