Repository navigation
Add LatentVectorFieldLoss: the reduced vector field against the pushed-forward full one #338
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
Open
benedict-96
wants to merge
5
commits into
main
Choose a base branch
from
add/latent-vector-field-loss
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
3a444d8
Add LatentVectorFieldLoss: reduced against pushed-forward vector field
benedict-96 4412889
LatentVectorFieldLoss: the target is the field the data follow
benedict-96 0fb1201
LatentVectorFieldLoss: keyword reconstruction = false fits the dynami…
benedict-96 fe4ea0d
LatentVectorFieldLoss: keyword energy = true adds the relative energy…
benedict-96 28ff6fd
LatentVectorFieldLoss: warn that reconstruction and dynamics can cont…
benedict-96 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| @doc raw""" | ||
| LatentVectorFieldLoss(arch, hamiltonian; λ = 1, h = 1e-4, reconstruction = true, energy = false) | ||
|
|
||
| Make an instance of `LatentVectorFieldLoss` for an [`AutoEncoder`](@ref) architecture `arch` and a Hamiltonian ``H`` on the full space. | ||
|
|
||
| The loss trains encoder and decoder together on states ``x`` of the full system and on its vector field ``X_H(x) = \mathbb{J}_{2N}\nabla{}H(x)`` there. With ``\xi = \Psi^\mathrm{enc}(x)`` it is | ||
|
|
||
| ```math | ||
| L = \frac{\lVert\Psi^\mathrm{dec}(\xi) - x\rVert}{\lVert x\rVert} | ||
| + \lambda\,\frac{\lVert\mathbb{J}_{2n}\nabla_\xi(H\circ\Psi^\mathrm{dec})(\xi) - \nabla\Psi^\mathrm{enc}(x)X_H(x)\rVert}{\lVert\nabla\Psi^\mathrm{enc}(x)X_H(x)\rVert}, | ||
| ``` | ||
|
|
||
| the reconstruction error plus ``\lambda`` times the error of the *reduced vector field* against the full vector field pushed forward by the encoder, both relative and with the norms taken over the batch. | ||
|
|
||
| !!! warning "Reconstruction and dynamics can contradict each other" | ||
| The reconstruction term asks that ``\Psi^\mathrm{dec}(\Psi^\mathrm{enc}(x)) = x``; the vector-field and energy terms ask that the reduced Hamiltonian system reproduce the full system's trajectories and energies. Where no symplectic chart can do both (for instance where the data contain a separatrix that a single chart cannot reconstruct), a network trained on both must fail one of them, and the loss decides which. All terms are relative errors summed with unit weights (and `λ`), so nothing depends on units; but that is a convention for where the network gives way, not a resolution of the conflict. | ||
|
|
||
| !!! warning "The vector field has to be the one the data follow" | ||
| When the states lie on a submanifold, as the states of a constrained system do, the target is the system's vector field there, which is tangent to it, and not ``\mathbb{J}_{2N}\nabla{}H`` of a Hamiltonian that merely restricts to the right energy on it. The push-forward of a field that leaves the submanifold involves the derivatives of the encoder off the data, which do not describe how encoded trajectories move. The second term compares the two vector fields in the latent space: it vanishes when the encoder maps the trajectories of the full system onto those of the reduced one, which for a symplectic decoder are the level sets of ``H\circ\Psi^\mathrm{dec}``. No target decoder and no latent targets are needed, only states and the full vector field. Where the pushed-forward field vanishes on the whole batch, the absolute error replaces the relative one. | ||
|
|
||
| Both derivatives are central differences with step `h`: ``\nabla_\xi(H\circ\Psi^\mathrm{dec})`` from ``2\cdot2n`` decoder evaluations, and ``\nabla\Psi^\mathrm{enc}(x)X_H(x) \approx (\Psi^\mathrm{enc}(x + hX_H) - \Psi^\mathrm{enc}(x - hX_H))/(2h)`` from two encoder evaluations. This keeps the loss differentiable with respect to the parameters by the same reverse-mode pass as any other loss, without nesting automatic differentiation. | ||
|
|
||
| # Arguments | ||
|
|
||
| - `arch`: the [`AutoEncoder`](@ref) whose network is trained; it fixes where the encoder ends in the chain. | ||
| - `hamiltonian`: a function that maps a matrix of states in ``\mathbb{R}^{2N}``, one per column, to the vector of their energies. It has to be differentiable by Zygote. | ||
| - `λ = 1`: the weight of the vector-field term. | ||
| - `h = 1e-4`: the step of the central differences. | ||
| - `energy = false`: with `true` the loss also has the relative energy error | ||
| ``\lVert H(\Psi^\mathrm{dec}(\xi)) - H(x)\rVert/\lVert H(x)\rVert``: the reduced Hamiltonian | ||
| ``H\circ\Psi^\mathrm{dec}`` has to take the energy of the state it encodes. Unlike the | ||
| reconstruction it does not tie ``\Psi^\mathrm{dec}(\xi)`` to ``x``, and unlike the vector-field | ||
| term it keeps its weight where the vector field vanishes. Together with `reconstruction = false` | ||
| it replaces the reconstruction term. | ||
| - `reconstruction = true`: with `false` the reconstruction term is left out and the loss is the vector-field term alone, ``\lambda`` times its relative error. Only the reduced dynamics are then fitted; nothing ties ``\Psi^\mathrm{dec}(\xi)`` to ``x`` except through ``H\circ\Psi^\mathrm{dec}``. | ||
|
|
||
| # Functor | ||
|
|
||
| ```julia | ||
| loss(model, ps, input, output) | ||
| loss(nn, input, output) | ||
| ``` | ||
|
|
||
| `input` holds the states ``x``, one per column (``2N`` rows), and `output` the vector field ``X_H(x)`` at them (``2N`` rows). The model is the whole autoencoder. | ||
|
|
||
| # Examples | ||
|
|
||
| The loss is zero when the vector-field targets are what the network itself predicts, here for the linear Hamiltonian ``H(x) = c\cdot x`` with a constant vector field: | ||
|
|
||
| ```jldoctest | ||
| using GeometricMachineLearning | ||
| import Random | ||
| Random.seed!(123) | ||
|
|
||
| arch = SymplecticAutoencoder(4, 2; n_encoder_blocks = 2, n_decoder_blocks = 2) | ||
| nn = NeuralNetwork(arch) | ||
| loss = LatentVectorFieldLoss(arch, X -> vec(sum(X; dims = 1))) | ||
| x = randn(4, 10) | ||
| v = ones(4, 10) | ||
| loss(nn, x, v) > 0 | ||
|
|
||
| # output | ||
|
|
||
| true | ||
| ``` | ||
| """ | ||
| struct LatentVectorFieldLoss{N, HT, T} <: NetworkLoss | ||
| hamiltonian::HT | ||
| λ::T | ||
| h::T | ||
| reconstruction::Bool | ||
| energy::Bool | ||
| function LatentVectorFieldLoss{N}(hamiltonian::HT, λ::T, h::T, reconstruction::Bool = true, energy::Bool = false) where {N, HT, T} | ||
| new{N, HT, T}(hamiltonian, λ, h, reconstruction, energy) | ||
| end | ||
| end | ||
|
|
||
| function LatentVectorFieldLoss(arch::AutoEncoder, hamiltonian; λ::Real = 1, h::Real = 1e-4, reconstruction::Bool = true, energy::Bool = false) | ||
| T = float(promote_type(typeof(λ), typeof(h))) | ||
| N = length(encoder_model(arch).layers) | ||
| LatentVectorFieldLoss{N}(hamiltonian, T(λ), T(h), reconstruction, energy) | ||
| end | ||
|
|
||
| n_encoder_layers(::LatentVectorFieldLoss{N}) where {N} = N | ||
|
|
||
| # The relative error, and the absolute one where the target vanishes. | ||
| _relative_vf_error(prediction, target) = (n = norm(target); iszero(n) ? norm(prediction) : norm(prediction - target) / n) | ||
|
|
||
| # The encoder and the decoder of the chain, each with its parameters. | ||
| function _split_autoencoder(loss::LatentVectorFieldLoss{N}, model::Chain, ps) where {N} | ||
| vals = values(ps) | ||
| M = length(model.layers) | ||
| enc = Chain(ntuple(i -> model.layers[i], Val(N))...) | ||
| dec = Chain(ntuple(i -> model.layers[N + i], Val(M - N))...) | ||
| enc, ntuple(i -> vals[i], Val(N)), dec, ntuple(i -> vals[N + i], Val(M - N)) | ||
| end | ||
|
|
||
| # ∇_ξ(H∘Ψ^dec) for each column of ξ, by central differences. | ||
| function _latent_hamiltonian_gradient(loss::LatentVectorFieldLoss, dec, ps_dec, ξ::AbstractMatrix) | ||
| n = size(ξ, 1) | ||
| h = convert(eltype(ξ), loss.h) | ||
| rows = map(1:n) do i | ||
| # the shift is a column broadcast over the batch; built without mutation for Zygote | ||
| δ = map(j -> j == i ? h : zero(h), 1:n) | ||
| Hp = loss.hamiltonian(dec(ξ .+ δ, ps_dec)) | ||
| Hm = loss.hamiltonian(dec(ξ .- δ, ps_dec)) | ||
| reshape((Hp .- Hm) ./ (2h), 1, :) | ||
| end | ||
| reduce(vcat, rows) | ||
| end | ||
|
|
||
| # 𝕁_{2n} g = (g_p, -g_q) for g = (g_q, g_p). | ||
| _poisson_latent(g::AbstractMatrix) = (n = size(g, 1) ÷ 2; vcat(g[(n + 1):end, :], -g[1:n, :])) | ||
|
|
||
| function (loss::LatentVectorFieldLoss)(model::Chain, ps, input::AbstractMatrix, output::AbstractMatrix) | ||
| enc, ps_enc, dec, ps_dec = _split_autoencoder(loss, model, ps) | ||
| h = convert(eltype(input), loss.h) | ||
| ξ = enc(input, ps_enc) | ||
| decoded = dec(ξ, ps_dec) | ||
| reconstruction_error = loss.reconstruction ? _relative_vf_error(decoded, input) : zero(eltype(input)) | ||
| energy_error = loss.energy ? _relative_vf_error(loss.hamiltonian(decoded), loss.hamiltonian(input)) : zero(eltype(input)) | ||
| pushed_forward = (enc(input .+ h .* output, ps_enc) .- enc(input .- h .* output, ps_enc)) ./ (2h) | ||
| reduced = _poisson_latent(_latent_hamiltonian_gradient(loss, dec, ps_dec, ξ)) | ||
| reconstruction_error + energy_error + loss.λ * _relative_vf_error(reduced, pushed_forward) | ||
| end | ||
|
|
||
| # A `DataLoader` built from an input and an output matrix holds them as tensors with a trailing | ||
| # dimension of one; the columns are independent states either way. | ||
| function (loss::LatentVectorFieldLoss)(model::Chain, ps, input::AbstractArray{T, 3}, output::AbstractArray{T, 3}) where {T} | ||
| loss(model, ps, reshape(input, size(input, 1), :), reshape(output, size(output, 1), :)) | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| using GeometricMachineLearning | ||
| using GeometricMachineLearning: params | ||
| using Zygote: Zygote | ||
| using Test | ||
| using LinearAlgebra: norm | ||
| import Random | ||
|
|
||
| Random.seed!(1234) | ||
|
|
||
| H(X) = vec(sum(abs2, X[3:4, :]; dims = 1)) ./ 2 .+ X[2, :] # |p|²/2 + q₂ on ℝ⁴ | ||
| XH(X) = vcat(X[3:4, :], vcat(zeros(1, size(X, 2)), -ones(1, size(X, 2)))) # 𝕁∇H = (p, -∇_q H) | ||
| arch = SymplecticAutoencoder(4, 2; n_encoder_blocks = 2, n_decoder_blocks = 2) | ||
|
|
||
| # The loss agrees with the same expression evaluated with Zygote's derivatives. | ||
| function test_against_autodiff() | ||
| nn = NeuralNetwork(arch) | ||
| enc, dec = encoder(nn), decoder(nn) | ||
| x = randn(4, 30); v = XH(x) | ||
| ξ = enc(x) | ||
| pushed = reduce(hcat, [Zygote.jacobian(enc, x[:, i])[1] * v[:, i] for i in axes(x, 2)]) | ||
| g = reduce(hcat, [Zygote.gradient(ζ -> H(reshape(dec(ζ), 4, 1))[1], ξ[:, i])[1] for i in axes(x, 2)]) | ||
| reduced = vcat(g[2:2, :], -g[1:1, :]) | ||
| expected = norm(dec(ξ) - x) / norm(x) + norm(reduced - pushed) / norm(pushed) | ||
| @test LatentVectorFieldLoss(arch, H)(nn, x, v) ≈ expected rtol = 1e-6 | ||
| end | ||
|
|
||
| # λ weighs the vector-field term only. | ||
| function test_weight() | ||
| nn = NeuralNetwork(arch) | ||
| x = randn(4, 30); v = XH(x) | ||
| rec = LatentVectorFieldLoss(arch, H; λ = 0)(nn, x, v) | ||
| @test LatentVectorFieldLoss(arch, H; λ = 3)(nn, x, v) - rec ≈ 3 * (LatentVectorFieldLoss(arch, H)(nn, x, v) - rec) rtol = 1e-8 | ||
| end | ||
|
|
||
| # Reverse mode through the loss gives a finite gradient for encoder and decoder parameters. | ||
| function test_differentiable() | ||
| nn = NeuralNetwork(arch) | ||
| x = randn(4, 30); v = XH(x) | ||
| loss = LatentVectorFieldLoss(arch, H) | ||
| dp = Zygote.gradient(ps -> loss(nn.model, ps, x, v), params(nn))[1] | ||
| @test dp !== nothing | ||
| end | ||
|
|
||
| # Training with the optimizer reduces the loss. | ||
| function test_training() | ||
| Random.seed!(2026) | ||
| nn = NeuralNetwork(arch) | ||
| x = randn(4, 200); v = XH(x) | ||
| loss = LatentVectorFieldLoss(arch, H) | ||
| before = loss(nn, x, v) | ||
| o = Optimizer(Adam(), nn) | ||
| o(nn, DataLoader(x, v; suppress_info = true), Batch(50), 200, loss; show_progress = false) | ||
| @test loss(nn, x, v) < before / 2 | ||
| end | ||
|
|
||
| # Without the reconstruction term the loss is the vector-field term alone. | ||
| function test_without_reconstruction() | ||
| nn = NeuralNetwork(arch) | ||
| x = randn(4, 30); v = XH(x) | ||
| rec = LatentVectorFieldLoss(arch, H; λ = 0)(nn, x, v) | ||
| @test LatentVectorFieldLoss(arch, H; reconstruction = false)(nn, x, v) ≈ LatentVectorFieldLoss(arch, H)(nn, x, v) - rec rtol = 1e-10 | ||
| end | ||
|
|
||
| # The energy term is the relative error of H∘Ψ^dec∘Ψ^enc against H. | ||
| function test_energy() | ||
| nn = NeuralNetwork(arch) | ||
| x = randn(4, 30); v = XH(x) | ||
| vf = LatentVectorFieldLoss(arch, H; reconstruction = false)(nn, x, v) | ||
| Hd = H(decoder(nn)(encoder(nn)(x))) | ||
| @test LatentVectorFieldLoss(arch, H; reconstruction = false, energy = true)(nn, x, v) ≈ vf + norm(Hd - H(x)) / norm(H(x)) rtol = 1e-8 | ||
| end | ||
|
|
||
| test_against_autodiff() | ||
| test_without_reconstruction() | ||
| test_energy() | ||
| test_weight() | ||
| test_differentiable() | ||
| test_training() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: JuliaGNI/GeometricMachineLearning.jl
Length of output: 5152
🏁 Script executed:
Repository: JuliaGNI/GeometricMachineLearning.jl
Length of output: 10549
🏁 Script executed:
Repository: JuliaGNI/GeometricMachineLearning.jl
Length of output: 8010
🏁 Script executed:
Repository: JuliaGNI/GeometricMachineLearning.jl
Length of output: 25749
🏁 Script executed:
Repository: JuliaGNI/GeometricMachineLearning.jl
Length of output: 10769
🏁 Script executed:
Repository: JuliaGNI/GeometricMachineLearning.jl
Length of output: 4678
Check each parameter group for finite gradients.
dp !== nothingchecks only the outer gradient.LatentVectorFieldLosssplits the parameters into encoder and decoder groups. The optimizer skips a group whose gradient isnothing, so the 200-step loss reduction does not establish that both groups receive finite gradients.Suggested fix
🤖 Prompt for AI Agents