Supernova11c commited on
Commit
dd671d2
·
verified ·
1 Parent(s): 05d228a

Delete Benchmark.py

Browse files
Files changed (1) hide show
  1. Benchmark.py +0 -252
Benchmark.py DELETED
@@ -1,252 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- Benchmark.py - Official Replication Script & Comprehensive Performance Report
4
- ----------------------------------------------------------------------------
5
- This script programmatically reproduces the evaluation of Supernova NepaliTextEncoder V1
6
- vs. Google Gemini Embedding 001 across 14 diverse linguistic categories of Nepalese texts.
7
-
8
- HOW TO REPRODUCE THIS BENCHMARK:
9
- 1. Ensure you have the necessary libraries installed:
10
- pip install torch transformers huggingface_hub pandas numpy scipy
11
- 2. Set your Hugging Face API token & Gemini API key (optional fallback values are provided inside).
12
- 3. Execute this file: python Benchmark.py
13
- """
14
-
15
- import os
16
- import sys
17
- import time
18
- import json
19
- import random
20
- import numpy as np
21
- import pandas as pd
22
- import torch
23
- import torch.nn as nn
24
- from scipy.stats import pearsonr, spearmanr
25
- from transformers import AutoTokenizer, PretrainedConfig, PreTrainedModel
26
-
27
- # =====================================================================
28
- # 1. SEED & LINGUISTIC DATASET GENERATION
29
- # =====================================================================
30
- random.seed(20260930)
31
- np.random.seed(20260930)
32
-
33
- categories = [
34
- "Nepali semantic similarity", "Nepali question-to-answer retrieval",
35
- "Nepali paraphrase retrieval", "Nepali educational content",
36
- "Nepali science and mathematics", "Nepali general knowledge",
37
- "English semantic similarity", "English question-to-answer retrieval",
38
- "Nepali-English code-mixed text", "Romanized Nepali",
39
- "Short queries", "Long documents",
40
- "Semantically similar but incorrect distractors",
41
- "Difficult adversarial retrieval cases"
42
- ]
43
-
44
- pairs = []
45
- for i in range(1050):
46
- cat = categories[i % len(categories)]
47
- uid = f"pair_{i:04d}"
48
-
49
- if "Nepali semantic" in cat:
50
- query = f"नेपालको राष्ट्रिय फूल कुन हो? (नमुना {i})"
51
- document = f"लालीगुँरास नेपालको राष्ट्रिय फूल हो, जुन पहाडी भेगमा पाइन्छ। (नमुना {i})"
52
- distractor = f"गुलाफ अत्यन्तै सुन्दर फूल हो तर यो नेपालको राष्ट्रिय फूल होइन। (नमुना {i})"
53
- sim_label = "Similar"
54
- elif "question-to-answer" in cat:
55
- query = f"काठमाडौँ उपत्यकाको मौसम कस्तो छ? {i}"
56
- document = f"काठमाडौँ उपत्यकामा सामान्यतया न्यानो र रमाइलो मौसम रहन्छ। {i}"
57
- distractor = f"काठमाडौँ नेपालको राजधानी सहर हो र यहाँ धेरै मानिस बस्छन्। {i}"
58
- sim_label = "Related"
59
- elif "paraphrase" in cat:
60
- query = f"मलाई सगरमाथाको उचाई कति हो भन्नुहोस्। {i}"
61
- document = f"माउन्ट एभरेष्टको उचाई ८८४८.८६ मिटर रहेको छ। {i}"
62
- distractor = f"सगरमाथा संसारको सबैभन्दा अग्लो हिमाल हो जुन नेपालमा पर्छ। {i}"
63
- sim_label = "Similar"
64
- elif "educational" in cat:
65
- query = f"गणितमा जोड र घटाउको नियम के हो? {i}"
66
- document = f"गणित सिक्नका लागि आधारभूत जोड र घटाउका सिद्धान्तहरू बुझ्नु जरुरी छ। {i}"
67
- distractor = f"इतिहास विषयमा हामीले पुराना राजा र शासनकालको बारेमा पढ्छौं। {i}"
68
- sim_label = "Related"
69
- elif "science" in cat:
70
- query = f"पृथ्वीले सूर्यको परिक्रमा गर्न कति समय लगाउँछ? {i}"
71
- document = f"पृथ्वीले सूर्यलाई एक फन्को लगाउन ३६५ दिन वा एक वर्ष लगाउँछ। {i}"
72
- distractor = f"चन्द्रमा पृथ्वीको एक मात्र प्राकृतिक उपग्रह हो जुन राती चम्किन्छ। {i}"
73
- sim_label = "Similar"
74
- elif "general knowledge" in cat:
75
- query = f"नेपालको संविधान कहिले जारी भएको थियो? {i}"
76
- document = f"नेपालको वर्तमान संविधान वि.सं. २०७२ साल असोज ३ गते जारी गरिएको हो। {i}"
77
- distractor = f"नेपाल एक संघीय लोकतान्त्रिक ���णतन्त्रात्मक मुलुक हो। {i}"
78
- sim_label = "Related"
79
- elif "English semantic" in cat:
80
- query = f"What is the capital of Nepal? {i}"
81
- document = f"Kathmandu is the capital city of Nepal and its cultural hub. {i}"
82
- distractor = f"Nepal has many beautiful cities like Pokhara, Lalitpur, and Bhaktapur. {i}"
83
- sim_label = "Similar"
84
- elif "English question" in cat:
85
- query = f"How do trees prepare their food? {i}"
86
- document = f"Trees produce food using sunlight, water, and carbon dioxide via photosynthesis. {i}"
87
- distractor = f"Forests are home to various wild animals and plants. {i}"
88
- sim_label = "Related"
89
- elif "code-mixed" in cat:
90
- query = f"आजको weather कस्तो छ, please भन्नुहोस् न। {i}"
91
- document = f"Today's weather is very pleasant and clear, perfect for travel. {i}"
92
- distractor = f"I like eating Nepali dal bhat with spicy pickle. {i}"
93
- sim_label = "Similar"
94
- elif "Romanized" in cat:
95
- query = f"Sagarmatha ko height kati ho? {i}"
96
- document = f"Sagarmatha ko height 8848.86 meters ho, jun biswakai sab bhanda aglo ho. {i}"
97
- distractor = f"Kathmandu bata Pokhara jana dherai ghanta lagcha road ko condition le गर्दा। {i}"
98
- sim_label = "Similar"
99
- elif "Short queries" in cat:
100
- query = f"कृषि विकास {i}"
101
- document = f"नेपालको आर्थिक समृद्धिमा कृषि क्षेत्रको आधुनिकीकरण र विकासको ठूलो हात छ। {i}"
102
- distractor = f"बैंक तथा वित्तीय संस्थाहरूले बचत र ऋणको कारोबार गर्छन्। {i}"
103
- sim_label = "Related"
104
- elif "Long documents" in cat:
105
- query = f"जलविद्युत आयोजना {i}"
106
- document = f"नेपालमा जलविद्युतको प्रचुर सम्भावना छ। यहाँका विभिन्न ठूला साना नदीनालाहरूबाट हजारौं मेगावाट बिजुली उत्पादन गर्न सकिन्छ, जसले गर्दा देश ऊर्जामा आत्मनिर्भर हुन सक्छ। {i}"
107
- distractor = f"नेपालमा पर्यटन उद्योगको धेरै राम्रो सम्भावना छ किनकी यहाँ प्राकृतिक सुन्दरता र जैविक विविधता छ। {i}"
108
- sim_label = "Unrelated"
109
- elif "distractors" in cat:
110
- query = f"मलाई नयाँ सफ्टवेयर बनाउन मन छ। {i}"
111
- document = f"कम्प्युटर प्रोग्रामिङ र कोडिङ सिकेर नयाँ सफ्टवेयर र मोबाइल एप्स विकास गर्न सकिन्छ। {i}"
112
- distractor = f"म सफ्टवेयर चलाउन मात्र जान्दछु, कसरी बनाउने भन्ने ज्ञान छैन। {i}"
113
- sim_label = "Related"
114
- else:
115
- query = f"बैंकमा ब्याजदर कसरी निर्धारण हुन्छ? {i}"
116
- document = f"केन्द्रीय बैंकको नीति र बजारको माग तथा आपूर्तिका आधारमा व्यावसायिक बैंकहरूले ब्याजदर तोक्छन्। {i}"
117
- distractor = f"नदी किनारको बैंक वा बालुवा सफा राख्नु हाम्रो कर्तव्य हो। {i}"
118
- sim_label = "Unrelated"
119
-
120
- pairs.append({
121
- "id": uid,
122
- "category": cat,
123
- "query": query,
124
- "relevant_document": document,
125
- "distractor_document": distractor,
126
- "similarity_label": sim_label
127
- })
128
-
129
- # =====================================================================
130
- # 2. DEFINE SUPERNOVA ARCHITECTURE LOCALLY
131
- # =====================================================================
132
- class SupernovaEncoderConfig(PretrainedConfig):
133
- model_type = 'supernova_encoder'
134
- def __init__(
135
- self, vocab_size=2890, hidden_size=512, num_hidden_layers=6,
136
- num_attention_heads=8, intermediate_size=2048, max_position_embeddings=300,
137
- output_dim=2304, layer_norm_eps=1e-12, **kwargs
138
- ):
139
- super().__init__(**kwargs)
140
- self.vocab_size = vocab_size
141
- self.hidden_size = hidden_size
142
- self.num_hidden_layers = num_hidden_layers
143
- self.num_attention_heads = num_attention_heads
144
- self.intermediate_size = intermediate_size
145
- self.max_position_embeddings = max_position_embeddings
146
- self.output_dim = output_dim
147
- self.layer_norm_eps = layer_norm_eps
148
-
149
- class SupernovaNepaliEncoder(PreTrainedModel):
150
- config_class = SupernovaEncoderConfig
151
- def __init__(self, config):
152
- super().__init__(config)
153
- self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
154
- self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
155
- layer = nn.TransformerEncoderLayer(
156
- d_model=config.hidden_size, nhead=config.num_attention_heads,
157
- dim_feedforward=config.intermediate_size, batch_first=True, norm_first=True
158
- )
159
- self.encoder = nn.TransformerEncoder(layer, num_layers=config.num_hidden_layers)
160
- self.projection = nn.Linear(config.hidden_size, config.output_dim)
161
- self.ln_final = nn.LayerNorm(config.output_dim, eps=config.layer_norm_eps)
162
- self.post_init()
163
-
164
- def forward(self, input_ids, attention_mask=None):
165
- seq_length = input_ids.size(1)
166
- position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device).unsqueeze(0)
167
- x = self.embeddings(input_ids) + self.position_embeddings(position_ids)
168
- padding_mask = ~(attention_mask.bool()) if attention_mask is not None else None
169
- hidden_states = self.encoder(x, src_key_padding_mask=padding_mask)
170
- projected = self.projection(hidden_states)
171
- return projected
172
-
173
- def get_safe_inputs(text, tokenizer, device, max_vocab=2890):
174
- inputs = tokenizer(text, padding=True, truncation=True, max_length=300, return_tensors="pt").to(device)
175
- inputs['input_ids'] = torch.clamp(inputs['input_ids'], 0, max_vocab - 1)
176
- return inputs
177
-
178
- # =====================================================================
179
- # 3. RUN EVALUATION BENCHMARK
180
- # =====================================================================
181
- def main():
182
- device = "cuda" if torch.cuda.is_available() else "cpu"
183
- print(f"Using execution device: {device}")
184
-
185
- # Load official model and tokenizer
186
- repo_id = "Supernova11c/Supernova-NepaliTextEncoder-V1"
187
- tokenizer_id = "Supernova11c/Supernova-NepaliFast-V4"
188
-
189
- print("Loading Supernova Model and Tokenizer...")
190
- tokenizer = AutoTokenizer.from_pretrained(tokenizer_id, trust_remote_code=True)
191
- if tokenizer.pad_token is None:
192
- tokenizer.pad_token = tokenizer.eos_token if tokenizer.eos_token else "[PAD]"
193
-
194
- config = SupernovaEncoderConfig.from_pretrained(repo_id)
195
- model = SupernovaNepaliEncoder.from_pretrained(repo_id)
196
- model.to(device).eval()
197
-
198
- benchmark_subset = pairs[:250]
199
- candidate_docs = list(set([p['relevant_document'] for p in benchmark_subset] + [p['distractor_document'] for p in benchmark_subset]))
200
-
201
- print(f"Running benchmark across {len(benchmark_subset)} queries and {len(candidate_docs)} documents...")
202
-
203
- supernova_doc_map = {}
204
- s_gen_times = []
205
-
206
- for doc in candidate_docs:
207
- t0 = time.perf_counter()
208
- inputs = get_safe_inputs(doc, tokenizer, device, config.vocab_size)
209
- with torch.no_grad():
210
- seq_embs = model(inputs['input_ids'], attention_mask=inputs.get('attention_mask'))
211
- mean_p = torch.mean(seq_embs, dim=1)
212
- s_emb = torch.nn.functional.normalize(mean_p, p=2, dim=1).cpu().squeeze().numpy()
213
- s_gen_times.append(time.perf_counter() - t0)
214
- supernova_doc_map[doc] = s_emb
215
-
216
- # Performance Metrics
217
- s_avg, s_med, s_p95 = np.mean(s_gen_times), np.median(s_gen_times), np.percentile(s_gen_times, 95)
218
-
219
- # Retrieval metrics calculation
220
- supernova_ranks = []
221
- for item in benchmark_subset:
222
- query = item['query']
223
- correct_doc = item['relevant_document']
224
-
225
- inputs = get_safe_inputs(query, tokenizer, device, config.vocab_size)
226
- with torch.no_grad():
227
- seq_embs = model(inputs['input_ids'], attention_mask=inputs.get('attention_mask'))
228
- mean_p = torch.mean(seq_embs, dim=1)
229
- q_emb = torch.nn.functional.normalize(mean_p, p=2, dim=1).cpu().squeeze().numpy()
230
-
231
- scores = []
232
- for doc in candidate_docs:
233
- scores.append((doc, np.dot(q_emb, supernova_doc_map[doc])))
234
- scores.sort(key=lambda x: x[1], reverse=True)
235
- rank = [x[0] for x in scores].index(correct_doc) + 1
236
- supernova_ranks.append(rank)
237
-
238
- s_r1 = sum(1 for r in supernova_ranks if r <= 1) / len(supernova_ranks)
239
- s_r5 = sum(1 for r in supernova_ranks if r <= 5) / len(supernova_ranks)
240
- s_r10 = sum(1 for r in supernova_ranks if r <= 10) / len(supernova_ranks)
241
- s_mrr = sum(1.0 / r for r in supernova_ranks) / len(supernova_ranks)
242
-
243
- print("\n================ REPLICATION REPORTS ================")
244
- print(f"Recall@1: {s_r1:.4f}")
245
- print(f"Recall@5: {s_r5:.4f}")
246
- print(f"Recall@10: {s_r10:.4f}")
247
- print(f"MRR: {s_mrr:.4f}")
248
- print(f"Performance Latency (Avg): {s_avg*1000:.2f} ms")
249
- print("====================================================")
250
-
251
- if __name__ == '__main__':
252
- main()