from dwave.system import DWaveSampler import dwave.inspector sampler = DWaveSampler(solver='DW_2000Q_6', #token='', ) h = {0: +1} # Hier wählen wir: # 0 = Lauch # 4 = Sellerie # 7 = Erbsen # 3 = Mais J = { (0, 4): -1, (0, 7): +1, (3, 4): +1, (3, 7): -1, } response = sampler.sample_ising( h, J, num_reads=100, ) dwave.inspector.show(response)
class model(): '''Class containing methods to create the networks and train them''' def __init__(self, N, M, L, annealing_time, programming_thermalization, readout_thermalization): self.N = N self.M = M self.L = L self.Vr = np.zeros((M, N)) self.Wr = np.zeros((L, M)) self.Wg = np.zeros((M, L)) self.Vg = np.zeros((N, M)) self.J = np.zeros((L, L)) self.h = np.zeros(L) self.bvr = np.zeros((M, )) self.bwr = np.zeros((L, )) self.bwg = np.zeros((M, )) self.bvg = np.zeros((N, )) self.annealing_time = annealing_time self.programming_thermalization = programming_thermalization self.readout_thermalization = readout_thermalization self.hidden_graph = [] #Adjacency Matrix of the hidden layer for i in range(L): #Creates the abovesaid Adjacency Matrix for j in range(i + 1, L): self.hidden_graph.append((i, j)) self.sampler_manual = DWaveSampler(solver={'qpu': True }) #DWave sampler instance self.embedding = find_embedding( self.hidden_graph, self.sampler_manual.edgelist, random_seed=10) #Calculates and stores heuristic embedding def qsample(self, J, h, n_read): #Returns samples from the quantum device self.hdict = {} self.Jdict = {} # print("Quantum Sampling") for i, hi in enumerate(h): self.hdict[i] = hi #Creates the bias dictionary for i in range(L): for j in range(i + 1, L): self.Jdict[(i, j)] = J[i][ j] #Creates the interaction dictionary from matrix #Embed self.th, self.tJ = dwave.embedding.embed_ising( self.hdict, self.Jdict, self.embedding, self.sampler_manual. adjacency) #Embeds the particular biases/interactions #Sample self.sampleset = self.sampler_manual.sample_ising( self.th, self.tJ, num_reads=n_read, answer_mode='raw', annealing_time=self.annealing_time, programming_thermalization=self.programming_thermalization, readout_thermalization=self.readout_thermalization) #Unembed the data self.bqm = dimod.BinaryQuadraticModel.from_ising( self.hdict, self.Jdict) self.samples = dwave.embedding.unembed_sampleset( self.sampleset, self.embedding, self.bqm) #Convert data into bits from spins and return return (self.samples.record.sample + 1) / 2 def wake(self, data, lr): #Does the wake phase gradient update #Samples the recognition network self.d = data self.y = sample(sig(np.matmul(self.Vr, self.d) + self.bvr)) self.x = sample(sig(np.matmul(self.Wr, self.y) + self.bwr)) #Passes back down through the generative network to find relevant probabilities self.psi = sig(np.matmul(self.Wg, self.x) + self.bwg) self.delta = sig(np.matmul(self.Vg, self.y) + self.bvg) #Computing gradients and updating parameters as mentioned in the report self.J = self.J - lr * np.outer(self.x, self.x) self.h = self.h - lr * self.x self.Wg = self.Wg + lr * np.outer((self.y - self.psi), self.x) self.bwg = self.bwg + lr * (self.y - self.psi) self.Vg = self.Vg + lr * np.outer((self.d - self.delta), self.y) self.bvg = self.bvg + lr * (self.d - self.delta) def sleep(self, lr): #Does the sleep phase gradient update #Samples the generative network self.x = self.qsample(self.J, self.h, 1)[0] self.y = sample(sig(np.matmul(self.Wg, self.x) + self.bwg)) self.d = sig(np.matmul(self.Vg, self.y) + self.bvg) #Passes back through recognition network to compute relevant probabilities self.psi = sig(np.matmul(self.Vr, self.d) + self.bvr) self.eta = sig(np.matmul(self.Wr, self.y) + self.bwr) self.Vr = self.Vr + lr * np.outer((self.y - self.psi), self.d) self.bvr = self.bvr + lr * (self.y - self.psi) self.Wr = self.Wr + lr * np.outer((self.x - self.eta), self.y) self.bwr = self.bwr + lr * (self.x - self.eta) def samplegen(self, N): #Returns N samples of the generative network l = [] self.qsamples = self.qsample(self.J, self.h, N) for i in range(N): self.x = self.qsamples[i] self.y = sample(sig(np.matmul(self.Wg, self.x) + self.bwg)) self.d = sig(np.matmul(self.Vg, self.y) + self.bvg) l.append(self.d) return l def print_params(self): #Prints the values of all the parameters print("N = ", self.N) print("M = ", self.M) print("N = ", self.L) print("Vr = ", self.Vr) print("bvr = ", self.bvr) print("Wr = ", self.Wr) print("bwr = ", self.bwr) print("Wg = ", self.Wg) print("bwg = ", self.bwg) print("Vg = ", self.Vg) print("bvg = ", self.bvg) print("J = ", self.J) print("h = ", self.h) def save_params(self): '''Saves parameters in a pickle file''' Model_save = model_save(Model.N, Model.M, Model.L, Model.J, Model.h, Model.Wg, Model.bwg, Model.Vg, Model.bvg, Model.Wr, Model.bwr, Model.Vr, Model.bvr) with open('model_save_final_final.pickle', 'wb') as f: pickle.dump(Model_save, f) def load_params(self): '''Loads parameters from a pickle file''' with open('model_save_final.pickle', 'rb') as f: Model_load = pickle.load(f) self.N = Model_load.N self.M = Model_load.M self.L = Model_load.L self.Vr = Model_load.Vr self.Wr = Model_load.Wr self.Wg = Model_load.Wg self.Vg = Model_load.Vg self.J = Model_load.J self.h = Model_load.h self.bvr = Model_load.bvr self.bwr = Model_load.bwr self.bwg = Model_load.bwg self.bvg = Model_load.bvg
class BaseChannel(ABC): def __init__(self, params, graph_type="chimera", n_nodes=None, n_edges=None): self.params = params self.graph_type = graph_type device_name = { 'chimera': 'DW_2000Q_6', 'pegasus': 'Advantage_system1.1', 'simulator': None } if graph_type == 'simulator': self.sampler = DWaveSampler(solver={'qpu': False}) else: self.sampler = DWaveSampler(solver={ 'qpu': True, 'name': device_name[graph_type] }) self.list_edges = np.array(self.sampler.edgelist) self.list_nodes = np.array(self.sampler.nodelist) nodes_file = "data/pegasus/list_nodes.npy" edges_file = "data/pegasus/list_edges.npy" if graph_type == 'pegasus': if n_nodes is not None: if os.path.exists(nodes_file): print("Loading list nodes...") self.list_nodes = np.load(nodes_file) else: print("Taking subgraph...") self.list_nodes = take_subgraph(self.sampler, n_nodes) np.save(nodes_file, self.list_nodes) self.graph = self.sampler.to_networkx_graph().subgraph( self.list_nodes) self.list_edges = np.array(self.graph.edges) if n_edges is not None: if os.path.exists(edges_file): print("Loading list edges...") self.list_edges = np.load(edges_file) else: print("Removing edges...") edges_idx = np.sort( np.random.choice(len(self.list_edges), n_edges, replace=False)) self.list_edges = self.list_edges[edges_idx] np.save(edges_file, self.list_edges) print("Number of qubits", len(self.list_nodes)) print("Number of edges", len(self.list_edges)) super().__init__() @abstractmethod def send(self, J_in, h_in): pass @abstractmethod def get_nishimori_temperature(self): pass @abstractmethod def conditional_density(self, y_out, y_in): pass def encode(self, x_in): x_dict = {node: x_in[i] for i, node in enumerate(self.list_nodes)} J = defaultdict(int) for (u, v) in self.list_edges: J[(u, v)] = -x_dict[u] * x_dict[v] h = {node: -x_dict[node] for node in x_dict.keys()} return J, h def decode(self, J_out, h_out, num_reads=1, num_spin_reversals=1): result = self.sampler.sample_ising( h_out, J_out, num_reads=num_reads, num_spin_reversal_transforms=num_spin_reversals) x_dec = np.array(list(list(result.data())[0].sample.values())) return x_dec def get_ber(self, x_in, x_dec): N = len(x_in) return np.sum(np.abs(x_in - x_dec)) / (2 * N)
from dwave.system import DWaveSampler from dwave.system.composites import EmbeddingComposite import dwave.inspector as dwi import numpy as np inner_qubits = [0, 1, 2, 3] outer_qubits = [4, 5, 6, 7] inner_qubits_qpu = [7, 3, 4, 0] outer_qubits_qpu = [15, 131, 12, 128] logical_qubits = inner_qubits + outer_qubits logical_couplers = [(i, (i + 1) % 4) for i in inner_qubits] + list(zip(inner_qubits, outer_qubits)) physical_qubits = inner_qubits_qpu + outer_qubits_qpu physical_couplers = [(physical_qubits[i], physical_qubits[j]) for (i, j) in logical_couplers] # thermal control parameter, 0 < alpha <= 1 alpha = 1 h_list = np.array([1] * len(inner_qubits) + [-1] * len(outer_qubits)).astype(np.float64) h_list *= alpha h = {q: h_list[i] for i, q in enumerate(physical_qubits)} J = {couple: -alpha for couple in physical_couplers} sampler = DWaveSampler(solver=dict(qpu=True)) response = sampler.sample_ising(h, J, num_reads=1000, num_spin_reversal_transforms=0) print(response.aggregate()) dwi.show(response)