코미 더 코뮤니스트 요즘 유행하는 AI 이미지, 생성 AI 를 한번 써보려다가 알아야 할것들이 좀 있는것 같아서. 일단 아래의 문서를 가지고 일부분을 번역하며 읽어볼 생각. https://stable-diffusion-art.com/how-stable-diffusion-work/
코미 더 코뮤니스트 Diffusion 모델 : 생성형 모델. 학습한것과 비슷한 것을 생성하도록 설계된 모델. 이름이 Diffusion인 이유는 수학적으로 물리학에서의 확산(Diffusion)과 비슷하기 때문이라고 한다. 솔직히 뭔 말인지 모르겠지만 일단 계속 보자... 정방향 확산(Forward Diffusion) 개 고양이 이미지에 노이즈를 단계적으로 계속 추가해서 뭔 그림인지 알수 없게 된 노이즈뿐인 이미지로 만드는 과정... 이라고 한다(중요). 역방향 확산(Reverse Diffusion) 정방향 확산을 거꾸로 되돌리는 것이라고 한다. (원문에서는 정방향 확산을 물에 잉크를 한방울 떨어뜨리고 물에 완전히 퍼지도록 놔두는것, 역방향 확산은 그렇게 완전히 물에 퍼져나간 잉크를 도로 뽑아내는 것에 비유하고 있다. ) 아무 의미없어진 이미지에서 다시 개, 고양이 이미지를 뽑아내는 작업이다. 이 주제에서 앞서나간 분들은 바로 이해했겠지만, 정방향 확산은 인터넷커뮤니티에서 흔히들 말하는 'AI에게 학습시키는 과정', 역방향 확산은 '그 AI로부터 원하는 이미지를 생성하는 과정'을 생각나게 한다. 그럼 그 역방향 확산(Reverse Diffusion)은 어떻게 해내는 것일까? 원문을 보면 이렇게 써있다. To reverse the diffusion, we need to know how much noise is added to an image. The answer is teaching a neural network model to predict the noise added. It is called the noise predictor in Stable Diffusion. It is a U-Net model. The training goes as follows. Pick a training image, like a photo of a cat. Generate a random noise image. Corrupt the training image by adding this noisy image up to a certain number of steps. Teach the noise predictor to tell us how much noise was added. This is done by tuning its weights and showing it the correct answer. '신경망 모델' 에게 노이즈를 예측하도록 학습시키는 방법을 쓴다고 한다. Stable Diffusion 에서는 이걸 'noise predictor' 라고 부르는것 같다. 정방향 확산(Forward Diffusion) 아이디어에 따라 개, 고양이 이미지에 단계적으로 노이즈를 넣어 손상시키고, 'noise predictor' 에게 노이즈가 추가된 정도를 학습시킨다. 노이즈 가중치를 얼마 더할때마다 정답을 보여주는 방식으로 학습시킨다고 한다. 그러니까... 이렇게 노이즈 1단계를 넣어서 그림을 훼손한다음 가장 왼쪽의 정답(정상적인 고양이 사진)을 보여주고, 노이즈 2단계를 넣어서 그림을 더 많이 망가트린다음 다시 가장 왼쪽의 고양이 사진을 보여주고... 를 반복해서 'noise predictor'를 학습시킨다는 얘기인것 같다. 이렇게 확보한 'noise predictor'로 역방향 확산(Reverse Diffusion)을 시도한다.
코미 더 코뮤니스트 noise predictor로 역방향 확산(Reverse Diffusion)을 하는 과정 먼저 완전한 무작위 이미지(completely random image)를 생성하고, 앞서 확보한 noise predictor에게 이 이미지에 노이즈가 얼마나 들어갔는지를 질의하면 → noise predictor가 노이즈 관련 정보를 반환하고 → 그 정보로 이미지에서 추정된 노이즈를 제거하고 → 이 과정을 몇차례 반복한다 내 생각엔 이건 '경험의 재현' 에 가까운듯... 컴퓨터가 참 대단한 물건이긴 하다. 원문에 따르면 여기까지가 기본(?) 개념이라고 한다. 이걸 구현하는데는 커다란 '이미지 공간'에서 diffusion 과정을 수행해야 하는데, 현존 최고의 GPU로 해도 연산이 매우 오래걸리거나 불가능하다는것 같다. The reason is that the above diffusion process is in image space. It is computationally very, very slow. You won’t be able to run on any single GPU, let alone the crappy GPU on your laptop. 솔직히 '이미지 공간'이 뭔 뜻인지는 모르겠지만 하여튼 성능문제로 개념을 그대로 구현하는데엔 한계가 있다는 의미인듯
코미 더 코뮤니스트 The image space is enormous. Think about it: a 512×512 image with three color channels (red, green, and blue) is a 786,432-dimensional space! (You need to specify that many values for ONE image.) Diffusion models like Google’s Imagen and Open AI’s DALL-E are in pixel space. They have used some tricks to make the model faster but still not enough. '이미지 공간' 은 크기가 거대해서 512x512짜리 이미지 하나를 만드는데 많은 코스트가 필요하다고 함. Google의 Imagen과 OpenAI의 DALL-E는 아직 부족하긴 하지만 저마다의 기법으로 이걸 좀더 빠르게 하고있다는 내용 Latent diffusion model Stable Diffusion is designed to solve the speed problem. Here’s how. Stable Diffusion is a latent diffusion model. Instead of operating in the high-dimensional image space, it first compresses the image into the latent space. The latent space is 48 times smaller so it reaps the benefit of crunching a lot fewer numbers. That’s why it’s a lot faster. Stable Diffusion에도 속도문제를 해결하기위한 설계가 있는데 그걸 'Latent diffusion model' 이라고 하는듯. 지금까지 읽어본 이론을 '고차원 이미지 공간(high-dimensional image space)' 에서 구현하는게 아니라 먼저 'latent space' 에서 압축한다음 처리한다고 한다. (맞게 이해하고 있는건가 점점 자신이 없어진다 ㅠㅠ) latent space는 이미지 공간에 비해 48배나 작아서 처리가 훨씬 빠르다고 함.
코미 더 코뮤니스트 Variational Autoencoder '가변성 자동 인코더' 정도로 변역할수 있는것 같다. 문서에서 곧바로 VAE 로 줄여쓰는데 Stable Diffusion 설치법을 인터넷에서 검색해서 설치해봤으면 설정화면에 VAE가 있는걸 봤을것이다. 드디어 본적있는게 나왔다! 이 VAE는 latent diffusion model을 만들때 사용하는 기법이라고 한다. The Variational Autoencoder (VAE) neural network has two parts: (1) an encoder and (2) a decoder. The encoder compresses an image to a lower dimensional representation in the latent space. The decoder restores the image from the latent space. VAE신경망은 인코더, 디코더 두가지로 되어있는데 인코더는 latent space에서 이미지를 닞은 차원의 표현으로 압축, 디코더는 latent space로부터 이미지를 되돌리는 기능을 한다 The latent space of Stable Diffusion model is 4x64x64, 48 times smaller than the image pixel space. All the forward and reverse diffusions we talked about are actually done in the latent space. Stable Diffusion 의 latent space 크기는 4x64x64 이며 이미지 픽셀 공간에 비해 48배나 작다. (지금까지 설명한) 정방향, 역방향 확산은 이 latent space에서 처리된다. So during training, instead of generating a noisy image, it generates a random tensor in latent space (latent noise). Instead of corrupting an image with noise, it corrupts the representation of the image in latent space with the latent noise. The reason for doing that is it is a lot faster since the latent space is smaller. 앞에서 개념을 설명할때 이미지를 '노이즈' 로 손상시킨다고 했지만 실제로는 latent space에서 노이즈로 손상시키는게 아니라 random tensor, latent noise 라는 수단으로 손상시킨다고 한다. 잘은 모르겠지만 latent space의 속도가 이미지 공간 개념보다 처리속도가 빠르니까 그 안에서 돌릴수 있는 '이미지 손상' 기법이 따로 있는것 같다.
코미 더 코뮤니스트 Image resolution The image resolution is reflected in the size of the latent image tensor. The size of the latent image is 4x64x64 for 512×512 images only. It is 4x96x64 for a 768×512 portrait image. That’s why it takes longer and more VRAM to generate a larger image. Since Stable Diffusion v1 is fine-tuned on 512×512 images, generating images larger than 512×512 could result in duplicate objects, e.g., the infamous two heads. Image upscaling To generate a large print, keep at least one side of the image to 512 pixels. Use an AI upscaler or image-to-image function for image upscaling. 대강 이미지 해상도가 클수록 VRAM을 많이 사용하며 이미지 확대할땐 SDXL모델을 쓰면 좋다는 내용. Why is latent space possible? You may wonder why the VAE can compress an image into a much smaller latent space without losing information. The reason is, unsurprisingly, natural images are not random. They have high regularity: A face follows a specific spatial relationship between the eyes, nose, cheek, and mouth. A dog has 4 legs and is a particular shape. In other words, the high dimensionality of images is artifactual. Natural images can be readily compressed into the much smaller latent space without losing any information. This is called the manifold hypothesis in machine learning. latent space가 어떻게 가능한가? VAE가 이미지를 latent space에 압축해서 처리할때 정보의 손실이 발생하지 않는이유 : 대부분의 이미지가 무작위(random)가 아니기 때문이라고 한다. 자연적인 이미지에는 높은 규칙성이 있다고 한다. 사람 얼굴의 눈,코,입 은 공간적으로 연관되어있고, 개는 대체로 4개의 다리가 있는 동물이라던지... 달리 말하면 자연적 이미지는 정보 손실없이 압축할 수 있다. 이걸 머신러닝 에서는 manifold hypothesis(다양체 가설) 이라고 한다.
코미 더 코뮤니스트 Reverse diffusion in latent space Here’s how latent reverse diffusion in Stable Diffusion works. A random latent space matrix is generated. The noise predictor estimates the noise of the latent matrix. The estimated noise is then subtracted from the latent matrix. Steps 2 and 3 are repeated up to specific sampling steps. he decoder of VAE converts the latent matrix to the final image. (이렇게 구현된) latent space에서 역방향 확산(Reverse Diffusion)을 하는 과정 무작위 latent space 행렬 생성 ➡️ noise predictor 가 latent space 행렬의 노이즈 예측 ➡️ 예측된 노이즈를 latent space에서 제거 ➡️ 지정 샘플링 단계에 있는 동안 앞의 단계를 반복 ➡️ VAE가 latent space로부터 최종이미지로 변환 What is a VAE file? VAE files are used in Stable Diffusion v1 to improve eyes and faces. They are the decoder of the autoencoder we just talked about. By further fine-tuning the decoder, the model can paint finer details. You may realize what I have mentioned previously is not entirely true. Compressing an image into the latent space does lose information since the original VAE did not recover the fine details. Instead, the VAE decoder is responsible for painting fine details. 그럼 VAE 파일이 무엇이냐 VAE 파일은 Stable Diffusion v1 에서 (사람 이미지의) 얼굴과 눈을 향상시키는데 사용되었다고 한다. 이것이 우리가 지금까지 얘기한 autoencoder다. 이 decoder를 튜닝하면 디테일이 더 좋아진 이미지를 디코더가 그릴수 있게 된다. 앞에서 분명히 자연적인 이미지는 규칙성이 있어서 손실없이 latent space로 압축할 수 있다고 했는데 여기서는 또 VAE가 얼굴과 눈을 향상시키는데 쓰였다고 설명하고 있다. 아무래도 VAE가 encoder를 작동시켜서 이미지를 latent space에 압축해 넣을때 완전히 손실이 없는건 아닌 모양. 그래서 VAE 디코더를 조정하는 것으로 미세한 부분을 보완할수 있다는 내용인것 같다.
코미 더 코뮤니스트 번역 도중에 재미난 기사가 나와서 슬쩍 끼워둠. 수능 지문을 소개한 기사. '노이즈'가 많이 나와서 웃기긴 한데 지문 내용에 순방향 확산, 노이즈 예측기, 잠재 표현 이런 말글이 나오는거 보면 Stable Diffusion 의 확산 모델을 설명한거 같음. 이게 수능에 나오는걸 보니깐 좀 신기하네요. https://www.yna.co.kr/view/AKR20241114120100530
코미 더 코뮤니스트 Conditioning Our understanding is incomplete: Where does the text prompt enter the picture? Without it, Stable Diffusion is not a text-to-image model. You will either get an image of a cat or a dog without any way to control it. This is where conditioning comes in. The purpose of conditioning is to steer the noise predictor so that the predicted noise will give us what we want after subtracting from the image. 이제 '프롬프트'가 나올 차례인듯. 프롬프트가 없으면 Stable Diffusion 은 그냥 latent space에서 학습한걸로 그냥 이미지를 뽑아낼뿐 원하는 이미지를 내놓도록 명령을 못하니까 text to image 모델이라고 할수가 없다고 한다. 그래서 컨디셔닝이 필요해진다고 한다. 컨디셔닝은 noise predictor 를 조정해 노이즈를 제거한 결과가 사용자가 원하는 이미지가 되도록 하는것이다. Text conditioning (text-to-image) Below is an overview of how a text prompt is processed and fed into the noise predictor. Tokenizer first converts each word in the prompt to a number called a token. Each token is then converted to a 768-value vector called embedding. (Yes, this is the same embedding you used in AUTOMATIC1111) The embeddings are then processed by the text transformer and are ready to be consumed by the noise predictor. 텍스트 컨디셔닝(text to image) : 프롬프트를 입력하면 어떤 과정을 거쳐서 noise predictor에 전달되는지 간단히 설명한 그림이 나와있다. 프롬프트 입력 ➡️ 단어들을 Tokenizer가 Token으로 변환 ➡️ Token들을 768개 값의 벡터로(embedding) 변환 ➡️ text transformer가 이것을 처리해서 noise predictor가 쓸수있는 형식으로 만듬. 각 단계가 도대체 뭔소린지는 모르겠지만 그 다음 내용에 단계별 설명이 나온다.