Buckets:

mishig's picture
|
download
raw
19.6 kB

Apache License, Version 2.0(「ライセンス」)の下でライセンスされています。

このファイルは、ライセンスに準拠した場合にのみ使用できます。

ライセンスのコピーは以下から入手できます

http://www.apache.org/licenses/LICENSE-2.0

適用される法律で要求される場合、または書面による合意がある場合を除き、ソフトウェア

ライセンスに基づき配布される本ソフトウェアは、「現状のまま」

明示的または黙示的を問わず、いかなる種類の保証や条件も付随しません。

権限を管理する特定の言語については、ライセンスを参照してください。

ライセンスの下での制限事項。

-->

GLM-Image

概要

GLM-Image は、ハイブリッドな自己回帰型 + 拡散型デコーダーアーキテクチャを採用した画像生成モデルであり、視覚的忠実度と細部表現の上限を効果的に押し上げています。一般的な画像生成の品質については、業界標準の LDM ベースのアプローチと同等の水準にあり、知識集約型の画像生成シナリオでは顕著な優位性を示しています。

モデルアーキテクチャ: オートレグレッシブ + ディフュージョンデコーダーのハイブリッド設計、

  • 自己回帰型ジェネレーター: GLM-4-9B-0414から初期化された9Bパラメータのモデルで、視覚トークンを組み込むために語彙が拡張されています。モデルはまず約256トークンのコンパクトなエンコーディングを生成し、その後1K〜4Kトークンに展開します。これにより、1K〜2Kの高解像度画像出力に対応します。transformersライブラリのGlmImageForConditionalGenerationクラスでARモデルを確認できます。
  • Diffusion Decoder: 潜在空間での画像デコードに特化した、単一ストリームのDiTアーキテクチャに基づく7Bパラメータのデコーダーです。Glyph Encoderテキストモジュールを備えており、画像内のテキストの正確なレンダリングを大幅に向上させます。

デカップルされた強化学習によるポストトレーニング:このモデルは、GRPOアルゴリズムを用いた細粒度かつモジュール化されたフィードバック戦略を導入し、セマンティック理解と視覚的詳細の品質を大幅に向上させます。

  • 自己回帰モジュール:美観と意味の整合性に焦点を当てた低周波数のフィードバック信号を提供し、指示の追従性と芸術的表現力を向上させます。
  • Decoder モジュール: 詳細の忠実度とテキストの正確さを対象とした高周波フィードバックを提供し、非常にリアルなテクスチャ、ライティング、色再現、そしてより正確なテキストレンダリングを実現します。

GLM-Imageは、単一のモデル内でテキストから画像への生成と画像から画像への生成の両方をサポートしています

  • テキストから画像へ: テキストの説明から高詳細な画像を生成し、情報密度の高いシナリオで特に優れたパフォーマンスを発揮します。
  • Image-to-image: 画像編集、スタイル転写、複数被写体の整合性、人物やオブジェクトのアイデンティティを保持した生成など、幅広いタスクに対応しています。

このパイプラインは zRzRzRzRzRzRzR によって貢献されました。コードベースは こちら で確認できます。

使用例

テキストから画像を生成

import torch
from diffusers.pipelines.glm_image import GlmImagePipeline

pipe = GlmImagePipeline.from_pretrained("zai-org/GLM-Image",dtype=torch.bfloat16,device_map="cuda")
prompt = "A beautifully designed modern food magazine style dessert recipe illustration, themed around a raspberry mousse cake. The overall layout is clean and bright, divided into four main areas: the top left features a bold black title 'Raspberry Mousse Cake Recipe Guide', with a soft-lit close-up photo of the finished cake on the right, showcasing a light pink cake adorned with fresh raspberries and mint leaves; the bottom left contains an ingredient list section, titled 'Ingredients' in a simple font, listing 'Flour 150g', 'Eggs 3', 'Sugar 120g', 'Raspberry puree 200g', 'Gelatin sheets 10g', 'Whipping cream 300ml', and 'Fresh raspberries', each accompanied by minimalist line icons (like a flour bag, eggs, sugar jar, etc.); the bottom right displays four equally sized step boxes, each containing high-definition macro photos and corresponding instructions, arranged from top to bottom as follows: Step 1 shows a whisk whipping white foam (with the instruction 'Whip egg whites to stiff peaks'), Step 2 shows a red-and-white mixture being folded with a spatula (with the instruction 'Gently fold in the puree and batter'), Step 3 shows pink liquid being poured into a round mold (with the instruction 'Pour into mold and chill for 4 hours'), Step 4 shows the finished cake decorated with raspberries and mint leaves (with the instruction 'Decorate with raspberries and mint'); a light brown information bar runs along the bottom edge, with icons on the left representing 'Preparation time: 30 minutes', 'Cooking time: 20 minutes', and 'Servings: 8'. The overall color scheme is dominated by creamy white and light pink, with a subtle paper texture in the background, featuring compact and orderly text and image layout with clear information hierarchy."
image = pipe(
    prompt=prompt,
    height=32 * 32,
    width=36 * 32,
    num_inference_steps=30,
    guidance_scale=1.5,
    generator=torch.Generator(device="cuda").manual_seed(42),  # or "mps", "xpu", "cpu"
).images[0]

image.save("output_t2i.png")

画像から画像への生成

import torch
from diffusers.pipelines.glm_image import GlmImagePipeline
from PIL import Image

pipe = GlmImagePipeline.from_pretrained("zai-org/GLM-Image",dtype=torch.bfloat16,device_map="cuda")
image_path = "cond.jpg" 
prompt = "Replace the background of the snow forest with an underground station featuring an automatic escalator."
image = Image.open(image_path).convert("RGB")
image = pipe(
    prompt=prompt,
    image=[image], # can input multiple images for multi-image-to-image generation such as [image, image1]
    height=33 * 32,
    width=32 * 32,
    num_inference_steps=30,
    guidance_scale=1.5,
    generator=torch.Generator(device="cuda").manual_seed(42),  # or "mps", "xpu", "cpu"
).images[0]

image.save("output_i2i.png")
  • GLM-Imageで使用されるARモデルは、デフォルトでdo_sample=Trueおよび温度0.95に設定されているため、実行ごとに生成される画像が大きく異なる場合があります。ARモデルから誤った出力や劣化した出力が得られる可能性があるため、do_sample=Falseを設定することは推奨されません。

GlmImagePipeline[[diffusers.GlmImagePipeline]]

diffusers.GlmImagePipeline[[diffusers.GlmImagePipeline]]

diffusers.GlmImagePipeline(tokenizer: ByT5Tokenizer, processor: GlmImageProcessor, text_encoder: T5EncoderModel, vision_language_encoder: GlmImageForConditionalGeneration, vae: AutoencoderKL, transformer: GlmImageTransformer2DModel, scheduler: FlowMatchEulerDiscreteScheduler)

ソース

パラメータ:

tokenizer (PreTrainedTokenizer) : テキストエンコーダー用のトークナイザー。

processor (AutoProcessor) : ARモデルのチャットテンプレートとトークナイズ処理を扱うプロセッサ。

text_encoder (T5EncoderModel) : グリフ埋め込み用の凍結されたテキストエンコーダー。

vision_language_encoder (GlmImageForConditionalGeneration) : テキストプロンプトから画像トークンを生成する AR モデル。

vae (AutoencoderKL) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデル。

transformer (GlmImageTransformer2DModel) : 符号化された画像潜在変数をノイズ除去するための、テキスト条件付きの Transformer (DiT)。

scheduler (SchedulerMixin) : transformer と組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。

GLM-Image を使用したテキストから画像への生成を行う Pipeline。

このパイプラインは、トークン生成用のAR(自己回帰)モデルと、画像デコード用のDiT(拡散トランスフォーマー)モデルの両方を統合しています。

call[[diffusers.GlmImagePipeline.call]]

__call__(prompt: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list[int] | None = None, sigmas: list[float] | None = None, guidance_scale: float = 1.5, num_images_per_prompt: int = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prior_token_ids: typing.Optional[torch.Tensor] = None, prior_token_image_ids: list[torch.Tensor] | None = None, source_image_grid_thw: list[torch.Tensor] | None = None, crops_coords_top_left: tuple[int, int] = (0, 0), output_type: str = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int, dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 2048)

ソース

パラメータ:

prompt (str または list[str]、任意) : 画像生成をガイドするためのプロンプトまたはプロンプトのリストです。'H W' の形式で形状情報を含める必要があります。ここで H と W はトークンの次元 (d32) です。例: "A beautiful sunset36 24" は 1152x768 の画像を生成します。

image : 画像から画像への生成に使用する任意の条件画像。

height (int、任意) : ピクセル単位の縦幅。指定しない場合、プロンプトの形状情報から導出されます。

width (int、任意) : ピクセル単位の幅。指定しない場合、プロンプトの形状情報から導出されます。

num_inference_steps (int、任意、デフォルトは50) : DiT のデノイジングステップ数。

timesteps (list[int]、任意) : デノイジングプロセスに使用するカスタムタイムステップ。定義されていない場合、num_inference_steps に対するスケジューラのデフォルトスケジュールが使用されます。

sigmas (list[float], 任意) : 去噪プロセスで使用するためのカスタムシグマ。未定義の場合、スケジューラのデフォルトスケジュールが使用されます。

guidance_scale (float、任意、デフォルトは1.5) : classifier-free guidanceのガイダンススケール。

num_images_per_prompt (int、任意、デフォルトは1) : プロンプトごとに生成する画像の数。

generator (torch.Generator, 任意) : 再現性のために使用する乱数ジェネレーター。

latents (torch.Tensor, 任意) : 画像生成の入力として使用する、事前生成されたノイズ付き潜在変数。

prompt_embeds (torch.Tensor, 任意) : 事前に生成されたテキスト埋め込み。指定しない場合、promptから埋め込みが生成されます。

negative_prompt_embeds (torch.Tensor, 任意) : 事前生成されたネガティブテキスト埋め込み。classifier-free guidance が有効な場合に使用されます。

prior_token_ids (torch.Tensor, 任意) : generate_prior_tokens によって事前生成されたトークン ID です。指定された場合、事前生成はスキップされます。

prior_token_image_ids (list[torch.Tensor], 任意) : prior_token_idsに関連付けられた画像トークンIDです。

source_image_grid_thw (list[torch.Tensor]、任意) : ソース画像トークンごとの THW グリッド情報。

crops_coords_top_left (tuple[int, int]、任意、デフォルトは(0, 0)) : 条件付け埋め込みに使用されるクロップの左上座標。

output_type (str、任意、デフォルトは "pil") : 出力形式: "pil"、"np"、または "latent"。

return_dict (bool、任意、デフォルトは True) : プレーンなタプルではなく GlmImagePipelineOutput を返すかどうか。

attention_kwargs (dict, 任意) : 指定された場合、AttentionProcessor に渡される kwargs の辞書です。

callback_on_step_end (Callable、PipelineCallback、MultiPipelineCallbacks、任意) : 各デノイジングステップの終了時に呼び出される関数。

callback_on_step_end_tensor_inputs (list[str]、任意) : callback_on_step_end に渡される Tensor 入力。

max_sequence_length (int、任意、デフォルトは2048) : テキストエンコーダーの最大シーケンス長。

戻り値: GlmImagePipelineOutput または tuple

生成された画像。

生成用のパイプラインを呼び出したときに実行される関数。

例:

>>> import torch
>>> from diffusers import GlmImagePipeline

>>> pipe = GlmImagePipeline.from_pretrained("zai-org/GLM-Image", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> prompt = "A photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt).images[0]
>>> image.save("output.png")

encode_prompt[[diffusers.GlmImagePipeline.encode_prompt]]

encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None, max_sequence_length: int = 2048)

ソース

パラメータ:

prompt (str または list[str]、省略可能) : エンコードするプロンプト

do_classifier_free_guidance (bool、任意、デフォルトはTrue) : classifier free guidance を使用するかどうか。

num_images_per_prompt (int、optional、デフォルトは 1) : プロンプトごとに生成すべき画像の数。結果の埋め込みを配置する torch デバイス

prompt_embeds (torch.Tensor, 任意) : 事前生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。

device : (torch.device, 任意): torch デバイス

dtype : (torch.dtype, 任意): torch dtype

max_sequence_length (int、デフォルトは2048) : エンコードされたプロンプトの最大シーケンス長です。他の値に設定することも可能ですが、結果の品質が低下する可能性があります。

プロンプトをテキストエンコーダーの隠れ状態にエンコードします。

generate_prior_tokens[[diffusers.GlmImagePipeline.generate_prior_tokens]]

generate_prior_tokens(prompt: str | list[str], height: int, width: int, image: list[list[PIL.Image.Image]] | None = None, device: typing.Optional[torch.device] = None, generator: typing.Optional[torch.Generator] = None)

ソース

パラメータ:

prompt : 単一のプロンプトまたはプロンプトのリスト

height : ターゲット画像の高さ

width : ターゲット画像の幅

image : List[List[PIL.Image]] 形式の正規化された画像入力。このメソッドを呼び出す前に、_validate_and_normalize_images() を使用して事前検証を行う必要があります。

device : ターゲットデバイス

generator : 再現性のための乱数生成器

戻り値: Tuple of

  • prior_token_ids: 上サンプリングされた先行トークンを含む、形状が (batch_size, num_tokens) の Tensor
  • prior_token_image_ids_per_sample: テンソルのリストで、サンプルごとに1つ含まれます。各テンソルには、そのサンプルのすべての条件画像に対するアップサンプリングされた prior トークン ID が含まれます。t2i の場合は None です。
  • source_image_grid_thw_per_sample: 各サンプルに対応するテンソルのリスト。各テンソルの形状は (num_condition_images, 3) で、アップサンプリングされたグリッド情報を持ちます。t2i の場合は None です。

ARモデルを使用して、DiTモデルの先行トークンを生成します。

get_glyph_texts[[diffusers.GlmImagePipeline.get_glyph_texts]]

get_glyph_texts(prompt)

ソース

プロンプトからグリフのテキストを抽出します。バッチ処理のためにリストのリストを返します。

GlmImagePipelineOutput[[diffusers.pipelines.glm_image.pipeline_output.GlmImagePipelineOutput]]

diffusers.pipelines.glm_image.pipeline_output.GlmImagePipelineOutput[[diffusers.pipelines.glm_image.pipeline_output.GlmImagePipelineOutput]]

diffusers.pipelines.glm_image.pipeline_output.GlmImagePipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray)

ソース

パラメータ:

images (List[PIL.Image.Image] または np.ndarray) : 長さ batch_size のデノイズ済み PIL イメージのリスト、または形状 (batch_size, height, width, num_channels) の numpy 配列。PIL イメージまたは numpy 配列には、拡散パイプラインのデノイズ済みイメージが含まれます。

CogView3 パイプライン用の出力クラスです。

Xet Storage Details

Size:
19.6 kB
·
Xet hash:
4497719264dcb7869c8fa7436664b30f92e68463aafa8a71b28044a1e526b453

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.