使用 .NET Core 的本地 DeepSeek-R1

发布于:2025-03-21 ⋅ 阅读:(35) ⋅ 点赞:(0)

使用 .NET 在我的 MacBook Pro 上与当地 LLM 聊天的历程。 

        如今,只需使用浏览器即可轻松使用 ChatGPT 或其他 genAI。作为开发人员,我们可以通过直接集成 OpenAI API 等来做更复杂的事情。如果我们想在自己的机器上运行 LLM,只是为了找人聊天或开发一些有趣的东西,该怎么办? 

        DeepSeek最近发布的模型在软件和技术行业引起了轰动。得益于蒸馏技术,更小、资源更便宜的模型现在可以在特定任务上发挥同样强大的作用。无论是在 genAI 还是 ML 世界中,Python 都是占主导地位的堆栈。虽然我个人很了解 Python,但作为#EverythingInCSharp系列的传统。在这篇文章中,我记录了如何deepseek-ai/DeekSeek-R1-Distill-Llama-8B在 C# 程序中运行模型。

1、先决条件

Python 3 +
.NET8+
支持 lfs 的Git

        由于 .NET 无法直接以格式使用 Hugging Face 模型.safetensors,因此您需要将.safetensors格式转换为(GPT 生成的统一格式)或下载其他人.gguf转换并上传到Hugging Face 的格式(例如这个)。如果您不想自己转换,请跳到第 5 点。

2.下载模型

使用以下 git 命令克隆模型存储库,请注意模型文件有 15GB 大:

git clone https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-8B

3. 克隆 Llama.cpp 仓库

您将需要里面的转换脚本将 HuggingFace 格式转换为 GGUF 格式。

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

4.转换模型

在成功运行转换脚本之前,我必须:

4.1 设置虚拟环境

cd llama.cpp
python3 -m venv .
source bin/activate

4.2 安装以下软件包

python3 -m pip install numpy torch sentencepiece gguf safetensors transformers

python3 convert_hf_to_gguf.py  --outfile your_filename.gguf ../DeepSeek-R1-Distill-Llama-8B

完成后您将看到以下内容:

5.创建一个新的C#控制台程序

dotnet new console

6.安装所需的软件包

由于该模型是基于骆驼的,我们需要LlamaSharp

dotnet add package LLamaSharp

我正在使用 Macbook Pro,因此我也需要安装一个特定的backends:

dotnet add package LLamaSharp.Backend.Cpu

如果您不使用 Mac,请参阅此处backends提供的官方列表。

7.创建聊天会话的代码

我将从自述文件中复制示例代码LlamaSharp来复制最小的聊天会话设置:

using LLama;
using LLama.Common;
using LLama.Sampling;

string modelPath = @"DeepSeek-R1-Distill-Llama-8B.gguf"; // change it to your own model path.

var parameters = new ModelParams(modelPath)
{
    ContextSize = 1024, // The longest length of chat as memory.
    GpuLayerCount = 5 // How many layers to offload to GPU. Please adjust it according to your GPU memory.
};
using var model = LLamaWeights.LoadFromFile(parameters);
using var context = model.CreateContext(parameters);
var executor = new InteractiveExecutor(context);

// Add chat histories as prompt to tell AI how to act.
var chatHistory = new ChatHistory();
chatHistory.AddMessage(AuthorRole.System, "Transcript of a dialog, where the User interacts with an Assistant named Bob. Bob is helpful, kind, honest, good at writing, and never fails to answer the User's requests immediately and with precision.");
chatHistory.AddMessage(AuthorRole.User, "Hello, Bob.");
chatHistory.AddMessage(AuthorRole.Assistant, "Hello. How may I help you today?");

ChatSession session = new(executor, chatHistory);

InferenceParams inferenceParams = new InferenceParams()
{
    MaxTokens = 256, // No more than 256 tokens should appear in answer. Remove it if antiprompt is enough for control.
    AntiPrompts = new List<string> { "User:" }, // Stop generation once antiprompts appear.

    SamplingPipeline = new DefaultSamplingPipeline(),
};

Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("The chat session has started.\nUser: ");
Console.ForegroundColor = ConsoleColor.Green;
string userInput = Console.ReadLine() ?? "";

while (userInput != "exit")
{
    await foreach ( // Generate the response streamingly.
        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() ?? "";
}

8.运行并尝试

dotnet run

在 M3 Pro 12 核 CPU 的 Macbook 上,token 生成占用了 45% 的 CPU 时间,同时占用了大约 16GB 的内存。内存使用量与模型本身的大小基本相同。 

生成令牌时的 CPU 使用率

生成 token 时的内存使用情况

不生成 token 时的内存使用情况

尽情享受吧!🎉迫不及待地去看看你的 C# 代码能用你本地的 LLM 做什么! 

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。


网站公告

今日签到

点亮在社区的每一天
去签到