How to implement shot allocation methods for VQA


I am trying to implement a new method for shot allocation:
The main idea is to be able to gain N samples from a given circuit, then I want to perform some calculations and based on the results decide if I need more shots or not. What is the best way to implement this?

I tried implementing an objective function that uses a circuit with qml.counts:

 def my_objective_function(params):
        sample_circuit = sample_circuit_wrapper(dev_shots)
        sum_samples = {}
        X_hist = []
        while np.sum(X_hist) < 10000: # shots count
            samples = sample_circuit(params)
            sum_samples = add_samples(sum_samples, samples)
            X_hist = np.asarray(list(sum_samples.values()))
            energy = MyEnergyEstimation(X_hist, hamiltonian)
            print(f'X_hist: {X_hist}')
            if enough_shots(X_hist, epsilon=epsilon):
        return energy

I use this objective function with a GradientDescentOptimizer which put this whole function under an autograd and the autograd.tracer doesn’t like the operations I do on the samples, I get this error:

TypeError: Can't differentiate w.r.t. type <class 'numpy.int64'>

Hi @yokkon, welcome to the forum!

Unfortunately samples returns stochastic results so it’s non-differentiable. Something you could try is using qml.expval and setting shots=1. This will be basically equivalent.
I hope this helps you!