AI大模型教程
一起来学习

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

一.认识ComfyUI

1.介绍

GUI 是 “Graphical User Interface”(图形用户界面)的缩写。简单来说,GUI 就电脑屏幕上的那种有图标、按钮和菜单的交互方式。而ComfyUI 是GUI的一种,是基于节点工作的用户界面,主要用于操作图像的生成技术,其中ComfyUI 的特别之处在于它采用了一种模块化的设计,把图像生成的过程分解成了许多小的步骤,每个步骤都是一个节点。通过连接这些节点形成一个工作流程,这样用户就可以根据需要定制自己的图像生成过程。

2.剖析

ComfyUI 的核心模块由模型加载器、提示词管理器、采样器、解码器组成,其中采样器是用于控制模型生成图像,调节生成速度和质量的平衡

具体图片生成流程如下:

同样,ComfyUI 也具有自己独特的优势,如模块化和灵活性:ComfyUI 提供了一个模块化的系统,用户可以通过拖放不同的模块来构建复杂的工作流程。这种灵活性允许用户根据自己的需求自由组合和调整模型、输入、输出、和其他处理步骤,使用户操作十分方便。

二.安装ComfyUI

1.下载脚本代码文件

利用如下代码下载安装ComfyUI的执行文件task1中微调完成Lora文件

git lfs install git clone https://www.modelscope.cn/datasets/maochase/kolors_test_comfyui.git mv kolors_test_comfyui/* ./ rm -rf kolors_test_comfyui/ mkdir -p /mnt/workspace/models/lightning_logs/version_0/checkpoints/ mv epoch=0-step=500.ckpt /mnt/workspace/models/lightning_logs/version_0/checkpoints/

2.运行程序等待结果

当执行到最后一个节点的内容输出了一个访问的链接的时候,复制链接到浏览器中访问

例如下图:

3.浅尝ComfyUI工作流

  1. 不带Lora的工作流样例

直接加载脚本,运行程序生图

  1. 带Lora的工作流样例

下载工作流脚本(带Lora训练),修改lora文件地址:/mnt/workspace/models/lightning_logs/version_0/checkpoints/epoch=0-step=500.ckpt

三.Lora微调

1.Lora简介

LoRA (Low-Rank Adaptation) 微调是一种用于在预训练模型上进行高效微调的技术。它可以通过高效且灵活的方式实现模型的个性化调整,使其能够适应特定的任务或领域,同时保持良好的泛化能力和较低的资源消耗。这对于推动大规模预训练模型的实际应用至关重要。

2.Lora微调原理

LoRA通过在预训练模型的关键层中添加低秩矩阵来实现。这些低秩矩阵通常被设计成具有较低维度的参数空间,这样它们就可以在不改变模型整体结构的情况下进行微调。

3.Lora详解(具体参数详情表)

参数名称

参数值

说明

pretrained_unet_path

models/kolors/Kolors/unet/diffusion_pytorch_model.safetensors

指定预训练UNet模型的路径

pretrained_text_encoder_path

models/kolors/Kolors/text_encoder

指定预训练文本编码器的路径

pretrained_fp16_vae_path

models/sdxl-vae-fp16-fix/diffusion_pytorch_model.safetensors

指定预训练VAE模型的路径

lora_rank

16

设置LoRA的秩(rank),影响模型的复杂度和性能

lora_alpha

4

设置LoRA的alpha值,控制微调的强度

dataset_path

data/lora_dataset_processed

指定用于训练的数据集路径

output_path

./models

指定训练完成后保存模型的路径

max_epochs

1

设置最大训练轮数为1

center_crop

启用中心裁剪,用于图像预处理

use_gradient_checkpointing

启用梯度检查点,节省显存

precision

“16-mixed”

设置训练时的精度为混合16位精度(half precision)

这里我将LoRA的秩(rank)从16改为32,更大程度的影响了模型的复杂度和性能

同时将max_epochs(最大训练轮数)改为2,使模型更加精确

四.准备数据集

1.明确需求

在准备和选择数据集时,我们需从以下三个角度考虑:

  • 关注应用场景:确定你的模型将被应用到什么样的场景中(例如,艺术风格转换、产品图像生成、医疗影像合成等)。

  • 关注数据类型:你需要什么样的图片?比如是真实世界的照片还是合成图像?是黑白的还是彩色的?是高分辨率还是低分辨率?

  • 关注数据量:考虑你的任务应该需要多少图片来支持训练和验证。

2.数据集来源整理

魔搭社区内开放了近3000个数据集,涉及文本、图像、音频、视频和多模态等多种场景,同时,左侧有标签栏帮助快速导览(如下图所示)

这里我选择了如下数据集:

最终训练出如下模型:

https://www.modelscope.cn/qwq123qwq123qwq/Loli-LoRA.git

文章来源于互联网:Datawhale X 魔搭 AI夏令营第四期 AIGC方向 Task03笔记

相关推荐: AI时代学术资料整理最佳实践:2025年如何高效管理书籍文献?

一、为什么需要专业的文献与书籍管理工具? 在当今信息爆炸的时代,研究人员、学者和学生面临着前所未有的信息管理挑战。传统的文献管理方法已无法满足现代学术工作的需求,专业管理工具应运而生以解决以下核心问题: 引用格式混乱:手动管理引用容易出错,导致学术论文格式不规…

赞(0)
未经允许不得转载:5bei.cn大模型教程网 » Datawhale X 魔搭 AI夏令营第四期 AIGC方向 Task03笔记

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

赛事任务:

1.参赛者需在可图Kolors 模型的基础上训练LoRA 模型,生成无限风格,如水墨画风格、水彩风格、赛博朋克风格、日漫风格……

2.基于LoRA模型生成 8 张图片组成连贯故事,故事内容可自定义

使用ComfyUI,其通过模块化的设计,把图像生成的过程分解成了许多小的步骤,每个步骤都是一个节点。这些节点可以连接起来形成一个工作流程,这样就可以根据需要定制自己的图像,流程可视化且操作方便。

核心模块由模型加载器、提示词管理器、采样器、解码器组成

选择模型,构造工作流调整参数后即可执行生成图像

import subprocess
import threading
import time
import socket
import urllib.request

def iframe_thread(port):
  while True:
      time.sleep(0.5)
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      result = sock.connect_ex(('127.0.0.1', port))
      if result == 0:
        break
      sock.close()
  print("nComfyUI finished loading, trying to launch cloudflared (if it gets stuck here cloudflared is having issues)n")

  p = subprocess.Popen(["cloudflared", "tunnel", "--url", "http://127.0.0.1:{}".format(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  for line in p.stderr:
    l = line.decode()
    if "trycloudflare.com " in l:
      print("This is the URL to access ComfyUI:", l[l.find("http"):], end='')
    #print(l, end='')


threading.Thread(target=iframe_thread, daemon=True, args=(8188,)).start()

不断地尝试连接本地服务器 (127.0.0.1) 上的指定端口(这里是8188),每次尝试之间会等待0.5秒。通过 socket.connect_ex() 方法,判断端口是否开放。如果端口开放(返回值为0),循环停止,继续执行后续代码。如果端口未开放,关闭套接字并继续循环。

通过 subprocess.Popen() 启动 cloudflared 隧道,连接到指定的本地端口,并重定向输出和错误流。读取隧道启动过程中的标准错误输出 stderr,如果在输出中找到包含 trycloudflare.com 的URL,就将该URL打印到控制台,用于访问 ComfyUI

import comfy.options
comfy.options.enable_args_parsing()

import os
import importlib.util
import folder_paths
import time
from comfy.cli_args import args


def execute_prestartup_script():
    def execute_script(script_path):
        module_name = os.path.splitext(script_path)[0]
        try:
            spec = importlib.util.spec_from_file_location(module_name, script_path)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            return True
        except Exception as e:
            print(f"Failed to execute startup-script: {script_path} / {e}")
        return False

    if args.disable_all_custom_nodes:
        return

    node_paths = folder_paths.get_folder_paths("custom_nodes")
    for custom_node_path in node_paths:
        possible_modules = os.listdir(custom_node_path)
        node_prestartup_times = []

        for possible_module in possible_modules:
            module_path = os.path.join(custom_node_path, possible_module)
            if os.path.isfile(module_path) or module_path.endswith(".disabled") or module_path == "__pycache__":
                continue

            script_path = os.path.join(module_path, "prestartup_script.py")
            if os.path.exists(script_path):
                time_before = time.perf_counter()
                success = execute_script(script_path)
                node_prestartup_times.append((time.perf_counter() - time_before, module_path, success))
    if len(node_prestartup_times) > 0:
        print("nPrestartup times for custom nodes:")
        for n in sorted(node_prestartup_times):
            if n[2]:
                import_message = ""
            else:
                import_message = " (PRESTARTUP FAILED)"
            print("{:6.1f} seconds{}:".format(n[0], import_message), n[1])
        print()

execute_prestartup_script()


# Main code
import asyncio
import itertools
import shutil
import threading
import gc

import logging

if os.name == "nt":
    logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())

if __name__ == "__main__":
    if args.cuda_device is not None:
        os.environ['CUDA_VISIBLE_DEVICES'] = str(args.cuda_device)
        logging.info("Set cuda device to: {}".format(args.cuda_device))

    if args.deterministic:
        if 'CUBLAS_WORKSPACE_CONFIG' not in os.environ:
            os.environ['CUBLAS_WORKSPACE_CONFIG'] = ":4096:8"

    import cuda_malloc

if args.windows_standalone_build:
    try:
        import fix_torch
    except:
        pass

import comfy.utils
import yaml

import execution
import server
from server import BinaryEventTypes
import nodes
import comfy.model_management

def cuda_malloc_warning():
    device = comfy.model_management.get_torch_device()
    device_name = comfy.model_management.get_torch_device_name(device)
    cuda_malloc_warning = False
    if "cudaMallocAsync" in device_name:
        for b in cuda_malloc.blacklist:
            if b in device_name:
                cuda_malloc_warning = True
        if cuda_malloc_warning:
            logging.warning("nWARNING: this card most likely does not support cuda-malloc, if you get "CUDA error" please run ComfyUI with: --disable-cuda-mallocn")

def prompt_worker(q, server):
    e = execution.PromptExecutor(server, lru_size=args.cache_lru)
    last_gc_collect = 0
    need_gc = False
    gc_collect_interval = 10.0

    while True:
        timeout = 1000.0
        if need_gc:
            timeout = max(gc_collect_interval - (current_time - last_gc_collect), 0.0)

        queue_item = q.get(timeout=timeout)
        if queue_item is not None:
            item, item_id = queue_item
            execution_start_time = time.perf_counter()
            prompt_id = item[1]
            server.last_prompt_id = prompt_id

            e.execute(item[2], prompt_id, item[3], item[4])
            need_gc = True
            q.task_done(item_id,
                        e.history_result,
                        status=execution.PromptQueue.ExecutionStatus(
                            status_str='success' if e.success else 'error',
                            completed=e.success,
                            messages=e.status_messages))
            if server.client_id is not None:
                server.send_sync("executing", { "node": None, "prompt_id": prompt_id }, server.client_id)

            current_time = time.perf_counter()
            execution_time = current_time - execution_start_time
            logging.info("Prompt executed in {:.2f} seconds".format(execution_time))

        flags = q.get_flags()
        free_memory = flags.get("free_memory", False)

        if flags.get("unload_models", free_memory):
            comfy.model_management.unload_all_models()
            need_gc = True
            last_gc_collect = 0

        if free_memory:
            e.reset()
            need_gc = True
            last_gc_collect = 0

        if need_gc:
            current_time = time.perf_counter()
            if (current_time - last_gc_collect) > gc_collect_interval:
                comfy.model_management.cleanup_models()
                gc.collect()
                comfy.model_management.soft_empty_cache()
                last_gc_collect = current_time
                need_gc = False

async def run(server, address='', port=8188, verbose=True, call_on_start=None):
    await asyncio.gather(server.start(address, port, verbose, call_on_start), server.publish_loop())


def hijack_progress(server):
    def hook(value, total, preview_image):
        comfy.model_management.throw_exception_if_processing_interrupted()
        progress = {"value": value, "max": total, "prompt_id": server.last_prompt_id, "node": server.last_node_id}

        server.send_sync("progress", progress, server.client_id)
        if preview_image is not None:
            server.send_sync(BinaryEventTypes.UNENCODED_PREVIEW_IMAGE, preview_image, server.client_id)
    comfy.utils.set_progress_bar_global_hook(hook)


def cleanup_temp():
    temp_dir = folder_paths.get_temp_directory()
    if os.path.exists(temp_dir):
        shutil.rmtree(temp_dir, ignore_errors=True)


def load_extra_path_config(yaml_path):
    with open(yaml_path, 'r') as stream:
        config = yaml.safe_load(stream)
    for c in config:
        conf = config[c]
        if conf is None:
            continue
        base_path = None
        if "base_path" in conf:
            base_path = conf.pop("base_path")
        for x in conf:
            for y in conf[x].split("n"):
                if len(y) == 0:
                    continue
                full_path = y
                if base_path is not None:
                    full_path = os.path.join(base_path, full_path)
                logging.info("Adding extra search path {} {}".format(x, full_path))
                folder_paths.add_model_folder_path(x, full_path)


if __name__ == "__main__":
    if args.temp_directory:
        temp_dir = os.path.join(os.path.abspath(args.temp_directory), "temp")
        logging.info(f"Setting temp directory to: {temp_dir}")
        folder_paths.set_temp_directory(temp_dir)
    cleanup_temp()

    if args.windows_standalone_build:
        try:
            import new_updater
            new_updater.update_windows_updater()
        except:
            pass

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    server = server.PromptServer(loop)
    q = execution.PromptQueue(server)

    extra_model_paths_config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "extra_model_paths.yaml")
    if os.path.isfile(extra_model_paths_config_path):
        load_extra_path_config(extra_model_paths_config_path)

    if args.extra_model_paths_config:
        for config_path in itertools.chain(*args.extra_model_paths_config):
            load_extra_path_config(config_path)

    nodes.init_extra_nodes(init_custom_nodes=not args.disable_all_custom_nodes)

    cuda_malloc_warning()

    server.add_routes()
    hijack_progress(server)

    threading.Thread(target=prompt_worker, daemon=True, args=(q, server,)).start()

    if args.output_directory:
        output_dir = os.path.abspath(args.output_directory)
        logging.info(f"Setting output directory to: {output_dir}")
        folder_paths.set_output_directory(output_dir)

    #These are the default folders that checkpoints, clip and vae models will be saved to when using CheckpointSave, etc.. nodes
    folder_paths.add_model_folder_path("checkpoints", os.path.join(folder_paths.get_output_directory(), "checkpoints"))
    folder_paths.add_model_folder_path("clip", os.path.join(folder_paths.get_output_directory(), "clip"))
    folder_paths.add_model_folder_path("vae", os.path.join(folder_paths.get_output_directory(), "vae"))

    if args.input_directory:
        input_dir = os.path.abspath(args.input_directory)
        logging.info(f"Setting input directory to: {input_dir}")
        folder_paths.set_input_directory(input_dir)

    if args.quick_test_for_ci:
        exit(0)

    call_on_start = None
    if args.auto_launch:
        def startup_server(scheme, address, port):
            import webbrowser
            if os.name == 'nt' and address == '0.0.0.0':
                address = '127.0.0.1'
            webbrowser.open(f"{scheme}://{address}:{port}")
        call_on_start = startup_server

    try:
        loop.run_until_complete(server.setup())
        loop.run_until_complete(run(server, address=args.listen, port=args.port, verbose=not args.dont_print_server, call_on_start=call_on_start))
    except KeyboardInterrupt:
        logging.info("nStopped server")

    cleanup_temp()

启动和管理ComfyUI服务器。它通过多线程、异步编程和动态模块加载的方式,实现了对任务的高效调度和资源管理(如 CUDA 设备和内存的优化使用)。同时,还支持加载自定义节点和扩展配置,是一个高度可配置和扩展的系统。 

 主要工作流程为:

1.初始化临时目录

2.独立构建更新检查

3. 实例化服务器对象 server.PromptServer,并为其传入事件循环。实例化任务队列 execution.PromptQueue,用于管理和调度任务。

4. 加载模型路径配置

5. 初始化自定义节点

6. CUDA 内存分配检查和报警

7. 添加服务器路由和进度钩子,设置全局进度条钩子 hijack_progress,以便在任务执行时能够实时更新进度信息给客户端。。并启动任务执行线程,这使得任务处理与主事件循环并行进行。

8. 自动启动服务器(在服务器启动后自动在浏览器中打开服务器地址)再启动事件循环并运行服务器,使用 asyncio 的事件循环 loop 运行服务器,监听指定地址和端口,处理客户端请求。

LoRA(Low-Rank Adaptation)是一种用于神经网络模型参数高效调优的方法,特别适用于在预训练模型(如大型语言模型、视觉模型等)上进行微调的场景。它的核心思想是通过低秩矩阵分解来减少参数更新的复杂性,从而降低计算成本和内存需求。

LoRA 原理

LoRA 的基本思想是将神经网络中的部分权重矩阵进行低秩分解,将原始的权重矩阵W 表示为两个低秩矩阵 A和B 的乘积: W′=W+ΔW=W+A×B其中:

  • W是预训练模型的权重矩阵,保持不变。
  • ΔW是通过 A×B计算得到的低秩近似更新矩阵。
  • AAA 和 BBB 是低秩矩阵,通常 A的维度是 (d,r)而 BBB 的维度是(r,k),其中 r是秩远小于d 和 k的值。

通过这种方式,LoRA 只需更新低秩矩阵 A和 B,而不需要更新完整的权重矩阵W,这显著减少了需要调优的参数量。

LoRA 的优势

  1. 参数效率高:LoRA 通过低秩分解大大减少了需要更新的参数数量,降低了计算和存储成本。

  2. 快速微调:由于参数量大幅减少,模型微调速度更快,适合资源受限的场景。

  3. 适应性强:LoRA 能够在不同任务中有效地微调预训练模型,而不需要重新训练整个模型。

  4. 节省内存:LoRA 只需存储低秩矩阵 A和 B的权重,相比于更新整个权重矩阵所需的内存开销更低。

  5. 可扩展性:LoRA 可以在各种预训练模型上应用,包括语言模型、视觉模型等。

文章来源于互联网:Datawhale X 魔搭 AI夏令营第四期 AIGC方向 task03笔记

相关推荐: Stable Diffusion ControlNet教程 :IP-Adapter 图片风格迁移

注:AI工具SD整合包、各种模型插件、提示词、AI人工智能学习资料都已经打包好放在网盘中了,有需要的小伙伴文末扫码自行获取。 前段时间腾讯发布的ControlNet新模型叫“IP-Adapter”,它的作用就是把上传的图像转化为图像提示词,简单的来说就是跟Mi…

赞(0)
未经允许不得转载:5bei.cn大模型教程网 » Datawhale X 魔搭 AI夏令营第四期 AIGC方向 task03笔记

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

第一次任务比较简单,只需要配置好环境,简单运行一次

项目背景

赛题任务

可图Kolors-LoRA风格故事挑战赛

1.参赛者需在可图Kolors 模型的基础上训练LoRA 模型,生成无限风格,如水墨画风格、水彩风格、赛博朋克风格、日漫风格……

2.基于LoRA模型生成 8 张图片组成连贯故事,故事内容可自定义;基于8图故事,评估LoRA风格的美感度及连贯性 样例:偶像少女养成日记

文生图基础知识

文生图主要以SD系列基础模型为主,以及在其基础上微调的lora模型和人物基础模型等。

提示词

提示词prompt很重要,一般写法:主体描述,细节描述,修饰词,艺术风格,艺术家

Lora

LoRA模型,全称Low-Rank Adaptation of Large Language Models,是一种用于微调大型语言模型的低秩适应技术。它最初应用于NLP领域,特别是用于微调GPT-3等模型。LoRA通过仅训练低秩矩阵,然后将这些参数注入到原始模型中,从而实现对模型的微调。这种方法不仅减少了计算需求,而且使得训练资源比直接训练原始模型要小得多,因此非常适合在资源有限的环境中使用。

Stable Diffusion(SD)模型的应用中,LoRA被用作一种插件,允许用户在不修改SD模型的情况下,利用少量数据训练出具有特定画风、IP或人物特征的模型。这种技术在社区使用和个人开发者中非常受欢迎。例如,可以通过LoRA模型改变SD模型的生成风格,或者为SD模型添加新的人物/IP。

ComfyUI

ComfyUI 是一个工作流工具,主要用于简化和优化 AI 模型的配置和训练过程。通过直观的界面和集成的功能,用户可以轻松地进行模型微调、数据预处理、图像生成等任务,从而提高工作效率和生成效果。

参考图控制

ControlNet是一种用于精确控制图像生成过程的技术组件。它是一个附加到预训练的扩散模型(如Stable Diffusion模型)上的可训练神经网络模块。扩散模型通常用于从随机噪声逐渐生成图像的过程,而ControlNet的作用在于引入额外的控制信号,使得用户能够更具体地指导图像生成的各个方面(如姿势关键点、分割图、深度图、颜色等)。

Task01实践过程

搭建环境

开通阿里云PAI-DSW试用

链接:阿里云免费试用 – 阿里云

按照以下步骤开通3个月试用PAI-DSW

在魔搭社区进行授权

链接:https://www.modelscope.cn/my/mynotebook/authorization

进入链接中的页面一步步进行授权即可,授权后方便在魔搭社区进行后续实践

报名赛事

赛事链接:https://tianchi.aliyun.com/competition/entrance/532254

可以选择报名比赛

创建实例

在魔搭社区创建PAI实例

如果前面成功进行魔搭社区授权,可以在魔搭社区上进行操作,否则需要在阿里云平台上操作

这里在魔搭社区上完成的以下操作

运行baseline

下载baseline文件

打开实例中的Jupyter Lab,在终端运行git指令下载baseline文件

git lfs install
git clone https://www.modelscope.cn/datasets/maochase/kolors.git

打开baseline文件,安装环境,重启

调整prompt,设置想要的图片风格

因为这里只是简单的初步测试,所以仅对第一张图片的prompt进行了调整

 依次顺序运行剩余的代码块,点击代码框左上角执行按钮,最终获得图片,过程较长,耐心等待

结果上传

通过终端移动并保存结果文件,在魔搭社区创建并发布自己的简单模型

#移动结果文件终端指令
mkdir /mnt/workspace/kolors/output & cd 
cp /mnt/workspace/kolors/models/lightning_logs/version_0/checkpoints/epoch=0-step=500.ckpt /mnt/workspace/kolors/output/
cp /mnt/workspace/kolors/1.jpg /mnt/workspace/kolors/output/

文件保存本地

上传模型链接:魔搭社区

模型成功发布

关闭PAI实例

运行完成后,切记回到魔搭,关闭实例,否则试用额度不知不觉就消耗殆尽了

个人感悟

本次Task01初步体验了一下AIGC的运行,但对于各个代码块功能尚不了解,对于其后的原理和相关知识也不是很了解,还需要进一步去学习和实践

文章来源于互联网:Datawhale X 魔搭 AI夏令营第四期 AIGC方向 Task01笔记

相关推荐: Stable Diffusion【真人模型】:人像光影摄影极限写实真实感大模型

大家好,我是极客菌 今天和大家分享一个基于SD1.5的真人大模型:人像光影摄影极限写实真实感大模型。 该模型具有以下特点: 真实肤感(在面部肌理和皮肤肌理上均有加强学习,拒绝ai出图假的问题) 永不脱妆(在不写正面妆容关键词的情况下,永远自带妆容) 摄影光感(…

赞(0)
未经允许不得转载:5bei.cn大模型教程网 » Datawhale X 魔搭 AI夏令营第四期 AIGC方向 Task01笔记
分享到: 更多 (0)

AI大模型,我们的未来

小欢软考联系我们