M1 Mac环境下PyTorch中torch.Generator不支持MPS设备的替代方案及Stable Diffusion报错解决请求
解决M1 Mac上Stable Diffusion的torch.Generator(MPS)报错问题
嘿,这个问题我之前在M1上跑Stable Diffusion的时候也碰到过,PyTorch对MPS的Generator支持确实还没跟上,不过有两个简单的解决办法,帮你搞定这个报错:
方案一:使用CPU生成器(推荐)
MPS设备目前不支持torch.Generator(device='mps'),但我们可以用CPU的生成器来生成种子,再传递给MPS上的pipe运算,这样既保留了种子的可控性,又能正常使用MPS加速。
只需要把报错的那行代码替换成:
generator = torch.Generator(device='cpu').manual_seed(int(seed))
修改后的完整txt2img函数如下:
def txt2img(prompt, width, height, guidance_scale, steps, seed): global pipe, pipe_type if pipe_type != 'txt2img': pipe = None clear_memory() pipe_type = 'txt2img' pipe = StableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", revision="fp16", torch_dtype=torch.float16, use_auth_token=YOUR_TOKEN # use huggingface token for private model ).to("mps") seed = random.randint(0, 2**32) if seed == -1 else seed # 替换成CPU生成器 generator = torch.Generator(device='cpu').manual_seed(int(seed)) pipe.enable_attention_slicing() with autocast("mps"): image = pipe(prompt=prompt, height=height, width=width, num_inference_steps=steps, guidance_scale=guidance_scale, generator=generator).images[0] return [[image], seed]
这个方案的好处是不需要改动其他逻辑,而且生成的图片随机性完全由你设置的seed控制,和原本的预期一致,实际扩散运算还是在MPS上进行,不会影响速度。
方案二:设置MPS全局种子
如果你不需要多个独立的生成器实例,也可以直接设置MPS的全局种子,这样就不用传递generator参数给pipe了:
- 替换报错的生成器代码为:
torch.mps.seed(int(seed))
- 调用pipe的时候去掉
generator=generator参数:
image = pipe(prompt=prompt, height=height, width=width, num_inference_steps=steps, guidance_scale=guidance_scale).images[0]
不过这个方案是全局生效的,如果同时运行多个生成任务,可能会出现种子冲突的情况,所以更适合单任务场景。
补充注意点
- 确保你的PyTorch版本在1.12及以上,这是MPS支持的最低版本;
- 如果后续PyTorch更新了MPS对Generator的支持,你可以再改回原来的写法。
内容的提问来源于stack exchange,提问作者lavascone
相关产品推荐
相关产品推荐

