AIGC 摄影不是简单“文生图”,而是把摄影语言转成模型可控条件。焦段、光圈、快门、光位、色温、构图、胶片曲线,都是可训练的风格变量。本文从专业角度给出数据集、训练与推理的工程化路径。
摄影 LoRA 的目标是学“风格”而非“内容”。建议同一人物或产品 20–50 张,覆盖多角度、多光位、多景别。清洗去水印,长边统一 1024/1536,保留 EXIF 作为元数据。
打标模板:
photo of {trigger}, 85mm, f/1.4, Rembrandt lighting, softbox,
Kodak Portra 400, shallow depth of field, 3:2关键标签:镜头焦段、光圈、光位、胶片模拟、景深、画幅。加入 5%–10% 通用摄影图做正则化,防止过拟合。
推荐 SDXL + LoRA:rank 16–32,学习率 1e-4,batch 1–2,梯度累积 4,epoch 10–20,文本编码器可训练。使用 AdamW 8bit、fp16、分桶(bucket)与颜色抖动。
使用 diffusers 官方脚本训练:
accelerate launch train_text_to_image_lora_sdxl.py \
--pretrained_model_name_or_path="stabilityai/stable-diffusion-xl-base-1.0" \
--train_data_dir="./photos" \
--output_dir="./lora-photo" \
--resolution=1024 \
--train_batch_size=1 \
--gradient_accumulation_steps=4 \
--learning_rate=1e-4 \
--lr_scheduler="cosine" \
--max_train_steps=2000 \
--rank=32 \
--mixed_precision="fp16" \
--checkpointing_steps=500 \
--caption_column="text"训练核心逻辑可简化为:
from diffusers import StableDiffusionXLPipeline, DDPMScheduler
from peft import LoraConfig, get_peft_model
import torch
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
lora = LoraConfig(
r=32, lora_alpha=32, lora_dropout=0.05,
target_modules=["to_q", "to_k", "to_v", "to_out.0"]
)
unet = get_peft_model(pipe.unet, lora)
optimizer = torch.optim.AdamW(unet.parameters(), lr=1e-4)
for step, batch in enumerate(loader):
pixel_values = batch["pixel_values"].to("cuda", dtype=torch.float16)
noise = torch.randn_like(pixel_values)
timesteps = torch.randint(0, 1000, (pixel_values.size(0),), device="cuda")
noisy = pipe.scheduler.add_noise(pixel_values, noise, timesteps)
pred = unet(noisy, timesteps, encoder_hidden_states=batch["prompt_embeds"]).sample
loss = torch.nn.functional.mse_loss(pred, noise)
loss.backward()
optimizer.step()
optimizer.zero_grad()真实训练还需 VAE 编码、文本编码器缓存、EMA、梯度裁剪与检查点保存。
import torch
from diffusers import StableDiffusionXLPipeline
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
).to("cuda")
pipe.load_lora_weights("./lora-photo", weight_name="pytorch_lora_weights.safetensors")
pipe.fuse_lora(lora_scale=0.8)
prompt = ("photo of sks person, 85mm, f/1.4, Rembrandt lighting, "
"softbox, Kodak Portra 400, shallow depth of field")
image = pipe(
prompt, num_inference_steps=30, guidance_scale=6.0,
width=1024, height=1024
).images[0]
image.save("output.jpg")要精确控制构图与人物一致性,可叠加 ControlNet(OpenPose、Depth、Canny)和 IP-Adapter。摄影参数建议写进提示词模板,而非依赖模型自由发挥。
评估指标:FID、CLIP Score、人工盲测、参数还原度(焦段/光位/胶片感)。每轮训练保留验证集,避免过拟合。
合规三条底线:
AIGC 摄影训练的核心是“把摄影语言结构化”。数据标注决定上限,LoRA 参数决定风格强度,ControlNet 与 IP-Adapter 决定构图与一致性。先跑通单风格 LoRA,再扩展到多光位、多胶片、多焦段组合,才能形成可商用的 AIGC 摄影流水线。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。