利用llama.cpp实现LLM大模型的格式转换、量化、推理、摆设 ...

打印 上一主题 下一主题

主题 582|帖子 582|积分 1746

llama.cpp实现大模型的格式转换、量化、推理、摆设

概述

   llama.cpp的重要目标是能够在各种硬件上实现LLM推理,只需最少的设置,并提供最先辈的性能。提供1.5位、2位、3位、4位、5位、6位和8位整数量化,以加速推理速度并淘汰内存利用。
  GitHub:https://github.com/ggerganov/llama.cpp
克隆和编译

克隆最新版llama.cpp堆栈代码
  1. git clone https://github.com/ggerganov/llama.cpp
复制代码
对llama.cpp项目举行编译,在目次下会生成一系列可执行文件
  1. main:使用模型进行推理
  2. quantize:量化模型
  3. server:提供模型API服务
复制代码
1.编译构建CPU执行环境,安装简单,实用于没有GPU的利用体系
  1. cd llama.cpp
  2. mkdir
复制代码
2.编译构建GPU执行环境,确保安装CUDA工具包,实用于有GPU的利用体系
   如果CUDA设置正确,那么执行nvidia-smi、nvcc --version没有错误提示,则表现一切设置正确。
  1. make clean
  2. &&  make LLAMA_CUDA=1
复制代码
3.如果编译失败大概需要重新编译,可实行清算并重新编译,直至编译乐成
  1. make clean
复制代码
环境准备

1.下载受支持的模型
   要利用llamma.cpp,首先需要准备它支持的模型。在官方文档中给出了说明,这里仅仅截取其中一部分
  
2.安装依靠
   llama.cpp项目下带有requirements.txt 文件,直接安装依靠即可。
  1. pip install -r requirements.txt
复制代码
模型格式转换

   根据模型架构,可以利用convert.py或convert-hf-to-gguf.py文件。
    转换脚本读取模型配置、分词器、张量名称+数据,并将它们转换为GGUF元数据和张量。
  GGUF格式

   Llama-3相比其前两代明显扩充了词表大小,由32K扩充至128K,而且改为BPE词表。因此需要利用--vocab-type参数指定分词算法,默认值是spm,如果是bpe,需要表现指定
  注意:
   官方文档说convert.py不支持LLaMA 3,喊利用convert-hf-to-gguf.py,但它不支持--vocab-type,且出现异常:error: unrecognized arguments: --vocab-type bpe,因此利用convert.py且没出问题
  利用llama.cpp项目中的convert.py脚本转换模型为GGUF格式
  1. root@master:~/work/llama.cpp# python3 ./convert.py  /root/work/models/Llama3-Chinese-8B-Instruct/ --outtype f16 --vocab-type bpe --outfile ./models/Llama3-FP16.gguf
  2. INFO:convert:Loading model file /root/work/models/Llama3-Chinese-8B-Instruct/model-00001-of-00004.safetensors
  3. INFO:convert:Loading model file /root/work/models/Llama3-Chinese-8B-Instruct/model-00001-of-00004.safetensors
  4. INFO:convert:Loading model file /root/work/models/Llama3-Chinese-8B-Instruct/model-00002-of-00004.safetensors
  5. INFO:convert:Loading model file /root/work/models/Llama3-Chinese-8B-Instruct/model-00003-of-00004.safetensors
  6. INFO:convert:Loading model file /root/work/models/Llama3-Chinese-8B-Instruct/model-00004-of-00004.safetensors
  7. INFO:convert:model parameters count : 8030261248 (8B)
  8. INFO:convert:params = Params(n_vocab=128256, n_embd=4096, n_layer=32, n_ctx=8192, n_ff=14336, n_head=32, n_head_kv=8, n_experts=None, n_experts_used=None, f_norm_eps=1e-05, rope_scaling_type=None, f_rope_freq_base=500000.0, f_rope_scale=None, n_orig_ctx=None, rope_finetuned=None, ftype=<GGMLFileType.MostlyF16: 1>, path_model=PosixPath('/root/work/models/Llama3-Chinese-8B-Instruct'))
  9. INFO:convert:Loaded vocab file PosixPath('/root/work/models/Llama3-Chinese-8B-Instruct/tokenizer.json'), type 'bpe'
  10. INFO:convert:Vocab info: <BpeVocab with 128000 base tokens and 256 added tokens>
  11. INFO:convert:Special vocab info: <SpecialVocab with 280147 merges, special tokens {'bos': 128000, 'eos': 128001}, add special tokens unset>
  12. INFO:convert:Writing models/Llama3-FP16.gguf, format 1
  13. WARNING:convert:Ignoring added_tokens.json since model matches vocab size without it.
  14. INFO:gguf.gguf_writer:gguf: This GGUF file is for Little Endian only
  15. INFO:gguf.vocab:Adding 280147 merge(s).
  16. INFO:gguf.vocab:Setting special token type bos to 128000
  17. INFO:gguf.vocab:Setting special token type eos to 128001
  18. INFO:gguf.vocab:Setting chat_template to {% set loop_messages = messages %}{% for message in loop_messages %}{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|>
  19. '+ message['content'] | trim + '<|eot_id|>' %}{% if loop.index0 == 0 %}{% set content = bos_token + content %}{% endif %}{{ content }}{% endfor %}{{ '<|start_header_id|>assistant<|end_header_id|>
  20. ' }}
  21. INFO:convert:[  1/291] Writing tensor token_embd.weight                      | size 128256 x   4096  | type F16  | T+   1
  22. INFO:convert:[  2/291] Writing tensor blk.0.attn_norm.weight                 | size   4096           | type F32  | T+   2
  23. INFO:convert:[  3/291] Writing tensor blk.0.ffn_down.weight                  | size   4096 x  14336  | type F16  | T+   2
  24. INFO:convert:[  4/291] Writing tensor blk.0.ffn_gate.weight                  | size  14336 x   4096  | type F16  | T+   2
  25. INFO:convert:[  5/291] Writing tensor blk.0.ffn_up.weight                    | size  14336 x   4096  | type F16  | T+   2
  26. INFO:convert:[  6/291] Writing tensor blk.0.ffn_norm.weight                  | size   4096           | type F32  | T+   2
  27. INFO:convert:[  7/291] Writing tensor blk.0.attn_k.weight                    | size   1024 x   4096  | type F16  | T+   2
  28. INFO:convert:[  8/291] Writing tensor blk.0.attn_output.weight               | size   4096 x   4096  | type F16  | T+   2
  29. INFO:convert:[  9/291] Writing tensor blk.0.attn_q.weight                    | size   4096 x   4096  | type F16  | T+   3
  30. INFO:convert:[ 10/291] Writing tensor blk.0.attn_v.weight                    | size   1024 x   4096  | type F16  | T+   3
  31. INFO:convert:[ 11/291] Writing tensor blk.1.attn_norm.weight                 | size   4096           | type F32  | T+   3
复制代码
转换为FP16的GGUF格式,模型体积大概15G。
  1. root@master:~/work/llama.cpp# ll models -h
  2. -rw-r--r--  1 root root  15G May 17 07:47 Llama3-FP16.gguf
复制代码
bin格式

  1. root@master:~/work/llama.cpp# python3 ./convert.py  /root/work/models/Llama3-Chinese-8B-Instruct/ --outtype f16 --vocab-type bpe --outfile ./models/Llama3-FP16.bin
  2. INFO:convert:Loading model file /root/work/models/Llama3-Chinese-8B-Instruct/model-00001-of-00004.safetensors
  3. INFO:convert:Loading model file /root/work/models/Llama3-Chinese-8B-Instruct/model-00001-of-00004.safetensors
  4. INFO:convert:Loading model file /root/work/models/Llama3-Chinese-8B-Instruct/model-00002-of-00004.safetensors
  5. INFO:convert:Loading model file /root/work/models/Llama3-Chinese-8B-Instruct/model-00003-of-00004.safetensors
  6. INFO:convert:Loading model file /root/work/models/Llama3-Chinese-8B-Instruct/model-00004-of-00004.safetensors
  7. INFO:convert:model parameters count : 8030261248 (8B)
  8. INFO:convert:params = Params(n_vocab=128256, n_embd=4096, n_layer=32, n_ctx=8192, n_ff=14336, n_head=32, n_head_kv=8, n_experts=None, n_experts_used=None, f_norm_eps=1e-05, rope_scaling_type=None, f_rope_freq_base=500000.0, f_rope_scale=None, n_orig_ctx=None, rope_finetuned=None, ftype=<GGMLFileType.MostlyF16: 1>, path_model=PosixPath('/root/work/models/Llama3-Chinese-8B-Instruct'))
  9. INFO:convert:Loaded vocab file PosixPath('/root/work/models/Llama3-Chinese-8B-Instruct/tokenizer.json'), type 'bpe'
  10. INFO:convert:Vocab info: <BpeVocab with 128000 base tokens and 256 added tokens>
  11. INFO:convert:Special vocab info: <SpecialVocab with 280147 merges, special tokens {'bos': 128000, 'eos': 128001}, add special tokens unset>
  12. INFO:convert:Writing models/Llama3-FP16.bin, format 1
  13. WARNING:convert:Ignoring added_tokens.json since model matches vocab size without it.
  14. INFO:gguf.gguf_writer:gguf: This GGUF file is for Little Endian only
  15. INFO:gguf.vocab:Adding 280147 merge(s).
  16. INFO:gguf.vocab:Setting special token type bos to 128000
  17. INFO:gguf.vocab:Setting special token type eos to 128001
  18. INFO:gguf.vocab:Setting chat_template to {% set loop_messages = messages %}{% for message in loop_messages %}{% set content = '<|start_header_id|>' + message['role'] + '<|end_header_id|>
  19. '+ message['content'] | trim + '<|eot_id|>' %}{% if loop.index0 == 0 %}{% set content = bos_token + content %}{% endif %}{{ content }}{% endfor %}{{ '<|start_header_id|>assistant<|end_header_id|>
  20. ' }}
  21. INFO:convert:[  1/291] Writing tensor token_embd.weight                      | size 128256 x   4096  | type F16  | T+   4
  22. INFO:convert:[  2/291] Writing tensor blk.0.attn_norm.weight                 | size   4096           | type F32  | T+   4
  23. INFO:convert:[  3/291] Writing tensor blk.0.ffn_down.weight                  | size   4096 x  14336  | type F16  | T+   4
  24. INFO:convert:[  4/291] Writing tensor blk.0.ffn_gate.weight                  | size  14336 x   4096  | type F16  | T+   5
  25. INFO:convert:[  5/291] Writing tensor blk.0.ffn_up.weight                    | size  14336 x   4096  | type F16  | T+   5
  26. INFO:convert:[  6/291] Writing tensor blk.0.ffn_norm.weight                  | size   4096           | type F32  | T+   5
  27. INFO:convert:[  7/291] Writing tensor blk.0.attn_k.weight                    | size   1024 x   4096  | type F16  | T+   5
  28. INFO:convert:[  8/291] Writing tensor blk.0.attn_output.weight               | size   4096 x   4096  | type F16  | T+   5
  29. INFO:convert:[  9/291] Writing tensor blk.0.attn_q.weight                    | size   4096 x   4096  | type F16  | T+   5
  30. INFO:convert:[ 10/291] Writing tensor blk.0.attn_v.weight                    | size   1024 x   4096  | type F16  | T+   5
  31. INFO:convert:[ 11/291] Writing tensor blk.1.attn_norm.weight                 | size   4096           | type F32  | T+   5
  32. INFO:convert:[ 12/291] Writing tensor blk.1.ffn_down.weight                  | size   4096 x  14336  | type F16  | T+   5
  33. INFO:convert:[ 13/291] Writing tensor blk.1.ffn_gate.weight                  | size  14336 x   4096  | type F16  | T+   5
复制代码
  1. root@master:~/work/llama.cpp# ll models -h
  2. -rw-r--r--  1 root root  15G May 17 07:47 Llama3-FP16.gguf
  3. -rw-r--r--  1 root root  15G May 17 08:02 Llama3-FP16.bin
复制代码
模型量化

模型量化利用quantize命令,其具体可用参数与答应量化的范例如下:
  1. root@master:~/work/llama.cpp# ./quantize
  2. usage: ./quantize [--help] [--allow-requantize] [--leave-output-tensor] [--pure] [--imatrix] [--include-weights] [--exclude-weights] [--output-tensor-type] [--token-embedding-type] [--override-kv] model-f32.gguf [model-quant.gguf] type [nthreads]
  3.   --allow-requantize: Allows requantizing tensors that have already been quantized. Warning: This can severely reduce quality compared to quantizing from 16bit or 32bit
  4.   --leave-output-tensor: Will leave output.weight un(re)quantized. Increases model size but may also increase quality, especially when requantizing
  5.   --pure: Disable k-quant mixtures and quantize all tensors to the same type
  6.   --imatrix file_name: use data in file_name as importance matrix for quant optimizations
  7.   --include-weights tensor_name: use importance matrix for this/these tensor(s)
  8.   --exclude-weights tensor_name: use importance matrix for this/these tensor(s)
  9.   --output-tensor-type ggml_type: use this ggml_type for the output.weight tensor
  10.   --token-embedding-type ggml_type: use this ggml_type for the token embeddings tensor
  11.   --keep-split: will generate quatized model in the same shards as input  --override-kv KEY=TYPE:VALUE
  12.       Advanced option to override model metadata by key in the quantized model. May be specified multiple times.
  13. Note: --include-weights and --exclude-weights cannot be used together
  14. Allowed quantization types:
  15.    2  or  Q4_0    :  3.56G, +0.2166 ppl @ LLaMA-v1-7B
  16.    3  or  Q4_1    :  3.90G, +0.1585 ppl @ LLaMA-v1-7B
  17.    8  or  Q5_0    :  4.33G, +0.0683 ppl @ LLaMA-v1-7B
  18.    9  or  Q5_1    :  4.70G, +0.0349 ppl @ LLaMA-v1-7B
  19.   19  or  IQ2_XXS :  2.06 bpw quantization
  20.   20  or  IQ2_XS  :  2.31 bpw quantization
  21.   28  or  IQ2_S   :  2.5  bpw quantization
  22.   29  or  IQ2_M   :  2.7  bpw quantization
  23.   24  or  IQ1_S   :  1.56 bpw quantization
  24.   31  or  IQ1_M   :  1.75 bpw quantization
  25.   10  or  Q2_K    :  2.63G, +0.6717 ppl @ LLaMA-v1-7B
  26.   21  or  Q2_K_S  :  2.16G, +9.0634 ppl @ LLaMA-v1-7B
  27.   23  or  IQ3_XXS :  3.06 bpw quantization
  28.   26  or  IQ3_S   :  3.44 bpw quantization
  29.   27  or  IQ3_M   :  3.66 bpw quantization mix
  30.   12  or  Q3_K    : alias for Q3_K_M
  31.   22  or  IQ3_XS  :  3.3 bpw quantization
  32.   11  or  Q3_K_S  :  2.75G, +0.5551 ppl @ LLaMA-v1-7B
  33.   12  or  Q3_K_M  :  3.07G, +0.2496 ppl @ LLaMA-v1-7B
  34.   13  or  Q3_K_L  :  3.35G, +0.1764 ppl @ LLaMA-v1-7B
  35.   25  or  IQ4_NL  :  4.50 bpw non-linear quantization
  36.   30  or  IQ4_XS  :  4.25 bpw non-linear quantization
  37.   15  or  Q4_K    : alias for Q4_K_M
  38.   14  or  Q4_K_S  :  3.59G, +0.0992 ppl @ LLaMA-v1-7B
  39.   15  or  Q4_K_M  :  3.80G, +0.0532 ppl @ LLaMA-v1-7B
  40.   17  or  Q5_K    : alias for Q5_K_M
  41.   16  or  Q5_K_S  :  4.33G, +0.0400 ppl @ LLaMA-v1-7B
  42.   17  or  Q5_K_M  :  4.45G, +0.0122 ppl @ LLaMA-v1-7B
  43.   18  or  Q6_K    :  5.15G, +0.0008 ppl @ LLaMA-v1-7B
  44.    7  or  Q8_0    :  6.70G, +0.0004 ppl @ LLaMA-v1-7B
  45.    1  or  F16     : 14.00G, -0.0020 ppl @ Mistral-7B
  46.   32  or  BF16    : 14.00G, -0.0050 ppl @ Mistral-7B
  47.    0  or  F32     : 26.00G              @ 7B
  48.           COPY    : only copy tensors, no quantizing
复制代码
  利用quantize量化模型,它提供各种量化位数的模型:Q2、Q3、Q4、Q5、Q6、Q8、F16。
    量化模型的定名方法遵循: Q + 量化比特位 + 变种。量化位数越少,对硬件资源的要求越低,但是模型的精度也越低。
  模型经过量化之后,可以发现模型的大小从15G降低到8G,但模型精度从16位浮点数降低到8位整数。
  1. root@master:~/work/llama.cpp# ./quantize ./models/Llama3-FP16.gguf  ./models/Llama3-q8.gguf q8_0
  2. main: build = 2908 (359cbe3f)
  3. main: built with cc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 for x86_64-linux-gnu
  4. main: quantizing '/root/work/models/Llama3-FP16.gguf' to '/root/work/models/Llama3-q8.gguf' as Q8_0
  5. llama_model_loader: loaded meta data with 21 key-value pairs and 291 tensors from /root/work/models/Llama3-FP16.gguf (version GGUF V3 (latest))
  6. llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output.
  7. llama_model_loader: - kv   0:                       general.architecture str              = llama
  8. llama_model_loader: - kv   1:                               general.name str              = Llama3-Chinese-8B-Instruct
  9. llama_model_loader: - kv   2:                           llama.vocab_size u32              = 128256
  10. llama_model_loader: - kv   3:                       llama.context_length u32              = 8192
  11. llama_model_loader: - kv   4:                     llama.embedding_length u32              = 4096
  12. llama_model_loader: - kv   5:                          llama.block_count u32              = 32
  13. llama_model_loader: - kv   6:                  llama.feed_forward_length u32              = 14336
  14. llama_model_loader: - kv   7:                 llama.rope.dimension_count u32              = 128
  15. llama_model_loader: - kv   8:                 llama.attention.head_count u32              = 32
  16. llama_model_loader: - kv   9:              llama.attention.head_count_kv u32              = 8
  17. llama_model_loader: - kv  10:     llama.attention.layer_norm_rms_epsilon f32              = 0.000010
  18. llama_model_loader: - kv  11:                       llama.rope.freq_base f32              = 500000.000000
  19. llama_model_loader: - kv  12:                          general.file_type u32              = 1
  20. llama_model_loader: - kv  13:                       tokenizer.ggml.model str              = gpt2
  21. llama_model_loader: - kv  14:                      tokenizer.ggml.tokens arr[str,128256]  = ["!", """, "#", "$", "%", "&", "'", ...
  22. llama_model_loader: - kv  15:                      tokenizer.ggml.scores arr[f32,128256]  = [0.000000, 0.000000, 0.000000, 0.0000...
  23. llama_model_loader: - kv  16:                  tokenizer.ggml.token_type arr[i32,128256]  = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...
  24. llama_model_loader: - kv  17:                      tokenizer.ggml.merges arr[str,280147]  = ["Ġ Ġ", "Ġ ĠĠĠ", "ĠĠ ĠĠ", "...
  25. llama_model_loader: - kv  18:                tokenizer.ggml.bos_token_id u32              = 128000
  26. llama_model_loader: - kv  19:                tokenizer.ggml.eos_token_id u32              = 128001
  27. llama_model_loader: - kv  20:                    tokenizer.chat_template str              = {% set loop_messages = messages %}{% ...
  28. llama_model_loader: - type  f32:   65 tensors
  29. llama_model_loader: - type  f16:  226 tensors
  30. [   1/ 291]                    token_embd.weight - [ 4096, 128256,     1,     1], type =    f16, converting to q8_0 .. size =  1002.00 MiB ->   532.31 MiB
  31. [   2/ 291]               blk.0.attn_norm.weight - [ 4096,     1,     1,     1], type =    f32, size =    0.016 MB
  32. [   3/ 291]                blk.0.ffn_down.weight - [14336,  4096,     1,     1], type =    f16, converting to q8_0 .. size =   112.00 MiB ->    59.50 MiB
  33. [   4/ 291]                blk.0.ffn_gate.weight - [ 4096, 14336,     1,     1], type =    f16, converting to q8_0 .. size =   112.00 MiB ->    59.50 MiB
  34. [   5/ 291]                  blk.0.ffn_up.weight - [ 4096, 14336,     1,     1], type =    f16, converting to q8_0 .. size =   112.00 MiB ->    59.50 MiB
  35. [   6/ 291]                blk.0.ffn_norm.weight - [ 4096,     1,     1,     1], type =    f32, size =    0.016 MB
  36. [   7/ 291]                  blk.0.attn_k.weight - [ 4096,  1024,     1,     1], type =    f16, converting to q8_0 .. size =     8.00 MiB ->     4.25 MiB
  37. [   8/ 291]             blk.0.attn_output.weight - [ 4096,  4096,     1,     1], type =    f16, converting to q8_0 .. size =    32.00 MiB ->    17.00 MiB
  38. [   9/ 291]                  blk.0.attn_q.weight - [ 4096,  4096,     1,     1], type =    f16, converting to q8_0 .. size =    32.00 MiB ->    17.00 MiB
  39. [  10/ 291]                  blk.0.attn_v.weight - [ 4096,  1024,     1,     1], type =    f16, converting to q8_0 .. size =     8.00 MiB ->     4.25 MiB
  40. [  11/ 291]               blk.1.attn_norm.weight - [ 4096,     1,     1,     1], type =    f32, size =    0.016 MB
  41. [  12/ 291]                blk.1.ffn_down.weight - [14336,  4096,     1,     1], type =    f16, converting to q8_0 .. size =   112.00 MiB ->    59.50 MiB
  42. [  13/ 291]                blk.1.ffn_gate.weight - [ 4096, 14336,     1,     1], type =    f16, converting to q8_0 .. size =   112.00 MiB ->    59.50 MiB
  43. [  14/ 291]                  blk.1.ffn_up.weight - [ 4096, 14336,     1,     1], type =    f16, converting to q8_0 .. size =   112.00 MiB ->    59.50 MiB
  44. [  15/ 291]                blk.1.ffn_norm.weight - [ 4096,     1,     1,     1], type =    f32, size =    0.016 MB
  45. [  16/ 291]                  blk.1.attn_k.weight - [ 4096,  1024,     1,     1], type =    f16, converting to q8_0 .. size =     8.00 MiB ->     4.25 MiB
  46. [  17/ 291]             blk.1.attn_output.weight - [ 4096,  4096,     1,     1], type =    f16, converting to q8_0 .. size =    32.00 MiB ->    17.00 MiB
  47. [  18/ 291]                  blk.1.attn_q.weight - [ 4096,  4096,     1,     1], type =    f16, converting to q8_0 .. size =    32.00 MiB ->    17.00 MiB
  48. [  19/ 291]                  blk.1.attn_v.weight - [ 4096,  1024,     1,     1], type =    f16, converting to q8_0 .. size =     8.00 MiB ->     4.25 MiB
复制代码
  1. root@master:~/work/llama.cpp# ll -h models/
  2. -rw-r--r--  1 root root 8.0G May 17 07:54 Llama3-q8.gguf
复制代码
模型加载与推理

模型加载与推理利用main命令,其支持如下可用参数:
  1. root@master:~/work/llama.cpp# ./main -h
  2. usage: ./main [options]
  3. options:
  4.   -h, --help            show this help message and exit
  5.   --version             show version and build info
  6.   -i, --interactive     run in interactive mode
  7.   --interactive-specials allow special tokens in user text, in interactive mode
  8.   --interactive-first   run in interactive mode and wait for input right away
  9.   -cnv, --conversation  run in conversation mode (does not print special tokens and suffix/prefix)
  10.   -ins, --instruct      run in instruction mode (use with Alpaca models)
  11.   -cml, --chatml        run in chatml mode (use with ChatML-compatible models)
  12.   --multiline-input     allows you to write or paste multiple lines without ending each in '\'
  13.   -r PROMPT, --reverse-prompt PROMPT
  14.                         halt generation at PROMPT, return control in interactive mode
  15.                         (can be specified more than once for multiple prompts).
  16.   --color               colorise output to distinguish prompt and user input from generations
  17.   -s SEED, --seed SEED  RNG seed (default: -1, use random seed for < 0)
  18.   -t N, --threads N     number of threads to use during generation (default: 30)
  19.   -tb N, --threads-batch N
  20.                         number of threads to use during batch and prompt processing (default: same as --threads)
  21.   -td N, --threads-draft N                        number of threads to use during generation (default: same as --threads)
  22.   -tbd N, --threads-batch-draft N
  23.                         number of threads to use during batch and prompt processing (default: same as --threads-draft)
  24.   -p PROMPT, --prompt PROMPT
  25.                         prompt to start generation with (default: empty)
复制代码
  可以加载预练习模型大概经过量化之后的模型,这里选择加载量化后的模型举行推理。
  在llama.cpp项目标根目次,执行如下命令,加载模型举行推理。
  1. root@master:~/work/llama.cpp# ./main -m models/Llama3-q8.gguf --color -f prompts/alpaca.txt -ins -c 2048 --temp 0.2 -n 256 --repeat_penalty 1.1
  2. Log start
  3. main: build = 2908 (359cbe3f)
  4. main: built with cc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 for x86_64-linux-gnu
  5. main: seed  = 1715935175
  6. llama_model_loader: loaded meta data with 22 key-value pairs and 291 tensors from models/Llama3-q8.gguf (version GGUF V3 (latest))
  7. llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output.
  8. llama_model_loader: - kv   0:                       general.architecture str              = llama
  9. llama_model_loader: - kv   1:                               general.name str              = Llama3-Chinese-8B-Instruct
  10. llama_model_loader: - kv   2:                           llama.vocab_size u32              = 128256
  11. llama_model_loader: - kv   3:                       llama.context_length u32              = 8192
  12. llama_model_loader: - kv   4:                     llama.embedding_length u32              = 4096
  13. llama_model_loader: - kv   5:                          llama.block_count u32              = 32
  14. llama_model_loader: - kv   6:                  llama.feed_forward_length u32              = 14336
  15. llama_model_loader: - kv   7:                 llama.rope.dimension_count u32              = 128
  16. == Running in interactive mode. ==
  17. - Press Ctrl+C to interject at any time.
  18. - Press Return to return control to LLaMa.
  19. - To return control without starting a new line, end your input with '/'.
  20. - If you want to submit another line, end your input with '\'.
  21. <|begin_of_text|>Below is an instruction that describes a task. Write a response that appropriately completes the request.
  22. > hi
  23. Hello! How can I help you today?<|eot_id|>
  24. >
复制代码
在提示符>之后输入prompt,利用ctrl+c中断输出,多行信息以\作为行尾。执行./main -h命令查看帮助和参数说明,以下是一些常用的参数: `
命令形貌-m指定 LLaMA 模型文件的路径-mu指定远程 http url 来下载文件-i以交互模式运行步伐,答应直接提供输入并接收实时响应。-ins以指令模式运行步伐,这在处置惩罚羊驼模型时特殊有用。-f指定prompt模板,alpaca模型请加载prompts/alpaca.txt-n控制回复生成的最大长度(默认:128)-c设置提示上下文的大小,值越大越能参考更长的对话汗青(默认:512)-b控制batch size(默认:8),可得当增加-t控制线程数量(默认:4),可得当增加--repeat_penalty控制生成回复中对重复文本的惩罚力度--temp温度系数,值越低回复的随机性越小,反之越大--top_p, top_k控制解码采样的相干参数--color区分用户输入和生成的文本 模型API服务

llama.cpp提供了完全与OpenAI API兼容的API接口,利用经过编译生成的server可执行文件启动API服务。
  1. root@master:~/work/llama.cpp# ./server -m models/Llama3-q8.gguf --host 0.0.0.0 --port 8000
  2. {"tid":"140018656950080","timestamp":1715936504,"level":"INFO","function":"main","line":2942,"msg":"build info","build":2908,"commit":"359cbe3f"}
  3. {"tid":"140018656950080","timestamp":1715936504,"level":"INFO","function":"main","line":2947,"msg":"system info","n_threads":30,"n_threads_batch":-1,"total_threads":30,"system_info":"AVX = 1 | AVX_VNNI = 0 | AVX2 = 1 | AVX512 = 1 | AVX512_VBMI = 0 | AVX512_VNNI = 0 | FMA = 1 | NEON = 0 | ARM_FMA = 0 | F16C = 1 | FP16_VA = 0 | WASM_SIMD = 0 | BLAS = 0 | SSE3 = 1 | SSSE3 = 1 | VSX = 0 | MATMUL_INT8 = 0 | LLAMAFILE = 1 | "}
  4. llama_model_loader: loaded meta data with 22 key-value pairs and 291 tensors from models/Llama3-q8.gguf (version GGUF V3 (latest))
  5. llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output.
  6. llama_model_loader: - kv   0:                       general.architecture str              = llama
  7. llama_model_loader: - kv   1:                               general.name str              = Llama3-Chinese-8B-Instruct
  8. llama_model_loader: - kv   2:                           llama.vocab_size u32              = 128256
  9. llama_model_loader: - kv   3:                       llama.context_length u32              = 8192
  10. llama_model_loader: - kv   4:                     llama.embedding_length u32              = 4096
  11. llama_model_loader: - kv   5:                          llama.block_count u32              = 32
  12. llama_model_loader: - kv   6:                  llama.feed_forward_length u32              = 14336
复制代码
启动API服务后,可以利用curl命令举行测试
  1. curl --request POST \
  2.     --url http://localhost:8000/completion \
  3.     --header "Content-Type: application/json" \
  4.     --data '{"prompt": "Hi"}'
复制代码
模型API服务(第三方)

   在llamm.cpp项目中有提到各种语言编写的第三方工具包,可以利用这些工具包提供API服务,这里以Python为例,利用llama-cpp-python提供API服务。
  安装依靠
  1. pip install llama-cpp-python
  2. pip install llama-cpp-python -i https://mirrors.aliyun.com/pypi/simple/
复制代码
注意:可能还需要安装以下缺失依靠,可根据启动时的异常提示分别安装。
  1. pip install sse_starlette starlette_context pydantic_settings
复制代码
启动API服务,默认运行在http://localhost:8000
  1. python -m llama_cpp.server --model models/Llama3-q8.gguf
复制代码
安装openai依靠
  1. pip install openai
复制代码
利用openai调用API服务
  1. import os
  2. from openai import OpenAI  # 导入OpenAI库
  3. # 设置OpenAI的BASE_URL
  4. os.environ["OPENAI_BASE_URL"] = "http://localhost:8000/v1"
  5. client = OpenAI()  # 创建OpenAI客户端对象
  6. # 调用模型
  7. completion = client.chat.completions.create(
  8.     model="llama3", # 任意填
  9.     messages=[
  10.         {"role": "system", "content": "你是一个乐于助人的助手。"},
  11.         {"role": "user", "content": "你好!"}
  12.     ]
  13. )
  14. # 输出模型回复
  15. print(completion.choices[0].message)
复制代码

GPU推理

   如果编译构建了GPU执行环境,可以利用-ngl N或 --n-gpu-layers N参数,指定offload层数,让模型在GPU上运行推理
    例如:-ngl 40表现offload 40层模型参数到GPU
  未利用-ngl N或 --n-gpu-layers N参数,步伐默认在CPU上运行
  1. root@master:~/work/llama.cpp# ./server -m models/Llama3-FP16.gguf  --host 0.0.0.0 --port 8000
复制代码
可从以下关键启动日志看出,模型并没有在GPU上执行
  1. ggml_cuda_init: GGML_CUDA_FORCE_MMQ:   no
  2. ggml_cuda_init: CUDA_USE_TENSOR_CORES: yes
  3. ggml_cuda_init: found 1 CUDA devices:
  4.   Device 0: Tesla V100S-PCIE-32GB, compute capability 7.0, VMM: yes
  5. llm_load_tensors: ggml ctx size =    0.15 MiB
  6. llm_load_tensors: offloading 0 repeating layers to GPU
  7. llm_load_tensors: offloaded 0/33 layers to GPU
  8. llm_load_tensors:        CPU buffer size =  8137.64 MiB
  9. .........................................................................................
  10. llama_new_context_with_model: n_ctx      = 2048
  11. llama_new_context_with_model: n_batch    = 2048
  12. llama_new_context_with_model: n_ubatch   = 512
复制代码
利用-ngl N或 --n-gpu-layers N参数,步伐默认在GPU上运行
  1. root@master:~/work/llama.cpp# ./server -m models/Llama3-FP16.gguf  --host 0.0.0.0 --port 8000
  2.    --n-gpu-layers 1000
复制代码
可从以下关键启动日志看出,模型在GPU上执行
  1. ggml_cuda_init: GGML_CUDA_FORCE_MMQ:   no
  2. ggml_cuda_init: CUDA_USE_TENSOR_CORES: yes
  3. ggml_cuda_init: found 1 CUDA devices:
  4.   Device 0: Tesla V100S-PCIE-32GB, compute capability 7.0, VMM: yes
  5. llm_load_tensors: ggml ctx size =    0.30 MiB
  6. llm_load_tensors: offloading 32 repeating layers to GPU
  7. llm_load_tensors: offloading non-repeating layers to GPU
  8. llm_load_tensors: offloaded 33/33 layers to GPU
  9. llm_load_tensors:        CPU buffer size =  1002.00 MiB
  10. llm_load_tensors:      CUDA0 buffer size = 14315.02 MiB
  11. .........................................................................................
  12. llama_new_context_with_model: n_ctx      = 512
  13. llama_new_context_with_model: n_batch    = 512
  14. llama_new_context_with_model: n_ubatch   = 512
  15. llama_new_context_with_model: flash_attn = 0
复制代码
执行nvidia-smi命令,可以���一步验证模型已在GPU上运行。


如何学习AI大模型?

我在一线互联网企业工作十余年里,指导过不少偕行后辈。帮助很多人得到了学习和发展。
我意识到有很多经验和知识值得分享给大家,也可以通过我们的本事和经验解答大家在人工智能学习中的很多狐疑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将紧张的AI大模型资料包括AI大模型入门学习头脑导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。

第一阶段: 从大模型体系设计入手,讲解大模型的重要方法;
第二阶段: 在通过大模型提示词工程从Prompts角度入手更好发挥模型的作用;
第三阶段: 大模型平台应用开发借助阿里云PAI平台构建电商领域虚拟试衣体系;
第四阶段: 大模型知识库应用开发以LangChain框架为例,构建物流行业咨询智能问答体系;
第五阶段: 大模型微调开发借助以大健康、新零售、新媒体领域构建适合当前领域大模型;
第六阶段: 以SD多模态大模型为主,搭建了文生图小步伐案例;
第七阶段: 以大模型平台应用与开发为主,通过星火大模型,文心大模型等成熟大模型构建大模型行业应用。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

北冰洋以北

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表