qwen.cpp简明教程

1、下载并编译qwen.cpp

git clone --recursive https://github.com/QwenLM/qwen.cpp
cd qwen.cpp
cmake -B build
cmake -B build -DGGML_OPENBLAS=ON
cmake -B build -DGGML_CUBLAS=ON
cmake --build build -j --config Release

2、下载模型,转化为ggml格式

#从hf下载模型,下载完成后,本地地址为 ~/.cache/huggingface/hub/模型名称
#部分代码文件会有缺失,可以到hf上对比下载
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat",trust_remote_code=True)
#模型转化为ggml格式
#同时进行量化,降低资源需求
python3 qwen_cpp/convert.py -i PATH_TO_MODEL -t q4_0 -o qwen7b-q40-ggml.bin

3、运行模型

./build/bin/main -m qwen7b-q40-ggml.bin --tiktoken PATH_TO_MODEL/qwen.tiktoken -i

chatglm.cpp简明教程

1、下载并编译chatglm.cpp

git clone --recursive https://github.com/li-plus/chatglm.cpp.git
cd chatglm.cpp
git submodule update --init --recursive
#cmake -B build
cmake -B build -DGGML_OPENBLAS=ON
#cmake -B build -DGGML_CUBLAS=ON
cmake --build build -j --config Release

2、下载模型,转化为ggml格式

#从hf下载模型,下载完成后,本地地址为 ~/.cache/huggingface/hub/模型名称
#部分代码文件会有缺失,可以到hf上对比下载
from transformers import AutoModel
model = AutoModel.from_pretrained("THUDM/chatglm-6b",trust_remote_code=True)
#模型转化为ggml格式
#同时进行量化,降低资源需求
pip install torch tabulate tqdm transformers accelerate sentencepiece
python3 chatglm_cpp/convert.py -i PATH_TO_MODEL -t q4_0 -o chatglm-6b-q40-ggml.bin

3、运行模型

./build/bin/main -m chatglm-6b-q40-ggml.bin -i

4、常见问题

#下面的错误,是transformers版本太高导致
AttributeError: 'ChatGLMTokenizer' object has no attribute 'sp_tokenizer'. Did you mean: '_tokenize'?
#需要降低transformers版本
pip uninstall transformers
pip install transformers==4.33.2

大语言模型资料汇总

一、之前整理了一些大模型的Demo,汇总如下
1、ChatGPT
https://github.com/neohope/NeoDemosChatGPT

2、Llama2
https://github.com/neohope/NeoDemosLlama2
可同步看一下中文版Llama2
https://github.com/ymcui/Chinese-LLaMA-Alpaca-2

3、阿里千问
https://github.com/neohope/NeoDemosQwen

4、清华ChatGLM
https://github.com/neohope/NeoDemosChatGLM

二、建议看一下llama.cpp
1、llama.cpp
https://github.com/ggerganov/llama.cpp

2、python的llama.cpp封装
https://github.com/abetlen/llama-cpp-python

3、千问的qwen.cpp实现
https://github.com/QwenLM/qwen.cpp

4、ChatGLM的chatglm.cpp实现
https://github.com/li-plus/chatglm.cpp

三、还有量化
https://github.com/AutoGPTQ/AutoGPTQ

四、当然还有langchain
https://github.com/langchain-ai/langchain

五、如果有余力,看一下Transformer实现
https://github.com/huggingface/transformers

llama.cpp简要教程

1、下载并编译llama.cpp

git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp
make

2、下载llama-2-7b-chat
a、可以从fb或hf下载
b、可以使用脚本下载工具,比如llama-dl
c、可以使用Chinese-LLaMA-2-7B
d、可以使用其他三方源

3、模型转换为ggml格式

python3 convert.py ../llama/llama-2-7b-chat/ 
Loading model file ../llama/llama-2-7b-chat/consolidated.00.pth
params = Params(n_vocab=32000, n_embd=4096, n_layer=32, n_ctx=2048, n_ff=11008, n_head=32, n_head_kv=32, n_experts=None, n_experts_used=None, f_norm_eps=1e-06, rope_scaling_type=None, f_rope_freq_base=None, f_rope_scale=None, n_orig_ctx=None, rope_finetuned=None, ftype=None, path_model=PosixPath('../llama/llama-2-7b-chat'))
Found vocab files: {'tokenizer.model': PosixPath('../llama/tokenizer.model'), 'vocab.json': None, 'tokenizer.json': None}
Loading vocab file '../llama/tokenizer.model', type 'spm'
Vocab info: <SentencePieceVocab with 32000 base tokens and 0 added tokens>
Special vocab info: <SpecialVocab with 0 merges, special tokens unset, add special tokens unset>
tok_embeddings.weight                            -> token_embd.weight                        | BF16   | [32000, 4096]
norm.weight                                      -> output_norm.weight                       | BF16   | [4096]
output.weight                                    -> output.weight                            | BF16   | [32000, 4096]
layers.0.attention.wq.weight                     -> blk.0.attn_q.weight                      | BF16   | [4096, 4096]
...
layers.31.ffn_norm.weight                        -> blk.31.ffn_norm.weight                   | BF16   | [4096]
skipping tensor rope_freqs
Writing ../llama/llama-2-7b-chat/ggml-model-f16.gguf, format 1
Ignoring added_tokens.json since model matches vocab size without it.
gguf: This GGUF file is for Little Endian only
[  1/291] Writing tensor token_embd.weight                      | size  32000 x   4096  | type F16  | T+   3
...
[291/291] Writing tensor blk.31.ffn_norm.weight                 | size   4096           | type F32  | T+ 314
Wrote ../llama/llama-2-7b-chat/ggml-model-f16.gguf

4、模型量化,减少资源使用

./quantize ../llama/llama-2-7b-chat/ggml-model-f16.gguf  ../llama/llama-2-7b-chat/ggml-model-f16-q4_0.gguf q4_0 
main: build = 2060 (5ed26e1f)
main: built with cc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 for x86_64-linux-gnu
main: quantizing '../llama/llama-2-7b-chat/ggml-model-f16.gguf' to '../llama/llama-2-7b-chat/ggml-model-f16-q4_0.gguf' as Q4_0
llama_model_loader: loaded meta data with 15 key-value pairs and 291 tensors from ../llama/llama-2-7b-chat/ggml-model-f16.gguf (version GGUF V3 (latest))
llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output.
llama_model_loader: - kv   0:                       general.architecture str              = llama
llama_model_loader: - kv   1:                               general.name str              = llama
llama_model_loader: - kv   2:                       llama.context_length u32              = 2048
llama_model_loader: - kv   3:                     llama.embedding_length u32              = 4096
llama_model_loader: - kv   4:                          llama.block_count u32              = 32
llama_model_loader: - kv   5:                  llama.feed_forward_length u32              = 11008
llama_model_loader: - kv   6:                 llama.rope.dimension_count u32              = 128
llama_model_loader: - kv   7:                 llama.attention.head_count u32              = 32
llama_model_loader: - kv   8:              llama.attention.head_count_kv u32              = 32
llama_model_loader: - kv   9:     llama.attention.layer_norm_rms_epsilon f32              = 0.000001
llama_model_loader: - kv  10:                          general.file_type u32              = 1
llama_model_loader: - kv  11:                       tokenizer.ggml.model str              = llama
llama_model_loader: - kv  12:                      tokenizer.ggml.tokens arr[str,32000]   = ["<unk>", "<s>", "</s>", "<0x00>", "<...
llama_model_loader: - kv  13:                      tokenizer.ggml.scores arr[f32,32000]   = [0.000000, 0.000000, 0.000000, 0.0000...
llama_model_loader: - kv  14:                  tokenizer.ggml.token_type arr[i32,32000]   = [2, 3, 3, 6, 6, 6, 6, 6, 6, 6, 6, 6, ...
llama_model_loader: - type  f32:   65 tensors
llama_model_loader: - type  f16:  226 tensors
llama_model_quantize_internal: meta size = 740928 bytes
[   1/ 291]                    token_embd.weight - [ 4096, 32000,     1,     1], type =    f16, quantizing to q4_0 .. size =   250.00 MiB ->    70.31 MiB | hist: 0.037 0.016 0.025 0.039 0.057 0.077 0.096 0.111 0.116 0.111 0.096 0.077 0.057 0.039 0.025 0.021 
...   
[ 291/ 291]               blk.31.ffn_norm.weight - [ 4096,     1,     1,     1], type =    f32, size =    0.016 MB
llama_model_quantize_internal: model size  = 12853.02 MB
llama_model_quantize_internal: quant size  =  3647.87 MB
llama_model_quantize_internal: hist: 0.036 0.015 0.025 0.039 0.056 0.076 0.096 0.112 0.118 0.112 0.096 0.077 0.056 0.039 0.025 0.021 
main: quantize time = 323302.84 ms
main:    total time = 323302.84 ms

5、使用模型

./main -m ../llama/llama-2-7b-chat/ggml-model-f16-q4_0.gguf -n 256 --repeat_penalty 1.0 --color -ins

使用ChatGPT翻译了几本书

在2014年左右,一直想翻译几本小册子(主要是介绍编的程经验教训,内容其实很老了,但当时有些内容确实触动了我),陆陆续续翻译了其中的一些文章,但各种原因还是没能翻译完毕,算是一个小遗憾。

最近用ChatGPT硬翻了一遍,感觉效果还可以,感兴趣的朋友可以随便翻翻。

架构师应该知道的97件事【ChatGPT翻译版本,52篇】
https://github.com/neohope/97-things-every-software-architect-should-know.git

敏捷程序员应该知道的97件事【ChatGPT翻译版本,26篇】
https://github.com/neohope/97-things-every-agile-developer-should-know.git

程序员应该知道的97件事【ChatGPT翻译版本,97篇】
https://github.com/neohope/97-things-every-programmer-should-know.git

对比了一下自己翻译的版本:
1、最大的感触之一是质量的提升,比Goolge、NewBing翻译的都要好很多,十年前的翻译效果更是没法比
2、最大的感触之二是效率,175篇文章,加上编程、翻译及校对的时间,花了不到10小时(很多是零散时间),平均一篇文章3分半不到,比之前人工+Google的速度快了不止10倍
3、有些文章质量仍有待提升

还有一些感触:
1、虽然有些文章质量有待提升,但非专业领域翻译相关工作被替代可能性十分高大概率会被迫转型,专业领域翻译相关工作效率也会大幅增加大概率不需要这么多人力了
2、后续互联网客服、视频脚本编写、字幕翻译、新闻稿编写、文章编纂、律师助理等文字相关工作人员,会逐步面临更大职业压力
3、建议早点学会用AI提升个人生产力,淘汰不会用AI的人

谈谈ChatGPT

春节期间,试用了ChatGPT,让我被惊艳到了。
大模型的涌现效果,能达到ChatGPT3.5的程度,着实让我有些吃惊,真是大力出奇迹啊。

在此之前,我一直认为本次AI技术革命已经接近尾声了:
1、在影像和视频方面,AI已经可以实现商业化:医疗影像AI诊断、自动驾驶、人脸识别、图像搜索、P图滤镜等;
2、在语音方面,语音识别和语音合成已经很成熟;
3、在NLP方面,简单重复任务可以较好完成,比如机器翻译、文本搜索等。但在复杂任务上,还处于有多少人工就有多少智能的尴尬阶段,距离商业化有较长的路需要走;
而且,无论是哪个领域,大家可以发现,AI还是只是一种能力、一个工具,也就是处于“业务X+AI”的模式。
就算AI是生产力,但想象空间也就那么大,因为领域已经被限制死了。

但ChatGPT改变了这个局面,聊天这个场景,可以让ChatGPT成为一个各种能力的插座。
也就是说,一个类似于ChatGPT的大模型,如果能快速整合各种外部能力,从“业务X+AI”,变成“AI+业务X、业务Y、业务Z”的模式,很可能会成为下一代互联网的入口,并从各种维度给人类带来全新体验。

钢铁侠的贾维斯(J.A.R.V.I.S.)还是保守了,我们有更广阔的空间,十分期待这个时代能尽快到来。

同时,国内大厂的大模型层出不穷,究竟谁能成功,还要看三个地方:
1、要有足够大量的数据
2、要有AI人才储备
3、要有足够算力,如果现在才去买显卡,就很难赶上了
国内满足这几点的有:百度、字节、阿里

最近看了一些ChatGPT资料,整理了一些相关示例:
https://github.com/neohope/NeoDemosChatGPT

其中多数例子,来源于极客时间徐文浩老师的课程《AI大模型之美》:
https://time.geekbang.org/column/intro/100541001?tab=catalog

================
补充0812:
当前国内大模型厂商,在底层方面依赖英伟达,在模型技术层面无法相互拉开差距,只能继续向上做:
1、在基础模型层面,支持各类开源模型,弥补自家模型缺点
2、在行业领域,开展合作,把垂直领域模型吃掉
3、在应用层面,也开始逐步布局
加上外资撤出,投资方的钱更难拿,围剿之下,AI方向国内的创业氛围就比较差了。

TensorFlow入门02:Tensor

Tensorflow中所有的数据都称为Tensor,可以是一个变量、数组或者多维数组。Tensor 有几个重要的属性:
Rank:纬数,比如scalar rank=0, vector rank=1, matrix rank=2
Shape:形状,比如vector shape=[D0], matrix shape=[D0, D1]
类型:数据类型,比如tf.float32, tc.uint8等

Rank与Shape关系如下表所示

Rank Shape Dimension number Example
0 [] 0-D A 0-D tensor. A scalar.
1 [D0] 1-D A 1-D tensor with shape [5].
2 [D0, D1] 2-D A 2-D tensor with shape [3, 4].
3 [D0, D1, D2] 3-D A 3-D tensor with shape [1, 4, 3].
n [D0, D1, … Dn-1] n-D A tensor with shape [D0, D1, … Dn-1].

TensorFlow入门01:环境搭建

1、CPU版本安装

1.1 安装tensorflow

pip3 install --upgrade tensorflow

1.2 Python验证,看到版本信息就可以了

python3
>>> import tensorflow as tf
>>> print('Tensorflow version ', tf.__version__)

Tensorflow version  1.12.0

2、GPU版本安装(需要NVIDIA显卡)

2.1 检查驱动信息

nvidia-smi

Fri Nov 16 21:22:13 2018
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 390.77                 Driver Version: 390.77                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 106...  Off  | 00000000:01:00.0 Off |                  N/A |
| N/A   52C    P2    27W /  N/A |   5938MiB /  6078MiB |     22%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      7953      G   /usr/lib/xorg/Xorg                           126MiB |
|    0      8215      G   /usr/bin/gnome-shell                         109MiB |
|    0     13578    C+G   python3                                     5689MiB |
+-----------------------------------------------------------------------------+

2.2 安装CUDA

# 查看网站 https://developer.nvidia.com/cuda-90-download-archive?target_os=Linux&target_arch=x86_64&target_distro=Ubuntu&target_version=1704&target_type=runfilelocal
# 选择下载这个版本 Linux x86_64 Ubuntu 17.04 runfile
# 安装,但注意不要更新驱动
sudo chmod +x cuda_9.0.176_384.81_linux.run
./cuda_9.0.176_384.81_linux.run --override

2.3 安装CUDNN

# 查看网站 https://developer.nvidia.com/rdp/cudnn-download
# 选择下载这个版本 9.0 cuDNN Library for Linux
# 解压
tar -zxvf cudnn-9.0-linux-x64-v7.tgz
# 手工安装
sudo cp -P cuda/lib64/libcudnn* /usr/local/cuda-9.0/lib64/
sudo cp  cuda/include/cudnn.h /usr/local/cuda-9.0/include/
# 调整权限
sudo chmod a+r /usr/local/cuda-9.0/include/cudnn.h /usr/local/cuda-9.0/lib64/libcudnn*

2.3 安装libcupti-dev

sudo apt-get install libcupti-dev

2.4 修改.bashrc

# 增加下面两行
export PATH=/usr/local/cuda-9.0/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}

2.5 安装tensorflow-gpu

pip3 install --upgrade tensorflow-gpu

2.6 Python验证,看到GPU就可以啦

Python3
>>> from tensorflow.python.client import device_lib
>>> device_lib.list_local_devices()

[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
...
incarnation: 2559160109308400478
physical_device_desc: "device: 0, name: GeForce GTX 1060 with Max-Q Design, pci bus id: 0000:01:00.0, compute capability: 6.1"
]

3、Docker方式安装
3.1 CPU版

# 运行tensorflow
docker run -it -p 8888:8888 gcr.io/tensorflow/tensorflow

3.2 GPU版

# 安装nvidia-docker
wget https://github.com/NVIDIA/nvidia-docker/releases/download/v1.0.1/nvidia-docker_1.0.1-1_amd64.deb
sudo dpkg -i nvidia-docker*.deb

# 测试nvidia-docker,执行nvidia-smi命令
nvidia-docker run --rm nvidia/cuda nvidia-smi

# 运行tensorflow
nvidia-docker run -it -p 8888:8888 gcr.io/tensorflow/tensorflow:latest-gpu

4、编译CUDA Demo(非必须)

# 咱们选用的版本只支持到gcc6
apt-get install gcc-6 g++-6
ln -s /bin/gcc /bin/gcc-6

# 安装libmpich-dev
sudo apt-get install libmpich-dev


# 切换路径
cd PATH_TO_DEMO

# 编译
make

知识图谱03:JENA

1、下载apache-jena-fuseki和apache-jena
https://jena.apache.org/download/index.cgi

2、将上一篇教程的nt文件转换为tdb格式

cd apache-jena-3.9.0\bat
tdbloader.bat --loc="PATH_TO_TDB\tdb" "PATH_TO_NT\movies_mapping.nt"

3、切换到apache-jena-fuseki-3.9.0目录,启动一次服务,然后退出

4、将教程1里面的Movies.owl,拷贝到apache-jena-fuseki-3.9.0\run\databases路径下面,并重命名为Movies.ttl

5、创建配置文件apache-jena-fuseki-3.9.0\run\configuration\fuseki_conf.ttl

@prefix fuseki: <http://jena.apache.org/fuseki#> . 
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . 
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . 
@prefix tdb: <http://jena.hpl.hp.com/2008/tdb#> . 
@prefix ja: <http://jena.hpl.hp.com/2005/11/Assembler#> . 
@prefix : <http://base/#> . 

<#service> rdf:type fuseki:Service ; 
    fuseki:name "movies" ;
    fuseki:serviceQuery "sparql" ;
    fuseki:dataset <#dataset> ; 
    fuseki:serviceReadGraphStore      "get" ;
    fuseki:serviceReadWriteGraphStore "data" ;
    fuseki:serviceUpdate              "update" ;
    fuseki:serviceUpload              "upload"
    . 

<#dataset> rdf:type ja:RDFDataset ;
	ja:defaultGraph <#modelInf> ;
	.

<#modelInf> 
    rdf:type ja:InfModel ;
    #ja:reasoner [ja:reasonerURL <http://jena.hpl.hp.com/2003/OWLFBRuleReasoner>]  
    ja:reasoner [ 
        ja:reasonerURL <http://jena.hpl.hp.com/2003/GenericRuleReasoner> ; 
        ja:rulesFrom <file:///D:/ProjectsMy/KG/apache-jena-fuseki-3.9.0/run/databases/Rules.ttl> ] ; 
    ja:baseModel <#baseModel> ; 
    . 

<#baseModel> rdf:type tdb:GraphTDB ; 
    tdb:location "D:/ProjectsMy/KG/workspace/data/tdb" ; 
    tdb:unionDefaultGraph true ; 
    .

6、创建规则文件apache-jena-fuseki-3.9.0\run\databases\Movies.ttl
这个规则规定了,演过喜剧的演员,叫做喜剧演员(Comedian)

@prefix xsd: <XML Schema> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix : <https://www.neohope.com/hansen/ontologies/2018/movies#> .

[ruleComedian: (?aPerson :hasActedIn ?aMovie) (?aMovie :hasGenre ?aGenre) (?aGenre :genreName '喜剧') -> (?aPerson rdf:type :Comedian)]
[ruleInverse: (?aPerson :hasActedIn ?aMove) -> (?aMovie :hasActor ?aPerson)]

7、启动apache-jena-fuseki-3.9.0

8、访问http://localhost:3030/

9、进行查询,上一篇的例子也都可以用
http://localhost:3030/dataset.html?tab=query&ds=/movies

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
prefix owl: <http://www.w3.org/2002/07/owl#>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
prefix : <https://www.neohope.com/hansen/ontologies/2018/movies#>

SELECT ?name WHERE {
?aComedian rdf:type :Comedian.
?aComedian :personName ?name.
}
LIMIT 10

10、通过python访问
https://github.com/neohope/kg-demo-for-movie/tree/master/src/query-jena.py

参考链接:
https://zhuanlan.zhihu.com/knowledgegraph
https://github.com/SimmerChan/KG-demo-for-movie

PS:
参考教程中,原作者通过结巴分词+正则匹配+Jena,实现了一个简单的问答系统,感兴趣的话,大家可以看下。

知识图谱02:RDF

1、安装MySQL5,并新建movies库

2、导入数据
https://github.com/neohope/kg-demo-for-movie/tree/master/data/movies.sql

3、下载d2rq,并配置好JDK环境变量
http://d2rq.org/

4、利用d2rq生成mapping

generate-mapping -u movie -p password -o movies_mapping.ttl jdbc:mysql:///movies

5、手工编辑ttl,任务如下
设置正确的域名
修正类名与属性名
删除一些不需要的字段
修改前后的数据可以在这里找到
https://github.com/neohope/kg-demo-for-movie/tree/master/data/movies_mapping.ttl
https://github.com/neohope/kg-demo-for-movie/tree/master/data/movies_mapping_ok.ttl

6、输出RDF文件,用于后续的教程

dump-rdf.bat -o movies_mapping.nt movies_mapping_ok.ttl

7、启动d2r服务

d2r-server.bat movies_mapping_ok.ttl

8、访问及浏览数据
http://localhost:2020/

9、查询
http://localhost:2020/snorql/

#周星驰演过的电影
SELECT ?title WHERE {
  ?aPerson rdf:type :Person.
  ?aPerson :personName '周星驰'.
  ?aPerson :hasActedIn ?aMovie.
  ?aMovie :movieTitle ?title
}
LIMIT 10


#英雄的演员
SELECT ?actor WHERE {
  ?aMovie rdf:type :Movie.
  ?aMovie :movieTitle '英雄'.
  ?aPerson :hasActedIn ?aMovie.
  ?aPerson :personName ?actor
}
LIMIT 10


#巩俐参演的,评分高于7的电影
SELECT ?title WHERE {
  ?aPerson rdf:type :Person.
  ?aPerson  :personName '巩俐'.
  ?aPerson  :hasActedIn ?aMovie.
  ?aMovie :movieTitle ?title.
  ?aMovie :movieRating ?rating.
  FILTER (?rating>=7)
}
LIMIT 10

10、通过python访问
https://github.com/neohope/kg-demo-for-movie/tree/master/src/query-d2rq.py

参考链接:
https://zhuanlan.zhihu.com/knowledgegraph
https://github.com/SimmerChan/KG-demo-for-movie