Yao.jl icon indicating copy to clipboard operation
Yao.jl copied to clipboard

The inplace dispatch! function works incorrectly (inconsistently with dispatch) for some circuits

Open dandanua opened this issue 7 months ago • 0 comments

Hello!

The inplace dispatch! function works incorrectly (inconsistently with dispatch) for some circuits. Here is the minimal mwe:

using Yao
using LinearAlgebra

function sample_circ(nbit, nlayer)
    circuit = chain(nbit)
    push!(circuit, chain(put(i=>Ry(0.0)) for i in 1:nbit))
	layer = chain(
		chain(cnot(i,i+1) for i in 1:2:nbit-1),
		chain(put(i=>Ry(0.0)) for i in 1:nbit-1),
		chain(cnot(i,i+1) for i in 2:2:nbit-1),
		chain(put(i=>Rz(0.0)) for i in 2:nbit),
		chain(cnot(i,i+1) for i in 1:2:nbit-1),
		chain(put(i=>Rx(0.0)) for i in 1:nbit-1),
		chain(cnot(i,i+1) for i in 2:2:nbit-1),
		chain(put(i=>Ry(0.0)) for i in 2:nbit),
		chain(cnot(i,i+1) for i in 1:2:nbit-1),
		chain(put(i=>Rz(0.0)) for i in 1:nbit-1),
		chain(cnot(i,i+1) for i in 2:2:nbit-1),
		chain(put(i=>Rx(0.0)) for i in 2:nbit),
	)
    for k in 1:nlayer
		push!(circuit, layer)
    end
    return circuit
end

function circuit_param_correct(p, nlayer)
    circuit = sample_circ(12, nlayer)
    ret = dispatch(circuit, p)

    return ret
end

function circuit_param_wrong(p, nlayer)
    circuit = sample_circ(12, nlayer)
    dispatch!(circuit, p)

    return circuit
end

function test(nlayer)
    p = rand(nparameters(sample_circ(12, nlayer)))

    c_cor = circuit_param_correct(p, nlayer)
    c_wro = circuit_param_wrong(p, nlayer)

    # @show parameters(c_cor)
    # @show parameters(c_wro)

    return parameters(c_cor)-parameters(c_wro) |> norm
end

test(1) with one layer works ok and returns 0. test(2) returns non-zero value. I've noticed that in the wrongly dispatched circuit both layers have the same parameters. I guess the inplace version dispatches the first layer and then simply copies the block with dispatched parameters.

dandanua avatar Aug 20 '25 10:08 dandanua