Skip to content

Commit

Permalink
Bluff eval
Browse files Browse the repository at this point in the history
  • Loading branch information
johny-b committed Nov 10, 2023
1 parent a53f52b commit 198ccaa
Show file tree
Hide file tree
Showing 17 changed files with 1,493 additions and 0 deletions.
73 changes: 73 additions & 0 deletions evals/elsuite/bluff/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# BLUFF #

Evaluate how well a model can play (a variant of) the game of bluff, also known as "liar's dice".
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 198ccaa

Please sign in to comment.