├── CHANGELOG.md ├── figs ├── pdfs │ ├── nas.pdf │ ├── lp_solns.pdf │ ├── log_regrets.pdf │ ├── lp_solns_D.pdf │ ├── branin_by_D_d.pdf │ ├── lp_solns_ext.pdf │ ├── new_embedding.pdf │ ├── ard_mahalanobis.pdf │ ├── hesbo_embeddings.pdf │ ├── log_likelihood.pdf │ ├── rembo_p_interior.pdf │ ├── benchmark_results.pdf │ ├── model_predictions.pdf │ ├── branin_by_d_D_traces.pdf │ ├── rembo_illustrations.pdf │ └── branin_ablation_traces.pdf ├── data │ ├── fig3_sim_output.pckl │ ├── fig4_sim_output.pckl │ ├── figS3_sim_output.pckl │ ├── figS4_sim_output.pckl │ └── figS6_sim_output.pckl ├── table_S1.py ├── fig_2.py ├── plot_config.py ├── fig_S9.py ├── fig_S10.py ├── fig_6.py ├── fig_S5.py ├── fig_S1.py ├── fig_S2.py ├── fig_S6.py ├── fig_S8.py ├── fig_S3.py ├── fig_S4.py ├── fig_4.py ├── fig_1.py ├── fig_S7.py ├── fig_5.py └── fig_3.py ├── requirements.txt ├── CONTRIBUTING.md ├── .gitignore ├── benchmarks ├── run_linebo_benchmarks.py ├── run_addgpucb_benchmarks.py ├── data │ └── hartmann6_100.yaml ├── run_turbo_benchmarks.py ├── run_nasbench.py ├── run_cmaes_benchmarks.py ├── nasbench_evaluation.py ├── run_smac_benchmarks.py ├── ablation_models.py ├── run_ebo_benchmarks.py ├── run_ax_benchmarks.py ├── run_rrembo_benchmarks.R ├── compile_benchmark_results.py └── benchmark_problems.py ├── CODE_OF_CONDUCT.md ├── README.md ├── LICENSE └── quickstart.ipynb /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 1.0 (2020-01-31) 2 | ================== 3 | 4 | Initial release 5 | -------------------------------------------------------------------------------- /figs/pdfs/nas.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/nas.pdf -------------------------------------------------------------------------------- /figs/pdfs/lp_solns.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/lp_solns.pdf -------------------------------------------------------------------------------- /figs/pdfs/log_regrets.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/log_regrets.pdf -------------------------------------------------------------------------------- /figs/pdfs/lp_solns_D.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/lp_solns_D.pdf -------------------------------------------------------------------------------- /figs/pdfs/branin_by_D_d.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/branin_by_D_d.pdf -------------------------------------------------------------------------------- /figs/pdfs/lp_solns_ext.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/lp_solns_ext.pdf -------------------------------------------------------------------------------- /figs/pdfs/new_embedding.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/new_embedding.pdf -------------------------------------------------------------------------------- /figs/data/fig3_sim_output.pckl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/data/fig3_sim_output.pckl -------------------------------------------------------------------------------- /figs/data/fig4_sim_output.pckl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/data/fig4_sim_output.pckl -------------------------------------------------------------------------------- /figs/pdfs/ard_mahalanobis.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/ard_mahalanobis.pdf -------------------------------------------------------------------------------- /figs/pdfs/hesbo_embeddings.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/hesbo_embeddings.pdf -------------------------------------------------------------------------------- /figs/pdfs/log_likelihood.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/log_likelihood.pdf -------------------------------------------------------------------------------- /figs/pdfs/rembo_p_interior.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/rembo_p_interior.pdf -------------------------------------------------------------------------------- /figs/data/figS3_sim_output.pckl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/data/figS3_sim_output.pckl -------------------------------------------------------------------------------- /figs/data/figS4_sim_output.pckl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/data/figS4_sim_output.pckl -------------------------------------------------------------------------------- /figs/data/figS6_sim_output.pckl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/data/figS6_sim_output.pckl -------------------------------------------------------------------------------- /figs/pdfs/benchmark_results.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/benchmark_results.pdf -------------------------------------------------------------------------------- /figs/pdfs/model_predictions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/model_predictions.pdf -------------------------------------------------------------------------------- /figs/pdfs/branin_by_d_D_traces.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/branin_by_d_D_traces.pdf -------------------------------------------------------------------------------- /figs/pdfs/rembo_illustrations.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/rembo_illustrations.pdf -------------------------------------------------------------------------------- /figs/pdfs/branin_ablation_traces.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/alebo/HEAD/figs/pdfs/branin_ablation_traces.pdf -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | matplotlib 3 | scipy 4 | ax-platform>=0.1.17 5 | # json 6 | 7 | # For comparisons 8 | git+https://github.com/uber-research/TuRBO 9 | cma == 2.7.0 10 | dragonfly-opt == 0.1.4 11 | smac==0.11.1 12 | -------------------------------------------------------------------------------- /figs/table_S1.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import json 6 | import numpy as np 7 | 8 | from ax.storage.json_store.decoder import object_from_json 9 | 10 | 11 | def table_S1_data(): 12 | with open('../benchmarks/results/all_aggregated_results.json', 'r') as fin: 13 | res = object_from_json(json.load(fin)) 14 | 15 | for D in [100, 1000]: 16 | pname = f'Hartmann6, D={D}' 17 | print('-----', pname) 18 | for m, ts in res[pname].gen_times.items(): 19 | # Get average total time for fit and gen 20 | t = np.mean(ts) 21 | t += np.mean(res[pname].fit_times[m]) 22 | # Divide by 200 to be time per iteration 23 | t /= 200. 24 | print(f'{m}: {t}') 25 | 26 | 27 | if __name__ == '__main__': 28 | table_S1_data() 29 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to ALEBO 2 | We want to make contributing to this project as easy and transparent as 3 | possible. 4 | 5 | ## Pull Requests 6 | We actively welcome your pull requests. 7 | 8 | 1. Fork the repo and create your branch from `master`. 9 | 2. If you've added code that should be tested, add tests. 10 | 3. If you've changed APIs, update the documentation. 11 | 4. Ensure the test suite passes. 12 | 5. Make sure your code lints. 13 | 6. If you haven't already, complete the Contributor License Agreement ("CLA"). 14 | 15 | ## Contributor License Agreement ("CLA") 16 | In order to accept your pull request, we need you to submit a CLA. You only need 17 | to do this once to work on any of Facebook's open source projects. 18 | 19 | Complete your CLA here: 20 | 21 | ## Issues 22 | We use GitHub issues to track public bugs. Please ensure your description is 23 | clear and has sufficient instructions to be able to reproduce the issue. 24 | 25 | Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe 26 | disclosure of security bugs. In those cases, please go through the process 27 | outlined on that page and do not file a public issue. 28 | 29 | ## License 30 | By contributing to ALEBO, you agree that your contributions will be licensed 31 | under the LICENSE file in the root directory of this source tree. -------------------------------------------------------------------------------- /figs/fig_2.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import numpy as np 6 | 7 | from plot_config import * 8 | 9 | 10 | def make_fig_2(): 11 | # Run the simulation 12 | np.random.seed(1) 13 | 14 | Ds = [20, 100, 1000] 15 | ds = list(range(1, 6)) 16 | nsamp = 1000 17 | p_interior = {} 18 | for D in Ds: 19 | for d in ds: 20 | p_interior[(D, d)] = 0. 21 | for _ in range(nsamp): 22 | # Generate a REMBO projection 23 | A = np.random.randn(D, d) 24 | # Sample a point in [-sqrt(d), sqrt(d)]^d 25 | x = (np.random.rand(d) * 2 - 1) * np.sqrt(d) 26 | # Project up 27 | z = A @ x 28 | # Check if satisfies box bounds 29 | if z.min() >= -1 and z.max() <= 1: 30 | p_interior[(D, d)] += 1 31 | p_interior[(D, d)] /= nsamp 32 | 33 | # Make the figure 34 | fig = plt.figure(figsize=(2., 1.55)) 35 | ax = fig.add_subplot(111) 36 | ax.grid(alpha=0.5) 37 | 38 | for i, D in enumerate(Ds): 39 | ax.plot(ds, [p_interior[(D, d)] for d in ds], 'x-', c=plt.cm.tab10(i)) 40 | ax.legend([r'$D=20$', r'$D=100$', r'$D=1000$'], fontsize=7) 41 | ax.set_xlabel(r'Embedding dimension $d_e$', fontsize=9) 42 | ax.set_ylabel('Probability projection\nsatisfies box bounds', fontsize=9) 43 | plt.subplots_adjust(right=0.99, bottom=0.22, left=0.3, top=0.94) 44 | 45 | plt.savefig('pdfs/rembo_p_interior.pdf', pad_inches=0) 46 | 47 | if __name__ == '__main__': 48 | make_fig_2() 49 | -------------------------------------------------------------------------------- /figs/plot_config.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | from matplotlib import pyplot as plt 6 | from matplotlib.lines import Line2D 7 | from matplotlib import rc 8 | import matplotlib 9 | rc('font', family='serif', style='normal', variant='normal', weight='normal', stretch='normal', size=8) 10 | matplotlib.rcParams['ps.useafm'] = True 11 | matplotlib.rcParams['pdf.use14corefonts'] = True 12 | matplotlib.rcParams['text.usetex'] = True 13 | matplotlib.rcParams['xtick.labelsize'] = 7 14 | matplotlib.rcParams['ytick.labelsize'] = 7 15 | matplotlib.rcParams['axes.titlesize'] = 9 16 | 17 | plot_method_names = [ 18 | 'ALEBO (ours)', 19 | 'REMBO', 20 | 'HeSBO, $d_e$=$d$', 21 | 'HeSBO, $d_e$=$2d$', 22 | 'REMBO-$\phi k_{\Psi}$', 23 | 'REMBO-$\gamma k_{\Psi}$', 24 | 'EBO', 25 | 'Add-GP-UCB', 26 | 'SMAC', 27 | 'CMA-ES', 28 | 'TuRBO', 29 | 'Sobol', 30 | 'CoordinateLineBO', 31 | 'RandomLineBO', 32 | 'DescentLineBO', 33 | ] 34 | 35 | plot_colors={ 36 | 'ALEBO (ours)': plt.cm.tab20(0), 37 | 'REMBO': plt.cm.tab20(1), 38 | 'HeSBO, $d_e$=$d$': plt.cm.tab20(2), 39 | 'HeSBO, $d_e$=$2d$': plt.cm.tab20(3), 40 | 'REMBO-$\phi k_{\Psi}$': plt.cm.tab20(4), 41 | 'REMBO-$\gamma k_{\Psi}$': plt.cm.tab20(5), 42 | 'EBO': plt.cm.tab20(6), 43 | 'Add-GP-UCB': plt.cm.tab20(7), 44 | 'SMAC': plt.cm.tab20(8), 45 | 'CMA-ES': plt.cm.tab20(9), 46 | 'TuRBO': plt.cm.tab20(10), 47 | 'Sobol': plt.cm.tab20(14), 48 | 'CoordinateLineBO': plt.cm.tab20(12), 49 | 'RandomLineBO': plt.cm.tab20(16), 50 | 'DescentLineBO': plt.cm.tab20(18), 51 | } 52 | -------------------------------------------------------------------------------- /figs/fig_S9.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | from fig_S8 import * 6 | 7 | 8 | def make_fig_S9(): 9 | ys1, ys2 = extract_sensitivity_results() 10 | 11 | d_es = [2, 3, 4, 5, 6, 7, 8] 12 | mus_de = [] 13 | sems_de = [] 14 | for d_e in d_es: 15 | Y = ys1[d_e][:, 49] 16 | mus_de.append(Y.mean()) 17 | sems_de.append(Y.std() / np.sqrt(len(Y))) 18 | 19 | Ds = [50, 100, 200, 500, 1000] 20 | mus_D = [] 21 | sems_D = [] 22 | for D in Ds: 23 | Y = ys2[D][:, 49] 24 | mus_D.append(Y.mean()) 25 | sems_D.append(Y.std() / np.sqrt(len(Y))) 26 | 27 | fig = plt.figure(figsize=(5.5, 1.8)) 28 | 29 | ax = fig.add_subplot(121) 30 | ax.errorbar(d_es, mus_de, yerr=2*np.array(sems_de)) 31 | ax.set_ylim([0.3, 2.85]) 32 | ax.set_yticks([0.5, 1.0, 1.5, 2.0, 2.5]) 33 | ax.set_xlabel(r'Embedding dimension $d_e$', fontsize=9) 34 | ax.set_title(r'Branin, $D=100$') 35 | ax.set_ylabel('Best value found', fontsize=9) 36 | ax.grid(alpha=0.2) 37 | 38 | ax = fig.add_subplot(122) 39 | ax.errorbar(Ds, mus_D, yerr=2*np.array(sems_D)) 40 | ax.set_ylim([0.3, 2.85]) 41 | ax.set_yticks([0.5, 1.0, 1.5, 2.0, 2.5]) 42 | ax.set_yticklabels([]) 43 | ax.set_xlabel(r'Ambient dimension $D$', fontsize=9) 44 | ax.set_title('Branin, $d_e=4$') 45 | ax.grid(alpha=0.2) 46 | ax.set_xticks([50, 200, 500, 1000]) 47 | 48 | plt.subplots_adjust(right=0.93, bottom=0.19, left=0.12, top=0.89, wspace=0.1) 49 | plt.savefig('pdfs/branin_by_D_d.pdf', pad_inches=0) 50 | 51 | 52 | if __name__ == '__main__': 53 | make_fig_S9() 54 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | # Pycharm 92 | .idea/ 93 | 94 | # Project 95 | benchmarks/Ensemble-Bayesian-Optimization/ 96 | benchmarks/outcmaes/ 97 | benchmarks/smac3*/ 98 | benchmarks/tmp/ 99 | benchmarks/results/*.json 100 | evaluations.hdf5 101 | benchmarks/nasbench_only108.tfrecord 102 | -------------------------------------------------------------------------------- /benchmarks/run_linebo_benchmarks.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | """ 6 | Run benchmarks for LineBO on the Hartmann6 100 problem. 7 | 8 | These benchmarks are run using the benchmarking suite contained in the LineBO 9 | codebase. The code here loads in those results and extracts just the function 10 | evaluations, which are then stored in json. There are several steps that must 11 | be done before this script can be run. 12 | 13 | 1) Clone and install the LineBO software from https://github.com/jkirschner42/LineBO 14 | 2) copy data/hartmann6_100.yaml from here into the LineBO/config/ directory. 15 | This problem configuration is based on LineBO/config/hartmann6_sub14.yaml. 16 | 3) Run the experiments by executing: 17 | 18 | febo create hartmann6_100 --config config/hartmann6_100.yaml 19 | febo run hartmann6_100 20 | 21 | 4) Copy LineBO/runs/hartmann6_100/data/evaluations.hdf5 into results/ 22 | """ 23 | 24 | import numpy as np 25 | import h5py 26 | import json 27 | 28 | f = h5py.File('results/evaluations.hdf5', 'r') 29 | methods = ['RandomLineBO', 'CoordinateLineBO', 'DescentLineBO', 'Random', 'CMA-ES'] 30 | 31 | ys = {} 32 | for i, m in enumerate(methods): 33 | ys[m] = np.zeros((50, 200)) 34 | for rep in range(50): 35 | ys[m][rep, :] = f[str(i)][str(rep)]['y_exact'] * -3.32237 36 | 37 | with open('results/hartmann6_100_randomlinebo.json', 'w') as fout: 38 | json.dump(ys['RandomLineBO'].tolist(), fout) 39 | 40 | with open('results/hartmann6_100_coordinatelinebo.json', 'w') as fout: 41 | json.dump(ys['CoordinateLineBO'].tolist(), fout) 42 | 43 | with open('results/hartmann6_100_descentlinebo.json', 'w') as fout: 44 | json.dump(ys['DescentLineBO'].tolist(), fout) 45 | -------------------------------------------------------------------------------- /figs/fig_S10.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import json 6 | import numpy as np 7 | 8 | from ax.storage.json_store.decoder import object_from_json 9 | 10 | from plot_config import * 11 | 12 | 13 | def extract_ablation_results(): 14 | with open(f'../benchmarks/results/ablation_aggregated_results.json', 'r') as fin: 15 | res = object_from_json(json.load(fin)) 16 | 17 | # Results 18 | ys = { 19 | 'ALEBO': res['Branin, D=100_ablation'].objective_at_true_best['ALEBO, base'], 20 | 'Ablation: Matern kernel': res['Branin, D=100_ablation'].objective_at_true_best['ALEBO, kernel ablation'], 21 | 'Ablation: Normal projection': res['Branin, D=100_ablation'].objective_at_true_best['ALEBO, projection ablation'], 22 | } 23 | return ys 24 | 25 | 26 | def make_fig_S_ablation(): 27 | ys = extract_ablation_results() 28 | 29 | fig = plt.figure(figsize=(4, 2.5)) 30 | ax = fig.add_subplot(111) 31 | 32 | x = np.arange(1, 51) 33 | for k, y in ys.items(): 34 | f = y.mean(axis=0) 35 | sem = y.std(axis=0) / np.sqrt(y.shape[0]) 36 | ax.errorbar(x, f, yerr=2 * sem, label=k) 37 | 38 | ax.set_ylim([0, 7]) 39 | ax.set_yticks([0, 2, 4, 6]) 40 | ax.legend(fontsize=7, loc='lower left') 41 | ax.set_title(r'Branin, $D=100$') 42 | ax.set_ylabel('Best value found', fontsize=9) 43 | ax.set_xlabel('Function evaluations', fontsize=9) 44 | ax.axhline(y=0.397887, c='gray', ls='--') 45 | ax.grid(alpha=0.2, zorder=-10) 46 | ax.set_xlim([0, 51]) 47 | 48 | plt.subplots_adjust(right=0.995, bottom=0.16, left=0.1, top=0.91, wspace=0.05) 49 | plt.savefig('pdfs/branin_ablation_traces.pdf', pad_inches=0) 50 | 51 | 52 | if __name__ == '__main__': 53 | make_fig_S_ablation() 54 | -------------------------------------------------------------------------------- /figs/fig_6.py: -------------------------------------------------------------------------------- 1 | import json 2 | import numpy as np 3 | 4 | from ax.storage.json_store.decoder import object_from_json 5 | 6 | from plot_config import * 7 | 8 | 9 | def make_nasbench_figure(): 10 | with open('../benchmarks/results/nasbench_aggregated_results.json', 'r') as fin: 11 | res = object_from_json(json.load(fin)) 12 | 13 | # A map from method idx in plot_method_names to the name used in res 14 | method_idx_to_res_name = { 15 | 1: 'REMBO', 16 | 3: 'HeSBO', 17 | 9: 'cmaes', 18 | 10: 'turbo', 19 | 11: 'Sobol', 20 | 0: 'ALEBO', 21 | } 22 | plot_method_names[3] = 'HeSBO' 23 | plot_colors['HeSBO'] = plt.cm.tab20(3) 24 | 25 | fig = plt.figure(figsize=(2.96, 2.0)) 26 | ax1 = fig.add_subplot(111) 27 | method_idx = 1 28 | method_names_used = [] 29 | for i, m in method_idx_to_res_name.items(): 30 | f = np.nanmean(res[m], axis=0) 31 | sem = np.nanstd(res[m], axis=0) / np.sqrt(res[m].shape[0]) 32 | x = np.arange(1, 51) 33 | mname = plot_method_names[i] 34 | color = plot_colors[mname] 35 | ax1.plot(x, f, color=color, label=mname) 36 | ax1.errorbar(x, f, yerr=2 * sem, color=color, alpha=0.5, ls='') 37 | 38 | ax1.set_xlim([0, 51]) 39 | ax1.set_ylabel('Best feasible test accuracy', fontsize=9) 40 | ax1.set_xlabel('Function evaluations', fontsize=9) 41 | 42 | #ax1.legend(bbox_to_anchor=(1.0, 1.24), ncol=4, fontsize=6, columnspacing=1.65) 43 | ax1.legend(ncol=2, loc='lower right', fontsize=7) 44 | 45 | ax1.set_ylim([0.92, 0.936]) 46 | ax1.set_yticks([0.92, 0.925, 0.93, 0.935]) 47 | ax1.set_yticklabels(['92.0\%', '92.5\%', '93.0\%', '93.5\%']) 48 | ax1.grid(alpha=0.2, zorder=-10) 49 | 50 | plt.subplots_adjust(right=0.98, bottom=0.17, left=0.19, top=0.98) 51 | plt.savefig(f'pdfs/nas.pdf', pad_inches=0) 52 | #plt.show() 53 | 54 | 55 | if __name__ == '__main__': 56 | make_nasbench_figure() 57 | -------------------------------------------------------------------------------- /figs/fig_S5.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import numpy as np 6 | import pickle 7 | 8 | from plot_config import * 9 | 10 | 11 | def make_fig_S5(): 12 | with open('data/fig4_sim_output.pckl', 'rb') as fin: 13 | res = pickle.load(fin) 14 | 15 | nsamp = 1000 16 | fig = plt.figure(figsize=(5.5, 2)) 17 | for i, d in enumerate([2, 6, 10]): 18 | ax = fig.add_subplot(1, 3, i + 1) 19 | x = [d_use for d_use in range(21) if d_use >= d] 20 | y1 = np.array([res['rembo'][(100, d, d_use)] for d_use in x]) 21 | y2 = np.array([res['hesbo'][(100, d, d_use)] for d_use in x]) 22 | y3 = np.array([res['unitsphere'][(100, d, d_use)] for d_use in x]) 23 | y1err = 2 * np.sqrt(y1 * (1 - y1) / nsamp) 24 | y2err = 2 * np.sqrt(y2 * (1 - y2) / nsamp) 25 | y3err = 2 * np.sqrt(y3 * (1 - y3) / nsamp) 26 | ax.errorbar(x, y1, yerr=y1err, color=plt.cm.tab10(0), marker='') 27 | ax.errorbar(x, y2, yerr=y2err, color=plt.cm.tab10(1), marker='') 28 | ax.errorbar(x, y3, yerr=y3err, color=plt.cm.tab10(2), marker='') 29 | ax.set_title(r'$d={d}$'.format(d=d)) 30 | if i == 0: 31 | ax.set_ylabel('Probability embedding\ncontains optimizer', fontsize=9) 32 | ax.legend(['REMBO', 'HeSBO', r'Hypersphere'], loc='lower right', fontsize=7) 33 | ax.set_xlabel(r'$d_e$', fontsize=9) 34 | ax.set_xlim([0, 21]) 35 | ax.set_ylim([-0.02, 1.02]) 36 | ax.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0]) 37 | if i > 0: 38 | ax.set_yticklabels([]) 39 | ax.grid(True, alpha=0.2) 40 | 41 | plt.subplots_adjust(right=0.99, bottom=0.17, left=0.10, top=0.89, wspace=0.1) 42 | 43 | plt.savefig('pdfs/lp_solns_ext.pdf', pad_inches=0) 44 | 45 | if __name__ == '__main__': 46 | # Assumes fig_4 has been run 47 | make_fig_S5() 48 | -------------------------------------------------------------------------------- /figs/fig_S1.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import numpy as np 6 | 7 | from fig_1 import * 8 | 9 | 10 | def hesbo_branin(X, mode): 11 | # In 2-D, HESBO has 3 possible embeddings: 12 | # Full rank, span x1 and x2 13 | # x1=x2 14 | # x1=-x2 15 | Y = X.copy() 16 | if mode == 1: 17 | pass # All is well here! 18 | elif mode == 2: 19 | Y[:, 0] = Y[:, 1] 20 | elif mode == 3: 21 | Y[:, 0] = -Y[:, 1] 22 | return branin_centered(Y) 23 | 24 | 25 | def make_fig_S1(): 26 | # Evaluate the branin function on the grid under the three possible embeddings 27 | grid_xhes, grid_yhes, fs_hesbo1 = eval_f_on_grid(hesbo_branin, [-1, 1], [-1, 1], {'mode': 1}, 2, density=1000) 28 | grid_xhes, grid_yhes, fs_hesbo2 = eval_f_on_grid(hesbo_branin, [-1, 1], [-1, 1], {'mode': 3}, 2, density=1000) 29 | grid_xhes, grid_yhes, fs_hesbo3 = eval_f_on_grid(hesbo_branin, [-1, 1], [-1, 1], {'mode': 2}, 2, density=1000) 30 | 31 | fig = plt.figure(figsize=(5.5, 1.8), facecolor='w', edgecolor='w') 32 | plt.set_cmap('RdBu_r') 33 | 34 | for i, fs in enumerate([fs_hesbo1, fs_hesbo2, fs_hesbo3]): 35 | ax = fig.add_subplot(1, 3, i + 1) 36 | CS1 = ax.contourf(grid_xhes, grid_yhes, np.log(fs), levels=np.linspace(-1, 6, 30)) 37 | ax.grid(False) 38 | ax.set_xlabel(r'$x_1$', fontsize=9) 39 | ax.set_xlim([-1, 1]) 40 | ax.set_xticks([-1, -0.5, 0, 0.5, 1]) 41 | ax.set_yticks([-1, -0.5, 0, 0.5, 1]) 42 | if i == 0: 43 | ax.set_ylabel(r'$x_2$', fontsize=9) 44 | ax.set_ylim([-1, 1]) 45 | else: 46 | ax.set_yticklabels([]) 47 | 48 | plt.subplots_adjust(right=0.98, top=0.975, left=0.1, bottom=0.195) 49 | plt.savefig('pdfs/hesbo_embeddings.pdf', pad_inches=0) 50 | 51 | 52 | if __name__ == '__main__': 53 | make_fig_S1() 54 | -------------------------------------------------------------------------------- /figs/fig_S2.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import numpy as np 6 | import pickle 7 | 8 | from plot_config import * 9 | 10 | 11 | def make_fig_S2(): 12 | # Load in simulation results 13 | with open('data/fig3_sim_output.pckl', 'rb') as fin: 14 | (test_Y, f1, var1, f2, var2, f3, var3) = pickle.load(fin) 15 | 16 | fig = plt.figure(figsize=(5.5, 2)) 17 | 18 | ax = fig.add_subplot(131) 19 | ax.errorbar( 20 | x=test_Y.numpy(), y=f3.numpy(), yerr = 2 * np.sqrt(var3.numpy()), 21 | c='gray', lw=1, ls='', marker='.', mfc='k', mec='k', ms=3 22 | ) 23 | x0 = -2.5 24 | x1 = 0.5 25 | ax.plot([x0, x1], [x0, x1], '-', zorder=-5, alpha=0.5, c='steelblue', lw=2) 26 | ax.set_xlim([x0, x1]) 27 | ax.set_ylim([x0, x1]) 28 | ax.set_xlabel('True value', fontsize=9) 29 | ax.set_ylabel('Model prediction', fontsize=9) 30 | ax.set_title('ARD RBF', fontsize=9) 31 | 32 | 33 | ax = fig.add_subplot(132) 34 | ax.errorbar( 35 | x=test_Y.numpy(), y=f2.numpy(), yerr = 2 * np.sqrt(var2.numpy()), 36 | c='gray', lw=1, ls='', marker='.', mfc='k', mec='k', ms=3 37 | ) 38 | x0 = -2.5 39 | x1 = 0.5 40 | ax.plot([x0, x1], [x0, x1], '-', zorder=-5, alpha=0.5, c='steelblue', lw=2) 41 | ax.set_xlim([x0, x1]) 42 | ax.set_ylim([x0, x1]) 43 | ax.set_xlabel('True value', fontsize=9) 44 | ax.set_title('Mahalanobis\npoint estimate', fontsize=9) 45 | 46 | 47 | ax = fig.add_subplot(133) 48 | ax.errorbar( 49 | x=test_Y.numpy(), y=f1.numpy(), yerr = 2 * np.sqrt(var1.numpy()), 50 | c='gray', lw=1, ls='', marker='.', mfc='k', mec='k', ms=3 51 | ) 52 | x0 = -3. 53 | x1 = 1 54 | ax.plot([x0, x1], [x0, x1], '-', zorder=-5, alpha=0.5, c='steelblue', lw=2) 55 | ax.set_xlim([x0, x1]) 56 | ax.set_ylim([x0, x1]) 57 | ax.set_title('Mahalanobis\nposterior sampled', fontsize=9) 58 | ax.set_xticks([-3, -2, -1, 0, 1]) 59 | ax.set_xlabel('True value', fontsize=9) 60 | 61 | plt.subplots_adjust(right=0.99, bottom=0.17, left=0.1, top=0.84, wspace=0.3) 62 | plt.savefig('pdfs/model_predictions.pdf', pad_inches=0) 63 | 64 | 65 | if __name__ == '__main__': 66 | # Assumes fig_3 has already been run 67 | make_fig_S2() 68 | -------------------------------------------------------------------------------- /benchmarks/run_addgpucb_benchmarks.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | """ 6 | Run benchmarks for Add-GP-UCB. 7 | 8 | Requires installing dragonfly-opt from pip. The experiments here used version 9 | 0.1.4. 10 | """ 11 | import os 12 | os.environ['OPENBLAS_NUM_THREADS'] = '1' 13 | os.environ['OMP_NUM_THREADS'] = '1' 14 | 15 | from argparse import Namespace 16 | import json 17 | 18 | from benchmark_problems import ( 19 | branin_100, 20 | hartmann6_100, 21 | hartmann6_1000, 22 | ) 23 | 24 | from ax.benchmark.benchmark import benchmark_minimize_callable 25 | from ax.storage.json_store.encoder import object_to_json 26 | from dragonfly import minimise_function # dragonfly-opt==0.1.4 27 | 28 | def run_hartmann6_benchmarks(D, rep): 29 | if D == 100: 30 | problem = hartmann6_100 31 | elif D == 1000: 32 | problem = hartmann6_1000 33 | 34 | experiment, f = benchmark_minimize_callable( 35 | problem=problem, 36 | num_trials=200, 37 | method_name='add_gp_ucb', 38 | replication_index=rep, 39 | ) 40 | 41 | options = Namespace(acq="add_ucb") 42 | res = minimise_function(f, domain=[[0, 1]] * D, max_capital=199, options=options) 43 | 44 | with open(f'results/hartmann6_{D}_addgpucb_rep_{rep}.json', "w") as fout: 45 | json.dump(object_to_json(experiment), fout) 46 | 47 | 48 | def run_branin_benchmarks(rep): 49 | 50 | experiment, f = benchmark_minimize_callable( 51 | problem=branin_100, 52 | num_trials=50, 53 | method_name='add_gp_ucb', 54 | replication_index=rep, 55 | ) 56 | 57 | options = Namespace(acq="add_ucb") 58 | res = minimise_function( 59 | f, 60 | domain=[[-5, 10]] * 50 + [[0, 15]] * 50, 61 | max_capital=49, 62 | options=options, 63 | ) 64 | 65 | with open(f'results/branin_100_addgpucb_rep_{rep}.json', "w") as fout: 66 | json.dump(object_to_json(experiment), fout) 67 | 68 | 69 | if __name__ == '__main__': 70 | # Run all of the Add-GP-UCB benchmarks using Dragonfly. 71 | # These can be distributed. 72 | 73 | for i in range(50): 74 | run_hartmann6_benchmarks(D=100, rep=i) 75 | 76 | ## Hartmann6, D=1000: Too slow, not run 77 | #run_hartmann6_benchmarks(D=1000, rep=i) 78 | 79 | # Branin, D=100: Each rep takes ~3 hours 80 | run_branin_benchmarks(rep=i) 81 | -------------------------------------------------------------------------------- /figs/fig_S6.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | from fig_4 import * 6 | 7 | 8 | def run_simulation(): 9 | t1 = time.time() 10 | nsamp = 1000 11 | res = {'unitsphere': {}} 12 | for D in [50, 100, 200]: 13 | for d in range(2, 19, 2): 14 | for d_use in range(2, 21, 2): 15 | if d_use < d: 16 | continue 17 | res['unitsphere'][(D, d, d_use)] = p_A_contains_optimizer( 18 | d=d, D=D, d_use=d_use, gen_A_fn=gen_A_unitsphere, nsamp=nsamp 19 | ) 20 | with open('data/figS6_sim_output.pckl', 'wb') as fout: 21 | pickle.dump(res, fout) 22 | print(time.time() - t1) 23 | 24 | 25 | def make_fig_S6(): 26 | with open('data/figS6_sim_output.pckl', 'rb') as fin: 27 | res = pickle.load(fin) 28 | 29 | fig, (ax1, ax2, ax3, ax4) = plt.subplots(ncols=4,figsize=(5.5, 2), 30 | gridspec_kw={"width_ratios":[1, 1, 1, 0.15]}) 31 | 32 | axes = [ax1, ax2, ax3] 33 | 34 | for i, D in enumerate([50, 100, 200]): 35 | 36 | ds = [] 37 | duses = [] 38 | ps = [] 39 | for d in range(2, 19, 2): 40 | for d_use in range(2, 21, 2): 41 | if d_use < d: 42 | continue 43 | ds.append(d) 44 | duses.append(d_use) 45 | ps.append(res['unitsphere'][(D, d, d_use)]) 46 | 47 | cntr = axes[i].tricontourf(duses, ds, ps, levels=np.linspace(0, 1.001, 21), cmap='viridis') 48 | axes[i].set_title(f'$D={D}$') 49 | if i == 0: 50 | axes[i].set_yticks([2, 6, 10, 14, 18]) 51 | axes[i].set_ylabel(r'True subspace dimension $d$', fontsize=9) 52 | else: 53 | axes[i].set_yticks([2, 6, 10, 14, 18]) 54 | axes[i].set_yticklabels([]) 55 | axes[i].grid(alpha=0.2, zorder=-2) 56 | axes[i].set_xlabel(r'Embedding $d_e$') 57 | axes[i].set_xticks([2, 6, 10, 14, 18]) 58 | 59 | ax4.patch.set_visible(False) 60 | ax4.set_yticks([]) 61 | ax4.set_xticks([]) 62 | fig.colorbar(cntr, ax=ax4, ticks=[0, 0.25, 0.5, 0.75, 1.], fraction=1) 63 | 64 | plt.subplots_adjust(right=0.97, bottom=0.2, left=0.07, top=0.89, wspace=0.1) 65 | plt.savefig('pdfs/lp_solns_D.pdf', pad_inches=0) 66 | 67 | 68 | if __name__ == '__main__': 69 | #run_simulation() # This takes about 3hrs and produces data/figS6_sim_output.pckl 70 | make_fig_S6() 71 | -------------------------------------------------------------------------------- /benchmarks/data/hartmann6_100.yaml: -------------------------------------------------------------------------------- 1 | algorithm: 2 | noise_model_config: {} 3 | noise_model: 4 | constraints_model_config: {} 5 | constraints_model: 6 | model_config: {} 7 | model: febo.models.gp.GP 8 | 9 | 10 | model: 11 | beta: 8 12 | models.gp: 13 | noise_var: 0.0000001 14 | kernels: 15 | - - GPy.kern.RBF 16 | - variance: 1.0 17 | lengthscale: 0.2 18 | ARD: false 19 | calculate_gradients: true # Enable/Disable computation of gradient on each update. 20 | 21 | 22 | algorithm.subdomainbo: 23 | min_queries_line: 5 24 | max_queries_line: 10 25 | #min_queries_tr: 1*d 26 | #max_queries_tr: 1*d 27 | min_queries_tr: 5 28 | max_queries_tr: 10 29 | acquisition: febo.algorithms.subdomainbo.acquisition.ucb 30 | plot_every_step: false 31 | plot: false 32 | tr_radius: 0.1 33 | 34 | algorithm.rembo: 35 | emb_d: 6 36 | interleaved_runs: 4 37 | 38 | algorithm.spsa: 39 | niter: 1200 40 | 41 | algorithm.nelder_mead: 42 | contraction_factor: 0.3 43 | 44 | controller: 45 | best_predicted_every: 1 46 | T: 200 # Horizon 47 | repetitions: 50 48 | 49 | 50 | environment.benchmark: 51 | noise_obs_mode: none # Can be set to "full", "evaluation" or "hidden". 52 | noise_function: 0.0 53 | aug_d: 94 54 | random_x0: true 55 | 56 | 57 | experiment.multi: 58 | label: febo.labels.algorithm_name 59 | multi_controller: febo.controller.multi.RepetitionController 60 | iterator: 61 | - experiment.simple:algorithm: febo.algorithms.RandomLineBO 62 | - experiment.simple:algorithm: febo.algorithms.CoordinateLineBO 63 | - experiment.simple:algorithm: febo.algorithms.AscentLineBO 64 | #- experiment.simple:algorithm: febo.algorithms.NelderMead 65 | - experiment.simple:algorithm: febo.algorithms.Random 66 | #- experiment.simple:algorithm: febo.algorithms.UCB 67 | #- experiment.simple:algorithm: febo.algorithms.rembo.Rembo 68 | #- experiment.simple:algorithm: febo.algorithms.rembo.InterleavedRembo 69 | #- experiment.simple:algorithm: febo.algorithms.spsa.SPSA 70 | - experiment.simple:algorithm: febo.algorithms.cmaes.CMAES 71 | fixed_environment: false 72 | 73 | 74 | experiment.simple: 75 | algorithm: febo.algorithms.Random 76 | environment: febo.environment.benchmarks.subspace.AugmentedHartmann6 77 | controller: febo.controller.simple.SimpleController 78 | 79 | 80 | solver.grid: 81 | points_per_dimension: 300 82 | solver.scipy: 83 | convergence_warnings: true 84 | sync_restarts: true 85 | num_processes: 1 86 | num_restart: 50 87 | lbfgs_maxfun: 1000 88 | lbfgs_use_gradients: false 89 | 90 | 91 | main: 92 | log_level_file: INFO 93 | log_level_console: INFO 94 | experiment: febo.experiment.MultiExperiment # Experiment 95 | -------------------------------------------------------------------------------- /figs/fig_S8.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import json 6 | import numpy as np 7 | 8 | from ax.storage.json_store.decoder import object_from_json 9 | 10 | from plot_config import * 11 | 12 | 13 | def extract_sensitivity_results(): 14 | res = {} 15 | for fname in [ 16 | 'branin_gramacy_100', 17 | 'sensitivity', 18 | ]: 19 | with open(f'../benchmarks/results/{fname}_aggregated_results.json', 'r') as fin: 20 | res.update(object_from_json(json.load(fin))) 21 | 22 | # Results for D=100 23 | ys1 = {} 24 | for d in [2, 3, 4, 5, 6, 7, 8]: 25 | if d == 4: 26 | ys1[d] = res['Branin, D=100'].objective_at_true_best['ALEBO'] 27 | else: 28 | ys1[d] = res['Branin, D=100_sensitivity'].objective_at_true_best[f'ALEBO, d={d}'] 29 | 30 | # Results for d_e=4 31 | ys2 = {} 32 | for D in [50, 100, 200, 500, 1000]: 33 | if D == 100: 34 | ys2[D] = res['Branin, D=100'].objective_at_true_best['ALEBO'] 35 | else: 36 | ys2[D] = res[f'Branin, D={D}_sensitivity'].objective_at_true_best['ALEBO'] 37 | return ys1, ys2 38 | 39 | 40 | def make_fig_S8(): 41 | ys1, ys2 = extract_sensitivity_results() 42 | 43 | fig = plt.figure(figsize=(5.5, 2.2)) 44 | ax = fig.add_subplot(121) 45 | 46 | x = np.arange(1, 51) 47 | for d_e in [2, 3, 4, 6, 8]: 48 | ax.plot(x, ys1[d_e].mean(axis=0), label=f'$d_e={d_e}$') 49 | 50 | ax.set_ylim([0, 7]) 51 | ax.set_yticks([0, 2, 4, 6]) 52 | ax.legend(fontsize=7) 53 | ax.set_title(r'Branin, $D=100$') 54 | ax.set_ylabel('Best value found', fontsize=9) 55 | ax.set_xlabel('Function evaluations', fontsize=9) 56 | ax.axhline(y=0.397887, c='gray', ls='--') 57 | ax.grid(alpha=0.2, zorder=-10) 58 | ax.set_xlim([0, 51]) 59 | 60 | ax = fig.add_subplot(122) 61 | 62 | for D in [50, 100, 200, 500, 1000]: 63 | ax.plot(x, ys2[D].mean(axis=0), label=f'$D={D}$') 64 | 65 | ax.set_title(r'Branin, $d_e=4$') 66 | 67 | ax.set_ylim([0, 7]) 68 | ax.legend(fontsize=7) 69 | ax.set_xlabel('Function evaluations', fontsize=9) 70 | ax.axhline(y=0.397887, c='gray', ls='--') 71 | ax.grid(alpha=0.2, zorder=-10) 72 | ax.set_yticks([0, 2, 4, 6]) 73 | ax.set_xlim([0, 51]) 74 | ax.set_yticklabels([]) 75 | 76 | plt.subplots_adjust(right=0.995, bottom=0.16, left=0.06, top=0.91, wspace=0.05) 77 | plt.savefig('pdfs/branin_by_d_D_traces.pdf', pad_inches=0) 78 | 79 | 80 | if __name__ == '__main__': 81 | make_fig_S8() 82 | -------------------------------------------------------------------------------- /figs/fig_S3.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | from math import pi 6 | 7 | from fig_3 import * 8 | 9 | 10 | def compute_ll(f, var, test_Y): 11 | return -0.5 * (torch.log(2 * pi * var) + ((test_Y - f) ** 2) / var).sum().item() 12 | 13 | 14 | def run_simulation(): 15 | D = 100 16 | d = 6 17 | 18 | # Get projection 19 | torch.manual_seed(10) 20 | B0 = torch.randn(d, D, dtype=torch.double) 21 | B = B0 / torch.sqrt((B0 ** 2).sum(dim=0)) 22 | 23 | # Get test data 24 | _, _, _, test_X, test_Y, _, _ = gen_train_test_sets(B, ntrain=10, ntest=1000, seed_test=1000) 25 | 26 | ns = np.array([40, 50, 75, 100, 125, 150, 175, 200]) 27 | nrep = 20 28 | 29 | ll_alebo = np.zeros((nrep, len(ns))) 30 | ll_ard = np.zeros((nrep, len(ns))) 31 | 32 | for i in range(nrep): 33 | for j, n in enumerate(ns): 34 | # Generate training data 35 | train_X, train_Y, train_Yvar, _, _, mu, sigma = gen_train_test_sets( 36 | B, ntrain=n, ntest=10, seed_train=(i + 1) * len(ns) + j 37 | ) 38 | 39 | # Predict with each model 40 | f1, var1 = fit_and_predict_alebo(B, train_X, train_Y, train_Yvar, test_X, mu, sigma) 41 | f3, var3 = fit_and_predict_ARDRBF(B, train_X, train_Y, train_Yvar, test_X, mu, sigma) 42 | ll_alebo[i, j] = compute_ll(f1, var1, test_Y) 43 | ll_ard[i, j] = compute_ll(f3, var3, test_Y) 44 | 45 | # Save outcome 46 | with open('data/figS3_sim_output.pckl', 'wb') as fout: 47 | pickle.dump((ns, ll_alebo, ll_ard), fout) 48 | 49 | 50 | def make_fig_S3(): 51 | with open('data/figS3_sim_output.pckl', 'rb') as fin: 52 | (ns, ll_alebo, ll_ard) = pickle.load(fin) 53 | 54 | ntest = 1000. 55 | nrep = 20 56 | 57 | fig = plt.figure(figsize=(3, 2)) 58 | ax = fig.add_subplot(111) 59 | ax.errorbar(ns, ll_alebo.mean(axis=0) / ntest, yerr=2 * ll_alebo.std(axis=0)/ ntest / np.sqrt(nrep)) 60 | ax.errorbar(ns, ll_ard.mean(axis=0) / ntest, yerr=2 * ll_ard.std(axis=0)/ ntest / np.sqrt(nrep)) 61 | ax.grid(alpha=0.2) 62 | ax.set_ylabel('Average test-set\nlog likelihood', fontsize=9) 63 | ax.set_xlabel('Training set size', fontsize=9) 64 | ax.legend(['Mahalanobis, sampled', 'ARD RBF'], fontsize=7, loc='lower right') 65 | 66 | plt.subplots_adjust(right=0.995, bottom=0.19, left=0.21, top=0.98, wspace=0.3) 67 | plt.savefig('pdfs/log_likelihood.pdf', pad_inches=0) 68 | 69 | if __name__ == '__main__': 70 | run_simulation() # Produces data/figS3_sim_output.pckl 71 | make_fig_S3() 72 | -------------------------------------------------------------------------------- /figs/fig_S4.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import pickle 6 | 7 | from fig_1 import * 8 | 9 | 10 | def evaluate_function_in_polytope(): 11 | # Generate projection matrix 12 | np.random.seed(3) 13 | B0 = np.random.randn(2, 100) # A REMBO projection 14 | B = B0 / np.sqrt((B0 ** 2).sum(axis=0)) # A hypersphere projection 15 | 16 | # Generate grid in low-d space 17 | b = 60. # Something big to be sure we capture the whole range 18 | density = 1000 19 | grid_x = np.linspace(-b, b, density) 20 | grid_y = np.linspace(-b, b, density) 21 | grid2_x, grid2_y = np.meshgrid(grid_x, grid_y) 22 | X = np.array([grid2_x.flatten(), grid2_y.flatten()]).transpose() 23 | 24 | # Project up 25 | Y = (np.linalg.pinv(B) @ X.transpose()).transpose() 26 | z = ((Y<-1).any(axis=1) | (Y>1).any(axis=1)) # Points outside box bounds 27 | Y[z, :] = 0. # Set them to 0 for now; we'll drop them later 28 | fs = branin_centered(Y[:, :2]) 29 | # Drop points that violate polytope constraints in (1) 30 | fs[z] = np.nan 31 | fs = fs.reshape(grid2_x.shape) 32 | 33 | # Same thing with B0 instead of B. 34 | Y = (np.linalg.pinv(B0) @ X.transpose()).transpose() 35 | z = ((Y<-1).any(axis=1) | (Y>1).any(axis=1)) # Points outside box bounds 36 | Y[z, :] = 0. # Set them to 0 for now; we'll drop them later 37 | fs_B0 = branin_centered(Y[:, :2]) 38 | fs_B0[z] = np.nan # Drop points outside the box bounds 39 | fs_B0 = fs_B0.reshape(grid2_x.shape) 40 | with open('data/figS4_sim_output.pckl', 'wb') as fout: 41 | pickle.dump((grid_x, grid_y, fs, fs_B0), fout) 42 | 43 | 44 | def make_fig_S4(): 45 | with open('data/figS4_sim_output.pckl', 'rb') as fin: 46 | grid_x, grid_y, fs, fs_B0 = pickle.load(fin) 47 | 48 | fig = plt.figure(figsize=(5.5, 2)) 49 | plt.set_cmap('RdBu_r') 50 | 51 | ax = fig.add_subplot(121) 52 | CS1 = ax.contourf(grid_x, grid_y, np.log(fs_B0), levels=np.linspace(-1, 6, 30)) 53 | ax.grid(False) 54 | ax.set_xlabel(r'$x_1$', fontsize=9) 55 | ax.set_ylabel(r'$x_2$', fontsize=9) 56 | ax.set_xlim([-45, 45]) 57 | ax.set_ylim([-35, 35]) 58 | 59 | ax = fig.add_subplot(122) 60 | CS1 = ax.contourf(grid_x, grid_y, np.log(fs), levels=np.linspace(-1, 6, 30)) 61 | ax.grid(False) 62 | ax.set_xlabel(r'$x_1$', fontsize=9) 63 | ax.set_ylabel(r'$x_2$', fontsize=9) 64 | ax.set_xlim([-62, 62]) 65 | ax.set_ylim([-50, 50]) 66 | 67 | plt.subplots_adjust(right=0.99, top=0.99, left=0.1, bottom=0.17, wspace=0.45) 68 | plt.savefig('pdfs/new_embedding.pdf', pad_inches=0) 69 | 70 | 71 | if __name__ == '__main__': 72 | #evaluate_function_in_polytope() # Takes 20s to run, creates data/figS4_sim_output.pckl 73 | make_fig_S4() 74 | -------------------------------------------------------------------------------- /benchmarks/run_turbo_benchmarks.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | """ 6 | Run benchmarks for TuRBO. 7 | 8 | Requires installing turbo from https://github.com/uber-research/TuRBO. 9 | 10 | The experiments here used version 0.0.1 (commit 8461f9c). 11 | """ 12 | import os 13 | os.environ['OPENBLAS_NUM_THREADS'] = '1' 14 | os.environ['OMP_NUM_THREADS'] = '1' 15 | 16 | import json 17 | import numpy as np 18 | 19 | from benchmark_problems import ( 20 | branin_100, 21 | hartmann6_100, 22 | hartmann6_1000, 23 | hartmann6_random_subspace_1000, 24 | ) 25 | 26 | from ax.benchmark.benchmark import benchmark_minimize_callable 27 | from ax.storage.json_store.encoder import object_to_json 28 | import turbo 29 | 30 | 31 | def run_hartmann6_benchmarks(D, rep, random_subspace=False): 32 | if D == 100: 33 | problem = hartmann6_100 34 | elif D == 1000 and not random_subspace: 35 | problem = hartmann6_1000 36 | elif D == 1000 and random_subspace: 37 | problem = hartmann6_random_subspace_1000 38 | 39 | experiment, f = benchmark_minimize_callable( 40 | problem=problem, 41 | num_trials=200, 42 | method_name='turbo', 43 | replication_index=rep, 44 | ) 45 | 46 | turbo1 = turbo.Turbo1( 47 | f=f, 48 | lb=np.zeros(D), 49 | ub=np.ones(D), 50 | n_init=10, 51 | max_evals=200, 52 | ) 53 | 54 | turbo1.optimize() 55 | 56 | rs_str = 'random_subspace_' if random_subspace else '' 57 | with open(f'results/hartmann6_{rs_str}{D}_turbo_rep_{rep}.json', "w") as fout: 58 | json.dump(object_to_json(experiment), fout) 59 | 60 | 61 | def run_branin_benchmarks(rep): 62 | 63 | experiment, f = benchmark_minimize_callable( 64 | problem=branin_100, 65 | num_trials=50, 66 | method_name='turbo', 67 | replication_index=rep, 68 | ) 69 | 70 | turbo1 = turbo.Turbo1( 71 | f=f, 72 | lb=np.hstack((-5 * np.ones(50), np.zeros(50))), 73 | ub=np.hstack((10 * np.ones(50), 15 * np.ones(50))), 74 | n_init=10, 75 | max_evals=50, 76 | ) 77 | 78 | turbo1.optimize() 79 | 80 | with open(f'results/branin_100_turbo_rep_{rep}.json', "w") as fout: 81 | json.dump(object_to_json(experiment), fout) 82 | 83 | 84 | if __name__ == '__main__': 85 | # Run all of the TuRBO experiments. 86 | # These can be distributed. 87 | 88 | for i in range(50): 89 | # Hartmann6, D=100: Each rep takes ~15 mins 90 | run_hartmann6_benchmarks(D=100, rep=i) 91 | 92 | # Hartmann6, D=1000: Each rep takes ~30 mins 93 | run_hartmann6_benchmarks(D=1000, rep=i) 94 | 95 | # Branin, D=100: Each rep takes ~5 mins 96 | run_branin_benchmarks(rep=i) 97 | 98 | # Hartmann6 random subspace, D=1000 99 | run_hartmann6_benchmarks(D=1000, rep=i, random_subspace=True) 100 | -------------------------------------------------------------------------------- /benchmarks/run_nasbench.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | """ 6 | Run NASBench benchmarks 7 | """ 8 | import os 9 | os.environ['OPENBLAS_NUM_THREADS'] = '1' 10 | os.environ['OMP_NUM_THREADS'] = '1' 11 | 12 | import json 13 | import numpy as np 14 | 15 | # This loads the nasbench dataset, which takes ~30s 16 | from nasbench_evaluation import ( 17 | get_nasbench_ax_client, 18 | evaluate_parameters, 19 | NASBenchRunner, 20 | ) 21 | 22 | from ax.modelbridge.registry import Models 23 | from ax.modelbridge.generation_strategy import GenerationStep, GenerationStrategy 24 | from ax.modelbridge.strategies.alebo import ALEBOStrategy 25 | from ax.modelbridge.strategies.rembo import HeSBOStrategy, REMBOStrategy 26 | from ax.storage.json_store.encoder import object_to_json 27 | from ax.core.data import Data 28 | 29 | import turbo 30 | import cma 31 | 32 | 33 | def run_nasbench_benchmarks_ax(rep): 34 | """ 35 | Runs the Ax methods on the nasbench benchmark 36 | (Sobol, ALEBO, HeSBO, REMBO) 37 | """ 38 | gs_list = [ 39 | GenerationStrategy(name="Sobol", steps=[GenerationStep(model=Models.SOBOL, num_trials=-1)]), 40 | ALEBOStrategy(D=36, d=12, init_size=10), 41 | HeSBOStrategy(D=36, d=12, init_per_proj=10), 42 | REMBOStrategy(D=36, d=12, init_per_proj=4), 43 | ] 44 | for gs in gs_list: 45 | try: 46 | axc = get_nasbench_ax_client(gs) 47 | for i in range(50): 48 | param_dict_i, trial_index = axc.get_next_trial() 49 | raw_data = evaluate_parameters(param_dict_i) 50 | axc.complete_trial(trial_index=trial_index, raw_data=raw_data) 51 | with open(f'results/nasbench_{gs.name}_rep_{rep}.json', 'w') as fout: 52 | json.dump(object_to_json(axc.experiment), fout) 53 | except Exception: 54 | pass 55 | return 56 | 57 | 58 | def run_nasbench_benchmarks_turbo(rep): 59 | r = NASBenchRunner(max_eval=50) 60 | turbo1 = turbo.Turbo1( 61 | f=r.f, 62 | lb=np.zeros(36), 63 | ub=np.ones(36), 64 | n_init=10, 65 | max_evals=50, 66 | batch_size=1, 67 | ) 68 | turbo1.optimize() 69 | with open(f'results/nasbench_turbo_rep_{rep}.json', "w") as fout: 70 | json.dump((r.fs, r.feas), fout) 71 | 72 | 73 | def run_nasbench_benchmarks_cmaes(rep): 74 | r = NASBenchRunner(max_eval=50) 75 | try: 76 | cma.fmin( 77 | objective_function=r.f, 78 | x0=[0.5] * 36, 79 | sigma0=0.25, 80 | options={ 81 | 'bounds': [[0.0] * 36, [1.0] * 36], 82 | 'maxfevals': 50, 83 | }, 84 | ) 85 | except ValueError: 86 | pass # CMA-ES doesn't always terminate at exactly maxfevals 87 | with open(f'results/nasbench_cmaes_rep_{rep}.json', "w") as fout: 88 | json.dump((r.fs, r.feas), fout) 89 | 90 | 91 | if __name__ == '__main__': 92 | for rep in range(100): 93 | run_nasbench_benchmarks_cmaes(rep) 94 | run_nasbench_benchmarks_turbo(rep) 95 | run_nasbench_benchmarks_notbatch(rep) 96 | -------------------------------------------------------------------------------- /benchmarks/run_cmaes_benchmarks.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | """ 6 | Run benchmarks for CMAES. 7 | 8 | Requires installing cma from pip. The experiments here used version 2.7.0. 9 | """ 10 | import os 11 | os.environ['OPENBLAS_NUM_THREADS'] = '1' 12 | os.environ['OMP_NUM_THREADS'] = '1' 13 | 14 | import json 15 | 16 | from benchmark_problems import ( 17 | branin_100, 18 | hartmann6_100, 19 | hartmann6_1000, 20 | hartmann6_random_subspace_1000, 21 | ) 22 | 23 | from ax.benchmark.benchmark import benchmark_minimize_callable 24 | from ax.storage.json_store.encoder import object_to_json 25 | import cma # cma==2.7.0 26 | 27 | 28 | def run_hartmann6_benchmarks(D, rep, random_subspace=False): 29 | if D == 100: 30 | problem = hartmann6_100 31 | elif D == 1000 and not random_subspace: 32 | problem = hartmann6_1000 33 | elif D == 1000 and random_subspace: 34 | problem = hartmann6_random_subspace_1000 35 | 36 | experiment, f = benchmark_minimize_callable( 37 | problem=problem, 38 | num_trials=200, 39 | method_name='cmaes', 40 | replication_index=rep, 41 | ) 42 | 43 | try: 44 | cma.fmin( 45 | objective_function=f, 46 | x0=[0.5] * D, 47 | sigma0=0.25, 48 | options={'bounds': [[0] * D, [1] * D], 'maxfevals': 200}, 49 | ) 50 | except ValueError: 51 | pass # CMA-ES doesn't always terminate at exactly maxfevals 52 | 53 | rs_str = 'random_subspace_' if random_subspace else '' 54 | with open(f'results/hartmann6_{rs_str}{D}_cmaes_rep_{rep}.json', "w") as fout: 55 | json.dump(object_to_json(experiment), fout) 56 | 57 | 58 | def run_branin_benchmarks(rep): 59 | 60 | experiment, f = benchmark_minimize_callable( 61 | problem=branin_100, 62 | num_trials=50, 63 | method_name='cmaes', 64 | replication_index=rep, 65 | ) 66 | 67 | try: 68 | cma.fmin( 69 | objective_function=f, 70 | x0=[2.5] * 50 + [7.5] * 50, 71 | sigma0=3.75, 72 | options={ 73 | 'bounds': [[-5] * 50 + [0] * 50, [10] * 50 + [15] * 50], 74 | 'maxfevals': 50, 75 | }, 76 | ) 77 | except ValueError: 78 | pass # CMA-ES doesn't always terminate at exactly maxfevals 79 | 80 | with open(f'results/branin_100_cmaes_rep_{rep}.json', "w") as fout: 81 | json.dump(object_to_json(experiment), fout) 82 | 83 | 84 | if __name__ == '__main__': 85 | # Run all of the CMAES experiments. 86 | # These can be distributed. 87 | 88 | for i in range(50): 89 | # Hartmann6, D=100: Each rep takes ~5 s 90 | run_hartmann6_benchmarks(D=100, rep=i) 91 | 92 | # Hartmann6, D=1000: Each rep takes ~10 s 93 | run_hartmann6_benchmarks(D=1000, rep=i) 94 | 95 | # Branin, D=100: Each rep takes ~1 s 96 | run_branin_benchmarks(rep=i) 97 | 98 | # Hartmann6 random subspace, D=1000 99 | run_hartmann6_benchmarks(D=1000, rep=i, random_subspace=True) 100 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to make participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies within all project spaces, and it also applies when 49 | an individual is representing the project or its community in public spaces. 50 | Examples of representing a project or community include using an official 51 | project e-mail address, posting via an official social media account, or acting 52 | as an appointed representative at an online or offline event. Representation of 53 | a project may be further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at . All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ALEBO 2 | This is the code associated with the paper "[Re-Examining Linear Embeddings for High-Dimensional Bayesian 3 | Optimization](https://arxiv.org/abs/2001.11659)" 4 | 5 | If you find this code useful please cite it as 6 | 7 | @inproceedings{Letham2020Re, 8 | author = {Letham, Benjamin and Calandra, Roberto and Rai, Akshara and Bakshy, Eytan}, 9 | title = {Re-Examining Linear Embeddings for High-Dimensional {B}ayesian Optimization}, 10 | booktitle = {Advances in Neural Information Processing Systems 33}, 11 | year = {2020}, 12 | series = {NeurIPS}, 13 | } 14 | 15 | ## Installation 16 | To install the code clone the repo and install the dependencies as 17 | 18 | git clone https://github.com/facebookresearch/alebo.git 19 | cd alebo 20 | pip install -r requirements.txt 21 | 22 | Some of the baselines require additional packages that can not be pip-installed. 23 | Detailed instructions can be found inside each file of the `benchmarks/` folder. 24 | 25 | ## Using ALEBO for optimizing a function 26 | See `quickstart.ipynb` for a simple example of how to use ALEBO to optimize a function. ALEBO is built using the [Ax platform](https://ax.dev/); see instructions there on how to install via pip. You will need version 0.1.17 or later. 27 | 28 | ## Reproducing the experiments 29 | This repository contains the code required to run the benchmark experiments and generate the figures in the paper. The only exception are the DAISY figures, since the simulator is not yet open source. 30 | 31 | ### Generating figures: 32 | The `figs/` directory contains a file to generate each of the figures in the paper, as indicated by the file name. Some figures show the results of simulations; in these cases the file contains code to both run the simulation and create the figure. For example, executing `figs/fig_4.py` will run the P_opt simulation described in the paper, will store the simulation results in `figs/data/`, and will then generate the figure based on those results. The pdf for Fig. 4 will be saved in `figs/pdfs/`. 33 | 34 | ### Running benchmark experiments 35 | The `benchmarks/` directory contains code for running the benchmark BO experiments described in the paper. The benchmark problems are defined in `benchmark_problems.py`. Each method has its own script for evaluating that method on the appropriate set of benchmark problems: `run_{method}_benchmarks.py`, where `{method}` is: 36 | 37 | * `ax`, for our implementations of ALEBO, HeSBO, and REMBO 38 | * `addgpucb` for Add-GP-UCB via Dragonfly 39 | * `cmaes` for CMA-ES 40 | * `ebo` for Ensemble Bayesian Optimization 41 | * `linebo` for LineBO 42 | * `smac` for SMAC 43 | * `turbo` for TuRBO 44 | 45 | See the paper for references for each of these methods. Each file explains what needs to be done in order to run the experiments for that method. For instance, `run_cmaes_benchmarks.py` requires installing `cma` from pip; `run_ebo_benchmarks.py` requires cloning a repository. See each file for its instructions. 46 | 47 | The file `run_rrembo_benchmarks.R` provides a similar script in R for running the benchmark experiments for k-\Psi REMBO variants. These use the R package `RRembo`, and results are stored in json. 48 | 49 | All benchmark results are stored in `benchmark/results/` (the json files produced by each run of each method are not shipped in this repo). Once all of the `run_*_benchmarks.*` files have been run, `compile_benchmark_results.py` is used to compile the results from all of the different methods into a single file for each experiment. These files are `benchmarks/results/*_aggregated_results.json` and are included in this repository as the benchmark results used in the paper. 50 | 51 | Executing `figs/fig_5.py` loads these aggregated results and generates the benchmark results figure in the paper. 52 | 53 | A separate script `benchmarks/run_nasbench.py` contains all of the code for running the NASBench experiment. 54 | 55 | ### The ALEBO model and generation code 56 | The actual implementation of the ALEBO method is at: https://github.com/facebook/Ax/blob/master/ax/models/torch/alebo.py 57 | 58 | ## License 59 | This code is licensed under CC-by-NC, as found in the LICENSE file. 60 | -------------------------------------------------------------------------------- /benchmarks/nasbench_evaluation.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | """ 6 | Requires nasbench==1.0 from https://github.com/google-research/nasbench 7 | Also requires dataset nasbench_only108.tfrecord to be downloaded here. 8 | 9 | Creates an evaluation functionn for neural architecture search 10 | """ 11 | import numpy as np 12 | 13 | from ax.service.ax_client import AxClient 14 | 15 | from nasbench.lib.model_spec import ModelSpec 16 | from nasbench import api 17 | 18 | nasbench = api.NASBench('nasbench_only108.tfrecord') 19 | 20 | 21 | def get_spec(adj_indxs, op_indxs): 22 | """ 23 | Construct a NASBench spec from adjacency matrix and op indicators 24 | """ 25 | op_names = ['conv1x1-bn-relu', 'conv3x3-bn-relu', 'maxpool3x3'] 26 | ops = ['input'] 27 | ops.extend([op_names[i] for i in op_indxs]) 28 | ops.append('output') 29 | iu = np.triu_indices(7, k=1) 30 | adj_matrix = np.zeros((7, 7), dtype=np.int32) 31 | adj_matrix[(iu[0][adj_indxs], iu[1][adj_indxs])] = 1 32 | spec = ModelSpec(adj_matrix, ops) 33 | return spec 34 | 35 | 36 | def evaluate_x(x): 37 | """ 38 | Evaluate NASBench on the model defined by x. 39 | 40 | x is a 36-d array. 41 | The first 21 are for the adjacency matrix. Largest entries will have the 42 | corresponding element in the adjacency matrix set to 1, with as many 1s as 43 | possible within the NASBench model space. 44 | The last 15 are for the ops in each of the five NASBench model components. 45 | One-hot encoded for each of the 5 components, 3 options. 46 | """ 47 | assert len(x) == 36 48 | x_adj = x[:21] 49 | x_op = x[-15:] 50 | x_ord = x_adj.argsort()[::-1] 51 | op_indxs = x_op.reshape(3, 5).argmax(axis=0).tolist() 52 | last_good = None 53 | for i in range(1, 22): 54 | model_spec = get_spec(x_ord[:i], op_indxs) 55 | if model_spec.matrix is not None: 56 | # We have a connected graph 57 | # See if it has too many edges 58 | if model_spec.matrix.sum() > 9: 59 | break 60 | last_good = model_spec 61 | if last_good is None: 62 | # Could not get a valid spec from this x. Return bad metric values. 63 | return [0.80], [50 * 60] 64 | fixed_metrics, computed_metrics = nasbench.get_metrics_from_spec(last_good) 65 | test_acc = [r['final_test_accuracy'] for r in computed_metrics[108]] 66 | train_time = [r['final_training_time'] for r in computed_metrics[108]] 67 | return np.mean(test_acc), np.mean(train_time) 68 | 69 | 70 | def evaluate_parameters(parameters): 71 | x = np.array([parameters[f'x{i}'] for i in range(36)]) 72 | test_acc, train_time = evaluate_x(x) 73 | return { 74 | 'final_test_accuracy': (test_acc, 0.0), 75 | 'final_training_time': (train_time, 0.0), 76 | } 77 | 78 | 79 | def get_nasbench_ax_client(generation_strategy): 80 | # Get parameters 81 | parameters = [ 82 | { 83 | "name": f"x{i}", 84 | "type": "range", 85 | "bounds": [0, 1], 86 | "value_type": "float", 87 | "log_scale": False, 88 | } for i in range(36) 89 | ] 90 | axc = AxClient(generation_strategy=generation_strategy, verbose_logging=False) 91 | axc.create_experiment( 92 | name="nasbench", 93 | parameters=parameters, 94 | objective_name="final_test_accuracy", 95 | minimize=False, 96 | outcome_constraints=["final_training_time <= 1800"], 97 | ) 98 | return axc 99 | 100 | 101 | class NASBenchRunner: 102 | """ 103 | A runner for non-Ax methods. 104 | Assumes method MINIMIZES. 105 | """ 106 | def __init__(self, max_eval): 107 | # For tracking iterations 108 | self.fs = [] 109 | self.feas = [] 110 | self.n_eval = 0 111 | self.max_eval = max_eval 112 | 113 | def f(self, x): 114 | if self.n_eval >= self.max_eval: 115 | raise ValueError("Evaluation budget exhuasted") 116 | test_acc, train_time = evaluate_x(x) 117 | feas = bool(train_time <= 1800) 118 | if not feas: 119 | val = 0.80 # bad value for infeasible 120 | else: 121 | val = test_acc 122 | self.n_eval += 1 123 | self.fs.append(test_acc) # Store the true, not-negated value 124 | self.feas.append(feas) 125 | return -val # ASSUMES METHOD MINIMIZES 126 | -------------------------------------------------------------------------------- /benchmarks/run_smac_benchmarks.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | """ 6 | Run benchmarks for SMAC. 7 | 8 | Requires installing smac from pip. The experiments here used version 2.7.0. 9 | """ 10 | import os 11 | os.environ['OPENBLAS_NUM_THREADS'] = '1' 12 | os.environ['OMP_NUM_THREADS'] = '1' 13 | 14 | import json 15 | import numpy as np 16 | 17 | from benchmark_problems import ( 18 | branin_100, 19 | hartmann6_100, 20 | hartmann6_1000, 21 | hartmann6_random_subspace_1000, 22 | ) 23 | 24 | from ax.benchmark.benchmark import benchmark_minimize_callable 25 | from ax.storage.json_store.encoder import object_to_json 26 | 27 | from smac.facade.smac_hpo_facade import SMAC4HPO 28 | from smac.scenario.scenario import Scenario 29 | from smac.configspace import ConfigurationSpace 30 | from smac.runhistory.runhistory import RunKey 31 | from smac.initial_design.random_configuration_design import RandomConfigurations 32 | from smac.tae.execute_func import ExecuteTAFuncArray 33 | from ConfigSpace.hyperparameters import UniformFloatHyperparameter 34 | 35 | 36 | def fmin_smac_nopynisher(func, x0, bounds, maxfun, rng): 37 | """ 38 | Minimize a function using SMAC, but without pynisher, which doesn't work 39 | well with benchmark_minimize_callable. 40 | 41 | This function is based on SMAC's fmin_smac. 42 | """ 43 | cs = ConfigurationSpace() 44 | tmplt = 'x{0:0' + str(len(str(len(bounds)))) + 'd}' 45 | for idx, (lower_bound, upper_bound) in enumerate(bounds): 46 | parameter = UniformFloatHyperparameter( 47 | name=tmplt.format(idx + 1), 48 | lower=lower_bound, 49 | upper=upper_bound, 50 | default_value=x0[idx], 51 | ) 52 | cs.add_hyperparameter(parameter) 53 | 54 | scenario_dict = { 55 | "run_obj": "quality", 56 | "cs": cs, 57 | "deterministic": "true", 58 | "initial_incumbent": "DEFAULT", 59 | "runcount_limit": maxfun, 60 | } 61 | scenario = Scenario(scenario_dict) 62 | 63 | def call_ta(config): 64 | x = np.array([val for _, val in sorted(config.get_dictionary().items())], 65 | dtype=np.float) 66 | return func(x) 67 | 68 | smac = SMAC4HPO( 69 | scenario=scenario, 70 | tae_runner=ExecuteTAFuncArray, 71 | tae_runner_kwargs={'ta': call_ta, 'use_pynisher': False}, 72 | rng=rng, 73 | initial_design=RandomConfigurations, 74 | ) 75 | 76 | smac.optimize() 77 | return 78 | 79 | 80 | def run_hartmann6_benchmarks(D, rep, random_subspace=False): 81 | if D == 100: 82 | problem = hartmann6_100 83 | elif D == 1000 and not random_subspace: 84 | problem = hartmann6_1000 85 | elif D == 1000 and random_subspace: 86 | problem = hartmann6_random_subspace_1000 87 | 88 | experiment, f = benchmark_minimize_callable( 89 | problem=problem, 90 | num_trials=200, 91 | method_name='smac', 92 | replication_index=rep, 93 | ) 94 | 95 | fmin_smac_nopynisher( 96 | func=f, 97 | x0=[0.5] * D, 98 | bounds=[[0, 1]] * D, 99 | maxfun=200, 100 | rng=rep + 1, 101 | ) 102 | 103 | rs_str = 'random_subspace_' if random_subspace else '' 104 | with open(f'results/hartmann6_{rs_str}{D}_smac_rep_{rep}.json', "w") as fout: 105 | json.dump(object_to_json(experiment), fout) 106 | 107 | 108 | def run_branin_benchmarks(rep): 109 | 110 | experiment, f = benchmark_minimize_callable( 111 | problem=branin_100, 112 | num_trials=50, 113 | method_name='smac', 114 | replication_index=rep, 115 | ) 116 | 117 | fmin_smac_nopynisher( 118 | func=f, 119 | x0=[2.5] * 50 + [7.5] * 50, 120 | bounds=[[-5, 10]] * 50 + [[0, 15]] * 50, 121 | maxfun=50, 122 | rng=rep + 1, 123 | ) 124 | 125 | with open(f'results/branin_100_smac_rep_{rep}.json', "w") as fout: 126 | json.dump(object_to_json(experiment), fout) 127 | 128 | 129 | if __name__ == '__main__': 130 | # Run all of the SMAC experiments. 131 | # These can be distributed. 132 | 133 | for i in range(50): 134 | # Hartmann6, D=100: Each rep takes ~1.5 hours 135 | run_hartmann6_benchmarks(D=100, rep=i) 136 | 137 | # Branin, D=100: Each rep takes ~20 mins 138 | run_branin_benchmarks(rep=i) 139 | 140 | # Hartmann6, D=1000: Each rep takes ~36 hours 141 | for i in range(10): 142 | run_hartmann6_benchmarks(D=1000, rep=i) 143 | 144 | # Hartmann6 random subspace, D=1000 145 | run_hartmann6_benchmarks(D=1000, rep=i, random_subspace=True) 146 | -------------------------------------------------------------------------------- /benchmarks/ablation_models.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | from typing import Any, Callable, Dict, List, MutableMapping, Optional, Tuple, Union 6 | 7 | from ax.models.torch.botorch_defaults import get_and_fit_model 8 | from ax.modelbridge.strategies.alebo import ALEBOStrategy, get_ALEBOInitializer 9 | 10 | import torch 11 | from torch import Tensor 12 | from ax.core.data import Data 13 | from ax.core.experiment import Experiment 14 | from ax.core.search_space import SearchSpace 15 | from ax.modelbridge.factory import DEFAULT_TORCH_DEVICE 16 | from ax.modelbridge.generation_strategy import GenerationStep, GenerationStrategy 17 | from ax.modelbridge.random import RandomModelBridge 18 | from ax.modelbridge.torch import TorchModelBridge 19 | from ax.modelbridge.transforms.centered_unit_x import CenteredUnitX 20 | from ax.modelbridge.transforms.standardize_y import StandardizeY 21 | from botorch.models.gpytorch import GPyTorchModel 22 | from ax.models.torch.alebo import ALEBO 23 | 24 | 25 | class ALEBO_kernel_ablation(ALEBO): 26 | 27 | def get_and_fit_model( 28 | self, 29 | Xs: List[Tensor], 30 | Ys: List[Tensor], 31 | Yvars: List[Tensor], 32 | state_dicts: Optional[List[MutableMapping[str, Tensor]]] = None, 33 | ) -> GPyTorchModel: 34 | return get_and_fit_model( 35 | Xs=Xs, 36 | Ys=Ys, 37 | Yvars=Yvars, 38 | task_features=[], 39 | fidelity_features=[], 40 | metric_names=[], 41 | state_dict=None, 42 | ) 43 | 44 | 45 | def get_ALEBO_kernel_ablation( 46 | experiment: Experiment, 47 | search_space: SearchSpace, 48 | data: Data, 49 | B: torch.Tensor, 50 | **model_kwargs: Any, 51 | ) -> TorchModelBridge: 52 | if search_space is None: 53 | search_space = experiment.search_space 54 | return TorchModelBridge( 55 | experiment=experiment, 56 | search_space=search_space, 57 | data=data, 58 | model=ALEBO_kernel_ablation(B=B, **model_kwargs), 59 | transforms=[CenteredUnitX, StandardizeY], 60 | torch_dtype=B.dtype, 61 | torch_device=B.device, 62 | ) 63 | 64 | 65 | class ALEBOStrategy_kernel_ablation(GenerationStrategy): 66 | 67 | def __init__( 68 | self, 69 | D: int, 70 | d: int, 71 | init_size: int, 72 | name: str = "ALEBO", 73 | dtype: torch.dtype = torch.double, 74 | device: torch.device = DEFAULT_TORCH_DEVICE, 75 | random_kwargs: Optional[Dict[str, Any]] = None, 76 | gp_kwargs: Optional[Dict[str, Any]] = None, 77 | gp_gen_kwargs: Optional[Dict[str, Any]] = None, 78 | ) -> None: 79 | self.D = D 80 | self.d = d 81 | self.init_size = init_size 82 | self.dtype = dtype 83 | self.device = device 84 | self.random_kwargs = random_kwargs if random_kwargs is not None else {} 85 | self.gp_kwargs = gp_kwargs if gp_kwargs is not None else {} 86 | self.gp_gen_kwargs = gp_gen_kwargs 87 | 88 | B = self.gen_projection(d=d, D=D, device=device, dtype=dtype) 89 | 90 | self.gp_kwargs.update({"B": B}) 91 | self.random_kwargs.update({"B": B.cpu().numpy()}) 92 | 93 | steps = [ 94 | GenerationStep( 95 | model=get_ALEBOInitializer, 96 | num_arms=init_size, 97 | model_kwargs=self.random_kwargs, 98 | ), 99 | GenerationStep( 100 | model=get_ALEBO_kernel_ablation, 101 | num_arms=-1, 102 | model_kwargs=self.gp_kwargs, 103 | model_gen_kwargs=gp_gen_kwargs, 104 | ), 105 | ] 106 | super().__init__(steps=steps, name=name) 107 | 108 | def clone_reset(self) -> "ALEBOStrategy": 109 | """Copy without state.""" 110 | return self.__class__( 111 | D=self.D, 112 | d=self.d, 113 | init_size=self.init_size, 114 | name=self.name, 115 | dtype=self.dtype, 116 | device=self.device, 117 | random_kwargs=self.random_kwargs, 118 | gp_kwargs=self.gp_kwargs, 119 | gp_gen_kwargs=self.gp_gen_kwargs, 120 | ) 121 | 122 | def gen_projection( 123 | self, d: int, D: int, dtype: torch.dtype, device: torch.device 124 | ) -> torch.Tensor: 125 | """Generate the projection matrix B as a (d x D) tensor 126 | """ 127 | B0 = torch.randn(d, D, dtype=dtype, device=device) 128 | B = B0 / torch.sqrt((B0 ** 2).sum(dim=0)) 129 | return B 130 | 131 | 132 | class ALEBOStrategy_projection_ablation(ALEBOStrategy): 133 | def gen_projection( 134 | self, d: int, D: int, dtype: torch.dtype, device: torch.device 135 | ) -> torch.Tensor: 136 | B0 = torch.randn(d, D, dtype=dtype, device=device) 137 | return B0 138 | -------------------------------------------------------------------------------- /figs/fig_4.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import pickle 6 | import time 7 | import torch 8 | import numpy as np 9 | import cvxpy as cp # 1.0.25 10 | 11 | from plot_config import * 12 | 13 | 14 | def gen_A_rembo(d: int, D: int) -> np.ndarray: 15 | A = torch.randn(D, d, dtype=torch.double) 16 | return A.numpy() 17 | 18 | def gen_A_hesbo(d: int, D:int) -> np.ndarray: 19 | A = torch.zeros((D, d), dtype=torch.double) 20 | h = torch.randint(d, size=(D,)) 21 | s = 2 * torch.randint(2, size=(D,), dtype=torch.double) - 1 22 | for i in range(D): 23 | A[i, h[i]] = s[i] 24 | return A.numpy() 25 | 26 | def gen_A_unitsphere(d: int, D: int) -> np.ndarray: 27 | A = np.random.randn(D, d) # A REMBO projection _up_ 28 | A = A / np.sqrt((A ** 2).sum(axis=1))[:, None] 29 | return A 30 | 31 | def A_contains_xstar(xstar, A, perm): 32 | d = len(xstar) 33 | D = A.shape[0] 34 | Acon = np.zeros((d, D)) 35 | Acon[:d, :d] = np.diag(np.ones(d)) 36 | # Shuffle columns, to place true embedding on columns perm 37 | Acon = Acon[:, perm] 38 | Q = A @ np.linalg.pinv(A) - np.eye(D) 39 | A_eq = np.vstack((Acon, Q)) 40 | b_eq = np.hstack((xstar, np.zeros(D))) 41 | 42 | c = np.zeros(D) 43 | 44 | x = cp.Variable(D) 45 | prob = cp.Problem( 46 | cp.Minimize(c.T * x), 47 | [ 48 | A_eq @ x == b_eq, 49 | x >= -1, 50 | x <= 1, 51 | ], 52 | ) 53 | prob.solve(solver=cp.ECOS) 54 | 55 | if prob.status == cp.OPTIMAL: 56 | has_opt = True 57 | elif prob.status == cp.INFEASIBLE: 58 | has_opt = False 59 | else: 60 | raise ValueError(prob.status) 61 | return has_opt, prob 62 | 63 | def p_A_contains_optimizer(d, D, d_use, gen_A_fn, nsamp): 64 | num_feas = 0. 65 | for _ in range(nsamp): 66 | # Sample location of optimizer uniformly on [-1, 1]^d 67 | xstar = np.random.rand(d) * 2 - 1 68 | # Sample features of embedding (first d) uniformly at random 69 | perm = list(range(D)) 70 | np.random.shuffle(perm) 71 | # Generate projection matrix 72 | A = gen_A_fn(d_use, D) 73 | has_opt, _ = A_contains_xstar(xstar, A, perm) 74 | num_feas += float(has_opt) 75 | return num_feas / nsamp 76 | 77 | def run_simulation1(): 78 | t1 = time.time() 79 | nsamp = 1000 80 | res = {'rembo': {}, 'hesbo': {}, 'unitsphere': {}} 81 | D = 100 82 | for d in [2, 6, 10]: 83 | for d_use in range(1, 21): 84 | if d_use < d: 85 | continue 86 | res['rembo'][(D, d, d_use)] = p_A_contains_optimizer( 87 | d=d, D=D, d_use=d_use, gen_A_fn=gen_A_rembo, nsamp=nsamp 88 | ) 89 | res['hesbo'][(D, d, d_use)] = p_A_contains_optimizer( 90 | d=d, D=D, d_use=d_use, gen_A_fn=gen_A_hesbo, nsamp=nsamp 91 | ) 92 | res['unitsphere'][(D, d, d_use)] = p_A_contains_optimizer( 93 | d=d, D=D, d_use=d_use, gen_A_fn=gen_A_unitsphere, nsamp=nsamp 94 | ) 95 | print(time.time() - t1) 96 | with open('data/fig4_sim_output.pckl', 'wb') as fout: 97 | pickle.dump(res, fout) 98 | 99 | def make_fig_4(): 100 | with open('data/fig4_sim_output.pckl', 'rb') as fin: 101 | res = pickle.load(fin) 102 | 103 | nsamp = 1000 104 | fig = plt.figure(figsize=(2.63, 1.45)) 105 | for i, d in enumerate([2, 6]): 106 | ax = fig.add_subplot(1, 2, i + 1) 107 | x = [d_use for d_use in range(21) if d_use >= d] 108 | y1 = np.array([res['rembo'][(100, d, d_use)] for d_use in x]) 109 | y2 = np.array([res['hesbo'][(100, d, d_use)] for d_use in x]) 110 | y3 = np.array([res['unitsphere'][(100, d, d_use)] for d_use in x]) 111 | y1err = 2 * np.sqrt(y1 * (1 - y1) / nsamp) 112 | y2err = 2 * np.sqrt(y2 * (1 - y2) / nsamp) 113 | y3err = 2 * np.sqrt(y3 * (1 - y3) / nsamp) 114 | ax.errorbar(x, y1, yerr=y1err, color=plt.cm.tab10(0), marker='') 115 | ax.errorbar(x, y2, yerr=y2err, color=plt.cm.tab10(1), marker='') 116 | ax.errorbar(x, y3, yerr=y3err, color=plt.cm.tab10(2), marker='') 117 | ax.set_title(r'$d={d}$'.format(d=d)) 118 | if i == 0: 119 | ax.set_ylabel(r'$P_{\textrm{opt}}$', fontsize=9) 120 | ax.legend(['REMBO', 'HeSBO', r'Hypersphere'], loc='lower right', fontsize=5) 121 | ax.set_xlabel(r'$d_e$', fontsize=9) 122 | ax.set_xlim([0, 21]) 123 | ax.set_ylim([-0.02, 1.02]) 124 | ax.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0]) 125 | if i > 0: 126 | ax.set_yticklabels([]) 127 | ax.grid(True, alpha=0.2) 128 | 129 | plt.subplots_adjust(right=0.99, bottom=0.23, left=0.17, top=0.87, wspace=0.1) 130 | 131 | plt.savefig('pdfs/lp_solns.pdf', pad_inches=0) 132 | 133 | if __name__ == '__main__': 134 | #run_simulation1() # Will take about 30mins, produces data/fig4_sim_output.pckl 135 | make_fig_4() 136 | -------------------------------------------------------------------------------- /benchmarks/run_ebo_benchmarks.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | """ 6 | Run benchmarks for Ensemble BO. 7 | 8 | A few steps are required to use EBO: 9 | 10 | (1) git clone https://github.com/zi-w/Ensemble-Bayesian-Optimization 11 | in this directory. These experiments used commit 12 | 4e6f9ed04833cc2e21b5906b1181bc067298f914. 13 | 14 | (2) fix a python3 issue by editing ebo_core/helper.py to insert 15 | shape = int(shape) 16 | in line 7. 17 | """ 18 | import os 19 | os.environ['OPENBLAS_NUM_THREADS'] = '1' 20 | os.environ['OMP_NUM_THREADS'] = '1' 21 | 22 | import sys 23 | sys.path.insert(1, os.path.join(os.getcwd(), 'Ensemble-Bayesian-Optimization')) 24 | from ebo_core.ebo import ebo 25 | 26 | import json 27 | import numpy as np 28 | 29 | from benchmark_problems import ( 30 | branin_100, 31 | hartmann6_100, 32 | hartmann6_1000, 33 | ) 34 | 35 | from ax.benchmark.benchmark import benchmark_minimize_callable 36 | from ax.storage.json_store.encoder import object_to_json 37 | 38 | 39 | # These options are taken as package defaults from test_ebo.py 40 | core_options = { 41 | #'x_range':x_range, # input domain 42 | #'dx':x_range.shape[1], # input dimension 43 | #'max_value':f.f_max + sigma*5, # target value 44 | #'T':10, # number of iterations 45 | 'B':10, # number of candidates to be evaluated 46 | 'dim_limit':3, # max dimension of the input for each additive function component 47 | 'isplot':0, # 1 if plotting the result; otherwise 0. 48 | 'z':None, 'k':None, # group assignment and number of cuts in the Gibbs sampling subroutine 49 | 'alpha':1., # hyperparameter of the Gibbs sampling subroutine 50 | 'beta':np.array([5.,2.]), 51 | 'opt_n':1000, # points randomly sampled to start continuous optimization of acfun 52 | 'pid':'test3', # process ID for Azure 53 | 'datadir':'tmp_data/', # temporary data directory for Azure 54 | 'gibbs_iter':10, # number of iterations for the Gibbs sampling subroutine 55 | 'useAzure':False, # set to True if use Azure for batch evaluation 56 | 'func_cheap':True, # if func cheap, we do not use Azure to test functions 57 | 'n_add':None, # this should always be None. it makes dim_limit complicated if not None. 58 | 'nlayers': 100, # number of the layers of tiles 59 | 'gp_type':'l1', # other choices are l1, sk, sf, dk, df 60 | #'gp_sigma':0.1, # noise standard deviation 61 | 'n_bo':10, # min number of points selected for each partition 62 | 'n_bo_top_percent': 0.5, # percentage of top in bo selections 63 | 'n_top':10, # how many points to look ahead when doing choose Xnew 64 | 'min_leaf_size':10, # min number of samples in each leaf 65 | 'max_n_leaves':10, # max number of leaves 66 | 'thresAzure':1, # if batch size > thresAzure, we use Azure 67 | 'save_file_name': 'tmp/tmp.pk', 68 | } 69 | 70 | 71 | def run_hartmann6_benchmarks(D, rep): 72 | if D == 100: 73 | problem = hartmann6_100 74 | elif D == 1000: 75 | problem = hartmann6_1000 76 | 77 | experiment, f = benchmark_minimize_callable( 78 | problem=problem, 79 | num_trials=200, 80 | method_name='ebo', 81 | replication_index=rep, 82 | ) 83 | 84 | options = { 85 | 'x_range': np.vstack((np.zeros(D), np.ones(D))), 86 | 'dx': D, 87 | 'max_value': 3.32237, # Let it cheat and know the true max value 88 | 'T': 200, 89 | 'gp_sigma': 1e-7, 90 | } 91 | options.update(core_options) 92 | 93 | f_max = lambda x: -f(x) # since EBO maximizes 94 | 95 | e = ebo(f_max, options) 96 | try: 97 | e.run() 98 | except ValueError: 99 | pass # EBO can ask for more than T function evaluations 100 | 101 | with open(f'results/hartmann6_{D}_ebo_rep_{rep}.json', "w") as fout: 102 | json.dump(object_to_json(experiment), fout) 103 | 104 | 105 | def run_branin_benchmarks(rep): 106 | 107 | experiment, f = benchmark_minimize_callable( 108 | problem=branin_100, 109 | num_trials=50, 110 | method_name='ebo', 111 | replication_index=rep, 112 | ) 113 | 114 | options = { 115 | 'x_range': np.vstack(( 116 | np.hstack((-5 * np.ones(50), np.zeros(50))), 117 | np.hstack((10 * np.ones(50), 15 * np.ones(50))), 118 | )), 119 | 'dx': 100, 120 | 'max_value': -0.397887, # Let it cheat and know the true max value 121 | 'T': 50, 122 | 'gp_sigma': 1e-7, 123 | } 124 | options.update(core_options) 125 | 126 | f_max = lambda x: -f(x) # since EBO maximizes 127 | 128 | e = ebo(f_max, options) 129 | try: 130 | e.run() 131 | except ValueError: 132 | pass # EBO can ask for more than T function evaluations 133 | 134 | with open(f'results/branin_100_ebo_rep_{rep}.json', "w") as fout: 135 | json.dump(object_to_json(experiment), fout) 136 | 137 | 138 | if __name__ == '__main__': 139 | # Run all of the EBO benchmarks. 140 | # These can be distributed. 141 | 142 | for i in range(50): 143 | # Hartmann6, D=100: Each rep takes ~2 hours 144 | run_hartmann6_benchmarks(D=100, rep=i) 145 | 146 | ## Hartmann6, D=1000: Too slow, not run 147 | #run_hartmann6_benchmarks(D=1000, rep=i) 148 | 149 | # Branin, D=100: Each rep takes ~20 mins 150 | run_branin_benchmarks(rep=i) 151 | -------------------------------------------------------------------------------- /figs/fig_1.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import numpy as np 6 | 7 | from ax.utils.measurement.synthetic_functions import branin, hartmann6 8 | 9 | from plot_config import * 10 | 11 | 12 | def branin_centered(X): 13 | # Evaluate branin problem, scaled to X \in [-1, 1]^2 14 | # Map from [-1, 1]^2 to [[-5, 10], [0, 15]] 15 | assert X.min() >= -1 16 | assert X.max() <= 1 17 | Xu = (X + 1) / 2. 18 | Xu *= 15 19 | Xu[:, 0] -= 5 20 | return branin(Xu) 21 | 22 | def hartmann6_centered(X): 23 | # Evaluate hartmann6 problem, scaled to X \in [-1, 1]^2 24 | # Map from [-1, 1]^6 to [0, 1]^6 25 | assert X.min() >= -1 26 | assert X.max() <= 1 27 | Xu = (X + 1) / 2. 28 | return hartmann6(Xu) 29 | 30 | def rembo_branin(X, A): 31 | # Map from low-d to high-D 32 | Y = (A @ X.transpose()).transpose() 33 | # Clip to [-1, 1] 34 | Y = np.clip(Y, a_min=-1, a_max=1) 35 | # Evaluate Branin on first two components 36 | return branin_centered(Y[:, :2]) 37 | 38 | def rembo_hartmann6(X, A): 39 | # Map from low-d to high-D 40 | Y = (A @ X.transpose()).transpose() 41 | # Clip to [-1, 1] 42 | Y = np.clip(Y, a_min=-1, a_max=1) 43 | # Evaluate Hartmann6 on first six components 44 | return hartmann6_centered(Y[:, :6]) 45 | 46 | def eval_f_on_grid(f, bounds_x, bounds_y, f_kwargs, d, density=100): 47 | # prepare the grid on which to evaluate the problem 48 | grid_x = np.linspace(bounds_x[0], bounds_x[1], density) 49 | grid_y = np.linspace(bounds_y[0], bounds_y[1], density) 50 | grid2_x, grid2_y = np.meshgrid(grid_x, grid_y) 51 | X = np.array([grid2_x.flatten(), grid2_y.flatten()]).transpose() 52 | if d > 2: 53 | # Add in the other components, just at 0 54 | X = np.hstack((X, np.zeros((X.shape[0], d - 2)))) 55 | fs = f(X, **f_kwargs).reshape(grid2_x.shape) 56 | return grid_x, grid_y, fs 57 | 58 | def make_fig_1(): 59 | ## Branin 60 | # Evaluate the usual Branin problem, but scaled to [-1, 1]^2 61 | grid_x1, grid_y1, fs_branin = eval_f_on_grid(branin_centered, [-1, 1], [-1, 1], {}, 2) 62 | 63 | # Generate a REMBO projection matrix 64 | D = 100 65 | np.random.seed(1) 66 | A_b = np.random.randn(D, 2) 67 | # Evaluate the function across the low-d space 68 | bounds = [-np.sqrt(2), np.sqrt(2)] 69 | grid_x2, grid_y2, fs_rembo = eval_f_on_grid(rembo_branin, bounds, bounds, {'A': A_b}, 2) 70 | 71 | ## Hartmann6 72 | # Evaluate the usual Hartmann6 problem, but scaled to [-1, 1]^6 73 | grid_x1h, grid_y1h, fs_hartmann6 = eval_f_on_grid(hartmann6_centered, [-1, 1], [-1, 1], {}, 6) 74 | 75 | # Generate a REMBO projection matrix 76 | D = 100 77 | A_h = np.random.randn(D, 6) 78 | # Evaluate the function across the low-d space 79 | bounds = [-np.sqrt(6), np.sqrt(6)] 80 | grid_x2h, grid_y2h, fs_rembo_h = eval_f_on_grid(rembo_hartmann6, bounds, bounds, {'A': A_h}, 6) 81 | 82 | # Make the figure 83 | fig = plt.figure(figsize=(5.5, 1.2), facecolor='w', edgecolor='w') 84 | plt.set_cmap('RdBu_r') 85 | 86 | ### Branin 87 | 88 | ax = fig.add_subplot(141) 89 | CS1 = ax.contourf(grid_x1, grid_y1, np.log(fs_branin), levels=np.linspace(-1, 6, 30)) 90 | ax.grid(False) 91 | #ax.set_xlabel(r'$x_1$', fontsize=9) 92 | ax.set_xlim([-1, 1]) 93 | #ax.set_xticks([-1, -0.5, 0, 0.5, 1]) 94 | ax.set_xticks([]) 95 | #ax.set_ylabel(r'$x_2$', fontsize=9) 96 | ax.set_ylim([-1, 1]) 97 | ax.set_yticks([]) 98 | #ax.set_yticks([-1, -0.5, 0, 0.5, 1]) 99 | ax.set_title(r'Branin function, $d$=2') 100 | 101 | ax = fig.add_subplot(142) 102 | CS1 = ax.contourf(grid_x2, grid_y2, np.log(fs_rembo), levels=np.linspace(-1, 6, 30)) 103 | ax.grid(False) 104 | #ax.set_xlabel(r'$x_1$', fontsize=9) 105 | ax.set_xlim([-np.sqrt(2), np.sqrt(2)]) 106 | ax.set_xticks([]) 107 | #ax.set_xticks([-1.4, -1, -0.5, 0, 0.5, 1, 1.4]) 108 | #ax.set_ylabel(r'$x_2$', fontsize=9) 109 | ax.set_ylim([-np.sqrt(2), np.sqrt(2)]) 110 | ax.set_yticks([]) 111 | #ax.set_yticks([-1.4, -1, -0.5, 0, 0.5, 1, 1.4]) 112 | ax.set_title('REMBO embedding,\n$D$=100, $d_e$=2') 113 | 114 | ### Hartmann6 115 | 116 | ax = fig.add_subplot(143) 117 | CS1f = ax.contourf(grid_x1h, grid_y1h, fs_hartmann6, levels=np.linspace(-1.2, 0., 20)) 118 | ax.grid(False) 119 | #ax.set_xlabel(r'$x_1$', fontsize=9) 120 | ax.set_xlim([-1, 1]) 121 | ax.set_xticks([]) 122 | #ax.set_xticks([-1, -0.5, 0, 0.5, 1]) 123 | #ax.set_ylabel(r'$x_2$', fontsize=9) 124 | ax.set_ylim([-1, 1]) 125 | ax.set_yticks([]) 126 | #ax.set_yticks([-1, -0.5, 0, 0.5, 1]) 127 | ax.set_title(r'Hartmann6 function, $d$=6') 128 | 129 | ax = fig.add_subplot(144) 130 | CS1f = ax.contourf(grid_x2h, grid_y2h, fs_rembo_h, levels=np.linspace(-1.2, 0., 20)) 131 | ax.grid(False) 132 | #ax.set_xlabel(r'$x_1$', fontsize=9) 133 | ax.set_xlim([-np.sqrt(6), np.sqrt(6)]) 134 | ax.set_xticks([]) 135 | #ax.set_xticks([-2, -1, 0, 1, 2,]) 136 | #ax.set_ylabel(r'$x_2$', fontsize=9) 137 | ax.set_ylim([-np.sqrt(6), np.sqrt(6)]) 138 | ax.set_yticks([]) 139 | #ax.set_yticks([-2, -1, 0, 1, 2,]) 140 | ax.set_title('REMBO embedding,\n$D$=100, $d_e$=6') 141 | 142 | fig.subplots_adjust(wspace=0.13, top=0.74, bottom=0.05, right=0.99, left=0.01) 143 | plt.savefig('pdfs/rembo_illustrations_w.pdf', pad_inches=0) 144 | 145 | if __name__ == '__main__': 146 | make_fig_1() 147 | -------------------------------------------------------------------------------- /figs/fig_S7.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import json 6 | import numpy as np 7 | 8 | from ax.storage.json_store.decoder import object_from_json 9 | 10 | from plot_config import * 11 | 12 | 13 | def make_fig_S7(): 14 | # Load in the benchmark results 15 | res = {} 16 | for fname in [ 17 | 'hartmann6_1000', 18 | 'branin_gramacy_100', 19 | 'hartmann6_100', 20 | 'hartmann6_random_subspace_1000', 21 | ]: 22 | with open(f'../benchmarks/results/{fname}_aggregated_results.json', 'r') as fin: 23 | res.update(object_from_json(json.load(fin))) 24 | 25 | # A map from method idx in plot_method_names to the name used in res 26 | method_idx_to_res_name = { 27 | 0: 'ALEBO', 28 | 1: 'REMBO', 29 | 2: 'HeSBO, d=d', 30 | 3: 'HeSBO, d=2d', 31 | 4: 'rrembos_standard_kPsi', 32 | 5: 'rrembos_reverse_kPsi', 33 | 6: 'ebo', 34 | 7: 'addgpucb', 35 | 8: 'smac', 36 | 9: 'cmaes', 37 | 10: 'turbo', 38 | 11: 'Sobol', 39 | 12: 'coordinatelinebo', 40 | 13: 'randomlinebo', 41 | 14: 'descentlinebo', 42 | } 43 | 44 | # Make the figure 45 | fig = plt.figure(figsize=(5.5, 7.5)) 46 | 47 | ####### Branin, D=100 48 | ax1 = fig.add_subplot(511) 49 | 50 | res_h = res['Branin, D=100'] 51 | 52 | for idx, m in enumerate(plot_method_names): 53 | res_name = method_idx_to_res_name[idx] 54 | if res_name not in res_h.objective_at_true_best: 55 | continue # Not run on this problem 56 | Y = np.log(res_h.objective_at_true_best[res_name] - 0.397887) 57 | f = Y.mean(axis=0) 58 | sem = Y.std(axis=0) / np.sqrt(Y.shape[0]) 59 | x = np.arange(1, 51) 60 | color = plot_colors[m] 61 | ax1.plot(x, f, color=color, label=m) 62 | ax1.errorbar(x[4::5], f[4::5], yerr=2 * sem[4::5], color=color, alpha=0.5, ls='') 63 | 64 | ax1.set_xlim([0, 51]) 65 | ax1.set_ylim([-6, 2]) 66 | ax1.set_ylabel('Log regret', fontsize=9) 67 | ax1.grid(alpha=0.2, zorder=-10) 68 | ax1.set_title(r'Branin, $d$=2, $D$=100') 69 | 70 | ####### Hartmann6, D=1000 71 | ax2 = fig.add_subplot(512) 72 | 73 | res_h = res['Hartmann6, D=1000'] 74 | 75 | for idx, m in enumerate(plot_method_names): 76 | res_name = method_idx_to_res_name[idx] 77 | if res_name not in res_h.objective_at_true_best: 78 | continue # Not run on this problem 79 | Y = np.log(res_h.objective_at_true_best[res_name] - (-3.32237)) 80 | f = Y.mean(axis=0) 81 | sem = Y.std(axis=0) / np.sqrt(Y.shape[0]) 82 | x = np.arange(1, 201) 83 | color = plot_colors[m] 84 | ax2.plot(x, f, color=color, label=m) 85 | ax2.errorbar(x[9::10], f[9::10], yerr=2 * sem[9::10], color=color, alpha=0.5, ls='') 86 | 87 | ax2.set_xlim([0, 201]) 88 | ax2.set_ylim([-2.5, 1.7]) 89 | ax2.set_ylabel('Log regret', fontsize=9) 90 | ax2.grid(alpha=0.2, zorder=-10) 91 | ax2.set_title(r'Hartmann6, $d$=6, $D$=1000') 92 | 93 | ####### Gramacy, D=100 94 | ax3 = fig.add_subplot(513) 95 | 96 | res_h = res['Gramacy, D=100'] 97 | 98 | for idx, m in enumerate(plot_method_names): 99 | res_name = method_idx_to_res_name[idx] 100 | if res_name not in res_h.objective_at_true_best: 101 | continue # Not run on this problem 102 | Y = np.log(res_h.objective_at_true_best[res_name] - 0.5998) 103 | f = Y.mean(axis=0) 104 | sem = Y.std(axis=0) / np.sqrt(Y.shape[0]) 105 | x = np.arange(1, 51) 106 | color = plot_colors[m] 107 | ax3.plot(x, f, color=color, label=m) 108 | ax3.errorbar(x[4::5], f[4::5], yerr=2 * sem[4::5], color=color, alpha=0.5, ls='') 109 | 110 | ax3.set_xlim([0, 51]) 111 | ax3.set_ylabel('Log regret', fontsize=9) 112 | ax3.grid(alpha=0.2, zorder=-10) 113 | ax3.set_title(r'Gramacy, $d$=2, $D=100$') 114 | 115 | ####### Hartmann6, D=100 116 | ax4 = fig.add_subplot(514) 117 | 118 | res_h = res['Hartmann6, D=100'] 119 | 120 | for idx, m in enumerate(plot_method_names): 121 | res_name = method_idx_to_res_name[idx] 122 | if res_name not in res_h.objective_at_true_best: 123 | continue # Not run on this problem 124 | Y = np.log(res_h.objective_at_true_best[res_name] - (-3.32237)) 125 | f = Y.mean(axis=0) 126 | sem = Y.std(axis=0) / np.sqrt(Y.shape[0]) 127 | x = np.arange(1, 201) 128 | color = plot_colors[m] 129 | ax4.plot(x, f, color=color, label=m) 130 | ax4.errorbar(x[9::10], f[9::10], yerr=2 * sem[9::10], color=color, alpha=0.5, ls='') 131 | 132 | ax4.set_xlim([0, 201]) 133 | ax4.set_ylim([-4, 1.7]) 134 | ax4.set_ylabel('Log regret', fontsize=9) 135 | ax4.grid(alpha=0.2, zorder=-10) 136 | ax4.set_title(r'Hartmann6, $d$=6, $D$=100') 137 | 138 | # Add the legend 139 | ax4.legend(bbox_to_anchor=(1.44, 5.405), fontsize=8) 140 | 141 | ####### Hartmann6 random subspace, D=1000 142 | ax5 = fig.add_subplot(515) 143 | 144 | res_h = res['Hartmann6 random subspace, D=1000'] 145 | 146 | for idx, m in enumerate(plot_method_names): 147 | res_name = method_idx_to_res_name[idx] 148 | if res_name not in res_h.objective_at_true_best: 149 | continue # Not run on this problem 150 | Y = np.log(res_h.objective_at_true_best[res_name] - (-3.32237)) 151 | f = Y.mean(axis=0) 152 | sem = Y.std(axis=0) / np.sqrt(Y.shape[0]) 153 | x = np.arange(1, 201) 154 | color = plot_colors[m] 155 | ax5.plot(x, f, color=color, label=m) 156 | ax5.errorbar(x[9::10], f[9::10], yerr=2 * sem[9::10], color=color, alpha=0.5, ls='') 157 | 158 | ax5.set_xlim([0, 201]) 159 | ax5.set_ylim([-2.1, 1.7]) 160 | ax5.set_xlabel('Function evaluations', fontsize=9) 161 | ax5.set_ylabel('Log regret', fontsize=9) 162 | ax5.grid(alpha=0.2, zorder=-10) 163 | ax5.set_title(r'Hartmann6, $d$=6 random subspace, $D$=1000') 164 | 165 | plt.subplots_adjust(right=0.72, bottom=0.06, left=0.08, top=0.97, hspace=0.45) 166 | plt.savefig('pdfs/log_regrets.pdf', pad_inches=0) 167 | 168 | 169 | if __name__ == '__main__': 170 | make_fig_S7() 171 | -------------------------------------------------------------------------------- /benchmarks/run_ax_benchmarks.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | """ 6 | Run benchmarks for: ALEBO, REMBO, HeSBO, and Sobol. 7 | """ 8 | import os 9 | os.environ['OPENBLAS_NUM_THREADS'] = '1' 10 | os.environ['OMP_NUM_THREADS'] = '1' 11 | 12 | import json 13 | 14 | from benchmark_problems import ( 15 | branin_100, 16 | branin_by_D, 17 | gramacy_100, 18 | hartmann6_100, 19 | hartmann6_1000, 20 | hartmann6_random_subspace_1000, 21 | ) 22 | 23 | from ablation_models import ( 24 | ALEBOStrategy_projection_ablation, 25 | ALEBOStrategy_kernel_ablation, 26 | ) 27 | 28 | from ax.benchmark.benchmark import full_benchmark_run 29 | from ax.benchmark.benchmark_result import aggregate_problem_results 30 | from ax.modelbridge.registry import Models 31 | from ax.modelbridge.generation_strategy import GenerationStep, GenerationStrategy 32 | from ax.modelbridge.strategies.alebo import ALEBOStrategy 33 | from ax.modelbridge.strategies.rembo import HeSBOStrategy, REMBOStrategy 34 | from ax.storage.json_store.encoder import object_to_json 35 | 36 | 37 | def run_hartmann6_benchmarks(D, rep, random_subspace=False): 38 | if D == 100: 39 | problem = hartmann6_100 40 | elif D == 1000 and not random_subspace: 41 | problem = hartmann6_1000 42 | elif D == 1000 and random_subspace: 43 | problem = hartmann6_random_subspace_1000 44 | 45 | strategy0 = GenerationStrategy( 46 | name="Sobol", 47 | steps=[ 48 | GenerationStep( 49 | model=Models.SOBOL, num_arms=-1, model_kwargs={'seed': rep + 1} 50 | ) 51 | ], 52 | ) 53 | strategy1 = ALEBOStrategy(D=D, d=12, init_size=10) 54 | strategy2 = REMBOStrategy(D=D, d=6, init_per_proj=2) 55 | strategy3 = HeSBOStrategy(D=D, d=6, init_per_proj=10, name=f"HeSBO, d=d") 56 | strategy4 = HeSBOStrategy(D=D, d=12, init_per_proj=10, name=f"HeSBO, d=2d") 57 | 58 | all_benchmarks = full_benchmark_run( 59 | num_replications=1, # Running them 1 at a time for distributed 60 | num_trials=200, 61 | batch_size=1, 62 | methods=[strategy0, strategy1, strategy2, strategy3, strategy4], 63 | problems=[problem], 64 | ) 65 | 66 | rs_str = 'random_subspace_' if random_subspace else '' 67 | with open( 68 | f'results/hartmann6_{rs_str}{D}_alebo_rembo_hesbo_sobol_rep_{rep}.json', "w" 69 | ) as fout: 70 | json.dump(object_to_json(all_benchmarks), fout) 71 | 72 | 73 | def run_branin_and_gramacy_100_benchmarks(rep): 74 | strategy0 = GenerationStrategy( 75 | name="Sobol", 76 | steps=[ 77 | GenerationStep( 78 | model=Models.SOBOL, num_arms=-1, model_kwargs={'seed': rep + 1} 79 | ) 80 | ], 81 | ) 82 | strategy1 = ALEBOStrategy(D=100, d=4, init_size=10) 83 | strategy2 = REMBOStrategy(D=100, d=2, init_per_proj=2) 84 | strategy3 = HeSBOStrategy(D=100, d=4, init_per_proj=10, name=f"HeSBO, d=2d") 85 | 86 | all_benchmarks = full_benchmark_run( 87 | num_replications=1, 88 | num_trials=50, 89 | batch_size=1, 90 | methods=[strategy0, strategy1, strategy2, strategy3], 91 | problems=[branin_100, gramacy_100], 92 | ) 93 | 94 | with open( 95 | f'results/branin_gramacy_100_alebo_rembo_hesbo_sobol_rep_{rep}.json', "w" 96 | ) as fout: 97 | json.dump(object_to_json(all_benchmarks), fout) 98 | 99 | 100 | def run_sensitivity_D_benchmarks(rep): 101 | results_dict = {} 102 | for D, problem in branin_by_D.items(): 103 | strategy1 = ALEBOStrategy(D=D, d=4, init_size=10) 104 | 105 | all_benchmarks = full_benchmark_run( 106 | num_replications=1, 107 | num_trials=50, 108 | batch_size=1, 109 | methods=[strategy1], 110 | problems=[problem], 111 | ) 112 | 113 | results_dict[D] = object_to_json(all_benchmarks) 114 | 115 | with open(f'results/sensitivity_D_rep_{rep}.json', "w") as fout: 116 | json.dump(results_dict, fout) 117 | 118 | 119 | def run_sensitivity_d_e_benchmarks(rep): 120 | strategies = [ 121 | ALEBOStrategy(D=100, d=d_e, init_size=10, name=f'ALEBO, d={d_e}') 122 | for d_e in [2, 3, 5, 6, 7, 8] 123 | ] 124 | 125 | all_benchmarks = full_benchmark_run( 126 | num_replications=1, 127 | num_trials=50, 128 | batch_size=1, 129 | methods=strategies, 130 | problems=[branin_100], 131 | ) 132 | 133 | with open(f'results/sensitivity_d_e_rep_{rep}.json', "w") as fout: 134 | json.dump(object_to_json(all_benchmarks), fout) 135 | 136 | 137 | def run_ablation_benchmarks(rep): 138 | strategies = [ 139 | ALEBOStrategy_projection_ablation(D=100, d=4, init_size=10, name='ALEBO, projection ablation'), 140 | ALEBOStrategy_kernel_ablation(D=100, d=4, init_size=10, name='ALEBO, kernel ablation'), 141 | ALEBOStrategy(D=100, d=4, init_size=10, name='ALEBO, base'), 142 | ] 143 | 144 | all_benchmarks = full_benchmark_run( 145 | num_replications=1, 146 | num_trials=50, 147 | batch_size=1, 148 | methods=strategies, 149 | problems=[branin_100], 150 | ) 151 | 152 | with open(f'results/ablation_rep_{rep}.json', "w") as fout: 153 | json.dump(object_to_json(all_benchmarks), fout) 154 | 155 | 156 | if __name__ == '__main__': 157 | # Run all of the benchmark replicates. 158 | # They are set up here to run as individual replicates becaus they can be 159 | # distributed. 160 | 161 | for i in range(50): 162 | # Hartmann6, D=100: Each rep takes ~2 hrs 163 | run_hartmann6_benchmarks(D=100, rep=i) 164 | 165 | # Hartmann6, D=1000: Each rep takes ~2.5 hrs 166 | run_hartmann6_benchmarks(D=1000, rep=i) 167 | 168 | # Hartmann6, D=1000: Each rep takes ~2.5 hrs 169 | run_hartmann6_benchmarks(D=1000, rep=i, random_subspace=True) 170 | 171 | # Branin and Gramacy, D=100: Each rep takes ~20 mins 172 | run_branin_and_gramacy_100_benchmarks(rep=i) 173 | 174 | # Sensitivity benchmarks: Each rep takes ~2 hrs 175 | run_sensitivity_D_benchmarks(rep=i) 176 | run_sensitivity_d_e_benchmarks(rep=i) 177 | 178 | for i in range(100): 179 | # Ablation benchmarks 180 | run_ablation_benchmarks(rep=i) 181 | -------------------------------------------------------------------------------- /figs/fig_5.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import json 6 | import numpy as np 7 | 8 | from ax.storage.json_store.decoder import object_from_json 9 | 10 | from plot_config_nr import * 11 | 12 | 13 | def make_fig_5(): 14 | # Load in the benchmark results 15 | res = {} 16 | for fname in ['hartmann6_1000', 'branin_gramacy_100']: 17 | with open(f'../benchmarks/results/{fname}_aggregated_results.json', 'r') as fin: 18 | res.update(object_from_json(json.load(fin))) 19 | 20 | # A map from method idx in plot_method_names to the name used in res 21 | method_idx_to_res_name = { 22 | 0: 'ALEBO', 23 | 1: 'REMBO', 24 | 2: 'HeSBO, d=d', 25 | 3: 'HeSBO, d=2d', 26 | 4: 'rrembos_standard_kPsi', 27 | 5: 'rrembos_reverse_kPsi', 28 | 6: 'ebo', 29 | 7: 'addgpucb', 30 | 8: 'smac', 31 | 9: 'cmaes', 32 | 10: 'turbo', 33 | 11: 'Sobol', 34 | 12: 'coordinatelinebo', 35 | 13: 'randomlinebo', 36 | 14: 'descentlinebo', 37 | } 38 | 39 | # Make the figure 40 | fig = plt.figure(figsize=(5.5, 3.7)) 41 | 42 | ####### Branin, D=100 43 | ax1 = fig.add_subplot(231) 44 | ax2 = fig.add_subplot(234) 45 | 46 | res_h = res['Branin, D=100'] 47 | 48 | for idx, m in enumerate(plot_method_names): 49 | res_name = method_idx_to_res_name[idx] 50 | if res_name not in res_h.objective_at_true_best: 51 | continue # Not run on this problem 52 | Y = res_h.objective_at_true_best[res_name] 53 | f = Y.mean(axis=0) 54 | x = np.arange(1, 51) 55 | color = plot_colors[m] 56 | ax1.plot(x, f, color=color, label=m) 57 | 58 | parts = ax2.violinplot(positions=[idx], dataset=Y[:, 49], showmeans=True) 59 | for pc in parts['bodies']: 60 | pc.set_facecolor(color) 61 | pc.set_edgecolor(color) 62 | for field in ['cmeans', 'cmaxes', 'cmins', 'cbars']: 63 | parts[field].set_color(color) 64 | 65 | ax1.set_xlim([0, 51]) 66 | ax1.set_ylabel('Best value found', fontsize=7) 67 | ax1.set_xlabel('Function evaluations', fontsize=7) 68 | 69 | ax1.axhline(y=0.397887, c='gray', ls='--') 70 | ax1.grid(alpha=0.2, zorder=-10) 71 | ax1.set_ylim([0, 7]) 72 | 73 | 74 | ax2.set_xticks(range(12)) 75 | ax2.set_xticklabels([]) 76 | ax2.set_ylabel('Final value', fontsize=7) 77 | ax2.grid(alpha=0.2, zorder=-10) 78 | ax2.set_xticklabels([plot_method_names[i] for i in range(12)], fontsize=6) 79 | ax2.xaxis.set_tick_params(rotation=90) 80 | 81 | 82 | # Make the legend 83 | custom_lines = [] 84 | names = [] 85 | for i in range(12): 86 | names.append(plot_method_names[i]) 87 | custom_lines.append( 88 | Line2D([0], [0], color=plot_colors[plot_method_names[i]], lw=2) 89 | ) 90 | 91 | order = range(12) 92 | names = [names[o] for o in order] 93 | custom_lines = [custom_lines[o] for o in order] 94 | ax1.legend(custom_lines, names, ncol=6, fontsize=5.5, bbox_to_anchor=(3.52, -2.26)) 95 | ax1.set_title('Branin, $d$=2, $D$=100', fontsize=8) 96 | 97 | ####### Hartmann6, D=1000 98 | ax1 = fig.add_subplot(232) 99 | ax2 = fig.add_subplot(235) 100 | 101 | res_h = res['Hartmann6, D=1000'] 102 | 103 | for idx, m in enumerate(plot_method_names): 104 | res_name = method_idx_to_res_name[idx] 105 | if res_name not in res_h.objective_at_true_best: 106 | continue # Not run on this problem 107 | Y = res_h.objective_at_true_best[res_name] 108 | f = Y.mean(axis=0) 109 | x = np.arange(1, 201) 110 | color = plot_colors[m] 111 | ax1.plot(x, f, color=color, label=m) 112 | 113 | parts = ax2.violinplot(positions=[idx], dataset=Y[:, 199], showmeans=True) 114 | for pc in parts['bodies']: 115 | pc.set_facecolor(color) 116 | pc.set_edgecolor(color) 117 | for field in ['cmeans', 'cmaxes', 'cmins', 'cbars']: 118 | parts[field].set_color(color) 119 | 120 | ax1.set_xlim([0, 201]) 121 | #ax1.set_ylabel('Best value found', fontsize=9) 122 | ax1.set_xlabel('Function evaluations', fontsize=7) 123 | 124 | ax1.axhline(y=-3.32237, c='gray', ls='--') 125 | ax1.grid(alpha=0.2, zorder=-10) 126 | ax1.set_ylim([-3.5, -0.5]) 127 | 128 | ax2.set_xticks(range(12)) 129 | ax2.set_xticklabels([]) 130 | #ax2.set_ylabel('Final value', fontsize=9) 131 | ax2.grid(alpha=0.2, zorder=-10) 132 | ax2.set_xticklabels([plot_method_names[i] for i in range(12)], fontsize=6) 133 | ax2.xaxis.set_tick_params(rotation=90) 134 | ax1.set_title('Hartmann6, $d$=6, $D$=1000', fontsize=8) 135 | 136 | ####### Gramacy, D=100 137 | ax1 = fig.add_subplot(233) 138 | ax2 = fig.add_subplot(236) 139 | 140 | res_h = res['Gramacy, D=100'] 141 | 142 | for idx, m in enumerate(plot_method_names): 143 | res_name = method_idx_to_res_name[idx] 144 | if res_name not in res_h.objective_at_true_best: 145 | continue # Not run on this problem 146 | Y = res_h.objective_at_true_best[res_name] 147 | f = Y.mean(axis=0) 148 | x = np.arange(1, 51) 149 | color = plot_colors[m] 150 | ax1.plot(x, f, color=color, label=m) 151 | 152 | parts = ax2.violinplot(positions=[idx], dataset=Y[:, 49], showmeans=True) 153 | for pc in parts['bodies']: 154 | pc.set_facecolor(color) 155 | pc.set_edgecolor(color) 156 | for field in ['cmeans', 'cmaxes', 'cmins', 'cbars']: 157 | parts[field].set_color(color) 158 | 159 | ax1.set_xlim([0, 51]) 160 | #ax1.set_ylabel('Best value found', fontsize=9) 161 | ax1.set_xlabel('Function evaluations', fontsize=7) 162 | ax1.set_ylim([0.58, 1]) 163 | 164 | ax1.axhline(y=0.5998, c='gray', ls='--') 165 | ax1.grid(alpha=0.2, zorder=-10) 166 | 167 | ax2.set_xticks(range(12)) 168 | ax2.set_xticklabels([plot_method_names[i] for i in range(12)], fontsize=6) 169 | ax2.xaxis.set_tick_params(rotation=90) 170 | #ax2.set_ylabel('Final value', fontsize=9) 171 | ax2.grid(alpha=0.2, zorder=-10) 172 | ax1.set_title('Gramacy, $d$=2, $D$=100', fontsize=8) 173 | 174 | plt.subplots_adjust(right=0.995, bottom=0.3, left=0.07, top=0.94, wspace=0.25, hspace=0.45) 175 | plt.savefig('pdfs/benchmark_results_t.pdf', pad_inches=0) 176 | 177 | 178 | if __name__ == '__main__': 179 | make_fig_5() 180 | -------------------------------------------------------------------------------- /figs/fig_3.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import os 6 | os.environ['OPENBLAS_NUM_THREADS'] = '1' 7 | os.environ['OMP_NUM_THREADS'] = '1' 8 | 9 | import time 10 | import numpy as np 11 | import torch 12 | import pickle 13 | 14 | from ax.models.torch.alebo import ALEBO 15 | from ax.models.random.alebo_initializer import ALEBOInitializer 16 | from ax.models.torch.botorch import BotorchModel 17 | 18 | from botorch.test_functions.synthetic import Hartmann 19 | from botorch.models.gpytorch import BatchedMultiOutputGPyTorchModel 20 | from torch import Tensor 21 | from gpytorch.means.constant_mean import ConstantMean 22 | from gpytorch.models.exact_gp import ExactGP 23 | from gpytorch.likelihoods.gaussian_likelihood import FixedNoiseGaussianLikelihood 24 | from gpytorch.kernels.rbf_kernel import RBFKernel 25 | from gpytorch.kernels.scale_kernel import ScaleKernel 26 | from gpytorch.mlls.exact_marginal_log_likelihood import ExactMarginalLogLikelihood 27 | from botorch.fit import fit_gpytorch_model 28 | from gpytorch.distributions.multivariate_normal import MultivariateNormal 29 | 30 | from plot_config import * 31 | 32 | 33 | def highDhartmann6(X): 34 | # X \in [-1, 1]^D 35 | h = Hartmann() 36 | Xd = (X[:, :6] + 1) / 2. 37 | return h.evaluate_true(Xd) 38 | 39 | def gen_train_test_sets(B, ntrain, ntest, seed_train=1000, seed_test=2000): 40 | # Generate training points 41 | m1 = ALEBOInitializer(B=B.numpy(), seed=seed_train) 42 | train_X = torch.tensor(m1.gen(n=ntrain, bounds=[])[0], dtype=torch.double) 43 | train_Y = highDhartmann6(train_X) 44 | # Standardize train Y 45 | mu = train_Y.mean() 46 | sigma = train_Y.std() 47 | train_Y = (train_Y - mu) / sigma 48 | train_Y = train_Y.unsqueeze(1) 49 | train_Yvar = 1e-7 * torch.ones(train_Y.shape) 50 | 51 | # Generate test points 52 | m2 = ALEBOInitializer(B=B.numpy(), seed=seed_test) 53 | test_X = torch.tensor(m2.gen(n=ntest, bounds=[])[0], dtype=torch.double) 54 | test_Y = highDhartmann6(test_X) 55 | return train_X, train_Y, train_Yvar, test_X, test_Y, mu, sigma 56 | 57 | def fit_and_predict_alebo(B, train_X, train_Y, train_Yvar, test_X, mu, sigma): 58 | m = ALEBO(B=B) 59 | m.fit([train_X], [train_Y], [train_Yvar], [], [], [], [], []) 60 | f, var = m.predict(test_X) 61 | # Return predictions, un-standardized 62 | return f.squeeze() * sigma + mu, var.squeeze() * sigma ** 2 63 | 64 | def fit_and_predict_map(B, train_X, train_Y, train_Yvar, test_X, mu, sigma): 65 | m = ALEBO(B=B, laplace_nsamp=1) # laplace_nsamp=1 uses MAP estimate 66 | m.fit([train_X], [train_Y], [train_Yvar], [], [], [], [], []) 67 | f, var = m.predict(test_X) 68 | # Return predictions, un-standardized 69 | return f.squeeze() * sigma + mu, var.squeeze() * sigma ** 2 70 | 71 | class ARDRBFGP(BatchedMultiOutputGPyTorchModel, ExactGP): 72 | """A GP with fixed observation noise and an ARD RBF kernel.""" 73 | 74 | def __init__(self, train_X: Tensor, train_Y: Tensor, train_Yvar: Tensor) -> None: 75 | self._validate_tensor_args(X=train_X, Y=train_Y, Yvar=train_Yvar) 76 | self._set_dimensions(train_X=train_X, train_Y=train_Y) 77 | train_X, train_Y, train_Yvar = self._transform_tensor_args( 78 | X=train_X, Y=train_Y, Yvar=train_Yvar 79 | ) 80 | likelihood = FixedNoiseGaussianLikelihood( 81 | noise=train_Yvar, batch_shape=self._aug_batch_shape 82 | ) 83 | ExactGP.__init__( 84 | self, train_inputs=train_X, train_targets=train_Y, likelihood=likelihood 85 | ) 86 | self.mean_module = ConstantMean(batch_shape=self._aug_batch_shape) 87 | self.covar_module = ScaleKernel( 88 | base_kernel=RBFKernel( 89 | ard_num_dims=train_X.shape[-1], 90 | batch_shape=self._aug_batch_shape, 91 | ), 92 | batch_shape=self._aug_batch_shape, 93 | ) 94 | self.to(train_X) 95 | 96 | def forward(self, x: Tensor) -> MultivariateNormal: 97 | mean_x = self.mean_module(x) 98 | covar_x = self.covar_module(x) 99 | return MultivariateNormal(mean_x, covar_x) 100 | 101 | def get_and_fit_ARDRBF( 102 | Xs, Ys, Yvars, task_features=None, fidelity_features=None, refit_model=None, state_dict=None, 103 | fidelity_model_id=None, metric_names=None, 104 | ): 105 | m = ARDRBFGP(train_X=Xs[0], train_Y=Ys[0], train_Yvar=Yvars[0]) 106 | mll = ExactMarginalLogLikelihood(m.likelihood, m) 107 | mll = fit_gpytorch_model(mll) 108 | return m 109 | 110 | def fit_and_predict_ARDRBF(B, train_X, train_Y, train_Yvar, test_X, mu, sigma): 111 | # Project training data down to the embedding 112 | BX = train_X @ B.t() 113 | m = BotorchModel(model_constructor=get_and_fit_ARDRBF) 114 | # Fit ARD RBF model on data in embedding 115 | m.fit([BX], [train_Y], [train_Yvar], [], [], [], [], []) 116 | # Predict on test points in embedding 117 | f, var = m.predict(test_X @ B.t()) 118 | # Return predictions, un-standardized 119 | return f.squeeze() * sigma + mu, var.squeeze() * sigma ** 2 120 | 121 | def run_simulation(): 122 | D = 100 123 | d = 6 124 | ntrain = 100 125 | ntest = 50 126 | 127 | # Get projection 128 | torch.manual_seed(1000) 129 | B0 = torch.randn(d, D, dtype=torch.double) 130 | B = B0 / torch.sqrt((B0 ** 2).sum(dim=0)) 131 | 132 | # Get fixed train/test data 133 | train_X, train_Y, train_Yvar, test_X, test_Y, mu, sigma = gen_train_test_sets(B, ntrain, ntest) 134 | 135 | # Predict with each model 136 | f1, var1 = fit_and_predict_alebo(B, train_X, train_Y, train_Yvar, test_X, mu, sigma) 137 | f2, var2 = fit_and_predict_map(B, train_X, train_Y, train_Yvar, test_X, mu, sigma) 138 | f3, var3 = fit_and_predict_ARDRBF(B, train_X, train_Y, train_Yvar, test_X, mu, sigma) 139 | 140 | # Save outcome 141 | with open('data/fig3_sim_output.pckl', 'wb') as fout: 142 | pickle.dump((test_Y, f1, var1, f2, var2, f3, var3), fout) 143 | 144 | def make_fig_3(): 145 | # Load in simulation results 146 | with open('data/fig3_sim_output.pckl', 'rb') as fin: 147 | (test_Y, f1, var1, f2, var2, f3, var3) = pickle.load(fin) 148 | 149 | fig = plt.figure(figsize=(2.63, 1.45)) 150 | 151 | ax = fig.add_subplot(121) 152 | ax.errorbar( 153 | x=test_Y.numpy(), y=f3.numpy(), yerr = 2 * np.sqrt(var3.numpy()), 154 | c='gray', lw=1, ls='', marker='.', mfc='k', mec='k', ms=3 155 | ) 156 | x0 = -2.5 157 | x1 = 0.5 158 | ax.plot([x0, x1], [x0, x1], '-', zorder=-5, alpha=0.5, c='steelblue', lw=2) 159 | ax.set_xlim([x0, x1]) 160 | ax.set_ylim([x0, x1]) 161 | ax.set_yticks([0, -1, -2]) 162 | ax.set_xlabel('True value', fontsize=9) 163 | ax.set_ylabel('Model prediction', fontsize=9) 164 | ax.set_title('ARD RBF', fontsize=9) 165 | ax.grid(True, alpha=0.2) 166 | 167 | ax = fig.add_subplot(122) 168 | ax.errorbar( 169 | x=test_Y.numpy(), y=f1.numpy(), yerr = 2 * np.sqrt(var1.numpy()), 170 | c='gray', lw=1, ls='', marker='.', mfc='k', mec='k', ms=3 171 | ) 172 | x0 = -3 173 | x1 = 1 174 | ax.plot([x0, x1], [x0, x1], '-', zorder=-5, alpha=0.5, c='steelblue', lw=2) 175 | ax.set_xlim([x0, x1]) 176 | ax.set_ylim([x0, x1]) 177 | ax.set_title('Mahalanobis', fontsize=9) 178 | ax.set_xticks([-3, -2, -1, 0, 1]) 179 | ax.set_xlabel('True value', fontsize=9) 180 | ax.grid(True, alpha=0.2) 181 | 182 | plt.subplots_adjust(right=0.99, bottom=0.24, left=0.16, top=0.87, wspace=0.3) 183 | plt.savefig('pdfs/ard_mahalanobis.pdf', pad_inches=0) 184 | 185 | if __name__ == '__main__': 186 | #run_simulation() # This will take ~20s, produces data/fig3_sim_output.pckl 187 | make_fig_3() 188 | -------------------------------------------------------------------------------- /benchmarks/run_rrembo_benchmarks.R: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | """ 6 | Runs benchmarks for REMBO variance implemented in RRembo (k_\Psi kernel, with 7 | standard projection and with \gamma back projection). 8 | 9 | RRembo should be installed from https://github.com/mbinois/RRembo . 10 | 11 | Code below is based on examples/Tests_RRembo.R from that repo. 12 | """ 13 | 14 | library("doParallel") 15 | library("foreach") 16 | library("RRembo") 17 | library("DiceKriging") 18 | library("rjson") 19 | 20 | 21 | ######################################## Branin 100 22 | 23 | nCores <- 7 24 | cl <- makeCluster(nCores) 25 | registerDoParallel(cl) 26 | 27 | nrep <- 50 28 | popsize <- 80 29 | gen <- 40 30 | roll <- TRUE 31 | 32 | d <- 2 33 | D <- 100 34 | budget <- 50 35 | covtype <- "matern5_2" 36 | ftest <- branin_mod 37 | 38 | mat_effective <- c(20, 65) 39 | fstar <- 0.397887 40 | 41 | lower <- rep(0, D) 42 | upper <- rep(1, D) 43 | 44 | ### 45 | 46 | cat('REMBO standard k_Psi \n') 47 | # Standard REMBO-like method 48 | tsP <- Sys.time() 49 | res_standard_kPsi <- foreach(i=1:nrep, .packages = c("RRembo", "DiceKriging"), .combine = 'rbind') %dopar% { 50 | set.seed(i) 51 | res <- easyREMBO( 52 | par = runif(d), 53 | fn = ftest, 54 | budget = budget, 55 | lower = lower, 56 | upper = upper, 57 | ii = mat_effective, 58 | control = list( 59 | Atype = 'standard', 60 | reverse = FALSE, 61 | warping = 'Psi', 62 | testU = FALSE, 63 | standard = TRUE, 64 | popsize = popsize, 65 | gen = gen, 66 | inneroptim = "StoSOO", 67 | roll = roll 68 | ), 69 | kmcontrol = list(covtype = covtype) 70 | ) 71 | res$y 72 | } 73 | tsP <- difftime(Sys.time(), tsP, units = "sec") 74 | print(paste0('-------------------------', tsP)) 75 | 76 | ### 77 | 78 | cat('REMBO reverse + A Gaussian + Psi \n') 79 | trP <- Sys.time() 80 | res_reverse_kPsi <- foreach(i=1:nrep, .packages = c("RRembo", "DiceKriging"), .combine = 'rbind') %dopar% { 81 | set.seed(i) 82 | res <- easyREMBO( 83 | par = runif(d), 84 | fn = ftest, 85 | budget = budget, 86 | lower = lower, 87 | upper = upper, 88 | ii = mat_effective, 89 | control = list( 90 | Atype = 'Gaussian', 91 | reverse = TRUE, 92 | warping = 'Psi', 93 | testU = TRUE, 94 | standard = FALSE, 95 | popsize = popsize, 96 | gen = gen, 97 | inneroptim = "StoSOO", 98 | roll = roll 99 | ), 100 | kmcontrol = list(covtype = covtype) 101 | ) 102 | res$y 103 | } 104 | trP <- difftime(Sys.time(), trP, units = "sec") 105 | print(paste0('-------------------------', trP)) 106 | 107 | ### 108 | 109 | stopCluster(cl) 110 | 111 | res_sP <- list() 112 | for (i in 1:50) { 113 | res_sP[[i]] <- res_standard_kPsi[i,] 114 | } 115 | 116 | res_rP <- list() 117 | for (i in 1:50) { 118 | res_rP[[i]] <- res_reverse_kPsi[i,] 119 | } 120 | 121 | write(toJSON(res_sP), file="results/branin_100_rrembos_standard_kPsi.json") 122 | write(toJSON(res_rP), file="results/branin_100_rrembos_reverse_kPsi.json") 123 | 124 | 125 | ######################################## Hartmann6 100 126 | 127 | nCores <- 7 128 | cl <- makeCluster(nCores) 129 | registerDoParallel(cl) 130 | 131 | nrep <- 50 132 | popsize <- 80 133 | gen <- 40 134 | roll <- TRUE 135 | 136 | d <- 6 137 | D <- 100 138 | budget <- 200 139 | covtype <- "matern5_2" 140 | ftest <- hartman6_mod 141 | 142 | mat_effective <- c(20, 15, 44, 38, 67, 4) 143 | fstar <- -3.32237 144 | 145 | lower <- rep(0, D) 146 | upper <- rep(1, D) 147 | 148 | ### 149 | 150 | cat('REMBO standard k_Psi \n') 151 | # Standard REMBO-like method 152 | tsP <- Sys.time() 153 | res_standard_kPsi <- foreach(i=1:nrep, .packages = c("RRembo", "DiceKriging"), .combine = 'rbind') %dopar% { 154 | set.seed(i) 155 | res <- easyREMBO( 156 | par = runif(d), 157 | fn = ftest, 158 | budget = budget, 159 | lower = lower, 160 | upper = upper, 161 | ii = mat_effective, 162 | control = list( 163 | Atype = 'standard', 164 | reverse = FALSE, 165 | warping = 'Psi', 166 | testU = FALSE, 167 | standard = TRUE, 168 | popsize = popsize, 169 | gen = gen, 170 | inneroptim = "StoSOO", 171 | roll = roll 172 | ), 173 | kmcontrol = list(covtype = covtype) 174 | ) 175 | res$y 176 | } 177 | tsP <- difftime(Sys.time(), tsP, units = "sec") 178 | print(paste0('-------------------------', tsP)) 179 | 180 | 181 | ### 182 | 183 | cat('REMBO reverse + A Gaussian + Psi \n') 184 | trP <- Sys.time() 185 | res_reverse_kPsi <- foreach(i=1:nrep, .packages = c("RRembo", "DiceKriging"), .combine = 'rbind') %dopar% { 186 | set.seed(i) 187 | res <- easyREMBO( 188 | par = runif(d), 189 | fn = ftest, 190 | budget = budget, 191 | lower = lower, 192 | upper = upper, 193 | ii = mat_effective, 194 | control = list( 195 | Atype = 'Gaussian', 196 | reverse = TRUE, 197 | warping = 'Psi', 198 | testU = TRUE, 199 | standard = FALSE, 200 | popsize = popsize, 201 | gen = gen, 202 | inneroptim = "StoSOO", 203 | roll = roll 204 | ), 205 | kmcontrol = list(covtype = covtype) 206 | ) 207 | res$y 208 | } 209 | trP <- difftime(Sys.time(), trP, units = "sec") 210 | print(paste0('-------------------------', trP)) 211 | 212 | ### 213 | 214 | stopCluster(cl) 215 | 216 | res_sP <- list() 217 | for (i in 1:50) { 218 | res_sP[[i]] <- res_standard_kPsi[i,] 219 | } 220 | 221 | res_rP <- list() 222 | for (i in 1:50) { 223 | res_rP[[i]] <- res_reverse_kPsi[i,] 224 | } 225 | 226 | write(toJSON(res_sP), file="results/hartmann6_100_rrembos_standard_kPsi.json") 227 | write(toJSON(res_rP), file="results/hartmann6_100_rrembos_reverse_kPsi.json") 228 | 229 | 230 | ######################################## Hartmann6 1000 231 | 232 | nCores <- 7 233 | cl <- makeCluster(nCores) 234 | registerDoParallel(cl) 235 | 236 | nrep <- 50 237 | popsize <- 80 238 | gen <- 40 239 | roll <- TRUE 240 | 241 | d <- 6 242 | D <- 1000 243 | budget <- 200 244 | covtype <- "matern5_2" 245 | ftest <- hartman6_mod 246 | 247 | mat_effective <- c(191, 141, 431, 371, 661, 31) 248 | fstar <- -3.32237 249 | 250 | lower <- rep(0, D) 251 | upper <- rep(1, D) 252 | 253 | ### 254 | 255 | cat('REMBO standard k_Psi \n') 256 | # Standard REMBO-like method 257 | tsP <- Sys.time() 258 | res_standard_kPsi <- foreach(i=1:nrep, .packages = c("RRembo", "DiceKriging"), .combine = 'rbind') %dopar% { 259 | set.seed(i) 260 | res <- easyREMBO( 261 | par = runif(d), 262 | fn = ftest, 263 | budget = budget, 264 | lower = lower, 265 | upper = upper, 266 | ii = mat_effective, 267 | control = list( 268 | Atype = 'standard', 269 | reverse = FALSE, 270 | warping = 'Psi', 271 | testU = FALSE, 272 | standard = TRUE, 273 | popsize = popsize, 274 | gen = gen, 275 | inneroptim = "StoSOO", 276 | roll = roll 277 | ), 278 | kmcontrol = list(covtype = covtype) 279 | ) 280 | res$y 281 | } 282 | tsP <- difftime(Sys.time(), tsP, units = "sec") 283 | print(paste0('-------------------------', tsP)) 284 | 285 | 286 | ### Too slow, not run 287 | 288 | # cat('REMBO reverse + A Gaussian + Psi \n') 289 | # trP <- Sys.time() 290 | # res_reverse_kPsi <- foreach(i=1:nrep, .packages = c("RRembo", "DiceKriging"), .combine = 'rbind') %dopar% { 291 | # set.seed(i) 292 | # res <- easyREMBO( 293 | # par = runif(d), 294 | # fn = ftest, 295 | # budget = budget, 296 | # lower = lower, 297 | # upper = upper, 298 | # ii = mat_effective, 299 | # control = list( 300 | # Atype = 'Gaussian', 301 | # reverse = TRUE, 302 | # warping = 'Psi', 303 | # testU = TRUE, 304 | # standard = FALSE, 305 | # popsize = popsize, 306 | # gen = gen, 307 | # inneroptim = "StoSOO", 308 | # roll = roll 309 | # ), 310 | # kmcontrol = list(covtype = covtype) 311 | # ) 312 | # res$y 313 | # } 314 | # trP <- difftime(Sys.time(), trP, units = "sec") 315 | # print(paste0('-------------------------', trP)) 316 | 317 | ### 318 | 319 | stopCluster(cl) 320 | 321 | res_sP <- list() 322 | for (i in 1:50) { 323 | res_sP[[i]] <- res_standard_kPsi[i,] 324 | } 325 | 326 | write(toJSON(res_sP), file="results/hartmann6_1000_rrembos_standard_kPsi.json") 327 | -------------------------------------------------------------------------------- /benchmarks/compile_benchmark_results.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | """ 6 | Compile all of the benchmark results from the different methods (potentially 7 | run in a distributed fashion) into a single BenchmarkResult object. 8 | 9 | All of the benchmark runs should be completed before running this. 10 | """ 11 | 12 | import gc 13 | import json 14 | import numpy as np 15 | 16 | from benchmark_problems import ( 17 | branin_100, 18 | branin_by_D, 19 | gramacy_100, 20 | hartmann6_100, 21 | hartmann6_1000, 22 | hartmann6_random_subspace_1000, 23 | ) 24 | from ax.benchmark.benchmark_result import aggregate_problem_results 25 | from ax.storage.json_store.encoder import object_to_json 26 | from ax.storage.json_store.decoder import object_from_json 27 | 28 | 29 | def merge_benchmark_results(res1, res2): 30 | """ 31 | Merges two benchmark results dictionaries in-place (res2 into res1) 32 | """ 33 | for problem_name in res2: 34 | for method_name in res2[problem_name]: 35 | for exp in res2[problem_name][method_name]: 36 | res1 = add_exp( 37 | res=res1, 38 | exp=exp, 39 | problem_name=problem_name, 40 | method_name=method_name, 41 | ) 42 | return res1 43 | 44 | 45 | def add_exp(res, exp, problem_name, method_name): 46 | """ 47 | Add benchmark experiment exp to results dict res, under the specified 48 | problem_name and method_name. 49 | """ 50 | if problem_name not in res: 51 | res[problem_name] = {} 52 | if method_name not in res[problem_name]: 53 | res[problem_name][method_name] = [] 54 | res[problem_name][method_name].append(exp) 55 | return res 56 | 57 | 58 | def compile_hartmann6(D, random_subspace=False): 59 | if D == 100: 60 | problem = hartmann6_100 61 | other_methods = ['addgpucb', 'cmaes', 'ebo', 'smac', 'turbo'] 62 | rls = ['rrembos_standard_kPsi', 'rrembos_reverse_kPsi', 'coordinatelinebo', 'descentlinebo', 'randomlinebo'] 63 | rs_str = '' 64 | elif D == 1000 and not random_subspace: 65 | problem = hartmann6_1000 66 | other_methods = ['cmaes', 'smac', 'turbo'] 67 | rls = ['rrembos_standard_kPsi'] 68 | rs_str = '' 69 | elif D == 1000 and random_subspace: 70 | problem = hartmann6_random_subspace_1000 71 | other_methods = ['cmaes', 'smac', 'turbo'] 72 | rls = [] 73 | rs_str = 'random_subspace_' 74 | 75 | all_results = {} 76 | 77 | for rep in range(50): 78 | with open(f'results/hartmann6_{rs_str}{D}_alebo_rembo_hesbo_sobol_rep_{rep}.json', 'r') as fin: 79 | res_i = object_from_json(json.load(fin)) 80 | 81 | all_results = merge_benchmark_results(all_results, res_i) 82 | 83 | for method_name in other_methods: 84 | if D==1000 and method_name == 'smac' and rep > 9: 85 | # SMAC D=1000 only run for 10 reps 86 | continue 87 | 88 | with open(f'results/hartmann6_{rs_str}{D}_{method_name}_rep_{rep}.json', 'r') as fin: 89 | exp_i = object_from_json(json.load(fin)) 90 | 91 | all_results = add_exp(res=all_results, exp=exp_i, problem_name=problem.name, method_name=method_name) 92 | 93 | res = aggregate_problem_results(runs=all_results[problem.name], problem=problem) 94 | 95 | # Add in RRembo and LineBOresults 96 | for method in rls: 97 | with open(f'results/hartmann6_{D}_{method}.json', 'r') as fin: 98 | A = json.load(fin) 99 | res.objective_at_true_best[method] = np.minimum.accumulate(np.array(A), axis=1) 100 | 101 | # Save 102 | with open(f'results/hartmann6_{rs_str}{D}_aggregated_results.json', "w") as fout: 103 | json.dump(object_to_json({problem.name: res}), fout) 104 | 105 | 106 | def compile_branin_gramacy_100(): 107 | all_results = {} 108 | 109 | for rep in range(50): 110 | with open(f'results/branin_gramacy_100_alebo_rembo_hesbo_sobol_rep_{rep}.json', 'r') as fin: 111 | res_i = object_from_json(json.load(fin)) 112 | 113 | all_results = merge_benchmark_results(all_results, res_i) 114 | 115 | for method_name in ['addgpucb', 'cmaes', 'ebo', 'smac', 'turbo']: 116 | with open(f'results/branin_100_{method_name}_rep_{rep}.json', 'r') as fin: 117 | exp_i = object_from_json(json.load(fin)) 118 | 119 | all_results = add_exp( 120 | res=all_results, 121 | exp=exp_i, 122 | problem_name='Branin, D=100', 123 | method_name=method_name, 124 | ) 125 | 126 | res = { 127 | p.name: aggregate_problem_results(runs=all_results[p.name], problem=p) 128 | for p in [branin_100, gramacy_100] 129 | } 130 | 131 | # Add in RRembo results 132 | for proj in ['standard', 'reverse']: 133 | method = f'rrembos_{proj}_kPsi' 134 | with open(f'results/branin_100_{method}.json', 'r') as fin: 135 | A = json.load(fin) 136 | res['Branin, D=100'].objective_at_true_best[method] = np.minimum.accumulate(np.array(A), axis=1) 137 | 138 | # Save 139 | with open(f'results/branin_gramacy_100_aggregated_results.json', "w") as fout: 140 | json.dump(object_to_json(res), fout) 141 | 142 | 143 | def compile_sensitivity_benchmarks(): 144 | all_results = {} 145 | 146 | for rep in range(50): 147 | ## Sensitivity to D 148 | with open(f'results/sensitivity_D_rep_{rep}.json', 'r') as fin: 149 | results_dict = json.load(fin) 150 | 151 | for D, obj in results_dict.items(): 152 | res_i = object_from_json(obj) 153 | all_results = merge_benchmark_results(all_results, res_i) 154 | 155 | ## Sensitivity to d_e 156 | with open(f'results/sensitivity_d_e_rep_{rep}.json', 'r') as fin: 157 | res_i = object_from_json(json.load(fin)) 158 | 159 | all_results = merge_benchmark_results(all_results, res_i) 160 | 161 | all_problems = ( 162 | [hartmann6_100, hartmann6_1000, branin_100, gramacy_100] 163 | + list(branin_by_D.values()) 164 | ) 165 | 166 | problems = [branin_100] + list(branin_by_D.values()) 167 | res = { 168 | p.name+'_sensitivity': aggregate_problem_results(runs=all_results[p.name], problem=p) 169 | for p in problems 170 | } 171 | # Save 172 | with open(f'results/sensitivity_aggregated_results.json', "w") as fout: 173 | json.dump(object_to_json(res), fout) 174 | 175 | 176 | def compile_ablation_benchmarks(): 177 | all_results = {} 178 | 179 | for rep in range(100): 180 | with open(f'results/ablation_rep_{rep}.json', 'r') as fin: 181 | res_i = object_from_json(json.load(fin)) 182 | 183 | all_results = merge_benchmark_results(all_results, res_i) 184 | 185 | problems = [branin_100] 186 | res = { 187 | p.name+'_ablation': aggregate_problem_results(runs=all_results[p.name], problem=p) 188 | for p in problems 189 | } 190 | # Save 191 | with open(f'results/ablation_aggregated_results.json', "w") as fout: 192 | json.dump(object_to_json(res), fout) 193 | 194 | 195 | def compile_nasbench(): 196 | all_res = {} 197 | # TuRBO and CMAES 198 | for method in ['turbo', 'cmaes']: 199 | all_res[method] = [] 200 | for rep in range(100): 201 | with open(f'results/nasbench_{method}_rep_{rep}.json', 'r') as fin: 202 | fs, feas = json.load(fin) 203 | # Set infeasible points to nan 204 | fs = np.array(fs) 205 | fs[~np.array(feas)] = np.nan 206 | all_res[method].append(fs) 207 | 208 | # Ax methods 209 | for method in ['Sobol', 'ALEBO', 'HeSBO', 'REMBO']: 210 | all_res[method] = [] 211 | for rep in range(100): 212 | with open(f'results/nasbench_{method}_rep_{rep}.json', 'r') as fin: 213 | exp = object_from_json(json.load(fin)) 214 | # Pull out results and set infeasible points to nan 215 | df = exp.fetch_data().df.sort_values(by='arm_name') 216 | df_obj = df[df['metric_name'] == 'final_test_accuracy'].copy().reset_index(drop=True) 217 | df_con = df[df['metric_name'] == 'final_training_time'].copy().reset_index(drop=True) 218 | infeas = df_con['mean'] > 1800 219 | df_obj.loc[infeas, 'mean'] = np.nan 220 | all_res[method].append(df_obj['mean'].values) 221 | 222 | for method, arr in all_res.items(): 223 | all_res[method] = np.fmax.accumulate(np.vstack(all_res[method]), axis=1) 224 | 225 | with open(f'results/nasbench_aggregated_results.json', "w") as fout: 226 | json.dump(object_to_json(all_res), fout) 227 | 228 | 229 | if __name__ == '__main__': 230 | compile_nasbench() 231 | gc.collect() 232 | compile_hartmann6(D=100) 233 | gc.collect() 234 | compile_hartmann6(D=1000) 235 | gc.collect() 236 | compile_branin_gramacy_100() 237 | gc.collect() 238 | compile_sensitivity_benchmarks() 239 | gc.collect() 240 | compile_hartmann6(D=1000, random_subspace=True) 241 | gc.collect() 242 | compile_ablation_benchmarks() 243 | -------------------------------------------------------------------------------- /benchmarks/benchmark_problems.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. 2 | 3 | # This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. 4 | 5 | import json 6 | import numpy as np 7 | from scipy.stats import special_ortho_group 8 | from typing import List, Optional 9 | 10 | from ax.benchmark.benchmark_problem import BenchmarkProblem 11 | from ax.core.objective import Objective 12 | from ax.core.optimization_config import OptimizationConfig 13 | from ax.core.outcome_constraint import ComparisonOp, OutcomeConstraint 14 | from ax.core.parameter import ParameterType, RangeParameter 15 | from ax.core.search_space import SearchSpace 16 | from ax.metrics.branin import BraninMetric 17 | from ax.metrics.hartmann6 import Hartmann6Metric 18 | from ax.metrics.noisy_function import NoisyFunctionMetric 19 | from ax.storage.metric_registry import register_metric 20 | from ax.utils.measurement.synthetic_functions import hartmann6 21 | 22 | 23 | ### Hartmann6 problem, D=100 and D=1000 24 | 25 | # Relevant parameters were chosen randomly using 26 | # x = np.arange(100) 27 | # np.random.seed(10) 28 | # np.random.shuffle(x) 29 | # print(x[:6]) # [19 14 43 37 66 3] 30 | 31 | hartmann6_100 = BenchmarkProblem( 32 | name="Hartmann6, D=100", 33 | optimal_value=-3.32237, 34 | optimization_config=OptimizationConfig( 35 | objective=Objective( 36 | metric=Hartmann6Metric( 37 | name="objective", 38 | param_names=["x19", "x14", "x43", "x37", "x66", "x3"], 39 | noise_sd=0.0, 40 | ), 41 | minimize=True, 42 | ) 43 | ), 44 | search_space=SearchSpace( 45 | parameters=[ 46 | RangeParameter( 47 | name=f"x{i}", parameter_type=ParameterType.FLOAT, lower=0.0, upper=1.0 48 | ) 49 | for i in range(100) 50 | ] 51 | ), 52 | ) 53 | 54 | 55 | hartmann6_1000 = BenchmarkProblem( 56 | name="Hartmann6, D=1000", 57 | optimal_value=-3.32237, 58 | optimization_config=OptimizationConfig( 59 | objective=Objective( 60 | metric=Hartmann6Metric( 61 | name="objective", 62 | param_names=["x190", "x140", "x430", "x370", "x660", "x30"], 63 | noise_sd=0.0, 64 | ), 65 | minimize=True, 66 | ) 67 | ), 68 | search_space=SearchSpace( 69 | parameters=[ 70 | RangeParameter( 71 | name=f"x{i}", parameter_type=ParameterType.FLOAT, lower=0.0, upper=1.0 72 | ) 73 | for i in range(1000) 74 | ] 75 | ), 76 | ) 77 | 78 | 79 | ### Branin problem, D=100 and sensitivity analysis 80 | 81 | # Original x1 and x2 have different bounds, so we create blocks of 50 for each 82 | # with each of the bounds and set the relevant parameters in those blocks. 83 | 84 | branin_100 = BenchmarkProblem( 85 | name="Branin, D=100", 86 | optimal_value=0.397887, 87 | optimization_config=OptimizationConfig( 88 | objective=Objective( 89 | metric=BraninMetric( 90 | name="objective", param_names=["x19", "x64"], noise_sd=0.0 91 | ), 92 | minimize=True, 93 | ) 94 | ), 95 | search_space=SearchSpace( 96 | parameters=[ # pyre-ignore 97 | RangeParameter( 98 | name=f"x{i}", parameter_type=ParameterType.FLOAT, lower=-5.0, upper=10.0 99 | ) 100 | for i in range(50) 101 | ] 102 | + [ 103 | RangeParameter( 104 | name=f"x{i + 50}", 105 | parameter_type=ParameterType.FLOAT, 106 | lower=0.0, 107 | upper=15.0, 108 | ) 109 | for i in range(50) 110 | ] 111 | ), 112 | ) 113 | 114 | # Additional dimensionalities for the sensitivity analysis to D. 115 | # Random embedding methods are invariant to the ordering of relevant/irrelevant 116 | # parameters, and also to the bounds on the irrelevant parameters. So since 117 | # these problems are being used only for ALEBO, we can simplify their 118 | # definition and take x0 and x1 as the relevant. 119 | 120 | base_branin_parameters = [ 121 | RangeParameter( 122 | name="x0", parameter_type=ParameterType.FLOAT, lower=-5.0, upper=10.0 123 | ), 124 | RangeParameter( 125 | name="x1", parameter_type=ParameterType.FLOAT, lower=0.0, upper=15.0 126 | ), 127 | ] 128 | 129 | branin_by_D = { 130 | D: BenchmarkProblem( 131 | name="Branin, D=" + str(D), 132 | optimal_value=0.397887, 133 | optimization_config=OptimizationConfig( 134 | objective=Objective( 135 | metric=BraninMetric( 136 | name="objective", param_names=["x0", "x1"], noise_sd=0.0 137 | ), 138 | minimize=True, 139 | ) 140 | ), 141 | search_space=SearchSpace( 142 | parameters=base_branin_parameters # pyre-ignore 143 | + [ 144 | RangeParameter( 145 | name=f"x{i}", 146 | parameter_type=ParameterType.FLOAT, 147 | lower=0.0, 148 | upper=1.0, 149 | ) 150 | for i in range(2, D) 151 | ] 152 | ), 153 | ) 154 | for D in [50, 200, 500, 1000] 155 | } 156 | 157 | 158 | ### Gramacy problem, D=100 159 | 160 | class GramacyObjective(NoisyFunctionMetric): 161 | def f(self, x: np.ndarray) -> float: 162 | return x.sum() 163 | 164 | 165 | class GramacyConstraint1(NoisyFunctionMetric): 166 | def f(self, x: np.ndarray) -> float: 167 | return 1.5 - x[0] - 2 * x[1] - 0.5 * np.sin(2 * np.pi * (x[0] ** 2 - 2 * x[1])) 168 | 169 | 170 | class GramacyConstraint2(NoisyFunctionMetric): 171 | def f(self, x: np.ndarray) -> float: 172 | return x[0] ** 2 + x[1] ** 2 - 1.5 173 | 174 | 175 | # Register these metrics so they can be serialized to json 176 | register_metric(metric_cls=GramacyObjective, val=101) 177 | register_metric(metric_cls=GramacyConstraint1, val=102) 178 | register_metric(metric_cls=GramacyConstraint2, val=103) 179 | 180 | 181 | gramacy_100 = BenchmarkProblem( 182 | name="Gramacy, D=100", 183 | optimal_value=0.5998, 184 | optimization_config=OptimizationConfig( 185 | objective=Objective( 186 | metric=GramacyObjective( 187 | name="objective", param_names=["x19", "x64"], noise_sd=0.0 188 | ), 189 | minimize=True, 190 | ), 191 | outcome_constraints=[ 192 | OutcomeConstraint( 193 | metric=GramacyConstraint1( 194 | name="constraint1", param_names=["x19", "x64"], noise_sd=0.0 195 | ), 196 | op=ComparisonOp.LEQ, 197 | bound=0.0, 198 | relative=False, 199 | ), 200 | OutcomeConstraint( 201 | metric=GramacyConstraint2( 202 | name="constraint2", param_names=["x19", "x64"], noise_sd=0.0 203 | ), 204 | op=ComparisonOp.LEQ, 205 | bound=0.0, 206 | relative=False, 207 | ), 208 | ], 209 | ), 210 | search_space=SearchSpace( 211 | parameters=[ 212 | RangeParameter( 213 | name=f"x{i}", parameter_type=ParameterType.FLOAT, lower=0.0, upper=1.0 214 | ) 215 | for i in range(100) 216 | ] 217 | ), 218 | ) 219 | 220 | ### Hartmann6 D=1000 with random subspace 221 | 222 | class Hartmann6RandomSubspace1000Metric(NoisyFunctionMetric): 223 | def __init__( 224 | self, 225 | name: str, 226 | param_names: List[str], 227 | noise_sd: float = 0.0, 228 | lower_is_better: Optional[bool] = None, 229 | ) -> None: 230 | super().__init__( 231 | name=name, 232 | param_names=param_names, 233 | noise_sd=noise_sd, 234 | lower_is_better=lower_is_better, 235 | ) 236 | # Set the random basis 237 | try: 238 | with open('data/random_subspace_1000x6.json', 'r') as fin: 239 | self.random_basis = np.array(json.load(fin)) 240 | except IOError: 241 | np.random.seed(1000) 242 | self.random_basis = special_ortho_group.rvs(1000)[:6, :] 243 | with open('data/random_subspace_1000x6.json', 'w') as fout: 244 | json.dump(self.random_basis.tolist(), fout) 245 | 246 | def f(self, x: np.ndarray) -> float: 247 | # Project down to the true subspace 248 | z = self.random_basis @ x 249 | # x \in [-1, 1], so adjust z to be closer to [0, 1], and evaluate 250 | return hartmann6((z + 1) / 2.) 251 | 252 | register_metric(metric_cls=Hartmann6RandomSubspace1000Metric, val=104) 253 | 254 | hartmann6_random_subspace_1000 = BenchmarkProblem( 255 | name="Hartmann6 random subspace, D=1000", 256 | optimal_value=-3.32237, 257 | optimization_config=OptimizationConfig( 258 | objective=Objective( 259 | metric=Hartmann6RandomSubspace1000Metric( 260 | name="objective", 261 | param_names=[f"x{i}" for i in range(1000)], 262 | noise_sd=0.0, 263 | ), 264 | minimize=True, 265 | ) 266 | ), 267 | search_space=SearchSpace( 268 | parameters=[ 269 | RangeParameter( 270 | name=f"x{i}", parameter_type=ParameterType.FLOAT, lower=-1.0, upper=1.0 271 | ) 272 | for i in range(1000) 273 | ] 274 | ), 275 | ) 276 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | Section 1 -- Definitions. 71 | 72 | a. Adapted Material means material subject to Copyright and Similar 73 | Rights that is derived from or based upon the Licensed Material 74 | and in which the Licensed Material is translated, altered, 75 | arranged, transformed, or otherwise modified in a manner requiring 76 | permission under the Copyright and Similar Rights held by the 77 | Licensor. For purposes of this Public License, where the Licensed 78 | Material is a musical work, performance, or sound recording, 79 | Adapted Material is always produced where the Licensed Material is 80 | synched in timed relation with a moving image. 81 | 82 | b. Adapter's License means the license You apply to Your Copyright 83 | and Similar Rights in Your contributions to Adapted Material in 84 | accordance with the terms and conditions of this Public License. 85 | 86 | c. Copyright and Similar Rights means copyright and/or similar rights 87 | closely related to copyright including, without limitation, 88 | performance, broadcast, sound recording, and Sui Generis Database 89 | Rights, without regard to how the rights are labeled or 90 | categorized. For purposes of this Public License, the rights 91 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 92 | Rights. 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. NonCommercial means not primarily intended for or directed towards 116 | commercial advantage or monetary compensation. For purposes of 117 | this Public License, the exchange of the Licensed Material for 118 | other material subject to Copyright and Similar Rights by digital 119 | file-sharing or similar means is NonCommercial provided there is 120 | no payment of monetary compensation in connection with the 121 | exchange. 122 | 123 | j. Share means to provide material to the public by any means or 124 | process that requires permission under the Licensed Rights, such 125 | as reproduction, public display, public performance, distribution, 126 | dissemination, communication, or importation, and to make material 127 | available to the public including in ways that members of the 128 | public may access the material from a place and at a time 129 | individually chosen by them. 130 | 131 | k. Sui Generis Database Rights means rights other than copyright 132 | resulting from Directive 96/9/EC of the European Parliament and of 133 | the Council of 11 March 1996 on the legal protection of databases, 134 | as amended and/or succeeded, as well as other essentially 135 | equivalent rights anywhere in the world. 136 | 137 | l. You means the individual or entity exercising the Licensed Rights 138 | under this Public License. Your has a corresponding meaning. 139 | 140 | Section 2 -- Scope. 141 | 142 | a. License grant. 143 | 144 | 1. Subject to the terms and conditions of this Public License, 145 | the Licensor hereby grants You a worldwide, royalty-free, 146 | non-sublicensable, non-exclusive, irrevocable license to 147 | exercise the Licensed Rights in the Licensed Material to: 148 | 149 | a. reproduce and Share the Licensed Material, in whole or 150 | in part, for NonCommercial purposes only; and 151 | 152 | b. produce, reproduce, and Share Adapted Material for 153 | NonCommercial purposes only. 154 | 155 | 2. Exceptions and Limitations. For the avoidance of doubt, where 156 | Exceptions and Limitations apply to Your use, this Public 157 | License does not apply, and You do not need to comply with 158 | its terms and conditions. 159 | 160 | 3. Term. The term of this Public License is specified in Section 161 | 6(a). 162 | 163 | 4. Media and formats; technical modifications allowed. The 164 | Licensor authorizes You to exercise the Licensed Rights in 165 | all media and formats whether now known or hereafter created, 166 | and to make technical modifications necessary to do so. The 167 | Licensor waives and/or agrees not to assert any right or 168 | authority to forbid You from making technical modifications 169 | necessary to exercise the Licensed Rights, including 170 | technical modifications necessary to circumvent Effective 171 | Technological Measures. For purposes of this Public License, 172 | simply making modifications authorized by this Section 2(a) 173 | (4) never produces Adapted Material. 174 | 175 | 5. Downstream recipients. 176 | 177 | a. Offer from the Licensor -- Licensed Material. Every 178 | recipient of the Licensed Material automatically 179 | receives an offer from the Licensor to exercise the 180 | Licensed Rights under the terms and conditions of this 181 | Public License. 182 | 183 | b. No downstream restrictions. You may not offer or impose 184 | any additional or different terms or conditions on, or 185 | apply any Effective Technological Measures to, the 186 | Licensed Material if doing so restricts exercise of the 187 | Licensed Rights by any recipient of the Licensed 188 | Material. 189 | 190 | 6. No endorsement. Nothing in this Public License constitutes or 191 | may be construed as permission to assert or imply that You 192 | are, or that Your use of the Licensed Material is, connected 193 | with, or sponsored, endorsed, or granted official status by, 194 | the Licensor or others designated to receive attribution as 195 | provided in Section 3(a)(1)(A)(i). 196 | 197 | b. Other rights. 198 | 199 | 1. Moral rights, such as the right of integrity, are not 200 | licensed under this Public License, nor are publicity, 201 | privacy, and/or other similar personality rights; however, to 202 | the extent possible, the Licensor waives and/or agrees not to 203 | assert any such rights held by the Licensor to the limited 204 | extent necessary to allow You to exercise the Licensed 205 | Rights, but not otherwise. 206 | 207 | 2. Patent and trademark rights are not licensed under this 208 | Public License. 209 | 210 | 3. To the extent possible, the Licensor waives any right to 211 | collect royalties from You for the exercise of the Licensed 212 | Rights, whether directly or through a collecting society 213 | under any voluntary or waivable statutory or compulsory 214 | licensing scheme. In all other cases the Licensor expressly 215 | reserves any right to collect such royalties, including when 216 | the Licensed Material is used other than for NonCommercial 217 | purposes. 218 | 219 | Section 3 -- License Conditions. 220 | 221 | Your exercise of the Licensed Rights is expressly made subject to the 222 | following conditions. 223 | 224 | a. Attribution. 225 | 226 | 1. If You Share the Licensed Material (including in modified 227 | form), You must: 228 | 229 | a. retain the following if it is supplied by the Licensor 230 | with the Licensed Material: 231 | 232 | i. identification of the creator(s) of the Licensed 233 | Material and any others designated to receive 234 | attribution, in any reasonable manner requested by 235 | the Licensor (including by pseudonym if 236 | designated); 237 | 238 | ii. a copyright notice; 239 | 240 | iii. a notice that refers to this Public License; 241 | 242 | iv. a notice that refers to the disclaimer of 243 | warranties; 244 | 245 | v. a URI or hyperlink to the Licensed Material to the 246 | extent reasonably practicable; 247 | 248 | b. indicate if You modified the Licensed Material and 249 | retain an indication of any previous modifications; and 250 | 251 | c. indicate the Licensed Material is licensed under this 252 | Public License, and include the text of, or the URI or 253 | hyperlink to, this Public License. 254 | 255 | 2. You may satisfy the conditions in Section 3(a)(1) in any 256 | reasonable manner based on the medium, means, and context in 257 | which You Share the Licensed Material. For example, it may be 258 | reasonable to satisfy the conditions by providing a URI or 259 | hyperlink to a resource that includes the required 260 | information. 261 | 262 | 3. If requested by the Licensor, You must remove any of the 263 | information required by Section 3(a)(1)(A) to the extent 264 | reasonably practicable. 265 | 266 | 4. If You Share Adapted Material You produce, the Adapter's 267 | License You apply must not prevent recipients of the Adapted 268 | Material from complying with this Public License. 269 | 270 | Section 4 -- Sui Generis Database Rights. 271 | 272 | Where the Licensed Rights include Sui Generis Database Rights that 273 | apply to Your use of the Licensed Material: 274 | 275 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 276 | to extract, reuse, reproduce, and Share all or a substantial 277 | portion of the contents of the database for NonCommercial purposes 278 | only; 279 | 280 | b. if You include all or a substantial portion of the database 281 | contents in a database in which You have Sui Generis Database 282 | Rights, then the database in which You have Sui Generis Database 283 | Rights (but not its individual contents) is Adapted Material; and 284 | 285 | c. You must comply with the conditions in Section 3(a) if You Share 286 | all or a substantial portion of the contents of the database. 287 | 288 | For the avoidance of doubt, this Section 4 supplements and does not 289 | replace Your obligations under this Public License where the Licensed 290 | Rights include other Copyright and Similar Rights. 291 | 292 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 293 | 294 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 295 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 296 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 297 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 298 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 299 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 300 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 301 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 302 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 303 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 304 | 305 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 306 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 307 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 308 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 309 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 310 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 311 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 312 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 313 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 314 | 315 | c. The disclaimer of warranties and limitation of liability provided 316 | above shall be interpreted in a manner that, to the extent 317 | possible, most closely approximates an absolute disclaimer and 318 | waiver of all liability. 319 | 320 | Section 6 -- Term and Termination. 321 | 322 | a. This Public License applies for the term of the Copyright and 323 | Similar Rights licensed here. However, if You fail to comply with 324 | this Public License, then Your rights under this Public License 325 | terminate automatically. 326 | 327 | b. Where Your right to use the Licensed Material has terminated under 328 | Section 6(a), it reinstates: 329 | 330 | 1. automatically as of the date the violation is cured, provided 331 | it is cured within 30 days of Your discovery of the 332 | violation; or 333 | 334 | 2. upon express reinstatement by the Licensor. 335 | 336 | For the avoidance of doubt, this Section 6(b) does not affect any 337 | right the Licensor may have to seek remedies for Your violations 338 | of this Public License. 339 | 340 | c. For the avoidance of doubt, the Licensor may also offer the 341 | Licensed Material under separate terms or conditions or stop 342 | distributing the Licensed Material at any time; however, doing so 343 | will not terminate this Public License. 344 | 345 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 346 | License. 347 | 348 | Section 7 -- Other Terms and Conditions. 349 | 350 | a. The Licensor shall not be bound by any additional or different 351 | terms or conditions communicated by You unless expressly agreed. 352 | 353 | b. Any arrangements, understandings, or agreements regarding the 354 | Licensed Material not stated herein are separate from and 355 | independent of the terms and conditions of this Public License. 356 | 357 | Section 8 -- Interpretation. 358 | 359 | a. For the avoidance of doubt, this Public License does not, and 360 | shall not be interpreted to, reduce, limit, restrict, or impose 361 | conditions on any use of the Licensed Material that could lawfully 362 | be made without permission under this Public License. 363 | 364 | b. To the extent possible, if any provision of this Public License is 365 | deemed unenforceable, it shall be automatically reformed to the 366 | minimum extent necessary to make it enforceable. If the provision 367 | cannot be reformed, it shall be severed from this Public License 368 | without affecting the enforceability of the remaining terms and 369 | conditions. 370 | 371 | c. No term or condition of this Public License will be waived and no 372 | failure to comply consented to unless expressly agreed to by the 373 | Licensor. 374 | 375 | d. Nothing in this Public License constitutes or may be interpreted 376 | as a limitation upon, or waiver of, any privileges and immunities 377 | that apply to the Licensor or You, including from the legal 378 | processes of any jurisdiction or authority. 379 | 380 | ======================================================================= 381 | 382 | Creative Commons is not a party to its public 383 | licenses. Notwithstanding, Creative Commons may elect to apply one of 384 | its public licenses to material it publishes and in those instances 385 | will be considered the “Licensor.” The text of the Creative Commons 386 | public licenses is dedicated to the public domain under the CC0 Public 387 | Domain Dedication. Except for the limited purpose of indicating that 388 | material is shared under a Creative Commons public license or as 389 | otherwise permitted by the Creative Commons policies published at 390 | creativecommons.org/policies, Creative Commons does not authorize the 391 | use of the trademark "Creative Commons" or any other trademark or logo 392 | of Creative Commons without its prior written consent including, 393 | without limitation, in connection with any unauthorized modifications 394 | to any of its public licenses or any other arrangements, 395 | understandings, or agreements concerning use of licensed material. For 396 | the avoidance of doubt, this paragraph does not form part of the 397 | public licenses. 398 | 399 | Creative Commons may be contacted at creativecommons.org. -------------------------------------------------------------------------------- /quickstart.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n", 10 | "\n", 11 | "# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree." 12 | ] 13 | }, 14 | { 15 | "cell_type": "markdown", 16 | "metadata": {}, 17 | "source": [ 18 | "## Optimizing a high-dimensional function with ALEBO\n", 19 | "This notebook provides a simple example of how to optimize a high-dimensional function with ALEBO.\n", 20 | "\n", 21 | "ALEBO is described in:\n", 22 | "\n", 23 | "B Letham, R Calandra, A Rai, E Bakshy (2020) Re-examining linear embeddings for high-dimensional Bayesian optimization. _Submitted_.\n", 24 | "\n", 25 | "See the github repository for the full code used for the benchmark experiments in the paper.\n", 26 | "\n", 27 | "We use Ax to manage the optimization loop; see https://ax.dev/tutorials/gpei_hartmann_loop.html for more documentation on the API used here." 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 1, 33 | "metadata": {}, 34 | "outputs": [], 35 | "source": [ 36 | "# Define a function to be optimized.\n", 37 | "# Here we use a simple synthetic function with a d=2 true linear embedding, in\n", 38 | "# a D=100 ambient space.\n", 39 | "\n", 40 | "import numpy as np\n", 41 | "from ax.utils.measurement.synthetic_functions import branin\n", 42 | "\n", 43 | "\n", 44 | "def branin_evaluation_function(parameterization):\n", 45 | " # Evaluates Branin on the first two parameters of the parameterization.\n", 46 | " # Other parameters are unused.\n", 47 | " x = np.array([parameterization[\"x0\"], parameterization[\"x1\"]])\n", 48 | " return {\"objective\": (branin(x), 0.0)}" 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": 2, 54 | "metadata": {}, 55 | "outputs": [], 56 | "source": [ 57 | "# Define the parameters in the format expected by Ax.\n", 58 | "# Here we define a D=100 search space by augmenting the real Branin parameters\n", 59 | "# with 98 unused parameters.\n", 60 | "\n", 61 | "parameters = [\n", 62 | " {\"name\": \"x0\", \"type\": \"range\", \"bounds\": [-5.0, 10.0], \"value_type\": \"float\"},\n", 63 | " {\"name\": \"x1\", \"type\": \"range\", \"bounds\": [0.0, 15.0], \"value_type\": \"float\"},\n", 64 | "]\n", 65 | "parameters.extend([\n", 66 | " {\"name\": f\"x{i}\", \"type\": \"range\", \"bounds\": [-5.0, 10.0], \"value_type\": \"float\"}\n", 67 | " for i in range(2, 100)\n", 68 | "])" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": 3, 74 | "metadata": {}, 75 | "outputs": [ 76 | { 77 | "name": "stderr", 78 | "output_type": "stream", 79 | "text": [ 80 | "[INFO 01-09 12:20:47] ax.modelbridge.generation_strategy: Using model via callable function, so optimization is not resumable if interrupted.\n" 81 | ] 82 | } 83 | ], 84 | "source": [ 85 | "# Setup the ALEBO optimization strategy\n", 86 | "# We must specify the ambient dimensionality (determined by the problem - here 100),\n", 87 | "# the embedding dimensionality, and the number of initial random points. As\n", 88 | "# discussed in the paper, the embedding dimensionality should be larger than the\n", 89 | "# true subspace dimensionality. Here we use 4, since the true dimensionality is 2;\n", 90 | "# see the paper for more discussion on this point.\n", 91 | "\n", 92 | "from ax.modelbridge.strategies.alebo import ALEBOStrategy\n", 93 | "\n", 94 | "alebo_strategy = ALEBOStrategy(D=100, d=4, init_size=5)" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": 4, 100 | "metadata": {}, 101 | "outputs": [ 102 | { 103 | "name": "stderr", 104 | "output_type": "stream", 105 | "text": [ 106 | "[INFO 01-09 12:20:50] ax.service.managed_loop: Started full optimization with 30 steps.\n", 107 | "[INFO 01-09 12:20:50] ax.service.managed_loop: Running optimization trial 1...\n", 108 | "[INFO 01-09 12:20:52] ax.service.managed_loop: Running optimization trial 2...\n", 109 | "[INFO 01-09 12:20:54] ax.service.managed_loop: Running optimization trial 3...\n", 110 | "[INFO 01-09 12:20:55] ax.service.managed_loop: Running optimization trial 4...\n", 111 | "[INFO 01-09 12:20:57] ax.service.managed_loop: Running optimization trial 5...\n", 112 | "[INFO 01-09 12:20:59] ax.service.managed_loop: Running optimization trial 6...\n", 113 | "[INFO 01-09 12:22:43] ax.service.managed_loop: Running optimization trial 7...\n", 114 | "[INFO 01-09 12:24:06] ax.service.managed_loop: Running optimization trial 8...\n", 115 | "[INFO 01-09 12:25:29] ax.service.managed_loop: Running optimization trial 9...\n", 116 | "[INFO 01-09 12:26:49] ax.service.managed_loop: Running optimization trial 10...\n", 117 | "[INFO 01-09 12:28:26] ax.service.managed_loop: Running optimization trial 11...\n", 118 | "[INFO 01-09 12:29:41] ax.service.managed_loop: Running optimization trial 12...\n", 119 | "[INFO 01-09 12:31:11] ax.service.managed_loop: Running optimization trial 13...\n", 120 | "[INFO 01-09 12:32:35] ax.service.managed_loop: Running optimization trial 14...\n", 121 | "[INFO 01-09 12:34:21] ax.service.managed_loop: Running optimization trial 15...\n", 122 | "[INFO 01-09 12:36:08] ax.service.managed_loop: Running optimization trial 16...\n", 123 | "[INFO 01-09 12:37:29] ax.service.managed_loop: Running optimization trial 17...\n", 124 | "[INFO 01-09 12:38:24] ax.service.managed_loop: Running optimization trial 18...\n", 125 | "[INFO 01-09 12:39:20] ax.service.managed_loop: Running optimization trial 19...\n", 126 | "[INFO 01-09 12:40:40] ax.service.managed_loop: Running optimization trial 20...\n", 127 | "[INFO 01-09 12:43:05] ax.service.managed_loop: Running optimization trial 21...\n", 128 | "[INFO 01-09 12:44:46] ax.service.managed_loop: Running optimization trial 22...\n", 129 | "[INFO 01-09 12:46:20] ax.service.managed_loop: Running optimization trial 23...\n", 130 | "[INFO 01-09 12:47:36] ax.service.managed_loop: Running optimization trial 24...\n", 131 | "/usr/local/lib/python3.7/site-packages/ax_platform-0.1.8-py3.7.egg/ax/models/torch/alebo.py:325: RuntimeWarning:\n", 132 | "\n", 133 | "covariance is not symmetric positive-semidefinite.\n", 134 | "\n", 135 | "[INFO 01-09 12:49:24] ax.service.managed_loop: Running optimization trial 25...\n", 136 | "[INFO 01-09 12:50:48] ax.service.managed_loop: Running optimization trial 26...\n", 137 | "[INFO 01-09 12:52:34] ax.service.managed_loop: Running optimization trial 27...\n", 138 | "[INFO 01-09 12:54:13] ax.service.managed_loop: Running optimization trial 28...\n", 139 | "[INFO 01-09 12:55:50] ax.service.managed_loop: Running optimization trial 29...\n", 140 | "[INFO 01-09 12:57:11] ax.service.managed_loop: Running optimization trial 30...\n" 141 | ] 142 | } 143 | ], 144 | "source": [ 145 | "# Run the optimization loop with that strategy\n", 146 | "# This will take about 30 mins to run\n", 147 | "\n", 148 | "from ax.service.managed_loop import optimize\n", 149 | "\n", 150 | "best_parameters, values, experiment, model = optimize(\n", 151 | " parameters=parameters,\n", 152 | " experiment_name=\"branin_100\",\n", 153 | " objective_name=\"objective\",\n", 154 | " evaluation_function=branin_evaluation_function,\n", 155 | " minimize=True,\n", 156 | " total_trials=30,\n", 157 | " generation_strategy=alebo_strategy,\n", 158 | ")" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": 20, 164 | "metadata": {}, 165 | "outputs": [ 166 | { 167 | "data": { 168 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAtEAAAF3CAYAAABjZBdpAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDMuMC4zLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvnQurowAAIABJREFUeJzt3Xl8nWWZ//Hvla1Zmi45adPSZoHSlhaGFiwIyE6qiKgwMoAKwjgzRdwoqCPwY0aUGZcZkUVHhiqI48KiiAIiWiplEYVSLAVa2kJJS0v3dEnTLcv1+yNPMF2SnJSePPdzzuf9ep1Xznmes1xw5cC3d+/nvs3dBQAAACB9eXEXAAAAACQNIRoAAADoI0I0AAAA0EeEaAAAAKCPCNEAAABAHxGiAQAAgD4iRAMAAAB9RIgGAAAA+ogQDQAAAPQRIRoAAADoo4K4C0hHZWWl19XV9fic9vZ25eXxZ4KQ0aPw0aPw0aPw0aPw0aPwxdmjuXPnrnf3Yb09LxEhuq6uTs8//3yPz2lqalJ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QAAMgCvYZodz++PwpBdhtWPkAlhXlatoEQDQAAkq/bEG1m97n7+dE0jq5Xg5kkd/cjM14dsoaZafTQEqZzAACArNDTSPQV0c+z+6MQZL/qIcWMRAMAgKzQ7YWF7r4quvtpd1/W9Sbp0/1THrJJTUWJljVuY5k7AACQeOkscTd1H8fef6ALQfarHlKsXa3tWtPEhpcAACDZepoTfbk6RpzHmNn8LqfK1bHMHdAno4eWSJKWbdimkYNLYq4GAABg//U0J/rnkn4n6RuSru5yvMndGzNaFbJSTUWxpI61oo87JBVzNQAAAPuvpznRm929QdItkhq7zIduNbN391eByB4jBhWrIM+4uBAAACReOnOib5O0tcvjrdExoE8K8kzVFaWEaAAAkHjphGhz97eXU3D3dqW30yGwl5qKUi1rZK1oAACQbOmE6KVm9nkzK4xuV0hamunCkJ1qUx0j0V3+XAYAAJA46YToT0k6QdJKSSskvVvStEwWhexVmypT045WbdzWEncpAAAA+63XaRnuvlbShf1QC3JAbUWppI4VOirKimKuBgAAYP/0OhJtZuPMbJaZvRw9PtLMrst8achGtamOEL28kYsLAQBAcqUzneMHkq6R1CJJ7j5fjExjP1VXlMpMalhPiAYAAMmVTogudffn9jjWmolikP2KC/M1YlAxK3QAAIBESydErzezMZJckszsPEmrMloVslrnCh0AAABJlc56z5+RNEPSYWa2UtIbki7KaFXIarUVZZr16tq4ywAAANhv6azOsVRSvZmVScpz96bMl4VsVpMq1fqtO9W8s1VlA9i3BwAAJE+3CcbMLnL3n5rZVXsclzqmdjRKetDdN3bz+jslnS1prbsfER27XtK/SFoXPe1ad3/knf5DIFnqUmWSpGUbtmniQYNirgYAAKDvepoTXRb9LN/HbZCkd0n6XQ+vv0vSmfs4fpO7T45uBOgc9Ldl7ri4EAAAJFO3I9Hufnv086vdPcfMvtbD6580s7p3UhyyU02qc8MVLi4EAADJlM5mK4eY2UNmts7M1prZb8zsEEly93/fj8/8rJnNN7M7zWzofrweCTeouFAVZUVqIEQDAICESueqrp9L+h9J50aPL5R0t6R378fn3Sbp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IWMHoWPHoUvKT1as2WH7vzTGyoqyNOxdRU6eVylThk3XOOqBsrM4i4v55m7x11Dr6ZMmeLPP/98j89pampSeXl5P1WE/UGPwkePwkePwkePwpeUHu1oadOchkY9sWidnlyyTovXbJUkjRhUrJPHVerkccN04qGVGlJaFHOlB16cPTKzue4+pbfnMRINAAAQoOLCfJ00dphOGjtMkvTWpu16ask6PbF4nR59ebXue36F8kyaVD1Ep4wbppPHDdOk0UOUn8codX8gRAMAACTAQUNKdMExNbrgmBq1trXrxRWb9MTi9Xpy8TrdMmuJbn5siQaXFOrEsZU6ZdwwnTJumKoGFcdddtYiRAMAACRMQX6e3lVboXfVVuiqqeO0sXmXnn5tvZ5YvE5PLl6n385fJUk6bES5To4C9ZS6oRpQwAWKBwohGgAAIOGGlhXpg5MO0gcnHSR316urm/Tk4o6pH3f9qUEznlyqksJ8jRtRriTM9qgsLdAPLn133GX0iBANAACQRcxME0YO0oSRg3TZKWPUvLNVf1m6QU8uXqel65OxSVkSlvQjRAMAAGSxsgEFOmNClc6YUBV3KWlramqKu4ReJSJEL1q0SKeeeupux84//3x9+tOf1rZt23TWWWepra1N+fl/+1PLpZdeqksvvVTr16/Xeeedt9d7Xn755brgggv05ptv6uKLL97r/Be+8AV98IMf1KJFi3TZZZftdf66665TfX295s2bp+nTp+91/utf/7pOOOEEPfPMM7r22mv3On/zzTdr8uTJeuyxx/Qf//Efe52//fbbNX78eD300EO68cYb9zr/k5/8RNXV1br33nt122237XX+l7/8pSorK3XXXXfprrvu2uv8I488otLSUn3/+9/Xfffdt9f52bNnS5K+/e1v6+GHH97tXElJiX73u99Jkm644QbNmjVrt/OpVEr333+/JOmaa67Rn//8Z0l6u0ejR4/WT3/6U0nS9OnTNW/e7puljBs3TjNmzJAkTZs2TYsXL97t/OTJk3XzzTdLki666CKtWLFit/PHH3+8vvGNb0iSPvKRj2jDhg27nT/jjDP0b//2b5Kk97///dq+fftu588++2x98YtflKS9fu+kvX/39pTk3722tjb98Ic/zLrfvU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vSfqTpPdIevrA/+MCQPIwEg0A4XuvpE+Y2Tx1bCedkjQ2OvdclwAtSZ83sxcl/UVSdZfndedESXe7e5u7r5H0hKRjurz3CndvlzRPHdNMAABiJBoAksAkfc7df7/bQbNTJTXv8bhe0vHuvs3MZksqfgefu7PL/Tbx/wwAeBsj0QAQniZJ5V0e/17S5WZWKElmNs7MyvbxusGSNkYB+jBJx3U519L5+j08JemCaN71MEknS3rugPxTAEAWY1QBAMIzX1JbNC3jLkm3qGMqxQvRxX3rJJ2zj9c9KulTZrZQ0iJ1TOnoNEPSfDN7wd0/3uX4A5KOl/SiJJf0r+6+OgrhAIBumLvHXQMAAACQKEznAAAAAPqIEA0AAAD0ESEaAAAA6CNCNAAAANBHhGgAAACgjwjRAAAAQB8RogEAAIA+IkQDAAAAffT/AYvN4LFHjBBiAAAAAElFTkSuQmCC\n", 169 | "text/plain": [ 170 | "
" 171 | ] 172 | }, 173 | "metadata": { 174 | "needs_background": "light" 175 | }, 176 | "output_type": "display_data" 177 | } 178 | ], 179 | "source": [ 180 | "# Extract out the objective values at each iteration and make a plot\n", 181 | "\n", 182 | "from matplotlib import pyplot as plt\n", 183 | "\n", 184 | "objectives = np.array([trial.objective_mean for trial in experiment.trials.values()])\n", 185 | "\n", 186 | "fig = plt.figure(figsize=(12, 6))\n", 187 | "ax = fig.add_subplot(111)\n", 188 | "ax.grid(alpha=0.2)\n", 189 | "ax.plot(range(1, 31), np.minimum.accumulate(objectives))\n", 190 | "ax.axhline(y=branin.fmin, ls='--', c='k')\n", 191 | "ax.set_xlabel('Iteration')\n", 192 | "ax.set_ylabel('Best objective found');" 193 | ] 194 | } 195 | ], 196 | "metadata": { 197 | "kernelspec": { 198 | "display_name": "Python 3", 199 | "language": "python", 200 | "name": "python3" 201 | }, 202 | "language_info": { 203 | "codemirror_mode": { 204 | "name": "ipython", 205 | "version": 3 206 | }, 207 | "file_extension": ".py", 208 | "mimetype": "text/x-python", 209 | "name": "python", 210 | "nbconvert_exporter": "python", 211 | "pygments_lexer": "ipython3", 212 | "version": "3.7.5" 213 | } 214 | }, 215 | "nbformat": 4, 216 | "nbformat_minor": 2 217 | } 218 | --------------------------------------------------------------------------------