kayrahan35 commited on
Commit
8b4fbe2
·
verified ·
1 Parent(s): 401e3ae

Delete benchmark_quality.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. benchmark_quality.py +0 -250
benchmark_quality.py DELETED
@@ -1,250 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- from torch.utils.data import DataLoader, TensorDataset
4
- from transformers import AutoTokenizer, GPT2Config, GPT2LMHeadModel
5
- import matplotlib.pyplot as plt
6
- import os
7
- import math
8
- import numpy as np
9
- import urllib.request
10
- import zipfile
11
-
12
- def download_and_prepare_data(tokenizer):
13
- print("Veri Seti İndiriliyor (Tiny Shakespeare)...")
14
- url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt"
15
- txt_path = "tinyshakespeare.txt"
16
-
17
- if not os.path.exists(txt_path):
18
- urllib.request.urlretrieve(url, txt_path)
19
-
20
- with open(txt_path, 'r', encoding='utf-8') as f:
21
- text = f.read()
22
-
23
- print("Tokenizasyon Başlıyor...")
24
- # Train / Val Split (%90 Train, %10 Val)
25
- split_idx = int(len(text) * 0.9)
26
- train_text = text[:split_idx]
27
- val_text = text[split_idx:]
28
-
29
- train_enc = tokenizer(train_text, return_tensors='pt', truncation=False)['input_ids'][0]
30
- val_enc = tokenizer(val_text, return_tensors='pt', truncation=False)['input_ids'][0]
31
-
32
- seq_len = 64
33
-
34
- def chunk_data(data):
35
- chunks = []
36
- for i in range(0, len(data) - seq_len, seq_len):
37
- chunks.append(data[i:i+seq_len])
38
- return torch.stack(chunks)
39
-
40
- train_chunks = chunk_data(train_enc)
41
- val_chunks = chunk_data(val_enc)
42
-
43
- train_ds = TensorDataset(train_chunks)
44
- val_ds = TensorDataset(val_chunks)
45
-
46
- print(f"Train Büyüklüğü: {len(train_ds)} batch | Val Büyüklüğü: {len(val_ds)} batch")
47
- return train_ds, val_ds
48
-
49
- def generate_text(model, tokenizer, device, prompt="The theory of general relativity", max_tokens=20):
50
- model.eval()
51
- input_ids = tokenizer(prompt, return_tensors='pt')['input_ids'].to(device)
52
-
53
- with torch.no_grad():
54
- for _ in range(max_tokens):
55
- try:
56
- outputs = model(input_ids)
57
- next_token_logits = outputs.logits[:, -1, :]
58
- next_token = torch.argmax(next_token_logits, dim=-1).unsqueeze(-1)
59
- input_ids = torch.cat([input_ids, next_token], dim=-1)
60
- except AttributeError:
61
- # If HFP Model
62
- outputs = model(input_ids)
63
- next_token_logits = outputs.logits[:, -1, :]
64
- next_token = torch.argmax(next_token_logits, dim=-1).unsqueeze(-1)
65
- input_ids = torch.cat([input_ids, next_token], dim=-1)
66
-
67
- generated = tokenizer.decode(input_ids[0])
68
- model.train()
69
- return generated
70
-
71
- def benchmark_quality():
72
- print("=== HFP vs Standard Transformer: Akademik Kalite Testi (Multi-Seed) ===")
73
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
74
- print(f"Cihaz: {device}")
75
-
76
- tokenizer = AutoTokenizer.from_pretrained("gpt2")
77
- tokenizer.pad_token = tokenizer.eos_token
78
- vocab_size = len(tokenizer)
79
-
80
- train_ds, val_ds = download_and_prepare_data(tokenizer)
81
-
82
- # 3 Farklı Seed ile hata payı/varyans hesaplama
83
- seeds = [42, 100, 999]
84
- max_steps = min(300, len(train_ds) // 4)
85
- val_interval = 25
86
-
87
- all_std_val_losses = []
88
- all_hfp_val_losses = []
89
- eval_steps = []
90
-
91
- from hfp.models.configuration_hfp import HFPConfig
92
- from hfp.models.modeling_hfp import HFPForCausalLM
93
-
94
- hidden_size = 256
95
- num_layers = 4
96
- num_heads = 4
97
-
98
- best_hfp_model = None
99
- best_std_model = None
100
-
101
- for seed_idx, seed in enumerate(seeds):
102
- print(f"\n--- Seed {seed_idx+1}/3: {seed} ---")
103
- torch.manual_seed(seed)
104
-
105
- train_loader = DataLoader(train_ds, batch_size=4, shuffle=True)
106
- val_loader = DataLoader(val_ds, batch_size=8)
107
-
108
- std_config = GPT2Config(vocab_size=vocab_size, n_embd=hidden_size, n_head=num_heads, n_layer=num_layers, n_inner=512)
109
- std_model = GPT2LMHeadModel(std_config).to(device)
110
-
111
- hfp_config = HFPConfig(vocab_size=vocab_size, hidden_size=hidden_size, num_hidden_layers=num_layers, num_attention_heads=num_heads, intermediate_size=512, short_len=8, bulk_dim=32)
112
- hfp_model = HFPForCausalLM(hfp_config).to(device)
113
-
114
- std_optim = torch.optim.AdamW(std_model.parameters(), lr=5e-4)
115
- hfp_optim = torch.optim.AdamW(hfp_model.parameters(), lr=5e-4)
116
-
117
- std_losses = []
118
- hfp_losses = []
119
- current_eval_steps = []
120
-
121
- def evaluate(model):
122
- model.eval()
123
- total_loss = 0
124
- with torch.no_grad():
125
- for batch in val_loader:
126
- inputs = batch[0].to(device)
127
- outputs = model(inputs)
128
- logits = outputs.logits
129
- shift_logits = logits[..., :-1, :].contiguous()
130
- shift_labels = inputs[..., 1:].contiguous()
131
- loss = nn.functional.cross_entropy(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
132
- total_loss += loss.item()
133
- model.train()
134
- return total_loss / len(val_loader)
135
-
136
- std_model.train()
137
- hfp_model.train()
138
-
139
- step = 0
140
- for batch in train_loader:
141
- if step > max_steps:
142
- break
143
-
144
- inputs = batch[0].to(device)
145
-
146
- # Train Std
147
- std_optim.zero_grad()
148
- out_std = std_model(inputs)
149
- std_loss = nn.functional.cross_entropy(out_std.logits[..., :-1, :].contiguous().view(-1, out_std.logits.size(-1)), inputs[..., 1:].contiguous().view(-1))
150
- std_loss.backward()
151
- std_optim.step()
152
-
153
- # Train HFP
154
- hfp_optim.zero_grad()
155
- out_hfp = hfp_model(inputs)
156
- hfp_loss = nn.functional.cross_entropy(out_hfp.logits[..., :-1, :].contiguous().view(-1, out_hfp.logits.size(-1)), inputs[..., 1:].contiguous().view(-1))
157
- hfp_loss.backward()
158
- hfp_optim.step()
159
-
160
- if step % val_interval == 0:
161
- std_vloss = evaluate(std_model)
162
- hfp_vloss = evaluate(hfp_model)
163
- std_losses.append(std_vloss)
164
- hfp_losses.append(hfp_vloss)
165
- if seed_idx == 0:
166
- current_eval_steps.append(step)
167
- print(f"Adım {step}/{max_steps} | Std Val: {std_vloss:.4f} | HFP Val: {hfp_vloss:.4f}")
168
-
169
- step += 1
170
-
171
- all_std_val_losses.append(std_losses)
172
- all_hfp_val_losses.append(hfp_losses)
173
-
174
- if seed_idx == 0:
175
- eval_steps = current_eval_steps
176
- best_hfp_model = hfp_model
177
- best_std_model = std_model
178
-
179
- print("\nMetin Üretimi (Qualitative Check) Yapılıyor...")
180
- prompt = "The theory of general relativity"
181
- hfp_gen = generate_text(best_hfp_model, tokenizer, device, prompt)
182
- std_gen = generate_text(best_std_model, tokenizer, device, prompt)
183
-
184
- print(f"\n[STANDART MODEL ÜRETİMİ]:\n{std_gen}")
185
- print(f"\n[HFP MODEL ÜRETİMİ]:\n{hfp_gen}")
186
-
187
- # Mean ve Std hesaplama
188
- std_arr = np.array(all_std_val_losses)
189
- hfp_arr = np.array(all_hfp_val_losses)
190
-
191
- std_mean = std_arr.mean(axis=0)
192
- std_std = std_arr.std(axis=0)
193
-
194
- hfp_mean = hfp_arr.mean(axis=0)
195
- hfp_std = hfp_arr.std(axis=0)
196
-
197
- # PPL (Perplexity)
198
- # Ortalama PPL
199
- std_ppl = np.exp(np.clip(std_mean, a_min=None, a_max=20))
200
- hfp_ppl = np.exp(np.clip(hfp_mean, a_min=None, a_max=20))
201
-
202
- # Üst ve Alt Band PPL
203
- std_ppl_upper = np.exp(np.clip(std_mean + std_std, a_min=None, a_max=20))
204
- std_ppl_lower = np.exp(np.clip(std_mean - std_std, a_min=None, a_max=20))
205
-
206
- hfp_ppl_upper = np.exp(np.clip(hfp_mean + hfp_std, a_min=None, a_max=20))
207
- hfp_ppl_lower = np.exp(np.clip(hfp_mean - hfp_std, a_min=None, a_max=20))
208
-
209
- plt.style.use('ggplot')
210
- plt.figure(figsize=(14, 6))
211
-
212
- # Doğrulama Kaybı (Gölgeli)
213
- ax1 = plt.subplot(1, 2, 1)
214
- ax1.plot(eval_steps, hfp_mean, label="HFP Bulk (Mean)", color='#2ca02c', linewidth=2.5)
215
- ax1.fill_between(eval_steps, hfp_mean - hfp_std, hfp_mean + hfp_std, color='#2ca02c', alpha=0.2)
216
-
217
- ax1.plot(eval_steps, std_mean, label="Standart Transformer (Mean)", color='#1f77b4', linewidth=2.5, linestyle='--')
218
- ax1.fill_between(eval_steps, std_mean - std_std, std_mean + std_std, color='#1f77b4', alpha=0.2)
219
-
220
- ax1.set_title("WikiText-2 Validation Loss (3 Seeds)\n(Daha düşük daha iyidir)")
221
- ax1.set_xlabel("Eğitim Adımı")
222
- ax1.set_ylabel("Cross-Entropy Loss")
223
- ax1.legend()
224
-
225
- # Perplexity (Gölgeli)
226
- ax2 = plt.subplot(1, 2, 2)
227
- ax2.plot(eval_steps, hfp_ppl, label="HFP Bulk (Mean)", color='#2ca02c', linewidth=2.5)
228
- ax2.fill_between(eval_steps, hfp_ppl_lower, hfp_ppl_upper, color='#2ca02c', alpha=0.2)
229
-
230
- ax2.plot(eval_steps, std_ppl, label="Standart Transformer (Mean)", color='#1f77b4', linewidth=2.5, linestyle='--')
231
- ax2.fill_between(eval_steps, std_ppl_lower, std_ppl_upper, color='#1f77b4', alpha=0.2)
232
-
233
- ax2.set_title("WikiText-2 Validation Perplexity (3 Seeds)\n(Sıfıra Çakılmaz, Doğal Bir Sınıra Yakınsar)")
234
- ax2.set_xlabel("Eğitim Adımı")
235
- ax2.set_ylabel("Perplexity")
236
- ax2.legend()
237
-
238
- plt.tight_layout()
239
- plot_path = os.path.join(os.path.dirname(__file__), "benchmark_quality_results.png")
240
- plt.savefig(plot_path, dpi=150)
241
- print(f"Başarılı! Grafik kaydedildi: {plot_path}")
242
-
243
- with open("benchmark_text_samples.txt", "w", encoding="utf-8") as f:
244
- f.write("[STANDART MODEL URETIMI]\n")
245
- f.write(std_gen + "\n\n")
246
- f.write("[HFP MODEL URETIMI]\n")
247
- f.write(hfp_gen + "\n")
248
-
249
- if __name__ == "__main__":
250
- benchmark_quality()