跟DataWhale的步骤跑通baseline
环境安装
!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_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
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_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="一只可爱的小象穿着探险帽,身穿狩猎装,站在沙漠地面上,鼻子高举,风格为Pixar animation。",
negative_prompt="丑陋、变形、嘈杂、模糊、低对比度",
cfg_scale=4,
num_inference_steps=50, height=1024, width=1024,
)
image.save("1.jpg")
感想:粗浅的感受到了提示词的使用,和体验了生成图片的过程,作为一个大一的学生感觉很新奇。
总结
## 跟DataWhale的步骤跑通baseline总结### 环境安装
本文详细介绍了通过pip命令安装多个依赖库的步骤,包括`simple-aesthetics-predictor`、`data-juicer`(以可编辑模式安装)、`pytorch-lightning`的卸载及重新安装`peft`、`lightning`、`pandas`、`torchvision`,以及以可编辑模式安装`DiffSynth-Studio`,以确保项目所需的所有环境和库都被正确设置。
### 下载数据集
通过`modelscope`的`MsDataset`工具,下载了`AI-ModelScope/lowres_anime`数据集,并将数据集的图片保存至本地指定路径。同时,为每张图片生成了包含文本描述和图像路径的metadata信息,并保存为JSON Lines格式的文件。
### 数据集处理
利用`data-juicer`进行数据预处理,设置了一系列图像过滤规则,如图像尺寸和纵横比等,以筛选高质量图像。处理后的数据被保存至指定路径,并生成了包含文件名和文本描述的CSV文件,便于后续模型训练过程的使用。
### LoRA微调
首先,通过DiffSynth的`download_models`函数下载训练所需的预训练模型。随后,通过编写并执行训练命令,对LoRA进行了微调训练,调整了LoRA权重以学习从给定文本到目标图像风格的映射。
### 加载微调好的模型
通过`ModelManager`和`SDXLImagePipeline`加载了预训练模型和微调好的LoRA权重,并将这些组件整合到一个图像处理pipeline中。这一步使得我们能够加载并利用微调后的模型进行图像生成。
### 图片生成
最后,通过修改input prompt和其他设置(如cfg_scale、num_inference_steps、图像尺寸等),利用加载好的模型生成了自定义图片,展示了模型根据文本描述生成高质量图像的能力。
### 感想
作为大一学生,通过这一系列步骤的体验,深刻感受到了AI生成图像的魅力和可能性,尤其是通过调整提示词和模型参数来控制生成图像的过程,既感新奇又具挑战性。这也意味着,在AI驱动的创意内容生成领域,有着广阔的探索空间和无限可能。