1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LLMと拡散モデル

1
Last updated at Posted at 2026-01-07

第1章:言語モデル(LLM)における生成制御

LLMの出力は、最終的に数万次元の語彙ベクトルに対する確率分布として計算されます。この「確率の海」から一滴(一つのトークン)を掬い上げるプロセスがサンプリングです。

1.1 分布変形:Temperature(温度 )

Temperatureは、Softmax関数の「鋭敏さ」を物理学の熱力学になぞらえて調整するものです。

  • 数理的な再解釈:
    ロジット を温度 で割ることは、「最大確率とそれ以外の差」をスケーリングすることを意味します。

  • ** (鋭鋭化)**: ロジットの差が強調されます。例えば、Aの確率が60%、Bが30%の時、 にするとAはほぼ100%に張り付きます。これにより、モデルは「最も確実な道」を選び続けます。

  • ** (平滑化)**: ロジットの差が縮小されます。圧倒的な自信がある選択肢であっても、他の選択肢との差が小さくなるため、意外な言葉が選ばれる確率が相対的に上昇します。

  • 実務上の注意点:
    温度を上げすぎると、文脈的にあり得ないトークン(ノイズ)の確率も底上げされるため、出力が「ハルシネーション(幻覚)」や意味不明な記号の羅列に陥りやすくなります。


1.2 支持集合制限:Top-k / Top-p(分布の刈り込み)

これらは、Temperatureが変形させた分布に対し、「候補として認める範囲」を物理的に制限するフィルターです。

Top-k サンプリング(固定数制限)

  • 原理: 確率の高い順に 個のみを残し、残りの確率を強制的に にします。
  • メリット: 計算負荷が一定であり、極端に低い確率のトークンを確実に排除できます。
  • デメリット: 文脈によって「正解に近い候補が1つしかない場合」も「100個ある場合」も、常に 個選んでしまうため、不自然な多様性が生まれることがあります。

Top-p (Nucleus) サンプリング(累積確率制限)

  • 原理: 確率の高い順にトークンを足していき、その合計が に達した時点でカットオフします。
  • 原理のメリット: **「自信がないときほど候補を増やし、自信があるときは絞る」**という動的な制御が可能です。
  • 例:「私は」 の次は多くの動詞が考えられるため候補が広がる。
  • 例:「切磋」 の次は 「琢磨」 がほぼ確定的(累積確率がすぐに に達する)なため、候補が極端に絞られる。

1.3 logit 補正:Penalty 項の付加

ペナルティは、一度生成されたトークンが「二度と(あるいは過剰に)出ないよう」に、ロジットを動的に書き換える操作です。

  • Frequency Penalty(頻度ペナルティ):
    出現回数に応じて重くなる制約です。「同じ単語を何度も使う」という、LLM特有の単調な繰り返し(Repetition)を抑制します。専門用語の過剰な連呼を防ぐのに有効です。
  • Presence Penalty(存在ペナルティ):
    一度でも出現したかどうかが基準です。これを高く設定すると、モデルは「まだ使っていない新しい言葉」を使おうとするため、語彙が豊富になり、話題が広がりやすくなります。
  • 実装による違い:
  • OpenAI方式: ロジットから一定値を減算する。
  • HuggingFace (Repetition Penalty) 方式: ロジットを特定の係数で除算する。この場合、1.0以上を設定すると抑制効果が出ます。

1.4 時間打ち切り:終了条件の仕組み

生成の「出口戦略」を定義します。

  1. Stop Sequences(停止シーケンス):
    推論エンジンがトークンを生成するたびに、指定した文字列と一致するかをチェックします。一致した場合、そのトークンをユーザーに返さずに生成を即時停止します。
  • 応用: Few-shot プロンプトで Example 2: が生成されたら止める、といった構造化データ生成に多用されます。
  1. EOS (End of Sentence) の重要性:
    これは学習データ内の「文章の終わり」を学習した結果出力されるトークンです。もしモデルが EOS を出力するように学習されていなければ、Max Tokens に達するまで無限に話し続けてしまいます。
  2. トークンと文字数の乖離:
    Max Tokens = 100 としても、100文字で止まるとは限りません。日本語の場合、1文字が複数のトークンに分割されることが多いため、文字数換算では想定より短くなる傾向があります(例:1トークン ≒ 0.7〜1文字程度)。
# Program Name: Generation_Control_Sensitivity_Analyzer
# Creation Date: 2026-01-08
# Purpose: Interactive simulation with PDF export capability for LLM and Diffusion parameters

# ==========================================
# 1. README (print function)
# ==========================================
def print_documentation():
    print("""
================================================================================
[README / 概要]
本プログラムは、生成AI(LLMおよび拡散モデル)における生成制御パラメータの影響を可視化する
インタラクティブ・シミュレータです。

1. 目的:
   - LLMにおけるTemperature, Top-k, Top-pによる確率分布変容の理解。
   - 拡散モデルにおけるCFG Scaleが生成軌跡(ガイダンス)に与える影響の解析。

2. 使い方:
   - [Model Parameters] で各制御変数を設定します。
   - "Run Simulation" ボタンで計算とプロットを実行します。
   - "Save PDF" ボタンで結果をファイルとしてダウンロードします。

3. 支配方程式 (Governing Equations):
   A) LLM Softmax with Temperature:
      P(xi) = exp(zi / tau) / sum(exp(zj / tau))
   B) Classifier-Free Guidance (CFG):
      v_final = v_uncond + w * (v_cond - v_uncond)
      (w: CFG Scale, v: score/velocity vector)

4. 変数定義:
   - Temperature (tau): 分布の平滑化度。低値で鋭敏化、高値で一様化。
   - Top-k: 上位k個のトークンのみを抽出対象とする。
   - Top-p (Nucleus): 累積確率がpに達するまでの語彙集合を抽出対象とする。
   - CFG Scale (w): 条件付きガイダンスの強度。
   - Denoising Strength: i2iにおける初期ノイズ付加量(逆拡散の開始点)。
================================================================================
    """)

# ==========================================
# 2. Setup Code
# ==========================================
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
from IPython.display import display, clear_output
from google.colab import files
from datetime import datetime
import os

# Seed setting for reproducibility
# 再現性のためのシード設定
np.random.seed(42)

# Global variables for logging and ghosting
# ログとゴースト表示用のグローバル変数
simulation_logs = []
last_result = None

# ==========================================
# 3. TheoreticalModel
# ==========================================
class TheoreticalModel:
    @staticmethod
    def validate(params):
        """Validate input parameters / 入力パラメータの検証"""
        if params['temp'] <= 0:
            print("[Warning/警告] Temperature must be > 0. / 温度は0より大きい必要があります。")
            return False
        if not (0 <= params['top_p'] <= 1.0):
            print("[Warning/警告] Top-p must be between 0 and 1. / Top-pは0から1の間である必要があります。")
            return False
        if params['top_k'] < 1:
            print("[Warning/警告] Top-k must be >= 1. / Top-kは1以上である必要があります。")
            return False
        return True

    @staticmethod
    def calculate_llm_distribution(logits, temp, top_k, top_p):
        """Calculate LLM token probability distribution / LLMトークン確率分布の計算"""
        # 1. Apply Temperature / 温度の適用
        scaled_logits = logits / temp
        
        # 2. Apply Top-k / Top-kの適用
        indices_to_remove = scaled_logits < np.sort(scaled_logits)[-int(top_k)]
        scaled_logits[indices_to_remove] = -float('inf')
        
        # 3. Apply Top-p / Top-pの適用
        sorted_indices = np.argsort(scaled_logits)[::-1]
        sorted_logits = scaled_logits[sorted_indices]
        cumulative_probs = np.cumsum(np.exp(sorted_logits - np.max(sorted_logits)) / np.sum(np.exp(sorted_logits - np.max(sorted_logits))))
        
        sorted_indices_to_remove = cumulative_probs > top_p
        # Shift the indices to keep at least one token
        # 少なくとも1つのトークンを保持するようにインデックスをシフト
        sorted_indices_to_remove[1:] = sorted_indices_to_remove[:-1].copy()
        sorted_indices_to_remove[0] = False
        
        indices_to_remove = sorted_indices[sorted_indices_to_remove]
        scaled_logits[indices_to_remove] = -float('inf')
        
        # 4. Final Softmax / 最終的なソフトマックス
        e_z = np.exp(scaled_logits - np.max(scaled_logits))
        probs = e_z / e_z.sum()
        return probs

    @staticmethod
    def simulate_diffusion_path(steps, cfg_scale, strength):
        """Simulate simplified 1D diffusion trajectory / 簡易的な1次元拡散軌跡のシミュレーション"""
        # Starting point from noise (T) to data (0)
        # ノイズ(T)からデータ(0)への開始点
        t_start = int(steps * strength)
        x = np.random.randn() # Initial noise / 初期ノイズ
        
        path_cond = [x]
        path_uncond = [x]
        path_cfg = [x]
        
        for t in range(t_start, 0, -1):
            # Simulated scores (gradients)
            # シミュレートされたスコア(勾配)
            score_cond = -0.1 * x + 0.2  # Toward "target"
            score_uncond = -0.1 * x      # Toward "center"
            
            # Apply CFG
            v_cfg = score_uncond + cfg_scale * (score_cond - score_uncond)
            
            # Update (Simple Euler step)
            x_c = path_cond[-1] + score_cond
            x_u = path_uncond[-1] + score_uncond
            x_cfg = path_cfg[-1] + v_cfg
            
            path_cond.append(x_c)
            path_uncond.append(x_u)
            path_cfg.append(x_cfg)
            
        return np.array(path_cond), np.array(path_uncond), np.array(path_cfg)

    @staticmethod
    def print_calculation_steps(params, results):
        """Show calculation process / 計算過程の表示"""
        print("\n--- Calculation Steps / 計算過程 ---")
        print(f"1. Temperature Scaling: z_i' = z_i / {params['temp']}")
        print(f"2. Top-k Filtering: Keep top {int(params['top_k'])} elements, set others to -inf")
        print(f"3. Top-p Filtering: Keep elements until sum(P) >= {params['top_p']}")
        print(f"4. Softmax: P_i = exp(z_i') / sum(exp(z_j'))")
        print(f"5. CFG Guidance: v = v_uncond + {params['cfg']} * (v_cond - v_uncond)")
        print(f"Max Prob Result / 最大確率結果: {np.max(results['llm_probs']):.4f}")
        print("------------------------------------\n")

# ==========================================
# 4. Visualizer
# ==========================================
def run_visualization(params):
    global last_result
    plt.style.use('seaborn-v0_8-muted')
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
    
    # --- Plot 1: LLM Probability Distribution ---
    # Generate dummy logits
    num_tokens = 50
    logits = np.linspace(2, -2, num_tokens) + np.random.normal(0, 0.5, num_tokens)
    probs = TheoreticalModel.calculate_llm_distribution(logits, params['temp'], params['top_k'], params['top_p'])
    
    # Ghost line (previous result)
    if last_result is not None:
        ax1.bar(range(num_tokens), last_result['llm_probs'], alpha=0.2, color='gray', label='Previous')
    
    ax1.bar(range(num_tokens), probs, alpha=0.8, color='skyblue', label='Current')
    ax1.set_title("LLM Token Probability Distribution")
    ax1.set_xlabel("Token Index (Sorted)")
    ax1.set_ylabel("Probability (0-1)")
    ax1.grid(True, linestyle='--', alpha=0.6)
    ax1.legend()

    # --- Plot 2: Diffusion CFG Trajectory ---
    p_cond, p_uncond, p_cfg = TheoreticalModel.simulate_diffusion_path(params['steps'], params['cfg'], params['strength'])
    
    time_steps = np.arange(len(p_cfg))
    ax2.plot(time_steps, p_cond, 'g--', alpha=0.5, label='Conditional Only')
    ax2.plot(time_steps, p_uncond, 'r--', alpha=0.5, label='Unconditional Only')
    ax2.plot(time_steps, p_cfg, 'b-', linewidth=2, label='CFG Guided')
    
    ax2.set_title(f"Diffusion Trajectory (CFG Scale: {params['cfg']})")
    ax2.set_xlabel("Denoising Steps (t)")
    ax2.set_ylabel("Latent State Value (x)")
    ax2.grid(True, linestyle='--', alpha=0.6)
    ax2.legend()

    plt.tight_layout()
    
    results = {
        'llm_probs': probs,
        'diff_path': p_cfg,
        'fig': fig
    }
    
    TheoreticalModel.print_calculation_steps(params, results)
    last_result = results
    return results

# ==========================================
# 5. UIBuilder
# ==========================================
# UI Components
# [Model Parameters]
temp_input = widgets.BoundedFloatText(value=1.0, min=0.01, max=5.0, step=0.1, description='Temp (tau):')
top_k_input = widgets.IntText(value=50, description='Top-k:')
top_p_input = widgets.BoundedFloatText(value=1.0, min=0.0, max=1.0, step=0.05, description='Top-p:')
cfg_input = widgets.FloatText(value=7.5, description='CFG Scale:')
strength_input = widgets.BoundedFloatText(value=0.8, min=0.0, max=1.0, step=0.1, description='Strength:')

# [Observed / Input Data]
steps_input = widgets.IntText(value=20, description='Steps:')
seed_input = widgets.IntText(value=42, description='Seed:')

# [Environment / Options]
run_btn = widgets.Button(description='Run Simulation', button_style='primary')
reset_btn = widgets.Button(description='Reset / リセット', button_style='warning')
save_pdf_btn = widgets.Button(description='Save PDF / PDF保存', button_style='success')
show_log_btn = widgets.Button(description='Show Log / 履歴表示')
clear_log_btn = widgets.Button(description='Clear Log / 履歴消去')

output_area = widgets.Output()

def get_params():
    return {
        'temp': temp_input.value,
        'top_k': top_k_input.value,
        'top_p': top_p_input.value,
        'cfg': cfg_input.value,
        'strength': strength_input.value,
        'steps': steps_input.value,
        'seed': seed_input.value
    }

def on_run_clicked(b):
    with output_area:
        clear_output(wait=True)
        params = get_params()
        np.random.seed(params['seed'])
        
        if TheoreticalModel.validate(params):
            res = run_visualization(params)
            plt.show()
            
            # Log entry
            log_entry = {
                'timestamp': datetime.now().isoformat(),
                'params': params,
                'max_prob': float(np.max(res['llm_probs']))
            }
            simulation_logs.append(log_entry)
            print(f"[Log] Simulation finished at {log_entry['timestamp']}")

def on_reset_clicked(b):
    global last_result, simulation_logs
    temp_input.value = 1.0
    top_k_input.value = 50
    top_p_input.value = 1.0
    cfg_input.value = 7.5
    strength_input.value = 0.8
    steps_input.value = 20
    seed_input.value = 42
    last_result = None
    simulation_logs = []
    with output_area:
        clear_output()
        print("Reset complete. / リセットが完了しました。")

def on_save_pdf_clicked(b):
    if last_result is None:
        with output_area: print("No simulation data to save. / 保存するデータがありません。")
        return
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"sim_result_{timestamp}.pdf"
    last_result['fig'].savefig(filename, format='pdf')
    
    with output_area:
        print(f"Starting PDF download: {filename} / PDFのダウンロードを開始します。")
        files.download(filename)

def on_show_log_clicked(b):
    with output_area:
        print("\n--- Simulation History / 履歴 ---")
        for i, entry in enumerate(simulation_logs):
            print(f"ID: {i} | Time: {entry['timestamp']} | MaxProb: {entry['max_prob']:.4f}")
        if not simulation_logs:
            print("No logs found. / 履歴はありません。")

def on_clear_log_clicked(b):
    global simulation_logs
    simulation_logs = []
    with output_area: print("Logs cleared. / 履歴を消去しました。")

run_btn.on_click(on_run_clicked)
reset_btn.on_click(on_reset_clicked)
save_pdf_btn.on_click(on_save_pdf_clicked)
show_log_btn.on_click(on_show_log_clicked)
clear_log_btn.on_click(on_clear_log_clicked)

# Layout
ui_layout = widgets.VBox([
    widgets.HTML("<b>[Model Parameters]</b>"),
    widgets.HBox([temp_input, top_k_input, top_p_input]),
    widgets.HBox([cfg_input, strength_input]),
    widgets.HTML("<br><b>[Observed / Input Data]</b>"),
    widgets.HBox([steps_input, seed_input]),
    widgets.HTML("<br><b>[Environment / Options]</b>"),
    widgets.HBox([run_btn, reset_btn, save_pdf_btn]),
    widgets.HBox([show_log_btn, clear_log_btn]),
    output_area
])

# ==========================================
# 6. Initialization
# ==========================================
print_documentation()
display(ui_layout)

第2章:拡散モデル(Image Generation)における生成制御

拡散モデルは、データ分布 をガウスノイズへと変換する拡散過程の「逆過程」を、スコアベースモデルやODE/SDEとして学習する。

2.1 初期条件と観測空間

  • Seed / Noise: 初期ノイズ を決定する。
  • Resolution / Aspect Ratio: 生成対象となるテンソル空間の次元 。

2.2 時間離散化と数値積分(Steps / Sampler)

逆拡散過程の連続時間変化は一般に以下の常微分方程式(Probability Flow ODE)で記述される。

  • Steps (): 区間 を 分割し、離散的な更新を行う。
  • Sampler: 上記の微分方程式を解くための数値解法。
  • Euler法: 1次精度。。
  • Heun法 / DPM-Solver: 2次以上の精度を持ち、少ないステップで高精度な解を得る。

2.3 条件勾配強度:CFG Scale

Classifier-Free Guidance。条件 (プロンプト)への適合度を線形補間によって制御する。

  • : 条件を無視(無条件生成)。
  • : 条件方向へのベクトルを定数倍し、指示への忠実度を強調する。

2.4 条件表現:Clip Skip

CLIPエンコーダの第 層の隠れ状態を出力として採用する。
層数を とすると、採用する層は となる。

  • 後方層ほど具体的な物体名称に、前方層ほど抽象的な概念(色彩や構図)に対応する傾向がある。

2.5 途中開始:Denoising Strength

i2iにおいて、元の画像 に加えるノイズ量、すなわち逆拡散の開始時刻 を制御する。

  • **Strength **: 原画を維持(ノイズ付加なし)。
  • **Strength **: 完全な新規生成( から開始)。

【付録】パラメータ相互作用の検討

研究対象 物理的・数学的解釈 調整の指針
温度とTop-p 確率密度の集中と裾野の切断 創造性が必要な場合は両者を高めに設定。
StepsとSampler 離散化誤差と計算コスト DPM-Solver等の高次解法では20-30 stepsで収束。
CFGとDenoising 指示の強制力と原画保持力 構図を維持しつつ描き込む場合は両者の均衡が重要。

第2章:拡散モデル(Image Generation)における生成制御

画像生成AI(Stable Diffusion等)は、完全なガウスノイズから、各ステップで少しずつノイズを取り除く(デノイズ)ことで画像を復元します。この「逆拡散過程」をいかに制御するかが、生成の質と多様性を決定します。

2.1 初期条件と観測空間:生成の「種」と「キャンバス」

  • Seed / Noise (): 拡散モデルにおける生成は、高次元(例:)の潜在空間における特定の座標 から開始されます。Seedを固定することは、この初期座標を固定することを意味し、他のパラメータを変更した際の比較を可能にします。
  • Resolution / Aspect Ratio: 生成対象となるテンソルサイズ。学習時の解像度(SD1.5なら512、SDXLなら1024)から大きく逸脱すると、構図の崩れ(体が2つある等)が発生します。これは、アテンション機構が学習した「空間的な関係性」の範囲を超えるためです。

2.2 時間離散化と数値積分(Steps / Sampler)

逆拡散過程は、連続的な時間変化を記述する確率微分方程式 (SDE) や、それと対応する Probability Flow ODE として定式化されます。

  • Steps (): ノイズ から画像 への軌跡を何分割で計算するかを決定します。
  • Sampler(数値解法):
  • Euler法: 1次精度の単純な解法。勾配方向に直線的に進むため、ステップ数が少ないと誤差が蓄積し、画像がボヤけたり崩れたりしやすい。
  • Heun法: 2次精度。現在の位置と、一歩先の予測位置の両方の勾配を平均化するため、Eulerよりも正確ですが、1ステップあたりの計算量は2倍になります。
  • DPM-Solver / UniPC: 拡散モデル特有の軌跡(指数的な変化)に最適化された高次解法。20ステップ程度で高品質な収束が可能です。

2.3 条件勾配強度:CFG Scale (Classifier-Free Guidance)

プロンプトに対する「忠実度」を調整する核心的なパラメータです。

  • 数理的仕組み:
    無条件生成(Negative Prompt)のスコア と、条件付き生成のスコア を線形補間します。

  • 挙動の性質:

  • : ガイダンスなし。モデル本来の自由な解釈。

  • : 標準的。プロンプトに従いつつ、質感も保たれる。

  • : 過剰な強調。色の彩度が極端に上がり、コントラストが強すぎて「画像が焼ける(Deep fried)」現象が発生します。

2.4 条件表現:Clip Skip

CLIP(Text Encoder)は、入力テキストを多層のトランスフォーマーで処理します。

  • 層の役割:

  • 最終層 (Skip 1): 具体的で細かい属性(「赤いネクタイ」「左手に持った剣」等)に特化します。

  • 1〜2層手前 (Skip 2): より抽象的な概念や全体的な雰囲気を保持しています。

  • 実務上の選択: 多くのアニメ系モデルでは、最終層の「具体的すぎて柔軟性を欠く表現」を避け、あえて1層飛ばした Clip Skip 2 が推奨されます。これにより、構図や色彩の自由度が増し、破綻の少ない生成が可能になります。


2.5 途中開始:Denoising Strength (i2i)

「元の絵をどの程度残すか」を決定します。

  • 物理的意味:
    拡散過程のタイムライン()のどの地点から逆拡散をスタートさせるかを制御します。
  • Strength 0.5: 全体の工程の半分までノイズを加え、そこからデノイズを開始します。大まかな色や形は維持されます。
  • Strength 0.8以上: ほぼ全ての情報がノイズに埋もれるため、元の絵の構成を無視した新しい画像が生成されやすくなります。

【付録】パラメータ相互作用の検討(統合的理解)

生成AIの制御は、単一のパラメータではなく、以下のトレードオフの均衡点を見つける作業です。

パラメータの組み合わせ 相互作用の挙動
CFG Scale × Denoising i2iにおいて、CFGが高いと元の絵よりもプロンプトの指示が優先され、Denoisingが高いと描き込み量が増えます。
Steps × Sampler Euler系はステップ数を増やすほど品質が向上しますが、DPM系はある程度のステップ(20〜30)で飽和するため、過剰なステップは時間効率を下げます。
Temperature (LLM) × Seed (Diff) 両者は「ランダム性の源泉」として機能します。LLMでは選択肢の確率を、拡散モデルでは初期のノイズパターンを決定します。
# Program Name: Diffusion_Control_Physics_Simulator
# Creation Date: 2026-01-08
# Purpose: Interactive simulation of Diffusion Model controls (CFG, Samplers, i2i) with PDF export

# ==========================================
# 1. README (print function)
# ==========================================
def print_documentation():
    print("""
================================================================================
[README / 概要]
本プログラムは、拡散モデル(Diffusion Models)の逆過程における生成制御パラメータが、
どのように潜在空間上の軌跡を変化させるかをシミュレートする工学的検証ツールです。

1. 目的:
   - CFG Scale(Classifier-Free Guidance)による条件付けの強制力の視覚化。
   - Sampler(数値解法)の精度差(Euler vs Heun)による誤差の検証。
   - Denoising Strengthによるi2i(Image-to-Image)の開始点制御の理解。

2. 支配方程式 (Governing Equations):
   - Classifier-Free Guidance:
     e_final = e_uncond + w * (e_cond - e_uncond)
     (e: predicted noise / score, w: CFG Scale)
   - Reverse Diffusion Step (Deterministic):
     x_{t-1} = x_t + f(x_t, t, e_final)
   - i2i Noise Injection:
     x_start = sqrt(alpha_bar_t) * x_0 + sqrt(1 - alpha_bar_t) * epsilon
     (strength ∝ t)

3. 変数定義:
   - CFG Scale: 条件ベクトルへの近似度。高いほどプロンプトに忠実だが、軌跡が発散しやすい。
   - Steps: 離散化数。多いほどODEの解としての精度が高まる。
   - Denoising Strength: 0に近いほど原画(x0)を維持し、1に近いほど完全なノイズから開始。
================================================================================
    """)

# ==========================================
# 2. Setup Code
# ==========================================
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
from IPython.display import display, clear_output
from google.colab import files
from datetime import datetime

# Import and Seed
np.random.seed(42)

# Global storage for comparison
# 比較用のグローバルストレージ
sim_history = []
last_plot_data = None

# ==========================================
# 3. TheoreticalModel
# ==========================================
class DiffusionEngine:
    @staticmethod
    def validate(p):
        """Validate input / 入力バリデーション"""
        if p['steps'] < 1: 
            print("[Error] Steps must be >= 1 / ステップ数は1以上必要です。")
            return False
        return True

    @staticmethod
    def get_score(x, t, condition_pos):
        """
        Simplified score function (gradient toward target)
        簡易的なスコア関数(ターゲットへの勾配)
        """
        # Condition score (toward prompt)
        score_cond = condition_pos - x
        # Uncondition score (toward origin/density center)
        score_uncond = -x 
        return score_cond, score_uncond

    @staticmethod
    def solve_trajectory(params):
        """
        Compute reverse diffusion path
        逆拡散過程の軌跡計算
        """
        steps = params['steps']
        cfg = params['cfg']
        strength = params['strength']
        sampler = params['sampler'] # 0: Euler, 1: Heun
        
        # Target condition in 2D latent space
        # 2次元潜在空間上の目標地点
        c_pos = np.array([1.0, 1.0])
        
        # Initial state based on strength (i2i logic)
        # 強度に基づいた初期状態 (i2iロジック)
        t_start = int(steps * strength)
        x_0 = np.array([0.2, -0.2]) # Original image latent / 原画の潜在変数
        noise = np.random.randn(2)
        
        # Simplified forward alpha schedule
        # 簡易的なアルファスケジュールの適用
        alpha_t = 1.0 - (t_start / steps)
        x = np.sqrt(alpha_t) * x_0 + np.sqrt(1 - alpha_t) * noise
        
        path = [x.copy()]
        dt = 1.0 / steps

        for i in range(t_start, 0, -1):
            t_curr = i / steps
            
            # 1. CFG Score Calculation
            s_cond, s_uncond = DiffusionEngine.get_score(x, t_curr, c_pos)
            v = s_uncond + cfg * (s_cond - s_uncond)
            
            # 2. Integration Step (Sampler)
            if sampler == 0: # Euler
                x = x + v * dt
            else: # Heun (2nd order)
                x_pred = x + v * dt
                s_cond_next, s_uncond_next = DiffusionEngine.get_score(x_pred, (i-1)/steps, c_pos)
                v_next = s_uncond_next + cfg * (s_cond_next - s_uncond_next)
                x = x + 0.5 * (v + v_next) * dt
            
            path.append(x.copy())
            
        return np.array(path), c_pos

    @staticmethod
    def print_calculation_steps(p, traj):
        """Display logic / 計算ロジックの表示"""
        print("\n--- Theoretical Execution Trace / 理論実行トレース ---")
        print(f"Start Step (t_start): {int(p['steps'] * p['strength'])} / {p['steps']}")
        print(f"CFG Linear Interpolation: e = e_uncond + {p['cfg']} * (e_cond - e_uncond)")
        if p['sampler'] == 1:
            print("Sampler: Heun (2nd order trapezoidal integration)")
        else:
            print("Sampler: Euler (1st order forward integration)")
        print(f"Final Latent Distance to Target: {np.linalg.norm(traj[-1] - np.array([1.0,1.0])):.4f}")
        print("--------------------------------------------------\n")

# ==========================================
# 4. Visualizer
# ==========================================
def plot_simulation(params):
    global last_plot_data
    plt.style.use('seaborn-v0_8-muted')
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
    
    trajectory, target = DiffusionEngine.solve_trajectory(params)
    
    # Plot 1: 2D Latent Trajectory (Phase Portrait)
    # 潜在空間上の軌跡(相図)
    ax1.plot(trajectory[:, 0], trajectory[:, 1], 'o-', markersize=3, label='Denoising Path', color='blue', alpha=0.7)
    ax1.scatter(target[0], target[1], marker='*', s=200, color='gold', label='Prompt Target', edgecolors='black', zorder=5)
    ax1.scatter(trajectory[0, 0], trajectory[0, 1], marker='s', s=100, color='red', label='Start Point (Noise)')
    
    # Ghosting previous run
    if last_plot_data is not None:
        ax1.plot(last_plot_data['path'][:, 0], last_plot_data['path'][:, 1], '--', color='gray', alpha=0.3, label='Previous Run')

    ax1.set_title("2.2 - 2.3: Latent Space Trajectory & CFG Guidance")
    ax1.set_xlabel("Latent Dimension 1 (z1)")
    ax1.set_ylabel("Latent Dimension 2 (z2)")
    ax1.grid(True)
    ax1.legend()

    # Plot 2: Convergence Analysis (Distance to Target over Time)
    # 収束解析(時間経過による目標距離の変化)
    distances = np.linalg.norm(trajectory - target, axis=1)
    ax2.plot(distances, color='green', linewidth=2, label='Error to Target')
    ax2.set_title("2.5: Convergence & Denoising Analysis")
    ax2.set_xlabel("Inference Steps (Reverse Time)")
    ax2.set_ylabel("Euclidean Distance")
    ax2.grid(True)
    ax2.legend()

    plt.tight_layout()
    
    last_plot_data = {'path': trajectory, 'fig': fig}
    DiffusionEngine.print_calculation_steps(params, trajectory)
    return fig

# ==========================================
# 5. UIBuilder
# ==========================================
# [Model Parameters]
cfg_scale = widgets.FloatText(value=7.5, description='CFG Scale:')
denoising_strength = widgets.BoundedFloatText(value=0.8, min=0.0, max=1.0, step=0.05, description='Denoising:')
sampler_type = widgets.Dropdown(options=[('Euler', 0), ('Heun', 1)], value=0, description='Sampler:')

# [Observed / Input Data]
steps_count = widgets.IntText(value=30, description='Steps:')
seed_val = widgets.IntText(value=42, description='Seed:')

# [Environment / Options]
run_button = widgets.Button(description='Run Simulation', button_style='primary')
reset_button = widgets.Button(description='Reset / リセット', button_style='warning')
pdf_button = widgets.Button(description='Save PDF / PDF保存', button_style='success')
log_button = widgets.Button(description='Show Log / 履歴表示')
clear_log_button = widgets.Button(description='Clear Log / 履歴消去')

out = widgets.Output()

def get_current_params():
    return {
        'cfg': cfg_scale.value,
        'strength': denoising_strength.value,
        'sampler': sampler_type.value,
        'steps': steps_count.value,
        'seed': seed_val.value
    }

def on_run(b):
    with out:
        clear_output(wait=True)
        p = get_current_params()
        np.random.seed(p['seed'])
        if DiffusionEngine.validate(p):
            fig = plot_simulation(p)
            plt.show()
            
            entry = {'time': datetime.now().isoformat(), 'cfg': p['cfg'], 'steps': p['steps']}
            sim_history.append(entry)
            print(f"[System] Simulation completed at {entry['time']}.")

def on_reset(b):
    cfg_scale.value = 7.5
    denoising_strength.value = 0.8
    sampler_type.value = 0
    steps_count.value = 30
    seed_val.value = 42
    global last_plot_data, sim_history
    last_plot_data = None
    sim_history = []
    with out:
        clear_output()
        print("All parameters and history reset. / すべてのパラメータと履歴をリセットしました。")

def on_pdf(b):
    if last_plot_data is None:
        with out: print("Error: No plot available. / エラー: プロットが存在しません。")
        return
    fname = f"diffusion_sim_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
    last_plot_data['fig'].savefig(fname)
    with out:
        print(f"PDF saved as {fname}. Downloading... / PDFを保存しました。ダウンロードを開始します。")
        files.download(fname)

def on_log(b):
    with out:
        print("\n--- Simulation Logs / 実行履歴 ---")
        for log in sim_history:
            print(f"[{log['time']}] CFG: {log['cfg']}, Steps: {log['steps']}")
        if not sim_history: print("No logs available. / 履歴なし。")

def on_clear_log(b):
    global sim_history
    sim_history = []
    with out: print("Logs cleared. / 履歴を消去しました。")

run_button.on_click(on_run)
reset_button.on_click(on_reset)
pdf_button.on_click(on_pdf)
log_button.on_click(on_log)
clear_log_button.on_click(on_clear_log)

# UI Assembly
ui = widgets.VBox([
    widgets.HTML("<h3>Diffusion Generation Control Simulator</h3>"),
    widgets.HTML("<b>[Model Parameters]</b>"),
    widgets.HBox([cfg_scale, denoising_strength, sampler_type]),
    widgets.HTML("<b>[Observed / Input Data]</b>"),
    widgets.HBox([steps_count, seed_val]),
    widgets.HTML("<b>[Environment / Options]</b>"),
    widgets.HBox([run_button, reset_button, pdf_button]),
    widgets.HBox([log_button, clear_log_button]),
    out
])

# ==========================================
# 6. Initialization
# ==========================================
print_documentation()
display(ui)

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?