使用 Python 从零构建 DeepSeek R1

DeepSeek R1 的整个训练过程,本质上就是在基础模型(即 deepseek V3)之上采用不同方式的强化学习。

从一个小型本地运行的基础模型开始,我们将基于 DeepSeek R1 技术报告从头构建所有内容,并在每个步骤中同步讲解相关理论。

目录

搭建基础环境

训练数据集

DeepSeek R1 训练快速概览

选择基础模型

强化学习设置中的策略模型(R)

R1 Zero 的 GRPO 算法

提示模板

预处理训练数据

奖励函数

Accuracy Reward

Format Reward

Reasoning Steps Reward

Cosine Scaled Reward

Repetition Penalty Reward

R1 Zero 的训练配置

GRPO Training Loop

Saving Tiny R1 Zero LLM

Two main problems with R1 Zero

Preparing Cold Start Data for SFT

长思维链的少样本提示

Direct Prompting

Post Processing Refinement

SFT Stage 1 With Cold Start Data

Stage 1 SFT Trainer Configs for R1

Stage 1 STF Training Loop

Saving Tiny R1 LLM

Reasoning-Oriented RL

Rejection Sampling

SFT Stage 2 Training

Distillation  


搭建基础环境

pip install -r requirements.txt
--extra-index-url https://download.pytorch.org/whl/cu118
torch
torchvision
torchaudio
transformers
datasets
accelerate
peft
trl
wandb
vllm
latex2sympy2_extended
math_verify

现在,让我们导入所需的库。

# Import necessary libraries
import logging
import os
import sys
import re
import math
from dataclasses import dataclass, field
from typing import List, Optional

# Import PyTorch and Hugging Face Transformers
import torch
import transformers
from transformers import (
    AutoModelF
### 部署DeepSeek R1并创建知识库 为了在本地环境中使用 Python 部署 DeepSeek R1 并创建知识库,以下是详细的指南: #### 准备环境 确保已安装必要的依赖项和工具链。通常这包括 Python 和 pip 的最新版本。 #### 安装DeepSeek R1 可以通过 Git 或者直接下载源码包来获取项目文件。之后利用pip命令安装所需的Python库。 ```bash git clone https://github.com/deepseek-r1/repo.git cd repo pip install -r requirements.txt ``` #### 初始化模型和服务 启动服务之前,需先加载预训练权重到指定位置,并初始化API端点。 ```python from deepseek_r1 import initialize_model, start_service initialize_model(model_path='./models/weights') start_service(host='0.0.0.0', port=8080) ``` [^2] #### 构建知识库 一旦服务运行正常,则可着手于数据收集与处理阶段。此过程涉及文本清洗、分词以及向量化表示等操作。 ```python import json from pathlib import Path from deepseek_r1.utils import preprocess_text, vectorize_documents data_dir = './data' output_file = 'knowledge_base.json' documents = [] for file in Path(data_dir).glob('*.txt'): with open(file, encoding='utf-8') as f: content = f.read() cleaned_content = preprocess_text(content) documents.append(cleaned_content) vectors = vectorize_documents(documents) with open(output_file, 'w', encoding='utf-8') as fout: json.dump(vectors, fout, ensure_ascii=False, indent=4) ``` [^3] 通过上述步骤,在本地成功部署了 DeepSeek R1 模型,并完成了初步的知识库建设工作。后续可以根据具体应用场景进一步优化和完善该系统功能。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

runner000001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值