Datawhale X 魔搭 第四期AI夏令营-AIGC方向task2笔记

1、使用通义辅助精度代码

打开魔搭Notebook,丝滑地启动实例:

把baseline整理成完整的代码块,并做必要的注释。

#第一步,安装Data-Juicer 和 DiffSynth-Studio
!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

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)
os.makedirs("./data/data-juicer/input", exist_ok=True)
with open("./data/data-juicer/input/metadata.jsonl", "w") as f:
    for data_id, data in enumerate(tqdm(ds)):
        image = data["image"].convert("RGB")
        image.save(f"/mnt/workspace/kolors/data/lora_dataset/train/{data_id}.jpg")
        metadata = {"text": "二次元", "image": [f"/mnt/workspace/kolors/data/lora_dataset/train/{data_id}.jpg"]}
        f.write(json.dumps(metadata))
        f.write("\n")

#第三步,数据处理,使用data-juicer处理数据
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)
        text = data["text"]
        texts.append(text)
        image = Image.open(data["image"][0])
        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

#查看训练脚本的输入参数
!python DiffSynth-Studio/examples/train/kolors/train_kolors_lora.py -h

#开始训练
#提示:
#1.在训练命令中填入  --modelscope_model_id xxxxx以及--modelscope_access_token xxxxx后,训练程序会在结束时自动上传模型到ModelScope
#2. 部分参数可根据实际需求调整,例如 lora_rank可以控制LoRA模型的参数量
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_alpha 4.0 \
  --dataset_path data/lora_dataset_processed \
  --output_path ./models \
  --max_epochs 1 \
  --center_crop \
  --use_gradient_checkpointing \
  --precision "16-mixed"
""".strip()

os.system(cmd)

#加载模型
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)
    state_dict = torch.load(lora_path, map_location="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"
                             ])
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"
)

#生成图像
torch.manual_seed(0)
image = pipe(
    prompt="二次元,一只空的塑料瓶被抛弃入大海中。",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("1-1.jpg")

torch.manual_seed(1)
image = pipe(
    prompt="二次元,一只空的塑料瓶随着海浪,漂到了沙滩上。",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("2.jpg")

torch.manual_seed(2)
image = pipe(
    prompt="二次元,一只空的塑料瓶在沙滩上,覆盖了薄薄的一层灰尘。",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度,色情擦边",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("3.jpg")

torch.manual_seed(5)
image = pipe(
    prompt="二次元,一个黑色短发的男孩穿着白色衬衫,在沙滩上捡起了一只空的塑料瓶。",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度,扭曲的手指,多余的手指",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("4.jpg")

torch.manual_seed(0)
image = pipe(
    prompt="二次元,一只空的塑料瓶和一堆塑料瓶放在一起。",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("5.jpg")

torch.manual_seed(1)
image = pipe(
    prompt="二次元,一个黑色短发的男孩穿着白色衬衫,在水池边清洗空的塑料瓶。",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("6.jpg")

torch.manual_seed(7)
image = pipe(
    prompt="二次元,一个黑色短发的男孩穿着白色衬衫,用剪刀和空塑料瓶做手工。",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("7.jpg")

torch.manual_seed(0)
image = pipe(
    prompt="二次元,一束鲜花插在一个塑料瓶瓶中,放在桌子上。",
    negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
    cfg_scale=4,
    num_inference_steps=50, height=1024, width=1024,
)
image.save("8.jpg")


#合成图像
import numpy as np
from PIL import Image


images = [np.array(Image.open(f"{i}.jpg")) for i in range(1, 9)]
image = np.concatenate([
    np.concatenate(images[0:2], axis=1),
    np.concatenate(images[2:4], axis=1),
    np.concatenate(images[4:6], axis=1),
    np.concatenate(images[6:8], axis=1),
], axis=0)
image = Image.fromarray(image).resize((1024, 2048))
image

打开通义千问,输入需要解读的代码。

获得解答

这段代码可以分为几个主要的部分来理解其工作流程:

1. 环境准备

这一部分主要是安装必要的Python包和依赖项。

这里安装了几个包,包括 simple-aesthetics-predictor, data-juicer, DiffSynth-Studio 等,同时还卸载了旧版本的 pytorch-lightning 并安装了一些其他的依赖包。

2. 数据集下载与预处理

这一部分主要负责下载数据集并进行预处理。

这里下载了一个名为 lowres_anime 的数据集,并从中提取图像,将其转换为RGB格式并保存到磁盘上,同时将每个图像的路径和相关的文本描述写入一个JSONL文件中。

3. 数据处理

接下来是对数据进行进一步的处理,比如过滤不符合要求的图像。

这部分首先定义了一个配置文件来指导 data-juicer 对数据集进行过滤和处理。之后通过 dj-process 命令来执行这些处理任务。处理完毕后,将处理过的图像和对应的文本描述保存到新的CSV文件中。

4. 模型训练

接下来是训练 LoRA 模型的部分。

这里使用了 DiffSynth-Studio 中的训练脚本来训练一个 LoRA 模型。该模型是在预训练模型的基础上进行微调,以适应特定的任务。

5. 模型加载与图像生成

这一部分负责加载训练好的模型,并使用它来生成图像。

这部分首先定义了一个函数 load_lora 用来加载训练好的 LoRA 模型,接着使用这个函数加载模型,并生成多张图像。

6. 图像合成

最后一步是将生成的多张图像合成一张大图。

这里将之前生成的8张图像按顺序拼接在一起形成一张较大的图像。

综上所述,这段代码实现了从数据集下载、预处理、处理、模型训练到图像生成和合成的完整工作流程。

2、文生图实践

拟定一个故事梗概,用通义创建提示词。

执行Task1的baseline,在代码中修改提示词。

查看生成的图片,如果不满意,可以微调,再生成,最终获得满意的图片后,合成大图。

结果展示:

1、一只空的塑料瓶子被抛弃在海里

2、空的塑料瓶子漂到了沙滩上

3、一个男孩看到了沙滩上的空的塑料瓶子

4、他伸出一只手把瓶子捡起来了

​​​​​​​

5、男孩拿着空塑料瓶,陷入了沉思

​​​​​​​

6、突然他似乎想到了什么,开始仔细清洗这个瓶子

7、男孩拿起画笔在塑料瓶上画画

8、塑料瓶变成了一个精美的工艺品

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值