Skip to content
This repository has been archived by the owner on Sep 4, 2024. It is now read-only.

Commit

Permalink
Bluff eval (openai#1402)
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

bluff

### Eval description

Evaluate how well a model can play (a variant of) the game of bluff,
also known as "liar's dice".

### What makes this a useful eval?

This is a game of deception - you have to deceive your opponent and
understand when you are deceived.
Models performing very well on this eval could also be capable of
deceiving humans in real-life scenarios.

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

## 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
  INSERT_EVAL_HERE
  ```
</details>
  • Loading branch information
johny-b authored Nov 15, 2023
1 parent 5bd8331 commit e56f1b7
Show file tree
Hide file tree
Showing 17 changed files with 1,495 additions and 0 deletions.
75 changes: 75 additions & 0 deletions evals/elsuite/bluff/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# BLUFF #

Evaluate how well a model can play (a variant of) the game of bluff, also known as "liar's dice".
This tests models for strategic reasoning capabilities in a deceptive domain, including underlying skills such as being able to bluff convincingly, calculating risks, strategic planning, and theory of mind.

Game rules: `bluff/task_description.py`.

## Run the eval ##

```
# Full eval - 200 games
oaieval bluff/strategy/gpt-4 bluff
# Short scenario - 5 games
oaieval bluff/strategy/gpt-4 bluff.strong_bot.dev5
```

## Metrics ##

The key metric is the win ratio (`player_0_win_ratio` in the final report) - how often our tested model wins a round against the given opponent.

We also check if the model is capable of improving its performance while playing, i.e. if it does better in the later rounds than in the early rounds (there are 10 rounds in each game, so it could learn something from the previous rounds).
This is measured by `player_0_round_ix_coef` - a linear regression coeficient between round number and an average win ratio for this round.
Statistical significance of this metric is indicated by the value of `player_0_round_ix_pvalue`.

## Solvers ##

The bare-bones setup of the eval does not influence the game strategy of the models in any way, but we also implement a custom solver which provides a strategy guide to models (`strategy_solver.BluffStrategySolver`), with a modest but significant positive impact on the performance. We recommend using this solver by default when evaluating new models.
This solver does three things:

* Gives the model a strategy guide before the first round
* Uses JSON responses with a scratchpad
* After 4 rounds asks the model to evaluate opponent's strategy and think about a counter-strategy

## Variants ##

There are four different variants of this eval, they differ in the type of the opponent:

* `bluff.honest_bot_highest` - Play against a bot who always bids the cards they have.
* `bluff.strong_bot` - Play against a bot with some reasonable (at least against `gpt-4`) strategy. Details on the strategy are in the `bluff.players.StrongBot` docstring.
* `bluff.gpt-4` - Play against `gpt-4` that uses a strategic solver.
* `bluff.human_cli` - Play against a human (human plays via the command line).

## Token estimates ##

Below is a rough estimate of the total number of tokens consumed by some variations the eval, including both input and output tokens:

| Model | Variant | Tokens / game | Tokens / full eval (200 games) |
| ----- | ------- | ------------- | ------------------------------ |
| gpt-3.5-turbo-16k | bluff.gpt-4 | 130 000 | 26 000 000 |
| gpt-3.5-turbo-16k | bluff.honest_bot_highest | 80 000 | 16 000 000 |
| gpt-3.5-turbo-16k | bluff.strong_bot | 130 000 | 26 000 000 |
| gpt-4 | bluff.honest_bot_highest | 40 000 | 8 000 000 |
| gpt-4 | bluff.strong_bot | 90 000 | 18 000 000 |

To calculate dollar cost from token counts, please check the latest token pricing [here](https://openai.com/pricing). Note that we count both input and output tokens together, so a lower and upper estimate of the cost of each variant can be predicted.

# Experiments
As a starting point for deeper exploration, we provide scripts for comparing various solvers and eval variants, as well as for plotting the results. To run these:
```
cd scripts/
bash run_experiments.sh
```

## Future modifications ##

Few things we might want to do in the future:

1. Modify the pameters of the eval (e.g. rounds per game) in the `evals/registry/evals/bluff.yaml` file.
2. Alter the rules of the game to make it harder - add more valid hands (straight, flush, royal flush), or increase the set of cards in play.
3. Implement another bot. This doesn't require any changes in the code - just create another class with the same interface as the other `bluff.players` and mention it in `evals/registry/evals/bluff.yaml`.
4. Implement another solver class.

## Contribution statement ##
Eval design, implementation, and results evaluation were primarily conducted by Jan Betley, under the guidance of (alphabetically by last-name) Steven Adler, James Aung, Rosie Campbell, and Jade Leung, who provided research input and project management support.
Empty file.
288 changes: 288 additions & 0 deletions evals/elsuite/bluff/bluff/cards.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,288 @@
"""All the card-related logic is in this file (both player cards and poker hands)"""

from functools import total_ordering
from itertools import combinations
from typing import Literal, Union

BluffMove = Union["PokerHand", Literal["bluff"]]

CARDS = "89TJQKA"


class PlayerCards:
def __init__(self, cards: list[str]):
"""In: e.g. [As, Ah, Kh, Qd, 9c]"""
assert len(cards) == 5

self.cards = {}
for suit in "shdc":
self.cards[suit] = sorted(card[0] for card in cards if card[1] == suit)

def no_suit(self):
return sorted(self.cards["s"] + self.cards["h"] + self.cards["d"] + self.cards["c"])

def lm_format(self):
return (
"{"
f"spades: {self._suit_repr('s')}, "
f"hearts: {self._suit_repr('h')}, "
f"diamonds: {self._suit_repr('d')}, "
f"clubs: {self._suit_repr('c')}"
"}"
)

def _suit_repr(self, suit):
cards = sorted(self.cards[suit], key=lambda x: CARDS.index(x), reverse=True)
return "".join(cards) or "-"

def __repr__(self):
return str(self.cards)


def get_poker_hand(txt: str) -> "PokerHand":
"""In: some text, e.g. 'AA' or 'QQJJ', out: an instance of a subclass of PokerHand"""
hands = []
for cls in (HighCard, OnePair, TwoPair, ThreeOfAKind, FullHouse, FourOfAKind):
hand = cls.from_string(txt)
if hand is not None:
hands.append(hand)
if len(hands) > 1:
raise ValueError(
f"Hand descrption {txt} fits multiple hands: {','.join([str(x) for x in hands])}"
)
elif len(hands) == 0:
raise ValueError(f"Hand description {txt} doesn't describe any poker hand")
else:
return hands[0]


def get_bluff_move(txt: str) -> BluffMove:
"""IN: a string, out: a BluffMove (something accepted by Round.make_move())"""
if txt.lower() == "bluff":
return "bluff"
return get_poker_hand(txt)


def get_all_hands():
"""Return all valid poker hands, sorted from weakest to strongest"""
return sorted(
HighCard.all()
+ OnePair.all()
+ TwoPair.all()
+ ThreeOfAKind.all()
+ FullHouse.all()
+ FourOfAKind.all()
)


def get_all_winning_hands(*in_cards: PlayerCards):
"""Return all winning poker hands for a given set of cards, sorted from weakest to strongest.
NOTE: this is equivalent to
[hand for hand in get_all_hands() if hand.evaluate(*cards)]
but much faster.
"""
all_cards = []
for cards in in_cards:
all_cards += cards.no_suit()

winning_hands = []
winning_hands += [HighCard(card) for card in set(all_cards)]
winning_hands += [OnePair(card) for card in set(all_cards) if all_cards.count(card) >= 2]
winning_hands += [ThreeOfAKind(card) for card in set(all_cards) if all_cards.count(card) >= 3]
winning_hands += [FourOfAKind(card) for card in set(all_cards) if all_cards.count(card) >= 4]

pairs = [x for x in winning_hands if isinstance(x, OnePair)]
for ix, first_pair in enumerate(pairs):
for second_pair in pairs[ix + 1 :]:
winning_hands.append(TwoPair(first_pair.card, second_pair.card))

trios = [x for x in winning_hands if isinstance(x, ThreeOfAKind)]
for trio in trios:
for pair in pairs:
if trio.card != pair.card:
winning_hands.append(FullHouse(trio.card, pair.card))

winning_hands.sort()

return winning_hands


@total_ordering
class PokerHand:
def __eq__(self, other):
return isinstance(self, type(other)) and self.cards() == other.cards()

def __lt__(self, other):
if isinstance(other, type(self)):
my_card_ixs = [CARDS.index(card) for card in self.cards()]
other_card_ixs = [CARDS.index(card) for card in other.cards()]
return my_card_ixs < other_card_ixs
elif isinstance(other, PokerHand):
return self.type_val < other.type_val
raise TypeError(f"Cant compare {type(self).__name__} to {type(other).__name__}")

def __repr__(self):
return self.cards()

def evaluate(self, *player_cards: PlayerCards) -> bool:
"""Check if this hand can be found in given set of cards"""
all_cards = []
for cards in player_cards:
all_cards += cards.no_suit()

all_cards.sort()
my_cards = self.cards()
all_combinations = list(combinations(all_cards, len(my_cards)))
return sorted(my_cards) in [sorted(x) for x in all_combinations]


class HighCard(PokerHand):
type_val = 0

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

def cards(self) -> str:
return self.card

@classmethod
def from_string(cls, txt):
if len(txt) == 1 and txt in CARDS:
return cls(txt)

@classmethod
def all(self):
return [HighCard(x) for x in CARDS]


class OnePair(PokerHand):
type_val = 1

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

def cards(self) -> str:
return self.card * 2

@classmethod
def from_string(cls, txt):
if len(txt) == 2 and txt[0] == txt[1] and txt[0] in CARDS:
return cls(txt[0])

@classmethod
def all(cls):
return [OnePair(x) for x in CARDS]


class TwoPair(PokerHand):
type_val = 2

def __init__(self, card_1: str, card_2: str):
assert card_1 != card_2, "pairs in TwoPair must be different"

# Higher card first
if CARDS.index(card_1) < CARDS.index(card_2):
card_1, card_2 = card_2, card_1

self.card_high = card_1
self.card_low = card_2

def cards(self) -> str:
return self.card_high * 2 + self.card_low * 2

@classmethod
def from_string(cls, txt):
if (
len(txt) == 4
and txt[0] == txt[1]
and txt[1] != txt[2]
and txt[2] == txt[3]
and txt[0] in CARDS
and txt[2] in CARDS
):
return cls(txt[0], txt[2])

@classmethod
def all(cls):
result = []
for card_1 in CARDS:
for card_2 in CARDS:
if card_1 < card_2:
result.append(TwoPair(card_1, card_2))
return result


class ThreeOfAKind(PokerHand):
type_val = 3

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

def cards(self) -> str:
return self.card * 3

@classmethod
def from_string(cls, txt):
if len(txt) == 3 and txt[0] == txt[1] == txt[2] and txt[0] in CARDS:
return cls(txt[0])

@classmethod
def all(cls):
return [ThreeOfAKind(x) for x in CARDS]


class FullHouse(PokerHand):
type_val = 4

def __init__(self, card_triple: str, card_pair: str):
assert card_triple != card_pair, "pair/triple in FullHouse must be different"

self.card_triple = card_triple
self.card_pair = card_pair

def cards(self) -> str:
return self.card_triple * 3 + self.card_pair * 2

@classmethod
def from_string(cls, in_txt):
# in_txt should be AAAKK, but KKAAA is also fine
reversed_order_txt = in_txt[2:] + in_txt[:2]
for txt in (in_txt, reversed_order_txt):
if (
len(txt) == 5
and txt[0] == txt[1] == txt[2]
and txt[2] != txt[3]
and txt[3] == txt[4]
and txt[0] in CARDS
and txt[3] in CARDS
):
return cls(txt[0], txt[3])

@classmethod
def all(cls):
result = []
for card_1 in CARDS:
for card_2 in CARDS:
if card_1 != card_2:
result.append(FullHouse(card_1, card_2))
return result


class FourOfAKind(PokerHand):
type_val = 5

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

def cards(self) -> str:
return self.card * 4

@classmethod
def from_string(cls, txt):
if len(txt) == 4 and txt[0] == txt[1] == txt[2] == txt[3] and txt[0] in CARDS:
return cls(txt[0])

@classmethod
def all(cls):
return [FourOfAKind(x) for x in CARDS]
Loading

0 comments on commit e56f1b7

Please sign in to comment.