AI 페인팅

Colab Stable Diffusion 그림그리기

coding art 2023. 2. 7. 18:11
728x90

 

Untitled0.ipynb 시작단계에서 반드시 런타임을 클릭하여 런타임 유형변경에서 GPU를 설정하자.

 

2023년 2월 7일 기준 tensorflow가 불과 며칠 전에 버전 2.92였던 것이 2.11로 업그레이드 되었다. 하지만 default 버전을 출력해 보면 여전히 2.9.2로 출력된다. 여타의 머신러닝에서는 문제가 되지 않지만 Stable Diffuaion에 의한 그림 그리기작업에서 tensorflow 버전이 맞지 않는다는 에러 메세지가 발생하여 뜬다.

1 import tensorflow as tf
print(tf.__version__)
-----------------------------------------------------------
2.9.2

 

아래와 같이 TensorFlow 최신 버전으로 업그레드 하자. 출력 결과를 보면

tensorflow 2.11.0 과 keras 2.11.0 이 함께 설치됨을 알 수 있다. 아울러 런타임에서 런타임 다시시작을 클릭하자.

2 pip install —upgrade tensorflow
-----------------------------------------------------------
Successfully installed flatbuffers-23.1.21 keras-2.11.0 tensorboard-2.11.2 tensorflow-2.11.0 tensorflow-estimator-2.11.0
WARNING: ... You must restart the runtime in order to...

 

가장 중요한 keras-cv를 설치하자. TensorFlow 2.11.0으로 업그레이드 되지 않았다면 이 부분에서 에러가 발생함에 유의하자.

3 !pip install keras_cv
-----------------------------------------------------------
...
Installing collected packages: keras_cv
Successfully installed keras_cv-0.4.2

 

파이선 라이브러리 time, keras_cv, keras, matplotlib.pyplot 라이브러리들을 설치하자.

4 import time
import keras_cv
from tensorflow import keras
import matplotlib.pyplot as plt

 

그림을 그릴수 있도록 그래픽 규격을 설정한다.

5 def plot_images(images):
plt.figure(figsize=(20,20))
for i in range(len(images)):
ax = plt.subplot(1, len(images), i+1)
plt.imshow(images[i])
plt.axis("off")
plt.tight_layout()

 

keras_cv,models를 상속하는 class StableDiffusion을 model로 설정하자.

6 model = keras_cv.models.StableDiffusion(img_width=512, img_height=256)

 

그림의 스타일을 지정하는 문구를 잘작성하여 넣은 후 코드를 실행하자.

최초 실행인 경우 서버로부터 binary 파일 형태의 사전학습된 내용을 다운받는 시간이 수분 소요되며 그림 한 장당 1~2분 안에 출력이 이루어진다.

7 images = model.text_to_image("photograph of a castle in the style of Van Gogh's Saint Remy", batch_size=3)
plot_images(images)

 

3번째 그림이 고호풍으로 그려진 그럴듯한 고성 그림임을 인정할 수 밖에 없을 것이다.

 

마지막으로 TensorFlow 버전과 GPU 디바이스를 확인해보자.

8 import tensorflow as tf
print(tf.__version__)
tf.test.gpu_device_name()
------------------------------------------------------------
2.11.0
/device:GPU:0

 

첨부된 파일을 다운받아 Colab에서 실행해보자.