Repository navigation
Symbolic differentiation of scalar/tensor expressions, with series substitution and Hartree-Fock derivatives - #812
zhihao-deng wants to merge 25 commits into
Conversation
|
I reviewed this at Pushed
Verified locally with Apple Clang: 2863 assertions in Debug, 7933 in Release (long mode). All deriv test files pass a GCC 15 Left for the author
|
|
I pushed five commits on top of 971ef27 (head now db2a860). They add what analytic CCSD(T)/F12 gradients need from Additions
Fixes found in review
Tests and docs
|
ajay-mk
left a comment
There was a problem hiding this comment.
General comment: several names here are not self-explanatory: judge, family, own-equations, spelling. Could they say what they check, e.g. numerical_check, cc_variants?
| run: | | ||
| valgrind --error-exitcode=1 --leak-check=full ./tests/unit/unit_tests-sequant '~[valgrind_skip]' | ||
| # the rule and series tests of SeQuant-deriv; its identity and finite-difference tests take too long here | ||
| valgrind --error-exitcode=1 --leak-check=full ./tests/unit/deriv/unit_tests-sequant-deriv '[rules],[series]~deriv/series/cc-lagrangian' |
There was a problem hiding this comment.
Do these tests need their own executable? They could go into unit_tests-sequant as a unit_tests-sequant-deriv-obj, like the other modules. Then the slow tests could be tagged [valgrind_skip], and this extra CI line would not be needed.
There was a problem hiding this comment.
The slow tests should use the existing SKIP_LONG_TEST macro mechanism, unless they are fine in Debug build and only problematic for Valgrind
| mbpt::CC cc{2}; | ||
| auto L = mbpt::op::ref_av((1 + mbpt::op::Λ(2)) * cc.hbar(), | ||
| {.connect = cc.hbar_connections()}); | ||
| simplify(L); |
There was a problem hiding this comment.
This simplify call is probably not needed. ref_av should return a simplified version.
| } | ||
|
|
||
| { | ||
| // start-snippet-2 |
There was a problem hiding this comment.
For the ease of reading (since this is part of documentation), I suggest the following pattern for this snippet and elsewhere:
const auto t1 = deserialize(L"t{a_2;i_2}:N-N-N");
const auto expr1 = deserialize(L"f{i_1;a_1}:N-N-N t{a_1;i_1}:N-N-N");
const auto result1 = deserialize(L"f{i_2;a_2}:N-N-N");
require_equivalent(diff(expr1, {t1}), result1);
| auto registry = mbpt::make_min_sr_spaces(); | ||
| std::vector<std::wstring> keys; | ||
| for (const auto& space : *registry) keys.push_back(space.base_key()); | ||
| for (const auto& key : keys) | ||
| if (!key.empty()) registry->field(key, Field::Real); |
There was a problem hiding this comment.
Nit: not necessarily part of this PR, but logic for setting field is a repeating pattern in tests and example. We should introduce a helper or utility function.
| /// Symmetrizers are never expanded: those of @p E stay factors, and that of | ||
| /// x is put on the result as a factor. | ||
| /// @throw Exception for a null argument and for an input that is rejected | ||
| [[nodiscard]] ExprPtr diff(const ExprPtr& E, |
There was a problem hiding this comment.
I think calling this diff is okay and I know that sympy also uses diff. But there is also vimdiff, git diff etc which usually means difference.
There was a problem hiding this comment.
We also have exprdiff in SeQuant so calling this diff is kinda confusing (given that an actual diff utility exists as well)
| /// @p order above 9, an mbpt::Operator or a Variable labelled @p label in | ||
| /// @p expr , a leaf of @p label under a TensorPower, or a tensor in @p expr | ||
| /// labelled like a coefficient p⁽ᵏ⁾ (or its adjoint), 1 ≤ k ≤ @p order | ||
| [[nodiscard]] ExprPtr series(const ExprPtr& expr, std::wstring_view label, |
There was a problem hiding this comment.
Should we call this taylor_series? Just series is a bit ambiguous?
There was a problem hiding this comment.
I also like taylor_series more than just plain series. In mathematical literature, the act of approximating something as a Taylor series is often referred to as expanding (as a series) but that is even more ambiguous in the context of SeQuant. Maybe taylor_expansion?
| Note that "core" is both the source directory (`SeQuant/core/`, which feeds | ||
| `symb`, `eval`, `optimize` and `export`) and the small umbrella target. Backend | ||
| `symb`, `deriv`, `eval`, `optimize` and `export`) and the small umbrella | ||
| target, which links all of those but `deriv`. Backend |
There was a problem hiding this comment.
What is the rationale behind keeping deriv out of core? deriv depends only on SeQuant-symb and it could even be part of SeQuant-symb. That would also drop this exception, the extra CMake and config entries.
| } | ||
|
|
||
| { | ||
| // start-snippet-7 |
There was a problem hiding this comment.
Nit: This should be moved down in the file or renumbered.
| symbolic form. Both are declared in ``SeQuant/core/deriv/deriv.hpp`` and built as the CMake target ``SeQuant::deriv``, | ||
| which ``SeQuant::SeQuant`` links (``SeQuant::core`` does not). |
| derivative of any order. A variable is a scalar :class:`sequant::Variable` or a single tensor, a *leaf* of the | ||
| expression tree: one :class:`sequant::Tensor`, not a product or a sum, and neither a symmetrizer nor a Kronecker delta. |
There was a problem hiding this comment.
How is a leaf in the expression tree different from the requirement of being a Variable or a Tensor? Just naming these two seems exhaustive together with the exception of symmetrizers and Kronecker deltas.
| For a tensor variable, that factor is an occurrence of it (defined below), whatever its index names, that lies inside | ||
| the variable: in a spelling of the variable that it matches, each of its slots runs within the index space of the | ||
| spelling's slot. A leaf that holds elements of the variable and elements outside it, such as ``k{p_1;i_1}`` for the | ||
| variable ``k{a_2;i_2}``, would be neither zero nor unchanged, and is rejected. With several variables, a leaf must lie | ||
| inside one of them: ``k{p_1;i_1}`` is rejected for the variables ``k{m_2;i_2}`` and ``k{e_3;i_3}`` together, although | ||
| together they hold all of its elements. |
There was a problem hiding this comment.
I don't understand what this paragraph is describing 👀
| A scalar variable is complex: ``x`` and its adjoint ``x^*`` (:func:`sequant::adjoint`) are independent variables, so | ||
| the derivative by ``x`` treats ``x^*`` as a constant. |
There was a problem hiding this comment.
What about complex-conjugate tensors?
The docs should mention that the presence of a quantity and its complex-conjugate in the same expression makes the expression non-holomorphic and that what we are computing are so-called Wirtinger derivatives.
| In a term of ``E`` (a product of factors), an index is *summed* if it stands in exactly two slots of the term's | ||
| factors, not counting the symmetrizers ``Â`` and ``Ŝ``; every other index of the term is *external*, including one |
There was a problem hiding this comment.
We should not use this definition. This does not hold in general (think of THC expressions). Named/External indices must be given explicitly. Probably the easiest way to enforce this would be to restrict these functions to work on ResultExpr objects only.
| ``diff`` takes the dependence on a variable from ``E`` as written. To differentiate with respect to the strength | ||
| :math:`\varepsilon` of a perturbation, write every quantity that depends on it as its series in :math:`\varepsilon`, | ||
| differentiate, and set :math:`\varepsilon = 0` with ``at_zero``. The :math:`n`-th derivative at zero is :math:`n!` | ||
| times the coefficient of :math:`\varepsilon^n`. The example writes the series by hand; ``mbpt::series`` writes it for |
There was a problem hiding this comment.
Why does series live in mbpt? It seems a to perform a contex-independent (purely mathematical) series expansion.
| kinds: | ||
|
|
||
| - **What a variable is.** A variable is a ``Variable`` or a single tensor leaf, not a symmetrizer or a Kronecker delta, | ||
| and a tensor variable puts each index in one slot only. |
There was a problem hiding this comment.
Why is that required? Wouldn't the machinery also work if I were to take the derivative w.r.t. a matrix's diagonal?
There was a problem hiding this comment.
I think it would be good if we found a different term than variable for the thing we perform the derivative with. I find this rather confusing with the Variable type.
|
|
||
| How ``diff`` computes the result is described in :doc:`the developer guide </developer/differentiation>`. | ||
|
|
||
| Series substitution |
There was a problem hiding this comment.
This could/should be its independent documentation as it seems useful in its own right. Maybe the same applies to the at_zero function 🤔
| build_test_as_needed(unit_tests-sequant "sequant/unit" TEST_NAMES) | ||
| endif() | ||
|
|
||
| # symbolic differentiation (SeQuant-deriv) has its own executable |
A new library, SeQuant::deriv, on top of SeQuant-symb. deriv::diff(E, variables) differentiates an explicit expression by each variable in turn; this commit handles a scalar Variable (x and x^* are independent). The result is cleaned up with rapid_simplify, not simplify: simplify renames or reorders the indices a symmetrizer carries, and in a derivative those are free indices.
A derivative can be written in many equivalent ways, so the tests do not rely on its text alone. The judge gives every tensor random data with exactly its declared symmetry and compares the result, element by element, with the exact change of the function when one element of the variable is raised. It shares no code with the engine, and its own tests show that each of its checks can fail.
The variable may now be a tensor leaf, read here as an array without symmetry. The derivative of a leaf by the variable is a Kronecker delta for every label the two pair, never an overlap: a derivative pairs a coordinate with itself, whatever the basis. A protoindex labels the element just as a slot index does, so it is paired as well. Where the leaf's label is summed the delta is contracted away by renaming; an external label keeps its delta. All pairing of a leaf's indices with the variable's is in one function, elementary().
A symmetric variable has fewer independent elements than positions, so the derivative by an independent element is the positional gradient summed over the variable's symmetry operations. Differentiation commutes with that sum: for slots that are alike it is SeQuant's  or Ŝ, put on the result as one factor and never expanded.  and Ŝ are normalized, hence the factor counting the permutations. With this convention the derivative of a coupled-cluster Lagrangian by a multiplier is SeQuant's amplitude equation with no extra constant.
A symmetrizer only permutes slots that are alike. The variable's other operations (permuting slots over different spaces, exchanging bra and ket) write its indices in another slot order, a spelling. A tensor of the function over a larger space holds the variable's elements in several of these orders: with a bra-ket symmetric h, sum_pq G_qp h_pq holds h_ia both as h_pq and as h_qp, so its derivative by h_ia is G_ai + G_ia. The derivative is therefore summed over the spellings, each with its sign. Leaves are compared as written, not brought to a canonical slot order first: canonicalizing a bra-ket symmetric leaf exchanges its bra and ket, which the symmetrizer on the result would not follow. Over real spaces a variable and its adjoint hold the same elements, so the adjoint's spellings are included; over complex spaces x and x^+ stay independent.
An input the rule cannot differentiate correctly is refused before any derivative is taken, with a fixed message, rather than detected case by case afterwards. The rejections are of four kinds: the variable is not a well-formed Variable or tensor leaf; its symmetry is one a symmetrizer over like slots cannot express; protoindex lists of the variable or of one of its leaves do not identify an element unambiguously; the function is not a valid expression, holds operators, or holds the variable where the rule does not reach (under a TensorPower, or with a protoindex label that is not summed).
at_zero(E, variables) drops the terms that hold a listed variable: a derivative is usually wanted at a reference point, such as zero perturbation strength. A leaf that holds elements both inside and outside a tensor variable's block is neither zero nor unchanged, so it is rejected.
The rule tests pin chosen inputs. These tests run diff over the equations SeQuant generates for coupled-cluster singles and doubles (spin-orbital, closed-shell and open-shell; canonical and CSV) and check identities every correct derivative satisfies: the numerical definition, the Taylor expansion, the equality of mixed partials, and that the derivatives of the Lagrangian are SeQuant's own amplitude and λ equations. The numbers of checked and of rejected variables are pinned, so a loss of coverage fails.
A user guide page for deriv::diff and deriv::at_zero and a developer page on how the engine works. The code samples come from an example that is compiled and run with the tests.
mbpt::series replaces every leaf of a label (or its adjoint) by its Taylor series in a scalar or tensor strength, the coefficients labelled by order. Core replace is not used: it matches leaves of one block of spaces only and puts an index the replacement adds (a perturbation index) unchanged into every match, so two perturbed leaves of one term would share it.
mbpt::hf::rotated_energy(order) is <0|e^(-κ) H e^(κ)|0> through the given order in the rotation κ = K - K⁺, K exciting every reference-occupied orbital into its complement; its derivatives are the orbital gradient and Hessian. K is labelled κₒ because κ is core's cumulant label. H is normal ordered, so the reference energy is not part of the result.
…rmalized orbitals hf::energy writes the energy under an orbital rotation in h and g; hf::orthonormalized expands h and g in symmetrically orthonormalized orbitals as a series in a perturbation strength. In those orbitals the operators, and so the form of the energy, stay the same at every geometry: all dependence on the perturbation is in the integrals.
…ences The second-order forms are too long to write by hand. The reference is the exact energy of a small model built from the evaluator's own data, differenced in the perturbation strength and in the orbital rotation; no Hartree-Fock equation is solved and no term is assumed zero.
The user guide gains mbpt::series and the Hartree-Fock orbital gradient and Hessian, nuclear gradient and response equation as worked uses of diff and at_zero, with compiled and checked examples.
…documentation - core: one unused_label_validator() (utility/indices) names indices apart from an expression; extended Wick, the engine's renaming apart and series' fresh indices use it. Each keeps its own counter: the engine and series draw from Index::make_tmp_index so that separate calls never share a name. - tests: drop the test that fails once core's open-shell CSV spin tracing is fixed; the exclusion and its reason stay with family_models(). - tests: SEQUANT_SKIP_LONG_TESTS (and Debug) runs the identities over the two spin-orbital models and the strength-tensor finite differences at one value of z and one pair of values; Debug drops from 9.4 min to 2.7 min. The identity tests pin the models of the family in either setting. - tests: check_rule() requires a nonzero element read or a zero derivative. - tests: the judge names its dummies apart from f's indices too. - hf: assert that the k-body part of op::H() holds one tensor. - hf: label the rotation κ̂, which to_latex() renders (κₒ gave \kappaₒ). - doc: the reorderings of a protoindex list count as operations of the variable; at_zero() lists every rejection; AGENTS.md names unit_tests-sequant-deriv.
…efault GCC's -Wextra warns (-Wmissing-field-initializers) where a designated initializer leaves out a member that has no default member initializer, and the tests are built with -Werror: evaluator.cpp, identities.cpp and test_deriv_identities.cpp did not compile with g++-14, which failed every Linux job. The members of Slot, Factor, Perturbation, Projection, Term, Family and OwnEquation now have one.
diff() and at_zero() dereferenced a null expression or variable; they now throw, as mbpt::series does.
… scalar The external indices of a term decide, for a tensor variable, which labels are renamed and which keep a Kronecker delta, and finding them rejects an index in more than two slots. The scalar rule reads no index, so by_one() no longer finds them for a Variable: a term with a hyperindex, as in a THC or CP factorization, can be differentiated by a perturbation strength. For a tensor variable nothing changes.
The valgrind job ran unit_tests-sequant only, so no code of SeQuant-deriv or mbpt::series was checked there. The rule and series cases take 13 s natively in a Debug build; the identity and finite-difference cases are left out as too long under valgrind.
Column symmetry permutes nothing when neither side has two slots, so such a
variable, e.g. an orbital-energy vector ε{;a}, is differentiated as a
nonsymmetric one. Needed to differentiate broadcast-sum denominators by ε.
A leaf of the variable under a TensorPower of exponent e is differentiated
element by element, e x^(e-1); the result is a Hadamard product.
diff(E, variables, definitions) takes a list of ResultExpr: a leaf whose
label and ranks are those of a head, alone or under a TensorPower, stands
for the definition's expression, its slots renamed to the leaf's, and the
chain rule is applied through it (recursively through other definitions).
A definition holds for every element of its head, so a broadcast sum such as
the perturbative denominator D{i;a} = ε{;a} - ε{i;} qualifies: a function of
D⁻¹ can be differentiated by the orbital energies without D being a variable
(D is totally symmetric, which diff does not accept as a variable).
A Kronecker delta that the chain leaves between a summed index of the term
and one of the variable is summed away, as for a leaf of the variable.
Rejected: a head that is not a labeled tensor, has protoindices or the
variable's label; two definitions of one head; a cycle among definitions.
A term with an index in three or more slots was rejected for a tensor variable. Such an index is summed: it is a Hadamard product under a contraction, the shape of a perturbative correction L ⊙ D⁻¹ · R or of a hyperindex of a factorized integral, and renaming it to the variable's label throughout the term, as for an index in two slots, sums the Kronecker delta away. The derivative of a Hadamard product holds the variable's indices in two slots, where the count alone reads them as summed, so diff() passes the indices of each variable to the derivatives by later ones as external. A free index of the function itself must stand in one slot.
- the leaves of a definition are checked with its head renamed apart from the variable: a head named like the variable is valid (its names are dummies), and an unexpanded expression is expanded first; - instantiating a definition renames the protoindices of its summed indices along with the slots they name; - a leaf with a definition and protoindices is rejected (its summed protoindices would need renaming beyond the definition), as are a head that repeats an index and an expression with a free index the head lacks.
An index of  or Ŝ was counted only by the other factors, so an external index of a residual that two other factors hold, as in the elementwise residual  D⁻¹ t, was read as summed and renamed to the variable's label, losing the free indices of the function. The indices of a symmetrizer are those of the residual, so they are external whatever the other slots.
fcdba5d to
c7c23c8
Compare
This draft adds symbolic differentiation of any order, respecting the variable's permutational symmetry, adjoint and protoindices.
Differentiation engine
SeQuant/core/derivderiv::diff(E, {x_1, ..., x_n})returns ∂ⁿE/∂x_1…∂x_n, andderiv::at_zero(E, {x_1, ..., x_n})returnsEwith the variables set to zero.x's label byxis a product of Kronecker deltas, one per slot. A delta on a summed index is summed away at once by renaming that index to the variable's; a delta on an external index stays as a factor (make_kronecker, never an overlap: a derivative pairs an element with itself in any basis).rapid_simplify, which keeps every index name.ÂorŜfactor on the result, and the symmetrizers ofEare never expanded.Generators:
SeQuant/domain/mbptmbpt::series(expr, label, strength, order)replaces every tensor of a label by its Taylor series in a strength.The code has been tested on generating HF nuclear gradient
mbpt::hf::rotated_energyandmbpt::hf::energygive the Hartree-Fock energy under an orbital rotationκ̂.Brillouin condition, stationarity are not applied since the engine only generates symbolic expression. It is user's responsibility to apply physical condition.