Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,13 +4,17 @@ import math
|
|
| 4 |
|
| 5 |
import torch
|
| 6 |
import matplotlib.pyplot as plt
|
| 7 |
-
from
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# โโ 0. ๅฎๅ
จใช .to() ใใใ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 11 |
-
# bitsandbytes ใฎ้ๅญๅ
|
| 12 |
-
# ใใไปฅๅคใฏๆฌๆฅใฎ to() ใๅผใณๅบ
|
| 13 |
-
from transformers.modeling_utils import PreTrainedModel
|
| 14 |
_original_module_to = torch.nn.Module.to
|
| 15 |
_original_ptm_to = PreTrainedModel.to
|
| 16 |
|
|
@@ -23,76 +27,76 @@ def _safe_to(self, *args, **kwargs):
|
|
| 23 |
|
| 24 |
torch.nn.Module.to = _safe_to
|
| 25 |
PreTrainedModel.to = _safe_to
|
| 26 |
-
print("๐ฉน Applied safe .to() patch: skip only bitsandbytes modules")
|
| 27 |
-
|
| 28 |
-
# โโ 1. ใขใใซใปใใผใฏใใคใถใผ่จญๅฎ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 29 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 30 |
-
from peft import LoraConfig, get_peft_model
|
| 31 |
-
|
| 32 |
-
MODEL_ID = "NousResearch/Meta-Llama-3-8B-Instruct"
|
| 33 |
-
bnb_cfg = BitsAndBytesConfig(
|
| 34 |
-
load_in_4bit=True,
|
| 35 |
-
bnb_4bit_quant_type="nf4",
|
| 36 |
-
bnb_4bit_compute_dtype=torch.float16,
|
| 37 |
-
bnb_4bit_use_double_quant=True,
|
| 38 |
-
)
|
| 39 |
|
| 40 |
-
tok = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 41 |
-
tok.pad_token = tok.eos_token
|
| 42 |
|
| 43 |
-
# โโ
|
| 44 |
-
|
| 45 |
-
MODEL_ID
|
| 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 |
@torch.no_grad()
|
| 95 |
-
def
|
|
|
|
| 96 |
enc = tok(prompt, return_tensors="pt")
|
| 97 |
input_ids = enc["input_ids"].to(device)
|
| 98 |
attention_mask = enc["attention_mask"].to(device)
|
|
@@ -108,11 +112,10 @@ def symp_generate_with_drift(prompt: str, max_new: int = 128):
|
|
| 108 |
h = out.hidden_states[-1][:, -1]
|
| 109 |
q, p = h.chunk(2, dim=-1)
|
| 110 |
|
| 111 |
-
H_val
|
| 112 |
-
H_mean = 0.5 * (p.mean(0)**2).sum() + 0.5 * ฮฒ * (q.mean(0)**2).sum()
|
| 113 |
H_list.append(H_val.item())
|
| 114 |
|
| 115 |
-
ฮH = abs(H_val.item() -
|
| 116 |
temp = max(0.8 * math.exp(-0.1 * ฮH), 0.2)
|
| 117 |
|
| 118 |
nxt = model.generate(
|
|
@@ -122,8 +125,8 @@ def symp_generate_with_drift(prompt: str, max_new: int = 128):
|
|
| 122 |
temperature=temp,
|
| 123 |
do_sample=True,
|
| 124 |
pad_token_id=tok.eos_token_id,
|
|
|
|
| 125 |
)
|
| 126 |
-
# ๆซๅฐพใใผใฏใณใ ใๅใๅบใ
|
| 127 |
next_token = nxt[:, -1].unsqueeze(-1)
|
| 128 |
input_ids = torch.cat([input_ids, next_token], dim=1)
|
| 129 |
attention_mask = torch.cat([attention_mask, torch.ones_like(next_token)], dim=1)
|
|
@@ -131,36 +134,43 @@ def symp_generate_with_drift(prompt: str, max_new: int = 128):
|
|
| 131 |
if next_token[0, 0] == tok.eos_token_id:
|
| 132 |
break
|
| 133 |
|
| 134 |
-
# ็ๆใใญในใใฎใฟใใใณใผใ
|
| 135 |
gen_ids = input_ids[0, initial_len:]
|
| 136 |
gen_text = tok.decode(gen_ids, skip_special_tokens=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
plt.figure()
|
| 141 |
-
plt.plot(
|
|
|
|
| 142 |
plt.xlabel("Step")
|
| 143 |
plt.ylabel("Energy H(q,p)")
|
| 144 |
-
plt.title("
|
|
|
|
| 145 |
plt.tight_layout()
|
| 146 |
-
plt.savefig(
|
| 147 |
-
plt.
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
return gen_text, img
|
| 152 |
-
|
| 153 |
-
# โโ 7. Gradio UI โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 154 |
-
iface = gr.Interface(
|
| 155 |
-
fn=symp_generate_with_drift,
|
| 156 |
-
inputs=gr.Textbox(label="Prompt", lines=3, placeholder="Enter your prompt..."),
|
| 157 |
-
outputs=[
|
| 158 |
-
gr.Textbox(label="Generation"),
|
| 159 |
-
gr.Image(label="Energy Drift")
|
| 160 |
-
],
|
| 161 |
-
title="Llama-3 8B + Symplectic Control",
|
| 162 |
-
description="4-bit้ๅญๅ๏ผLoRA๏ผใทใณใใฌใฏใใฃใใฏ่ฃๆญฃ ๏ผ Energy Drift Visualization"
|
| 163 |
-
)
|
| 164 |
|
| 165 |
if __name__ == "__main__":
|
| 166 |
-
|
|
|
|
| 4 |
|
| 5 |
import torch
|
| 6 |
import matplotlib.pyplot as plt
|
| 7 |
+
from transformers import (
|
| 8 |
+
AutoModelForCausalLM,
|
| 9 |
+
AutoTokenizer,
|
| 10 |
+
BitsAndBytesConfig
|
| 11 |
+
)
|
| 12 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 13 |
+
from peft import LoraConfig, get_peft_model
|
| 14 |
|
| 15 |
# โโ 0. ๅฎๅ
จใช .to() ใใใ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 16 |
+
# bitsandbytes ใฎ้ๅญๅใขใธใฅใผใซใ ใในใญใใใใ
|
| 17 |
+
# ใใไปฅๅคใฏๆฌๆฅใฎ to() ใๅผใณๅบใ
|
|
|
|
| 18 |
_original_module_to = torch.nn.Module.to
|
| 19 |
_original_ptm_to = PreTrainedModel.to
|
| 20 |
|
|
|
|
| 27 |
|
| 28 |
torch.nn.Module.to = _safe_to
|
| 29 |
PreTrainedModel.to = _safe_to
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
# โโ 1. ใขใใซใญใผใ๏ผLoRA้ฉ็จใฎ้ขๆฐ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 33 |
+
def load_quantized_lora_model():
|
| 34 |
+
MODEL_ID = "NousResearch/Meta-Llama-3-8B-Instruct"
|
| 35 |
+
|
| 36 |
+
# ้ๅญๅ่จญๅฎ
|
| 37 |
+
bnb_cfg = BitsAndBytesConfig(
|
| 38 |
+
load_in_4bit=True,
|
| 39 |
+
bnb_4bit_quant_type="nf4",
|
| 40 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 41 |
+
bnb_4bit_use_double_quant=True,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
# ใใผใฏใใคใถใผ
|
| 45 |
+
tok = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 46 |
+
tok.pad_token = tok.eos_token
|
| 47 |
+
|
| 48 |
+
# ใขใใซใญใผใ
|
| 49 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 50 |
+
MODEL_ID,
|
| 51 |
+
quantization_config=bnb_cfg,
|
| 52 |
+
device_map={"": "cuda:0"},
|
| 53 |
+
torch_dtype=torch.float16,
|
| 54 |
+
low_cpu_mem_usage=True,
|
| 55 |
+
)
|
| 56 |
+
model.gradient_checkpointing_enable()
|
| 57 |
+
|
| 58 |
+
# CPUไธใฎๆฎ็ใใฉใกใผใฟใๅ
จใฆGPUใธ
|
| 59 |
+
device = torch.device("cuda:0")
|
| 60 |
+
for name, param in model.named_parameters():
|
| 61 |
+
if param.device != device:
|
| 62 |
+
param.data = param.data.to(device)
|
| 63 |
+
for name, buf in model.named_buffers():
|
| 64 |
+
if buf.device != device:
|
| 65 |
+
buf.data = buf.data.to(device)
|
| 66 |
+
|
| 67 |
+
# LoRA้ฉ็จ
|
| 68 |
+
lora_cfg = LoraConfig(
|
| 69 |
+
r=16,
|
| 70 |
+
lora_alpha=32,
|
| 71 |
+
lora_dropout=0.05,
|
| 72 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
|
| 73 |
+
)
|
| 74 |
+
model = get_peft_model(model, lora_cfg)
|
| 75 |
+
|
| 76 |
+
return model, tok
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# โโ 2. ใทใณใใฌใฏใใฃใใฏ่ฃๆญฃใใใฏ็ป้ฒ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 80 |
+
def register_symp_hook(model, ฮt=1e-2, ฮฒ=1e-4):
|
| 81 |
+
def symp_hook(module, input_, out):
|
| 82 |
+
if isinstance(out, tuple):
|
| 83 |
+
hidden, *rest = out
|
| 84 |
+
else:
|
| 85 |
+
hidden, rest = out, []
|
| 86 |
+
q, p = hidden.chunk(2, dim=-1)
|
| 87 |
+
p.sub_(ฮt * ฮฒ * q)
|
| 88 |
+
q.add_(ฮt * p)
|
| 89 |
+
new_hidden = torch.cat([q, p], dim=-1)
|
| 90 |
+
return (new_hidden, *rest) if rest else new_hidden
|
| 91 |
+
|
| 92 |
+
for blk in model.model.layers:
|
| 93 |
+
blk.register_forward_hook(symp_hook)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# โโ 3. ใจใใซใฎใผใใชใใ่จๆธฌไปใ็ๆ้ขๆฐ โโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 97 |
@torch.no_grad()
|
| 98 |
+
def generate_with_drift(model, tok, prompt, max_new=128):
|
| 99 |
+
device = torch.device("cuda:0")
|
| 100 |
enc = tok(prompt, return_tensors="pt")
|
| 101 |
input_ids = enc["input_ids"].to(device)
|
| 102 |
attention_mask = enc["attention_mask"].to(device)
|
|
|
|
| 112 |
h = out.hidden_states[-1][:, -1]
|
| 113 |
q, p = h.chunk(2, dim=-1)
|
| 114 |
|
| 115 |
+
H_val = 0.5 * (p**2).sum(-1) + 0.5 * ฮฒ * (q**2).sum(-1)
|
|
|
|
| 116 |
H_list.append(H_val.item())
|
| 117 |
|
| 118 |
+
ฮH = abs(H_val.item() - H_list[0]) # drift relative to first step
|
| 119 |
temp = max(0.8 * math.exp(-0.1 * ฮH), 0.2)
|
| 120 |
|
| 121 |
nxt = model.generate(
|
|
|
|
| 125 |
temperature=temp,
|
| 126 |
do_sample=True,
|
| 127 |
pad_token_id=tok.eos_token_id,
|
| 128 |
+
return_full_text=False
|
| 129 |
)
|
|
|
|
| 130 |
next_token = nxt[:, -1].unsqueeze(-1)
|
| 131 |
input_ids = torch.cat([input_ids, next_token], dim=1)
|
| 132 |
attention_mask = torch.cat([attention_mask, torch.ones_like(next_token)], dim=1)
|
|
|
|
| 134 |
if next_token[0, 0] == tok.eos_token_id:
|
| 135 |
break
|
| 136 |
|
|
|
|
| 137 |
gen_ids = input_ids[0, initial_len:]
|
| 138 |
gen_text = tok.decode(gen_ids, skip_special_tokens=True)
|
| 139 |
+
return gen_text, H_list
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# โโ 4. ใกใคใณๅฆ็๏ผBaseline vs Symplectic ๆฏ่ผ โโโโโโโโโโโโโโโโโโโโโ
|
| 143 |
+
def main():
|
| 144 |
+
prompt = "Explain in about 250 tokens how symplectic integrators preserve energy in Hamiltonian systems."
|
| 145 |
+
|
| 146 |
+
results = {}
|
| 147 |
+
texts = {}
|
| 148 |
+
|
| 149 |
+
for mode in ["baseline", "symplectic"]:
|
| 150 |
+
model, tok = load_quantized_lora_model()
|
| 151 |
+
if mode == "symplectic":
|
| 152 |
+
register_symp_hook(model)
|
| 153 |
|
| 154 |
+
gen_text, H_list = generate_with_drift(model, tok, prompt)
|
| 155 |
+
results[mode] = H_list
|
| 156 |
+
texts[mode] = gen_text
|
| 157 |
+
|
| 158 |
+
print(f"\n=== {mode.upper()} Generation ===")
|
| 159 |
+
print(gen_text)
|
| 160 |
+
|
| 161 |
+
# ใใชใใๆฏ่ผใใญใใ
|
| 162 |
plt.figure()
|
| 163 |
+
plt.plot(results["baseline"], label="Baseline")
|
| 164 |
+
plt.plot(results["symplectic"], label="Symplectic")
|
| 165 |
plt.xlabel("Step")
|
| 166 |
plt.ylabel("Energy H(q,p)")
|
| 167 |
+
plt.title("Energy Drift: Baseline vs Symplectic")
|
| 168 |
+
plt.legend()
|
| 169 |
plt.tight_layout()
|
| 170 |
+
plt.savefig("drift_comparison.png")
|
| 171 |
+
plt.show()
|
| 172 |
+
|
| 173 |
+
print("\nComparison plot saved as drift_comparison.png")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
if __name__ == "__main__":
|
| 176 |
+
main()
|