# Fine-Tuning and Guidance 在这一节中,我们将讲解基于现有模型实现模型改造的方法,主要实现方法有两种: * **微调(fine-tuning)**:通过在新的数据集上重新训练现有模型,来改变原有模型的生成类型 * **引导(guidance)**:通过在推理阶段对现有模型加入额外的控制信息,来引导原有模型某些特性的生成过程 ## 你将学到: 到本章结束时,你将学会: - 创建一个采样循环,并使用新调度器(scheduler)更快地完成采样 - 在新数据集上基于现有的扩散模型微调,这包括: - 使用梯度累加方法来应对训练硬件条件对 batch size 的限制 - 上传训练样本和日志(通过附带的脚本程序)至 [Weights and Biases](https://wandb.ai/site) 网站,以此来监控训练过程 - 保存最终结果管线(pipeline)并上传到 Hub - 通过引入损失函数来引导采样过程,以此对现有模型施加控制,这包括: - 通过一个简单的基于颜色的损失函数来探索不同的引导方法 - 使用 CLIP,用文本来引导生成过程 - 在 Gradio 和 🤗 Spaces 上分享你定制的采样循环方法 ❓如果你有任何问题,欢迎在 Hugging Face Discord 的 `#diffusion-models-class` 频道留言。如果你还没有 Discord 账号,可以点击这里注册:https://huggingface.co/join/discord ## 配置过程和需要引入的库 要将微调模型上传到 Hugging Face Hub 上,你需要登录 Hugging Face 账号,获取一个 **具有写入权限的访问令牌**。运行下列代码,你可以登陆账号并跳转到相关页面配置令牌。在模型训练过程中,如果你想使用训练脚本记录样本和日志,你还需要一个 Weights and Biases 账号,同样地,在需要登录账号时,也会有相关代码指引。 除此之外,你还需要安装一些依赖库并在程序中按需引入,以及指定计算设备,这样就配置完成了。代码如下: ```python !pip install -qq diffusers datasets accelerate wandb open-clip-torch ``` ```python # 登录 Hugging Face Hub,分享模型 # 请确保访问令牌具有写入权限 from huggingface_hub import notebook_login notebook_login() ``` Token is valid. Your token has been saved in your configured git credential helpers (store). Your token has been saved to /root/.huggingface/token Login successful ```python import numpy as np import torch import torch.nn.functional as F import torchvision from datasets import load_dataset from diffusers import DDIMScheduler, DDPMPipeline from matplotlib import pyplot as plt from PIL import Image from torchvision import transforms from tqdm.auto import tqdm ``` ```python device = ( "mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu" ) ``` ## 载入一个预训练过的管线 首先我们载入一个现有的管线,来看看它能为我们做些什么: ```python image_pipe = DDPMPipeline.from_pretrained("google/ddpm-celebahq-256") image_pipe.to(device); ``` Fetching 4 files: 0%| | 0/4 [00:00] ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_28_5.png) **考虑因素2:** 我们的损失值曲线简直像噪声一样混乱!这是因为每一次迭代我们都只用了四个训练图片,而且加到图片上的噪声还都是随机采样的,这对于训练过程不太友好。一种弥补措施是:使用非常小的学习率来限制权重每次更新的幅度。但还有一个更好的方法,既能得到与大 batch size 训练相当的收益,又不会让我们的内存爆掉。 可以点击查看 [gradient accumulation](https://kozodoi.me/python/deep%20learning/pytorch/tutorial/2021/02/19/gradient-accumulation.html#:~:text=Simply%20speaking%2C%20gradient%20accumulation%20means,might%20find%20this%20tutorial%20useful.) 的详细信息。如果我们先调用多次 `loss.backward()` 函数,再调用 `optimizer.step()` 和 `optimizer.zero_grad()`,PyTorch 就会把梯度累加(加和)起来,这样多个批次的数据计算的 loss 就会被高效地融合,这样只产出一个单独的(更好的)梯度估计用于参数更新。这样做会减少参数更新的总次数,就跟使用更大的 batch size 时的效果是一致的,这是一种时间换空间的思想。目前有很多深度学习框架都实现了梯度累加(比如 🤗 的 [Accelerate](https://huggingface.co/docs/accelerate/usage_guides/gradient_accumulation) 库就可以非常简便的调用)。不过在本书,我们会学习从零实现梯度累加,掌握了之后会对你以后训练模型但 GPU 内存受限时非常有帮助。如上述代码(在注释 `# 梯度累加` 之后)可见,其实也写不了几行代码。 ```python # 练习:试试你能不能在第一单元的训练循环中实现梯度累加。 # 思考应该怎么基于梯度累积的次数来调整学习率? # 思考为什么需要调整学习率? ``` **考虑因素3:** 即使这样,我们的训练过程还是太慢了。而且每遍历完一轮数据集才打印出一行更新信息,这样的反馈不足以让我们知道训练的怎么样了。我们还可以: * 训练过程中时不时地生成一些图像,来检查一下模型性能; * 训练过程中记录一些信息到日志里,如 loss 值、生成图片等,然后可以使用诸如 Weights and Biases 或 tensorboard 之类的工具来可视化监控。 我创建了一个可以快速上手的脚本程序([`finetune_model.py`](https://github.com/huggingface/diffusion-models-class/blob/main/unit2/finetune_model.py)),实现了在上述的训练代码中加入少量日志记录的功能。可以点击查看 [一次训练日志](https://wandb.ai/johnowhitaker/dm_finetune/runs/2upaa341): ```python %wandb johnowhitaker/dm_finetune/2upaa341 # 需要一个 W&B 账户,如果不需要登录可跳过此代码 ``` 随着训练过程的进展,观察生成的样本图片是如何一步步演变的也挺有意思。即使从损失值的变化看不出模型在进步,从图片上我们仍然能看到一个从原有图像分布(卧室数据集)到新的数据集(wikiart 数据集)逐渐演变的过程。在本章的最后还有一些被注释掉的用于微调的代码,可以使用该脚本程序替代上面的代码块。 ```python # 练习:试试你能不能修改第一单元的官方示例训练脚本程序 # 实现使用现有模型训练,而不是从头开始 # 对比一下上面链接指向的脚本程序,哪些额外功能是脚本程序里没有的? ``` 用微调的模型生成一些图片,可以看到这些脸部已经变得非常奇怪了! ```python # 生成图片并可视化: x = torch.randn(8, 3, 256, 256).to(device) # Batch of 8 for i, t in tqdm(enumerate(scheduler.timesteps)): model_input = scheduler.scale_model_input(x, t) with torch.no_grad(): noise_pred = image_pipe.unet(model_input, t)["sample"] x = scheduler.step(noise_pred, t, x).prev_sample grid = torchvision.utils.make_grid(x, nrow=4) plt.imshow(grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5); ``` 0it [00:00, ?it/s] ![png](01_finetuning_and_guidance_CN_files/01_finetuning_and_guidance_CN_36_1.png) **考虑因素4:** 微调的结果很可能是难以预知的。不过如果把训练时间设置的长一些,模型生成的蝴蝶图片会很完美。要是你对艺术风格很感兴趣,你会发现训练的中间过程模型生成的图片演变极其有趣!不妨试试观察一下短期和长期的训练过程,并调整学习率大小,看看这会怎样影响模型的最终输出。 ### 代码实战:用上面使用样例脚本程序在 WikiArt 数据集上去微调模型 如果你想训练一个和我在 WikiArt 数据集上训练的类似的模型,你可以去掉下列代码的注释符号并运行代码。不过由于这需要消耗不少的时间和 GPU 内存,我还是建议你学习完本章节内容后再尝试。 ```python ## 下载微调用的脚本: # !wget https://github.com/huggingface/diffusion-models-class/raw/main/unit2/finetune_model.py ``` ```python ## 运行脚本,在 Vintage Face 数据集上训练模型 ## (最好在终端里跑): # !python finetune_model.py --image_size 128 --batch_size 8 --num_epochs 16\ # --grad_accumulation_steps 2 --start_model "google/ddpm-celebahq-256"\ # --dataset_name "Norod78/Vintage-Faces-FFHQAligned" --wandb_project 'dm-finetune'\ # --log_samples_every 100 --save_model_every 1000 --model_save_name 'vintageface' ``` ### 保存和载入微调过的管线 现在我们已经微调好了扩散模型中 U-Net 的权重,接下来可以运行以下代码将它保存到本地文件夹中: ```python image_pipe.save_pretrained("my-finetuned-model") ``` 与第一单元类似,运行代码后会保存配置文件、模型、调度器。 ```python !ls {"my-finetuned-model"} ``` model_index.json scheduler unet 接下来你可以参照第一单元的 [Introduction to Diffusers](https://github.com/darcula1993/diffusion-models-class-CN/blob/main/unit1/01_introduction_to_diffusers_CN.ipynb) 部分,把模型上传到 Hub 上以备后续使用: ```python # @title: 将本地保存的管线上传至 Hub # 代码: 将本地保存的管线上传至 Hub from huggingface_hub import HfApi, ModelCard, create_repo, get_full_repo_name # 配置 Hub 仓库,上传文件 model_name = "ddpm-celebahq-finetuned-butterflies-2epochs" # @param 给传到 Hub 上的文件命名 local_folder_name = "my-finetuned-model" # @param 脚本程序生成的名字,你也可以通过 image_pipe.save_pretrained('save_name') 指定 description = "Describe your model here" # @param hub_model_id = get_full_repo_name(model_name) create_repo(hub_model_id) api = HfApi() api.upload_folder( folder_path=f"{local_folder_name}/scheduler", path_in_repo="", repo_id=hub_model_id ) api.upload_folder( folder_path=f"{local_folder_name}/unet", path_in_repo="", repo_id=hub_model_id ) api.upload_file( path_or_fileobj=f"{local_folder_name}/model_index.json", path_in_repo="model_index.json", repo_id=hub_model_id, ) # 添加一个模型名片 (可选,建议添加) content = f""" --- license: mit tags: - pytorch - diffusers - unconditional-image-generation - diffusion-models-class --- # Example Fine-Tuned Model for Unit 2 of the [Diffusion Models Class 🧨](https://github.com/huggingface/diffusion-models-class) {description} ## Usage ```python from diffusers import DDPMPipeline pipeline = DDPMPipeline.from_pretrained('{hub_model_id}') image = pipeline().images[0] image ``` """ card = ModelCard(content) card.push_to_hub(hub_model_id) ``` 'https://huggingface.co/lewtun/ddpm-celebahq-finetuned-butterflies-2epochs/blob/main/README.md' 至此,你已经完成了你的第一个微调扩散模型!祝贺! 接下里的部分,我将使用一个在 [LSUM bedrooms 数据集](https://huggingface.co/google/ddpm-bedroom-256) 上训练且在 WikiArt 数据集上微调了大约一轮的 [模型](https://huggingface.co/johnowhitaker/sd-class-wikiart-from-bedrooms)。你可以根据自己偏好来选择是否跳过这部分代码,使用上文中我们微调过的人脸或蝴蝶管线,或者直接从 Hub 上加载一个模型。 ```python # 加载预训练管线 pipeline_name = "johnowhitaker/sd-class-wikiart-from-bedrooms" image_pipe = DDPMPipeline.from_pretrained(pipeline_name).to(device) # 使用 DDIM 调度器,设置采样步长不小于 40,采样图片 scheduler = DDIMScheduler.from_pretrained(pipeline_name) scheduler.set_timesteps(num_inference_steps=40) # 随机初始化噪声 (每批次包含 8 张图片) x = torch.randn(8, 3, 256, 256).to(device) # 采样循环 for i, t in tqdm(enumerate(scheduler.timesteps)): model_input = scheduler.scale_model_input(x, t) with torch.no_grad(): noise_pred = image_pipe.unet(model_input, t)["sample"] x = scheduler.step(noise_pred, t, x).prev_sample # 可视化结果 grid = torchvision.utils.make_grid(x, nrow=4) plt.imshow(grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5); ``` Downloading: 0%| | 0.00/180 [00:00