+
+
+
+现在我们有了自己的数据集,让我们定义一个辅助函数来可视化查看一些图像:
+
+
+```python
+from PIL import Image
+
+def image_grid(imgs, rows, cols):
+ assert len(imgs) == rows * cols
+ w, h = imgs[0].size
+ grid = Image.new("RGB", size=(cols * w, rows * h))
+ grid_w, grid_h = grid.size
+ for i, img in enumerate(imgs):
+ grid.paste(img, box=(i % cols * w, i // cols * h))
+ return grid
+
+num_samples = 4
+image_grid(dataset["image"][:num_samples], rows=1, cols=num_samples)
+```
+
+这些图像如果看起来不错,您可以继续下一步 —— 创建 PyTorch 数据集以使用 DreamBooth 进行训练。
+
+### 创建训练数据集
+
+要为我们的图像创建训练集,需要一些组件:
+
+* **实例提示** : 用于在训练开始时预热模型。大多数情况下,使用一张「标识符 + 类别名词」的照片效果已足够好,例如为我们可爱的柯基图片写上提示: "一张柯柯基狗的照片"。
+ * **注意:** 建议您选择一个独特的/虚构词来描述您的主体,如 `柯柯基`。以此确保模型词汇表中的常用词不会被覆盖。
+* **分词器** : 用于将实例提示转换为输入 ID,并且可以将其提供给 Stable Diffusion 的文本编码器。
+* 一组 **图像变换** : 尤其是将图像缩放至通用形状,以及将像素值归一化至通用均值和标准分布。
+
+根据以上描述,让我们从定义实例提示开始:
+
+
+```python
+name_of_your_concept = "dashdash" # 根据您的主体修改,我这里把 dash 称之为 dashdash
+type_of_thing = "toy" # 根据您的主体修改
+instance_prompt = f"a photo of {name_of_your_concept} {type_of_thing}"
+print(f"Instance prompt: {instance_prompt}")
+```
+
+ Instance prompt: a photo of dashdash toy
+
+
+接下来,我们需要创建一个 PyTorch `Dataset` 类, 并实现 `__len__` 和 `__getitem__` 方法:
+
+
+```python
+from torch.utils.data import Dataset
+from torchvision import transforms
+
+
+class DreamBoothDataset(Dataset):
+ def __init__(self, dataset, instance_prompt, tokenizer, size=512):
+ self.dataset = dataset
+ self.instance_prompt = instance_prompt
+ self.tokenizer = tokenizer
+ self.size = size
+ self.transforms = transforms.Compose(
+ [
+ transforms.Resize(size),
+ transforms.CenterCrop(size),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5], [0.5]),
+ ]
+ )
+
+ def __len__(self):
+ return len(self.dataset)
+
+ def __getitem__(self, index):
+ example = {}
+ image = self.dataset[index]["image"]
+ example["instance_images"] = self.transforms(image)
+ example["instance_prompt_ids"] = self.tokenizer(
+ self.instance_prompt,
+ padding="do_not_pad",
+ truncation=True,
+ max_length=self.tokenizer.model_max_length,
+ ).input_ids
+ return example
+```
+
+很好,现在让我们加载与原始 Stable Diffusion 模型的文本编码器关联的 CLIP 分词器,然后检查上一步是否生效,然后创建训练数据集:
+
+
+```python
+from transformers import CLIPTokenizer
+
+# 用来微调的 Stable Diffusion 检查点
+model_id = MODEL_SD_PATH
+tokenizer = CLIPTokenizer.from_pretrained(
+ model_id,
+ subfolder="tokenizer",
+)
+
+train_dataset = DreamBoothDataset(dataset, instance_prompt, tokenizer)
+train_dataset[0]
+```
+
+
+
+
+ {'instance_images': tensor([[[ 0.6941, 0.6941, 0.6941, ..., 0.3647, 0.3647, 0.3647],
+ [ 0.6941, 0.7020, 0.6941, ..., 0.3647, 0.3647, 0.3647],
+ [ 0.6863, 0.6863, 0.6863, ..., 0.3647, 0.3647, 0.3569],
+ ...,
+ [ 0.5216, 0.5294, 0.5216, ..., 0.5529, 0.5451, 0.5451],
+ [ 0.5216, 0.5216, 0.5294, ..., 0.5529, 0.5451, 0.5529],
+ [ 0.5216, 0.5373, 0.5373, ..., 0.5451, 0.5529, 0.5608]],
+
+ [[ 0.5529, 0.5529, 0.5529, ..., -0.0275, -0.0275, -0.0275],
+ [ 0.5529, 0.5608, 0.5529, ..., -0.0275, -0.0275, -0.0275],
+ [ 0.5451, 0.5451, 0.5451, ..., -0.0275, -0.0275, -0.0353],
+ ...,
+ [ 0.5216, 0.5294, 0.5216, ..., 0.5608, 0.5529, 0.5529],
+ [ 0.5216, 0.5216, 0.5294, ..., 0.5608, 0.5529, 0.5608],
+ [ 0.5216, 0.5373, 0.5373, ..., 0.5529, 0.5608, 0.5686]],
+
+ [[ 0.6784, 0.6784, 0.6784, ..., -0.6000, -0.6000, -0.6000],
+ [ 0.6784, 0.6863, 0.6784, ..., -0.5922, -0.5922, -0.5922],
+ [ 0.6706, 0.6706, 0.6706, ..., -0.5843, -0.5843, -0.5922],
+ ...,
+ [ 0.5843, 0.5922, 0.5843, ..., 0.5765, 0.5686, 0.5686],
+ [ 0.5843, 0.5843, 0.5922, ..., 0.5765, 0.5686, 0.5765],
+ [ 0.5843, 0.6000, 0.6000, ..., 0.5686, 0.5765, 0.5843]]]),
+ 'instance_prompt_ids': [49406, 320, 1125, 539, 13858, 10206, 5988, 49407]}
+
+
+
+## 第 4 步:定义数据整理器
+
+现在我们有了一个训练数据集,接下来我们需要定义一个数据整理器。数据整理器是一个函数,它实现的功能是:收集一个批次数据中的元素、应用一些逻辑来构成单个张量、提供给模型训练等。如果您想了解更多信息,可以观看 [Hugging Face 的视频课程](hf.co/course)。
+
+对于 DreamBooth,我们定义的数据整理器需要为模型提供两个部分:分词器的输入 ID、图像的像素值堆叠张量。具体函数代码如下所示:
+
+
+```python
+import torch
+
+def collate_fn(examples):
+ input_ids = [example["instance_prompt_ids"] for example in examples]
+ pixel_values = [example["instance_images"] for example in examples]
+ pixel_values = torch.stack(pixel_values)
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
+
+ input_ids = tokenizer.pad(
+ {"input_ids": input_ids}, padding=True, return_tensors="pt"
+ ).input_ids
+
+ batch = {
+ "input_ids": input_ids,
+ "pixel_values": pixel_values,
+ }
+ return batch
+```
+
+## 第 5 步:加载 Stable Diffusion 管道组件
+
+到此我们已经准备好训练所需的大部分组件了!如 Stable Diffusion 第 3 单元 Notebook 中所示,一个管道包含多个模型:
+
+* 文本编码器: 用于将文本提示转换为嵌入矩阵。这里我们使用 CLIP,因为它是用于训练 Stable Diffusion v1-4 的编码器
+* VAE (变分自动编码器, variational autoencoder): 用于将图像转换为压缩表征(隐式表征),并在推理时解压缩
+* UNet: 用于在隐式 VAE 中去噪
+
+我们可以使用 🤗 Diffusers 和 🤗 Transformers 库加载上述所有组件,如下代码所示:
+
+
+
+```python
+from diffusers import AutoencoderKL, UNet2DConditionModel
+from transformers import CLIPFeatureExtractor, CLIPTextModel
+
+text_encoder = CLIPTextModel.from_pretrained(model_id, subfolder="text_encoder")
+vae = AutoencoderKL.from_pretrained(model_id, subfolder="vae")
+unet = UNet2DConditionModel.from_pretrained(model_id, subfolder="unet")
+feature_extractor = CLIPFeatureExtractor.from_pretrained(MODEL_CLIP_VIT_PATH)
+```
+
+## 第 6 步:微调模型
+
+有趣的一步来了!使用 DreamBooth 训练自己的模型!如 [Hugging Face 的博客文章](https://huggingface.co/blog/dreambooth) 所描述的那样,需要手动调整的最重要的超参数是学习率和训练次数。
+
+通常,较低的学习率和较长的训练次数可以获得更好的结果。下面设置的初始值是一个不错的训练起点,但您可能仍然需要根据您的数据集调整它们:
+
+
+```python
+learning_rate = 2e-06
+max_train_steps = 400
+```
+
+接下来,将训练需要的其他超参数包装在 `Namespace` 对象中,来使配置和训练更简单:
+
+
+```python
+from argparse import Namespace
+
+OUTPUT_DIR = "/home/mw/work/my-dreambooth"
+args = Namespace(
+ pretrained_model_name_or_path=model_id,
+ resolution=512, # Reduce this if you want to save some memory
+ train_dataset=train_dataset,
+ instance_prompt=instance_prompt,
+ learning_rate=learning_rate,
+ max_train_steps=max_train_steps,
+ train_batch_size=1,
+ gradient_accumulation_steps=1, # Increase this if you want to lower memory usage
+ max_grad_norm=1.0,
+ gradient_checkpointing=True, # set this to True to lower the memory usage.
+ use_8bit_adam=True, # use 8bit optimizer from bitsandbytes
+ seed=3434554,
+ sample_batch_size=2,
+ output_dir=OUTPUT_DIR, # where to save the pipeline
+)
+```
+
+最后要定义一个 `training_function()` 函数,它包装了一些训练逻辑,并且可以传递给 🤗 Accelerate 库来处理 1 个或多个 GPU 上的训练。如果这是您第一次使用 🤗 Accelerate,请观看我们官方的 Bilibili 频道视频以快速了解它的功能:[Supercharge your PyTorch training loop with Accelerate](https://www.bilibili.com/video/BV1gD4y157ee/) (带中英文字幕)。
+
+
+当我们从头开始训练自己的扩散模型时,这些细节与我们在第 1 和第 2 单元中看到的类似:
+
+
+```python
+import math
+
+import torch.nn.functional as F
+from accelerate import Accelerator
+from accelerate.utils import set_seed
+from diffusers import DDPMScheduler, PNDMScheduler, StableDiffusionPipeline
+from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
+from torch.utils.data import DataLoader
+from tqdm.auto import tqdm
+
+
+def training_function(text_encoder, vae, unet):
+
+ accelerator = Accelerator(
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
+ )
+
+ set_seed(args.seed)
+
+ if args.gradient_checkpointing:
+ unet.enable_gradient_checkpointing()
+
+ # 使用 8 位 Adam 优化器以降低内存占用,或者在 16GB GPU 微调模型
+ if args.use_8bit_adam:
+ import bitsandbytes as bnb
+ optimizer_class = bnb.optim.AdamW8bit
+ else:
+ optimizer_class = torch.optim.AdamW
+
+ optimizer = optimizer_class(
+ unet.parameters(), # 仅优化 UNet
+ lr=args.learning_rate,
+ )
+
+ noise_scheduler = DDPMScheduler(
+ beta_start=0.00085,
+ beta_end=0.012,
+ beta_schedule="scaled_linear",
+ num_train_timesteps=1000,
+ )
+
+ train_dataloader = DataLoader(
+ args.train_dataset,
+ batch_size=args.train_batch_size,
+ shuffle=True,
+ collate_fn=collate_fn,
+ )
+
+ unet, optimizer, train_dataloader = accelerator.prepare(
+ unet, optimizer, train_dataloader
+ )
+
+ # 将 text_encode 和 VAE 转移到 gpu
+ text_encoder.to(accelerator.device)
+ vae.to(accelerator.device)
+
+ # 我们需要重新计算我们的总训练次数,因为数据加载器的大小可能发生改变。
+ num_update_steps_per_epoch = math.ceil(
+ len(train_dataloader) / args.gradient_accumulation_steps
+ )
+ num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
+
+ # 训练!
+ total_batch_size = (
+ args.train_batch_size
+ * accelerator.num_processes
+ * args.gradient_accumulation_steps
+ )
+ # 每台机器仅显示一次进度条
+ progress_bar = tqdm(
+ range(args.max_train_steps), disable=not accelerator.is_local_main_process
+ )
+ progress_bar.set_description("Steps")
+ global_step = 0
+
+ for epoch in range(num_train_epochs):
+ unet.train()
+ for step, batch in enumerate(train_dataloader):
+ with accelerator.accumulate(unet):
+ # 转换图像至隐式空间
+ with torch.no_grad():
+ latents = vae.encode(batch["pixel_values"]).latent_dist.sample()
+ latents = latents * 0.18215
+
+ # 采样要添加到隐式空间的噪声样本
+ noise = torch.randn(latents.shape).to(latents.device)
+ bsz = latents.shape[0]
+ # 为每张图像采样随机时间步
+ timesteps = torch.randint(
+ 0,
+ noise_scheduler.config.num_train_timesteps,
+ (bsz,),
+ device=latents.device,
+ ).long()
+
+ # 根据每个时间步的噪声幅度,将噪声添加到隐式空间
+ # (即前向扩散过程)
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
+
+ # 获取用于条件调节的文本嵌入
+ with torch.no_grad():
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0]
+
+ # 预测噪声残差
+ noise_pred = unet(
+ noisy_latents, timesteps, encoder_hidden_states
+ ).sample
+ loss = (
+ F.mse_loss(noise_pred, noise, reduction="none")
+ .mean([1, 2, 3])
+ .mean()
+ )
+
+ accelerator.backward(loss)
+ if accelerator.sync_gradients:
+ accelerator.clip_grad_norm_(unet.parameters(), args.max_grad_norm)
+ optimizer.step()
+ optimizer.zero_grad()
+
+ # 检查加速器是否在幕后执行了优化
+ if accelerator.sync_gradients:
+ progress_bar.update(1)
+ global_step += 1
+
+ logs = {"loss": loss.detach().item()}
+ progress_bar.set_postfix(**logs)
+
+ if global_step >= args.max_train_steps:
+ break
+
+ accelerator.wait_for_everyone()
+
+ # 使用经训练的模块,创建管道并保存。
+ if accelerator.is_main_process:
+ print(f"Loading pipeline and saving to {args.output_dir}...")
+ scheduler = PNDMScheduler(
+ beta_start=0.00085,
+ beta_end=0.012,
+ beta_schedule="scaled_linear",
+ skip_prk_steps=True,
+ steps_offset=1,
+ )
+ pipeline = StableDiffusionPipeline(
+ text_encoder=text_encoder,
+ vae=vae,
+ unet=accelerator.unwrap_model(unet),
+ tokenizer=tokenizer,
+ scheduler=scheduler,
+ safety_checker=StableDiffusionSafetyChecker.from_pretrained(
+ MODEL_SD_SAFETY_PATH
+ ),
+ feature_extractor=feature_extractor,
+ )
+ pipeline.save_pretrained(args.output_dir)
+```
+
+现在我们已经定义了训练所需的所有函数,开始训练吧!根据您的数据集的大小和 GPU 的类型,可能需要 5 分钟到 1 小时不等的时间才能运行:
+
+
+```python
+from accelerate import notebook_launcher
+
+num_of_gpus = 1 # 以及您拥有的 GPU 数量修改此项
+notebook_launcher(
+ training_function, args=(text_encoder, vae, unet), num_processes=num_of_gpus
+)
+```
+
+ Launching training on one GPU.
+
+ ===================================BUG REPORT===================================
+ Welcome to bitsandbytes. For bug reports, please submit your error trace to: https://github.com/TimDettmers/bitsandbytes/issues
+ For effortless bug reporting copy-paste your error into this form: https://docs.google.com/forms/d/e/1FAIpQLScPB8emS3Thkp66nvqwmjTEgxp8Y9ufuWTzFyr9kJ5AoI47dQ/viewform?usp=sf_link
+ ================================================================================
+ CUDA_SETUP: WARNING! libcudart.so not found in any environmental path. Searching /usr/local/cuda/lib64...
+ CUDA SETUP: CUDA runtime path found: /usr/local/cuda/lib64/libcudart.so
+ CUDA SETUP: Highest compute capability among GPUs detected: 7.5
+ CUDA SETUP: Detected CUDA version 116
+ CUDA SETUP: Loading binary /opt/conda/lib/python3.9/site-packages/bitsandbytes/libbitsandbytes_cuda116.so...
+
+
+ /opt/conda/lib/python3.9/site-packages/bitsandbytes/cuda_setup/main.py:134: UserWarning: WARNING: The following directories listed in your path were found to be non-existent: {PosixPath('/usr/local/nvidia/lib'), PosixPath('/usr/local/nvidia/lib64')}
+ warn(msg)
+ /opt/conda/lib/python3.9/site-packages/bitsandbytes/cuda_setup/main.py:134: UserWarning: /usr/local/nvidia/lib:/usr/local/nvidia/lib64 did not contain libcudart.so as expected! Searching further paths...
+ warn(msg)
+ /opt/conda/lib/python3.9/site-packages/bitsandbytes/cuda_setup/main.py:134: UserWarning: WARNING: The following directories listed in your path were found to be non-existent: {PosixPath('//172.16.252.1'), PosixPath('tcp'), PosixPath('443')}
+ warn(msg)
+ /opt/conda/lib/python3.9/site-packages/bitsandbytes/cuda_setup/main.py:134: UserWarning: WARNING: The following directories listed in your path were found to be non-existent: {PosixPath('//matplotlib_inline.backend_inline'), PosixPath('module')}
+ warn(msg)
+
+
+
+ 0%| | 0/400 [00:00, ?it/s]
+
+
+如果您在单个 GPU 上运行,您可以将下面的代码复制到一个新的单元格并运行来为下一部分释放一些内存。对于多 GPU 机器,🤗 Accelerate 不允许 _任何_ 单元格直接使用 torch.cuda 访问 GPU,因此我们不建议在这些情况下使用此技巧:
+
+```python
+with torch.no_grad():
+ torch.cuda.empty_cache()
+```
+
+## 第 7 步:运行推理并检查生成
+
+现在我们的模型已经训练完毕,让我们用它生成一些图像,看看它的表现如何!首先,我们要从模型保存目录加载管道:
+
+
+```python
+pipe = StableDiffusionPipeline.from_pretrained(
+ args.output_dir,
+ torch_dtype=torch.float16,
+).to("cuda")
+```
+
+接下来让我们尝试生成一些图像。在抱抱脸 Hub 小部件上为 `prompt` 变量设置默认值,可以稍微试验几次来找到一个较好的值。如果您还想尝试使用 [CLIP Interrogator](https://huggingface.co/spaces/pharma/CLIP-Interrogator) 创建更详细的提示,请参考下文:
+
+
+```python
+# Pick a funny prompt here and it will be used as the widget's default
+# when we push to the Hub in the next section
+prompt = f"illustration of a dashdash toy sitting on top of the deck of a battle ship traveling through the open sea with a lot of ships surrounding it"
+
+# Tune the guidance to control how closely the generations follow the prompt.
+# Values between 7-11 usually work best
+guidance_scale = 7
+
+num_cols = 2
+all_images = []
+for _ in range(num_cols):
+ images = pipe(prompt, guidance_scale=guidance_scale).images
+ all_images.extend(images)
+
+image_grid(all_images, 1, num_cols)
+```
+
+## 第 8 步:将您的模型推送到 Hub
+
+如果您觉得自己的模型非常棒,最后一步是将其推送到 Hub 并在 [DreamBooth 排行榜](https://huggingface.co/spaces/dreambooth-hackathon/leaderboard)上查看!
+
+⚠️ 由于网络原因,这一步可能会花费几分钟。如果失败,请重试。
+
+首先,您需要为模型库起一个名字。默认情况下,我们使用唯一标识符和类名来命名,但如果您愿意,可以随时更改:
+
+
+```python
+# 在 Hub 上为您的模型起一个名字。不允许包含空格。
+model_name = f"{name_of_your_concept}-{type_of_thing}-heywhale"
+```
+
+接下来,添加一个简短描述,介绍一下您训练的模型类型或者想要分享的任何其他信息:
+
+
+```python
+# 描述一下您选择的主题以及训练好的模型
+description = f"""
+This is a Stable Diffusion model fine-tuned on `{type_of_thing}` images for the {theme} theme,
+for the Hugging Face DreamBooth Hackathon, from the HF CN Community,
+corporated with the HeyWhale.
+"""
+
+print(description)
+```
+
+
+ This is a Stable Diffusion model fine-tuned on `toy` images for the wildcard theme,
+ for the Hugging Face DreamBooth Hackathon, from the HF CN Community,
+ corporated with the HeyWhale.
+
+
+
+最后,运行下面的单元格在 Hub 上创建一个 repo,并使用一个精美的模型卡,同时将所有的文件推送到引导:
+
+
+```python
+# 将本地保存的管道上传到 Hub 的代码
+from huggingface_hub import HfApi, ModelCard, create_repo, get_full_repo_name
+
+# 创建库
+hub_model_id = get_full_repo_name(model_name)
+create_repo(hub_model_id)
+```
+
+
+```python
+# 上传文件
+api = HfApi()
+api.upload_folder(folder_path=args.output_dir, path_in_repo="", repo_id=hub_model_id)
+```
+
+
+```python
+# 添加 metadata
+content = f"""
+---
+license: creativeml-openrail-m
+tags:
+- pytorch
+- diffusers
+- stable-diffusion
+- text-to-image
+- diffusion-models-class
+- dreambooth-hackathon
+- {theme}
+widget:
+- text: {prompt}
+---
+
+# DreamBooth model for the {name_of_your_concept} concept trained by {api.whoami()["name"]}.
+
+This is a Stable Diffusion model fine-tuned on the {name_of_your_concept} concept with DreamBooth. It can be used by modifying the `instance_prompt`: **{instance_prompt}**
+
+This model was created as part of the DreamBooth Hackathon 🔥. Visit the [organisation page](https://huggingface.co/dreambooth-hackathon) for instructions on how to take part!
+
+## Description
+
+{description}
+
+## Usage
+
+```python
+from diffusers import StableDiffusionPipeline
+
+pipeline = StableDiffusionPipeline.from_pretrained('{hub_model_id}')
+image = pipeline().images[0]
+image
+```
+"""
+
+card = ModelCard(content)
+hub_url = card.push_to_hub(hub_model_id)
+print(f"Upload successful! Model can be found here: {hub_url}")
+print(
+ f"View your submission on the public leaderboard here: https://huggingface.co/spaces/dreambooth-hackathon/leaderboard"
+)
+```
+
+恭喜恭喜 🎉 你已经训练了一个自己的文生图模型,并且成功上传到了 HuggingFace!快去跟朋友们分享,请他们使用和点赞吧~
+
+## 下一步
+
+提交参赛作品,请在 [这里](https://www.heywhale.com/org/HuggingFace/competition/area/63bbfb98de6c0e9cdb0d9dd5/submit) 提交已经上传到 Hugging Face 上的模型 URL。
+
diff --git a/markdown/unit1/01_introduction_to_diffusers_CN.md b/markdown/unit1/01_introduction_to_diffusers_CN.md
new file mode 100644
index 0000000000000000000000000000000000000000..8b3791d68dff5da1e46edbc6860542b5a030c0c0
--- /dev/null
+++ b/markdown/unit1/01_introduction_to_diffusers_CN.md
@@ -0,0 +1,882 @@
+# 🤗 Diffusers 介绍
+
+
+
+在这个 Notebook 里,你将训练你的第一个扩散模型来 **生成美丽的蝴蝶的图片 🦋**。在此过程中,你将了解 🤗 Diffuers 库,它将为我们稍后将在课程中介绍的更高级的应用程序提供良好的基础
+
+让我们开始吧!
+
+## 你将学习到
+
+在这个 Notebook 中,你将:
+
+- 看到一个强大的自定义扩散模型管道 (并了解到如何制作一个自己的版本)
+- 通过以下方式创建你自己的迷你管道:
+- 回顾扩散模型背后的核心思想
+- 从 Hub 中加载数据进行训练
+- 探索如何使用 scheduler 将噪声添加到数据中
+- 创建和训练一个 UNet 模型
+- 将各个组件拼装在一起来形成一个工作管道 (working pipelines)
+- 编辑并运行一个脚本,用于初始化一个较长的训练,该脚本将处理
+- 使用 Accelerate 来进行多 GPU 加速训练
+- 实验日志记录以跟踪关键统计数据
+- 将最终的模型上传到 Hugging Face Hub
+
+❓如果你有任何问题,请发布在 Hugging Face 的 Discord 服务器`#diffusion-models-class`频道中。你可以在这里完成注册: https://huggingface.co/join/discord
+
+## 预备知识
+
+在进入 Notebook 之前,你需要:
+
+* 📖 阅读第一单元的材料
+* 🤗 在 Hugging Face Hub 上创建一个账户。你可以在这里完成注册: https://huggingface.co/join
+
+## 步骤 1: 设置
+
+运行以下单元以安装 diffusers 库以及一些其他要求:
+
+
+```python
+%pip install -qq -U diffusers datasets transformers accelerate ftfy pyarrow
+```
+
+接下来,请前往 https://huggingface.co/settings/tokens 创建具有写权限的访问令牌:
+
+
+
+你可以使用命令行来通过此令牌登录 (`huggingface-cli login`) 或者运行以下单元来登录:
+
+
+```python
+from huggingface_hub import notebook_login
+
+notebook_login()
+```
+
+ Login successful
+ Your token has been saved to /root/.huggingface/token
+
+
+然后你需要安装 Git LFS 来上传模型检查点:
+
+
+```python
+%%capture
+!sudo apt -qq install git-lfs
+!git config --global credential.helper store
+```
+
+最后,让我们导入将要使用的库,并定义一些方便函数,稍后我们将会在 Notebook 中使用这些函数:
+
+
+```python
+import numpy as np
+import torch
+import torch.nn.functional as F
+from matplotlib import pyplot as plt
+from PIL import Image
+
+
+def show_images(x):
+ """Given a batch of images x, make a grid and convert to PIL"""
+ x = x * 0.5 + 0.5 # Map from (-1, 1) back to (0, 1)
+ grid = torchvision.utils.make_grid(x)
+ grid_im = grid.detach().cpu().permute(1, 2, 0).clip(0, 1) * 255
+ grid_im = Image.fromarray(np.array(grid_im).astype(np.uint8))
+ return grid_im
+
+
+def make_grid(images, size=64):
+ """Given a list of PIL images, stack them together into a line for easy viewing"""
+ output_im = Image.new("RGB", (size * len(images), size))
+ for i, im in enumerate(images):
+ output_im.paste(im.resize((size, size)), (i * size, 0))
+ return output_im
+
+
+# Mac users may need device = 'mps' (untested)
+device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+```
+
+好了,我们都准备好了!
+
+## Dreambooth:即将到来的巅峰
+
+如果你在过去几个月里看过人工智能相关的社交媒体,你就会听说过 Stable Diffusion 模型。这是一个强大的文本条件隐式扩散模型(别担心,我们将会学习这些概念)。但它有一个缺点:它不知道你或我长什么样,除非我们足够出名以至于互联网上发布我们的照片。
+
+Dreambooth 允许我们创建自己的模型变体,并对特定的面部、对象或样式有一些额外的了解。Corridor Crew 制作了一段出色的视频,用一致的任务形象来讲故事,这是一个很好的说明了这种技术的能力的例子:
+
+
+```python
+from IPython.display import YouTubeVideo
+
+YouTubeVideo("W4Mcuh38wyM")
+```
+
+
+
+
+
+
+
+
+
+
+这是一个使用了 [这个模型](https://huggingface.co/sd-dreambooth-library/mr-potato-head) 的例子。该模型的训练使用了 5 张著名的儿童玩具 "Mr Potato Head"的照片。
+
+首先,让我们来加载这个管道。这些代码会自动从 Hub 下载模型权重等需要的文件。由于这个只有一行的 demo 需要下载数 GB 的数据,因此你可以跳过此单元格,只需欣赏样例输出即可!
+
+
+```python
+from diffusers import StableDiffusionPipeline
+
+# Check out https://huggingface.co/sd-dreambooth-library for loads of models from the community
+model_id = "sd-dreambooth-library/mr-potato-head"
+
+# Load the pipeline
+pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to(
+ device
+)
+```
+
+
+ Fetching 15 files: 0%| | 0/15 [00:00, ?it/s]
+
+
+管道加载完成后,我们可以使用以下命令生成图像:
+
+
+```python
+prompt = "an abstract oil painting of sks mr potato head by picasso"
+image = pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0]
+image
+```
+
+
+ 0%| | 0/51 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+**练习:** 你可以使用不同的提示 (prompt) 自行尝试。在这个 demo 中,`sks`是一个新概念的唯一标识符 (UID) - 那么如果把它留空的话会发生什么事呢?你还可以尝试改变`num_inference_steps`和`guidance_scale`。这两个参数分别代表了采样步骤的数量(试试最多可以设为多低?)和模型将花多大的努力来尝试匹配提示。
+
+这条神奇的管道里有很多事情!课程结束时,你将知道这一切是如何运作的。现在,让我们看看如何从头开始训练扩散模型。
+
+## MVP (最简可实行管道)
+🤗 Diffusers 的核心 API 被分为三个主要部分:
+1. **管道**: 从高层出发设计的多种类函数,旨在以易部署的方式,能够做到快速通过主流预训练好的扩散模型来生成样本。
+2. **模型**: 训练新的扩散模型时用到的主流网络架构,*e.g.* [UNet](https://arxiv.org/abs/1505.04597).
+3. **管理器 (or 调度器)**: 在 *推理* 中使用多种不同的技巧来从噪声中生成图像,同时也可以生成在 *训练* 中所需的带噪图像。
+
+管道对于末端使用者来说已经非常棒,但你既然已经参加了这门课程,我们就索性认为你想了解更多其中的奥秘!在此篇笔记结束之后,我们会来构建属于你自己,能够生成小蝴蝶图片的管道。下面这里会是最终的结果:
+
+
+```python
+from diffusers import DDPMPipeline
+
+# Load the butterfly pipeline
+butterfly_pipeline = DDPMPipeline.from_pretrained(
+ "johnowhitaker/ddpm-butterflies-32px"
+).to(device)
+
+# Create 8 images
+images = butterfly_pipeline(batch_size=8).images
+
+# View the result
+make_grid(images)
+```
+
+
+ Fetching 4 files: 0%| | 0/4 [00:00, ?it/s]
+
+
+
+ 0%| | 0/1000 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+也许这看起来并不如 DreamBooth 所展示的样例那样惊艳,但要知道我们在训练这些图画时只用了不到训练稳定扩散模型用到数据的 0.0001%。说到模型训练,从引入介绍直到本单元,训练一个扩散模型的流程看起来像是这样:
+
+1. 从训练集中加载一些图像
+2. 加入噪声,从不同程度上
+3. 把带了不同版本噪声的数据送进模型
+4. 评估模型在对这些数据做增强去噪时的表现
+5. 使用这个信息来更新模型权重,然后重复此步骤
+
+我们会在接下来几节中逐一实现这些步骤,直至训练循环可以完整的运行,在这之后我们会来探索如何使用训练好的模型来生成样本,还有如何封装模型到管道中来轻松的分享给别人。下面我们来从数据入手吧。。。
+
+## 步骤 2:下载一个训练数据集
+
+在这个例子中,我们会用到一个来自 Hugging Face Hub 的图像集。具体来说,[是个 1000 张蝴蝶图像收藏集](https://huggingface.co/datasets/huggan/smithsonian_butterflies_subset). 这是个非常小的数据集,我们这里也同时包含了已被注释的内容指向一些规模更大的选择。如果你想使用你自己的图像收藏,你也可以使用这里被注释掉的示例代码,从一个指定的文件夹来装载图片。
+
+
+```python
+import torchvision
+from datasets import load_dataset
+from torchvision import transforms
+
+dataset = load_dataset("huggan/smithsonian_butterflies_subset", split="train")
+
+# Or load images from a local folder
+# dataset = load_dataset("imagefolder", data_dir="path/to/folder")
+
+# We'll train on 32-pixel square images, but you can try larger sizes too
+image_size = 32
+# You can lower your batch size if you're running out of GPU memory
+batch_size = 64
+
+# Define data augmentations
+preprocess = transforms.Compose(
+ [
+ transforms.Resize((image_size, image_size)), # Resize
+ transforms.RandomHorizontalFlip(), # Randomly flip (data augmentation)
+ transforms.ToTensor(), # Convert to tensor (0, 1)
+ transforms.Normalize([0.5], [0.5]), # Map to (-1, 1)
+ ]
+)
+
+
+def transform(examples):
+ images = [preprocess(image.convert("RGB")) for image in examples["image"]]
+ return {"images": images}
+
+
+dataset.set_transform(transform)
+
+# Create a dataloader from the dataset to serve up the transformed images in batches
+train_dataloader = torch.utils.data.DataLoader(
+ dataset, batch_size=batch_size, shuffle=True
+)
+```
+
+我们可以从中取出一批图像数据来看一看他们是什么样子:
+
+
+```python
+xb = next(iter(train_dataloader))["images"].to(device)[:8]
+print("X shape:", xb.shape)
+show_images(xb).resize((8 * 64, 64), resample=Image.NEAREST)
+```
+
+ X shape: torch.Size ([8, 3, 32, 32])
+
+
+ /tmp/ipykernel_4278/3975082613.py:3: DeprecationWarning: NEAREST is deprecated and will be removed in Pillow 10 (2023-07-01). Use Resampling.NEAREST or Dither.NONE instead.
+ show_images (xb).resize ((8 * 64, 64), resample=Image.NEAREST)
+
+
+
+
+
+
+
+
+
+
+
+我们在此篇笔记中使用一个只有 32 像素的小图片集来保证训练时长是可控的。
+
+## 步骤 3:定义管理器
+
+我们的训练计划是,取出这些输入图片然后对它们增添噪声,在这之后把带噪的图片送入模型。在推理阶段,我们将用模型的预测值来不断迭代去除这些噪点。在`diffusers`中,这两个步骤都是由 **管理器(调度器)** 来处理的。
+
+噪声管理器决定在不同的迭代周期时分别加入多少噪声。我们可以这样创建一个管理器,是取自于训练并能取样 'DDPM' 的默认配置。 (基于此篇论文 ["Denoising Diffusion Probabalistic Models"](https://arxiv.org/abs/2006.11239):
+
+
+```python
+from diffusers import DDPMScheduler
+
+noise_scheduler = DDPMScheduler(num_train_timesteps=1000)
+```
+
+DDPM 论文这样来描述一个损坏过程,为每一个 ' 迭代周期 '(timestep) 增添一点少量的噪声。设在某个迭代周期有 $x_{t-1}$, 我们可以得到它的下一个版本 $x_t$ (比之前更多一点点噪声):
+
+
+ 图片来源于 DDPM paper (https://arxiv.org/abs/2006.11239)。
+
+
+扩散模型成功的秘诀在于扩散过程的迭代本质。最先生成的只是一组随机噪声,但是经过若干步的逐渐改善之后,最终会出现有意义的图像。在每一步中,模型都会估计如何从当前的输入生成完全去噪的结果。因为我们在每一步都只做了一个小小的变动,所以在早期阶段(预测最终输出实际上非常困难),这个估计中的任何 error 都可以在以后的更新中得到纠正。
+
+与其他类型的生成模型相比,训练扩散模型相对较为容易。我们只需要重复以下步骤即可:
+
+1) 从训练数据中加载一些图像
+2) 添加不同级别的噪声。请记住,我们希望模型在面对添加了极端噪声和几乎没有添加噪声的带噪图像时,都能够很好地估计如何 “修复”(去噪)。
+3) 将带噪输入送入模型中
+4) 评估模型对这些输入进行去噪的效果
+5) 使用此信息更新模型权重
+
+为了用训练好的模型生成新的图像,我们从完全随机的输入开始,反复将其输入模型,每次根据模型预测进行少量更新。我们之后会学到有许多采样方法试图简化这个过程,以便我们可以用尽可能少的步骤生成好的图像。
+我们将在第一单元的实践笔记本中详细介绍这些步骤。在第二单元中,我们将了解如何修改此过程,来通过额外的条件(例如类标签)或使用指导等技术来增加对模型输出的额外控制。第三单元和第四单元将探索一种非常强大的扩散模型,称为稳定扩散 (stable diffusion),它可以生成给定文本描述的图像。
+
+## 实践笔记本
+
+到这里,你已经足够了解如何开始使用附带的笔记本了!这里的两个笔记本以不同的方式表达了相同的想法。
+
+| Chapter | Colab | Kaggle | Gradient | Studio Lab |
+|:--------------------------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| Introduction to Diffusers | [](https://colab.research.google.com/github/darcula1993/diffusion-models-class-CN/blob/main/unit1/01_introduction_to_diffusers_CN.ipynb) | [](https://kaggle.com/kernels/welcome?src=https://github.com/huggingface/diffusion-models-class/blob/main/unit1/01_introduction_to_diffusers_CN.ipynb) | [](https://console.paperspace.com/github/darcula1993/diffusion-models-class-CN/blob/main/unit1/01_introduction_to_diffusers_CN.ipynb) | [](https://studiolab.sagemaker.aws/import/github/darcula1993/diffusion-models-class-CN/blob/main/unit1/01_introduction_to_diffusers_CN.ipynb) |
+| Diffusion Models from Scratch | [](https://colab.research.google.com/github/darcula1993/diffusion-models-class-CN/blob/main/unit1/02_diffusion_models_from_scratch_CN.ipynb) | [](https://kaggle.com/kernels/welcome?src=https://github.com/huggingface/diffusion-models-class/blob/main/unit1/02_diffusion_models_from_scratch_CN.ipynb) | [](https://console.paperspace.com/github/darcula1993/diffusion-models-class-CN/blob/main/unit1/02_diffusion_models_from_scratch_CN.ipynb) | [](https://studiolab.sagemaker.aws/import/github/darcula1993/diffusion-models-class-CN/blob/main/unit1/02_diffusion_models_from_scratch_CN.ipynb) |
+
+在 _**Introduction to Diffusers**_ 这个 Notebook 中,我们使用 diffusers 库中的构造模块显示了与上述不同的步骤。你将很快看到如何根据你选择的任何数据创建、训练和采样你自己的扩散模型。 在笔记本结束时,你将能够阅读和修改示例训练脚本,以训练扩散模型,并将其与全世界共同分享! 本笔记本还介绍了与本单元相关的主要练习,在这里,我们将共同尝试为不同规模的扩散模型找出好的「训练脚本」- 请参阅下一节了解更多信息。
+
+在 _**Diffusion Models from Scratch**_ 这个 Notebook 中,我们展示了相同的步骤(向数据添加噪声、创建模型、训练和采样),并尽可能简单地在 PyTorch 中从头开始实现。然后,我们将这个「玩具示例」与 `diffusers` 版本进行比较,并关注两者的区别以及改进之处。这里的目标是熟悉不同的组件和其中的设计决策,以便在查看新的实现时能够快速确定关键思想。
+
+## 项目时间
+
+现在,你已经掌握了基本知识,可以开始训练你自己的扩散模型了! _**Introduction to Diffusers**_ 这个 Notebook 的末尾有一些小提示,希望你能与社区分享你的成果、训练脚本和发现,以便我们能够一起找出训练这些模型的最佳方法。
+
+## 一些额外的材料
+
+- [《Hugging Face 博客: 带注释的扩散模型》](https://huggingface.co/blog/annotated-diffusion)是对 DDPM 背后的代码和理论的非常深入的介绍,其中包括数学和显示了所有不同的组件的代码。它还链接了一些论文供进一步阅读:
+- [Hugging Face 文档: 无条件图像生成 (Unconditional Image-Generation)](https://huggingface.co/docs/diffusers/training/unconditional_training),包含了有关如何使用官方训练示例脚本训练扩散模型的一些示例,包括演示如何创建自己的数据集的代码:
+- AI Coffee Break video on Diffusion Models: https://www.youtube.com/watch?v=344w5h24-h8
+- Yannic Kilcher Video on DDPMs: https://www.youtube.com/watch?v=W-O7AZNzbzQ
+
+发现了有其他任何有帮助的资源?请 [向我们提出](https://github.com/huggingface/diffusion-models-class/issues),我们会将其加入到上面的列表中。
\ No newline at end of file
diff --git a/markdown/unit2/01_finetuning_and_guidance_CN.md b/markdown/unit2/01_finetuning_and_guidance_CN.md
new file mode 100644
index 0000000000000000000000000000000000000000..800bd89d67ebb023dd1ca2d087efc6d8315fd105
--- /dev/null
+++ b/markdown/unit2/01_finetuning_and_guidance_CN.md
@@ -0,0 +1,1048 @@
+# Fine-Tuning and Guidance
+
+在这一节的笔记本中,我们将讲解两种主要的基于现有模型实现改造的方法:
+
+* 通过**微调(fine-tuning)**,我们将在新的数据集上重新训练已有的模型,来改变它原有的输出类型
+* 通过**引导(guidance)**,我们将在推理阶段引导现有模型的生成过程,以此来获取额外的控制
+
+## 你将学到:
+
+在阅读完这一节笔记本后,你将学会:
+
+- 创建一个采样循环,并使用调度器(scheduler)更快地生成样本
+- 在新数据集上微调一个现有的扩散模型,这包括:
+ - 使用累积梯度的方法去应对训练的 batch 太小所带来的一些问题
+ - 在训练过程中,将样本上传到 [Weights and Biases](https://wandb.ai/site) 来记录日志,以此来监控训练过程(通过附加的实例脚本程序)
+ - 将最终结果管线(pipeline)保存下来,并上传到Hub
+- 通过新加的损失函数来引导采样过程,以此对现有模型施加控制,这包括:
+ - 通过一个简单的基于颜色的损失来探索不同的引导方法
+ - 使用 CLIP,用文本来引导生成过程
+ - 用 Gradio 和 🤗 Spaces 来分享你的定制的采样循环
+
+❓如果你有问题,请在 Hugging Face Discord 的 `#diffusion-models-class` 频道提出。如果你还没有 Hugging Face 的账号,你可以在这里注册:https://huggingface.co/join/discord
+
+## 配置过程和需要引入的库
+
+为了将你的微调过的模型保存到 Hugging Face Hub 上,你需要使用一个**具有写权限的访问令牌**来登录。下列代码将会引导你登陆并连接上你的账号的相关令牌页。如果在模型训练过程中,你想使用训练脚本将样本记录到日志,你也需要一个 Weights and Biases 账号 —— 同样地,这些代码也会在需要的时候引导你登录。
+
+此外,你唯一需要配置的就是安装几个依赖,并在程序中引入我们需要的东西然后制定好我们将使用的计算设备。
+
+
+
+```python
+!pip install -qq diffusers datasets accelerate wandb open-clip-torch
+```
+
+
+```python
+# Code to log in to the Hugging Face Hub, needed for sharing models
+# Make sure you use a token with WRITE access
+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, ?it/s]
+
+
+生成图像就像调用管线的[`__call__`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ddpm/pipeline_ddpm.py#L42)方法一样简单,我们像调用函数一样来试试:
+
+
+```python
+images = image_pipe().images
+images[0]
+```
+
+
+ 0%| | 0/1000 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+过程很简洁,但速度有点慢!所以,在我们进入今天的正题之前,我们先窥探一下实际的采样循环是什么样,并看看我们能不能用一个更炫酷点的采样器来加速这一过程:
+
+## DDIM更快的采样过程
+
+在生成的每一步中,模型都是接收一个加噪声的输入,并被要求去预测这个噪声(以此来估计完全没噪声的图片是什么样)。最初这些预测都还不算太好,因此我们把这一过程分解成很多步。但另一方面,使用1000+步来实现整个生成过程也不是必要的,因为最近的很多研究已经找到了使用尽可能少的步数来生成好的结果的方法。
+
+在 🤗 Diffusers 库中,**这些采样方法是通过调度器(scheduler)来操控的**,每次更新通过`step()`函数完成。为了生成图片,我们从随机噪声$x$开始,每一个迭代周期(timestep)我们都送入模型一个带噪声的输入$x$并把模型预测结果再次输入`step()`函数。这里返回的输出都被命名为`prev_sample` —— 之所以是“previous”,是因为我们是在时间上“后退”,即从高噪声到低噪声(这和前向扩散过程是相反的)。
+
+我们实践一下看看:先载入一个 scheduler,这里用的是 DDIMScheduler(基于这篇论文:[Denoising Diffusion Implicit Models](https://arxiv.org/abs/2010.02502))。与原版的 DDPM 相比,它可以用少得多的迭代周期来产生很不错的采样样本。
+
+
+```python
+# Create new scheduler and set num inference steps
+scheduler = DDIMScheduler.from_pretrained("google/ddpm-celebahq-256")
+scheduler.set_timesteps(num_inference_steps=40)
+```
+
+可以看到,这个模型只使用了 40 步,走一步抵得上原始 1000 步调度器走 25 步了:
+
+
+```python
+scheduler.timesteps
+```
+
+
+
+
+ tensor([975, 950, 925, 900, 875, 850, 825, 800, 775, 750, 725, 700, 675, 650,
+ 625, 600, 575, 550, 525, 500, 475, 450, 425, 400, 375, 350, 325, 300,
+ 275, 250, 225, 200, 175, 150, 125, 100, 75, 50, 25, 0])
+
+
+
+我们来造出 4 个随机噪声图片,用它们跑一跑采样循环,同时观察一下每一步的$x$和预测出的去噪版本:
+
+
+```python
+# The random starting point
+x = torch.randn(4, 3, 256, 256).to(device) # Batch of 4, 3-channel 256 x 256 px images
+
+# Loop through the sampling timesteps
+for i, t in tqdm(enumerate(scheduler.timesteps)):
+
+ # Prepare model input
+ model_input = scheduler.scale_model_input(x, t)
+
+ # Get the prediction
+ with torch.no_grad():
+ noise_pred = image_pipe.unet(model_input, t)["sample"]
+
+ # Calculate what the updated sample should look like with the scheduler
+ scheduler_output = scheduler.step(noise_pred, t, x)
+
+ # Update x
+ x = scheduler_output.prev_sample
+
+ # Occasionally display both x and the predicted denoised images
+ if i % 10 == 0 or i == len(scheduler.timesteps) - 1:
+ fig, axs = plt.subplots(1, 2, figsize=(12, 5))
+
+ grid = torchvision.utils.make_grid(x, nrow=4).permute(1, 2, 0)
+ axs[0].imshow(grid.cpu().clip(-1, 1) * 0.5 + 0.5)
+ axs[0].set_title(f"Current x (step {i})")
+
+ pred_x0 = (
+ scheduler_output.pred_original_sample
+ ) # Not available for all schedulers
+ grid = torchvision.utils.make_grid(pred_x0, nrow=4).permute(1, 2, 0)
+ axs[1].imshow(grid.cpu().clip(-1, 1) * 0.5 + 0.5)
+ axs[1].set_title(f"Predicted denoised images (step {i})")
+ plt.show()
+```
+
+
+ 0it [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+可以看出,一开始预测结果并不是那么好,但随着这一过程的推进,预测的输出被一步步改善。如果你想了解`steps()`函数内的数学原理,你可以通过这行指令来看看(带详细注释的)代码:
+
+
+```python
+# ??scheduler.step
+```
+
+你也可以直接用新的调度器替换原有管线(pipeline)中的调度器,然后采样。像这样做:
+
+
+```python
+image_pipe.scheduler = scheduler
+images = image_pipe(num_inference_steps=40).images
+images[0]
+```
+
+
+ 0%| | 0/40 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+好了!我们现在可以在可接受的时间内采样了!这样我们学习接下来的部分就能快点了:)
+
+## 微调
+
+现在玩点好玩的!给我们一个预训练过的管线(pipeline),我们怎样使用新的训练数据重训模型来生成图片?
+
+看起来这和我们从头训练模型是几乎一样的(正如我们在[第一单元](../unit1)所见的一样),除了我们这里是用现有模型作为初始化的。让我们实践一下看看,并额外考虑几点我们要注意的东西。
+
+首先,数据方面,你可以尝试用 [Vintage Faces 数据集](https://huggingface.co/datasets/Norod78/Vintage-Faces-FFHQAligned) 或者[这些动漫人脸图片](https://huggingface.co/datasets/huggan/anime-faces)来获取和这个人脸模型的原始训练数据类似的数据。但我们现在还是先用和第一单元一样的蝴蝶数据集吧。通过以下代码来下载蝴蝶数据集,并建立一个能按批(batch)采样图片的`dataloader`:
+
+
+```python
+# @markdown load and prepare a dataset:
+# Not on Colab? Comments with #@ enable UI tweaks like headings or user inputs
+# but can safely be ignored if you're working on a different platform.
+
+dataset_name = "huggan/smithsonian_butterflies_subset" # @param
+dataset = load_dataset(dataset_name, split="train")
+image_size = 256 # @param
+batch_size = 4 # @param
+preprocess = transforms.Compose(
+ [
+ transforms.Resize((image_size, image_size)),
+ transforms.RandomHorizontalFlip(),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5], [0.5]),
+ ]
+)
+
+
+def transform(examples):
+ images = [preprocess(image.convert("RGB")) for image in examples["image"]]
+ return {"images": images}
+
+
+dataset.set_transform(transform)
+
+train_dataloader = torch.utils.data.DataLoader(
+ dataset, batch_size=batch_size, shuffle=True
+)
+
+print("Previewing batch:")
+batch = next(iter(train_dataloader))
+grid = torchvision.utils.make_grid(batch["images"], nrow=4)
+plt.imshow(grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5);
+```
+
+ Using custom data configuration huggan--smithsonian_butterflies_subset-7665b1021a37404c
+ Found cached dataset parquet (/home/lewis_huggingface_co/.cache/huggingface/datasets/huggan___parquet/huggan--smithsonian_butterflies_subset-7665b1021a37404c/0.0.0/2a3b91fbd88a2c90d1dbbb32b460cf621d31bd5b05b934492fdef7d8d6f236ec)
+
+
+ Previewing batch:
+
+
+
+
+
+
+
+
+**考虑因素1:** 我们这里使用的 batch size 很小(只有 4),因为我们的训练是基于较大的图片尺寸的(256px),并且我们的模型也很大,如果我们的 batch size 太高,GPU 的内存可能会不够用了。你可以减小图片尺寸,换取更大的 batch size 来加速训练,但这里的模型一开始都是基于生成 256px 尺寸的图片来设计和训练的。
+
+现在我们看看训练循环。我们把要优化的目标参数设定为`image_pipe.unet.parameters()`,以此来更新预训练过的模型的权重。其它部分的代码基本上和第一单元例子中的对应部分一样。在 Colab 上跑的话,大约需要10分钟,你可以趁这个时间喝杯茶休息一下。
+
+
+```python
+num_epochs = 2 # @param
+lr = 1e-5 # 2param
+grad_accumulation_steps = 2 # @param
+
+optimizer = torch.optim.AdamW(image_pipe.unet.parameters(), lr=lr)
+
+losses = []
+
+for epoch in range(num_epochs):
+ for step, batch in tqdm(enumerate(train_dataloader), total=len(train_dataloader)):
+ clean_images = batch["images"].to(device)
+ # Sample noise to add to the images
+ noise = torch.randn(clean_images.shape).to(clean_images.device)
+ bs = clean_images.shape[0]
+
+ # Sample a random timestep for each image
+ timesteps = torch.randint(
+ 0,
+ image_pipe.scheduler.num_train_timesteps,
+ (bs,),
+ device=clean_images.device,
+ ).long()
+
+ # Add noise to the clean images according to the noise magnitude at each timestep
+ # (this is the forward diffusion process)
+ noisy_images = image_pipe.scheduler.add_noise(clean_images, noise, timesteps)
+
+ # Get the model prediction for the noise
+ noise_pred = image_pipe.unet(noisy_images, timesteps, return_dict=False)[0]
+
+ # Compare the prediction with the actual noise:
+ loss = F.mse_loss(
+ noise_pred, noise
+ ) # NB - trying to predict noise (eps) not (noisy_ims-clean_ims) or just (clean_ims)
+
+ # Store for later plotting
+ losses.append(loss.item())
+
+ # Update the model parameters with the optimizer based on this loss
+ loss.backward(loss)
+
+ # Gradient accumulation:
+ if (step + 1) % grad_accumulation_steps == 0:
+ optimizer.step()
+ optimizer.zero_grad()
+
+ print(
+ f"Epoch {epoch} average loss: {sum(losses[-len(train_dataloader):])/len(train_dataloader)}"
+ )
+
+# Plot the loss curve:
+plt.plot(losses)
+```
+
+
+ 0%| | 0/250 [00:00, ?it/s]
+
+
+ Epoch 0 average loss: 0.013324214214226231
+
+
+
+ 0%| | 0/250 [00:00, ?it/s]
+
+
+ Epoch 1 average loss: 0.014018508377484978
+
+
+
+
+
+ [
+_示例图片,由 Stable Diffusion 生成_
+
+Stable Diffusion 是一个强大的文本条件隐式扩散模型(text-conditioned latent diffusion model)。不要担心,我们马上就会解释这些名词。它根据文字描述生成令人惊艳的图片的能力震惊了整个互联网。在本单元,我们将会一探 SD 的工作原理并了解一下它还能搞出什么其它花招。
+
+## 隐式扩散(Latent Diffusion)
+
+当图片尺寸变大时,需要的计算能力也随之增加。这种现象在自注意力机制(self-attention)这种操作的影响下尤为突出,因为操作数随着输入量的增大呈平方地增加。一个 128px 的正方形图片有着四倍于 64px 正方形图片的像素数量,所以在自注意力层就需要16倍(42)的内存和计算量。这是任何需要生成高分辨率图片的人都会遇到的问题。
+
+
+_Diagram from the [Latent Diffusion paper](http://arxiv.org/abs/2112.10752)_
+
+隐式扩散致力于克服这一难题,它使用一个独立的模型 Variational Auto-Encoder(VAE)**压缩**图片到一个更小的空间维度。这背后的原理是,图片通场都包含了大量的冗余信息 —— 给定足够的训练数据,一个 VAE 可以学会产出一个比输入图片小得多的表征,并把这个**隐式**表征重建回原图片,同时保留较高的保真度。SD 模型中的 VAE 接收一个三通道图片输入,生成出一个四通道的隐式表征,同时每一个空间维度上都减少为原来的八分之一。比如,一个 512px 的正方形图片将会被压缩到一个 4×64×64 的隐式表征上。
+
+通过把扩散过程引用到这些**隐式表征**而不是完整图像上,我们可以从中得到很多好处(更低的内存使用、更少的 UNet 层数、更快的生成速度...)。同时我们仍能把结果使用 VAE 中的解码器解码到高分辨率图片上来查看最终结果。这一创新点极大地降低了训练和运行这些模型的成本。
+
+## 以文本为生成条件
+
+在第二单元,我们展示了如何将额外信息输入到 UNet,让我们对生成的图片有了额外的控制。我们把这种方法叫做条件生成。给定一个带噪图片,我们让模型**基于额外的线索**(比如类别标签,或 Stable Diffusion 中的文字描述)去预测去噪的版本。在推理阶段,我们可以输入对期望图片的文字表述和纯噪声数据作为起始点,然后模型就开始全力对随机输入进行“去噪”,以求生成的图片能匹配上文字描述。
+
+
+_图表:文本编码过程,即将输入的文本提示转化为一系列的文本嵌入(即图中的 encoder_hidden_states),然后输入 Unet 作为生成条件_
+
+为了达成这一目的,我们首先需要为文本创建一个数值的表示形式,用来获取文字描述的相关信息。为此,SD 利用了一个名为CLIP的预训练transformer模型。CLIP 的文本编码器是用来处理图像说明文字、将其转换为可以用来对比图片和文本的形式的。所以这个模型非常适合用来从文字描述来为图像创建有用的表征信息。一个输入文字提示会首先被分词(tokenize,基于一个很大的词汇库把句中的词语或短语转化为一个个的token),然后被输入进 CLIP 的文字编码器,为每个token产出一个 768 维(针对 SD 1.X版本)或1024维(针对SD 2.X版本)的向量。为了使得输入格式一致,文本提示总是被补全或截断到含有 77 个 token 的长度,所以每个文字提示最终作为生成条件的表示形式是一个形状为 77×1024 的张量。
+
+
+
+那我们如何实际地将这些条件信息输入到 UNet 里让它预测使用呢?答案是使用交叉注意力机制(cross-attention)。交叉注意力层从头到尾贯穿了 UNet 结构。UNet 中的每个空间位置都可以“注意”文字条件中不同的token,以此从文字提示中获取到了不同位置的相互关联信息。上面的图表就展示了文字条件信息(以及基于时间周期 time-step 的条件)是如何在不同的位置点输入的。 可以看到,UNet 的每一层都由充足的机会去利用这些条件信息!
+
+## 无分类器的引导
+
+然而很多时候,即使我们付出了很多努力尽可能让文本成为生成的条件,但模型仍然会在预测时大量地基于带噪输入图片,而不是文字。在某种程度上,这其实是可以解释得通的 —— 很多说明文字和与之关联的图片相关性很弱,所以模型就学着不去过度依赖文字描述!可是这并不是我们期望的效果。如果模型不遵从文本提示,那么我们很可能得到与我们描述根本不相关的图片。
+
+
+_由描述 "An oil painting of a collie in a top hat" 生成的图片(从左到右的 CFG scale 分别是 0、1、2、10)_
+
+为了解决这一问题,我们使用了一个小技巧,叫做无分类器的引导(Classifie-free Guidance,CGF)。在训练时,我们时不时把文字条件置空,强迫模型去学着在无文字信息的情况下对图片去噪(无条件生成)。在推理阶段,我们分别做两个预测:一个有文字条件,一个没有。我们可以用这两者的差异来建立一个最终结合版的预测,让最终结果在文本条件预测所指明的方向上依据一个缩放系数(即引导尺度)去“走得更远”,希望最终生成一个更好地匹配文字提示的结果。上图就展示了在同一个文本提示下使用不同引导尺度得到的不同结果。可以看到,更高的引导尺度能让生成的图片更接近文字描述。
+
+## 其它类型的条件生成:超分辨率、图像修补、深度图到图像的转换
+
+我们也可以创建各种接收不同生成条件的 Stable Diffusion 模型。比如[深度图到图像转换模型](https://huggingface.co/stabilityai/stable-diffusion-2-depth)使用一个额外的输入通道接收要被去噪的图片的深度信息。所以在推理阶段,我们就可以输入一个目标图片的深度图(由另一个独立的模型预测出来),以此来希望模型生成一个有相似全局结构的图片。
+
+
+_基于深度的 SD 模型可以根据同一个全局结构生成不同的图片(示例来自StabilityAI)_
+
+用相似的方式,我们也可以输入一个低分辨率图片作为条件,让模型生成对应的高分辨率图片([正如Stable Diffusion Upscaler](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler)一样)。此外,我们还可以输入一个掩膜(mask),让模型知道图像相应的区域需要让模型用in-painting的方式重新生成一下:掩膜外的区域要和原图片保持一致,掩膜内的区域要生成出新的内容。
+
+## 使用 DreamBooth 微调
+
+
+_由 Imagen model 生成的图片,来自[dreambooth 项目页](https://dreambooth.github.io/)_
+
+DreamBooth 可以用来微调一个文字到图像的生成模型,教它一些新的概念,比如某一特定物体或某种特定风格。这一技术一开始是为 Google 的 Imagen Model 开发的,但被很快应用于 [stable diffusion](https://huggingface.co/docs/diffusers/training/dreambooth) 中。效果十分惊艳(如果你最近在社交媒体上看到谁使用了 AI 生成的头像,那这个头像有很大概率是出自于基于 DreamBooth 的服务),但该技术也对各种设置十分敏感。所以请学习我们这一单元的笔记本,并阅读[这个对不同训练参数的调研资料](https://huggingface.co/blog/dreambooth)来获取些参考,让模型尽可能地起作用。
+
+## 用来上手的笔记本示例
+
+| Chapter | Colab | Kaggle | Gradient | Studio Lab |
+|:--------------------------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| Stable Diffusion Introduction | [](https://colab.research.google.com/github/huggingface/diffusion-models-class/blob/main/unit3/01_stable_diffusion_introduction.ipynb) | [](https://kaggle.com/kernels/welcome?src=https://github.com/huggingface/diffusion-models-class/blob/main/unit3/01_stable_diffusion_introduction.ipynb) | [](https://console.paperspace.com/github/huggingface/diffusion-models-class/blob/main/unit3/01_stable_diffusion_introduction.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/diffusion-models-class/blob/main/unit3/01_stable_diffusion_introduction.ipynb) |
+| DreamBooth Hackathon Notebook | [](https://colab.research.google.com/github/huggingface/diffusion-models-class/blob/main/hackathon/dreambooth.ipynb) | [](https://kaggle.com/kernels/welcome?src=https://github.com/huggingface/diffusion-models-class/blob/main/hackathon/dreambooth.ipynb) | [](https://console.paperspace.com/github/huggingface/diffusion-models-class/blob/main/hackathon/dreambooth.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/diffusion-models-class/blob/main/hackathon/dreambooth.ipynb) |
+| Stable Diffusion Deep Dive | [](https://colab.research.google.com/github/fastai/diffusion-nbs/blob/master/Stable%20Diffusion%20Deep%20Dive.ipynb ) | [](https://kaggle.com/kernels/welcome?src=https://github.com/fastai/diffusion-nbs/blob/master/Stable%20Diffusion%20Deep%20Dive.ipynb ) | [](https://console.paperspace.com/github/fastai/diffusion-nbs/blob/master/Stable%20Diffusion%20Deep%20Dive.ipynb ) | [](https://studiolab.sagemaker.aws/import/github/fastai/diffusion-nbs/blob/master/Stable%20Diffusion%20Deep%20Dive.ipynb ) |
+
+至此,你已经准备好学习相关笔记本了!通过上面的链接使用你选择的平台打开它们!DreamBooth 需要的算力比较多,所以如果你是用的 Kaggle 或 Google Colab,那请确保将运行时模式设为 GPU 来获得最好效果。
+
+Stable Diffusion Introduction 这节笔记本是使用🤗 Diffusers 库对 Stable Diffusion 所作的一个简短介绍,包含了一些基本的使用管线生成和修改图片的示例。
+
+在 DreamBooth Hackathon 这节笔记本(在 [hackathon 文件夹里](../hackathon))中,我们展示了如何使用你自己的图片微调 SD,来获取一个涵盖新的风格或内容的自定义版本模型。
+
+最后,在 Stable Diffusion Deep Dive 笔记本中和视频中,我们分解了一个典型的生成管线中的每一个步骤,并提出了一些新奇的方法去对每一步进行修改,来有创造性地控制生成。
+
+## 项目时间
+
+仿照 **DreamBooth** 笔记本中的指导,针对某个特定种类的数据训练你自己的模型。请确保在提交时加入一些输出的例子,以便我们为不同的种类数据选出最好的模型!请查阅 [hackathon 信息](../hackathon),进一步了解关于奖项、GPU额度等信息。
+
+## 一些其它学习资源
+
+- [High-Resolution Image Synthesis with Latent Diffusion Models](http://arxiv.org/abs/2112.10752) - 这篇论文介绍了 Stable Diffusion 背后的方法
+
+- [CLIP](https://openai.com/blog/clip/) - CLIP 学习着去将文字和图片联系起来,CLIP 文本编码器被用来将文本提示转化为 SD 使用的信息量丰富的数值表征形式。也可查阅 [这篇关于 OpenCLIP 的文献](https://wandb.ai/johnowhitaker/openclip-benchmarking/reports/Exploring-OpenCLIP--VmlldzoyOTIzNzIz),了解最近的一些 CLIP 开源版本(其中一个被用于第二版 SD 模型)。
+
+- [GLIDE: Towards Photorealistic Image Generation and Editing with Text-Guided Diffusion Models](https://arxiv.org/abs/2112.10741) 是一篇较早的论文,介绍了把文本作为生成条件以及 CFG 相关内容。
+
+如果你找到了更好的学习资源,也别忘了告诉我们让我们加到这个列表里!
diff --git a/markdown/unit3/cfg_example_0_1_2_10.jpeg b/markdown/unit3/cfg_example_0_1_2_10.jpeg
new file mode 100644
index 0000000000000000000000000000000000000000..b685f6157517a933e19755425d207fc6dea72a35
--- /dev/null
+++ b/markdown/unit3/cfg_example_0_1_2_10.jpeg
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a5d9636a1381fe0e9570774ddda7a88d23fe01c52fa4ae563850686efc84a685
+size 204059
diff --git a/markdown/unit3/sd_demo_images.jpg b/markdown/unit3/sd_demo_images.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..5f2770e21c196774cb52ab55d5dfee2bf9721bd6
--- /dev/null
+++ b/markdown/unit3/sd_demo_images.jpg
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:cfd6aca118d829e505cfb60167f6020c5e9680690bd747b50e38350b8377d6a8
+size 227696
diff --git a/markdown/unit3/sd_unet_color.png b/markdown/unit3/sd_unet_color.png
new file mode 100644
index 0000000000000000000000000000000000000000..4ac89f297f2b9a6c90933a84db65d6d3380387fa
--- /dev/null
+++ b/markdown/unit3/sd_unet_color.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9a66f5943946a88a8e39ac686fb7d4d7d13acd740b2f8f146c7f1e01dec340a7
+size 190494
diff --git a/markdown/unit3/text_encoder_noborder.png b/markdown/unit3/text_encoder_noborder.png
new file mode 100644
index 0000000000000000000000000000000000000000..9c534a526fc61c0aafc0ded3eefb3d18365d5edb
--- /dev/null
+++ b/markdown/unit3/text_encoder_noborder.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:befb00d52c33291fb23739e1214ab4977a1b6476d56b199b13a1e310997f6a0f
+size 55584
diff --git a/markdown/unit4/01_ddim_inversion_CN.md b/markdown/unit4/01_ddim_inversion_CN.md
new file mode 100644
index 0000000000000000000000000000000000000000..9802309d168520a4e7c6fb7b39dc6937e922a49d
--- /dev/null
+++ b/markdown/unit4/01_ddim_inversion_CN.md
@@ -0,0 +1,570 @@
+# DDIM反转
+
+在此篇笔记我们会来探索**反转**,看看它是如何影响取样的,并把它应用到扩散模型的编辑图像功能中去。
+
+## 你将会学到什么
+
+- DDIM采样是怎么工作的
+- 确定性vs随机性取样器
+- DDIM反转的理论支撑
+- 使用反转来编辑图像
+
+我们开始吧!
+
+## 设置
+
+
+```python
+# !pip install -q transformers diffusers accelerate
+```
+
+
+```python
+import torch
+import requests
+import torch.nn as nn
+import torch.nn.functional as F
+from PIL import Image
+from io import BytesIO
+from tqdm.auto import tqdm
+from matplotlib import pyplot as plt
+from torchvision import transforms as tfms
+from diffusers import StableDiffusionPipeline, DDIMScheduler
+
+# Useful function for later
+def load_image(url, size=None):
+ response = requests.get(url,timeout=0.2)
+ img = Image.open(BytesIO(response.content)).convert('RGB')
+ if size is not None:
+ img = img.resize(size)
+ return img
+```
+
+
+```python
+device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+```
+
+## 加载一个已训练的pipeline
+
+
+```python
+# Load a pipeline
+pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5").to(device)
+```
+
+
+```python
+# Set up a DDIM scheduler:
+pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
+```
+
+
+```python
+# Sample an image to make sure it is all working
+prompt = 'Beautiful DSLR Photograph of a penguin on the beach, golden hour'
+negative_prompt = 'blurry, ugly, stock photo'
+im = pipe(prompt, negative_prompt=negative_prompt).images[0]
+im.resize((256, 256)) # resize for convenient viewing
+```
+
+## DDIM取样过程
+
+在给定时间 $t$, 带噪图像 $x_t$ 是原始图像($x_0$)与一些噪声 ($\epsilon$)的叠加。这是在DDIM论文中$x_t$的定义式,我们把它引用到此节里:
+
+$$ x_t = \sqrt{\alpha_t}x_0 + \sqrt{1-\alpha_t}\epsilon $$
+
+$\epsilon$ 是一些归一方差的高斯噪声
+$\alpha_t$ ('alpha')在DDPM论文中也被叫做$\bar{\alpha}$ ('alpha_bar'),被用来定义噪声调度器(scheduler)。在扩散模型中,alpha调度器是被计算出来并排序存储在`scheduler.alphas_cumprod`中。这令人费解,我理解!我们把这些值画出来,然后在下文中我们会使用DDIM的标注方式。
+
+
+```python
+# Plot 'alpha' (alpha_bar in DDPM language, alphas_cumprod in diffusers for clarity)
+timesteps = pipe.scheduler.timesteps.cpu()
+alphas = pipe.scheduler.alphas_cumprod[timesteps]
+plt.plot(timesteps, alphas, label='alpha_t');
+plt.legend();
+```
+
+最初(timestep 0 ,图中左侧)是从一个无噪的干净图像开始,$\alpha_t = 1$。当我们到达更高的timesteps,我们得到一个几乎全是噪声的图像,$\alpha_t$也几乎下降到0。
+
+在采样过程,我们从timestep1000的纯噪声开始,慢慢地向timestep0前进。为了计算采样轨迹中的下一时刻($x_{t-1}$因为我们是从后向前移动)的值,我们预测噪声($\epsilon_\theta(x_t)$,这就是我们模型的输出),用它来预测出无噪的图片$x_0$。在这之后我们用这个预测结果朝着'$x_t$的方向'方向移动一小步。最终,我们可以加一些带$\sigma_t$系数的额外噪声。这是论文中与上述操作相关的章节内容:
+
+
+
+好,我们有了在可控量度噪声下,从$x_t$ 移动到 $x_{t-1}$的公式。今天我们所说案例是不需要再额外添加噪声的 - 即完全确定的DDIM采样。我们来看看这些是如何用代码表达的。
+
+
+```python
+# Sample function (regular DDIM)
+@torch.no_grad()
+def sample(prompt, start_step=0, start_latents=None,
+ guidance_scale=3.5, num_inference_steps=30,
+ num_images_per_prompt=1, do_classifier_free_guidance=True,
+ negative_prompt='', device=device):
+
+ # Encode prompt
+ text_embeddings = pipe._encode_prompt(
+ prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
+ )
+
+ # Set num inference steps
+ pipe.scheduler.set_timesteps(num_inference_steps, device=device)
+
+ # Create a random starting point if we don't have one already
+ if start_latents is None:
+ start_latents = torch.randn(1, 4, 64, 64, device=device)
+ start_latents *= pipe.scheduler.init_noise_sigma
+
+ latents = start_latents.clone()
+
+ for i in tqdm(range(start_step, num_inference_steps)):
+
+ t = pipe.scheduler.timesteps[i]
+
+ # expand the latents if we are doing classifier free guidance
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
+ latent_model_input = pipe.scheduler.scale_model_input(latent_model_input, t)
+
+ # predict the noise residual
+ noise_pred = pipe.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
+
+ # perform guidance
+ if do_classifier_free_guidance:
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
+
+
+ # Normally we'd rely on the scheduler to handle the update step:
+ # latents = pipe.scheduler.step(noise_pred, t, latents).prev_sample
+
+ # Instead, let's do it ourselves:
+ prev_t = max(1, t.item() - (1000//num_inference_steps)) # t-1
+ alpha_t = pipe.scheduler.alphas_cumprod[t.item()]
+ alpha_t_prev = pipe.scheduler.alphas_cumprod[prev_t]
+ predicted_x0 = (latents - (1-alpha_t).sqrt()*noise_pred) / alpha_t.sqrt()
+ direction_pointing_to_xt = (1-alpha_t_prev).sqrt()*noise_pred
+ latents = alpha_t_prev.sqrt()*predicted_x0 + direction_pointing_to_xt
+
+ # Post-processing
+ images = pipe.decode_latents(latents)
+ images = pipe.numpy_to_pil(images)
+
+ return images
+```
+
+
+```python
+# Test our sampling function by generating an image
+sample('Watercolor painting of a beach sunset', negative_prompt=negative_prompt, num_inference_steps=50)[0].resize((256, 256))
+```
+
+看看你是否能把这些代码和论文中的公式对应起来。注意$\sigma$=0是因为我们只注意 无-额外-噪声 的场景,所以我们略去了公式中的那部分。
+
+## 反转
+
+反转的目标就是'颠倒'取样的过程。我们想最终得到一个带噪的隐式(latent),如果把它作为我们正常取样过程的起始点,结果将生成一副原图像。
+
+这里我们先加载一个原始图像,当然你也可以生成一副图像来代替。
+
+
+```python
+# https://www.pexels.com/photo/a-beagle-on-green-grass-field-8306128/
+input_image = load_image('https://images.pexels.com/photos/8306128/pexels-photo-8306128.jpeg', size=(512, 512))
+input_image
+```
+
+我们可以用包含随意分类指引(classifier-free-guidance)的prompt来做反转操作,输入一个图片的描述:
+
+
+```python
+input_image_prompt = "Photograph of a puppy on the grass"
+```
+
+接下来我们来把这个PIL图像变成一些列隐式,它们会被用来当作反转的起点:
+
+
+```python
+# encode with VAE
+with torch.no_grad(): latent = pipe.vae.encode(tfms.functional.to_tensor(input_image).unsqueeze(0).to(device)*2-1)
+l = 0.18215 * latent.latent_dist.sample()
+```
+
+好了,到有趣的部分了。这个函数看起来和上面的取样函数很像,但我们在timesteps上是在向相反的方向移动,从t=0开始,向越来越多的噪声前进。代替更新隐式时噪声会越来越少,我们估计所预测出的噪声,用它来撤回一步更新操作,把它们从t移动到t+1。
+
+
+```python
+## Inversion
+@torch.no_grad()
+def invert(start_latents, prompt, guidance_scale=3.5, num_inference_steps=80,
+ num_images_per_prompt=1, do_classifier_free_guidance=True,
+ negative_prompt='', device=device):
+
+ # Encode prompt
+ text_embeddings = pipe._encode_prompt(
+ prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
+ )
+
+ # latents are now the specified start latents
+ latents = start_latents.clone()
+
+ # We'll keep a list of the inverted latents as the process goes on
+ intermediate_latents = []
+
+ # Set num inference steps
+ pipe.scheduler.set_timesteps(num_inference_steps, device=device)
+
+ # Reversed timesteps <<<<<<<<<<<<<<<<<<<<
+ timesteps = reversed(pipe.scheduler.timesteps)
+
+ for i in tqdm(range(1, num_inference_steps), total=num_inference_steps-1):
+
+ # We'll skip the final iteration
+ if i >= num_inference_steps - 1: continue
+
+ t = timesteps[i]
+
+ # expand the latents if we are doing classifier free guidance
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
+ latent_model_input = pipe.scheduler.scale_model_input(latent_model_input, t)
+
+ # predict the noise residual
+ noise_pred = pipe.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
+
+ # perform guidance
+ if do_classifier_free_guidance:
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
+
+ current_t = max(0, t.item() - (1000//num_inference_steps))#t
+ next_t = t # min(999, t.item() + (1000//num_inference_steps)) # t+1
+ alpha_t = pipe.scheduler.alphas_cumprod[current_t]
+ alpha_t_next = pipe.scheduler.alphas_cumprod[next_t]
+
+ # Inverted update step (re-arranging the update step to get x(t) (new latents) as a function of x(t-1) (current latents)
+ latents = (latents - (1-alpha_t).sqrt()*noise_pred)*(alpha_t_next.sqrt()/alpha_t.sqrt()) + (1-alpha_t_next).sqrt()*noise_pred
+
+
+ # Store
+ intermediate_latents.append(latents)
+
+ return torch.cat(intermediate_latents)
+
+```
+
+把它在小狗图片的隐式表达上运行,我们可以在反转的中间过程得到一系列的隐式:
+
+
+```python
+inverted_latents = invert(l, input_image_prompt,num_inference_steps=50)
+inverted_latents.shape
+```
+
+
+ 0%| | 0/49 [00:00, ?it/s]
+
+
+
+
+
+ torch.Size([48, 4, 64, 64])
+
+
+
+我们可以来看一下最终的隐式 - 希望这可以作为我们尝试新的取样过程的起点噪声:
+
+
+```python
+# Decode the final inverted latents:
+with torch.no_grad():
+ im = pipe.decode_latents(inverted_latents[-1].unsqueeze(0))
+pipe.numpy_to_pil(im)[0]
+```
+
+
+
+
+
+
+
+
+
+
+你可以把这个反转隐式通过正常的 __call__ 方法来传递给pipeline。
+
+
+```python
+pipe(input_image_prompt, latents=inverted_latents[-1][None], num_inference_steps=50, guidance_scale=3.5).images[0]
+
+```
+
+
+ 0%| | 0/50 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+但这里我们遇见了第一个问题:这 **并不是我们一开始的那张图片**!这是因为DDIM的反转依赖一个重要的假设,在t时刻预测的噪声与t+1时刻会是相同的 - 这在我们只反转50或100步时是不陈立的。我们可以寄希望于更多的timesteps开得到一个更准确的反转,但我们也可以'作弊'一下,就是说直接从做对应反转过程中的第20/50步的隐式开始:
+
+
+```python
+# The reason we want to be able to specify start step
+start_step=20
+sample(input_image_prompt, start_latents=inverted_latents[-(start_step+1)][None],
+ start_step=start_step, num_inference_steps=50)[0]
+
+```
+
+
+ 0%| | 0/30 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+距离我们的输入图像已经很接近了!我们为什么要这么做?嗯,这是因为如果我们现在若要用一个新的prompt来生成图像,我们会得到一个匹配于源图像,除了,与新prompt相关的内容。例如,把'小狗'替换为'猫',我们能看到一只猫在几乎一样草地背景上:
+
+
+```python
+# Sampling with a new prompt
+start_step=10
+new_prompt = input_image_prompt.replace('puppy', 'cat')
+sample(new_prompt, start_latents=inverted_latents[-(start_step+1)][None],
+ start_step=start_step, num_inference_steps=50)[0]
+```
+
+
+ 0%| | 0/40 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+### 为什么不直接用 img2img?
+
+为什么要做反转,不是多此一举吗?为什么不直接对输入图片加入噪声,然后用新的promt直接来去噪呢?我们可以这么做,但这会带来一个到处都被改变得夸张得多的照片(如果我们加入了很多噪声),或哪也没怎么变的图像(如果加了太少的噪声)。来自己试试:
+
+
+```python
+start_step = 10
+num_inference_steps=50
+pipe.scheduler.set_timesteps(num_inference_steps)
+noisy_l = pipe.scheduler.add_noise(l, torch.randn_like(l), pipe.scheduler.timesteps[start_step])
+sample(new_prompt, start_latents=noisy_l, start_step=start_step, num_inference_steps=num_inference_steps)[0]
+```
+
+
+ 0%| | 0/40 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+注意背景和草坪有着非常大的变化。
+
+# 把它们都组装起来
+
+来把我们目前所写的代码都组装在一个简单的函数里,输入一张图像和两个prompts,就会得到一个通过反转得到的修改后的图片:
+
+
+```python
+def edit(input_image, input_image_prompt, edit_prompt, num_steps=100, start_step=30, guidance_scale=3.5):
+ with torch.no_grad(): latent = pipe.vae.encode(tfms.functional.to_tensor(input_image).unsqueeze(0).to(device)*2-1)
+ l = 0.18215 * latent.latent_dist.sample()
+ inverted_latents = invert(l, input_image_prompt,num_inference_steps=num_steps)
+ final_im = sample(edit_prompt, start_latents=inverted_latents[-(start_step+1)][None],
+ start_step=start_step, num_inference_steps=num_steps, guidance_scale=guidance_scale)[0]
+ return final_im
+```
+
+And in action:
+实际操作起来:
+
+
+```python
+edit(input_image, 'A puppy on the grass', 'an old grey dog on the grass', num_steps=50, start_step=10)
+```
+
+
+ 0%| | 0/49 [00:00, ?it/s]
+
+
+
+ 0%| | 0/40 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+
+```python
+edit(input_image, 'A puppy on the grass', 'A blue dog on the lawn', num_steps=50, start_step=12, guidance_scale=6)
+```
+
+
+ 0%| | 0/49 [00:00, ?it/s]
+
+
+
+ 0%| | 0/38 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+
+```python
+# Exercise: Try this on some more images! Explore the different parameters
+```
+
+## 更多迭代 = 更好的表现
+
+如果你因为反转结果不准确而烦恼,你可以试试多迭代几次(代价就是更长的运行时间)。为了测试一下反转过程,你可以使用这里的edit函数并输入相同的prompt:
+
+
+```python
+# Inversion test with far more steps:
+edit(input_image, 'A puppy on the grass', 'A puppy on the grass', num_steps=350, start_step=1)
+```
+
+
+ 0%| | 0/349 [00:00, ?it/s]
+
+
+
+ 0%| | 0/349 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+好多了!来试试用它编辑图片:
+
+
+```python
+edit(input_image, 'A photograph of a puppy', 'A photograph of a grey cat', num_steps=150, start_step=30, guidance_scale=5.5)
+```
+
+
+ 0%| | 0/149 [00:00, ?it/s]
+
+
+
+ 0%| | 0/120 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+
+```python
+# source: https://www.pexels.com/photo/girl-taking-photo-1493111/
+face = load_image('https://images.pexels.com/photos/1493111/pexels-photo-1493111.jpeg', size=(512, 512))
+face
+```
+
+
+
+
+
+
+
+
+
+
+
+```python
+edit(face, 'A photograph of a face', 'A photograph of a face with sunglasses', num_steps=250, start_step=30, guidance_scale=3.5)
+```
+
+
+ 0%| | 0/249 [00:00, ?it/s]
+
+
+
+ 0%| | 0/220 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+
+```python
+edit(face, 'A photograph of a face', 'Acrylic palette knife painting of a face, colorful', num_steps=250, start_step=65, guidance_scale=5.5)
+```
+
+
+ 0%| | 0/249 [00:00, ?it/s]
+
+
+
+ 0%| | 0/185 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+# 接下来会是?
+
+有了此篇笔记的帮助,我建议你再研究下['Null-text Inversion'](https://null-text-inversion.github.io/),它是基于DDIM来优化空文本(无条件文字prompt)的反转过程,有着更准确的反转与更好的编辑效果。
diff --git a/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_32_0.png b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_32_0.png
new file mode 100644
index 0000000000000000000000000000000000000000..d94471ae7864abaa28aac3967a6799dbd728530c
--- /dev/null
+++ b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_32_0.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:86d76af2b4ab1199dbb6df1e2cbb97b4906d0112b51abb7949ebbda480faa31f
+size 593387
diff --git a/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_34_1.png b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_34_1.png
new file mode 100644
index 0000000000000000000000000000000000000000..c133b849307ea5bb40e818ecf9c2fda39d0f8e08
--- /dev/null
+++ b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_34_1.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e66168a0e8a2a21c8272323e239e4bb5cf933b7b2d2b09837b1edd94a97b88da
+size 411736
diff --git a/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_36_1.png b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_36_1.png
new file mode 100644
index 0000000000000000000000000000000000000000..47b8f29ee87ca023bad1dc1e9bab44f2370f5668
--- /dev/null
+++ b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_36_1.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:07d51d7ce45b25f0be9d37228dff87ab107f7db2f0be2f867b4a5079648a9abc
+size 423986
diff --git a/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_38_1.png b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_38_1.png
new file mode 100644
index 0000000000000000000000000000000000000000..ccef4cbe8e335e3e6422e5f41f9ae69867380d52
--- /dev/null
+++ b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_38_1.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b4586a074bb15e50ec5d6261d9a8e4eab02fa94fca5bae085ddc3274d37ba666
+size 418608
diff --git a/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_40_1.png b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_40_1.png
new file mode 100644
index 0000000000000000000000000000000000000000..b3f4571c071ae896d58d87ed721f191bc327525c
--- /dev/null
+++ b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_40_1.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:78267d83bf9d3d5a7153d503517c2b807923d7d72db397b8af3109f2eb78a54f
+size 387302
diff --git a/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_45_2.png b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_45_2.png
new file mode 100644
index 0000000000000000000000000000000000000000..2606f03300c5b151c0d09f6a4244c16e49ffe126
--- /dev/null
+++ b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_45_2.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:981edbde071a56deaa977160dc30911a13dc3368867c62ab1656c0223cbd0721
+size 425076
diff --git a/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_46_2.png b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_46_2.png
new file mode 100644
index 0000000000000000000000000000000000000000..4855bb05e72f91640cd171e9bab313193f07859b
--- /dev/null
+++ b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_46_2.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:df036d0124b15296a2554b70fc48b39f45eec57b85cfdd5dfc9ec22580929551
+size 430325
diff --git a/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_49_2.png b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_49_2.png
new file mode 100644
index 0000000000000000000000000000000000000000..ad3df74dde36c0a7d80d4db82effea085260738a
--- /dev/null
+++ b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_49_2.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d9f571854f2a418a5864ceb5c3979531dc8cd80eda98c30890124fba6ac65959
+size 427293
diff --git a/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_51_2.png b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_51_2.png
new file mode 100644
index 0000000000000000000000000000000000000000..8edcf7d7c685b5506c6fbfb44783f8855cc226e6
--- /dev/null
+++ b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_51_2.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:26e5e5841478cec02a0fa2e5d11b399604794e5f57ccfa4c02428d34cc26dd9b
+size 436567
diff --git a/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_52_0.png b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_52_0.png
new file mode 100644
index 0000000000000000000000000000000000000000..5663b1eb4d9806c3c9ef0b76ea343e7d795ace13
--- /dev/null
+++ b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_52_0.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0ad6233c1dcba4f19ad4361e202b99a49261db0b25a7bdb03061f427703173e1
+size 324984
diff --git a/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_53_2.png b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_53_2.png
new file mode 100644
index 0000000000000000000000000000000000000000..2a9674696d2f19636b5cb5c29629728740793306
--- /dev/null
+++ b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_53_2.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2aa6b0897da211eabd95437d99a3386f27c092e5eac3f708ea66460b73477fd4
+size 317598
diff --git a/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_54_2.png b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_54_2.png
new file mode 100644
index 0000000000000000000000000000000000000000..aac269ef7396f3709e0b21577e05afbcb3e40001
--- /dev/null
+++ b/markdown/unit4/01_ddim_inversion_CN_files/01_ddim_inversion_CN_54_2.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f479cf2004b0119405d91dedf791bea6f2f9031857e185af9eccae922c3122f7
+size 337488
diff --git a/markdown/unit4/02_diffusion_for_audio_CN.md b/markdown/unit4/02_diffusion_for_audio_CN.md
new file mode 100644
index 0000000000000000000000000000000000000000..66e91b48132af8265dfce272cfd73ec1d35f4d8f
--- /dev/null
+++ b/markdown/unit4/02_diffusion_for_audio_CN.md
@@ -0,0 +1,632 @@
+# 音频扩散模型
+
+在此篇笔记,我们将简短地来看看使用扩散模型生成音频的过程。
+
+## 你将会学习到:
+- 音频在电脑中被如何展示
+- 源音频数据与频谱间的转换方法
+- 如何准备一个由特定的整理函数(collate function),能够把音频片段转换到频谱的数据生成器
+- 微调一个指定分类曲风的音频扩散模型
+- 把自己的pipeline上传到HFhub
+
+警告:这完全是出于教学目的 - 不能保证我们的模型一定很好听😉
+
+我们开始吧!
+
+## 设置与导入
+
+
+```python
+# !pip install -q datasets diffusers torchaudio accelerate
+```
+
+
+```python
+import torch, random
+import numpy as np
+import torch.nn.functional as F
+from tqdm.auto import tqdm
+from IPython.display import Audio
+from matplotlib import pyplot as plt
+from diffusers import DiffusionPipeline
+from torchaudio import transforms as AT
+from torchvision import transforms as IT
+
+```
+
+## 从预训练的音频Pipline开始
+
+我们通过参考[Audio Diffusion docs](https://huggingface.co/docs/diffusers/api/pipelines/audio_diffusion)来加载一个预训练的音频扩散模型pipeline:
+
+
+```python
+# Load a pre-trained audio diffusion pipeline
+device = "cuda" if torch.cuda.is_available() else "cpu"
+pipe = DiffusionPipeline.from_pretrained("teticio/audio-diffusion-instrumental-hiphop-256").to(device)
+```
+
+
+ Fetching 5 files: 0%| | 0/5 [00:00, ?it/s]
+
+
+如同我们在之前单元使用的pipelines一样,我们可以这样调用pipeline来创造几个样例:
+
+
+```python
+# Sample from the pipeline and display the outputs:
+output = pipe()
+display(output.images[0])
+display(Audio(output.audios[0], rate=pipe.mel.get_sample_rate()))
+```
+
+
+ 0%| | 0/1000 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+这里,`rate`参数明确了音频的 _采样率_ ;过会儿我们会再深入了解它。同时你也会注意到pipeline也返回了几样其他的东西。这发生了什么?我们来仔细看看这两个输出。
+
+第一项是一个数据数组,代表生成的音频:
+
+
+```python
+# The audio array:
+output.audios[0].shape
+```
+
+
+
+
+ (1, 130560)
+
+
+
+第二项看起来像是灰度图:
+
+
+```python
+# The output image (spectrogram):
+output.images[0].size
+```
+
+
+
+
+ (256, 256)
+
+
+
+这给了我们一个提示,关于这个pipeline是如何工作的。音频不是直接被扩散模型生成 - 而是,这个pipeline有着与在第一单元看到的无条件图像生成pipelines类似的2D Unet结构 [Unit 1](https://github.com/huggingface/diffusion-models-class/tree/main/unit1) 用它来生成频谱,之后再在后处理中把它变化为最终的音频。
+
+此pipe中有额外的组件来处理这个变化,我们可以通过`pipe.mel`来进行:
+
+
+```python
+pipe.mel
+```
+
+
+
+
+ Mel {
+ "_class_name": "Mel",
+ "_diffusers_version": "0.12.0.dev0",
+ "hop_length": 512,
+ "n_fft": 2048,
+ "n_iter": 32,
+ "sample_rate": 22050,
+ "top_db": 80,
+ "x_res": 256,
+ "y_res": 256
+ }
+
+
+
+## 音频到频谱的转换
+
+音频的'波形'从时间上表现出了源音频 - 比如,这可能是接收自麦克风的电信号。从这种'时域'的表达方式上做处理会有些棘手,所以有种更普遍的做法把它转换成其他形式,通常把这叫做频谱。频谱直接展示出在不同频率(y轴)与时间(x轴)上的剧烈程度。
+
+
+```python
+# Calculate and show a spectrogram for our generated audio sample using torchaudio
+spec_transform = AT.Spectrogram(power=2)
+spectrogram = spec_transform(torch.tensor(output.audios[0]))
+print(spectrogram.min(), spectrogram.max())
+log_spectrogram = spectrogram.log()
+plt.imshow(log_spectrogram[0], cmap='gray');
+```
+
+ tensor(0.) tensor(6.0842)
+
+
+
+
+
+
+
+
+我们刚刚做好的这个频谱取值范围在0.0000000000001到1之间,其中大部分内容都接近取值下限。这对于可视化与建模并不理想 - 实际上我们需要对这些值取log来得到一个可以看到更多细节的灰度图。同样也因此,我们特别使用一种专门的梅尔频谱(Mel spectrogram),这是一种通过对不同频率成分做一些变化,专门设计的一种符合人耳感知特性而利于提取重要信息的方式。
+
+
+_一些来自 [torchaudio docs](https://pytorch.org/audio/stable/transforms.html)的音频转换方法_
+
+幸运的是,我们并不需要太过于担心这些变换方法 - pipeline中的`mel`功能会为我们处理这些细节。这样操作,我们就能把频谱图像转换成音频:
+
+
+```python
+a = pipe.mel.image_to_audio(output.images[0])
+a.shape
+```
+
+
+
+
+ (130560,)
+
+
+
+我们可以先读出源音频数据然后调用 `audio_slice_to_image()`函数来把音频数组数据转化为频谱图片。更长的片段会被自动切片为能够正常输出 256x256 频谱图片的长度。
+
+
+```python
+pipe.mel.load_audio(raw_audio=a)
+im = pipe.mel.audio_slice_to_image(0)
+im
+```
+
+
+
+
+
+
+
+
+
+
+音频被表现为一串很长的数字数组。要把它播放出来的话,我们还需要一个关键信息:采样率。我们要用到多少个采样点(单个的数值),才能够播放出单位秒的音频呢?
+
+我们可以在pipeline中这样来看使用的采样率:
+
+
+```python
+sample_rate_pipeline = pipe.mel.get_sample_rate()
+sample_rate_pipeline
+```
+
+
+
+
+ 22050
+
+
+
+如果我们故意把采样率设置错误,可以得到一个可能被加速或慢放的音频:
+
+
+```python
+display(Audio(output.audios[0], rate=44100)) # 2x speed
+```
+
+
+
+
+
+
+
+## 微调pipeline
+
+现在我们已经大致理解了这个pipeline是怎么工作的,现在来在一些新音频数据上对它进行微调!
+
+这个数据集是不同类别的音频片段集合,我们可以从hub上这样加载它:
+
+
+```python
+from datasets import load_dataset
+dataset = load_dataset('lewtun/music_genres', split='train')
+dataset
+```
+
+ Using custom data configuration lewtun--music_genres-2cfa9201f94788d8
+ Found cached dataset parquet (/home/ubuntu/.cache/huggingface/datasets/lewtun___parquet/lewtun--music_genres-2cfa9201f94788d8/0.0.0/2a3b91fbd88a2c90d1dbbb32b460cf621d31bd5b05b934492fdef7d8d6f236ec)
+
+
+
+
+
+ Dataset({
+ features: ['audio', 'song_id', 'genre_id', 'genre'],
+ num_rows: 19909
+ })
+
+
+
+你可以使用下面的代码来看看在数据集中各类别样本的占比:
+
+
+```python
+for g in list(set(dataset['genre'])):
+ print(g, sum(x==g for x in dataset['genre']))
+```
+
+ Pop 945
+ Blues 58
+ Punk 2582
+ Old-Time / Historic 408
+ Experimental 1800
+ Folk 1214
+ Electronic 3071
+ Spoken 94
+ Classical 495
+ Country 142
+ Instrumental 1044
+ Chiptune / Glitch 1181
+ International 814
+ Ambient Electronic 796
+ Jazz 306
+ Soul-RnB 94
+ Hip-Hop 1757
+ Easy Listening 13
+ Rock 3095
+
+
+这个数据集把音频存储为数组:
+
+
+```python
+audio_array = dataset[0]['audio']['array']
+sample_rate_dataset = dataset[0]['audio']['sampling_rate']
+print('Audio array shape:', audio_array.shape)
+print('Sample rate:', sample_rate_dataset)
+display(Audio(audio_array, rate=sample_rate_dataset))
+```
+
+ Audio array shape: (1323119,)
+ Sample rate: 44100
+
+
+
+
+
+
+
+
+注意这条音频的采样率会更高 - 如果我们想用手头的这个pipeline,需要对它'重采样'来匹配。这个片段也比pipeline所预设的长度更长。幸运的是,当我们使用`pipe.mel`在加载音频时,会自动把它切片成更短的片区。
+
+
+```python
+a = dataset[0]['audio']['array'] # Get the audio array
+pipe.mel.load_audio(raw_audio=a) # Load it with pipe.mel
+pipe.mel.audio_slice_to_image(0) # View the first 'slice' as a spectrogram
+```
+
+
+
+
+
+
+
+
+
+
+我们要记得去调整采样率,因为此数据集的数据在每秒中有着多两倍的数据点。
+
+
+```python
+sample_rate_dataset = dataset[0]['audio']['sampling_rate']
+sample_rate_dataset
+```
+
+
+
+
+ 44100
+
+
+
+这里我们用torchaudio's transforms(导入为AT)来做音频的重采样,pipe中的`mel`把音频转换为图像,torchvision's transforms(导入为IT)来把图片转换为tensors。这个函数可以把音频片段转换为频谱tensor供训练使用:
+
+
+```python
+resampler = AT.Resample(sample_rate_dataset, sample_rate_pipeline, dtype=torch.float32)
+to_t = IT.ToTensor()
+
+def to_image(audio_array):
+ audio_tensor = torch.tensor(audio_array).to(torch.float32)
+ audio_tensor = resampler(audio_tensor)
+ pipe.mel.load_audio(raw_audio=np.array(audio_tensor))
+ num_slices = pipe.mel.get_number_of_slices()
+ slice_idx = random.randint(0, num_slices-1) # Pic a random slice each time (excluding the last short slice)
+ im = pipe.mel.audio_slice_to_image(slice_idx)
+ return im
+```
+
+来使用我们的`to_image()`函数来组成我们特定的整理函数(collate function)来把数据集转换到dataloader中来训练模型。整理函数定义了如何把一批来自数据集的样例变换为最终训练用数据。在这个例子中我们把每个音频转换为频谱图像再把他们的tensors堆叠起来:
+
+
+```python
+def collate_fn(examples):
+ # to image -> to tensor -> rescale to (-1, 1) -> stack into batch
+ audio_ims = [to_t(to_image(x['audio']['array']))*2-1 for x in examples]
+ return torch.stack(audio_ims)
+
+# Create a dataset with only the 'Chiptune / Glitch' genre of songs
+batch_size=4 # 4 on colab, 12 on A100
+chosen_genre = 'Electronic' # <<< Try training on different genres <<<
+indexes = [i for i, g in enumerate(dataset['genre']) if g == chosen_genre]
+filtered_dataset = dataset.select(indexes)
+dl = torch.utils.data.DataLoader(filtered_dataset.shuffle(), batch_size=batch_size, collate_fn=collate_fn, shuffle=True)
+batch = next(iter(dl))
+print(batch.shape)
+```
+
+ torch.Size([4, 1, 256, 256])
+
+
+**留心: 你可能要用一个更小的batchsize(比如4)除非你有足够的显存可用**
+
+## 训练循环
+
+这是一个在dataloader中读取数据的简洁训练循环,用几个周期来微调pipeline的UNet网络。你可以跳过此块,直接使用下一块代码来加载pipeline。
+
+
+```python
+epochs = 3
+lr = 1e-4
+
+pipe.unet.train()
+pipe.scheduler.set_timesteps(1000)
+optimizer = torch.optim.AdamW(pipe.unet.parameters(), lr=lr)
+
+for epoch in range(epochs):
+ for step, batch in tqdm(enumerate(dl), total=len(dl)):
+
+ # Prepare the input images
+ clean_images = batch.to(device)
+ bs = clean_images.shape[0]
+
+ # Sample a random timestep for each image
+ timesteps = torch.randint(
+ 0, pipe.scheduler.num_train_timesteps, (bs,), device=clean_images.device
+ ).long()
+
+ # Add noise to the clean images according to the noise magnitude at each timestep
+ noise = torch.randn(clean_images.shape).to(clean_images.device)
+ noisy_images = pipe.scheduler.add_noise(clean_images, noise, timesteps)
+
+ # Get the model prediction
+ noise_pred = pipe.unet(noisy_images, timesteps, return_dict=False)[0]
+
+ # Calculate the loss
+ loss = F.mse_loss(noise_pred, noise)
+ loss.backward(loss)
+
+ # Update the model parameters with the optimizer
+ optimizer.step()
+ optimizer.zero_grad()
+```
+
+
+```python
+# OR: Load the version I trained earlier:
+pipe = DiffusionPipeline.from_pretrained("johnowhitaker/Electronic_test").to(device)
+```
+
+
+ Downloading: 0%| | 0.00/282 [00:00, ?B/s]
+
+
+
+ Fetching 5 files: 0%| | 0/5 [00:00, ?it/s]
+
+
+
+ Downloading: 0%| | 0.00/192 [00:00, ?B/s]
+
+
+
+ Downloading: 0%| | 0.00/294 [00:00, ?B/s]
+
+
+
+ Downloading: 0%| | 0.00/1.03k [00:00, ?B/s]
+
+
+
+ Downloading: 0%| | 0.00/455M [00:00, ?B/s]
+
+
+
+```python
+output = pipe()
+display(output.images[0])
+display(Audio(output.audios[0], rate=22050))
+```
+
+
+ 0%| | 0/1000 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+```python
+# Make a longer sample by passing in a starting noise tensor with a different shape
+noise = torch.randn(1, 1, pipe.unet.sample_size[0],pipe.unet.sample_size[1]*4).to(device)
+output = pipe(noise=noise)
+display(output.images[0])
+display(Audio(output.audios[0], rate=22050))
+```
+
+
+ 0%| | 0/1000 [00:00, ?it/s]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+这个输出听起来不是最美妙的,但这是一个开始 :)探索一下调整学习率和迭代周期,并在Discord上分享你的最佳结果,我们就可以来一起进步了!
+
+一些需要考虑的事情
+- 我们使用的是256像素点的方形频谱图片,这会限制住我们的batchsize。你能够从128x128的频谱中恢复出质量足够好的音频吗?
+- 为了替代随机图像增强,我们每次挑选不同的音频片段,但这种做法在训练迭代的后期是否可以用其他增强方式再优化一下?
+- 我们有什么其他办法可以用它来生成更长的音频?也许你可以先生成开头的5s音频然后再用类似图像修复的思路接着卡开头片段来继续生成后续内容...
+- 扩散模型生成的内容与图像到图像的生成有什么相同之处?
+
+## Push到Hub
+
+当你对你的模型足够满意了,你就可以把它保存下来并上传到hub上给他人来共享:
+
+
+```python
+from huggingface_hub import get_full_repo_name, HfApi, create_repo, ModelCard
+```
+
+
+```python
+# Pick a name for the model
+model_name = "audio-diffusion-electronic"
+hub_model_id = get_full_repo_name(model_name)
+```
+
+
+```python
+# Save the pipeline locally
+pipe.save_pretrained(model_name)
+```
+
+
+```python
+# Inspect the folder contents
+!ls {model_name}
+```
+
+ mel model_index.json scheduler unet
+
+
+
+```python
+# Create a repository
+create_repo(hub_model_id)
+```
+
+
+
+
+ 'https://huggingface.co/johnowhitaker/Electronic_test'
+
+
+
+
+```python
+# Upload the files
+api = HfApi()
+api.upload_folder(
+ folder_path=f"{model_name}/scheduler", path_in_repo="scheduler", repo_id=hub_model_id
+)
+api.upload_folder(
+ folder_path=f"{model_name}/mel", path_in_repo="mel", repo_id=hub_model_id
+)
+api.upload_folder(folder_path=f"{model_name}/unet", path_in_repo="unet", repo_id=hub_model_id)
+api.upload_file(
+ path_or_fileobj=f"{model_name}/model_index.json",
+ path_in_repo="model_index.json",
+ repo_id=hub_model_id,
+)
+```
+
+
+
+
+ 'https://huggingface.co/johnowhitaker/Electronic_test/blob/main/model_index.json'
+
+
+
+
+```python
+# Push a model card
+content = f"""
+---
+license: mit
+tags:
+- pytorch
+- diffusers
+- unconditional-audio-generation
+- diffusion-models-class
+---
+
+# Model Card for Unit 4 of the [Diffusion Models Class 🧨](https://github.com/huggingface/diffusion-models-class)
+
+This model is a diffusion model for unconditional audio generation of music in the genre {chosen_genre}
+
+## Usage
+
+```python
+from IPython.display import Audio
+from diffusers import DiffusionPipeline
+
+pipe = DiffusionPipeline.from_pretrained("{hub_model_id}")
+output = pipe()
+display(output.images[0])
+display(Audio(output.audios[0], rate=pipe.mel.get_sample_rate()))
+```
+"""
+
+card = ModelCard(content)
+card.push_to_hub(hub_model_id)
+```
+
+
+
+
+ 'https://huggingface.co/johnowhitaker/Electronic_test/blob/main/README.md'
+
+
+
+## 总结
+
+希望这片笔记让你浅尝到音频生成的潜力。请再留意下此单元在介绍中的一些参考链接,去看一些更酷炫的方法和它们所创造的惊艳内容!
diff --git a/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_17_1.png b/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_17_1.png
new file mode 100644
index 0000000000000000000000000000000000000000..b1db6df1bbe1e83d6b0518ed5253e8857650e00b
--- /dev/null
+++ b/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_17_1.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d6079cab3bab81154a55724d67efbfaca32338a9482b02b9481017846180345b
+size 40006
diff --git a/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_23_0.png b/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_23_0.png
new file mode 100644
index 0000000000000000000000000000000000000000..6729d20f7566245945f00dc079caf5101f153aae
--- /dev/null
+++ b/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_23_0.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:147e7ceecc2953ea9ed21a97b0e93286bbaa3a2882cc00a41d1d43d85ceeb2cf
+size 43626
diff --git a/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_37_0.png b/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_37_0.png
new file mode 100644
index 0000000000000000000000000000000000000000..b217590cf1429dea04a16445ebe71b9aa9c6389c
--- /dev/null
+++ b/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_37_0.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9b64ae99aa9ba1edf437985809c1bbb54bf0c6ddda3146d1783c8cabe666f874
+size 40345
diff --git a/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_48_1.png b/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_48_1.png
new file mode 100644
index 0000000000000000000000000000000000000000..76e745ed5e4493c3f4a89fbf316c39f63d0f84e1
--- /dev/null
+++ b/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_48_1.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:bb8425622f549cf0a00240a0a91aba8bb9da6263243ee9f57012a0c4f34985e8
+size 42749
diff --git a/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_49_1.png b/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_49_1.png
new file mode 100644
index 0000000000000000000000000000000000000000..52508aeaae08184c692db134a867f9bcf257dd6b
--- /dev/null
+++ b/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_49_1.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c5c99f6100f71ed24a99e766078294c1ced31580c86a5f8b17403d07fba4a47a
+size 163880
diff --git a/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_8_1.png b/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_8_1.png
new file mode 100644
index 0000000000000000000000000000000000000000..18033ea9795137357ea1a25a64f398c95d8f73e9
--- /dev/null
+++ b/markdown/unit4/02_diffusion_for_audio_CN_files/02_diffusion_for_audio_CN_8_1.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2babaa4b3f5d633ada48d83890881e1092044d70f51fad82208977733ad475a2
+size 43502
diff --git a/markdown/unit4/README_CN.md b/markdown/unit4/README_CN.md
new file mode 100644
index 0000000000000000000000000000000000000000..2c1fe9222207a66c95cfb701af737f8158d21fc6
--- /dev/null
+++ b/markdown/unit4/README_CN.md
@@ -0,0 +1,167 @@
+# Unit 4: 深入研究扩散模型
+
+欢迎来到 Hugging Face 扩散模型课程的第四单元!在这个单元中,我们将探讨最新研究中出现的扩散模型的许多改进和扩展。它将比以往的单元代码更少,旨在为您提供进一步研究的起点。
+
+## 开始本单元 :rocket:
+
+以下是本单元的学习步骤:
+
+- 请确保你已经 [注册了该课程](https://huggingface.us17.list-manage.com/subscribe?u=7f57e683fa28b51bfc493d048&id=ef963b4162) 以便在课程中添加其他单元时通知您
+- 阅读下面的材料,以了解本单元中涉及的不同主题的梗概
+- 通过链接的视频和资源深入了解任何您感兴趣的主题
+- 浏览演示笔记本,然后阅读“下一步”部分以获取一些项目建议
+
+:loudspeaker: 别忘了加入我们的 [Discord频道](https://huggingface.co/join/discord), 在这里,您可以讨论课程内容,并在`#diffusion-models-class` 频道中分享您的作品!
+
+## Table of Contents
+
+- [Unit 4: 深入研究扩散模型](#unit-4-going-further-with-diffusion-models)
+ - [开始本单元 :rocket:](#start-this-unit-rocket)
+ - [课程目录](#table-of-contents)
+ - [通过蒸馏进行快速采样](#faster-sampling-via-distillation)
+ - [训练改进](#training-improvements)
+ - [对生成与编辑的更多控制](#more-control-for-generation-and-editing)
+ - [视频](#video)
+ - [音频](#audio)
+ - [新的体系结构和方法 - 走向“迭代优化”](#new-architectures-and-approaches---towards-iterative-refinement)
+ - [动手笔记本](#hands-on-notebooks)
+ - [下一步?](#where-next)
+
+
+## 通过蒸馏进行快速采样
+
+渐进蒸馏是一种采用现有扩散模型并使用它来训练需要更少推理步骤的模型的新版本的技术。“学生”模型初始化自“教师”模型的权重。在训练过程中,教师模型执行两个采样步骤,学生模型尝试在一个步骤中匹配结果预测。这个过程可以重复多次,上一次迭代的学生模型成为下一阶段的教师模型。结果是,这个模型可以用比原来的教师模型少得多的步骤(通常是4或8步)生成较好的样本。核心机制如下图所示,图片来源于[这篇论文](http://arxiv.org/abs/2202.00512):
+
+
+
+_渐进蒸馏图示 (来源于[该篇论文](http://arxiv.org/abs/2202.00512))_
+
+使用现有模型“教授”新模型的想法可以扩展到创建指导模型,其中教师模型使用无分类器指导技术,学生模型必须学会在指定目标指导尺度的额外输入的基础上,在单个步骤中产生等价的输出。[这个视频](https://www.youtube.com/watch?v=ZXuK6IRJlnk) 对该方法做了一个概述。
+
+NB: Stable Diffusion的蒸馏版将很快发布。
+
+主要文献:
+- [Progressive Distillation For Fast Sampling Of Diffusion Models](http://arxiv.org/abs/2202.00512)
+- [On Distillation Of Guided Diffusion Models](http://arxiv.org/abs/2210.03142)
+
+## 训练改进
+
+研究者们现在已经开发了一些额外的技巧来改进扩散模型的训练过程。在本节中,我们试图从最近的论文中寻找一些相关的核心理念。更多关于改进方法的研究论文也是不断涌现,因此,如果你看到一篇你觉得应该添加在这里的论文,请联系我们!
+
+
+_图像2来自于 [ERNIE-ViLG 2.0 paper](http://arxiv.org/abs/2210.15257)_
+
+关键的训练改进:
+- 调整噪声计划、损失加权和采样轨迹,以获得更有效的训练。这里是一篇探讨这些设计选择的优秀论文 [Elucidating the Design Space of Diffusion-Based Generative Models](http://arxiv.org/abs/2206.00364) by Karras et al.
+- 在不同的长宽比上进行训练。这一方法被描述在[课程启动活动提到的这个视频中](https://www.youtube.com/watch?v=g6tIUrMvOec)
+- 级联扩散模型,首先训练一个低分辨率模型,然后训练一个或多个超分辨率模型。这一方法被广泛运用于DALLE-2,Imagen等高分辨率图像生成模型中。
+- Better conditioning, incorporating rich text embeddings ([Imagen](https://arxiv.org/abs/2205.11487) uses a large language model called T5) or multiple types of conditioning ([eDiffi](http://arxiv.org/abs/2211.01324))
+- 更好的调节、结合富文本嵌入 ([Imagen](https://arxiv.org/abs/2205.11487) 使用了一个名为T-5的大语言模型) 或进行多种类型的调节 ([eDiffi](http://arxiv.org/abs/2211.01324))
+- “知识增强” - 将预先训练的图像描述和物体检测模型纳入训练过程,以创建更有信息的描述,并产生更好的表现 ([ERNIE-ViLG 2.0](http://arxiv.org/abs/2210.15257))
+- “复合降噪专家” (MoDE) - 训练模型的不同变体(“专家”)以适应不同的噪声水平,如上图所示 [ERNIE-ViLG 2.0 paper](http://arxiv.org/abs/2210.15257).
+
+主要文献:
+- [Elucidating the Design Space of Diffusion-Based Generative Models](http://arxiv.org/abs/2206.00364)
+- [eDiffi: Text-to-Image Diffusion Models with an Ensemble of Expert Denoisers](http://arxiv.org/abs/2211.01324)
+- [ERNIE-ViLG 2.0: Improving Text-to-Image Diffusion Model with Knowledge-Enhanced Mixture-of-Denoising-Experts](http://arxiv.org/abs/2210.15257)
+- [Imagen - Photorealistic Text-to-Image Diffusion Models with Deep Language Understanding](https://arxiv.org/abs/2205.11487) ([demo site](https://imagen.research.google/))
+
+## 对生成与编辑的更多控制
+
+除了训练方面的改进,在采样和推断阶段也有一些创新方法。这其中有许多甚至可以为现有扩散模型添加新的功能。
+
+
+_由'paint-with-words'生成的样本 ([eDiffi](http://arxiv.org/abs/2211.01324))_
+
+这个视频 ['使用扩散模型编辑图片'](https://www.youtube.com/watch?v=zcG7tG3xS3s) 概述了如何使用的不同的方法来通过应用扩散模型对已有的图片进行编辑。可用的技术主要分为四个主要类别:
+1) 添加噪声,然后用一个新的提示(prompt)来进行去噪. 这就是 'img2img ' 管道背后的思想,已经在各种论文中得到了扩展:
+- [SDEdit](https://sde-image-editing.github.io/) and [MagicMix](https://magicmix.github.io/) 这两篇论文都是建立在这一理念的基础上的
+- DDIM 反演 (TODO link tutorial)使用模型来“反转”采样轨迹来取代添加随机噪声, 从而提供了更多的控制
+- [Null-text Inversion](https://null-text-inversion.github.io/) 通过在每一步中优化用于无分类器引导的无条件文本嵌入,允许极高质量的基于文本的图像编辑,极大地增强了这种方法的性能。
+
+2) 扩展了(1)中的思想,但使用蒙版来控制效果的应用位置
+- [Blended Diffusion](https://omriavrahami.com/blended-diffusion-page/) 介绍了基础的理念
+- [这个 demo](https://huggingface.co/spaces/nielsr/text-based-inpainting) 使用现有的分割模型(CLIPSeg)来创建基于文本描述的掩码
+- [DiffEdit](https://arxiv.org/abs/2210.11427) 是一篇展示了如何使用扩散模型本身来生成适当的掩码,以根据文本编辑图像的优秀论文。
+- [SmartBrush: Text and Shape Guided Object Inpainting with Diffusion Model](https://arxiv.org/abs/2212.05034) 微调扩散模型以获得更准确的掩模引导图像修补。
+
+3) 交叉注意力控制:利用扩散模型中的交叉注意力机制控制编辑的空间位置,实现更细粒度的控制。
+- [Prompt-to-Prompt Image Editing with Cross Attention Control](https://arxiv.org/abs/2208.01626) 是介绍这一想法的关键论文,并且该技术[已经应用于Stable Diffusion](https://wandb.ai/wandb/cross-attention-control/reports/Improving-Generative-Images-with-Instructions-Prompt-to-Prompt-Image-Editing-with-Cross-Attention-Control--VmlldzoyNjk2MDAy)
+- 这个想法也被用于 'paint-with-words'中 ([eDiffi](http://arxiv.org/abs/2211.01324))
+
+4) 对单个图像进行微调(“过拟合”),然后使用微调模型进行图像生成。以下论文几乎在同一时间发表了非常类似的想法:
+- [Imagic: Text-Based Real Image Editing with Diffusion Models](https://arxiv.org/abs/2210.09276)
+- [UniTune: Text-Driven Image Editing by Fine Tuning an Image Generation Model on a Single Image
+](https://arxiv.org/abs/2210.09477)
+
+值得注意的是,这篇论文 [InstructPix2Pix: Learning to Follow Image Editing Instructions](https://arxiv.org/abs/2211.09800) 使用了上面描述的一些图像编辑技术来构建一个图像对的合成数据集以及图像编辑指令(由GPT3.5生成),训练生成了一个能够基于自然语言指令编辑图像的新模型。
+
+
+## 视频
+
+
+_Still frames from [样本视频通过Imagen Video生成](https://imagen.research.google/video/)_
+
+视频可以表示为一组图像的序列,而扩散模型的核心思想可以被应用于这些序列。最近的工作主要集中在寻找合适的架构(例如“3D unet”,它可以对整个序列进行操作)并有效地处理视频数据。由于高帧率视频比静止图像涉及更多的数据,目前的方法倾向于首先生成低分辨率和低帧率视频,然后应用空间和时间超分辨率方法来生成最终的高质量视频输出。
+
+主要文献:
+- [Video Diffusion Models](https://video-diffusion.github.io/)
+- [IMAGEN VIDEO: HIGH DEFINITION VIDEO GENERATION WITH DIFFUSION MODELS](https://imagen.research.google/video/paper.pdf)
+
+## 音频
+
+
+
+_用Riffusion生成的一幅光谱图 ([图片来源](https://www.riffusion.com/about))_
+
+虽然已经有一些直接使用扩散模型生成音频的工作(e.g. [DiffWave](https://arxiv.org/abs/2009.09761)),但迄今为止最成功的方法还是将音频信号转换为一种称为频谱图的东西,这种方法有效地将音频“编码”为2D“图像”,然后可以用于训练我们用来做图像生成的扩散模型。之后就可以使用现有方法将生成的频谱图转换为音频。最近发布的Riffusion模型就是基于这样的设计思路。该模型通过微调Stable Diffusion模型来基于文字生成频谱图 - [点击这里进行尝试](https://www.riffusion.com/)。
+
+音频生成领域发展非常迅速。至少有5个新的进展在过去的一周(在撰写本文时)被发布了。在下面的列表中,我们用星号将他们标了出来:
+
+主要文献:
+- [DiffWave: A Versatile Diffusion Model for Audio Synthesis](https://arxiv.org/abs/2009.09761)
+- ['Riffusion'](https://www.riffusion.com/about) (and [code](https://github.com/riffusion/riffusion))
+- *[MusicLM](https://google-research.github.io/seanet/musiclm/examples/) 通过谷歌从文本生成一致的音频,并可以调节哼唱或吹口哨的旋律
+- *[RAVE2](https://github.com/acids-ircam/RAVE) - 一个新版本的变分自动编码器,可以被用在latent diffusion音频任务上。 这个新结构将被用在下面这篇即将发布的模型中 *[AudioLDM](https://twitter.com/LiuHaohe/status/1619119637660327936?s=20&t=jMkPWBFuAH19HI9m5Sklmg)
+- *[Noise2Music](https://noise2music.github.io/) - 该扩散模型可以基于文本描述来生成一段高质量的30秒音频片段
+- *[Make-An-Audio: Text-To-Audio Generation with Prompt-Enhanced Diffusion Models](https://text-to-audio.github.io/) - 该扩散模型可以基于文本描述来生成不同的声音
+- *[Moûsai: Text-to-Music Generation with Long-Context Latent Diffusion](https://arxiv.org/abs/2301.11757)
+
+## 新的体系结构和方法 - 走向“迭代优化”
+
+
+
+_图片1来自 [Cold Diffusion](http://arxiv.org/abs/2208.09392) paper_
+
+我们正在慢慢地超越最初的“扩散”模型的狭义定义,并向更一般的、执行**迭代优化**的一类模型前进。这其中某种形式的破坏(例如在正向扩散过程中添加高斯噪声)被逐渐逆转以生成样本。这篇有关“冷扩散”的论文证明了许多其他类型的退化过程可以迭代地被“撤销”以生成图像(如上所示的示例)。同时最近基于transformer的方法也证明了符记替换(token replacement)或遮蔽(masking)作为噪声策略的有效性。
+
+
+
+_Pipeline from [MaskGIT](http://arxiv.org/abs/2202.04200)_
+
+目前许多扩散模型的核心UNet架构也正在被不同的替代方案所取代,最显著的是各种基于transformer的架构。在 [Scalable Diffusion Models with Transformers (DiT)](https://www.wpeebles.com/DiT)中,transformer结构被用来替换了一个标准扩散模型方法中的UNet结构, 并获得了相当不错的成果。 [Recurrent Interface Networks](https://arxiv.org/pdf/2212.11972.pdf) 应用一种新的基于transformer的架构和训练策略,以追求额外的效率。[MaskGIT](http://arxiv.org/abs/2202.04200) 和 [MUSE](http://arxiv.org/abs/2301.00704) 使用 transformer 模型来处理图像的标记化表示。 而[Paella](https://arxiv.org/abs/2211.07292v1)这篇文章也表示,UNet结构同样可以在这些token-based的设计中成功发挥作用。
+
+随着每一篇新论文的发表,更有效的方法正在陆续被开发出来。我们可能还需要一段时间才能看到这种迭代细化任务的巅峰性能。我们十分期待还有更多的东西被探索和发掘!
+
+主要文献
+- [Cold Diffusion: Inverting Arbitrary Image Transforms Without Noise](http://arxiv.org/abs/2208.09392)
+- [Scalable Diffusion Models with Transformers (DiT)](https://www.wpeebles.com/DiT)
+- [MaskGIT: Masked Generative Image Transformer](http://arxiv.org/abs/2202.04200)
+- [Muse: Text-To-Image Generation via Masked Generative Transformers](http://arxiv.org/abs/2301.00704)
+- [Fast Text-Conditional Discrete Denoising on Vector-Quantized Latent Spaces (Paella)](https://arxiv.org/abs/2211.07292v1)
+- [Recurrent Interface Networks](https://arxiv.org/pdf/2212.11972.pdf) - 一种很有前途的新架构,可以在不依赖latent diffusion或超分辨率模型的情况下生成高分辨率图像。另请参阅 [simple diffusion: End-to-end diffusion for high-resolution images](https://arxiv.org/abs/2301.11093) 该论文强调了噪声表(noise schedule)在高分辨率训练中的重要性。
+
+## 动手笔记本
+
+| 章节 | Colab | Kaggle | Gradient | Studio Lab |
+|:--------------------------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| DDIM Inversion | [](https://colab.research.google.com/github/huggingface/diffusion-models-class/blob/main/unit4/01_ddim_inversion.ipynb) | [](https://kaggle.com/kernels/welcome?src=https://github.com/huggingface/diffusion-models-class/blob/main/unit4/01_ddim_inversion.ipynb) | [](https://console.paperspace.com/github/huggingface/diffusion-models-class/blob/main/unit4/01_ddim_inversion.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/diffusion-models-class/blob/main/unit4/01_ddim_inversion.ipynb) |
+| Diffusion for Audio | [](https://colab.research.google.com/github/huggingface/diffusion-models-class/blob/main/unit4/02_diffusion_for_audio.ipynb) | [](https://kaggle.com/kernels/welcome?src=https://github.com/huggingface/diffusion-models-class/blob/main/unit4/02_diffusion_for_audio.ipynb) | [](https://console.paperspace.com/github/huggingface/diffusion-models-class/blob/main/unit4/02_diffusion_for_audio.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/diffusion-models-class/blob/main/unit4/02_diffusion_for_audio.ipynb) |
+
+在本单元中,我们已经讨论了很多不同的想法,其中许多值得在未来的后续课程中进行更详细的学习。现在,你可以通过我们准备的动手笔记本来学习其中的两个主题。
+- **DDIM Inversion** 展示了如何使用一种被称为“反转”的技术来使用已有的扩散模型编辑图像
+- **Diffusion for Audio** 介绍了频谱图的思想,并展示了如何对特定音乐风格的音频扩散模型进行微调。
+
+## 下一步?
+
+这是本课程的最后一个单元,这意味着接下来要做什么取决于你! 请记得你永远都可以来Hugging Face [discord频道](https://huggingface.co/join/discord)上来询问问题或者聊聊你自己的project。 我们期待看到你的创作! 🤗