lambeq: CircuitNotRunError: Circuit corresponding to ResultHandle('3ab8e99f-729a-47aa-b523-f7f16d58e163', 0, 8, 'null') has not been run by this backend instance.

Hello everybody, I’m trying to explore the lambeq library to deal with a multiclass classification task. Following the guidelines on the documentation, I’ve implemented the following code:

`print(df)

index                                    RequirementText _class_

0 0 system shall interface faculty central server O 1 1 product expected integrate multiple database m… O 2 2 dispute application shall interface merchant i… O 3 3 system shall able operate within business offi… O 4 4 website must fully operational msn tv2 O … … … … 75 216 system shall used realtor training US 76 217 product shall installed untrained realtor with… US 77 218 user need read user manual able use application US 78 219 product shall easy customer novice skill inter… US 79 220 product shall easy use adjuster collision esti… US

[80 rows x 3 columns]`

def create_multi_diagrams(df, reader): diagrams, targets = [], [] for _, row in enumerate(df.to_numpy()): sentence, target = str(row[1]), str(row[2]) try: diagrams.append(reader.sentence2diagram(sentence)) except Exception as e: print(sentence) print(e) continue if target == "US": targets.append([1.0, 0.0, 0.0, 0.0]) elif target == "SE": targets.append([0.0, 1.0, 0.0, 0.0]) elif target == "O": targets.append([0.0, 0.0, 1.0, 0.0]) elif target == "PE": targets.append([0.0, 0.0, 0.0, 1.0]) return diagrams, targets

cups_diagrams, cups_targets = create_multi_diagrams(df, cups_reader)

`def create_circuits(diagrams, targets, ansatz): circuits = [] new_targets = [] i=0 for diagram in diagrams: try: circuits.append(ansatz(diagram)) except Exception as e: print(e) i += 1 continue new_targets.append(targets[i]) i += 1 return circuits, new_targets

ob_map = {AtomicType.SENTENCE:1, AtomicType.NOUN: 1}

iqpansatz = IQPAnsatz(ob_map, n_layers=1, n_single_qubit_params=2)`

cups_iqp_circuits, cups_iqp_targets = create_circuits(cups_diagrams, cups_targets, iqpansatz)

`def accuracy(y_hat, y): y_true = torch.argmax(y, dim=1) y_pred = torch.argmax(y_hat, dim=1) return accuracy_score(y_true, y_pred)

def precision(y_hat, y): y_true = torch.argmax(y, dim=1) y_pred = torch.argmax(y_hat, dim=1) return precision_score(y_true, y_pred, average=‘weighted’, zero_division=1)

def recall(y_hat, y): y_true = torch.argmax(y, dim=1) y_pred = torch.argmax(y_hat, dim=1) return recall_score(y_true, y_pred, average=‘weighted’, zero_division=1)

def f1score(y_hat, y): y_true = torch.argmax(y, dim=1) y_pred = torch.argmax(y_hat, dim=1) return f1_score(y_true, y_pred, average=‘weighted’, zero_division=1)

eval_metrics = {“prec”: precision, “rec”: recall, “acc”: accuracy, “f1”: f1score}`

`from pytket.extensions.qiskit import AerBackend from lambeq import BinaryCrossEntropyLoss

backend = AerBackend() backend_config = { ‘backend’: backend, ‘compilation’: backend.default_compilation_pass(2), ‘shots’: 8192 }

model = TketModel.from_diagrams(cups_iqp_circuits, backend_config=backend_config)

trainer = QuantumTrainer( model, loss_function=BinaryCrossEntropyLoss(), epochs=20, optimizer=NelderMeadOptimizer, optim_hyperparams={‘a’: 0.05, ‘c’: 0.06, ‘A’:0.001*20}, evaluate_functions=eval_metrics, evaluate_on_train=True, verbose = ‘text’, seed=SEED )

X_train_grid, X_val_grid, y_train_grid, y_val_grid = train_test_split(cups_iqp_circuits, cups_iqp_targets, test_size=1/10, random_state=SEED) train_dataset = Dataset(X_train_grid, y_train_grid, batch_size=64) val_dataset = Dataset(X_val_grid, y_val_grid, shuffle=False)

trainer.fit(train_dataset, val_dataset, log_interval = 1)`

Everything works fine, untile on the trainer.fit(train_dataset, val_dataset, log_interval = 1) I get the following error:

`--------------------------------------------------------------------------- CircuitNotRunError Traceback (most recent call last) /usr/local/lib/python3.10/dist-packages/pytket/extensions/qiskit/backends/aer.py in get_result(self, handle, **kwargs) 343 try: –> 344 return super().get_result(handle) 345 except CircuitNotRunError:

14 frames CircuitNotRunError: Circuit corresponding to ResultHandle(‘3ab8e99f-729a-47aa-b523-f7f16d58e163’, 0, 8, ‘null’) has not been run by this backend instance.

During handling of the above exception, another exception occurred:

KeyError Traceback (most recent call last) /usr/local/lib/python3.10/dist-packages/pytket/extensions/qiskit/backends/aer.py in get_result(self, handle, **kwargs) 353 backresults = qiskit_result_to_backendresult(res) 354 for circ_index, backres in enumerate(backresults): –> 355 self._cache[ResultHandle(jobid, circ_index, qubit_n, ppc)][ 356 “result” 357 ] = backres

KeyError: ResultHandle(‘3ab8e99f-729a-47aa-b523-f7f16d58e163’, 1, 8, ‘null’)`

Any suggestion on how to modify the code to make it work?

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 16

Most upvoted comments

Thanks again for your assistance and suggestions! Best of luck, see you next time!

Hi @fcasillo

You can use NumpyModel with JIT (following the instructions here). There’s a note there, though, that it’s not advisable to use JIT for large models, e.g. high qubit count, due to larger memory requirements.

For the other backends, you have to go to their specific docs to see if they enable GPU acceleration. For example, Pennylane has this lightning.gpu device.

Good morning @neiljdo! This version works, even though I had to update the metrics to use numpy. Thank you for your big help! Last question that is unrelated with this issue: I noticed the simulator is somehow slow when it comes to deal with more instances, so there is a way to run it on GPU?

It worked! Thank you so much! I tried again with the AER simulator, but KeyError: ResultHandle('6925cc08-282a-46d1-9f7c-f95166382196', 1, 13, 'null') persists. Any idea on how can I exploit a quantum simulator? I was also planning to try IonQ platform to run the experiments on real quantum hardware, but at least I would to make a simulator work. Maybe I try directly with the one provided by IonQ?

Hi @fcasillo

With the switch to the NumpyModel all the tensor outputs will be of type np.ndarray - you just need to update your metrics to use the equivalent numpy functions instead of torch.

Thank you for your help! So, I tried with NumpyModel and on training the following is the output.


ValueError Traceback (most recent call last) <ipython-input-68-eec6b12fd449> in <cell line: 30>() 28 val_dataset = Dataset(X_val_grid, y_val_grid, shuffle=False) 29 —> 30 trainer.fit(train_dataset, val_dataset, log_interval = 1)

8 frames /usr/local/lib/python3.10/dist-packages/lambeq/training/loss.py in _match_shapes(self, y1, y2) 64 y2: np.ndarray | jnp.ndarray) -> None: 65 if y1.shape != y2.shape: —> 66 raise ValueError(‘Provided arrays must be of equal shape. Got ’ 67 f’arrays of shape {y1.shape} and {y2.shape}.’) 68

ValueError: Provided arrays must be of equal shape. Got arrays of shape (18, 2, 2) and (18, 4).


The first one seems to be the dimensions of the circuits (18 instances and 2,2 the outputs). I tried to set the Atomic.Types.SENTENCE: 4, and the error changes in:


ValueError: Provided arrays must be of equal shape. Got arrays of shape (18, 2, 2, 2, 2) and (18, 4).


As last test I tried to set again Atomic.Types.SENTENCE: 2 but encoded the targets in the following way:

if target == “US”: targets.append([[1.0, 0.0],[0.0, 0.0]]) elif target == “SE”: targets.append([[0.0, 1.0],[0.0, 0.0]]) elif target == “O”: targets.append([[0.0, 0.0],[1.0, 0.0]]) elif target == “PE”: targets.append([[0.0, 0.0],[0.0, 1.0]])

And I got the following error:


TypeError Traceback (most recent call last) <ipython-input-127-eec6b12fd449> in <cell line: 30>() 28 val_dataset = Dataset(X_val_grid, y_val_grid, shuffle=False) 29 —> 30 trainer.fit(train_dataset, val_dataset, log_interval = 1)

3 frames <ipython-input-126-b4a87a1ed3f7> in precision(y_hat, y) 5 6 def precision(y_hat, y): ----> 7 y_true = torch.argmax(y, dim=1) 8 y_pred = torch.argmax(y_hat, dim=1) 9 return precision_score(y_true, y_pred, average=‘weighted’, zero_division=1)

TypeError: argmax(): argument ‘input’ (position 1) must be Tensor, not numpy.ndarray


Am I cursed?