求助:safety_checker文件缺失及Torch未编译CUDA的技术问题
问题描述
运行基于FastAPI的Stable Diffusion代码时遇到两个错误:
safety_checker\model.safetensors not foundAssertionError: Torch not compiled with CUDA enabled
运行代码
from auth_token import auth_token from fastapi import FastAPI, Response from fastapi.middleware.cors import CORSMiddleware import torch from torch import autocast from diffusers import StableDiffusionPipeline from io import BytesIO import base64 app = FastAPI() app.add_middleware( CORSMiddleware, allow_credentials=True, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"] ) device = "cuda" model_id = "CompVis/stable-diffusion-v1-4" pipe = StableDiffusionPipeline.from_pretrained(model_id, revision="fp16", torch_dtype=torch.float16, use_auth_token=auth_token) pipe.to(device) @app.get("/") def generate(prompt: str): with autocast(device): image = pipe(prompt, guidance_scale=8.5).images[0] image.save("testimage.png") buffer = BytesIO() image.save(buffer, format="PNG") imgstr = base64.b64encode(buffer.getvalue()) return Response(content=imgstr, media_type="image/png")
完整报错信息
safety_checker\model.safetensors not found Loading pipeline components...: 71%|█████████████████████████████████████████████████████████████████████████████▊ | 5/7 [00:01<00:00, 3.89it/s]C:\Users\mouba\AppData\Roaming\Python\Python311\site-packages\transformers\models\clip\feature_extraction_clip.py:28: FutureWarning: The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please use CLIPImageProcessor instead. warnings.warn( `text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The value `text_config["id2label"]` will be overriden. `text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The value `text_config["bos_token_id"]` will be overriden. `text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The value `text_config["eos_token_id"]` will be overriden. Loading pipeline components...: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████| 7/7 [00:01<00:00, 3.63it/s] Traceback (most recent call last): File "g:\Projects\Code-That-ReactStableDiffusion-main\api\api.py", line 23, in <module> pipe.to(device) File "C:\Users\mouba\AppData\Roaming\Python\Python311\site-packages\diffusers\pipelines\pipeline_utils.py", line 727, in to module.to(torch_device, torch_dtype) File "C:\Users\mouba\AppData\Roaming\Python\Python311\site-packages\torch\nn\modules\module.py", line 1145, in to return self._apply(convert) ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\mouba\AppData\Roaming\Python\Python311\site-packages\torch\nn\modules\module.py", line 797, in _apply module._apply(fn) File "C:\Users\mouba\AppData\Roaming\Python\Python311\site-packages\torch\nn\modules\module.py", line 797, in _apply module._apply(fn) File "C:\Users\mouba\AppData\Roaming\Python\Python311\site-packages\torch\nn\modules\module.py", line 820, in _apply param_applied = fn(param) ^^^^^^^^^ File "C:\Users\mouba\AppData\Roaming\Python\Python311\site-packages\torch\nn\modules\module.py", line 1143, in convert return t.to(device, dtype if t.is_floating_point() or t.is_complex() else None, non_blocking) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\mouba\AppData\Roaming\Python\Python311\site-packages\torch\cuda\__init__.py", line 239, in _lazy_init raise AssertionError("Torch not compiled with CUDA enabled") AssertionError: Torch not compiled with CUDA enabled
解决方案
1. 解决safety_checker\model.safetensors not found错误
这个错误是安全检查器权重文件缺失,有两种处理方式:
禁用安全检查器:初始化
StableDiffusionPipeline时添加safety_checker=None参数,跳过该组件加载,修改代码如下:pipe = StableDiffusionPipeline.from_pretrained( model_id, revision="fp16", torch_dtype=torch.float16, use_auth_token=auth_token, safety_checker=None # 新增该行 )重新下载完整模型:删除本地模型缓存目录(通常在
C:\Users\你的用户名\.cache\huggingface\hub下的CompVis/stable-diffusion-v1-4文件夹),重新运行代码让diffusers自动下载完整权重。
2. 解决AssertionError: Torch not compiled with CUDA enabled错误
该错误说明当前PyTorch版本不支持CUDA,按以下步骤处理:
卸载现有PyTorch:
pip uninstall torch torchvision torchaudio安装带CUDA支持的PyTorch:根据你的NVIDIA显卡CUDA版本(通过
nvidia-smi查看),安装对应版本。例如CUDA 11.8版本运行:pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118验证CUDA是否启用:运行
python -c "import torch; print(torch.cuda.is_available())",输出True则说明成功。无NVIDIA显卡的处理:将代码中
device = "cuda"改为device = "cpu",同时移除revision="fp16"和torch_dtype=torch.float16参数(CPU不支持半精度运算),修改后代码:device = "cpu" model_id = "CompVis/stable-diffusion-v1-4" pipe = StableDiffusionPipeline.from_pretrained(model_id, use_auth_token=auth_token, safety_checker=None) pipe.to(device)
内容的提问来源于stack exchange,提问作者131 Mohammad Ubaida
相关产品推荐
相关产品推荐

