generated from kyegomez/Python-Package-Template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmajority_voting.py
50 lines (36 loc) · 1.31 KB
/
majority_voting.py
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
import torch
from litellm import encode
class BaseModel:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
return self.model(*args, **kwargs)
class MajorityVoting(BaseModel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.models = []
def __call__(self, *args, **kwargs):
return self.model(*args, **kwargs)
def compute_accuracy(self, answer: str, target: str) -> float:
# first convert to tensors and then compute cosine similarity
answer_tokens = encode(model="gpt-4o", text=answer)
target_tokens = encode(model="gpt-4o", text=target)
answer_tensor = torch.tensor(
answer_tokens, dtype=torch.float32
)
target_tensor = torch.tensor(
target_tokens, dtype=torch.float32
)
if answer_tensor.dim() == 1:
answer_tensor = answer_tensor.unsqueeze(0)
if target_tensor.dim() == 1:
target_tensor = target_tensor.unsqueeze(0)
return (
torch.cosine_similarity(
answer_tensor, target_tensor, dim=1
)
.mean()
.item()
)
vote = MajorityVoting()
print(vote.compute_accuracy("hello", "chicken"))