Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[evals] Refactor evals package to expose completion_fn. #515

Merged
merged 23 commits into from
Apr 11, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
d87a056
[evals] Refactor evals package to expose `completion_fn`.
hwchung27 Mar 29, 2023
d9c1395
Add `record_raw_samples`
hwchung27 Apr 2, 2023
a1c6207
Andrew/evals refactor (#579)
andrew-openai Apr 5, 2023
deb29d3
update manifest and pyproject to support fetching data on pip install…
andrew-openai Apr 5, 2023
9b1c350
we need to still use the interop for string/list[dicts] for modelgrad…
andrew-openai Apr 5, 2023
c470d52
refactor simple evals to not use result.prompt (#593)
andrew-openai Apr 5, 2023
b691cfa
Clean up duplicate recordings
hwchung27 Apr 6, 2023
7266049
Replace ModelSpecs with CompletionFn (#594)
jwang47 Apr 6, 2023
b2a45cf
Add --registry_path CLI arg (#601)
jwang47 Apr 6, 2023
924d2d4
Andrew/langchain llms (#602)
andrew-openai Apr 7, 2023
4401cce
rm sample freeform, some docs (#603)
andrew-openai Apr 7, 2023
013d636
Update completion-fn-protocol.md
andrew-openai Apr 7, 2023
08062bc
some documentation cleanup
joe-at-openai Apr 10, 2023
3367006
some documentation cleanup
joe-at-openai Apr 10, 2023
5e71a76
some documentation cleanup
joe-at-openai Apr 10, 2023
e621b6f
inner monologue example (#610)
andrew-openai Apr 10, 2023
49d17ed
Update README.md
andrew-openai Apr 10, 2023
1bfba77
Update run-evals.md
andrew-openai Apr 10, 2023
b018aff
cleanup
andrew-openai Apr 10, 2023
5222f2c
Merge branch 'main' into evals_refactor_merge_main
andrew-openai Apr 10, 2023
9db703d
get oaieval to run
andrew-openai Apr 10, 2023
02bc2cb
address comments
andrew-openai Apr 11, 2023
50114a5
bump version
andrew-openai Apr 11, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
rm sample freeform, some docs (#603)
# 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 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 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. We encourage partial PR's with
~5-10 example that we can then run the evals on and share the results
with you so you know how your eval does with GPT-4 before writing all
100 examples.

## Eval details 📑
### Eval name
[Insert Eval name here]

### Eval description

[Insert a short description of what your eval does here]

### What makes this a useful eval?

[Insert why this eval is worth including and any additional context]

## 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:

- [ ] 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.
- [ ] Contains failures where a human can do the task, but either GPT-4
or GPT-3.5-Turbo could not.
- [ ] 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.
- [ ] Include at least 100 high quality examples (it is okay to only
contribute 5-10 meaningful examples and have us test them with GPT-4
before adding all 100)

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
- [ ] Check that your data is in `evals/registry/data/{name}`
- [ ] Check that your yaml is registered at
`evals/registry/evals/{name}.yaml`
- [ ] 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.)

## 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).

- [ ] 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 merged pull request.

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

### Limited availability acknowledgement

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 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.

- [ ] 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
granted.

### Submit eval

- [ ] I have filled out all required fields in the evals PR form
- [ ] (Ignore if not submitting code) I have run `pip install
pre-commit; pre-commit install` and have verified that `black`, `isort`,
and `autoflake` 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
  INSERT_EVAL_HERE
  ```
</details>
  • Loading branch information
andrew-openai authored Apr 7, 2023
commit 4401cce5dc3475f654ce9e3c5baa285a231edc56
30 changes: 20 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
# Evals

Evals is a framework for evaluating OpenAI models and an open-source registry of benchmarks.
Evals is a framework for evaluating large language models (LLMs) and other prompt completion functions. It also includes an open-source registry of challenging benchmark evals.

You can use Evals to create and run evaluations that:
- use datasets to generate prompts,
- measure the quality of completions provided by an OpenAI model, and
- compare performance across different datasets and models.

With Evals, we aim to make it as simple as possible to build an eval while writing as little code as possible. To get started, we recommend that you follow these steps **in order**:
1. Read through this doc and follow the [setup instructions below](README.md#Setup).
2. Learn how to run existing evals: [run-evals.md](docs/run-evals.md).
3. Familiarize yourself with the existing eval templates: [eval-templates.md](docs/eval-templates.md).
4. Walk through the process for building an eval: [build-eval.md](docs/build-eval.md)
5. See an example of implementing custom eval logic: [custom-eval.md](docs/custom-eval.md).
- measure the quality of completions provided by prompt completion functions, and
- compare performance across different datasets.

(April 7 update): We now support evaluating the performance of any prompt completion function, like LLMs, prompt chains or tool-using agents, via the [Completion Function Protocol](docs/completion-fns.md).

With Evals, we aim to make it as simple as possible to build an eval while writing as little code as possible. To get started, we recommend that you follow these steps:

To get set up with evals, follow the [setup instructions below](README.md#Setup).

#### Running evals
- Learn how to run existing evals: [run-evals.md](docs/run-evals.md).
- Familiarize yourself with the existing eval templates: [eval-templates.md](docs/eval-templates.md).

#### Writing evals
- Walk through the process for building an eval: [build-eval.md](docs/build-eval.md)
- See an example of implementing custom eval logic: [custom-eval.md](docs/custom-eval.md).

#### Writing CompletionFns
- Write your own completion functions: [completion-fns.md](docs/completion-fns.md)

If you think you have an interesting eval, please open a PR with your contribution. OpenAI staff actively review these evals when considering improvements to upcoming models.

Expand Down
2 changes: 1 addition & 1 deletion docs/build-eval.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ In general, running the same eval name against the same model should always give

## Running the eval

You can now run your eval on your data from the CLI with your choice of model:
You can now run your eval on your data from the CLI with your choice of model or completion function:
```
oaieval gpt-3.5-turbo <eval_name>
```
Expand Down
37 changes: 37 additions & 0 deletions docs/completion-fn-protocol.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
### The Completion Function Protocol

Here are the interfaces needed to implement the completion function protocol. Any implementation of this interface can be used inside `oaieval`.

#### CompletionFn
Completion functions should implement the `CompletionFn` interface:
```python
class CompletionFn(Protocol):
def __call__(
self,
prompt: Union[str, list[dict[str, str]]],
**kwargs,
) -> CompletionResult:
```

We take a `prompt` representing a single sample from an eval. These prompts can be represented as either a text string or a list of messages in [OpenAI Chat format](https://platform.openai.com/docs/guides/chat/introduction). To work with the existing evals, Completion Function implementations would need to handle both types of inputs, but we provide helper functionality to convert Chat formatted messages into a text string if that is the preferred input for your program:
```python
from evals.prompt.base import CompletionPrompt

# chat_prompt: list[dict[str, str]] -> text_prompt: str
text_prompt = CompletionPrompt(chat_prompt).to_formatted_prompt()
```

#### CompletionResult
The completion function should return an object implementing the `CompletionResult` interface:
```python
class CompletionResult(ABC):
@abstractmethod
def get_completions(self) -> list[str]:
pass
```
The `get_completions` method returns a list of string completions. Each element should be considered a unique completion (in most cases this will be a list of length 1).

#### Using your CompletionFn
This is all that's needed to implement a Completion function that works with our existing Evals, allowing you to more easily evaluate your end-to-end logic on tasks.

See [completion-fns.md](completion-fns.md) to see how to register and use your completion function with `oaieval`.
49 changes: 49 additions & 0 deletions docs/completion-fns.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Completion Functions

## What are completion functions
In [run-evals.md](run-evals.md), we learned how to make calls to `oaieval` to run an eval against a completion function. Completion Functions are generalizations of model completions, where a "completion" is some text output that would be our answer to the prompt. For example, if "Who played the girl elf in the hobbit?" is our prompt, the correct completion is "Evangeline Lilly". While we can just test a model directly to see if it generates "Evangeline Lilly", we can imagine doing numerous other operations under the hood to improve our ability to answer this question, like giving the model access to a browser to look up the answer before responding. Making it easy to implement this kind of under-the-hood operators before responding is the motivation behind building Completion Functions.

## How to implement completion functions
A completion function needs to implement some interfaces that make it usable within Evals. At its core, it is just standardizing inputs to be a text string or [Chat conversation](https://platform.openai.com/docs/guides/chat), and the output to be a list of text strings. Implementing this interface will allow you to run your Completion Function against any eval in Evals.

The exact interfaces needed are described in detail in [completion-fn-protocol.md](completion-fn-protocol.md)

We include some example implementations inside `evals/completion_fns`. For example, the [`LangChainLLMCompletionFn`](../evals/completion_fns/langchain_llm.py) implements a way to generate completions from [LangChain LLMs](https://python.langchain.com/en/latest/modules/models/llms/getting_started.html). We can then use these completion functions with `oaieval`:
```
oaieval langchain/llm/flan-t5-xl test-match
```

## Registering Completion Functions
Once you have written a completion function, we need to make the class visible to the `oaieval` CLI. Similar to how we register our evals, we also register Completion Functions inside `evals/registry/completion_fns` as `yaml` files. Here is the registration for our langchain LLM completion function:
```yaml
langchain/llm/flan-t5-xl:
class: evals.completion_fns.langchain_llm:LangChainLLMCompletionFn
args:
llm: HuggingFaceHub
llm_kwargs:
repo_id: google/flan-t5-xl
```
Here is how it breaks down
`langchain/llm/flan-t5-xl`: This is the top level key that will be used to access this completion function with `oaieval`.
`class`: This is the path to your implementation of the completion function protocol. This class needs to importable within your python environment.
`args`: These are arguments that are passed to your completion function when it is instantiated.


### Developing Completion Functions outside of Evals
It is possible to register CompletionFunctions without directly modifying the registry or code inside `Evals` by using the `--registry_path` argument. As an example, let's say I want to use `MyCompletionFn` located inside `~/my_project/`:
```
my_project
├── my_completion_fn.py
└── completion_fns
└── my_completion_fn.yaml
```

If `my_project` is importable within the python environment (accessible via PYTHONPATH), we can structure `my_completion_fn.yaml` as:
```
my_completion_fn:
class: my_project.my_completion_fn:MyCompletionFn
```
Then, we can make calls to `oaieval` using:
```
oaieval my_completion_fn test-match --registry_path ~/my_project
```
7 changes: 5 additions & 2 deletions docs/run-evals.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ We provide two command line interfaces (CLIs): `oaieval` for running a single ev

## Running an eval

When using the `oaieval` command, you will need to provide both the model you wish to evaluate as well as the eval to run. E.g.,
When using the `oaieval` command, you will need to provide the completion function you wish to evaluate as well as the eval to run. E.g.,
```sh
oaieval gpt-3.5-turbo test-match
```
The valid eval names are specified in the YAML files under `evals/registry/evals` and their corresponding implementations can be found in `evals/elsuite`.

In this example, `gpt-3.5-turbo` is the model to evaluate, and `test-match` is the eval to run. The valid model names are those which you have access to via the API. The valid eval names are specified in the YAML files under `evals/registry/evals`, and their corresponding implementations can be found in `evals/elsuite`.
In this example, `gpt-3.5-turbo` is an OpenAI model that we dynamically instantiate as a completion function using `OpenAIChatCompletionFn(model=gpt-3.5-turbo)`. Any implementation of the `CompletionFn` protocol can be run against `oaieval`. By default, we support calling `oaieval` with any model availableon the OpenAI API or with CompletionFunctions available in [`evals/registry/completion_fns`](../evals/registry/completion_fns/).
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo: availableon


More details on `CompletionFn` found here: [`completion-fns.md`](completion-fns.md)

These CLIs can accept various flags to modify their default behavior. For example:
- If you wish to log to a Snowflake database (which you have already set up as described in the [README](../README.md)), add `--no-local-run`.
Expand Down
7 changes: 2 additions & 5 deletions evals/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
from .api import (
CompletionFn,
CompletionResult,
from .api import CompletionFn, CompletionResult, DummyCompletionFn, record_and_check_match
from .completion_fns.openai import (
OpenAIChatCompletionFn,
OpenAICompletionFn,
OpenAICompletionResult,
record_and_check_match,
sample_freeform,
)
from .data import get_csv, get_json, get_jsonl, get_jsonls, get_lines, iter_jsonls
from .eval import Eval
195 changes: 16 additions & 179 deletions evals/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,8 @@
from abc import ABC, abstractmethod
from typing import Any, Callable, Optional, Protocol, Union, runtime_checkable

from evals.prompt.base import (
ChatCompletionPrompt,
CompletionPrompt,
OpenAICreateChatPrompt,
OpenAICreatePrompt,
Prompt,
)
from evals.record import record_match, record_sampling
from evals.utils.api_utils import (
openai_chat_completion_create_retrying,
openai_completion_create_retrying,
)
from evals.prompt.base import OpenAICreateChatPrompt, OpenAICreatePrompt, Prompt
from evals.record import record_match

logger = logging.getLogger(__name__)

Expand All @@ -33,7 +23,7 @@ def get_completions(self) -> list[str]:
class CompletionFn(Protocol):
def __call__(
self,
prompt: Union[OpenAICreatePrompt, OpenAICreateChatPrompt, Prompt],
prompt: Union[str, OpenAICreateChatPrompt],
**kwargs,
) -> CompletionResult:
"""
Expand All @@ -50,127 +40,6 @@ def __call__(
"""


class OpenAICompletionResult(CompletionResult):
def __init__(self, raw_data: Any, prompt: Any):
self.raw_data = raw_data
self.prompt = prompt

def get_completions(self) -> list[str]:
raise NotImplementedError


class OpenAIChatCompletionResult(OpenAICompletionResult):
def get_completions(self) -> list[str]:
completions = []
if self.raw_data and "choices" in self.raw_data:
for choice in self.raw_data["choices"]:
if "message" in choice:
completions.append(choice["message"]["content"])
return completions


class OpenAICompletionResult(OpenAICompletionResult):
def get_completions(self) -> list[str]:
completions = []
if self.raw_data and "choices" in self.raw_data:
for choice in self.raw_data["choices"]:
if "text" in choice:
completions.append(choice["text"])
return completions


class OpenAICompletionFn(CompletionFn):
def __init__(
self,
model: Optional[str] = None,
api_base: Optional[str] = None,
api_key: Optional[str] = None,
n_ctx: Optional[int] = None,
extra_options: Optional[dict] = {},
):
self.model = model
self.api_base = api_base
self.api_key = api_key
self.n_ctx = n_ctx
self.extra_options = extra_options

def __call__(
self,
prompt: Union[OpenAICreatePrompt, Prompt],
**kwargs,
) -> OpenAICompletionResult:
if not isinstance(prompt, Prompt):
assert (
isinstance(prompt, str)
or (isinstance(prompt, list) and all(isinstance(token, int) for token in prompt))
or (isinstance(prompt, list) and all(isinstance(token, str) for token in prompt))
or (isinstance(prompt, list) and all(isinstance(msg, dict) for msg in prompt))
), f"Got type {type(prompt)}, with val {type(prompt[0])} for prompt, expected str or list[int] or list[str] or list[dict[str, str]]"

prompt = CompletionPrompt(
raw_prompt=prompt,
)

openai_create_prompt: OpenAICreatePrompt = prompt.to_formatted_prompt()

result = openai_completion_create_retrying(
model=self.model,
api_base=self.api_base,
api_key=self.api_key,
prompt=openai_create_prompt,
**{**kwargs, **self.extra_options},
)
result = OpenAICompletionResult(raw_data=result, prompt=openai_create_prompt)
record_sampling(prompt=result.prompt, sampled=result.get_completions())
return result


class OpenAIChatCompletionFn(CompletionFn):
def __init__(
self,
model: Optional[str] = None,
api_base: Optional[str] = None,
api_key: Optional[str] = None,
n_ctx: Optional[int] = None,
extra_options: Optional[dict] = {},
):
self.model = model
self.api_base = api_base
self.api_key = api_key
self.n_ctx = n_ctx
self.extra_options = extra_options

def __call__(
self,
prompt: Union[OpenAICreateChatPrompt, Prompt],
**kwargs,
) -> OpenAIChatCompletionResult:
if not isinstance(prompt, Prompt):
assert (
isinstance(prompt, str)
or (isinstance(prompt, list) and all(isinstance(token, int) for token in prompt))
or (isinstance(prompt, list) and all(isinstance(token, str) for token in prompt))
or (isinstance(prompt, list) and all(isinstance(msg, dict) for msg in prompt))
), f"Got type {type(prompt)}, with val {type(prompt[0])} for prompt, expected str or list[int] or list[str] or list[dict[str, str]]"

prompt = ChatCompletionPrompt(
raw_prompt=prompt,
)

openai_create_prompt: OpenAICreateChatPrompt = prompt.to_formatted_prompt()

result = openai_chat_completion_create_retrying(
model=self.model,
api_base=self.api_base,
api_key=self.api_key,
messages=openai_create_prompt,
**{**kwargs, **self.extra_options},
)
result = OpenAIChatCompletionResult(raw_data=result, prompt=openai_create_prompt)
record_sampling(prompt=result.prompt, sampled=result.get_completions())
return result


class DummyCompletionResult(CompletionResult):
def get_completions(self) -> list[str]:
return ["This is a dummy response."]
Expand All @@ -190,6 +59,19 @@ def record_and_check_match(
separator: Callable[[str], bool] = None,
options: Optional[list[str]] = None,
):
"""
Records and checks if a sampled response from a CompletionFn matches the expected result.

Args:
prompt: The input prompt.
sampled: The sampled response from the model.
expected: The expected response or list of responses.
separator: Optional function to check if a character is a separator.
options: Optional list of options to match against the sampled response.

Returns:
The matched option or None if no match found.
"""
if isinstance(expected, tuple):
expected = list(expected)
elif not isinstance(expected, list):
Expand Down Expand Up @@ -221,48 +103,3 @@ def record_and_check_match(
result["match"] = match
record_match(match, expected=expected, picked=picked, sampled=sampled, options=options)
return picked


def sample_freeform(
prompt: Union[OpenAICreatePrompt, OpenAICreateChatPrompt, Prompt],
*,
completion_fn: CompletionFn = OpenAIChatCompletionFn(),
temperature: float = 1.0,
top_p: float = 0.9,
max_tokens: int = 512,
stop: Optional[str] = None,
n_samples: Optional[int] = None,
**kwargs,
) -> Union[str, list[str], dict]:
"""
Samples a freeform response from the specified model, records the sampling,
and returns the sampled text.

ARGS
====
`model_spec`: See `completion_query`.
`prompt`: See `completion_query`.
`temperature`: Passed to `openai.Completion.create`.
`top_p`: Passed to `openai.Completion.create`.
`max_tokens`: Passed to `openai.Completion.create`.
`stop`: Passed to `openai.Completion.create`.
`n_samples`: The number of samples to generate (1 if None).
`kwargs`: See `completion_query`.

RETURNS
=======
Returns the sampled text, or a list of sampled texts if
`n_samples` is not None.
"""
result = completion_fn(
prompt=prompt,
temperature=temperature,
top_p=top_p,
max_tokens=max_tokens,
stop=stop,
n=(1 if n_samples is None else n_samples),
headers={},
**kwargs,
)
sampled = result.get_completions()[0]
return sampled
Loading