Diffusers documentation

GLM-Image

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.43.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

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

class diffusers.GlmImagePipeline

< >

( tokenizer: ByT5Tokenizerprocessor: GlmImageProcessortext_encoder: T5EncoderModelvision_language_encoder: GlmImageForConditionalGenerationvae: AutoencoderKLtransformer: GlmImageTransformer2DModelscheduler: FlowMatchEulerDiscreteScheduler )

パラメータ

  • tokenizer (PreTrainedTokenizer) — テキストエンコーダー用のトークナイザー。
  • processor (AutoProcessor) — ARモデル用のプロセッサ。チャットテンプレートとトークン化を処理します。
  • text_encoder (T5EncoderModel) — グリフ埋め込み用の凍結されたテキストエンコーダー。
  • vision_language_encoder (GlmImageForConditionalGeneration) — テキストプロンプトから画像トークンを生成する AR モデルです。
  • vae (AutoencoderKL) — 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ (VAE) モデル。
  • transformer (GlmImageTransformer2DModel) — エンコードされた画像の潜在変数(latents)をデノイズするための、テキスト条件付きの transformer(DiT)。
  • scheduler (SchedulerMixin) — transformer と組み合わせて、エンコードされた画像の潜在変数(latents)のノイズ除去を行うために使用するスケジューラ。

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

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

__call__

< >

( prompt: str | list[str] | None = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50timesteps: list[int] | None = Nonesigmas: list[float] | None = Noneguidance_scale: float = 1.5num_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneprior_token_ids: typing.Optional[torch.Tensor] = Noneprior_token_image_ids: list[torch.Tensor] | None = Nonesource_image_grid_thw: list[torch.Tensor] | None = Nonecrops_coords_top_left: tuple[int, int] = (0, 0)output_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Union[typing.Callable[[int, int, dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 2048 ) → GlmImagePipelineOutput or tuple

パラメータ

  • prompt (str または list[str]、省略可能) — 画像生成をガイドするためのプロンプトです。H と W がトークン次元 (d32) である形式 ’<sop>H W<eop>’ で形状情報を含む必要があります。例: “A beautiful sunset<sop>36 24<eop>” は 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 に渡されるテンソル入力。
  • 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

< >

( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonedevice: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = Nonemax_sequence_length: int = 2048 )

パラメータ

  • prompt (str または list[str]、省略可能) — エンコードするプロンプト
  • do_classifier_free_guidance (bool、任意、デフォルトは True) — classifier free guidance を使用するかどうかを指定します。
  • num_images_per_prompt (int、任意、デフォルトは 1)— プロンプトごとに生成する画像の数。結果の埋め込みを配置する torch デバイス
  • prompt_embeds (torch.Tensor, 任意) — 事前に生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。
  • device — (torch.device、任意): torch デバイス
  • dtype — (torch.dtype、省略可): torch の dtype
  • max_sequence_length (int、デフォルトは 2048) — エンコードされたプロンプトの最大シーケンス長です。他の値に設定することも可能ですが、結果の品質が低下する可能性があります。

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

generate_prior_tokens

< >

( prompt: str | list[str]height: intwidth: intimage: list[list[PIL.Image.Image]] | None = Nonedevice: typing.Optional[torch.device] = Nonegenerator: typing.Optional[torch.Generator] = None ) → Tuple of

パラメータ

  • prompt — 単一のプロンプトまたはプロンプトのリスト
  • height — 対象画像の高さ
  • width — 対象画像の幅
  • image — List[List[PIL.Image]] 形式の正規化された画像入力。このメソッドを呼び出す前に、_validate_and_normalize_images() を使用して事前検証を行う必要があります。
  • device — ターゲットデバイス
  • generator — 再現性のために使用する乱数ジェネレーター

戻り値

タプル

  • 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

< >

( prompt )

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

GlmImagePipelineOutput

class 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 パイプライン用の出力クラスです。

Update on GitHub