ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

Diffusers 远程推理 API 参考:remote_decode 与 remote_encode 全参数实战指南

Diffusers 远程推理 API 参考:remote_decode 与 remote_encode 全参数实战指南 Diffusers 远程推理 API 参考remote_decode 与 remote_encode 全参数实战指南【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusers远程推理Remote inference / Hybrid Inference允许把 VAE 的解码decode与编码encode过程卸载到远程 [Inference Endpoints] 上执行从而显著降低本地大模型推理的显存占用。本指南以diffusers仓库的 API 参考文档 docs/source/en/hybrid_inference/api_reference.md 为骨架完整讲解diffusers.utils.remote_utils模块中remote_decode与remote_encode两个核心函数的全部参数、传输协议与返回值语义并结合仓库源码与测试用例给出可直接落地的调用方案。读完本文你将掌握如何在本地只加载 UNet/Transformer、把图像与视频的 VAE 编解码交给远程端点处理并学会针对不同模型Stable Diffusion v1、SDXL、Flux、HunyuanVideo选择正确的scaling_factor、shift_factor与输出类型。一、功能概览为什么需要远程编解码在常规 Diffusers 推理流程中VAE 负责两件事编码——把输入图像压缩成潜空间张量latent解码——把扩散模型产出的 latent 还原为像素图像或视频。随着模型分辨率提高VAE 解码在 1024×1024 甚至更高分辨率下会消耗大量显存常常成为推理的瓶颈迫使开发者使用模型卸载offload或 tiled 解码后者会增加耗时并可能影响画质。远程推理的解决思路是本地只运行 UNet/Transformer 等生成主干的采样过程把 encode/decode 通过 HTTP 请求转发到托管的 VAE 端点。仓库在 src/diffusers/utils/remote_utils.py 中提供了两个顶层函数remote_decode(endpoint, tensor, ...)把 latent 张量发送到远程端点解码后返回PIL.Image.Image、list[Image.Image]、bytesMP4或torch.Tensorremote_encode(endpoint, image, ...)把图像发送到远程端点编码后返回 latenttorch.Tensor。两个函数均由diffusers.utils.remote_utils提供其中remote_decode还通过 src/diffusers/utils/init.py 从diffusers.utils顶层直接导出。该特性目前标记为实验性支持范围与端点对应关系见 docs/source/en/hybrid_inference/overview.md 中的表格。支持模型与端点模型端点检查点支持能力Stable Diffusion v1https://q1bj3bpq6kzilnsu.us-east-1.aws.endpoints.huggingface.cloud/stabilityai/sd-vae-ft-mseencode / decodeStable Diffusion XLhttps://x2dmsqunjd6k9prw.us-east-1.aws.endpoints.huggingface.cloud/madebyollin/sdxl-vae-fp16-fixencode / decodeFluxhttps://whhx50ex1aryqvw6.us-east-1.aws.endpoints.huggingface.cloud/black-forest-labs/FLUX.1-schnellencode / decodeHunyuanVideohttps://o7ywnmrahorts457.us-east-1.aws.endpoints.huggingface.cloud/hunyuanvideo-community/HunyuanVideodecode这些端点 URL 同样以常量形式定义在 src/diffusers/utils/constants.py 中DECODE_ENDPOINT_SD_V1、DECODE_ENDPOINT_SD_XL、DECODE_ENDPOINT_FLUX、DECODE_ENDPOINT_HUNYUAN_VIDEO、ENCODE_ENDPOINT_SD_V1、ENCODE_ENDPOINT_SD_XL、ENCODE_ENDPOINT_FLUX测试代码也直接引用这些常量。需要注意的是这些是 Hugging Face 官方托管的实验性端点可能随部署调整而变动例如仓库测试注释中已说明部分ENCODE_ENDPOINT_*曾被下线并返回 404生产使用时应以实际可用端点为准。二、remote_decode远程解码remote_decode是远程推理的核心解码入口定义于 src/diffusers/utils/remote_utils.py 的remote_decode函数。其职责是把本地采样得到的 latent 张量序列化后 POST 到端点再把端点返回的字节流反序列化为指定类型的输出。完整签名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参数逐项详解endpointstr必填远程解码端点地址即上文表格中的DECODE_ENDPOINT_*常量。tensortorch.Tensor必填待解码的 latent 张量。本地设备不影响结果——测试用例 tests/remote/test_remote_decode.py 的注释明确指出张量在远程被序列化并解码本地设备对结果没有影响因此在 CPU 上随机生成 latent 再移动到目标设备即可。processorVaeImageProcessor或VideoProcessor可选用于return_typept以及视频模型的return_typepil场景。图像模型用VaeImageProcessor来自 src/diffusers/image_processor.py视频模型用VideoProcessor来自 src/diffusers/video_processor.py。视频模型需要 processor 来调用postprocess_video把张量转成帧列表。do_scalingbool默认True已废弃源码中明确标注DEPRECATED计划在版本 1.0.0 移除。为兼容旧行为do_scalingTrue时仍会远程应用缩放如latents / vae.config.scaling_factor但官方推荐直接传scaling_factor/shift_factor。若不需要任何缩放传do_scalingNone或do_scalingFalse。从源码看do_scalingTrue且scaling_factor is None时会触发弃用警告FutureWarning测试test_do_scaling_deprecation对此有专门断言。scaling_factorfloat可选缩放因子传值后远程应用缩放等价于latents / self.vae.config.scaling_factor。各模型的参考值SD v10.18215SD XL0.13025Flux0.3611若为None则要求输入已经完成缩放。shift_factorfloat可选平移因子传值后远程应用平移等价于latents self.vae.config.shift_factor。参考值Flux0.1159若为None则要求输入已经完成平移。注意缩放与平移是两步独立操作latents latents / scaling_factor shift_factorFlux 需要同时传两个值。output_typemp4、pil或pt默认pil端点返回的类型源码标注该字段可能变更建议反馈偏好。mp4视频模型支持。端点返回视频的bytes。pil图像与视频模型均支持。图像模型端点返回image_format指定的图片字节流视频模型端点返回已做部分后处理的torch.Tensor此时需传processor任意非None值均可。pt图像与视频模型均支持。端点返回torch.Tensor配合partial_postprocessTrue时返回后处理为uint8的图像张量。return_typemp4、pil或pt默认pil函数的返回类型。mp4函数返回视频bytes。pil函数返回PIL.Image.Image。当output_typepil时无需进一步处理当output_typept时由函数创建PIL.Image.Image——此时若partial_postprocessFalse必须提供processor若partial_postprocessTrue则不需要。pt函数返回torch.Tensor不需要processor。partial_postprocessFalse时张量为float16/bfloat16且未做反归一化partial_postprocessTrue时张量为uint8且已反归一化。image_formatpng或jpg默认jpg仅与output_typepil配合使用决定端点返回 jpg 还是 png 编码的图片。partial_postprocessbool默认False仅与output_typept配合。False时张量为float16/bfloat16且不反归一化最兼容第三方代码True时张量为uint8且已反归一化可最小化传输体积同时保留全质量。input_tensor_type/output_tensor_typebinary默认binary张量传输类型。源码中base64已被废弃计划 1.0.0 移除传入base64会触发FutureWarning并自动回退为binary测试test_input_tensor_type_base64_deprecation与test_output_tensor_type_base64_deprecation验证了这一行为。当前只支持二进制直传。height/widthint可选packed latents 必填。Flux 的 latent 是打包packed格式形状如(1, 4096, 64)见测试中TestRemoteAutoencoderKLFluxPacked此时张量自身不含空间维度信息必须显式传入height/width供端点还原形状check_inputs_decode中会校验tensor.ndim 3且height/width缺失时直接抛出ValueError。返回值Image.Image单帧图像、list[Image.Image]视频帧序列HunyuanVideo 的pt→pil路径返回帧列表、bytesMP4 视频、或torch.Tensor原始或后处理张量。底层调用链与协议实现remote_decode内部依次调用三个辅助函数形成清晰的校验 → 打包 → 收发 → 解析流水线check_inputs_decode参数合法性校验。三个关键规则见 src/diffusers/utils/remote_utils.py三维packedlatent 缺少height/width时抛ValueErroroutput_typept且return_typepil且未做部分后处理时必须提供VaeImageProcessor或VideoProcessordo_scalingTrue但未提供scaling_factor时触发弃用警告。prepare_decode把请求打包成requests.post的 kwargs。核心细节元数据image_format、output_type、partial_postprocess、shape、dtype及可选的scaling_factor/shift_factor/height/width放进请求参数HTTP 头默认Content-Type: tensor/binary、Accept: tensor/binary当output_typepil且未传 processor 时Accept切换为image/jpeg或image/pngoutput_typemp4时切换为text/plain张量数据通过safetensors.torch._to_ndarray(tensor)[0].tobytes()序列化为裸二进制。postprocess_decode解析响应。端点通过响应头返回shapeJSON与dtype函数用DTYPE_MAPfloat16/float32/bfloat16/uint8定义于模块顶部把dtype字符串映射回torch.dtype再用torch.frombuffer(...).reshape(shape)重建张量。随后依据output_type/return_type/processor组合分派到不同分支纯图片字节流output_typepil且无 processorImage.open(io.BytesIO(...)).convert(RGB)并通过detect_image_type按魔数JPEG\xff\xd8、PNG 签名、GIF87a/89a、BMPBM还原图片格式有 processor 的 PIL 路径(tensor.permute(0,2,3,1).float().numpy() * 255).round().astype(uint8)转为帧列表视频模型走VideoProcessor.postprocess_videoMP4直接返回原始bytes。请求失败时response.ok为假会抛出RuntimeError(response.json())把端点返回的错误信息透传给调用方。三、remote_encode远程编码remote_encode是远程推理的编码入口把输入图像发送到端点返回 latent 张量定义于同一文件的remote_encode函数。完整签名remote_encode( endpoint: str, image: torch.Tensor | Image.Image, scaling_factor: float | None None, shift_factor: float | None None, ) - torch.Tensor参数详解endpointstr必填远程编码端点地址ENCODE_ENDPOINT_*常量。imagetorch.Tensor或PIL.Image.Image必填待编码的图像。可以是 PIL 图像或预处理的张量。scaling_factorfloat可选缩放因子传值后远程应用缩放等价于latents * self.vae.config.scaling_factor。参考值SD v10.18215、SD XL0.13025、Flux0.3611。为None时要求输入已完成缩放。shift_factorfloat可选平移因子传值后远程应用平移等价于latents - self.vae.config.shift_factor。参考值Flux0.1159。注意编码方向的符号与解码相反解码为加、编码为减。为None时要求输入已完成平移。返回值torch.Tensor编码后的 latent。输出形状遵循[1, channels, height // 8, width // 8]的 8 倍下采样规律SD 系为 4 通道、Flux 为 16 通道测试test_image_input与test_multi_res对此有明确断言。底层调用链remote_encode同样遵循校验 → 打包 → 收发 → 解析流程但更简洁check_inputs_encode当前为空实现占位校验prepare_encode若输入是torch.Tensor通过safetensors.torch._to_ndarray(image.contiguous())[0].tobytes()序列化并携带shape/dtype元数据若输入是 PIL 图像则编码为 PNG 字节流。scaling_factor/shift_factor以参数形式随请求发送postprocess_encode与解码的postprocess_decode前半段相同——从响应头读取shape/dtype用torch.frombuffer重建 latent 张量。四、实战示例在 Pipeline 中接入远程编解码下面结合 docs/source/en/hybrid_inference/overview.md 的完整示例演示三种典型接入方式。核心模式一致构造 Pipeline 时传vaeNone采样时设output_typelatent再把 latent 交给remote_decode图像编码则直接把图像交给remote_encode。4.1 远程编码图像为 latentimg2img 前置步骤import torch 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, device_mapcuda # 或 mps、xpu、cpu ) init_image load_image(https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg) init_image init_image.resize((768, 512)) init_latent remote_encode( endpointhttps://whhx50ex1aryqvw6.us-east-1.aws.endpoints.huggingface.cloud/, imageinit_image, scaling_factor0.3611, shift_factor0.1159, )要点Flux 必须同时传scaling_factor0.3611与shift_factor0.1159SD v1/SDXL 只传scaling_factor0.18215/0.13025即可。4.2 远程解码 Flux latentpacked latent 需 height/widthfrom diffusers import FluxPipeline pipeline FluxPipeline.from_pretrained( black-forest-labs/FLUX.1-schnell, dtypetorch.bfloat16, vaeNone, device_mapcuda # 或 mps、xpu、cpu ) prompt A photorealistic Apollo-era photograph of a cat in a small astronaut suit... latent pipeline( promptprompt, guidance_scale0.0, num_inference_steps4, output_typelatent, ).images image remote_decode( endpointhttps://whhx50ex1aryqvw6.us-east-1.aws.endpoints.huggingface.cloud/, tensorlatent, height1024, width1024, # Flux packed latent 必填 scaling_factor0.3611, shift_factor0.1159, ) image.save(image.jpg)4.3 远程解码视频 latentHunyuanVideo 输出 MP4import 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 # 或 mps、xpu、cpu ) 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)视频解码只需设output_typemp4即可直接拿回视频字节流也可以改用output_typeptprocessorVideoProcessor()return_typepil拿回帧列表对应测试RemoteAutoencoderKLHunyuanVideoMixin的行为。五、output_type / return_type 组合决策表remote_decode最复杂的是output_type端点返回格式与return_type函数返回格式的组合。结合源码postprocess_decode的分支逻辑与测试断言可归纳为下表output_typereturn_type函数返回额外要求pilpilPIL.Image.Imagejpg/png 解码图像模型无 processor格式由image_format决定pilpillist[Image.Image]视频模型需processorpilpttorch.Tensor需processorptpilPIL.Image.Image或帧列表partial_postprocessFalse时必须传 processorTrue时可不传ptpttorch.Tensorfloat16/bfloat16或uint8无需 processormp4mp4bytes视频流仅视频模型选择建议源码 docstring 中的官方推荐output_typeptpartial_postprocessTrue传输体积最小且全质量output_typeptpartial_postprocessFalse与第三方代码兼容性最好output_typepilimage_formatjpg整体传输体积最小适合预览场景。六、测试用例印证与行为契约仓库在 tests/remote/test_remote_decode.py 与 tests/remote/test_remote_encode.py 中对上述行为做了系统验证可作为 API 行为契约参考输出形状契约编码输出严格满足[1, channels, height // 8, width // 8]解码返回图像尺寸与传入 latent 按 8 倍还原一致。test_multi_res遍历 320 至 2048 共 12 种边长组合逐一校验。各模型通道数SD v1/SDXL 为 4 通道 latent(1, 4, 64, 64)→ 512×512Flux 为 16 通道(1, 16, 128, 128)→ 1024×1024Flux packed 形态为(1, 4096, 64)HunyuanVideo 为 5 维(1, 16, 3, 40, 64)。无缩放路径test_no_scaling展示了当调用方本地预先完成tensor / scaling_factor与tensor shift_factor时可传do_scalingFalse并置scaling_factorNone。弃用警告do_scaling、input_tensor_typebase64、output_tensor_typebase64均会触发FutureWarning对应消息文本已在测试中硬编码断言提醒开发者迁移到scaling_factor/shift_factor与二进制传输。网络可达性前提这些测试标注为slow需要实际访问在线端点仓库注释明确说明此类测试不属于快速 CI 契约且部分编码端点曾被下线返回 404 并抛RuntimeError标记为xfail而非删除。七、队列化吞吐优化远程解码是异步网络 I/O可以在等待当前 latent 解码时提前排队下一个生成请求实现流水线化吞吐。overview 文档给出了线程 队列的经典实现StableDiffusionXLPipeline remote_decode关键结构import queue import threading from diffusers import StableDiffusionXLPipeline from diffusers.utils.remote_utils import remote_decode def decode_worker(q: queue.Queue): while True: item q.get() if item is None: break image remote_decode( endpointhttps://q1bj3bpq6kzilnsu.us-east-1.aws.endpoints.huggingface.cloud/, tensoritem, scaling_factor0.13025, ) # display(image) # 处理解码结果 q.task_done() q queue.Queue() thread threading.Thread(targetdecode_worker, args(q,), daemonTrue) thread.start() def decode(latent: torch.Tensor): q.put(latent) pipeline StableDiffusionXLPipeline.from_pretrained( stabilityai/stable-diffusion-xl-base-1.0, dtypetorch.float16, vaeNone, device_mapcuda, ) # 可选配合 torch.compile 进一步提升本地主干推理速度 # pipeline.unet pipeline.unet.to(memory_formattorch.channels_last) # pipeline.unet torch.compile(pipeline.unet, modereduce-overhead, fullgraphTrue) _ pipeline(promptwarmup, output_typelatent) # 预热 for prompt in prompts: latent pipeline(promptprompt, output_typelatent).images decode(latent) q.put(None) # 停止信号 thread.join()八、总结与注意事项remote_decode/remote_encode把 VAE 编解码从本地推理管线中剥离出去是低显存环境运行大模型的实用方案。使用时请重点核对以下几点缩放/平移参数必须与模型匹配SD v10.18215、SDXL0.13025、Flux0.36110.1159传None则必须本地预处理完毕勿混用Flux packed latent 必须传height/width否则check_inputs_decode直接抛ValueErrorAPI 正处在演进期do_scaling与base64传输已标记废弃1.0.0 移除新代码直接使用scaling_factor/shift_factorbinary传输端点为在线依赖请求依赖外网可达的 Hugging Face Inference Endpoints端点下线会表现为RuntimeError如编码端点的 404生产环境需做好端点的可用性与容错设计该功能目前为实验性experimentalAPI 字段可能随反馈调整升级 diffusers 版本后建议回归验证参数行为。如需查看更多端到端示例与基准测试数据可继续阅读 docs/source/en/hybrid_inference/overview.md深入源码可查看 src/diffusers/utils/remote_utils.py 与 src/diffusers/utils/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),仅供参考
返回列表