File size: 12,124 Bytes
0987091 |
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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
import json
from typing import List, Dict, Tuple
import time
# ์ฃผ์: ์ด๊ฒ์ SEAL ๋
ผ๋ฌธ์ ๊ฐ๋
์ ๋ณด์ฌ์ฃผ๋ ๋จ์ํ๋ ๋ฐ๋ชจ์
๋๋ค.
# ์ค์ ๊ตฌํ์์๋ LoRA ํ์ธํ๋๊ณผ ์ ์ฒด RL ๋ฃจํ๊ฐ ํ์ํฉ๋๋ค.
class SEALDemo:
def __init__(self):
# ์ค์ ๋ก๋ Qwen2.5-7B๋ฅผ ์ฌ์ฉํ์ง๋ง, ๋ฐ๋ชจ์์๋ ์์ ๋ชจ๋ธ ์ฌ์ฉ
self.model_name = "gpt2"
print("Loading model...")
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
self.model = AutoModelForCausalLM.from_pretrained(self.model_name)
self.tokenizer.pad_token = self.tokenizer.eos_token
# ์๋ฎฌ๋ ์ด์
์ ์ํ ๊ฐ์์ self-edit ํจ๊ณผ
self.adaptation_history = []
def generate_self_edit(self, passage: str, edit_type: str = "implications") -> str:
"""์ฃผ์ด์ง passage์ ๋ํ self-edit ์์ฑ"""
prompts = {
"implications": f"Let's read the following passage and produce a list of implications derived directly or indirectly from the content.\n\nPassage:\n{passage}\n\nImplications:\n",
"rewrite": f"Let's read the following passage and rewrite it in a few different ways, each one separated by a newline.\n\nPassage:\n{passage}\n\nRewritten passages:\n",
"qa": f"Let's read the following passage and rewrite it in a question-answer format.\n\nPassage:\n{passage}\n\nQuestion 1:\n"
}
prompt = prompts.get(edit_type, prompts["implications"])
# ์ค์ ์์ฑ (๋ฐ๋ชจ์ฉ์ผ๋ก ๊ฐ๋จํ๊ฒ)
inputs = self.tokenizer(prompt, return_tensors="pt", max_length=512, truncation=True)
with torch.no_grad():
outputs = self.model.generate(
inputs.input_ids,
max_new_tokens=200,
temperature=0.8,
do_sample=True,
top_p=0.9,
pad_token_id=self.tokenizer.eos_token_id
)
generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
self_edit = generated_text[len(prompt):].strip()
# ๋ฐ๋ชจ๋ฅผ ์ํ ์์ self-edit ์ถ๊ฐ (์ค์ ๋ชจ๋ธ์ด ์์ฑํ์ง ๋ชปํ ๊ฒฝ์ฐ๋ฅผ ๋๋น)
if len(self_edit) < 50:
if edit_type == "implications":
self_edit = """1. The information in this passage can be used to answer specific questions about the content.
2. Understanding this passage requires identifying key facts and their relationships.
3. The main concepts should be broken down into smaller, learnable components.
4. Each fact in the passage has potential implications for related topics.
5. This content can be restructured to improve learning and retention."""
elif edit_type == "rewrite":
self_edit = f"""Version 1: {passage[:100]}...
Version 2: The key information from this passage includes...
Version 3: In summary, this passage discusses..."""
else: # qa
self_edit = """Question 1: What is the main topic of this passage?
Answer: The passage discusses...
Question 2: What are the key facts mentioned?
Answer: The key facts include..."""
return self_edit
def simulate_adaptation(self, passage: str, self_edit: str) -> Dict[str, float]:
"""self-edit๋ฅผ ์ฌ์ฉํ ์ ์ ๊ณผ์ ์๋ฎฌ๋ ์ด์
"""
# ์ค์ ๋ก๋ LoRA ํ์ธํ๋์ ์ํํ์ง๋ง, ์ฌ๊ธฐ์๋ ์๋ฎฌ๋ ์ด์
adaptation_score = len(self_edit.split('\n')) * 0.1 # ๋ ๋ง์ implications = ๋ ๋์ ์ ์
# ์ ์ ๊ธฐ๋ก ์ ์ฅ
self.adaptation_history.append({
"passage": passage[:100] + "...",
"self_edit_lines": len(self_edit.split('\n')),
"adaptation_score": adaptation_score
})
return {
"original_performance": 0.33, # ๋
ผ๋ฌธ์ baseline
"adapted_performance": min(0.33 + adaptation_score, 0.47), # ๋
ผ๋ฌธ์ SEAL ์ฑ๋ฅ
"improvement": min(adaptation_score, 0.14)
}
def answer_question(self, question: str, passage: str, use_adaptation: bool) -> Tuple[str, float]:
"""์ง๋ฌธ์ ๋ํ ๋ต๋ณ ์์ฑ (์ ์ ์ /ํ ๋น๊ต)"""
if use_adaptation:
# ์ ์๋ ๋ชจ๋ธ๋ก ๋ต๋ณ (์๋ฎฌ๋ ์ด์
)
prompt = f"Based on the learned information, answer this question concisely:\n\nQuestion: {question}\nAnswer:"
confidence = 0.8
else:
# ์๋ณธ ๋ชจ๋ธ๋ก ๋ต๋ณ
prompt = f"Answer this question:\n\nQuestion: {question}\nAnswer:"
confidence = 0.3
inputs = self.tokenizer(prompt, return_tensors="pt", max_length=256, truncation=True)
with torch.no_grad():
outputs = self.model.generate(
inputs.input_ids,
max_new_tokens=50,
temperature=0.7,
do_sample=True,
pad_token_id=self.tokenizer.eos_token_id
)
answer = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
answer = answer[len(prompt):].strip()
# ๋ต๋ณ์ด ๋๋ฌด ์งง์ผ๋ฉด ๊ธฐ๋ณธ ๋ต๋ณ ์ ๊ณต
if len(answer) < 10:
answer = "The model cannot provide a confident answer without adaptation." if not use_adaptation else "Based on the adapted knowledge, the answer is [specific to the passage content]."
return answer, confidence
# ์ ์ญ ์ธ์คํด์ค
demo = SEALDemo()
def process_seal_adaptation(passage, edit_type, question):
"""SEAL ์ ์ ํ๋ก์ธ์ค ์คํ"""
if not passage or not question:
return "Please provide both a passage and a question.", "", {}, "", ""
# 1. Self-edit ์์ฑ
self_edit = demo.generate_self_edit(passage, edit_type)
# 2. ์ ์ ์๋ฎฌ๋ ์ด์
adaptation_results = demo.simulate_adaptation(passage, self_edit)
# 3. ์ง๋ฌธ์ ๋ํ ๋ต๋ณ (์ ์ ์ /ํ)
answer_before, conf_before = demo.answer_question(question, passage, use_adaptation=False)
answer_after, conf_after = demo.answer_question(question, passage, use_adaptation=True)
# ๊ฒฐ๊ณผ ํฌ๋งทํ
results_text = f"""๐ Adaptation Results:
Original Model Performance: {adaptation_results['original_performance']:.1%}
Adapted Model Performance: {adaptation_results['adapted_performance']:.1%}
Improvement: +{adaptation_results['improvement']:.1%}
๐ Answer Confidence:
Before Adaptation: {conf_before:.1%}
After Adaptation: {conf_after:.1%}"""
return self_edit, results_text, adaptation_results, answer_before, answer_after
def visualize_rl_process():
"""RL ํ๋ จ ๊ณผ์ ์๊ฐํ (๋
ผ๋ฌธ Figure 4 ์ฌํ)"""
# ๋
ผ๋ฌธ์ RL iteration ๊ฒฐ๊ณผ ์๋ฎฌ๋ ์ด์
iterations = [0, 1, 2]
performance = [33.5, 43.7, 47.0] # ๋
ผ๋ฌธ์ ์ค์ ์์น
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 6))
# ๋ค์ํ ๋ฐฉ๋ฒ๋ค์ ์ฑ๋ฅ
methods = {
'Base Model': 32.7,
'Raw Passage': 33.5,
'Base Model Synthetic': 39.7,
'GPT-4.1 Synthetic': 46.3,
}
# ์ํ์ ์ผ๋ก baseline ํ์
for method, score in methods.items():
ax.axhline(y=score, linestyle='--', alpha=0.5, label=method)
# SEAL ์ฑ๋ฅ ๊ณก์
ax.plot(iterations, performance, 'ro-', linewidth=2, markersize=8, label='SEAL')
ax.set_xlabel('ReSTEM RL Training Iterations')
ax.set_ylabel('Knowledge Incorporation (%)')
ax.set_title('Single-Passage Knowledge Incorporation Performance')
ax.legend()
ax.grid(True, alpha=0.3)
ax.set_ylim(30, 50)
return fig
# Gradio ์ธํฐํ์ด์ค
with gr.Blocks(title="SEAL: Self-Adapting Language Models Demo") as interface:
gr.Markdown("""
# ๐ SEAL: Self-Adapting Language Models Demo
This demo illustrates the key concepts from the paper "Self-Adapting Language Models" (Zweiger et al., 2025).
SEAL enables LLMs to self-adapt by generating their own finetuning data and update directives.
## ๐ How it works:
1. **Input a passage** containing new information
2. **Model generates self-edits** (implications, rewrites, or Q&A pairs)
3. **Simulated adaptation** using the self-edits
4. **Compare performance** before and after adaptation
""")
with gr.Tab("Knowledge Incorporation"):
with gr.Row():
with gr.Column():
passage_input = gr.Textbox(
label="๐ Input Passage",
placeholder="Enter a passage with factual information...",
lines=8,
value="The Apollo program faced significant challenges before achieving its goal. Kennedy's science advisor, Jerome Wiesner, initially opposed manned spacecraft flights. Despite internal disagreements at NASA, the program eventually succeeded in landing humans on the Moon in 1969."
)
edit_type = gr.Radio(
choices=["implications", "rewrite", "qa"],
value="implications",
label="Self-Edit Type"
)
question_input = gr.Textbox(
label="โ Test Question",
placeholder="Enter a question about the passage...",
value="Who was Kennedy's science advisor?"
)
adapt_btn = gr.Button("๐ Run SEAL Adaptation", variant="primary")
with gr.Column():
self_edit_output = gr.Textbox(
label="๐ค Generated Self-Edit",
lines=8
)
results_output = gr.Textbox(
label="๐ Adaptation Results",
lines=6
)
with gr.Row():
answer_before = gr.Textbox(
label="โ Answer Before Adaptation",
lines=2
)
answer_after = gr.Textbox(
label="โ
Answer After Adaptation",
lines=2
)
adapt_btn.click(
process_seal_adaptation,
inputs=[passage_input, edit_type, question_input],
outputs=[self_edit_output, results_output, gr.State(), answer_before, answer_after]
)
with gr.Tab("RL Training Visualization"):
gr.Markdown("""
## ๐ Reinforcement Learning Training Process
This visualization shows how SEAL improves over RL iterations, eventually surpassing even GPT-4.1 synthetic data.
""")
plot_btn = gr.Button("Generate Performance Plot")
plot_output = gr.Plot()
plot_btn.click(visualize_rl_process, outputs=plot_output)
with gr.Tab("Paper Overview"):
gr.Markdown("""
## ๐ Key Contributions
1. **Self-Edits**: Models generate their own training data in natural language
2. **RL Training**: Use reinforcement learning to optimize self-edit generation
3. **Two Applications**:
- Knowledge Incorporation: 47.0% accuracy (vs 33.5% baseline)
- Few-shot Learning: 72.5% success rate on ARC tasks
## ๐ง Technical Details
- **Base Models**: Qwen2.5-7B (knowledge), Llama-3.2-1B (few-shot)
- **Optimization**: ReSTEM (rejection sampling + SFT)
- **Adaptation**: LoRA for efficient weight updates
- **Reward Signal**: Downstream task performance
## โ ๏ธ Demo Limitations
This demo simulates the core concepts but doesn't perform actual LoRA finetuning or full RL training due to computational constraints.
""")
if __name__ == "__main__":
interface.launch() |