def install_package(install_name): try: package_path = PLUGIN_INSTALLATIONS[install_name] except KeyError as ex: xacc.info( F"There is no '{install_name}' XACC Python plugin package available." ) exit(1) install_directive = os.path.join(package_path + "/install.ini") if os.path.isfile( package_path + "/install.ini") else None plugin_files = [] if not install_directive: plugin_files += [ package_path + "/" + f for f in os.listdir(package_path) if os.path.isfile(os.path.join(package_path, f)) and f.endswith(".py") ] else: plugin_dict, plugin_list = read_install_directive( install_directive, package_path) for k, v in plugin_dict.items(): mini_package_path = v plugin_files += [ v + "/" + f for f in os.listdir(v) if os.path.isfile(os.path.join(v, f)) and f.endswith(".py") ] n_plugins = len(plugin_files) for plugin in plugin_files: copy(os.path.join(plugin), XACC_PYTHON_PLUGIN_PATH) xacc.info( F"Installed {n_plugins} plugins from the '{install_name}' package to the {XACC_PYTHON_PLUGIN_PATH}." )
def __call__(self, *args, **kwargs): super().__call__(*args, **kwargs) def getParams(params): return ','.join(map(str, params)) execParams = {'accelerator': self.qpu, 'ansatz': self.compiledKernel, 'task': 'vqe'} obs = self.kwargs['observable'] ars = list(args) if not isinstance(args[0], xacc.AcceleratorBuffer): raise RuntimeError( 'First argument of an xacc kernel must be the Accelerator Buffer to operate on.') buffer = ars[0] ars = ars[1:] if len(ars) > 0: arStr = getParams(ars) execParams['vqe-params'] = arStr # optimizer given if 'optimizer' in self.kwargs: opt_name = self.kwargs['optimizer'] optimizer_args = {} # get optimizer from available vqe_optimization services if opt_name not in self.vqe_optimizers: xacc.info("The {} 'vqe_optimization' service is not available.".format(opt_name)) exit(1) else: optimizer = self.vqe_optimizers[opt_name] # get all the options to pass to optimizer if 'options' in self.kwargs: optimizer_args = self.kwargs['options'] # call optimize() method of optimizer optimizer.optimize(obs, buffer, optimizer_args, execParams) else: vqe.execute(obs, buffer, **execParams) return
def batchData(self, array, batch_size): part_batches = array.shape[0] % batch_size if part_batches > 0: padding = batch_size - part_batches padded_array = np.zeros((padding, array.shape[1])) array = np.append(array, padded_array, axis=0) whole_batches = array.shape[0] // batch_size final_array = np.zeros((whole_batches, batch_size, array.shape[1])) fidx = 0 for i in range(final_array.shape[0]): final_array[i] = array[i*batch_size:batch_size+(batch_size*i)] xacc.info("Batched Array: " + str(final_array.shape)) return final_array
def main(argv=None): opts = parse_args(sys.argv[1:]) get_packages() if opts.path: set_plugin_path(opts.path) if opts.install: install_package(opts.install) if opts.list: xacc.info("Available XACC Python plugin packages:") for k, v in MASTER_PACKAGES.items(): xacc.info("{:5}: {!s}".format(k, v))
def energy(self, params): xacc.info( "The energy() method is meant to be implemented by VQEOpt subclasses!" ) exit(1) pass
def __call__(self, *args, **kwargs): super().__call__(*args, **kwargs) self.initial_rbm = True self.buffer = args[0] self.embedding = self.buffer.getInformation('embedding') # Get the training parameters (rate, num_epochs, batch_size, momentum) self.learn_rate = self.kwargs['rate'] self.num_epochs = self.kwargs['num_epochs'] self.momentum = self.kwargs['momentum'] self.batch_size = self.kwargs['batch_size'] self.num_classes = self.kwargs['max_classes'] self.train_steps = self.kwargs['train_steps'] if 'chain-strength' in self.kwargs: xacc.setOption('chain-strength', self.kwargs['chain_strength']) if 'num_samples' in self.kwargs: xacc.setOption('dwave-num-reads', self.kwargs['num_samples']) # Get parameterized DWK self.rbm_function = self.compiledKernel # Might be a better way to get these values, but this is what I'm shooting for right now self.numV = 0 self.numH = 0 self.numW = 0 for inst in self.rbm_function.getParameters(): if 'v' in inst: self.numV += 1 if 'h' in inst: self.numH += 1 if 'w' in inst: self.numW += 1 # Initializing the weights from a random normal distribution # Initializing the hidden and visible biases to be zero self.weights = np.random.normal(0.01, 1.0, (self.numV, self.numH)) self.visible_bias = np.zeros((1, self.numV)) self.hidden_bias = np.zeros((1, self.numH)) tic = time.clock() self.data, self.n_evts = self.readTrainData(self.kwargs['train_data']) self.data = self.batchData(self.data, self.batch_size) for epoch in range(self.num_epochs): train_step = 0 for batch in self.data: xacc.info("Train Step {}".format(train_step)) if train_step >= self.train_steps > -1: break # get data expectation values dataExpW, dataExpV, dataExpH = self.getDataExpectations(batch) # set the RBM self.setRBM() training_buffer = self.qpu.createBuffer("buffer") training_buffer.addExtraInfo('embedding', self.embedding) # Execute the RBM with the new parameters self.executeRBM(training_buffer) # Get the expectation values from the D-Wave execution modelExpW, modelExpV, modelExpH = self.getExpectations() # Update the parameters for this batch self.updateParameters(dataExpW, modelExpW, dataExpV, modelExpV, dataExpH, modelExpH) train_step += 1 self.buffer.addExtraInfo("rbm_visible", self.visible_bias.flatten().tolist()) self.buffer.addExtraInfo("rbm_hidden", self.hidden_bias.flatten().tolist()) self.buffer.addExtraInfo("rbm_weights", self.weights.flatten().tolist()) toc = time.clock() training_time = toc - tic if 'test_data' in self.kwargs: self.test_data, self.test_targets, n_tests = self.readTestData( self.kwargs['test_data']) self.test_data = self.batchData(self.test_data, self.batch_size) evals = np.zeros((n_tests, self.num_classes)) truth_vals = np.zeros(n_tests) for digit in range(self.num_classes): w = np.reshape( np.array(self.buffer.getInformation("rbm_weights")), (self.numV, self.numH)) v = np.reshape( np.array(self.buffer.getInformation("rbm_visible")), (1, self.numV)) h = np.reshape( np.array(self.buffer.getInformation("rbm_hidden")), (1, self.numH)) count = 0 for i, batch in enumerate(self.test_data): Fv = self.freeEnergy(batch, w, v, h) targets = np.reshape(self.test_targets[i], (-1, )) ll = list(zip(targets, Fv)) for j, item in enumerate(ll): idx = i * self.batch_size + j evals[idx, digit] = item[1] if digit == 0: truth_vals[idx] = item[0] softmax = np.exp(-evals) / sum(np.exp(-evals)) predictions = np.argmax(softmax, axis=1) accuracy = np.sum(predictions == truth_vals) / len(truth_vals) self.buffer.addExtraInfo('accuracy', str(accuracy)) timestr = time.strftime("%Y%m%d-%H%M%S") self.buffer.addExtraInfo("training-time", training_time) print("Finished Training") print("Accuracy: ", self.buffer.getInformation('accuracy')) print("Training Time: ", self.buffer.getInformation('training-time')) output_name = self.kwargs[ 'output'] + '.ab' if 'output' in self.kwargs else "trained-rbm-buffer-{}.ab".format( timestr) f = open(output_name, "w") f.write(str(self.buffer)) f.close() return
def execute(self, inputParams): """ This method is intended to be inherited by vqe and vqe_energy subclasses to allow algorithm-specific implementation. This superclass method adds extra information to the buffer and allows XACC settings options to be set before executing VQE. Parameters: inputParams : dictionary a dictionary of input parameters obtained from .ini file return QPU Accelerator buffer Options used (obtained from inputParams): 'qubit-map': map of logical qubits to physical qubits 'n-execs': number of sampler executions of measurements 'initial-parameters': list of initial parameters for the VQE algorithm 'restart-from-file': AcceleratorDecorator option to allow restart of VQE algorithm 'readout-error': AcceleratorDecorator option for readout-error mitigation """ self.qpu = xacc.getAccelerator(inputParams['accelerator']) xaccOp = self.hamiltonian_generators[ inputParams['hamiltonian-generator']].generate(inputParams) self.ansatz = self.ansatz_generators[inputParams['name']].generate( inputParams, xaccOp.nQubits()) if 'qubit-map' in inputParams: qubit_map = ast.literal_eval(inputParams['qubit-map']) xaccOp, self.ansatz, n_qubits = xaccvqe.mapToPhysicalQubits( xaccOp, self.ansatz, qubit_map) else: n_qubits = xaccOp.nQubits() self.op = xaccOp self.n_qubits = n_qubits self.buffer = self.qpu.createBuffer('q', n_qubits) self.buffer.addExtraInfo('hamiltonian', str(xaccOp)) self.buffer.addExtraInfo( 'ansatz-qasm', self.ansatz.toString('q').replace('\\n', '\\\\n')) pycompiler = xacc.getCompiler('xacc-py') self.buffer.addExtraInfo( 'ansatz-qasm-py', '\n'.join(pycompiler.translate('q', self.ansatz).split('\n')[1:])) self.optimizer = None self.optimizer_options = {} if 'optimizer' in inputParams: if inputParams['optimizer'] in self.vqe_optimizers: self.optimizer = self.vqe_optimizers[inputParams['optimizer']] if 'method' in inputParams: self.optimizer_options['method'] = inputParams['method'] if 'options' in inputParams: self.optimizer_options['options'] = ast.literal_eval( inputParams['options']) if 'user-params' in inputParams: self.optimizer_options['options'][ 'user_params'] = ast.literal_eval( inputParams['user-params']) else: xacc.setOption('vqe-backend', inputParams['optimizer']) else: xacc.info( "No classical optimizer specified. Setting to default XACC optimizer." ) self.buffer.addExtraInfo('accelerator', inputParams['accelerator']) if 'n-execs' in inputParams: xacc.setOption('sampler-n-execs', inputParams['n-execs']) self.qpu = xacc.getAcceleratorDecorator('improved-sampling', self.qpu) if 'restart-from-file' in inputParams: xacc.setOption('vqe-restart-file', inputParams['restart-from-file']) self.qpu = xacc.getAcceleratorDecorator('vqe-restart', self.qpu) self.qpu.initialize() if 'readout-error' in inputParams and inputParams['readout-error']: self.qpu = xacc.getAcceleratorDecorator('ro-error', self.qpu) if 'rdm-purification' in inputParams and inputParams[ 'rdm-purification']: self.qpu = xacc.getAcceleratorDecorator('rdm-purification', self.qpu) self.vqe_options_dict = { 'accelerator': self.qpu, 'ansatz': self.ansatz } if 'initial-parameters' in inputParams: self.vqe_options_dict['vqe-params'] = ','.join([ str(x) for x in ast.literal_eval(inputParams['initial-parameters']) ]) xacc.setOptions(inputParams)
def install_package(install_name): try: xacc.info("Retrieving package and checking requirements..") package_path = PLUGIN_INSTALLATIONS[install_name] for k, v in MASTER_PACKAGES.items(): if install_name in v and k in REQUIREMENTS: requirement = REQUIREMENTS[k]['module'] mdir = k importlib.import_module(requirement) except KeyError as ex: xacc.info( "There is no '{}' XACC Python plugin package available.".format( install_name)) exit(1) # this might have to change as more packages and their requirements get added # for now, it works fine, and should work fine for any XACC requirement # that needs to be git-cloned and built with cmake-make (vqe) except ModuleNotFoundError as ex: xacc.info( "You do not have the required Python module `{}` to install and run the '{}' XACC benchmark plugin package." .format(requirement, install_name)) yn = input("Install requirements? (y/n) ") if yn == "y": dest = os.path.dirname(inspect.getfile(xacc)) install_path = os.path.join(dest, REQUIREMENTS[mdir]['dir']) build_path = os.path.join(install_path, 'build') os.chdir(dest) subprocess.run([ 'git', 'clone', '--recursive', '{}'.format(REQUIREMENTS[mdir]['repo']) ]) os.makedirs(build_path) os.chdir(build_path) subprocess.run([ 'cmake', '..', '-DXACC_DIR={}'.format(dest), '-DPYTHON_INCLUDE_DIR={}'.format( sysconfig.get_paths()['include']) ]) subprocess.run(['make', '-j2', 'install']) else: exit(1) install_directive = os.path.join(package_path + "/install.ini") if os.path.isfile( package_path + "/install.ini") else None plugin_files = [] if not install_directive: plugin_files += [ package_path + "/" + f for f in os.listdir(package_path) if os.path.isfile(os.path.join(package_path, f)) and f.endswith(".py") ] else: plugin_dict, plugin_list = read_install_directive( install_directive, package_path) for k, v in plugin_dict.items(): mini_package_path = v plugin_files += [ v + "/" + f for f in os.listdir(v) if os.path.isfile(os.path.join(v, f)) and f.endswith(".py") ] n_plugins = len(plugin_files) for plugin in plugin_files: copy(os.path.join(plugin), XACC_PYTHON_PLUGIN_PATH) xacc.info( "Installed {} plugins from the '{}' package to the {} directory.". format(n_plugins, install_name, XACC_PYTHON_PLUGIN_PATH))
def execute(self, buffer, program): from dwave.system.samplers import DWaveSampler from dwave.system.composites import EmbeddingComposite from collections import Counter import dimod h = {} J = {} Q = {} for inst in program.getInstructions(): Q[(inst.bits()[0], inst.bits()[1])] = inst.getParameter(0) if inst.bits()[0] == inst.bits()[1]: h[inst.bits()[0]] = inst.getParameter(0) else: J[(inst.bits()[0], inst.bits()[1])] = inst.getParameter(0) buffer.setSize(max(h.keys()) + 1) if self.use_exact: sampler = dimod.ExactSolver() else: if buffer.hasExtraInfoKey('embedding'): sampler = FixedEmbeddingComposite( DWaveSampler(token=self.token, solver=self.backend), buffer['embedding']) else: sampler = EmbeddingComposite( DWaveSampler(token=self.token, solver=self.backend)) if program.getTag() == "ising": response = sampler.sample_ising(h, J, num_reads=self.shots, return_embedding=True) sampleset = dimod.ExactSolver().sample_ising(h, J) else: response = sampler.sample_qubo(Q, chain_strength=self.chain_strength, num_reads=self.shots) print('executing!') sampleset = dimod.ExactSolver().sample_qubo(Q, return_embedding=True) if not buffer.hasExtraInfoKey('embedding'): # we used embeddingcomposite, get the computed # embedding emb = sampleset.info['embedding_context']['embedding'] print('EMBEDDING WAS ', emb) xacc.info('[Dwave Accelerator] Exact Ground Energy = ' + str( next(sampleset.data(fields=['energy'], name='ExactSolverSample')).energy)) counts_list = [] e_map = {} for r in response.record: sample, energy, nocc, _ = r bitstring = ''.join([str(s) for s in sample]) for i in range(nocc): counts_list.append(bitstring) e_map[bitstring] = energy counts = Counter(counts_list) buffer.setMeasurements(counts) buffer.addExtraInfo('energies', e_map)