DeepSeek 正在颠覆 AI 领域!通过推出一系列先进的推理模型,它挑战了 OpenAI 长期占据的主导地位。

最令人兴奋的是,这些革命性的模型完全免费使用,没有任何限制,任何人都可以随时访问并利用它们。是不是听起来像是科幻小说中的情节?但它已然成为现实!

在本教程中,我们将带你深入探讨如何在 Hugging Face 的 Medical Chain-of-Thought 数据集 上微调 DeepSeek-R1-Distill-Llama-8B 模型。

这个经过精心提炼的 DeepSeek-R1 模型,是通过对 DeepSeek-R1 生成的数据微调 Llama 3.1 8B 模型创建的,展示了与原始模型相似的卓越推理能力。这不仅是一次技术突破,也是你进一步掌握 AI 推理能力的最佳时机!

中国 AI 公司 DeepSeek AI 正式开源了其第一代推理模型 DeepSeek-R1DeepSeek-R1-Zero,它们在数学、编码、逻辑等推理任务上的表现,已可与 OpenAIGPT-4(o1)相媲美。

更值得关注的是,DeepSeek-R1-Zero 采用了一种全新的训练方法——大规模强化学习(RL),而非传统的 监督微调(SFT)。这种创新的训练方式使得模型能够独立探索思维链(CoT)推理,能够在面对复杂问题时,进行自我迭代优化输出。

然而,尽管 DeepSeek-R1-Zero 展示了强大的推理能力,但也带来了不容忽视的挑战。由于模型在强化学习中自主进行推理,它可能会产生重复的推理步骤、可读性较差,甚至出现语言混合等问题,这些都可能影响最终输出的清晰度和可用性。

因此,尽管其能力令人震惊,但在实际应用中,如何优化其推理流程,提升输出质量,仍然是一个值得关注的技术难题。

这场AI领域的创新革命正在悄然进行,DeepSeek 正在引领新一轮的推理技术变革。

除了需要大量计算能力和内存才能运行的大型语言模型外,DeepSeek 还引入了蒸馏模型。这些更小、更高效的模型已经证明,它们仍然可以实现卓越的推理性能。

这些模型从 1.5B 到 70B 参数不等,保留了强大的推理能力,DeepSeek-R1-Distill-Qwen-32B 在多个基准测试中都优于 OpenAI-o1-mini。

安装 unsloth Python 包。Unsloth 是一个开源框架,旨在使微调大型语言模型的速度提高 2LLMs 倍,内存效率更高。

%%capture!pip install unsloth!pip install --force-reinstall --no-cache-dir --no-deps git+https://github.com/unslothai/unsloth.git

使用我们从 Kaggle Secrets 中安全提取的 Hugging Face API 登录到 Hugging Face CLI。

from huggingface_hub import loginfrom kaggle_secrets import UserSecretsClientuser_secrets = UserSecretsClient()
hf_token = user_secrets.get_secret("HUGGINGFACE_TOKEN")login(hf_token)

使用您的API密钥登录Weights & Biases (wandb),并创建一个新项目来跟踪实验和微调进度。​​​​​​​

import wandb
wb_token = user_secrets.get_secret("wandb")
wandb.login(key=wb_token)run = wandb.init(    project='Fine-tune-DeepSeek-R1-Distill-Llama-8B on Medical COT Dataset',     job_type="training",     anonymous="allow")

对于此项目,我们将加载 DeepSeek-R1-Distill-Llama-8B 的 Unsloth 版本。 此外,我们将以 4 位量化加载模型,以优化内存使用和性能。

from unsloth import FastLanguageModel
max_seq_length = 2048 dtype = None load_in_4bit = True

model, tokenizer = FastLanguageModel.from_pretrained(    model_name = "unsloth/DeepSeek-R1-Distill-Llama-8B",    max_seq_length = max_seq_length,    dtype = dtype,    load_in_4bit = load_in_4bit,    token = hf_token, )

要为模型创建提示样式,我们将定义系统提示并包含用于问题和响应生成的占位符。该提示将指导模型逐步思考并提供合乎逻辑、准确的响应。

prompt_style = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request. Before answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.
### Instruction:You are a medical expert with advanced knowledge in clinical reasoning, diagnostics, and treatment planning. Please answer the following medical question. 
### Question:{}
### Response:<think>{}"""

在此示例中,我们将向 prompt_style 提供一个医学问题,将其转换为标记,然后将标记传递给模型以生成响应。

​​​​​​​

question = "A 61-year-old woman with a long history of involuntary urine loss during activities like coughing or sneezing but no leakage at night undergoes a gynecological exam and Q-tip test. Based on these findings, what would cystometry most likely reveal about her residual volume and detrusor contractions?"

FastLanguageModel.for_inference(model) inputs = tokenizer([prompt_style.format(question, "")], return_tensors="pt").to("cuda")
outputs = model.generate(    input_ids=inputs.input_ids,    attention_mask=inputs.attention_mask,    max_new_tokens=1200,    use_cache=True,)response = tokenizer.batch_decode(outputs)print(response[0].split("### Response:")[1])

我们将通过为 complex chain of thought 列添加第三个占位符来略微更改处理数据集的提示样式。

train_prompt_style = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request. Before answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.
### Instruction:You are a medical expert with advanced knowledge in clinical reasoning, diagnostics, and treatment planning. Please answer the following medical question. 
### Question:{}
### Response:<think>{}</think>{}"""

编写 Python 函数,该函数将在数据集中创建一个 “text” 列,该列由训练提示样式组成。在占位符中填写问题、文本链和答案。

​​​​​​​

EOS_TOKEN = tokenizer.eos_token  # Must add EOS_TOKEN

def formatting_prompts_func(examples):    inputs = examples["Question"]    cots = examples["Complex_CoT"]    outputs = examples["Response"]    texts = []    for input, cot, output in zip(inputs, cots, outputs):        text = train_prompt_style.format(input, cot, output) + EOS_TOKEN        texts.append(text)    return {        "text": texts,    }

我们将从  FreedomIntelligence/medical-o1-reasoning-SFT 数据集加载前 500 个样本,该数据集可在 Hugging Face 中心获得。之后,我们将使用 formatting_prompts_func 函数映射文本列。

​​​​​​​

from datasets import load_datasetdataset = load_dataset("FreedomIntelligence/medical-o1-reasoning-SFT","en", split = "train[0:500]",trust_remote_code=True)dataset = dataset.map(formatting_prompts_func, batched = True,)dataset["text"][0]

使用目标模块,我们将通过将低排名的采用者添加到模型来设置模型。

​​​​​​​

model = FastLanguageModel.get_peft_model(    model,    r=16,      target_modules=[        "q_proj",        "k_proj",        "v_proj",        "o_proj",        "gate_proj",        "up_proj",        "down_proj",    ],    lora_alpha=16,    lora_dropout=0,      bias="none",      use_gradient_checkpointing="unsloth",  # True or "unsloth" for very long context    random_state=3407,    use_rslora=False,      loftq_config=None,)

接下来,我们将通过提供模型、分词器、数据集和其他重要的训练参数来设置训练参数和训练器,这些参数将优化我们的微调过程。

from trl import SFTTrainerfrom transformers import TrainingArgumentsfrom unsloth import is_bfloat16_supported
trainer = SFTTrainer(    model=model,    tokenizer=tokenizer,    train_dataset=dataset,    dataset_text_field="text",    max_seq_length=max_seq_length,    dataset_num_proc=2,    args=TrainingArguments(        per_device_train_batch_size=2,        gradient_accumulation_steps=4,        # Use num_train_epochs = 1, warmup_ratio for full training runs!        warmup_steps=5,        max_steps=60,        learning_rate=2e-4,        fp16=not is_bfloat16_supported(),        bf16=is_bfloat16_supported(),        logging_steps=10,        optim="adamw_8bit",        weight_decay=0.01,        lr_scheduler_type="linear",        seed=3407,        output_dir="outputs",    ),)

trainer_stats = trainer.train()

为了比较结果,我们将向微调模型提出与之前相同的问题,以查看发生了什么变化。

​​​​​​​

question = "A 61-year-old woman with a long history of involuntary urine loss during activities like coughing or sneezing but no leakage at night undergoes a gynecological exam and Q-tip test. Based on these findings, what would cystometry most likely reveal about her residual volume and detrusor contractions?"

FastLanguageModel.for_inference(model)  # Unsloth has 2x faster inference!inputs = tokenizer([prompt_style.format(question, "")], return_tensors="pt").to("cuda")
outputs = model.generate(    input_ids=inputs.input_ids,    attention_mask=inputs.attention_mask,    max_new_tokens=1200,    use_cache=True,)response = tokenizer.batch_decode(outputs)print(response[0].split("### Response:")[1])

现在,让我们在本地保存 adopter、full model 和 tokenizer,以便我们可以在其他项目中使用它们。

​​​​​​​

new_model_local = "DeepSeek-R1-Medical-COT"model.save_pretrained(new_model_local) tokenizer.save_pretrained(new_model_local)
model.save_pretrained_merged(new_model_local, tokenizer, save_method = "merged_16bit",)

AI 领域正在迅速变化。开源社区现在正在接管,挑战过去三年来统治 AI 领域的专有模型的主导地位。

开源大型语言模型 LLMs 变得越来越好、更快、更高效,这使得在较低的计算和内存资源上对其进行微调变得比以往任何时候都更容易。

 

 如何学习AI大模型?

我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。

第一阶段: 从大模型系统设计入手,讲解大模型的主要方法;

第二阶段: 在通过大模型提示词工程从Prompts角度入手更好发挥模型的作用;

第三阶段: 大模型平台应用开发借助阿里云PAI平台构建电商领域虚拟试衣系统;

第四阶段: 大模型知识库应用开发以LangChain框架为例,构建物流行业咨询智能问答系统;

第五阶段: 大模型微调开发借助以大健康、新零售、新媒体领域构建适合当前领域大模型;

第六阶段: 以SD多模态大模型为主,搭建了文生图小程序案例;

第七阶段: 以大模型平台应用与开发为主,通过星火大模型,文心大模型等成熟大模型构建大模型行业应用。


👉学会后的收获:👈
• 基于大模型全栈工程实现(前端、后端、产品经理、设计、数据分析等),通过这门课可获得不同能力;

• 能够利用大模型解决相关实际项目需求: 大数据时代,越来越多的企业和机构需要处理海量数据,利用大模型技术可以更好地处理这些数据,提高数据分析和决策的准确性。因此,掌握大模型应用开发技能,可以让程序员更好地应对实际项目需求;

• 基于大模型和企业数据AI应用开发,实现大模型理论、掌握GPU算力、硬件、LangChain开发框架和项目实战技能, 学会Fine-tuning垂直训练大模型(数据准备、数据蒸馏、大模型部署)一站式掌握;

• 能够完成时下热门大模型垂直领域模型训练能力,提高程序员的编码能力: 大模型应用开发需要掌握机器学习算法、深度学习框架等技术,这些技术的掌握可以提高程序员的编码能力和分析能力,让程序员更加熟练地编写高质量的代码。


1.AI大模型学习路线图
2.100套AI大模型商业化落地方案
3.100集大模型视频教程
4.200本大模型PDF书籍
5.LLM面试题合集
6.AI产品经理资源合集

👉获取方式:
😝有需要的小伙伴,可以保存图片到wx扫描二v码免费领取【保证100%免费】🆓

Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐