Spaces:
Sleeping
Sleeping
Download app.py from UTKojima/2ndPaper_v5: direct link, hf CLI and curl.
- Browser
- Download file 7.56 kB
-
https://huggingface.co/spaces/UTKojima/2ndPaper_v5/resolve/main/app.py
- Command line
-
hf download hf://spaces/UTKojima/2ndPaper_v5/app.py
-
curl -L -o app.py https://huggingface.co/spaces/UTKojima/2ndPaper_v5/resolve/main/app.py
7.56 kB
| 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. ็ๆ๏ผใใชใใ่จๆธฌใใซใใผ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| 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. ๆฏ่ผ็ๆ้ขๆฐ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| 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() |