forked from deepmodeling/deepmd-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake_model.py
More file actions
1275 lines (1154 loc) · 48.8 KB
/
Copy pathmake_model.py
File metadata and controls
1275 lines (1154 loc) · 48.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: LGPL-3.0-or-later
from collections.abc import (
Callable,
)
from typing import (
TYPE_CHECKING,
Any,
)
if TYPE_CHECKING:
from deepmd.dpmodel.atomic_model.dp_atomic_model import (
DPAtomicModel,
)
from deepmd.dpmodel.utils.exclude_mask import (
PairExcludeMask,
)
import array_api_compat
import numpy as np
from deepmd.dpmodel.array_api import (
Array,
)
from deepmd.dpmodel.atomic_model.base_atomic_model import (
BaseAtomicModel,
)
from deepmd.dpmodel.common import (
GLOBAL_ENER_FLOAT_PRECISION,
GLOBAL_NP_FLOAT_PRECISION,
PRECISION_DICT,
RESERVED_PRECISION_DICT,
get_xp_precision,
)
from deepmd.dpmodel.output_def import (
FittingOutputDef,
ModelOutputDef,
OutputVariableCategory,
OutputVariableOperation,
check_operation_applied,
)
from deepmd.dpmodel.utils import (
DefaultNeighborList,
NeighborList,
format_nlist,
nlist_distinguish_types,
)
from deepmd.dpmodel.utils.neighbor_graph import (
NeighborGraph,
build_neighbor_graph,
build_neighbor_graph_ase,
compact_nodes,
expand_node_values,
)
from deepmd.utils.path import (
DPPath,
)
from .edge_transform_output import (
fit_output_to_model_output_graph,
)
from .transform_output import (
communicate_extended_output,
fit_output_to_model_output,
)
def model_call_from_call_lower(
*, # enforce keyword-only arguments
call_lower: Callable[
[
np.ndarray,
np.ndarray,
np.ndarray,
np.ndarray | None,
np.ndarray | None,
bool,
],
dict[str, Array],
],
rcut: float,
sel: list[int],
mixed_types: bool,
model_output_def: ModelOutputDef,
coord: Array,
atype: Array,
box: Array | None = None,
fparam: Array | None = None,
aparam: Array | None = None,
do_atomic_virial: bool = False,
coord_corr_for_virial: Array | None = None,
charge_spin: Array | None = None,
neighbor_list: NeighborList | None = None,
pair_excl: "PairExcludeMask | None" = None,
) -> dict[str, Array]:
"""Return model prediction from lower interface.
Parameters
----------
coord
The coordinates of the atoms.
shape: nf x (nloc x 3)
atype
The type of atoms. shape: nf x nloc
box
The simulation box. shape: nf x 9
fparam
frame parameter. nf x ndf
aparam
atomic parameter. nf x nloc x nda
do_atomic_virial
If calculate the atomic virial.
neighbor_list
The neighbor-list construction strategy. ``None`` uses the default
all-pairs builder (:class:`DefaultNeighborList`), reproducing the
historical behavior. An alternative strategy (e.g. an O(N) cell list)
may be injected to speed up neighbor-list construction; it returns the
same extended representation, so model outputs are unchanged.
pair_excl
Model-level pair-type exclusion mask. Exclusion is a nlist-BUILD
transform (decision #18/A4): it is folded into the nlist here, at the
build seam, and ``call_lower`` consumes a pre-excluded nlist without
re-applying it.
Returns
-------
ret_dict
The result dict of type dict[str,np.ndarray].
The keys are defined by the `ModelOutputDef`.
"""
nframes, nloc = atype.shape[:2]
cc, bb, fp, ap = coord, box, fparam, aparam
del coord, box, fparam, aparam
builder = neighbor_list if neighbor_list is not None else DefaultNeighborList()
# Model-level pair exclusion is a nlist-BUILD transform (decision #18/A4):
# the BUILDER owns it (mirroring build_neighbor_graph on the graph path), so
# the lower always consumes a pre-excluded nlist. ``pair_excl`` is part of
# the NeighborList.build() contract; a custom strategy predating it fails
# loudly (TypeError) instead of silently including excluded pairs.
extended_coord, extended_atype, nlist, mapping = builder.build(
cc, atype, bb, rcut, sel, pair_excl=pair_excl
)
extended_coord = extended_coord.reshape(nframes, -1, 3)
if coord_corr_for_virial is not None:
xp = array_api_compat.array_namespace(coord_corr_for_virial)
# mapping: nf x nall -> nf x nall x 1, then tile to nf x nall x 3
mapping_idx = xp.tile(
xp.reshape(mapping, (nframes, -1, 1)),
(1, 1, 3),
)
extended_coord_corr = xp.take_along_axis(
coord_corr_for_virial,
mapping_idx,
axis=1,
)
else:
extended_coord_corr = None
call_lower_kwargs: dict[str, Any] = {
"fparam": fp,
"aparam": ap,
"do_atomic_virial": do_atomic_virial,
"charge_spin": charge_spin,
}
if extended_coord_corr is not None:
call_lower_kwargs["extended_coord_corr"] = extended_coord_corr
model_predict_lower = call_lower(
extended_coord,
extended_atype,
nlist,
mapping,
**call_lower_kwargs,
)
model_predict = communicate_extended_output(
model_predict_lower,
model_output_def,
mapping,
do_atomic_virial=do_atomic_virial,
)
return model_predict
def make_model(
T_AtomicModel: type[BaseAtomicModel],
T_Bases: tuple[type, ...] = (),
) -> type:
"""Make a model as a derived class of an atomic model.
The model provide two interfaces.
1. the `call_lower`, that takes extended coordinates, atyps and neighbor list,
and outputs the atomic and property and derivatives (if required) on the extended region.
2. the `call`, that takes coordinates, atypes and cell and predicts
the atomic and reduced property, and derivatives (if required) on the local region.
Parameters
----------
T_AtomicModel
The atomic model.
T_Bases
Additional base classes for the returned model class.
Defaults to ``()``. For example, dpmodel passes ``(NativeOP,)``.
Returns
-------
CM
The model.
"""
class CM(*T_Bases):
def __init__(
self,
*args: Any,
# underscore to prevent conflict with normal inputs
atomic_model_: T_AtomicModel | None = None,
**kwargs: Any,
) -> None:
self.model_def_script = ""
self.min_nbor_dist = None
if atomic_model_ is not None:
self.atomic_model: T_AtomicModel = atomic_model_
else:
self.atomic_model: T_AtomicModel = T_AtomicModel(*args, **kwargs)
self.precision_dict = PRECISION_DICT
# not supported by flax
# self.reverse_precision_dict = RESERVED_PRECISION_DICT
self.global_np_float_precision = GLOBAL_NP_FLOAT_PRECISION
self.global_ener_float_precision = GLOBAL_ENER_FLOAT_PRECISION
def model_output_def(self) -> ModelOutputDef:
"""Get the output def for the model."""
return ModelOutputDef(self.atomic_output_def())
def model_output_type(self) -> list[str]:
"""Get the output type for the model."""
output_def = self.model_output_def()
var_defs = output_def.var_defs
vars = [
kk
for kk, vv in var_defs.items()
if vv.category == OutputVariableCategory.OUT
]
return vars
def enable_compression(
self,
table_extrapolate: float = 5,
table_stride_1: float = 0.01,
table_stride_2: float = 0.1,
check_frequency: int = -1,
) -> None:
"""Call atomic_model enable_compression().
Parameters
----------
table_extrapolate
The scale of model extrapolation
table_stride_1
The uniform stride of the first table
table_stride_2
The uniform stride of the second table
check_frequency
The overflow check frequency
"""
self.atomic_model.enable_compression(
self.get_min_nbor_dist(),
table_extrapolate,
table_stride_1,
table_stride_2,
check_frequency,
)
def call_common(
self,
coord: Array,
atype: Array,
box: Array | None = None,
fparam: Array | None = None,
aparam: Array | None = None,
do_atomic_virial: bool = False,
coord_corr_for_virial: Array | None = None,
charge_spin: Array | None = None,
neighbor_list: NeighborList | None = None,
neighbor_graph_method: str | None = None,
spin: Array | None = None,
) -> dict[str, Array]:
"""Return model prediction.
Parameters
----------
coord
The coordinates of the atoms.
shape: nf x (nloc x 3)
atype
The type of atoms. shape: nf x nloc
box
The simulation box. shape: nf x 9
fparam
frame parameter. nf x ndf
aparam
atomic parameter. nf x nloc x nda
do_atomic_virial
If calculate the atomic virial.
coord_corr_for_virial
The coordinates correction for virial.
shape: nf x (nloc x 3)
charge_spin
Frame-level charge/spin FiLM conditioning, ``(nf, 2)`` or
``None``. Both the dense (nlist) and NeighborGraph lowers
consume it (currently only DPA4/SeZM); the graph route no
longer forces this model onto dense (former ``cs -> dense``
gate removed) -- it threads through
``_call_common_graph``/``call_lower_graph`` to the
descriptor's ``call_graph``, gated per-descriptor by
``supports_charge_spin``.
spin
Per-local-atom spin, ``(nf, nloc, 3)``, or ``None``. Only the
NeighborGraph lower consumes it (native magnetic conditioning,
e.g. DPA4/SeZM); the dense (nlist) route has no spin support
and raises if ``spin`` is supplied without a graph
``neighbor_graph_method``.
neighbor_list
Neighbor-list construction strategy for the DENSE-nlist path
only. ``None`` uses the default all-pairs builder; an
alternative strategy (e.g. an O(N) cell list) may be injected to
speed up nlist construction without changing model outputs. It
is consumed by the dense lower; supplying it forces the dense
route (see below) and it is rejected together with an explicit
``neighbor_graph_method``.
neighbor_graph_method
Selects the lower the model routes through. The option strings
refer to the neighbor-GRAPH builder, NOT the legacy dense nlist:
- ``None`` -- default. dpmodel/jax keep the dense nlist path;
pt_expt default-flips graph-eligible mixed_types descriptors to
the carry-all graph (decision #17).
- ``"legacy"`` -- force the dense nlist path (opt out of the
default-flip).
- ``"dense"`` -- build a carry-all :class:`NeighborGraph` with the
in-tree O(N^2) ALL-PAIRS search (this is NOT the dense nlist
lower; "dense" = the all-pairs graph builder).
- ``"ase"`` -- build the carry-all graph with the O(N) ASE cell
list.
The graph routes (``"dense"``/``"ase"``, and the pt_expt
default-flip) require a ``mixed_types`` descriptor with a graph
lower (dpa1/se_atten with concat type embedding; attention layers included).
At non-binding ``sel`` the graph matches the dense path exactly for the
non-smooth branch; at binding ``sel`` the carry-all graph keeps
neighbors the dense path truncates, and for
``smooth_type_embedding=True`` the graph drops the dense
layout's sel-padding softmax terms, so the energy intentionally
differs (sel-independent graph semantics).
Returns
-------
ret_dict
The result dict of type dict[str,np.ndarray].
The keys are defined by the `ModelOutputDef`.
"""
cc, bb, fp, ap, cs, sp, input_prec = self._input_type_cast(
coord,
box=box,
fparam=fparam,
aparam=aparam,
charge_spin=charge_spin,
spin=spin,
)
del coord, box, fparam, aparam, charge_spin, spin
graph_method = self._resolve_graph_method(neighbor_graph_method)
# ``neighbor_list`` is a DENSE-nlist strategy; the graph path cannot
# consume it. Reject an explicit graph+nlist combination, and
# otherwise honor the supplied nlist by taking the dense route
# (don't let the pt_expt default-flip silently ignore it).
if neighbor_list is not None:
if neighbor_graph_method not in (None, "legacy"):
raise ValueError(
"neighbor_list is a dense-nlist strategy and cannot be "
f"combined with neighbor_graph_method={neighbor_graph_method!r}; "
"pass one or the other"
)
graph_method = None
# model-level spin rides ONLY the NeighborGraph lower
if sp is not None and graph_method is None:
raise NotImplementedError(
"model-level spin rides only the NeighborGraph lower; the "
"dense (nlist) route has no spin support -- use a graph "
"neighbor_graph_method"
)
if graph_method is not None:
# carry-all NeighborGraph energy forward (Option B / decision #17)
model_predict = self._call_common_graph(
cc,
atype,
bb,
fp,
ap,
graph_method,
do_atomic_virial,
spin=sp,
charge_spin=cs,
)
else:
# legacy dense-nlist path (builds the extended quartet)
model_predict = model_call_from_call_lower(
call_lower=self.call_common_lower,
rcut=self.get_rcut(),
sel=self.get_sel(),
mixed_types=self.mixed_types(),
model_output_def=self.model_output_def(),
coord=cc,
atype=atype,
box=bb,
fparam=fp,
aparam=ap,
do_atomic_virial=do_atomic_virial,
coord_corr_for_virial=coord_corr_for_virial,
charge_spin=cs,
neighbor_list=neighbor_list,
# exclusion is a nlist-BUILD transform (decision #18/A4)
pair_excl=getattr(self.atomic_model, "pair_excl", None),
)
model_predict = self._output_type_cast(model_predict, input_prec)
return model_predict
def _resolve_graph_method(
self, neighbor_graph_method: str | None
) -> str | None:
"""Resolve the neighbor-graph method.
Base (dpmodel/jax): ``None`` => the dense path. These backends compute
force/virial ANALYTICALLY inside ``call_common`` (``energy_derv_r`` in
the output); the carry-all graph lower here is ENERGY-only, so it is
NOT used by default (it would drop force). ``"legacy"`` => dense;
explicit ``"dense"``/``"ase"`` => opt into the (energy-only) graph.
pt_expt OVERRIDES this so ``None`` defaults graph-eligible mixed_types
descriptors to the carry-all graph (decision #17) -- pt_expt has the
autograd ``forward_common_lower_graph`` that produces force/virial.
Parameters
----------
neighbor_graph_method
The user-requested method: ``None`` (default), ``"legacy"``
(force dense), or ``"dense"``/``"ase"`` (force the graph builder).
Returns
-------
method
The resolved method passed to :meth:`_call_common_graph`, or
``None`` to take the dense path.
"""
if neighbor_graph_method == "legacy":
return None
return neighbor_graph_method
def _call_common_graph(
self,
cc: Array,
atype: Array,
bb: Array | None,
fp: Array | None,
ap: Array | None,
method: str,
do_atomic_virial: bool = False,
spin: Array | None = None,
charge_spin: Array | None = None,
) -> dict[str, Array]:
"""Carry-all graph forward (opt-in, Option B).
Builds a carry-all :class:`NeighborGraph` from ``cc``/``atype``/``bb``
and routes the forward through the OUTPUT-AGNOSTIC
:meth:`call_lower_graph`. Input/output type-casting is done by the
caller.
Parameters
----------
cc
coordinates. nf x nloc x 3 (or nf x (nloc x 3))
atype
the atom types. nf x nloc
bb
the simulation cell. nf x 3 x 3, or ``None`` for non-periodic.
fp
the frame parameter. nf x ndf
ap
the atomic parameter. nf x nloc x nda
method
the carry-all builder, ``"dense"`` or ``"ase"``.
do_atomic_virial
whether to calculate the atomic virial.
spin
Per-local-atom spin, ``(nf, nloc, 3)``, or ``None``. Flattened
to the flat node axis ``(N, 3)`` and forwarded unchanged to
:meth:`call_lower_graph`.
charge_spin
Frame-level charge/spin conditioning, ``(nf, 2)`` or ``None``.
Unflattened (per-frame, not per-node) and forwarded unchanged
to :meth:`call_lower_graph`, whose ``n_node`` here is always
the rectangular ``full(nf, nloc)`` this method builds -- the
one shape the descriptor's per-frame FiLM division requires.
Returns
-------
model_predict
the standard model dict mirroring the dense ``call_common`` keys
(``<var>`` per-atom, ``<var>_redu`` reduced, derivative
name-holders ``None``, plus the int ``mask``).
"""
if not (self.mixed_types() and self.atomic_model.uses_graph_lower()):
raise NotImplementedError(
"neighbor_graph_method requires a mixed_types descriptor with a "
"graph lower (e.g. dpa1 attn_layer=0)"
)
# Model-level ``pair_exclude_types`` is a graph-BUILD transform
# (decision #18): apply it here, at the seam where the NeighborGraph
# is constructed, so the graph lower / exported ``.pt2`` consumes an
# already-excluded ``edge_mask`` and never re-applies it. Mirrors the
# pt_expt eager path and the C++ ``applyPairExclusion`` at build.
pair_excl = getattr(self.atomic_model, "pair_excl", None)
if method == "dense":
ng = build_neighbor_graph(
cc, atype, bb, self.get_rcut(), pair_excl=pair_excl
)
elif method == "ase":
ng = build_neighbor_graph_ase(
cc, atype, bb, self.get_rcut(), pair_excl=pair_excl
)
else:
raise ValueError(
f"unknown neighbor_graph_method {method!r}; the dpmodel/jax backend "
"supports 'dense'/'ase' only ('vesin'/'nv' require the pt_expt backend)."
)
xp = array_api_compat.array_namespace(atype)
nf, nloc = atype.shape[:2]
n_padded = nf * nloc
atype_flat = xp.reshape(atype, (n_padded,))
# A batch of unequal atom counts arrives padded to a common width
# with phantom atoms (atype < 0). The builders leave them out of
# every edge, so dropping them from the node axis costs nothing and
# spares the network from evaluating them. On a batch of uniform
# atom count the mask is all true and this is a renumbering by the
# identity.
ng, node_index = compact_nodes(ng, atype_flat >= 0)
# OUTPUT-AGNOSTIC standard model dict (``<var>``, ``<var>_redu``,
# derivative name-holders ``None``, plus int ``mask``), like the
# dense ``call_common``. ``call_lower_graph`` masks virtual atoms
# (atype<0) and sets the real int mask.
model_predict = self.call_lower_graph(
atype=xp.take(atype_flat, node_index, axis=0),
n_node=ng.n_node,
edge_index=ng.edge_index,
edge_vec=ng.edge_vec,
edge_mask=ng.edge_mask,
fparam=fp,
# graph-lower ABI: aparam is FLAT on the node axis, (N, nda).
aparam=(
xp.take(
xp.reshape(ap, (n_padded, ap.shape[-1])), node_index, axis=0
)
if ap is not None
else None
),
spin=(
xp.take(xp.reshape(spin, (n_padded, 3)), node_index, axis=0)
if spin is not None
else None
),
charge_spin=charge_spin,
)
# Public ABI is rectangular (nf, nloc, *); the lower is flat over
# the real atoms. Scatter per-atom keys back onto the padded width
# here at the boundary, where a phantom slot reads zero, which is
# what a masked-out atom contributed there before.
# Only the rectangular entry reaches this scatter; the ragged
# one keeps the flat axis its caller handed over.
n_real = node_index.shape[0]
for k in list(model_predict.keys()):
v = model_predict[k]
# per-frame reduced keys (..._redu) keep their (nf, *) shape; only node-level (N,*) keys unravel — guards the nloc==1 case where N == nf.
if (
v is not None
and not k.endswith("_redu")
and v.shape[:1] == (n_real,)
):
model_predict[k] = xp.reshape(
expand_node_values(v, node_index, n_padded),
(nf, nloc, *v.shape[1:]),
)
return model_predict
def call_common_lower(
self,
extended_coord: Array,
extended_atype: Array,
nlist: Array,
mapping: Array | None = None,
fparam: Array | None = None,
aparam: Array | None = None,
do_atomic_virial: bool = False,
extended_coord_corr: Array | None = None,
comm_dict: dict | None = None,
charge_spin: Array | None = None,
) -> dict[str, Array]:
"""Return model prediction. Lower interface that takes
extended atomic coordinates and types, nlist, and mapping
as input, and returns the predictions on the extended region.
The predictions are not reduced.
Parameters
----------
extended_coord
coordinates in extended region. nf x (nall x 3).
extended_atype
atomic type in extended region. nf x nall.
nlist
neighbor list. nf x nloc x nsel.
mapping
mapps the extended indices to local indices. nf x nall.
fparam
frame parameter. nf x ndf
aparam
atomic parameter. nf x nloc x nda
do_atomic_virial
whether calculate atomic virial
extended_coord_corr
coordinates correction for virial in extended region.
nf x (nall x 3)
comm_dict
MPI communication metadata for parallel inference (e.g.
LAMMPS multi-rank). Carries send/recv lists, processor IDs,
the MPI communicator handle, and per-rank nlocal/nghost.
``None`` for non-parallel inference (default).
Returns
-------
result_dict
the result dict, defined by the `FittingOutputDef`.
"""
nframes, nall = extended_atype.shape[:2]
extended_coord = extended_coord.reshape(nframes, -1, 3)
nlist = self.format_nlist(
extended_coord,
extended_atype,
nlist,
extra_nlist_sort=self.need_sorted_nlist_for_lower(),
)
cc_ext, _, fp, ap, cs, _, input_prec = self._input_type_cast(
extended_coord, fparam=fparam, aparam=aparam, charge_spin=charge_spin
)
del extended_coord, fparam, aparam, charge_spin
model_predict = self.forward_common_atomic(
cc_ext,
extended_atype,
nlist,
mapping=mapping,
fparam=fp,
aparam=ap,
do_atomic_virial=do_atomic_virial,
extended_coord_corr=extended_coord_corr,
comm_dict=comm_dict,
charge_spin=cs,
)
model_predict = self._output_type_cast(model_predict, input_prec)
return model_predict
def forward_common_atomic(
self,
extended_coord: Array,
extended_atype: Array,
nlist: Array,
mapping: Array | None = None,
fparam: Array | None = None,
aparam: Array | None = None,
do_atomic_virial: bool = False,
extended_coord_corr: Array | None = None,
comm_dict: dict | None = None,
charge_spin: Array | None = None,
) -> dict[str, Array]:
atomic_ret = self.atomic_model.forward_common_atomic(
extended_coord,
extended_atype,
nlist,
mapping=mapping,
fparam=fparam,
aparam=aparam,
comm_dict=comm_dict,
charge_spin=charge_spin,
)
return fit_output_to_model_output(
atomic_ret,
self.atomic_output_def(),
extended_coord,
do_atomic_virial=do_atomic_virial,
mask=atomic_ret["mask"] if "mask" in atomic_ret else None,
)
def forward_common_atomic_graph(
self,
atype: Array,
n_node: Array,
edge_index: Array,
edge_vec: Array,
edge_mask: Array,
n_local: Array | None = None,
fparam: Array | None = None,
aparam: Array | None = None,
comm_dict: dict | None = None,
charge_spin: Array | None = None,
spin: Array | None = None,
) -> dict[str, Array]:
"""Model-level graph forward (no type cast). Analogue of the dense
:meth:`forward_common_atomic`.
Builds a :class:`NeighborGraph` from the flat edge fields, runs the
atomic model's :meth:`forward_common_atomic_graph` (flat ``(N, *)``
per-node output), then the flat-N output transform (per-frame
``segment_sum`` reduction; derivative name-holders ``None`` --
force/virial come from the pt_expt autograd lower). The
``(nf, nloc)`` unravel for the public ABI happens in the caller
(:meth:`_call_common_graph`).
Parameters
----------
atype
(N,) flat local-plus-halo atom types, ``N == sum(n_node)``.
n_node
(nf,) per-frame total node counts.
edge_index
(2, E) ``[src, dst]`` edge endpoints (flat local indices).
edge_vec
(E, 3) neighbor-minus-center edge vectors.
edge_mask
(E,) boolean/0-1 valid-edge mask.
n_local
Per-rank local (owned) atom counts for multi-rank inference,
``(nf,)``. When given, ghost rows (index ``>= n_local[frame]``)
are excluded from ``<var>_redu`` (see
:func:`fit_output_to_model_output_graph`); ``None`` (default)
is the single-rank/all-owned behavior.
fparam
Frame parameter, ``(nf, ndf)``.
aparam
Atomic parameter, ``(N, nda)``.
comm_dict
Optional MPI communication metadata.
charge_spin
Charge/spin conditioning.
spin
Per-node spin vectors, flat (N, 3), or ``None``. Forwarded
unchanged to the atomic model's ``forward_common_atomic_graph``
(and, from there, the descriptor's ``call_graph``).
Returns
-------
dict
The standard model dict (``<var>`` per-node, ``<var>_redu``
reduced, derivative name-holders ``None``), matching
:func:`fit_output_to_model_output_graph`.
"""
graph = NeighborGraph(
n_node=n_node,
edge_index=edge_index,
edge_vec=edge_vec,
edge_mask=edge_mask,
n_local=n_local,
)
atomic_ret = self.atomic_model.forward_common_atomic_graph(
graph,
atype,
fparam=fparam,
aparam=aparam,
charge_spin=charge_spin,
spin=spin,
)
return fit_output_to_model_output_graph(
atomic_ret,
self.atomic_output_def(),
graph,
mask=atomic_ret["mask"] if "mask" in atomic_ret else None,
n_local=n_local,
)
def call_common_lower_graph(
self,
atype: Array,
n_node: Array,
edge_index: Array,
edge_vec: Array,
edge_mask: Array,
n_local: Array | None = None,
fparam: Array | None = None,
aparam: Array | None = None,
comm_dict: dict | None = None,
charge_spin: Array | None = None,
spin: Array | None = None,
) -> dict[str, Array]:
"""Graph-native PUBLIC lower (dpa1/se_atten concat-tebd, attention included).
The PRIMARY directly-callable graph interface (spec decision #14).
Casts inputs/outputs to/from the model precision exactly like the
dense :meth:`call_common_lower` (``edge_vec`` is the geometry, in
place of ``coord``), then runs :meth:`forward_common_atomic_graph`.
OUTPUT-AGNOSTIC: every fitting (energy/dos/dipole/polar/property/...)
flows through with no change on the fitting side; force/virial are
produced by the pt_expt autograd lower. Must match the dense
:meth:`call_common_lower` reduction on the SAME neighbor set.
Parameters
----------
atype
(N,) flat local-plus-halo atom types, ``N == sum(n_node)``.
n_node
(nf,) per-frame total node counts.
edge_index
(2, E) ``[src, dst]`` edge endpoints (flat local indices).
edge_vec
(E, 3) neighbor-minus-center edge vectors.
edge_mask
(E,) boolean/0-1 valid-edge mask.
n_local
Per-rank local (owned) atom counts for multi-rank inference,
``(nf,)``. When given, ghost rows (index ``>= n_local[frame]``)
are excluded from ``<var>_redu``; ``None`` (default) is the
single-rank/all-owned behavior.
fparam
Frame parameter, ``(nf, ndf)``.
aparam
Atomic parameter, ``(N, nda)``.
comm_dict
Optional MPI communication metadata.
charge_spin
Charge/spin conditioning.
spin
Per-node spin vectors, flat (N, 3), or ``None``. Cast to the
model precision alongside the other node inputs and forwarded
unchanged to :meth:`forward_common_atomic_graph`.
Returns
-------
dict
The standard model dict in the INPUT precision.
"""
edge_vec, _, fparam, aparam, cs, sp, input_prec = self._input_type_cast(
edge_vec,
fparam=fparam,
aparam=aparam,
charge_spin=charge_spin,
spin=spin,
)
model_predict = self.forward_common_atomic_graph(
atype,
n_node,
edge_index,
edge_vec,
edge_mask,
n_local=n_local,
fparam=fparam,
aparam=aparam,
comm_dict=comm_dict,
charge_spin=cs,
spin=sp,
)
model_predict = self._output_type_cast(model_predict, input_prec)
return model_predict
# backward-compat alias (mirrors ``call_lower = call_common_lower``)
call_lower_graph = call_common_lower_graph
call = call_common
call_lower = call_common_lower
def get_out_bias(self) -> Array:
"""Get the output bias."""
return self.atomic_model.get_out_bias()
def get_observed_type_list(self) -> list[str]:
"""Get observed types (elements) of the model during data statistics.
Bias-based fallback for old models without metadata.
Returns
-------
list[str]
A list of the observed type names in this model.
"""
type_map = self.get_type_map()
out_bias = self.get_out_bias()[0]
assert out_bias is not None, "No out_bias found in the model."
assert out_bias.ndim == 2, "The supported out_bias should be a 2D array."
assert out_bias.shape[0] == len(type_map), (
"The out_bias shape does not match the type_map length."
)
xp = array_api_compat.array_namespace(out_bias)
bias_mask = xp.any(xp.abs(out_bias) > 1e-6, axis=-1)
return [type_map[i] for i in range(len(type_map)) if bias_mask[i]]
def set_out_bias(self, out_bias: Array) -> None:
"""Set the output bias."""
self.atomic_model.set_out_bias(out_bias)
def change_out_bias(
self,
merged: Any,
bias_adjust_mode: str = "change-by-statistic",
) -> None:
"""Change the output bias according to the input data and the pretrained model.
Parameters
----------
merged
The merged data samples.
bias_adjust_mode : str
The mode for changing output bias:
'change-by-statistic' or 'set-by-statistic'.
"""
self.atomic_model.change_out_bias(merged, bias_adjust_mode=bias_adjust_mode)
def _input_type_cast(
self,
coord: Array,
box: Array | None = None,
fparam: Array | None = None,
aparam: Array | None = None,
charge_spin: Array | None = None,
spin: Array | None = None,
) -> tuple[
Array,
Array | None,
Array | None,
Array | None,
Array | None,
Array | None,
Any,
]:
"""Cast the input data to global float type."""
xp = array_api_compat.array_namespace(coord)
input_dtype = coord.dtype
global_dtype = get_xp_precision(
xp, RESERVED_PRECISION_DICT[self.global_np_float_precision]
)
###
### type checking would not pass jit, convert to coord prec anyway
###
_lst: list[Array | None] = [
xp.astype(vv, input_dtype) if vv is not None else None
for vv in [box, fparam, aparam, charge_spin, spin]
]
box, fparam, aparam, charge_spin, spin = _lst
if input_dtype == global_dtype:
return coord, box, fparam, aparam, charge_spin, spin, input_dtype
else:
return (
xp.astype(coord, global_dtype),
xp.astype(box, global_dtype) if box is not None else None,
xp.astype(fparam, global_dtype) if fparam is not None else None,
xp.astype(aparam, global_dtype) if aparam is not None else None,
xp.astype(charge_spin, global_dtype)
if charge_spin is not None
else None,
xp.astype(spin, global_dtype) if spin is not None else None,
input_dtype,
)
def _output_type_cast(
self,
model_ret: dict[str, Array],
input_prec: Any,
) -> dict[str, Array]:
"""Convert the model output to the input prec.
Parameters
----------
model_ret
The model output.
input_prec
The input dtype returned by ``_input_type_cast``.
"""
model_ret_not_none = [vv for vv in model_ret.values() if vv is not None]
if not model_ret_not_none:
return model_ret
xp = array_api_compat.array_namespace(model_ret_not_none[0])
global_dtype = get_xp_precision(
xp, RESERVED_PRECISION_DICT[self.global_np_float_precision]
)
ener_dtype = get_xp_precision(
xp, RESERVED_PRECISION_DICT[self.global_ener_float_precision]