微信扫码
添加专属顾问
手把手教你用Colab免费微调Qwen3-4B模型,轻松实现本地大模型部署! 核心内容: 1. 详细的环境配置与GPU资源检查步骤 2. 从下载模型到启动服务的完整流程 3. 数据集构建与模型验证的关键操作
pip install unsloth -i https://pypi.tuna.tsinghua.edu.cn/simple
import torchdef print_cuda_info():try:print("-" * 40)print("PyTorch CUDA Environment Information:")print("-" * 40)if torch.cuda.is_available():device_count = torch.cuda.device_count()print(f"Number of CUDA devices: {device_count}")if device_count > 0:device_name = torch.cuda.get_device_name(0)print(f"0th CUDA Device Name: {device_name}")total_memory = torch.cuda.get_device_properties(0).total_memoryallocated_memory = torch.cuda.memory_allocated(0)free_memory = total_memory - allocated_memoryprint(f"Total Memory: {total_memory / (1024 ** 3):.2f} GB")print(f"Allocated Memory: {allocated_memory / (1024 ** 3):.2f} GB")print(f"Free Memory: {free_memory / (1024 ** 3):.2f} GB")else:print("No CUDA devices found.")else:print("CUDA is not available.")print("-" * 40)except Exception as e:print("-" * 40)print(f"An error occurred: {e}")print("-" * 40)if __name__ == "__main__":print_cuda_info()
curl -fsSL https://ollama.com/install.sh | sh
ollama serve &
ollama pull qwen3:4B
(下载完成后需结束当前运行进程)
from unsloth import FastLanguageModelfrom datasets import load_datasetimport torch# 配置max_seq_length = 2048load_in_4bit = True # 4bit量化# 从 Hugging Face Hub 加载模型和分词器model, tokenizer = FastLanguageModel.from_pretrained("Qwen/Qwen3-4B-Instruct-2507", # 模型名称max_seq_length=max_seq_length,load_in_4bit=load_in_4bit,trust_remote_code=True # Qwen模型需此参数)# 配置 LoRA 适配器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",random_state=3407,use_rslora=False,loftq_config=None,)EOS_TOKEN = tokenizer.eos_token# 加载数据集(需修改为你的数据集路径)dataset = load_dataset("json", data_files="/content/noli.json", split="train")# 查看数据集信息print("数据集样例:", dataset[0])print("数据集大小:", len(dataset))
# 导入必要的库from unsloth import FastLanguageModelfrom datasets import load_dataset, Datasetfrom trl import SFTTrainerfrom transformers import TrainingArgumentsfrom unsloth import is_bfloat16_supportedimport torch# --- 1. 模型和分词器加载 ---print("正在加载模型和分词器...")model, tokenizer = FastLanguageModel.from_pretrained(model_name="Qwen/Qwen3-4B-Instruct-2507",max_seq_length=2048,load_in_4bit=True,trust_remote_code=True # Qwen 模型需要此参数)print("模型和分词器加载完成。")# --- 2. LoRA 配置 ---print("正在配置LoRA适配器...")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",random_state=3407,use_rslora=False,loftq_config=None,)print("LoRA适配器配置完成。")# --- 3. 数据集加载 ---print("正在加载数据集...")raw_dataset = load_dataset("json", data_files="/content/NOLI.json", split="train") # 修改为你的数据集路径print(f"原始数据集加载完成。数据集大小: {len(raw_dataset)}")print("原始数据集样例:", raw_dataset[0])# --- 4. 预处理数据集:添加 'text' 列 ---def create_text_column(example):"""将单个样本格式化为模型训练所需的文本格式。"""# 安全地获取字段,确保是字符串instruction = str(example.get("instruction", "")).strip()input_text = str(example.get("input", "")).strip()output_text = str(example.get("output", "")).strip()# 构建用户部分if input_text:user_content = f"{instruction}\n{input_text}"else:user_content = instruction# 构建完整的提示(符合Qwen3对话格式)full_prompt = (f"<|im_start|>user\n{user_content}<|im_end|>\n"f"<|im_start|>assistant\n{output_text}<|im_end|>")return {"text": full_prompt}print("正在预处理数据集,添加 'text' 列...")# 使用 map 函数为数据集中的每个样本添加 'text' 列dataset = raw_dataset.map(create_text_column)print("数据集预处理完成。")print("处理后数据集样例:", dataset[0])# --- 5. 配置并创建 SFTTrainer ---print("正在配置SFTTrainer...")trainer = SFTTrainer(model=model,tokenizer=tokenizer,train_dataset=dataset, # 使用预处理后的数据集dataset_text_field="text", # 指定使用 'text' 列max_seq_length=2048,dataset_num_proc=2,packing=False, # 此格式下禁用packingargs=TrainingArguments(per_device_train_batch_size=2,gradient_accumulation_steps=4,warmup_steps=5,max_steps=100, # 可根据需求调整训练步数learning_rate=2e-4,fp16=not is_bfloat16_supported(),bf16=is_bfloat16_supported(),logging_steps=5,optim="adamw_8bit",output_dir="./qwen_finetune_output_v2",overwrite_output_dir=True,report_to="none", # 禁用外部日志记录seed=3407,),)print("SFTTrainer配置完成。")# --- 6. 开始训练 ---print("开始训练...")trainer.train()print("训练完成。")# --- 7. 保存 LoRA 权重 ---print("正在保存LoRA适配器权重...")model.save_pretrained("./lora_adapters_v2")tokenizer.save_pretrained("./lora_adapters_v2") # 同时保存分词器配置print("LoRA适配器已保存到 './lora_adapters_v2' 目录。")
# 导入必要的库from unsloth import FastLanguageModelimport torchfrom peft import PeftModel # 用于加载和合并LoRA权重# --- 1. 加载基础模型(非4bit量化,用于完整权重合并)---print("正在加载基础模型...")model, tokenizer = FastLanguageModel.from_pretrained(model_name="Qwen/Qwen3-4B-Instruct-2507",max_seq_length=2048,load_in_4bit=False, # 加载完整精度模型trust_remote_code=True)print("基础模型加载完成。")# --- 2. 加载 LoRA 适配器 ---print("正在加载LoRA适配器...")model = PeftModel.from_pretrained(model=model,model_id="/content/lora_adapters_v2" # LoRA权重保存路径)print("LoRA适配器加载完成。")# --- 3. 合并 LoRA 权重到基础模型 ---print("正在合并LoRA权重到基础模型...")model = model.merge_and_unload() # 执行权重合并print("权重合并完成。")# --- 4. 保存完整模型(32位和16位)---print("正在保存完整模型...")# 保存为32位完整模型(高精度,体积较大)model.save_pretrained("./qwen_merged_full_model")tokenizer.save_pretrained("./qwen_merged_full_model")# 保存为16位模型(平衡精度与体积)model.save_pretrained("./qwen_merged_full_model_16bit", torch_dtype=torch.float16)tokenizer.save_pretrained("./qwen_merged_full_model_16bit")print("完整模型保存完成!")print("32位模型保存路径:./qwen_merged_full_model")print("16位模型保存路径:./qwen_merged_full_model_16bit")
from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamerimport torchfrom typing import List, Tuplefrom threading import Thread# --- 1. 加载模型和分词器 ---model_path = "./qwen_merged_full_model_16bit" # 16位模型路径print(f"正在加载模型: {model_path}...")tokenizer = AutoTokenizer.from_pretrained(model_path,trust_remote_code=True,padding_side="left")# 确保pad_token存在(使用eos_token作为pad_token)if tokenizer.pad_token is None:tokenizer.pad_token = tokenizer.eos_tokenmodel = AutoModelForCausalLM.from_pretrained(model_path,torch_dtype=torch.float16,device_map="auto", # 自动分配设备(优先GPU)trust_remote_code=True)model.eval() # 推理模式print("模型加载完成,可开始对话。")# --- 2. 自定义流式输出器(仅打印新生成内容)---class CurrentResponseStreamer(TextStreamer):def __init__(self, tokenizer, input_prompt_length: int, skip_prompt: bool = True, **decode_kwargs):super().__init__(tokenizer, skip_prompt=skip_prompt, **decode_kwargs)self.input_prompt_length = input_prompt_lengthself.first_token = Truedef on_finalized_text(self, text: str, stream_end: bool = False):if self.first_token:print("Noli: ", end="", flush=True)self.first_token = Falseprint(text, end="", flush=True)if stream_end:print() # 结束时换行# --- 3. 流式生成函数 ---def generate_response_streaming(conversation_history: List[Tuple[str, str]]):"""根据对话历史生成流式响应,并返回完整响应文本"""# 构建完整对话promptprompt = ""for role, content in conversation_history:if role == "user":prompt += f"<|im_start|>user\n{content}<|im_end|>\n"else:prompt += f"<|im_start|>assistant\n{content}<|im_end|>\n"prompt += f"<|im_start|>assistant\n" # 启动助手回复生成# 计算输入prompt的token长度input_ids = tokenizer(prompt, return_tensors="pt")["input_ids"]input_prompt_length = input_ids.shape[1]# 移动输入到模型设备inputs = {"input_ids": input_ids.to(model.device),"attention_mask": tokenizer(prompt, return_tensors="pt")["attention_mask"].to(model.device),}# 初始化流式输出器streamer = CurrentResponseStreamer(tokenizer,input_prompt_length=input_prompt_length,skip_special_tokens=True)# 启动流式生成(独立线程)generation_kwargs = dict(**inputs,max_new_tokens=512,temperature=0.7,top_p=0.9,repetition_penalty=1.1,eos_token_id=tokenizer.eos_token_id,pad_token_id=tokenizer.pad_token_id,do_sample=True,streamer=streamer)thread = Thread(target=model.generate, kwargs=generation_kwargs)thread.start()thread.join() # 等待生成完成# 生成完整响应文本(用于更新对话历史)with torch.no_grad():outputs = model.generate(**inputs,max_new_tokens=512,temperature=0.7,top_p=0.9,repetition_penalty=1.1,eos_token_id=tokenizer.eos_token_id,pad_token_id=tokenizer.pad_token_id,do_sample=True)# 仅解码新生成的部分generated_ids = outputs[:, inputs['input_ids'].shape[1]:]full_response = tokenizer.decode(generated_ids[0], skip_special_tokens=True)return full_response# --- 4. 对话主程序 ---if __name__ == "__main__":conversation_history: List[Tuple[str, str]] = []print("你好!我是诺丽,一个AI助手。输入'退出'即可结束对话。")while True:try:user_input = input("\n你: ").strip()if not user_input:continueif user_input.lower() in ["退出", "quit", "exit"]:print("Noli: 再见!很高兴与你交谈。")break# 更新对话历史conversation_history.append(("user", user_input))# 流式生成响应current_response = generate_response_streaming(conversation_history)# 保存完整响应到历史conversation_history.append(("assistant", current_response))except KeyboardInterrupt:print("\n\nNoli: 看起来你中断了对话。再见!")breakexcept Exception as e:print(f"\nNoli: 抱歉,处理你的请求时出现了错误: {e}")
解决办法:重启 Colab 会话(菜单栏 -> Runtime -> Restart session)
from google.colab import driveimport osimport shutil# 1. 挂载 Google 云盘print("正在挂载 Google 云盘...")if not os.path.ismount('/content/drive'):drive.mount('/content/drive')print("Google 云盘已挂载。")else:print("Google 云盘已挂载。")# 2. 定义路径(可修改目标路径)source_dir_path = '/content/lora_adapters_v2' # LoRA权重源路径destination_folder_path = '/content/drive/MyDrive/lora' # 云盘目标文件夹destination_dir_path = os.path.join(destination_folder_path, os.path.basename(source_dir_path))# 配置:是否覆盖已存在的目标目录OVERWRITE_EXISTING = True# 3. 创建目标文件夹(若不存在)os.makedirs(destination_folder_path, exist_ok=True)print(f"目标备份文件夹: {destination_folder_path}")# 4. 检查源目录有效性if not os.path.exists(source_dir_path) or not os.path.isdir(source_dir_path):print(f"❌ 错误:源目录不存在或不是目录 - {source_dir_path}")else:try:# 计算源目录大小source_size_mb = sum(os.path.getsize(os.path.join(dirpath, filename))for dirpath, dirnames, filenames in os.walk(source_dir_path)for filename in filenames) / (1024 * 1024)print(f"✅ 找到源目录: {source_dir_path} (估算大小: {source_size_mb:.2f} MB)")# 处理目标目录已存在的情况if os.path.exists(destination_dir_path):dest_size_mb = sum(os.path.getsize(os.path.join(dirpath, filename))for dirpath, dirnames, filenames in os.walk(destination_dir_path)for filename in filenames) / (1024 * 1024)print(f"⚠️ 警告:目标目录已存在 - {destination_dir_path} (估算大小: {dest_size_mb:.2f} MB)")if OVERWRITE_EXISTING:print("正在删除旧目录以覆盖...")shutil.rmtree(destination_dir_path)print("旧目录已删除。")else:print("OVERWRITE_EXISTING=False,跳过复制。")print("如需覆盖,请将 OVERWRITE_EXISTING 设为 True。")# 复制目录到云盘if OVERWRITE_EXISTING or not os.path.exists(destination_dir_path):print(f"正在复制目录到云盘...")print(f" 源: {source_dir_path}")print(f" 目标: {destination_dir_path}")shutil.copytree(source_dir_path, destination_dir_path)print(f"✅ 目录已备份到云盘: {destination_dir_path}")else:print("操作已取消或跳过。")except Exception as e:print(f"❌ 复制错误: {e}")
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业
2026-06-19
从 BERT 标注到 Agent Skill:短文本标签体系的四次“工业革命”
2026-05-14
多轮 Agent 场景下,滴滴的 EAGLE-3 训推加速实践
2026-05-06
谁说 Mac 只能写代码?Google 官宣:M 芯片本地微调 Gemma 4 时代开启!
2026-04-20
用 Unsloth 微调 Embedding 模型,让你的 RAG 检索不再答非所问
2026-04-15
ComfyUI v0.19.0 更新:大量新节点、新模型、新修复与性能优化全面落地,工作流与训练能力再升级
2026-04-13
Agent 持续学习落地路径:先做 Traces,再做 Context,最后才微调模型 | Jinqiu Select
2026-03-23
养死四只龙虾的小白有感
2026-03-22
Mistral Forge 的真正意义:企业AI从“租用”走向“拥有”
2026-04-15
2026-04-13
2026-04-20
2026-05-06
2026-05-14
2026-06-19
2026-01-02
2025-11-19
2025-09-25
2025-06-20
2025-06-17
2025-05-21
2025-05-17
2025-05-14
欢迎您使用【53AI 官方网站】(以下简称“本网站”或“我们”)。本《会员服务协议》(以下简称“本协议”)是您(以下简称“会员”或“用户”)与【深圳市博思协创网络科技有限公司】之间关于注册、登录及使用本网站会员服务所订立的法律协议。
在您注册或登录前,请务必审慎阅读、充分理解各条款内容,特别是免除或限制责任的条款、知识产权条款、争议解决条款等。此类条款将以加粗形式提示您注意。 当您通过微信公众号授权、手机验证码验证或其他方式成功登录本网站时,即视为您已完全理解并同意接受本协议的全部内容。
一、 定义
本网站:指由【深圳市博思协创网络科技有限公司】运营的,域名为【53ai.com】的网站及相关移动端页面。
会员服务:指本网站向注册会员提供的知识库文章查阅、内容检索及其他相关增值服务。
知识库内容:指本网站发布的包括但不限于文字、图表、数据、研究报告、行业分析等数字化内容资源。
二、 账号注册与登录
登录方式:本网站支持以下登录方式,您可根据实际情况选择:
微信公众号授权登录:您同意将您的微信OpenID信息授权给本网站,用于创建或关联会员账号。
手机验证码登录:您需提供真实有效的手机号码,并通过短信验证码完成身份验证与登录/注册。
账号安全:您的账号仅限您本人使用,禁止赠与、借用、租用、转让或售卖。因您保管不善导致的账号被盗、密码泄露等损失,由您自行承担。
实名认证:根据相关法律法规要求,我们可能要求您在特定功能下完成实名认证。如您拒绝提供,可能无法使用部分或全部服务。
未成年人保护:若您未满18周岁,请在法定监护人的陪同下阅读本协议,并在征得监护人同意后使用本服务。
三、 服务内容与规范
知识库查阅权限:会员登录后,有权按照其会员等级对应的权限范围,在线浏览、检索本网站知识库中的相关文章及内容。
服务变更:我们有权根据业务发展需要,调整、变更或终止部分服务内容,并将以网站公告、公众号消息等方式提前通知。
禁止行为:您在使用服务时不得实施以下行为:
利用技术手段批量爬取、下载、转存知识库内容;
将知识库内容用于商业目的或未经授权地向第三方传播;
干扰本网站正常运行或侵犯其他用户合法权益;
发布违法违规信息或从事违反公序良俗的活动。
四、 知识产权声明
权利归属:本网站知识库中的排版设计、软件代码等内容的知识产权均归【公司全称】或原权利人所有,受《中华人民共和国著作权法》等法律保护。
有限许可:本网站授予会员一项非独占、不可转让、不可转授权的普通许可,仅限于个人学习、研究之目的在线查阅知识库内容。
侵权追责:未经书面许可,任何单位或个人不得以任何形式复制、转载、摘编、镜像、汇编或以其他方式使用上述内容。一经发现,我们保留追究其法律责任的权利。
五、 个人信息保护
我们重视对您个人信息的保护。关于我们如何收集、使用、存储和保护您的个人信息,请单独阅读 《隐私政策》。
您通过微信公众号授权或手机号验证所提供的信息,我们将严格按照《个人信息保护法》的规定处理,仅用于身份识别、服务提供及安全验证等必要用途。
您可以随时通过网站设置或联系客服行使查阅、更正、删除个人信息及撤回授权同意的权利。
六、 免责声明
内容准确性:知识库内容仅供参考,不构成专业建议。我们不对其完整性、准确性、时效性作任何明示或暗示的保证,您应自行判断并承担使用风险。
不可抗力:因自然灾害、政策法规变化、网络故障、第三方平台接口异常(如微信接口维护、运营商短信通道故障)等不可抗力导致的服务中断或延迟,我们不承担违约责任。
第三方链接:本网站可能包含指向第三方网站的链接,该等网站的内容和服务不受我们控制,请您自行甄别风险。
七、 违约责任
如您违反本协议约定,我们有权视情节采取警告、限制功能、暂停服务、注销账号等措施,并保留要求赔偿损失的权利。
如因您的违约行为导致我们遭受行政处罚、第三方索赔或商誉损失,您应承担全部赔偿责任(包括但不限于罚款、赔偿金、律师费、公证费等)。
八、 法律适用与争议解决
本协议的订立、执行和解释均适用中华人民共和国大陆地区法律。
因本协议产生的或与本协议有关的任何争议,双方应友好协商解决;协商不成的,任何一方均可向【公司所在地】有管辖权的人民法院提起诉讼。
九、 其他
本协议构成双方就本服务达成的完整协议,取代此前任何口头或书面约定。
本协议任一条款被认定为无效或不可执行的,不影响其他条款的效力。
我们对本协议享有最终解释权,并在法律允许的范围内保留随时修改的权利。修改后的协议一经公布即生效,继续使用服务即视为同意修订内容。