GStreamer 开发手册:从 pipeline 到 caps 协商与性能调优
2026/10/21 8:56:39
在使用 Hugging Face Transformers 库下载或加载模型时,遇到以下错误:
PermissionError: [Errno 13] Permission denied: '/root/.cache/huggingface/hub/models--xxx--xxx-model/snapshots'这个错误通常由以下原因引起:
# 查看缓存目录权限ls-la /root/.cache/huggingface/# 更改缓存目录所有权(需要 root 权限)sudochown-R$USER:$USER/root/.cache/huggingface/# 或更改到当前用户的主目录rm-rf /root/.cache/huggingface/mkdir-p ~/.cache/huggingface/exportHUGGINGFACE_HUB_CACHE=~/.cache/huggingface/# 设置环境变量# Linux/MacexportHUGGINGFACE_HUB_CACHE=/path/to/custom/cache# WindowssetHUGGINGFACE_HUB_CACHE=C:\path\to\custom\cache# 或在 Python 代码中设置importos os.environ["HUGGINGFACE_HUB_CACHE"]="/path/to/custom/cache"cache_dir参数fromtransformersimportAutoTokenizer,AutoModelForCausalLM# 使用自定义缓存目录tokenizer=AutoTokenizer.from_pretrained("facebook/opt-1.3b",cache_dir="./custom_cache")model=AutoModelForCausalLM.from_pretrained("facebook/opt-1.3b",cache_dir="./custom_cache")# 检查磁盘空间df-h# 清理不必要的文件sudoapt-getcleanrm-rf ~/.cache/*# 在 Dockerfile 中设置RUNmkdir-p /app/cache&&chmod777/app/cache ENVHUGGINGFACE_HUB_CACHE=/app/cache# 或在运行容器时挂载卷dockerrun -v ~/.cache/huggingface:/root/.cache/huggingface your-image# 检查当前用户whoami# 切换到正确的用户su- your-user# 或使用 sudo 运行(不推荐,可能导致权限问题)sudo-u your-user python your-script.py# 清理缓存目录rm-rf ~/.cache/huggingface/# 重建缓存目录并设置权限mkdir-p ~/.cache/huggingface/chmod755~/.cache/huggingface/importosimportsubprocessfromtransformersimportAutoTokenizer,AutoModelForCausalLMdefcheck_cache_permissions():"""检查缓存目录权限"""# 获取默认缓存目录default_cache=os.path.expanduser("~/.cache/huggingface/")print(f"Default cache directory:{default_cache}")# 检查目录是否存在ifos.path.exists(default_cache):print("Cache directory exists")# 检查权限try:test_file=os.path.join(default_cache,"test_permission.txt")withopen(test_file,"w")asf:f.write("test")os.remove(test_file)print("Write permission: OK")returnTrueexceptExceptionase:print(f"Write permission error:{e}")returnFalseelse:print("Cache directory does not exist")# 创建目录try:os.makedirs(default_cache,exist_ok=True)print("Cache directory created")returnTrueexceptExceptionase:print(f"Error creating cache directory:{e}")returnFalsedefload_model_with_cache(model_name,custom_cache=None):"""加载模型,处理缓存权限问题"""try:print(f"Loading model:{model_name}")# 使用自定义缓存目录ifcustom_cache:print(f"Using custom cache directory:{custom_cache}")# 确保目录存在os.makedirs(custom_cache,exist_ok=True)tokenizer=AutoTokenizer.from_pretrained(model_name,cache_dir=custom_cache)model=AutoModelForCausalLM.from_pretrained(model_name,cache_dir=custom_cache)else:# 使用默认缓存目录tokenizer=AutoTokenizer.from_pretrained(model_name)model=AutoModelForCausalLM.from_pretrained(model_name)print("Model loaded successfully")returntokenizer,modelexceptPermissionErrorase:print(f"PermissionError:{e}")# 尝试使用自定义缓存目录custom_cache=os.path.join(os.getcwd(),"hf_cache")print(f"Trying with custom cache directory:{custom_cache}")returnload_model_with_cache(model_name,custom_cache)exceptExceptionase:print(f"Error loading model:{e}")returnNone,Nonedeftest_model(tokenizer,model):"""测试模型"""ifnottokenizerornotmodel:print("Tokenizer or model not loaded")returntry:inputs=tokenizer("Hello, ",return_tensors="pt")outputs=model.generate(**inputs,max_new_tokens=20)print(f"Generated text:{tokenizer.decode(outputs[0],skip_special_tokens=True)}")returnTrueexceptExceptionase:print(f"Error testing model:{e}")returnFalse# 使用示例if__name__=="__main__":# 检查缓存权限print("Checking cache permissions...")check_cache_permissions()# 加载模型model_name="facebook/opt-1.3b"tokenizer,model=load_model_with_cache(model_name)# 测试模型iftokenizerandmodel:print("\nTesting model...")test_model(tokenizer,model)else:print("Failed to load model")A: 这通常是因为当前用户没有权限访问或修改 Hugging Face 缓存目录,或者缓存目录的所有权属于其他用户。
A: 使用ls -la /path/to/cache/directory命令查看目录权限和所有权。
A: 设置HUGGINGFACE_HUB_CACHE环境变量到一个你有权限的目录。
A: 在 Dockerfile 中设置正确的缓存目录和权限,或者在运行容器时挂载卷。
cache_dir参数是个好选择?A: 使用cache_dir参数可以指定一个你有权限的目录,避免权限问题,同时也便于管理模型缓存。
遇到PermissionError: [Errno 13] Permission denied: '/root/.cache/huggingface/hub/models--xxx--xxx-model/snapshots'错误时,主要需要:
cache_dir参数指定缓存位置通过以上解决方案,大部分情况下都能成功解决权限问题,顺利下载和加载 Hugging Face 模型。