chessnets 0.1.0__py3-none-any.whl

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.
Files changed (82) hide show
  1. chessnets/__init__.py +29 -0
  2. chessnets/_optional.py +64 -0
  3. chessnets/cli.py +101 -0
  4. chessnets/loaders/__init__.py +5 -0
  5. chessnets/loaders/convert_lc0.py +237 -0
  6. chessnets/loaders/convert_maia2.py +209 -0
  7. chessnets/loaders/convert_unimaia_config.py +89 -0
  8. chessnets/loaders/convert_unimaia_mergekit.py +424 -0
  9. chessnets/loaders/load_lc0_model.py +179 -0
  10. chessnets/loaders/load_unimaia_model.py +362 -0
  11. chessnets/loaders/safetensors.py +139 -0
  12. chessnets/models/__init__.py +1 -0
  13. chessnets/models/_pretrained.py +59 -0
  14. chessnets/models/allie/__init__.py +0 -0
  15. chessnets/models/allie/configuration_allie.py +81 -0
  16. chessnets/models/allie/data.py +371 -0
  17. chessnets/models/allie/modeling_allie.py +277 -0
  18. chessnets/models/allie/moves.py +1979 -0
  19. chessnets/models/allie/utils.py +32 -0
  20. chessnets/models/chess_clip/__init__.py +3 -0
  21. chessnets/models/chess_clip/model_configs/chessclip-quickgelu.json +32 -0
  22. chessnets/models/chess_clip/modeling_chess_clip.py +977 -0
  23. chessnets/models/lc0.py +37 -0
  24. chessnets/models/lc0_cf/__init__.py +5 -0
  25. chessnets/models/lc0_cf/layers_lc0_cf.py +735 -0
  26. chessnets/models/lc0_cf/modeling_lc0_cf.py +206 -0
  27. chessnets/models/lc0_policy_map.py +108 -0
  28. chessnets/models/lc0_senet/__init__.py +5 -0
  29. chessnets/models/lc0_senet/configuration_lc0_senet.py +562 -0
  30. chessnets/models/lc0_senet/layers_lc0_senet.py +125 -0
  31. chessnets/models/lc0_senet/modeling_lc0_senet.py +93 -0
  32. chessnets/models/maia2/__init__.py +17 -0
  33. chessnets/models/maia2/configuration_maia2.py +128 -0
  34. chessnets/models/maia2/modeling_maia2.py +384 -0
  35. chessnets/models/maia2/utils.py +104 -0
  36. chessnets/models/unimaia/__init__.py +28 -0
  37. chessnets/models/unimaia/configuration_unimaia.py +219 -0
  38. chessnets/models/unimaia/modeling_unimaia.py +533 -0
  39. chessnets/pipelines/__init__.py +64 -0
  40. chessnets/pipelines/allie/__init__.py +15 -0
  41. chessnets/pipelines/allie/pipeline_allie.py +434 -0
  42. chessnets/pipelines/auto_pipeline.py +484 -0
  43. chessnets/pipelines/base.py +352 -0
  44. chessnets/pipelines/carlini/__init__.py +4 -0
  45. chessnets/pipelines/carlini/pipeline_carlini.py +1000 -0
  46. chessnets/pipelines/chess_clip/__init__.py +13 -0
  47. chessnets/pipelines/chess_clip/pipeline_chess_clip.py +296 -0
  48. chessnets/pipelines/lc0/__init__.py +5 -0
  49. chessnets/pipelines/lc0/pipeline_lc0.py +343 -0
  50. chessnets/pipelines/maia2/__init__.py +13 -0
  51. chessnets/pipelines/maia2/pipeline_maia2.py +346 -0
  52. chessnets/pipelines/outputs.py +564 -0
  53. chessnets/pipelines/pipeline_utils.py +242 -0
  54. chessnets/pipelines/text_generation/__init__.py +4 -0
  55. chessnets/pipelines/text_generation/pipeline_text_generation.py +1196 -0
  56. chessnets/pipelines/unimaia/__init__.py +28 -0
  57. chessnets/pipelines/unimaia/pipeline_unimaia.py +651 -0
  58. chessnets/play/__init__.py +75 -0
  59. chessnets/play/adapters.py +187 -0
  60. chessnets/play/config.py +271 -0
  61. chessnets/play/context.py +285 -0
  62. chessnets/play/lichess_bot/__init__.py +11 -0
  63. chessnets/play/lichess_bot/cli.py +107 -0
  64. chessnets/play/lichess_bot/client.py +175 -0
  65. chessnets/play/lichess_bot/runner.py +365 -0
  66. chessnets/play/matching.py +97 -0
  67. chessnets/play/metadata.py +213 -0
  68. chessnets/play/uci.py +718 -0
  69. chessnets/utils/__init__.py +19 -0
  70. chessnets/utils/board_history.py +552 -0
  71. chessnets/utils/decode_policy.py +60 -0
  72. chessnets/utils/time_control.py +189 -0
  73. chessnets-0.1.0.dist-info/METADATA +183 -0
  74. chessnets-0.1.0.dist-info/RECORD +82 -0
  75. chessnets-0.1.0.dist-info/WHEEL +4 -0
  76. chessnets-0.1.0.dist-info/entry_points.txt +4 -0
  77. chessnets-0.1.0.dist-info/licenses/LICENSE +201 -0
  78. chessnets-0.1.0.dist-info/licenses/LICENSES/Allie-MIT.txt +21 -0
  79. chessnets-0.1.0.dist-info/licenses/LICENSES/ChessGPT-Apache-2.0.txt +202 -0
  80. chessnets-0.1.0.dist-info/licenses/LICENSES/Maia2-MIT.txt +21 -0
  81. chessnets-0.1.0.dist-info/licenses/LICENSES/OpenCLIP-MIT.txt +23 -0
  82. chessnets-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +40 -0
chessnets/__init__.py ADDED
@@ -0,0 +1,29 @@
1
+ """ChessNets: chess-playing and human move-imitation models.
2
+
3
+ ``AutoPipeline`` is imported lazily so that ``import chessnets`` (and the
4
+ ``chessnets`` command line) stay fast; PyTorch loads on first use.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import typing as _tp
10
+ from importlib import metadata as _metadata
11
+
12
+ if _tp.TYPE_CHECKING:
13
+ from .pipelines.auto_pipeline import AutoPipeline
14
+
15
+ try:
16
+ __version__ = _metadata.version("chessnets")
17
+ except _metadata.PackageNotFoundError: # running from a source tree without installing
18
+ __version__ = "0+unknown"
19
+
20
+
21
+ def __getattr__(name: str) -> _tp.Any:
22
+ if name == "AutoPipeline":
23
+ from .pipelines.auto_pipeline import AutoPipeline
24
+
25
+ return AutoPipeline
26
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
27
+
28
+
29
+ __all__ = ["AutoPipeline", "__version__"]
chessnets/_optional.py ADDED
@@ -0,0 +1,64 @@
1
+ """Access to third-party packages supplied by optional extras.
2
+
3
+ Each call site names the extra that provides the package, so a missing
4
+ dependency produces an actionable ``install chessnets[<extra>]`` error at the
5
+ point of use. ChessNets' own modules are imported normally.
6
+
7
+ Use :func:`optional_module` for a lazy module-level handle (the import happens
8
+ on first attribute access) and :func:`import_optional` when the package is
9
+ needed immediately, for example to define classes at import time.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import importlib
15
+ import types
16
+ import typing as tp
17
+
18
+
19
+ def import_optional(module_name: str, extra: str | None) -> types.ModuleType:
20
+ """Import ``module_name`` or explain how to install it.
21
+
22
+ ``extra`` names the ChessNets extra that provides the package. Pass ``None``
23
+ for rarely needed packages that no extra provides; the error then asks for
24
+ the package itself.
25
+ """
26
+ try:
27
+ return importlib.import_module(module_name)
28
+ except ModuleNotFoundError as exc:
29
+ # Only translate the error for the requested package itself; a missing
30
+ # transitive dependency of an installed package should surface as-is.
31
+ if exc.name is not None and (
32
+ module_name == exc.name or module_name.startswith(f"{exc.name}.")
33
+ ):
34
+ requirement = (
35
+ f"chessnets[{extra}]" if extra else module_name.split(".", 1)[0]
36
+ )
37
+ raise ImportError(
38
+ f"{module_name} is required for this feature; install {requirement}."
39
+ ) from exc
40
+ raise
41
+
42
+
43
+ class OptionalModule:
44
+ """Module proxy that imports its target on first attribute access."""
45
+
46
+ def __init__(self, module_name: str, extra: str | None):
47
+ self.module_name = module_name
48
+ self.extra = extra
49
+ self._module: types.ModuleType | None = None
50
+
51
+ def _load(self) -> types.ModuleType:
52
+ if self._module is None:
53
+ self._module = import_optional(self.module_name, self.extra)
54
+ return self._module
55
+
56
+ def __getattr__(self, name: str) -> tp.Any:
57
+ return getattr(self._load(), name)
58
+
59
+
60
+ def optional_module(module_name: str, extra: str | None) -> OptionalModule:
61
+ return OptionalModule(module_name, extra)
62
+
63
+
64
+ __all__ = ["OptionalModule", "import_optional", "optional_module"]
chessnets/cli.py ADDED
@@ -0,0 +1,101 @@
1
+ """The ``chessnets`` command line.
2
+
3
+ Subcommands are dispatched by name and imported only when they run, so
4
+ ``chessnets --help`` stays fast and never loads PyTorch.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import dataclasses
10
+ import importlib
11
+ import sys
12
+ import typing as tp
13
+
14
+
15
+ @dataclasses.dataclass(frozen=True)
16
+ class Command:
17
+ module: str
18
+ help: str
19
+
20
+ def run(self, argv: list[str], prog: str) -> int:
21
+ main = importlib.import_module(self.module).main
22
+ return main(argv, prog=prog) or 0
23
+
24
+
25
+ CommandTable = dict[str, tp.Union[Command, "CommandGroup"]]
26
+
27
+
28
+ @dataclasses.dataclass(frozen=True)
29
+ class CommandGroup:
30
+ help: str
31
+ commands: CommandTable
32
+
33
+
34
+ COMMANDS: CommandTable = {
35
+ "uci": Command(
36
+ "chessnets.play.uci",
37
+ "run a pipeline as a UCI chess engine (also installed as chessnets-uci)",
38
+ ),
39
+ "lichess-bot": Command(
40
+ "chessnets.play.lichess_bot.cli",
41
+ "run a pipeline as a Lichess Bot account",
42
+ ),
43
+ "convert": CommandGroup(
44
+ "convert checkpoints to ChessNets safetensors repositories",
45
+ {
46
+ "lc0": Command(
47
+ "chessnets.loaders.convert_lc0",
48
+ "convert an Lc0/Maia protobuf checkpoint "
49
+ "(requires the chessnets-lc0-protobuf adapter)",
50
+ ),
51
+ },
52
+ ),
53
+ }
54
+
55
+
56
+ def _usage(prog: str, commands: CommandTable) -> str:
57
+ width = max(len(name) for name in commands)
58
+ lines = [f"usage: {prog} <command> [<args>]", "", "commands:"]
59
+ lines += [
60
+ f" {name.ljust(width)} {entry.help}" for name, entry in commands.items()
61
+ ]
62
+ lines += ["", f"Run '{prog} <command> --help' for a command's options."]
63
+ return "\n".join(lines)
64
+
65
+
66
+ def _dispatch(commands: CommandTable, argv: list[str], prog: str) -> int:
67
+ if not argv:
68
+ print(_usage(prog, commands), file=sys.stderr)
69
+ return 2
70
+ name, rest = argv[0], argv[1:]
71
+ if name in {"-h", "--help"}:
72
+ print(_usage(prog, commands))
73
+ return 0
74
+ if name == "--version" and commands is COMMANDS:
75
+ from chessnets import __version__
76
+
77
+ print(f"{prog} {__version__}")
78
+ return 0
79
+ entry = commands.get(name)
80
+ if entry is None:
81
+ print(
82
+ f"{prog}: unknown command {name!r}\n\n{_usage(prog, commands)}",
83
+ file=sys.stderr,
84
+ )
85
+ return 2
86
+ if isinstance(entry, CommandGroup):
87
+ return _dispatch(entry.commands, rest, f"{prog} {name}")
88
+ return entry.run(rest, f"{prog} {name}")
89
+
90
+
91
+ def main(argv: list[str] | None = None) -> int:
92
+ return _dispatch(
93
+ COMMANDS, list(sys.argv[1:] if argv is None else argv), "chessnets"
94
+ )
95
+
96
+
97
+ if __name__ == "__main__":
98
+ raise SystemExit(main())
99
+
100
+
101
+ __all__ = ["COMMANDS", "Command", "CommandGroup", "main"]
@@ -0,0 +1,5 @@
1
+ """Checkpoint loaders."""
2
+
3
+ from .load_unimaia_model import load_unimaia_model
4
+
5
+ __all__ = ["load_unimaia_model"]
@@ -0,0 +1,237 @@
1
+ """Convert Lc0/Maia protobuf checkpoints to canonical safetensors repos."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import json
8
+ import pathlib
9
+ import shutil
10
+ import typing as tp
11
+
12
+ import torch
13
+ from safetensors.torch import save_file
14
+
15
+ from chessnets.models._pretrained import resolve_pretrained_file
16
+ from chessnets.models.lc0_senet.configuration_lc0_senet import (
17
+ LeelaInferenceConfig,
18
+ )
19
+
20
+
21
+ def _sha256(path: pathlib.Path) -> str:
22
+ digest = hashlib.sha256()
23
+ with path.open("rb") as stream:
24
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
25
+ digest.update(chunk)
26
+ return digest.hexdigest()
27
+
28
+
29
+ def _resolve_source(
30
+ source: str | pathlib.Path, resolve_kwargs: dict[str, tp.Any]
31
+ ) -> pathlib.Path:
32
+ path = pathlib.Path(source).expanduser()
33
+ if path.is_file():
34
+ return path.resolve()
35
+ if path.is_dir():
36
+ candidate = path / "model.pb.gz"
37
+ if candidate.is_file():
38
+ return candidate.resolve()
39
+ raise FileNotFoundError(f"Could not find 'model.pb.gz' in {path}")
40
+ return resolve_pretrained_file(source, "model.pb.gz", **resolve_kwargs)
41
+
42
+
43
+ def _resolve_config(
44
+ source: str | pathlib.Path,
45
+ source_path: pathlib.Path,
46
+ config_path: str | pathlib.Path | None,
47
+ resolve_kwargs: dict[str, tp.Any],
48
+ ) -> tuple[pathlib.Path, LeelaInferenceConfig]:
49
+ if config_path is not None:
50
+ path = pathlib.Path(config_path).expanduser().resolve()
51
+ else:
52
+ path = source_path.parent / "config.json"
53
+ if not path.is_file():
54
+ path = source_path.parent / "config.yaml"
55
+ if not path.is_file():
56
+ for filename in ("config.json", "config.yaml"):
57
+ try:
58
+ path = resolve_pretrained_file(source, filename, **resolve_kwargs)
59
+ break
60
+ except FileNotFoundError:
61
+ continue
62
+ else:
63
+ raise FileNotFoundError(
64
+ "No config was found; pass --config for a protobuf-only directory"
65
+ )
66
+
67
+ if path.suffix == ".json":
68
+ inference_config = LeelaInferenceConfig.from_json(path)
69
+ else:
70
+ inference_config = LeelaInferenceConfig.from_yaml(path)
71
+ return path, inference_config
72
+
73
+
74
+ def convert_checkpoint(
75
+ source: str | pathlib.Path,
76
+ output_dir: str | pathlib.Path,
77
+ *,
78
+ config_path: str | pathlib.Path | None = None,
79
+ retain_protobuf: bool = True,
80
+ dry_run: bool = False,
81
+ revision: str | None = None,
82
+ cache_dir: str | pathlib.Path | None = None,
83
+ token: str | bool | None = None,
84
+ local_files_only: bool = False,
85
+ ) -> dict[str, tp.Any]:
86
+ """Decode a LINEAR16 protobuf into a float32 safetensors checkpoint."""
87
+ resolve_kwargs = {
88
+ "revision": revision,
89
+ "cache_dir": cache_dir,
90
+ "token": token,
91
+ "local_files_only": local_files_only,
92
+ }
93
+ source_path = _resolve_source(source, resolve_kwargs)
94
+ resolved_config_path, config = _resolve_config(
95
+ source, source_path, config_path, resolve_kwargs
96
+ )
97
+ output = pathlib.Path(output_dir).expanduser().resolve()
98
+ from chessnets.loaders.load_lc0_model import _get_protobuf_adapter
99
+
100
+ source_format = _get_protobuf_adapter().inspect_checkpoint(source_path)
101
+ report: dict[str, tp.Any] = {
102
+ "source": str(source_path),
103
+ "source_sha256": _sha256(source_path),
104
+ "source_config": str(resolved_config_path),
105
+ "source_config_sha256": _sha256(resolved_config_path),
106
+ "output": str(output),
107
+ "architecture": config.architectures[0],
108
+ **source_format,
109
+ }
110
+ if dry_run:
111
+ return report
112
+
113
+ from chessnets.loaders.load_lc0_model import load_local_model
114
+
115
+ model = load_local_model(source_path, resolved_config_path, is_eval=True).float()
116
+ state_dict = {
117
+ name: tensor.detach().cpu().contiguous()
118
+ for name, tensor in model.state_dict().items()
119
+ }
120
+ non_float = {
121
+ name: str(tensor.dtype)
122
+ for name, tensor in state_dict.items()
123
+ if not tensor.is_floating_point()
124
+ }
125
+ float_dtypes = {
126
+ str(tensor.dtype)
127
+ for tensor in state_dict.values()
128
+ if tensor.is_floating_point()
129
+ }
130
+ if float_dtypes != {str(torch.float32)}:
131
+ raise RuntimeError(f"Conversion produced non-float32 tensors: {float_dtypes}")
132
+
133
+ output.mkdir(parents=True, exist_ok=True)
134
+ weights_path = output / "model.safetensors"
135
+ save_file(
136
+ state_dict,
137
+ str(weights_path),
138
+ metadata={
139
+ "format": "pt",
140
+ "source_container_format": "lc0-protobuf",
141
+ "source_weight_encoding": "LINEAR16",
142
+ "decoded_tensor_dtype": "float32",
143
+ },
144
+ )
145
+ config.save_pretrained(output)
146
+ if retain_protobuf:
147
+ original_dir = output / "original"
148
+ original_dir.mkdir(exist_ok=True)
149
+ retained_path = original_dir / "model.pb.gz"
150
+ if source_path.resolve() != retained_path.resolve():
151
+ shutil.copy2(source_path, retained_path)
152
+ report["retained_source"] = str(retained_path)
153
+ if resolved_config_path.suffix in {".yaml", ".yml"}:
154
+ training_dir = output / "training"
155
+ training_dir.mkdir(exist_ok=True)
156
+ retained_config = training_dir / "original_lczero_training_config.yaml"
157
+ if resolved_config_path.resolve() != retained_config.resolve():
158
+ shutil.copy2(resolved_config_path, retained_config)
159
+ report["retained_source_config"] = str(retained_config)
160
+ report.update(
161
+ {
162
+ "safetensors": str(weights_path),
163
+ "safetensors_sha256": _sha256(weights_path),
164
+ "tensor_count": len(state_dict),
165
+ "non_float_tensors": non_float,
166
+ }
167
+ )
168
+ provenance = {
169
+ "schema_version": 1,
170
+ "source_reference": str(source),
171
+ "source_sha256": report["source_sha256"],
172
+ "source_config_sha256": report["source_config_sha256"],
173
+ "source_container_format": report["source_container_format"],
174
+ "source_weight_encoding": report["source_weight_encoding"],
175
+ "decoded_tensor_dtype": report["decoded_tensor_dtype"],
176
+ "architecture": report["architecture"],
177
+ "safetensors_sha256": report["safetensors_sha256"],
178
+ "tensor_count": report["tensor_count"],
179
+ }
180
+ (output / "provenance.json").write_text(
181
+ json.dumps(provenance, indent=2, sort_keys=True) + "\n", encoding="utf-8"
182
+ )
183
+ return report
184
+
185
+
186
+ def _parser(prog: str | None = None) -> argparse.ArgumentParser:
187
+ parser = argparse.ArgumentParser(
188
+ prog=prog,
189
+ description=__doc__,
190
+ epilog=(
191
+ "Requires the separately distributed chessnets-lc0-protobuf adapter; "
192
+ "see plugins/lc0-protobuf in the ChessNets source repository."
193
+ ),
194
+ )
195
+ parser.add_argument("source", help="Model repo, directory, or model.pb.gz path")
196
+ parser.add_argument("output", help="Output model repository directory")
197
+ parser.add_argument("--config", help="Config JSON/YAML for protobuf-only sources")
198
+ parser.add_argument(
199
+ "--no-retain-protobuf",
200
+ action="store_true",
201
+ help="Do not copy the source to original/model.pb.gz",
202
+ )
203
+ parser.add_argument("--dry-run", action="store_true")
204
+ parser.add_argument("--revision")
205
+ parser.add_argument("--cache-dir")
206
+ parser.add_argument("--token")
207
+ parser.add_argument("--local-files-only", action="store_true")
208
+ return parser
209
+
210
+
211
+ def main(argv: list[str] | None = None, *, prog: str | None = None) -> None:
212
+ args = _parser(prog).parse_args(argv)
213
+ from chessnets.loaders.load_lc0_model import _get_protobuf_adapter
214
+
215
+ try:
216
+ _get_protobuf_adapter()
217
+ except ModuleNotFoundError as exc:
218
+ raise SystemExit(f"error: {exc}") from None
219
+ report = convert_checkpoint(
220
+ args.source,
221
+ args.output,
222
+ config_path=args.config,
223
+ retain_protobuf=not args.no_retain_protobuf,
224
+ dry_run=args.dry_run,
225
+ revision=args.revision,
226
+ cache_dir=args.cache_dir,
227
+ token=args.token,
228
+ local_files_only=args.local_files_only,
229
+ )
230
+ print(json.dumps(report, indent=2, sort_keys=True))
231
+
232
+
233
+ if __name__ == "__main__":
234
+ main()
235
+
236
+
237
+ __all__ = ["convert_checkpoint", "main"]
@@ -0,0 +1,209 @@
1
+ """Convert an upstream Maia 2 training checkpoint to exact safetensors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import json
8
+ import pathlib
9
+ import typing as tp
10
+
11
+ import torch
12
+ from safetensors.torch import load_file, save_file
13
+
14
+ from chessnets.models.maia2.configuration_maia2 import Config
15
+
16
+
17
+ def _sha256(path: pathlib.Path) -> str:
18
+ digest = hashlib.sha256()
19
+ with path.open("rb") as stream:
20
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
21
+ digest.update(chunk)
22
+ return digest.hexdigest()
23
+
24
+
25
+ def _inference_state(checkpoint: tp.Any) -> dict[str, torch.Tensor]:
26
+ if not isinstance(checkpoint, dict):
27
+ raise TypeError("Maia 2 checkpoint must contain a mapping")
28
+ raw = checkpoint.get("model_state_dict", checkpoint)
29
+ if not isinstance(raw, dict) or not raw:
30
+ raise ValueError("Maia 2 checkpoint has no model_state_dict")
31
+ state: dict[str, torch.Tensor] = {}
32
+ for original_name, tensor in raw.items():
33
+ if not isinstance(original_name, str) or not isinstance(tensor, torch.Tensor):
34
+ raise TypeError("Maia 2 state dict must contain named tensors only")
35
+ name = original_name.removeprefix("module.")
36
+ if name in state:
37
+ raise ValueError(f"Duplicate normalized state-dict key: {name}")
38
+ state[name] = tensor.detach().cpu().contiguous()
39
+ return state
40
+
41
+
42
+ def _assert_identical(
43
+ expected: dict[str, torch.Tensor], actual: dict[str, torch.Tensor]
44
+ ) -> None:
45
+ if expected.keys() != actual.keys():
46
+ missing = sorted(expected.keys() - actual.keys())
47
+ unexpected = sorted(actual.keys() - expected.keys())
48
+ raise RuntimeError(
49
+ f"Safetensors keys differ; missing={missing}, unexpected={unexpected}"
50
+ )
51
+ for name, tensor in expected.items():
52
+ restored = actual[name]
53
+ if tensor.dtype != restored.dtype or tensor.shape != restored.shape:
54
+ raise RuntimeError(f"Safetensors metadata differs for {name!r}")
55
+ if not torch.equal(tensor, restored):
56
+ raise RuntimeError(f"Safetensors tensor differs for {name!r}")
57
+
58
+
59
+ def _assert_outputs_identical(
60
+ config: Config,
61
+ expected: dict[str, torch.Tensor],
62
+ actual: dict[str, torch.Tensor],
63
+ ) -> None:
64
+ from chessnets.models.maia2.modeling_maia2 import Maia2Model
65
+
66
+ original = Maia2Model.from_config(config)
67
+ converted = Maia2Model.from_config(config)
68
+ original.load_state_dict(expected, strict=True)
69
+ converted.load_state_dict(actual, strict=True)
70
+ original.eval()
71
+ converted.eval()
72
+ boards = torch.zeros((2, config.input_channels, 8, 8), dtype=torch.float32)
73
+ elos_self = torch.tensor([0, 1], dtype=torch.int32)
74
+ elos_oppo = torch.tensor([1, 0], dtype=torch.int32)
75
+ with torch.inference_mode():
76
+ expected_outputs = original(boards, elos_self, elos_oppo)
77
+ actual_outputs = converted(boards, elos_self, elos_oppo)
78
+ for index, (left, right) in enumerate(zip(expected_outputs, actual_outputs)):
79
+ if not torch.equal(left, right):
80
+ raise RuntimeError(f"Converted model output {index} is not bit-identical")
81
+
82
+
83
+ def convert_maia2_checkpoint(
84
+ checkpoint: str | pathlib.Path,
85
+ training_config: str | pathlib.Path,
86
+ output_dir: str | pathlib.Path,
87
+ *,
88
+ time_control: tp.Literal["blitz", "rapid"],
89
+ source_url: str | None = None,
90
+ training_config_url: str | None = None,
91
+ write: bool = True,
92
+ ) -> dict[str, tp.Any]:
93
+ """Convert and verify one Maia 2 checkpoint."""
94
+ checkpoint_path = pathlib.Path(checkpoint).expanduser().resolve()
95
+ config_path = pathlib.Path(training_config).expanduser().resolve()
96
+ output = pathlib.Path(output_dir).expanduser().resolve()
97
+ if time_control not in {"blitz", "rapid"}:
98
+ raise ValueError("time_control must be 'blitz' or 'rapid'")
99
+ if not checkpoint_path.is_file():
100
+ raise FileNotFoundError(checkpoint_path)
101
+ if not config_path.is_file():
102
+ raise FileNotFoundError(config_path)
103
+
104
+ legacy_config = Config.from_yaml(config_path)
105
+ values = legacy_config.to_dict()
106
+ values["time_control"] = time_control
107
+ config = Config.from_dict(values)
108
+ checkpoint_hash = _sha256(checkpoint_path)
109
+ training_config_hash = _sha256(config_path)
110
+ report: dict[str, tp.Any] = {
111
+ "checkpoint": str(checkpoint_path),
112
+ "checkpoint_sha256": checkpoint_hash,
113
+ "config": config.to_dict(),
114
+ "output_dir": str(output),
115
+ "time_control": time_control,
116
+ "training_config_sha256": training_config_hash,
117
+ "write": write,
118
+ }
119
+ if source_url:
120
+ report["source_url"] = source_url
121
+ if training_config_url:
122
+ report["training_config_url"] = training_config_url
123
+ if not write:
124
+ return report
125
+
126
+ output.mkdir(parents=True, exist_ok=True)
127
+ for filename in ("config.json", "model.safetensors", "provenance.json"):
128
+ if (output / filename).exists():
129
+ raise FileExistsError(f"Refusing to overwrite {output / filename}")
130
+
131
+ checkpoint_data = torch.load(checkpoint_path, map_location="cpu", weights_only=True)
132
+ state = _inference_state(checkpoint_data)
133
+ model_path = output / "model.safetensors"
134
+ save_file(
135
+ state,
136
+ model_path,
137
+ metadata={
138
+ "format": "pt",
139
+ "source_checkpoint_sha256": checkpoint_hash,
140
+ "time_control": time_control,
141
+ },
142
+ )
143
+ restored = load_file(model_path, device="cpu")
144
+ _assert_identical(state, restored)
145
+ _assert_outputs_identical(config, state, restored)
146
+ config.save_pretrained(output)
147
+
148
+ provenance = {
149
+ "conversion": {
150
+ "key_normalization": (
151
+ "renamed each state-dict key from module.<name> to <name> by "
152
+ "removing the PyTorch DataParallel prefix"
153
+ ),
154
+ "output_format": "safetensors",
155
+ "tensor_equality": "torch.equal for every tensor",
156
+ "output_equality": "torch.equal for policy, auxiliary, and value outputs",
157
+ },
158
+ "source": {
159
+ "checkpoint_filename": checkpoint_path.name,
160
+ "checkpoint_sha256": checkpoint_hash,
161
+ "training_config_filename": config_path.name,
162
+ "training_config_sha256": training_config_hash,
163
+ },
164
+ "tensor_count": len(state),
165
+ "time_control": time_control,
166
+ }
167
+ if source_url:
168
+ provenance["source"]["url"] = source_url
169
+ if training_config_url:
170
+ provenance["source"]["training_config_url"] = training_config_url
171
+ (output / "provenance.json").write_text(
172
+ json.dumps(provenance, indent=2, sort_keys=True) + "\n", encoding="utf-8"
173
+ )
174
+ report.update(
175
+ model_safetensors_sha256=_sha256(model_path),
176
+ tensor_count=len(state),
177
+ tensors_identical=True,
178
+ outputs_identical=True,
179
+ )
180
+ return report
181
+
182
+
183
+ def main(argv: list[str] | None = None) -> None:
184
+ parser = argparse.ArgumentParser(description=__doc__)
185
+ parser.add_argument("checkpoint")
186
+ parser.add_argument("training_config")
187
+ parser.add_argument("output_dir")
188
+ parser.add_argument("--time-control", choices=("blitz", "rapid"), required=True)
189
+ parser.add_argument("--source-url")
190
+ parser.add_argument("--training-config-url")
191
+ parser.add_argument("--dry-run", action="store_true")
192
+ args = parser.parse_args(argv)
193
+ report = convert_maia2_checkpoint(
194
+ args.checkpoint,
195
+ args.training_config,
196
+ args.output_dir,
197
+ time_control=args.time_control,
198
+ source_url=args.source_url,
199
+ training_config_url=args.training_config_url,
200
+ write=not args.dry_run,
201
+ )
202
+ print(json.dumps(report, indent=2, sort_keys=True))
203
+
204
+
205
+ if __name__ == "__main__":
206
+ main()
207
+
208
+
209
+ __all__ = ["convert_maia2_checkpoint", "main"]