図解でわかるStable Diffusion
Jay Alammar が執筆した本記事は、Stable Diffusion の内部構造を視覚的に解説し、テキストエンコーダーと潜在空間での拡散プロセスという技術的基盤を一般向けに明確に理解させる重要な入門資料である。
キーポイント
Stable Diffusion の非単一モデル構成
Stable Diffusion は単一の巨大モデルではなく、テキスト理解コンポーネントと画像生成コンポーネントなど複数のモジュールで構成されるシステムである。
CLIP ベースのテキストエンコーダー
入力されたテキストを CLIP モデルの特殊な Transformer 言語モデル(テキストエンコーダー)が処理し、単語やトークンごとの数値ベクトル表現に変換する。
潜在空間での拡散プロセス
画像生成はピクセル空間ではなく計算効率の高い「潜在空間(latent space)」で行われ、UNet 神経ネットワークとスケジューリングアルゴリズムが複数ステップで画像情報を創出する。
テキストから画像への生成フロー
テキスト入力からベクトル化を経て画像生成器へ渡され、拡散プロセスを通じて最終的な画像が出力される一連のワークフローを解説している。
Stable Diffusion の主要構成要素
テキストエンコーディングを行う ClipText、ノイズから情報を拡散する UNet と Scheduler、そして最終画像を描画する Autoencoder Decoder という 3 つのニューラルネットワークで構成されています。
拡散プロセスの本質
ランダムなノイズ(潜在変数)から始まり、各ステップでテキスト埋め込みベクトルに基づいて情報を加算・加工し、最終的に画像デコーダが描画できる情報配列へと変化させる段階的な処理です。
学習メカニズム
既存の画像にノイズを加える逆過程を学習することで、モデルは画像生成において複雑な操作を習得し、入力テキストと訓練データから得た視覚情報を反映した画像を作成できるようになります。
影響分析・編集コメントを表示
影響分析
この記事は、Stable Diffusion の複雑な技術的仕組みを視覚的な図解を用いて直感的に理解できる形に変換しており、開発者や研究者だけでなく一般ユーザーにとってもこの技術の核心を理解するための重要な指針となる。特に「潜在空間」での処理という画期的なアプローチがなぜ高速化と低リソース化を実現したかを明確に示すことで、AI 画像生成技術の普及と発展を加速させる役割を果たしている。
編集コメント
技術的な詳細を解説する記事は多いが、Jay Alammar のような「視覚的・図解中心」の解説は初学者にとって極めて価値が高く、実装やパラメータ調整の背景にある理論を理解する上で不可欠なリソースです。
イラストで学ぶStable Diffusion
イラストで学ぶStable Diffusion
翻訳: 中国語、ベトナム語。
(V2 2022年11月: 順拡散の記述をより正確にするため画像を更新。このバージョンではさらにいくつかの画像を追加)
AI画像生成は、人々(私も含めて)の心を揺さぶる最新のAI能力です。テキストの説明から印象的なビジュアルを生み出す能力には魔法のような性質があり、人間が芸術を創造する方法の明らかな変化を示しています。Stable Diffusionのリリースは、この発展における明確なマイルストーンです。なぜなら、高性能なモデルを大衆に利用可能にしたからです(ここでの性能とは、画質だけでなく、速度や比較的低いリソース/メモリ要件も含みます)。
AI画像生成を試した後、あなたはその仕組みについて不思議に思うかもしれません。
これは、Stable Diffusionがどのように機能するかを優しく紹介するものです。
Stable Diffusionは多才で、いくつかの異なる方法で使用できます。まずは、テキストのみからの画像生成(text2img)に焦点を当てましょう。上の画像は、テキスト入力の例と、それによって生成された画像を示しています(実際の完全なプロンプトはこちら)。テキストから画像への変換以外に、もう一つの主な使用方法は、画像を変更させることです(つまり、入力はテキスト+画像です)。
内部の仕組みを見ていきましょう。なぜなら、それは構成要素、それらの相互作用、そして画像生成のオプション/パラメータが何を意味するかを説明するのに役立つからです。
Stable Diffusionの構成要素
Stable Diffusionは、いくつかの構成要素とモデルからなるシステムです。単一の巨大なモデルではありません。
内部を見ると、最初に観察できるのは、テキスト情報を、テキスト内のアイデアを捉えた数値表現に変換するテキスト理解コンポーネントがあることです。
私たちは高レベルな視点から始め、この記事の後半でより詳細な機械学習の内容に入っていきます。しかし、このテキストエンコーダは特別なTransformer言語モデルであると言えます(技術的には:CLIPモデルのテキストエンコーダ)。入力テキストを受け取り、テキスト内の各単語/トークンを表す数値のリスト(トークンごとのベクトル)を出力します。
その情報は次に、画像生成器に提示されます。画像生成器自体もいくつかのコンポーネントで構成されています。
画像生成器は2つの段階を経ます:
1- 画像情報生成器
このコンポーネントはStable Diffusionの秘伝のタレです。以前のモデルに対する多くの性能向上はここで達成されています。
このコンポーネントは、画像情報を生成するために複数のステップで実行されます。これはStable Diffusionのインターフェースやライブラリにおけるstepsパラメータで、多くの場合デフォルトは50または100です。
画像情報生成器は、完全に画像情報空間(または潜在空間)で動作します。これが何を意味するかについては、後ほどこの記事で詳しく説明します。この特性により、ピクセル空間で動作していた以前の拡散モデルよりも高速です。技術的には、このコンポーネントはUNetニューラルネットワークとスケジューリングアルゴリズムで構成されています。
「拡散」という言葉は、このコンポーネントで起こることを表しています。それは、最終的に(次のコンポーネントである画像デコーダによって)高品質な画像が生成されるように、情報を段階的に処理していくことです。
2- 画像デコーダ
画像デコーダは、情報生成器から得た情報を使って絵を描きます。この処理は、最終的なピクセル画像を生成するために、プロセスの最後に一度だけ実行されます。
これにより、Stable Diffusionを構成する3つの主要コンポーネント(それぞれが独自のニューラルネットワークを持つ)が見えてきます:
テキストエンコーディングのためのClipText。入力:テキスト。出力:77個のトークン埋め込みベクトル(各768次元)。
情報(潜在)空間で情報を段階的に処理/拡散させるためのUNet + Scheduler。入力:テキスト埋め込みと、ノイズで構成される開始多次元配列(構造化された数値のリスト、テンソルとも呼ばれる)。出力:処理済み情報配列
処理済み情報配列を使用して最終画像を描画するAutoencoder Decoder。入力:処理済み情報配列(次元: (4,64,64))。出力:結果の画像(次元: (3, 512, 512)、これは(赤/緑/青、幅、高さ))
拡散とは一体何か?
拡散は、ピンク色の「画像情報生成器」コンポーネント内部で行われるプロセスです。入力テキストを表すトークン埋め込みと、ランダムな開始画像情報配列(これらは潜在変数とも呼ばれます)を持って、このプロセスは画像デコーダが最終画像を描画するために使用する情報配列を生成します。
このプロセスは段階的に行われます。各ステップで、より関連性の高い情報が追加されます。プロセスの直感を得るために、ランダムな潜在変数配列を調べ、それが視覚的なノイズに変換されることを確認できます。この場合の視覚的検査とは、それを画像デコーダに通すことです。
拡散は複数のステップで起こり、各ステップは入力潜在変数配列に対して動作し、入力テキストと、モデルが学習したすべての画像からモデルが拾ったすべての視覚情報により似た、別の潜在変数配列を生成します。
これらの潜在変数のセットを可視化して、各ステップでどのような情報が追加されるかを見ることができます。
このプロセスを見るのは、かなり息をのむものです。
この場合、ステップ2と4の間には特に魅力的なことが起こります。まるで輪郭がノイズから浮かび上がってくるようです。
拡散の仕組み
拡散モデルによる画像生成の中心的な考え方は、強力なコンピュータビジョンモデルが存在するという事実に依存しています。十分に大きなデータセットがあれば、これらのモデルは複雑な操作を学習できます。拡散モデルは、画像生成の問題を次のように捉えます:
画像があるとします。そこにノイズを生成して追加します。
これは今、学習例と見なすことができます。この同じ式を使って、多くの学習例を作成し、画像生成モデルの中心コンポーネントを学習させることができます。
この例では、画像(量0、ノイズなし)から完全なノイズ(量4、完全なノイズ)までのいくつかのノイズ量の値を示していますが、画像に追加するノイズの量を簡単に制御できるので、それを数十のステップに分散させ、学習データセット内のすべての画像に対して、画像ごとに数十の学習例を作成できます。
このデータセットを使って、ノイズ予測器を学習させ、特定の構成で実行すると実際に画像を作成する優れたノイズ予測器を手に入れることができます。機械学習に触れたことがあれば、学習ステップは見覚えがあるはずです:
さて、これがどのように画像を生成できるかを見てみましょう。
ノイズを取り除いて画像を描く
学習済みのノイズ予測器は、ノイズの多い画像と、ノイズ除去ステップの番号を受け取り、ノイズの一片を予測することができます。
サンプリングされたノイズは、それを画像から減算すると、モデルが学習した画像(正確な画像そのものではなく、分布 – 空は通常青く地面の上にあり、人は2つの目を持ち、猫はある特定の見た目 – 尖った耳と明らかに感心していない表情 – を持つ、ピクセル配置の世界)に近い画像が得られるように予測されます。
学習データセットが美的に優れた画像(例えば、Stable Diffusionが学習されたLAION Aesthetics)であれば、結果の画像は美的に優れたものになる傾向があります。ロゴの画像で学習させれば、ロゴ生成モデルができあがります。
これは、Denoising Diffusion Probabilistic Modelsで主に説明されているような、拡散モデルによる画像生成の説明を締めくくります。この拡散の直感を得た今、あなたはStable Diffusionだけでなく、Dall-E 2やGoogleのImagenの主要コンポーネントも知っていることになります。
ここまで説明した拡散プロセスは、テキストデータを一切使用せずに画像を生成することに注意してください。したがって、このモデルをデプロイすると、見た目が素晴らしい画像を生成しますが、それがピラミッドの画像なのか、猫の画像なのか、それとも他の何かなのかを制御する方法はありません。次のセクションでは、モデルが生成する画像の種類を制御するために、プロセスにテキストをどのように組み込むかを説明します。
スピードブースト:ピクセル画像の代わりに圧縮(潜在)データでの拡散
画像生成プロセスを高速化するために、Stable Diffusionの論文は拡散プロセスをピクセル画像上ではなく、
原文を表示
The Illustrated Stable Diffusion
Translations: Chinese, Vietnamese.
(V2 Nov 2022: Updated images for more precise description of forward diffusion. A few more images in this version)
AI image generation is the most recent AI capability blowing people’s minds (mine included). The ability to create striking visuals from text descriptions has a magical quality to it and points clearly to a shift in how humans create art. The release of Stable Diffusion is a clear milestone in this development because it made a high-performance model available to the masses (performance in terms of image quality, as well as speed and relatively low resource/memory requirements).
After experimenting with AI image generation, you may start to wonder how it works.
This is a gentle introduction to how Stable Diffusion works.
Stable Diffusion is versatile in that it can be used in a number of different ways. Let’s focus at first on image generation from text only (text2img). The image above shows an example text input and the resulting generated image (The actual complete prompt is here). Aside from text to image, another main way of using it is by making it alter images (so inputs are text + image).
Let’s start to look under the hood because that helps explain the components, how they interact, and what the image generation options/parameters mean.
The Components of Stable Diffusion
Stable Diffusion is a system made up of several components and models. It is not one monolithic model.
As we look under the hood, the first observation we can make is that there’s a text-understanding component that translates the text information into a numeric representation that captures the ideas in the text.
We’re starting with a high-level view and we’ll get into more machine learning details later in this article. However, we can say that this text encoder is a special Transformer language model (technically: the text encoder of a CLIP model). It takes the input text and outputs a list of numbers representing each word/token in the text (a vector per token).
That information is then presented to the Image Generator, which is composed of a couple of components itself.
The image generator goes through two stages:
1- Image information creator
This component is the secret sauce of Stable Diffusion. It’s where a lot of the performance gain over previous models is achieved.
This component runs for multiple steps to generate image information. This is the steps parameter in Stable Diffusion interfaces and libraries which often defaults to 50 or 100.
The image information creator works completely in the image information space (or latent space). We’ll talk more about what that means later in the post. This property makes it faster than previous diffusion models that worked in pixel space. In technical terms, this component is made up of a UNet neural network and a scheduling algorithm.
The word “diffusion” describes what happens in this component. It is the step by step processing of information that leads to a high-quality image being generated in the end (by the next component, the image decoder).
2- Image Decoder
The image decoder paints a picture from the information it got from the information creator. It runs only once at the end of the process to produce the final pixel image.
With this we come to see the three main components (each with its own neural network) that make up Stable Diffusion:
ClipText for text encoding. Input: text. Output: 77 token embeddings vectors, each in 768 dimensions.
UNet + Scheduler to gradually process/diffuse information in the information (latent) space. Input: text embeddings and a starting multi-dimensional array (structured lists of numbers, also called a tensor) made up of noise. Output: A processed information array
Autoencoder Decoder that paints the final image using the processed information array. Input: The processed information array (dimensions: (4,64,64)) Output: The resulting image (dimensions: (3, 512, 512) which are (red/green/blue, width, height))
What is Diffusion Anyway?
Diffusion is the process that takes place inside the pink “image information creator” component. Having the token embeddings that represent the input text, and a random starting image information array (these are also called latents), the process produces an information array that the image decoder uses to paint the final image.
This process happens in a step-by-step fashion. Each step adds more relevant information. To get an intuition of the process, we can inspect the random latents array, and see that it translates to visual noise. Visual inspection in this case is passing it through the image decoder.
Diffusion happens in multiple steps, each step operates on an input latents array, and produces another latents array that better resembles the input text and all the visual information the model picked up from all images the model was trained on.
We can visualize a set of these latents to see what information gets added at each step.
The process is quite breathtaking to look at.
Something especially fascinating happens between steps 2 and 4 in this case. It’s as if the outline emerges from the noise.
How diffusion works
The central idea of generating images with diffusion models relies on the fact that we have powerful computer vision models. Given a large enough dataset, these models can learn complex operations. Diffusion models approach image generation by framing the problem as following:
Say we have an image, we generate some noise, and add it to the image.
This can now be considered a training example. We can use this same formula to create lots of training examples to train the central component of our image generation model.
While this example shows a few noise amount values from image (amount 0, no noise) to total noise (amount 4, total noise), we can easily control how much noise to add to the image, and so we can spread it over tens of steps, creating tens of training examples per image for all the images in a training dataset.
With this dataset, we can train the noise predictor and end up with a great noise predictor that actually creates images when run in a certain configuration. A training step should look familiar if you’ve had ML exposure:
Let’s now see how this can generate images.
Painting images by removing noise
The trained noise predictor can take a noisy image, and the number of the denoising step, and is able to predict a slice of noise.
The sampled noise is predicted so that if we subtract it from the image, we get an image that’s closer to the images the model was trained on (not the exact images themselves, but the distribution - the world of pixel arrangements where the sky is usually blue and above the ground, people have two eyes, cats look a certain way – pointy ears and clearly unimpressed).
If the training dataset was of aesthetically pleasing images (e.g., LAION Aesthetics, which Stable Diffusion was trained on), then the resulting image would tend to be aesthetically pleasing. If the we train it on images of logos, we end up with a logo-generating model.
This concludes the description of image generation by diffusion models mostly as described in Denoising Diffusion Probabilistic Models. Now that you have this intuition of diffusion, you know the main components of not only Stable Diffusion, but also Dall-E 2 and Google’s Imagen.
Note that the diffusion process we described so far generates images without using any text data. So if we deploy this model, it would generate great looking images, but we’d have no way of controlling if it’s an image of a pyramid or a cat or anything else. In the next sections we’ll describe how text is incorporated in the process in order to control what type of image the model generates.
Speed Boost: Diffusion on Compressed (Latent) Data Instead of the Pixel Image
To speed up the image generation process, the Stable Diffusion paper runs the diffusion process not on the pixel images themselves, but on a compressed version of the image. The paper calls this “Departure to Latent Space”.
This compression (and later decompression/painting) is done via an autoencoder. The autoencoder compresses the image into the latent space using its encoder, then reconstructs it using only the compressed information using the decoder.
Now the forward diffusion process is done on the compressed latents. The slices of noise are of noise applied to those latents, not to the pixel image. And so the noise predictor is actually trained to predict noise in the compressed representation (the latent space).
The forward process (using the autoencoder’s encoder) is how we generate the data to train the noise predictor. Once it’s trained, we can generate images by running the reverse process (using the autoencoder’s decoder).
These two flows are what’s shown in Figure 3 of the LDM/Stable Diffusion paper:
This figure additionally shows the “conditioning” components, which in this case is the text prompts describing what image the model should generate. So let’s dig into the text components.
The Text Encoder: A Transformer Language Model
A Transformer language model is used as the language understanding component that takes the text prompt and produces token embeddings. The released Stable Diffusion model uses ClipText (A GPT-based model), while the paper used BERT.
The choice of language model is shown by the Imagen paper to be an important one. Swapping in larger language models had more of an effect on generated image quality than larger image generation components.
The early Stable Diffusion models just plugged in the pre-trained ClipText model released by OpenAI. It’s possible that future models may switch to the newly released and much larger OpenCLIP variants of CLIP (Nov2022 update: True enough, Stable Diffusion V2 uses OpenClip). This new batch includes text models of sizes up to 354M parameters, as opposed to the 63M parameters in ClipText.
How CLIP is trained
CLIP is trained on a dataset of images and their captions. Think of a dataset looking like this, only with 400 million images and their captions:
In actuality, CLIP was trained on images crawled from the web along with their “alt” tags.
CLIP is a combination of an image encoder and a text encoder. Its training process can be simplified to thinking of taking an image and its caption. We encode them both with the image and text encoders respectively.
We then compare the resulting embeddings using cosine similarity. When we begin the training process, the similarity will be low, even if the text describes the image correctly.
We update the two models so that the next time we embed them, the resulting embeddings are similar.
By repeating this across the dataset and with large batch sizes, we end up with the encoders being able to produce embeddings where an image of a dog and the sentence “a picture of a dog” are similar. Just like in word2vec, the training process also needs to include negative examples of images and captions that don’t match, and the model needs to assign them low similarity scores.
Feeding Text Information Into The Image Generation Process
To make text a part of the image generation process, we have to adjust our noise predictor to use the text as an input.
Our dataset now includes the encoded text. Since we’re operating in the latent space, both the input images and predicted noise are in the latent space.
To get a better sense of how the text tokens are used in the Unet, let’s look deeper inside the Unet.
Layers of the Unet Noise predictor (without text)
Let’s first look at a diffusion Unet that does not use text. Its inputs and outputs would look like this:
Inside, we see that:
The Unet is a series of layers that work on transforming the latents array
Each layer operates on the output of the previous layer
Some of the outputs are fed (via residual connections) into the processing later in the network
The ti
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み