尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

Diffusers 混合推理 API 参考:`remote_encode` 与 `remote_decode` 远程 VAE 编解码实战指南

Diffusers 混合推理 API 参考:`remote_encode` 与 `remote_decode` 远程 VAE 编解码实战指南 Diffusers 混合推理 API 参考remote_encode与remote_decode远程 VAE 编解码实战指南【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusers混合推理Hybrid Inference是 Diffusers 提供的一项实验性能力它把 VAE 编码、解码过程卸载到远程推理端点执行从而让本地仅需加载扩散模型主体即可完成完整推理流程。本文以 api_reference.md 为骨架结合 remote_utils.py 的源码 docstring 与 tests/remote 下的测试用例系统讲解remote_encode与remote_decode两个公开 API 的完整参数语义、底层实现与实战用法读完即可在低显存环境下跑通编码 → 生成 → 解码的完整链路。一、混合推理 API 概述1.1 为什么需要混合推理扩散模型推理的显存压力通常来自两部分UNet/Transformer 主干与 VAE。混合推理将占用可观显存、且与主干计算解耦的 VAE 部分转移到远程端点本地只需要承担文本编码器与 UNet/Transformer 的推理负载显著降低硬件门槛。其核心优势见 overview.md包括降低要求无需昂贵硬件即可访问强大模型质量无损解码、编码仍由对应模型的官方 VAE 完成不牺牲输出质量成本友好当前以免费 Pilot 形式提供开发者友好只需一次简单的 HTTP 请求即可获得响应。整个功能由 Hugging Face Inference Endpoints 支撑对应端点常量集中定义在 constants.py。1.2 API 入口api_reference.md通过 autodoc 指令从源码 docstring 自动生成参考文档公开 API 位于diffusers.utils.remote_utils模块模块导出处共两个函数函数作用返回值remote_encode将图像/视频远程编码为潜在表示latenttorch.Tensorremote_decode将潜在表示远程解码为图像/视频Image.Image/list[Image.Image]/bytes/torch.Tensor调用方式from diffusers.utils.remote_utils import remote_decode, remote_encode二、remote_encode远程 VAE 编码remote_encode适用于训练、图生图、图生视频等场景——把图像或视频转换为潜在表示。其函数签名为def remote_encode( endpoint: str, image: torch.Tensor | Image.Image, scaling_factor: float | None None, shift_factor: float | None None, ) - torch.Tensor:2.1 参数说明参数类型必填说明endpointstr是远程编码端点的 URL。不同模型对应不同端点见 constants.py 中的ENCODE_ENDPOINT_*常量imagetorch.Tensor或PIL.Image.Image是待编码的图像。传入torch.Tensor时需为float16/bfloat16等内存布局连续的张量传入 PIL 图像时会自动序列化为 PNG 字节流发送scaling_factorfloat否缩放因子。传入后端点会在编码过程中自动应用缩放等价于latents * scaling_factor的逆操作。若为None则输入必须已由调用方完成缩放shift_factorfloat否平移因子。传入后端点自动应用平移等价于latents - shift_factor的逆操作。若为None则输入必须已由调用方完成平移2.2 基本用法示例以 Flux 模型为例将一张图像远程编码为潜在表示from diffusers import FluxPipeline from diffusers.utils import load_image from diffusers.utils.remote_utils import remote_encode pipeline FluxPipeline.from_pretrained( black-forest-labs/FLUX.1-schnell, dtypetorch.float16, vaeNone, # 关键不加载本地 VAE device_mapcuda, # 也可用 mps、xpu、cpu ) init_image load_image(path/to/astronaut.jpg) init_image init_image.resize((768, 512)) init_latent remote_encode( endpointhttps://ptccx55jz97f9zgo.us-east-1.aws.endpoints.huggingface.cloud/, imageinit_image, scaling_factor0.3611, # Flux 的缩放因子 shift_factor0.1159, # Flux 的平移因子 )提示remote_encode使用的 Flux 编码端点与解码端点不同编码端点在 constants.py 中定义为ENCODE_ENDPOINT_FLUX。三、remote_decode远程 VAE 解码remote_decode将扩散模型输出的潜在表示转换回图像或视频是混合推理最常用的 API。其函数签名为def remote_decode( endpoint: str, tensor: torch.Tensor, processor: VaeImageProcessor | VideoProcessor | None None, do_scaling: bool True, scaling_factor: float | None None, shift_factor: float | None None, output_type: Literal[mp4, pil, pt] pil, return_type: Literal[mp4, pil, pt] pil, image_format: Literal[png, jpg] jpg, partial_postprocess: bool False, input_tensor_type: Literal[binary] binary, output_tensor_type: Literal[binary] binary, height: int | None None, width: int | None None, ) - Image.Image | list[Image.Image] | bytes | torch.Tensor:3.1 核心参数详解输入相关参数类型默认值说明endpointstr—远程解码端点 URL见 constants.py 的DECODE_ENDPOINT_*常量tensortorch.Tensor—待解码的潜在表示张量。序列化在本地 CPU 完成本地设备不影响结果processorVaeImageProcessor/VideoProcessorNone图像/视频后处理器。当return_typept且需要图像输出、或视频模型返回pil时需要传入height/widthintNone仅packed latents如 Flux 打包格式必须显式传入用于还原空间尺寸普通[1, C, H, W]布局无需传入缩放与平移Scaling / Shift参数类型默认值说明do_scalingboolTrue已弃用计划在 1.0.0 移除。应改用显式传入scaling_factor/shift_factor。为True时缩放如latents / vae.config.scaling_factor在远端执行为False时输入必须已应用缩放scaling_factorfloatNone传入后在远端自动应用缩放。若为None输入必须已由调用方完成缩放shift_factorfloatNone传入后在远端自动应用平移如latents vae.config.shift_factor。若为None输入必须已由调用方完成平移输出控制参数类型默认值说明output_typemp4/pil/ptpil端点的输出类型mp4仅视频模型支持端点返回视频bytespil图像模型返回image_format编码的图像字节视频模型返回已部分后处理的torch.Tensorpt图像与视频均支持端点返回torch.Tensorreturn_typemp4/pil/ptpil函数的返回类型mp4返回视频bytespil返回PIL.Image.Imagept返回torch.Tensorimage_formatpng/jpgjpg仅output_typepil时生效指定端点返回 jpg 还是 pngpartial_postprocessboolFalse仅output_typept时生效False时返回未反归一化的float16/bfloat16张量True时返回已反归一化的uint8张量input_tensor_type/output_tensor_typebinarybinary张量传输格式。base64已被弃用统一使用binary3.2output_type与return_type的四种组合两个参数独立控制端点侧输出与本地侧返回组合后可覆盖几乎所有使用场景output_typepilreturn_typepil端点返回图片字节本地直接打开为 PIL 图像无需processoroutput_typeptreturn_typepil端点返回张量本地用processor后处理为 PIL 图像partial_postprocessTrue时可不传processoroutput_typeptreturn_typept端到端张量传输适合对接第三方后处理代码不要求processoroutput_typemp4return_typemp4视频字节流直通本地写文件即可。3.3 官方推荐源码 docstring 中给出了三条传输方案建议ptpartial_postprocessTrue最小传输体积下保持完整质量uint8 已反归一化ptpartial_postprocessFalse与第三方代码兼容性最好保留浮点张量pilimage_formatjpg整体传输体积最小。3.4 解码实战示例FluxFlux 的 latent 是打包packed布局解码时必须显式传入height与widthfrom diffusers import FluxPipeline from diffusers.utils.remote_utils import remote_decode pipeline FluxPipeline.from_pretrained( black-forest-labs/FLUX.1-schnell, dtypetorch.bfloat16, vaeNone, device_mapcuda, ) prompt A photorealistic Apollo-era photograph of a cat astronaut on the Moon... latent pipeline( promptprompt, guidance_scale0.0, num_inference_steps4, output_typelatent, # 关键管线输出 latent 而非图像 ).images image remote_decode( endpointhttps://whhx50ex1aryqvw6.us-east-1.aws.endpoints.huggingface.cloud/, tensorlatent, height1024, width1024, scaling_factor0.3611, shift_factor0.1159, ) image.save(image.jpg)3.5 视频解码实战示例HunyuanVideo视频模型的远端解码支持output_typemp4直接获得视频字节import torch from diffusers import HunyuanVideoPipeline, HunyuanVideoTransformer3DModel from diffusers.utils.remote_utils import remote_decode transformer HunyuanVideoTransformer3DModel.from_pretrained( hunyuanvideo-community/HunyuanVideo, subfoldertransformer, dtypetorch.bfloat16 ) pipeline HunyuanVideoPipeline.from_pretrained( hunyuanvideo-community/HunyuanVideo, transformertransformer, vaeNone, dtypetorch.float16, device_mapcuda, ) latent pipeline( promptA cat walks on the grass, realistic, height320, width512, num_frames61, num_inference_steps30, output_typelatent, ).frames video remote_decode( endpointhttps://o7ywnmrahorts457.us-east-1.aws.endpoints.huggingface.cloud/, tensorlatent, output_typemp4, ) if isinstance(video, bytes): with open(video.mp4, wb) as f: f.write(video)四、模型缩放/平移因子速查scaling_factor与shift_factor因模型而异源码 docstring 与 tests/remote/test_remote_decode.py 中给出了各模型的权威取值模型scaling_factorshift_factor解码端点常量备注Stable Diffusion v10.18215—DECODE_ENDPOINT_SD_V1参考stabilityai/sd-vae-ft-mseStable Diffusion XL0.13025—DECODE_ENDPOINT_SD_XL参考madebyollin/sdxl-vae-fp16-fixFlux0.36110.1159DECODE_ENDPOINT_FLUXlatent 为 packed 布局解码需传height/width测试中 dtype 为bfloat16HunyuanVideo0.476986—DECODE_ENDPOINT_HUNYUAN_VIDEO仅支持解码dtype 为float16注意以上数值必须与所选端点对应的 VAE 模型严格匹配。若scaling_factor/shift_factor传None则调用方必须在发送前自行完成缩放与平移测试用例test_no_scaling正是先本地tensor / scaling_factor、tensor shift_factor再调用。五、底层实现剖析remote_utils.py的每个公开函数都由输入校验 → 请求准备 → HTTP 传输 → 响应后处理四个阶段组成理解这一链路有助于排查问题。5.1 编码链路prepare_encode→postprocess_encodecheck_inputs_encode参数校验占位当前为空实现prepare_encode若输入是torch.Tensor通过safetensors.torch._to_ndarray(image.contiguous())取出底层 numpy 数组再转字节同时把shape与dtype写入请求参数若输入是 PIL 图像则保存为 PNG 字节流。缩放/平移因子也会随请求参数一并发送HTTP 传输requests.post(endpoint, **kwargs)端点异常时抛出RuntimeError(response.json())postprocess_encode从响应头读取shape与dtype用torch.frombuffer在本地零拷贝重建torch.Tensor。5.2 解码链路prepare_decode→postprocess_decode解码链路多了内容协商逻辑prepare_decode依据参数组合设置Content-Type: tensor/binary与Accept头——pil jpg 时为image/jpegpng 时为image/pngmp4时为text/plain其余为tensor/binaryshape、dtype、scaling_factor、shift_factor等随请求发送postprocess_decode按output_type分支处理响应pt从字节流重建张量partial_postprocessFalse且传processor时经由processor.postprocess/postprocess_video得到 PIL 图像pil且无processorImage.open(io.BytesIO(...))直接打开端点返回的图片字节并通过 detect_image_type依据 JPEG/PNG/GIF/BMP 魔数还原图片格式pil且有processor将float张量permute后乘以 255 转为uint8图像数组mp4原样返回视频字节。5.3 张量 dtype 映射端到端传输使用 DTYPE_MAP 在字符串与torch.dtype之间映射覆盖float16、float32、bfloat16、uint8四种这也是output_typept时能无损还原张量的关键。六、测试验证与限制说明6.1 测试覆盖仓库在 tests/remote/test_remote_decode.py 与 tests/remote/test_remote_encode.py 中对上述 API 进行了系统性验证组合覆盖test_output_type_pt、test_output_type_pil、test_output_type_pt_partial_postprocess、test_output_type_pt_return_type_pt、test_output_type_mp4等用例逐一验证各输出组合无缩放路径test_no_scaling验证调用方本地预缩放后传入do_scalingFalse的兼容路径弃用告警test_do_scaling_deprecation、test_input_tensor_type_base64_deprecation验证do_scaling与base64传输的FutureWarning多分辨率test_multi_res覆盖 3202048 共 12 档分辨率下的编码→解码往返确定性测试在 CPU 上以固定种子manual_seed(13)生成 latent 再搬运到目标设备以保证参考切片可复现。这些测试均标记为slow命中真实 Inference Endpoints不属于常规 CI 契约。6.2 使用限制与注意事项实验性功能混合推理当前处于实验阶段接口与端点随时可能调整反馈可通过项目 Issue 提交端点可用性以仓库当前状态为准编码端点ENCODE_ENDPOINT_*曾出现下架并返回404 NOT_FOUND的情况test_remote_encode.py 中的xfail标记即为此记录实际使用时请以端点当前状态为准packed latents 必传尺寸解码 Flux 等打包格式 latent 时漏传height/width会直接触发ValueError: height and width required for packed latents见 check_inputs_decode管线侧配合使用混合推理时管线需设置vaeNone且生成时传output_typelatent本地不再执行 VAE 相关计算。七、完整链路示例图生图综合编码与解码一个完整的远程编码 → 本地生成 → 远程解码流程如下对应 vae_encode.md 中的生成示例import torch from diffusers import StableDiffusionImg2ImgPipeline from diffusers.utils import load_image from diffusers.utils.remote_utils import remote_decode, remote_encode pipe StableDiffusionImg2ImgPipeline.from_pretrained( stable-diffusion-v1-5/stable-diffusion-v1-5, dtypetorch.float16, variantfp16, vaeNone, ).to(cuda) init_image load_image(path/to/sketch-mountains-input.jpg) init_image init_image.resize((768, 512)) # 1. 远程编码图像 → latent init_latent remote_encode( endpointhttps://qc6479g0aac6qwy9.us-east-1.aws.endpoints.huggingface.cloud/, imageinit_image, scaling_factor0.18215, ) # 2. 本地生成latent → 新的 latent prompt A fantasy landscape, trending on artstation latent pipe( promptprompt, imageinit_latent, strength0.75, output_typelatent, ).images # 3. 远程解码latent → 图像 image remote_decode( endpointhttps://q1bj3bpq6kzilnsu.us-east-1.aws.endpoints.huggingface.cloud/, tensorlatent, scaling_factor0.18215, ) image.save(fantasy_landscape.jpg)八、性能参考编码显存对比混合推理的价值在显存对比中最为直观。根据 vae_encode.md 中记录的 SD v1 编码实测数据VAE 本地运行2048×2048 分辨率在 RTX 3070 上会占用约 96% 显存、RTX 3080 上约 86.7%而采用分块tiled编码后内存可压至约 8.5%10.7%——但分块会增加耗时并影响质量。混合推理把 VAE 完全移出本地等效于将这部分显存占用归零从而为文本编码器与 UNet/Transformer 释放空间这正是无需昂贵硬件即可运行大模型的机制基础。对于更进一步的批量解码吞吐优化可参考 overview.md 中基于queue.Queue 后台线程的解码队列模式在解码当前 latent 的同时排队下一个 prompt 的生成请求实现生成与解码流水线化。延伸阅读混合推理的整体概念与模型支持见 overview.md编码入门与内存基准见 vae_encode.md完整实现源码见 remote_utils.py端点常量见 constants.py。【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusers创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表