问题
在模型加载的时候,我们会观察到 trust_remote_code这个参数
model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto",
torch_dtype=torch.bfloat16,
trust_remote_code=True)
从名字上看,就是相信远程代码.如果我们的模型是完全下载到本地的,哪里来的远程代码呢?
解释
我们使用Transformer加载模型的时候,一般下载的文件只有权重文件(.bin、 .safetensors)、配置(config.json)、tokenizer.json 等静态资源,不一定列出对应的自定义 modeling_*.py 源码文件
py文件用于指定模型是怎么运行的,如果是Transformer框架里面自带的类,就不需要另外下载远程py文件,
例子
一个典型例子就是你现在看的 Qwen3-30B-A3B 这类模型,它在仓库里自带了自定义的 Python 源码(例如自定义的 Qwen3MoeForCausalLM 模型类、注意力层、MoE 结构等),因此必须依赖 trust_remote_code=True 才能正常加载这些类。
但是我们通过浏览https://modelscope.cn/models/Qwen/Qwen3-30B-A3B/files
也没有发现对应的py文件,那是因为py文件并没有通过modelscope开放.
我们怎么看到py文件??
想看源码可以怎么做
在本地先用:
AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-30B-A3B", trust_remote_code=True)
载入一次模型。
载入完成后,到本机的缓存目录下(如 Hugging Face 对应
~/.cache/huggingface/modules/transformers_modules/
,ModelScope 也有类似目录)去找包含 qwen3_moe、Qwen3MoeForCausalLM 等名字的 .py 文件,就能看到真正的实现。
在无网络机器部署
在没有外网的环境部署这类需要下载远程 Python 代码的模型,思路是:
在有网环境:
用 trust_remote_code=True 正常 from_pretrained 一次,把模型、tokenizer 和远程代码都拉进本机缓存。
然后用 save_pretrained()(或直接 git clone 模型仓库)把权重、配置和代码保存到你自己的目录或镜像仓库里。
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "Qwen/Qwen3-30B-A3B" # 也可以是 modelscope 对应的 id
tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True)
save_dir = "./qwen3-30b-a3b-offline"
tok.save_pretrained(save_dir)
model.save_pretrained(save_dir)
在无网环境:
拷贝这个目录到离线机器。
用 from_pretrained("本地路径", trust_remote_code=True, local_files_only=True) 这样的方式加载,只从本地读文件,不再访问外网。
from transformers import AutoModelForCausalLM, AutoTokenizer
local_dir = "/path/to/qwen3-30b-a3b-offline"
tok = AutoTokenizer.from_pretrained(
local_dir,
trust_remote_code=True,
local_files_only=True,
)
model = AutoModelForCausalLM.from_pretrained(
local_dir,
trust_remote_code=True,
local_files_only=True,
)
local_files_only=True 确保完全离线,如果少文件会直接报错而不是悄悄访问外网。