File size: 33,341 Bytes
d5fd5b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
"""Build a weighted, shuffled, materialized token-shard "mix" from multiple
molecular sources, ready for streaming training. TORCH-FREE (numpy + pyarrow +
boto3 [+ huggingface_hub for remote parquet] only) so it runs on a CPU node in
a torch-free venv (e.g. `.venv-convert`).

Two source kinds:
  parquet  A HF-dataset-style parquet file with columns `sequence` (SELFIES str)
           and `tokenized_sequence` (list<int16>, [cls, ...ids, sep, pad, pad...]).
           `path` is either a local file or an HF repo-relative path like
           "datasets/<org>/<repo>/sub/dir/file.parquet" (opened via
           `huggingface_hub.HfFileSystem`). Read streaming via pyarrow
           `iter_batches` -- never materializes the whole file.
  bin      An existing .bin/.idx/.desc shard corpus (see `molvae.data.format`).
           `path` is a local directory of shards, or an `s3://bucket/prefix`
           (optionally capped to a random `max_shards` subset, downloaded via
           boto3 before reading, then deleted).

DISK-BACKED, two-phase pipeline -- scales to 1B+ molecules on a bounded-RAM node
by never holding a whole source (or the whole mix) as an in-memory array of
tokens/objects:

Phase A -- per-source SAMPLE-TO-DISK (streaming, O(1) RAM, no reservoir):
  For each source, get its available-mol count CHEAPLY (parquet:
  `metadata.num_rows`; bin: sum of the selected shards' `.idx` sizes, capped by
  `per_shard_cap`) and derive a keep-probability `p = target / available`.
  Stream every mol exactly once (parquet: `iter_batches`; bin:
  `ShardReader.tokens`, always COPIED -- an uncopied memmap view would pin that
  shard's mmap open for the rest of the run once it lands in a Phase-B bucket
  buffer), drop holdout matches, and fraction-sample it: keep with probability
  `p` when `p <= 1` (undersample), or emit `floor(p)` copies plus one more with
  probability `frac(p)` when `p > 1` (oversample). Kept mols are written
  straight to temp per-source shards under `<out>/_scratch/<name>/` via
  `ShardWriter`, rotated every `--shard-size` mols -- so a source's whole
  sample is never resident in RAM, only the one shard currently being
  buffered.

Phase B -- external SCATTER-SHUFFLE (single streaming pass, O(out-shards *
  shard-size) RAM): the per-source temp shards are source-contiguous (not
  mixed). One pass reads every mol from every temp shard and routes it to one
  of `--out-shards` open output `ShardWriter` buckets, chosen uniformly at
  random -- a `val_frac`-sized band of bucket ids is designated val, the rest
  train. Whenever a bucket's buffer reaches `--shard-size` mols it is
  (optionally within-shard shuffled, then) flushed to a numbered output shard,
  uploaded to S3 (if `--s3`), and replaced with a fresh buffer. Peak RAM is
  bounded by `out-shards * shard-size` mols -- a constant chosen by the
  operator, independent of the total mix size.

    python scripts/mix_dataset.py --config mix.json --out /data/mix \
        --dedup-holdout testdata/mechano_test.jsonl \
        --s3 s3://mechanophore/molvae/tokens/mix-v1

`--config` mix.json (format UNCHANGED):
    {"total": 40000000, "val_frac": 0.005, "seed": 0,
     "sources": [
       {"name": "zinc", "type": "bin", "path": "s3://.../zinc-tw2b-v2/train",
        "max_shards": 30, "weight": 0.40},
       {"name": "gdb4c3d", "type": "parquet",
        "path": "datasets/MechanophoresResearch/AutoencoderDataset/gdb/GDB4c3D.parquet",
        "weight": 0.35}
     ]}
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import re
import shutil
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from urllib.parse import urlparse

import numpy as np
import pyarrow.parquet as pq

from molvae.data.format import (
    OFFSET_DTYPE, TOKEN_DTYPE, Manifest, ShardReader, ShardStat, ShardWriter,
)

SELFIES_RE = re.compile(r"\[.*?\]")

# Every existing corpus in this repo (convert.py / convert_zinc.py) was built with
# the 12-name RDKit panel in molvae.descriptors.PROPERTY_NAMES -> that's the default
# width for reading a `bin`-type source's .desc file. Override per-source with a
# "n_desc" config key if a source was built with a different descriptor count.
DEFAULT_SOURCE_N_DESC = 12
# The mix itself never computes real descriptors (every mol gets a NaN row -- the
# VAE loss NaN-masks the property head and prop_w=0 in these runs anyway).
N_DESC_OUT = 12


# --------------------------------------------------------------------------- #
# tokenizer metadata -- read tokenizer.json directly (no molvae.tokenizer import,
# so this script's dependency graph stays stdlib + numpy + pyarrow + boto3 +
# huggingface_hub, never torch).
# --------------------------------------------------------------------------- #

def load_tokenizer_meta(path: str) -> Tuple[dict, dict, int, str]:
    raw = Path(path).read_bytes()
    sha = hashlib.sha256(raw).hexdigest()
    cfg = json.loads(raw)
    vocab = cfg["vocab"]
    sp = cfg["special_tokens"]
    special_ids = {
        "cls": vocab[sp["cls_token"]],
        "sep": vocab[sp["sep_token"]],
        "pad": vocab[sp["pad_token"]],
        "unk": vocab[sp["unk_token"]],
    }
    return vocab, special_ids, len(vocab), sha


def encode_selfies(s: str, vocab: dict, cls_id: int, sep_id: int, unk_id: int) -> np.ndarray:
    syms = SELFIES_RE.findall(s)
    ids = [cls_id] + [vocab.get(t, unk_id) for t in syms] + [sep_id]
    return np.asarray(ids, dtype=TOKEN_DTYPE)


# --------------------------------------------------------------------------- #
# holdout dedup set: exact token-sequence bytes, so equality is exact (no hash
# collisions possible -- the "hash" the caller cares about is just the dict key).
# --------------------------------------------------------------------------- #

def load_holdout(path: Optional[str], vocab: dict, special_ids: dict) -> set:
    if not path:
        return set()
    out = set()
    with open(path) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            obj = json.loads(line)
            arr = encode_selfies(obj["selfies"], vocab, special_ids["cls"],
                                  special_ids["sep"], special_ids["unk"])
            out.add(arr.tobytes())
    return out


# --------------------------------------------------------------------------- #
# S3 (lazy boto3 import; same endpoint-override convention as the rest of the repo)
# --------------------------------------------------------------------------- #

def s3_client():
    import boto3
    from botocore.config import Config
    endpoint = os.environ.get("AWS_ENDPOINT_URL_S3") or os.environ.get("AWS_ENDPOINT_URL")
    cfg = Config(retries={"max_attempts": 10, "mode": "adaptive"})
    return boto3.client("s3", endpoint_url=endpoint, config=cfg)


def upload_shard(stem: Path, s3_stem: str) -> None:
    s3 = s3_client()
    u = urlparse(s3_stem)
    for ext in (".bin", ".idx", ".desc"):        # .desc last -> its presence = complete
        for attempt in range(6):
            try:
                s3.upload_file(str(stem) + ext, u.netloc, u.path.lstrip("/") + ext)
                break
            except Exception:                     # noqa: BLE001
                if attempt == 5:
                    raise
                time.sleep(2 ** attempt)
    for ext in (".bin", ".idx", ".desc"):
        os.remove(str(stem) + ext)                 # free local disk once uploaded


def upload_manifest(out_dir: Path, s3_prefix: str) -> None:
    u = urlparse(f"{s3_prefix.rstrip('/')}/manifest.json")
    s3_client().upload_file(str(out_dir / "manifest.json"), u.netloc, u.path.lstrip("/"))


# --------------------------------------------------------------------------- #
# parquet source: HF-dataset-style {sequence, tokenized_sequence} rows
# --------------------------------------------------------------------------- #

def _open_parquet(path: str) -> pq.ParquetFile:
    if os.path.exists(path):
        return pq.ParquetFile(path, memory_map=True)
    # HF path "datasets/<org>/<repo>/<subpath>": DOWNLOAD the file (hf_hub_download ~50 MB/s,
    # cached so a repeat open is free) then mmap-read locally. fsspec streaming (HfFileSystem)
    # is ~15x slower here (~3.5 MB/s) -- fatal for gdb13's 9.5 GB / the 1B build.
    from huggingface_hub import hf_hub_download  # lazy: only for remote sources
    parts = path.split("/")
    assert parts[0] == "datasets" and len(parts) >= 4, f"bad HF parquet path: {path}"
    local = hf_hub_download(repo_id=f"{parts[1]}/{parts[2]}", filename="/".join(parts[3:]),
                            repo_type="dataset", local_dir="/tmp/hf_parquet_cache")
    return pq.ParquetFile(local, memory_map=True)


def _parquet_lenfilter_passrate(pf: pq.ParquetFile, pad_id: int, min_len: int,
                                 max_len: int, n_sample: int = 40000) -> float:
    """Fraction of a parquet's mols with token-len in [min_len,max_len] (trailing pad
    stripped), estimated from the first ~n_sample rows. Used to calibrate the keep-prob
    of a length-filtered parquet source to its POST-filter pool (else it undersamples;
    e.g. mcule is only ~23% >=55 tok). Assumes the file is not length-SORTED (mcule /
    eMolecules are id-ordered, verified)."""
    seen = passed = 0
    for batch in pf.iter_batches(batch_size=8192, columns=["tokenized_sequence"]):
        for row in batch.column(0).to_pylist():
            n = len(row)
            while n > 0 and row[n - 1] == pad_id:
                n -= 1
            seen += 1
            passed += (min_len <= n <= max_len)
        if seen >= n_sample:
            break
    return (passed / seen) if seen else 1.0


def sample_parquet_batch(col, pad_id, min_len, max_len, p, floor_p, frac_p, holdout, rng):
    """VECTORIZED per-batch sampler for a parquet `tokenized_sequence` column (the hot path:
    parquet sources are 10M-1B rows, so per-row Python is far too slow ~34k rows/s). Computes
    real token-lengths, the length filter, and the fraction-keep for the WHOLE batch with numpy,
    then materializes ONLY the kept rows (typically ~1%). Returns (kept_arrays, n_eligible,
    n_dropped). Holdout is checked only on kept rows -> no holdout mol is ever written (zero
    leakage); the dropped COUNT is thus a lower bound, which is fine (dedup correctness != count)."""
    la = col.combine_chunks() if hasattr(col, "combine_chunks") else col
    offs = la.offsets.to_numpy()
    vals = np.asarray(la.values.to_numpy(zero_copy_only=False), dtype=TOKEN_DTYPE)
    n = len(la)
    if n == 0:
        return [], 0, 0
    # real length = # non-pad tokens per row (pad only trails; pad_id never appears mid-sequence)
    real_len = np.add.reduceat((vals != pad_id).astype(np.int64), offs[:-1])
    mask = (real_len >= min_len) & (real_len <= max_len)
    n_eligible = int(mask.sum())
    if p <= 1.0:
        copies = np.where(mask & (rng.random(n) < p), 1, 0)
    else:
        copies = np.where(mask, floor_p + (rng.random(n) < frac_p).astype(np.int64), 0)
    kept_arrays: List[np.ndarray] = []
    n_dropped = 0
    for i in np.flatnonzero(copies > 0):
        arr = vals[offs[i]:offs[i] + real_len[i]]   # [cls..sep], trailing pad stripped by real_len
        if holdout and arr.tobytes() in holdout:
            n_dropped += 1
            continue
        c = int(copies[i])
        kept_arrays.extend([arr] * c)
    return kept_arrays, n_eligible, n_dropped


def iter_parquet_mols(pf: pq.ParquetFile, pad_id: int, batch_size: int = 8192):
    """Stream `tokenized_sequence` rows off an ALREADY-OPEN ParquetFile (so callers
    can cheaply read `pf.metadata.num_rows` first), trailing-pad stripped to
    [cls, ...ids, sep]."""
    for batch in pf.iter_batches(batch_size=batch_size, columns=["tokenized_sequence"]):
        for row in batch.column(0).to_pylist():
            arr = np.asarray(row, dtype=TOKEN_DTYPE)
            keep = np.flatnonzero(arr != pad_id)
            if keep.size == 0:
                continue
            yield arr[:keep[-1] + 1]


# --------------------------------------------------------------------------- #
# bin/idx shard source: local dir of shards, or s3://prefix (+ optional
# max_shards random subset, downloaded locally then deleted after reading)
# --------------------------------------------------------------------------- #

def _list_local_stems(path: str) -> List[Tuple[str, int]]:
    return sorted(((str(p)[:-4], p.stat().st_size) for p in Path(path).glob("*.bin")),
                  key=lambda x: x[0])


def _list_s3_stems(s3_prefix: str) -> Tuple[str, List[Tuple[str, int]]]:
    """Return (bucket, [(stem, bin_size_bytes), ...]) for every shard under the prefix."""
    u = urlparse(s3_prefix)
    bucket, prefix = u.netloc, u.path.lstrip("/")
    s3 = s3_client()
    stems: List[Tuple[str, int]] = []
    tok = None
    while True:
        kw = {"Bucket": bucket, "Prefix": prefix}
        if tok:
            kw["ContinuationToken"] = tok
        r = s3.list_objects_v2(**kw)
        stems += [(o["Key"][:-4], o["Size"]) for o in r.get("Contents", [])
                  if o["Key"].endswith(".bin")]
        if r.get("IsTruncated"):
            tok = r["NextContinuationToken"]
        else:
            break
    return bucket, sorted(stems, key=lambda x: x[0])


# rough bytes-per-molecule in a .bin (uint16 tokens, ~45 tok/mol) — for shard-count estimation
_BYTES_PER_MOL = 95


def _select_bin_stems(stems_sz: List[Tuple[str, int]], target: int, spec: dict, rng
                      ) -> Tuple[List[str], Optional[int]]:
    """Pick shards from a size-SKEWED corpus (heavy-atom-bucketed: most shards tiny, a few huge).
    Returns (stems_to_download, per_shard_cap). Two strategies:

    - 'largest' (default): biggest shards first until the target is covered. Fast, but for a
      heavy-atom-bucketed corpus this is the abundant DRUG-SIZE band only — it misses the large
      molecules, which live in the SMALL shards (rare per band).
    - 'stratified': span the full size range for a VARIED molecule-size distribution. Split shards
      into `tiers` equal-count groups by size, allocate the target EVENLY across tiers, and within
      each tier take (shuffled) shards up to a per-shard cap. This undersamples the abundant
      drug-size band and pulls in the small shards that hold the large (and tiny) molecules."""
    min_mb = float(spec.get("min_shard_mb", 0.0))
    qual = [(s, sz) for s, sz in stems_sz if sz >= min_mb * 1e6] or list(stems_sz)
    cap = spec.get("per_shard_cap")
    if spec.get("strategy", "largest") == "stratified":
        tiers = int(spec.get("tiers", 8))
        spt = int(spec.get("shards_per_tier", 15))     # BOUNDED: <= tiers*spt shards total
        cap = cap or 400_000                           # per-shard cap (undersamples huge drug-size shards)
        qual.sort(key=lambda x: x[1])                  # ascending size
        picked: List[str] = []
        for t in range(tiers):                         # contiguous equal-count size groups
            grp = qual[t * len(qual) // tiers:(t + 1) * len(qual) // tiers]
            if not grp:
                continue
            order = rng.permutation(len(grp))[:spt]    # up to `spt` RANDOM shards per size tier
            picked += [grp[int(gi)][0] for gi in order]
        return picked, cap
    qual.sort(key=lambda x: -x[1])                      # largest first
    picked, est = [], 0.0
    for s, sz in qual:
        picked.append(s)
        est += sz / _BYTES_PER_MOL
        if spec.get("max_shards") and len(picked) >= int(spec["max_shards"]):
            break
        if est >= target * 1.3:
            break
    return picked, cap


def _download_stems(bucket: str, stems: List[str], dest: Path, workers: int) -> List[Path]:
    dest.mkdir(parents=True, exist_ok=True)
    s3 = s3_client()

    def fetch(stem: str) -> Path:
        local_stem = dest / Path(stem).name
        for ext in (".bin", ".idx", ".desc"):
            s3.download_file(bucket, stem + ext, str(local_stem) + ext)
        return local_stem

    out: List[Path] = []
    with ThreadPoolExecutor(max_workers=max(1, workers)) as ex:
        for p in ex.map(fetch, stems):
            out.append(p)
    return out


def iter_bin_mols(stems: List[Path], n_desc: int, cap: Optional[int] = None, rng=None):
    """Yield mols from each shard; if `cap` is set, yield at most `cap` RANDOM mols per shard
    (so a huge drug-size shard doesn't dominate a stratified sample)."""
    for stem in stems:
        r = ShardReader(stem, n_desc)
        n = len(r)
        idxs = rng.choice(n, size=cap, replace=False) if (cap and n > cap) else range(n)
        for i in idxs:
            yield np.array(r.tokens(int(i)))           # COPY: don't retain a memmap view (fd leak)
        del r                                          # release the shard's .bin/.idx/.desc memmaps


# --------------------------------------------------------------------------- #
# Phase A: per-source SAMPLE-TO-DISK (streaming, O(1) RAM -- no reservoir).
# --------------------------------------------------------------------------- #

def _shard_n_mol(stem: Path) -> int:
    """Mol count of a LOCAL shard from its `.idx` file size alone -- no data read."""
    itemsize = np.dtype(OFFSET_DTYPE).itemsize
    return os.path.getsize(f"{stem}.idx") // itemsize - 1


def _shard_n_mol_inrange(stem: Path, min_len: int, max_len: int) -> Tuple[int, int]:
    """(total, in_range) mol counts for a LOCAL shard: reads only the small .idx and
    derives per-mol token lengths (diff of offsets). Used to length-calibrate the
    keep-probability when a source has a min_len/max_len filter (e.g. long-ZINC)."""
    idx = np.fromfile(f"{stem}.idx", dtype=OFFSET_DTYPE)
    lens = np.diff(idx)
    return int(lens.size), int(((lens >= min_len) & (lens <= max_len)).sum())


def sample_source_to_disk(idx: int, spec: dict, target: int, seed: int, pad_id: int,
                           holdout: set, out_dir: Path, workers: int, shard_size: int
                           ) -> Tuple[dict, List[Path]]:
    """Phase A for one source: stream its mols once, drop holdout matches, and
    fraction-sample to ~`target` (keep-probability `p = target/available` when
    undersampling, replicate `floor(p)`(+1) copies when oversampling) -- writing
    kept mols DIRECTLY to temp per-source shards under `out_dir/_scratch/<name>/`
    via `ShardWriter`. Never buffers more than one output shard's worth of mols in
    RAM. Returns (report dict, [temp shard stems written])."""
    name = spec["name"]
    kind = spec["type"]
    min_len = int(spec.get("min_len", 0))         # keep only mols with min_len <= tok_len <= max_len
    max_len = int(spec.get("max_len", 1 << 30))   # (tok_len incl cls+sep); e.g. min_len 55 -> long ZINC
    rng = np.random.default_rng([seed, idx, 1])   # independent per-source stream
    report = {"name": name, "type": kind, "target": int(target), "available": 0,
              "kept": 0, "oversample": 0, "holdout_dropped": 0}
    if target <= 0:
        return report, []

    dl_scratch: Optional[Path] = None
    parquet_pf = None
    gen = None
    if kind == "parquet":
        pf = _open_parquet(spec["path"])
        available = int(pf.metadata.num_rows)
        if min_len > 0 or max_len < (1 << 30):       # calibrate keep-prob to the post-filter pool
            rate = _parquet_lenfilter_passrate(pf, pad_id, min_len, max_len)
            available = int(available * rate)
            pf = _open_parquet(spec["path"])          # fresh handle for the streaming pass
        parquet_pf = pf                               # streamed batch-vectorized below
    elif kind == "bin":
        path = spec["path"]
        n_desc = int(spec.get("n_desc", DEFAULT_SOURCE_N_DESC))
        if path.startswith("s3://"):
            bucket, stems_sz = _list_s3_stems(path)
            picked, cap = _select_bin_stems(stems_sz, target, spec, rng)
            dl_scratch = out_dir / "_scratch" / f"{name}__dl"
            local_stems = _download_stems(bucket, picked, dl_scratch, workers)
        else:
            picked, cap = _select_bin_stems(_list_local_stems(path), target, spec, rng)
            local_stems = [Path(s) for s in picked]
        # available mols is CAP-AWARE (iter_bin_mols streams at most `cap` random mols per
        # shard) AND length-filter-AWARE (only mols in [min_len,max_len] survive the stream
        # filter) -- keep-probability must be computed against the pool the loop actually sees.
        if min_len > 0 or max_len < (1 << 30):
            available = 0
            for s in local_stems:
                n, n_in = _shard_n_mol_inrange(s, min_len, max_len)
                available += int(round(cap * n_in / n)) if (cap and n > cap and n) else n_in
        else:
            available = int(sum((min(_shard_n_mol(s), cap) if cap else _shard_n_mol(s))
                                 for s in local_stems))
        gen = iter_bin_mols(local_stems, n_desc, cap=cap, rng=rng)
    else:
        raise ValueError(f"unknown source type {kind!r} for {name!r}")

    p = target / available if available > 0 else 0.0
    floor_p = int(p)                              # p >= 0, so int(p) == floor(p)
    frac_p = p - floor_p

    scratch_dir = out_dir / "_scratch" / name
    nan_row = np.full(N_DESC_OUT, np.nan, dtype=np.float16)
    temp_stems: List[Path] = []
    part_i = 0
    writer = ShardWriter(scratch_dir / f"part-{part_i:05d}", N_DESC_OUT)
    n_eligible = 0
    n_dropped = 0
    kept = 0

    def _roll() -> None:
        nonlocal writer, part_i
        st = writer.flush()
        temp_stems.append(scratch_dir / st.name)
        part_i += 1
        writer = ShardWriter(scratch_dir / f"part-{part_i:05d}", N_DESC_OUT)

    def _write(arr: np.ndarray) -> None:
        nonlocal kept
        writer.add(arr, nan_row)
        kept += 1
        if len(writer) >= shard_size:
            _roll()

    if parquet_pf is not None:                         # VECTORIZED parquet hot path (per batch)
        for batch in parquet_pf.iter_batches(batch_size=16384, columns=["tokenized_sequence"]):
            kept_arrays, ne, nd = sample_parquet_batch(
                batch.column(0), pad_id, min_len, max_len, p, floor_p, frac_p, holdout, rng)
            n_eligible += ne
            n_dropped += nd
            for arr in kept_arrays:
                _write(arr)
    else:                                              # bin source: per-mol (smaller scale)
        for arr in gen:
            arr = np.asarray(arr, dtype=TOKEN_DTYPE)
            if arr.size < min_len or arr.size > max_len:
                continue
            if holdout and arr.tobytes() in holdout:
                n_dropped += 1
                continue
            n_eligible += 1
            copies = (1 if rng.random() < p else 0) if p <= 1.0 else (
                floor_p + (1 if rng.random() < frac_p else 0))
            for _ in range(copies):
                _write(arr)

    if len(writer):
        _roll()

    if dl_scratch is not None:
        shutil.rmtree(dl_scratch, ignore_errors=True)

    report.update(available=available, kept=kept,
                   oversample=max(0, kept - n_eligible), holdout_dropped=n_dropped)
    return report, temp_stems


# --------------------------------------------------------------------------- #
# Phase B: external SCATTER-SHUFFLE (single streaming pass, O(out_shards *
# shard_size) RAM) -- routes every mol from every per-source temp shard to a
# uniform-random output bucket, giving a global shuffle without ever sorting or
# holding the whole mix in memory.
# --------------------------------------------------------------------------- #

def scatter_shuffle_to_shards(temp_stems: List[Path], out_dir: Path, man: Manifest,
                               n_out: int, val_frac: float, shard_size: int, seed: int,
                               n_desc: int, s3_prefix: Optional[str]
                               ) -> Tuple[Dict[str, Tuple[int, int, int]], int]:
    """Read every mol out of every (source-contiguous) temp shard exactly once, in
    arbitrary order, and route it to one of `n_out` open output-shard buckets chosen
    uniformly at random -- bucket ids `[0, n_val)` are `val`, the rest `train`. A
    bucket is flushed (and its writer replaced) as soon as it reaches `shard_size`
    mols. Mutates `man` in place (one `ShardStat` per flushed shard). Returns
    ({"val"|"train": (n_mol, n_tokens, n_shards)}, max_mol_len_seen)."""
    rng = np.random.default_rng([seed, 0x5CA77E12])   # distinct from per-source streams
    n_out = max(1, n_out)
    n_val = min(n_out, (max(1, round(val_frac * n_out)) if val_frac > 0 else 0))

    def _fresh() -> ShardWriter:
        return ShardWriter(out_dir / "_pending", n_desc)   # stem overwritten before flush

    writers: List[ShardWriter] = [_fresh() for _ in range(n_out)]
    shard_ct = {"val": 0, "train": 0}
    n_mol_tot = {"val": 0, "train": 0}
    n_tok_tot = {"val": 0, "train": 0}
    n_shard_tot = {"val": 0, "train": 0}
    max_len = 0

    def _flush(b: int) -> None:
        w = writers[b]
        if len(w) == 0:
            return
        split = "val" if b < n_val else "train"
        w.shuffle(rng)                        # cheap extra within-shard mixing
        i = shard_ct[split]
        shard_ct[split] += 1
        w.stem = out_dir / split / f"shard-{i:05d}"
        st = w.flush()
        st.split = split
        man.add(st)
        n_mol_tot[split] += st.n_mol
        n_tok_tot[split] += st.n_tokens
        n_shard_tot[split] += 1
        if s3_prefix:
            upload_shard(w.stem, f"{s3_prefix.rstrip('/')}/{split}/{st.name}")
        writers[b] = _fresh()

    # Temp shards arrive GROUPED by source (Phase A appends one source's shards at a
    # time). If they were read in that order, a bucket's buffer would accumulate
    # source A, then source B, ... in TIME order, and its LAST flush (esp. the final
    # trailing flush after the whole pass) would end up dominated by whichever source
    # was streamed last -- source-contiguous, defeating the shuffle. Visiting temp
    # shards in a random order instead means every point in the pass draws from a mix
    # of sources, so every flush (including the tail) interleaves them. Cheap: just a
    # permutation over the (small) shard-COUNT, not the mols.
    order = rng.permutation(len(temp_stems))
    for k in order:
        stem = temp_stems[int(k)]
        r = ShardReader(stem, n_desc)
        n = len(r)
        if n:
            buckets = rng.integers(0, n_out, size=n)
            for i in range(n):
                ids = np.array(r.tokens(i))   # COPY -- an uncopied memmap view would pin
                desc = np.array(r.desc(i))    # this temp shard's mmap open indefinitely
                if ids.size > max_len:
                    max_len = int(ids.size)
                b = int(buckets[i])
                writers[b].add(ids, desc)
                if len(writers[b]) >= shard_size:
                    _flush(b)
        del r

    for b in range(n_out):
        _flush(b)

    totals = {"val": (n_mol_tot["val"], n_tok_tot["val"], n_shard_tot["val"]),
              "train": (n_mol_tot["train"], n_tok_tot["train"], n_shard_tot["train"])}
    return totals, max_len


# --------------------------------------------------------------------------- #
# main
# --------------------------------------------------------------------------- #

def _normalized_targets(sources_cfg: List[dict], total: int) -> List[int]:
    """Largest-remainder rounding so per-source targets sum to exactly `total`."""
    weights = np.array([float(s["weight"]) for s in sources_cfg], dtype=np.float64)
    if weights.sum() <= 0:
        raise SystemExit("sum of source weights must be > 0")
    weights = weights / weights.sum()
    raw = weights * total
    targets = np.floor(raw).astype(np.int64)
    remainder = int(total - targets.sum())
    if remainder > 0:
        order = np.argsort(-(raw - targets))
        for i in order[:remainder]:
            targets[i] += 1
    return targets.tolist()


def main(argv: Optional[List[str]] = None) -> None:
    ap = argparse.ArgumentParser(description=__doc__,
                                  formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--config", required=True, help="mix spec: JSON file path or inline JSON string")
    ap.add_argument("--out", required=True, help="local output dir (train/, val/, manifest.json)")
    ap.add_argument("--s3", default=None, help="optional s3://bucket/prefix to upload shards to")
    ap.add_argument("--dedup-holdout", default=None,
                     help="jsonl with a 'selfies' field per line; exact token-seq matches are dropped")
    ap.add_argument("--shard-size", type=int, default=200_000,
                     help="mols per shard -- both Phase-A temp per-source shards and "
                          "Phase-B final output shards")
    ap.add_argument("--out-shards", type=int, default=1024,
                     help="Phase-B scatter-shuffle output-bucket count; peak RAM is "
                          "~= out-shards * shard-size mols, independent of total mix size")
    ap.add_argument("--workers", type=int, default=8, help="parallel S3 shard downloads")
    ap.add_argument("--tokenizer", default="tokenizer.json")
    ap.add_argument("--seed", type=int, default=None, help="override the config's seed")
    a = ap.parse_args(argv)

    cfg_path = Path(a.config)
    cfg = json.loads(cfg_path.read_text()) if cfg_path.exists() else json.loads(a.config)

    total = int(cfg["total"])
    val_frac = float(cfg.get("val_frac", 0.005))
    seed = int(a.seed if a.seed is not None else cfg.get("seed", 0))
    sources_cfg = cfg["sources"]

    vocab, special_ids, vocab_size, tok_sha = load_tokenizer_meta(a.tokenizer)
    pad_id = special_ids["pad"]

    holdout = load_holdout(a.dedup_holdout, vocab, special_ids)
    if a.dedup_holdout:
        print(f"holdout: {len(holdout)} unique token-sequences loaded from {a.dedup_holdout}")

    targets = _normalized_targets(sources_cfg, total)

    out_dir = Path(a.out)
    out_dir.mkdir(parents=True, exist_ok=True)

    print("=== Phase A: per-source sample-to-disk ===")
    reports: List[dict] = []
    all_temp_stems: List[Path] = []
    for i, (spec, target) in enumerate(zip(sources_cfg, targets)):
        print(f"[{i + 1}/{len(sources_cfg)}] sampling {spec['name']!r} (target {target:,}) ...")
        rep, temp_stems = sample_source_to_disk(i, spec, target, seed, pad_id, holdout,
                                                 out_dir, a.workers, a.shard_size)
        reports.append(rep)
        all_temp_stems += temp_stems
        avail_s = f"{rep['available']:,}"
        osf = f"{rep['target'] / rep['available']:.2f}x" if rep["available"] else "n/a"
        print(f"    target={rep['target']:,} available={avail_s} kept={rep['kept']:,} "
              f"oversample_factor={osf} holdout_dropped={rep['holdout_dropped']:,}")

    total_actual = sum(r["kept"] for r in reports)
    if total_actual == 0:
        raise SystemExit("no molecules collected from any source -- aborting")

    man = Manifest(
        tokenizer_sha256=tok_sha, vocab_size=vocab_size, vocab=vocab,
        special_ids=special_ids, max_len=256,
        descriptor_names=[f"desc{i}" for i in range(N_DESC_OUT)],
    )

    print(f"\n=== Phase B: scatter-shuffling {total_actual:,} mols into "
          f"{a.out_shards} output buckets ===")
    split_totals, max_len_val = scatter_shuffle_to_shards(
        all_temp_stems, out_dir, man, a.out_shards, val_frac, a.shard_size, seed,
        N_DESC_OUT, a.s3)
    man.max_len = max_len_val or 256
    for split_name in ("val", "train"):
        if split_totals[split_name][0] == 0:
            print(f"WARNING: {split_name} split is empty")

    man.stats = {
        "n_mol": man.n_mol,
        "desc_mean": [0.0] * N_DESC_OUT,             # NaN rows -> (NaN-0)/1 stays NaN
        "desc_std": [1.0] * N_DESC_OUT,
        "desc_count": [0] * N_DESC_OUT,
        "seed": seed,
        "val_frac": val_frac,
        "mix_total_requested": total,
        "mix_total_actual": total_actual,
        "mix_sources": reports,
        "holdout_path": a.dedup_holdout,
        "holdout_dropped_total": sum(r["holdout_dropped"] for r in reports),
    }
    man.save(out_dir)
    if a.s3:
        upload_manifest(out_dir, a.s3)

    scratch_root = out_dir / "_scratch"
    if scratch_root.exists():
        shutil.rmtree(scratch_root, ignore_errors=True)

    print("\n=== mix summary ===")
    for r in reports:
        avail_s = f"{r['available']:,}"
        print(f"  {r['name']:<16} type={r['type']:<8} target={r['target']:>10,} "
              f"available={avail_s:>12} kept={r['kept']:>10,} "
              f"oversample={r['oversample']:>8,} holdout_dropped={r['holdout_dropped']:>6,}")
    for split_name in ("train", "val"):
        n, n_tok, n_shards = split_totals[split_name]
        print(f"  {split_name}: {n:,} mols, {n_tok:,} tokens, {n_shards} shards")
    print(f"  total: {total_actual:,} mols (requested {total:,})")
    print(f"  output: {a.s3 if a.s3 else str(out_dir)}")


if __name__ == "__main__":
    main()