File size: 48,906 Bytes
ff0f77d | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 | /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Copyright (c) 2022-2024 of Luigi Bonati and Enrico Trizio.
The pytorch module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The pytorch module is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with plumed. If not, see <http://www.gnu.org/licenses/>.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
#ifdef __PLUMED_HAS_LIBTORCH
#include <cmath>
#include <memory>
#include <fstream>
#include <torch/torch.h>
#include <torch/script.h>
#include <torch/csrc/jit/jit_log.h>
#include "core/PlumedMain.h"
#include "colvar/Colvar.h"
#include "colvar/ActionRegister.h"
#include "tools/NeighborList.h"
#include "tools/Communicator.h"
#include "tools/OpenMP.h"
#include "tools/File.h"
#include "tools/PDB.h"
// NOTE: Freezing a ScriptModule (torch::jit::freeze) works only in >=1.11
// For 1.8 <= versions <=1.10 we need a hack
// (see https://discuss.pytorch.org/t/how-to-check-libtorch-version/77709/4 and also
// https://github.com/pytorch/pytorch/blob/dfbd030854359207cb3040b864614affeace11ce/torch/csrc/jit/api/module.cpp#L479)
// adapted from NequIP https://github.com/mir-group/nequip
#if (TORCH_VERSION_MAJOR == 1 && TORCH_VERSION_MINOR <= 10)
#define DO_TORCH_FREEZE_HACK
// For the hack, need more headers:
#include <torch/csrc/jit/passes/freeze_module.h>
#include <torch/csrc/jit/passes/frozen_graph_optimizations.h>
#endif
using namespace std;
namespace PLMD {
class NeighborList;
namespace colvar {
namespace pytorch_gnn {
//+PLUMEDOC PYTORCH_GNN PYTORCH_GNN
/*
Load a Graph Neural Network (GNN) model compiled with TorchScript.
This module uses a fixed length unit of _Angstrom_. Thus, the GNN model read by
this module should be trained under the same unit convention. Besides, the
module constructs node attributes w.r.t to the atomic types. As a result, this
module require a PDB file which records names of _ALL_ atoms in the system
(the STRUCTURE keyword). Note that the atom names in this PDB file could
_ONLY_ be element symbols, e.g.:
\auxfile{plumed_topo.pdb}
ATOM 1 H ACE A 1 15.100 12.940 29.390 1.00 0.00 H
ATOM 2 C ACE A 1 14.970 13.860 29.960 1.00 0.00 C
ATOM 3 H ACE A 1 15.720 13.820 30.760 1.00 0.00 H
ATOM 4 H ACE A 1 13.980 13.920 30.410 1.00 0.00 H
ATOM 5 C ACE A 1 15.300 15.070 29.100 1.00 0.00 C
\endauxfile
The module constructs graph edges between neighbors inside the selected atom
group, using the cutoff value recorded in the model file. By default, such an
atom group is defined by the single GROUPA keyword. Under this case, the node
number of the input graph in each MD step is fixed, and the number of edges
will change according to the relative postions of the atoms.
However, if the GROUPB parameter is given, the atom group mentioned above will
contain all atoms in GROUPA, _AND_ atoms in GROUPB which are within a radius of
_ANY_ atom in GROUPA. Such a radius of selecting atoms from GROUPB equals to the
cutoff radius recorded in the model file _plus_ the buffer size controlled by
the BUFFER keyword. Thus, when GROUPB is given, the node number of the input
graph could fluctuate in different MD steps. Besides, when SUBGROUPA is defined
the module will add long edges bewteen such a group. Cutoff radius of these
long edges will equal to the cutoff_l attribute recorded in the model file.
This module also support committor calculations. When the input PyTorch model
is a committor model, the outputs will assign the zeta value to the first
output (node-0) and the q value to the second output (node-1). If the KBIAS
keyword is also given, the module will also calculate the committor bias and
assign it with a label of kbias. These information will be shown in the log as
well.
Note that this function requires \ref installation-libtorch LibTorch C++ library.
Check the instructions in the \ref PYTORCH page to enable the module.
Specifically, we encourage the user to install the GPU-enabled version of
LibTorch, when dealing with large input graphs.
\par Examples
The following example instructs plumed to evaluate the GNN model using the atoms 1-10. The neighbor list for determining the edges will be updated every 100 steps.
\plumedfile
PYTORCH_GNN ...
GROUPA=1-10
MODEL=model.ptc
STRUCTURE=plumed_topo.pdb
NL_STRIDE=100
LABEL=gnn
... PYTORCH_GNN
\endplumedfile
The following example instructs plumed to do the same calculation as the above example, but will evaluate the model on CUDA using double precision, and add an OPES bias potential on the CV.
\plumedfile
PYTORCH_GNN ...
GROUPA=1-10
MODEL=model.ptc
STRUCTURE=plumed_topo.pdb
NL_STRIDE=100
CUDA
FLOAT64
LABEL=gnn
... PYTORCH_GNN
OPES_METAD ...
LABEL=opes
ARG=gnn.node-0
FILE=KERNELS
PACE=500
TEMP=300
BARRIER=35
... OPES_METAD
\endplumedfile
The following example instructs plumed to do the same calculation as the above example, but will sample Kang's (or Kolmogolov's) transition state ensemble.
\plumedfile
PYTORCH_GNN ...
GROUPA=1-10
MODEL=model.ptc
STRUCTURE=plumed_topo.pdb
NL_STRIDE=100
FLOAT64
KBIAS
KBLAMBDA=-2.0
LABEL=gnn
... PYTORCH_GNN
BIASVALUE ARG=gnn.kbias LABEL=vk
\endplumedfile
The following example instructs plumed to evaluate the GNN model using the atoms 1-10 as center atoms, and atoms 11-100 as the environment atoms. The buffer size used for selecting active atoms from the environment atoms is 2 PLUMED unit. The neighbor list for determining the edges will be updated every 2 steps.
\plumedfile
PYTORCH_GNN ...
GROUPA=1-10
GROUPB=11-100
MODEL=model.ptc
STRUCTURE=plumed_topo.pdb
NL_STRIDE=2
BUFFER=2.0
LABEL=gnn
... PYTORCH_GNN
\endplumedfile
*/
//+ENDPLUMEDOC
class PytorchGNN: public Colvar
{
int n_out = 0;
int summary_level = 3;
bool pbc = true;
bool serial = false;
bool firsttime = true;
bool invalidate_list = true;
bool is_committor = false;
bool k_bias = false;
bool kb_weighted = false;
bool kb_truncated = false;
bool bailout_fusion = false;
double r_max = 0.0; // In PLUMED length unit
double buffer = 0.0; // In PLUMED length unit
double r_max_l = -1.0; // In PLUMED length unit
double kb_lambda = -1.0;
double kb_epsilon = -1.0;
double kb_sigmoid_p = -1.0;
std::string model_file_name;
std::string model_training_time;
std::string structure_file_name;
std::vector<int> system_node_types;
std::vector<int> model_atomic_numbers;
std::vector<double> model_atomic_masses;
std::vector<AtomNumber> atom_list_a;
std::vector<AtomNumber> atom_list_b;
std::vector<AtomNumber> atom_list_sub_a;
std::vector<int> atom_list_active; // local_ids
std::vector<int> atom_list_active_subgroup; // local_ids
std::unique_ptr<NeighborList> neighbor_list;
torch::jit::script::Module model;
torch::ScalarType torch_float_dtype = torch::kFloat32;
torch::Device device = c10::Device(torch::kCPU);
const std::array<std::string, 118> periodic_table = {
"h", "he",
"li", "be", "b", "c", "n", "o", "f", "ne",
"na", "mg", "al", "si", "p", "s", "cl", "ar",
"k", "ca", "sc", "ti", "v", "cr", "mn", "fe", "co", "ni", "cu", "zn", "ga", "ge", "as", "se", "br", "kr",
"rb", "sr", "y", "zr", "nb", "mo", "tc", "ru", "rh", "pd", "ag", "cd", "in", "sn", "sb", "te", "i", "xe",
"cs", "ba", "la", "ce", "pr", "nd", "pm", "sm", "eu", "gd", "tb", "dy", "ho", "er", "tm", "yb", "lu",
"hf", "ta", "w", "re", "os", "ir", "pt", "au", "hg", "tl", "pb", "bi", "po", "at", "rn",
"fr", "ra", "ac", "th", "pa", "u", "np", "pu", "am", "cm", "bk", "cf", "es", "fm", "md", "no", "lr",
"rf", "db", "sg", "bh", "hs", "mt", "ds", "rg", "cn", "nh", "fl", "mc", "lv", "ts", "og"
}; // TODO: add ghost atoms
std::string model_summary(
std::string model_name, torch::jit::Module module, int level_max, int level
);
int get_number_of_parameters(void);
int atomic_number_from_name(std::string name);
bool groups_have_intersection(void);
bool subgroup_is_in_group_a(void);
void find_active_atoms(int n_threads);
void find_active_subgroup_atoms(void);
public:
explicit PytorchGNN(const ActionOptions&);
~PytorchGNN();
static void registerKeywords(Keywords& keys);
void calculate() override;
void prepare() override;
}; // class PytorchGNN
PLUMED_REGISTER_ACTION(PytorchGNN, "PYTORCH_GNN")
void PytorchGNN::registerKeywords(Keywords& keys)
{
Colvar::registerKeywords(keys);
keys.add(
"atoms",
"GROUPA",
"First list of atoms (corresponding to the `system_selection in mlcolvar`)"
);
keys.add(
"atoms",
"GROUPB",
"Second list of atoms (corresponding to the `environment_selection in mlcolvar`)"
);
keys.add(
"atoms",
"SUBGROUPA",
"List of subsystem atoms (corresponding to the `subsystem_selection in mlcolvar`)"
);
keys.add(
"compulsory",
"MODEL",
"Filename of the PyTorch compiled model"
);
keys.add(
"compulsory",
"STRUCTURE",
"PDB file name that contains the whole simulated system, with currect atom names and orders"
);
keys.add(
"optional",
"NL_STRIDE",
"The frequency with which we are updating the atoms in the neighbor list"
);
keys.add(
"optional",
"BUFFER",
"Buffer size used in finding active environment atoms"
);
keys.add(
"optional",
"KBLAMBDA",
"The LAMBDA value for calculating $V_K$. Only vaild for GNN committor models"
);
keys.add(
"optional",
"KBEPSILON",
"The EPSILON value for calculating $V_K$. Only vaild for GNN committor models, the default value depends on the model precision"
);
keys.add(
"optional",
"_SUMMARYLEVEL",
"Maximum verbosity level for the model structure printing"
);
keys.addFlag(
"CUDA",
false,
"Perform the calculation on CUDA"
);
keys.addFlag(
"SERIAL",
false,
"Perform the calculation in serial - for debug purpose"
);
keys.addFlag(
"FLOAT64",
false,
"Evaluate the model in double precise"
);
keys.addFlag(
"_BAILOUTFUSION",
false,
"Use a faster LibTorch fusion strategy (experimental)"
);
keys.addFlag(
"KBIAS",
false,
"Calculate Kang's bias potential $V_K$ (a.k.a. Kolmogolov's bias). Only vaild for GNN committor models"
);
keys.addFlag(
"KBWEIGHTED",
false,
"Calculate mass-weighted (exact) $V_K$. Only vaild for GNN committor models"
);
keys.addFlag(
"KBTRUNCATED",
false,
"Calculate truncated (twisted) $V_K$. Only vaild for GNN committor models"
);
keys.addOutputComponent(
"node",
"default",
"Model outputs"
);
keys.addOutputComponent(
"kbias",
"KBIAS",
"Kang's bias potential $V_K$"
);
}
PytorchGNN::PytorchGNN(const ActionOptions& ao):
PLUMED_COLVAR_INIT(ao)
{
// print libtorch version
std::stringstream ss;
ss << TORCH_VERSION_MAJOR << "." \
<< TORCH_VERSION_MINOR << "." \
<< TORCH_VERSION_PATCH;
std::string version;
ss >> version; // extract into the string.
std::string version_info = " LibTorch version: " + version + "\n";
log.printf(version_info.data());
// parse input
parseAtomList("GROUPA", atom_list_a);
parseAtomList("GROUPB", atom_list_b);
parseAtomList("SUBGROUPA", atom_list_sub_a);
parse("MODEL", model_file_name);
parse("STRUCTURE", structure_file_name);
int neighbor_list_stride = 1;
parse("NL_STRIDE", neighbor_list_stride);
if (neighbor_list_stride <= 0)
plumed_merror("NL_STRIDE should be positive!");
parse("BUFFER", buffer);
if (buffer > 0 && atom_list_b.size() == 0)
plumed_merror("Not GROUPB given! Cannot define the BUFFER key!");
parse("KBLAMBDA", kb_lambda);
parse("KBEPSILON", kb_epsilon);
parse("_SUMMARYLEVEL", summary_level);
bool use_cuda = false;
bool required_cuda = false;
parseFlag("CUDA", required_cuda);
parseFlag("SERIAL", serial);
if (required_cuda and serial)
plumed_merror("Can not enable CUDA with SERIAL at the same time!");
bool use_float64 = false;
parseFlag("FLOAT64", use_float64);
if (kb_epsilon < 0) {
if (use_float64)
kb_epsilon = 1E-14;
else
kb_epsilon = 1E-7;
}
bool nopbc = !pbc;
parseFlag("NOPBC", nopbc);
pbc = !nopbc;
parseFlag("KBIAS", k_bias);
parseFlag("KBWEIGHTED", kb_weighted);
parseFlag("KBTRUNCATED", kb_truncated);
parseFlag("_BAILOUTFUSION", bailout_fusion);
checkRead();
// check groups
if (atom_list_b.size() > 0) {
if (groups_have_intersection())
plumed_merror("GROUPA can not intersect with GROUPB!");
atom_list_active.resize(atom_list_a.size() + atom_list_b.size());
atom_list_active.clear();
} else {
atom_list_active.resize(atom_list_a.size());
atom_list_active.clear();
find_active_atoms(1);
}
if (atom_list_sub_a.size() > 0)
find_active_subgroup_atoms();
if (atom_list_sub_a.size() > 0)
if (!subgroup_is_in_group_a())
plumed_merror("Not all atoms in SUBGROUPA present in GROUPA!");
// check precise
if (use_float64)
torch_float_dtype = torch::kFloat64;
// check CUDA
if (required_cuda && torch::cuda::is_available()) {
device = c10::Device(torch::kCUDA);
use_cuda = true;
} else if (required_cuda) {
use_cuda = false;
}
// check structure file
PDB pdb;
FILE *fp = fopen(structure_file_name.c_str(), "r");
if (fp != NULL) {
pdb.readFromFilepointer(
fp,
atoms.usingNaturalUnits(), // TODO: remove the `atoms.` prefix when release
0.1 / atoms.getUnits().getLength() // TODO: remove the `atoms.` prefix when release
);
fclose(fp);
} else {
plumed_merror("Can not open PDB file: '" + structure_file_name + "'");
}
// deserialize the model from file
try {
model = torch::jit::load(model_file_name, device);
} catch (const c10::Error& e) {
plumed_merror(
"Cannot load model file: '" + model_file_name + "'. Reason: " + e.what()
);
}
// disable parameter grads
for (auto p: model.parameters())
p.requires_grad_(false);
// set up model precise
model.to(torch_float_dtype);
// summary
int model_parameters = get_number_of_parameters();
std::string model_architecture = model_summary("CV", model, summary_level, 0);
// get CV length
if (!model.hasattr("n_out") && !model.hasattr("n_cvs"))
plumed_merror(
"Can not find model attribute: 'n_out' or 'n_cvs'! One of these attributes has to be set during the compilation of the model!"
);
else if (model.hasattr("n_out") && model.hasattr("n_cvs"))
plumed_merror(
"Both model attribute: 'n_out' and 'n_cvs' are defined!"
);
if (model.hasattr("n_out"))
n_out = model.attr("n_out").toTensor().item<int>();
else
n_out = model.attr("n_cvs").toTensor().item<int>();
// get cutoff radius
if (!model.hasattr("r_max") && !model.hasattr("cutoff") )
plumed_merror(
"Can not find model attribute: 'r_max' or 'cutoff'! One of these attributes has to be set during the compilation of the model!"
);
else if (model.hasattr("r_max") && model.hasattr("cutoff") )
plumed_merror(
"Both model attribute: 'r_max' and 'cutoff' are defined!"
);
// TODO: now, the `r_max` parameter in the model file is defined in unit of Angstrom.
// We should warn the users about this default
if (model.hasattr("cutoff"))
r_max = model.attr("cutoff").toTensor().item<double>();
else
r_max = model.attr("r_max").toTensor().item<double>();
r_max = r_max / atoms.getUnits().getLength() * 0.1; // TODO: remove the `atoms.` prefix when release
// get long cutoff radius
if (atom_list_sub_a.size() > 0) {
if (!model.hasattr("cutoff_l")) {
plumed_merror(
"Can not find model attribute: 'cutoff_l'! Such an attributes is required for defining the subsystem group (SUBGROUPA)!"
);
} else if (model.attr("cutoff_l").toTensor().item<double>() < 0) {
plumed_merror(
"Model attribute: 'cutoff_l' is negative! A positive long cutoff radius is required for defining the subsystem group (SUBGROUPA)!"
);
} else {
r_max_l = model.attr("cutoff_l").toTensor().item<double>();
r_max_l = r_max_l / atoms.getUnits().getLength() * 0.1; // TODO: remove the `atoms.` prefix when release
}
} else if (
model.hasattr("cutoff_l")
&& model.attr("cutoff_l").toTensor().item<double>() > 0
) {
plumed_merror(
"Found model attribute: 'cutoff_l'! Such an attributes requires defining the subsystem group (SUBGROUPA)!"
);
}
// get atomic numbers
if (!model.hasattr("atomic_numbers"))
plumed_merror(
"Can not find model attribute: 'atomic_numbers'! This attribute has to be set during the compilation of the model!"
);
auto atomic_numbers = model.attr("atomic_numbers").toTensor();
for (int64_t i = 0; i < atomic_numbers.size(0); i++)
model_atomic_numbers.push_back(atomic_numbers[i].item<int64_t>());
// check model type
if (model.hasattr("is_committor"))
is_committor = model.attr("is_committor").toTensor().item<int>() != 0;
if (!is_committor && k_bias)
plumed_merror(
"Can not calculate Kang's bias potential for a non-committor model!"
);
if (is_committor) {
if (n_out != 2)
plumed_merror(
"The committor model should output two values!"
);
for (auto p: model.named_attributes())
if (p.name == "sigmoid.p")
kb_sigmoid_p = p.value.toDouble();
if (kb_sigmoid_p < 0)
plumed_merror(
"Can not load the sigmoid_p value from the model!"
);
if (k_bias && kb_weighted) {
auto atomic_masses = model.attr("atomic_masses").toTensor();
for (int64_t i = 0; i < atomic_masses.size(0); i++)
model_atomic_masses.push_back(atomic_masses[i].item<double>());
if (model_atomic_masses.size() != model_atomic_numbers.size())
plumed_merror(
"Mismatch between model attributes: 'atomic_numbers' and 'atomic_masses'!"
);
}
}
// training time
if (model.hasattr("training_time")) {
auto ts = model.attr("training_time").toTensor();
std::stringstream ss_time;
ss_time
<< "UTC"
<< (ts[0].item<int64_t>() >= 0 ? "+" : "")
<< std::to_string(ts[0].item<int64_t>())
<< " "
<< std::to_string(ts[1].item<int64_t>())
<< "-"
<< std::setw(2) << std::setfill('0') << std::to_string(ts[2].item<int64_t>())
<< "-"
<< std::setw(2) << std::setfill('0') << std::to_string(ts[3].item<int64_t>())
<< " "
<< std::setw(2) << std::setfill('0') << std::to_string(ts[4].item<int64_t>())
<< ":"
<< std::setw(2) << std::setfill('0') << std::to_string(ts[5].item<int64_t>())
<< ":"
<< std::setw(2) << std::setfill('0') << std::to_string(ts[6].item<int64_t>());
model_training_time = ss_time.str();
} else {
model_training_time = "unknown";
}
// idk ... stolen from:
// https://stackoverflow.com/questions/77102532/libtorch-performance-issue-when-using-multiple-gpus-in-multiple-threads
if (bailout_fusion) {
torch::jit::FusionStrategy bailout = {
{torch::jit::FusionBehavior::STATIC, 0},
{torch::jit::FusionBehavior::DYNAMIC, 0},
};
torch::jit::setFusionStrategy(bailout);
}
// optimize model
model.eval();
#ifdef DO_TORCH_FREEZE_HACK
// NOTE: do the hack
// copied from the implementation of torch::jit::freeze,
// except without the broken check
// see https://github.com/pytorch/pytorch/blob/dfbd030854359207cb3040b864614affeace11ce/torch/csrc/jit/api/module.cpp
bool optimize_numerics = true; // the default
// the {} is preserved_attrs
auto out_mod = torch::jit::freeze_module(model, {});
// see 1.11 bugfix in https://github.com/pytorch/pytorch/pull/71436
auto graph = out_mod.get_method("forward").graph();
OptimizeFrozenGraph(graph, optimize_numerics);
model = out_mod;
#else
// do it normally
model = torch::jit::freeze(model);
#endif
// optimize model for inference
#ifndef DO_TORCH_FREEZE_HACK
model = torch::jit::optimize_for_inference(model);
#endif
// send the model to device
model.to(device);
// create system atomic numbers
std::vector<int> atom_is_required(pdb.getAtomNumbers().size());
for (size_t i = 0; i < atom_list_a.size(); i++) {
int index = atom_list_a[i].index();
atom_is_required[index] = 1;
}
for (size_t i = 0; i < atom_list_b.size(); i++) {
int index = atom_list_b[i].index();
atom_is_required[index] = 1;
}
for (size_t i = 0; i < pdb.getAtomNumbers().size(); i++) {
AtomNumber index = pdb.getAtomNumbers()[i];
std::string name = pdb.getAtomName(index);
int number = atomic_number_from_name(name);
auto iter = std::find(
model_atomic_numbers.begin(),
model_atomic_numbers.end(),
number
);
if (iter == model_atomic_numbers.end()) {
if (atom_is_required[i])
plumed_merror(
"Element '" + name + "' does not present in model " + model_file_name
);
else
system_node_types.push_back(-1);
} else {
int node_type = std::distance(model_atomic_numbers.begin(), iter);
system_node_types.push_back(node_type);
}
}
// create components
if (!is_committor) {
for (int i = 0; i < n_out; i++) {
string name_comp = "node-" + std::to_string(i);
addComponentWithDerivatives(name_comp);
componentIsNotPeriodic(name_comp);
}
} else {
string name_comp_z = "node-0";
addComponentWithDerivatives(name_comp_z);
componentIsNotPeriodic(name_comp_z);
string name_comp_q = "node-1";
addComponent(name_comp_q);
componentIsNotPeriodic(name_comp_q);
if (k_bias) {
string name_comp_b = "kbias";
addComponentWithDerivatives(name_comp_b);
componentIsNotPeriodic(name_comp_b);
}
}
// initialize the neighbor list
if (atom_list_b.size() > 0)
neighbor_list = Tools::make_unique<NeighborList>(
atom_list_a,
atom_list_b,
serial,
false,
pbc,
getPbc(),
comm,
r_max + buffer,
neighbor_list_stride
);
else
neighbor_list = Tools::make_unique<NeighborList>(
atom_list_a,
serial,
pbc,
getPbc(),
comm,
r_max + buffer,
neighbor_list_stride
);
requestAtoms(neighbor_list->getFullAtomList());
// print log
std::string thename = getLabel();
if(atom_list_b.size() > 0) {
log.printf(
" Will build graphs using %u system and %u environment atoms\n",
static_cast<unsigned>(atom_list_a.size()),
static_cast<unsigned>(atom_list_b.size())
);
log.printf(" System atom list (GROUPA):\n");
for (unsigned int i = 0; i < atom_list_a.size(); i++) {
if (((i + 1) % 10) == 0)
log.printf("\n");
log.printf(" %d", atom_list_a[i].serial());
}
log.printf("\n");
log.printf(" Environment atom list (GROUPB):\n");
for (unsigned int i = 0; i < atom_list_b.size(); i++) {
if (((i + 1) % 10) == 0)
log.printf("\n");
log.printf(" %d", atom_list_b[i].serial());
}
log.printf("\n");
} else {
log.printf(
" Will build graphs using %u atoms\n",
static_cast<unsigned>(atom_list_a.size())
);
log.printf(" Atom list:\n");
for (unsigned int i = 0; i < atom_list_a.size(); i++) {
if (((i + 1) % 10) == 0)
log.printf("\n");
log.printf(" %d", atom_list_a[i].serial());
}
log.printf("\n");
}
if (atom_list_sub_a.size() > 0) {
log.printf(
" Will add long edges between %u atoms\n",
static_cast<unsigned>(atom_list_sub_a.size())
);
log.printf(" Subsystem atom list:\n");
for (unsigned int i = 0; i < atom_list_sub_a.size(); i++) {
if (((i + 1) % 10) == 0)
log.printf("\n");
log.printf(" %d", atom_list_sub_a[i].serial());
}
log.printf("\n");
}
log << " Model atomic numbers: " << model_atomic_numbers;
log.printf("\n");
log.printf(" Boundary conditions: ");
if (pbc)
log.printf("periodic\n");
else
log.printf("non-periodic\n");
log.printf(" Neighbor List update stride: %d\n", neighbor_list_stride);
log.printf(" Graph cutoff radius: %f (PLUMED length unit)\n", r_max);
if (atom_list_b.size() > 0)
log.printf(" Environment buffer size: %f (PLUMED length unit)\n", buffer);
if (atom_list_sub_a.size() > 0)
log.printf(" Subsystem cutoff radius: %f (PLUMED length unit)\n", r_max_l);
log.printf(" Number of outputs: %d \n", n_out);
log.printf(" Is this a committor model: ");
if (is_committor)
log.printf("yes\n");
else
log.printf("no\n");
if (is_committor) {
log.printf(" If sample Kang's (or Kolmogolov's) ensemble: ");
if (k_bias)
log.printf("yes\n");
else
log.printf("no\n");
if (k_bias) {
log.printf(" If calculate truncated V_K: ");
if (kb_truncated)
log.printf("yes\n");
else
log.printf("no\n");
log.printf(" If calculate mass-weighted V_K: ");
if (kb_weighted) {
log.printf("yes\n");
log << " Model atomic masses: " << model_atomic_masses << "\n";
} else {
log.printf("no\n");
}
log.printf(" LAMBDA value for calculating V_K: %f\n", kb_lambda);
log.printf(" EPSILON value for calculating V_K: %e\n", kb_epsilon);
log.printf(" SIGMOID_P value for calculating V_K: %e\n", kb_sigmoid_p);
}
if (k_bias) {
log << " Output alignment: " + thename + ".kbias -> V_K\n";
log << " Output alignment: " + thename + ".node-0 -> zeta\n";
} else {
log << " Output alignment: " + thename + ".node-0 -> zeta\n";
}
log << " Output alignment: " + thename + ".node-1 -> q (no grad)\n";
}
log.printf(" Will run on device: ");
if (use_cuda)
log.printf("CUDA\n");
else if (required_cuda)
log.printf("CPU (CUDA device not found/LibTorch does not support CUDA)\n");
else
log.printf("CPU (as required)\n");
log << " Model file name: " + model_file_name + "\n";
log << " Model training time: " + model_training_time + "\n";
log << " Model parameters: " + std::to_string(model_parameters) + "\n";
log << " Model architecture: \n";
log << model_architecture;
log << " Bibliography: ";
if (is_committor || r_max_l > 0 || atom_list_b.size() > 0)
log << plumed.cite("Kang et al. arXiv preprint arXiv:2510.18018 (2025)");
log << plumed.cite("Zhang et al., J. Chem. Theory Comput. 20, 24, 10787–10797 (2024)");
log << plumed.cite("Bonati, Trizio, Rizzi and Parrinello, J. Chem. Phys. 159, 014801 (2023)");
log << plumed.cite("Bonati, Rizzi and Parrinello, J. Phys. Chem. Lett. 11, 2998-3004 (2020)");
log.printf("\n");
}
PytorchGNN::~PytorchGNN()
{
return;
}
void PytorchGNN::prepare()
{
if (neighbor_list->getStride() > 0) {
if (firsttime || ((getStep() % neighbor_list->getStride()) == 0)) {
requestAtoms(neighbor_list->getFullAtomList());
invalidate_list = true;
firsttime = false;
} else {
requestAtoms(neighbor_list->getReducedAtomList());
invalidate_list = false;
if (getExchangeStep())
plumed_merror(
"Neighbor lists should be updated on exchange steps - choose a NL_STRIDE which divides the exchange stride!"
);
}
if (getExchangeStep())
firsttime = true;
}
}
void PytorchGNN::calculate()
{
// get some common data
auto pbc_tools = getPbc();
int n_atoms = getNumberOfAtoms();
std::vector<PLMD::Vector> x_local = getPositions();
// threads
int n_threads = OpenMP::getNumThreads();
if (!serial)
n_threads = std::min(n_threads, n_atoms);
else
n_threads = 1;
// perform the size check
if (system_node_types.size() != (size_t)atoms.getNatoms())
plumed_merror(
"Structure file '" +
structure_file_name +
"' has different number of atoms with the simulated system!"
);
// update the neighbor list and number of atoms
if (neighbor_list->getStride() > 0 && invalidate_list)
neighbor_list->update(x_local);
if (atom_list_b.size() > 0)
find_active_atoms(n_threads);
n_atoms = (int)atom_list_active.size();
n_threads = std::min(n_threads, n_atoms);
// get the unit
double to_ang = 10 * atoms.getUnits().getLength(); // TODO: remove the `atoms.` prefix when release
// get the positions
// TODO: now, the positions used by the model file is in unit of Angstrom.
// We should warn the users about this default
std::vector<float> positions_vector(n_atoms * 3);
#pragma omp parallel for num_threads(n_threads)
for (int i = 0; i < n_atoms; i++) {
int index = atom_list_active[i];
positions_vector[i * 3 + 0] = x_local[index][0] * to_ang;
positions_vector[i * 3 + 1] = x_local[index][1] * to_ang;
positions_vector[i * 3 + 2] = x_local[index][2] * to_ang;
}
torch::Tensor positions = torch::from_blob(
positions_vector.data(),
n_atoms * 3,
torch::TensorOptions().dtype(torch::kFloat32)
);
positions = positions.to(device).to(torch_float_dtype);
positions = positions.reshape({n_atoms, 3});
// cell
// TODO: now, the box data used by the model file is in unit of Angstrom.
// We should warn the users about this default
PLMD::Tensor box = getBox();
std::vector<float> cell_vector(9);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
cell_vector[i * 3 + j] = box[i][j] * to_ang;
}
torch::Tensor cell = torch::from_blob(
cell_vector.data(),
9,
torch::TensorOptions().dtype(torch::kFloat32)
);
cell = cell.to(device).to(torch_float_dtype);
cell = cell.reshape({3, 3});
// build node attributes
// TODO: now, the node attributes are in MACE's format.
// We should try to give more options, or warn the users about this default
int n_node_feats = (int)model_atomic_numbers.size();
std::vector<float> node_attrs_vector(n_node_feats * n_atoms);
#pragma omp parallel for num_threads(n_threads)
for (int i = 0; i < n_atoms; i++) {
int index = atom_list_active[i];
int node_type = system_node_types[getAbsoluteIndex(index).index()];
node_attrs_vector[i * n_node_feats + node_type] = 1.0;
}
torch::Tensor node_attrs = torch::from_blob(
node_attrs_vector.data(),
n_node_feats * n_atoms,
torch::TensorOptions().dtype(torch::kFloat32)
);
node_attrs = node_attrs.to(device).to(torch_float_dtype);
node_attrs = node_attrs.reshape({n_atoms, n_node_feats});
// build edges
int n_edges = 0;
int n_edges_l = 0;
torch::Tensor edge_index;
if (atom_list_b.size() > 0) {
n_edges = n_atoms * (n_atoms - 1);
std::vector<float> distance_vector(n_edges);
std::vector<std::vector<int64_t>> edge_index_vector;
edge_index_vector.resize(2, std::vector<int64_t>(n_edges));
#pragma omp parallel for num_threads(n_threads)
for (int i = 0; i < n_atoms; i++) {
int count = 0;
for (int j = 0; j < n_atoms; j++) {
if (i != j) {
// NOTE: build edge index using the full local index list
edge_index_vector[0][i * (n_atoms - 1) + count] = i;
edge_index_vector[1][i * (n_atoms - 1) + count] = j;
count++;
}
}
}
#pragma omp parallel for num_threads(n_threads)
for (int i = 0; i < n_edges; i++) {
distance_vector[i] = pbc_tools.distance(
pbc,
x_local[atom_list_active[edge_index_vector[0][i]]],
x_local[atom_list_active[edge_index_vector[1][i]]]
);
}
torch::Tensor distances = torch::from_blob(
distance_vector.data(),
n_edges,
torch::TensorOptions().dtype(torch::kFloat32)
);
torch::Tensor senders = torch::from_blob(
edge_index_vector[0].data(),
n_edges,
torch::TensorOptions().dtype(torch::kInt64)
);
torch::Tensor receivers = torch::from_blob(
edge_index_vector[1].data(),
n_edges,
torch::TensorOptions().dtype(torch::kInt64)
);
const torch::Tensor mask = distances <= r_max;
senders = senders.index({mask});
receivers = receivers.index({mask});
edge_index = torch::vstack({senders, receivers});
n_edges = (int)edge_index.size(1);
} else {
n_edges = (int)neighbor_list->size() * 2;
int n_pairs = (int)neighbor_list->size();
std::vector<std::vector<int64_t>> edge_index_vector;
edge_index_vector.resize(2, std::vector<int64_t>(n_edges));
#pragma omp parallel for num_threads(n_threads)
for (int i = 0; i < n_pairs; i++) {
auto pair = neighbor_list->getClosePair(i);
edge_index_vector[0][i] = pair.first;
edge_index_vector[1][i] = pair.second;
edge_index_vector[0][n_pairs + i] = pair.second;
edge_index_vector[1][n_pairs + i] = pair.first;
}
torch::Tensor senders = torch::from_blob(
edge_index_vector[0].data(),
n_edges,
torch::TensorOptions().dtype(torch::kInt64)
);
torch::Tensor receivers = torch::from_blob(
edge_index_vector[1].data(),
n_edges,
torch::TensorOptions().dtype(torch::kInt64)
);
edge_index = torch::vstack({senders, receivers});
}
if (atom_list_sub_a.size() > 0) {
torch::Tensor edge_index_l;
int n_atoms_l = atom_list_sub_a.size();
n_edges_l = n_atoms_l * (n_atoms_l - 1);
std::vector<float> distance_vector_l(n_edges_l);
std::vector<std::vector<int64_t>> edge_index_vector_l;
edge_index_vector_l.resize(2, std::vector<int64_t>(n_edges_l));
#pragma omp parallel for num_threads(n_threads)
for (int i = 0; i < n_atoms_l; i++) {
int count = 0;
for (int j = 0; j < n_atoms_l; j++) {
if (i != j) {
// NOTE: build edge index using the partial local index list
edge_index_vector_l[0][
i * (n_atoms_l - 1) + count
] = atom_list_active_subgroup[i];
edge_index_vector_l[1][
i * (n_atoms_l - 1) + count
] = atom_list_active_subgroup[j];
count++;
}
}
}
#pragma omp parallel for num_threads(n_threads)
for (int i = 0; i < n_edges_l; i++) {
distance_vector_l[i] = pbc_tools.distance(
pbc,
x_local[edge_index_vector_l[0][i]],
x_local[edge_index_vector_l[1][i]]
);
}
torch::Tensor distances_l = torch::from_blob(
distance_vector_l.data(),
n_edges_l,
torch::TensorOptions().dtype(torch::kFloat32)
);
const torch::Tensor mask_l = distances_l <= r_max_l;
if (mask_l.size(0) > 0) {
torch::Tensor senders_l = torch::from_blob(
edge_index_vector_l[0].data(),
n_edges_l,
torch::TensorOptions().dtype(torch::kInt64)
);
torch::Tensor receivers_l = torch::from_blob(
edge_index_vector_l[1].data(),
n_edges_l,
torch::TensorOptions().dtype(torch::kInt64)
);
senders_l = senders_l.index({mask_l});
receivers_l = receivers_l.index({mask_l});
edge_index_l = torch::vstack({senders_l, receivers_l});
n_edges_l = (int)edge_index_l.size(1);
edge_index = torch::hstack({edge_index, edge_index_l});
n_edges = n_edges + n_edges_l;
}
}
edge_index = edge_index.to(device);
// edge shifts
torch::Tensor shifts;
torch::Tensor unit_shifts;
if (pbc) {
if (pbc_tools.isOrthorombic()) {
auto deltas = (
torch::index_select(positions, 0, edge_index[0])
- torch::index_select(positions, 0, edge_index[1])
);
unit_shifts = torch::round(deltas / torch::diagonal(cell, 0));
shifts = unit_shifts * torch::diagonal(cell, 0);
} else {
auto cell_inv = torch::linalg_pinv(cell.transpose(1, 0));
auto positions_s = torch::matmul(
cell_inv, positions.transpose(1, 0)
);
auto deltas = (
torch::index_select(positions_s, 1, edge_index[0])
- torch::index_select(positions_s, 1, edge_index[1])
);
unit_shifts = torch::round(deltas).transpose(1, 0);
shifts = torch::matmul(unit_shifts, cell);
}
} else {
shifts = torch::zeros({n_edges, 3}, torch_float_dtype);
unit_shifts = torch::zeros({n_edges, 3}, torch_float_dtype);
}
shifts = shifts.to(device);
unit_shifts = unit_shifts.to(device);
// other things
// TODO: some of these things are required by MACE. We should disable
// some of them when not using MACE, maybe by distinguishing the MACE model.
auto batch = torch::zeros({n_atoms}, torch::dtype(torch::kInt64));
auto ptr = torch::empty({2}, torch::dtype(torch::kInt64));
auto weight = torch::empty({1}, torch_float_dtype);
ptr[0] = 0;
ptr[1] = n_atoms;
weight[0] = 1.0;
// load data to device
// TODO: some of these things are required by MACE. We should disable
// some of them when not using MACE, maybe by distinguishing the MACE model.
batch = batch.to(device);
ptr = ptr.to(device);
weight = weight.to(device);
// pack the input, call the model
// TODO: some of these things are required by MACE. We should disable
// some of them when not using MACE, maybe by distinguishing the MACE model.
c10::Dict<std::string, torch::Tensor> input;
input.insert("batch", batch);
input.insert("cell", cell);
input.insert("edge_index", edge_index);
input.insert("node_attrs", node_attrs);
input.insert("positions", positions);
input.insert("ptr", ptr);
input.insert("weight", weight);
input.insert("shifts", shifts);
input.insert("unit_shifts", unit_shifts);
// Optional fields.
if (atom_list_b.size() > 0) {
auto system_masks = torch::vstack({
torch::ones(
{(int64_t)atom_list_a.size(), 1}, torch::dtype(torch::kBool)
),
torch::zeros(
{n_atoms - (int64_t)atom_list_a.size(), 1}, torch::dtype(torch::kBool)
),
});
system_masks = system_masks.to(device);
input.insert("system_masks", system_masks);
auto n_system = torch::ones({1, 1}, torch::dtype(torch::kInt64));
n_system = n_system.to(device);
n_system[0][0] = (int64_t)atom_list_a.size();
input.insert("n_system", n_system);
}
if (atom_list_sub_a.size() > 0){
auto edge_masks_le = torch::vstack({
torch::zeros({n_edges - n_edges_l, 1}, torch::dtype(torch::kBool)),
torch::ones({n_edges_l, 1}, torch::dtype(torch::kBool)),
});
edge_masks_le = edge_masks_le.to(device);
input.insert("edge_masks_le", edge_masks_le);
}
// TODO: figure out how to enable virials. Maybe we could port MACE's python
// code to our python module.
auto output = model.forward({input, false}).toTensor();
// helper variables
std::vector<PLMD::Vector> derivatives(n_atoms);
auto grad_output = torch::ones({1}).expand({1, 1}).to(device);
if (!is_committor) {
for (int i = 0; i < n_out; i++) {
// set CV values
string name_comp = "node-" + std::to_string(i);
getPntrToComponent(name_comp)->set(output[0][i].cpu().item<double>());
// set derivatives
auto gradients = torch::autograd::grad(
{output.slice(1, i, (i + 1))},
{positions},
{grad_output}, // grad_outputs
true, // retain_graph
false // create_graph
)[0].cpu();
#pragma omp parallel for num_threads(n_threads)
for (int j = 0; j < n_atoms; j++) {
derivatives[j][0] = gradients[j][0].item<double>() * to_ang;
derivatives[j][1] = gradients[j][1].item<double>() * to_ang;
derivatives[j][2] = gradients[j][2].item<double>() * to_ang;
}
#pragma omp parallel for num_threads(n_threads)
for (int j = 0; j < n_atoms; j++) {
int index = atom_list_active[j];
setAtomsDerivatives(
getPntrToComponent(name_comp), index, derivatives[j]
);
}
}
} else if (!k_bias) {
// set committor values
string name_comp_z = "node-0";
getPntrToComponent(name_comp_z)->set(output[0][0].cpu().item<double>());
string name_comp_q = "node-1";
getPntrToComponent(name_comp_q)->set(output[0][1].cpu().item<double>());
// set derivatives of z
auto gradients = torch::autograd::grad(
{output.slice(1, 0, 1)},
{positions},
{grad_output}, // grad_outputs
false, // retain_graph
false // create_graph
)[0].cpu();
#pragma omp parallel for num_threads(n_threads)
for (int j = 0; j < n_atoms; j++) {
derivatives[j][0] = gradients[j][0].item<double>() * to_ang;
derivatives[j][1] = gradients[j][1].item<double>() * to_ang;
derivatives[j][2] = gradients[j][2].item<double>() * to_ang;
}
#pragma omp parallel for num_threads(n_threads)
for (int j = 0; j < n_atoms; j++) {
int index = atom_list_active[j];
setAtomsDerivatives(
getPntrToComponent(name_comp_z), index, derivatives[j]
);
}
} else {
auto z = output[0][0];
auto q = output[0][1];
auto epsilon = torch::tensor(kb_epsilon, torch_float_dtype).to(device);
auto sigmoid_p = torch::tensor(kb_sigmoid_p, torch_float_dtype).to(device);
// get bias value
auto gradients_z = torch::autograd::grad(
{z},
{positions},
{grad_output}, // grad_outputs
true, // retain_graph
true // create_graph
)[0];
// square
auto gradients_z_2 = torch::pow(gradients_z, 2);
// mass-weighting
if (kb_weighted) {
std::vector<float> node_masses_vector(n_atoms);
#pragma omp parallel for num_threads(n_threads)
for (int i = 0; i < n_atoms; i++) {
int index = atom_list_active[i];
int node_type = system_node_types[getAbsoluteIndex(index).index()];
node_masses_vector[i] = model_atomic_masses[node_type];
}
torch::Tensor node_masses = torch::from_blob(
node_masses_vector.data(),
n_atoms,
torch::TensorOptions().dtype(torch::kFloat32)
);
node_masses = node_masses.to(device).to(torch_float_dtype);
node_masses = node_masses.reshape({n_atoms, 1});
gradients_z_2 = gradients_z_2 / node_masses;
}
// sum over all dims
auto gradients_z_sum = torch::sum(gradients_z_2);
// chain rules
auto k_bias_value = torch::ones(1, torch_float_dtype).to(device);
if (!kb_truncated)
k_bias_value = kb_lambda * (
torch::log(gradients_z_sum + epsilon)
- 4.0 * torch::log(1.0 + torch::exp(-sigmoid_p * z))
- 2.0 * sigmoid_p * z
- torch::log(epsilon)
);
else
k_bias_value = kb_lambda * (
torch::log(gradients_z_sum * torch::pow(q * (1 - q), 2) + epsilon)
- torch::log(epsilon)
);
// set committor values
string name_comp_z = "node-0";
getPntrToComponent(name_comp_z)->set(output[0][0].cpu().item<double>());
string name_comp_q = "node-1";
getPntrToComponent(name_comp_q)->set(output[0][1].cpu().item<double>());
string name_comp_b = "kbias";
getPntrToComponent(name_comp_b)->set(k_bias_value.cpu().item<double>());
// set derivatives of z
#pragma omp parallel for num_threads(n_threads)
for (int j = 0; j < n_atoms; j++) {
derivatives[j][0] = gradients_z[j][0].item<double>() * to_ang;
derivatives[j][1] = gradients_z[j][1].item<double>() * to_ang;
derivatives[j][2] = gradients_z[j][2].item<double>() * to_ang;
}
#pragma omp parallel for num_threads(n_threads)
for (int j = 0; j < n_atoms; j++) {
int index = atom_list_active[j];
setAtomsDerivatives(
getPntrToComponent(name_comp_z), index, derivatives[j]
);
}
// set derivatives of bias
auto gradients_b = torch::autograd::grad(
{k_bias_value},
{positions},
{grad_output}, // grad_outputs
false, // retain_graph
false // create_graph
)[0].cpu();
#pragma omp parallel for num_threads(n_threads)
for (int j = 0; j < n_atoms; j++) {
derivatives[j][0] = gradients_b[j][0].item<double>() * to_ang;
derivatives[j][1] = gradients_b[j][1].item<double>() * to_ang;
derivatives[j][2] = gradients_b[j][2].item<double>() * to_ang;
}
#pragma omp parallel for num_threads(n_threads)
for (int j = 0; j < n_atoms; j++) {
int index = atom_list_active[j];
setAtomsDerivatives(
getPntrToComponent(name_comp_b), index, derivatives[j]
);
}
}
}
int PytorchGNN::atomic_number_from_name(std::string name)
{
std::transform(
name.begin(),
name.end(),
name.begin(),
[](unsigned char c){return std::tolower(c);}
);
auto iter = std::find(periodic_table.begin(), periodic_table.end(), name);
if (iter == periodic_table.end())
plumed_merror(
"Can not find element name '" + name + "' from the periodic table!"
);
return std::distance(periodic_table.begin(), iter) + 1;
}
std::string PytorchGNN::model_summary(
std::string model_name, torch::jit::Module module, int level_max, int level
) {
std::stringstream ss;
std::string model_type = module.type()->name()->name();
ss << " (" << model_name << "): " << model_type;
if (module.named_children().size() != 0) {
if (level <= level_max) {
ss << " {\n";
for (const torch::jit::NameModule& s : module.named_children())
ss << torch::jit::jit_log_prefix(
" ",
model_summary(s.name, s.value, level_max, level + 1)
);
ss << " }\n";
} else {
ss << " { ... }";
}
} else {
ss << "\n";
}
return ss.str();
}
bool PytorchGNN::groups_have_intersection(void) {
std::vector<AtomNumber> intersections;
std::vector<AtomNumber> atom_list_a_copy(atom_list_a);
std::vector<AtomNumber> atom_list_b_copy(atom_list_b);
std::sort(atom_list_a_copy.begin(), atom_list_a_copy.end());
std::sort(atom_list_b_copy.begin(), atom_list_b_copy.end());
std::set_intersection(
atom_list_a_copy.begin(),
atom_list_a_copy.end(),
atom_list_b_copy.begin(),
atom_list_b_copy.end(),
back_inserter(intersections)
);
return intersections.size() > 0;
}
bool PytorchGNN::subgroup_is_in_group_a(void) {
std::vector<AtomNumber> atom_list_a_copy(atom_list_a);
std::vector<AtomNumber> atom_list_sub_a_copy(atom_list_sub_a);
for (auto atom_elt: atom_list_sub_a_copy)
if (
std::find(atom_list_a_copy.begin(),
atom_list_a_copy.end(), atom_elt) == atom_list_a_copy.end()
)
return false;
return true;
}
void PytorchGNN::find_active_atoms(int n_threads) {
if (atom_list_b.size() > 0) {
atom_list_active.clear();
std::vector<int> neighbors(neighbor_list->size());
#pragma omp parallel for num_threads(n_threads)
for (size_t i = 0; i < neighbor_list->size(); i++)
neighbors[i] = neighbor_list->getClosePair(i).second;
// TODO: make this faster
std::unordered_set<int> neighbors_set;
for (int i : neighbors)
neighbors_set.insert(i);
neighbors.assign(neighbors_set.begin(), neighbors_set.end());
// NOTE: the system atoms (atom_list_a) should always appear at the head of
// this list. Do NOT change the order!
for (size_t i = 0; i < atom_list_a.size(); i++)
atom_list_active.push_back(i);
// NOTE: the neighbors should be appended to the tail of this list.
for (size_t i = 0; i < neighbors.size(); i++)
atom_list_active.push_back(neighbors[i]);
} else if (atom_list_active.size() == 0) {
atom_list_active.clear();
for (size_t i = 0; i < atom_list_a.size(); i++)
atom_list_active.push_back(i);
}
}
void PytorchGNN::find_active_subgroup_atoms(void) {
atom_list_active_subgroup.clear();
// NOTE: since system atoms (atom_list_a) always appear at the head of the
// local indices, we simply find subsystem indices in atom_list_a.
for (auto atom_sub: atom_list_sub_a) {
int index = (int)std::distance(
atom_list_a.begin(),
find(atom_list_a.begin(), atom_list_a.end(), atom_sub)
);
atom_list_active_subgroup.push_back(index);
}
}
int PytorchGNN::get_number_of_parameters(void)
{
int n_parameters = 0;
for (auto p: model.parameters())
n_parameters += p.numel();
return n_parameters;
}
} // pytorch_gnn
} // colvar
} // PLMD
#endif // PLUMED_HAS_LIBTORCH
|