docs: top-level README + mixes/ (catalog, per-mix configs, mix_dataset.py builder)
Browse files- README.md +40 -71
- mixes/README.md +54 -0
- mixes/mix-phase1-40M.config.json +7 -0
- mixes/mix-v2-1B.config.json +62 -0
- mixes/mix-v2-40M.config.json +66 -0
- mixes/mix_dataset.py +712 -0
README.md
CHANGED
|
@@ -1,71 +1,40 @@
|
|
| 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 |
-
- `-v, --verbose`: Optional. Increase output verbosity
|
| 42 |
-
- `-b BATCH_SIZE, --batch-size BATCH_SIZE`: Optional. Batch size for processing (default: 10000)
|
| 43 |
-
|
| 44 |
-
### Running with find and xargs for parallel processing
|
| 45 |
-
|
| 46 |
-
To convert all .smi files in parallel:
|
| 47 |
-
|
| 48 |
-
```bash
|
| 49 |
-
find . -name "*.smi" | xargs -I {} -P$(nproc) sh -c 'python selfies_converter.py {}'
|
| 50 |
-
```
|
| 51 |
-
|
| 52 |
-
To convert files and remove the original .smi files after successful conversion:
|
| 53 |
-
|
| 54 |
-
```bash
|
| 55 |
-
find . -name "*.smi" | xargs -I {} -P$(nproc) sh -c 'python selfies_converter.py {} && rm {}'
|
| 56 |
-
```
|
| 57 |
-
|
| 58 |
-
Note: Be cautious when using the command that removes original files. Ensure you have backups before running it.
|
| 59 |
-
|
| 60 |
-
With gz:
|
| 61 |
-
```bash
|
| 62 |
-
find . -name "*.smi.gz" | xargs -P$(nproc) -I {} sh -c 'f="{}"; g="${f%.gz}"; gzip -dc "$f" > "$g" && python selfies_converter.py "$g" && rm "$g" && rm "$f"'
|
| 63 |
-
```
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
## Output
|
| 67 |
-
|
| 68 |
-
Both scripts will create output files in the same directory as the input files:
|
| 69 |
-
|
| 70 |
-
- The file splitter creates `<original_name>.part01.smi`, `<original_name>.part02.smi`, etc.
|
| 71 |
-
- The SELFIES converter creates `<original_name>.selfies` for the converted file and `<original_name>.alph` for the alphabet file.
|
|
|
|
| 1 |
+
# AutoencoderDataset
|
| 2 |
+
|
| 3 |
+
Data for training **molvae** — a SELFIES molecular VAE (matryoshka latent) for Bayesian
|
| 4 |
+
optimization of mechanophores. Two layers:
|
| 5 |
+
|
| 6 |
+
- **`raw/`** — the source chemical databases (SMILES/SELFIES, pre-tokenized), as collected.
|
| 7 |
+
- **`mixes/`** — the *derived* training datasets: weighted, shuffled, materialized token-shard
|
| 8 |
+
"mixes" built from the raw sources. Each mix is documented by its **config + README + build
|
| 9 |
+
code**, so it is fully reproducible. The multi-GB token shards themselves live on **S3**
|
| 10 |
+
(`s3://mechanophore/molvae/tokens/<name>/`) — the training home — and are mirrored here.
|
| 11 |
+
|
| 12 |
+
Everything shares one tokenizer (`raw/tokenizer.json`, vocab 1458; cls=1, sep=2, pad=3).
|
| 13 |
+
|
| 14 |
+
## Raw sources (`raw/`)
|
| 15 |
+
Uniform schema per parquet: `sequence` (SELFIES string) + `tokenized_sequence` (int16,
|
| 16 |
+
`[cls, …ids, sep, pad…]`). Highlights:
|
| 17 |
+
|
| 18 |
+
| source | rows | notes |
|
| 19 |
+
|--------|-----:|-------|
|
| 20 |
+
| `gdb/gdb13` | 977M | exhaustive ≤13-heavy-atom enumeration — dense strained/spiro/bridged rings |
|
| 21 |
+
| `gdb/GDB-13s`, `gdb/gdb11`, `gdb/GDB4c3D`, `gdb/GDBMedChem`, `gdb/GDB17…` | 6.6M–99M | GDB variants (strained/ring-rich, small) |
|
| 22 |
+
| `mcule_full/…` | 42M | purchasable; **long molecules** (median 46, to 154 tok) |
|
| 23 |
+
| `emolecules/ordersc/…` | 36M | purchasable; **long + diverse** (to 168 tok) |
|
| 24 |
+
| `Kaggle/chembl_22_clean…` | 1.6M | drug-like (short) |
|
| 25 |
+
| `zinc22-2d-all/…` | ~1.9B | ZINC22 SELFIES by heavy-atom band H04–H49 (source of the `zinc-tw2b-v2` corpus) |
|
| 26 |
+
|
| 27 |
+
## Mixes (`mixes/`)
|
| 28 |
+
See [`mixes/README.md`](mixes/README.md) for the catalog, composition tables, and the exact
|
| 29 |
+
rebuild command. Builder: [`mixes/mix_dataset.py`](mixes/mix_dataset.py) (from the molvae repo).
|
| 30 |
+
|
| 31 |
+
| mix | mols | on S3 | what |
|
| 32 |
+
|-----|-----:|-------|------|
|
| 33 |
+
| `zinc-tw2b-v2` | 1.855B | `…/tokens/zinc-tw2b-v2` | the ZINC-only base corpus (H04–H49) |
|
| 34 |
+
| `mix-phase1-40M` | 40M | `…/tokens/mix-phase1-40M` | v1 pilot: ZINC-heavy (40%) + GDB4c3D/GDBMedChem/ChEMBL |
|
| 35 |
+
| `mix-v2-40M` | 40M | `…/tokens/mix-v2-40M` | v2 pilot: strained-heavy (GDB) + **long** (mcule/eMol) |
|
| 36 |
+
| `mix-v2-1B` | 1B | `…/tokens/mix-v2-1B` | v2 full: the strained-rich pretrain mix |
|
| 37 |
+
|
| 38 |
+
## Held-out
|
| 39 |
+
The ~132 real mechanophores are a **held-out reconstruction test set** (not in any training mix;
|
| 40 |
+
every build dedups against them). They live on S3 (`…/eval/mechano_test.jsonl`), not here.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
mixes/README.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Training mixes
|
| 2 |
+
|
| 3 |
+
Each mix is a weighted, shuffled, materialized set of token shards (`.bin`/`.idx`/`.desc` +
|
| 4 |
+
`manifest.json`, per `molvae.data.format`), built from `../raw/` by [`mix_dataset.py`](mix_dataset.py).
|
| 5 |
+
The shards live on **S3** (`s3://mechanophore/molvae/tokens/<name>/`) and are mirrored under each
|
| 6 |
+
mix's `data/`. The `*.config.json` here is the exact, re-runnable spec.
|
| 7 |
+
|
| 8 |
+
## Builder
|
| 9 |
+
`mix_dataset.py` is torch-free (numpy + pyarrow + boto3 + huggingface_hub). Disk-backed & bounded-RAM:
|
| 10 |
+
**Phase A** streams each source once and fraction-samples it to disk (vectorized per parquet batch —
|
| 11 |
+
~7M rows/s; parquets are downloaded, not fsspec-streamed); **Phase B** external scatter-shuffles the
|
| 12 |
+
per-source temp shards into `--out-shards` output buckets. Per-source knobs: `weight`, `min_len`/`max_len`
|
| 13 |
+
(length filter, e.g. long-molecule streams — keep-prob is calibrated to the post-filter pool), and for
|
| 14 |
+
`bin` sources a size-`stratified` shard selection with `per_shard_cap` (or default largest-first).
|
| 15 |
+
Every build **dedups against the held-out mechanophore test set** (`--dedup-holdout`).
|
| 16 |
+
|
| 17 |
+
```bash
|
| 18 |
+
# rebuild a mix (on the CPU node; source S3 creds first)
|
| 19 |
+
python mix_dataset.py --config mix-v2-1B.config.json \
|
| 20 |
+
--dedup-holdout mechano_test.jsonl --out /tmp/mix \
|
| 21 |
+
--s3 s3://mechanophore/molvae/tokens/mix-v2-1B --out-shards 512 --shard-size 100000
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
## Design principle
|
| 25 |
+
Sample by **weights, not raw counts** — the mechanophore target is a *strained core at ~27 heavy
|
| 26 |
+
atoms with esters/nitriles*, which no single source spans. GDB gives strained ring grammar (but
|
| 27 |
+
small); mcule/eMolecules give the long molecules (but drug-like); ZINC gives a medium size anchor.
|
| 28 |
+
The mix's job is to span the composition. (Long+strained *together* still needs Phase-2 sources —
|
| 29 |
+
COCONUT / SAVI — not yet added.)
|
| 30 |
+
|
| 31 |
+
## `mix-v2-1B` — the strained-rich pretrain mix (current)
|
| 32 |
+
~60% GDB (strain) · ~40% size/length · ~9–13% of mols ≥55 tokens (long-decode).
|
| 33 |
+
|
| 34 |
+
| weight | source | role |
|
| 35 |
+
|------:|--------|------|
|
| 36 |
+
| 35% | gdb13 | strain-volume workhorse (≤13 HA rings) |
|
| 37 |
+
| 8% | GDB4c3D | curated strained |
|
| 38 |
+
| 8% | GDB-13s | ring diversity |
|
| 39 |
+
| 4% | gdb11 | small exhaustive |
|
| 40 |
+
| 5% | GDBMedChem | drug-like ring |
|
| 41 |
+
| 12% | ZINC (largest-first) | medium size anchor |
|
| 42 |
+
| 10% | mcule | long-ish (median 46) |
|
| 43 |
+
| 5% | mcule-long (`min_len 55`) | long-decode leg (all ≥55, to 154 tok) |
|
| 44 |
+
| 13% | eMolecules ordersc | long + diverse (to 168 tok) |
|
| 45 |
+
|
| 46 |
+
`mix-v2-40M` is the same composition at 40M (pilot). `mix-phase1-40M` is the earlier v1
|
| 47 |
+
(ZINC 40% / GDB4c3D 35% / GDBMedChem 15% / ChEMBL 10%). See each `*.config.json` for exact specs.
|
| 48 |
+
|
| 49 |
+
## Loading (training side, needs torch)
|
| 50 |
+
```python
|
| 51 |
+
from molvae.data import MolvaeDataset, make_loader
|
| 52 |
+
ds = MolvaeDataset("<local>/mix-v2-1B", "train") # mmap token shards
|
| 53 |
+
loader = make_loader(ds, pad_id=3, token_budget=12288)
|
| 54 |
+
```
|
mixes/mix-phase1-40M.config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"total": 40000000, "val_frac": 0.005, "seed": 0,
|
| 2 |
+
"sources": [
|
| 3 |
+
{"name":"zinc","type":"bin","path":"s3://mechanophore/molvae/tokens/zinc-tw2b-v2/train","weight":0.40,"strategy":"stratified","tiers":8,"shards_per_tier":20,"per_shard_cap":400000},
|
| 4 |
+
{"name":"gdb4c3d","type":"parquet","path":"datasets/MechanophoresResearch/AutoencoderDataset/gdb/GDB4c3D.parquet","weight":0.35},
|
| 5 |
+
{"name":"gdbmedchem","type":"parquet","path":"datasets/MechanophoresResearch/AutoencoderDataset/gdb/GDBMedChem.parquet","weight":0.15},
|
| 6 |
+
{"name":"chembl","type":"parquet","path":"datasets/MechanophoresResearch/AutoencoderDataset/Kaggle/chembl_22_clean_1576904_sorted_std_final.parquet","weight":0.10}
|
| 7 |
+
]}
|
mixes/mix-v2-1B.config.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"total": 1000000000,
|
| 3 |
+
"val_frac": 0.001,
|
| 4 |
+
"seed": 0,
|
| 5 |
+
"sources": [
|
| 6 |
+
{
|
| 7 |
+
"name": "gdb13",
|
| 8 |
+
"type": "parquet",
|
| 9 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/gdb/gdb13.parquet",
|
| 10 |
+
"weight": 0.35
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"name": "gdb4c3d",
|
| 14 |
+
"type": "parquet",
|
| 15 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/gdb/GDB4c3D.parquet",
|
| 16 |
+
"weight": 0.08
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"name": "gdb13s",
|
| 20 |
+
"type": "parquet",
|
| 21 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/gdb/GDB-13s.parquet",
|
| 22 |
+
"weight": 0.08
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"name": "gdb11",
|
| 26 |
+
"type": "parquet",
|
| 27 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/gdb/gdb11.parquet",
|
| 28 |
+
"weight": 0.04
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"name": "gdbmedchem",
|
| 32 |
+
"type": "parquet",
|
| 33 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/gdb/GDBMedChem.parquet",
|
| 34 |
+
"weight": 0.05
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"name": "zinc",
|
| 38 |
+
"type": "bin",
|
| 39 |
+
"path": "s3://mechanophore/molvae/tokens/zinc-tw2b-v2/train",
|
| 40 |
+
"weight": 0.12
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"name": "mcule",
|
| 44 |
+
"type": "parquet",
|
| 45 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/mcule_full/mcule_purchasable_full_240823.parquet",
|
| 46 |
+
"weight": 0.1
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"name": "mcule_long",
|
| 50 |
+
"type": "parquet",
|
| 51 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/mcule_full/mcule_purchasable_full_240823.parquet",
|
| 52 |
+
"weight": 0.05,
|
| 53 |
+
"min_len": 55
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"name": "emol",
|
| 57 |
+
"type": "parquet",
|
| 58 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/emolecules/ordersc/2024-10-01/parent.parquet",
|
| 59 |
+
"weight": 0.13
|
| 60 |
+
}
|
| 61 |
+
]
|
| 62 |
+
}
|
mixes/mix-v2-40M.config.json
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"total": 40000000,
|
| 3 |
+
"val_frac": 0.005,
|
| 4 |
+
"seed": 0,
|
| 5 |
+
"sources": [
|
| 6 |
+
{
|
| 7 |
+
"name": "gdb13",
|
| 8 |
+
"type": "parquet",
|
| 9 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/gdb/gdb13.parquet",
|
| 10 |
+
"weight": 0.35
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"name": "gdb4c3d",
|
| 14 |
+
"type": "parquet",
|
| 15 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/gdb/GDB4c3D.parquet",
|
| 16 |
+
"weight": 0.08
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"name": "gdb13s",
|
| 20 |
+
"type": "parquet",
|
| 21 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/gdb/GDB-13s.parquet",
|
| 22 |
+
"weight": 0.08
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"name": "gdb11",
|
| 26 |
+
"type": "parquet",
|
| 27 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/gdb/gdb11.parquet",
|
| 28 |
+
"weight": 0.04
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"name": "gdbmedchem",
|
| 32 |
+
"type": "parquet",
|
| 33 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/gdb/GDBMedChem.parquet",
|
| 34 |
+
"weight": 0.05
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"name": "zinc",
|
| 38 |
+
"type": "bin",
|
| 39 |
+
"path": "s3://mechanophore/molvae/tokens/zinc-tw2b-v2/train",
|
| 40 |
+
"weight": 0.12,
|
| 41 |
+
"strategy": "stratified",
|
| 42 |
+
"tiers": 8,
|
| 43 |
+
"shards_per_tier": 20,
|
| 44 |
+
"per_shard_cap": 400000
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"name": "mcule",
|
| 48 |
+
"type": "parquet",
|
| 49 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/mcule_full/mcule_purchasable_full_240823.parquet",
|
| 50 |
+
"weight": 0.1
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"name": "mcule_long",
|
| 54 |
+
"type": "parquet",
|
| 55 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/mcule_full/mcule_purchasable_full_240823.parquet",
|
| 56 |
+
"weight": 0.05,
|
| 57 |
+
"min_len": 55
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"name": "emol",
|
| 61 |
+
"type": "parquet",
|
| 62 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/emolecules/ordersc/2024-10-01/parent.parquet",
|
| 63 |
+
"weight": 0.13
|
| 64 |
+
}
|
| 65 |
+
]
|
| 66 |
+
}
|
mixes/mix_dataset.py
ADDED
|
@@ -0,0 +1,712 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build a weighted, shuffled, materialized token-shard "mix" from multiple
|
| 2 |
+
molecular sources, ready for streaming training. TORCH-FREE (numpy + pyarrow +
|
| 3 |
+
boto3 [+ huggingface_hub for remote parquet] only) so it runs on a CPU node in
|
| 4 |
+
a torch-free venv (e.g. `.venv-convert`).
|
| 5 |
+
|
| 6 |
+
Two source kinds:
|
| 7 |
+
parquet A HF-dataset-style parquet file with columns `sequence` (SELFIES str)
|
| 8 |
+
and `tokenized_sequence` (list<int16>, [cls, ...ids, sep, pad, pad...]).
|
| 9 |
+
`path` is either a local file or an HF repo-relative path like
|
| 10 |
+
"datasets/<org>/<repo>/sub/dir/file.parquet" (opened via
|
| 11 |
+
`huggingface_hub.HfFileSystem`). Read streaming via pyarrow
|
| 12 |
+
`iter_batches` -- never materializes the whole file.
|
| 13 |
+
bin An existing .bin/.idx/.desc shard corpus (see `molvae.data.format`).
|
| 14 |
+
`path` is a local directory of shards, or an `s3://bucket/prefix`
|
| 15 |
+
(optionally capped to a random `max_shards` subset, downloaded via
|
| 16 |
+
boto3 before reading, then deleted).
|
| 17 |
+
|
| 18 |
+
DISK-BACKED, two-phase pipeline -- scales to 1B+ molecules on a bounded-RAM node
|
| 19 |
+
by never holding a whole source (or the whole mix) as an in-memory array of
|
| 20 |
+
tokens/objects:
|
| 21 |
+
|
| 22 |
+
Phase A -- per-source SAMPLE-TO-DISK (streaming, O(1) RAM, no reservoir):
|
| 23 |
+
For each source, get its available-mol count CHEAPLY (parquet:
|
| 24 |
+
`metadata.num_rows`; bin: sum of the selected shards' `.idx` sizes, capped by
|
| 25 |
+
`per_shard_cap`) and derive a keep-probability `p = target / available`.
|
| 26 |
+
Stream every mol exactly once (parquet: `iter_batches`; bin:
|
| 27 |
+
`ShardReader.tokens`, always COPIED -- an uncopied memmap view would pin that
|
| 28 |
+
shard's mmap open for the rest of the run once it lands in a Phase-B bucket
|
| 29 |
+
buffer), drop holdout matches, and fraction-sample it: keep with probability
|
| 30 |
+
`p` when `p <= 1` (undersample), or emit `floor(p)` copies plus one more with
|
| 31 |
+
probability `frac(p)` when `p > 1` (oversample). Kept mols are written
|
| 32 |
+
straight to temp per-source shards under `<out>/_scratch/<name>/` via
|
| 33 |
+
`ShardWriter`, rotated every `--shard-size` mols -- so a source's whole
|
| 34 |
+
sample is never resident in RAM, only the one shard currently being
|
| 35 |
+
buffered.
|
| 36 |
+
|
| 37 |
+
Phase B -- external SCATTER-SHUFFLE (single streaming pass, O(out-shards *
|
| 38 |
+
shard-size) RAM): the per-source temp shards are source-contiguous (not
|
| 39 |
+
mixed). One pass reads every mol from every temp shard and routes it to one
|
| 40 |
+
of `--out-shards` open output `ShardWriter` buckets, chosen uniformly at
|
| 41 |
+
random -- a `val_frac`-sized band of bucket ids is designated val, the rest
|
| 42 |
+
train. Whenever a bucket's buffer reaches `--shard-size` mols it is
|
| 43 |
+
(optionally within-shard shuffled, then) flushed to a numbered output shard,
|
| 44 |
+
uploaded to S3 (if `--s3`), and replaced with a fresh buffer. Peak RAM is
|
| 45 |
+
bounded by `out-shards * shard-size` mols -- a constant chosen by the
|
| 46 |
+
operator, independent of the total mix size.
|
| 47 |
+
|
| 48 |
+
python scripts/mix_dataset.py --config mix.json --out /data/mix \
|
| 49 |
+
--dedup-holdout testdata/mechano_test.jsonl \
|
| 50 |
+
--s3 s3://mechanophore/molvae/tokens/mix-v1
|
| 51 |
+
|
| 52 |
+
`--config` mix.json (format UNCHANGED):
|
| 53 |
+
{"total": 40000000, "val_frac": 0.005, "seed": 0,
|
| 54 |
+
"sources": [
|
| 55 |
+
{"name": "zinc", "type": "bin", "path": "s3://.../zinc-tw2b-v2/train",
|
| 56 |
+
"max_shards": 30, "weight": 0.40},
|
| 57 |
+
{"name": "gdb4c3d", "type": "parquet",
|
| 58 |
+
"path": "datasets/MechanophoresResearch/AutoencoderDataset/gdb/GDB4c3D.parquet",
|
| 59 |
+
"weight": 0.35}
|
| 60 |
+
]}
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
from __future__ import annotations
|
| 64 |
+
|
| 65 |
+
import argparse
|
| 66 |
+
import hashlib
|
| 67 |
+
import json
|
| 68 |
+
import os
|
| 69 |
+
import re
|
| 70 |
+
import shutil
|
| 71 |
+
import time
|
| 72 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 73 |
+
from pathlib import Path
|
| 74 |
+
from typing import Dict, List, Optional, Tuple
|
| 75 |
+
from urllib.parse import urlparse
|
| 76 |
+
|
| 77 |
+
import numpy as np
|
| 78 |
+
import pyarrow.parquet as pq
|
| 79 |
+
|
| 80 |
+
from molvae.data.format import (
|
| 81 |
+
OFFSET_DTYPE, TOKEN_DTYPE, Manifest, ShardReader, ShardStat, ShardWriter,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
SELFIES_RE = re.compile(r"\[.*?\]")
|
| 85 |
+
|
| 86 |
+
# Every existing corpus in this repo (convert.py / convert_zinc.py) was built with
|
| 87 |
+
# the 12-name RDKit panel in molvae.descriptors.PROPERTY_NAMES -> that's the default
|
| 88 |
+
# width for reading a `bin`-type source's .desc file. Override per-source with a
|
| 89 |
+
# "n_desc" config key if a source was built with a different descriptor count.
|
| 90 |
+
DEFAULT_SOURCE_N_DESC = 12
|
| 91 |
+
# The mix itself never computes real descriptors (every mol gets a NaN row -- the
|
| 92 |
+
# VAE loss NaN-masks the property head and prop_w=0 in these runs anyway).
|
| 93 |
+
N_DESC_OUT = 12
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# --------------------------------------------------------------------------- #
|
| 97 |
+
# tokenizer metadata -- read tokenizer.json directly (no molvae.tokenizer import,
|
| 98 |
+
# so this script's dependency graph stays stdlib + numpy + pyarrow + boto3 +
|
| 99 |
+
# huggingface_hub, never torch).
|
| 100 |
+
# --------------------------------------------------------------------------- #
|
| 101 |
+
|
| 102 |
+
def load_tokenizer_meta(path: str) -> Tuple[dict, dict, int, str]:
|
| 103 |
+
raw = Path(path).read_bytes()
|
| 104 |
+
sha = hashlib.sha256(raw).hexdigest()
|
| 105 |
+
cfg = json.loads(raw)
|
| 106 |
+
vocab = cfg["vocab"]
|
| 107 |
+
sp = cfg["special_tokens"]
|
| 108 |
+
special_ids = {
|
| 109 |
+
"cls": vocab[sp["cls_token"]],
|
| 110 |
+
"sep": vocab[sp["sep_token"]],
|
| 111 |
+
"pad": vocab[sp["pad_token"]],
|
| 112 |
+
"unk": vocab[sp["unk_token"]],
|
| 113 |
+
}
|
| 114 |
+
return vocab, special_ids, len(vocab), sha
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def encode_selfies(s: str, vocab: dict, cls_id: int, sep_id: int, unk_id: int) -> np.ndarray:
|
| 118 |
+
syms = SELFIES_RE.findall(s)
|
| 119 |
+
ids = [cls_id] + [vocab.get(t, unk_id) for t in syms] + [sep_id]
|
| 120 |
+
return np.asarray(ids, dtype=TOKEN_DTYPE)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# --------------------------------------------------------------------------- #
|
| 124 |
+
# holdout dedup set: exact token-sequence bytes, so equality is exact (no hash
|
| 125 |
+
# collisions possible -- the "hash" the caller cares about is just the dict key).
|
| 126 |
+
# --------------------------------------------------------------------------- #
|
| 127 |
+
|
| 128 |
+
def load_holdout(path: Optional[str], vocab: dict, special_ids: dict) -> set:
|
| 129 |
+
if not path:
|
| 130 |
+
return set()
|
| 131 |
+
out = set()
|
| 132 |
+
with open(path) as f:
|
| 133 |
+
for line in f:
|
| 134 |
+
line = line.strip()
|
| 135 |
+
if not line:
|
| 136 |
+
continue
|
| 137 |
+
obj = json.loads(line)
|
| 138 |
+
arr = encode_selfies(obj["selfies"], vocab, special_ids["cls"],
|
| 139 |
+
special_ids["sep"], special_ids["unk"])
|
| 140 |
+
out.add(arr.tobytes())
|
| 141 |
+
return out
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# --------------------------------------------------------------------------- #
|
| 145 |
+
# S3 (lazy boto3 import; same endpoint-override convention as the rest of the repo)
|
| 146 |
+
# --------------------------------------------------------------------------- #
|
| 147 |
+
|
| 148 |
+
def s3_client():
|
| 149 |
+
import boto3
|
| 150 |
+
from botocore.config import Config
|
| 151 |
+
endpoint = os.environ.get("AWS_ENDPOINT_URL_S3") or os.environ.get("AWS_ENDPOINT_URL")
|
| 152 |
+
cfg = Config(retries={"max_attempts": 10, "mode": "adaptive"})
|
| 153 |
+
return boto3.client("s3", endpoint_url=endpoint, config=cfg)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def upload_shard(stem: Path, s3_stem: str) -> None:
|
| 157 |
+
s3 = s3_client()
|
| 158 |
+
u = urlparse(s3_stem)
|
| 159 |
+
for ext in (".bin", ".idx", ".desc"): # .desc last -> its presence = complete
|
| 160 |
+
for attempt in range(6):
|
| 161 |
+
try:
|
| 162 |
+
s3.upload_file(str(stem) + ext, u.netloc, u.path.lstrip("/") + ext)
|
| 163 |
+
break
|
| 164 |
+
except Exception: # noqa: BLE001
|
| 165 |
+
if attempt == 5:
|
| 166 |
+
raise
|
| 167 |
+
time.sleep(2 ** attempt)
|
| 168 |
+
for ext in (".bin", ".idx", ".desc"):
|
| 169 |
+
os.remove(str(stem) + ext) # free local disk once uploaded
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def upload_manifest(out_dir: Path, s3_prefix: str) -> None:
|
| 173 |
+
u = urlparse(f"{s3_prefix.rstrip('/')}/manifest.json")
|
| 174 |
+
s3_client().upload_file(str(out_dir / "manifest.json"), u.netloc, u.path.lstrip("/"))
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
# --------------------------------------------------------------------------- #
|
| 178 |
+
# parquet source: HF-dataset-style {sequence, tokenized_sequence} rows
|
| 179 |
+
# --------------------------------------------------------------------------- #
|
| 180 |
+
|
| 181 |
+
def _open_parquet(path: str) -> pq.ParquetFile:
|
| 182 |
+
if os.path.exists(path):
|
| 183 |
+
return pq.ParquetFile(path, memory_map=True)
|
| 184 |
+
# HF path "datasets/<org>/<repo>/<subpath>": DOWNLOAD the file (hf_hub_download ~50 MB/s,
|
| 185 |
+
# cached so a repeat open is free) then mmap-read locally. fsspec streaming (HfFileSystem)
|
| 186 |
+
# is ~15x slower here (~3.5 MB/s) -- fatal for gdb13's 9.5 GB / the 1B build.
|
| 187 |
+
from huggingface_hub import hf_hub_download # lazy: only for remote sources
|
| 188 |
+
parts = path.split("/")
|
| 189 |
+
assert parts[0] == "datasets" and len(parts) >= 4, f"bad HF parquet path: {path}"
|
| 190 |
+
local = hf_hub_download(repo_id=f"{parts[1]}/{parts[2]}", filename="/".join(parts[3:]),
|
| 191 |
+
repo_type="dataset", local_dir="/tmp/hf_parquet_cache")
|
| 192 |
+
return pq.ParquetFile(local, memory_map=True)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _parquet_lenfilter_passrate(pf: pq.ParquetFile, pad_id: int, min_len: int,
|
| 196 |
+
max_len: int, n_sample: int = 40000) -> float:
|
| 197 |
+
"""Fraction of a parquet's mols with token-len in [min_len,max_len] (trailing pad
|
| 198 |
+
stripped), estimated from the first ~n_sample rows. Used to calibrate the keep-prob
|
| 199 |
+
of a length-filtered parquet source to its POST-filter pool (else it undersamples;
|
| 200 |
+
e.g. mcule is only ~23% >=55 tok). Assumes the file is not length-SORTED (mcule /
|
| 201 |
+
eMolecules are id-ordered, verified)."""
|
| 202 |
+
seen = passed = 0
|
| 203 |
+
for batch in pf.iter_batches(batch_size=8192, columns=["tokenized_sequence"]):
|
| 204 |
+
for row in batch.column(0).to_pylist():
|
| 205 |
+
n = len(row)
|
| 206 |
+
while n > 0 and row[n - 1] == pad_id:
|
| 207 |
+
n -= 1
|
| 208 |
+
seen += 1
|
| 209 |
+
passed += (min_len <= n <= max_len)
|
| 210 |
+
if seen >= n_sample:
|
| 211 |
+
break
|
| 212 |
+
return (passed / seen) if seen else 1.0
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def sample_parquet_batch(col, pad_id, min_len, max_len, p, floor_p, frac_p, holdout, rng):
|
| 216 |
+
"""VECTORIZED per-batch sampler for a parquet `tokenized_sequence` column (the hot path:
|
| 217 |
+
parquet sources are 10M-1B rows, so per-row Python is far too slow ~34k rows/s). Computes
|
| 218 |
+
real token-lengths, the length filter, and the fraction-keep for the WHOLE batch with numpy,
|
| 219 |
+
then materializes ONLY the kept rows (typically ~1%). Returns (kept_arrays, n_eligible,
|
| 220 |
+
n_dropped). Holdout is checked only on kept rows -> no holdout mol is ever written (zero
|
| 221 |
+
leakage); the dropped COUNT is thus a lower bound, which is fine (dedup correctness != count)."""
|
| 222 |
+
la = col.combine_chunks() if hasattr(col, "combine_chunks") else col
|
| 223 |
+
offs = la.offsets.to_numpy()
|
| 224 |
+
vals = np.asarray(la.values.to_numpy(zero_copy_only=False), dtype=TOKEN_DTYPE)
|
| 225 |
+
n = len(la)
|
| 226 |
+
if n == 0:
|
| 227 |
+
return [], 0, 0
|
| 228 |
+
# real length = # non-pad tokens per row (pad only trails; pad_id never appears mid-sequence)
|
| 229 |
+
real_len = np.add.reduceat((vals != pad_id).astype(np.int64), offs[:-1])
|
| 230 |
+
mask = (real_len >= min_len) & (real_len <= max_len)
|
| 231 |
+
n_eligible = int(mask.sum())
|
| 232 |
+
if p <= 1.0:
|
| 233 |
+
copies = np.where(mask & (rng.random(n) < p), 1, 0)
|
| 234 |
+
else:
|
| 235 |
+
copies = np.where(mask, floor_p + (rng.random(n) < frac_p).astype(np.int64), 0)
|
| 236 |
+
kept_arrays: List[np.ndarray] = []
|
| 237 |
+
n_dropped = 0
|
| 238 |
+
for i in np.flatnonzero(copies > 0):
|
| 239 |
+
arr = vals[offs[i]:offs[i] + real_len[i]] # [cls..sep], trailing pad stripped by real_len
|
| 240 |
+
if holdout and arr.tobytes() in holdout:
|
| 241 |
+
n_dropped += 1
|
| 242 |
+
continue
|
| 243 |
+
c = int(copies[i])
|
| 244 |
+
kept_arrays.extend([arr] * c)
|
| 245 |
+
return kept_arrays, n_eligible, n_dropped
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def iter_parquet_mols(pf: pq.ParquetFile, pad_id: int, batch_size: int = 8192):
|
| 249 |
+
"""Stream `tokenized_sequence` rows off an ALREADY-OPEN ParquetFile (so callers
|
| 250 |
+
can cheaply read `pf.metadata.num_rows` first), trailing-pad stripped to
|
| 251 |
+
[cls, ...ids, sep]."""
|
| 252 |
+
for batch in pf.iter_batches(batch_size=batch_size, columns=["tokenized_sequence"]):
|
| 253 |
+
for row in batch.column(0).to_pylist():
|
| 254 |
+
arr = np.asarray(row, dtype=TOKEN_DTYPE)
|
| 255 |
+
keep = np.flatnonzero(arr != pad_id)
|
| 256 |
+
if keep.size == 0:
|
| 257 |
+
continue
|
| 258 |
+
yield arr[:keep[-1] + 1]
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
# --------------------------------------------------------------------------- #
|
| 262 |
+
# bin/idx shard source: local dir of shards, or s3://prefix (+ optional
|
| 263 |
+
# max_shards random subset, downloaded locally then deleted after reading)
|
| 264 |
+
# --------------------------------------------------------------------------- #
|
| 265 |
+
|
| 266 |
+
def _list_local_stems(path: str) -> List[Tuple[str, int]]:
|
| 267 |
+
return sorted(((str(p)[:-4], p.stat().st_size) for p in Path(path).glob("*.bin")),
|
| 268 |
+
key=lambda x: x[0])
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _list_s3_stems(s3_prefix: str) -> Tuple[str, List[Tuple[str, int]]]:
|
| 272 |
+
"""Return (bucket, [(stem, bin_size_bytes), ...]) for every shard under the prefix."""
|
| 273 |
+
u = urlparse(s3_prefix)
|
| 274 |
+
bucket, prefix = u.netloc, u.path.lstrip("/")
|
| 275 |
+
s3 = s3_client()
|
| 276 |
+
stems: List[Tuple[str, int]] = []
|
| 277 |
+
tok = None
|
| 278 |
+
while True:
|
| 279 |
+
kw = {"Bucket": bucket, "Prefix": prefix}
|
| 280 |
+
if tok:
|
| 281 |
+
kw["ContinuationToken"] = tok
|
| 282 |
+
r = s3.list_objects_v2(**kw)
|
| 283 |
+
stems += [(o["Key"][:-4], o["Size"]) for o in r.get("Contents", [])
|
| 284 |
+
if o["Key"].endswith(".bin")]
|
| 285 |
+
if r.get("IsTruncated"):
|
| 286 |
+
tok = r["NextContinuationToken"]
|
| 287 |
+
else:
|
| 288 |
+
break
|
| 289 |
+
return bucket, sorted(stems, key=lambda x: x[0])
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# rough bytes-per-molecule in a .bin (uint16 tokens, ~45 tok/mol) — for shard-count estimation
|
| 293 |
+
_BYTES_PER_MOL = 95
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _select_bin_stems(stems_sz: List[Tuple[str, int]], target: int, spec: dict, rng
|
| 297 |
+
) -> Tuple[List[str], Optional[int]]:
|
| 298 |
+
"""Pick shards from a size-SKEWED corpus (heavy-atom-bucketed: most shards tiny, a few huge).
|
| 299 |
+
Returns (stems_to_download, per_shard_cap). Two strategies:
|
| 300 |
+
|
| 301 |
+
- 'largest' (default): biggest shards first until the target is covered. Fast, but for a
|
| 302 |
+
heavy-atom-bucketed corpus this is the abundant DRUG-SIZE band only — it misses the large
|
| 303 |
+
molecules, which live in the SMALL shards (rare per band).
|
| 304 |
+
- 'stratified': span the full size range for a VARIED molecule-size distribution. Split shards
|
| 305 |
+
into `tiers` equal-count groups by size, allocate the target EVENLY across tiers, and within
|
| 306 |
+
each tier take (shuffled) shards up to a per-shard cap. This undersamples the abundant
|
| 307 |
+
drug-size band and pulls in the small shards that hold the large (and tiny) molecules."""
|
| 308 |
+
min_mb = float(spec.get("min_shard_mb", 0.0))
|
| 309 |
+
qual = [(s, sz) for s, sz in stems_sz if sz >= min_mb * 1e6] or list(stems_sz)
|
| 310 |
+
cap = spec.get("per_shard_cap")
|
| 311 |
+
if spec.get("strategy", "largest") == "stratified":
|
| 312 |
+
tiers = int(spec.get("tiers", 8))
|
| 313 |
+
spt = int(spec.get("shards_per_tier", 15)) # BOUNDED: <= tiers*spt shards total
|
| 314 |
+
cap = cap or 400_000 # per-shard cap (undersamples huge drug-size shards)
|
| 315 |
+
qual.sort(key=lambda x: x[1]) # ascending size
|
| 316 |
+
picked: List[str] = []
|
| 317 |
+
for t in range(tiers): # contiguous equal-count size groups
|
| 318 |
+
grp = qual[t * len(qual) // tiers:(t + 1) * len(qual) // tiers]
|
| 319 |
+
if not grp:
|
| 320 |
+
continue
|
| 321 |
+
order = rng.permutation(len(grp))[:spt] # up to `spt` RANDOM shards per size tier
|
| 322 |
+
picked += [grp[int(gi)][0] for gi in order]
|
| 323 |
+
return picked, cap
|
| 324 |
+
qual.sort(key=lambda x: -x[1]) # largest first
|
| 325 |
+
picked, est = [], 0.0
|
| 326 |
+
for s, sz in qual:
|
| 327 |
+
picked.append(s)
|
| 328 |
+
est += sz / _BYTES_PER_MOL
|
| 329 |
+
if spec.get("max_shards") and len(picked) >= int(spec["max_shards"]):
|
| 330 |
+
break
|
| 331 |
+
if est >= target * 1.3:
|
| 332 |
+
break
|
| 333 |
+
return picked, cap
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def _download_stems(bucket: str, stems: List[str], dest: Path, workers: int) -> List[Path]:
|
| 337 |
+
dest.mkdir(parents=True, exist_ok=True)
|
| 338 |
+
s3 = s3_client()
|
| 339 |
+
|
| 340 |
+
def fetch(stem: str) -> Path:
|
| 341 |
+
local_stem = dest / Path(stem).name
|
| 342 |
+
for ext in (".bin", ".idx", ".desc"):
|
| 343 |
+
s3.download_file(bucket, stem + ext, str(local_stem) + ext)
|
| 344 |
+
return local_stem
|
| 345 |
+
|
| 346 |
+
out: List[Path] = []
|
| 347 |
+
with ThreadPoolExecutor(max_workers=max(1, workers)) as ex:
|
| 348 |
+
for p in ex.map(fetch, stems):
|
| 349 |
+
out.append(p)
|
| 350 |
+
return out
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def iter_bin_mols(stems: List[Path], n_desc: int, cap: Optional[int] = None, rng=None):
|
| 354 |
+
"""Yield mols from each shard; if `cap` is set, yield at most `cap` RANDOM mols per shard
|
| 355 |
+
(so a huge drug-size shard doesn't dominate a stratified sample)."""
|
| 356 |
+
for stem in stems:
|
| 357 |
+
r = ShardReader(stem, n_desc)
|
| 358 |
+
n = len(r)
|
| 359 |
+
idxs = rng.choice(n, size=cap, replace=False) if (cap and n > cap) else range(n)
|
| 360 |
+
for i in idxs:
|
| 361 |
+
yield np.array(r.tokens(int(i))) # COPY: don't retain a memmap view (fd leak)
|
| 362 |
+
del r # release the shard's .bin/.idx/.desc memmaps
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
# --------------------------------------------------------------------------- #
|
| 366 |
+
# Phase A: per-source SAMPLE-TO-DISK (streaming, O(1) RAM -- no reservoir).
|
| 367 |
+
# --------------------------------------------------------------------------- #
|
| 368 |
+
|
| 369 |
+
def _shard_n_mol(stem: Path) -> int:
|
| 370 |
+
"""Mol count of a LOCAL shard from its `.idx` file size alone -- no data read."""
|
| 371 |
+
itemsize = np.dtype(OFFSET_DTYPE).itemsize
|
| 372 |
+
return os.path.getsize(f"{stem}.idx") // itemsize - 1
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _shard_n_mol_inrange(stem: Path, min_len: int, max_len: int) -> Tuple[int, int]:
|
| 376 |
+
"""(total, in_range) mol counts for a LOCAL shard: reads only the small .idx and
|
| 377 |
+
derives per-mol token lengths (diff of offsets). Used to length-calibrate the
|
| 378 |
+
keep-probability when a source has a min_len/max_len filter (e.g. long-ZINC)."""
|
| 379 |
+
idx = np.fromfile(f"{stem}.idx", dtype=OFFSET_DTYPE)
|
| 380 |
+
lens = np.diff(idx)
|
| 381 |
+
return int(lens.size), int(((lens >= min_len) & (lens <= max_len)).sum())
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def sample_source_to_disk(idx: int, spec: dict, target: int, seed: int, pad_id: int,
|
| 385 |
+
holdout: set, out_dir: Path, workers: int, shard_size: int
|
| 386 |
+
) -> Tuple[dict, List[Path]]:
|
| 387 |
+
"""Phase A for one source: stream its mols once, drop holdout matches, and
|
| 388 |
+
fraction-sample to ~`target` (keep-probability `p = target/available` when
|
| 389 |
+
undersampling, replicate `floor(p)`(+1) copies when oversampling) -- writing
|
| 390 |
+
kept mols DIRECTLY to temp per-source shards under `out_dir/_scratch/<name>/`
|
| 391 |
+
via `ShardWriter`. Never buffers more than one output shard's worth of mols in
|
| 392 |
+
RAM. Returns (report dict, [temp shard stems written])."""
|
| 393 |
+
name = spec["name"]
|
| 394 |
+
kind = spec["type"]
|
| 395 |
+
min_len = int(spec.get("min_len", 0)) # keep only mols with min_len <= tok_len <= max_len
|
| 396 |
+
max_len = int(spec.get("max_len", 1 << 30)) # (tok_len incl cls+sep); e.g. min_len 55 -> long ZINC
|
| 397 |
+
rng = np.random.default_rng([seed, idx, 1]) # independent per-source stream
|
| 398 |
+
report = {"name": name, "type": kind, "target": int(target), "available": 0,
|
| 399 |
+
"kept": 0, "oversample": 0, "holdout_dropped": 0}
|
| 400 |
+
if target <= 0:
|
| 401 |
+
return report, []
|
| 402 |
+
|
| 403 |
+
dl_scratch: Optional[Path] = None
|
| 404 |
+
parquet_pf = None
|
| 405 |
+
gen = None
|
| 406 |
+
if kind == "parquet":
|
| 407 |
+
pf = _open_parquet(spec["path"])
|
| 408 |
+
available = int(pf.metadata.num_rows)
|
| 409 |
+
if min_len > 0 or max_len < (1 << 30): # calibrate keep-prob to the post-filter pool
|
| 410 |
+
rate = _parquet_lenfilter_passrate(pf, pad_id, min_len, max_len)
|
| 411 |
+
available = int(available * rate)
|
| 412 |
+
pf = _open_parquet(spec["path"]) # fresh handle for the streaming pass
|
| 413 |
+
parquet_pf = pf # streamed batch-vectorized below
|
| 414 |
+
elif kind == "bin":
|
| 415 |
+
path = spec["path"]
|
| 416 |
+
n_desc = int(spec.get("n_desc", DEFAULT_SOURCE_N_DESC))
|
| 417 |
+
if path.startswith("s3://"):
|
| 418 |
+
bucket, stems_sz = _list_s3_stems(path)
|
| 419 |
+
picked, cap = _select_bin_stems(stems_sz, target, spec, rng)
|
| 420 |
+
dl_scratch = out_dir / "_scratch" / f"{name}__dl"
|
| 421 |
+
local_stems = _download_stems(bucket, picked, dl_scratch, workers)
|
| 422 |
+
else:
|
| 423 |
+
picked, cap = _select_bin_stems(_list_local_stems(path), target, spec, rng)
|
| 424 |
+
local_stems = [Path(s) for s in picked]
|
| 425 |
+
# available mols is CAP-AWARE (iter_bin_mols streams at most `cap` random mols per
|
| 426 |
+
# shard) AND length-filter-AWARE (only mols in [min_len,max_len] survive the stream
|
| 427 |
+
# filter) -- keep-probability must be computed against the pool the loop actually sees.
|
| 428 |
+
if min_len > 0 or max_len < (1 << 30):
|
| 429 |
+
available = 0
|
| 430 |
+
for s in local_stems:
|
| 431 |
+
n, n_in = _shard_n_mol_inrange(s, min_len, max_len)
|
| 432 |
+
available += int(round(cap * n_in / n)) if (cap and n > cap and n) else n_in
|
| 433 |
+
else:
|
| 434 |
+
available = int(sum((min(_shard_n_mol(s), cap) if cap else _shard_n_mol(s))
|
| 435 |
+
for s in local_stems))
|
| 436 |
+
gen = iter_bin_mols(local_stems, n_desc, cap=cap, rng=rng)
|
| 437 |
+
else:
|
| 438 |
+
raise ValueError(f"unknown source type {kind!r} for {name!r}")
|
| 439 |
+
|
| 440 |
+
p = target / available if available > 0 else 0.0
|
| 441 |
+
floor_p = int(p) # p >= 0, so int(p) == floor(p)
|
| 442 |
+
frac_p = p - floor_p
|
| 443 |
+
|
| 444 |
+
scratch_dir = out_dir / "_scratch" / name
|
| 445 |
+
nan_row = np.full(N_DESC_OUT, np.nan, dtype=np.float16)
|
| 446 |
+
temp_stems: List[Path] = []
|
| 447 |
+
part_i = 0
|
| 448 |
+
writer = ShardWriter(scratch_dir / f"part-{part_i:05d}", N_DESC_OUT)
|
| 449 |
+
n_eligible = 0
|
| 450 |
+
n_dropped = 0
|
| 451 |
+
kept = 0
|
| 452 |
+
|
| 453 |
+
def _roll() -> None:
|
| 454 |
+
nonlocal writer, part_i
|
| 455 |
+
st = writer.flush()
|
| 456 |
+
temp_stems.append(scratch_dir / st.name)
|
| 457 |
+
part_i += 1
|
| 458 |
+
writer = ShardWriter(scratch_dir / f"part-{part_i:05d}", N_DESC_OUT)
|
| 459 |
+
|
| 460 |
+
def _write(arr: np.ndarray) -> None:
|
| 461 |
+
nonlocal kept
|
| 462 |
+
writer.add(arr, nan_row)
|
| 463 |
+
kept += 1
|
| 464 |
+
if len(writer) >= shard_size:
|
| 465 |
+
_roll()
|
| 466 |
+
|
| 467 |
+
if parquet_pf is not None: # VECTORIZED parquet hot path (per batch)
|
| 468 |
+
for batch in parquet_pf.iter_batches(batch_size=16384, columns=["tokenized_sequence"]):
|
| 469 |
+
kept_arrays, ne, nd = sample_parquet_batch(
|
| 470 |
+
batch.column(0), pad_id, min_len, max_len, p, floor_p, frac_p, holdout, rng)
|
| 471 |
+
n_eligible += ne
|
| 472 |
+
n_dropped += nd
|
| 473 |
+
for arr in kept_arrays:
|
| 474 |
+
_write(arr)
|
| 475 |
+
else: # bin source: per-mol (smaller scale)
|
| 476 |
+
for arr in gen:
|
| 477 |
+
arr = np.asarray(arr, dtype=TOKEN_DTYPE)
|
| 478 |
+
if arr.size < min_len or arr.size > max_len:
|
| 479 |
+
continue
|
| 480 |
+
if holdout and arr.tobytes() in holdout:
|
| 481 |
+
n_dropped += 1
|
| 482 |
+
continue
|
| 483 |
+
n_eligible += 1
|
| 484 |
+
copies = (1 if rng.random() < p else 0) if p <= 1.0 else (
|
| 485 |
+
floor_p + (1 if rng.random() < frac_p else 0))
|
| 486 |
+
for _ in range(copies):
|
| 487 |
+
_write(arr)
|
| 488 |
+
|
| 489 |
+
if len(writer):
|
| 490 |
+
_roll()
|
| 491 |
+
|
| 492 |
+
if dl_scratch is not None:
|
| 493 |
+
shutil.rmtree(dl_scratch, ignore_errors=True)
|
| 494 |
+
|
| 495 |
+
report.update(available=available, kept=kept,
|
| 496 |
+
oversample=max(0, kept - n_eligible), holdout_dropped=n_dropped)
|
| 497 |
+
return report, temp_stems
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
# --------------------------------------------------------------------------- #
|
| 501 |
+
# Phase B: external SCATTER-SHUFFLE (single streaming pass, O(out_shards *
|
| 502 |
+
# shard_size) RAM) -- routes every mol from every per-source temp shard to a
|
| 503 |
+
# uniform-random output bucket, giving a global shuffle without ever sorting or
|
| 504 |
+
# holding the whole mix in memory.
|
| 505 |
+
# --------------------------------------------------------------------------- #
|
| 506 |
+
|
| 507 |
+
def scatter_shuffle_to_shards(temp_stems: List[Path], out_dir: Path, man: Manifest,
|
| 508 |
+
n_out: int, val_frac: float, shard_size: int, seed: int,
|
| 509 |
+
n_desc: int, s3_prefix: Optional[str]
|
| 510 |
+
) -> Tuple[Dict[str, Tuple[int, int, int]], int]:
|
| 511 |
+
"""Read every mol out of every (source-contiguous) temp shard exactly once, in
|
| 512 |
+
arbitrary order, and route it to one of `n_out` open output-shard buckets chosen
|
| 513 |
+
uniformly at random -- bucket ids `[0, n_val)` are `val`, the rest `train`. A
|
| 514 |
+
bucket is flushed (and its writer replaced) as soon as it reaches `shard_size`
|
| 515 |
+
mols. Mutates `man` in place (one `ShardStat` per flushed shard). Returns
|
| 516 |
+
({"val"|"train": (n_mol, n_tokens, n_shards)}, max_mol_len_seen)."""
|
| 517 |
+
rng = np.random.default_rng([seed, 0x5CA77E12]) # distinct from per-source streams
|
| 518 |
+
n_out = max(1, n_out)
|
| 519 |
+
n_val = min(n_out, (max(1, round(val_frac * n_out)) if val_frac > 0 else 0))
|
| 520 |
+
|
| 521 |
+
def _fresh() -> ShardWriter:
|
| 522 |
+
return ShardWriter(out_dir / "_pending", n_desc) # stem overwritten before flush
|
| 523 |
+
|
| 524 |
+
writers: List[ShardWriter] = [_fresh() for _ in range(n_out)]
|
| 525 |
+
shard_ct = {"val": 0, "train": 0}
|
| 526 |
+
n_mol_tot = {"val": 0, "train": 0}
|
| 527 |
+
n_tok_tot = {"val": 0, "train": 0}
|
| 528 |
+
n_shard_tot = {"val": 0, "train": 0}
|
| 529 |
+
max_len = 0
|
| 530 |
+
|
| 531 |
+
def _flush(b: int) -> None:
|
| 532 |
+
w = writers[b]
|
| 533 |
+
if len(w) == 0:
|
| 534 |
+
return
|
| 535 |
+
split = "val" if b < n_val else "train"
|
| 536 |
+
w.shuffle(rng) # cheap extra within-shard mixing
|
| 537 |
+
i = shard_ct[split]
|
| 538 |
+
shard_ct[split] += 1
|
| 539 |
+
w.stem = out_dir / split / f"shard-{i:05d}"
|
| 540 |
+
st = w.flush()
|
| 541 |
+
st.split = split
|
| 542 |
+
man.add(st)
|
| 543 |
+
n_mol_tot[split] += st.n_mol
|
| 544 |
+
n_tok_tot[split] += st.n_tokens
|
| 545 |
+
n_shard_tot[split] += 1
|
| 546 |
+
if s3_prefix:
|
| 547 |
+
upload_shard(w.stem, f"{s3_prefix.rstrip('/')}/{split}/{st.name}")
|
| 548 |
+
writers[b] = _fresh()
|
| 549 |
+
|
| 550 |
+
# Temp shards arrive GROUPED by source (Phase A appends one source's shards at a
|
| 551 |
+
# time). If they were read in that order, a bucket's buffer would accumulate
|
| 552 |
+
# source A, then source B, ... in TIME order, and its LAST flush (esp. the final
|
| 553 |
+
# trailing flush after the whole pass) would end up dominated by whichever source
|
| 554 |
+
# was streamed last -- source-contiguous, defeating the shuffle. Visiting temp
|
| 555 |
+
# shards in a random order instead means every point in the pass draws from a mix
|
| 556 |
+
# of sources, so every flush (including the tail) interleaves them. Cheap: just a
|
| 557 |
+
# permutation over the (small) shard-COUNT, not the mols.
|
| 558 |
+
order = rng.permutation(len(temp_stems))
|
| 559 |
+
for k in order:
|
| 560 |
+
stem = temp_stems[int(k)]
|
| 561 |
+
r = ShardReader(stem, n_desc)
|
| 562 |
+
n = len(r)
|
| 563 |
+
if n:
|
| 564 |
+
buckets = rng.integers(0, n_out, size=n)
|
| 565 |
+
for i in range(n):
|
| 566 |
+
ids = np.array(r.tokens(i)) # COPY -- an uncopied memmap view would pin
|
| 567 |
+
desc = np.array(r.desc(i)) # this temp shard's mmap open indefinitely
|
| 568 |
+
if ids.size > max_len:
|
| 569 |
+
max_len = int(ids.size)
|
| 570 |
+
b = int(buckets[i])
|
| 571 |
+
writers[b].add(ids, desc)
|
| 572 |
+
if len(writers[b]) >= shard_size:
|
| 573 |
+
_flush(b)
|
| 574 |
+
del r
|
| 575 |
+
|
| 576 |
+
for b in range(n_out):
|
| 577 |
+
_flush(b)
|
| 578 |
+
|
| 579 |
+
totals = {"val": (n_mol_tot["val"], n_tok_tot["val"], n_shard_tot["val"]),
|
| 580 |
+
"train": (n_mol_tot["train"], n_tok_tot["train"], n_shard_tot["train"])}
|
| 581 |
+
return totals, max_len
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
# --------------------------------------------------------------------------- #
|
| 585 |
+
# main
|
| 586 |
+
# --------------------------------------------------------------------------- #
|
| 587 |
+
|
| 588 |
+
def _normalized_targets(sources_cfg: List[dict], total: int) -> List[int]:
|
| 589 |
+
"""Largest-remainder rounding so per-source targets sum to exactly `total`."""
|
| 590 |
+
weights = np.array([float(s["weight"]) for s in sources_cfg], dtype=np.float64)
|
| 591 |
+
if weights.sum() <= 0:
|
| 592 |
+
raise SystemExit("sum of source weights must be > 0")
|
| 593 |
+
weights = weights / weights.sum()
|
| 594 |
+
raw = weights * total
|
| 595 |
+
targets = np.floor(raw).astype(np.int64)
|
| 596 |
+
remainder = int(total - targets.sum())
|
| 597 |
+
if remainder > 0:
|
| 598 |
+
order = np.argsort(-(raw - targets))
|
| 599 |
+
for i in order[:remainder]:
|
| 600 |
+
targets[i] += 1
|
| 601 |
+
return targets.tolist()
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def main(argv: Optional[List[str]] = None) -> None:
|
| 605 |
+
ap = argparse.ArgumentParser(description=__doc__,
|
| 606 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 607 |
+
ap.add_argument("--config", required=True, help="mix spec: JSON file path or inline JSON string")
|
| 608 |
+
ap.add_argument("--out", required=True, help="local output dir (train/, val/, manifest.json)")
|
| 609 |
+
ap.add_argument("--s3", default=None, help="optional s3://bucket/prefix to upload shards to")
|
| 610 |
+
ap.add_argument("--dedup-holdout", default=None,
|
| 611 |
+
help="jsonl with a 'selfies' field per line; exact token-seq matches are dropped")
|
| 612 |
+
ap.add_argument("--shard-size", type=int, default=200_000,
|
| 613 |
+
help="mols per shard -- both Phase-A temp per-source shards and "
|
| 614 |
+
"Phase-B final output shards")
|
| 615 |
+
ap.add_argument("--out-shards", type=int, default=1024,
|
| 616 |
+
help="Phase-B scatter-shuffle output-bucket count; peak RAM is "
|
| 617 |
+
"~= out-shards * shard-size mols, independent of total mix size")
|
| 618 |
+
ap.add_argument("--workers", type=int, default=8, help="parallel S3 shard downloads")
|
| 619 |
+
ap.add_argument("--tokenizer", default="tokenizer.json")
|
| 620 |
+
ap.add_argument("--seed", type=int, default=None, help="override the config's seed")
|
| 621 |
+
a = ap.parse_args(argv)
|
| 622 |
+
|
| 623 |
+
cfg_path = Path(a.config)
|
| 624 |
+
cfg = json.loads(cfg_path.read_text()) if cfg_path.exists() else json.loads(a.config)
|
| 625 |
+
|
| 626 |
+
total = int(cfg["total"])
|
| 627 |
+
val_frac = float(cfg.get("val_frac", 0.005))
|
| 628 |
+
seed = int(a.seed if a.seed is not None else cfg.get("seed", 0))
|
| 629 |
+
sources_cfg = cfg["sources"]
|
| 630 |
+
|
| 631 |
+
vocab, special_ids, vocab_size, tok_sha = load_tokenizer_meta(a.tokenizer)
|
| 632 |
+
pad_id = special_ids["pad"]
|
| 633 |
+
|
| 634 |
+
holdout = load_holdout(a.dedup_holdout, vocab, special_ids)
|
| 635 |
+
if a.dedup_holdout:
|
| 636 |
+
print(f"holdout: {len(holdout)} unique token-sequences loaded from {a.dedup_holdout}")
|
| 637 |
+
|
| 638 |
+
targets = _normalized_targets(sources_cfg, total)
|
| 639 |
+
|
| 640 |
+
out_dir = Path(a.out)
|
| 641 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 642 |
+
|
| 643 |
+
print("=== Phase A: per-source sample-to-disk ===")
|
| 644 |
+
reports: List[dict] = []
|
| 645 |
+
all_temp_stems: List[Path] = []
|
| 646 |
+
for i, (spec, target) in enumerate(zip(sources_cfg, targets)):
|
| 647 |
+
print(f"[{i + 1}/{len(sources_cfg)}] sampling {spec['name']!r} (target {target:,}) ...")
|
| 648 |
+
rep, temp_stems = sample_source_to_disk(i, spec, target, seed, pad_id, holdout,
|
| 649 |
+
out_dir, a.workers, a.shard_size)
|
| 650 |
+
reports.append(rep)
|
| 651 |
+
all_temp_stems += temp_stems
|
| 652 |
+
avail_s = f"{rep['available']:,}"
|
| 653 |
+
osf = f"{rep['target'] / rep['available']:.2f}x" if rep["available"] else "n/a"
|
| 654 |
+
print(f" target={rep['target']:,} available={avail_s} kept={rep['kept']:,} "
|
| 655 |
+
f"oversample_factor={osf} holdout_dropped={rep['holdout_dropped']:,}")
|
| 656 |
+
|
| 657 |
+
total_actual = sum(r["kept"] for r in reports)
|
| 658 |
+
if total_actual == 0:
|
| 659 |
+
raise SystemExit("no molecules collected from any source -- aborting")
|
| 660 |
+
|
| 661 |
+
man = Manifest(
|
| 662 |
+
tokenizer_sha256=tok_sha, vocab_size=vocab_size, vocab=vocab,
|
| 663 |
+
special_ids=special_ids, max_len=256,
|
| 664 |
+
descriptor_names=[f"desc{i}" for i in range(N_DESC_OUT)],
|
| 665 |
+
)
|
| 666 |
+
|
| 667 |
+
print(f"\n=== Phase B: scatter-shuffling {total_actual:,} mols into "
|
| 668 |
+
f"{a.out_shards} output buckets ===")
|
| 669 |
+
split_totals, max_len_val = scatter_shuffle_to_shards(
|
| 670 |
+
all_temp_stems, out_dir, man, a.out_shards, val_frac, a.shard_size, seed,
|
| 671 |
+
N_DESC_OUT, a.s3)
|
| 672 |
+
man.max_len = max_len_val or 256
|
| 673 |
+
for split_name in ("val", "train"):
|
| 674 |
+
if split_totals[split_name][0] == 0:
|
| 675 |
+
print(f"WARNING: {split_name} split is empty")
|
| 676 |
+
|
| 677 |
+
man.stats = {
|
| 678 |
+
"n_mol": man.n_mol,
|
| 679 |
+
"desc_mean": [0.0] * N_DESC_OUT, # NaN rows -> (NaN-0)/1 stays NaN
|
| 680 |
+
"desc_std": [1.0] * N_DESC_OUT,
|
| 681 |
+
"desc_count": [0] * N_DESC_OUT,
|
| 682 |
+
"seed": seed,
|
| 683 |
+
"val_frac": val_frac,
|
| 684 |
+
"mix_total_requested": total,
|
| 685 |
+
"mix_total_actual": total_actual,
|
| 686 |
+
"mix_sources": reports,
|
| 687 |
+
"holdout_path": a.dedup_holdout,
|
| 688 |
+
"holdout_dropped_total": sum(r["holdout_dropped"] for r in reports),
|
| 689 |
+
}
|
| 690 |
+
man.save(out_dir)
|
| 691 |
+
if a.s3:
|
| 692 |
+
upload_manifest(out_dir, a.s3)
|
| 693 |
+
|
| 694 |
+
scratch_root = out_dir / "_scratch"
|
| 695 |
+
if scratch_root.exists():
|
| 696 |
+
shutil.rmtree(scratch_root, ignore_errors=True)
|
| 697 |
+
|
| 698 |
+
print("\n=== mix summary ===")
|
| 699 |
+
for r in reports:
|
| 700 |
+
avail_s = f"{r['available']:,}"
|
| 701 |
+
print(f" {r['name']:<16} type={r['type']:<8} target={r['target']:>10,} "
|
| 702 |
+
f"available={avail_s:>12} kept={r['kept']:>10,} "
|
| 703 |
+
f"oversample={r['oversample']:>8,} holdout_dropped={r['holdout_dropped']:>6,}")
|
| 704 |
+
for split_name in ("train", "val"):
|
| 705 |
+
n, n_tok, n_shards = split_totals[split_name]
|
| 706 |
+
print(f" {split_name}: {n:,} mols, {n_tok:,} tokens, {n_shards} shards")
|
| 707 |
+
print(f" total: {total_actual:,} mols (requested {total:,})")
|
| 708 |
+
print(f" output: {a.s3 if a.s3 else str(out_dir)}")
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
if __name__ == "__main__":
|
| 712 |
+
main()
|