• 在Windows或Mac上安装并运行LLAMA2


    llama.cpp 的主要目标是在本地和云端的各种硬件上以最少的设置和最先进的性能实现 LLM 推理。没有任何依赖的纯 C/C++ 实现(Plain C/C++ implementation without any dependencies)

    Llama.cpp在不同系统上运行的结果

    LLAMA.cpp 在windows 上运行的结果

    LLAMA.cpp 在Mac上运行的结果

    安装llama.cpp的不同方法

    方法一:

     编译 llama.cpp

    克隆 llama.cpp

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

    编译llama.cpp

    on mac

    LLAMA_METAL=1 make

    on windows , 用powershell 运行

    make

    如果不行,就要下载最新的fortran版本 w64devkit.

    然后解压,运行w64devkit.exe后再运行make命令

    下载llama2模型

    直接在huggingface里下载量化了的 gguf格式的llama2模型。

    https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGUF/tree/main

    我下载的是llama-2-7b-chat.Q4_0.gguf

    拷贝llama-2-7b-chat.Q4_0.gguf 到llama.cpp目录里的models目录里

    运行模型

    如果是windows,要用powershell

    ./main -m ./models/llama-2-7b-chat.Q4_0.gguf --color --ctx_size 2048 -n -1 -ins -b 256 --top_k 10000 --temp 0.2 --repeat_penalty 1.1 -t 8

    用Python code 运行。

    1. 配置下面系统变量

    $env:CMAKE_GENERATOR = "MinGW Makefiles"
    $env:CMAKE_ARGS = "-DCMAKE_C_COMPILER=C:/apps/w64devkit/bin/gcc.exe -DCMAKE_CXX_COMPILER=C:/apps/w64devkit/bin/g++.exe"

    2. 安装 llama-cpp-python

    3. 运行下面代码

    1. from llama_cpp import Llama
    2. # Instanciate the nous-hermes model
    3. my_gguf_llama_model = Llama(model_path="./llama2-7b-nous-hermes-8-bit.gguf")
    4. prompt = "Write a java code that prints hello"
    5. max_tokens = 100
    6. temperature = 0
    7. echo = False
    8. stop = ["Q", "\n"]
    9. # Define the inference parameters and run the model...in cpu
    10. model_output = my_gguf_llama_model(
    11. prompt,
    12. max_tokens=max_tokens,
    13. temperature=temperature,
    14. echo=echo,
    15. stop=stop,
    16. )
    17. final_result = model_output["choices"][0]["text"]

    方法二:

    Meta已将llama2开源,任何人都可以通过在meta ai上申请并接受许可证、提供电子邮件地址来获取模型。 Meta 将在电子邮件中发送下载链接。

    下载llama2 

    • 获取download.sh文件,将其存储在mac上
    • 打开mac终端,执行 chmod +x ./download.sh 赋予权限。
    • 运行 ./download.sh 开始下载过程
    • 复制电子邮件中的下载链接,粘贴到终端
    • 仅下载13B-chat

    安装系统依赖的东西


    必须安装 Xcode 才能编译 C++ 项目。 如果您没有,请执行以下操作:

    xcode-select --install

    接下来,安装用于构建 C++ 项目的依赖项。

    brew install pkgconfig cmake
    

    最后,我们安装 Torch。

    如果您没有安装python3,请通过以下方式安装

    brew install python@3.11

    像这样创建一个虚拟环境:

    /opt/homebrew/bin/python3.11 -m venv venv

    激活 venv。

    source venv/bin/activate

    安装 PyTorch:

    pip install --pre torch torchvision --extra-index-url https://download.pytorch.org/whl/nightly/cpu

    编译 llama.cpp

    克隆 llama.cpp

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

    安装python依赖包

    pip3 install -r requirements.txt

    编译

    LLAMA_METAL=1 make

    如果你有两个arch (x86_64, arm64), 可以用下面指定arm64

    arch -arm64 make

    将下载的 13B 移至 models 文件夹下的 llama.cpp 项目。

    将模型转换为ggml格式
    13B和70B是不一样的。 Convert-pth-to-ggml.py 已弃用,请使用 Convert.py 代替

    13B-chat

     python3 convert.py --outfile ./models/llama-2-13b-chat/ggml-model-f16.bin --outtype f16 ./models/llama-2-13b-chat

    Quantize 模型:

    In order to run these huge LLMs in our small laptops we will need to reconstruct and quantize the model with the following commands, here we will convert the model’s weights from float16 to int4 requiring less memory to be executed and only losing a little bit of quality in the process.

    13B-chat:

    ./quantize ./models/llama-2-13b-chat/ggml-model-f16.bin ./models/llama-2-13b-chat/ggml-model-q4_0.bin q4_0

    运行模型

    ./main -m ./models/llama-2-13b-chat/ggml-model-q4_0.bin -t 4 -c 2048 -n 2048 --color -i -r '### Question:' -p '### Question:'

    您可以使用 -ngl 1 命令行参数启用 GPU 推理。 任何大于 0 的值都会将计算负载转移到 GPU。 例如:

    ./main -m ./models/llama-2-13b-chat/ggml-model-q4_0.bin -t 4 -c 2048 -n 2048 --color -i -ngl 1 -r '### Question:' -p '### Question:'

    在我的 Mac 上测试时,它比纯 cpu 快大约 25%。

    用Web server 的方式运行Llama.cpp

    在powershell 上运行下面命令

    ./server -m ./models/llama-2-7b-chat.Q4_0.gguf

    其它参数

    1. options:
    2. -h, --help show this help message and exit
    3. -v, --verbose verbose output (default: disabled)
    4. -t N, --threads N number of threads to use during computation (default: 4)
    5. -tb N, --threads-batch N number of threads to use during batch and prompt processing (default: same as --threads)
    6. -c N, --ctx-size N size of the prompt context (default: 512)
    7. --rope-scaling {none,linear,yarn}
    8. RoPE frequency scaling method, defaults to linear unless specified by the model
    9. --rope-freq-base N RoPE base frequency (default: loaded from model)
    10. --rope-freq-scale N RoPE frequency scaling factor, expands context by a factor of 1/N
    11. --yarn-ext-factor N YaRN: extrapolation mix factor (default: 1.0, 0.0 = full interpolation)
    12. --yarn-attn-factor N YaRN: scale sqrt(t) or attention magnitude (default: 1.0)
    13. --yarn-beta-slow N YaRN: high correction dim or alpha (default: 1.0)
    14. --yarn-beta-fast N YaRN: low correction dim or beta (default: 32.0)
    15. -b N, --batch-size N batch size for prompt processing (default: 512)
    16. --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)
    17. not recommended: doubles context memory required and no measurable increase in quality
    18. --mlock force system to keep model in RAM rather than swapping or compressing
    19. --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)
    20. --numa attempt optimizations that help on some NUMA systems
    21. -ngl N, --n-gpu-layers N
    22. number of layers to store in VRAM
    23. -ts SPLIT --tensor-split SPLIT
    24. how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1
    25. -mg i, --main-gpu i the GPU to use for scratch and small tensors
    26. -nommq, --no-mul-mat-q
    27. use cuBLAS instead of custom mul_mat_q CUDA kernels.
    28. Not recommended since this is both slower and uses more VRAM.
    29. -m FNAME, --model FNAME
    30. model path (default: models/7B/ggml-model-f16.gguf)
    31. -a ALIAS, --alias ALIAS
    32. set an alias for the model, will be added as `model` field in completion response
    33. --lora FNAME apply LoRA adapter (implies --no-mmap)
    34. --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter
    35. --host ip address to listen (default (default: 127.0.0.1)
    36. --port PORT port to listen (default (default: 8080)
    37. --path PUBLIC_PATH path from which to serve static files (default examples/server/public)
    38. -to N, --timeout N server read/write timeout in seconds (default: 600)
    39. --embedding enable embedding vector output (default: disabled)
    40. -np N, --parallel N number of slots for process requests (default: 1)
    41. -cb, --cont-batching enable continuous batching (a.k.a dynamic batching) (default: disabled)
    42. -spf FNAME, --system-prompt-file FNAME
    43. Set a file to load a system prompt (initial prompt of all slots), this is useful for chat applications.
    44. --mmproj MMPROJ_FILE path to a multimodal projector file for LLaVA.

    访问

    http://127.0.0.1:8080/

    你也可以用Python代码用post url 访问

    1. import requests
    2. from file_reader import *
    3. from nltk_test.punkt_test import *
    4. def chat(prompt, history):
    5. resp = requests.post(
    6. url = "http://localhost:8080/completion",
    7. json={"prompt":prompt , "history": history},
    8. # data = '{"prompt": "Building a website can be done in 10 simple steps:","n_predict": 128}',
    9. headers={"Content-Type": "application/json;charset=utf-8"}
    10. )
    11. print(resp.json())
    12. return resp.json()["content"]
    13. if __name__ == '__main__':
    14. prompt = "hi"
    15. chat(prompt, [])

    运行huggingface版本的llama2

    下载

    https://huggingface.co/meta-llama/Llama-2-7b-chat-hf/tree/main

    下载这个下面的所有文件,safetensors 和pytorch这个两个任意选一个。一般是safetensors的模型。下载后放在同一个目录,我的目录的是C:\apps\ml_model\llama2-7b-chat-hf。

    用python代码运行

    1. from transformers import AutoTokenizer, AutoModelForCausalLM
    2. import transformers
    3. import torch
    4. model = r"C:\apps\ml_model\llama2-7b-chat-hf"
    5. def get_completion(prompt = "hello" ):
    6. tokenizer = AutoTokenizer.from_pretrained(model)
    7. pipeline = transformers.pipeline(
    8. "text-generation",
    9. model=model,
    10. torch_dtype=torch.float16,
    11. device_map="auto",
    12. # device_map="cuda"
    13. )
    14. sequences = pipeline(
    15. prompt,
    16. do_sample=True,
    17. top_k=10,
    18. num_return_sequences=1,
    19. eos_token_id=tokenizer.eos_token_id,
    20. max_length=4096,
    21. return_full_text=False,
    22. # top_p=0.5, # default=0.9
    23. # temperature=0.6 # default=0
    24. )
    25. for index, seq in enumerate(sequences):
    26. print(index,f"Result: {seq['generated_text']}")
    27. if __name__ == '__main__':
    28. prompt = "hello"
    29. completion = get_completion(prompt)

    其它

    ggml格式的llama2

     通过conda 创建或者venv. 下面是通过conda 创建的。

    1. conda create --name llama_test python=3.9
    2. conda activate llama_test

    安装python依赖的包

    pip3 install -r requirements.txt

    如果你下载的是ggml格式的, 要运行下面命令转换格式

    python convert-llama-ggml-to-gguf.py --eps 1e-5 -i ./models/llama-2-13b-chat.ggmlv3.q4_0.bin -o ./models/llama-2-13b-chat.ggmlv3.q4_0.gguf.bin
    1. (llama) C:\Users\Harry\PycharmProjects\llama.cpp>python convert-llama-ggml-to-gguf.py --eps 1e-5 -i ./models/llama-2-13b-chat.ggmlv3.q4_0.bin -o ./models/llama-2-13b-chat.ggmlv3.q4_0.gguf.bin
    2. * Using config: Namespace(input=WindowsPath('models/llama-2-13b-chat.ggmlv3.q4_0.bin'), output=WindowsPath('models/llama-2-13b-chat.ggmlv3.q4_0.gguf.bin'), name=None, desc=None, gqa=1, eps='1e-5', context_length=2048, model_metadata_dir=None, vocab_dir=None, vocabtype='spm')
    3. === WARNING === Be aware that this conversion script is best-effort. Use a native GGUF model if possible. === WARNING ===
    4. - Note: If converting LLaMA2, specifying "--eps 1e-5" is required. 70B models also need "--gqa 8".
    5. * Scanning GGML input file
    6. * File format: GGJTv3 with ftype MOSTLY_Q4_0
    7. * GGML model hyperparameters:
    8. === WARNING === Special tokens may not be converted correctly. Use --model-metadata-dir if possible === WARNING ===
    9. * Preparing to save GGUF file
    10. This gguf file is for Little Endian only
    11. * Adding model parameters and KV items
    12. * Adding 32000 vocab item(s)
    13. * Adding 363 tensor(s)
    14. gguf: write header
    15. gguf: write metadata
    16. gguf: write tensors
    17. * Successful completion. Output saved to: models\llama-2-13b-chat.ggmlv3.q4_0.gguf.bin

    参考资料

    GitHub - facebookresearch/llama: Inference code for LLaMA models

    A comprehensive guide to running Llama 2 locally – Replicate

  • 相关阅读:
    D-Wave 推出快速退火功能,扩大量子计算性能增益
    Python调试指南
    c语言tips-结构体
    2024年,提升Windows开发和使用体验实践 - 终端&命令行篇
    ROS2 与 Gazebo 联合仿真项目模版
    Kotlin 特殊字符处理
    10.3 单源负权D’Esopo-Pape
    【STM32】认识库函数引脚GPIO开启时钟,需要初始化的结构体GPIOMode_TypeDef
    西瓜视频基于 Hertz 的微服务落地实践
    汽车空调器前缸盖数控加工工艺的制订及夹具设计
  • 原文地址:https://blog.csdn.net/keeppractice/article/details/134216056