import os import io import math import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image import gradio as gr import scipy.stats as stats # ── 0. 安全な .to() パッチ ───────────────────────────────────── from transformers.modeling_utils import PreTrainedModel _original_module_to = torch.nn.Module.to _original_ptm_to = PreTrainedModel.to def _safe_to(self, *args, **kwargs): # bitsandbytes の量子化モジュールのみスキップ if getattr(self, "quantization_method", None) is not None: return self # PreTrainedModel の to() は元に戻す if isinstance(self, PreTrainedModel): return _original_ptm_to(self, *args, **kwargs) # その他は通常の to() return _original_module_to(self, *args, **kwargs) torch.nn.Module.to = _safe_to PreTrainedModel.to = _safe_to # ── グローバルパラメータ ─────────────────────────────────────── #Δt, β = 1e-2, 1e-4 # シンプレクティック補正用タイムステップと強度 Δt, β = 2e-2, 1e-4 # Δt を 2 倍に # ── 1. 必要モジュールインポート ──────────────────────────────── from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig from transformers.models.llama.modeling_llama import LlamaDecoderLayer from peft import LoraConfig, get_peft_model # ── 2. シンプレクティック補正フック定義 ───────────────────────── def symp_hook(module, input_, out): hidden = out[0] if isinstance(out, tuple) else out q, p = hidden.chunk(2, dim=-1) p.sub_(Δt * β * q) q.add_(Δt * p) new_hidden = torch.cat([q, p], dim=-1) if isinstance(out, tuple): return (new_hidden, *out[1:]) return new_hidden # ── 3. フック登録関数 ───────────────────────────────────────── def register_symp_hook(model): for module in model.modules(): if isinstance(module, LlamaDecoderLayer): module.register_forward_hook(symp_hook) # ── 4. モデルロード&LoRA適用関数 ─────────────────────────────── def load_quantized_lora_model(): MODEL_ID = "NousResearch/Meta-Llama-3-8B-Instruct" bnb_cfg = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True, ) tok = AutoTokenizer.from_pretrained(MODEL_ID) tok.pad_token = tok.eos_token model = AutoModelForCausalLM.from_pretrained( MODEL_ID, quantization_config=bnb_cfg, device_map={"": "cuda:0"}, torch_dtype=torch.float16, low_cpu_mem_usage=True, ) model.gradient_checkpointing_enable() device = torch.device("cuda:0") for name, param in model.named_parameters(): param.data = param.data.to(device) for name, buf in model.named_buffers(): buf.data = buf.data.to(device) lora_cfg = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, target_modules=["q_proj","k_proj","v_proj","o_proj"], ) model = get_peft_model(model, lora_cfg) return model, tok # ── 5. 生成+ドリフト計測ヘルパー ───────────────────────────────── @torch.no_grad() def generate_and_drift(model, tok, prompt: str, max_new: int = 128): device = torch.device("cuda:0") enc = tok(prompt, return_tensors="pt") input_ids = enc["input_ids"].to(device) attention_mask = enc["attention_mask"].to(device) initial_len = input_ids.shape[1] H_list = [] for _ in range(max_new): outputs = model( input_ids=input_ids, attention_mask=attention_mask, output_hidden_states=True, ) h = outputs.hidden_states[-1][:, -1] q, p = h.chunk(2, dim=-1) H_list.append((0.5*(p**2).sum(-1) + 0.5*β*(q**2).sum(-1)).item()) ΔH = abs(H_list[-1] - H_list[0]) temp = max(0.8*math.exp(-0.1*ΔH), 0.2) nxt = model.generate( input_ids=input_ids, attention_mask=attention_mask, max_new_tokens=1, temperature=temp, do_sample=True, pad_token_id=tok.eos_token_id, ) token = nxt[:, -1].unsqueeze(-1) input_ids = torch.cat([input_ids, token], dim=1) attention_mask = torch.cat([attention_mask, torch.ones_like(token)], dim=1) if token[0, 0] == tok.eos_token_id: break gen_ids = input_ids[0, initial_len:] gen_text = tok.decode(gen_ids, skip_special_tokens=True) return gen_text, H_list # ── 6. 比較生成関数 ───────────────────────────────────────────────── @torch.no_grad() def compare_generate(prompt: str): # Baseline model_b, tok_b = load_quantized_lora_model() gen_b, H_b = generate_and_drift(model_b, tok_b, prompt) # Symplectic model_s, tok_s = load_quantized_lora_model() register_symp_hook(model_s) gen_s, H_s = generate_and_drift(model_s, tok_s, prompt) # 統計量 def compute_stats(H): arr = np.array(H) return arr.min(), arr.max(), arr.mean(), np.median(arr), arr.std() stats_b = compute_stats(H_b) stats_s = compute_stats(H_s) # 有意差検定 t_stat, p_val = stats.ttest_ind(H_b, H_s, equal_var=False) lev_stat, lev_p = stats.levene(H_b, H_s) # プロット buf = io.BytesIO() plt.figure() plt.plot(H_b, label="Baseline") plt.plot(H_s, label="Symplectic") plt.xlabel("Step") plt.ylabel("Energy H(q,p)") plt.title("Energy Drift Comparison") plt.legend() plt.tight_layout() plt.savefig(buf, format="png") plt.close() buf.seek(0) img = Image.open(buf) # テキスト出力用 stat_text_b = f"Baseline: min={stats_b[0]:.1f}, max={stats_b[1]:.1f}, mean={stats_b[2]:.1f}, median={stats_b[3]:.1f}, std={stats_b[4]:.1f}" stat_text_s = f"Symplectic: min={stats_s[0]:.1f}, max={stats_s[1]:.1f}, mean={stats_s[2]:.1f}, median={stats_s[3]:.1f}, std={stats_s[4]:.1f}" test_text = f"t-test p-value={p_val:.3f}, Levene p-value={lev_p:.3f}" return gen_b, gen_s, stat_text_b, stat_text_s, test_text, img # ── 7. Gradio UI ───────────────────────────────────────────────────── iface = gr.Interface( fn=compare_generate, inputs=gr.Textbox(label="Prompt", lines=3, placeholder="Enter your prompt..."), outputs=[ gr.Textbox(label="Baseline Generation"), gr.Textbox(label="Symplectic Generation"), gr.Textbox(label="Baseline Stats"), gr.Textbox(label="Symplectic Stats"), gr.Textbox(label="Significance Tests"), gr.Image(label="Energy Drift Comparison") ], title="Baseline vs Symplectic Control Demo", description="Compare generation, statistics & energy drift: baseline vs symplectic correction with significance tests" ) if __name__ == "__main__": iface.launch()