Hugging Face Diffusers Custom Diffusion 训练指南:用 4~5 张示例图实现图像生成模型个性化
2026/9/12 8:54:07 网站建设 项目流程

Hugging Face Diffusers Custom Diffusion 训练指南:用 4~5 张示例图实现图像生成模型个性化

【免费下载链接】diffusers🤗 Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusers

Custom Diffusion 是 🤗 Diffusers 生态中一种面向图像生成模型的个性化训练技术,与 Textual Inversion、DreamBooth、LoRA 一样,只需要约 4~5 张示例图片即可完成概念注入。与上述方法不同,Custom Diffusion 只训练交叉注意力(cross-attention)层的权重,并借助一个特殊占位词(modifier token)来代表新学到的概念,而且它还能同时学习多个概念。本文将以 docs/source/en/training/custom_diffusion.md 为骨架,结合仓库中的 train_custom_diffusion.py 训练脚本、retrieve.py 数据采集脚本与 test_custom_diffusion.py 测试用例,完整讲解环境准备、脚本参数、正则化策略、训练代码原理,以及单概念与多概念场景下的训练与推理实战。

一、Custom Diffusion 核心原理:只训练交叉注意力层

Custom Diffusion 出自论文 Multi-Concept Customization of Text-to-Image Diffusion(arXiv:2212.04488)。它的设计思路非常简洁:在扩散模型的 UNet 中,文本条件正是通过交叉注意力层注入到图像生成过程中的,因此只需要微调交叉注意力层的键(Key)与值(Value)投影权重,就足以让模型学会把某个新概念绑定到指定文本 token 上,而不必像 DreamBooth 那样微调整个 UNet。

仓库训练脚本 train_custom_diffusion.py 中通过--freeze_model参数控制冻结范围:

  • crossattn_kv(默认):只训练交叉注意力层中的 K、V 投影;
  • crossattn:训练交叉注意力层中的所有参数(K、V、Q 与输出投影)。

对应到源码中,该参数直接影响train_q_out的取值(train_custom_diffusion.py):

# Only train key, value projection layers if freeze_model = 'crossattn_kv' else train all params in the cross attention layer train_kv = True train_q_out = False if args.freeze_model == "crossattn_kv" else True

与微调整个 UNet 相比,可训练参数数量大幅减少,这正是 Custom Diffusion 能用极少数据、在有限显存下完成训练的根本原因。同时,文本编码器的所有参数也会被冻结,仅保留新加入的 modifier token 嵌入参与学习(详见下文"训练脚本解析")。

二、环境准备与依赖安装

1. 从源码安装 diffusers

建议从源码安装 diffusers 库,以保证训练脚本与库版本一致:

git clone https://github.com/huggingface/diffusers cd diffusers pip install .

也可以使用pip install -e .进行可编辑安装,便于跟随示例脚本的更新同步代码。

2. 安装示例依赖

进入 Custom Diffusion 示例目录并安装依赖(依赖清单见 requirements.txt):

cd examples/custom_diffusion pip install -r requirements.txt pip install clip-retrieval

requirements.txt 中包含acceleratetorchvisiontransformers>=4.25.1ftfytensorboardJinja2。其中:

  • accelerate:负责多 GPU / TPU 训练与混合精度管理;
  • clip-retrieval:用于从 LAION 数据集中检索真实图片作为正则化样本(详见"正则化"一节),它不属于 requirements.txt,需要单独安装;
  • tensorboard:默认的日志后端,若改用 wandb 则需额外安装wandb

3. 初始化 Accelerate 环境

🤗 Accelerate 会根据你的硬件自动配置训练环境,支持多 GPU、TPU 与混合精度。有三种初始化方式:

交互式配置(推荐):

accelerate config

使用默认配置(无需回答任何问题):

accelerate config default

在笔记本等无交互 shell 环境中使用 Python API:

from accelerate.utils import write_basic_config write_basic_config()

如果你打算用自己的数据集训练,可先阅读 创建用于训练的数据集 指南,了解如何构造与训练脚本兼容的数据集结构。

提示:accelerate launch是训练脚本的标准启动方式。脚本其余部分(训练循环、评估、保存)依赖 Accelerate 提供的Accelerator对象统一调度设备、混合精度与分布式状态。

4. 显存优化建议

  • 在显存有限的 GPU 上,开启 xFormers 内存高效注意力可以显著降低显存占用(约 16GB 即可训练):在训练命令中加入--enable_xformers_memory_efficient_attention。源码会在启用该参数时切换到CustomDiffusionXFormersAttnProcessor(train_custom_diffusion.py),若未安装 xformers 会直接报错提示。
  • 进一步节省显存可以加入--set_grads_to_none:将梯度置为None而非零。该选项会改变某些行为,若训练中遇到异常,请先尝试移除该参数。其底层对应 PyTorch 的optimizer.zero_grad(set_to_none=True)(train_custom_diffusion.py)。
  • 8GB/16GB 级显卡还可考虑--use_8bit_adam(基于 bitsandbytes 的 8-bit Adam,需要单独安装 bitsandbytes)与--gradient_checkpointing(以更慢的反向传播换取更低显存)。

三、脚本参数详解

所有训练参数都在训练脚本的parse_args()函数中定义(train_custom_diffusion.py),均带默认值,可通过命令行覆盖。例如修改输入图像分辨率:

accelerate launch train_custom_diffusion.py \ --resolution=256

许多基础参数(如--pretrained_model_name_or_path--instance_data_dir--output_dir--resolution--train_batch_size--learning_rate--max_train_steps等)与 DreamBooth 训练指南 一致,这里不再赘述。下面重点说明 Custom Diffusion 独有的四个核心参数:

参数默认值说明
--freeze_modelcrossattn_kv冻结交叉注意力层的 K/V 参数;设为crossattn时训练交叉注意力层全部参数。取值限定为["crossattn_kv", "crossattn"](源码)
--concepts_listNone学习多个概念时,提供一个包含各概念信息的 JSON 文件路径(JSON 会覆盖instance_promptclass_prompt等参数)
--modifier_tokenNone代表所学概念的特殊占位词,如<new1>;多概念时用+分隔,如<new1>+<new2>
--initializer_tokenktn+pll+ucd用于初始化modifier_token嵌入的初始词,多概念同样用+分隔

关于 modifier token 与 initializer token 的对应关系,源码(train_custom_diffusion.py)要求:

  • modifier_tokeninitializer_token均按+拆分并一一对应;
  • 若 modifier token 数量多于 initializer token,脚本会直接抛出ValueError
  • modifier token 必须是 tokenizer 中尚不存在的词(tokenizer.add_tokens返回 0 时报错),以保证它是一个真正"新"的占位符;
  • initializer token 必须能被编码为单个 token(编码结果超过 1 个 token 时报错)。

其他值得关注的参数

  • --scale_lr:按gradient_accumulation_steps × train_batch_size × num_processes自动放大学习率;开启 prior preservation 时再额外乘以 2.0(train_custom_diffusion.py)。
  • --lr_scheduler:默认constant,可选["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"]
  • --report_to:默认tensorboard,可选wandbcomet_mlall
  • --mixed_precision:可选no/fp16/bf16bf16需要 PyTorch ≥ 1.10 且为 Ampere 及以上架构的 NVIDIA GPU。
  • --noaug:关闭训练中的随机尺寸缩放等数据增强(人脸训练建议开启)。
  • --center_crop:开启时对输入图像居中裁剪,否则随机裁剪。
  • --no_safe_serialization:以.bin(PyTorch 原生格式)而非.safetensors保存权重。
  • --checkpointing_steps(默认 250)与--resume_from_checkpoint--checkpoints_total_limit:控制训练中断点保存、恢复与数量上限,仓库测试 test_custom_diffusion.py 专门验证了 checkpoint 轮换与断点续训行为。

四、防止过拟合:先验保持损失与正则化

Custom Diffusion 仅用几张图训练,极易过拟合。脚本提供了两级防护:

1. 先验保持损失(Prior Preservation Loss)

先验保持损失利用模型自身的生成样本,帮助模型保留对目标类别的既有认知。由于生成样本与目标图片属于同一类别,模型能在学习新概念的同时不忘记"如何画一只猫"。相关参数与 DreamBooth 训练指南 一致:--with_prior_preservation--prior_loss_weight--class_prompt--num_class_images

2. 用真实图片做正则化(--real_prior

Custom Diffusion 的独特之处在于:它支持用一小批真实图片参与训练以抑制过拟合。脚本通过clip_retrieval按类别提示词从大规模图文数据集中检索 200 张真实图片,class_prompt应与目标图片属于同一类别,检索结果存放在class_data_dir指定的目录。

首先安装并运行检索脚本 retrieve.py:

python retrieve.py --class_prompt cat --class_data_dir real_reg/samples_cat --num_class_images 200

从源码看,retrieve.py会通过 CLIP 检索 LAION-400M 索引(retrieve.py),按 1.5 倍冗余量查询候选,逐张下载图片,并在class_data_dir下生成images/caption.txturls.txtimages.txt(retrieve.py)。CustomDiffusionDataset会优先读取images/目录中的图片,若该路径是文本文件,则按行读取图片路径与类别提示词(train_custom_diffusion.py)。

训练时开启正则化只需加上如下参数:

accelerate launch train_custom_diffusion.py \ --with_prior_preservation \ --prior_loss_weight=1.0 \ --class_data_dir="./real_reg/samples_cat" \ --class_prompt="cat" \ --real_prior=True \
  • --with_prior_preservation:是否启用先验保持损失;
  • --prior_loss_weight:控制先验保持损失对模型的影响权重;
  • --real_prior:是否使用真实图片做正则化;不启用时(默认生成图片)则用模型自身生成的类别样本充当先验。

注意:脚本在--with_prior_preservation开启时强制要求提供class_data_dirclass_prompt,否则直接抛错(train_custom_diffusion.py)。反过来,未开启该选项却传入了这两个参数时,脚本仅给出警告。

在损失计算层面,训练循环会把模型输出与目标按 batch 维度切分为实例部分与先验部分,分别计算 MSE 损失后按权重合并(train_custom_diffusion.py):

if args.with_prior_preservation: model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0) target, target_prior = torch.chunk(target, 2, dim=0) mask = torch.chunk(batch["mask"], 2, dim=0)[0] loss = F.mse_loss(model_pred.float(), target.float(), reduction="none") loss = ((loss * mask).sum([1, 2, 3]) / mask.sum([1, 2, 3])).mean() prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction="mean") loss = loss + args.prior_loss_weight * prior_loss

注意这里的maskCustomDiffusionDataset在预处理时会对目标图片做随机缩放、裁剪,并同步生成"有效图像区域掩码",损失只在掩码覆盖的真实内容区域上计算,从而进一步缓解小样本下的背景记忆与过拟合(train_custom_diffusion.py)。

五、训练脚本解析

Custom Diffusion 的训练脚本与 DreamBooth 大量相似,以下仅聚焦其特有实现。

1. 两个数据集类

脚本中定义了两个数据集类:

  • CustomDiffusionDataset:负责预处理实例图片、类别图片与提示词。它支持多概念(遍历concepts_list收集各概念的实例图与类别图)、随机水平翻转、随机缩放裁剪增强,并生成与裁剪区域对应的掩码;开启with_prior_preservation时还会把类别图片与其提示词成对组装进数据集(train_custom_diffusion.py)。数据集长度取实例图片数与类别图片数的较大值,采样时按索引取模轮转,保证每个 epoch 两类样本都被充分利用(train_custom_diffusion.py)。
  • PromptDataset:当--real_prior未开启、需要用模型生成类别样本时,为多 GPU 环境准备提示词数据。

__getitem__中还包含一个细节:当随机缩放尺度小于 0.6 倍原始尺寸时,会在提示词前拼接 "a far away " 或 "very small ";当放大超过原始尺寸时,则拼接 "zoomed in " 或 "close up "(train_custom_diffusion.py)。这套基于视觉缩放程度的提示词自适应,能让模型理解"远/近"语义,是 Custom Diffusion 官方实现中的特色增强。

2. 注入 modifier token 并初始化嵌入

下一步是把modifier_token加入 tokenizer、转为 token id,并扩容 token 嵌入矩阵以容纳新 token;随后用initializer_token的嵌入初始化modifier_token的嵌入(train_custom_diffusion.py):

text_encoder.resize_token_embeddings(len(tokenizer)) token_embeds = text_encoder.get_input_embeddings().weight.data for x, y in zip(modifier_token_id, initializer_token_id): token_embeds[x] = token_embeds[y]

随后冻结文本编码器中除 token 嵌入外的全部参数——因为模型要学习的就是"把新概念与这些 token 嵌入关联起来":

params_to_freeze = itertools.chain( text_encoder.text_model.encoder.parameters(), text_encoder.text_model.final_layer_norm.parameters(), text_encoder.text_model.embeddings.position_embedding.parameters(), ) freeze_params(params_to_freeze)

同时,vaeunet主体也通过requires_grad_(False)完全冻结(train_custom_diffusion.py),整条训练链中只有交叉注意力处理器与 modifier token 嵌入可更新。

3. 向注意力层注入 Custom Diffusion 权重

这是决定注意力权重形状与数量正确性的关键步骤(train_custom_diffusion.py)。脚本遍历 UNet 的每个注意力处理器,依据所在块(down/mid/up)从unet.config.block_out_channels推导hidden_size,依据是否为交叉注意力(attn1为自注意力、attn2为交叉注意力)决定cross_attention_dim,并据此构造CustomDiffusionAttnProcessor

st = unet.state_dict() for name, _ in unet.attn_processors.items(): cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim if name.startswith("mid_block"): hidden_size = unet.config.block_out_channels[-1] elif name.startswith("up_blocks"): block_id = int(name[len("up_blocks.")]) hidden_size = list(reversed(unet.config.block_out_channels))[block_id] elif name.startswith("down_blocks"): block_id = int(name[len("down_blocks.")]) hidden_size = unet.config.block_out_channels[block_id] layer_name = name.split(".processor")[0] weights = { "to_k_custom_diffusion.weight": st[layer_name + ".to_k.weight"], "to_v_custom_diffusion.weight": st[layer_name + ".to_v.weight"], } if train_q_out: weights["to_q_custom_diffusion.weight"] = st[layer_name + ".to_q.weight"] weights["to_out_custom_diffusion.0.weight"] = st[layer_name + ".to_out.0.weight"] weights["to_out_custom_diffusion.0.bias"] = st[layer_name + ".to_out.0.bias"] if cross_attention_dim is not None: custom_diffusion_attn_procs[name] = attention_class( train_kv=train_kv, train_q_out=train_q_out, hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, ).to(unet.device) custom_diffusion_attn_procs[name].load_state_dict(weights) else: custom_diffusion_attn_procs[name] = attention_class( train_kv=False, train_q_out=False, hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, ) del st unet.set_attn_processor(custom_diffusion_attn_procs) custom_diffusion_layers = AttnProcsLayers(unet.attn_processors)

代码注释给出一个直观的数量估算:对 Stable Diffusion 结构而言,共 32 个注意力层(down 12 + mid 2 + up 18)。自注意力处理器(attn1)保持完全冻结(train_kv=False, train_q_out=False),只有交叉注意力处理器承载可训练权重。处理器实现位于 src/diffusers/models/attention_processor.py 中的CustomDiffusionAttnProcessor,并在 PyTorch ≥ 2.0 支持scaled_dot_product_attention时自动切换到CustomDiffusionAttnProcessor2_0(train_custom_diffusion.py)。

4. 优化器:只更新交叉注意力层与 token 嵌入

优化器仅接收文本编码器输入嵌入(token 嵌入)与自定义注意力层的参数:

optimizer = optimizer_class( itertools.chain(text_encoder.get_input_embeddings().parameters(), custom_diffusion_layers.parameters()) if args.modifier_token is not None else custom_diffusion_layers.parameters(), lr=args.learning_rate, betas=(args.adam_beta1, args.adam_beta2), weight_decay=args.adam_weight_decay, eps=args.adam_epsilon, )

默认使用torch.optim.AdamW;指定--use_8bit_adam时切换为bitsandbytes.optim.AdamW8bit(train_custom_diffusion.py)。

5. 训练循环:只更新目标概念 token 的梯度

训练循环最关键的细节是:只更新当前学习概念的 token 嵌入梯度,其余 token 嵌入的梯度一律清零(train_custom_diffusion.py):

if args.modifier_token is not None: if accelerator.num_processes > 1: grads_text_encoder = text_encoder.module.get_input_embeddings().weight.grad else: grads_text_encoder = text_encoder.get_input_embeddings().weight.grad index_grads_to_zero = torch.arange(len(tokenizer)) != modifier_token_id[0] for i in range(1, len(modifier_token_id)): index_grads_to_zero = index_grads_to_zero & ( torch.arange(len(tokenizer)) != modifier_token_id[i] ) grads_text_encoder.data[index_grads_to_zero, :] = grads_text_encoder.data[ index_grads_to_zero, : ].fill_(0)

这段逻辑先在梯度回传后构造一个"除 modifier token 外全部置零"的布尔索引,再把其他所有 token 的梯度清零,确保大规模嵌入矩阵中只有新概念相关的行发生更新。多概念训练时,多个 modifier token 的梯度都会被保留。

6. 模型保存与训练中验证

训练结束后,主进程会把可训练部分分别保存(train_custom_diffusion.py):

  • 注意力层权重:unet.save_attn_procs(output_dir, ...)生成pytorch_custom_diffusion_weights.safetensors(或.bin);
  • token 嵌入:save_new_embed()为每个 modifier token 单独保存<new1>.safetensors(或<new1>.bin)文件(train_custom_diffusion.py)。

此外,脚本内置了训练中验证:指定--validation_prompt--validation_steps后,会周期性构建推理管线(使用 DPMSolverMultistepScheduler)生成示例图并记录到 TensorBoard 或 wandb(train_custom_diffusion.py)。训练结束还会自动跑一次"最终推理"以自检模型效果。

六、启动训练:单概念 vs 多概念

单概念训练(示例:猫)

下载官方示例猫图数据集(约 4~5 张),或用 创建用于训练的数据集 指南构造自己的数据集。然后设置环境变量并启动训练:

export MODEL_NAME="CompVis/stable-diffusion-v1-4" export OUTPUT_DIR="path-to-save-model" export INSTANCE_DIR="./data/cat" accelerate launch train_custom_diffusion.py \ --pretrained_model_name_or_path=$MODEL_NAME \ --instance_data_dir=$INSTANCE_DIR \ --output_dir=$OUTPUT_DIR \ --class_data_dir=./real_reg/samples_cat/ \ --with_prior_preservation \ --real_prior \ --prior_loss_weight=1.0 \ --class_prompt="cat" \ --num_class_images=200 \ --instance_prompt="photo of a <new1> cat" \ --resolution=512 \ --train_batch_size=2 \ --learning_rate=1e-5 \ --lr_warmup_steps=0 \ --max_train_steps=250 \ --scale_lr \ --hflip \ --modifier_token "<new1>" \ --validation_prompt="<new1> cat sitting in a bucket" \ --report_to="wandb" \ --push_to_hub
  • --instance_prompt中的<new1>是与 modifier token 对应的提示词占位符;
  • --hflip开启水平翻转增强;--scale_lr自动按批量与进程数缩放学习率;
  • 添加--report_to=wandb--validation_prompt后,可用 Weights & Biases 监控训练进度、调试并保存中间结果;配套的--num_validation_images(默认 2)与--validation_steps(默认 50)可调整验证频率;
  • 添加--push_to_hub会把学到的参数推送到 Hugging Face Hub 仓库;
  • 若使用 stable-diffusion-2 的 768×768 模型,需把--resolution改为 768。

多概念训练(示例:猫 + 木壶)

Custom Diffusion 的独特能力是同时学习多个概念。此时提供一个 JSON 文件(如concept_list.json),其中按概念列出instance_data_dirinstance_promptclass_data_dirclass_prompt等信息,脚本会读取该文件并覆盖对应的命令行参数(train_custom_diffusion.py)。

先为 JSON 中的每个概念分别运行 clip-retrieval 收集真实正则化图片:

pip install clip-retrieval python retrieve.py --class_prompt {} --class_data_dir {} --num_class_images 200

然后启动训练:

export MODEL_NAME="CompVis/stable-diffusion-v1-4" export OUTPUT_DIR="path-to-save-model" accelerate launch train_custom_diffusion.py \ --pretrained_model_name_or_path=$MODEL_NAME \ --output_dir=$OUTPUT_DIR \ --concepts_list=./concept_list.json \ --with_prior_preservation \ --real_prior \ --prior_loss_weight=1.0 \ --resolution=512 \ --train_batch_size=2 \ --learning_rate=1e-5 \ --lr_warmup_steps=0 \ --max_train_steps=500 \ --num_class_images=200 \ --scale_lr \ --hflip \ --modifier_token "<new1>+<new2>" \ --push_to_hub

注意多概念时 modifier token 用+连接(<new1>+<new2>),脚本会将其拆分为两个 token 分别初始化与优化。

人脸训练经验参数

若训练对象是人脸,Custom Diffusion 团队验证过以下参数组合效果更好(完整命令见 examples/custom_diffusion/README.md):

  • --learning_rate=5e-6
  • --max_train_steps设置在 1000~2000 之间
  • --freeze_model=crossattn(训练交叉注意力全部参数)
  • 至少使用 15~20 张图片
  • 收集正则化图片时使用--class_prompt person

七、推理:加载注意力权重与文本反转嵌入

训练完成后,产物包含两套权重:pytorch_custom_diffusion_weights.safetensors/.bin(交叉注意力层权重)与<new1>.safetensors/.bin(modifier token 嵌入)。推理时需要同时加载两者。

单概念推理

import torch from diffusers import DiffusionPipeline pipeline = DiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", dtype=torch.float16, ).to("cuda") # 或 "mps"、"xpu"、"cpu" pipeline.unet.load_attn_procs("path-to-save-model", weight_name="pytorch_custom_diffusion_weights.bin") pipeline.load_textual_inversion("path-to-save-model", weight_name="<new1>.bin") image = pipeline( "<new1> cat sitting in a bucket", num_inference_steps=100, guidance_scale=6.0, eta=1.0, ).images[0] image.save("cat.png")
  • load_attn_procs把训练好的交叉注意力处理器挂载到 UNet;
  • load_textual_inversion把训练好的<new1>token 嵌入注入文本编码器;
  • 提示词中必须包含 modifier token(如<new1>)才能触发学到的概念。

多概念推理

多概念模型需要为每个 modifier token 分别加载文本反转嵌入:

import torch from huggingface_hub.repocard import RepoCard from diffusers import DiffusionPipeline pipeline = DiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", dtype=torch.float16, ).to("cuda") # 或 "mps"、"xpu"、"cpu" model_id = "sayakpaul/custom-diffusion-cat-wooden-pot" pipeline.unet.load_attn_procs(model_id, weight_name="pytorch_custom_diffusion_weights.bin") pipeline.load_textual_inversion(model_id, weight_name="<new1>.bin") pipeline.load_textual_inversion(model_id, weight_name="<new2>.bin") image = pipeline( "the <new1> cat sculpture in the style of a <new2> wooden pot", num_inference_steps=100, guidance_scale=6.0, eta=1.0, ).images[0] image.save("multi-subject.png")

这里catwooden pot分别对应两个已学习的概念,提示词中同时使用<new1><new2>即可组合两个概念。多概念推理还可以直接从 Hub 仓库加载(无需先下载权重到本地),仓库 examples/custom_diffusion/README.md 提供了通过RepoCard读取base_model再加载的完整示例。

八、仓库测试验证

仓库在 test_custom_diffusion.py 中为训练脚本提供了端到端冒烟测试,可作为复现训练管线正确性的参考:

  • test_custom_diffusion:使用微型模型hf-internal-testing/tiny-stable-diffusion-torch跑 2 步训练,断言产出pytorch_custom_diffusion_weights.bin<new1>.bin两个文件;
  • test_custom_diffusion_checkpointing_checkpoints_total_limit..._removes_multiple_checkpoints:验证--checkpointing_steps--checkpoints_total_limit的轮换逻辑,以及--resume_from_checkpoint断点续训后 checkpoint 目录的最终状态。

这组测试说明:训练脚本的可训练权重结构、保存/恢复机制都被自动化用例持续守护,你可以放心地把同样的流程迁移到自己的数据集上。

九、总结与下一步

Custom Diffusion 提供了一种"参数极少、数据极少"的模型个性化路径:只训练交叉注意力层与一个特殊 token 的嵌入,支持单概念与多概念同时学习,并借助真实图片正则化与掩码损失有效抑制小样本过拟合。从本仓库的 train_custom_diffusion.py、retrieve.py 到推理示例,整个闭环都可以直接复制运行。

进一步学习建议:

  • 阅读 Custom Diffusion 团队的 Multi-Concept Customization of Text-to-Image Diffusion 博客,了解论文中的实验结果细节(论文 arXiv:2212.04488);
  • 如需准备自定义数据集,参见 创建用于训练的数据集;
  • 对比学习 DreamBooth 训练指南 中介绍的基础训练参数与先验保持损失用法;
  • 仓库示例目录 examples/custom_diffusion/README.md 中还提供了人脸训练的完整命令、wandb 实验记录示例以及 Hub 推理加载方式。

【免费下载链接】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),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询