Skip to content

[Code scan] Register magnetic cell derivatives in the cell-derivative bucket #5632

Description

@njzjz

Found during a Codex global scan of deepmodeling/deepmd-kit at commit 73de44b1f94471b2e3bdb6b11f57b34d7bc791bb.

Problem

Magnetic cell-derivative output definitions are inserted into the coordinate-derivative bucket instead of the cell-derivative bucket.

Evidence:

  • ModelOutputDef stores coordinate derivatives in def_derv_r, cell derivatives in def_derv_c, and builds reduced cell derivatives from def_derv_c:
    self.def_outp = fit_defs
    self.def_redu = do_reduce(self.def_outp.get_data())
    self.def_derv_r, self.def_derv_c = do_derivative(self.def_outp.get_data())
    self.def_hess_r, _ = do_derivative(self.def_derv_r)
    self.def_derv_c_redu = do_reduce(self.def_derv_c)
    self.def_mask = do_mask(self.def_outp.get_data())
    self.var_defs: dict[str, OutputVariableDef] = {}
    for ii in [
    self.def_outp.get_data(),
    self.def_redu,
    self.def_derv_c,
    self.def_derv_r,
    self.def_derv_c_redu,
    self.def_hess_r,
    self.def_mask,
    ]:
    self.var_defs.update(ii)
  • keys_derv_c() returns self.def_derv_c.keys():
    def keys_derv_c(self): # noqa: ANN201
    return self.def_derv_c.keys()
    def keys_derv_c_redu(self): # noqa: ANN201
    return self.def_derv_c_redu.keys()
  • In do_derivative(), the non-magnetic cell derivative is correctly placed in def_derv_c:
    if vv.c_differentiable:
    assert vv.r_differentiable
    def_derv_c[rkc] = OutputVariableDef(
    rkc,
    vv.shape + [9], # noqa: RUF005
    reducible=True,
    r_differentiable=False,
    c_differentiable=False,
    atomic=True,
    category=apply_operation(vv, OutputVariableOperation.DERV_C),
    )
  • The magnetic cell derivative rkcm is instead assigned into def_derv_r:
    if vv.magnetic:
    def_derv_r[rkcm] = OutputVariableDef(
    rkcm,
    vv.shape + [9], # noqa: RUF005
    reducible=True,
    r_differentiable=False,
    c_differentiable=False,
    atomic=True,
    category=apply_operation(vv, OutputVariableOperation.DERV_C),
    magnetic=True,
    )

Impact

keys_derv_c() misses magnetic cell derivatives, and do_reduce(self.def_derv_c) cannot create the corresponding reduced magnetic virial definition. Magnetic models can therefore omit or misclassify *_derv_c_mag outputs even when the fitting output is cell-differentiable.

Suggested Fix

Change the magnetic cell-derivative assignment from def_derv_r[rkcm] to def_derv_c[rkcm]. Add a unit test with a magnetic, cell-differentiable output definition that asserts *_derv_c_mag appears in keys_derv_c() and its reduced definition is present.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    Status
    In Progress

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions