from openmind import AutoTokenizer, AutoModel, is_torch_npu_available
from openmind_hub import snapshot_download
import torch
import argparse
import torch.nn.functional as F
# 均值池化 - 考虑注意力掩码以进行正确的平均
def mean_pooling(model_output, attention_mask):
token_embeddings = model_output[0] # model_output的第一个元素包含所有token嵌入
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--model_name_or_path",
type=str,
help="Path to model",
default="Rose/granite-3.0-2b-base",
)
args = parser.parse_args()
return args
def main():
args = parse_args()
model_path = args.model_name_or_path
if is_torch_npu_available():
device = "npu:0"
else:
device = "cpu"
# 我们想要获取句子嵌入的句子
sentences = ['This is an example sentence', 'Each sentence is converted']
# 从openmind_hub加载模型
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModel.from_pretrained(model_path)
# 对句子进行分词
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
# 计算token嵌入
with torch.no_grad():
model_output = model(**encoded_input)
# 执行池化
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
# 归一化嵌入
sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
print("Sentence embeddings:")
print(sentence_embeddings)
if __name__ == "__main__":
main()模型概述: Granite-3.0-2B-Base 是一款仅解码器语言模型,支持多种文本到文本生成任务。它采用两阶段训练策略从头开始训练。第一阶段,模型在来自不同领域的 10 万亿个 token 上进行训练。第二阶段,使用精心挑选的高质量数据混合集进一步训练 2 万亿个 token,旨在提升其在特定任务上的性能。
支持语言: 英语、德语、西班牙语、法语、日语、葡萄牙语、阿拉伯语、捷克语、意大利语、韩语、荷兰语和中文。用户可以对 Granite 3.0 模型进行微调,以支持这 12 种语言之外的其他语言。
预期用途: 大型语言模型(LLMs)在文本到文本生成中的主要应用场景包括文本摘要、文本分类、信息提取、问答等。所有 Granite Base 模型均能处理这些任务,因为它们是在来自各种领域的大量数据上训练的。此外,它们还可用作基准,为特定应用场景创建专用模型。
生成: 以下是使用 Granite-3.0-2B-Base 模型的简单示例。
安装以下库:
pip install torch torchvision torchaudio
pip install accelerate
pip install transformers然后,复制下面的代码片段来运行示例。
from transformers import AutoModelForCausalLM, AutoTokenizer
device = "auto"
model_path = "ibm-granite/granite-3.0-2b-base"
tokenizer = AutoTokenizer.from_pretrained(model_path)
# drop device_map if running on CPU
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()
# change input text as desired
input_text = "Where is the Thomas J. Watson Research Center located?"
# tokenize the text
input_tokens = tokenizer(input_text, return_tensors="pt").to(device)
# generate output tokens
output = model.generate(**input_tokens,
max_length=4000)
# decode output tokens into text
output = tokenizer.batch_decode(output)
# print output
print(output)模型架构:
Granite-3.0-2B-Base 基于纯解码器的密集型 transformer 架构。该架构的核心组件包括:GQA(分组查询注意力)、RoPE(旋转位置编码)、带 SwiGLU 激活函数的 MLP(多层感知机)、RMSNorm(均方根归一化)以及共享的输入/输出嵌入。
| 模型 | 2B 密集型 | 8B 密集型 | 1B MoE | 3B MoE |
|---|---|---|---|---|
| 嵌入维度 | 2048 | 4096 | 1024 | 1536 |
| 层数 | 40 | 40 | 24 | 32 |
| 注意力头维度 | 64 | 128 | 64 | 64 |
| 注意力头数量 | 32 | 32 | 16 | 24 |
| KV 头数量 | 8 | 8 | 8 | 8 |
| MLP 隐藏层维度 | 8192 | 12800 | 512 | 512 |
| MLP 激活函数 | SwiGLU | SwiGLU | SwiGLU | SwiGLU |
| 专家数量 | — | — | 32 | 40 |
| MoE TopK | — | — | 8 | 8 |
| 初始化标准差 | 0.1 | 0.1 | 0.1 | 0.1 |
| 序列长度 | 4096 | 4096 | 4096 | 4096 |
| 位置嵌入方式 | RoPE | RoPE | RoPE | RoPE |
| 参数总量 | 2.5B | 8.1B | 1.3B | 3.3B |
| 活跃参数数量 | 2.5B | 8.1B | 400M | 800M |
| 训练 tokens 总量 | 12T | 12T | 10T | 10T |
训练数据:
本模型采用两阶段训练策略,训练数据混合了开源数据和专有数据。
数据集的详细来源说明可参见 Granite 技术报告 和 作者致谢名单。
基础设施:
我们使用 IBM 的超级计算集群 Blue Vela 训练 Granite 3.0 语言模型,该集群配备了 NVIDIA H100 GPU。此集群提供了可扩展且高效的基础设施,支持在数千块 GPU 上训练模型,同时通过 100% 使用可再生能源,最大限度地降低环境影响。
伦理考量与局限性:
大型语言模型的使用涉及风险和伦理考量,使用者必须予以关注,包括但不限于:偏见与公平性、虚假信息以及自主决策。Granite-3.0-2B-Base 模型在这方面也不例外。尽管该模型适用于多种生成式 AI 任务,但它未经过任何安全对齐处理,因此可能会产生有问题的输出。此外,由于较小模型的规模和记忆能力有限,在生成场景中可能更容易通过逐字复制训练数据中的文本来产生幻觉,这一点目前尚不确定。这一领域目前是研究热点,我们期待未来能有更深入的探索、理解和缓解措施。在伦理方面,所有大型语言模型都存在被恶意利用的潜在风险。我们呼吁社区以符合伦理的意图并负责任地使用 Granite-3.0-2B-Base 模型。