class_docstr: The method class for GraphAF algorithm proposed in the paper `GraphAF: a Flow-based Autoregressive Model for Molecular Graph Generation <https://arxiv.org/abs/2001.09382>`_. This class provides interfaces for running random generation, property
  optimization, and constrained optimization with GraphAF. Please refer to the `example codes <https://github.com/divelab/DIG/tree/dig-stable/examples/ggraph/GraphAF>`_ for usage examples.
class_docstr_tok: ["The","method","class","for","GraphAF","algorithm","proposed","in","the","paper","`","GraphAF",":","a","Flow-based","Autoregressive","Model","for","Molecular","Graph","Generation","<","https",":","\/\/arxiv.org\/abs\/2001.09382",">","`","_",".","This","class","provides","interfaces","for","running","random","generation",",","property","optimization",",","and","constrained","optimization","with","GraphAF",".","Please","refer","to","the","`","example","codes","<","https",":","\/\/github.com\/divelab\/DIG\/tree\/dig-stable\/examples\/ggraph\/GraphAF",">","`","_","for","usage","examples","."]
docstr: Running training for random generation task.
  
  Args:
      loader: The data loader for loading training samples. It is supposed to use dig.ggraph.dataset.QM9/ZINC250k
          as the dataset class, and apply torch_geometric.data.DenseDataLoader to it to form the data loader.
      lr (float): The learning rate for training.
      wd (float): The weight decay factor for training.
      max_epochs (int): The maximum number of training epochs.
      model_conf_dict (dict): The python dict for configuring the model hyperparameters.
      save_interval (int): Indicate the frequency to save the model parameters to .pth files,
          *e.g.*, if save_interval=2, the model parameters will be saved for every 2 training epochs.
      save_dir (str): The directory to save the model parameters.
docstr_tok: ["Running","training","for","random","generation","task",".","Args",":","loader",":","The","data","loader","for","loading","training","samples",".","It","is","supposed","to","use","dig.ggraph.dataset.QM9\/ZINC250k","as","the","dataset","class",",","and","apply","torch_geometric.data.DenseDataLoader","to","it","to","form","the","data","loader",".","lr","(","float",")",":","The","learning","rate","for","training",".","wd","(","float",")",":","The","weight","decay","factor","for","training",".","max_epochs","(","int",")",":","The","maximum","number","of","training","epochs",".","model_conf_dict","(","dict",")",":","The","python","dict","for","configuring","the","model","hyperparameters",".","save_interval","(","int",")",":","Indicate","the","frequency","to","save","the","model","parameters","to",".pth","files",",","*","e.g",".","*",",","if","save_interval=2",",","the","model","parameters","will","be","saved","for","every","2","training","epochs",".","save_dir","(","str",")",":","The","directory","to","save","the","model","parameters","."]
code: def train_rand_gen(
      self,
      loader,
      lr,
      wd,
      max_epochs,
      model_conf_dict,
      save_interval,
      save_dir,
  ):
      r"""
      Running training for random generation task.
  
      Args:
          loader: The data loader for loading training samples. It is supposed to use dig.ggraph.dataset.QM9/ZINC250k
              as the dataset class, and apply torch_geometric.data.DenseDataLoader to it to form the data loader.
          lr (float): The learning rate for training.
          wd (float): The weight decay factor for training.
          max_epochs (int): The maximum number of training epochs.
          model_conf_dict (dict): The python dict for configuring the model hyperparameters.
          save_interval (int): Indicate the frequency to save the model parameters to .pth files,
              *e.g.*, if save_interval=2, the model parameters will be saved for every 2 training epochs.
          save_dir (str): The directory to save the model parameters.
      """
  
      self.get_model("rand_gen", model_conf_dict)
      self.model.train()
      optimizer = torch.optim.Adam(
          filter(lambda p: p.requires_grad, self.model.parameters()),
          lr=lr,
          weight_decay=wd,
      )
      if not os.path.isdir(save_dir):
          os.mkdir(save_dir)
  
      for epoch in range(1, max_epochs + 1):
          total_loss = 0
          for batch, data_batch in enumerate(loader):
              optimizer.zero_grad()
              inp_node_features = data_batch.x  # (B, N, node_dim)
              inp_adj_features = data_batch.adj  # (B, 4, N, N)
              if model_conf_dict["use_gpu"]:
                  inp_node_features = inp_node_features.cuda()
                  inp_adj_features = inp_adj_features.cuda()
  
              out_z, out_logdet = self.model(
                  inp_node_features, inp_adj_features
              )
              loss = self.model.log_prob(out_z, out_logdet)
              loss.backward()
              optimizer.step()
  
              total_loss += loss.to("cpu").item()
              print(
                  "Training iteration {} | loss {}".format(
                      batch, loss.to("cpu").item()
                  )
              )
  
          avg_loss = total_loss / (batch + 1)
          print("Training | Average loss {}".format(avg_loss))
  
          if epoch % save_interval == 0:
              torch.save(
                  self.model.state_dict(),
                  os.path.join(
                      save_dir, "rand_gen_ckpt_{}.pth".format(epoch)
                  ),
              )
  
file_path: DIG/dig/ggraph/method/GraphAF/graphaf.py
imports: import os
  import torch
  import torch.nn
  from rdkit import Chem
  from dig.ggraph.method import Generator
  from .model import GraphFlowModel, GraphFlowModel_rl, GraphFlowModel_con_rl
  from .train_utils import adjust_learning_rate, DataIterator
label_desc: Use image node_id 4 for calling the GraphAF obj's underlying member method code with example usage: obj.train_rand_gen(loader, lr, wd, max_epochs, model_conf_dict, save_interval, save_dir) without return types