Spaces:
Sleeping
Sleeping
File size: 7,558 Bytes
a45e1a3 57d52e5 a45e1a3 57d52e5 3c1334a 57d52e5 ac0c700 232f9db 2586b09 57d52e5 ac0c700 7983474 38eaed7 a8cedff 38eaed7 a8cedff 38eaed7 a8cedff 38eaed7 7241194 f1caac5 2c0f768 10b9b1c 9d0b4a7 a8cedff 4c3bc6e a8cedff 4c3bc6e a8cedff cb6c33b 3c1334a cb6c33b 3c1334a ac0c700 cb6c33b a8cedff cb6c33b 38eaed7 57d52e5 9d0b4a7 7241194 a8cedff 9d0b4a7 a8cedff 9d0b4a7 a8cedff 26f3e68 4c3bc6e a8cedff 4c3bc6e 9d0b4a7 a8cedff 9d0b4a7 ac0c700 9d0b4a7 ac0c700 a8cedff 57d52e5 cb6c33b a8cedff ac0c700 3c1334a a8cedff 3c1334a a8cedff 232f9db 3c1334a 232f9db ac0c700 9d0b4a7 a8cedff 9d0b4a7 ac0c700 232f9db ac0c700 a8cedff ac0c700 3c1334a 232f9db ac0c700 232f9db ac0c700 7241194 b617150 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | 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() |