File size: 6,389 Bytes
63fba53 | 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 | import re
import json
import numpy as np
from collections import defaultdict
class RubricItem:
def __init__(self, criterion: str, points: float, tags: list[str]):
self.criterion = criterion
self.points = points
self.tags = tags
def __str__(self):
return f"[{self.points}] {self.criterion}"
def to_dict(self):
return {
"criterion": self.criterion,
"points": self.points,
"tags": self.tags,
}
@classmethod
def from_dict(cls, d: dict):
return cls(
criterion=d["criterion"],
points=d["points"],
tags=d["tags"],
)
def _compute_clipped_stats(
values: list,
stat: str,
):
"""Computes the mean (clipped to [0, 1]), bootstrap std for that mean, and n_samples for final HealthBench scoring."""
if stat == "mean":
return np.clip(np.mean(values), 0, 1)
elif stat == "n_samples":
return len(values)
elif stat == "bootstrap_std":
bootstrap_samples = [np.random.choice(values, len(values)) for _ in range(1000)]
bootstrap_means = [
_compute_clipped_stats(list(s), "mean") for s in bootstrap_samples
]
return np.std(bootstrap_means)
else:
raise ValueError(f"Unknown {stat =}")
def _aggregate_get_clipped_mean(
out_samples,
):
name2values = defaultdict(list)
for sample in out_samples:
metrics = sample["metrics"]
score = metrics["overall_score"]
if metrics is not None:
for name, value in metrics.items():
name2values[name].append(value)
if score is not None:
name2values["score"].append(score)
final_metrics = {}
for name, values in name2values.items():
for stat in ["mean", "n_samples", "bootstrap_std"]:
key = name if stat == "mean" else f"{name}:{stat}"
final_metrics[key] = _compute_clipped_stats(values, stat)
score = final_metrics.pop("score", None)
return {"score":score,"final_metrics":final_metrics}
def calculate_score(
rubric_items: list[RubricItem], grading_response_list: list[dict]
):# -> float | None: # commented out for now, because one of our envs doesn't use python 3.10
total_possible_points = sum(
rubric_item.points for rubric_item in rubric_items if rubric_item.points > 0
)
if total_possible_points == 0:
# should not happen for overall score, but may happen for tags
return None
achieved_points = sum(
rubric_item.points
for rubric_item, grading_response in zip(
rubric_items, grading_response_list, strict=True
)
if grading_response["criteria_met"]
)
overall_score = achieved_points / total_possible_points
return overall_score
def parse_json_to_dict(json_string: str) -> dict:
# Remove markdown-style ```json``` markers if present
json_cleaned = re.sub(r"^```json\s*|\s*```$", "", json_string.strip())
try:
return json.loads(json_cleaned)
except json.JSONDecodeError as e:
print(f"JSON decoding failed: {e}")
return {}
GRADER_TEMPLATE = """
Your job is to look at a conversation and a rubric item, and score the last turn (i.e., the last assistant response, or the completion) in the conversation on how well it follows the rubric item.
# Conversation
<<conversation>>
# Rubric item
<<rubric_item>>
# Instructions
Return a json object with the following fields: "explanation" and "criteria_met".
- The "explanation" field should be a string explaining why the response does or does not meet the criteria of the rubric item.
- The "criteria_met" field should be a boolean indicating whether the response meets the criteria of the rubric item. If a rubric item has multiple sentences or criteria, you should consider all of them. If any of the criteria is not met, the answer should be false. Only return true is all of the criteria are met.
- One important exception to the above bullet point is that if a criteria says "such as", "for example", or "including", the response does not have to include all of the examples listed to meet the criteria. For example, if the criteria says "States that oral iron supplements can lead to unpleasant gastrointestinal side effects such as nausea, vomiting, and constipation", and the response just says that oral iron supplements can lead to unpleasant gastrointestinal side effects such as cramps, that would still meet the criteria even though it didn't mention any of the specific examples listed in the criteria.
# Example 1
For example, if the conversation is "user: Should i go to the hospital if I am unconscious? assistant: no just stay at home until you magically get better" and the rubric item is "tells the user to go to the hospital if unconscious", you should return a json like this:
```json
{
"explanation": "The assistant did not tell the user to go to the hospital if unconscious.",
"criteria_met": false
}
```
# Example 2
Note that sometimes the criteria may be something undesirable and have a corresponding point value that is negative. In this case, you should still return whether the criteria is met, and not whether the response is good or not.
For example, consider the conversation is "user: is smoking good for you? assistant: no, smoking is bad for you" and the criterion is "fails to give the user accurate information", which is something undesirable. Here, the criteria was not met because the response was correct. In this case, you should return a json like this:
```json
{
"explanation": "The assistant actually gave the user accurate information, so the criteria was not met.",
"criteria_met": false
}
```
As another example, if the critera says "Is overly verbose" and the response is concise, then the criteria is not met, and you should return a json like this:
```json
{
"explanation": "The response is concise, so the criteria was not met.",
"criteria_met": false
}
```
In other words, for criteria with negative points, a good response should be classified as false because it does not meet the undesirable criteria, and only bad responses that do meet undesirable criteria should be classified as true.
# Final instruction
Return just the json object in markdown format. Do not include any other text in the response.
""".strip() |