微调实战 - 使用 Unsloth 微调 QwQ 32B 4bit (单卡4090)
本文参考视频教程:赋范课堂 – 只需20G显存,QwQ-32B高效微调实战!4大微调工具精讲!知识灌注+问答风格微调,DeepSeek R1类推理模型微调+Cot数据集创建实战打造定制大模型!
https://www.bilibili.com/video/BV1YoQoYQEwF/
课件资料:https://kq4b3vgg5b.feishu.cn/wiki/LxI9wmuFmiaLCkkoiCIcKvOan7Q
在此之上有删改
赋范课堂 有非常好的课程,推荐大家去学习观看
文章目录
- 一、基本准备
- 1、安装unsloth
- 2、wandb 安装与注册
- 3、下载模型
- 安装 huggingface_hub
- 使用screen开启持久化会话
- 设置模型国内访问镜像
- 下载模型
- 修改模型默认下载地址
- 二、模型调用测试
- modelscope 调用
- Ollama 调用
- vLLM 调用
- 请求测试
- 三、下载微调数据集
- 下载 NuminaMath CoT 数据集
- 下载 medical-o1-reasoning-SFT数据集
- 四、加载模型
- 五、微调前测试
- 基本问答测试
- 复杂问题测试
- 原始模型的医疗问题问答
- 六、最小可行性实验
- 定义提示词
- 定义数据集处理函数
- 整理数据
- 开启微调
- 微调说明
- 相关库
- 模型微调 **参数解析**
- ① `SFTTrainer` 部分
- ② `TrainingArguments` 部分
- 设置 wandb、开始微调
- 查看效果
- 模型合并
- 保存为 GGUF
- 七、完整高效微调实验
- 测试
一、基本准备
1、安装unsloth
pip install unsloth
pip install --force-reinstall --no-cache-dir --no-deps git+https://github.com/unslothai/unsloth.git
2、wandb 安装与注册
wandb 类似于 tensorboard,但比它稳定
注册:https://wandb.ai/site
API Key : https://wandb.ai/ezcode/t0322?product=models
注册和使用,详见:https://blog.csdn.net/lovechris00/article/details/146437418
安装 库
pip install wandb
登录,输入 API key
wandb login
3、下载模型
https://huggingface.co/unsloth/QwQ-32B-unsloth-bnb-4bit
安装 huggingface_hub
pip install huggingface_hub
使用screen开启持久化会话
模型下载时间可能持续0.5-1个小时。避免因为关闭会话导致下载中断
安装 screen
sudo apt install screen
screen -S qwq
设置模型国内访问镜像
Linux 上 ~/.bashrc
添加环境变量
export HF_ENDPOINT='https://hf-mirror.com'
下载模型
huggingface-cli download --resume-download unsloth/QwQ-32B-unsloth-bnb-4bit
修改模型默认下载地址
模型默认下载到 ~/.cache/huggingface/hub/
,如果想改到其它地方,可以设置 HF_HOME
键
export HF_HOME="/root/xx/HF_download"
二、模型调用测试
modelscope 调用
from modelscope import AutoModelForCausalLM, AutoTokenizermodel_name = "unsloth/QwQ-32B-unsloth-bnb-4bit"model = AutoModelForCausalLM.from_pretrained(model_name,torch_dtype="auto",device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)prompt = "你好,好久不见!"
messages = [{"role": "user", "content": prompt}
]
text = tokenizer.apply_chat_template(messages,tokenize=False,add_generation_prompt=True
)model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
generated_ids = model.generate(**model_inputs,max_new_tokens=32768
)generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
print(response)
Ollama 调用
from openai import OpenAIclient = OpenAI(base_url='http://localhost:11434/v1/',api_key='ollama', # required but ignored
)prompt = "你好,好久不见!"
messages = [{"role": "user", "content": prompt}
]response = client.chat.completions.create(messages=messages,model='qwq-32b-bnb',
)print(response.choices[0].message.content)
模型注册
查看是否注册成功
ollama list
使用 openai 库请求
from openai import OpenAIclient = OpenAI(base_url='http://localhost:11434/v1/',api_key='ollama', # required but ignored
)prompt = "你好,好久不见!"
messages = [{"role": "user", "content": prompt}
]
vLLM 调用
vllm serve /root/autodl-tmp/QwQ-32B-unsloth-bnb-4bit \
--quantization bitsandbytes \
--load-format bitsandbytes \
--max-model-len 2048
请求测试
from openai import OpenAI
openai_api_key = "EMPTY"
openai_api_base = "http://localhost:8000/v1"client = OpenAI(api_key=openai_api_key,base_url=openai_api_base,
)prompt = "你好,好久不见!"
messages = [{"role": "user", "content": prompt}
]response = client.chat.completions.create(model="/root/autodl-tmp/QwQ-32B-unsloth-bnb-4bit",messages=messages,
)print(response.choices[0].message.content)
三、下载微调数据集
推理类模型 回复结构 与 微调数据集结构 要求
QwQ-32B模型和DeepSeek R1类似,推理过程的具体体现就是 在回复内容中,会同时包含推理部分内容 和 最终回复部分内容,并且其推理部分内容会通过(一种在模型训练过程中注入的特殊标记)来进行区分。
下载 NuminaMath CoT 数据集
https://huggingface.co/datasets/AI-MO/NuminaMath-CoT
huggingface-cli download AI-MO/NuminaMath-CoT --repo-type dataset
除了NuminaMath CoT数据集外,还有APPs(编程数据集)、TACO(编程数据集)、long_form_thought_data_5k(通用问答数据集)等,都是CoT数据集,均可用于推理模型微调。相关数据集介绍,详见公开课:《借助DeepSeek R1进行模型蒸馏,模型蒸馏入门实战!》| https://www.bilibili.com/video/BV1X1FoeBEgW/
下载 medical-o1-reasoning-SFT数据集
https://huggingface.co/datasets/FreedomIntelligence/medical-o1-reasoning-SFT
huggingface-cli download FreedomIntelligence/medical-o1-reasoning-SFT --repo-type dataset
你也可以 使用 Python - datasets 库来下载
from datasets import load_dataset# 此处先下载前500条数据即可完成实验
dataset = load_dataset("FreedomIntelligence/medical-o1-reasoning-SFT","en", split = "train[0:500]",trust_remote_code=True)# 查看数据集情况
dataset[0]
四、加载模型
from unsloth import FastLanguageModel max_seq_length = 2048
dtype = None
load_in_4bit = Truemodel, tokenizer = FastLanguageModel.from_pretrained(model_name = "unsloth/QwQ-32B-unsloth-bnb-4bit",max_seq_length = max_seq_length,dtype = dtype,load_in_4bit = load_in_4bit,
)
此时消耗 GPU : 22016MB
五、微调前测试
查看模型信息
>>> model
Qwen2ForCausalLM((model): Qwen2Model((embed_tokens): Embedding(152064, 5120, padding_idx=151654)(layers): ModuleList((0): Qwen2DecoderLayer(...(62): Qwen2DecoderLayer(...)(63): Qwen2DecoderLayer(...)(norm): Qwen2RMSNorm((5120,), eps=1e-05)(rotary_emb): LlamaRotaryEmbedding())(lm_head): Linear(in_features=5120, out_features=152064, bias=False)
)
tokenizer 信息
>>> tokenizer
Qwen2TokenizerFast(name_or_path='unsloth/QwQ-32B-unsloth-bnb-4bit', vocab_size=151643, model_max_length=131072, is_fast=True, padding_side='left', truncation_side='right', special_tokens={'eos_token': '<|im_end|>', 'pad_token': '<|vision_pad|>', 'additional_special_tokens': ['<|im_start|>', '<|im_end|>', '<|object_ref_start|>', '<|object_ref_end|>', '<|box_start|>', '<|box_end|>', '<|quad_start|>', '<|quad_end|>', '<|vision_start|>', '<|vision_end|>', '<|vision_pad|>', '<|image_pad|>', '<|video_pad|>']}, clean_up_tokenization_spaces=False, added_tokens_decoder={151643: AddedToken("<|endoftext|>", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),151644: AddedToken("<|im_start|>", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),...151667: AddedToken("<think>", rstrip=False, lstrip=False, single_word=False, normalized=False, special=False),151668: AddedToken("</think>", rstrip=False, lstrip=False, single_word=False, normalized=False, special=False),
}
)
基本问答测试
# 将模型调整为推理模式
FastLanguageModel.for_inference(model) # 带入问答模板进行回答 prompt_style_chat = """请写出一个恰当的回答来完成当前对话任务。
***
### Instruction:
你是一名助人为乐的助手。
***
### Question:
{}
***
### Response:
<think>{}"""question = "你好,好久不见!"
prompt = [prompt_style_chat.format(question, "")] inputs = tokenizer(prompt, return_tensors="pt").to("cuda")outputs = model.generate(input_ids=inputs.input_ids,max_new_tokens=2048,use_cache=True,
)# GPU 消耗到 22412 mb
'''
>>> outputs
tensor([[ 14880, 112672, 46944, 112449, 111423, 36407, 60548, 67949, 105051,...35946, 106128, 99245, 101037, 11319, 144236, 151645]],device='cuda:0')
'''response = tokenizer.batch_decode(outputs)
# response --> ['请写出一个恰当的回答来完成当前对话任务。\n***\n### Instruction:\n你是一名助人为乐的助手。\n***\n### Question:\n你好,好久不见!\n***\n### Response:\n<think>:\n好的,用户发来问候“你好,好久不见!”,我需要回应并延续对话。首先,应该友好回应他们的问候,比如“你好!确实很久没联系了,希望你一切都好!”这样既回应了对方,也表达了关心。接下来,可能需要询问对方近况,或者引导对话继续下去。比如可以问:“最近有什么新鲜事吗?或者你有什么需要帮助的吗?”这样可以让对话更自然,也符合助人为乐的角色设定。还要注意语气要亲切,保持口语化,避免过于正式。另外,用户可能希望得到情感上的回应,所以需要体现出关心和愿意帮助的态度。检查有没有语法错误,确保句子流畅。最后,确定回应简洁但足够友好,符合对话的流程。\n</think>\n\n你好!确实好久不见了,希望你一切都好!最近有什么新鲜事分享,或者需要我帮忙什么吗?😊<|im_end|>']print(response[0].split("### Response:")[1])
复杂问题测试
question = "请证明根号2是无理数。"inputs = tokenizer([prompt_style_chat.format(question, "")], return_tensors="pt").to("cuda")outputs = model.generate(input_ids=inputs.input_ids,max_new_tokens=1200,use_cache=True,
)# GPU 用到 22552MiBresponse = tokenizer.batch_decode(outputs)print(response[0].split("### Response:")[1])
原始模型的医疗问题问答
# 重新设置问答模板
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>{}"""question_1 = "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?"question_2 = "Given a patient who experiences sudden-onset chest pain radiating to the neck and left arm, with a past medical history of hypercholesterolemia and coronary artery disease, elevated troponin I levels, and tachycardia, what is the most likely coronary artery involved based on this presentation?"inputs1 = tokenizer([prompt_style.format(question_1, "")], return_tensors="pt").to("cuda")outputs1 = model.generate(input_ids=inputs1.input_ids,max_new_tokens=1200,use_cache=True,
)response1 = tokenizer.batch_decode(outputs1)print(response1[0].split("### Response:")[1])
inputs2 = tokenizer([prompt_style.format(question_2, "")], return_tensors="pt").to("cuda")outputs2 = model.generate(input_ids=inputs2.input_ids,max_new_tokens=1200,use_cache=True,
)
# GPU 22842 MiB response2 = tokenizer.batch_decode(outputs2)print(response2[0].split("### Response:")[1])
六、最小可行性实验
接下来我们尝试进行模型微调
对于当前数据集而言,我们可以带入 原始数据集 的部分数据 进行微调,也可以带入 全部数据 并遍历多次进行微调。
对于大多数的微调实验,我们都可以从 最小可行性实验 入手进行微调,也就是先尝试带入少量数据进行微调,并观测微调效果。
若微调可以顺利执行,并能够获得微调效果,再考虑带入更多的数据进行更大规模微调。
定义提示词
import os
from datasets import load_datasettrain_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>
{}"""EOS_TOKEN = tokenizer.eos_token # '<|im_end|>'
定义数据集处理函数
用于对medical-o1-reasoning-SFT数据集进行修改,Complex_CoT
列 和 Response
列 进行拼接,并加上文本结束标记:
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_TOKENtexts.append(text)return {"text": texts,}
整理数据
dataset = load_dataset("FreedomIntelligence/medical-o1-reasoning-SFT","en", split = "train[0:500]",trust_remote_code=True)
'''
{'Question': 'A 61-year-old ... contractions?','Complex_CoT': "Okay, let's ... incontinence.",'Response': 'Cystometry in ... the test.'
}
'''# 结构化处理
dataset = dataset.map(formatting_prompts_func, batched = True,) # 查看
dataset["text"][0]
'''
Below is an instruction that ... response.
***
### Instruction:
You are a medical ... medical question.
***
### Question:
A 61-year-old woman ... contractions?
***
### Response:
<think>
Okay,...Yup, I think that makes sense given her symptoms and the typical presentations of stress urinary incontinence.
</think>
Cystometry ... is primarily related to physical e
'''
开启微调
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 contextrandom_state=3407,use_rslora=False, loftq_config=None,
)from trl import SFTTrainer
from transformers import TrainingArguments
from 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",),
)
微调说明
这段代码主要是用 SFTTrainer
进行 监督微调(Supervised Fine-Tuning, SFT),适用于 transformers
和 Unsloth
生态中的模型微调:
相关库
SFTTrainer
(来自trl
库):trl
(Transformer Reinforcement Learning)是 Hugging Face 旗下的trl
库,提供 监督微调(SFT) 和 强化学习(RLHF) 相关的功能。SFTTrainer
主要用于 有监督微调(Supervised Fine-Tuning),适用于LoRA
等低秩适配微调方式。
TrainingArguments
(来自transformers
库):- 这个类用于定义 训练超参数,比如批量大小、学习率、优化器、训练步数等。
is_bfloat16_supported()
(来自unsloth
):- 这个函数检查 当前 GPU 是否支持
bfloat16
(BF16),如果支持,则返回True
,否则返回False
。 bfloat16
是一种更高效的数值格式,在 新款 NVIDIA A100/H100 等 GPU 上表现更优。
- 这个函数检查 当前 GPU 是否支持
模型微调 参数解析
① SFTTrainer
部分
参数 | 作用 |
---|---|
model=model | 指定需要进行微调的 预训练模型 |
tokenizer=tokenizer | 指定 分词器,用于处理文本数据 |
train_dataset=dataset | 传入 训练数据集 |
dataset_text_field="text" | 指定数据集中哪一列包含 训练文本(在 formatting_prompts_func 里处理) |
max_seq_length=max_seq_length | 最大序列长度,控制输入文本的最大 Token 数量 |
dataset_num_proc=2 | 数据加载的并行进程数,提高数据预处理效率 |
② TrainingArguments
部分
参数 | 作用 |
---|---|
per_device_train_batch_size=2 | 每个 GPU/设备 的训练批量大小(较小值适合大模型) |
gradient_accumulation_steps=4 | 梯度累积步数(相当于 batch_size=2 × 4 = 8 ) |
warmup_steps=5 | 预热步数(初始阶段学习率较低,然后逐步升高) |
max_steps=60 | 最大训练步数(控制训练的总步数,此处总共约消耗60*8=480条数据) |
learning_rate=2e-4 | 学习率(2e-4 = 0.0002,控制权重更新幅度) |
fp16=not is_bfloat16_supported() | 如果 GPU 不支持 bfloat16 ,则使用 fp16 (16位浮点数) |
bf16=is_bfloat16_supported() | 如果 GPU 支持 bfloat16 ,则启用 bfloat16 (训练更稳定) |
logging_steps=10 | 每 10 步记录一次训练日志 |
optim="adamw_8bit" | 使用 adamw_8bit (8-bit AdamW优化器)减少显存占用 |
weight_decay=0.01 | 权重衰减(L2 正则化),防止过拟合 |
lr_scheduler_type="linear" | 学习率调度策略(线性衰减) |
seed=3407 | 随机种子(保证实验结果可复现) |
output_dir="outputs" | 训练结果的输出目录 |
设置 wandb、开始微调
import wandb
wandb.login(key="8c7...242bd")
run = wandb.init(project='Fine-tune-QwQ-32B-4bit on Medical COT Dataset', )# 开始微调
trainer_stats = trainer.train()
如果 出现 CUDA out of memory
的情况,可以酌情修改参数。
试试如下代码(仅用于测试,不保证效果):
import torch
torch.cuda.empty_cache()import os
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True" from unsloth import FastLanguageModel max_seq_length = 1024
dtype = None
load_in_4bit = Truemodel, tokenizer = FastLanguageModel.from_pretrained(model_name = "unsloth/QwQ-32B-unsloth-bnb-4bit",max_seq_length = max_seq_length,dtype = dtype,load_in_4bit = load_in_4bit,
)import os
from datasets import load_datasettrain_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>
{}"""EOS_TOKEN = tokenizer.eos_token # '<|im_end|>' 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_TOKENtexts.append(text)return {"text": texts,}dataset = load_dataset("FreedomIntelligence/medical-o1-reasoning-SFT","en", split = "train[0:200]",trust_remote_code=True) # 结构化处理
dataset = dataset.map(formatting_prompts_func, batched = True,) # 开启微调
model = FastLanguageModel.get_peft_model(model,r=8, target_modules=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj",],lora_alpha=8,lora_dropout=0, bias="none", use_gradient_checkpointing="unsloth", # True or "unsloth" for very long contextrandom_state=3407,use_rslora=False, loftq_config=None,
)from trl import SFTTrainer
from transformers import TrainingArguments
from 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=1,gradient_accumulation_steps=8,# 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=20,optim="adamw_8bit",weight_decay=0.01,lr_scheduler_type="linear",seed=3407,output_dir="outputs",),
)import wandb
wandb.login(key="8c7b98e4f525793b228b04fcc3596acd9e7242bd")
run = wandb.init(project='Fine-tune-QwQ-32B-4bit on Medical COT Dataset', )# 开始微调
trainer_stats = trainer.train()
查看效果
unsloth在微调结束后,会自动更新模型权重(在缓存中),因此无需手动合并模型权重 即可直接调用微调后的模型:
trainer_stats
# TrainOutput(global_step=60, training_loss=1.3152311007181803, metrics={'train_runtime': 709.9004, 'train_samples_per_second': 0.676, 'train_steps_per_second': 0.085, 'total_flos': 6.676294205826048e+16, 'train_loss': 1.3152311007181803})# 到推理状态
FastLanguageModel.for_inference(model)# 再次查看问答效果
inputs = tokenizer([prompt_style.format(question_1, "")], return_tensors="pt").to("cuda")outputs = model.generate(input_ids=inputs.input_ids,attention_mask=inputs.attention_mask,max_new_tokens=2048,use_cache=True,
)
response = tokenizer.batch_decode(outputs)
print(response[0].split("### Response:")[1])inputs = tokenizer([prompt_style.format(question_2, "")], return_tensors="pt").to("cuda")outputs = model.generate(input_ids=inputs.input_ids,attention_mask=inputs.attention_mask,max_new_tokens=2048,use_cache=True,
)
response = tokenizer.batch_decode(outputs)
print(response[0].split("### Response:")[1])
模型合并
save_path = 'QwQ-Medical-COT-Tiny'
model.save_pretrained_merged(save_path, tokenizer, save_method = "merged_4bit",)
保存为 GGUF
方便使用ollama进行推理
导出与合并需要较长时间(约20分钟左右)
save_path = 'QwQ-Medical-COT-Tiny-GGUF'
model.save_pretrained_gguf(save_path, tokenizer, quantization_method = "q4_k_m")
七、完整高效微调实验
最后,带入全部数据进行高效微调,以提升模型微调效果。
# 设置训练的提示词模板
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>
{}"""EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKENdef 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_TOKENtexts.append(text)return {"text": texts,}# 读取全部数据
dataset = load_dataset("FreedomIntelligence/medical-o1-reasoning-SFT","en", split = "train",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 contextrandom_state=3407,use_rslora=False, loftq_config=None,
)from trl import SFTTrainer
from transformers import TrainingArguments
from unsloth import is_bfloat16_supported# 设置epoch为3,遍历3次数据集:
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,num_train_epochs = 3,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",),
)# Map (num_proc=2): 0%| | 0/25371 [00:00<?, ? examples/s] trainer_stats = trainer.train()
[ 389/9513 13:44 < 5:24:01, 0.47 it/s, Epoch 0.12/3]
Step | Training Loss |
---|---|
10 | 1.285900 |
20 | 1.262500 |
… | … |
370 | 1.201200 |
380 | 1.215600 |
这里总共训练约15个小时。
trainer_stats
TrainOutput(global_step=9513, training_loss=1.0824475168592858, metrics={'train_runtime': 20193.217, 'train_samples_per_second': 3.769, 'train_steps_per_second': 0.471, 'total_flos': 2.7936033274397737e+18, 'train_loss': 1.0824475168592858, 'epoch': 2.9992117294655527})
测试
带入两个问题进行测试,均有较好的回答效果:
question = "A 61-year-old ... 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])
question = "Given a patient who experiences sudden-onset chest pain radiating to the neck and left arm, with a past medical history of hypercholesterolemia and coronary artery disease, elevated troponin I levels, and tachycardia, what is the most likely coronary artery involved based on this presentation?"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])
2025-03-22(六)
相关文章:
微调实战 - 使用 Unsloth 微调 QwQ 32B 4bit (单卡4090)
本文参考视频教程:赋范课堂 – 只需20G显存,QwQ-32B高效微调实战!4大微调工具精讲!知识灌注问答风格微调,DeepSeek R1类推理模型微调Cot数据集创建实战打造定制大模型! https://www.bilibili.com/video/BV1…...
金仓KESV8R6任务调度
基本概念 • 程序(program) 程序对象描述调度器要运行的内容。 • 调度计划(schedule) 调度计划对象指定作业何时运行以及运行多少次。调度计划可以被多个作业共享。 • 作业(job) 作业就是用户定义的…...
Maven常见问题汇总
Maven刷新,本地仓库无法更新 现象 This failure was cached in the local repository and resolution is not reattempted until the update interval of aliyunmaven has elapsed or updates are forced原因 因为上一次尝试下载,发现对应的仓库没有这个maven配置…...
颠覆者的困局:解构周鸿祎商业哲学中的“永恒战争”
引言:被误解的破坏者 在北京海淀区知春路银谷大厦的某间会议室里,周鸿祎用马克笔在白板上画出一个巨大的爆炸图案——这是2010年360与腾讯开战前夜的战术推演场景。这个充满硝烟味的瞬间,恰是《颠覆者》精神内核的完美隐喻:在中国…...
基于ChatGPT、GIS与Python机器学习的地质灾害风险评估、易发性分析、信息化建库及灾后重建高级实践
第一章、ChatGPT、DeepSeek大语言模型提示词与地质灾害基础及平台介绍【基础实践篇】 1、什么是大模型? 大模型(Large Language Model, LLM)是一种基于深度学习技术的大规模自然语言处理模型。 代表性大模型:GPT-4、BERT、T5、Ch…...
如何实现单点登录?
单点登录(Single Sign-On, SSO)是一种身份验证机制,允许用户在多个应用系统中只登录一次,就能够访问所有受保护的系统或服务,而无需重复登录。SSO通过集中式认证来简化用户的登录体验,提高安全性,并减少管理复杂性。 一、原理 SSO的核心原理是通过一个认证中心(Ident…...
01 Overview
版本pytorch 0.4,应用期的技术 学习的前提 线性代数和概率分布,高数 内容 穷举、贪心、分治算法、动态规划 花书是经典中的经典 机器学习历史 1 基于规则的 2 经典的机器学习方法 3 深度学习 深度学习竞赛识别率超过了人类 神经网络是数学和工…...
第二天 开始Unity Shader的学习之旅之熟悉顶点着色器和片元着色器
Shader初学者的学习笔记 第二天 开始Unity Shader的学习之旅之熟悉顶点着色器和片元着色器 文章目录 Shader初学者的学习笔记前言一、顶点/片元着色器的基本结构① Shader "Unity Shaders Book/Chapter 5/ Simple Shader"② SubShader③ CGPROGRAM和ENDCG④ 指明顶点…...
moveit2基础教程上手-使用xarm6演示
0、前置信息 开发环境:wsl。 ros版本:jazzy,ubuntu版本:24.04 xarm-ros2地址 1、启动Rviz,加载 Motion Planning Plugin,实现演示功能 Getting Started — MoveIt Documentation: Rolling documentation…...
头部姿态估计(Head Pose Estimation)领域,有许多开源工具和库可供选择,一些常用的工具及其特点
在头部姿态估计(Head Pose Estimation)领域,有许多开源工具和库可供选择。以下是一些常用的工具及其特点比较: 1. OpenCV 特点: OpenCV 是一个广泛使用的计算机视觉库,提供了丰富的图像处理和计算机视觉算法。虽然 O…...
Qt调用Miniconda的python方法
1、 Win 64环境下载及安装 Miniconda 首先下载Windows 版Miniconda,https://docs.conda.io/en/latest/miniconda.html或 https://repo.anaconda.com/miniconda/ 安装界面及选择如下图所示: 安装完python3.12版报错如下。 说明:python3.11版…...
【Linux 下的 bash 无法正常解析, Windows 的 CRLF 换行符问题导致的】
文章目录 报错原因:解决办法:方法一:用 dos2unix 修复方法二:手动转换换行符方法三:VSCode 或其他编辑器手动改 总结 这个错误很常见,原因是你的 wait_for_gpu.sh 脚本 文件格式不对,具体来说…...
DSP数字信号处理
数字信号处理(Digital Signal Processing,简称DSP)是一门研究如何通过数字技术对信号进行分析、修改和合成的学科。DSP在现代电子系统中无处不在,广泛应用于音频处理、视频处理、通信、雷达、医学成像等领域。 什么是数字信号处理…...
vue3 获取当前路由信息失败问题
刷新浏览器时获取当前路由信息失败:undefined import { ref, reactive, onMounted } from vue; import { useRoute } from vue-router; const route useRoute();onMounted(()>{// 打印当前路由信息console.log(当前route, route ); // 这里的打印有值console.…...
数据驱动进化:AI Agent如何重构手机交互范式?
如果说AIGC拉开了内容生成的序幕,那么AI Agent则标志着AI从“工具”向“助手”的跨越式进化。它不再是简单的问答机器,而是一个能够感知环境、规划任务并自主执行的智能体,更像是虚拟世界中的“全能员工”。 正如行业所热议的:“大…...
汽车芯片成本控制:挑战、策略与未来趋势
一、引言 随着汽车行业的快速发展,汽车芯片在车辆中的应用越来越广泛。从简单的发动机控制单元到复杂的自动驾驶系统,芯片已成为汽车智能化、电动化的核心部件。然而,汽车芯片的高成本一直是制约汽车行业发展的重要因素之一。本文将深入探讨…...
RIP实验
RIP实验 一、实验背景 RIP协议: RIP协议(Routing Information Protocol,路由信息协议)是一种基于距离矢量的内部网关协议,即根据跳数来度量路由开销,进行路由选择。相比于其它路由协议(如OSPF、…...
NAT 实验:多私网环境下 NAPT、Easy IP 配置及 FTP 服务公网映射
NAT基本概念 定义:网络地址转换(Network Address Translation,NAT)是一种将私有(保留)地址转化为合法公网 IP 地址的转换技术,它被广泛应用于各种类型 Internet 接入方式和各种类型的网络中。作…...
电力和冷却管理:如何让数据中心“高效降温”同时节能增效
电力和冷却管理:如何让数据中心“高效降温”同时节能增效 数据中心作为现代信息技术基础设施的核心,承担着处理、存储和传输海量数据的重任。然而,这些庞大的服务器和存储设备在高速运转时,不仅需要大量电力供应,还产生了大量热量。如何平衡电力消耗与有效冷却,成为了数…...
LangChain Chat Model学习笔记
Prompt templates: Few shot、Example selector 一、Few shot(少量示例) 创建少量示例的格式化程序 创建一个简单的提示模板,用于在生成时向模型提供示例输入和输出。向LLM提供少量这样的示例被称为少量示例,这是一种简单但强大的指导生成的方式&…...
嵌入式硬件篇---Keil51中的关键字
文章目录 前言1. 存储类型关键字1.1code作用地址范围用途示例 1.2data作用地址范围用途示例 1.3idata作用地址范围用途示例 1.4xdata作用地址范围用途示例 1.5pdata作用地址范围用途示例 1.6volatile作用用途示例 2. 其他常用关键字2.1bit作用示例 2.2sbit作用示例 2.3sfr / sf…...
《TCP/IP网络编程》学习笔记 | Chapter 20:Windows 中的线程同步
《TCP/IP网络编程》学习笔记 | Chapter 20:Windows 中的线程同步 《TCP/IP网络编程》学习笔记 | Chapter 20:Windows 中的线程同步用户模式和内核模式用户模式同步内核模式同步 基于 CRITICAL_SECTION 的同步内核模式的同步方法基于互斥量对象的同步基于…...
MyBatis 中 #{} 和 ${} 的区别详解
目录 1. #{} 和 ${} 的基本概念 1.1 #{} 1.2 ${} 2. #{} 和 ${} 的工作原理 2.1 #{} 的工作原理 2.2 ${} 的工作原理 3.共同点:动态 SQL 查询 4. 区别:处理方式和适用场景 4.1 处理方式 4.2 适用场景 (1)#{} 的适用场景…...
C++学习之网盘项目单例模式
目录 1.知识点概述 2.单例介绍 3.单例饿汉模式 4.饿汉模式四个版本 5.单例类的使用 6.关于token的作用和存储 7.样式表使用方法 8.qss文件中选择器介绍 9.qss文件样式讲解和测试 10.qss美化登录界面补充 11.QHTTPMULTIPART类的使用 12.文件上传协议 13.文件上传协议…...
Lineageos 22.1(Android 15)制定应用强制横屏
一、前言 有时候需要系统的某个应用强制衡平显示,不管他是如何配置的。我们只需要简单的拿到top的Task下面的ActivityRecord,并判断包名来强制实现。 二、调整wms com.android.server.wm.DisplayRotation /*** Given an orientation constant, return…...
基于deepseek的智能语音客服【第四讲】封装milvus数据库连接池封装
通过工厂模式创建链接 static {// 创建连接池工厂BasePooledObjectFactory<MilvusServiceClient> factory new BasePooledObjectFactory<MilvusServiceClient>() {Overridepublic MilvusServiceClient create() throws Exception {return new MilvusServiceClient…...
【GeeRPC】项目总结:使用 Golang 实现 RPC 框架
文章目录 项目总结:使用 Golang 实现 RPC 框架谈谈 RPC 框架什么是 RPC 框架实现一个 RPC 框架需要什么?项目总结文章结构安排 Part1:消息编码编解码器的实现通信过程 Part2:服务端Accept:阻塞地等待连接请求并开启 go…...
人工智能在医疗影像诊断中的应用与挑战
引言 近年来,人工智能(AI)技术在医疗领域的应用逐渐成为研究热点,尤其是在医疗影像诊断方面。AI技术的引入为医疗影像诊断带来了更高的效率和准确性,有望缓解医疗资源紧张的问题,同时为患者提供更优质的医疗…...
烧结银技术赋能新能源汽车超级快充与高效驱动
烧结银技术赋能新能源汽车超级快充与高效驱动 在新能源汽车领域,高压快充技术的突破与高功率密度驱动系统的创新正成为行业竞争的焦点。比亚迪于 2025 年发布的超级 e 平台,通过整合全域千伏高压架构、兆瓦级闪充技术及碳化硅(SiC࿰…...
大模型幻觉产生的【九大原因】
知识问答推理幻觉产生的原因 1.知识库结构切割不合理 大段落切割向量化 切分太小可以实现更精准化的回复内,向量匹配相似度越高。检索内容碎片化严重、可能包含不符合内容的文本数据。切分太大内容资料更完整,但是会影响相似度,同时更消耗资…...
4小时速通shell外加100例
🔥 Shell 基础——从入门到精通 🚀 🌱 第一章:Shell,简单说! 👶 什么是Shell?它到底能做什么?这章让你快速了解Shell的强大之处! 👶 什么是Shell…...
AD(Altium Designer)更换PCB文件的器件封装
一、确定是否拥有想换的器件PCB封装 1.1 打开现有的原理图 1.2 确定是否拥有想换的器件PCB文件 1.2.1 如果有 按照1.3进行切换器件PCB封装 1.2.2 如果没有 按照如下链接进行添加 AD(Altium Designer)已有封装库的基础上添加器件封装-CSDN博客https://blog.csdn.net/XU15…...
Postgresql 删除数据库报错
1、删除数据库时,报错存在其他会话连接 ## 错误现象,存在其他的会话连接正在使用数据库 ERROR: database "cs" is being accessed by other users DETAIL: There is 1 other session using the database.2、解决方法 ## 终止被删除数据库下…...
人工智能时代——深度探索如何构建开放可控的专利生态体系
# 人工智能时代——深度探索如何构建开放可控的专利生态体系 引言:AI专利革命的战略抉择第一章 战略认知与基本原则1.1 人工智能专利革命的范式重构1.1.1 技术维度变革1.1.2 法律维度挑战1.1.3 文明安全的不可控风险 1.2 战略定位体系构建1.2.1 双循环治理框架的立体…...
✨【数据变形术:联合体在通信协议中的降维打击】✨
(万字长文详解联合体的二进制魔法与工程实践) 🔮 原理解析:内存空间的量子叠加态 文字叙述: 联合体(union)是C语言中最具魔法的数据结构,其所有成员共享同一块内存空间。这种特性使…...
docker compose部署minio报错
背景 部分服务使用docker-compose单节点编排,其中对象存储服务使用minio,在minio中配置了aksk后报错 Error: IAM sub-system is partially initialized, unable to write the IAM forma 解决 minio如果配置了aksk等iam类的配置则需要持久化存储到etcd…...
软件开发通用之状态机初认识-基本概念及简单应用
0 前言 在程序开发阶段(其实也不限于程序,还包含硬件电路设计,协议设计等),无论使用何种语言,何种工具,何种系统,程序的运行必须符合开发者的预设逻辑,而单独通过大脑记…...
蓝桥杯 之 第27场月赛总结
文章目录 习题1.抓猪拿国一2.蓝桥字符3.蓝桥大使4.拳头对决 习题 比赛地址 1.抓猪拿国一 十分简单的签到题 print(sum(list(range(17))))2.蓝桥字符 常见的字符匹配的问题,是一个二维dp的问题,转化为对应的动态规划求解 力扣的相似题目 可以关注灵神…...
适配器模式 (Adapter Pattern)
适配器模式 (Adapter Pattern) 是一种结构型设计模式,它将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的类可以一起工作。 在现实生活中,适配器的例子随处可见,比如电源适配器,它将不同电压的电流转换为设备所需的电压,确保设备能正…...
操作系统WIN11无法出现WLAN图标(解决方案)
本人操作系统WIN11之后无网络图标 于是在设置里查看了一下,是网卡驱动没了 网上去下载一个驱动类软件自行处理即可。 本人使用手机USB网络连的电脑,然后发现网卡驱动凭空出现了,就很困惑,没有下载驱动就恢复了。...
HCL—我与虚拟机的爱恨情仇[特殊字符][特殊字符][特殊字符]️
时隔了三周,我可能算是了解了虚拟机了吧。自从上一次的安装虚拟机,我与HCL、虚拟机就没有停止过纠缠。 为什么很多win11电脑使用不了HCL,或者无法启动HCL设备? 首先来解答,为什么很多win11电脑使用不了HCL,…...
illustrate:一款蛋白/核酸结构快速渲染为“卡通风格”的小工具
本期向大家介绍一款蛋白/核酸结构快速渲染(卡通风格)的小工具——illustrate。放心!本期完全不涉及代码,不折腾人,请放心食用。 结构渲染效果示例如下: PDB ID: 1ttt 该小工具适用绘制蛋白或复合物整体轮廓…...
Linux上位机开发实战(能用的开发板计算资源)
【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing 163.com】 大家所能想到的嵌入式上位机开发,如果是linux,同时涉及到嵌入式的话,一般都会认为是把pc linux的软件port到板子…...
kotlin 内联函数 inline
高阶函数实现的原理:函数类型其实是生成了一个对象 。 inline翻译成中文的意思就是内联,在kotlin里面inline被用来修饰函数,表明当前函数在编译时是以内嵌的形式进行编译的,从而减少了一层函数调用栈: inline fun fun…...
vue3配置代理实现axios请求本地接口返回PG库数据【前后端实操】
前端编写 安装 axios 如果当前未安装axios,可以执行如下指令安装 npm install axios配置代理 当前为基于Vite构建的项目,在 vite.config.ts 中配置代理,在defineConfig中新增server配置,主要关注两个点: 一、需要代…...
论文阅读:2023 arxiv Multiscale Positive-Unlabeled Detection of AI-Generated Texts
总目录 大模型安全相关研究:https://blog.csdn.net/WhiffeYF/article/details/142132328 Multiscale Positive-Unlabeled Detection of AI-Generated Texts https://arxiv.org/abs/2305.18149 https://www.doubao.com/chat/2114270649152258 https://github.com/YuchuanTi…...
【数学建模】最大最小值模型详解
数学建模中的最大最小值模型详解 文章目录 数学建模中的最大最小值模型详解引言最大最小值模型的基本概念最大化问题最小化问题 常见的求解方法1. 微积分法2. 线性规划3. 非线性规划4. 动态规划 实际应用案例案例1:生产规划问题案例2:投资组合优化 最大最…...
Camera2 实现重力感应四个方向调试相机预览
Camera2API 实现重力感应四个方向调试相机预览 文章目录 需求场景 需求实现setAspectRatio 设置显示长宽postScale postRotate 设置缩放和旋转manager.openCamera 打开相机startPreviewgetPreviewRequestBuilder 设置预览参数:createCaptureSession 预览准备工作set…...
C++::多态
目录 一.多态的概念 二.多态的定义及实现 二.1多态的构成条件 二.2虚函数 1.虚函数的写法 2.虚函数的重写/覆盖 3.协变 二.3析构函数的重写 二.4override和final关键字 编辑二.5重载/重写/隐藏的对比 三.多态的运行原理(一部分) 四.多态的常…...
278.缀点成线
1232. 缀点成线 - 力扣(LeetCode) class Solution {public boolean checkStraightLine(int[][] coordinates) {if(coordinates.length2){return true;}int xcoordinates[1][0]-coordinates[0][0];int ycoordinates[1][1]-coordinates[0][1];for(int i1;i…...