### Install torch-molecule via pip Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/install.md Install the torch-molecule package using pip for a standard installation. ```bash pip install torch-molecule ``` -------------------------------- ### Install from Source Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/install.md Install the torch-molecule package after cloning the repository, using the setup.py file. ```bash pip install . ``` -------------------------------- ### Install Dependencies for Development Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/install.md Install all necessary dependencies from the requirements.txt file for development purposes. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Transformers Package Source: https://github.com/liugangcode/torch-molecule/blob/main/README.md Install the transformers package, required for models like HFPretrainedMolecularEncoder. ```bash pip install transformers ``` -------------------------------- ### Clone Repository for Source Installation Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/install.md Clone the torch-molecule repository from GitHub to install the latest version from source. ```bash git clone https://github.com/liugangcode/torch-molecule cd torch-molecule ``` -------------------------------- ### Editable Installation for Development Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/install.md Install the torch-molecule package in editable mode, allowing direct code modifications to take effect immediately. ```bash pip install -e . ``` -------------------------------- ### Install torch-scatter for Specific Models Source: https://github.com/liugangcode/torch-molecule/blob/main/README.md Install the torch-scatter package, which is required by certain models. Ensure you replace `${TORCH}` and `${CUDA}` with your PyTorch and CUDA versions. ```bash pip install torch-scatter -f https://data.pyg.org/whl/torch-${TORCH}+${CUDA}.html ``` ```bash pip install torch-scatter -f https://data.pyg.org/whl/torch-2.7.1+cu128.html ``` -------------------------------- ### Load QM9 Dataset Source: https://context7.com/liugangcode/torch-molecule/llms.txt Downloads and loads the QM9 dataset. Specify `local_dir` for storage and `target_cols` to select specific properties. Optionally return the local data path. ```python from torch_molecule.datasets import load_qm9 # Load default target (HOMO-LUMO gap) dataset = load_qm9(local_dir="torchmol_data") smiles_list = dataset.data # List[str], len=133885 property_array = dataset.target # np.ndarray, shape=(133885, 1) # Load multiple quantum chemical targets dataset = load_qm9( local_dir="torchmol_data", target_cols=["homo", "lumo", "gap"] ) smiles_list = dataset.data # 133885 SMILES strings property_array = dataset.target # shape=(133885, 3) print(f"Molecules: {len(smiles_list)}, Properties shape: {property_array.shape}") # Molecules: 133885, Properties shape: (133885, 3) # Optionally retrieve local file path dataset, path = load_qm9(local_dir="torchmol_data", return_local_data_path=True) print(path) # torchmol_data/qm9.csv ``` -------------------------------- ### Calculate ROC AUC Score Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/utils.md Computes ROC AUC scores for multi-task binary classification, handling NaN values. Use this to evaluate model performance across multiple tasks, with options to average scores or get individual task scores. ```python >>> y_true = np.array([[0, 1, np.nan], [1, 0, 1], [1, np.nan, 0], [0, 0, 1]]) >>> y_pred = np.array([[0.1, 0.8, 0.7], [0.9, 0.2, 0.8], [0.8, 0.7, 0.3], [0.2, 0.1, 0.9]]) >>> score = roc_auc_score(y_true, y_pred) >>> print(f"Average ROC AUC across valid tasks: {score:.3f}") ``` -------------------------------- ### init_weights Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/utils.md Initialize network weights. ```APIDOC ## init_weights ### Description Initialize network weights. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **net** (network) – The network to initialize. * **init_type** (*str* *,* *default='xavier'*) – The type of initialization. Options: normal | xavier | kaiming | orthogonal. * **init_gain** (*float* *,* *default=0.02*) – The gain factor for initialization. * **verbose** (*bool* *,* *default=False*) – If True, print initialization details. ### Returns None ### Return type None ### Raises None ``` -------------------------------- ### Train GREA Model for Molecular Property Prediction Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/example.md Demonstrates how to define search parameters and train a GREA model for molecular property prediction using autofit. Requires specifying task details, batch size, epochs, and evaluation criteria. ```python from torch_molecule import GREAMolecularPredictor, GNNMolecularPredictor from torch_molecule.utils.search import ParameterType, ParameterSpec # Define search parameters search_GNN = { "gnn_type": ParameterSpec(ParameterType.CATEGORICAL, ["gin-virtual", "gcn-virtual", "gin", "gcn"]), "norm_layer": ParameterSpec(ParameterType.CATEGORICAL, ["batch_norm", "layer_norm"]), "graph_pooling": ParameterSpec(ParameterType.CATEGORICAL, ["mean", "sum", "max"]), "augmented_feature": ParameterSpec(ParameterType.CATEGORICAL, ["maccs,morgan", "maccs", "morgan", None]), "num_layer": ParameterSpec(ParameterType.INTEGER, (2, 5)), "hidden_size": ParameterSpec(ParameterType.INTEGER, (64, 512)), "drop_ratio": ParameterSpec(ParameterType.FLOAT, (0.0, 0.5)), "learning_rate": ParameterSpec(ParameterType.LOG_FLOAT, (1e-5, 1e-2)), "weight_decay": ParameterSpec(ParameterType.LOG_FLOAT, (1e-10, 1e-3)), } search_GREA = { "gamma": ParameterSpec(ParameterType.FLOAT, (0.25, 0.75)), **search_GNN } # Train GREA model grea_model = GREAMolecularPredictor( num_task=num_task, task_type="regression", model_name="GREA_multitask", batch_size=BATCH_SIZE, epochs=N_epoch, evaluate_criterion='r2', evaluate_higher_better=True, verbose='progress_bar' ) # Fit the model X_train = ['C1=CC=CC=C1', 'C1=CC=CC=C1'] y_train = [[0.5], [1.5]] X_val = ['C1=CC=CC=C1', 'C1=CC=CC=C1'] y_val = [[0.5], [1.5]] N_trial = 100 grea_model.autofit( X_train=X_train.tolist(), y_train=y_train, X_val=X_val.tolist(), y_val=y_val, n_trials=N_trial, search_parameters=search_GREA ) ``` -------------------------------- ### Load Pretrained Model and Predict Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/example.md Loads a pretrained GREAMolecularPredictor model from a local directory and sets prediction parameters. Use this to initialize a model for molecular property prediction. ```python model_dir = "local_model_dir_to_save" model = GREAMolecularPredictor() model.load_model(f"{model_dir}/GREA_{task_name}.pt", repo_id=repo_id) model.set_params(verbose='progress_bar') predictions = model.predict(smiles_list) ``` -------------------------------- ### Create and Activate Conda Environment Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/install.md Create a new conda environment named 'torch_molecule' with Python 3.11.7 and then activate it. ```bash conda create --name torch_molecule python=3.11.7 conda activate torch_molecule ``` -------------------------------- ### load_qm9 Source: https://context7.com/liugangcode/torch-molecule/llms.txt Loads the QM9 quantum chemistry dataset from Hugging Face Hub. Supports loading default or multiple target properties. ```APIDOC ## load_qm9 — Load the QM9 quantum chemistry dataset ### Description Downloads and loads the QM9 dataset (~134k molecules) from Hugging Face Hub. Returns a `SMILESDataset` object with `.data` (SMILES list) and `.target` (numpy array of property values). Default target is `"gap"` (HOMO-LUMO gap), but multiple targets can be selected. ### Usage ```python from torch_molecule.datasets import load_qm9 # Load default target (HOMO-LUMO gap) dataset = load_qm9(local_dir="torchmol_data") smiles_list = dataset.data # List[str], len=133885 property_array = dataset.target # np.ndarray, shape=(133885, 1) # Load multiple quantum chemical targets dataset = load_qm9( local_dir="torchmol_data", target_cols=["homo", "lumo", "gap"] ) smiles_list = dataset.data # 133885 SMILES strings property_array = dataset.target # shape=(133885, 3) print(f"Molecules: {len(smiles_list)}, Properties shape: {property_array.shape}") # Molecules: 133885, Properties shape: (133885, 3) # Optionally retrieve local file path dataset, path = load_qm9(local_dir="torchmol_data", return_local_data_path=True) print(path) # torchmol_data/qm9.csv ``` ### Parameters - `local_dir` (str): Directory to save the dataset. - `target_cols` (List[str], optional): List of target columns to load. Defaults to `["gap"]`. - `return_local_data_path` (bool, optional): If True, returns the local data file path along with the dataset. Defaults to False. ``` -------------------------------- ### Load QM9 Dataset Source: https://github.com/liugangcode/torch-molecule/blob/main/README.md Load the QM9 dataset, which contains quantum chemical properties. The dataset is saved to the specified local directory. By default, it loads the 'gap' property, but custom target columns can be specified. ```python from torch_molecule.datasets import load_qm9 # local_dir is the local path where the dataset will be saved molecular_data = load_qm9(local_dir='torchmol_data') smiles_list, property_np_array = molecular_data.data, molecular_data.target # len(smiles_list): 133885 # Property array shape: (133885, 1) # load_qm9 returns the target "gap" by default, but you can adjust it by passing new target_cols target_cols = ['homo', 'lumo', 'gap'] molecular_data = load_qm9(local_dir='torchmol_data', target_cols=target_cols) smiles_list, property_np_array = molecular_data.data, molecular_data.target ``` -------------------------------- ### save / load Source: https://context7.com/liugangcode/torch-molecule/llms.txt Provides a unified interface for saving and loading models, automatically routing to local storage or Hugging Face Hub based on the arguments provided. ```APIDOC ## save / load — Unified save/load interface ### Description The `save()` and `load()` methods automatically route to local or Hugging Face storage based on the arguments provided. ### Method - `save(**kwargs)` - `load(**kwargs)` ### Parameters #### `save` - **path** (str) - Optional - Local file path to save the model. - **repo_id** (str) - Optional - Hugging Face repository ID to save the model to. - **task_id** (str) - Optional - Identifier for the task (required if `repo_id` is provided). - Other arguments are passed to `save_to_local` or `save_to_hf` as appropriate. #### `load` - **path** (str) - Optional - Local file path to load the model from. Takes priority over `repo_id`. - **repo_id** (str) - Optional - Hugging Face repository ID to load the model from (used if `path` is not provided or not found). - **local_cache** (str) - Optional - Path for caching when loading from `repo_id`. ### Request Example ```python from torch_molecule import GNNMolecularPredictor model = GNNMolecularPredictor(num_task=1, task_type="regression", epochs=5) # model.fit(...) # Save to both local and HF simultaneously model.save(path="local_model.pt", repo_id="your-user/my-model", task_id="demo") # Load: local path takes priority over repo_id model2 = GNNMolecularPredictor() model2.load(path="local_model.pt") # from local model2.load(repo_id="your-user/my-model") # from HF (when no local path) try: model2.load(path="nonexistent.pt") except FileNotFoundError as e: print(e) # No local file found at 'nonexistent.pt'. ``` ``` -------------------------------- ### Load Model from Hugging Face Hub Source: https://context7.com/liugangcode/torch-molecule/llms.txt Loads a model from a Hugging Face repository into a new session. Specify a local cache path for faster subsequent loads. ```python from torch_molecule import GREAMolecularPredictor # Load from HF Hub (works in a new process/session) loaded = GREAMolecularPredictor() loaded.load_from_hf( repo_id="your-username/my-grea-model", local_cache="grea_qm9_cached.pt" ) loaded.set_params(verbose="none") print(loaded.is_fitted_) # True ``` -------------------------------- ### Push Trained Model to Hugging Face Hub Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/example.md Shows how to train a GREAMolecularPredictor, evaluate it, and then push the trained model and its metrics to a Hugging Face repository. ```python from torch_molecule import GREAMolecularPredictor from sklearn.metrics import mean_absolute_error # huggingface repo_id including the user name and repo name repo_id = "user/repo_id" # Train and push a model to Hugging Face model = GREAMolecularPredictor() model.autofit( X_train=X.tolist(), y_train=y_train, X_val=X_val.tolist(), y_val=y_val, n_trials=100 ) output = model.predict(X_test.tolist()) mae = mean_absolute_error(y_test, output['prediction']) metrics = {'MAE': mae} model.push_to_huggingface( repo_id=repo_id, task_id=f"{task_name}", metrics=metrics, commit_message=f"Upload GREA_{task_name} model with metrics: {metrics}", private=False ) ``` -------------------------------- ### LocalCheckpointManager.load_model_from_local Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/utils.md Loads model weights and configuration from a specified local file path. ```APIDOC ## load_model_from_local ### Description Load model weights and configuration from a local file. ### Method `static` ### Parameters * **model_instance** – The model instance to load weights into. * **path** (*str*) – The local file path to load the model from. ``` -------------------------------- ### Project Structure Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/additional.md Displays the directory structure of the torch-molecule package. ```text torch_molecule ├── base ├── encoder ├── generator ├── nn ├── predictor └── utils ``` -------------------------------- ### autofit Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/predictor.md Automatically find the best hyperparameters using Optuna optimization. ```APIDOC ## autofit ### Description Automatically find the best hyperparameters using Optuna optimization. ### Method `autofit` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **X_train** (List[str]) - Required - Training data features. - **y_train** (List | ndarray | None) - Optional - Training data labels. - **X_val** (List[str] | None) - Optional - Validation data features. - **y_val** (List | ndarray | None) - Optional - Validation data labels. - **X_unlbl** (List[str] | None) - Optional - Unlabeled data features for semi-supervised learning. - **search_parameters** (Dict[str, ParameterSpec] | None) - Optional - Dictionary of hyperparameters to search over. - **n_trials** (int) - Optional - Number of optimization trials. Defaults to 10. ### Request Example ```python predictor.autofit(X_train=smiles_list, y_train=labels, search_parameters=search_space, n_trials=50) ``` ### Response #### Success Response (GNNMolecularPredictor) Returns a trained GNNMolecularPredictor model with optimized hyperparameters. #### Response Example ```python # Returns an instance of GNNMolecularPredictor ``` ``` -------------------------------- ### Initialize and Fit GREAMolecularPredictor Source: https://github.com/liugangcode/torch-molecule/blob/main/README.md Initialize a GREAMolecularPredictor model with specified parameters for multi-task regression. The 'verbose' option controls the output during training. ```python from torch_molecule import GREAMolecularPredictor split = int(0.8 * len(smiles_list)) grea = GREAMolecularPredictor( num_task=num_task, task_type="regression", evaluate_higher_better=False, verbose="progress_bar" #or "print_statement" recommended for jupyter notebooks, or "none" ) ``` -------------------------------- ### load_toxcast Source: https://context7.com/liugangcode/torch-molecule/llms.txt Downloads the ToxCast dataset, featuring 617 toxicity assays for multi-task classification. ```APIDOC ## load_toxcast — Load the ToxCast toxicity dataset ### Description Downloads ToxCast (617 toxicity assays) from the EPA via Hugging Face Hub for multi-task toxicity classification. ### Usage ```python from torch_molecule.datasets import load_toxcast dataset = load_toxcast(local_dir="torchmol_data") smiles_list = dataset.data labels = dataset.target # shape=(n_mols, 617), binary 0/1/NaN # Load with explicit target selection dataset = load_toxcast( local_dir="torchmol_data", target_cols=["TOX21_ARE_BLA_Agonist_viability", "TOX21_AhR_LUC_Agonist"] ) ``` ### Parameters - `local_dir` (str): Directory to save the dataset. - `target_cols` (List[str], optional): List of target columns to load. If not specified, all 617 targets are loaded. ``` -------------------------------- ### Load ToxCast Dataset Source: https://context7.com/liugangcode/torch-molecule/llms.txt Downloads the ToxCast dataset for toxicity prediction. Specify `local_dir` and optionally `target_cols` to select specific toxicity assays from the 617 available. ```python from torch_molecule.datasets import load_toxcast dataset = load_toxcast(local_dir="torchmol_data") smiles_list = dataset.data labels = dataset.target # shape=(n_mols, 617), binary 0/1/NaN # Load with explicit target selection dataset = load_toxcast( local_dir="torchmol_data", target_cols=["TOX21_ARE_BLA_Agonist_viability", "TOX21_AhR_LUC_Agonist"] ) ``` -------------------------------- ### Local checkpoint management with save_to_local/load_from_local Source: https://context7.com/liugangcode/torch-molecule/llms.txt Save and load complete model states, including architecture and trained weights, to/from local '.pt' files. This utility is essential for persisting trained models and resuming training or inference. ```python from torch_molecule import GREAMolecularPredictor from torch_molecule.datasets import load_qm9 dataset = load_qm9(local_dir="torchmol_data") smiles, props = dataset.data[:2000], dataset.target[:2000] model = GREAMolecularPredictor(num_task=1, task_type="regression", epochs=5) model.fit(smiles[:1600], props[:1600], smiles[1600:], props[1600:]) ``` -------------------------------- ### Unified Save/Load Interface Source: https://context7.com/liugangcode/torch-molecule/llms.txt Saves and loads models, automatically routing to local or Hugging Face storage based on provided arguments. Local paths take precedence during loading. ```python from torch_molecule import GNNMolecularPredictor model = GNNMolecularPredictor(num_task=1, task_type="regression", epochs=5) # model.fit(...) # Save to both local and HF simultaneously model.save(path="local_model.pt", repo_id="your-user/my-model", task_id="demo") # Load: local path takes priority over repo_id model2 = GNNMolecularPredictor() model2.load(path="local_model.pt") # from local model2.load(repo_id="your-user/my-model") # from HF (when no local path) try: model2.load(path="nonexistent.pt") except FileNotFoundError as e: print(e) # No local file found at 'nonexistent.pt'. ``` -------------------------------- ### Training and Generation Methods Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/generator.md Common methods for training and generating molecules supported by the generator models. ```APIDOC ## fit(X, **kwargs) ### Description Train the model on given data. ### Parameters - **X** (list or array) - Required - SMILES strings of the training data. - **kwargs** - Optional - Additional keyword arguments for training. ### Usage ```python model.fit(smiles_list) ``` ## generate(n_samples, **kwargs) ### Description Generate new molecules. ### Parameters - **n_samples** (int) - Required - The number of molecules to generate. - **kwargs** - Optional - Additional keyword arguments for generation (e.g., conditioning variables 'y'). ### Returns - list - A list of generated SMILES strings. ### Usage ```python smiles_list = model.generate(100) ``` ``` -------------------------------- ### Molecular Generation with DiGress (Diffusion Models) Source: https://context7.com/liugangcode/torch-molecule/llms.txt Utilize DigressMolecularGenerator for high-quality molecular graph generation using a discrete diffusion process. Requires fitting on SMILES strings before generation. ```python from torch_molecule import DigressMolecularGenerator from torch_molecule.datasets import load_zinc250k dataset = load_zinc250k(local_dir="torchmol_data") smiles = dataset.data[:5000] gen = DigressMolecularGenerator( timesteps=500, batch_size=64, epochs=500, verbose="progress_bar", ) gen.fit(smiles) generated = gen.generate(n_samples=50) print(f"Generated: {generated[:3]}") gen.save_to_local("digress_zinc.pt") ``` -------------------------------- ### Automatic Hyperparameter Tuning with Autofit Source: https://github.com/liugangcode/torch-molecule/blob/main/README.md Use `autofit` for hyperparameter tuning with a specified number of trials. Ensure training and validation data are prepared. ```python grea.autofit( X_train=smiles_list[:split], y_train=property_np_array[:split], X_val=smiles_list[split:] y_val=property_np_array[split:] n_trials=10, ) ``` -------------------------------- ### load_gasperm Source: https://context7.com/liugangcode/torch-molecule/llms.txt Loads the polymer gas permeability dataset, containing 6 regression targets for different gases. ```APIDOC ## load_gasperm — Load the polymer gas permeability dataset ### Description Loads the gas permeability dataset for polymeric materials (6 regression targets: He, H2, O2, N2, CO2, CH4 permeability). ### Usage ```python from torch_molecule.datasets import load_gasperm dataset = load_gasperm(local_dir="torchmol_data") polymer_smiles = dataset.data # List of polymer SMILES strings permeability = dataset.target # shape=(n_polymers, 6) ``` ### Parameters - `local_dir` (str): Directory to save the dataset. ``` -------------------------------- ### hf.get_existing_repo_data Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/utils.md Retrieves existing repository data, including whether the repository exists, its configuration, and its README content, from the Hugging Face Hub. ```APIDOC ## get_existing_repo_data ### Description Get existing repository data from HuggingFace Hub. ### Parameters * **repo_id** (*str*) – Repository ID * **token** (*Optional* *[**str* *]*) – HuggingFace token ### Returns Tuple containing (repo_exists, existing_config, existing_readme) ### Return type Tuple[bool, Dict, str] ``` -------------------------------- ### Save Model to Hugging Face Hub Source: https://context7.com/liugangcode/torch-molecule/llms.txt Pushes a trained model, along with metrics and metadata, to a Hugging Face repository. Requires a Hugging Face account and optionally a token. ```python from torch_molecule import GREAMolecularPredictor # Assume model is already trained model = GREAMolecularPredictor(num_task=1, task_type="regression", epochs=5) # model.fit(...) # fit first # Push to HF Hub model.save_to_hf( repo_id="your-username/my-grea-model", task_id="qm9_gap_prediction", metrics={\"mae\": 0.042, \"r2\": 0.91}, metadata_dict={\"dataset\": \"QM9\", \"target\": \"gap\"}, commit_message="Upload GREA QM9 gap model v1", private=False, hf_token=None, # uses HUGGING_FACE_HUB_TOKEN env var if None ) ``` -------------------------------- ### autofit Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/predictor.md Automatically finds the best hyperparameters for the model using Optuna optimization. ```APIDOC ## autofit ### Description Automatically find the best hyperparameters using Optuna optimization. ### Parameters * **X_train** (*List* *[**str* *]*) – Training set input molecular structures as SMILES strings * **y_train** (*Union* *[**List* *,* *np.ndarray* *]* *,* *optional*) – Training set target values for property prediction * **X_val** (*List* *[**str* *]* *,* *optional*) – Validation set input molecular structures as SMILES strings. If None, training data will be used for validation * **y_val** (*Union* *[**List* *,* *np.ndarray* *]* *,* *optional*) – Validation set target values. Required if X_val is provided * **X_unlbl** (*List* *[**str* *]* *,* *optional*) – Unlabeled set input molecular structures as SMILES strings. * **search_parameters** (*Dict* *[**str** *,* *ParameterSpec* *]* *,* *optional*) – Dictionary of hyperparameters to search over. * **n_trials** (*int*) – Number of optimization trials to run. Defaults to 10. ### Returns [GNNMolecularPredictor](#torch_molecule.predictor.gnn.modeling_gnn.GNNMolecularPredictor) – The fitted model with optimized hyperparameters. ``` -------------------------------- ### autofit Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/predictor.md Automatically finds the best hyperparameters for the model using Optuna optimization. ```APIDOC ## autofit ### Description Automatically find the best hyperparameters using Optuna optimization. ### Parameters * **gamma** (*float*, default=0.4) – GREA-specific parameter that penalize the size of the rationales. * **num_task** (*int*, default=1) – Number of prediction tasks. * **task_type** (*str*, default="regression") – Type of prediction task, either “regression” or “classification”. * **num_layer** (*int*, default=5) – Number of GNN layers. * **hidden_size** (*int*, default=300) – Dimension of hidden node features. * **gnn_type** (*str*, default="gin-virtual") – Type of GNN architecture to use. One of ["gin-virtual", "gcn-virtual", "gin", "gcn"]. * **drop_ratio** (*float*, default=0.5) – Dropout probability. * **norm_layer** (*str*, default="batch_norm") – Type of normalization layer to use. One of ["batch_norm", "layer_norm", "instance_norm", "graph_norm", "size_norm", "pair_norm"]. * **graph_pooling** (*str*, default="sum") – Method for aggregating node features to graph-level representations. One of ["sum", "mean", "max"]. * **augmented_feature** (*list* or *None*, default=None) – Additional molecular fingerprints to use as features. * **batch_size** (*int*, default=128) – Number of samples per batch for training. * **epochs** (*int*, default=500) – Maximum number of training epochs. * **learning_rate** (*float*, default=0.001) – Learning rate for optimizer. * **weight_decay** (*float*, default=0.0) – L2 regularization strength. * **grad_clip_value** (*float*, optional) – Maximum norm of gradients for gradient clipping. * **patience** (*int*, default=50) – Number of epochs to wait for improvement before early stopping. * **use_lr_scheduler** (*bool*, default=False) – Whether to use learning rate scheduler. * **scheduler_factor** (*float*, default=0.5) – Factor by which to reduce learning rate when plateau is reached. * **scheduler_patience** (*int*, default=5) – Number of epochs with no improvement after which learning rate will be reduced. * **loss_criterion** (*callable*, optional) – Loss function for training. * **evaluate_criterion** (*str* or *callable*, optional) – Metric for model evaluation. * **evaluate_higher_better** (*bool*, optional) – Whether higher values of the evaluation metric are better. * **verbose** (*bool*, default=False) – Whether to print progress information during training. * **device** (*torch.device* or *str*, optional) – Device to use for computation. * **model_name** (*str*, default="GREAMolecularPredictor") – Name of the model. * **search_parameters** (*Dict[str, ParameterSpec]*, optional) – Dictionary of parameters to search over. * **n_trials** (*int*, default=10) – Number of optimization trials. ### Returns * **self** – Fitted estimator ### Return type [GNNMolecularPredictor](#torch_molecule.predictor.gnn.modeling_gnn.GNNMolecularPredictor) ``` -------------------------------- ### autofit Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/predictor.md Automatically finds the best hyperparameters for the model using Optuna optimization. ```APIDOC ## autofit ### Description Automatically find the best hyperparameters using Optuna optimization. ### Method `autofit(X_train: List[str], y_train: List | ndarray | None, X_val: List[str] | None = None, y_val: List | ndarray | None = None, X_unlbl: List[str] | None = None, search_parameters: Dict[str, [ParameterSpec](utils.md#torch_molecule.utils.search.ParameterSpec)] | None = None, n_trials: int = 10)` ### Parameters * **X_train** (*List[str]*) - Training data features. * **y_train** (*List | ndarray | None*) - Training data labels. * **X_val** (*List[str] | None*) - Validation data features. * **y_val** (*List | ndarray | None*) - Validation data labels. * **X_unlbl** (*List[str] | None*) - Unlabeled data features for semi-supervised learning. * **search_parameters** (*Dict[str, [ParameterSpec](utils.md#torch_molecule.utils.search.ParameterSpec)] | None*) - Dictionary of hyperparameters to search over. * **n_trials** (*int*, default=10) - Number of optimization trials. ### Returns * **[GNNMolecularPredictor](#torch_molecule.predictor.gnn.modeling_gnn.GNNMolecularPredictor)** - The trained model with optimized hyperparameters. ``` -------------------------------- ### Load Gas Permeability Dataset Source: https://context7.com/liugangcode/torch-molecule/llms.txt Loads the polymer gas permeability dataset. The dataset contains 6 regression targets for different gases. ```python from torch_molecule.datasets import load_gasperm dataset = load_gasperm(local_dir="torchmol_data") polymer_smiles = dataset.data # List of polymer SMILES strings permeability = dataset.target # shape=(n_polymers, 6) ``` -------------------------------- ### get_params / set_params Source: https://context7.com/liugangcode/torch-molecule/llms.txt Provides scikit-learn compatible parameter management for models. Allows inspecting and changing hyperparameters after initialization. ```APIDOC ## get_params / set_params ### Description Provides scikit-learn compatible parameter management for models. Allows inspecting and changing hyperparameters after initialization. ### Methods #### `get_params()` Returns a dictionary of all hyperparameters for the model. #### `set_params(**params)` Sets the hyperparameters of the model. - **params** (dict): A dictionary of hyperparameters to set. ### Example ```python from torch_molecule import GNNMolecularPredictor model = GNNMolecularPredictor(num_task=1, task_type="regression", learning_rate=0.001) # Inspect all parameters params = model.get_params() print(params["learning_rate"]) # 0.001 print(params["gnn_type"]) # "gin-virtual" print(params["hidden_size"]) # 300 # Update parameters model.set_params(verbose="progress_bar", learning_rate=0.0005) print(model.learning_rate) # 0.0005 # Chaining is supported model.set_params(num_layer=3, drop_ratio=0.3).set_params(batch_size=64) ``` ``` -------------------------------- ### Initialize Network Weights Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/utils.md Initializes the weights of a neural network using specified initialization types like 'xavier' or 'kaiming'. This function is useful for setting up network layers before training. ```python :param net: :type net: network :param init_type: normal | xavier | kaiming | orthogonal :type init_type: str :param init_gain: :type init_gain: float ``` -------------------------------- ### Model Persistence Methods Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/generator.md Methods for saving and loading trained molecular generation models. ```APIDOC ## save_to_local(path) ### Description Save the trained model to a local file. ### Parameters - **path** (str) - Required - The file path to save the model. ## load_from_local(path) ### Description Load a trained model from a local file. ### Parameters - **path** (str) - Required - The file path to load the model from. ## save_to_hf(repo_id) ### Description Push the model to Hugging Face Hub. ### Parameters - **repo_id** (str) - Required - The repository ID on Hugging Face Hub. ### Note Not implemented for `GraphGAMolecularGenerator`. ## load_from_hf(repo_id, local_cache) ### Description Load a model from Hugging Face Hub and save it to a local file. ### Parameters - **repo_id** (str) - Required - The repository ID on Hugging Face Hub. - **local_cache** (str) - Required - The local path to cache the model. ### Note Not implemented for `GraphGAMolecularGenerator`. ## save(path, repo_id) ### Description Save the model to either local storage or Hugging Face Hub. ### Parameters - **path** (str) - Required - The local path for saving. - **repo_id** (str) - Required - The Hugging Face repository ID for Hub saving. ## load(path, repo_id) ### Description Load a model from either local storage or Hugging Face Hub. ### Parameters - **path** (str) - Required - The local path for loading. - **repo_id** (str) - Required - The Hugging Face repository ID for Hub loading. ``` -------------------------------- ### torch_molecule.utils.search.suggest_parameter Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/utils.md Suggests a parameter value using the appropriate Optuna suggest method based on the provided parameter specification. It handles different parameter types like categorical, float, integer, and log-float. ```APIDOC ## suggest_parameter ### Description Suggest a parameter value using the appropriate Optuna suggest method. ### Parameters - **trial** (optuna.Trial) - The Optuna trial object - **param_name** (str) - Name of the parameter - **param_spec** (ParameterSpec) - Specification of the parameter type and range ### Returns The suggested parameter value ### Return type Any ### Raises **ValueError** - If the parameter type is not recognized ``` -------------------------------- ### Save and Load Model Checkpoints Locally Source: https://github.com/liugangcode/torch-molecule/blob/main/README.md Save and load trained models to and from local files. Ensure a `GREAMolecularPredictor` instance is created before loading from a local path. ```python grea.save_to_local("qm9_grea.pt") new_model = GREAMolecularPredictor() new_model.load_from_local("qm9_grea.pt") ``` -------------------------------- ### save_to_local / load_from_local Source: https://context7.com/liugangcode/torch-molecule/llms.txt Utilities for saving and loading model checkpoints to and from local files. This includes architecture, hyperparameters, and trained weights. ```APIDOC ## save_to_local / load_from_local ### Description Utilities for saving and loading model checkpoints to and from local files. This includes architecture, hyperparameters, and trained weights. ### Methods #### `save_to_local(path: str)` Saves the model's state (architecture, hyperparameters, weights) to a local `.pt` file. - **path** (str): The path to the file where the model will be saved. #### `load_from_local(path: str)` Loads the model's state from a local `.pt` file. - **path** (str): The path to the file from which the model will be loaded. ### Example ```python from torch_molecule import GREAMolecularPredictor from torch_molecule.datasets import load_qm9 dataset = load_qm9(local_dir="torchmol_data") smiles, props = dataset.data[:2000], dataset.target[:2000] model = GREAMolecularPredictor(num_task=1, task_type="regression", epochs=5) model.fit(smiles[:1600], props[:1600], smiles[1600:], props[1600:]) # Save the model model.save_to_local("my_model.pt") # Load the model loaded_model = GREAMolecularPredictor() loaded_model.load_from_local("my_model.pt") ``` ``` -------------------------------- ### Molecular Generation with MolGPT (GPT-based) Source: https://context7.com/liugangcode/torch-molecule/llms.txt Generate molecules using MolGPTMolecularGenerator, which trains a GPT decoder on SMILES strings for auto-regressive generation. Fit the model on SMILES data before generating new molecules. ```python from torch_molecule import MolGPTMolecularGenerator from torch_molecule.datasets import load_zinc250k dataset = load_zinc250k(local_dir="torchmol_data") smiles = dataset.data[:10000] gen = MolGPTMolecularGenerator( batch_size=128, epochs=10, verbose="progress_bar", ) gen.fit(smiles) generated = gen.generate(n_samples=100) print(f"Generated {len(generated)} SMILES") print(generated[:3]) ``` -------------------------------- ### HuggingFaceCheckpointManager.load_model_from_hf Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/utils.md Loads a model from the Hugging Face Hub, saving it locally to a specified path first. ```APIDOC ## load_model_from_hf ### Description Load model from Hugging Face Hub, saving locally to path first. ### Method `static` ### Parameters * **model_instance** – The model instance to load weights into. * **repo_id** (*str*) – The Hugging Face repository ID. * **path** (*str*) – The local path to save the model. * **config_filename** (*str*, optional) – The name of the configuration file. Defaults to 'config.json'. ``` -------------------------------- ### Save and Load Model Checkpoints to Hugging Face Source: https://github.com/liugangcode/torch-molecule/blob/main/README.md Save trained models to Hugging Face for easy sharing and loading. Replace `user/repo_id` with your Hugging Face repository details. Ensure the `GREAMolecularPredictor` is initialized before loading. ```python from torch_molecule import GREAMolecularPredictor repo_id = "user/repo_id" # replace with your own Hugging Face username and repo_id # Save the trained model to Hugging Face grea.save_to_hf( repo_id=repo_id, task_id="qm9_grea", commit_message="Upload qm9_grea", private=False ) # Load a pretrained checkpoint from Hugging Face model = GREAMolecularPredictor() model.load_from_hf(repo_id=repo_id, local_cache=f"{model_dir}/GREA_{task_name}.pt") # Adjust model parameters and make predictions model.set_params(verbose='none') predictions = model.predict(smiles_list) ``` -------------------------------- ### Save and Load Model Locally Source: https://context7.com/liugangcode/torch-molecule/llms.txt Saves a trained model to a local file and reloads it in a new session. Ensure the model architecture is defined before loading. ```python model.save_to_local("my_grea_model.pt") # Reload in a new session (architecture is stored in checkpoint) loaded_model = GREAMolecularPredictor() loaded_model.load_from_local("my_grea_model.pt") loaded_model.set_params(verbose="none") preds = loaded_model.predict(smiles[:5])["prediction"] print(preds.shape) # (5, 1) ``` -------------------------------- ### autofit Source: https://github.com/liugangcode/torch-molecule/blob/main/docs/source/api/predictor.md Automatically find the best hyperparameters for the GNNMolecularPredictor model using Optuna optimization. This function searches through a defined parameter space to identify the optimal configuration for the model based on performance metrics. ```APIDOC ## autofit ### Description Automatically find the best hyperparameters using Optuna optimization. ### Method autofit ### Parameters #### Path Parameters - **X_train** (List[str]) - Required - Training set input molecular structures as SMILES strings - **y_train** (Union[List, np.ndarray] | None) - Required - Training set target values for property prediction - **X_val** (List[str] | None) - Optional - Validation set input molecular structures as SMILES strings. If None, training data will be used for validation - **y_val** (Union[List, np.ndarray] | None) - Optional - Validation set target values. Required if X_val is provided - **X_unlbl** (List[str] | None) - Optional - Unlabeled set input molecular structures as SMILES strings. - **search_parameters** (Dict[str, [ParameterSpec](#torch_molecule.utils.search.ParameterSpec)] | None) - Optional - Dictionary defining the hyperparameter search space. - **n_trials** (int) - Optional - Number of optimization trials to perform. Defaults to 10. ### Returns **self** - Fitted estimator ### Return type [GNNMolecularPredictor](#torch_molecule.predictor.gnn.modeling_gnn.GNNMolecularPredictor) ``` -------------------------------- ### save_to_hf / load_from_hf Source: https://context7.com/liugangcode/torch-molecule/llms.txt Integrates with the Hugging Face Hub to push trained models or load them from a repository. Supports storing metrics, metadata, and custom commit messages. ```APIDOC ## save_to_hf / load_from_hf — Hugging Face Hub integration ### Description Pushes trained models to a Hugging Face repository or loads them from one. Supports storing metrics, metadata, and custom commit messages alongside the model weights. ### Method - `save_to_hf(**kwargs)` - `load_from_hf(**kwargs)` ### Parameters #### `save_to_hf` - **repo_id** (str) - Required - The Hugging Face repository ID (e.g., "your-username/my-grea-model"). - **task_id** (str) - Required - An identifier for the task the model performs (e.g., "qm9_gap_prediction"). - **metrics** (dict) - Optional - A dictionary of metrics to store with the model (e.g., `{"mae": 0.042, "r2": 0.91}`). - **metadata_dict** (dict) - Optional - A dictionary of metadata to store with the model (e.g., `{"dataset": "QM9", "target": "gap"}`). - **commit_message** (str) - Optional - A custom commit message for the Hugging Face push. - **private** (bool) - Optional - Whether the repository should be private (default: `False`). - **hf_token** (str) - Optional - Hugging Face authentication token. Uses `HUGGING_FACE_HUB_TOKEN` environment variable if `None`. #### `load_from_hf` - **repo_id** (str) - Required - The Hugging Face repository ID to load the model from. - **local_cache** (str) - Optional - A path to store the cached model locally (e.g., "grea_qm9_cached.pt"). ### Request Example ```python from torch_molecule import GREAMolecularPredictor # Assume model is already trained model = GREAMolecularPredictor(num_task=1, task_type="regression", epochs=5) # model.fit(...) # fit first # Push to HF Hub model.save_to_hf( repo_id="your-username/my-grea-model", task_id="qm9_gap_prediction", metrics={"mae": 0.042, "r2": 0.91}, metadata_dict={"dataset": "QM9", "target": "gap"}, commit_message="Upload GREA QM9 gap model v1", private=False, hf_token=None, # uses HUGGING_FACE_HUB_TOKEN env var if None ) # Load from HF Hub (works in a new process/session) loaded = GREAMolecularPredictor() loaded.load_from_hf( repo_id="your-username/my-grea-model", local_cache="grea_qm9_cached.pt" ) loaded.set_params(verbose="none") print(loaded.is_fitted_) # True ``` ```