AI大模型学习之模型选择及环境创建

张开发
2026/4/19 22:48:39 15 分钟阅读

分享文章

AI大模型学习之模型选择及环境创建
1 模型选择DeepSeek-R1-Distill-Qwen-7B 用4-bit量化把模型“塞”进内存只需4GB内存即可。选 DeepSeek-R1-Distill-Qwen-7B​ 主要是冲着它“小身材、大智慧”的极致性价比去的核心原因可以总结为这三点1推理能力“越级”它是用 DeepSeek-R1对标 OpenAI-o1 的强推理模型蒸馏出来的。虽然只有 7B 参数但在数学推导、代码生成和逻辑拆解上表现远超同尺寸的 Llama 3 或普通 Qwen 2.5甚至能逼近 13B-32B 模型的水平 。2硬件门槛极低你的环境搞定了 4-bit 量化这个模型量化后体积很小约 4-5GB消费级显卡甚至大显存核显就能流畅跑完全不需要昂贵的专业卡 。3中文与逻辑兼顾基于 Qwen 架构中文理解很扎实而且继承了 R1 的“思维链”能力回答问题会分步推导不容易胡说八道特别适合处理需要逻辑的本地任务2 环境创建创建Anaconda环境conda create -n ds7b python3.10安装关键库pip install transformers accelerate bitsandbytes3 测试环境通不通先用Qwen2.5-0.5B 小模型测试验证bitsandbytes是否支持4-bit。Qwen2.5-0.5B只有 5 亿参数体量极小主要用来验证你的 Python 环境、CUDA 和 transformers 库能不能正常工作基本没有复杂的逻辑推理能力。# 先用Qwen2.5-0.5B 小模型测试importosfromtransformersimportAutoModelForCausalLM,AutoTokenizer,BitsAndBytesConfigimporttorchfromhuggingface_hubimportsnapshot_download# 1. 网络设置 # 强制使用国内镜像修正填入正确的镜像地址os.environ[HF_ENDPOINT]https://hf-mirror.com# 从链接内容获得# 强制 huggingface_hub 工具走镜像 (解决 tokenizer 加载报错)os.environ[HF_HUB_ENABLE_HF_TRANSFER]0# 1. 模型路径与本地缓存 model_pathQwen/Qwen2.5-0.5B-Instructlocal_model_path./models/Qwen2.5-0.5B-Instruct# 本地模型目录需提前下载# 确保本地模型目录存在如果没有先下载ifnotos.path.exists(local_model_path):print(本地模型不存在开始下载...)snapshot_download(repo_idmodel_path,local_dirlocal_model_path,local_files_onlyFalse,# 首次下载需要联网)print(本地模型下载完成)# 3. 量化配置 # 使用 BitsAndBytesConfig 定义量化参数比 load_in_4bitTrue 更稳定quantization_configBitsAndBytesConfig(load_in_4bitTrue,# 开启4-bit量化bnb_4bit_quant_typenf4,# 量化类型bnb_4bit_use_double_quantTrue,# 双重量化bnb_4bit_compute_dtypetorch.float16,# 计算精度)# 3. 加载模型本地 print(正在加载 4-bit 量化模型...)modelAutoModelForCausalLM.from_pretrained(local_model_path,# 用本地路径quantization_configquantization_config,device_mapauto,trust_remote_codeTrue,)print(f✅ 4-bit 量化模型加载成功)print(f内存占用:{model.get_memory_footprint()/1024**3:.2f}GB)# 4. 加载分词器本地 print(\n正在加载分词器...)tokenizerAutoTokenizer.from_pretrained(local_model_path,# 用本地路径trust_remote_codeTrue,local_files_onlyTrue,# 强制本地)print(✅ 分词器加载成功)# 5. 测试推理 input_text你好请介绍一下你自己。inputstokenizer(input_text,return_tensorspt)withtorch.no_grad():outputsmodel.generate(**inputs,max_new_tokens50)responsetokenizer.decode(outputs[0],skip_special_tokensTrue)print(f\n测试对话:)print(f用户:{input_text})print(f模型:{response})运行日志;(ds7b)D:\prj\open\ds7b-4bitD:/softs/anaconda/envs/ds7b/python.exe d:/prj/open/ds7b-4bit/test.py 本地模型不存在开始下载...Fetching10files:100%|██████████████████████████████████████████████████████████████|10/10[00:0600:00,1.43it/s]Download complete::11.5MB[00:06,2.54MB/s]本地模型下载完成|8/10[00:0600:01,1.15it/s]正在加载4-bit 量化模型...Download complete::11.5MB[00:07,1.51MB/s]Loading weights:0%||0/290[00:00?,?it/s]D:\softs\anaconda\envs\ds7b\lib\site-packages\bitsandbytes\backends\default\ops.py:223:FutureWarning:_check_is_size will be removedina future PyTorch release alongwithguard_size_oblivious.Use _check(i0)instead.torch._check_is_size(blocksize)D:\softs\anaconda\envs\ds7b\lib\site-packages\bitsandbytes\backends\cpu\ops.py:36:FutureWarning:_check_is_size will be removedina future PyTorch release alongwithguard_size_oblivious.Use _check(i0)instead.torch._check_is_size(blocksize)Loading weights:100%|██████████████████████████████████████████████████████████████|290/290[00:2600:00,10.76it/s]✅4-bit 量化模型加载成功 内存占用:0.42GB 正在加载分词器...✅ 分词器加载成功 D:\softs\anaconda\envs\ds7b\lib\site-packages\bitsandbytes\backends\cpu\ops.py:80:FutureWarning:_check_is_size will be removedina future PyTorch release alongwithguard_size_oblivious.Use _check(i0)instead.torch._check_is_size(blocksize)D:\softs\anaconda\envs\ds7b\lib\site-packages\bitsandbytes\backends\cpu\ops.py:132:FutureWarning:_check_is_size will be removedina future PyTorch release alongwithguard_size_oblivious.Use _check(i0)instead.torch._check_is_size(blocksize)测试对话:用户:你好请介绍一下你自己。 模型:你好我叫人工智能是一种计算机程序或系统可以执行特定的任务和功能。我的主要目标是提供信息、协助决策、解决问题和实现各种任务。 我是如何工作的 我的工作方式主要是通过机器学习和深度4bit环境测试通过可以看到用1GB内存的cpu就可以跑。下载的Qwen2.5-0.5B-Instruct的所在路径在该python脚本所存在目录下的models/Qwen2.5-0.5B-Instruct4 最终学习模型下载既然 Qwen2.5-0.5B-Instruct 已经跑通验证了环境那我们就按计划进入“解剖 DeepSeek-R1-Distill-Qwen-7B 源码”​ 的学习阶段。从 0.5B 切换到 7B将第2节的test.py代码中的模型标识符从 Qwen/Qwen2.5-0.5B-Instruct换成目标模型# 将这两行model_pathQwen/Qwen2.5-0.5B-Instructlocal_model_path./model/Qwen2.5-0.5B-Instruct# 改为model_pathdeepseek-ai/DeepSeek-R1-Distill-Qwen-7Blocal_model_path./model/DeepSeek-R1-Distill-Qwen-7B完整如下# 先用Qwen2.5-0.5B 小模型测试 验证bitsandbytes是否支持4-bitimportosfromtransformersimportAutoModelForCausalLM,AutoTokenizer,BitsAndBytesConfigimporttorchfromhuggingface_hubimportsnapshot_download# 1. 网络设置 # 强制使用国内镜像修正填入正确的镜像地址os.environ[HF_ENDPOINT]https://hf-mirror.com# 从链接内容获得# 强制 huggingface_hub 工具走镜像 (解决 tokenizer 加载报错)os.environ[HF_HUB_ENABLE_HF_TRANSFER]0# 1. 模型路径与本地缓存 # model_path Qwen/Qwen2.5-0.5B-Instruct# local_model_path ./models/Qwen2.5-0.5B-Instructmodel_pathdeepseek-ai/DeepSeek-R1-Distill-Qwen-7Blocal_model_path./models/DeepSeek-R1-Distill-Qwen-7B# 确保本地模型目录存在如果没有先下载ifnotos.path.exists(local_model_path):print(本地模型不存在开始下载...)snapshot_download(repo_idmodel_path,local_dirlocal_model_path,local_files_onlyFalse,# 首次下载需要联网)print(本地模型下载完成)# 3. 量化配置 # 使用 BitsAndBytesConfig 定义量化参数比 load_in_4bitTrue 更稳定quantization_configBitsAndBytesConfig(load_in_4bitTrue,# 开启4-bit量化bnb_4bit_quant_typenf4,# 量化类型bnb_4bit_use_double_quantTrue,# 双重量化bnb_4bit_compute_dtypetorch.float16,# 计算精度)# 3. 加载模型本地 print(正在加载 4-bit 量化模型...)modelAutoModelForCausalLM.from_pretrained(local_model_path,# 用本地路径quantization_configquantization_config,device_mapauto,trust_remote_codeTrue,)print(f✅ 4-bit 量化模型加载成功)print(f内存占用:{model.get_memory_footprint()/1024**3:.2f}GB)# 4. 加载分词器本地 print(\n正在加载分词器...)tokenizerAutoTokenizer.from_pretrained(local_model_path,# 用本地路径trust_remote_codeTrue,local_files_onlyTrue,# 强制本地)print(✅ 分词器加载成功)# # 5. 测试推理:该版本输出会把输入也输出 # input_text 你好请介绍一下你自己。# inputs tokenizer(input_text, return_tensorspt)# with torch.no_grad():# outputs model.generate(**inputs, max_new_tokens50)# response tokenizer.decode(outputs[0], skip_special_tokensTrue)# print(f\n测试对话:)# print(f用户: {input_text})# print(f模型: {response})# 6. 测试推理修正版 input_text你好请介绍一下你自己。# 1. 对输入进行分词并移动到模型所在设备inputstokenizer(input_text,return_tensorspt).to(model.device)# 2. 生成输出withtorch.no_grad():outputsmodel.generate(**inputs,max_new_tokens50)# 3. 关键修复切片去除输入部分只保留新生成的 tokens# outputs[0] 是整个序列inputs.input_ids.shape[1] 是输入长度generated_tokensoutputs[0][inputs.input_ids.shape[1]:]# 4. 仅解码新生成的部分responsetokenizer.decode(generated_tokens,skip_special_tokensTrue)print(f\n测试对话:)print(f用户:{input_text})print(f模型:{response})运行日志(ds7b)D:\prj\open\ds7b-4bitD:/softs/anaconda/envs/ds7b/python.exe d:/prj/open/ds7b-4bit/test.py 本地模型不存在开始下载...Downloading(incomplete total...):1%|▍|176M/15.2G[03:463:58:24,1.05MB/s]Fetching11files:45%|████████████████████████████▋|5/11[00:0400:04,1.35it/s]等待模型下载完成执行推理测试即可。

更多文章