Diksha2001 commited on
Commit
da55dcc
·
verified ·
1 Parent(s): a0ae865

Create Llm_Evaluation.py

Browse files
Files changed (1) hide show
  1. Llm_Evaluation.py +131 -0
Llm_Evaluation.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from sentence_transformers import SentenceTransformer, util
3
+ import nltk
4
+ from openai import OpenAI
5
+ import os
6
+ from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
7
+ import time
8
+ import asyncio
9
+ import logging
10
+ import sys
11
+ # Configure logging
12
+ logging.basicConfig(level=logging.INFO)
13
+ # Download necessary NLTK resources
14
+ nltk.download('punkt')
15
+ def load_input_data():
16
+ """Load input data from command line arguments."""
17
+ try:
18
+ input_data = json.loads(sys.argv[1])
19
+ return input_data
20
+ except json.JSONDecodeError as e:
21
+ logging.error(f"Failed to decode JSON input: {e}")
22
+ sys.exit(1)
23
+
24
+ def initialize_openai_client(api_key, base_url):
25
+ """Initialize the OpenAI client."""
26
+ return OpenAI(api_key=api_key, base_url=base_url)
27
+
28
+ def load_model():
29
+ """Load the pre-trained models for evaluation."""
30
+ semantic_model = SentenceTransformer('all-MiniLM-L6-v2')
31
+ return semantic_model
32
+
33
+ def evaluate_semantic_similarity(expected_response, model_response, semantic_model):
34
+ """Evaluate semantic similarity using Sentence-BERT."""
35
+ expected_embedding = semantic_model.encode(expected_response, convert_to_tensor=True)
36
+ model_embedding = semantic_model.encode(model_response, convert_to_tensor=True)
37
+ similarity_score = util.pytorch_cos_sim(expected_embedding, model_embedding)
38
+ return similarity_score.item()
39
+
40
+ def evaluate_bleu(expected_response, model_response):
41
+ """Evaluate BLEU score using NLTK's sentence_bleu."""
42
+ expected_tokens = nltk.word_tokenize(expected_response.lower())
43
+ model_tokens = nltk.word_tokenize(model_response.lower())
44
+ smoothing_function = nltk.translate.bleu_score.SmoothingFunction().method1
45
+ bleu_score = nltk.translate.bleu_score.sentence_bleu([expected_tokens], model_tokens, smoothing_function=smoothing_function)
46
+ return bleu_score
47
+
48
+ async def create_with_retries(client, **kwargs):
49
+ """Retry mechanism for handling transient server errors asynchronously."""
50
+ for attempt in range(3): # Retry up to 3 times
51
+ try:
52
+ return client.chat.completions.create(**kwargs)
53
+ except Exception as e: # Catch all exceptions since 'InternalServerError' is not defined
54
+ if attempt < 2: # Only retry for the first two attempts
55
+ print(f"Error: {e}, retrying... (Attempt {attempt + 1}/3)")
56
+ await asyncio.sleep(5) # Wait for 5 seconds before retrying
57
+ else:
58
+ raise Exception("API request failed after retries") from e
59
+
60
+
61
+ async def evaluate_model(data, model_name, client, semantic_model):
62
+ """Evaluate the model using the provided data."""
63
+ semantic_scores = []
64
+ bleu_scores = []
65
+
66
+ for entry in data:
67
+ prompt = entry['prompt']
68
+ expected_response = entry['response']
69
+
70
+ # Create a chat completion using OpenAI API
71
+ response = await create_with_retries(
72
+ client,
73
+ model=f"PharynxAI/{model_name}",
74
+ messages=[
75
+ {"role": "system", "content": "You are a helpful assistant."},
76
+ {"role": "user", "content": prompt}
77
+ ],
78
+ temperature=0.7,
79
+ max_tokens=200,
80
+ timeout=300
81
+ )
82
+
83
+ model_response = response.choices[0].message.content # Extract model's response
84
+
85
+ # Evaluate scores
86
+ semantic_score = evaluate_semantic_similarity(expected_response, model_response, semantic_model)
87
+ semantic_scores.append(semantic_score)
88
+
89
+ bleu_score = evaluate_bleu(expected_response, model_response)
90
+ bleu_scores.append(bleu_score)
91
+
92
+ # Calculate average scores
93
+ avg_semantic_score = sum(semantic_scores) / len(semantic_scores) if semantic_scores else 0
94
+ avg_bleu_score = sum(bleu_scores) / len(bleu_scores) if bleu_scores else 0
95
+
96
+ print(f"Average Semantic Similarity: {avg_semantic_score:.4f}")
97
+ print(f"Average BLEU Score: {avg_bleu_score:.4f}")
98
+ # Create comprehensive results dictionary
99
+ evaluation_results = {
100
+ 'average_semantic_score': avg_semantic_score,
101
+ 'average_bleu_score': avg_bleu_score
102
+ }
103
+ # Print results to stdout for capturing in handler
104
+ print(json.dumps(evaluation_results))
105
+
106
+ logging.info("\nOverall Average Scores:")
107
+ logging.info(f"Average Semantic Similarity: {avg_semantic_score:.4f}")
108
+ logging.info(f"Average BLEU Score: {avg_bleu_score:.4f}")
109
+
110
+ return evaluation_results
111
+
112
+ async def main():
113
+ # Load input data
114
+ input_data = load_input_data()
115
+ model_name = input_data["model_name"]
116
+ # Initialize the OpenAI Client with your RunPod API Key and Endpoint URL
117
+ client = OpenAI(
118
+ api_key="MIGZGJKYD6PU8KTHTBQ8FMEMGP2RAW5DVXABFVFD",
119
+ base_url="https://api.runpod.ai/v2/6vg8gj8ia9vd1w/openai/v1",
120
+ )
121
+ # Load pre-trained models
122
+ semantic_model = load_model()
123
+ # Load your dataset (replace with your actual JSON file)
124
+ with open('output_json.json', 'r') as f:
125
+ data = json.load(f)
126
+
127
+ # Run the evaluation asynchronously
128
+ await evaluate_model(data, model_name, client, semantic_model)
129
+
130
+ # Start the event loop
131
+ asyncio.run(main())