Stable Diffusion は、構築の全プロセスを記録し、独自の芸術的な写真を生成します。

序章

最近、Silicon Star の関係者は AI 画像生成技術を何度も報告しており、DALL・E、Midjourney、DALL・E mini (現在の Craiyon)、Imagen、TikTok AI green screen などの有名な製品について言及しています。

実際、Stable Diffusion は強力な生成機能と幅広い使用の可能性を備えており、モデルはコンシューマ グレードのグラフィックス カードで直接実行でき、生成速度は非常に高速です。そして、その自由でオープンな性質により、AI 画像生成モデルは、業界の少数の人々にとってもはや遊び道具ではなくなります。

強者が雲のように、巨人が続々と登場するAI映像生成の現場には、Stable Diffusionの背後にある“謎”の組織、Stability AIも“アウトサイダーモンク”のように存在する。創業者はあまり知られていないため、創業の経緯や資金調達の詳細は公開されていません。無料でオープンソースの Stable Diffusion のチャリティーと相まって、人々はこの神秘的な AI 研究機関への関心を高めています。

安定拡散入門

AI ビデオ編集技術のスタートアップである Runway の Patrick Esser と、ミュンヘン大学の Machine Vision Learning Group の Robin Romabach の 2 人のプロジェクト開発リーダーがいます。このプロジェクトの技術的基盤は、主に、コンピュータ ビジョン カンファレンス CVPR22 で 2 人の開発者が共同で発表した潜在拡散モデル (潜在拡散モデル) の研究に基づいています。

トレーニングに関しては、モデルは 4,000 枚の A100 グラフィックス カードのクラスターを使用し、1 か月かかりました。トレーニング データは、大規模な AI オープン ネットワーク プロジェクトの下で「美学」に焦点を当てたデータ サブセットである LAION-Aesthetics から取得され、約 59 億の写真とテキストの並列データが含まれます。

トレーニング プロセスの計算能力要件は特に高くなりますが、Stable Diffusion は非常にユーザー フレンドリーです。通常のグラフィック カードで実行でき、ビデオ メモリが 10 GB 未満であっても、高解像度の画像結果を生成できます。数秒で。

拡散モデルをトレーニングして、各ステップでサンプルのノイズを軽く除去する方法を予測し、数回反復した後、結果を取得します。拡散モデルは、画像、音声、3D 形状、グラフ合成などのさまざまな生成タスクに適用されています。

拡散モデルは、次の 2 つのステップで構成されます。

  • Forward Diffusion - 入力データを徐々に摂動することにより、データをノイズにマッピングします。これは、データ サンプルから開始し、単純なガウス拡散カーネルを使用してノイズ サンプルを繰り返し生成する単純な確率的プロセスによって正式に達成されます。このプロセスは、推論ではなくトレーニング中にのみ使用されます。
  • Parametric Backward - 前方拡散を元に戻し、反復ノイズ除去を実行します。このプロセスはデータ合成の略で、ランダム ノイズを実際のデータに変換してデータを生成するようにトレーニングされています。

これは実際には非常に面倒であり、これに基づいて、Stable Diffusion は拡散モデルを構築するためのより効率的な方法を採用しています (モデル ペーパーから)。

ここに画像の説明を挿入

安定拡散モデル構築実績

stable-diffusion-v1-1 環境の準備

v1.1 を後の v1.4 環境と区別する理由は、v1.1 ウェアハウスは単なるテストのように見えるためです. v1.4 の完全なコードはなく、モデルの重量とインストールの難しさはるかに小さいです。

  • sd-v1-1.ckpt: laion2B-en の解像度 256x256 で 237k ステップ。laion-high resolution の解像度 512x512 で 194k ステップ (解像度 >= 1024x1024 の LAION-5B からの 170M の例)。
  • sd-v1-2.ckpt: sd-v1-1.ckpt から再開。laion-aesthetics v2 5+ での解像度 512x512 での 515k ステップ (推定美学スコアが 5.0 を超える laion2B-en のサブセットで、元のサイズが 512x512 以上で、推定透かし確率が 0.5 未満の画像にさらにフィルター処理されます。透かし推定は LAION-5B メタデータからのものであり、審美性スコアは LAION-Aesthetics Predictor V2 を使用して推定されます)。
  • sd-v1-3.ckpt: sd-v1-2.ckpt から再開。「laion-aesthetics v2 5+」で解像度 512x512 で 195,000 ステップ、テキスト条件付けを 10% ドロップして、分類器を使用しないガイダンス サンプリングを改善します。
  • sd-v1-4.ckpt: sd-v1-2.ckpt から再開。「laion-aesthetics v2 5+」での解像度 512x512 での 225k ステップと、分類器を使用しないガイダンス サンプリングを改善するためのテキスト条件付けの 10% の削除。

上記はGithubより、簡単に説明するとsd-v1-1.ckpt1.3Gくらいですsd-v1-4.ckptが 4Gfull-v1.4は7.4Gなので、v1.1環境のインストール手順に入ります。

pip install --upgrade diffusers transformers scipy

そうです、たった一文です。v1.1 環境は v1.4 の簡易版であり、v1.4 は完全版です。

stable-diffusion-v1-4 環境の準備

この問題はもう少しです。外部ネットワークの問題が原因で、一部のパッケージは実際にはインストールが簡単ではありません。私はサーバー上にいるため、はしごを開く方がはるかに速い場合があります。以下は私の記録です。ピットを踏む。

https://github.com/CompVis/stable-diffusion.git
conda env create -f environment.yaml
conda activate ldm

上記のバグは主に 2 番目のステップで発生し、ダウンロード速度が非常に遅くなります。作成者が yaml で設定したチャネルは、pytorch と conda のデフォルト ソースに基づいていますが、明らかに、はしごがないと非常に遅くなるだけでなく、タイムアウトの可能性が大幅に増加します。チャネル アドレスを次のように変更することを検討してください。

name: ldm
channels:
  - http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
  - http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
  - http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/msys2/
  - http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/bioconda/
  - http://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
    # - defaults

Solving environment: failed,ResolvePackageNotFoundこのエラーの意味を分析していませんでしたが、
ここに画像の説明を挿入
おそらく何か矛盾していると感じたので、手動で変更しました、手動で py38 として仮想環境を作成し、パッケージをダウンロードします。CLIPに加えてtaming-transformers、他に問題はありません。

最後の 2 つのパッケージが間違っています error: RPC failed; curl 56 GnuTLS recv error (-54): Error in the pull function.。エラーの解決策は次のとおりですnote: This error originates from a subprocess, and is likely not a problem with pip.
ここに画像の説明を挿入
このエラーの理由は、手動で作成した仮想環境の pip は通常、最新バージョンをインストールするためですが、これら 2 つのパッケージに必要な環境は であるためpip==20.3、 pip バージョンが撤回された後、インストールは成功します。

ハグフェイスのディフュージョンの申し込み資格

まず、Stable Diffusion モデルをダウンロードするには、huggingface にアクセスしてダウンロード契約に同意する必要があります。具体的なリンクは次のとおりです。

stable-diffusion-v1-1:
https://huggingface.co/CompVis/stable-diffusion-v1-1

stable-diffusion-v1-4:
https://huggingface.co/CompVis/stable-diffusion-v1-4

この2つをクリックすると、関連する同意書が最初にポップアップします。おそらく商用目的ではなく、違法行為、xxxxxなどではありませんが、どのように表現すればよいでしょうか。キュービットの記事「安定拡散は非常に人気があったため、アーティストをまとめて、ネチズンの人気科学の背後にある「メカニズムはLeCunに気に入られた」という記事を読んだ後、人気が高すぎるため、商用会社はまだ商用に使用していると思いますか?うーん。. . トピックに戻りますが、契約に同意するためにクリックした後でのみ、サーバー側でダウンロードできます。

サーバー側で次のように入力します。

huggingface-cli login

ログイン インターフェイスがポップアップします。
ここに画像の説明を挿入
次に Web ページに移動して設定を入力します。これは GitHub の操作と同様です。 を選択し、User Access Tokensトークンをコピーし、上記の画像を入力してログインします。そうでない場合はUser Access Tokens、作成してください。
ここに画像の説明を挿入

トークンがログインされると、モデル テストを実行できます。

安定拡散 v1-1 テスト

import torch
from torch import autocast
from diffusers import StableDiffusionPipeline

model_id = "CompVis/stable-diffusion-v1-1"
device = "cuda"


pipe = StableDiffusionPipeline.from_pretrained(model_id, use_auth_token=True)
pipe = pipe.to(device)

prompt = "a photo of an astronaut riding a horse on mars"
with autocast("cuda"):
    image = pipe(prompt, guidance_scale=7.5)["sample"][0]

image.save("astronaut_rides_horse.png")

当然のことながら、棒状のスクロール モデルのダウンロード出力が表示されます。モデルは 1.3G しかありませんが、もうデモはしませんが、私のインターネット速度は少し遅く、v1.4 をダウンロードしました。すでに制限されています。.

もちろん、上記は最もオリジナルなモデルのダウンロード方法にすぎません。さまざまなウェイトをダウンロードする他のオプションがあります。

"""
如果您受到 GPU 内存的限制并且可用的 GPU RAM 少于 10GB,请确保以 float16 精度加载 StableDiffusionPipeline,而不是如上所述的默认 float32 精度。
"""
import torch

pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16, revision="fp16", use_auth_token=True)
pipe = pipe.to(device)

prompt = "a photo of an astronaut riding a horse on mars"
with autocast("cuda"):
    image = pipe(prompt, guidance_scale=7.5)["sample"][0]  
    
image.save("astronaut_rides_horse.png")

"""
要换出噪声调度程序,请将其传递给from_pretrained:
"""
from diffusers import StableDiffusionPipeline, LMSDiscreteScheduler

model_id = "CompVis/stable-diffusion-v1-1"
# Use the K-LMS scheduler here instead
scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
pipe = StableDiffusionPipeline.from_pretrained(model_id, scheduler=scheduler, use_auth_token=True)
pipe = pipe.to("cuda")

prompt = "a photo of an astronaut riding a horse on mars"
with autocast("cuda"):
    image = pipe(prompt, guidance_scale=7.5)["sample"][0]  
    
image.save("astronaut_rides_horse.png")

最後に、ネットワーク速度が非常に悪い場合は、Web ページにアクセスして直接ダウンロードできます。リンクは
https://huggingface.co/CompVis/stable-diffusion-v-1-1-originalです。

安定拡散 v1-4 テスト

1.1 と同様に、最初はモデルのダウンロードです。多くのオプションがあります。1 つずつリストしません。

# make sure you're logged in with `huggingface-cli login`
from torch import autocast
from diffusers import StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained(
        "CompVis/stable-diffusion-v1-4",
        use_auth_token=True
).to("cuda")

prompt = "a photo of an astronaut riding a horse on mars"
with autocast("cuda"):
    image = pipe(prompt)["sample"][0]

image.save("astronaut_rides_horse.png")


# device = "cuda"
# model_path = "CompVis/stable-diffusion-v1-4"
# 
# # Using DDIMScheduler as anexample,this also works with PNDMScheduler
# # uncomment this line if you want to use it.
# 
# # scheduler = PNDMScheduler.from_config(model_path, subfolder="scheduler", use_auth_token=True)
# 
# scheduler = DDIMScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", clip_sample=False, set_alpha_to_one=False)
# pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
#     model_path,
#     scheduler=scheduler,
#     revision="fp16", 
#     torch_dtype=torch.float16,
#     use_auth_token=True
# ).to(device)

上記の初期ダウンロード方法を使用しました。デフォルトは32ビットで、他のパラメーターは変更されていません。つまり、4Gモデル以上をダウンロードする必要があります。途中で数回切断され、そのたびにはxxxxと同じで、ネットワークが良くないと非常に不快です
ここに画像の説明を挿入
幸いなことに、ダウンロードはまだ完了しています. ダウンロード後は、pytorch のモデル ライブラリと同じです. ストレージ パスは次のとおりです。

ここに画像の説明を挿入
現在のディレクトリは、プロンプトの言葉に似た内容の画像を生成します。
写真の説明を追加してください
かなりコミカルに感じます。また、上記の待ち時間に両手で準備をして、公式サイトから直接モデルをダウンロードしたので、念のため10,000も怖くないです。アドレスは https://huggingface.co/CompVis/stable-diffusion-v-1-4-original/blob/main/sd-v1-4.ckpt です。
ここに画像の説明を挿入

いずれにせよ, それが使用できる限り, テキストから画像へのテキストルーチンをテストすることができます. ここで私は自分で2つ書きました. さらに, モデルメソッドのプロンプトと実行コマンドを参照します – Stable Diffusion ,なぜなら全体的に書かれているような気がします。例は次のとおりです。

python txt2img.py --prompt "Asia girl, glossy eyes, face, long hair, fantasy, elegant, highly detailed, digital painting, artstation, concept art, smooth, illustration, renaissance, flowy, melting, round moons, rich clouds, very detailed, volumetric light, mist, fine art, textured oil over canvas, epic fantasy art, very colorful, ornate intricate scales, fractal gems, 8 k, hyper realistic, high contrast" 
                  --plms 
                  --outdir ./output/
                  --ckpt ./models/sd-v1-4.ckpt 
                  --ddim_steps 100 
                  --H 512 
                  --W 512 
                  --seed 8

ここでは見栄えを良くするためにパラメータを改行しています. 直接実行する場合は改行を削除してください. パラメータの説明はGitHubで直接見ることができます. 難しすぎるパラメータ設定はありません. ターミナルの実行後、HardNet モデルをダウンロードする必要があります。
ここに画像の説明を挿入
ダウンロード後、結果を取得できます。画像は次のとおりです。
ここに画像の説明を挿入

先ほど書いたパラメーターのグループが他に 2 つあります。

prompt = "women, pink hair, ArtStation, on the ground, open jacket, video game art, digital painting, digital art, video game girls, sitting, game art, artwork"

prompt = "fantasy art, women, ArtStation, fantasy girl, artwork, closed eyes, long hair. 4K, Alec Tucker, pipes, fantasy city, fantasy art, ArtStation"

ここに画像の説明を挿入

何か変なのが混じってるような?ええと、なぜそれが出てきたのかわかりません。. .

これはテキストから画像への変換の使用例であり、別の種類の画像、起動方法は次のとおりです。

python img2img.py --prompt "magic fashion girl portrait, glossy eyes, face, long hair, fantasy, intricate, elegant, highly detailed, digital painting, artstation, concept art, smooth, sharp focus, illustration, renaissance, flowy, melting, round moons, rich clouds, very detailed, volumetric light, mist, fine art, textured oil over canvas, epic fantasy art, very colorful, ornate intricate scales, fractal gems, 8 k, hyper realistic, high contrast" 
                          --init-img ./ceshi/33.jpg 
                          --strength 0.8 
                          --outdir ./output/
                          --ckpt ./models/sd-v1-4.ckpt 
                          --ddim_steps 100

当初、デモを実行すればスムーズに終了するだろうと思っていましたが、残念ながらカード リソースが不足しています。わずか数 G のカード スペース (PS: つまり、v1.4 で必要なビデオ メモリ、15G 以上):

    return _VF.einsum(equation, operands)  # type: ignore[attr-defined]
RuntimeError: CUDA out of memory. Tried to allocate 2.44 GiB (GPU 0; 14.75 GiB total capacity; 11.46 GiB already allocated; 1.88 GiB free; 11.75 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

ということで、もう絡まらず、そのまま FP16 の精度に移行し、colab の実験を参考に t4 で成功した人がいると思うので、取り敢えずそのまま移行しますjupyter notebook

パイロットパッケージ:

import inspect
import warnings
from typing import List, Optional, Union

import torch
from torch import autocast
from tqdm.auto import tqdm

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    PNDMScheduler,
    UNet2DConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer

次に、データ パイプラインのソース コードを追加し、事前トレーニング済みの重みモデルをダウンロードして、モデルを次のように指定しますfloat16

class StableDiffusionImg2ImgPipeline(DiffusionPipeline):
    def __init__(
        self,
        vae: AutoencoderKL,
        text_encoder: CLIPTextModel,
        tokenizer: CLIPTokenizer,
        unet: UNet2DConditionModel,
        scheduler: Union[DDIMScheduler, PNDMScheduler],
        safety_checker: StableDiffusionSafetyChecker,
        feature_extractor: CLIPFeatureExtractor,
    ):
        super().__init__()
        scheduler = scheduler.set_format("pt")
        self.register_modules(
            vae=vae,
            text_encoder=text_encoder,
            tokenizer=tokenizer,
            unet=unet,
            scheduler=scheduler,
            safety_checker=safety_checker,
            feature_extractor=feature_extractor,
        )

    @torch.no_grad()
    def __call__(
        self,
        prompt: Union[str, List[str]],
        init_image: torch.FloatTensor,
        strength: float = 0.8,
        num_inference_steps: Optional[int] = 50,
        guidance_scale: Optional[float] = 7.5,
        eta: Optional[float] = 0.0,
        generator: Optional[torch.Generator] = None,
        output_type: Optional[str] = "pil",
    ):

        if isinstance(prompt, str):
            batch_size = 1
        elif isinstance(prompt, list):
            batch_size = len(prompt)
        else:
            raise ValueError(f"`prompt` has to be of type `str` or `list` but is {
      
      type(prompt)}")

        if strength < 0 or strength > 1:
          raise ValueError(f'The value of strength should in [0.0, 1.0] but is {
      
      strength}')

        # set timesteps
        accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
        extra_set_kwargs = {
    
    }
        offset = 0
        if accepts_offset:
            offset = 1
            extra_set_kwargs["offset"] = 1

        self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)

        # encode the init image into latents and scale the latents
        init_latents = self.vae.encode(init_image.to(self.device)).sample()
        init_latents = 0.18215 * init_latents

        # prepare init_latents noise to latents
        init_latents = torch.cat([init_latents] * batch_size)
        
        # get the original timestep using init_timestep
        init_timestep = int(num_inference_steps * strength) + offset
        init_timestep = min(init_timestep, num_inference_steps)
        timesteps = self.scheduler.timesteps[-init_timestep]
        timesteps = torch.tensor([timesteps] * batch_size, dtype=torch.long, device=self.device)
        
        # add noise to latents using the timesteps
        noise = torch.randn(init_latents.shape, generator=generator, device=self.device)
        init_latents = self.scheduler.add_noise(init_latents, noise, timesteps)

        # get prompt text embeddings
        text_input = self.tokenizer(
            prompt,
            padding="max_length",
            max_length=self.tokenizer.model_max_length,
            truncation=True,
            return_tensors="pt",
        )
        text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]

        # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
        # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
        # corresponds to doing no classifier free guidance.
        do_classifier_free_guidance = guidance_scale > 1.0
        # get unconditional embeddings for classifier free guidance
        if do_classifier_free_guidance:
            max_length = text_input.input_ids.shape[-1]
            uncond_input = self.tokenizer(
                [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
            )
            uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]

            # For classifier free guidance, we need to do two forward passes.
            # Here we concatenate the unconditional and text embeddings into a single batch
            # to avoid doing two forward passes
            text_embeddings = torch.cat([uncond_embeddings, text_embeddings])


        # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
        # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
        # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
        # and should be between [0, 1]
        accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
        extra_step_kwargs = {
    
    }
        if accepts_eta:
            extra_step_kwargs["eta"] = eta

        latents = init_latents
        t_start = max(num_inference_steps - init_timestep + offset, 0)
        for i, t in tqdm(enumerate(self.scheduler.timesteps[t_start:])):
            # expand the latents if we are doing classifier free guidance
            latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents

            # predict the noise residual
            noise_pred = self.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)

            # compute the previous noisy sample x_t -> x_t-1
            latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs)["prev_sample"]

        # scale and decode the image latents with vae
        latents = 1 / 0.18215 * latents
        image = self.vae.decode(latents)

        image = (image / 2 + 0.5).clamp(0, 1)
        image = image.cpu().permute(0, 2, 3, 1).numpy()

        # run safety checker
        safety_cheker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(self.device)
        image, has_nsfw_concept = self.safety_checker(images=image, clip_input=safety_cheker_input.pixel_values)

        if output_type == "pil":
            image = self.numpy_to_pil(image)

        return {
    
    "sample": image, "nsfw_content_detected": has_nsfw_concept}

device = "cuda"
model_path = "CompVis/stable-diffusion-v1-4"

# Using DDIMScheduler as anexample,this also works with PNDMScheduler
# uncomment this line if you want to use it.

# scheduler = PNDMScheduler.from_config(model_path, subfolder="scheduler", use_auth_token=True)

scheduler = DDIMScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", clip_sample=False, set_alpha_to_one=False)
pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
    model_path,
    scheduler=scheduler,
    revision="fp16", 
    torch_dtype=torch.float16,
    use_auth_token=True
).to(device)

おそらく、ここには 3G モデルに近いものもあり、エラーが発生しなくなったら、イメージをロードして前処理し、パイプラインに渡すことができるようにします。最初に、テスト用の公式マップを選択できます。

前処理:

import PIL
from PIL import Image
import numpy as np

def preprocess(image):
    w, h = image.size
    w, h = map(lambda x: x - x % 32, (w, h))  # resize to integer multiple of 32
    image = image.resize((w, h), resample=PIL.Image.LANCZOS)
    image = np.array(image).astype(np.float32) / 255.0
    image = image[None].transpose(0, 3, 1, 2)
    image = torch.from_numpy(image)
    return 2.*image - 1.

公式マップをロードします。手動でダウンロードしてアップロードするか、ネットワーク リクエストに直接アクセスできます。

import requests
from io import BytesIO

url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"

response = requests.get(url)
init_img = Image.open(BytesIO(response.content)).convert("RGB")
init_img = init_img.resize((768, 512))
init_img

ここに画像の説明を挿入
最後に、プロンプトをロードしてパイプラインにロードし、GitHub と同じ効果を得ます。

init_image = preprocess(init_img)

prompt = "A fantasy landscape, trending on artstation"

generator = torch.Generator(device=device).manual_seed(1024)
with autocast("cuda"):
    images = pipe(prompt=prompt, init_image=init_image, strength=0.75, guidance_scale=7.5, generator=generator)["sample"]

しかし、ここに追加したのは別のエントリです。

prompt = "Anime, Comic, pink hair, ArtStation, on the ground,cartoon, Game "

結果は次のとおりです。
ここに画像の説明を挿入

これは大丈夫そうですが、アニメの画像をいくつかダウンロードしに行って、主にピンクの髪のキーワードで上記のエントリを使用するつもりでした. 、しかし、Sakura + Hui の組み合わせには感銘を受けました)、その結果、上の写真の私の jupyter にはいくつかのコマンド ブロック コードがあり、80 回近く実行され、60 回以上微調整していました。. . Qian ロバのスキルが貧弱で、入力に問題があると感じますが、それだけです。より良い調整作業は次のとおりです。

最初の画像が表示されない場合に表示するテキスト
2番目の画像が表示されていない場合に表示するテキスト

しかし、他の人がオンラインで行ったことを見ると、それは本当に美しいものです。結果から言うと、1つ目は私のモデルの精度が低く選択されていること、2つ目は私の語彙が少し不足していることかもしれません.このユースケースはブログを書きながら調整しています.また、私は他のことで忙しいです.調整が少し面倒ですが、悪くないです。満足です。(PS: 満足できない場合はどうすればよいですか? emmm)

上記の内容は、環境を構築して自分で調整することであり、モデルのパラメーターを自分で手動で調整することと同じであり、目的の方向に進む. 以下では、huggingface とコマーシャルで私がチューニングしたいくつかのオンライン プラットフォームを紹介します。一。

オンラインで安定した拡散を体験

ここでは 2 つのアドレスを推奨します。1 つは公式のテスト アドレスです。

https://huggingface.co/spaces/stabilityai/stable-diffusion

ここに画像の説明を挿入

公式のオンライン展開はAnime, Comic, on the ground,cartoon, Game小さなモデルである必要があり、トレーニングの結果は非常に遅いです。

https://huggingface.co/spaces/huggingface/diffuse-the-rest

ここに画像の説明を挿入
はい、私の絵はまだ非常に写実的です。また、何回か経験してわかったのは、アジアというか、中国を直に言うと、男女問わず、欧米とは見た目が少し違うし、無いのかもしれません。十分な国内データセット。

最後に、次の名前の非オープン ソースstable-diffusion-animationプロジェクトを見つけます。

https://replicate.com/andreasjansson/stable-diffusion-animation

ここに画像の説明を挿入
これはより現実的です. 24 フレームの画像で 20 秒のビデオが作成されました. これはたまたま最も人気のある生物学的起源のビデオと一致しました. このプロジェクトで作成されたかどうかはわかりません. というわけで、このブログはここまでです。

おすすめ

転載: blog.csdn.net/submarineas/article/details/126634227