2024.05.14 Diffusion 代碼學習筆記

配環境

我個人用的是Geowizard的環境:https://github.com/fuxiao0719/GeoWizard。

出于方便考慮,用的pytorch官方的docker容器,因此python版本(3.10)和原作者(3.9)不同,其余都是一樣的。

https://hub.docker.com/r/pytorch/pytorch/tags?page=&page_size=&ordering=&name=2.0.1

安裝的時候,把requirements.txt 里面開頭的torch和torchvision刪掉就行了(因為我們的docker容器里已經有了,版本也是一樣的)。

如果遇到以下兩個報錯可以這樣解決:
apt install libgl1-mesa-glx # ImportError: libGL.so.1: cannot open shared object file: No such file or dir
apt-get install libxrender1 # ImportError: libXrender.so.1: cannot open shared object file: No such file or directory

hugging face的下載問題

把原網站換成鏡像,不然下不下來。
pip install -U huggingface_hub
export HF_ENDPOINT=https://hf-mirror.com

入門學習

網站

就用這個網站的tutorial就行:
https://huggingface.co/docs/diffusers/tutorials

打不開的話看這個鏡像:把huggingface.co換成hf-mirror.com即可
https://hf-mirror.com/docs/diffusers/tutorials/autopipeline
注意,沒有魔法的話,鏡像中還是無法顯示圖片。但代碼文字都有,所以也可以將就著用了。

學習內容

我看的2024.05.15版本是這些內容:
在這里插入圖片描述

學習建議

  • 我先開始用的還是pycharm。后來感覺還是jupyter notebook方便一點。
  • 每個教程可能會用到不同的stable diffusion模型,比如"stabilityai/stable-diffusion-xl-base-1.0"。 每次下載模型都很大,費時且費存儲空間。
    • 如果只是學習的話,可以試試都用““CompVis/stable-diffusion-v1-4”, 如果報錯了再試試"runwayml/stable-diffusion-v1-5",實在不行再換成教程里的。這樣就不用老下載新模型了
  • 建議先看好所有要學的教程,把里面的模型都load完,然后再一個個仔細看,因為模型下載真的很費時

學習總結

diffusers的用法

  • 簡單的說,可以直接使用一個pipeline。也可以用scheduler和model。

  • model一般包括一個最基本的UNet(輸入current xt和t,輸出predicted noise)

    • 如果是latent diffusion的話還有VAE
    • 如果是text conditioned的話還有tokenlizer和text_encoder
  • 有的scheduler有noise scaler參數,比如這位:
    https://huggingface.co/docs/diffusers/v0.27.2/en/api/schedulers/unipc#diffusers.UniPCMultistepScheduler

  • AutoPipeline就是,指定模型(比如runwayml/stable-diffusion-v1-5)和任務(比如text2img, img2img, 或inpainting),自動給你找到那個pipeline對應的類

  • noise scheduler有一個add_noise方法,大概是下面這樣:

    • 在這里插入圖片描述

其他

  • 這個過程中會下載很多模型或數據集,默認的路徑是:
    ~/.cache/huggingface/hub
  • 可能需要pip install datasets, 下載的路徑還是~/.cache/
  • 如果還沒研究明白怎么把模型上傳到huggingface,可以先把training config里面的push_to_hub設置為False
  • jupyter里面的PIL Image可以直接顯示(運行代碼image即可);pycharm的話可以image.save(‘temp.png’), 然后看這個圖

Understanding pipelines, models and schedulers

代碼例子1:直接使用DDPM的pipeline

from diffusers import DDPMPipelineddpm = DDPMPipeline.from_pretrained("google/ddpm-cat-256", use_safetensors=True).to("cuda")
image = ddpm(num_inference_steps=25).images[0]
image

代碼例子2:分解DDPM的pipeline:先load scheduler 和model,然后使用

from diffusers import DDPMScheduler, UNet2DModelscheduler = DDPMScheduler.from_pretrained("google/ddpm-cat-256")
model = UNet2DModel.from_pretrained("google/ddpm-cat-256", use_safetensors=True).to("cuda")
scheduler.set_timesteps(50)import torchsample_size = model.config.sample_size
noise = torch.randn((1, 3, sample_size, sample_size), device="cuda")input = noisefor t in scheduler.timesteps:with torch.no_grad():noisy_residual = model(input, t).sampleprevious_noisy_sample = scheduler.step(noisy_residual, t, input).prev_sampleinput = previous_noisy_sample
from PIL import Image
import numpy as npimage = (input / 2 + 0.5).clamp(0, 1).squeeze()
image = (image.permute(1, 2, 0) * 255).round().to(torch.uint8).cpu().numpy()
image = Image.fromarray(image)
image

代碼例子2:stable diffusion的inference

https://hf-mirror.com/docs/diffusers/using-diffusers/write_own_pipeline

# https://huggingface.co/docs/diffusers/using-diffusers/write_own_pipelinefrom PIL import Image
import torch
from transformers import CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, UNet2DConditionModel, PNDMScheduler'''Load Stuff'''
vae = AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="vae", use_safetensors=True)
tokenizer = CLIPTokenizer.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="tokenizer")
text_encoder = CLIPTextModel.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="text_encoder", use_safetensors=True
)
unet = UNet2DConditionModel.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="unet", use_safetensors=True
)from diffusers import UniPCMultistepSchedulerscheduler = UniPCMultistepScheduler.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="scheduler")torch_device = "cuda"
vae.to(torch_device)
text_encoder.to(torch_device)
unet.to(torch_device)'''Prepare and process input text'''
prompt = ["a photograph of an astronaut riding a horse"]
# prompt = ["a photograph of the cartoon character SpongeBob SqurePants"]
height = 512  # default height of Stable Diffusion
width = 512  # default width of Stable Diffusion
num_inference_steps = 25  # Number of denoising steps
guidance_scale = 7.5  # Scale for classifier-free guidance
generator = torch.manual_seed(1)  # Seed generator to create the initial latent noise
batch_size = len(prompt)text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt"
)with torch.no_grad():text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]max_length = text_input.input_ids.shape[-1]
uncond_input = tokenizer([""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt")
uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]text_embeddings = torch.cat([uncond_embeddings, text_embeddings])'''Diffuse'''
latents = torch.randn((batch_size, unet.config.in_channels, height // 8, width // 8),generator=generator
).to(torch_device)latents = latents * scheduler.init_noise_sigmafrom tqdm.auto import tqdmscheduler.set_timesteps(num_inference_steps)for t in tqdm(scheduler.timesteps):# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.latent_model_input = torch.cat([latents] * 2)latent_model_input = scheduler.scale_model_input(latent_model_input, timestep=t)# predict the noise residualwith torch.no_grad():noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample# perform guidancenoise_pred_uncond, noise_pred_text = noise_pred.chunk(2)noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)# compute the previous noisy sample x_t -> x_t-1latents = scheduler.step(noise_pred, t, latents).prev_sample'''Decode the image: latent to rgb'''
# scale and decode the image latents with vae
latents = 1 / 0.18215 * latents
with torch.no_grad():image = vae.decode(latents).sample
image = (image / 2 + 0.5).clamp(0, 1).squeeze()
image = (image.permute(1, 2, 0) * 255).to(torch.uint8).cpu().numpy()
image = Image.fromarray(image)
image.save('temp.png')

結果

下面是我seed為0和1分別生成的結果:
prompt:a photograph of an astronaut riding a horse
在這里插入圖片描述

AutoPipeline

task = 'img2img' # text2img, img2img, inpainting
if task == 'text2img':from diffusers import AutoPipelineForText2Imageimport torchpipeline = AutoPipelineForText2Image.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16, use_safetensors=True).to("cuda")prompt = "peasant and dragon combat, wood cutting style, viking era, bevel with rune"image = pipeline(prompt, num_inference_steps=25).images[0]image.save('temp.png')if task == 'img2img':from diffusers import AutoPipelineForImage2Imageimport torchimport requestsfrom PIL import Imagefrom io import BytesIOpipeline = AutoPipelineForImage2Image.from_pretrained("runwayml/stable-diffusion-v1-5",torch_dtype=torch.float16,use_safetensors=True,).to("cuda")prompt = "a portrait of a dog wearing a pearl earring"url = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/1665_Girl_with_a_Pearl_Earring.jpg/800px-1665_Girl_with_a_Pearl_Earring.jpg"response = requests.get(url)image = Image.open(BytesIO(response.content)).convert("RGB")image.thumbnail((768, 768))image.save('1665_Girl_with_a_Pearl_Earring.png')image = pipeline(prompt, image, num_inference_steps=200, strength=0.75, guidance_scale=10.5).images[0]image.save('temp.png')if task == 'inpainting':from diffusers import AutoPipelineForInpaintingfrom diffusers.utils import load_imageimport torchpipeline = AutoPipelineForInpainting.from_pretrained(# "stabilityai/stable-diffusion-xl-base-1.0","runwayml/stable-diffusion-v1-5",torch_dtype=torch.float16, use_safetensors=True).to("cuda")img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"init_image = load_image(img_url).convert("RGB")mask_image = load_image(mask_url).convert("RGB")init_image.save('init.png')mask_image.save('mask_image.png')prompt = "A majestic tiger sitting on a bench"image = pipeline(prompt, image=init_image, mask_image=mask_image, num_inference_steps=50, strength=0.80).images[0]image.save('temp.png')

結果

img2img: a portrait of a dog wearing a pearl earring
在這里插入圖片描述

inpainiting的結果:A majestic tiger sitting on a bench
在這里插入圖片描述

如果是隨機mask來inpaint的結果:(注意,黑色是要保留的)
在這里插入圖片描述

train a diffusion model

參考這個網站:
https://hf-mirror.com/docs/diffusers/tutorials/basic_training

注意,如果開頭的config里面push_to_hub設置為True的話,則需要改一下hub_model_id, 同時需要前面的

from huggingface_hub import notebook_login
notebook_login()

我試了一下有點問題,就直接設置為false了。

建議先把trianing跑完了,再仔細看trianing的代碼.

核心代碼:

for step, batch in enumerate(train_dataloader):clean_images = batch["images"]# Sample noise to add to the imagesnoise = torch.randn(clean_images.shape, device=clean_images.device)bs = clean_images.shape[0]# Sample a random timestep for each imagetimesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bs,), device=clean_images.device,dtype=torch.int64)# Add noise to the clean images according to the noise magnitude at each timestep# (this is the forward diffusion process)noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps)with accelerator.accumulate(model):# Predict the noise residualnoise_pred = model(noisy_images, timesteps, return_dict=False)[0]loss = F.mse_loss(noise_pred, noise)accelerator.backward(loss)accelerator.clip_grad_norm_(model.parameters(), 1.0)optimizer.step()lr_scheduler.step()optimizer.zero_grad()progress_bar.update(1)logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step}progress_bar.set_postfix(**logs)accelerator.log(logs, step=global_step)global_step += 1

結果:
在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/13125.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/13125.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/13125.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

一文說通用戶故事點數是什么?

一文說通用戶故事點數是什么? 第26期:一文說通用戶故事點數是什么? 用戶故事點數是一種采用相對估算法進行估算的一種工具,一般采用斐波那契數列表征用戶故事里說的大小,采用0 1 2 3 5 8 13這樣的一些數字來表征用戶…

【漏洞復現】Secnet-智能路由系統 actpt_5g.data信息泄露

0x01 產品簡介 Secnet安網智能AC管理系統是廣州安網通信技術有限公司(簡稱“安網通信”)的無線AP管理系統 0x02 漏洞描述 Secnet智能路由系統 acipt 5g.data 接口存在信息泄露漏洞,未經身份驗證的遠程攻擊者可以利用此漏洞獲取系統賬戶名密碼等重要憑據&#xff…

全流程TOUGH系列軟件實踐技術應用

TOUGH系列軟件是由美國勞倫斯伯克利實驗室開發的,旨在解決非飽和帶中地下水、熱運移的通用模擬軟件。和傳統地下水模擬軟件Feflow和Modflow不同,TOUGH系列軟件采用模塊化設計和有限積分差網格剖分方法,通過配合不同狀態方程(EOS模…

永磁同步電機的脈振高頻注入無速度傳感器simulink仿真模型

整理了永磁同步電機的脈振高頻注入無速度傳感器simulink仿真模型,該模型高頻注入仿真pmsm,無感控制,解決0速轉矩輸出問題,插入式永磁同步電機,凸極,高頻注入。MATLAB/simulink仿真,適合研究學習…

騰訊開源混元DiT文生圖模型,消費級單卡可推理

節前,我們組織了一場算法崗技術&面試討論會,邀請了一些互聯網大廠朋友、今年參加社招和校招面試的同學。 針對大模型技術趨勢、大模型落地項目經驗分享、新手如何入門算法崗、該如何準備面試攻略、面試常考點等熱門話題進行了深入的討論。 總結鏈接…

第七十八章 IIS 技術說明

文章目錄 第七十八章 IIS 技術說明IIS 應用程序池和Web Gardens應用程序池Web Gardens 應用程序池、Web花園和CSP 第七十八章 IIS 技術說明 對于那些有興趣使用 IIS 的人,此頁面介紹了應用程序池、網絡花園和位數。 IIS 應用程序池和Web Gardens 應用程序池 應用…

【AI+漫畫】程序員小李解決疑難雜癥BUG的日常

周末花了點時間制作的AI漫畫。 感慨一句,程序人生, 相伴隨行。 原文鏈接:【AI漫畫】程序員小李解決疑難雜癥BUG的日常

一物一碼數字化營銷進軍調味品行業,五豐黎紅“星廚俱樂部”火啦!

近日,由五豐黎紅聯合納寶科技精心打造的小程序“星廚俱樂部”火啦!一經上線就吸引了大量用戶注冊和參與,可以說取得了非常成功的市場反饋,那究竟是一個什么樣的小程序,竟然有這么大的吸引力呢? 介紹小程序之…

武漢星起航:中國賣家借力亞馬遜跨境電商平臺,拓展全球銷售市場

隨著互聯網技術的飛速發展,跨境電商已成為連接全球消費者與賣家的重要橋梁。作為全球領先的跨境電商平臺,亞馬遜憑借其強大的品牌影響力、豐富的商品資源和高效的物流體系,為全球消費者提供了一個便捷、安全的購物環境。在這個平臺上&#xf…

連鎖收銀系統如何助力實體門店私域運營

作為實體門店,私域運營是提升客戶黏性和增加復購率的重要策略之一。而連鎖收銀系統在私域運營中扮演了關鍵的角色,它不僅可以幫助門店管理客戶信息和消費記錄,還能夠通過數據分析和營銷功能提供個性化的服務和推廣活動。下面看看連鎖收銀系統…

能源能耗管理系統

隨著全球對綠色、低碳、可持續發展理念的深入認識,企業對于能源的管理和節能降耗的需求日益迫切。在這一背景下,HiWoo Cloud平臺憑借其先進的能源能耗管理系統,為企業提供了一套高效、智能的解決方案,助力企業實現綠色節能&#x…

InfiniGate自研網關實現五

17.核心通信組件管理和處理服務映射 引入模塊api-gateway-core 到 api-gateway-assist 中進行創建和使用,并拉取自注冊中心的映射信息注冊到本地的網關通信組件中。 第17節是在第15節的基礎上繼續完善服務發現的相關功能,把從注冊中心拉取的網關映射信…

GPT3.5與GPT4.0的差別對比

隨著人工智能技術的飛速發展,GPT系列模型已成為自然語言處理(NLP)領域的翹楚。GPT3.5和GPT4.0作為這一系列的最新成員,各自在性能和應用上都有所突破。 GPT4.0預計將擁有數千億個參數,與前代GPT3.5相比,模…

ZYNQ之嵌入式驅動開發——字符設備驅動

文章目錄 Linux驅動程序分類Linux應用程序和驅動程序的關系簡單的測試驅動程序在petalinux中添加LED驅動新字符設備驅動 Linux驅動程序分類 驅動程序分為字符設備驅動、塊設備驅動和網絡設備驅動。 字符設備是按字節訪問的設備,比如以一個字節收發數據的串口&#…

軟信天成:業務流程管理驅動企業數字化轉型

近日,在國家發展改革委辦公廳、國家數據局綜合司聯合印發的《數字經濟2024年工作要點》中,明確強調了本年度大力推進重點領域數字化轉型,營造數字化轉型生態的戰略舉措,標志著國家對于企業數字化轉型的高度重視與積極倡導。 企業…

dubbo復習:(3) 服務超時時間配置

在dubbo admin中 可以進行類似如下配置 configVersion: v2.7 enabled: true configs:- side: consumeraddresses:- 0.0.0.0parameters:timeout: 55這樣配置之后,當服務端響應超過55毫秒時,在服務消費者的控制臺就會看到超時信息

(保姆級教程傻瓜式操作)樹莓派--基于opencv實現人臉識別

前言 因為當時沒有邊實驗邊記錄,所以這篇文章可能存在疏漏。不過很多地方我推薦了我參考過的博客或者視頻,希望盡可能地解答您的疑惑,如果您仍有不懂的地方,歡迎評論,如果我知道答案,我會很樂意為您解答。 …

私活更好用:SpringBoot開源項目!!【送源碼】

今天分享一款非常香的SpringBoot大屏開源項目,非常適合接私活用。 這是一款基于SpringBoot代碼生成器的快速開發平臺!采用前后端分離架構:SpringBoot,Mybatis,Shiro,JWT,Vue&Ant Design。強…

MQTT_介紹_1.1

歷史 1999年:MQTT最初由IBM的Andy Stanford-Clark和Cirrus Link的Arlen Nipper開發,用于滿足石油和天然氣公司在遠程地區監控設備的需求。 2006年:IBM發布了MQTT的最初開源實現,但此時MQTT并未獲得廣泛的關注。 2010年&#xff…

三大平臺直播視頻下載保存方法

終于解決了視頻號下載的問題,2024年5月15日親測可用。 而且免費。 教程第二部分,有本地電腦無法下載的解決方案。 第一部分:使用教程(正常) 第1步:下載安裝包 下載迅雷網盤搜索:大海福利合集…