
跨平台本地运行LLaMA和LLaVA模型的高效库
LLamaSharp是一个基于llama.cpp的跨平台库,支持在本地设备上高效运行LLaMA和LLaVA等大语言模型。该库提供高级API和RAG支持,便于在应用中部署大型语言模型。LLamaSharp兼容多种后端,支持CPU和GPU推理,适用于Windows、Linux和Mac平台。通过集成semantic-kernel和kernel-memory等库,LLamaSharp简化了应用开发,并提供多个示例和教程帮助用户快速上手。
LLamaSharp 是一个跨平台的库,旨在在本地设备上运行诸如 LLaMA 和 LLaVA 等模型。它基于 llama.cpp 项目,使得在 CPU 和 GPU 上进行推理都能高效进行。通过其高级 API 和 RAG 支持,开发者可以十分方便地在应用程序中部署大型语言模型(LLM)。
LLamaSharp 支持通过多种后端(例如 CPU、CUDA、Metal、Vulkan)在不同操作系统(Windows、Linux、Mac)上运行,无需用户自行编译 C++ 代码。此外,它提供了与 Microsoft 的 semantic-kernel 以及 kernel-memory 的集成,支持诸如检索增强的生成(RAG)、合成记忆和提示工程等高级功能。
LLamaSharp 使用通过 C++ 编译的“后端”与原生库进行高性能交互,以下为安装步骤:
在 NuGet 上安装 LLamaSharp 包:
PM> Install-Package LLamaSharp
选择安装 一个或多个后端包,或使用自编译的后端。
LLamaSharp.Backend.Cpu: 适用于 Windows、Linux 和 Mac 的纯 CPU 后端。Mac 还支持 Metal(GPU)。LLamaSharp.Backend.Cuda11/12: 分别适用于 CUDA 11 和 CUDA 12 的 Windows 和 Linux 后端。LLamaSharp.Backend.Vulkan: 适用于 Windows 和 Linux 的 Vulkan 后端。(可选)为 Microsoft semantic-kernel 安装 LLamaSharp.semantic-kernel 包。
(可选)如需启用 RAG 支持,安装基于 Microsoft kernel-memory 集成的 LLamaSharp.kernel-memory 包。
LLamaSharp 使用 GGUF 格式的模型文件,可以通过以下方式获取:
以下是一个使用 LLamaSharp 进行简单聊天会话的例子:
using LLama.Common; using LLama; // 替换为自己的模型路径 string modelPath = @"<Your Model Path>"; var parameters = new ModelParams(modelPath) { ContextSize = 1024, GpuLayerCount = 5 }; using var model = LLamaWeights.LoadFromFile(parameters); using var context = model.CreateContext(parameters); var executor = new InteractiveExecutor(context); var chatHistory = new ChatHistory(); chatHistory.AddMessage(AuthorRole.System, "这是一个用户与助手对话的记录,助手名叫 Bob。Bob 乐于助人,友好诚实,能迅速和精确地回应用户请求。"); chatHistory.AddMessage(AuthorRole.User, "你好,Bob。"); chatHistory.AddMessage(AuthorRole.Assistant, "你好,我能为您做些什么呢?"); ChatSession session = new(executor, chatHistory); InferenceParams inferenceParams = new InferenceParams() { MaxTokens = 256, AntiPrompts = new List<string> { "User:" } }; Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("聊天会话已开始.\n用户: "); Console.ForegroundColor = ConsoleColor.Green; string userInput = Console.ReadLine() ?? ""; while (userInput != "exit") { await foreach (var text in session.ChatAsync(new ChatHistory.Message(AuthorRole.User, userInput), inferenceParams)) { Console.ForegroundColor = ConsoleColor.White; Console.Write(text); } Console.ForegroundColor = ConsoleColor.Green; userInput = Console.ReadLine() ?? ""; }
请确保安装的 CUDA 后端包版本与系统安装的 CUDA 版本匹配,并检查是否在代码开头添加日志代码以查看加载的原生库文件。
较大的 LLM 模型需要更多时间来生成输出。可以尝试增加 GpuLayerCount,如果性能仍不如预期,请参考 llama.cpp 上的同一模型设置进行对比。
LLamaSharp 欢迎所有的贡献,开发者可以从 TODO 列表中选择任务开始,并通过提交特性请求、撰写博客或协作开发 Web API 和 UI 集成来帮助项目成长。
开发者可以加入项目的 Discord 或 QQ 群,与其他成员交流、共享经验。
通过 LLamaSharp,开发者可以在本地轻松运行和集成大型语言模型,并利用其强大的后端支持和丰富的功能来构建高效的 AI 应用。