File size: 10,958 Bytes
3e3ee14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# CLI subcommands import the scientific stack only when executed.
# ruff: noqa: PLC0415

"""``morph`` — molecular generation CLI.

Run in-process (on a GPU node / via ``srun``):

    uv run --active --env-file .env morph generate -b 16
    # or, without (re)installing the console script:
    uv run --active --env-file .env python -m morph generate -b 16

Model bundles are downloaded from Hugging Face on demand.
Use ``morph models list`` to inspect variants and available epochs.
"""

from __future__ import annotations

import click


def _catalog_options(command):
    """Share explicit catalog source options across discovery and loading."""
    command = click.option(
        "--catalog-repo", help="HF repository hosting catalog.json."
    )(command)
    command = click.option(
        "--catalog-revision", help="Catalog commit, tag or branch (default: main)."
    )(command)
    return click.option(
        "--catalog-file",
        type=click.Path(exists=True, dir_okay=False),
        help="Local catalog JSON; skips catalog network access.",
    )(command)


def _get_catalog(repo, revision, path, cache_dir, offline, *, optional=False):
    """Resolve an explicit override, or leave default discovery to the loader."""
    from morph.inference import load_catalog

    if optional and repo is None and revision is None and path is None:
        return None
    return load_catalog(
        repo,
        revision=revision,
        path=path,
        cache_dir=cache_dir,
        local_files_only=offline,
    )


@click.group()
@click.version_option(package_name="morph")
def cli() -> None:
    """Morph — molecular generation CLI."""


@cli.group()
def models() -> None:
    """Discover and download pretrained model bundles."""


@models.command("list")
@_catalog_options
@click.option(
    "--cache-dir", type=click.Path(file_okay=False), help="HF cache directory."
)
@click.option("--offline", is_flag=True, help="Use only the cached catalog.")
def list_models(
    catalog_repo, catalog_revision, catalog_file, cache_dir, offline
) -> None:
    """Discover models from the Hub catalog without downloading weights."""
    try:
        catalog = _get_catalog(
            catalog_repo, catalog_revision, catalog_file, cache_dir, offline
        )
    except (ValueError, OSError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc

    click.echo(f"{'MODEL':24} {'DATASET':12} {'EPOCHS':18} DEFAULT EPOCH")
    for spec in catalog.models.values():
        epochs = ", ".join(map(str, spec.epochs)) or "from bundle"
        latest = spec.select_epoch() or "from bundle"
        click.echo(f"{spec.name:24} {spec.dataset or '-':12} {epochs:18} {latest}")
    click.echo(f"Default model: {catalog.default_model or '(none)'}")
    source = (
        f"{catalog.repo_id}@{catalog.revision}"
        if catalog.repo_id
        else str(catalog.path)
    )
    click.echo(f"Catalog: {source}")


@models.command("download")
@_catalog_options
@click.argument("model_name")
@click.option("--epoch", type=click.IntRange(min=1), help="Completed training epoch.")
@click.option("--subfolder", help="Bundle subfolder inside the repository.")
@click.option(
    "--revision", help="HF commit, tag or branch; catalog entries pin a commit."
)
@click.option(
    "--filename", help="Checkpoint path relative to the bundle, instead of epoch."
)
@click.option(
    "--cache-dir", type=click.Path(file_okay=False), help="HF cache directory."
)
@click.option(
    "--local-dir", type=click.Path(file_okay=False), help="Export root directory."
)
@click.option(
    "--offline", is_flag=True, help="Use cached files without network access."
)
def download_model(
    model_name,
    epoch,
    subfolder,
    revision,
    filename,
    cache_dir,
    local_dir,
    offline,
    catalog_repo,
    catalog_revision,
    catalog_file,
) -> None:
    """Download one epoch with its config, vocabularies and distributions.

    Auth: hf auth login, or set HF_TOKEN. Prints the local bundle directory.
    """
    from morph.inference.hub import download_pretrained

    try:
        catalog = _get_catalog(
            catalog_repo,
            catalog_revision,
            catalog_file,
            cache_dir,
            offline,
            optional=True,
        )
        bundle = download_pretrained(
            model_name,
            epoch=epoch,
            subfolder=subfolder,
            revision=revision,
            filename=filename,
            catalog=catalog,
            cache_dir=cache_dir,
            local_dir=local_dir,
            local_files_only=offline,
        )
    except (ValueError, OSError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    click.echo(str(bundle.directory))


@cli.command()
@_catalog_options
@click.option(
    "-b",
    "--batch",
    "n_mols",
    type=click.IntRange(min=1),
    default=16,
    show_default=True,
    help="Number of molecules to generate.",
)
@click.option(
    "-o",
    "--output",
    type=click.Path(),
    show_default=True,
    default="eval_outputs/denovo.sdf",
    help="Output SDF of valid final-frame molecules (3D coordinates + SMILES name).",
)
@click.option(
    "--model",
    "model_name",
    default=None,
    help="Catalog name (morph models list) or Hugging Face owner/repo ID.",
)
@click.option(
    "--epoch", type=click.IntRange(min=1), help="Epoch; defaults to latest published."
)
@click.option(
    "--subfolder", help="Bundle subfolder inside the repository or local root."
)
@click.option(
    "--revision", help="HF commit, tag or branch; catalog entries pin a commit."
)
@click.option(
    "--filename", help="Checkpoint path relative to the bundle, instead of epoch."
)
@click.option(
    "--cache-dir", type=click.Path(file_okay=False), help="HF cache directory."
)
@click.option(
    "--offline", is_flag=True, help="Use cached files without network access."
)
@click.option(
    "--device",
    type=click.Choice(["auto", "cpu", "cuda"]),
    default="auto",
    show_default=True,
)
@click.option("--steps", type=click.IntRange(min=1), default=100, show_default=True)
@click.option(
    "--ema/--no-ema",
    default=True,
    show_default=True,
    help="Use EMA or current weights.",
)
@click.option(
    "--weights-dir",
    default=None,
    type=click.Path(exists=True, file_okay=False),
    help="Local variant bundle or download root; skips Hugging Face entirely.",
)
@click.option(
    "--checkpoint",
    default=None,
    type=click.Path(exists=True, dir_okay=False),
    help="Override local weights; requires --weights-dir with matching assets.",
)
@click.option(
    "--save-trajs",
    is_flag=True,
    help="Save full trajectories in <output>_trajs/batch-*.pt files.",
)
@click.option("--seed", default=42, show_default=True)
@click.option(
    "--batch-size",
    type=click.IntRange(min=1),
    default=None,
    help="Molecules per sampling batch (default: up to 32).",
)
def generate(
    n_mols,
    output,
    model_name,
    weights_dir,
    checkpoint,
    save_trajs,
    seed,
    batch_size,
    epoch,
    subfolder,
    revision,
    filename,
    catalog_repo,
    catalog_revision,
    catalog_file,
    cache_dir,
    offline,
    device,
    steps,
    ema,
) -> None:
    """Generate molecules de-novo with an unconditional checkpoint.

    Downloads the selected checkpoint and matching assets on first use.
    Uses the saved model config, eager execution, and EMA weights by default.
    """
    from pathlib import Path

    import torch
    from rdkit import Chem

    from morph.inference.generate import final_mol, record_mol
    from morph.inference.hub import load_pretrained

    try:
        catalog = _get_catalog(
            catalog_repo,
            catalog_revision,
            catalog_file,
            cache_dir,
            offline,
            optional=True,
        )
        model = load_pretrained(
            model_name,
            epoch=epoch,
            subfolder=subfolder,
            revision=revision,
            filename=filename,
            catalog=catalog,
            device=device,
            weights_dir=weights_dir,
            checkpoint=checkpoint,
            cache_dir=cache_dir,
            local_files_only=offline,
            steps=steps,
            use_ema=ema,
        )
    except (ValueError, OSError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    click.echo(
        f"[morph generate] model={model.bundle.spec.name}  "
        f"ckpt={model.bundle.checkpoint}  n={n_mols}"
    )

    out = Path(output)
    out.parent.mkdir(parents=True, exist_ok=True)
    trajectory_dir = out.with_name(out.stem + "_trajs")
    if save_trajs:
        # Reusing a nonempty directory could mix batches from separate runs.
        if trajectory_dir.exists() and any(trajectory_dir.iterdir()):
            raise click.ClickException(
                f"Trajectory directory is not empty: {trajectory_dir}. "
                "Choose a different output filename."
            )
        trajectory_dir.mkdir(parents=True, exist_ok=True)

    attempted = n_written = n_valid = batch_index = 0
    unique_smiles = set()
    with Chem.SDWriter(str(out)) as writer:

        def consume(trajectories, is_valid):
            nonlocal attempted, n_written, n_valid, batch_index
            if save_trajs:
                torch.save(
                    {
                        "start_index": attempted,
                        "trajectories": trajectories,
                        "is_valid": is_valid,
                    },
                    trajectory_dir / f"batch-{batch_index:06d}.pt",
                )
            for traj, valid in zip(trajectories, is_valid, strict=True):
                if valid:
                    mol = final_mol(traj, model.vocab)
                    if mol is not None:
                        mol.SetProp("_Name", Chem.MolToSmiles(mol))
                        writer.write(mol)
                        n_written += 1
                row = record_mol(traj, model.vocab)
                n_valid += int(valid)
                if valid and row["smiles"] is not None:
                    unique_smiles.add(row["smiles"])
                click.echo(
                    f"   [{attempted}] valid={valid} N={row['n_atoms']} "
                    f"logP={row['logp']} {row['smiles']}"
                )
                attempted += 1
            writer.flush()
            batch_index += 1

        model.generate_to(
            consume,
            n_mols=n_mols,
            seed=seed,
            batch_size=batch_size,
            return_traj=save_trajs,
        )
    click.echo(f"wrote {n_written}/{attempted} attempts -> {out}")
    if save_trajs:
        click.echo(f"wrote {batch_index} trajectory batches -> {trajectory_dir}")
    click.echo(f"  valid: {n_valid}/{attempted} | unique SMILES: {len(unique_smiles)}")


if __name__ == "__main__":
    cli()