【生成模型】【小实验】VAE的作用与Flux-Fill

1. Flux Fill的官方示例

或者参考官方代码:https://huggingface.co/black-forest-labs/FLUX.1-Fill-dev

bfl_repo = "../model_hub/black-forest-labs/FLUX.1-Fill-dev"
pipe = load_flux_quanto_fp8(bfl_repo)

image = Image.open("../dataset/tmp/cup.png")    # input image has mul masked
mask = Image.open("../dataset/tmp/cup_mask.png")  # mask image

image_fill = pipe(
    prompt="a white paper cup",
    image=image,
    mask_image=mask,
    height=1632,
    width=1232,
    guidance_scale=30,
    num_inference_steps=50,
    max_sequence_length=512,
    generator=torch.Generator("cpu").manual_seed(0)
).images[0]
image_fill.save(f"../dataset/tmp/cup_flux_fill.png")

import huicv.visualization as huivis
huivis.grid_pil_images([image, mask, image_fill], 3, 1) # 可视化

在这里插入图片描述

2. 可视化Flux-Fill到底修改了什么

通过VAE decode可视化特征的差值

# VAE是卷积网络,具备很强的空间属性:也就图像和特征有很强的对于关系,改变某个位置的特征,影响最大的是其对应的图像。
# Flux-Fill主要这对Mask区域的特征做修改,说明模型在训练中能学习出针对Mask区域的VAE特征做大幅度变换的能力。

def vae_encode(self, image):
    width, height = image.size
    image_pre = self.image_processor.preprocess(image, height=height, width=width)
    image_pre = image_pre.to(device="cuda", dtype=torch.bfloat16)
    with torch.no_grad():
        encoder_output = self.vae.encode(image_pre)
        latents = encoder_output.latent_dist.sample(None)
    return latents

def vae_decode(self, latents_1):
    with torch.no_grad():
        image = self.vae.decode(latents_1, return_dict=False)[0]
        r_image = self.image_processor.postprocess(image, output_type="pil")[0]
    return r_image

latents_image = vae_encode(pipe, image)
latents_cont_image = vae_encode(pipe, context_image)
latents_image_fill = vae_encode(pipe, image_fill)

diff_latent_cont = latents_image_fill - latents_cont_image
diff_img_cont = vae_decode(pipe, diff_latent_cont)
diff_latent_ori = latents_image_fill - latents_image
diff_img_ori = vae_decode(pipe, diff_latent_ori)

huivis.grid_pil_images([diff_img_cont, diff_img_ori], 2, 1)

在这里插入图片描述

不使用VAE decode直接可视化特征

可以看见其实diffusion输出的特征中视觉要素已经很明显了,VAE只是让它们看起更像是自然图像。

1) diff_latent
def to_image(f):
    f = (f - f.min()) / (f.max() - f.min())
    a2 = (f*255).to(torch.float32).cpu().numpy().astype(np.uint8)
    return Image.fromarray(a2)
    
imgs = [to_image(f) for f in diff_latent_ori[0]]
huivis.grid_pil_images(imgs, 8, 2)

在这里插入图片描述
直接求和

to_image(diff_latent_ori.abs().sum(dim=1)[0])

在这里插入图片描述

2) 可视化原图和context图的latents
imgs = [to_image(f) for f in latents_image[0]]
huivis.grid_pil_images(imgs, 8, 2)

imgs = [to_image(f) for f in latents_cont_image[0]]
huivis.grid_pil_images(imgs, 8, 2)

在这里插入图片描述
在这里插入图片描述

3. VAE在做什么

image = Image.open("../dataset/tmp/cup.png")
image = Image.open(os.path.join(assert_dirs, "flux_fill/旅游出行_524169_ori.jpg")) 

def randn(latents): return torch.randn(size=latents.shape, device=latents.device, dtype=latents.dtype)
latents_image = vae_encode(pipe, image)
d = 80
ld = d / 255 * (latents_image.max() - latents_image.min()).item()
print("latents_image:", latents_image.max().item(), latents_image.min().item(), d, ld)

huivis.grid_pil_images([
    image,
    vae_decode(pipe, latents_image + ld),
    vae_decode(pipe, latents_image - ld),
    vae_decode(pipe, latents_image + ld*randn(latents_image)),
    vae_decode(pipe, latents_image - ld*randn(latents_image)),
    vae_decode(pipe, latents_image * 8),
    vae_decode(pipe, latents_image / 8),
], 7, 1)

在这里插入图片描述
在这里插入图片描述
可以看到,加法在调整亮度,乘法在改变色调。
这说明VAE特征空间可以看作是在不同色调的亮度值的分解,当应用加法,所有色调都被加亮,呈现为亮度增强,当应用乘法时,数值大的色调被增强的越大,体现为色调的强化。

### Flux1-Fill-Dev-FP16-Q4 工作流概述 Flux1-Fill-Dev-FP16-Q4 是一种基于 GGUF 的量化工作流,旨在优化 GPU 显存占用的同时保持较高的推理性能[^1]。该工作流适用于低显存设备(如 6GB 或更低),通过 FP16 和 Q4_0/Q4_1 等量化的组合来减少内存消耗并提升运行效率。 以下是关于此工作流的配置、实现及相关文档的具体说明: --- ### 配置指南 #### 下载安装 要使用 Flux1-Fill-Dev-FP16-Q4 工作流,需先完成以下准备工作: 1. **下载工具链**:访问资源站点获取最新的 Flux-GGUF 版本及其配套脚本文件。 2. **环境设置**:确保 Python 及 PyTorch 安装完毕,并验证 CUDA 是否支持当前硬件架构[^4]。 ```bash pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 ``` 3. **模型加载**:根据需求选择已预训练好的 GGUF 模型权重文件,或者自行转换原始模型至目标格式[^3]。 --- ### 实现细节 #### 数据处理流程 数据输入阶段涉及图像裁剪、缩放及标准化操作,具体代码如下所示: ```python from PIL import Image import numpy as np def preprocess_image(image_path, target_size=(512, 512)): img = Image.open(image_path).convert('RGB') img_resized = img.resize(target_size, resample=Image.BILINEAR) img_array = np.array(img_resized) / 255.0 return img_array.transpose(2, 0, 1)[np.newaxis].astype(np.float16) input_tensor = preprocess_image("example.jpg") print(input_tensor.shape) # 输出应为 (1, 3, 512, 512) ``` 上述函数实现了从图片到张量形式的数据准备过程。 #### 推理执行 利用 Quantization 技术降低计算复杂度,在实际调用时可参考以下模板: ```python import torch class InferenceModel(torch.nn.Module): def __init__(self, model_weights="model.gguf"): super().__init__() self.model = torch.jit.load(model_weights) @torch.no_grad() def forward(self, input_data): output = self.model(input_data.half()) return output.cpu().numpy() inference_engine = InferenceModel() result = inference_engine(torch.tensor(input_tensor)) print(result.shape) # 应返回预测结果维度信息 ``` 以上片段展示了如何加载量化后的模型并通过半精度浮点数加速推断速度。 --- ### 常见问题排查 | 错误描述 | 解决方案 | |----------|-----------| | `CUDA out of memory` | 减少批量大小或将部分层卸载回 CPU 运行 | | 输入尺寸不匹配 | 调整预处理器中的分辨率参数以适配网络预期输入形状[^2] | 对于更复杂的错误日志分析,则建议查阅官方论坛或社区贡献者维护的知识库链接。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值