Update add_mating_data.py
Browse files- add_mating_data.py +44 -70
add_mating_data.py
CHANGED
|
@@ -15,13 +15,14 @@ from pathlib import Path
|
|
| 15 |
|
| 16 |
import chess
|
| 17 |
import chess.engine
|
|
|
|
| 18 |
from tqdm import tqdm
|
| 19 |
|
| 20 |
from athena.datasets.chessbenchmate.utils.bagz import BagReader, BagWriter
|
| 21 |
from athena.datasets.chessbenchmate.utils.constants import CODERS
|
| 22 |
|
| 23 |
ENGINE_PATH = "models/stockfish"
|
| 24 |
-
ENGINE_LIMIT = chess.engine.Limit(time=
|
| 25 |
|
| 26 |
# Global variable for each worker process
|
| 27 |
engine = None
|
|
@@ -44,6 +45,13 @@ def close_worker():
|
|
| 44 |
except Exception:
|
| 45 |
pass
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
def annotate_single_record(record: bytes) -> bytes:
|
| 49 |
"""Annotate a single record with mate-in-N information."""
|
|
@@ -112,36 +120,6 @@ def stockfish_evaluate(
|
|
| 112 |
return win_prob, mate_label
|
| 113 |
|
| 114 |
|
| 115 |
-
def batch_annotate_records(records_batch):
|
| 116 |
-
"""Annotate a batch of records for better performance."""
|
| 117 |
-
global engine
|
| 118 |
-
results = []
|
| 119 |
-
|
| 120 |
-
for record in records_batch:
|
| 121 |
-
try:
|
| 122 |
-
fen, move_str, _, _ = CODERS["action_value_with_mate"].decode(record)
|
| 123 |
-
board = chess.Board(fen)
|
| 124 |
-
win_prob, mate_label = stockfish_evaluate(board, chess.Move.from_uci(move_str), engine)
|
| 125 |
-
|
| 126 |
-
# Validate outputs
|
| 127 |
-
assert 0.0 <= win_prob <= 1.0, f"Invalid win probability: {win_prob}"
|
| 128 |
-
valid_mate_label = (
|
| 129 |
-
mate_label == "#"
|
| 130 |
-
or mate_label == "-"
|
| 131 |
-
or (isinstance(mate_label, int) and abs(mate_label) <= 100)
|
| 132 |
-
)
|
| 133 |
-
assert valid_mate_label, f"Invalid mate label: {mate_label}"
|
| 134 |
-
|
| 135 |
-
results.append(
|
| 136 |
-
CODERS["action_value_with_mate"].encode((fen, move_str, win_prob, mate_label))
|
| 137 |
-
)
|
| 138 |
-
except Exception as e:
|
| 139 |
-
print(f"Error in batch processing: {e}")
|
| 140 |
-
raise
|
| 141 |
-
|
| 142 |
-
return results
|
| 143 |
-
|
| 144 |
-
|
| 145 |
def add_mate_annotations(bag_path: Path) -> None:
|
| 146 |
"""Annotate a .bag file with mate-in-N information in-place."""
|
| 147 |
if not bag_path.exists():
|
|
@@ -156,7 +134,7 @@ def add_mate_annotations(bag_path: Path) -> None:
|
|
| 156 |
return
|
| 157 |
|
| 158 |
# Create temporary file for writing
|
| 159 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".bag") as temp_file:
|
| 160 |
temp_path = temp_file.name
|
| 161 |
|
| 162 |
try:
|
|
@@ -166,33 +144,18 @@ def add_mate_annotations(bag_path: Path) -> None:
|
|
| 166 |
f"Processing {len(records)} records from {bag_path.name} using {cpu_count()} processes"
|
| 167 |
)
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
unit="batch",
|
| 182 |
-
desc=f"Annotating {bag_path.name}",
|
| 183 |
-
):
|
| 184 |
-
for annotated_record in batch_results:
|
| 185 |
-
writer.write(annotated_record)
|
| 186 |
-
else:
|
| 187 |
-
# Single record processing approach
|
| 188 |
-
with Pool(processes=cpu_count(), initializer=init_worker) as pool:
|
| 189 |
-
for annotated_record in tqdm(
|
| 190 |
-
pool.imap(annotate_single_record, records),
|
| 191 |
-
total=len(records),
|
| 192 |
-
unit="record",
|
| 193 |
-
desc=f"Annotating {bag_path.name}",
|
| 194 |
-
):
|
| 195 |
-
writer.write(annotated_record)
|
| 196 |
|
| 197 |
writer.close()
|
| 198 |
|
|
@@ -209,20 +172,31 @@ def add_mate_annotations(bag_path: Path) -> None:
|
|
| 209 |
|
| 210 |
|
| 211 |
def main():
|
| 212 |
-
"""Main entry point to
|
| 213 |
-
# Test with a small file first
|
| 214 |
-
test_bag_path = Path("src/athena/datasets/chessbenchmate/data/test/action_value_data.bag")
|
| 215 |
-
add_mate_annotations(test_bag_path)
|
| 216 |
-
|
| 217 |
-
# Process all training files
|
| 218 |
data_dir = Path("src/athena/datasets/chessbenchmate/data/train")
|
| 219 |
-
bag_files = list(data_dir.glob("*.bag"))
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
add_mate_annotations(bag_file)
|
| 224 |
|
| 225 |
-
print("
|
| 226 |
|
| 227 |
|
| 228 |
if __name__ == "__main__":
|
|
|
|
| 15 |
|
| 16 |
import chess
|
| 17 |
import chess.engine
|
| 18 |
+
import psutil
|
| 19 |
from tqdm import tqdm
|
| 20 |
|
| 21 |
from athena.datasets.chessbenchmate.utils.bagz import BagReader, BagWriter
|
| 22 |
from athena.datasets.chessbenchmate.utils.constants import CODERS
|
| 23 |
|
| 24 |
ENGINE_PATH = "models/stockfish"
|
| 25 |
+
ENGINE_LIMIT = chess.engine.Limit(time=0.05)
|
| 26 |
|
| 27 |
# Global variable for each worker process
|
| 28 |
engine = None
|
|
|
|
| 45 |
except Exception:
|
| 46 |
pass
|
| 47 |
|
| 48 |
+
def print_memory_usage(description=""):
|
| 49 |
+
"""Print current and total available memory usage."""
|
| 50 |
+
process = psutil.Process(os.getpid())
|
| 51 |
+
memory_mb = process.memory_info().rss / 1024 / 1024
|
| 52 |
+
total_mem_mb = psutil.virtual_memory().total / 1024 / 1024
|
| 53 |
+
print(f"{description}Memory usage: {memory_mb:.2f} MB / {total_mem_mb:.2f} MB total", flush=True)
|
| 54 |
+
|
| 55 |
|
| 56 |
def annotate_single_record(record: bytes) -> bytes:
|
| 57 |
"""Annotate a single record with mate-in-N information."""
|
|
|
|
| 120 |
return win_prob, mate_label
|
| 121 |
|
| 122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
def add_mate_annotations(bag_path: Path) -> None:
|
| 124 |
"""Annotate a .bag file with mate-in-N information in-place."""
|
| 125 |
if not bag_path.exists():
|
|
|
|
| 134 |
return
|
| 135 |
|
| 136 |
# Create temporary file for writing
|
| 137 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".bag", dir=bag_path.parent) as temp_file:
|
| 138 |
temp_path = temp_file.name
|
| 139 |
|
| 140 |
try:
|
|
|
|
| 144 |
f"Processing {len(records)} records from {bag_path.name} using {cpu_count()} processes"
|
| 145 |
)
|
| 146 |
|
| 147 |
+
|
| 148 |
+
# Single record processing approach
|
| 149 |
+
with Pool(processes=cpu_count(), initializer=init_worker) as pool:
|
| 150 |
+
for i, annotated_record in tqdm(enumerate(
|
| 151 |
+
pool.imap(annotate_single_record, records)),
|
| 152 |
+
total=len(records),
|
| 153 |
+
unit="record",
|
| 154 |
+
desc=f"Annotating {bag_path.name}",
|
| 155 |
+
):
|
| 156 |
+
writer.write(annotated_record)
|
| 157 |
+
if i % 10000 == 0:
|
| 158 |
+
print_memory_usage(f"Processed {i} records. ")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
writer.close()
|
| 161 |
|
|
|
|
| 172 |
|
| 173 |
|
| 174 |
def main():
|
| 175 |
+
"""Main entry point to process .bag files with optional SLURM array division."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
data_dir = Path("src/athena/datasets/chessbenchmate/data/train")
|
| 177 |
+
bag_files = sorted(list(data_dir.glob("*.bag")))
|
| 178 |
+
num_files = len(bag_files)
|
| 179 |
+
print(f"Found {num_files} bag files in {data_dir}")
|
| 180 |
+
|
| 181 |
+
# Detect SLURM environment variables
|
| 182 |
+
slurm_task_id = int(os.environ.get("SLURM_ARRAY_TASK_ID", "0"))
|
| 183 |
+
slurm_array_size = int(os.environ.get("SLURM_ARRAY_TASK_COUNT", "1"))
|
| 184 |
+
|
| 185 |
+
# Divide files evenly among SLURM array tasks
|
| 186 |
+
chunk_size = (num_files + slurm_array_size - 1) // slurm_array_size
|
| 187 |
+
start = slurm_task_id * chunk_size
|
| 188 |
+
end = min(start + chunk_size, num_files)
|
| 189 |
+
my_files = bag_files[start:end]
|
| 190 |
+
|
| 191 |
+
print(
|
| 192 |
+
f"[Job {slurm_task_id}/{slurm_array_size}] Processing {len(my_files)} files "
|
| 193 |
+
f"from index {start} to {end - 1}"
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
for bag_file in tqdm(my_files, total=len(my_files), desc=f"Job {slurm_task_id}"):
|
| 197 |
add_mate_annotations(bag_file)
|
| 198 |
|
| 199 |
+
print(f"[Job {slurm_task_id}] Completed {len(my_files)} files successfully.")
|
| 200 |
|
| 201 |
|
| 202 |
if __name__ == "__main__":
|