使用 .NET Core 的本地 DeepSeek-R1

使用 .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 做什么!

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

相关推荐
用户2986985301419 分钟前
C#:三行代码,给 Word 文档的文本框“一键清空”
后端·c#·.net
唐青枫6 小时前
C#.NET Expression Tree 深入解析:表达式树、动态查询与运行时代码生成
c#·.net
程序设计实验室1 天前
C# 扩展方法只会写 this 吗?C# 14 新语法直接把扩展方法玩出了花
c#
唐青枫1 天前
C#.NET SignalR 深入解析:实时通信、Hub 与连接管理实战
c#·.net
唐宋元明清21882 天前
.NET Win32磁盘动态卷/跨区卷触发“函数不正确”问题排查
windows·c#·存储
hez20102 天前
Satori GC:同时做到高吞吐、低延时和低内存占用
c#·.net·.net core·gc·clr
唐青枫2 天前
C#.NET Channel 深入解析:高性能异步生产者消费者模型实战
c#·.net
小峥降临3 天前
Rokid UXR 的手势追踪虚拟中更真实的手实战开发【含 工程源码 和 最终完成APK】
c#
晨星shine7 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530147 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net