Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reimplement Product on top of #223 #231

Merged
merged 19 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ext/TenetAdaptExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ Adapt.adapt_structure(to, x::TensorNetwork) = TensorNetwork(adapt.(Ref(to), tens

Adapt.adapt_structure(to, x::Quantum) = Quantum(adapt(to, TensorNetwork(x)), x.sites)
Adapt.adapt_structure(to, x::Ansatz) = Ansatz(adapt(to, Quantum(x)), Tenet.lattice(x))
Adapt.adapt_structure(to, x::Product) = Product(adapt(to, Ansatz(x)))

end
3 changes: 3 additions & 0 deletions ext/TenetChainRulesCoreExt/frules.jl
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ function ChainRulesCore.frule((_, ẋ), ::Type{Ansatz}, x::Quantum, lattice)
return Ansatz(x, lattice), Tangent{Ansatz}(; tn=ẋ, lattice=NoTangent())
end

# `AbstractAnsatz`-subtype constructors
ChainRulesCore.frule((_, ẋ), ::Type{Product}, x::Ansatz) = Product(x), Tangent{Product}(; tn=ẋ)

# `Base.conj` methods
ChainRulesCore.frule((_, Δ), ::typeof(Base.conj), tn::Tensor) = conj(tn), conj(Δ)

Expand Down
5 changes: 5 additions & 0 deletions ext/TenetChainRulesCoreExt/rrules.jl
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ Ansatz_pullback(ȳ) = (NoTangent(), ȳ.tn, NoTangent())
Ansatz_pullback(ȳ::AbstractThunk) = Ansatz_pullback(unthunk(ȳ))
ChainRulesCore.rrule(::Type{Ansatz}, x::Quantum, lattice) = Ansatz(x, lattice), Ansatz_pullback

# `AbstractAnsatz`-subtype constructors
Product_pullback(ȳ) = (NoTangent(), ȳ.tn)
Product_pullback(ȳ::AbstractThunk) = Product_pullback(unthunk(ȳ))
ChainRulesCore.rrule(::Type{Product}, x::Ansatz) = Product(x), Product_pullback

# `Base.conj` methods
conj_pullback(Δ::Tensor) = (NoTangent(), conj(Δ))
conj_pullback(Δ::Tangent{Tensor}) = (NoTangent(), conj(Δ))
Expand Down
12 changes: 12 additions & 0 deletions ext/TenetReactantExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ function Reactant.make_tracer(seen, prev::Ansatz, path::Tuple, mode::Reactant.Tr
return Ansatz(tracetn, copy(Tenet.lattice(prev)))
end

# TODO try rely on generic fallback for ansatzes
function Reactant.make_tracer(seen, prev::Tenet.Product, path::Tuple, mode::Reactant.TraceMode; kwargs...)
tracetn = Reactant.make_tracer(seen, Ansatz(prev), Reactant.append_path(path, :tn), mode; kwargs...)
return Tenet.Product(tracetn)
end

function Reactant.create_result(@nospecialize(tocopy::Tensor), @nospecialize(path), result_stores)
data = Reactant.create_result(parent(tocopy), Reactant.append_path(path, :data), result_stores)
return :($Tensor($data, $(inds(tocopy))))
Expand All @@ -58,6 +64,12 @@ function Reactant.create_result(tocopy::Ansatz, @nospecialize(path), result_stor
return :($Ansatz($tn, $(copy(Tenet.lattice(tocopy)))))
end

# TODO try rely on generic fallback for ansatzes
function Reactant.create_result(tocopy::Tenet.Product, @nospecialize(path), result_stores)
tn = Reactant.create_result(Ansatz(tocopy), Reactant.append_path(path, :tn), result_stores)
return :($(Tenet.Product)($tn))
end

# TODO try rely on generic fallback for ansatzes
# function Reactant.create_result(tocopy::Tenet.Product, @nospecialize(path), result_stores)
# tn = Reactant.create_result(Ansatz(tocopy), Reactant.append_path(path, :tn), result_stores)
Expand Down
95 changes: 95 additions & 0 deletions src/Product.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
using LinearAlgebra
using Graphs

"""
Product <: AbstractAnsatz

An [`Ansatz`](@ref) represented as a tensor product.

# Constructors

If you pass an `Abstract{<:AbstractVector}` to the constructor, it will create a [`State`](@ref).
If you pass an `Abstract{<:AbstractMatrix}` to the constructor, it will create an [`Operator`](@ref).
"""
struct Product <: AbstractAnsatz
tn::Ansatz
end

Ansatz(tn::Product) = tn.tn

Base.copy(x::Product) = Product(copy(Ansatz(x)))
Base.similar(x::Product) = Product(similar(Ansatz(x)))
Base.zero(x::Product) = Product(zero(Ansatz(x)))

function Product(arrays::AbstractArray{<:AbstractVector})
mofeing marked this conversation as resolved.
Show resolved Hide resolved
n = length(arrays)
gen = IndexCounter()
symbols = map(arrays) do _
nextindex!(gen)
end
_tensors = map(eachindex(arrays)) do i
Tensor(arrays[i], [symbols[i]])
end

sitemap = Dict(Site(i) => symbols[i] for i in eachindex(arrays))
qtn = Quantum(TensorNetwork(_tensors), sitemap)
graph = Graph(n)
mapping = BijectiveIdDict{Site,Int}(Pair{Site,Int}[site => i for (i, site) in enumerate(lanes(qtn))])
lattice = Lattice(mapping, graph)
ansatz = Ansatz(qtn, lattice)
return Product(ansatz)
end

function Product(arrays::AbstractArray{<:AbstractMatrix})
mofeing marked this conversation as resolved.
Show resolved Hide resolved
n = length(arrays)
gen = IndexCounter()
symbols = map(arrays) do _
(nextindex!(gen), nextindex!(gen))
end
_tensors = map(eachindex(arrays)) do i
Tensor(arrays[i], [symbols[i][1], symbols[i][2]])
end

sitemap = merge!(
Dict(Site(i; dual=true) => symbols[i][1] for i in eachindex(arrays)),
Dict(Site(i) => symbols[i][2] for i in eachindex(arrays)),
)
qtn = Quantum(TensorNetwork(_tensors), sitemap)
graph = Graph(n)
mapping = BijectiveIdDict{Site,Int}(Pair{Site,Int}[site => i for (i, site) in enumerate(lanes(qtn))])
lattice = Lattice(mapping, graph)
ansatz = Ansatz(qtn, lattice)
return Product(ansatz)
end

LinearAlgebra.norm(tn::Product, p::Real=2) = LinearAlgebra.norm(socket(tn), tn, p)
mofeing marked this conversation as resolved.
Show resolved Hide resolved
function LinearAlgebra.norm(::Union{State,Operator}, tn::Product, p::Real)
return mapreduce(*, tensors(tn)) do tensor
norm(tensor, p)
end^(1//p)
end

LinearAlgebra.opnorm(tn::Product, p::Real=2) = LinearAlgebra.opnorm(socket(tn), tn, p)
mofeing marked this conversation as resolved.
Show resolved Hide resolved
function LinearAlgebra.opnorm(::Operator, tn::Product, p::Real)
return mapreduce(*, tensors(tn)) do tensor
opnorm(parent(tensor), p)
end^(1//p)
end

LinearAlgebra.normalize!(tn::Product, p::Real=2) = LinearAlgebra.normalize!(socket(tn), tn, p)
mofeing marked this conversation as resolved.
Show resolved Hide resolved
function LinearAlgebra.normalize!(::Union{State,Operator}, tn::Product, p::Real)
for tensor in tensors(tn)
normalize!(tensor, p)
end
return tn
end

overlap(a::Product, b::Product) = overlap(socket(a), a, socket(b), b)
mofeing marked this conversation as resolved.
Show resolved Hide resolved

function overlap(::State, a::Product, ::State, b::Product)
@assert issetequal(sites(a), sites(b)) "Ansatzes must have the same sites"

mapreduce(*, zip(tensors(a), tensors(b))) do (ta, tb)
dot(parent(ta), conj(parent(tb)))
end
end
3 changes: 3 additions & 0 deletions src/Tenet.jl
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ export form
export canonize_site, canonize_site!, canonize, canonize!, mixed_canonize, mixed_canonize!, truncate!
export evolve!, expect, overlap

include("Product.jl")
export Product

# reexports from EinExprs
export einexpr, inds

Expand Down
7 changes: 3 additions & 4 deletions test/Product_test.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
@testset_skip "Product ansatz" begin
@testset "Product ansatz" begin
using LinearAlgebra
mofeing marked this conversation as resolved.
Show resolved Hide resolved

# TODO test `Product` with `Scalar` socket
Expand All @@ -14,9 +14,7 @@
end
@test adjoint(qtn) isa Product
@test socket(adjoint(qtn)) == State(; dual=true)

# conversion to `Quantum`
@test Quantum(qtn) isa Quantum
@test Ansatz(qtn) isa Ansatz

qtn = Product([rand(2, 2) for _ in 1:3])
@test socket(qtn) == Operator()
Expand All @@ -30,4 +28,5 @@
end
@test adjoint(qtn) isa Product
@test socket(adjoint(qtn)) == Operator()
@test Ansatz(qtn) isa Ansatz
end
6 changes: 6 additions & 0 deletions test/integration/ChainRules_test.jl
Original file line number Diff line number Diff line change
Expand Up @@ -199,4 +199,10 @@
test_frule(Ansatz, tn, lattice)
test_rrule(Ansatz, tn, lattice)
end

@testset "Product" begin
tn = Product([ones(2), ones(2), ones(2)])
test_frule(Product, Ansatz(tn))
test_rrule(Product, Ansatz(tn))
end
end
Loading