从零入门AI生图原理(二)(Datawhale X 魔搭 AI夏令营)

一,baseline代码结构

1、环境安装

!pip install simple-aesthetics-predictor

!pip install -v -e data-juicer

!pip uninstall pytorch-lightning -y
!pip install peft lightning pandas torchvision

!pip install -e DiffSynth-Studio

2、下载数据集

#下载数据集
from modelscope.msdatasets import MsDataset

ds = MsDataset.load(
    'AI-ModelScope/lowres_anime',    # 指定要下载的数据集的唯一标识符
    subset_name='default',    # 指定数据集的子集名称,这里使用默认子集
    split='train',    # 指定下载训练集部分的数据
    cache_dir="/mnt/workspace/kolors/data"    # 指定下载训练集部分的数据
)

import json, os
from data_juicer.utils.mm_utils import SpecialTokens
from tqdm import tqdm

os.makedirs("./data/lora_dataset/train", exist_ok=True)    # 创建用于存储处理后的图像文件的目录,exist_ok=True参数意味着如果目录已经存在,则不会抛出错误
os.makedirs("./data/data-juicer/input", exist_ok=True)    # 创建用于存储Data Juicer所需元数据文件的目录
with open("./data/data-juicer/input/metadata.jsonl", "w") as f:
    # 使用enumerate函数遍历数据集ds,同时获取每个数据项的索引(即数据ID)和数据本身
    for data_id, data in enumerate(tqdm(ds)):    
        image = data["image"].convert("RGB")    # 使用convert("RGB")方法将其转换为RGB模式
        image.save(f"/mnt/workspace/kolors/data/lora_dataset/train/{data_id}.jpg")    # 将处理后的图像保存到指定的文件路径
        # 构造一个包含文本描述和图像路径的字典metadata
        metadata = {"text": "二次元", "image": [f"/mnt/workspace/kolors/data/lora_dataset/train/{data_id}.jpg"]}
        f.write(json.dumps(metadata))    # 将metadata字典转换为JSON格式的字符串
        f.write("\n")

3、处理数据集,保存数据处理结果

data_juicer_config = """
# global parameters
project_name: 'data-process'    # 定义项目的名称
dataset_path: './data/data-juicer/input/metadata.jsonl'  # path to your dataset directory or file
np: 4  # number of subprocess to process your dataset

text_keys: 'text'    # 数据中文本的键名
image_key: 'image'    # 数据中图像的键名
image_special_token: '<__dj__image>'

export_path: './data/data-juicer/output/result.jsonl'    # 指定了处理后数据输出路径

# process schedule
# a list of several process operators with their arguments
# 包含了一系列数据处理的步骤和参数
process:
    - image_shape_filter:
        min_width: 1024
        min_height: 1024
        any_or_all: any
    - image_aspect_ratio_filter:
        min_ratio: 0.5
        max_ratio: 2.0
        any_or_all: any
"""
with open("data/data-juicer/data_juicer_config.yaml", "w") as file:
    file.write(data_juicer_config.strip())

!dj-process --config data/data-juicer/data_juicer_config.yaml


import pandas as pd
import os, json
from PIL import Image
from tqdm import tqdm


texts, file_names = [], []
os.makedirs("./data/lora_dataset_processed/train", exist_ok=True)
with open("./data/data-juicer/output/result.jsonl", "r") as file:
    for data_id, data in enumerate(tqdm(file.readlines())):
        data = json.loads(data)    # 将每行文本从 JSON 字符串转换为 Python 字典
        text = data["text"]
        texts.append(text)
        image = Image.open(data["image"][0])    # 使用 PIL(Pillow)库的 Image.open 方法打开图像文件
        image_path = f"./data/lora_dataset_processed/train/{data_id}.jpg"
        image.save(image_path)
        file_names.append(f"{data_id}.jpg")
data_frame = pd.DataFrame()
data_frame["file_name"] = file_names
data_frame["text"] = texts
data_frame.to_csv("./data/lora_dataset_processed/train/metadata.csv", index=False, encoding="utf-8-sig")
data_frame

4、lora微调

# 下载模型
from diffsynth import download_models
download_models(["Kolors", "SDXL-vae-fp16-fix"])

#模型训练
import os

cmd = """
python DiffSynth-Studio/examples/train/kolors/train_kolors_lora.py \
  --pretrained_unet_path models/kolors/Kolors/unet/diffusion_pytorch_model.safetensors \
  --pretrained_text_encoder_path models/kolors/Kolors/text_encoder \
  --pretrained_fp16_vae_path models/sdxl-vae-fp16-fix/diffusion_pytorch_model.safetensors \
  --lora_rank 16 \    # LoRA矩阵的秩
  --lora_alpha 4.0 \    # alpha值
  --dataset_path data/lora_dataset_processed \
  --output_path ./models \
  --max_epochs 1 \        # 指定了训练的最大轮次
  --center_crop \        # 数据预处理选项,用于在训练前对图像进行中心裁剪
  --use_gradient_checkpointing \    # 数据预处理选项,用于在训练前对图像进行中心裁剪
  --precision "16-mixed"    # 指定了训练时的精度设置,这里使用的是混合精度训练,其中某些操作使用16位浮点数来减少内存占用和加速计算
""".strip()

os.system(cmd)

5、加载微调好的模型

from diffsynth import ModelManager, SDXLImagePipeline
from peft import LoraConfig, inject_adapter_in_model
import torch


def load_lora(model, lora_rank, lora_alpha, lora_path):
    lora_config = LoraConfig(
        r=lora_rank,
        lora_alpha=lora_alpha,
        init_lora_weights="gaussian",
        target_modules=["to_q", "to_k", "to_v", "to_out"],
    )
    model = inject_adapter_in_model(lora_config, model)    # inject_adapter_in_model 函数将LoRA注入到模型中
    state_dict = torch.load(lora_path, map_location="cpu")    # 加载LoRA的权重到模型中,这里使用 torch.load 加载权重,并通过 map_location="cpu" 指定权重加载到CPU上
    model.load_state_dict(state_dict, strict=False)
    return model    # 返回修改后的模型


# Load models
# 加载预训练的模型组件
model_manager = ModelManager(torch_dtype=torch.float16, device="cuda",
                             file_path_list=[
                                 "models/kolors/Kolors/text_encoder",
                                 "models/kolors/Kolors/unet/diffusion_pytorch_model.safetensors",
                                 "models/kolors/Kolors/vae/diffusion_pytorch_model.safetensors"
                             ])
# 通过 SDXLImagePipeline.from_model_manager 方法,使用 ModelManager 实例来构建一个图像处理管道 pipe
pipe = SDXLImagePipeline.from_model_manager(model_manager)

# Load LoRA
pipe.unet = load_lora(
    pipe.unet,
    lora_rank=16, # This parameter should be consistent with that in your training script.
    lora_alpha=2.0, # lora_alpha can control the weight of LoRA.
    lora_path="models/lightning_logs/version_0/checkpoints/epoch=0-step=500.ckpt"
)

6、图片生成

torch.manual_seed(0)
image = pipe(
    prompt="二次元,一个紫色短发小女孩,在家中沙发上坐着,双手托着腮,很无聊,全身,粉色连衣裙",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("1.jpg")

参考文章:Datawhale (linklearner.com)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值