#!/usr/bin/env python # coding: utf-8 # # OPTaaS Batching # # ### Note: To run this notebook, you need an API Key. You can get one here. # # OPTaaS can facilitate parallel computation, where you generate a batch of configurations, pass them to a number of workers to calculate the results, and then store the results to get the next batch of configurations. # ## Connect to OPTaaS using your API Key # In[1]: from mindfoundry.optaas.client.client import OPTaaSClient client = OPTaaSClient('https://optaas.mindfoundry.ai', '') # ## Create your Task # In[2]: from mindfoundry.optaas.client.parameter import FloatParameter task = client.create_task( title='Batching Example', parameters=[ FloatParameter('x', minimum=0, maximum=1), FloatParameter('y', minimum=0.1, maximum=2) ] ) # ## Set up your workers # This is just a simple example of how you would pass a Configuration to a worker and get a Result back. Your process will of course likely be more complex! # # The number of workers will depend on how much processing power you have available. In order to get the best quality configurations from OPTaaS, we recommend using no more than 10. # In[3]: from multiprocessing import Pool from time import sleep from mindfoundry.optaas.client.result import Result number_of_workers = 4 def spin_off_workers_and_get_results(configurations): with Pool(number_of_workers) as pool: return pool.map(get_result, configurations) def get_result(configuration): x = configuration.values['x'] y = configuration.values['y'] sleep(1) # Calculating score... score = (x * y) - (x / y) return Result(configuration=configuration, score=score) # ## Generate the first batch of configurations # In[4]: configurations = task.generate_configurations(number_of_workers) display(configurations) # ## Record results to get the next batch of configurations # # The next batch will be the same size as the number of results you record. # In[5]: number_of_batches = 3 for _ in range(number_of_batches): results = spin_off_workers_and_get_results(configurations) print(f"Scores: {[result.score for result in results]}\n") configurations = task.record_results(results) print(f"Next configurations: {[c.values for c in configurations]}\n")