UTKojima commited on
Commit
cb6c33b
ยท
verified ยท
1 Parent(s): 0bd6c9a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -100
app.py CHANGED
@@ -4,13 +4,17 @@ import math
4
 
5
  import torch
6
  import matplotlib.pyplot as plt
7
- from PIL import Image
8
- import gradio as gr
 
 
 
 
 
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
- # โ”€โ”€ 2. ใƒขใƒ‡ใƒซใƒญใƒผใƒ‰ & GPU ๅ›บๅฎš โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
44
- model = AutoModelForCausalLM.from_pretrained(
45
- MODEL_ID,
46
- quantization_config=bnb_cfg,
47
- device_map={"": "cuda:0"},
48
- torch_dtype=torch.float16,
49
- low_cpu_mem_usage=True,
50
- )
51
- model.gradient_checkpointing_enable()
52
- print("๐Ÿ’พ model loaded")
53
-
54
- # โ”€โ”€ 3. ๆฎ‹็•™ใ™ใ‚‹ CPU ไธŠใƒ‘ใƒฉใƒกใƒผใ‚ฟใ‚’ใ™ในใฆ GPU:0 ใซ็งปๅ‹• โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
55
- device = torch.device("cuda:0")
56
- for name, param in model.named_parameters():
57
- if param.device != device:
58
- param.data = param.data.to(device)
59
- for name, buf in model.named_buffers():
60
- if buf.device != device:
61
- buf.data = buf.data.to(device)
62
- print(f"๐Ÿ”„ Moved all parameters/buffers to {device}")
63
-
64
- # โ”€โ”€ 4. ใ‚ทใƒณใƒ—ใƒฌใ‚ฏใƒ†ใ‚ฃใƒƒใ‚ฏ่ฃœๆญฃใƒ•ใƒƒใ‚ฏ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
65
- ฮ”t, ฮฒ = 1e-2, 1e-4
66
-
67
- def symp_hook(module, input_, out):
68
- # out ใŒใ‚ฟใƒ—ใƒซใ‹ใƒ†ใƒณใ‚ฝใƒซใ‹ๅˆคๅฎš
69
- if isinstance(out, tuple):
70
- hidden, *rest = out
71
- else:
72
- hidden = out
73
- rest = []
74
- # 2 ๅˆ†ๅ‰ฒใ—ใฆๆ›ดๆ–ฐ
75
- q, p = hidden.chunk(2, dim=-1)
76
- p.sub_(ฮ”t * ฮฒ * q)
77
- q.add_(ฮ”t * p)
78
- new_hidden = torch.cat([q, p], dim=-1)
79
- return (new_hidden, *rest) if rest else new_hidden
80
-
81
- for blk in model.model.layers:
82
- blk.register_forward_hook(symp_hook)
83
- print("๐Ÿ”ง symplectic hooks attached")
84
-
85
- # โ”€โ”€ 5. LoRA ้ฉ็”จ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
86
- lora_cfg = LoraConfig(
87
- r=16, lora_alpha=32, lora_dropout=0.05,
88
- target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
89
- )
90
- model = get_peft_model(model, lora_cfg)
91
- print("๐ŸŽ›๏ธ LoRA adapters ready")
92
-
93
- # โ”€โ”€ 6. ็”Ÿๆˆ้–ขๆ•ฐ๏ผ‹ใ‚จใƒใƒซใ‚ฎใƒผใƒ‰ใƒชใƒ•ใƒˆๅฏ่ฆ–ๅŒ– โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  @torch.no_grad()
95
- def symp_generate_with_drift(prompt: str, max_new: int = 128):
 
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 = 0.5 * (p**2).sum(-1) + 0.5 * ฮฒ * (q**2).sum(-1)
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() - H_mean.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
- buf = io.BytesIO()
 
 
 
 
 
 
140
  plt.figure()
141
- plt.plot(H_list, marker="o")
 
142
  plt.xlabel("Step")
143
  plt.ylabel("Energy H(q,p)")
144
- plt.title("Hidden-state Energy Drift")
 
145
  plt.tight_layout()
146
- plt.savefig(buf, format="png")
147
- plt.close()
148
- buf.seek(0)
149
- img = Image.open(buf)
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
- iface.launch()
 
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()