文章目录
- 一、从 GGUF 导入
- 1.1 CCUF 介绍
- 1.2 导入方式
- 二、由模型直接导入
- 2.1 模型下载
- 2.2 使用 llama.cpp 进行转换
- (1)克隆 llama.cpp 库到本地,并安装相关库
- (2)环境验证
- (3)执行转换程序
- 2.3 使用llama.cpp进行模型量化
- (1)创建Modelfile 文件
- (2)使 用 `ollama create` 命令创建模型并量化
- (3) 结果校验
- 三、从 Pytorch 或 Safetensors 导入
- 四、上传模型到huggingface
使用 Modelfile 在Ollama 自定义导入模型,包含三种方式,分别是1.从 GGUF 导入 2.从 Pytorch 或 Safetensors 导入,3由模型直接导入.
一、从 GGUF 导入
1.1 CCUF 介绍
GGUF (GPT-Generated Unified Format) 是一种文件格式,用于保存经过微调的语言模型,旨在帮助用于用于在不同的平台和环境之间共享和导入模型。
支持多种量化格式,可以有效的减少模型文件的大小
1.2 导入方式
(1)下载.gguf 文件
以qwen0.5b 模型为示例,下载链接为:
https://huggingface.co/RichardErkhov/Qwen_-_Qwen2-0.5B-gguf/resolve/main/Qwen2-0.5B.Q3_K_M.gguf?download=true
(2)在gguf 文件所在目录新建 ‘Modelfile’ 文件,并写入
FROM ./Qwen2-0.5B.Q3_K_M.gguf
其中Modelfile 为文件名,无后缀,可以根据实际情况进行更改。
(3)在ollama 中创建模型
ollama create mymodel -f Modelfile #mymodel为模型名,Modelfile 为第二个步骤中创建的文件 ,-f 参数用于指定从文件中进行创建
(4)检查模型导入是否成功
ollama list
以下为正常导入的结果
$ ollama list
NAME ID SIZE MODIFIED
mymodel:latest 3c4ac1ac3829 355 MB 46 hours ago
二、由模型直接导入
2.1 模型下载
以从 HuggingFace 下载 Model为例,首先需要用户个人的 ACCESS_TOKEN
,然后使用脚本进行下载。
(1)ACCESS_TOKEN
获取
登陆huggingface官网,并进行注册。ACCESS_TOKEN
获取链接为:
https://huggingface.co/settings/tokens
通过点击Create new token
进行token的创建。如图所示
(2)使用 huggingface_hub
的 snapshot_download
下载模型
以Qwen-0.5b 模型为例,首先下载安装包
pip install huggingface_hub
下载脚本如下
from huggingface_hub import snapshot_download
model_id = "Qwen/Qwen1.5-0.5B" # hugginFace's model name
snapshot_download(
repo_id=model_id,
local_dir="Qwen-0.5b",
local_dir_use_symlinks=False,
revision="main",
use_auth_token="<YOUR_ACCESS_TOKEN>")
需要注意虚拟环境的python版本>3.8。
下载后模型的模型为
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2025/2/12 18:17 1519 .gitattributes
-a---- 2025/2/12 18:17 661 config.json
-a---- 2025/2/12 18:17 138 generation_config.json
-a---- 2025/2/12 18:17 7281 LICENSE
-a---- 2025/2/12 18:17 1671839 merges.txt
-a---- 2025/2/12 11:02 1239173352 model.safetensors
-a---- 2025/2/12 18:17 2773 README.md
-a---- 2025/2/12 18:17 7028015 tokenizer.json
-a---- 2025/2/12 18:17 1289 tokenizer_config.json
-a---- 2025/2/12 18:17 2776833 vocab.json
2.2 使用 llama.cpp 进行转换
llama.cpp 是 GGML 主要作者基于最早的 llama 的 c/c++ 版本开发的,目的就是希望用 CPU 来推理各种 LLM。
(1)克隆 llama.cpp 库到本地,并安装相关库
git clone https://github.com/ggerganov/llama.cpp.git
由于使用 llama.cpp 转换模型的流程基于 python 开发,需要安装相关的库,推荐使用 conda 或 venv 新建一个环境。(建议python>3.8)
cd llama.cpp
pip install -r requirements.txt
(2)环境验证
python convert_hf_to_gguf.py -h
如果显示以下内容,说明转换程序已经安装好了。
$ python convert_hf_to_gguf.py -h
usage: convert_hf_to_gguf.py [-h] [--vocab-only] [--outfile OUTFILE] [--outtype {f32,f16,bf16,q8_0,tq1_0,tq2_0,auto}] [--bigendian] [--use-temp-file] [--no-lazy] [--model-name MODEL_NAME] [--verbose] [--split-max-tensors SPLIT_MAX_TENSORS]
[--split-max-size SPLIT_MAX_SIZE] [--dry-run] [--no-tensor-first-split] [--metadata METADATA] [--print-supported-models]
[model]
Convert a huggingface model to a GGML compatible file
positional arguments:
model directory containing model file
options:
-h, --help show this help message and exit
--vocab-only extract only the vocab
--outfile OUTFILE path to write to; default: based on input. {ftype} will be replaced by the outtype.
--outtype {f32,f16,bf16,q8_0,tq1_0,tq2_0,auto}
output format - use f32 for float32, f16 for float16, bf16 for bfloat16, q8_0 for Q8_0, tq1_0 or tq2_0 for ternary, and auto for the highest-fidelity 16-bit float type depending on the first loaded tensor type
--bigendian model is executed on big endian machine
--use-temp-file use the tempfile library while processing (helpful when running out of memory, process killed)
--no-lazy use more RAM by computing all outputs before writing (use in case lazy evaluation is broken)
--model-name MODEL_NAME
name of the model
--verbose increase output verbosity
--split-max-tensors SPLIT_MAX_TENSORS
max tensors in each split
--split-max-size SPLIT_MAX_SIZE
max size per split N(M|G)
--dry-run only print out a split plan and exit, without writing any new files
--no-tensor-first-split
do not add tensors to the first split (disabled by default)
--metadata METADATA Specify the path for an authorship metadata override file
--print-supported-models
Print the supported models
(3)执行转换程序
将刚刚从 HuggingFace 下载的模型转换为 GGUF 格式,具体使用以下脚本:
python convert_hf_to_gguf.py ../Qwen-0.5b --outfile TestQwen_instruct_0.5b.gguf --outtype f16
可以看到 llama.cpp 目录下多了一个 Qwen_instruct_0.5b.gguf 文件,这个过程只需要几秒钟。
出现Model successfully exported to ..
即说明转换成功,部分运行日志如下:
You are a helpful assistant<|im_end|>
' }}{% endif %}{{'<|im_start|>' + message['role'] + '
' + message['content'] + '<|im_end|>' + '
'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
' }}{% endif %}
INFO:hf-to-gguf:Set model quantization version
INFO:gguf.gguf_writer:Writing the following files:
INFO:gguf.gguf_writer:TestQwen_instruct_0.5b.gguf: n_tensors = 291, total_size = 1.2G
Writing: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1.24G/1.24G [00:03<00:00, 409Mbyte/s]
INFO:hf-to-gguf:Model successfully exported to TestQwen_instruct_0.5b.gguf
2.3 使用llama.cpp进行模型量化
模型量化的主要目的是减少模型的大小和计算成本,尽可能保持模型的准确性,其目标是使模型能够在资源有限的设备上运行,例如CPU或者移动设备。步骤如下
(1)创建Modelfile 文件
创建 Modelfile 文件并写入以下内容.
FROM ./TestQwen_instruct_0.5b.gguf
(2)使 用 ollama create
命令创建模型并量化
终端运行创建和量化脚本。
ollama create -q Q4_K_M mymodel3 -f ./Modelfile
运行日志如下
$ ollama create -q Q4_K_M Qwen_instruct_05b_Q4 -f ./Modelfile
gathering model components
copying file sha256:6847f0eb96c0d6e33f885abfd7e763bb4d95d278b489833d598718dcb3690c27 100%
parsing GGUF
quantizing F16 model to Q4_K_M
using existing layer sha256:e22e98740aac6978d9aa4c13d8fbc48231eca7182379b98d8ce9a2eca893c0c5
using autodetected template chatml
using existing layer sha256:f02dd72bb2423204352eabc5637b44d79d17f109fdb510a7c51455892aa2d216
writing manifest
success
(3) 结果校验
$ ollama list
NAME ID SIZE MODIFIED
Qwen_instruct_05b_Q4:latest 579ca029b3b3 407 MB About a minute ago
三、从 Pytorch 或 Safetensors 导入
Safetensors 是一种用于存储深度学习模型权重的文件格式,它旨在解决安全性、效率和易用性方面的问题。
如果正在导入的模型是以下架构之一,则可以通过 Modelfile 直接导入 Ollama。
- LlamaForCausalLM
- MistralForCausalLM
- GemmaForCausalLM
以llama-3-8b-bnb-4bit 为例,下载代码如下所示
from huggingface_hub import snapshot_download
model_id = "unsloth/llama-3-8b-bnb-4bit"
snapshot_download(
repo_id=model_id,
local_dir="llama-3-8b-bnb-4bit",
local_dir_use_symlinks=False,
revision="main",
# 怎么获取<YOUR_ACCESS_TOKEN>,请参照部分2
use_auth_token="<YOUR_ACCESS_TOKEN>")
转换步骤为
(1)根目录下创建 Modelfile 文件,内容如下:
FROM ./llama-3-8b-bnb-4bit
(2)在 Ollama 中创建模型
ollama create mymodel2 -f Modelfile
四、上传模型到huggingface
代码如下
from huggingface_hub import HfApi
import os
api = HfApi()
HF_ACCESS_TOKEN = "<YOUR_HF_WRITE_ACCESS_TOKEN>"
#TODO 这里需要设置你的model_id
#例如 model_id = "little1d/QWEN-0.5b"
model_id = "your_hf_name/QWEN-0.5b"
api.create_repo(
model_id,
exist_ok=True,
repo_type="model", # 上傳格式為模型
use_auth_token=HF_ACCESS_TOKEN,
)
# upload the model to the hub
# upload model name includes the Bailong-instruct-7B in same folder
for file in os.listdir():
if file.endswith(".gguf"):
model_name = file.lower()
api.upload_file(
repo_id=model_id,
path_in_repo=model_name,
path_or_fileobj=f"{os.getcwd()}/{file}",
repo_type="model", # 上傳格式為模型
use_auth_token=HF_ACCESS_TOKE)
需要注意的是如果想完成上传,你的 HF_ACCESS_TOKEN 权限必须要为 write,并且要修改你的 model_id,your_hf_name 指的是你 huggingface 账号名称。
上传后可以在网页上查看,效果如下: