{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# SchNet S2EF training example" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The purpose of this notebook is to demonstrate some of the basics of the Open Catalyst Project's (OCP) codebase and data. In this example, we will train a schnet model for predicting the energy and forces of a given structure (S2EF task). First, ensure you have installed the OCP ocp repo and all the dependencies according to the [README](https://github.com/Open-Catalyst-Project/ocp/blob/master/README.md)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Disclaimer: This notebook is for tutorial purposes, it is unlikely it will be practical to train baseline models on our larger datasets using this format. As a next step, we recommend trying the command line examples. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Imports" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "import torch\n", "import os\n", "from ocpmodels.trainers import ForcesTrainer\n", "from ocpmodels import models\n", "from ocpmodels.common import logger\n", "from ocpmodels.common.utils import setup_logging\n", "setup_logging()" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "# a simple sanity check that a GPU is available\n", "if torch.cuda.is_available():\n", " print(\"True\")\n", "else:\n", " print(\"False\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The essential steps for training an OCP model\n", "\n", "1) Download data\n", "\n", "2) Preprocess data (if necessary)\n", "\n", "3) Define or load a configuration (config), which includes the following\n", " \n", " - task\n", " - model\n", " - optimizer\n", " - dataset\n", " - trainer\n", "\n", "4) Train\n", "\n", "5) Depending on the model/task there might be intermediate relaxation step\n", "\n", "6) Predict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dataset" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This examples uses the LMDB generated from the following [tutorial](http://laikapack.cheme.cmu.edu/notebook/open-catalyst-project/mshuaibi/notebooks/projects/ocp/docs/source/tutorials/lmdb_dataset_creation.ipynb). Please run that notebook before moving on. Alternatively, if you have other LMDBs available you may specify that instead." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "# set the path to your local lmdb directory\n", "train_src = \"s2ef\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Define config" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For this example, we will explicitly define the config; however, a set of default config files exists in the config folder of this repository. Default config yaml files can easily be loaded with the `build_config` util (found in `ocp/ocpmodels/common/utils.py`). Loading a yaml config is preferrable when launching jobs from the command line. We have included our best models' config files [here](https://github.com/Open-Catalyst-Project/ocp/tree/master/configs/s2ef)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Task** " ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "task = {\n", " 'dataset': 'trajectory_lmdb', # dataset used for the S2EF task\n", " 'description': 'Regressing to energies and forces for DFT trajectories from OCP',\n", " 'type': 'regression',\n", " 'metric': 'mae',\n", " 'labels': ['potential energy'],\n", " 'grad_input': 'atomic forces',\n", " 'train_on_free_atoms': True,\n", " 'eval_on_free_atoms': True\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Model** - SchNet for this example" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "model = {\n", " 'name': 'schnet',\n", " 'hidden_channels': 1024, # if training is too slow for example purposes reduce the number of hidden channels\n", " 'num_filters': 256,\n", " 'num_interactions': 3,\n", " 'num_gaussians': 200,\n", " 'cutoff': 6.0\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Optimizer**" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "optimizer = {\n", " 'batch_size': 16, # if hitting GPU memory issues, lower this\n", " 'eval_batch_size': 8,\n", " 'num_workers': 8,\n", " 'lr_initial': 0.0001,\n", " 'scheduler': \"ReduceLROnPlateau\",\n", " 'mode': \"min\",\n", " 'factor': 0.8,\n", " 'patience': 3,\n", " 'max_epochs': 80,\n", " 'max_epochs': 1, # used for demonstration purposes\n", " 'force_coefficient': 100,\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Dataset**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For simplicity, `train_src` is used for all the train/val/test sets. Feel free to update with the actual S2EF val and test sets, but it does require additional downloads and preprocessing. If you desire to normalize your targets, `normalize_labels` must be set to `True` and corresponding `mean` and `stds` need to be specified. These values have been precomputed for you and can be found in any of the [`base.yml`](https://github.com/Open-Catalyst-Project/ocp/blob/master/configs/s2ef/20M/base.yml#L5-L9) config files." ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "dataset = [\n", "{'src': train_src, 'normalize_labels': False}, # train set \n", "{'src': train_src}, # val set (optional)\n", "{'src': train_src} # test set (optional - writes predictions to disk)\n", "]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Trainer**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use the `ForcesTrainer` for the S2EF and IS2RS tasks, and the `EnergyTrainer` for the IS2RE task " ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "amp: false\n", "cmd:\n", " checkpoint_dir: ./checkpoints/2021-09-04-08-51-28-SchNet-example\n", " commit: 98a06d8\n", " identifier: SchNet-example\n", " logs_dir: ./logs/tensorboard/2021-09-04-08-51-28-SchNet-example\n", " print_every: 5\n", " results_dir: ./results/2021-09-04-08-51-28-SchNet-example\n", " seed: 0\n", " timestamp_id: 2021-09-04-08-51-28-SchNet-example\n", "dataset:\n", " normalize_labels: false\n", " src: s2ef\n", "gpus: 1\n", "logger: tensorboard\n", "model: schnet\n", "model_attributes:\n", " cutoff: 6.0\n", " hidden_channels: 1024\n", " num_filters: 256\n", " num_gaussians: 200\n", " num_interactions: 3\n", "optim:\n", " batch_size: 16\n", " eval_batch_size: 8\n", " factor: 0.8\n", " force_coefficient: 100\n", " lr_initial: 0.0001\n", " max_epochs: 1\n", " mode: min\n", " num_workers: 8\n", " patience: 3\n", " scheduler: ReduceLROnPlateau\n", "slurm: {}\n", "task:\n", " dataset: trajectory_lmdb\n", " description: Regressing to energies and forces for DFT trajectories from OCP\n", " eval_on_free_atoms: true\n", " grad_input: atomic forces\n", " labels:\n", " - potential energy\n", " metric: mae\n", " train_on_free_atoms: true\n", " type: regression\n", "test_dataset:\n", " src: s2ef\n", "val_dataset:\n", " src: s2ef\n", "\n", "2021-09-04 08:51:37 (INFO): Loading dataset: trajectory_lmdb\n", "2021-09-04 08:51:37 (INFO): Loading model: schnet\n", "2021-09-04 08:51:37 (INFO): Loaded SchNet with 5704193 parameters.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "2021-09-04 08:51:37 (WARNING): Model gradient logging to tensorboard not yet supported.\n" ] } ], "source": [ "trainer = ForcesTrainer(\n", " task=task,\n", " model=model,\n", " dataset=dataset,\n", " optimizer=optimizer,\n", " identifier=\"SchNet-example\",\n", " run_dir=\"./\", # directory to save results if is_debug=False. Prediction files are saved here so be careful not to override!\n", " is_debug=False, # if True, do not save checkpoint, logs, or results\n", " is_vis=False,\n", " print_every=5,\n", " seed=0, # random seed to use\n", " logger=\"tensorboard\", # logger of choice (tensorboard and wandb supported)\n", " local_rank=0,\n", " amp=False, # use PyTorch Automatic Mixed Precision (faster training and less memory usage)\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Check the model" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "OCPDataParallel(\n", " (module): SchNet(hidden_channels=1024, num_filters=256, num_interactions=3, num_gaussians=200, cutoff=6.0)\n", ")\n" ] } ], "source": [ "print(trainer.model)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Train" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "scrolled": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2021-09-04 08:51:43 (INFO): forcesx_mae: 6.12e-01, forcesy_mae: 7.54e-01, forcesz_mae: 7.98e-01, forces_mae: 7.21e-01, forces_cos: -8.32e-03, forces_magnitude: 1.34e+00, energy_mae: 3.14e+01, energy_force_within_threshold: 0.00e+00, loss: 1.04e+02, lr: 1.00e-04, epoch: 1.25e-01, step: 5.00e+00\n", "2021-09-04 08:51:43 (INFO): forcesx_mae: 4.95e-01, forcesy_mae: 5.85e-01, forcesz_mae: 6.06e-01, forces_mae: 5.62e-01, forces_cos: -1.64e-03, forces_magnitude: 9.97e-01, energy_mae: 2.38e+01, energy_force_within_threshold: 0.00e+00, loss: 8.02e+01, lr: 1.00e-04, epoch: 2.50e-01, step: 1.00e+01\n", "2021-09-04 08:51:44 (INFO): forcesx_mae: 4.35e-01, forcesy_mae: 5.44e-01, forcesz_mae: 5.30e-01, forces_mae: 5.03e-01, forces_cos: 2.57e-02, forces_magnitude: 9.14e-01, energy_mae: 2.09e+01, energy_force_within_threshold: 0.00e+00, loss: 7.11e+01, lr: 1.00e-04, epoch: 3.75e-01, step: 1.50e+01\n", "2021-09-04 08:51:44 (INFO): forcesx_mae: 3.70e-01, forcesy_mae: 4.50e-01, forcesz_mae: 4.22e-01, forces_mae: 4.14e-01, forces_cos: 3.03e-03, forces_magnitude: 7.05e-01, energy_mae: 1.66e+01, energy_force_within_threshold: 0.00e+00, loss: 5.83e+01, lr: 1.00e-04, epoch: 5.00e-01, step: 2.00e+01\n", "2021-09-04 08:51:45 (INFO): forcesx_mae: 3.61e-01, forcesy_mae: 4.58e-01, forcesz_mae: 4.42e-01, forces_mae: 4.20e-01, forces_cos: 3.09e-02, forces_magnitude: 7.07e-01, energy_mae: 1.40e+01, energy_force_within_threshold: 0.00e+00, loss: 5.58e+01, lr: 1.00e-04, epoch: 6.25e-01, step: 2.50e+01\n", "2021-09-04 08:51:45 (INFO): forcesx_mae: 3.51e-01, forcesy_mae: 3.96e-01, forcesz_mae: 3.91e-01, forces_mae: 3.79e-01, forces_cos: 2.94e-02, forces_magnitude: 6.65e-01, energy_mae: 1.39e+01, energy_force_within_threshold: 0.00e+00, loss: 5.19e+01, lr: 1.00e-04, epoch: 7.50e-01, step: 3.00e+01\n", "2021-09-04 08:51:46 (INFO): forcesx_mae: 3.13e-01, forcesy_mae: 3.46e-01, forcesz_mae: 3.38e-01, forces_mae: 3.32e-01, forces_cos: 2.50e-02, forces_magnitude: 5.61e-01, energy_mae: 9.40e+00, energy_force_within_threshold: 0.00e+00, loss: 4.23e+01, lr: 1.00e-04, epoch: 8.75e-01, step: 3.50e+01\n", "2021-09-04 08:51:46 (INFO): forcesx_mae: 3.06e-01, forcesy_mae: 3.59e-01, forcesz_mae: 3.59e-01, forces_mae: 3.41e-01, forces_cos: 1.31e-02, forces_magnitude: 5.62e-01, energy_mae: 1.02e+01, energy_force_within_threshold: 0.00e+00, loss: 4.91e+01, lr: 1.00e-04, epoch: 1.00e+00, step: 4.00e+01\n", "2021-09-04 08:51:46 (INFO): Evaluating on val.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "device 0: 100%|██████████| 79/79 [00:01<00:00, 39.87it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "2021-09-04 08:51:48 (INFO): forcesx_mae: 0.2778, forcesy_mae: 0.3467, forcesz_mae: 0.3606, forces_mae: 0.3284, forces_cos: 0.0278, forces_magnitude: 0.5615, energy_mae: 12.4560, energy_force_within_threshold: 0.0000, loss: 44.8795, epoch: 1.0000\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "2021-09-04 08:51:49 (INFO): Predicting on test.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "device 0: 100%|██████████| 79/79 [00:01<00:00, 41.47it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "2021-09-04 08:51:51 (INFO): Writing results to ./results/2021-09-04-08-51-28-SchNet-example/s2ef_predictions.npz\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "trainer.train()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Load Checkpoint\n", "Once training has completed a `Trainer` class, by default, is loaded with the best checkpoint as determined by training or validation (if available) metrics. To load a `Trainer` class directly with a pretrained model, specify the `checkpoint_path` as defined by your previously trained model (`checkpoint_dir`):" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'./checkpoints/2021-09-04-08-51-28-SchNet-example/checkpoint.pt'" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "checkpoint_path = os.path.join(trainer.config[\"cmd\"][\"checkpoint_dir\"], \"checkpoint.pt\")\n", "checkpoint_path" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "amp: false\n", "cmd:\n", " checkpoint_dir: ./checkpoints/2021-09-04-08-51-28-SchNet-example\n", " commit: 98a06d8\n", " identifier: SchNet-example\n", " logs_dir: ./logs/tensorboard/2021-09-04-08-51-28-SchNet-example\n", " print_every: 10\n", " results_dir: ./results/2021-09-04-08-51-28-SchNet-example\n", " seed: 0\n", " timestamp_id: 2021-09-04-08-51-28-SchNet-example\n", "dataset:\n", " normalize_labels: false\n", " src: s2ef\n", "gpus: 1\n", "logger: tensorboard\n", "model: schnet\n", "model_attributes:\n", " cutoff: 6.0\n", " hidden_channels: 1024\n", " num_filters: 256\n", " num_gaussians: 200\n", " num_interactions: 3\n", "optim:\n", " batch_size: 16\n", " eval_batch_size: 8\n", " factor: 0.8\n", " force_coefficient: 100\n", " lr_initial: 0.0001\n", " max_epochs: 1\n", " mode: min\n", " num_workers: 8\n", " patience: 3\n", " scheduler: ReduceLROnPlateau\n", "slurm: {}\n", "task:\n", " dataset: trajectory_lmdb\n", " description: Regressing to energies and forces for DFT trajectories from OCP\n", " eval_on_free_atoms: true\n", " grad_input: atomic forces\n", " labels:\n", " - potential energy\n", " metric: mae\n", " train_on_free_atoms: true\n", " type: regression\n", "test_dataset:\n", " src: s2ef\n", "val_dataset:\n", " src: s2ef\n", "\n", "2021-09-04 08:51:51 (INFO): Loading dataset: trajectory_lmdb\n", "2021-09-04 08:51:51 (INFO): Loading model: schnet\n", "2021-09-04 08:51:51 (INFO): Loaded SchNet with 5704193 parameters.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "2021-09-04 08:51:51 (WARNING): Model gradient logging to tensorboard not yet supported.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "2021-09-04 08:51:51 (INFO): Loading checkpoint from: ./checkpoints/2021-09-04-08-51-28-SchNet-example/checkpoint.pt\n" ] } ], "source": [ "model = {\n", " 'name': 'schnet',\n", " 'hidden_channels': 1024, # if training is too slow for example purposes reduce the number of hidden channels\n", " 'num_filters': 256,\n", " 'num_interactions': 3,\n", " 'num_gaussians': 200,\n", " 'cutoff': 6.0\n", "}\n", "\n", "pretrained_trainer = ForcesTrainer(\n", " task=task,\n", " model=model,\n", " dataset=dataset,\n", " optimizer=optimizer,\n", " identifier=\"SchNet-example\",\n", " run_dir=\"./\", # directory to save results if is_debug=False. Prediction files are saved here so be careful not to override!\n", " is_debug=False, # if True, do not save checkpoint, logs, or results\n", " is_vis=False,\n", " print_every=10,\n", " seed=0, # random seed to use\n", " logger=\"tensorboard\", # logger of choice (tensorboard and wandb supported)\n", " local_rank=0,\n", " amp=False, # use PyTorch Automatic Mixed Precision (faster training and less memory usage)\n", ")\n", "\n", "pretrained_trainer.load_checkpoint(checkpoint_path=checkpoint_path)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Predict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If a test has been provided in your config, predictions are generated and written to disk automatically upon training completion. Otherwise, to make predictions on unseen data a `torch.utils.data` DataLoader object must be constructed. Here we reference our test set to make predictions on. Predictions are saved in `{results_file}.npz` in your `results_dir`." ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2021-09-04 08:51:51 (INFO): Predicting on test.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "device 0: 100%|██████████| 79/79 [00:01<00:00, 44.68it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "2021-09-04 08:51:53 (INFO): Writing results to ./results/2021-09-04-08-51-28-SchNet-example/s2ef_s2ef_results.npz\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# make predictions on the existing test_loader\n", "predictions = pretrained_trainer.predict(pretrained_trainer.test_loader, results_file=\"s2ef_results\", disable_tqdm=False)" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [ "energies = predictions[\"energy\"]\n", "forces = predictions[\"forces\"]" ] } ], "metadata": { "kernelspec": { "display_name": "ocp-models", "language": "python", "name": "ocp-models" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.10" } }, "nbformat": 4, "nbformat_minor": 4 }