当前位置: 首页 > news >正文

Flux 开源替代,他来了——Liberflux

LibreFLUX 是 FLUX.1-schnell 的 Apache 2.0 版本,它提供完整的 T5 上下文长度,使用注意力屏蔽,恢复了无分类器引导,并完全删除了 FLUX 美学微调/DPO 的大部分内容。 这意味着它比基本通量要难看得多,但它有可能更容易进行微调,以适应任何新的分布。 它牢记开源软件的核心原则,即它应该难以使用,比专有解决方案更慢、更笨拙,其美学风格也应该停留在 2000 年代早期。

在这里插入图片描述
prompt:The image features a man standing confidently, wearing a simple t-shirt with a humorous and quirky message printed across the front. The t-shirt reads: “I de-distilled FLUX schnell into a slow, ugly model and all I got was this stupid t-shirt.” The man’s expression suggests a mix of pride and irony, as if he’s aware of the complexity behind the statement, yet amused by the underwhelming reward. The background is neutral, keeping the focus on the man and his t-shirt, which pokes fun at the frustrating and often anticlimactic nature of technical processes or complex problem-solving, distilled into a comically understated punchline.

示例

推理

要使用该模型,只需使用 diffusers 调用自定义管道即可。 它目前适用于 diffusers==0.30.3,并将很快更新到最新的 diffusers。 该模型在 CFG 比例为 2.0 至 5.0 时效果最佳,因此如果您得到的图像模糊或有奇怪的阴影,请尝试调低 CFG 比例(扩散器中的 guidance_scale)。 另外,如果在前几个时间步中关闭 CFG 比例(自定义管道中的 no_cfg_until_timestep=2),也可以使用更高的 CFG 比例。

# ! pip install diffusers==0.30.3
import torch
from diffusers import DiffusionPipelinepipe = DiffusionPipeline.from_pretrained("jimmycarter/LibreFLUX",custom_pipeline="jimmycarter/LibreFLUX",use_safetensors=True,torch_dtype=torch.bfloat16,trust_remote_code=True,
)# High VRAM
prompt = "Photograph of a chalk board on which is written: 'I thought what I'd do was, I'd pretend I was one of those deaf-mutes.'"
negative_prompt = "blurry"
images = pipe(prompt=prompt,negative_prompt=negative_prompt,return_dict=False,# guidance_scale=3.5,# num_inference_steps=28,# generator=torch.Generator().manual_seed(42),# no_cfg_until_timestep=0,
)
images[0][0].save('chalkboard.png')# If you have <=24 GB VRAM, try:
# ! pip install optimum-quanto
# Then
from optimum.quanto import freeze, quantize, qint8
# quantize and freeze will take a short amount of time, so be patient.
quantize(pipe.transformer,weights=qint8,exclude=["*.norm", "*.norm1", "*.norm2", "*.norm2_context","proj_out", "x_embedder", "norm_out", "context_embedder",],
)
freeze(pipe.transformer)
pipe.enable_model_cpu_offload()images = pipe(prompt=prompt,negative_prompt=negative_prompt,device=None,return_dict=False,do_batch_cfg=False, # https://github.com/huggingface/optimum-quanto/issues/327# guidance_scale=3.5,# num_inference_steps=28,# generator=torch.Generator().manual_seed(42),# no_cfg_until_timestep=0,
)
images[0][0].save('chalkboard.png')

为便于在 ComfyUI 中使用,我们提供了一个转换器文件,但请注意,ComfyUI 目前不支持注意遮罩,因此您的图像可能会降低质量。

微调

使用 SimpleTuner 和 --flux_attention_masked_training 训练选项以及 jimmycarter/LibreFlux-SimpleTuner 中的模型,可以轻松地对模型进行微调。 这是去除了自定义管道的同一模型,目前自定义管道干扰了 SimpleTuner 对其进行微调的能力。 除了全等级微调外,SimpleTuner 还通过 LyCORIS 广泛支持参数效率微调。 要进行推理,请使用本软件仓库中的自定义管道,并按照 SimpleTuner 中的示例在 LyCORIS 权重中打补丁。

from lycoris import create_lycoris_from_weightspipe = DiffusionPipeline.from_pretrained("jimmycarter/LibreFLUX",custom_pipeline="jimmycarter/LibreFLUX",use_safetensors=True,torch_dtype=torch.bfloat16,trust_remote_code=True,
)lycoris_safetensors_path = 'pytorch_lora_weights.safetensors'
wrapper, _ = create_lycoris_from_weights(1.0, lycoris_safetensors_path, pipe.transformer)
wrapper.merge_to()
del wrapperprompt = "Photograph of a chalk board on which is written: 'I thought what I'd do was, I'd pretend I was one of those deaf-mutes.'"
negative_prompt = "blurry"
images = pipe(prompt=prompt,negative_prompt=negative_prompt,return_dict=False,
)
images[0][0].save('chalkboard.png')# optionally, save a merged pipeline containing the LyCORIS baked-in:
# pipe.save_pretrained('/path/to/output/pipeline')

Schnell 脱馏非技术报告

欢迎阅读我的非技术性报告,在资源极其有限的情况下,我用最不科学的方法对 FLUX.1-schnell 进行了去蒸馏。 我不敢说我做了一个很好的模型,但我确实做了一个模型。 它是在大约 1,500 H100 小时当量的基础上训练出来的。

在这里插入图片描述
人人都是艺术家机器学习研究员。

为什么

FLUX 是一个很好的文本到图像模型,但目前推出的版本都是经过提炼的。 FLUX.1-dev 经过蒸馏后无需使用 CFG(无分类器引导),因此无需为有条件(您的提示)和无条件(否定提示)制作样本,只需为有条件制作样本即可。 这意味着,FLUX.1-dev 的速度是没有经过蒸馏的模型的两倍。

FLUX.1-schnell(德语,意为 “快速”)经过进一步提炼,只需 4 步条件生成即可获得图像。 重要的是,FLUX.1-schnell 采用 Apache-2.0 许可,因此您可以免费使用,无需从 Black Forest Labs 获得商业许可。 开箱即用的 schnell 在使用 CFG 时非常糟糕,除非跳过前几个步骤。

FLUX 蒸馏模型是通过对教师模型(非蒸馏模型)和学生模型(蒸馏模型)的输出进行训练,再加上一些技巧(如对抗网络),为其基础模型(非蒸馏模型)创建的。

对于去除法模型,图像生成所需的时间比两倍还少,因为每一步都需要计算条件图像和非条件图像的样本。 这样做的好处是您可以免费在商业上使用它们,训练也更容易一些,而且它们可能更有创造力。

恢复最初的培训目标

这部分其实很简单。 您只需用 MSE 损失对正常流量匹配目标进行训练,模型就会开始重新学习如何进行匹配。 尽管如此,我并不认为 LibreFLUX 或 OpenFLUX.1 能够完全去除模型的抖动。 我看到的证据是,当使用的 CFG 比例值大于 4.0 时,这两个模型都会出现压倒图像的奇怪阴影或模糊现象。 与原始模型的训练时间(假设约为 0.5-2.0m H100 小时)相比,我们的训练时间都不长,所以这并不特别令人惊讶。

FLUX 和注意力掩蔽

FLUX 模型使用一种名为 T5-XXL 的文本模型来获取文本到图像任务的大部分条件。 重要的是,它们将文本填充为 256 个(schnell)或 512 个(dev)词组。 512 个标记是模型的最大训练长度。 所谓填充,是指重复最后一个标记,直到序列达到这个长度。

这就导致模型使用这些填充标记来存储信息。 如果将文本编码器填充段中标记符的注意力图可视化,就会发现在文本最后一个标记符之后不久的大约 10-40 个标记符和填充符末尾的大约 10-40 个标记符都包含模型用来制作图像的信息。 由于这些信息通常用于存储信息,这意味着任何足够长的提示符如果没有这些填充标记,最终都会导致性能下降。

要防止这种情况很容易,只要在注意力集中时屏蔽掉这些填充标记即可。 BFL 和他们的工程师都知道这一点,但他们可能决定不这么做,因为这样做可以保持原样,而且注意力的大多数快速实现都只使用因果(LLM)类型的填充,这样可以让他们训练得更快。

我已经实现了注意力屏蔽,我希望能够使用全部 512 个代币而不降低性能,因此我在进行微调时开启了注意力屏蔽。 小规模的微调往往会对模型造成损害,但由于我需要对蒸馏 schnell 进行大量训练才能让它正常工作,所以我觉得添加它可能没什么关系。

请注意,FLUX.1-schnell 只在 256 个标记上进行了训练,所以我的微调允许用户使用整个 512 个标记序列长度。

快速去除法,适合小型 GPU

由于 FLUX 很大,我完全避免进行任何全等级(正常,所有参数)微调。 我最初使用 quanto 以 int8 精度训练模型。 因为 LoKr 比 LoRA 更接近全等级微调,所以我从 6 亿个参数的 LoKr 开始。 刚开始时,损耗下降得非常慢,所以在尝试了将矩阵初始化到 LoKr 的代码后,我决定使用这个函数,它注入的噪声量只是所应用层的量级的一小部分。

def approximate_normal_tensor(inp, target, scale=1.0):tensor = torch.randn_like(target)desired_norm = inp.norm()desired_mean = inp.mean()desired_std = inp.std()current_norm = tensor.norm()tensor = tensor * (desired_norm / current_norm)current_std = tensor.std()tensor = tensor * (desired_std / current_std)tensor = tensor - tensor.mean() + desired_meantensor.mul_(scale)target.copy_(tensor)def init_lokr_network_with_perturbed_normal(lycoris, scale=1e-3):with torch.no_grad():for lora in lycoris.loras:lora.lokr_w1.fill_(1.0)approximate_normal_tensor(lora.org_weight, lora.lokr_w2, scale=scale)

这已经不是普通的 PEFT(参数有效微调)了,因为这会在开始时轻微扰动模型的所有权重。 经过测试,这似乎不会导致模型性能下降,而且它使我的 LoKr 的损失下降速度快了一倍,因此我在 scale=1e-3 时使用了它。 我用 bfloat16 训练了 LoKr 权重,并使用了 adamw_bf16 优化器。

利用 LoKr 选择更好的训练层

FLUX 是一个非常标准的变换器模型,但也有一些特殊之处。 其中一个特殊之处在于它们的 "规范 "层,该层包含非线性,因此除了在层中应用单一的规范化而不带任何权重(LayerNorm with elementwise_affine=False)外,它们的行为并不像规范。 当你进行微调并查看这些层的变化时,这些层似乎是变化最大的层之一。

关于变换器的另一个问题是,所有繁重的工作通常都是在网络的起始层和末端层完成的,因此你可以对这些层进行比其他层更多的微调。 当我观察扩散变换器中每个区块之间隐藏状态的余弦相似度时,它或多或少反映了在 LLMs 中观察到的情况。 因此,我向 LyCORIS 资源库(该资源库维护着一个 LoKr 实现)提出了一个拉动请求,该请求可以让您更轻松地选择单个层并在其上设置不同的因子,然后将我的 LoKr 重点放在这些层上。

Beta 时间步调度和时间步分层

扩散模型的一个问题是,它们是多任务模型(不同的时间步被视为不同的任务),而所有任务往往都与不同形状和大小的梯度以及不同程度的损失相关联。 如果批处理量很大,这并不是什么大问题,因此模型的时间步都会得到或多或少的均匀采样,梯度也会变得平滑,方差也会变小。 我还知道,schnell 模型在高噪声时间步采样时造成的图像失真问题较多,因此我做了两件事:

  1. 实施近似于原始 sigmoid 采样的 Beta 计划,让我将采样的时间步移到高噪声步,类似于 SD3 研究论文中的一些替代采样方法,但没有那么极端。
  2. 实施多级分层采样,以便在每一步中根据区域选择每批模型训练的时间步,这就像使用更大的批次规模一样,使梯度显著归一化。
from scipy.stats import beta as sp_betaalpha = 2.0
beta = 1.6
num_processes = self.accelerator.num_processes
process_index = self.accelerator.process_index
total_bsz = num_processes * bsz
start_idx = process_index * bsz
end_idx = (process_index + 1) * bsz
indices = torch.arange(start_idx, end_idx, dtype=torch.float64)
u = torch.rand(bsz)
p = (indices + u) / total_bsz
sigmas = torch.from_numpy(sp_beta.ppf(p.numpy(), a=alpha, b=beta)
).to(device=self.accelerator.device)

数据集

现在没有人再谈论他们训练的数据集是什么了,但我使用的是从网上公开的数据集,每个图像有 2-3 个 VLM 标题。 每张图片至少有一个短标题和一个长标题。 数据集多种多样,其中大部分没有审美选择,这有助于引导模型摆脱文本到图像模型的传统超优化图像生成方式。 很多人认为这看起来更糟糕,但我喜欢它能生成一堆不同的图像。 该模型在约 50 万张高分辨率图片上进行了随机正方形裁剪和随机长宽比裁剪的训练。

训练

我使用 5x 3090s 和大约 500,000 张图像开始了为期一个多月的训练。 我使用的是 600m LoKr,批量为 1(通过 DDP 有效批量为 5)。 之后,模型看起来还不错。 后来,我意外地获得了 7x H100 的计算资源,于是我将 PEFT 模型合并进来,开始在一个新的 LoKr 上以 3.2b 的参数进行训练。 在运行 7x H100 时,我的批处理规模为 6(通过 DDP,有效批处理规模为 42)。

图 1. LibreFLUX 和 OpenFLUX.1 的并排图像。 它们是使用扩散器制作的,LibreFLUX 的文本嵌入最大长度为 512 个标记,OpenFLUX.1 的文本嵌入最大长度为 256 个标记。 LibreFLUX 开启了注意力屏蔽,而 OpenFLUX 没有。 模型在不同分辨率下采样 35 步。 两者的负面提示都是 “模糊”。 所有推理都是通过 quanto 将变压器量化为 int8 来完成的。

在这里插入图片描述

A cinematic style shot of a polar bear standing confidently in the center of a vibrant nightclub. The bear is holding a large sign that reads ‘Open Source! Apache 2.0’ in one arm and giving a thumbs up with the other arm. Around him, the club is alive with energy as colorful lasers and disco lights illuminate the scene. People are dancing all around him, wearing glowsticks and candy bracelets, adding to the fun and electric atmosphere. The polar bear’s white fur contrasts against the dark, neon-lit background, and the entire scene has a surreal, festive vibe, blending technology activism with a lively party environment.

在这里插入图片描述

widescreen, vintage style from 1970s, Extreme realism in a complex, highly detailed composition featuring a woman with extremely long flowing rainbow-colored hair. The glowing background, with its vibrant colors, exaggerated details, intricate textures, and dynamic lighting, creates a whimsical, dreamy atmosphere in photorealistic quality. Threads of light that float and weave through the air, adding movement and intrigue. Patterns on the ground or in the background that glow subtly, adding a layer of complexity.Rainbows that appear faintly in the background, adding a touch of color and wonder.Butterfly wings that shimmer in the light, adding life and movement to the scene.Beams of light that radiate softly through the scene, adding focus and direction. The woman looks away from the camera, with a soft, wistful expression, her hair framing her face.

在这里插入图片描述

a highly detailed and atmospheric, painted western movie poster with the title text “Once Upon a Lime in the West” in a dark red western-style font and the tagline text “There were three men … and one very sour twist”, with movie credits at the bottom, featuring small white text detailing actor and director names and production company logos, inspired by classic western movie posters from the 1960s, an oversized lime is the central element in the middle ground of a rugged, sun-scorched desert landscape typical of a western, the vast expanse of dry, cracked earth stretches toward the horizon, framed by towering red rock formations, the absurdity of the lime is juxtaposed with the intense gravitas of the stoic, iconic gunfighters, as if the lime were as formidable an adversary as any seasoned gunslinger, in the foreground, the silhouettes of two iconic gunfighters stand poised, facing the lime and away from the viewer, the lime looms in the distance like a final showdown in the classic western tradition, in the foreground, the gunfighters stand with long duster coats flowing in the wind, and wide-brimmed hats tilted to cast shadows over their faces, their stances are tense, as if ready for the inevitable draw, and the weapons they carry glint, the background consists of the distant town, where the sun is casting a golden glow, old wooden buildings line the sides, with horses tied to posts and a weathered saloon sign swinging gently in the wind, in this poster, the lime plays the role of the silent villain, an almost mythical object that the gunfighters are preparing to confront, the tension of the scene is palpable, the gunfighters in the foreground have faces marked by dust and sweat, their eyes narrowed against the bright sunlight, their expressions are serious and resolute, as if they have come a long way for this final duel, the absurdity of the lime is in stark contrast with their stoic demeanor, a wide, panoramic shot captures the entire scene, with the gunfighters in the foreground, the lime in the mid-ground, and the town on the horizon, the framing emphasizes the scale of the desert and the dramatic standoff taking place, while subtly highlighting the oversized lime, the camera is positioned low, angled upward from the dusty ground toward the gunfighters, with the distant lime looming ahead, this angle lends the figures an imposing presence, while still giving the lime an absurd grandeur in the distance, the perspective draws the viewer’s eye across the desert, from the silhouettes of the gunfighters to the bizarre focal point of the lime, amplifying the tension, the lighting is harsh and unforgiving, typical of a desert setting, with the evening sun casting deep shadows across the ground, dust clouds drift subtly across the ground, creating a hazy effect, while the sky above is a vast expanse of pale blue, fading into golden hues near the horizon where the sun begins to set, the poster is shot as if using classic anamorphic lenses to capture the wide, epic scale of the desert, the color palette is warm and saturated, evoking the look of a classic spaghetti western, the lime looms unnaturally in the distance, as if conjured from the land itself, casting an absurdly grand shadow across the rugged landscape, the texture and detail evoke hand-painted, weathered posters from the golden age of westerns, with slightly frayed edges and faint creases mimicking the wear of vintage classics

在这里插入图片描述

Selfie of a woman in front of the eiffel tower, a man is standing next to her and giving a thumbs up

https://huggingface.co/jimmycarter/LibreFLUX


http://www.mrgr.cn/news/60108.html

相关文章:

  • MarkDown代码
  • Linux LVS详解
  • 『 Linux 』网络传输层 - TCP (一)
  • verilog中的function函数
  • Aptos Move 模块的发布与交互:完整指南
  • 2024年度最新家居好物分享!提升居家幸福感的秘密好物!
  • spring-第十二章 GoF代理模式
  • Bootstrap 5 弹出框
  • MSR寄存器独有的还是共享的
  • Java最全面试题->数据库/中间件->RocketMQ面试题
  • 后台管理系统的通用权限解决方案(三)SpringBoot整合Knife4j生成接口文档
  • 问:SQL中的通用函数及用法?
  • AI学习指南自然语言处理篇-Transformer模型的实践
  • fastjson解析null值问题: 解决 null的属性不显示问题
  • 如何从示波器上得到时间常数
  • Mybatis的关联关系-多对多
  • Python | Leetcode Python题解之第515题在每个树行中找最大值
  • 问:MySQL中的常用SQL函数整理?
  • jQuery Callback
  • 自由职业者的一天:作为小游戏开发者的真实工作日记
  • 栈和队列(上)-栈
  • 【skywalking 】监控 Spring Cloud Gateway 数据
  • 【c++高级篇】--多任务编程/多线程(Thread)
  • spring-第十一章 注解开发
  • C语言 | Leetcode C语言题解之第516题最长回文子序列
  • 《贪婪算法实战:从理论到面试题的全面解析》