├── .gitignore ├── setup.sh ├── README.md ├── src ├── mlp.py ├── solver.py ├── config.py ├── mk_problem.py ├── neurosat.py ├── eval.py ├── data_maker.py └── train.py ├── run_eval.sh ├── run_sr200to500.sh ├── run_sr3to10.sh ├── run_sr10to40.sh ├── run_sr40to100.sh └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.pkl 2 | *.log 3 | *.tar 4 | *.bak 5 | *.pyc 6 | 7 | -------------------------------------------------------------------------------- /setup.sh: -------------------------------------------------------------------------------- 1 | cd src 2 | git clone https://github.com/liffiton/PyMiniSolvers.git 3 | cd PyMiniSolvers 4 | make 5 | cd ../.. 6 | 7 | mkdir data model log 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NeuroSAT 2 | 3 | A pytorch implementation of NeuraSAT([github](https://github.com/dselsam/neurosat), [paper](https://arxiv.org/abs/1802.03685)) 4 | 5 | In this implementation, we use SR(U(10, 40)) for training and SR(40) for testing, achieving the same accuracy 85% as in the original paper. The model was trained on a single K40 gpu for ~3 days following the parameters in the original paper. 6 | -------------------------------------------------------------------------------- /src/mlp.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | class MLP(nn.Module): 5 | def __init__(self, in_dim, hidden_dim, out_dim): 6 | super(MLP, self).__init__() 7 | self.l1 = nn.Linear(in_dim, hidden_dim) 8 | self.l2 = nn.Linear(hidden_dim, hidden_dim) 9 | self.l3 = nn.Linear(hidden_dim, out_dim) 10 | 11 | def forward(self, x): 12 | x = self.l1(x) 13 | x = self.l2(x) 14 | x = self.l3(x) 15 | 16 | return x 17 | 18 | -------------------------------------------------------------------------------- /run_eval.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | #PBS -N neurosat_eval_sr40 4 | #PBS -l nodes=1:ppn=1:gpus=1 5 | #PBS -o $PBS_JOBID.o 6 | #PBS -e $PBS_JOBID.e 7 | #PBS -d /home/zhangfan-mff/projects/neurosat/pytorch_neurosat/ 8 | 9 | python src/eval.py \ 10 | --task-name 'neurosat_eval_sr40' \ 11 | --dim 128 \ 12 | --n_rounds 1024 \ 13 | --restore '/home/zhangfan-mff/projects/neurosat/pytorch_neurosat/model/neurosat_3rd_rnd_sr10to40_ep200_nr26_d128.pth.tar' \ 14 | --data-dir '/home/zhangfan-mff/projects/neurosat/tf_neurosat/data/eval/40/' 15 | -------------------------------------------------------------------------------- /run_sr200to500.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | #PBS -N neurosat_sr200t500 4 | #PBS -l nodes=1:ppn=1:gpus=1 5 | #PBS -o $PBS_JOBID.o 6 | #PBS -e $PBS_JOBID.e 7 | #PBS -d /home/zhangfan-mff/projects/neurosat/pytorch_neurosat/ 8 | 9 | python src/train.py \ 10 | --task-name 'neurosat' \ 11 | --dim 128 \ 12 | --n_rounds 64 \ 13 | --epochs 500 \ 14 | --n_pairs 50000 \ 15 | --max_nodes_per_batch 15000 \ 16 | --gen_log '/home/zhangfan-mff/projects/neurosat/pytorch_neurosat/log/data_maker_sr200t500.log' \ 17 | --min_n 200 \ 18 | --max_n 500 \ 19 | --val-file 'val_v500_vpb15000_b2564.pkl' 20 | -------------------------------------------------------------------------------- /run_sr3to10.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | #PBS -N neurosat_sr3t10 4 | #PBS -l nodes=1:ppn=1:gpus=1 5 | #PBS -o $PBS_JOBID.o 6 | #PBS -e $PBS_JOBID.e 7 | #PBS -d /home/zhangfan-mff/projects/neurosat/pytorch_neurosat/ 8 | 9 | python src/train.py \ 10 | --task-name 'neurosat_No2' \ 11 | --dim 128 \ 12 | --n_rounds 26 \ 13 | --epochs 10 \ 14 | --n_pairs 100000 \ 15 | --max_nodes_per_batch 12000 \ 16 | --gen_log '/home/zhangfan-mff/projects/neurosat/pytorch_neurosat/log/data_maker_sr3t10.log' \ 17 | --min_n 3 \ 18 | --max_n 10 \ 19 | --train-file 'train_v3t10_vpb12000_b3001.pkl' \ 20 | --val-file 'val_v10_vpb12000_b148.pkl' 21 | -------------------------------------------------------------------------------- /run_sr10to40.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | #PBS -N neurosat_sr10t40 4 | #PBS -l nodes=1:ppn=1:gpus=1 5 | #PBS -o $PBS_JOBID.o 6 | #PBS -e $PBS_JOBID.e 7 | #PBS -d /home/zhangfan-mff/projects/neurosat/pytorch_neurosat/ 8 | 9 | python src/train.py \ 10 | --task-name 'neurosat_4th_rnd' \ 11 | --dim 128 \ 12 | --n_rounds 26 \ 13 | --epochs 200 \ 14 | --n_pairs 100000 \ 15 | --max_nodes_per_batch 12000 \ 16 | --gen_log '/home/zhangfan-mff/projects/neurosat/pytorch_neurosat/log/data_maker_sr10t40.log' \ 17 | --min_n 10 \ 18 | --max_n 40 \ 19 | --restore '/home/zhangfan-mff/projects/neurosat/pytorch_neurosat/model/neurosat_3rd_rnd_sr10to40_ep200_nr26_d128.pth.tar' \ 20 | --val-file 'val_v40_vpb12000_b2604.pkl' 21 | -------------------------------------------------------------------------------- /run_sr40to100.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | #PBS -N neurosat_sr40t100 4 | #PBS -l nodes=1:ppn=1:gpus=1 5 | #PBS -o $PBS_JOBID.o 6 | #PBS -e $PBS_JOBID.e 7 | #PBS -d /home/zhangfan-mff/projects/neurosat/pytorch_neurosat/ 8 | 9 | python src/train.py \ 10 | --task-name 'neurosat_3rd_rnd' \ 11 | --dim 128 \ 12 | --n_rounds 32 \ 13 | --epochs 200 \ 14 | --n_pairs 100000 \ 15 | --max_nodes_per_batch 12000 \ 16 | --gen_log '/home/zhangfan-mff/projects/neurosat/pytorch_neurosat/log/data_maker_sr40t100.log' \ 17 | --min_n 40 \ 18 | --max_n 100 \ 19 | --restore '/home/zhangfan-mff/projects/neurosat/pytorch_neurosat/model/neurosat_2nd_rnd_sr40to100_ep200_nr32_d128_last.pth.tar' \ 20 | --val-file 'val_v100_vpb12000_b1284.pkl' 21 | -------------------------------------------------------------------------------- /src/solver.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Daniel Selsam. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # ============================================================================== 15 | 16 | import PyMiniSolvers.minisolvers as minisolvers 17 | 18 | def solve_sat(n_vars, iclauses): 19 | solver = minisolvers.MinisatSolver() 20 | for i in range(n_vars): solver.new_var(dvar=True) 21 | for iclause in iclauses: solver.add_clause(iclause) 22 | is_sat = solver.solve() 23 | stats = solver.get_stats() 24 | return is_sat, stats 25 | -------------------------------------------------------------------------------- /src/config.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | parser = argparse.ArgumentParser() 4 | parser.add_argument('--task-name', type=str, default='neurosat', help='task name') 5 | 6 | parser.add_argument('--dim', type=int, default=128, help='Dimension of variable and clause embeddings') 7 | parser.add_argument('--n_rounds', type=int, default=26, help='Number of rounds of message passing') 8 | parser.add_argument('--epochs', type=int, default=10) 9 | 10 | parser.add_argument('--n_pairs', action='store', type=int) 11 | parser.add_argument('--max_nodes_per_batch', action='store', type=int) 12 | parser.add_argument('--gen_log', type=str, default='/home/zhangfan-mff/projects/neurosat/pytorch_neurosat/log/data_maker.log') 13 | parser.add_argument('--min_n', type=int, default=10, help='min number of variables used for training') 14 | parser.add_argument('--max_n', type=int, default=40, help='max number of variables used for training') 15 | parser.add_argument('--p_k_2', action='store', dest='p_k_2', type=float, default=0.3) 16 | parser.add_argument('--p_geo', action='store', dest='p_geo', type=float, default=0.4) 17 | parser.add_argument('--py_seed', action='store', dest='py_seed', type=int, default=None) 18 | parser.add_argument('--np_seed', action='store', dest='np_seed', type=int, default=None) 19 | parser.add_argument('--one', action='store', dest='one', type=int, default=0) 20 | 21 | parser.add_argument('--log-dir', type=str, default='/home/zhangfan-mff/projects/neurosat/pytorch_neurosat/log/', help='log folder dir') 22 | parser.add_argument('--model-dir', type=str, default='/home/zhangfan-mff/projects/neurosat/pytorch_neurosat/model/', help='model folder dir') 23 | parser.add_argument('--data-dir', type=str, default='/home/zhangfan-mff/projects/neurosat/pytorch_neurosat/data/', help='data folder dir') 24 | parser.add_argument('--restore', type=str, default=None, help='continue train from model') 25 | 26 | parser.add_argument('--train-file', type=str, default=None, help='train file dir') 27 | parser.add_argument('--val-file', type=str, default=None, help='val file dir') 28 | 29 | -------------------------------------------------------------------------------- /src/mk_problem.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Daniel Selsam. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # ============================================================================== 15 | 16 | import numpy as np 17 | import math 18 | 19 | # TODO(dhs): duplication 20 | def ilit_to_var_sign(x): 21 | assert(abs(x) > 0) 22 | var = abs(x) - 1 23 | sign = x < 0 24 | return var, sign 25 | 26 | # TODO(dhs): duplication 27 | def ilit_to_vlit(x, n_vars): 28 | assert(x != 0) 29 | var, sign = ilit_to_var_sign(x) 30 | if sign: return var + n_vars 31 | else: return var 32 | 33 | class Problem(object): 34 | def __init__(self, n_vars, iclauses, is_sat, n_cells_per_batch, all_dimacs): 35 | self.n_vars = n_vars 36 | self.n_lits = 2 * n_vars 37 | self.n_clauses = len(iclauses) 38 | 39 | self.n_cells = sum(n_cells_per_batch) 40 | self.n_cells_per_batch = n_cells_per_batch 41 | 42 | self.is_sat = is_sat 43 | self.compute_L_unpack(iclauses) 44 | 45 | # will be a list of None for training problems 46 | self.dimacs = all_dimacs 47 | 48 | def compute_L_unpack(self, iclauses): 49 | self.L_unpack_indices = np.zeros([self.n_cells, 2], dtype=np.int) 50 | cell = 0 51 | for clause_idx, iclause in enumerate(iclauses): 52 | vlits = [ilit_to_vlit(x, self.n_vars) for x in iclause] 53 | for vlit in vlits: 54 | self.L_unpack_indices[cell, :] = [vlit, clause_idx] 55 | cell += 1 56 | 57 | assert(cell == self.n_cells) 58 | 59 | def shift_ilit(x, offset): 60 | assert(x != 0) 61 | if x > 0: return x + offset 62 | else: return x - offset 63 | 64 | def shift_iclauses(iclauses, offset): 65 | return [[shift_ilit(x, offset) for x in iclause] for iclause in iclauses] 66 | 67 | def mk_batch_problem(problems): 68 | all_iclauses = [] 69 | all_is_sat = [] 70 | all_n_cells = [] 71 | all_dimacs = [] 72 | offset = 0 73 | 74 | prev_n_vars = None 75 | for dimacs, n_vars, iclauses, is_sat in problems: 76 | assert(prev_n_vars is None or n_vars == prev_n_vars) 77 | prev_n_vars = n_vars 78 | 79 | all_iclauses.extend(shift_iclauses(iclauses, offset)) 80 | all_is_sat.append(is_sat) 81 | all_n_cells.append(sum([len(iclause) for iclause in iclauses])) 82 | all_dimacs.append(dimacs) 83 | offset += n_vars 84 | 85 | return Problem(offset, all_iclauses, all_is_sat, all_n_cells, all_dimacs) 86 | -------------------------------------------------------------------------------- /src/neurosat.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | from mlp import MLP 5 | 6 | class NeuroSAT(nn.Module): 7 | def __init__(self, args): 8 | super(NeuroSAT, self).__init__() 9 | self.args = args 10 | 11 | self.init_ts = torch.ones(1) 12 | self.init_ts.requires_grad = False 13 | 14 | self.L_init = nn.Linear(1, args.dim) 15 | self.C_init = nn.Linear(1, args.dim) 16 | 17 | self.L_msg = MLP(self.args.dim, self.args.dim, self.args.dim) 18 | self.C_msg = MLP(self.args.dim, self.args.dim, self.args.dim) 19 | 20 | self.L_update = nn.LSTM(self.args.dim*2, self.args.dim) 21 | # self.L_norm = nn.LayerNorm(self.args.dim) 22 | self.C_update = nn.LSTM(self.args.dim, self.args.dim) 23 | # self.C_norm = nn.LayerNorm(self.args.dim) 24 | 25 | self.L_vote = MLP(self.args.dim, self.args.dim, 1) 26 | 27 | self.denom = torch.sqrt(torch.Tensor([self.args.dim])) 28 | 29 | def forward(self, problem): 30 | n_vars = problem.n_vars 31 | n_lits = problem.n_lits 32 | n_clauses = problem.n_clauses 33 | n_probs = len(problem.is_sat) 34 | # print(n_vars, n_lits, n_clauses, n_probs) 35 | 36 | ts_L_unpack_indices = torch.Tensor(problem.L_unpack_indices).t().long() 37 | 38 | init_ts = self.init_ts.cuda() 39 | # 1 x n_lits x dim & 1 x n_clauses x dim 40 | L_init = self.L_init(init_ts).view(1, 1, -1) 41 | # print(L_init.shape) 42 | L_init = L_init.repeat(1, n_lits, 1) 43 | C_init = self.C_init(init_ts).view(1, 1, -1) 44 | # print(C_init.shape) 45 | C_init = C_init.repeat(1, n_clauses, 1) 46 | 47 | # print(L_init.shape, C_init.shape) 48 | 49 | L_state = (L_init, torch.zeros(1, n_lits, self.args.dim).cuda()) 50 | C_state = (C_init, torch.zeros(1, n_clauses, self.args.dim).cuda()) 51 | L_unpack = torch.sparse.FloatTensor(ts_L_unpack_indices, torch.ones(problem.n_cells), torch.Size([n_lits, n_clauses])).to_dense().cuda() 52 | 53 | # print(ts_L_unpack_indices.shape) 54 | 55 | for _ in range(self.args.n_rounds): 56 | # n_lits x dim 57 | L_hidden = L_state[0].squeeze(0) 58 | L_pre_msg = self.L_msg(L_hidden) 59 | # (n_clauses x n_lits) x (n_lits x dim) = n_clauses x dim 60 | LC_msg = torch.matmul(L_unpack.t(), L_pre_msg) 61 | # print(L_hidden.shape, L_pre_msg.shape, LC_msg.shape) 62 | 63 | _, C_state= self.C_update(LC_msg.unsqueeze(0), C_state) 64 | # print('C_state',C_state[0].shape, C_state[1].shape) 65 | 66 | # n_clauses x dim 67 | C_hidden = C_state[0].squeeze(0) 68 | C_pre_msg = self.C_msg(C_hidden) 69 | # (n_lits x n_clauses) x (n_clauses x dim) = n_lits x dim 70 | CL_msg = torch.matmul(L_unpack, C_pre_msg) 71 | # print(C_hidden.shape, C_pre_msg.shape, CL_msg.shape) 72 | 73 | _, L_state= self.L_update(torch.cat([CL_msg, self.flip(L_state[0].squeeze(0), n_vars)], dim=1).unsqueeze(0), L_state) 74 | # print('L_state',C_state[0].shape, C_state[1].shape) 75 | 76 | logits = L_state[0].squeeze(0) 77 | clauses = C_state[0].squeeze(0) 78 | 79 | # print(logits.shape, clauses.shape) 80 | vote = self.L_vote(logits) 81 | # print('vote', vote.shape) 82 | vote_join = torch.cat([vote[:n_vars, :], vote[n_vars:, :]], dim=1) 83 | # print('vote_join', vote_join.shape) 84 | self.vote = vote_join 85 | vote_join = vote_join.view(n_probs, -1, 2).view(n_probs, -1) 86 | vote_mean = torch.mean(vote_join, dim=1) 87 | # print('mean', vote_mean.shape) 88 | return vote_mean 89 | 90 | def flip(self, msg, n_vars): 91 | return torch.cat([msg[n_vars:2*n_vars, :], msg[:n_vars, :]], dim=0) 92 | 93 | -------------------------------------------------------------------------------- /src/eval.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import pickle 3 | import os 4 | import time 5 | from tqdm import tqdm 6 | 7 | import numpy as np 8 | 9 | import torch 10 | import torch.nn as nn 11 | import torch.optim as optim 12 | 13 | from neurosat import NeuroSAT 14 | from data_maker import generate 15 | import mk_problem 16 | 17 | from config import parser 18 | 19 | def load_model(args, log_file=None): 20 | net = NeuroSAT(args) 21 | net = net.cuda() 22 | if args.restore: 23 | if log_file is not None: 24 | print('restoring from', args.restore, file=log_file, flush=True) 25 | model = torch.load(args.restore) 26 | net.load_state_dict(model['state_dict']) 27 | 28 | return net 29 | 30 | def predict(net, data): 31 | net.eval() 32 | outputs = net(data) 33 | probs = net.vote 34 | preds = torch.where(outputs>0.5, torch.ones(outputs.shape).cuda(), torch.zeros(outputs.shape).cuda()) 35 | return preds.cpu().detach().numpy(), probs.cpu().detach().numpy() 36 | 37 | if __name__ == '__main__': 38 | args = parser.parse_args() 39 | log_file = open(os.path.join(args.log_dir, args.task_name+'.log'), 'a+') 40 | net = load_model(args) 41 | 42 | TP, TN, FN, FP = 0, 0, 0, 0 43 | times = [] 44 | for _ in os.listdir(args.data_dir): 45 | with open(os.path.join(args.data_dir, _), 'rb') as f: 46 | xs = pickle.load(f) 47 | 48 | for x in xs: 49 | start_time = time.time() 50 | preds, probs = predict(net, x) 51 | end_time = time.time() 52 | duration = (end_time - start_time) * 1000 53 | times.append(duration) 54 | 55 | target = np.array(x.is_sat) 56 | TP += int(((preds == 1) & (target == 1)).sum()) 57 | TN += int(((preds == 0) & (target == 0)).sum()) 58 | FN += int(((preds == 0) & (target == 1)).sum()) 59 | FP += int(((preds == 1) & (target == 0)).sum()) 60 | 61 | num_cases = TP + TN + FN + FP 62 | desc = "%d rnds: tot time %.2f ms for %d cases, avg time: %.2f ms; the pred acc is %.2f, in which TP: %.2f, TN: %.2f, FN: %.2f, FP: %.2f" \ 63 | % (args.n_rounds, sum(times), len(times), sum(times)*1.0/len(times), (TP + TN)*1.0/num_cases, TP*1.0/num_cases, TN*1.0/num_cases, FN*1.0/num_cases, FP*1.0/num_cases) 64 | print(desc, file=log_file, flush=True) 65 | 66 | 67 | ''' 68 | for epoch in range(start_epoch, args.epochs): 69 | if args.train_file is None: 70 | print('generate data online', file=log_file, flush=True) 71 | train = generate(args) 72 | 73 | print('==> %d/%d epoch, previous best: %.3f' % (epoch+1, args.epochs, best_acc)) 74 | print('==> %d/%d epoch, previous best: %.3f' % (epoch+1, args.epochs, best_acc), file=log_file, flush=True) 75 | print('==> %d/%d epoch, previous best: %.3f' % (epoch+1, args.epochs, best_acc), file=detail_log_file, flush=True) 76 | train_bar = tqdm(train) 77 | TP, TN, FN, FP = torch.zeros(1).long(), torch.zeros(1).long(), torch.zeros(1).long(), torch.zeros(1).long() 78 | desc += 'acc: %.3f, TP: %.3f, TN: %.3f, FN: %.3f, FP: %.3f' % ((TP.item()+TN.item())*1.0/TOT.item(), TP.item()*1.0/TOT.item(), TN.item()*1.0/TOT.item(), FN.item()*1.0/TOT.item(), FP.item()*1.0/TOT.item()) 79 | # train_bar.set_description(desc) 80 | if (_ + 1) % 100 == 0: 81 | print(desc, file=detail_log_file, flush=True) 82 | print(desc, file=log_file, flush=True) 83 | 84 | val_bar = tqdm(val) 85 | TP, TN, FN, FP = torch.zeros(1).long(), torch.zeros(1).long(), torch.zeros(1).long(), torch.zeros(1).long() 86 | for _, prob in enumerate(val_bar): 87 | optim.zero_grad() 88 | outputs = net(prob) 89 | target = torch.Tensor(prob.is_sat).cuda().float() 90 | # print(outputs.shape, target.shape) 91 | # print(outputs, target) 92 | outputs = sigmoid(outputs) 93 | preds = torch.where(outputs>0.5, torch.ones(outputs.shape).cuda(), torch.zeros(outputs.shape).cuda()) 94 | 95 | TP += (preds.eq(1) & target.eq(1)).cpu().sum() 96 | TN += (preds.eq(0) & target.eq(0)).cpu().sum() 97 | FN += (preds.eq(0) & target.eq(1)).cpu().sum() 98 | FP += (preds.eq(1) & target.eq(0)).cpu().sum() 99 | TOT = TP + TN + FN + FP 100 | 101 | desc = 'acc: %.3f, TP: %.3f, TN: %.3f, FN: %.3f, FP: %.3f' % ((TP.item()+TN.item())*1.0/TOT.item(), TP.item()*1.0/TOT.item(), TN.item()*1.0/TOT.item(), FN.item()*1.0/TOT.item(), FP.item()*1.0/TOT.item()) 102 | # val_bar.set_description(desc) 103 | if (_ + 1) % 100 == 0: 104 | print(desc, file=detail_log_file, flush=True) 105 | print(desc, file=log_file, flush=True) 106 | 107 | acc = (TP.item() + TN.item()) * 1.0 / TOT.item() 108 | torch.save({'epoch': epoch+1, 'acc': acc, 'state_dict': net.state_dict()}, os.path.join(args.model_dir, task_name+'_last.pth.tar')) 109 | ''' 110 | -------------------------------------------------------------------------------- /src/data_maker.py: -------------------------------------------------------------------------------- 1 | import math 2 | import os 3 | import numpy as np 4 | import random 5 | import pickle 6 | import sys 7 | import argparse 8 | import PyMiniSolvers.minisolvers as minisolvers 9 | from solver import solve_sat 10 | from mk_problem import mk_batch_problem 11 | 12 | def generate_k_iclause(n, k): 13 | vs = np.random.choice(n, size=min(n, k), replace=False) 14 | return [v + 1 if random.random() < 0.5 else -(v + 1) for v in vs] 15 | 16 | def gen_iclause_pair(args, n): 17 | solver = minisolvers.MinisatSolver() 18 | for i in range(n): solver.new_var(dvar=True) 19 | 20 | iclauses = [] 21 | 22 | while True: 23 | k_base = 1 if random.random() < args.p_k_2 else 2 24 | k = k_base + np.random.geometric(args.p_geo) 25 | iclause = generate_k_iclause(n, k) 26 | 27 | solver.add_clause(iclause) 28 | is_sat = solver.solve() 29 | if is_sat: 30 | iclauses.append(iclause) 31 | else: 32 | break 33 | 34 | iclause_unsat = iclause 35 | iclause_sat = [- iclause_unsat[0] ] + iclause_unsat[1:] 36 | return n, iclauses, iclause_unsat, iclause_sat 37 | 38 | def generate(args): 39 | f = open(args.gen_log, 'w') 40 | 41 | n_cnt = args.max_n - args.min_n + 1 42 | problems_per_n = args.n_pairs * 1.0 / n_cnt 43 | 44 | problems = [] 45 | batches = [] 46 | n_nodes_in_batch = 0 47 | prev_n_vars = None 48 | 49 | for n_var in range(args.min_n, args.max_n+1): 50 | lower_bound = int((n_var - args.min_n) * problems_per_n) 51 | upper_bound = int((n_var - args.min_n + 1) * problems_per_n) 52 | for problems_idx in range(lower_bound, upper_bound): 53 | n_vars, iclauses, iclause_unsat, iclause_sat = gen_iclause_pair(args, n_var) 54 | 55 | if random.random() < 0.5: 56 | iclauses.append(iclause_unsat) 57 | else: 58 | iclauses.append(iclause_sat) 59 | 60 | n_clauses = len(iclauses) 61 | n_cells = sum([len(iclause) for iclause in iclauses]) 62 | n_nodes = 2 * n_vars + n_clauses 63 | if n_nodes > args.max_nodes_per_batch: 64 | continue 65 | 66 | batch_ready = False 67 | if (args.one and len(problems) > 0): 68 | batch_ready = True 69 | elif (prev_n_vars and n_vars != prev_n_vars): 70 | batch_ready = True 71 | elif (not args.one) and n_nodes_in_batch + n_nodes > args.max_nodes_per_batch: 72 | batch_ready = True 73 | 74 | if batch_ready: 75 | batches.append(mk_batch_problem(problems)) 76 | print("batch %d done (%d vars, %d problems)..." % (len(batches), prev_n_vars, len(problems)), file=f) 77 | del problems[:] 78 | n_nodes_in_batch = 0 79 | 80 | prev_n_vars = n_vars 81 | 82 | is_sat, stats = solve_sat(n_vars, iclauses) 83 | problems.append(("sr_n=%.4d_pk2=%.2f_pg=%.2f_t=%d_sat=0" % (n_vars, args.p_k_2, args.p_geo, problems_idx), n_vars, iclauses, is_sat)) 84 | n_nodes_in_batch += n_nodes 85 | 86 | if len(problems) > 0: 87 | batches.append(mk_batch_problem(problems)) 88 | print("batch %d done (%d vars, %d problems)..." % (len(batches), n_vars, len(problems)), file=f) 89 | del problems[:] 90 | 91 | return batches 92 | 93 | 94 | if __name__ == "__main__": 95 | parser = argparse.ArgumentParser() 96 | parser.add_argument('out_dir', action='store', type=str) 97 | parser.add_argument('gen_log', action='store', type=str) 98 | parser.add_argument('n_pairs', action='store', type=int) 99 | parser.add_argument('max_nodes_per_batch', action='store', type=int) 100 | 101 | parser.add_argument('--min_n', action='store', dest='min_n', type=int, default=40) 102 | parser.add_argument('--max_n', action='store', dest='max_n', type=int, default=40) 103 | 104 | parser.add_argument('--p_k_2', action='store', dest='p_k_2', type=float, default=0.3) 105 | parser.add_argument('--p_geo', action='store', dest='p_geo', type=float, default=0.4) 106 | 107 | parser.add_argument('--py_seed', action='store', dest='py_seed', type=int, default=None) 108 | parser.add_argument('--np_seed', action='store', dest='np_seed', type=int, default=None) 109 | 110 | parser.add_argument('--print_interval', action='store', dest='print_interval', type=int, default=100) 111 | 112 | parser.add_argument('--one', action='store', dest='one', type=int, default=0) 113 | parser.add_argument('--max_dimacs', action='store', dest='max_dimacs', type=int, default=None) 114 | 115 | args = parser.parse_args() 116 | 117 | if args.py_seed is not None: random.seed(args.py_seed) 118 | if args.np_seed is not None: np.random.seed(args.np_seed) 119 | 120 | batches = generate(args) 121 | 122 | # create directory 123 | # if not os.path.exists(args.out_dir): 124 | # os.mkdir(args.out_dir) 125 | 126 | dataset_filename = args.out_dir 127 | print("Writing %d batches to %s..." % (len(batches), dataset_filename)) 128 | with open(dataset_filename, 'wb') as f_dump: 129 | pickle.dump(batches, f_dump) 130 | -------------------------------------------------------------------------------- /src/train.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import pickle 3 | import os 4 | from tqdm import tqdm 5 | 6 | import torch 7 | import torch.nn as nn 8 | import torch.optim as optim 9 | 10 | from neurosat import NeuroSAT 11 | from data_maker import generate 12 | import mk_problem 13 | 14 | from config import parser 15 | 16 | args = parser.parse_args() 17 | 18 | net = NeuroSAT(args) 19 | net = net.cuda() 20 | 21 | task_name = args.task_name + '_sr' + str(args.min_n) + 'to' + str(args.max_n) + '_ep' + str(args.epochs) + '_nr' + str(args.n_rounds) + '_d' + str(args.dim) 22 | log_file = open(os.path.join(args.log_dir, task_name+'.log'), 'a+') 23 | detail_log_file = open(os.path.join(args.log_dir, task_name+'_detail.log'), 'a+') 24 | 25 | train, val = None, None 26 | if args.train_file is not None: 27 | with open(os.path.join(args.data_dir, 'train', args.train_file), 'rb') as f: 28 | train = pickle.load(f) 29 | 30 | with open(os.path.join(args.data_dir, 'val', args.val_file), 'rb') as f: 31 | val = pickle.load(f) 32 | 33 | loss_fn = nn.BCELoss() 34 | optim = optim.Adam(net.parameters(), lr=0.00002, weight_decay=1e-10) 35 | sigmoid = nn.Sigmoid() 36 | 37 | best_acc = 0.0 38 | start_epoch = 0 39 | 40 | if train is not None: 41 | print('num of train batches: ', len(train), file=log_file, flush=True) 42 | 43 | print('num of val batches: ', len(val), file=log_file, flush=True) 44 | 45 | if args.restore is not None: 46 | print('restoring from', args.restore, file=log_file, flush=True) 47 | model = torch.load(args.restore) 48 | start_epoch = model['epoch'] 49 | best_acc = model['acc'] 50 | net.load_state_dict(model['state_dict']) 51 | 52 | for epoch in range(start_epoch, args.epochs): 53 | if args.train_file is None: 54 | print('generate data online', file=log_file, flush=True) 55 | train = generate(args) 56 | 57 | print('==> %d/%d epoch, previous best: %.3f' % (epoch+1, args.epochs, best_acc)) 58 | print('==> %d/%d epoch, previous best: %.3f' % (epoch+1, args.epochs, best_acc), file=log_file, flush=True) 59 | print('==> %d/%d epoch, previous best: %.3f' % (epoch+1, args.epochs, best_acc), file=detail_log_file, flush=True) 60 | train_bar = tqdm(train) 61 | TP, TN, FN, FP = torch.zeros(1).long(), torch.zeros(1).long(), torch.zeros(1).long(), torch.zeros(1).long() 62 | net.train() 63 | for _, prob in enumerate(train_bar): 64 | optim.zero_grad() 65 | outputs = net(prob) 66 | target = torch.Tensor(prob.is_sat).cuda().float() 67 | # print(outputs.shape, target.shape) 68 | # print(outputs, target) 69 | outputs = sigmoid(outputs) 70 | loss = loss_fn(outputs, target) 71 | desc = 'loss: %.4f; ' % (loss.item()) 72 | 73 | loss.backward() 74 | optim.step() 75 | 76 | preds = torch.where(outputs>0.5, torch.ones(outputs.shape).cuda(), torch.zeros(outputs.shape).cuda()) 77 | 78 | TP += (preds.eq(1) & target.eq(1)).cpu().sum() 79 | TN += (preds.eq(0) & target.eq(0)).cpu().sum() 80 | FN += (preds.eq(0) & target.eq(1)).cpu().sum() 81 | FP += (preds.eq(1) & target.eq(0)).cpu().sum() 82 | TOT = TP + TN + FN + FP 83 | 84 | desc += 'acc: %.3f, TP: %.3f, TN: %.3f, FN: %.3f, FP: %.3f' % ((TP.item()+TN.item())*1.0/TOT.item(), TP.item()*1.0/TOT.item(), TN.item()*1.0/TOT.item(), FN.item()*1.0/TOT.item(), FP.item()*1.0/TOT.item()) 85 | # train_bar.set_description(desc) 86 | if (_ + 1) % 100 == 0: 87 | print(desc, file=detail_log_file, flush=True) 88 | print(desc, file=log_file, flush=True) 89 | 90 | val_bar = tqdm(val) 91 | TP, TN, FN, FP = torch.zeros(1).long(), torch.zeros(1).long(), torch.zeros(1).long(), torch.zeros(1).long() 92 | net.eval() 93 | for _, prob in enumerate(val_bar): 94 | optim.zero_grad() 95 | outputs = net(prob) 96 | target = torch.Tensor(prob.is_sat).cuda().float() 97 | # print(outputs.shape, target.shape) 98 | # print(outputs, target) 99 | outputs = sigmoid(outputs) 100 | preds = torch.where(outputs>0.5, torch.ones(outputs.shape).cuda(), torch.zeros(outputs.shape).cuda()) 101 | 102 | TP += (preds.eq(1) & target.eq(1)).cpu().sum() 103 | TN += (preds.eq(0) & target.eq(0)).cpu().sum() 104 | FN += (preds.eq(0) & target.eq(1)).cpu().sum() 105 | FP += (preds.eq(1) & target.eq(0)).cpu().sum() 106 | TOT = TP + TN + FN + FP 107 | 108 | desc = 'acc: %.3f, TP: %.3f, TN: %.3f, FN: %.3f, FP: %.3f' % ((TP.item()+TN.item())*1.0/TOT.item(), TP.item()*1.0/TOT.item(), TN.item()*1.0/TOT.item(), FN.item()*1.0/TOT.item(), FP.item()*1.0/TOT.item()) 109 | # val_bar.set_description(desc) 110 | if (_ + 1) % 100 == 0: 111 | print(desc, file=detail_log_file, flush=True) 112 | print(desc, file=log_file, flush=True) 113 | 114 | acc = (TP.item() + TN.item()) * 1.0 / TOT.item() 115 | torch.save({'epoch': epoch+1, 'acc': acc, 'state_dict': net.state_dict()}, os.path.join(args.model_dir, task_name+'_last.pth.tar')) 116 | if acc >= best_acc: 117 | best_acc = acc 118 | torch.save({'epoch': epoch+1, 'acc': best_acc, 'state_dict': net.state_dict()}, os.path.join(args.model_dir, task_name+'_best.pth.tar')) 119 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2023] [Fan Zhang] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------