【StableDiffusion】秋叶包,安装 tensorRT 各种坑,包含请求超时、Exporting to ONNX failed、Failed to parse ONNX model

总览

1.无法安装
2.报错解决
3.显存小的就别玩 tensorRT 了

一、无法安装

1.使用魔法

我知道你要说,魔法也不行巴拉巴拉
我也很疑惑,最开始使用本地网络和魔法都不行
后来发现是概率问题
使用魔法,然后多试几次(我试了大概7、8次)然后下载成功了

在这里插入图片描述

2.疑难杂症

什么请求超时、服务器无法回应、回应错误之类的巴拉巴拉
直接使用魔法多试几次就好了

二、报错

1.报错情况1

ERROR:root:Exporting to ONNX failed. Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument mat1 in method wrapper_CUDA_addmm)

完整报错内容:

Disabling attention optimization
Exporting boleromixPony_v14 to TensorRT using - Batch Size: 1-1-1
Height: 768-768-768
Width: 768-768-768
Token Count: 75-75-75
Disabling attention optimization
ERROR:root:Exporting to ONNX failed. Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument mat1 in method wrapper_CUDA_addmm)
Building TensorRT engine... This can take a while, please check the progress in the terminal.
Building TensorRT engine for S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\models\Unet-onnx\boleromixPony_v14.onnx: S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\models\Unet-trt\boleromixPony_v14_ad5d6010_cc86_sample=2x4x96x96-timesteps=2-encoder_hidden_states=2x77x2048-y=2x2816.trt
Could not open file S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\models\Unet-onnx\boleromixPony_v14.onnx
Could not open file S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\models\Unet-onnx\boleromixPony_v14.onnx
[E] ModelImporter.cpp:773: Failed to parse ONNX model from file: S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\models\Unet-onnx\boleromixPony_v14.onnx
[!] Failed to parse ONNX model. Does the model file exist and contain a valid ONNX model?
Traceback (most recent call last):
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\python\lib\site-packages\gradio\routes.py", line 488, in run_predict
    output = await app.get_blocks().process_api(
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\python\lib\site-packages\gradio\blocks.py", line 1431, in process_api
    result = await self.call_function(
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\python\lib\site-packages\gradio\blocks.py", line 1103, in call_function
    prediction = await anyio.to_thread.run_sync(
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\python\lib\site-packages\anyio\to_thread.py", line 31, in run_sync
    return await get_asynclib().run_sync_in_worker_thread(
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\python\lib\site-packages\anyio\_backends\_asyncio.py", line 937, in run_sync_in_worker_thread
    return await future
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\python\lib\site-packages\anyio\_backends\_asyncio.py", line 867, in run
    result = context.run(func, *args)
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\python\lib\site-packages\gradio\utils.py", line 707, in wrapper
    response = f(*args, **kwargs)
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\extensions\Stable-Diffusion-WebUI-TensorRT\ui_trt.py", line 126, in export_unet_to_trt
    ret = export_trt(
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\extensions\Stable-Diffusion-WebUI-TensorRT\exporter.py", line 231, in export_trt
    ret = engine.build(
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\extensions\Stable-Diffusion-WebUI-TensorRT\utilities.py", line 227, in build
    network = network_from_onnx_path(
  File "<string>", line 3, in network_from_onnx_path
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\python\lib\site-packages\polygraphy\backend\base\loader.py", line 40, in __call__
    return self.call_impl(*args, **kwargs)
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\python\lib\site-packages\polygraphy\util\util.py", line 710, in wrapped
    return func(*args, **kwargs)
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\python\lib\site-packages\polygraphy\backend\trt\loader.py", line 247, in call_impl
    trt_util.check_onnx_parser_errors(parser, success)
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\python\lib\site-packages\polygraphy\backend\trt\util.py", line 88, in check_onnx_parser_errors
    G_LOGGER.critical(
  File "S:\app_AI\stableDiffusion-webui-aki\sd-webui-aki-v4.8\python\lib\site-packages\polygraphy\logger\logger.py", line 605, in critical
    raise ExceptionType(message) from None
polygraphy.exception.exception.PolygraphyException: Failed to parse ONNX model. Does the model file exist and contain a valid ONNX model?
2.解决办法

去这个目录:

X:\XXX\sd-webui-aki-v4.8\extensions\Stable-Diffusion-WebUI-TensorRT

替换这两个文件:

ui_trt.py
exporter.py

替换的代码如下:
ui_trt.py 替换代码(直接复制就好了,别忘了删掉 CSDN 水印):

import os
import gc
import json
import logging
from collections import defaultdict

import torch
from safetensors.torch import save_file
import gradio as gr

from modules.shared import cmd_opts
from modules.ui_components import FormRow
from modules import sd_hijack, sd_models, shared
from modules.ui_common import refresh_symbol
from modules.ui_components import ToolButton

from model_helper import UNetModel
from exporter import export_onnx, export_trt, export_lora
from model_manager import modelmanager, cc_major, TRT_MODEL_DIR
from datastructures import SDVersion, ProfilePrests, ProfileSettings


profile_presets = ProfilePrests()

logging.basicConfig(level=logging.INFO)


def get_context_dim():
    if shared.sd_model.is_sd1:
        return 768
    elif shared.sd_model.is_sd2:
        return 1024
    elif shared.sd_model.is_sdxl:
        return 2048


def is_fp32():
    use_fp32 = False
    if cc_major < 7:
        use_fp32 = True
        print("FP16 has been disabled because your GPU does not support it.")
    return use_fp32


def export_unet_to_trt(
    batch_min,
    batch_opt,
    batch_max,
    height_min,
    height_opt,
    height_max,
    width_min,
    width_opt,
    width_max,
    token_count_min,
    token_count_opt,
    token_count_max,
    force_export,
    static_shapes,
    preset,
):
    sd_hijack.model_hijack.apply_optimizations("None")

    is_xl = shared.sd_model.is_sdxl
    model_name = shared.sd_model.sd_checkpoint_info.model_name

    profile_settings = ProfileSettings(
        batch_min,
        batch_opt,
        batch_max,
        height_min,
        height_opt,
        height_max,
        width_min,
        width_opt,
        width_max,
        token_count_min,
        token_count_opt,
        token_count_max,
    )
    if preset == "Default":
        profile_settings = profile_presets.get_default(is_xl=is_xl)
    use_fp32 = is_fp32()

    print(f"Exporting {
     
     model_name} to TensorRT using - {
     
     profile_settings}")
    profile_settings.token_to_dim(static_shapes)

    model_hash = shared.sd_model.sd_checkpoint_info.hash
    model_name = shared.sd_model.sd_checkpoint_info.model_name

    onnx_filename, onnx_path = modelmanager.get_onnx_path(model_name)
    timing_cache = modelmanager.get_timing_cache()

    diable_optimizations = is_xl
    embedding_dim = get_context_dim()

    modelobj = UNetModel(
        shared.sd_model.model.diffusion_model,
        embedding_dim,
        text_minlen=profile_settings.t_min,
        is_xl=is_xl,
    )
    modelobj.apply_torch_model()

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    profile = modelobj.get_input_profile(profile_settings)
    modelobj.unet.to(device)
    for key, value in profile.items():
        if isinstance(value, torch.Tensor):
            profile[key] = value.to(device)
        elif isinstance(value, tuple):
            profile[key] = tuple(v.to(device) for v in value)

    export_onnx(
        onnx_path,
        modelobj,
        profile_settings,
        diable_optimizations=diable_optimizations,
    )
    gc.collect()
    torch.cuda.empty_cache()

    trt_engine_filename, trt_path = modelmanager.get_trt_path(
        model_name, model_hash, profile, static_shapes
    )

    if not os.path.exists(trt_path) or force_export:
        print(
            "Building TensorRT engine... This can take a while, please check the progress in the terminal."
        )
        gr.Info(
            "Building TensorRT engine... This can take a while, please check the progress in the terminal."
        )
        ret = export_trt(
            trt_path,
            onnx_path,
            timing_cache,
            profile=profile,
            use_fp16=not use_fp32,
        )
        if ret:
            return "## Export Failed due to unknown reason. See shell for more information. \n"

        print("TensorRT engines has been saved to disk.")
        modelmanager.add_entry(
            model_name,
            model_hash,
            profile,
            static_shapes,
            fp32=use_fp32,
            inpaint=True if modelobj.in_channels == 6 else False,
            refit=True,
            vram=0,
            unet_hidden_dim=modelobj.in_channels,
            lora=False,
        )
    else:
        print(
            "TensorRT engine found. Skipping build. You can enable Force Export in the Advanced Settings to force a rebuild if needed."
        )

    gc.collect()
    torch.cuda.empty_cache()

    return "## Exported Successfully \n"


def export_lora_to_trt(lora_name, force_export):
    is_xl = shared.sd_model.is_sdxl

    available_lora_models = get_lora_checkpoints()
    lora_name = lora_name.split(" ")[0]
    lora_model 
### 解决方案 当遇到 `Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported` 错误时,主要原因是浏览器的安全策略阻止了跨域图像数据的访问。为了防止潜在的安全风险,浏览器不允许将包含外部资源(尤其是来自不同源的图像)的画布转换为数据URL。 #### 方法一:设置CORS头 服务器端可以通过配置响应头来允许跨域资源共享 (CORS),从而使得客户端可以合法地加载并操作这些资源。具体来说,在提供图片资源的服务端添加如下HTTP头部: ```http Access-Control-Allow-Origin: * ``` 这表示任何域名都可以请求此资源。对于更严格控制的情况,则可以用具体的域名代替星号[^1]。 #### 方法二:使用代理服务 如果无法修改远程服务器上的 CORS 设置,另一种解决方案是在同一域内创建一个简单的 HTTP 代理脚本。这个脚本负责向目标 URL 发起请求并将返回的内容转发给前端应用。通过这种方式,所有的网络通信都发生在同一个源下,因此不会触发同源策略限制[^2]。 #### 方法三:确保所有资源都是本地文件或来自相同源 最简单的方法就是保证所使用的全部媒体素材要么托管在同一台服务器上,要么是从支持适当 CORS 头部的可信第三方获取而来。这样可以直接绕过跨域问题[^3]。 #### JavaScript 实现示例 下面是一个基于上述原则调整后的JavaScript代码片段,用于处理 OpenLayers 地图导出 PDF 的场景: ```javascript // 假设 map 是已经初始化好的OpenLayer地图实例对象 map.once('postrender', function () { var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); // 获取当前视口大小,并据此设定新创建的<canvas>尺寸 const size = map.getSize(); canvas.width = size[0]; canvas.height = size[1]; // 将地图渲染上下文复制到新的<canvas> Array.prototype.forEach.call( document.querySelectorAll('.ol-layer canvas'), function (layerCanvas) { if (layerCanvas.width > 0) { // 防止空白层干扰 let transform = layerCanvas.style.transform; transform = transform.replace(/^matrix\(([^\(]*)\)$/, '$1'); transform = transform.split(',').map(Number); // 应用变换矩阵以保持坐标系一致 ctx.setTransform(...transform); // 使用 drawImage 绘制每一层至最终输出的<canvas> ctx.drawImage(layerCanvas, 0, 0); } }); // 导出前先尝试清除现有样式属性中的transform影响 ctx.setTransform(1, 0, 0, 1, 0, 0); // 如果一切正常,此时应该能够成功调用toDataURL() try { console.log(canvas.toDataURL()); } catch(e){ alert(`Error exporting image:\n${e.message}`); } }); ```
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MicroLindb

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值