import gzip import json import random from tqdm.auto import tqdm from concurrent.futures import ProcessPoolExecutor MONTHS = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"] def determine_format(s): for format in ["Bullet", "Blitz", "Rapid", "Classical", "Correspondence"]: if format in s: return format else: return "" subsample_ratios = { 1700.0: 0.03773727310464546, 1800.0: 0.037873049537948796, 1600.0: 0.03882816595158128, 1900.0: 0.04081466062609689, 1500.0: 0.04225024822020829, 1400.0: 0.04841208365608056, 2000.0: 0.050853060082890485, 1300.0: 0.05542161997395184, 1200.0: 0.0683480281593876, 2100.0: 0.07245851749873197, 1100.0: 0.08971023593792052, 2200.0: 0.1211827435773146, 1000.0: 0.12567550584391102, 900.0: 0.22724690376093626, 2300.0: 0.24479804161566707, 800.0: 0.47438330170777987, 2400.0: 0.5417118093174431, 700.0: 1.0, 2500.0: 1.0, 600.0: 1.0, 2600.0: 1.0, 2700.0: 1.0, 2800.0: 1.0, 2900.0: 1.0 } def checks(game: dict) -> bool: format = determine_format(game["event"]) white_elo = int(game["white-elo"]) black_elo = int(game["black-elo"]) elo_diff = abs(white_elo - black_elo) elo_mean = (white_elo + black_elo) / 2 subsample_ratio = subsample_ratios.get( (elo_mean) // 100 * 100, 1.0 ) n_plys = len(game["moves-uci"].split()) return format in ("Blitz", "Rapid") and \ elo_diff <= 100 and \ random.random() < subsample_ratio and \ n_plys >= 4 def filter_month(month: str): train = gzip.open(f"/data/datasets/models/hf_cache/tmp-lichess/lichess-2022/br-subsample/train-2022-{month}.jsonl.gz", "wb") val = gzip.open(f"/data/datasets/models/hf_cache/tmp-lichess/lichess-2022/br-subsample/val-2022-{month}.jsonl.gz", "wb") test = gzip.open(f"/data/datasets/models/hf_cache/tmp-lichess/lichess-2022/br-subsample/test-2022-{month}.jsonl.gz", "wb") with gzip.open(f"/data/datasets/models/hf_cache/tmp-lichess/lichess-2022/all/2022-{month}.jsonl.gz", "rb") as f: for i, line in tqdm(enumerate(f), desc=month): d = json.loads(line) if checks(d): if random.random() < 1e-4: val.write((json.dumps(d) + '\n').encode()) elif random.random() < 2e-4: test.write((json.dumps(d) + '\n').encode()) else: train.write((json.dumps(d) + '\n').encode()) return 0 ppe = ProcessPoolExecutor(12) for _ in ppe.map(filter_month, MONTHS): ... ppe.shutdown() print("Done!")