Metadata-Version: 2.5
Name: pokerlm
Version: 0.1.0
Summary: A small poker language model (transformer written from scratch) with its data pipeline, probes and an interactive table
Project-URL: Homepage, https://github.com/jbr589/pokerlm
Project-URL: Repository, https://github.com/jbr589/pokerlm
Project-URL: Issues, https://github.com/jbr589/pokerlm/issues
Author: Joffray Braga
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Requires-Python: >=3.11
Requires-Dist: numpy
Requires-Dist: tokenizers
Requires-Dist: torch
Provides-Extra: llm
Requires-Dist: anthropic; extra == 'llm'
Provides-Extra: test
Requires-Dist: pytest; extra == 'test'
Description-Content-Type: text/markdown

# pokerlm

A small poker language model (a transformer written from scratch) with its data pipeline, probes and an interactive table, explained chapter by chapter.

## Why

Poker is not the point of this repository. It is the **pretext**: a language formal enough that what a model has
learned can be checked mechanically, and small enough that an entire transformer (tokenizer, embeddings, attention,
training, generation) fits on a consumer graphics card and can be read in an evening. The deliverable is as much the
**documentation** as the **model**: ten chapters in which every claim is backed by a command that was actually run,
replayed and compared byte for byte at every `make check`.

Concrete result, obtained and verified on this repository (reference checkpoint `pokerlm-reference.pt`,
2,737,536 parameters, 59,966,536 tokens seen):

| Measure | Value | Reference |
|---|---|---|
| Final validation loss | **1.2506** nats | unigram baseline: 3.9116 nats |
| Mechanical validity of generated hands | 84.88% (free) / 99.92% (constrained) | full CPN grammar |
| `bench_easy` (52 handwritten situations) | 14/52 | "always fold" baseline: 16/52 |
| Hand-strength probe (Spearman rho, 169 preflop hands) | **+0.9100**, p ≈ 1e-65 | 0 = no structure |
| Embedding cosine, cards of the same rank | **+0.933** | against +0.393 for two arbitrary cards |

The first figure says the model clearly learned a structure of the game; the third says, just as honestly, that it
plays **worse** than an agent that always folds. Both are true at the same time, and chapter 7 explains why this is
not a contradiction.

## Install

```sh
python -m venv .venv && . .venv/bin/activate
pip install pokerlm
```

The package requires Python 3.11 or later. The base package needs PyTorch, `tokenizers` and NumPy. On a machine without a GPU, `pip install pokerlm
--extra-index-url https://download.pytorch.org/whl/cpu` pulls the CPU-only PyTorch wheel instead of the CUDA one.
Two extras exist: `pokerlm[test]` (pytest) and `pokerlm[llm]` (the `anthropic` client, for the league and
flush-corpus commands that call remote model APIs).

## Quick start

Runs as-is after the install above, without cloning this repository and without any checkpoint:

```sh
python -m pokerlm tokens "[NLH] [CASH] [100BB] [6MAX] [HERO] BTN Ah Ad [PREFLOP] r 2.5 x f f"
python -c "import numpy as np; from pokerlm.equity import card_index, eval7; score = lambda hand: eval7(np.array([[card_index(c) for c in hand.split()]]))[0]; print('royal flush beats a full house:', score('Ah Kh Qh Jh Th 2c 3d') > score('As Ad Ac Ks Kd 2c 3d'))"
```

The first command prints the token table of a hand written in the notation the model reads (bet sizes are rounded
into buckets by the tokenizer); the second compares two seven-card hands with the pure-Python evaluator.

Everything that needs the trained weights (`inspect`, `sample`, `eval`, `postflop`, `ui`) takes
`--checkpoint <file>`: see "Reference checkpoint" below.

## The documentation

Each of the ten chapters starts from the previous one:

0. [`docs/0-the-data.md`](https://github.com/jbr589/pokerlm/blob/main/docs/0-the-data.md): where the hands come from, why heads-up, why the split is made by file and not by hand.
1. [`docs/1-the-language.md`](https://github.com/jbr589/pokerlm/blob/main/docs/1-the-language.md): the CPN notation, the bucketed tokenizer, the closed vocabulary.
2. [`docs/2-embeddings.md`](https://github.com/jbr589/pokerlm/blob/main/docs/2-embeddings.md): the embedding table, from initial isotropy to rank clustering at full scale.
3. [`docs/3-attention.md`](https://github.com/jbr589/pokerlm/blob/main/docs/3-attention.md): Q/K/V, the causal mask, specialised heads.
4. [`docs/4-the-block.md`](https://github.com/jbr589/pokerlm/blob/main/docs/4-the-block.md): residuals, LayerNorm, MLP: what breaks when each is removed.
5. [`docs/5-training.md`](https://github.com/jbr589/pokerlm/blob/main/docs/5-training.md): honest training: separate validation split, unigram baseline, token budget.
6. [`docs/6-generation.md`](https://github.com/jbr589/pokerlm/blob/main/docs/6-generation.md): autoregressive generation, constrained decoding, mechanical validity checker.
7. [`docs/7-what-it-learned.md`](https://github.com/jbr589/pokerlm/blob/main/docs/7-what-it-learned.md): the hand-strength probe, the `bench_easy` verdict.
8. [`docs/8-what-it-sees-of-the-board.md`](https://github.com/jbr589/pokerlm/blob/main/docs/8-what-it-sees-of-the-board.md): the postflop probe.
9. [`docs/9-playing-against-the-model.md`](https://github.com/jbr589/pokerlm/blob/main/docs/9-playing-against-the-model.md): the playable table, a laboratory instrument rather than an opponent.

Plus a self-contained HTML atlas, [`docs/atlas.html`](https://github.com/jbr589/pokerlm/blob/main/docs/atlas.html)
(no network request, openable from `file://`). The pitfalls met while writing the chapters are in
[`PITFALLS.md`](https://github.com/jbr589/pokerlm/blob/main/PITFALLS.md); adding a probe is described in
[`GUIDE-PROBE.md`](https://github.com/jbr589/pokerlm/blob/main/GUIDE-PROBE.md).

## Architecture

- `pokerlm/lang/`: the notation, the bucketed tokenizer and the closed vocabulary.
- `pokerlm/data/`: the corpus builder (PHH hand histories to training lines).
- `pokerlm/model.py`, `pokerlm/train.py`, `pokerlm/sample.py`: the transformer, its training loop and generation.
- `pokerlm/eval.py`, `pokerlm/postflop.py`, `pokerlm/validity.py`, `pokerlm/bench/`: probes, validity checker and handwritten benchmarks.
- `pokerlm/table/`, `pokerlm/ui/`: the no-limit heads-up engine and the local web table.
- `pokerlm/league/`, `pokerlm/llm/`, `pokerlm/flushcorpus/`: the multi-model league and the flush-targeted corpus.
- `pokerlm/checkdocs.py`: the gate that replays every `console` block of `docs/*.md`.
- `eval/`: the C 7-card hand evaluator (see below).

## The C evaluator

Some measurements (showdown correctness, the flush corpus) rely on a 7-card evaluator written in C under `eval/`,
used as a second, independent referee. The Python wheel does not ship the shared library; the source distribution
and a clone carry the C sources (see [`eval/README.md`](https://github.com/jbr589/pokerlm/blob/main/eval/README.md)).
Build it with a C compiler and `make`:

```sh
make -C eval libpokereval.so      # or: make lib
```

`pokerlm.eval7_c` looks for the library in `$POKER_EVAL_DIR`, then in `eval/` at the root of the repository. Without
it, the tests that target it are reported as skipped with a message that says what to run, and
`pokerlm.equity.eval7` (pure Python) serves as the fallback.

## Reference checkpoint

The checkpoint is **not** in the repository nor in the wheel. It is published as an asset of the `v0.1.0` release,
uploaded right after the release is created (the download below fails in the short window before that): the weights
alone (no optimiser state), 10,965,767 bytes.

```sh
mkdir -p checkpoints
curl -L -o checkpoints/pokerlm-reference.pt \
  https://github.com/jbr589/pokerlm/releases/download/v0.1.0/pokerlm-reference.pt
echo "264d9a1c127c6c79ad8c6edff7511643cb3f4a6dbc99cc2b13c0f38ad84c8b7d  checkpoints/pokerlm-reference.pt" | sha256sum --check
```

Provenance: the file is produced by the command of this repository
`python -m pokerlm export-weights --checkpoint runs/20260730-172646/best.pt --out checkpoints/pokerlm-reference.pt`;
the source `best.pt` was trained by `python -m pokerlm train` on the data described below. SHA-256 and size are the
ones to check before use. `pokerlm` loads checkpoints with `torch.load(..., weights_only=True)`, which refuses arbitrary pickled objects; still, only use a file whose sum matches.

With the checkpoint in `checkpoints/`, a clone replays the whole documentation, nothing skipped except the blocks
that need the corpus or a GPU, or the training-run artefacts (`metrics.csv`, `summary.json`), which are not published:

```sh
git clone https://github.com/jbr589/pokerlm && cd pokerlm
make -C eval libpokereval.so
uv sync --locked --extra test        # torch is resolved on the CPU index
uv run make check                    # pytest + replay of every console block of docs/*.md
```

`make check-ci` is the same gate without the checkpoint, the corpus and a GPU: it is what the CI of this repository
runs.

## Data and credits

The training corpus is derived from *A Dataset of Poker Hand Histories* (PHH Dataset, including Annual Computer
Poker Competition hand histories) by Juho Kim (University of Toronto; GitHub organisation
uoftcprg), <https://zenodo.org/records/17136841>, licensed under
[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). Changes were made: the published checkpoint is a model
trained on a subset (the ACPC 2009 hands) converted to this repository's notation. The reference checkpoint is a derivative of that
dataset and is distributed under the same attribution requirement (see [NOTICE](https://github.com/jbr589/pokerlm/blob/main/NOTICE)).
The raw corpus (the PHH Dataset archive, about 20 GB; the 2009 subset used here is about 1.2 GB once extracted) is
not in this repository; chapter 0 explains how to regenerate the training files.

The reports and logs under `data/token-maxing/` (a league of remote language models against PokerLM and two free
witnesses, a flush-targeted situation corpus) and `data/anti-flush-blindness/` are outputs of the commands recorded in
their reports, with the exceptions stated there: some logs (for instance `data/token-maxing/PILOT-league.md`) come from a
harness that is not versioned, as the report itself says. The language models' answers are third-party generated text.

## Limitations

- The model is a **weak poker player**: `bench_easy` 14/52, below the "always fold" baseline (16/52). The league
  ranking measures how much a weak opponent can be exploited, not strength at poker in general.
- It was trained on heads-up no-limit cash hands only; other formats are out of its vocabulary or untested.
- The reference checkpoint was trained once, on one machine (a consumer GPU); there is no seed-to-seed variance study.
- The playable table is a laboratory instrument bound to `127.0.0.1`, not a production server.
- Measurements and figures are those of the documentation at the time of the release; they are replayed by
  `make check`, not guaranteed on other hardware or library versions.
- The public history is a single squashed commit; statements in the reports about commit order, `git diff` output
  or commit timestamps refer to the private development history and cannot be verified here.

## Language and contributions

Everything is in English, except the following, kept verbatim in French so that results stay
reproducible.

- The frozen prompts sent to the language models: `pokerlm/league/prompt.py`, `_FORMAT_REMINDER` in
  `pokerlm/league/agents.py`, and `pokerlm/flushcorpus/generate.py`.
- The corpus category table `_CATEGORY_CLASS_COUNTS` in `pokerlm/flushcorpus/label.py`, and the `category` field it
  fills.
- Recorded data, never rewritten: everything under `data/token-maxing/league/` and `data/token-maxing/runs/`,
  `data/token-maxing/flush-corpus.jsonl`, everything under `data/anti-flush-blindness/league-after/` (manifests and
  logs; the logs are recorded command output, whose first three lines are French), and
  the `out_dir` of the recorded `summary.json` files, which holds the former directory name (explained in
  `data/anti-flush-blindness/REPORT-training.md`).
- The test fixtures that mirror these frozen strings: the category names in `tests/test_flushcorpus_label.py` and a
  fragment of the system prompt in `tests/test_league_integrity.py`.

This is a mirror repository: contributions are reviewed and ported by hand. Issues are welcome;
pull requests are read but not merged as such, and a change that is accepted lands in a later release.
Security reports: see [SECURITY.md](https://github.com/jbr589/pokerlm/blob/main/SECURITY.md).

## License

Apache License 2.0, see [LICENSE](https://github.com/jbr589/pokerlm/blob/main/LICENSE) and [NOTICE](https://github.com/jbr589/pokerlm/blob/main/NOTICE).
