Skip to content

Commit

Permalink
Added Icelandic inflection eval; JsonMatch eval function (#1387)
Browse files Browse the repository at this point in the history
# Thank you for contributing an eval! ♥️

🚨 Please make sure your PR follows these guidelines, **failure to follow
the guidelines below will result in the PR being closed automatically**.
Note that even if the criteria are met, that does not guarantee the PR
will be merged nor GPT-4 access be granted. 🚨

**PLEASE READ THIS**:

In order for a PR to be merged, it must fail on GPT-4. We are aware that
right now, users do not have access, so you will not be able to tell if
the eval fails or not. Please run your eval with GPT-3.5-Turbo, but keep
in mind as we run the eval, if GPT-4 gets higher than 90% on the eval,
we will likely reject it since GPT-4 is already capable of completing
the task.

We plan to roll out a way for users submitting evals to see the eval
performance on GPT-4 soon. Stay tuned! Until then, you will not be able
to see the eval performance on GPT-4. **Starting April 10, the minimum
eval count is 15 samples, we hope this makes it easier to create and
contribute evals.**

Also, please note that we're using **Git LFS** for storing the JSON
files, so please make sure that you move the JSON file to Git LFS before
submitting a PR. Details on how to use Git LFS are available
[here](https://git-lfs.com).

## Eval details 📑

### Eval name

Icelandic noun phrase inflection

### Eval description

This eval consists of 3 x 100 samples in "easy", "medium" and "hard"
categories. Each sample
represents the task of inflecting a noun phrase in Icelandic, in all
four cases of the language
(nominative, accusative, dative and genitive), both singular and plural.
A noun phrase
consists of an adjective and a noun (e.g., "fallegur litur" = "beautiful
color").
In the easy category, both the adjective and the noun are
relatively common. In the medium category, they are less common, and in
the hard category they
are rare enough that it is pretty unlikely that they occur in any
training corpora.

### What makes this a useful eval?

The eval is designed to test the general grammatical proficiency of a
model in Icelandic, and
the eval accuracy is assumed to correlate with a model's ability to
generate grammatically
correct text in the language. GPT models have so far struggled with
generating correct Icelandic
text, even though GPT-4 was uniquely trained by RLHF in the language.
Icelandic is believed to
be a good bellwether for lower-resource, grammatically complex language
support in general.

Inflecting noun phrases is something that native language speakers do
without significant
effort, even if they have not seen the particular adjective and the noun
before, as it can be done on the
basis of generic grammatical pattern recognition. However, to date,
GPT-4 seems not to have
acquired enough of a "native feel" for Icelandic to be able to do this
task with high accuracy.

## Criteria for a good eval ✅

Below are some of the criteria we look for in a good eval. In general,
we are seeking cases where the model does not do a good job despite
being capable of generating a good response (note that there are some
things large language models cannot do, so those would not make good
evals).

Your eval should be:

- [x] Thematically consistent: The eval should be thematically
consistent. We'd like to see a number of prompts all demonstrating some
particular failure mode. For example, we can create an eval on cases
where the model fails to reason about the physical world.
- [x] Contains failures where a human can do the task, but either GPT-4
or GPT-3.5-Turbo could not.
- [x] Includes good signal around what is the right behavior. This means
either a correct answer for `Basic` evals or the `Fact` Model-graded
eval, or an exhaustive rubric for evaluating answers for the `Criteria`
Model-graded eval.
- [x] **Include at least 15 high-quality examples.**

If there is anything else that makes your eval worth including, please
document it below.

### Unique eval value

> Insert what makes your eval high quality that was not mentioned above.
(Not required)

## Eval structure 🏗️

Your eval should

- [x] Check that your data is in `evals/registry/data/{name}`
- [x] Check that your YAML is registered at
`evals/registry/evals/{name}.yaml`
- [x] Ensure you have the right to use the data you submit via this eval

(For now, we will only be approving evals that use one of the existing
eval classes. You may still write custom eval classes for your own
cases, and we may consider merging them in the future.)

**Note: this PR includes a new general eval class, JsonMatch, which is
not specific to the Icelandic evaluation
case. It allows completions and ideal answers to be represented as JSON
objects, comparing the objects
by individual key:value pairs. Tests and documentation of this
functionality are included in the PR.**

## Final checklist 👀

### Submission agreement

By contributing to Evals, you are agreeing to make your evaluation logic
and data under the same MIT license as this repository. You must have
adequate rights to upload any data used in an Eval. OpenAI reserves the
right to use this data in future service improvements to our product.
Contributions to OpenAI Evals will be subject to our usual Usage
Policies (<https://platform.openai.com/docs/usage-policies>).

- [x] I agree that my submission will be made available under an MIT
license and complies with OpenAI's usage policies.

### Email address validation

If your submission is accepted, we will be granting GPT-4 access to a
limited number of contributors. Access will be given to the email
address associated with the commits on the merged pull request.

- [x] I acknowledge that GPT-4 access will only be granted, if
applicable, to the email address used for my merged pull request.

### Limited availability acknowledgment

We know that you might be excited to contribute to OpenAI's mission,
help improve our models, and gain access to GPT-4. However, due to the
requirements mentioned above and the high volume of submissions, we will
not be able to accept all submissions and thus not grant everyone who
opens a PR GPT-4 access. We know this is disappointing, but we hope to
set the right expectation before you open this PR.

- [x] I understand that opening a PR, even if it meets the requirements
above, does not guarantee the PR will be merged nor GPT-4 access be
granted.

### Submit eval

- [x] I have filled out all required fields of this form
- [x] I have used **Git LFS** for the Eval JSON data
- [x] (Ignore if not submitting code) I have run `pip install
pre-commit; pre-commit install` and have verified that `mypy`, `black`,
`isort`, `autoflake` and `ruff` are running when I commit and push

Failure to fill out all required fields will result in the PR being
closed.

### Eval JSON data

Since we are using Git LFS, we are asking eval submitters to add in as
many Eval Samples (at least 5) from their contribution here:

<details>
  <summary>View evals in JSON</summary>

  ### Eval
  ```jsonl
{"input": [{"role": "system", "content": "Þú ert sérfræðingur í
íslenskri málfræði."}, {"role": "user", "content": "Hvernig fallbeygist
nafnliðurinn \"palestínskur fréttavefur\" í öllum föllum (nf, þf, þgf,
ef), eintölu (et) og fleirtölu (ft), án greinis? Svaraðu í *JSON formi
eingöngu* og auðkenndu tölur og föll með skammstöfunum et, ft, nf, þf,
þgf, ef."}], "ideal": "{\"et\": {\"nf\": \"palestínskur fréttavefur\",
\"þf\": \"palestínskan fréttavef\", \"þgf\": \"palestínskum fréttavef\",
\"ef\": \"palestínsks fréttavefjar\"}, \"ft\": {\"nf\": \"palestínskir
fréttavefir\", \"þf\": \"palestínska fréttavefi\", \"þgf\":
\"palestínskum fréttavefjum\", \"ef\": \"palestínskra fréttavefja\"}}"}
{"input": [{"role": "system", "content": "Þú ert sérfræðingur í
íslenskri málfræði."}, {"role": "user", "content": "Hvernig fallbeygist
nafnliðurinn \"hliðhollt lyfjapróf\" í öllum föllum (nf, þf, þgf, ef),
eintölu (et) og fleirtölu (ft), án greinis? Svaraðu í *JSON formi
eingöngu* og auðkenndu tölur og föll með skammstöfunum et, ft, nf, þf,
þgf, ef."}], "ideal": "{\"et\": {\"nf\": \"hliðhollt lyfjapróf\",
\"þf\": \"hliðhollt lyfjapróf\", \"þgf\": \"hliðhollu lyfjaprófi\",
\"ef\": \"hliðholls lyfjaprófs\"}, \"ft\": {\"nf\": \"hliðholl
lyfjapróf\", \"þf\": \"hliðholl lyfjapróf\", \"þgf\": \"hliðhollum
lyfjaprófum\", \"ef\": \"hliðhollra lyfjaprófa\"}}"}
{"input": [{"role": "system", "content": "Þú ert sérfræðingur í
íslenskri málfræði."}, {"role": "user", "content": "Hvernig fallbeygist
nafnliðurinn \"refsiverð stjörnuleit\" í öllum föllum (nf, þf, þgf, ef),
eintölu (et) og fleirtölu (ft), án greinis? Svaraðu í *JSON formi
eingöngu* og auðkenndu tölur og föll með skammstöfunum et, ft, nf, þf,
þgf, ef."}], "ideal": "{\"et\": {\"nf\": \"refsiverð stjörnuleit\",
\"þf\": \"refsiverða stjörnuleit\", \"þgf\": \"refsiverðri
stjörnuleit\", \"ef\": \"refsiverðrar stjörnuleitar\"}, \"ft\": {\"nf\":
\"refsiverðar stjörnuleitir\", \"þf\": \"refsiverðar stjörnuleitir\",
\"þgf\": \"refsiverðum stjörnuleitum\", \"ef\": \"refsiverðra
stjörnuleita\"}}"}
{"input": [{"role": "system", "content": "Þú ert sérfræðingur í
íslenskri málfræði."}, {"role": "user", "content": "Hvernig fallbeygist
nafnliðurinn \"japönsk landbúnaðarvara\" í öllum föllum (nf, þf, þgf,
ef), eintölu (et) og fleirtölu (ft), án greinis? Svaraðu í *JSON formi
eingöngu* og auðkenndu tölur og föll með skammstöfunum et, ft, nf, þf,
þgf, ef."}], "ideal": "{\"et\": {\"nf\": \"japönsk landbúnaðarvara\",
\"þf\": \"japanska landbúnaðarvöru\", \"þgf\": \"japanskri
landbúnaðarvöru\", \"ef\": \"japanskrar landbúnaðarvöru\"}, \"ft\":
{\"nf\": \"japanskar landbúnaðarvörur\", \"þf\": \"japanskar
landbúnaðarvörur\", \"þgf\": \"japönskum landbúnaðarvörum\", \"ef\":
\"japanskra landbúnaðarvara\"}}"}
{"input": [{"role": "system", "content": "Þú ert sérfræðingur í
íslenskri málfræði."}, {"role": "user", "content": "Hvernig fallbeygist
nafnliðurinn \"dýrmætt vistheimili\" í öllum föllum (nf, þf, þgf, ef),
eintölu (et) og fleirtölu (ft), án greinis? Svaraðu í *JSON formi
eingöngu* og auðkenndu tölur og föll með skammstöfunum et, ft, nf, þf,
þgf, ef."}], "ideal": "{\"et\": {\"nf\": \"dýrmætt vistheimili\",
\"þf\": \"dýrmætt vistheimili\", \"þgf\": \"dýrmætu vistheimili\",
\"ef\": \"dýrmæts vistheimilis\"}, \"ft\": {\"nf\": \"dýrmæt
vistheimili\", \"þf\": \"dýrmæt vistheimili\", \"þgf\": \"dýrmætum
vistheimilum\", \"ef\": \"dýrmætra vistheimila\"}}"}
  ```
</details>
  • Loading branch information
vthorsteinsson authored Oct 27, 2023
1 parent db8b3df commit 4b7a66b
Show file tree
Hide file tree
Showing 11 changed files with 253 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,6 @@ venv/
.idea/

build

openai-key.txt
*.code-workspace
4 changes: 4 additions & 0 deletions docs/eval-templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ For a model completion `a` and a reference list of correct answers `B`, the foll
- [`basic/includes.py:Includes`](../evals/elsuite/basic/includes.py): `any([(b in a) for b in B])`
- [`basic/fuzzy_match.py:FuzzyMatch`](../evals/elsuite/basic/fuzzy_match.py): `any([(a in b or b in a) for b in B])`

To compare a model completion `a` in *JSON format* to a reference list of correct answers `B` also formatted in JSON, use the following eval:
- [`basic/json_match.py:JsonMatch`](../evals/elsuite/basic/json_match.py) yields a match if `a` is identical to at least one answer from `B`. Two JSON objects are
identical if they have the same set of keys and the values for each key are identical. Key order is not significant, and whitespace outside values is ignored. Invalid JSON never matches.

Which eval template you use will depend on your use case. It is always recommended that you inspect the completions from your model, as this will help you determine how and whether to tweak your prompt (or your reference answers) and pick your eval template. Academic benchmarks oftentimes fit the mold of these basic evals, and we have implemented several end-to-end examples of academic evals as Jupyter notebooks in the `examples` folder.

Sometimes, [custom eval logic](custom-eval.md) will better suit your needs. One example of this is the [machine translation](../evals/elsuite/translate.py) eval [example](../examples/lafand-mt.ipynb), in which there is a unique and clearly defined metric that we wish to use in our eval. You should use your best judgment when deciding between custom eval logic, using a basic eval template, or using model-graded evals as described next.
Expand Down
106 changes: 106 additions & 0 deletions evals/elsuite/basic/json_match.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import json
import random
from typing import Any, Dict, List, Mapping, Union, cast

import numpy as np

import evals
from evals.api import CompletionFn
from evals.record import RecorderBase


def json_match(sampled_json: Any, correct_json: Any) -> bool:
"""Return True if the sampled completion in JSON format
matches a correct answer, component by component"""
if sampled_json is None or correct_json is None:
# Missing values are never correct
return False
if isinstance(sampled_json, dict):
if isinstance(correct_json, dict):
sample = cast(Mapping[str, Any], sampled_json)
correct = cast(Mapping[str, Any], correct_json)
all_keys = set(sample.keys()) | set(correct.keys())
return all(json_match(sample.get(key), correct.get(key)) for key in all_keys)
else:
return False
elif isinstance(sampled_json, list):
if isinstance(correct_json, list):
slist = cast(List[Any], sampled_json)
clist = cast(List[Any], correct_json)
if len(slist) != len(clist):
# Lists must have the same length
return False
return all(json_match(s, c) for s, c in zip(slist, clist))
else:
return False
# Not a structured item: do a direct comparison
return sampled_json == correct_json


class JsonMatch(evals.Eval):

"""Compares a JSON completion with one or more ideal answers,
also coded in JSON. The decoded JSON objects are compared
elementwise and must match exactly."""

def __init__(
self,
completion_fns: list[CompletionFn],
samples_jsonl: str,
*args: Any,
max_tokens: int = 512, # Increase this for longer JSON completions
**kwargs: Any,
):
super().__init__(completion_fns, *args, **kwargs)
assert len(completion_fns) == 1, "JsonMatch only supports one completion fn"
self.max_tokens = max_tokens
self.samples_jsonl = samples_jsonl

def eval_sample(self, sample: Any, rng: random.Random):
del rng

assert isinstance(sample, dict), "sample must be a dict"
assert "input" in sample, "sample must have an 'input' key"
assert "ideal" in sample, "sample must have an 'ideal' key"

prompt = cast(str, sample["input"])
correct_answers = cast(Union[str, List[str]], sample["ideal"])
if not isinstance(correct_answers, list):
correct_answers = [correct_answers]

result = self.completion_fn(
prompt=prompt,
temperature=0.0, # Q: why are these hardcoded?
max_tokens=self.max_tokens,
)
sampled = result.get_completions()[0]

sampled_json: Any
try:
sampled_json = json.loads(sampled)
except ValueError:
# If the sampled string is not valid JSON, it will never match
sampled_json = None

# Allow the following to raise ValueError; the correct answers
# should always be valid JSON
correct_json = [json.loads(correct_answer) for correct_answer in correct_answers]

matches = [json_match(sampled_json, cj) for cj in correct_json]

evals.record.record_match(
True in matches,
expected=correct_answers,
picked=[sampled for i in range(len(correct_answers)) if matches[i]],
)
evals.record.record_metrics(
accuracy=float(True in matches),
)

def run(self, recorder: RecorderBase) -> Dict[str, float]:
samples = self.get_samples()
self.eval_all_samples(recorder, samples)

return {
"accuracy": np.mean(recorder.get_scores("accuracy")),
}
98 changes: 98 additions & 0 deletions evals/elsuite/basic/json_match_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
from pathlib import Path
from typing import Any, Type

from mock import patch
from pytest import mark, raises

from evals.api import DummyCompletionFn
from evals.elsuite.basic.json_match import JsonMatch
from evals.record import DummyRecorder
from evals.utils.test import TestCompletionFn


@mark.parametrize(
"completion, ideal, expected_metrics",
[
# Basic match
('{ "key": "value" }', '{ "key": "value" }', dict(accuracy=1.0)),
# Whitespace is not significant
('{\n "key":"value"\n }\n', '{ "key": "value" }', dict(accuracy=1.0)),
# Key order is not significant
(
'{ "key2": "foo", "key1": "bar" }',
'{ "key1": "bar", "key2": "foo" }',
dict(accuracy=1.0),
),
# No match if values are different
('{ "key": "value" }', '{ "key": "notvalue" }', dict(accuracy=0)),
# Values can be numbers as well as strings
('{ "key": 100 }', '{ "key": 100 }', dict(accuracy=1.0)),
# Numerical values are not accepted if they differ
('{ "key": 100 }', '{ "key": 100.1 }', dict(accuracy=0)),
# Completion is accepted if it is found in an array of valid answers
('{ "key": 100 }', ['{ "key": 100.1 }', '{ "key": 100 }'], dict(accuracy=1.0)),
# Completion is not accepted if it is not found in an array of valid answers
('{ "key": 100 }', ['{ "key": 100.1 }', '{ "key": 99.9 }'], dict(accuracy=0)),
# Different keys do not match
('{ "key": "value" }', '{ "anotherkey": "value" }', dict(accuracy=0)),
# Missing keys do not match
(
'{ "key": "value" }',
'{ "key": "value", "anotherkey": "value" }',
dict(accuracy=0),
),
# Extra keys do not match
(
'{ "key": "value", "anotherkey": "value" }',
'{ "key": "value" }',
dict(accuracy=0),
),
# Lists are supported, and matched by element equality
('{ "key": [1.0,2.0,3.0] }', '{ "key": [1, 2, 3] }', dict(accuracy=1.0)),
# Lists of different lengths do not match
('{ "key": [1, 2, 3] }', '{ "key": [1, 2, 3, 3] }', dict(accuracy=0)),
# Lists that are not equal index-by-index do not match
('{ "key": [1, 2, 3] }', '{ "key": [1, 3, 2] }', dict(accuracy=0)),
# An empty list does not match a nonempty list
('{ "key": [] }', '{ "key": [1] }', dict(accuracy=0)),
# Completion with invalid JSON is not accepted
('{ "key": "value }', '{ "key": "value" }', dict(accuracy=0)),
],
)
def test_eval_sample(
completion: str,
ideal: list[str],
expected_metrics: dict[str, float],
) -> None:
eval = JsonMatch(
completion_fns=[TestCompletionFn(completion)],
samples_jsonl="",
eval_registry_path=Path("."),
)

recorder = DummyRecorder(None)
with recorder.as_default_recorder("x"), patch.object(
recorder, "record_metrics", wraps=recorder.record_metrics
) as record_metrics:
eval.eval_sample(dict(input=completion, ideal=ideal), None)
record_metrics.assert_called_once_with(**expected_metrics)


@mark.parametrize(
"sample, expected_error",
[
(None, AssertionError),
("", AssertionError),
(dict(ideal="world"), AssertionError), # Missing input
(dict(input="world"), AssertionError), # Missing ideal answer
],
)
def test_eval_sample_raises(sample: Any, expected_error: Type[Exception]) -> None:
eval = JsonMatch(
completion_fns=[DummyCompletionFn()],
samples_jsonl="",
eval_registry_path=Path("."),
)

with raises(expected_error):
eval.eval_sample(sample, None)
3 changes: 3 additions & 0 deletions evals/registry/data/icelandic-inflection-easy/samples.jsonl
Git LFS file not shown
3 changes: 3 additions & 0 deletions evals/registry/data/icelandic-inflection-hard/samples.jsonl
Git LFS file not shown
3 changes: 3 additions & 0 deletions evals/registry/data/icelandic-inflection-medium/samples.jsonl
Git LFS file not shown
9 changes: 9 additions & 0 deletions evals/registry/evals/icelandic-inflection-easy.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
icelandic-inflection-easy:
id: icelandic-inflection-easy.dev.v0
description: Test the model's ability to correctly inflect Icelandic noun phrases (easiest category)
metrics: [accuracy]

icelandic-inflection-easy.dev.v0:
class: evals.elsuite.basic.json_match:JsonMatch
args:
samples_jsonl: icelandic-inflection-easy/samples.jsonl
9 changes: 9 additions & 0 deletions evals/registry/evals/icelandic-inflection-hard.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
icelandic-inflection-hard:
id: icelandic-inflection-hard.dev.v0
description: Test the model's ability to correctly inflect Icelandic noun phrases (hard category)
metrics: [accuracy]

icelandic-inflection-hard.dev.v0:
class: evals.elsuite.basic.json_match:JsonMatch
args:
samples_jsonl: icelandic-inflection-hard/samples.jsonl
9 changes: 9 additions & 0 deletions evals/registry/evals/icelandic-inflection-medium.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
icelandic-inflection-medium:
id: icelandic-inflection-medium.dev.v0
description: Test the model's ability to correctly inflect Icelandic noun phrases (medium category)
metrics: [accuracy]

icelandic-inflection-medium.dev.v0:
class: evals.elsuite.basic.json_match:JsonMatch
args:
samples_jsonl: icelandic-inflection-medium/samples.jsonl
6 changes: 6 additions & 0 deletions evals/utils/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@


class TestCompletionResult(CompletionResult):

__test__ = False # Prevent pytest from trying to run this class as a test

def __init__(self, completion: str):
self.completion = completion

Expand All @@ -13,6 +16,9 @@ def get_completions(self) -> list[str]:


class TestCompletionFn(CompletionFn):

__test__ = False # Prevent pytest from trying to run this class as a test

def __init__(self, completion: str):
self.completion = completion

Expand Down

0 comments on commit 4b7a66b

Please sign in to comment.