maia2 0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
maia2-0.1/.gitignore ADDED
@@ -0,0 +1,162 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
maia2-0.1/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ BSD 2-Clause License
2
+
3
+ Copyright (c) 2024, CSSLab
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
maia2-0.1/PKG-INFO ADDED
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.1
2
+ Name: maia2
3
+ Version: 0.1
4
+ Summary: An amazing sample package for maia2.
5
+ Author-email: csslab <josephtang@cs.toronto.edu>
6
+ Description-Content-Type: text/markdown
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Project-URL: Home, https://github.com/CSSLab/maia2
9
+
10
+ # maia2
maia2-0.1/README.md ADDED
@@ -0,0 +1 @@
1
+ # maia2
@@ -0,0 +1,3 @@
1
+ """An amazing sample package for maia2."""
2
+
3
+ __version__ = "0.1"
@@ -0,0 +1,28 @@
1
+ #!/bin/bash
2
+
3
+ # Loop over each year
4
+ for year in {2018..2023}; do
5
+ # Loop over each month
6
+ for month in {05..12}; do
7
+ # Form the URL
8
+ url="https://database.lichess.org/standard/lichess_db_standard_rated_${year}-${month}.pgn.zst"
9
+
10
+ # Check if the URL exists
11
+ if wget --spider $url 2>/dev/null; then
12
+ # Download the file
13
+ wget "$url"
14
+
15
+ # The downloaded file name
16
+ filename="lichess_db_standard_rated_${year}-${month}.pgn.zst"
17
+
18
+ else
19
+ echo "File for ${year}-${month} does not exist."
20
+ fi
21
+
22
+ # Stop the loop if we've reached October 2023
23
+ if [ "$year" -eq 2023 ] && [ "$month" = "10" ]; then
24
+ break
25
+ fi
26
+ done
27
+
28
+ done
@@ -0,0 +1,154 @@
1
+ from utils import *
2
+ from main import *
3
+
4
+
5
+ class TestDataset(torch.utils.data.Dataset):
6
+
7
+ def __init__(self, data, all_moves_dict, elo_dict):
8
+
9
+ self.all_moves_dict = all_moves_dict
10
+ self.data = data.values.tolist()
11
+ self.elo_dict = elo_dict
12
+
13
+ def __len__(self):
14
+
15
+ return len(self.data)
16
+
17
+ def __getitem__(self, idx):
18
+
19
+ fen, move, elo_self, elo_oppo = self.data[idx]
20
+
21
+ if fen.split(' ')[1] == 'w':
22
+ board = chess.Board(fen)
23
+ elif fen.split(' ')[1] == 'b':
24
+ board = chess.Board(fen).mirror()
25
+ move = mirror_move(move)
26
+ else:
27
+ raise ValueError(f"Invalid fen: {fen}")
28
+
29
+ board_input = board_to_tensor(board)
30
+
31
+ elo_self = map_to_category(elo_self, self.elo_dict)
32
+ elo_oppo = map_to_category(elo_oppo, self.elo_dict)
33
+
34
+ legal_moves, _ = get_side_info(board, move, self.all_moves_dict)
35
+
36
+ return fen, board_input, elo_self, elo_oppo, legal_moves
37
+
38
+
39
+ def get_preds(model, dataloader, all_moves_dict_reversed, cfg_inference):
40
+
41
+ all_probs = []
42
+ predicted_move_probs = []
43
+ predicted_moves = []
44
+ predicted_win_probs = []
45
+
46
+ model.eval()
47
+ with torch.no_grad():
48
+
49
+ for fens, boards, elos_self, elos_oppo, legal_moves in dataloader:
50
+
51
+ if cfg_inference.gpu:
52
+ boards = boards.cuda()
53
+ elos_self = elos_self.cuda()
54
+ elos_oppo = elos_oppo.cuda()
55
+ legal_moves = legal_moves.cuda()
56
+
57
+ logits_maia, _, logits_value = model(boards, elos_self, elos_oppo)
58
+ logits_maia_legal = logits_maia * legal_moves
59
+ probs = logits_maia_legal.softmax(dim=-1)
60
+
61
+ all_probs.append(probs.cpu())
62
+ predicted_move_probs.append(probs.max(dim=-1).values.cpu())
63
+ predicted_move_indices = probs.argmax(dim=-1)
64
+ for i in range(len(fens)):
65
+ fen = fens[i]
66
+ predicted_move = all_moves_dict_reversed[predicted_move_indices[i].item()]
67
+ if fen.split(' ')[1] == 'b':
68
+ predicted_move = mirror_move(predicted_move)
69
+ predicted_moves.append(predicted_move)
70
+
71
+ predicted_win_probs.append((logits_value / 2 + 0.5).cpu())
72
+
73
+ all_probs = torch.cat(all_probs).cpu().numpy()
74
+ predicted_move_probs = torch.cat(predicted_move_probs).numpy()
75
+ predicted_win_probs = torch.cat(predicted_win_probs).numpy()
76
+
77
+ return all_probs, predicted_move_probs, predicted_moves, predicted_win_probs
78
+
79
+
80
+ def inference_batch(data):
81
+
82
+ cfg = parse_args()
83
+ cfg_inference = parse_inference_args()
84
+ if cfg_inference.verbose:
85
+ show_cfg(cfg_inference)
86
+
87
+ all_moves = get_all_possible_moves()
88
+ all_moves_dict = {move: i for i, move in enumerate(all_moves)}
89
+ elo_dict = create_elo_dict()
90
+
91
+ model = MAIA2Model(len(all_moves), elo_dict, cfg)
92
+ model = nn.DataParallel(model)
93
+
94
+ checkpoint = torch.load(cfg_inference.model_path, map_location='cpu')
95
+ model.load_state_dict(checkpoint['model_state_dict'])
96
+ model = model.module
97
+
98
+ if cfg_inference.gpu:
99
+ model = model.cuda()
100
+
101
+ all_moves_dict_reversed = {v: k for k, v in all_moves_dict.items()}
102
+ dataset = TestDataset(data, all_moves_dict, elo_dict)
103
+ dataloader = torch.utils.data.DataLoader(dataset,
104
+ batch_size=cfg_inference.batch_size,
105
+ shuffle=False,
106
+ drop_last=False,
107
+ num_workers=cfg_inference.num_workers)
108
+ if cfg_inference.verbose:
109
+ dataloader = tqdm.tqdm(dataloader)
110
+ all_probs, predicted_move_probs, predicted_moves, predicted_win_probs = get_preds(model, dataloader, all_moves_dict_reversed, cfg_inference)
111
+
112
+ data['predicted_move'] = predicted_moves
113
+ data['predicted_move_prob'] = predicted_move_probs
114
+ data['predicted_win_prob'] = predicted_win_probs
115
+ data['all_probs'] = all_probs.tolist()
116
+
117
+ return data
118
+
119
+ def parse_inference_args(args=None):
120
+
121
+ parser = argparse.ArgumentParser()
122
+
123
+ parser.add_argument('--verbose', default=1, type=int)
124
+ parser.add_argument('--batch_size', default=2048, type=int)
125
+ parser.add_argument('--num_workers', default=16, type=int)
126
+ parser.add_argument('--model_path', default='your_model_path', type=str)
127
+ parser.add_argument('--gpu', default=True, type=bool)
128
+
129
+ return parser.parse_args(args)
130
+
131
+ def show_cfg(cfg):
132
+ print('Configurations:', flush=True)
133
+ for arg in vars(cfg):
134
+ print(f'\t{arg}: {getattr(cfg, arg)}', flush=True)
135
+
136
+
137
+ if __name__ == '__main__':
138
+
139
+ data = pd.read_csv('../data/all_reduced_rapid.csv')
140
+ data = data[data.move_ply > 10]
141
+
142
+ data_novice = data[data['rounded_elo'] <= 1500][['board', 'move', 'active_elo', 'opponent_elo']]
143
+ data_intermediate = data[(data['rounded_elo'] > 1500) & (data['rounded_elo'] < 2000)][['board', 'move', 'active_elo', 'opponent_elo']]
144
+ data_advanced = data[data['rounded_elo'] >= 2000][['board', 'move', 'active_elo', 'opponent_elo']]
145
+ print(f'lens: {len(data_novice)}, {len(data_intermediate)}, {len(data_advanced)}', flush=True)
146
+
147
+ results = []
148
+ for split in [data_novice, data_intermediate, data_advanced]:
149
+ inference_batch(split)
150
+ print(round(len(split[split['predicted_move'] == split['move']]) / len(split), 4))
151
+
152
+
153
+
154
+