QuantumBFS / YaoBlocks.jl

Standard basic quantum circuit simulator building blocks. (archived, for it is moved to Yao.jl)
Apache License 2.0
26 stars 11 forks source link

return the expectation and its gridient in the same function exp' #140

Closed ywlds closed 4 years ago

ywlds commented 4 years ago

can we put the function exp' in YaoBlocks/src/autodiff/specializes.jl to support return the expection and its gridients? I try this by adding the energy = copy(outδ)'*copy(out), but I feel the parameters or energy dose not change in the iteration. Is there is something wrong due to the parameters is changed somehow? iteration and Loss function energy is : 1 -6.783714426018552 + 0.0im iteration and Loss function energy is : 2 -6.783714426018552 + 0.0im iteration and Loss function energy is : 3 -6.783714426018552 + 0.0im iteration and Loss function energy is : 4 -6.783714426018552 + 0.0im iteration and Loss function energy is : 5 -6.783714426018552 + 0.0im iteration and Loss function energy is : 6 -6.783714426018552 + 0.0im iteration and Loss function energy is : 7 -6.783714426018552 + 0.0im iteration and Loss function energy is : 8 -6.783714426018552 + 0.0im iteration and Loss function energy is : 9 -6.783714426018552 + 0.0im iteration and Loss function energy is : 10 -6.783714426018552 + 0.0im iteration and Loss function energy is : 11 -6.783714426018552 + 0.0im iteration and Loss function energy is : 12 -6.783714426018552 + 0.0im

I use the optimizier lbfgs. previously before I change the function expect' seems everything ok.

function lbfgs_optimize(circuit::AbstractBlock{N}, hc, niter::Int) where N iteration = 0 function f(params, grad)

reg = zero_state(N) |> dispatch!(circuit, params)

    _, grad1 =  expect'(hc,zero_state(N)=>circuit)
    print("grad1 is ",grad1)
    for i= 1: length(grad1)
        grad[i] = grad1[i]
    end
    loss = expect(hc, reg) |> real
    println("Loss function is", loss)
    iteration += 1
    loss
end
opt = Opt(:LD_LBFGS, nparameters(circuit))
min_objective!(opt, f)
maxeval!(opt, niter)

print("here is ok")

ftol_rel!(opt,1e-7) # default this value

cost, params, info = optimize(opt, parameters(circuit))

pl = zero_state(N) |> circuit |> probs

print("info is", info)

print("iteration time is ", iteration)

cost, params, info, iteration

end

This is the origin expect' function(except the comment)

function (::Adjoint{Any,typeof(expect)})(op::AbstractBlock, circuit::Pair{<:ArrayReg,<:AbstractBlock}) reg, c = circuit

println("try to modify")

out = copy(reg) |> c
outδ = copy(out) |> op

energy = copy(outδ)'*copy(out)

#println("energy is ", energy)
(in, inδ), paramsδ = apply_back((out, outδ), c)
return inδ => paramsδ .* 2

end

ywlds commented 4 years ago

I think i found the mistakes, there, the function just need to update the parameters, using dispatch!(circuit, params) then it works.