diff --git a/.github/workflows/test_cc.yml b/.github/workflows/test_cc.yml index 361b709704..233cb2f649 100644 --- a/.github/workflows/test_cc.yml +++ b/.github/workflows/test_cc.yml @@ -88,7 +88,7 @@ jobs: if: matrix.enable_paddle - run: | export LD_LIBRARY_PATH=${{ github.workspace }}/dp_test/lib:$LD_LIBRARY_PATH - source/install/retry_on_sigterm.sh 3 pytest --cov=deepmd source/lmp/tests + source/install/retry_on_sigterm.sh 3 source/install/pytest_with_junit.sh lammps pytest --cov=deepmd source/lmp/tests env: OMP_NUM_THREADS: 1 TF_INTRA_OP_PARALLELISM_THREADS: 1 @@ -103,7 +103,7 @@ jobs: # test ipi - run: | export PATH=${{ github.workspace }}/dp_test/bin:$PATH - pytest --cov=deepmd source/ipi/tests + source/install/pytest_with_junit.sh ipi pytest --cov=deepmd source/ipi/tests env: OMP_NUM_THREADS: 1 TF_INTRA_OP_PARALLELISM_THREADS: 1 @@ -119,6 +119,18 @@ jobs: continue-on-error: true with: use_oidc: true + - name: Upload C++ test reports + if: ${{ always() && hashFiles('source/build_tests/generator-reports/**', 'source/build_tests/gtest-reports/**', 'source/build_tests/pytest-reports/**') != '' }} + uses: actions/upload-artifact@v7 + continue-on-error: true + with: + name: cpp-cpu-tf-${{ matrix.enable_tensorflow }}-pt-${{ matrix.enable_pytorch }}-pd-${{ matrix.enable_paddle }}-lsan-${{ matrix.check_memleak }} + path: | + source/build_tests/generator-reports/** + source/build_tests/gtest-reports/** + source/build_tests/pytest-reports/** + if-no-files-found: ignore + retention-days: 14 permissions: id-token: write pass: diff --git a/.github/workflows/test_cuda.yml b/.github/workflows/test_cuda.yml index c72d01f06a..91ede5d975 100644 --- a/.github/workflows/test_cuda.yml +++ b/.github/workflows/test_cuda.yml @@ -81,7 +81,11 @@ jobs: - name: Verify float64 CUDA kernels are enabled run: | python -c "import torch; import deepmd.pt.cxx_op; from deepmd.pt_expt.kernels.cuda.dpa4.so2_conv_train import op_available, float64_available; assert torch.cuda.is_available(); assert op_available(); assert float64_available() is True" - - run: python -m pytest ${{ matrix.pytest-args }} --ignore=source/tests/pd + - name: Test Python + run: >- + python -m pytest ${{ matrix.pytest-args }} --ignore=source/tests/pd + --junitxml=test-reports/python-${{ matrix.shard }}.xml + -o junit_duration_report=total env: NUM_WORKERS: 0 CUDA_VISIBLE_DEVICES: 0 @@ -89,6 +93,15 @@ jobs: XLA_PYTHON_CLIENT_PREALLOCATE: false XLA_PYTHON_CLIENT_ALLOCATOR: platform FLAGS_use_stride_compute_kernel: 0 + - name: Upload Python test reports + if: ${{ always() && hashFiles('test-reports/python-*.xml') != '' }} + uses: actions/upload-artifact@v7 + continue-on-error: true + with: + name: python-cuda-${{ matrix.shard }} + path: test-reports/python-*.xml + if-no-files-found: ignore + retention-days: 14 test_cc: name: Test ${{ matrix.name }} on CUDA @@ -222,8 +235,8 @@ jobs: run: | export LD_LIBRARY_PATH=$MPI_HOME/lib:$CUDA_PATH/lib64:/usr/lib/x86_64-linux-gnu/:$GITHUB_WORKSPACE/dp_test/lib:$LD_LIBRARY_PATH export PATH=$GITHUB_WORKSPACE/dp_test/bin:$PATH - python -m pytest -s source/lmp/tests || (cat log.lammps && exit 1) - python -m pytest source/ipi/tests + source/install/pytest_with_junit.sh lammps python -m pytest -s source/lmp/tests || (cat log.lammps && exit 1) + source/install/pytest_with_junit.sh ipi python -m pytest source/ipi/tests env: OMP_NUM_THREADS: 1 TF_INTRA_OP_PARALLELISM_THREADS: 1 @@ -232,6 +245,19 @@ jobs: DPA4SPIN_LMP_REQUIRED: 1 CUDA_VISIBLE_DEVICES: 0 ENABLE_PADDLE: 0 + - name: Upload C++ test reports + if: ${{ always() && hashFiles('source/build_tests/generator-reports/**', 'source/build_tests/gtest-reports/**', 'source/build_tests/pytest-reports/**', 'source/build_lammps_kokkos/test-reports/**') != '' }} + uses: actions/upload-artifact@v7 + continue-on-error: true + with: + name: cpp-cuda-${{ matrix.suite }} + path: | + source/build_tests/generator-reports/** + source/build_tests/gtest-reports/** + source/build_tests/pytest-reports/** + source/build_lammps_kokkos/test-reports/** + if-no-files-found: ignore + retention-days: 14 pass: name: Pass testing on CUDA needs: [test_python, test_cc] diff --git a/source/api_c/tests/test_deeppot_universal.cc b/source/api_c/tests/test_deeppot_universal.cc index 1547ef4350..a5ba55f7c5 100644 --- a/source/api_c/tests/test_deeppot_universal.cc +++ b/source/api_c/tests/test_deeppot_universal.cc @@ -46,7 +46,11 @@ class UniversalDeepPotCTest : public ::testing::TestWithParam { } ASSERT_TRUE(path_exists(param.model_path)) << "Model artifact is not available: " << param.model_path; + } + // Call after capability skips so unsupported cases do not load a model. + void InitModel() { + const auto& param = GetParam(); std::string model_path = param.model_path; if (param.convert_pbtxt) { converted_model = "deeppot_c_universal_" + param.name + ".pb"; @@ -92,7 +96,11 @@ class FParamAParamDeepPotCTest loaded_ref = load_fparam_ref(param.ref_path); ref = &loaded_ref; } + } + // Call after capability skips so unsupported cases do not load a model. + void InitModel() { + const auto& param = GetParam(); std::string model_path = param.model_path; if (param.convert_pbtxt) { converted_model = "deeppot_c_fparam_aparam_" + param.name + ".pb"; @@ -116,6 +124,7 @@ class FParamAParamDeepPotCTest }; TEST_P(UniversalDeepPotCTest, Metadata) { + ASSERT_NO_FATAL_FAILURE(InitModel()); const auto& ref = *GetParam().ref; EXPECT_DOUBLE_EQ(DP_DeepPotGetCutoff(dp), ref.cutoff); @@ -347,6 +356,7 @@ void check_fparam_compute_float(DP_DeepPot* dp, } TEST_P(UniversalDeepPotCTest, ComputeDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_double(dp, *GetParam().ref, GetParam().double_tol); } @@ -355,10 +365,12 @@ TEST_P(UniversalDeepPotCTest, ComputeFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_float(dp, *GetParam().ref, GetParam().float_tol); } TEST_P(UniversalDeepPotCTest, ComputeLegacyDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); const std::vector& box = deepmd_test::deeppot_box(); check_compute_legacy_double(dp, *GetParam().ref, box.data(), GetParam().double_tol); @@ -369,6 +381,7 @@ TEST_P(UniversalDeepPotCTest, ComputeLegacyFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); const std::vector& box_double = deepmd_test::deeppot_box(); const std::vector box(box_double.begin(), box_double.end()); check_compute_legacy_float(dp, *GetParam().ref, box.data(), @@ -380,6 +393,7 @@ TEST_P(UniversalDeepPotCTest, ComputeLegacyNoPbcDouble) { GTEST_SKIP() << backend_name(GetParam().backend) << " NoPBC reference is not available."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_legacy_double(dp, *GetParam().no_pbc_ref, nullptr, GetParam().double_tol); } @@ -393,17 +407,20 @@ TEST_P(UniversalDeepPotCTest, ComputeLegacyNoPbcFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " NoPBC reference is not available."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_legacy_float(dp, *GetParam().no_pbc_ref, nullptr, GetParam().float_tol); } TEST_P(FParamAParamDeepPotCTest, Metadata) { + ASSERT_NO_FATAL_FAILURE(InitModel()); EXPECT_EQ(DP_DeepPotGetDimFParam(dp), 1); EXPECT_EQ(DP_DeepPotGetDimAParam(dp), 1); EXPECT_FALSE(DP_DeepPotHasDefaultFParam(dp)); } TEST_P(FParamAParamDeepPotCTest, ComputeDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_compute_double(dp, *ref, GetParam().double_tol); } @@ -412,6 +429,7 @@ TEST_P(FParamAParamDeepPotCTest, ComputeFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_compute_float(dp, *ref, GetParam().float_tol); } diff --git a/source/api_cc/tests/test_deeppot_universal.cc b/source/api_cc/tests/test_deeppot_universal.cc index 5ee6e59471..7f76189f3f 100644 --- a/source/api_cc/tests/test_deeppot_universal.cc +++ b/source/api_cc/tests/test_deeppot_universal.cc @@ -410,7 +410,11 @@ class UniversalDeepPotTest : public ::testing::TestWithParam { } ASSERT_TRUE(path_exists(param.model_path)) << "Model artifact is not available: " << param.model_path; + } + // Call after capability skips so unsupported cases do not load a model. + void InitModel() { + const auto& param = GetParam(); std::string model_path = param.model_path; if (param.convert_pbtxt) { converted_model = "deeppot_universal_" + param.name + ".pb"; @@ -475,7 +479,11 @@ class VariantDeepPotTest : public ::testing::TestWithParam { no_pbc_ref = &loaded_no_pbc_ref; } } + } + // Call after capability skips so unsupported cases do not load a model. + void InitModel() { + const auto& param = GetParam(); std::string model_path = param.model_path; if (param.convert_pbtxt) { converted_model = "deeppot_variant_" + param.name + ".pb"; @@ -515,7 +523,11 @@ class FParamAParamDeepPotTest loaded_ref = load_fparam_ref(param.ref_path); ref = &loaded_ref; } + } + // Call after capability skips so unsupported cases do not load a model. + void InitModel() { + const auto& param = GetParam(); std::string model_path = param.model_path; if (param.convert_pbtxt) { converted_model = "deeppot_fparam_aparam_" + param.name + ".pb"; @@ -552,11 +564,14 @@ class DefaultFParamDeepPotTest ref = load_fparam_ref(param.ref_path); override_ref = load_expected_ref(param.ref_path, "override"); ref.has_default_fparam = true; - dp.init(param.model_path); } + + // Keep initialization outside EXPECT_THROW so load errors cannot pass a test. + void InitModel() { dp.init(GetParam().model_path); } }; TEST_P(UniversalDeepPotTest, Metadata) { + ASSERT_NO_FATAL_FAILURE(InitModel()); const auto& ref = *GetParam().ref; std::string type_map; @@ -1345,6 +1360,7 @@ void check_fparam_lmp_nlist(deepmd::DeepPot& dp, } TEST_P(UniversalDeepPotTest, ComputeDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_atomic(dp, *GetParam().ref, GetParam().double_tol); } @@ -1353,10 +1369,12 @@ TEST_P(UniversalDeepPotTest, ComputeFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_atomic(dp, *GetParam().ref, GetParam().float_tol); } TEST_P(UniversalDeepPotTest, ComputeSimpleDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_simple(dp, *GetParam().ref, GetParam().double_tol); } @@ -1365,10 +1383,12 @@ TEST_P(UniversalDeepPotTest, ComputeSimpleFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_simple(dp, *GetParam().ref, GetParam().float_tol); } TEST_P(UniversalDeepPotTest, FiniteDifferenceDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_finite_difference(dp); } @@ -1377,10 +1397,12 @@ TEST_P(UniversalDeepPotTest, FiniteDifferenceFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_finite_difference(dp); } TEST_P(UniversalDeepPotTest, LmpNlistDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist(dp, *GetParam().ref, GetParam().double_tol, 1.0, GetParam().supports_lmp_nlist_mapping); } @@ -1390,11 +1412,13 @@ TEST_P(UniversalDeepPotTest, LmpNlistFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist(dp, *GetParam().ref, GetParam().float_tol, 1.0, GetParam().supports_lmp_nlist_mapping); } TEST_P(UniversalDeepPotTest, LmpNlistAtomicDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_atomic(dp, *GetParam().ref, GetParam().double_tol, GetParam().supports_lmp_nlist_mapping); } @@ -1404,11 +1428,13 @@ TEST_P(UniversalDeepPotTest, LmpNlistAtomicFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_atomic(dp, *GetParam().ref, GetParam().float_tol, GetParam().supports_lmp_nlist_mapping); } TEST_P(UniversalDeepPotTest, LmpNlistDoubleCutoffTwice) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist(dp, *GetParam().ref, GetParam().double_tol, 2.0, GetParam().supports_lmp_nlist_mapping); } @@ -1418,11 +1444,13 @@ TEST_P(UniversalDeepPotTest, LmpNlistFloatCutoffTwice) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist(dp, *GetParam().ref, GetParam().float_tol, 2.0, GetParam().supports_lmp_nlist_mapping); } TEST_P(UniversalDeepPotTest, LmpNlistSkinBelowModelWidthDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_skin_below_model_width( dp, *GetParam().ref, GetParam().double_tol, GetParam().supports_lmp_nlist_mapping); @@ -1433,12 +1461,14 @@ TEST_P(UniversalDeepPotTest, LmpNlistSkinBelowModelWidthFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_skin_below_model_width( dp, *GetParam().ref, GetParam().float_tol, GetParam().supports_lmp_nlist_mapping); } TEST_P(UniversalDeepPotTest, LmpNlistTypeSelDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_type_sel(dp, *GetParam().ref, GetParam().double_tol, false, GetParam().supports_lmp_nlist_mapping); @@ -1449,11 +1479,13 @@ TEST_P(UniversalDeepPotTest, LmpNlistTypeSelFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_type_sel(dp, *GetParam().ref, GetParam().float_tol, false, GetParam().supports_lmp_nlist_mapping); } TEST_P(UniversalDeepPotTest, LmpNlistTypeSelAtomicDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_type_sel(dp, *GetParam().ref, GetParam().double_tol, true, GetParam().supports_lmp_nlist_mapping); } @@ -1463,6 +1495,7 @@ TEST_P(UniversalDeepPotTest, LmpNlistTypeSelAtomicFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_type_sel(dp, *GetParam().ref, GetParam().float_tol, true, GetParam().supports_lmp_nlist_mapping); } @@ -1472,6 +1505,7 @@ TEST_P(UniversalDeepPotTest, ComputeNoPbcDouble) { GTEST_SKIP() << backend_name(GetParam().backend) << " NoPBC reference is not available."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_atomic(dp, *GetParam().no_pbc_ref, GetParam().double_tol, false); } @@ -1485,6 +1519,7 @@ TEST_P(UniversalDeepPotTest, ComputeNoPbcFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " NoPBC reference is not available."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_atomic(dp, *GetParam().no_pbc_ref, GetParam().float_tol, false); } @@ -1494,6 +1529,7 @@ TEST_P(UniversalDeepPotTest, ComputeSimpleNoPbcDouble) { GTEST_SKIP() << backend_name(GetParam().backend) << " NoPBC reference is not available."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_simple(dp, *GetParam().no_pbc_ref, GetParam().double_tol, false); } @@ -1507,17 +1543,22 @@ TEST_P(UniversalDeepPotTest, ComputeSimpleNoPbcFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " NoPBC reference is not available."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_simple(dp, *GetParam().no_pbc_ref, GetParam().float_tol, false); } -TEST_P(UniversalDeepPotTest, PrintSummary) { dp.print_summary(""); } +TEST_P(UniversalDeepPotTest, PrintSummary) { + ASSERT_NO_FATAL_FAILURE(InitModel()); + dp.print_summary(""); +} TEST_P(UniversalDeepPotTest, NFramesComputeDouble) { if (!GetParam().supports_nframes) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_frames_simple(dp, *GetParam().ref, GetParam().double_tol, 2); } @@ -1531,6 +1572,7 @@ TEST_P(UniversalDeepPotTest, NFramesComputeFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_frames_simple(dp, *GetParam().ref, GetParam().float_tol, 2); } @@ -1540,6 +1582,7 @@ TEST_P(UniversalDeepPotTest, NFramesComputeAtomicDouble) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_frames_atomic(dp, *GetParam().ref, GetParam().double_tol, 2); } @@ -1553,6 +1596,7 @@ TEST_P(UniversalDeepPotTest, NFramesComputeAtomicFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_frames_atomic(dp, *GetParam().ref, GetParam().float_tol, 2); } @@ -1562,6 +1606,7 @@ TEST_P(UniversalDeepPotTest, NFramesLmpNlistDouble) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_frames(dp, *GetParam().ref, GetParam().double_tol, 2, false, 1.0, GetParam().supports_lmp_nlist_mapping); @@ -1576,6 +1621,7 @@ TEST_P(UniversalDeepPotTest, NFramesLmpNlistFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_frames(dp, *GetParam().ref, GetParam().float_tol, 2, false, 1.0, GetParam().supports_lmp_nlist_mapping); @@ -1586,6 +1632,7 @@ TEST_P(UniversalDeepPotTest, NFramesLmpNlistAtomicDouble) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_frames(dp, *GetParam().ref, GetParam().double_tol, 2, true, 1.0, GetParam().supports_lmp_nlist_mapping); @@ -1600,6 +1647,7 @@ TEST_P(UniversalDeepPotTest, NFramesLmpNlistAtomicFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_frames(dp, *GetParam().ref, GetParam().float_tol, 2, true, 1.0, GetParam().supports_lmp_nlist_mapping); @@ -1610,6 +1658,7 @@ TEST_P(UniversalDeepPotTest, NFramesLmpNlistDoubleCutoffTwice) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_frames(dp, *GetParam().ref, GetParam().double_tol, 2, false, 2.0, GetParam().supports_lmp_nlist_mapping); @@ -1624,6 +1673,7 @@ TEST_P(UniversalDeepPotTest, NFramesLmpNlistFloatCutoffTwice) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_frames(dp, *GetParam().ref, GetParam().float_tol, 2, false, 2.0, GetParam().supports_lmp_nlist_mapping); @@ -1634,6 +1684,7 @@ TEST_P(UniversalDeepPotTest, NFramesLmpNlistTypeSelDouble) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); const bool set_mapping = GetParam().supports_lmp_nlist_mapping; check_lmp_nlist_type_sel_frames( dp, *GetParam().ref, GetParam().double_tol, 2, false, set_mapping); @@ -1648,6 +1699,7 @@ TEST_P(UniversalDeepPotTest, NFramesLmpNlistTypeSelFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); const bool set_mapping = GetParam().supports_lmp_nlist_mapping; check_lmp_nlist_type_sel_frames( dp, *GetParam().ref, GetParam().float_tol, 2, false, set_mapping); @@ -1658,6 +1710,7 @@ TEST_P(UniversalDeepPotTest, NFramesLmpNlistTypeSelAtomicDouble) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); const bool set_mapping = GetParam().supports_lmp_nlist_mapping; check_lmp_nlist_type_sel_frames( dp, *GetParam().ref, GetParam().double_tol, 2, true, set_mapping); @@ -1672,6 +1725,7 @@ TEST_P(UniversalDeepPotTest, NFramesLmpNlistTypeSelAtomicFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " nframes coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); const bool set_mapping = GetParam().supports_lmp_nlist_mapping; check_lmp_nlist_type_sel_frames( dp, *GetParam().ref, GetParam().float_tol, 2, true, set_mapping); @@ -1686,6 +1740,7 @@ TEST_P(UniversalDeepPotTest, NFramesComputeNoPbcDouble) { GTEST_SKIP() << backend_name(GetParam().backend) << " NoPBC reference is not available."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_frames_simple(dp, *GetParam().no_pbc_ref, GetParam().double_tol, 2, false); } @@ -1703,11 +1758,13 @@ TEST_P(UniversalDeepPotTest, NFramesComputeNoPbcFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " NoPBC reference is not available."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_frames_simple(dp, *GetParam().no_pbc_ref, GetParam().float_tol, 2, false); } TEST_P(VariantDeepPotTest, ComputeDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_atomic(dp, *ref, GetParam().double_tol); } @@ -1716,10 +1773,12 @@ TEST_P(VariantDeepPotTest, ComputeFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_atomic(dp, *ref, GetParam().float_tol); } TEST_P(VariantDeepPotTest, ComputeSimpleDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_simple(dp, *ref, GetParam().double_tol); } @@ -1728,6 +1787,7 @@ TEST_P(VariantDeepPotTest, ComputeSimpleFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_simple(dp, *ref, GetParam().float_tol); } @@ -1736,6 +1796,7 @@ TEST_P(VariantDeepPotTest, FiniteDifferenceDouble) { GTEST_SKIP() << GetParam().name << " finite-difference coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_finite_difference(dp); } @@ -1748,6 +1809,7 @@ TEST_P(VariantDeepPotTest, FiniteDifferenceFloat) { GTEST_SKIP() << GetParam().name << " finite-difference coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); // DPA4 computes in reduced precision (same established bound for both the // dense-nlist and graph lowers -- they share the same descriptor/fitting // math, only the lower schema differs). @@ -1763,6 +1825,7 @@ TEST_P(VariantDeepPotTest, LmpNlistDouble) { if (!GetParam().supports_lmp_nlist) { GTEST_SKIP() << GetParam().name << " LAMMPS nlist coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist(dp, *ref, GetParam().double_tol); } @@ -1774,6 +1837,7 @@ TEST_P(VariantDeepPotTest, LmpNlistFloat) { if (!GetParam().supports_lmp_nlist) { GTEST_SKIP() << GetParam().name << " LAMMPS nlist coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist(dp, *ref, GetParam().float_tol); } @@ -1782,6 +1846,7 @@ TEST_P(VariantDeepPotTest, LmpNlistAtomicDouble) { GTEST_SKIP() << GetParam().name << " atomic LAMMPS nlist coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_atomic(dp, *ref, GetParam().double_tol); } @@ -1794,6 +1859,7 @@ TEST_P(VariantDeepPotTest, LmpNlistAtomicFloat) { GTEST_SKIP() << GetParam().name << " atomic LAMMPS nlist coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_atomic(dp, *ref, GetParam().float_tol); } @@ -1802,6 +1868,7 @@ TEST_P(VariantDeepPotTest, LmpNlistDoubleCutoffTwice) { GTEST_SKIP() << GetParam().name << " doubled-cutoff LAMMPS nlist coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist(dp, *ref, GetParam().double_tol, 2.0); } @@ -1814,6 +1881,7 @@ TEST_P(VariantDeepPotTest, LmpNlistFloatCutoffTwice) { GTEST_SKIP() << GetParam().name << " doubled-cutoff LAMMPS nlist coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist(dp, *ref, GetParam().float_tol, 2.0); } @@ -1822,6 +1890,7 @@ TEST_P(VariantDeepPotTest, LmpNlistTypeSelDouble) { GTEST_SKIP() << GetParam().name << " type-selected LAMMPS nlist coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_type_sel(dp, *ref, GetParam().double_tol, false); } @@ -1834,6 +1903,7 @@ TEST_P(VariantDeepPotTest, LmpNlistTypeSelFloat) { GTEST_SKIP() << GetParam().name << " type-selected LAMMPS nlist coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_lmp_nlist_type_sel(dp, *ref, GetParam().float_tol, false); } @@ -1841,6 +1911,7 @@ TEST_P(VariantDeepPotTest, PrintSummary) { if (!GetParam().supports_print_summary) { GTEST_SKIP() << GetParam().name << " summary coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); dp.print_summary(""); } @@ -1848,6 +1919,7 @@ TEST_P(VariantDeepPotTest, ComputeSimpleNoPbcDouble) { if (!GetParam().supports_no_pbc_simple) { GTEST_SKIP() << GetParam().name << " NoPBC coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_simple(dp, *no_pbc_ref, GetParam().double_tol, false); } @@ -1859,6 +1931,7 @@ TEST_P(VariantDeepPotTest, ComputeSimpleNoPbcFloat) { if (!GetParam().supports_no_pbc_simple) { GTEST_SKIP() << GetParam().name << " NoPBC coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_simple(dp, *no_pbc_ref, GetParam().float_tol, false); } @@ -1866,6 +1939,7 @@ TEST_P(VariantDeepPotTest, ComputeNoPbcDouble) { if (!GetParam().supports_no_pbc_atomic) { GTEST_SKIP() << GetParam().name << " atomic NoPBC coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_atomic(dp, *no_pbc_ref, GetParam().double_tol, false); } @@ -1877,6 +1951,7 @@ TEST_P(VariantDeepPotTest, ComputeNoPbcFloat) { if (!GetParam().supports_no_pbc_atomic) { GTEST_SKIP() << GetParam().name << " atomic NoPBC coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_compute_atomic(dp, *no_pbc_ref, GetParam().float_tol, false); } @@ -1885,6 +1960,7 @@ TEST_P(VariantDeepPotTest, NoPbcLmpNlistDouble) { GTEST_SKIP() << GetParam().name << " NoPBC LAMMPS nlist coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_no_pbc_lmp_nlist(dp, *no_pbc_ref, GetParam().double_tol, false); } @@ -1897,6 +1973,7 @@ TEST_P(VariantDeepPotTest, NoPbcLmpNlistFloat) { GTEST_SKIP() << GetParam().name << " NoPBC LAMMPS nlist coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_no_pbc_lmp_nlist(dp, *no_pbc_ref, GetParam().float_tol, false); } @@ -1905,6 +1982,7 @@ TEST_P(VariantDeepPotTest, NoPbcLmpNlistAtomicDouble) { GTEST_SKIP() << GetParam().name << " atomic NoPBC LAMMPS nlist coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_no_pbc_lmp_nlist(dp, *no_pbc_ref, GetParam().double_tol, true); } @@ -1917,10 +1995,12 @@ TEST_P(VariantDeepPotTest, NoPbcLmpNlistAtomicFloat) { GTEST_SKIP() << GetParam().name << " atomic NoPBC LAMMPS nlist coverage is not enabled."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_no_pbc_lmp_nlist(dp, *no_pbc_ref, GetParam().float_tol, true); } TEST_P(FParamAParamDeepPotTest, Metadata) { + ASSERT_NO_FATAL_FAILURE(InitModel()); EXPECT_EQ(dp.dim_fparam(), 1); EXPECT_EQ(dp.dim_aparam(), 1); EXPECT_FALSE(dp.has_default_fparam()); @@ -1930,6 +2010,7 @@ TEST_P(FParamAParamDeepPotTest, JAXRejectsMissingRequiredFParam) { if (GetParam().backend != Backend::JAX) { GTEST_SKIP() << "This regression targets JAX SavedModel tensor inputs."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); const std::vector coord = deepmd_test::deeppot_coord(); const std::vector atype = deepmd_test::fparam_aparam_atype(); const std::vector box = deepmd_test::deeppot_box(); @@ -1943,6 +2024,7 @@ TEST_P(FParamAParamDeepPotTest, JAXRejectsMissingRequiredFParam) { } TEST_P(FParamAParamDeepPotTest, ComputeDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_compute_atomic(dp, *ref, GetParam().double_tol, deepmd_test::fparam_value()); } @@ -1952,11 +2034,13 @@ TEST_P(FParamAParamDeepPotTest, ComputeFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_compute_atomic(dp, *ref, GetParam().float_tol, deepmd_test::fparam_value()); } TEST_P(FParamAParamDeepPotTest, ComputeSimpleDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_compute_simple(dp, *ref, GetParam().double_tol, deepmd_test::fparam_value()); } @@ -1966,11 +2050,13 @@ TEST_P(FParamAParamDeepPotTest, ComputeSimpleFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_compute_simple(dp, *ref, GetParam().float_tol, deepmd_test::fparam_value()); } TEST_P(FParamAParamDeepPotTest, LmpNlistDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_lmp_nlist(dp, *ref, GetParam().double_tol, deepmd_test::fparam_value(), false); } @@ -1980,11 +2066,13 @@ TEST_P(FParamAParamDeepPotTest, LmpNlistFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_lmp_nlist(dp, *ref, GetParam().float_tol, deepmd_test::fparam_value(), false); } TEST_P(FParamAParamDeepPotTest, LmpNlistAtomicDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_lmp_nlist(dp, *ref, GetParam().double_tol, deepmd_test::fparam_value(), true); } @@ -1994,11 +2082,13 @@ TEST_P(FParamAParamDeepPotTest, LmpNlistAtomicFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_lmp_nlist(dp, *ref, GetParam().float_tol, deepmd_test::fparam_value(), true); } TEST_P(FParamAParamDeepPotTest, LmpNlistDoubleCutoffTwice) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_lmp_nlist(dp, *ref, GetParam().double_tol, deepmd_test::fparam_value(), false, 2.0); } @@ -2008,17 +2098,20 @@ TEST_P(FParamAParamDeepPotTest, LmpNlistFloatCutoffTwice) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_lmp_nlist(dp, *ref, GetParam().float_tol, deepmd_test::fparam_value(), false, 2.0); } TEST_P(DefaultFParamDeepPotTest, Metadata) { + ASSERT_NO_FATAL_FAILURE(InitModel()); EXPECT_EQ(dp.dim_fparam(), 1); EXPECT_EQ(dp.dim_aparam(), 1); EXPECT_TRUE(dp.has_default_fparam()); } TEST_P(DefaultFParamDeepPotTest, ComputeWithEmptyFParamDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_compute_simple(dp, ref, GetParam().double_tol, {}); } @@ -2027,10 +2120,12 @@ TEST_P(DefaultFParamDeepPotTest, ComputeWithEmptyFParamFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_compute_simple(dp, ref, GetParam().float_tol, {}); } TEST_P(DefaultFParamDeepPotTest, ComputeWithExplicitFParamDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_compute_simple(dp, override_ref, GetParam().double_tol, override_fparam); } @@ -2040,11 +2135,13 @@ TEST_P(DefaultFParamDeepPotTest, ComputeWithExplicitFParamFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_compute_simple(dp, override_ref, GetParam().float_tol, override_fparam); } TEST_P(DefaultFParamDeepPotTest, LmpNlistWithEmptyFParamDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_lmp_nlist(dp, ref, GetParam().double_tol, {}, false, 1.0, 1); } @@ -2054,11 +2151,13 @@ TEST_P(DefaultFParamDeepPotTest, LmpNlistWithEmptyFParamFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_lmp_nlist(dp, ref, GetParam().float_tol, {}, false, 1.0, 1); } TEST_P(DefaultFParamDeepPotTest, LmpNlistWithExplicitFParamDouble) { + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_lmp_nlist(dp, override_ref, GetParam().double_tol, override_fparam, false, 1.0, 1); } @@ -2068,6 +2167,7 @@ TEST_P(DefaultFParamDeepPotTest, LmpNlistWithExplicitFParamFloat) { GTEST_SKIP() << backend_name(GetParam().backend) << " does not provide float inference coverage."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); check_fparam_lmp_nlist(dp, override_ref, GetParam().float_tol, override_fparam, false, 1.0, 1); } @@ -2076,6 +2176,7 @@ TEST_P(DefaultFParamDeepPotTest, JAXBroadcastsFParamAcrossFrames) { if (GetParam().backend != Backend::JAX) { GTEST_SKIP() << "This regression targets JAX SavedModel tensor inputs."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); const int nframes = 2; const std::vector coord = repeat_values(deepmd_test::deeppot_coord(), nframes); @@ -2117,6 +2218,7 @@ TEST_P(DefaultFParamDeepPotTest, JAXRejectsInvalidFParamSize) { if (GetParam().backend != Backend::JAX) { GTEST_SKIP() << "This regression targets JAX SavedModel tensor inputs."; } + ASSERT_NO_FATAL_FAILURE(InitModel()); const std::vector coord = deepmd_test::deeppot_coord(); const std::vector atype = deepmd_test::fparam_aparam_atype(); const std::vector box = deepmd_test::deeppot_box(); diff --git a/source/install/pytest_with_junit.sh b/source/install/pytest_with_junit.sh new file mode 100755 index 0000000000..65c197463c --- /dev/null +++ b/source/install/pytest_with_junit.sh @@ -0,0 +1,17 @@ +#!/bin/bash +set -euo pipefail + +# Keep every pytest process separate, including retry_on_sigterm.sh attempts. +# exec preserves the test command's exit status and signal handling. +if [[ $# -lt 2 ]]; then + echo "Usage: $0 REPORT_NAME COMMAND [ARG ...]" >&2 + exit 2 +fi +REPORT_NAME=$1 +shift +SCRIPT_PATH=$(dirname "$(realpath -s "$0")") +REPO_ROOT=$(realpath "${SCRIPT_PATH}/../..") +REPORT_ROOT=${REPO_ROOT}/source/build_tests/pytest-reports +mkdir -p "${REPORT_ROOT}" +REPORT_DIR=$(mktemp -d "${REPORT_ROOT}/run.XXXXXX") +exec "$@" --junitxml="${REPORT_DIR}/${REPORT_NAME}.xml" diff --git a/source/install/test_cc_local.sh b/source/install/test_cc_local.sh index b8fe41b5ae..0c9c07178c 100755 --- a/source/install/test_cc_local.sh +++ b/source/install/test_cc_local.sh @@ -93,6 +93,26 @@ if [ "$MODE" = "--build-only" ]; then exit 0 fi if [ "${ENABLE_PYTORCH:-TRUE}" == "TRUE" ]; then + # Keep one timing record per generator, including successful runs. Each + # invocation owns its directory and each parallel script owns its file. + mkdir -p "${BUILD_TMP_DIR}/generator-reports" + GENERATOR_REPORT_DIR=$(mktemp -d "${BUILD_TMP_DIR}/generator-reports/run.XXXXXX") + run_generator_named() { + local name=$1 + shift + local start=$SECONDS status=0 + if env ${_GEN_ENV} python -u "$@"; then + status=0 + else + status=$? + fi + printf 'generator\tseconds\texit_status\n%s\t%s\t%s\n' \ + "$name" "$((SECONDS - start))" "$status" >"${GENERATOR_REPORT_DIR}/${name}.tsv" + return "$status" + } + run_generator() { + run_generator_named "$(basename "${1%.py}")" "$@" + } # When the build uses -fsanitize=leak, the custom op .so requires the LSAN # runtime to be preloaded (otherwise dlopen fails). We disable leak detection # in the gen scripts to avoid false reports from torch/paddle internals. @@ -115,80 +135,89 @@ if [ "${ENABLE_PYTORCH:-TRUE}" == "TRUE" ]; then rm -f ${INFER_SCRIPT_PATH}/deeppot_dpa4c_long_range*.pt2 \ ${INFER_SCRIPT_PATH}/deeppot_dpa4c_long_range*.pte \ ${INFER_SCRIPT_PATH}/deeppot_dpa4c_long_range*.expected - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa4c_long_range.py + run_generator ${INFER_SCRIPT_PATH}/gen_dpa4c_long_range.py --compressed-only exit 0 fi # Remove stale generated model files so they can't be accidentally reused # if gen scripts change format or the code version changes. rm -f ${INFER_SCRIPT_PATH}/*.pt2 ${INFER_SCRIPT_PATH}/*.pte - # Run gen scripts in parallel for faster model generation. + # Refill the first three generator slots instead of leaving two idle + # behind the long DPA2 export. DPA3 and DPA4 have no input dependency + # on these generators and write distinct fixtures. Keep at most three + # processes in this phase; do not add both on top of the initial batch. # Wait on each PID separately so any failure is caught by set -e. - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_sea.py & + run_generator ${INFER_SCRIPT_PATH}/gen_sea.py & PID1=$! - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa1.py & + run_generator ${INFER_SCRIPT_PATH}/gen_dpa1.py & PID2=$! - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa2.py & + run_generator ${INFER_SCRIPT_PATH}/gen_dpa2.py & PID3=$! wait $PID1 + run_generator ${INFER_SCRIPT_PATH}/gen_dpa4.py & + PID9=$! wait $PID2 + run_generator ${INFER_SCRIPT_PATH}/gen_dpa3.py & + PID4=$! wait $PID3 + wait $PID9 + wait $PID4 - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa3.py & - PID4=$! - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_fparam_aparam.py & + run_generator ${INFER_SCRIPT_PATH}/gen_fparam_aparam.py & PID5=$! - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_model_devi.py & + run_generator ${INFER_SCRIPT_PATH}/gen_model_devi.py & PID6=$! - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_chg_spin.py & + run_generator ${INFER_SCRIPT_PATH}/gen_chg_spin.py & PID9=$! - wait $PID4 + # DPA1 completed above; its archive-reuse consumer needs no other + # producer. Fill the fourth slot freed by moving DPA3 into the first phase. + run_generator ${INFER_SCRIPT_PATH}/gen_dpa1_pairexcl.py --reuse-dpa1 & + PID10=$! wait $PID5 wait $PID6 wait $PID9 - - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa4.py & - PID9=$! - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa1_pairexcl.py & - PID10=$! - wait $PID9 wait $PID10 - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_spin.py & + # Keep both producers parallel, but compile the shared DPA1 spin model in + # model-devi's shorter branch, rather than repeating it on gen_spin's + # critical path. Finalize only after both producers succeed. Distinct + # report names retain both phases without overwriting their timings. + run_generator_named gen_spin_dpa3 ${INFER_SCRIPT_PATH}/gen_spin.py --dpa3-only & PID7=$! - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_spin_model_devi.py & + run_generator ${INFER_SCRIPT_PATH}/gen_spin_model_devi.py & PID8=$! wait $PID7 wait $PID8 + run_generator_named gen_spin_reuse ${INFER_SCRIPT_PATH}/gen_spin.py --reuse-model-devi # Copies of the multi-rank DPA3 archives of gen_dpa3.py and gen_spin.py # whose nested with-comm artifact is corrupt; without them the load-failure # cases of the pt_expt backends (test_with_comm_load_failure_ptexpt.cc) # skip. - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_corrupt_with_comm.py + run_generator ${INFER_SCRIPT_PATH}/gen_corrupt_with_comm.py # Native-spin DPA4 graph archives (baseline + model-level pair # exclusion). Without this the whole native-spin graph C++ suite # GTEST_SKIPs on the missing fixture, which is how a dead # applyPairExclusion seam in DeepSpinPTExpt went unnoticed. - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa4_spin.py & + run_generator ${INFER_SCRIPT_PATH}/gen_dpa4_spin.py & PID11=$! # DPA4 + analytical ZBL bridging: a linear COMPOSITION on the graph # lower, which no other C++ fixture covers. - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa4_zbl.py & + run_generator ${INFER_SCRIPT_PATH}/gen_dpa4_zbl.py & PID12=$! # Native-spin DPA4 + charge-spin FiLM: the ONLY fixture with both # is_spin=true and dim_chg_spin>0, i.e. the only one on which the # runtime charge_spin argument of DeepSpin::compute is not inert. - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa4_spin_chgspin.py & + run_generator ${INFER_SCRIPT_PATH}/gen_dpa4_spin_chgspin.py & PID13=$! # Native-spin DPA4 + ZBL bridging COMBINED: spin reaching a linear - # composition, and the only fixture pinning that a bridged model - # exports NO with-comm artifact (single-rank only by construction). - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa4_spin_zbl.py & + # composition, including the source-freeze gate's cross-rank exchange + # through the nested with-comm artifact. + run_generator ${INFER_SCRIPT_PATH}/gen_dpa4_spin_zbl.py & PID14=$! # Minimal native-spin DPA4C for LAMMPS pair_style dpa4spin (no # fparam/aparam/chg_spin). CPU-safe; used by the magnetic-force # convention behavioral tests. - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa4c_spin_lmp.py & + run_generator ${INFER_SCRIPT_PATH}/gen_dpa4c_spin_lmp.py & PID14B=$! # Native-spin DPA4C: the archives above all ship a with-comm artifact # and are therefore served by DeepSpinPTExpt, which leaves @@ -198,20 +227,20 @@ if [ "${ENABLE_PYTORCH:-TRUE}" == "TRUE" ]; then # fixture is generated only where the C++ suite has a GPU; the tests # built on it skip when it is absent. if [ "${DP_VARIANT}" = "cuda" ]; then - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa4c_spin.py & + run_generator ${INFER_SCRIPT_PATH}/gen_dpa4c_spin.py & PID15=$! # Compressed DPA4C, an energy and a native-spin model, on the compact # canonical lower: the only fixtures that reach the device-resident # entry points LAMMPS + Kokkos calls, with the replay of repeated # evaluations and a runtime charge state. - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa4c_canonical.py & + run_generator ${INFER_SCRIPT_PATH}/gen_dpa4c_canonical.py & PID16=$! fi # DPA4C with a latent-charge long-range module: the uncompressed archive # takes the all-pairs topology of the graph lower; for the CUDA variant the # script also writes the compressed archive, whose compact canonical lower # reads the node positions. - env ${_GEN_ENV} python ${INFER_SCRIPT_PATH}/gen_dpa4c_long_range.py & + run_generator ${INFER_SCRIPT_PATH}/gen_dpa4c_long_range.py & PID17=$! wait $PID11 wait $PID12 @@ -228,4 +257,10 @@ if [ "${ENABLE_PADDLE:-TRUE}" == "TRUE" ]; then PADDLE_INFERENCE_DIR=${BUILD_TMP_DIR}/paddle_inference_install_dir export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${PADDLE_INFERENCE_DIR}/third_party/install/onednn/lib:${PADDLE_INFERENCE_DIR}/third_party/install/mklml/lib fi -ctest --output-on-failure +# CTest otherwise hides every successful gtest's per-case time. Passing a +# directory makes GoogleTest use each executable's name (lib, cc, c), so even +# a parallel CTest run cannot overwrite another executable's JSON report. +mkdir -p "${BUILD_TMP_DIR}/gtest-reports" +GTEST_REPORT_DIR=$(mktemp -d "${BUILD_TMP_DIR}/gtest-reports/run.XXXXXX") +export GTEST_OUTPUT=${GTEST_OUTPUT:-json:${GTEST_REPORT_DIR}/} +ctest --output-on-failure --output-junit "${GTEST_REPORT_DIR}/ctest.xml" diff --git a/source/install/test_lammps_kokkos.sh b/source/install/test_lammps_kokkos.sh index 26467343e2..dbce79fd6e 100755 --- a/source/install/test_lammps_kokkos.sh +++ b/source/install/test_lammps_kokkos.sh @@ -78,7 +78,22 @@ mkdir -p "${PLUGIN_DIR}" ln -sfn "${PLUGIN_BUILD_DIR}/lmp/plugin/libdeepmd_lmp.so" "${PLUGIN_DIR}/dpplugin.so" export LD_LIBRARY_PATH=${LAMMPS_BUILD_DIR}:${DEEPMD_C_ROOT}/lib${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}} -python "${REPO_ROOT}/source/tests/infer/gen_dpa4c_spin_lmp_kokkos.py" +# Record the spin fixture separately from the two pytest sessions below. +# Keep a failed generator's report, then propagate its original exit status. +mkdir -p "${BUILD_ROOT}/test-reports" +GENERATOR_REPORT_DIR=$(mktemp -d "${BUILD_ROOT}/test-reports/run.XXXXXX") +GENERATOR_START=$SECONDS +if python -u "${REPO_ROOT}/source/tests/infer/gen_dpa4c_spin_lmp_kokkos.py"; then + GENERATOR_STATUS=0 +else + GENERATOR_STATUS=$? +fi +printf 'generator\tseconds\texit_status\n%s\t%s\t%s\n' \ + gen_dpa4c_spin_lmp_kokkos "$((SECONDS - GENERATOR_START))" "${GENERATOR_STATUS}" \ + >"${GENERATOR_REPORT_DIR}/gen_dpa4c_spin_lmp_kokkos.tsv" +if [[ ${GENERATOR_STATUS} != 0 ]]; then + exit "${GENERATOR_STATUS}" +fi # The wheel's Python package loads its own liblammps by absolute path. Merely # setting LD_LIBRARY_PATH would therefore still test the non-Kokkos wheel. @@ -105,12 +120,17 @@ with lammps.lammps(cmdargs=["-log", "none", "-screen", "none"]) as lmp: print(f"Verified matching LAMMPS Python and shared library: {mapped_libraries}") PY +# Keep each invocation and each pytest process separate, including failures. +mkdir -p "${BUILD_ROOT}/test-reports" +TEST_REPORT_DIR=$(mktemp -d "${BUILD_ROOT}/test-reports/run.XXXXXX") DPA4SPIN_KOKKOS_REQUIRED=1 python -m pytest -v -s \ - "${REPO_ROOT}/source/lmp/tests/test_dpa4spin_kokkos_magnetic_force.py" + "${REPO_ROOT}/source/lmp/tests/test_dpa4spin_kokkos_magnetic_force.py" \ + --junitxml="${TEST_REPORT_DIR}/spin.xml" # The compressed long-range fixtures come from gen_dpa4c_long_range.py of # test_cc_local.sh; the MPI runner of the test launches mpirun from PATH, which # leads with the launcher of the MPI prefix, while pytest runs on the Python of # the job. PYTHON=$(command -v python) PATH=${MPI_ROOT}/bin:${PATH} DPA4C_LONG_RANGE_KOKKOS_REQUIRED=1 "${PYTHON}" -m pytest -v -s \ - "${REPO_ROOT}/source/lmp/tests/test_lammps_dpa4c_long_range_kokkos.py" + "${REPO_ROOT}/source/lmp/tests/test_lammps_dpa4c_long_range_kokkos.py" \ + --junitxml="${TEST_REPORT_DIR}/long-range.xml" diff --git a/source/tests/infer/gen_common.py b/source/tests/infer/gen_common.py index 4ea27feb32..b0e4021e5c 100644 --- a/source/tests/infer/gen_common.py +++ b/source/tests/infer/gen_common.py @@ -4,6 +4,7 @@ import glob import json import os +import shutil import sys import zipfile @@ -28,9 +29,9 @@ def derive_pair_exclude_pt2(src_pt2, dst_pt2, exclude_types): #18/A4) applied at the C++ ingestion seam (from ``metadata.json``) and the Python DeepEval build seam (from the serialized ``model.json``); it is not baked into the exported graph, so the compiled AOTI artifact (including any - nested with-comm ``.pt2``) is byte-identical to the baseline. Only the two - JSON blobs that carry the list are patched -- both, so the C++ and Python - inference paths agree; patching one alone makes them disagree. This avoids + nested with-comm ``.pt2``) is byte-identical to the baseline. Patch metadata, + the serialized model, and the optional training config so C++, Python, + and subsequent backend conversions all see the same exclusion. This avoids a second inductor compile and is bit-identical to a full recompile. """ with zipfile.ZipFile(src_pt2) as zin: @@ -45,9 +46,55 @@ def derive_pair_exclude_pt2(src_pt2, dst_pt2, exclude_types): mdl = json.loads(blob) mdl["model"]["pair_exclude_types"] = exclude_types blob = json.dumps(mdl).encode() + elif info.filename == "model/extra/model_def_script.json": + config = json.loads(blob) + config["pair_exclude_types"] = exclude_types + blob = json.dumps(config).encode() zout.writestr(info, blob) +def reuse_pt2(src_pt2, dst_pt2, model_data, *, lower_kind="nlist"): + """Reuse an explicitly selected fixture after checking its complete model. + + The caller must name an archive generated earlier in this run. This is not + an existence-based cache: standalone generators still compile afresh. + Check weights, architecture, precision, lower ABI, and atomic-virial + support before copying, so later fixture changes cannot silently reuse an + incompatible model. Ignore provenance such as creation timestamps. + """ + import numpy as np + + from deepmd.pt_expt.utils.serialization import ( + serialize_from_file, + ) + + source = serialize_from_file(src_pt2) + + def equal(left, right): + if isinstance(left, np.ndarray) or isinstance(right, np.ndarray): + return ( + isinstance(left, np.ndarray) + and isinstance(right, np.ndarray) + and left.dtype == right.dtype + and np.array_equal(left, right) + ) + if isinstance(left, dict) and isinstance(right, dict): + return left.keys() == right.keys() and all( + equal(left[key], right[key]) for key in left + ) + if isinstance(left, (list, tuple)) and isinstance(right, (list, tuple)): + return len(left) == len(right) and all( + equal(a, b) for a, b in zip(left, right, strict=True) + ) + return left == right + + if source["lower_input_kind"] != lower_kind or not source["do_atomic_virial"]: + raise ValueError(f"Incompatible lower/atomic-virial contract in {src_pt2}") + if not equal(source["model"], model_data["model"]): + raise ValueError(f"Model architecture or weights differ from {src_pt2}") + shutil.copyfile(src_pt2, dst_pt2) + + def ensure_inductor_compiler(): """Ensure torch._inductor can find a C++ compiler. diff --git a/source/tests/infer/gen_dpa1.py b/source/tests/infer/gen_dpa1.py index 55f68b44a0..d8dc0f7920 100644 --- a/source/tests/infer/gen_dpa1.py +++ b/source/tests/infer/gen_dpa1.py @@ -366,10 +366,13 @@ def main(): aparam_vals = (np.arange(1, 13, dtype=np.float64) * 0.1).reshape(1, 6, 2) # ---- C.1 Independent nlist reference (same weights, dense path) ---- + # This oracle is consumed only here, never by a C++/LAMMPS loader. Keep + # the full exported dense forward/derivatives without compiling an AOTI + # package; the graph aparam artifact below still exercises native AOTI. aparam_nlist_ref_pt2 = os.path.join( - base_dir, "deeppot_dpa1_graph_aparam_nlist_ref.pt2" + base_dir, "deeppot_dpa1_graph_aparam_nlist_ref.pte" ) - print(f"Exporting reference nlist .pt2 to {aparam_nlist_ref_pt2} ...") # noqa: T201 + print(f"Exporting reference nlist .pte to {aparam_nlist_ref_pt2} ...") # noqa: T201 pt_expt_deserialize_to_file( aparam_nlist_ref_pt2, copy.deepcopy(data_a), diff --git a/source/tests/infer/gen_dpa1_pairexcl.py b/source/tests/infer/gen_dpa1_pairexcl.py index 452a7b4e86..5f47b47511 100644 --- a/source/tests/infer/gen_dpa1_pairexcl.py +++ b/source/tests/infer/gen_dpa1_pairexcl.py @@ -9,7 +9,9 @@ - deeppot_dpa1_pairexcl_nlist.pt2 (lower_kind="nlist", pair_exclude=[[0,1]]) - deeppot_dpa1_pairexcl_none.pt2 (lower_kind="graph", NO exclusion) -Only two inductor compiles are needed: the graph baseline (``_none``) and the +With ``--reuse-dpa1`` no new compile is needed: both baselines come from +``gen_dpa1.py`` Section B, after validating their complete serialized models. +Standalone execution still performs two inductor compiles: the graph baseline (``_none``) and the nlist route (``_nlist``). ``_graph`` has the same weights and lower_kind as ``_none`` and differs only in the exclusion list, so it is DERIVED from ``_none`` by patching the archive (``gen_common.derive_pair_exclude_pt2``) -- @@ -41,6 +43,7 @@ inductor codegen bug. """ +import argparse import copy import os import sys @@ -54,11 +57,12 @@ derive_pair_exclude_pt2, ensure_inductor_compiler, load_custom_ops, + reuse_pt2, write_expected_ref, ) -def main(): +def main(*, reuse_dpa1=False): from deepmd.dpmodel.model.model import ( get_model, ) @@ -132,9 +136,18 @@ def build_data(exclude_types): # ---- No-exclusion baseline (graph route) ---- none_pt2 = os.path.join(base_dir, "deeppot_dpa1_pairexcl_none.pt2") print(f"Exporting no-exclusion baseline to {none_pt2} ...") # noqa: T201 - pt_expt_deserialize_to_file( - none_pt2, build_data(None), do_atomic_virial=True, lower_kind="graph" - ) + if reuse_dpa1: + # gen_dpa1.py Section B has exactly these weights and both lowers. + reuse_pt2( + os.path.join(base_dir, "deeppot_dpa1_graph.pt2"), + none_pt2, + build_data(None), + lower_kind="graph", + ) + else: + pt_expt_deserialize_to_file( + none_pt2, build_data(None), do_atomic_virial=True, lower_kind="graph" + ) dp_none = DeepPot(none_pt2) e_none = dp_none.eval(coord, box, atype, atomic=False)[0][0, 0] print(f" baseline PBC energy: {e_none:.18e}") # noqa: T201 @@ -150,19 +163,28 @@ def build_data(exclude_types): "(pair_exclude_types patch, no recompile) ..." ) derive_pair_exclude_pt2(none_pt2, graph_pt2, exclude_types) - # nlist route: a DIFFERENT lower_kind (a different exported graph) that the - # graph baseline cannot supply -> compile it. + # nlist route needs a separate lower, supplied by gen_dpa1.py's dense + # oracle when explicitly requested, or compiled for standalone use. nlist_pt2 = os.path.join(base_dir, "deeppot_dpa1_pairexcl_nlist.pt2") print( # noqa: T201 f"Exporting to {nlist_pt2} (lower_kind='nlist', " f"pair_exclude_types={exclude_types}) ..." ) - pt_expt_deserialize_to_file( - nlist_pt2, - copy.deepcopy(build_data(exclude_types)), - do_atomic_virial=True, - lower_kind="nlist", - ) + if reuse_dpa1: + reuse_pt2( + os.path.join(base_dir, "deeppot_dpa1_graph_nlist_ref.pt2"), + nlist_pt2, + build_data(None), + ) + # Exclusion is an ingestion transform on this lower as well. + derive_pair_exclude_pt2(nlist_pt2, nlist_pt2, exclude_types) + else: + pt_expt_deserialize_to_file( + nlist_pt2, + copy.deepcopy(build_data(exclude_types)), + do_atomic_virial=True, + lower_kind="nlist", + ) # Eval + activeness check + reference sidecar for both routes. for tag in ("graph", "nlist"): pt2_path = os.path.join(base_dir, f"deeppot_dpa1_pairexcl_{tag}.pt2") @@ -209,4 +231,10 @@ def build_data(exclude_types): if __name__ == "__main__": - main() + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--reuse-dpa1", + action="store_true", + help="reuse the two baseline archives generated by gen_dpa1.py in this run", + ) + main(reuse_dpa1=parser.parse_args().reuse_dpa1) diff --git a/source/tests/infer/gen_dpa2.py b/source/tests/infer/gen_dpa2.py index be160f52fd..4029167465 100644 --- a/source/tests/infer/gen_dpa2.py +++ b/source/tests/infer/gen_dpa2.py @@ -23,6 +23,42 @@ ) +def _eval_nlist_reference(dp, coord, box, atype): + """Read atomic energy, force and total virial without requesting atomic virial.""" + # DeepPot's tuple API couples atomic energy to atomic virial. Its backend + # result already includes atomic energy when atomic=False, so retain the + # independent per-atom energy check without exporting three unused + # atomic-virial backward passes. + natoms = len(atype) + coord = np.asarray(coord).reshape(-1, natoms, 3) + box = None if box is None else np.asarray(box).reshape(-1, 9) + output = dp.deep_eval.eval(coord, box, atype, atomic=False) + return ( + output["energy_redu"].reshape(-1, 1), + output["energy_derv_r"].reshape(-1, natoms, 3), + output["energy_derv_c_redu"].reshape(-1, 9), + output["energy"].reshape(-1, natoms, 1), + ) + + +def _export_nlist_reference(path, data): + """Export the single-rank oracle without unused per-atom virial backward passes.""" + from deepmd.pt_expt.utils.serialization import ( + deserialize_to_file, + ) + + # Both consumers compare energy/force and the gen-time cross-check also + # compares total virial and atomic energy. Neither requests this oracle's + # atomic virial or MPI artifact. All deployment fixtures retain both. + deserialize_to_file( + path, + copy.deepcopy(data), + do_atomic_virial=False, + lower_kind="nlist", + with_comm=False, + ) + + def main(): from deepmd.dpmodel.model.model import ( get_model, @@ -295,19 +331,14 @@ def main(): # at non-binding sel the two paths must agree. nlist_ref_pt2 = os.path.join(base_dir, "deeppot_dpa2_graph_nlist_ref.pt2") print(f"Exporting reference nlist .pt2 to {nlist_ref_pt2} ...") # noqa: T201 - pt_expt_deserialize_to_file( - nlist_ref_pt2, - copy.deepcopy(data_g), - do_atomic_virial=True, - lower_kind="nlist", # independent: dense nlist, NOT graph - ) + _export_nlist_reference(nlist_ref_pt2, data_g) dp_nlist_ref = DeepPot(nlist_ref_pt2) # PBC reference from nlist path - e_r1, f_r1, v_r1, ae_r1, av_r1 = dp_nlist_ref.eval(coord, box, atype, atomic=True) + e_r1, f_r1, v_r1, ae_r1 = _eval_nlist_reference(dp_nlist_ref, coord, box, atype) # NoPBC reference from nlist path - e_rnp, f_rnp, v_rnp, ae_rnp, av_rnp = dp_nlist_ref.eval( - coord, None, atype, atomic=True + e_rnp, f_rnp, v_rnp, ae_rnp = _eval_nlist_reference( + dp_nlist_ref, coord, None, atype ) print(f"Nlist ref PBC energy: {e_r1[0, 0]:.18e}") # noqa: T201 diff --git a/source/tests/infer/gen_dpa4.py b/source/tests/infer/gen_dpa4.py index 3515c19de2..d227c70e44 100644 --- a/source/tests/infer/gen_dpa4.py +++ b/source/tests/infer/gen_dpa4.py @@ -10,6 +10,7 @@ import copy import os +import shutil import sys import numpy as np @@ -25,8 +26,6 @@ def main(): - import torch - from deepmd.pt_expt.model.get_model import ( get_model, ) @@ -68,34 +67,28 @@ def main(): model.to("cpu") model.eval() - # ---- 2b. Activate the zero-initialised residual branches ---- - # DPA4/SeZM follows the standard residual-network convention of - # ZERO-initialising the output projection of every residual branch - # (``*.so3_linear_2.weight``, ``post_focus_mix.weight``, - # ``env_seed_embedding.output_proj.w``) and the final descriptor output - # projection (``output_ffn.so3_linear_2.weight``). At random init these - # branches therefore contribute EXACTLY zero, so a freshly built DPA4 - # collapses to a type-embedding-only descriptor: the per-atom energy is a - # pure per-type constant and every force/virial is identically zero, - # regardless of geometry. Such a fixture exercises none of the - # force/virial code paths and would make the C++ inference test vacuous. - # - # A trained model has non-zero weights in these branches, so to obtain a - # representative (geometry-dependent, non-zero-force) reference we fill the - # all-zero parameters with small deterministic pseudo-random values. This - # is the minimal change that makes the descriptor coordinate-dependent - # while leaving the rest of the random init untouched. (Unlike DPA3, - # whose random init already yields non-zero forces, DPA4 needs this step.) - generator = torch.Generator().manual_seed(20240614) - with torch.no_grad(): - for _name, param in model.named_parameters(): - if float(param.detach().abs().max()) == 0.0: - param.copy_( - 0.1 - * torch.randn(param.shape, dtype=param.dtype, generator=generator) - ) - - model_dict = model.serialize() + # ---- 2b. Activate zero-initialized parameters and output biases ---- + # Keep the graph fixture's original serialized-array perturbation. In + # addition to the residual branches, this makes the model out_bias and + # fitting bias_atom_e nonzero; perturbing only named_parameters would + # silently lose that graph coverage. Dense and graph exports share these + # weights, so the dense archive can serve as the independent graph oracle. + def _jitter_zero_arrays(node, rng: np.random.Generator): + # Pure rebuild, matching source/tests/dpa4_fixtures.py. + if isinstance(node, dict): + return {k: _jitter_zero_arrays(v, rng) for k, v in node.items()} + if isinstance(node, list): + return [_jitter_zero_arrays(v, rng) for v in node] + if ( + isinstance(node, np.ndarray) + and node.dtype.kind == "f" + and node.size > 0 + and np.all(node == 0.0) + ): + return rng.normal(0.0, 0.05, size=node.shape).astype(node.dtype) + return node + + model_dict = _jitter_zero_arrays(model.serialize(), np.random.default_rng(20240615)) data = { "model": model_dict, @@ -293,52 +286,13 @@ def main(): print("\n---- Building graph DPA4 (jittered weights) ----") # noqa: T201 - # ---- B.1 Build a fresh DPA4 model; jitter zero-init residuals ---- - # A freshly built DPA4 zero-initializes several residual output - # projections (see step 2b above and the ``jitter_zero_arrays`` - # docstring in source/tests/dpa4_fixtures.py), so its output is - # architecturally edge-independent until those branches are perturbed - # away from exactly zero. Section A already does this via in-place - # torch-parameter replacement (step 2b); this section instead follows - # the dict-level ``jitter_zero_arrays`` pattern used by - # test_dpa4_call_graph.py / test_dpa4_graph_lower.py, for consistency - # with the rest of the DPA4 graph test suite. Inlined here (rather than - # imported from source/tests/dpa4_fixtures.py) because gen_dpa4.py is a - # standalone script run outside pytest's package machinery -- importing - # a source/tests/... module from it would need ad hoc sys.path / - # package surgery for no real benefit. - # Mirror of source/tests/dpa4_fixtures.py:jitter_zero_arrays -- keep in sync. - def _jitter_zero_arrays(node, rng: np.random.Generator): - # Mirror of source/tests/dpa4_fixtures.py:jitter_zero_arrays -- keep in - # sync. PURE rebuild (returns a new tree, does not mutate ``node``) to - # avoid CodeQL's py/modification-of-default-value dataflow; behavior - # (RNG draws, shapes, dtype) is bit-identical. - if isinstance(node, dict): - return {k: _jitter_zero_arrays(v, rng) for k, v in node.items()} - if isinstance(node, list): - return [_jitter_zero_arrays(v, rng) for v in node] - if ( - isinstance(node, np.ndarray) - and node.dtype.kind == "f" - and node.size > 0 - and np.all(node == 0.0) - ): - return rng.normal(0.0, 0.05, size=node.shape).astype(node.dtype) - return node - - model_g = get_model(copy.deepcopy(config)) - model_g.to("cpu") - model_g.eval() - model_dict_g = model_g.serialize() - model_dict_g = _jitter_zero_arrays(model_dict_g, np.random.default_rng(20240615)) - - data_g = { - "model": copy.deepcopy(model_dict_g), - "model_def_script": config, - "backend": "dpmodel", - "software": "deepmd-kit", - "version": "3.0.0", - } + # ---- B.1 Reuse the non-vacuous weights from Section A ---- + # Both lowers support the same DPA4 configuration. Section A already + # uses the original graph fixture's perturbed parameters and biases, so + # rebuilding that model would require another identical dense AOT compile. + # Keep the dense and graph artifacts on the same serialized weights; + # their different lowers remain independent numerical cross-checks. + data_g = copy.deepcopy(data) # ---- B.2 Independent cross-check via nlist .pt2 (dense-quartet) ---- # Like gen_dpa2.py's Section B.2: deeppot_dpa4_graph.expected is NOT @@ -355,13 +309,11 @@ def _jitter_zero_arrays(node, rng: np.random.Generator): # graph parity test, both exercised on the SAME jittered weights as the # graph model, so at non-binding sel the two paths must agree. nlist_ref_pt2 = os.path.join(base_dir, "deeppot_dpa4_graph_nlist_ref.pt2") - print(f"Exporting reference nlist .pt2 to {nlist_ref_pt2} ...") # noqa: T201 - pt_expt_deserialize_to_file( - nlist_ref_pt2, - copy.deepcopy(data_g), - do_atomic_virial=True, - lower_kind="nlist", # independent: dense nlist, NOT graph - ) + # The reference has exactly Section A's weights and lower. Preserve its + # established filename for C++/LAMMPS/Python consumers without compiling + # the same dense artifact again. Reload the copy below to keep the + # persisted-reference check independent of the in-process evaluator. + shutil.copyfile(pt2_path, nlist_ref_pt2) dp_nlist_ref = DeepPot(nlist_ref_pt2) # PBC reference from nlist path diff --git a/source/tests/infer/gen_dpa4c_long_range.py b/source/tests/infer/gen_dpa4c_long_range.py index 3c71034dd5..c50e68acec 100644 --- a/source/tests/infer/gen_dpa4c_long_range.py +++ b/source/tests/infer/gen_dpa4c_long_range.py @@ -37,6 +37,7 @@ suite checks the mesh it builds for the graph lower; it needs no archive. """ +import argparse import copy import dataclasses import json @@ -273,12 +274,15 @@ def _export_compressed(pt2_path: str, config: dict) -> None: deserialize_to_file(pt2_path, data, do_atomic_virial=True, lower_kind="auto") -def main() -> None: +def main(*, compressed_only: bool = False) -> None: from deepmd.pt_expt.utils.serialization import ( deserialize_to_file, mesh_freeze_supported, ) + if compressed_only and os.environ.get("DP_VARIANT") != "cuda": + raise ValueError("--compressed-only requires DP_VARIANT=cuda") + ensure_inductor_compiler() load_custom_ops() @@ -286,27 +290,29 @@ def main() -> None: for suffix, periodic in (("", False), ("_periodic", True)): config = _periodic(CONFIG) if periodic else CONFIG stem = os.path.join(base_dir, f"deeppot_dpa4c_long_range{suffix}") - data = { - "model": _model_dict(config), - "model_def_script": config, - "backend": "dpmodel", - "software": "deepmd-kit", - "version": "3.0.0", - } - if periodic: - _write_mesh_ref(config, f"{stem}_mesh.expected") - if periodic and not mesh_freeze_supported(): - # The C++ and LAMMPS suites skip the archive this torch cannot - # package. - print(f"Skipping {stem}.pt2: the mesh evaluation needs torch >= 2.12") # noqa: T201 - else: - print(f"Exporting to {stem}.pt2 (lower_kind='graph') ...") # noqa: T201 - deserialize_to_file( - f"{stem}.pt2", data, do_atomic_virial=True, lower_kind="graph" - ) - _check_metadata(f"{stem}.pt2", "graph", periodic) - _write_ref(f"{stem}.pt2", f"{stem}.expected", periodic) - + # The dedicated Kokkos job consumes only compact canonical archives. + # The main C++ job keeps the graph and mesh-builder reference coverage. + if not compressed_only: + data = { + "model": _model_dict(config), + "model_def_script": config, + "backend": "dpmodel", + "software": "deepmd-kit", + "version": "3.0.0", + } + if periodic: + _write_mesh_ref(config, f"{stem}_mesh.expected") + if periodic and not mesh_freeze_supported(): + # The C++ and LAMMPS suites skip the archive this torch cannot + # package. + print(f"Skipping {stem}.pt2: the mesh evaluation needs torch >= 2.12") # noqa: T201 + else: + print(f"Exporting to {stem}.pt2 (lower_kind='graph') ...") # noqa: T201 + deserialize_to_file( + f"{stem}.pt2", data, do_atomic_virial=True, lower_kind="graph" + ) + _check_metadata(f"{stem}.pt2", "graph", periodic) + _write_ref(f"{stem}.pt2", f"{stem}.expected", periodic) if os.environ.get("DP_VARIANT") == "cuda": compressed = f"{stem}_compressed" compressed_config = ( @@ -320,4 +326,10 @@ def main() -> None: if __name__ == "__main__": - main() + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--compressed-only", + action="store_true", + help="generate only the two CUDA compact-canonical fixtures for Kokkos", + ) + main(compressed_only=parser.parse_args().compressed_only) diff --git a/source/tests/infer/gen_spin.py b/source/tests/infer/gen_spin.py index 56b2f2a6cd..e46ed9123e 100644 --- a/source/tests/infer/gen_spin.py +++ b/source/tests/infer/gen_spin.py @@ -11,8 +11,15 @@ is then committed). Also prints reference values for C++ tests (PBC and NoPbc). + +Standalone execution exports all models. CI can run ``--dpa3-only`` alongside +``gen_spin_model_devi.py``, then, after BOTH generators succeed, run +``--reuse-model-devi`` to derive the baseline from the identical model-0 archive +and generate the .pth and reference values. No artifact is polled or implicitly +cached. """ +import argparse import copy import os import sys @@ -25,6 +32,7 @@ from gen_common import ( ensure_inductor_compiler, load_custom_ops, + reuse_pt2, write_expected_ref, ) @@ -220,13 +228,14 @@ def _build_dpa3_single_yaml(yaml_path: str) -> None: save_dp_model(yaml_path, data) -def main(): +def main(*, dpa3_only=False, reuse_model_devi=False): + if dpa3_only and reuse_model_devi: + raise ValueError("dpa3_only and reuse_model_devi are mutually exclusive") + from deepmd.entrypoints.convert_backend import ( convert_backend, ) - ensure_inductor_compiler() - base_dir = os.path.dirname(__file__) yaml_path = os.path.join(base_dir, "deeppot_dpa_spin.yaml") pth_path = os.path.join(base_dir, "deeppot_dpa_spin.pth") @@ -244,21 +253,37 @@ def main(): yaml_dpa3_single_path = os.path.join(base_dir, "deeppot_dpa3_spin.yaml") pt2_dpa3_single_path = os.path.join(base_dir, "deeppot_dpa3_spin.pt2") - # ---- 1. Build .yamls if they don't exist ---- - if not os.path.exists(yaml_path): - _build_yaml(yaml_path) - else: - print(f"Using existing {yaml_path}") # noqa: T201 + if reuse_model_devi: + source = os.path.join(base_dir, "deeppot_dpa_spin_md0.pt2") + # The shell removes stale .pt2 files and waits for both producers. + # Never silently compile missing artifacts or poll a failed producer. + for required in (pt2_dpa3_single_path, pt2_dpa3_path, source): + if not os.path.isfile(required): + raise FileNotFoundError( + "--reuse-model-devi requires gen_spin.py --dpa3-only and " + "gen_spin_model_devi.py to finish successfully in this run " + f"first; missing {required}" + ) - if not os.path.exists(yaml_dpa3_path): - _build_dpa3_mpi_yaml(yaml_dpa3_path) - else: - print(f"Using existing {yaml_dpa3_path}") # noqa: T201 + ensure_inductor_compiler() - if not os.path.exists(yaml_dpa3_single_path): - _build_dpa3_single_yaml(yaml_dpa3_single_path) - else: - print(f"Using existing {yaml_dpa3_single_path}") # noqa: T201 + # ---- 1. Build .yamls if they don't exist ---- + if not dpa3_only: + if not os.path.exists(yaml_path): + _build_yaml(yaml_path) + else: + print(f"Using existing {yaml_path}") # noqa: T201 + + if not reuse_model_devi: + if not os.path.exists(yaml_dpa3_path): + _build_dpa3_mpi_yaml(yaml_dpa3_path) + else: + print(f"Using existing {yaml_dpa3_path}") # noqa: T201 + + if not os.path.exists(yaml_dpa3_single_path): + _build_dpa3_single_yaml(yaml_dpa3_single_path) + else: + print(f"Using existing {yaml_dpa3_single_path}") # noqa: T201 # ---- 2. Convert .yaml -> .pth and .yaml -> .pt2 ---- # Import deepmd.pt to register the backend (needed for convert_backend) @@ -266,23 +291,38 @@ def main(): load_custom_ops() - print(f"Converting to {pth_path} ...") # noqa: T201 - convert_backend(INPUT=yaml_path, OUTPUT=pth_path) - - print(f"Converting to {pt2_path} ...") # noqa: T201 - convert_backend(INPUT=yaml_path, OUTPUT=pt2_path, atomic_virial=True) - - print(f"Converting to {pt2_dpa3_single_path} ...") # noqa: T201 - convert_backend( - INPUT=yaml_dpa3_single_path, - OUTPUT=pt2_dpa3_single_path, - atomic_virial=True, - ) + if not dpa3_only: + if reuse_model_devi: + from deepmd.dpmodel.utils.serialization import ( + load_dp_model, + ) + + print(f"Reusing {source} for {pt2_path} ...") # noqa: T201 + # The seed-1 YAMLs differ only in creation time. Check every + # serialized weight, dtype and the lower/atomic-virial contract. + reuse_pt2(source, pt2_path, load_dp_model(yaml_path)) + + print(f"Converting to {pth_path} ...") # noqa: T201 + convert_backend(INPUT=yaml_path, OUTPUT=pth_path) + + if not reuse_model_devi: + print(f"Converting to {pt2_path} ...") # noqa: T201 + convert_backend(INPUT=yaml_path, OUTPUT=pt2_path, atomic_virial=True) + + if not reuse_model_devi: + print(f"Converting to {pt2_dpa3_single_path} ...") # noqa: T201 + convert_backend( + INPUT=yaml_dpa3_single_path, + OUTPUT=pt2_dpa3_single_path, + atomic_virial=True, + ) - print(f"Converting to {pt2_dpa3_path} ...") # noqa: T201 - convert_backend(INPUT=yaml_dpa3_path, OUTPUT=pt2_dpa3_path, atomic_virial=True) + print(f"Converting to {pt2_dpa3_path} ...") # noqa: T201 + convert_backend(INPUT=yaml_dpa3_path, OUTPUT=pt2_dpa3_path, atomic_virial=True) print("Export done.") # noqa: T201 + if dpa3_only: + return # ---- 3. Run inference for PBC test ---- from deepmd.infer import ( @@ -388,4 +428,17 @@ def main(): if __name__ == "__main__": - main() + parser = argparse.ArgumentParser(description=__doc__) + mode = parser.add_mutually_exclusive_group() + mode.add_argument( + "--dpa3-only", + action="store_true", + help="export only the two DPA3 variants, without baseline references", + ) + mode.add_argument( + "--reuse-model-devi", + action="store_true", + help="reuse completed model 0 after both producers succeed, then evaluate", + ) + args = parser.parse_args() + main(dpa3_only=args.dpa3_only, reuse_model_devi=args.reuse_model_devi) diff --git a/source/tests/infer/test_gen_common.py b/source/tests/infer/test_gen_common.py new file mode 100644 index 0000000000..38e09f5160 --- /dev/null +++ b/source/tests/infer/test_gen_common.py @@ -0,0 +1,143 @@ +# SPDX-License-Identifier: LGPL-3.0-or-later +"""Safety checks for the explicit same-run C++ model fixture reuse.""" + +import copy +import json +import zipfile + +import numpy as np +import pytest + +from .gen_common import ( + derive_pair_exclude_pt2, + reuse_pt2, +) + + +@pytest.fixture +def archive(tmp_path, monkeypatch): + pytest.importorskip("torch") + from deepmd.pt_expt.utils import ( + serialization, + ) + + src = tmp_path / "source.pt2" + dst = tmp_path / "target.pt2" + src.write_bytes(b"a complete compiled fixture") + data = { + "model": { + "type": "ener", + "descriptor": {"sel": 8}, + "weights": np.array([0.25, 1.0], dtype=np.float64), + }, + "time": "source provenance", + "lower_input_kind": "nlist", + "do_atomic_virial": True, + } + monkeypatch.setattr(serialization, "serialize_from_file", lambda path: data) + return src, dst, data + + +def test_reuse_checks_model_not_provenance(archive): + src, dst, source = archive + expected = copy.deepcopy(source) + expected["time"] = "different provenance" + reuse_pt2(str(src), str(dst), expected) + assert dst.read_bytes() == src.read_bytes() + + +@pytest.mark.parametrize("change", ["weights", "dtype", "architecture", "keys"]) +def test_reuse_rejects_changed_model(archive, change): + src, dst, source = archive + expected = copy.deepcopy(source) + model = expected["model"] + if change == "weights": + model["weights"][0] += 0.1 + elif change == "dtype": + model["weights"] = model["weights"].astype(np.float32) + elif change == "architecture": + model["descriptor"]["sel"] = 16 + else: + model["pair_exclude_types"] = [[0, 1]] + with pytest.raises(ValueError, match="architecture or weights"): + reuse_pt2(str(src), str(dst), expected) + assert not dst.exists() + + +@pytest.mark.parametrize( + "field,value", [("lower_input_kind", "graph"), ("do_atomic_virial", False)] +) +def test_reuse_rejects_changed_abi(archive, field, value): + src, dst, source = archive + expected = copy.deepcopy(source) + source[field] = value + with pytest.raises(ValueError, match="lower/atomic-virial contract"): + reuse_pt2(str(src), str(dst), expected) + assert not dst.exists() + + +@pytest.mark.parametrize("in_place", [False, True]) +def test_pair_exclusion_changes_only_metadata(tmp_path, in_place): + source = tmp_path / "source.pt2" + target = source if in_place else tmp_path / "derived.pt2" + contents = { + "model/extra/metadata.json": {"pair_exclude_types": []}, + "model/extra/model.json": {"model": {"pair_exclude_types": []}}, + "model/extra/model_def_script.json": {"type_map": ["O", "H"]}, + } + with zipfile.ZipFile(source, "w") as archive: + for name, value in contents.items(): + archive.writestr(name, json.dumps(value)) + archive.writestr("model/kernel.so", b"compiled bytes must not change") + derive_pair_exclude_pt2(str(source), str(target), [[0, 1]]) + with zipfile.ZipFile(target) as archive: + assert archive.read("model/kernel.so") == b"compiled bytes must not change" + for name in contents: + value = json.loads(archive.read(name)) + if name.endswith("/model.json"): + value = value["model"] + assert value["pair_exclude_types"] == [[0, 1]] + + +@pytest.mark.parametrize("lower_kind", ["nlist", "graph"]) +@pytest.mark.parametrize("exclude_types", [[], [[0, 1]]]) +def test_dpa1_serialization_keeps_pair_exclusion_metadata(lower_kind, exclude_types): + pytest.importorskip("torch") + from deepmd.dpmodel.model.model import ( + get_model, + ) + from deepmd.pt_expt.model.model import ( + BaseModel, + ) + from deepmd.pt_expt.utils.serialization import ( + _collect_metadata, + ) + + # The CI fixtures reuse compiled lowers. Independently retain the real + # dpmodel -> pt_expt -> C++ metadata export contract without another AOT + # compile, including the no-exclusion control and both ingestion routes. + config = { + "type_map": ["O", "H"], + "descriptor": { + "type": "se_atten", + "sel": 30, + "rcut_smth": 2.0, + "rcut": 6.0, + "neuron": [2, 4, 8], + "axis_neuron": 4, + "attn": 5, + "attn_layer": 0, + "seed": 1, + }, + "fitting_net": {"neuron": [5, 5, 5], "resnet_dt": True, "seed": 1}, + "pair_exclude_types": exclude_types, + } + serialized = get_model(copy.deepcopy(config)).serialize() + assert serialized["pair_exclude_types"] == exclude_types + restored = BaseModel.deserialize(copy.deepcopy(serialized)) + assert restored.serialize()["pair_exclude_types"] == exclude_types + metadata = json.loads( + json.dumps(_collect_metadata(restored, lower_kind=lower_kind)) + ) + assert metadata["pair_exclude_types"] == exclude_types + assert metadata["lower_input_kind"] == lower_kind diff --git a/source/tests/infer/test_gen_dpa2_reference.py b/source/tests/infer/test_gen_dpa2_reference.py new file mode 100644 index 0000000000..17fdcd9b57 --- /dev/null +++ b/source/tests/infer/test_gen_dpa2_reference.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: LGPL-3.0-or-later +"""Keep the independent DPA2 oracle outputs while avoiding unused export work.""" + +import importlib +from pathlib import ( + Path, +) +from types import ( + SimpleNamespace, +) + +import numpy as np +import pytest + + +@pytest.fixture +def generator(monkeypatch): + monkeypatch.syspath_prepend(str(Path(__file__).parent)) + return importlib.import_module(".gen_dpa2", __package__) + + +def test_dense_oracle_exports_only_the_required_capabilities(generator, monkeypatch): + pytest.importorskip("torch") + from deepmd.pt_expt.utils import ( + serialization, + ) + + calls = [] + + def export(path, data, **kwargs): + calls.append((path, data, kwargs)) + data["model"]["weights"].append(2) + + monkeypatch.setattr(serialization, "deserialize_to_file", export) + data = {"model": {"weights": [1]}} + generator._export_nlist_reference("reference.pt2", data) + assert len(calls) == 1 + assert calls[0][0] == "reference.pt2" + assert calls[0][2] == { + "do_atomic_virial": False, + "lower_kind": "nlist", + "with_comm": False, + } + assert data == {"model": {"weights": [1]}} + + +@pytest.mark.parametrize("periodic", [False, True]) +@pytest.mark.parametrize("flat", [False, True]) +def test_dense_oracle_retains_atomic_energy_and_total_virial(generator, periodic, flat): + output = { + "energy_redu": np.arange(2), + "energy_derv_r": np.arange(2 * 6 * 3), + "energy_derv_c_redu": np.arange(2 * 9), + "energy": np.arange(2 * 6), + } + coords = np.zeros((2, 6, 3)) + box = np.tile(np.eye(3), (2, 1, 1)) if periodic else None + types = [0, 1, 1, 0, 1, 1] + + def evaluate(actual_coords, actual_box, actual_types, atomic): + np.testing.assert_array_equal(actual_coords, coords) + if box is None: + assert actual_box is None + else: + np.testing.assert_array_equal(actual_box, box.reshape(2, 9)) + assert actual_types is types + assert atomic is False + return output + + dp = SimpleNamespace(deep_eval=SimpleNamespace(eval=evaluate)) + energy, force, virial, atomic_energy = generator._eval_nlist_reference( + dp, + coords.ravel() if flat else coords, + box.ravel() if flat and box is not None else box, + types, + ) + for value, key, shape in ( + (energy, "energy_redu", (2, 1)), + (force, "energy_derv_r", (2, 6, 3)), + (virial, "energy_derv_c_redu", (2, 9)), + (atomic_energy, "energy", (2, 6, 1)), + ): + assert value.shape == shape + np.testing.assert_array_equal(value.ravel(), output[key]) diff --git a/source/tests/infer/test_gen_model_selection.py b/source/tests/infer/test_gen_model_selection.py new file mode 100644 index 0000000000..b70c8dfbfa --- /dev/null +++ b/source/tests/infer/test_gen_model_selection.py @@ -0,0 +1,98 @@ +# SPDX-License-Identifier: LGPL-3.0-or-later +"""Check fixture selection without compiling CUDA-only inference operators.""" + +import importlib +from pathlib import ( + Path, +) + +import pytest + + +@pytest.fixture +def generator(monkeypatch): + pytest.importorskip("torch") + # Standalone gen scripts import their sibling helpers by their short names. + monkeypatch.syspath_prepend(str(Path(__file__).parent)) + module = importlib.import_module(".gen_dpa4c_long_range", __package__) + from deepmd.pt_expt.utils import ( + serialization, + ) + + calls = {"graph": [], "compressed": [], "mesh": [], "metadata": [], "reference": []} + monkeypatch.setattr(module, "ensure_inductor_compiler", lambda: None) + monkeypatch.setattr(module, "load_custom_ops", lambda: None) + monkeypatch.setattr(module, "_model_dict", lambda cfg: {"config": cfg}) + monkeypatch.setattr(serialization, "mesh_freeze_supported", lambda: True) + monkeypatch.setattr( + serialization, + "deserialize_to_file", + lambda path, data, **kwargs: calls["graph"].append((path, data, kwargs)), + ) + for name, key in ( + ("_export_compressed", "compressed"), + ("_write_mesh_ref", "mesh"), + ("_check_metadata", "metadata"), + ("_write_ref", "reference"), + ): + monkeypatch.setattr( + module, name, lambda *args, key=key: calls[key].append(args) + ) + return module, calls + + +@pytest.mark.parametrize("compressed_only", [False, True]) +def test_kokkos_selection_keeps_both_compressed_models( + generator, monkeypatch, compressed_only +): + module, calls = generator + monkeypatch.setenv("DP_VARIANT", "cuda") + module.main(compressed_only=compressed_only) + assert [Path(path).name for path, _ in calls["compressed"]] == [ + "deeppot_dpa4c_long_range_compressed.pt2", + "deeppot_dpa4c_long_range_periodic_compressed.pt2", + ] + assert calls["compressed"][0][1] == module.COMPRESSED_CONFIG + assert calls["compressed"][1][1] == module._periodic(module.COMPRESSED_CONFIG) + assert len(calls["graph"]) == (0 if compressed_only else 2) + assert len(calls["mesh"]) == (0 if compressed_only else 1) + assert len(calls["metadata"]) == (2 if compressed_only else 4) + assert len(calls["reference"]) == (2 if compressed_only else 4) + + +def test_cpu_default_preserves_graph_and_mesh_fixtures(generator, monkeypatch): + module, calls = generator + monkeypatch.delenv("DP_VARIANT", raising=False) + module.main() + assert len(calls["graph"]) == 2 + assert len(calls["mesh"]) == 1 + assert not calls["compressed"] + assert all( + call[2] == {"do_atomic_virial": True, "lower_kind": "graph"} + for call in calls["graph"] + ) + + +def test_compressed_only_rejects_non_cuda_generation(generator, monkeypatch): + module, calls = generator + monkeypatch.delenv("DP_VARIANT", raising=False) + with pytest.raises(ValueError, match="requires DP_VARIANT=cuda"): + module.main(compressed_only=True) + assert not any(calls.values()) + + +def test_old_torch_keeps_mesh_reference_and_compressed_periodic_model( + generator, monkeypatch +): + module, calls = generator + from deepmd.pt_expt.utils import ( + serialization, + ) + + monkeypatch.setenv("DP_VARIANT", "cuda") + monkeypatch.setattr(serialization, "mesh_freeze_supported", lambda: False) + module.main() + assert len(calls["graph"]) == 1 + assert len(calls["mesh"]) == 1 + assert len(calls["compressed"]) == 2 + assert len(calls["reference"]) == 3 diff --git a/source/tests/infer/test_gen_spin.py b/source/tests/infer/test_gen_spin.py new file mode 100644 index 0000000000..bd50944739 --- /dev/null +++ b/source/tests/infer/test_gen_spin.py @@ -0,0 +1,322 @@ +# SPDX-License-Identifier: LGPL-3.0-or-later +"""Preserve spin artifacts and diagnostics without compiling an AOT model.""" + +import importlib +import json +import runpy +import sys +import zipfile +from pathlib import ( + Path, +) + +import numpy as np +import pytest + +from .gen_common import ( + reuse_pt2, +) + +_DPA3_MODELS = ("deeppot_dpa3_spin.pt2", "deeppot_dpa3_spin_mpi.pt2") + + +@pytest.fixture +def generator(monkeypatch, tmp_path): + pytest.importorskip("torch") + monkeypatch.syspath_prepend(str(Path(__file__).parent)) + module = importlib.import_module(".gen_spin", __package__) + from deepmd import ( + infer, + ) + from deepmd.dpmodel.utils import ( + serialization, + ) + from deepmd.entrypoints import ( + convert_backend, + ) + + monkeypatch.setattr(module, "__file__", str(tmp_path / "gen_spin.py")) + monkeypatch.setattr(module, "ensure_inductor_compiler", lambda: None) + monkeypatch.setattr(module, "load_custom_ops", lambda: None) + for name in ("deeppot_dpa_spin.pt2", *_DPA3_MODELS): + (tmp_path / name).with_suffix(".yaml").write_text("fixture YAML") + (tmp_path / "deeppot_dpa_spin_md0.pt2").write_bytes(b"model 0 generated this run") + data = {"model": {"weights": np.array([0.25], dtype=np.float64)}} + calls = { + name: [] + for name in ( + "exports", + "reuse", + "loads", + "evals", + "refs", + "events", + "yaml_loads", + ) + } + + def export(**kwargs): + calls["exports"].append(kwargs) + calls["events"].append("export") + Path(kwargs["OUTPUT"]).write_bytes(b"separately exported model") + + def reuse(src, dst, model_data): + calls["reuse"].append((src, dst, model_data)) + calls["events"].append("reuse") + Path(dst).write_bytes(Path(src).read_bytes()) + + def load_yaml(path): + calls["yaml_loads"].append(path) + return data + + class DeepPot: + def __init__(self, path): + self.path = Path(path).name + calls["loads"].append(self.path) + + def eval(self, coord, box, atype, *, atomic, spin): + natoms = len(atype) + offset = 100.0 if box is None else 10.0 + # Distinct arrays catch switched fields, and distinct PBC/NoPBC + # values catch writing both sidecar sections from the same eval. + outputs = tuple( + np.arange(np.prod(shape), dtype=np.float64).reshape(shape) + + offset + + index + for index, shape in enumerate( + ( + (1, 1), + (1, natoms, 3), + (1, 9), + (1, natoms, 1), + (1, natoms, 9), + (1, natoms, 3), + (1, natoms, 1), + ) + ) + ) + calls["evals"].append( + ( + self.path, + coord.copy(), + None if box is None else box.copy(), + list(atype), + atomic, + spin.copy(), + outputs, + ) + ) + calls["events"].append("eval") + return outputs + + write_ref = module.write_expected_ref + + def write_expected(path, **kwargs): + calls["refs"].append((path, kwargs)) + calls["events"].append("reference") + write_ref(path, **kwargs) + + monkeypatch.setattr(convert_backend, "convert_backend", export) + monkeypatch.setattr(serialization, "load_dp_model", load_yaml) + monkeypatch.setattr(module, "reuse_pt2", reuse) + monkeypatch.setattr(infer, "DeepPot", DeepPot) + monkeypatch.setattr(module, "write_expected_ref", write_expected) + return module, calls, tmp_path, data + + +def _assert_diagnostics(calls, directory): + coord = np.array( + [ + [12.83, 2.56, 2.18], + [12.09, 2.87, 2.74], + [0.25, 3.32, 1.68], + [3.36, 3.00, 1.81], + [3.51, 2.51, 2.60], + [4.27, 3.22, 1.56], + ] + ).reshape(-1) + spin = np.zeros((6, 3)) + spin[0] = [0.13, 0.02, 0.03] + spin[3] = [0.14, 0.10, 0.12] + assert calls["loads"] == ["deeppot_dpa_spin.pt2", "deeppot_dpa_spin.pth"] + assert len(calls["evals"]) == 3 + for index, (path, actual_coord, box, atype, atomic, actual_spin, _) in enumerate( + calls["evals"] + ): + assert path == f"deeppot_dpa_spin.{('pt2', 'pt2', 'pth')[index]}" + assert atomic is True + assert atype == [0, 1, 1, 0, 1, 1] + np.testing.assert_array_equal(actual_coord, coord) + np.testing.assert_array_equal(actual_spin, spin.reshape(-1)) + assert actual_coord.dtype == actual_spin.dtype == np.float64 + if index == 1: + assert box is None + else: + np.testing.assert_array_equal(box, (np.eye(3) * 13.0).reshape(-1)) + assert box.dtype == np.float64 + + assert len(calls["refs"]) == 1 + path, kwargs = calls["refs"][0] + assert Path(path) == directory / "deeppot_dpa_spin.expected" + assert kwargs["source_script"] == "source/tests/infer/gen_spin.py" + assert list(kwargs["sections"]) == ["pbc", "nopbc"] + for index, section in enumerate(kwargs["sections"].values()): + _, force, virial, atom_e, atom_v, force_m, _ = calls["evals"][index][-1] + expected = { + "expected_e": atom_e[0, :, 0], + "expected_f": force[0], + "expected_fm": force_m[0], + "expected_tot_v": virial[0], + "expected_atom_v": atom_v[0], + } + assert section.keys() == expected.keys() + for key in expected: + np.testing.assert_array_equal(section[key], expected[key]) + assert "[pbc]" in Path(path).read_text() + assert "[nopbc]" in Path(path).read_text() + + +def _export(directory, name): + args = { + "INPUT": str((directory / name).with_suffix(".yaml")), + "OUTPUT": str(directory / name), + } + if name.endswith(".pt2"): + args["atomic_virial"] = True + return args + + +def _complete_dpa3(directory): + for name in _DPA3_MODELS: + (directory / name).write_bytes(name.encode()) + + +def test_standalone_preserves_all_exports_and_diagnostics(generator): + module, calls, directory, _ = generator + module.main() + assert calls["exports"] == [ + _export(directory, name) + for name in ("deeppot_dpa_spin.pth", "deeppot_dpa_spin.pt2", *_DPA3_MODELS) + ] + assert not calls["reuse"] + assert not calls["yaml_loads"] + _assert_diagnostics(calls, directory) + + +def test_dpa3_only_exports_both_variants_without_baseline_or_diagnostics(generator): + module, calls, directory, _ = generator + # A missing baseline must not trigger its construction in this mode. + (directory / "deeppot_dpa_spin.yaml").unlink() + module.main(dpa3_only=True) + assert calls["exports"] == [_export(directory, name) for name in _DPA3_MODELS] + for key in ("reuse", "loads", "evals", "refs", "yaml_loads"): + assert not calls[key] + for extension in ("yaml", "pth", "pt2", "expected"): + assert not (directory / f"deeppot_dpa_spin.{extension}").exists() + + +def test_reuse_copies_checked_model0_then_exports_pth_and_keeps_diagnostics(generator): + module, calls, directory, data = generator + _complete_dpa3(directory) + module.main(reuse_model_devi=True) + assert calls["exports"] == [_export(directory, "deeppot_dpa_spin.pth")] + assert len(calls["reuse"]) == 1 + src, dst, actual_data = calls["reuse"][0] + assert Path(src) == directory / "deeppot_dpa_spin_md0.pt2" + assert Path(dst) == directory / "deeppot_dpa_spin.pt2" + assert actual_data is data + assert calls["yaml_loads"] == [str(directory / "deeppot_dpa_spin.yaml")] + assert calls["events"] == ["reuse", "export", "eval", "eval", "reference", "eval"] + assert Path(dst).read_bytes() == Path(src).read_bytes() + for name in _DPA3_MODELS: + assert (directory / name).read_bytes() == name.encode() + _assert_diagnostics(calls, directory) + + +@pytest.mark.parametrize("missing", (*_DPA3_MODELS, "deeppot_dpa_spin_md0.pt2")) +def test_reuse_requires_both_completed_producers_without_exporting(generator, missing): + module, calls, directory, _ = generator + _complete_dpa3(directory) + (directory / missing).unlink() + with pytest.raises(FileNotFoundError, match=missing): + module.main(reuse_model_devi=True) + assert not any(calls.values()) + + +def test_reuse_rejection_does_not_export_or_evaluate(generator, monkeypatch): + module, calls, directory, _ = generator + _complete_dpa3(directory) + + def reject(*args): + raise ValueError("Model architecture or weights differ") + + monkeypatch.setattr(module, "reuse_pt2", reject) + with pytest.raises(ValueError, match="architecture or weights"): + module.main(reuse_model_devi=True) + for key in ("exports", "loads", "evals", "refs"): + assert not calls[key] + assert not (directory / "deeppot_dpa_spin.pt2").exists() + + +def test_modes_are_mutually_exclusive(generator): + module, calls, _, _ = generator + with pytest.raises(ValueError, match="mutually exclusive"): + module.main(dpa3_only=True, reuse_model_devi=True) + assert not any(calls.values()) + + +def test_cli_modes_are_mutually_exclusive(monkeypatch): + script = Path(__file__).with_name("gen_spin.py") + monkeypatch.syspath_prepend(str(script.parent)) + monkeypatch.setattr(sys, "argv", [str(script), "--dpa3-only", "--reuse-model-devi"]) + with pytest.raises(SystemExit) as error: + runpy.run_path(str(script), run_name="__main__") + assert error.value.code == 2 + + +def test_committed_model0_reuses_for_baseline_but_seed2_is_rejected(tmp_path): + pytest.importorskip("torch") + from deepmd.dpmodel.utils.serialization import ( + load_dp_model, + ) + from deepmd.pt_expt.utils.serialization import ( + _numpy_to_json_serializable, + ) + + directory = Path(__file__).parent + base = load_dp_model(str(directory / "deeppot_dpa_spin.yaml")) + md0 = load_dp_model(str(directory / "deeppot_dpa_spin_md0.yaml")) + md1 = load_dp_model(str(directory / "deeppot_dpa_spin_md1.yaml")) + assert base["time"] != md0["time"] + assert base["model_def_script"] == md0["model_def_script"] + + def write_archive(path, data): + # Use the real JSON encoding and archive reader. The placeholder + # executable is never loaded or compiled. + with zipfile.ZipFile(path, "w") as archive: + archive.writestr( + "model/extra/model.json", json.dumps(_numpy_to_json_serializable(data)) + ) + archive.writestr( + "model/extra/metadata.json", + json.dumps({"lower_input_kind": "nlist", "do_atomic_virial": True}), + ) + archive.writestr( + "model/extra/model_def_script.json", + json.dumps(data["model_def_script"]), + ) + archive.writestr("model/kernel.so", b"placeholder, never loaded") + + src = tmp_path / "md0.pt2" + dst = tmp_path / "baseline.pt2" + write_archive(src, md0) + # This checks every serialized weight's dtype, shape and value, not only + # seed or architecture, in the same direction used by gen_spin.py. + reuse_pt2(str(src), str(dst), base) + assert dst.read_bytes() == src.read_bytes() + wrong = tmp_path / "md1.pt2" + rejected = tmp_path / "rejected.pt2" + write_archive(wrong, md1) + with pytest.raises(ValueError, match="architecture or weights"): + reuse_pt2(str(wrong), str(rejected), base) + assert not rejected.exists() diff --git a/source/tests/jax/test_make_hessian_model.py b/source/tests/jax/test_make_hessian_model.py index e9fe727139..5a81144eb5 100644 --- a/source/tests/jax/test_make_hessian_model.py +++ b/source/tests/jax/test_make_hessian_model.py @@ -7,6 +7,7 @@ from deepmd.dpmodel.common import ( to_numpy_array, ) +from deepmd.dpmodel.model import EnergyModel as EnergyModelDP from deepmd.dpmodel.output_def import ( OutputVariableCategory, ) @@ -35,9 +36,20 @@ def finite_hessian(f, x, delta=1e-6): + """Reuse identical oracle inputs within one finite-difference Hessian.""" in_shape = x.shape assert len(in_shape) == 1 - y0 = f(x) + values = {} + + def evaluate(point): + """Evaluate one exact input without retaining caller-owned buffers.""" + key = (point.dtype.str, point.shape, point.tobytes()) + if key not in values: + # A reference evaluator may return a reusable output buffer. + values[key] = np.array(f(point), copy=True) + return values[key] + + y0 = evaluate(x) out_shape = y0.shape res = np.empty(out_shape + in_shape + in_shape) for iidx in np.ndindex(*in_shape): @@ -54,14 +66,36 @@ def finite_hessian(f, x, delta=1e-6): i1[jidx] += delta i2[jidx] -= delta i3[jidx] -= delta - y0 = f(x + i0) - y1 = f(x + i1) - y2 = f(x + i2) - y3 = f(x + i3) + y0 = evaluate(x + i0) + y1 = evaluate(x + i1) + y2 = evaluate(x + i2) + y3 = evaluate(x + i3) res[(Ellipsis, *iidx, *jidx)] = (y0 + y3 - y1 - y2) / (4 * delta**2.0) return res +class TestFiniteHessian(unittest.TestCase): + def test_reuses_inputs_without_sharing_between_calls(self): + """Keep every Hessian entry while evaluating each input only once.""" + x = np.arange(9, dtype=np.float64) / 10 + calls = [] + buffer = np.empty(2) + + def oracle(point): + """Return two quadratic outputs through a deliberately reused buffer.""" + calls.append(point.copy()) + buffer[:] = (point @ point, np.sum(point) ** 2) + return buffer + + expected = np.stack((2 * np.eye(9), 2 * np.ones((9, 9)))) + for point in (x, x, x + 1): + calls.clear() + actual = finite_hessian(oracle, point, delta=1e-3) + np.testing.assert_allclose(actual, expected, rtol=1e-7, atol=1e-7) + self.assertEqual(len(calls), 2 * point.size**2 + 1) + self.assertEqual(len({value.tobytes() for value in calls}), len(calls)) + + class HessianTest: def test( self, @@ -102,26 +136,32 @@ def test( np.testing.assert_allclose(ret_dict0["energy"], ret_dict1["energy"]) ana_hess = ret_dict0["hessian"] + # Reuse the JAX atomic model with the value-only DP-model wrapper. + # Numerical energy differences do not need forces or virials, and the + # JAX model would differentiate the energy at every stencil point. + model_energy = EnergyModelDP(atomic_model_=self.model_valu.atomic_model) + np.testing.assert_allclose( + model_energy(coord, atype, box=cell, fparam=fparam, aparam=aparam)[ + "energy" + ], + ret_dict1["energy"], + ) + # compute finite difference fnt_hess = [] for ii in range(nf): - def np_infer( + def ff( xx, ): - ret = self.model_valu( + ret = model_energy( to_jax_array(xx)[None, ...], atype[ii][None, ...], box=cell[ii][None, ...], fparam=fparam[ii][None, ...], aparam=aparam[ii][None, ...], ) - # detach - ret = {kk: to_numpy_array(ret[kk]) for kk in ret} - return ret - - def ff(xx): - return np_infer(xx)["energy"] + return to_numpy_array(ret["energy"]) xx = to_numpy_array(coord[ii]) fnt_hess.append(finite_hessian(ff, xx, delta=delta).squeeze()) diff --git a/source/tests/pt/model/test_descriptor_dpa1_triton.py b/source/tests/pt/model/test_descriptor_dpa1_triton.py index 982d069dab..72bc73f6ab 100644 --- a/source/tests/pt/model/test_descriptor_dpa1_triton.py +++ b/source/tests/pt/model/test_descriptor_dpa1_triton.py @@ -190,15 +190,10 @@ def test_backward_matches_reference(self) -> None: self.device, basis_dim=basis_dim, ) - gout = torch.randn_like( - _se_conv_reference( - z2, h1, idt, tt, idx, sw, basis, mult, act, gated - ) - ) ref_in = [ t.detach().clone().requires_grad_(True) for t in (z2, h1, sw, basis) ] - _se_conv_reference( + reference = _se_conv_reference( ref_in[0], ref_in[1], idt, @@ -209,7 +204,10 @@ def test_backward_matches_reference(self) -> None: mult, act, gated, - ).backward(gout) + ) + gout = torch.randn_like(reference) + reference.backward(gout) + del reference got_in = [ t.detach().clone().requires_grad_(True) for t in (z2, h1, sw, basis) ] @@ -344,15 +342,15 @@ def test_backward_matches_reference(self) -> None: self.n_edge, self.n_node, ng, mult, has_idt, 169, self.device ) tail = (dst, em, self.n_node, mult, act, gated) - gout = torch.randn_like( - _edge_conv_reference(z2, h1, idt, tt, idx, sw, rr, *tail) - ) ref_in = [ t.detach().clone().requires_grad_(True) for t in (z2, h1, sw, rr) ] - _edge_conv_reference( + reference = _edge_conv_reference( ref_in[0], ref_in[1], idt, tt, idx, ref_in[2], ref_in[3], *tail - ).backward(gout) + ) + gout = torch.randn_like(reference) + reference.backward(gout) + del reference got_in = [ t.detach().clone().requires_grad_(True) for t in (z2, h1, sw, rr) ] @@ -410,13 +408,13 @@ def _check(self, ng: int, mult: int, gated: int, act: int) -> None: 512, n_node, ng, mult, True, 37, dev ) tail = (dst, em, n_node, mult, act, gated) - gout = torch.randn_like( - _edge_conv_reference(z2, h1, idt, tt, idx, sw, rr, *tail) - ) leaves = [t.detach().clone().requires_grad_(True) for t in (z2, h1, sw, rr)] - _edge_conv_reference( + reference = _edge_conv_reference( leaves[0], leaves[1], idt, tt, idx, leaves[2], leaves[3], *tail - ).backward(gout) + ) + gout = torch.randn_like(reference) + reference.backward(gout) + del reference closed = dict( zip( ("z2", "h1", "sw", "rr"), diff --git a/source/tests/pt/model/test_descriptor_sezm_triton.py b/source/tests/pt/model/test_descriptor_sezm_triton.py index f359f073d6..cfd2516020 100644 --- a/source/tests/pt/model/test_descriptor_sezm_triton.py +++ b/source/tests/pt/model/test_descriptor_sezm_triton.py @@ -1512,7 +1512,8 @@ def randn(*shape): gw_all = randn(self.N_LAYERS - 1, n_focus, focus_dim, half) * 0.3 return u0, alpha, w0_all, w1_all, gw_all - def _errors_against_fp64(self, op, u0, alpha, w0_all, w1_all, gw_all, grad_seed): + def _fp64_reference(self, u0, alpha, w0_all, w1_all, gw_all, grad_seed): + """Evaluate one oracle for both fp32 and fp16x3 on identical operands.""" from deepmd.pt_expt.kernels.triton.sezm.so2_value_path import ( _mixing_stack_reference, ) @@ -1530,7 +1531,12 @@ def _errors_against_fp64(self, op, u0, alpha, w0_all, w1_all, gw_all, grad_seed) True, ) gu_ref, _ = torch.autograd.grad(x_ref, [u0_ref, alpha_ref], grad_seed.double()) + return x_ref.detach(), gu_ref.detach() + def _errors_against_fp64( + self, op, u0, alpha, w0_all, w1_all, gw_all, grad_seed, *, reference + ): + x_ref, gu_ref = reference u0_run = u0.clone().requires_grad_(True) alpha_run = alpha.clone().requires_grad_(True) stack_output = op( @@ -1562,11 +1568,12 @@ def test_matches_fp64_within_fp32_error_budget(self): self.N_EDGE, self.N_FOCUS, row, device="cuda", generator=generator ) + reference = self._fp64_reference(*inputs, grad_seed) fp32_fwd, fp32_bwd = self._errors_against_fp64( - _mixing_stack_op, *inputs, grad_seed + _mixing_stack_op, *inputs, grad_seed, reference=reference ) x3_fwd, x3_bwd = self._errors_against_fp64( - mixing_stack_fp16x3, *inputs, grad_seed + mixing_stack_fp16x3, *inputs, grad_seed, reference=reference ) self.assertLess(x3_fwd, max(3.0 * fp32_fwd, 2e-6)) self.assertLess(x3_bwd, max(3.0 * fp32_bwd, 8e-6)) @@ -1595,12 +1602,14 @@ def test_extreme_input_scales_stay_finite_and_accurate(self): for scale in (1e-4, 1e2): with self.subTest(scale=scale): scaled = (u0 * scale, alpha, w0_all, w1_all, gw_all) + reference = self._fp64_reference(*scaled, grad_seed) fp32_fwd, fp32_bwd = self._errors_against_fp64( - _mixing_stack_op, *scaled, grad_seed + _mixing_stack_op, *scaled, grad_seed, reference=reference ) x3_fwd, x3_bwd = self._errors_against_fp64( - mixing_stack_fp16x3, *scaled, grad_seed + mixing_stack_fp16x3, *scaled, grad_seed, reference=reference ) + del reference self.assertLess(x3_fwd, max(3.0 * fp32_fwd, 2e-6)) self.assertLess(x3_bwd, max(3.0 * fp32_bwd, 8e-6)) diff --git a/source/tests/pt/model/test_jit.py b/source/tests/pt/model/test_jit.py index 0fc672db86..c1d9e63e0e 100644 --- a/source/tests/pt/model/test_jit.py +++ b/source/tests/pt/model/test_jit.py @@ -30,6 +30,11 @@ class JITTest: def test_jit(self) -> None: + # Sample multiple batches without repeating statistics for this smoke test. + self.config["model"]["data_stat_nbatch"] = 2 + # One update is enough to exercise checkpoint loading before scripting. + self.config["training"]["numb_steps"] = 1 + self.config["training"]["save_freq"] = 1 trainer = get_trainer(deepcopy(self.config)) trainer.run() model = torch.jit.script(inference.Tester("./model.pt").model) @@ -56,8 +61,6 @@ def setUp(self) -> None: self.config["training"]["training_data"]["systems"] = data_file self.config["training"]["validation_data"]["systems"] = data_file self.config["model"] = deepcopy(model_se_e2_a) - self.config["training"]["numb_steps"] = 10 - self.config["training"]["save_freq"] = 10 def tearDown(self) -> None: JITTest.tearDown(self) @@ -72,8 +75,6 @@ def setUp(self) -> None: self.config["training"]["training_data"]["systems"] = data_file self.config["training"]["validation_data"]["systems"] = data_file self.config["model"] = deepcopy(model_dos) - self.config["training"]["numb_steps"] = 10 - self.config["training"]["save_freq"] = 10 def tearDown(self) -> None: JITTest.tearDown(self) @@ -88,8 +89,6 @@ def setUp(self) -> None: self.config["training"]["training_data"]["systems"] = data_file self.config["training"]["validation_data"]["systems"] = data_file self.config["model"] = deepcopy(model_dpa1) - self.config["training"]["numb_steps"] = 10 - self.config["training"]["save_freq"] = 10 def tearDown(self) -> None: JITTest.tearDown(self) @@ -104,8 +103,6 @@ def setUp(self) -> None: self.config["training"]["training_data"]["systems"] = data_file self.config["training"]["validation_data"]["systems"] = data_file self.config["model"] = deepcopy(model_dpa2) - self.config["training"]["numb_steps"] = 10 - self.config["training"]["save_freq"] = 10 def tearDown(self) -> None: JITTest.tearDown(self) @@ -120,25 +117,6 @@ def setUp(self) -> None: self.config["training"]["training_data"]["systems"] = data_file self.config["training"]["validation_data"]["systems"] = data_file self.config["model"] = deepcopy(model_hybrid) - self.config["training"]["numb_steps"] = 10 - self.config["training"]["save_freq"] = 10 - - def tearDown(self) -> None: - JITTest.tearDown(self) - - -class TestEnergyModelHybrid2(unittest.TestCase, JITTest): - def setUp(self) -> None: - input_json = str(Path(__file__).parent / "water/se_atten.json") - with open(input_json) as f: - self.config = json.load(f) - data_file = [str(Path(__file__).parent / "water/data/data_0")] - self.config["training"]["training_data"]["systems"] = data_file - self.config["training"]["validation_data"]["systems"] = data_file - self.config["model"] = deepcopy(model_hybrid) - # self.config["model"]["descriptor"]["hybrid_mode"] = "sequential" - self.config["training"]["numb_steps"] = 10 - self.config["training"]["save_freq"] = 10 def tearDown(self) -> None: JITTest.tearDown(self) @@ -159,8 +137,6 @@ def setUp(self) -> None: self.config["model"]["descriptor"]["repinit"]["rcut_smth"] = int( self.config["model"]["descriptor"]["repinit"]["rcut_smth"] ) - self.config["training"]["numb_steps"] = 10 - self.config["training"]["save_freq"] = 10 def tearDown(self) -> None: JITTest.tearDown(self) diff --git a/source/tests/pt/model/test_mlp.py b/source/tests/pt/model/test_mlp.py index 5f067cb0e6..bb129be843 100644 --- a/source/tests/pt/model/test_mlp.py +++ b/source/tests/pt/model/test_mlp.py @@ -37,14 +37,15 @@ def setUp(self) -> None: [True, False], # use time step ["tanh", "none"], # activation [True, False], # resnet - [None, [4], [3, 2]], # prefix shapes ["float32", "double"], # precision ) def test_match_native_layer( self, ) -> None: - for (ninp, nout), bias, ut, ac, resnet, ashp, prec in self.test_cases: + for ((ninp, nout), bias, ut, ac, resnet, prec), ashp in itertools.product( + self.test_cases, [None, [4], [3, 2]] + ): # input inp_shap = [ninp] if ashp is not None: @@ -78,7 +79,7 @@ def test_match_native_layer( ) def test_jit(self) -> None: - for (ninp, nout), bias, ut, ac, resnet, _, prec in self.test_cases: + for (ninp, nout), bias, ut, ac, resnet, prec in self.test_cases: ml = MLPLayer(ninp, nout, bias, ut, ac, resnet, precision=prec) model = torch.jit.script(ml) ml1 = MLPLayer.deserialize(ml.serialize()) @@ -93,14 +94,15 @@ def setUp(self) -> None: [True, False], # use time step ["tanh", "none"], # activation [True, False], # resnet - [None, [4], [3, 2]], # prefix shapes ["float32", "double"], # precision ) def test_match_native_net( self, ) -> None: - for ndims, bias, ut, ac, resnet, ashp, prec in self.test_cases: + for (ndims, bias, ut, ac, resnet, prec), ashp in itertools.product( + self.test_cases, [None, [4], [3, 2]] + ): # input inp_shap = [ndims[0]] if ashp is not None: @@ -139,17 +141,19 @@ def test_match_native_net( ) def test_jit(self) -> None: - for ndims, bias, ut, ac, resnet, _, prec in self.test_cases: + for ndims, bias, ut, ac, resnet, prec in self.test_cases: layers = [] for ii in range(1, len(ndims)): - ml = layers.append( + layers.append( MLPLayer( ndims[ii - 1], ndims[ii], bias, ut, ac, resnet, precision=prec ).serialize() ) - ml = MLP(ml) + ml = MLP(layers) + self.assertEqual(len(ml.layers), len(ndims) - 1) model = torch.jit.script(ml) ml1 = MLP.deserialize(ml.serialize()) + self.assertEqual(len(ml1.layers), len(ndims) - 1) model = torch.jit.script(ml1) diff --git a/source/tests/pt/model/test_sezm_export.py b/source/tests/pt/model/test_sezm_export.py index 037bc2d4ba..38500a873e 100644 --- a/source/tests/pt/model/test_sezm_export.py +++ b/source/tests/pt/model/test_sezm_export.py @@ -510,11 +510,11 @@ def test_loaded_pte_matches_eager_different_nloc(self) -> None: class _FrozenPt2Fixture(_ClearDefaultDeviceTestCase): - """Shared setUp/tearDown: freeze a tiny SeZM checkpoint to ``.pt2`` once. + """Freeze a tiny SeZM checkpoint once for archive and inference checks. - AOTInductor compilation costs a few seconds; classes that share this - fixture avoid paying that cost twice. ``cls.ckpt_path`` / ``cls.out_path`` - / ``cls.params`` are populated and live for the lifetime of the class. + The checks share one test class, so CI keeps them together and does not + repeat the expensive AOTInductor compilation on another shard. + ``cls.ckpt_path`` / ``cls.out_path`` / ``cls.params`` live for the class. """ params: dict @@ -553,8 +553,7 @@ def tearDownClass(cls) -> None: super().tearDownClass() -@unittest.skipIf(_SKIP_OFF_COMPILE_TORCH, _SKIP_OFF_COMPILE_TORCH_REASON) -class TestSeZMExportArchive(_FrozenPt2Fixture): +class _SeZMExportArchiveChecks: """AOTI ``.pt2`` archive structure + load-and-run smoke. Numerical parity of the compiled ``.pt2`` is covered by the @@ -646,9 +645,19 @@ def test_aoti_load_and_run_returns_finite_outputs(self) -> None: self.assertIn(key, out_map) self.assertTrue(torch.isfinite(out_map[key]).all().item()) + def test_freeze_embeds_with_comm_artifact(self) -> None: + """The real compiled archive includes the multi-rank with-comm artifact.""" + with zipfile.ZipFile(self.out_path, "r") as archive: + names = archive.namelist() + metadata = json.loads(archive.read("model/extra/metadata.json")) + + self.assertTrue(metadata["has_comm_artifact"]) + self.assertTrue(metadata["has_message_passing"]) + self.assertIn("model/extra/forward_lower_with_comm.pt2", names) + @unittest.skipIf(_SKIP_OFF_COMPILE_TORCH, _SKIP_OFF_COMPILE_TORCH_REASON) -class TestSeZMViaDeepPot(_FrozenPt2Fixture): +class TestSeZMViaDeepPot(_SeZMExportArchiveChecks, _FrozenPt2Fixture): """Integration through the standard :class:`deepmd.infer.DeepPot` entry. Locks in the contract that makes ``dp test -m frozen.pt2`` and the @@ -1070,36 +1079,6 @@ def fake_compile(_exported: torch.export.ExportedProgram, package_path: str): self.assertTrue(metadata["has_comm_artifact"]) self.assertIn("model/extra/forward_lower_with_comm.pt2", names) - @unittest.skipIf(_SKIP_OFF_COMPILE_TORCH, _SKIP_OFF_COMPILE_TORCH_REASON) - def test_freeze_embeds_with_comm_artifact(self) -> None: - """A plain SeZM checkpoint ships the nested multi-rank with-comm artifact.""" - - def fake_compile(_exported: torch.export.ExportedProgram, package_path: str): - with zipfile.ZipFile(package_path, "w") as zf: - zf.writestr("model/data.pkl", b"") - - with tempfile.TemporaryDirectory() as tmp: - tmp_path = Path(tmp) - params = _tiny_sezm_model_params() - ckpt_path = _write_tiny_sezm_checkpoint(tmp_path, params) - out = tmp_path / "with_comm.pt2" - - with mock.patch( - "torch._inductor.aoti_compile_and_package", - side_effect=fake_compile, - ): - freeze_sezm_to_pt2(str(ckpt_path), str(out), device=_CPU) - - with zipfile.ZipFile(str(out), "r") as zf: - names = zf.namelist() - metadata = json.loads( - zf.read("model/extra/metadata.json").decode("utf-8") - ) - - self.assertTrue(metadata["has_comm_artifact"]) - self.assertTrue(metadata["has_message_passing"]) - self.assertIn("model/extra/forward_lower_with_comm.pt2", names) - if __name__ == "__main__": unittest.main() diff --git a/source/tests/pt/model/test_sezm_vacuum_freeze.py b/source/tests/pt/model/test_sezm_vacuum_freeze.py index bb1bce9490..58959aa172 100644 --- a/source/tests/pt/model/test_sezm_vacuum_freeze.py +++ b/source/tests/pt/model/test_sezm_vacuum_freeze.py @@ -139,7 +139,9 @@ def check_frozen_model( ckpt = Path(tmp) / "vacuum.pt" torch.save({"model": wrapper.state_dict()}, ckpt) out = Path(tmp) / "vacuum.pt2" - freeze_sezm_to_pt2(str(ckpt), str(out), device=device) + # These checks consume only the single-process artifact. Parallel + # export and communication parity have their own tests. + freeze_sezm_to_pt2(str(ckpt), str(out), device=device, with_comm=False) # the evaluator runs on the device the archive is compiled for saved_device = pt_expt_env.DEVICE pt_expt_env.DEVICE = device diff --git a/source/tests/pt/test_data_modifier.py b/source/tests/pt/test_data_modifier.py index 7b8f8096ce..70174301e0 100644 --- a/source/tests/pt/test_data_modifier.py +++ b/source/tests/pt/test_data_modifier.py @@ -15,12 +15,18 @@ import json import os +import shutil +import tempfile import unittest +from copy import ( + deepcopy, +) from pathlib import ( Path, ) import numpy as np +import pytest import torch from dargs import ( Argument, @@ -225,22 +231,53 @@ def forward( return model_pred +@pytest.fixture(scope="module") +def modifier_reference_path(tmp_path_factory) -> Path: + """Share only the unmodified frozen reference, never a mutable trainer.""" + return tmp_path_factory.mktemp("modifier_reference") / "reference.pth" + + @parameterized( (1, 2), # training data batch_size (1, 2), # validation data batch_size (True, False), # use_cache ) class TestDataModifier(unittest.TestCase): + @pytest.fixture + def _modifier_reference(self, modifier_reference_path) -> None: + self.modifier_reference_path = modifier_reference_path + def setUp(self) -> None: """Set up test fixtures.""" input_json = str(Path(__file__).parent / "water/se_e2_a.json") - training_data = [ - str(Path(__file__).parent / "water/data/data_0"), - str(Path(__file__).parent / "water/data/data_1"), - ] - validation_data = [str(Path(__file__).parent / "water/data/data_1")] + # Four distinct frames per system exercise both batch sizes, cache + # reuse, and multiple systems without modifying all 240 source frames + # before every test. Keep the real coordinates, forces, and atom types. + data_dir = tempfile.TemporaryDirectory(prefix="pt_modifier_data_") + self.addCleanup(data_dir.cleanup) + if not hasattr(self, "modifier_reference_path"): + # unittest does not inject pytest fixtures. Keep standalone runs + # independent, while pytest shares its immutable module reference. + self.modifier_reference_path = Path(data_dir.name) / "reference.pth" + training_data = [] + for name in ("data_0", "data_1"): + source = Path(__file__).parent / "water/data" / name + target = Path(data_dir.name) / name + (target / "set.000").mkdir(parents=True) + for filename in ("type.raw", "type_map.raw"): + shutil.copyfile(source / filename, target / filename) + for array in (source / "set.000").glob("*.npy"): + np.save(target / "set.000" / array.name, np.load(array)[:4]) + training_data.append(str(target)) + validation_data = [training_data[1]] with open(input_json, encoding="utf-8") as f: config = json.load(f) + # Modifier correctness is independent of network width. Still train + # and freeze a real energy/force model for every parameter combination. + config["model"]["descriptor"]["neuron"] = [8, 16] + config["model"]["descriptor"]["axis_neuron"] = 4 + config["model"]["fitting_net"]["neuron"] = [16, 16] + config["model"]["data_stat_nbatch"] = 2 config["training"]["numb_steps"] = 1 config["training"]["save_freq"] = 1 config["learning_rate"]["start_lr"] = 1.0 @@ -255,7 +292,7 @@ def setUp(self) -> None: def test_init_modify_data(self): """Ensure modify_data applied.""" - tmp_config = self.config.copy() + tmp_config = deepcopy(self.config) # add tester data modifier tmp_config["model"]["modifier"] = { "type": "zero_tester", @@ -277,7 +314,7 @@ def test_init_modify_data(self): def test_full_modify_data(self): """Ensure modify_data only applied once.""" - tmp_config = self.config.copy() + tmp_config = deepcopy(self.config) # add tester data modifier tmp_config["model"]["modifier"] = { "type": "random_tester", @@ -314,19 +351,24 @@ def test_full_modify_data(self): validation_data_before, validation_data_after, label_kw ) + @pytest.mark.usefixtures("_modifier_reference") def test_inference(self): """Test the inference with data modification by verifying scaled model predictions are properly applied.""" - # Generate frozen energy model used in modifier - trainer = get_trainer(self.config) - trainer.run() - freeze("model.ckpt.pt", "frozen_model_dm.pth") - - tmp_config = self.config.copy() + # The reference is arbitrary trained weights, independent of the + # modifier's batch/cache matrix. Prepare it once; each case still + # trains and freezes its own modifier-bearing model below. + reference_path = str(self.modifier_reference_path) + if not self.modifier_reference_path.exists(): + trainer = get_trainer(deepcopy(self.config)) + trainer.run() + freeze("model.ckpt.pt", reference_path) + + tmp_config = deepcopy(self.config) sfactor = np.random.default_rng(1).random() # add tester data modifier tmp_config["model"]["modifier"] = { "type": "scaling_tester", - "model_name": "frozen_model_dm.pth", + "model_name": reference_path, "sfactor": sfactor, "use_cache": self.param[2], } @@ -370,7 +412,7 @@ def test_inference(self): atype = np.array([0, 0, 0, 1, 1]).reshape(1, -1) model = DeepEval("frozen_model.pth") - modifier = DeepEval("frozen_model_dm.pth") + modifier = DeepEval(reference_path) # model inference without modifier model_ref = DeepEval("model.ckpt.pt") @@ -379,9 +421,18 @@ def test_inference(self): model_pred_ref = model_ref.eval(coord, cell, atype) # expected: output_model = output_model_ref + sfactor * output_modifier for ii in range(3): + # The compact reference must still make a real correction in all + # three outputs; otherwise additive parity could pass vacuously. + self.assertTrue(np.isfinite(modifier_pred[ii]).all()) + self.assertGreater(np.max(np.abs(modifier_pred[ii])), 1e-10) + expected = model_pred_ref[ii] + sfactor * modifier_pred[ii] + self.assertFalse( + np.allclose(model_pred_ref[ii], expected, rtol=1e-5, atol=1e-8), + "Omitting the modifier must fail the inference tolerance", + ) np.testing.assert_allclose( model_pred[ii], - model_pred_ref[ii] + sfactor * modifier_pred[ii], + expected, rtol=1e-5, atol=1e-8, ) @@ -421,13 +472,13 @@ def get_dataset_nframes(dataset: list[str]) -> int: return nframes @staticmethod - def get_sampled_data(trainer, nbatch: int, is_train: bool): + def get_sampled_data(trainer, nframes: int, is_train: bool): """ Collect all data from trainer and organize by IDs for easy comparison. Args: trainer: The trainer object - nbatch: Number of batches to iterate through + nframes: Total number of distinct frames across the datasets is_train: Whether to get training data (True) or validation data (False) Returns @@ -439,8 +490,9 @@ def get_sampled_data(trainer, nbatch: int, is_train: bool): # Keep track of all unique frames we've collected collected_frames = set() - # Continue collecting data until we've gone through all batches - for _ in range(nbatch): + # Sampling selects systems randomly. Require every frame, rather than + # comparing only a possibly empty intersection of two partial passes. + for _ in range(10 * nframes): _, label_dict, log_dict = trainer.get_data(is_train=is_train) system_id = log_dict["sid"] @@ -474,8 +526,12 @@ def get_sampled_data(trainer, nbatch: int, is_train: bool): output[system_id][frame_id] = frame_data collected_frames.add(frame_key) + if len(collected_frames) == nframes: + return output - return output + raise AssertionError( + f"Collected {len(collected_frames)} of {nframes} expected frames" + ) @staticmethod def check_sampled_data( @@ -492,14 +548,12 @@ def check_sampled_data( ------ AssertionError: If the data doesn't match between reference and test """ - for sid in ref_data.keys(): + assert ref_data.keys() == test_data.keys() + for sid in ref_data: ref_sys = ref_data[sid] test_sys = test_data[sid] - for fid in ref_sys.keys(): - # compare common elements - try: - ref_label = to_numpy_array(ref_sys[fid][label_kw]) - test_label = to_numpy_array(test_sys[fid][label_kw]) - except KeyError: - continue + assert ref_sys.keys() == test_sys.keys() + for fid in ref_sys: + ref_label = to_numpy_array(ref_sys[fid][label_kw]) + test_label = to_numpy_array(test_sys[fid][label_kw]) np.testing.assert_allclose(ref_label, test_label) diff --git a/source/tests/pt/test_training.py b/source/tests/pt/test_training.py index 052d0166c6..9b06c8d15b 100644 --- a/source/tests/pt/test_training.py +++ b/source/tests/pt/test_training.py @@ -201,8 +201,13 @@ def mark_remote_rank_empty( class DPTrainTest: test_zbl_from_standard: bool = False + stat_nbatch: int = 2 def test_dp_train(self) -> None: + # Keep multi-batch statistics without repeating sampling for finetuning. + self.config["model"]["data_stat_nbatch"] = self.stat_nbatch + if self.test_zbl_from_standard: + self.config_zbl["model"]["data_stat_nbatch"] = self.stat_nbatch # test training from scratch trainer = get_trainer(deepcopy(self.config)) trainer.run() @@ -306,6 +311,7 @@ def test_dp_train(self) -> None: def test_trainable(self) -> None: fix_params = deepcopy(self.config) + fix_params["model"]["data_stat_nbatch"] = self.stat_nbatch fix_params["model"]["descriptor"]["trainable"] = False fix_params["model"]["fitting_net"]["trainable"] = False free_descriptor = hasattr(self, "not_all_grad") and self.not_all_grad @@ -447,6 +453,9 @@ def tearDown(self) -> None: class TestFparam(unittest.TestCase, DPTrainTest): """Test if `fparam` can be loaded correctly.""" + # Preserve full-dataset sampling for the fparam normalization transfer test. + stat_nbatch = 100 + def setUp(self) -> None: input_json = str(Path(__file__).parent / "water/se_atten.json") with open(input_json) as f: @@ -950,6 +959,18 @@ def test_fitting_stat_consistency(self) -> None: ) +def _small_control_flow_model() -> dict: + """Keep real energy/force training cheap for checkpoint and schedule tests.""" + model = deepcopy(model_se_e2_a) + model["descriptor"]["neuron"] = [4, 8] + model["descriptor"]["axis_neuron"] = 4 + model["fitting_net"]["neuron"] = [8, 8] + # Exercise statistics on multiple batches without sampling twenty batches + # for tests whose assertions concern training control flow, not accuracy. + model["data_stat_nbatch"] = 2 + return model + + class TestLearningRateRestart(unittest.TestCase): def setUp(self) -> None: self._cwd = os.getcwd() @@ -962,7 +983,7 @@ def setUp(self) -> None: data_file = [str(Path(__file__).parent / "water/data/data_0")] self.config["training"]["training_data"]["systems"] = data_file self.config["training"]["validation_data"]["systems"] = data_file - self.config["model"] = deepcopy(model_se_e2_a) + self.config["model"] = _small_control_flow_model() self.config["learning_rate"] = { "type": "wsd", "start_lr": 5e-4, @@ -1024,7 +1045,7 @@ def setUp(self) -> None: data_file = [str(Path(__file__).parent / "water/data/data_0")] self.config["training"]["training_data"]["systems"] = data_file self.config["training"]["validation_data"]["systems"] = data_file - self.config["model"] = deepcopy(model_se_e2_a) + self.config["model"] = _small_control_flow_model() self.config["training"]["numb_steps"] = 4 self.config["training"]["save_freq"] = 100 self.config["training"]["disp_training"] = False @@ -1256,7 +1277,7 @@ def setUp(self) -> None: data_file = [str(Path(__file__).parent / "water/data/data_0")] self.config["training"]["training_data"]["systems"] = data_file self.config["training"]["validation_data"]["systems"] = data_file - self.config["model"] = deepcopy(model_se_e2_a) + self.config["model"] = _small_control_flow_model() self.config["training"]["numb_steps"] = 2 self.config["training"]["save_freq"] = 2 self.config["training"]["disp_training"] = False @@ -1313,7 +1334,7 @@ def setUp(self) -> None: data_file = [str(Path(__file__).parent / "water/data/data_0")] self.config["training"]["training_data"]["systems"] = data_file self.config["training"]["validation_data"]["systems"] = data_file - self.config["model"] = deepcopy(model_se_e2_a) + self.config["model"] = _small_control_flow_model() self.config["training"]["numb_steps"] = 4 self.config["training"]["save_freq"] = 1 self.config["training"]["max_ckpt_keep"] = 3 diff --git a/source/tests/pt_expt/descriptor/test_dpa4c_cuda.py b/source/tests/pt_expt/descriptor/test_dpa4c_cuda.py index a23f8713a6..307ebd8f15 100644 --- a/source/tests/pt_expt/descriptor/test_dpa4c_cuda.py +++ b/source/tests/pt_expt/descriptor/test_dpa4c_cuda.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: LGPL-3.0-or-later """Numerical contract of the compressed DPA4C CUDA mega kernel.""" +import copy import dataclasses import functools import json @@ -155,18 +156,51 @@ def _build_graph( The atoms of each frame are uniform in a cube of ``side`` Å, and atom ``i`` carries type ``types[i % len(types)]``. """ - generator = torch.Generator(device="cuda").manual_seed(23) + template = _graph_template( + descriptor.rcut, + canonical, + node_count, + single_type, + side, + frames, + tuple(types), + torch.device("cuda", torch.cuda.current_device()), + ) + # Every caller owns its tensors: gradient leaves, masks, CSR buffers and + # atom types may be changed without contaminating another parameter case. + return copy.deepcopy(template) + + +@functools.lru_cache(maxsize=1) +def _graph_template( + rcut: float, + canonical: bool, + node_count: int, + single_type: bool, + side: float, + frames: int, + types: tuple[int, ...], + device: torch.device, +): + """Build the last geometry once, independent of descriptor channels. + + Large slotted/tiling cases repeatedly use the same geometry across channel, + degree and compression variants. The dense neighbor search is quadratic + in node count; cloning its compact result is linear in the edge count. + Keep only one template so the CUDA matrix cannot accumulate GPU graphs. + """ + generator = torch.Generator(device=device).manual_seed(23) coordinate = torch.rand( frames, node_count, 3, dtype=torch.float32, - device="cuda", + device=device, generator=generator, ) coordinate = coordinate * side - pattern = torch.as_tensor(list(types), device="cuda") - atype = pattern[torch.arange(node_count, device="cuda") % len(types)].repeat( + pattern = torch.as_tensor(list(types), device=device) + atype = pattern[torch.arange(node_count, device=device) % len(types)].repeat( frames, 1 ) if single_type: @@ -174,7 +208,7 @@ def _build_graph( coord_ext, atype_ext, mapping, nlist = extend_input_and_build_neighbor_list( coordinate, atype, - descriptor.rcut, + rcut, [48], mixed_types=True, box=None, @@ -193,6 +227,13 @@ def _build_graph( return graph, flat_type +@pytest.fixture(scope="module", autouse=True) +def _release_graph_template(): + """Release the one cached GPU graph when this module finishes.""" + yield + _graph_template.cache_clear() + + def _arguments( descriptor: DescrptDPA4C, graph, diff --git a/source/tests/pt_expt/infer/test_deep_eval.py b/source/tests/pt_expt/infer/test_deep_eval.py index c9acfdc147..112efd99ab 100644 --- a/source/tests/pt_expt/infer/test_deep_eval.py +++ b/source/tests/pt_expt/infer/test_deep_eval.py @@ -50,6 +50,52 @@ GLOBAL_SEED, ) +# These APIs read the same unconditioned models. Keep only the immutable files +# across classes: each consumer creates its own DeepPot (and deserialized model) +# so swapping _dpmodel for a conditioning check cannot affect another class. +_INTROSPECTION_ARCHIVES: dict[str, tuple[str, int]] = {} + + +def _introspection_archive(descriptor_type: str) -> tuple[str, int]: + if descriptor_type not in _INTROSPECTION_ARCHIVES: + if descriptor_type == "se_e2_a": + ds = DescrptSeA(4.0, 0.5, [8, 6], seed=GLOBAL_SEED) + else: + from deepmd.pt_expt.descriptor.dpa1 import ( + DescrptDPA1, + ) + + ds = DescrptDPA1(4.0, 0.5, [8, 6], ntypes=2, seed=GLOBAL_SEED) + ft = EnergyFittingNet( + 2, ds.get_dim_out(), mixed_types=ds.mixed_types(), seed=GLOBAL_SEED + ) + model = EnergyModel(ds, ft, type_map=["foo", "bar"]).to(torch.float64).eval() + with tempfile.NamedTemporaryFile(suffix=".pte", delete=False) as archive: + path = archive.name + try: + deserialize_to_file(path, {"model": model.serialize()}) + except BaseException: + os.unlink(path) + raise + _INTROSPECTION_ARCHIVES[descriptor_type] = path, ds.get_dim_out() + return _INTROSPECTION_ARCHIVES[descriptor_type] + + +def tearDownModule() -> None: + for path, _ in _INTROSPECTION_ARCHIVES.values(): + os.unlink(path) + _INTROSPECTION_ARCHIVES.clear() + + +def _set_up_introspection(cls) -> str: + cls.rcut, cls.rcut_smth = 4.0, 0.5 + cls.sel, cls.nt, cls.type_map = [8, 6], 2, ["foo", "bar"] + pte_sea, cls.dim_descrpt_sea = _introspection_archive("se_e2_a") + pte_dpa1, cls.dim_descrpt_dpa1 = _introspection_archive("dpa1") + cls.dp_sea = DeepPot(pte_sea) + cls.dp_dpa1 = DeepPot(pte_dpa1) + return pte_sea + def _assert_repeatable(a, b) -> None: """Two evals of the same inputs must agree. @@ -1686,58 +1732,7 @@ class TestEvalTypeEbd(unittest.TestCase): @classmethod def setUpClass(cls) -> None: - cls.rcut = 4.0 - cls.rcut_smth = 0.5 - cls.sel = [8, 6] - cls.nt = 2 - cls.type_map = ["foo", "bar"] - - # se_e2_a model (no type embedding) - ds_sea = DescrptSeA(cls.rcut, cls.rcut_smth, cls.sel) - ft_sea = EnergyFittingNet( - cls.nt, - ds_sea.get_dim_out(), - mixed_types=ds_sea.mixed_types(), - seed=GLOBAL_SEED, - ) - model_sea = EnergyModel(ds_sea, ft_sea, type_map=cls.type_map) - model_sea = model_sea.to(torch.float64) - model_sea.eval() - cls._tmpdir = tempfile.mkdtemp() - pte_sea = os.path.join(cls._tmpdir, "sea.pte") - deserialize_to_file(pte_sea, {"model": model_sea.serialize()}) - cls.dp_sea = DeepPot(pte_sea) - - # DPA1 model (has type embedding) - from deepmd.pt_expt.descriptor.dpa1 import ( - DescrptDPA1, - ) - - ds_dpa1 = DescrptDPA1( - cls.rcut, - cls.rcut_smth, - cls.sel, - ntypes=cls.nt, - seed=GLOBAL_SEED, - ) - ft_dpa1 = EnergyFittingNet( - cls.nt, - ds_dpa1.get_dim_out(), - mixed_types=ds_dpa1.mixed_types(), - seed=GLOBAL_SEED, - ) - model_dpa1 = EnergyModel(ds_dpa1, ft_dpa1, type_map=cls.type_map) - model_dpa1 = model_dpa1.to(torch.float64) - model_dpa1.eval() - pte_dpa1 = os.path.join(cls._tmpdir, "dpa1.pte") - deserialize_to_file(pte_dpa1, {"model": model_dpa1.serialize()}) - cls.dp_dpa1 = DeepPot(pte_dpa1) - - @classmethod - def tearDownClass(cls) -> None: - import shutil - - shutil.rmtree(cls._tmpdir, ignore_errors=True) + _set_up_introspection(cls) def test_typeebd_dpa1(self) -> None: """DPA1 model has type embedding, should return valid array.""" @@ -1758,54 +1753,7 @@ class TestEvalDescriptor(unittest.TestCase): @classmethod def setUpClass(cls) -> None: - cls.rcut = 4.0 - cls.rcut_smth = 0.5 - cls.sel = [8, 6] - cls.nt = 2 - cls.type_map = ["foo", "bar"] - - # se_e2_a model - ds_sea = DescrptSeA(cls.rcut, cls.rcut_smth, cls.sel) - ft_sea = EnergyFittingNet( - cls.nt, - ds_sea.get_dim_out(), - mixed_types=ds_sea.mixed_types(), - seed=GLOBAL_SEED, - ) - model_sea = EnergyModel(ds_sea, ft_sea, type_map=cls.type_map) - model_sea = model_sea.to(torch.float64) - model_sea.eval() - cls._tmpdir = tempfile.mkdtemp() - pte_sea = os.path.join(cls._tmpdir, "sea.pte") - deserialize_to_file(pte_sea, {"model": model_sea.serialize()}) - cls.dp_sea = DeepPot(pte_sea) - cls.dim_descrpt_sea = ds_sea.get_dim_out() - - # DPA1 model - from deepmd.pt_expt.descriptor.dpa1 import ( - DescrptDPA1, - ) - - ds_dpa1 = DescrptDPA1( - cls.rcut, - cls.rcut_smth, - cls.sel, - ntypes=cls.nt, - seed=GLOBAL_SEED, - ) - ft_dpa1 = EnergyFittingNet( - cls.nt, - ds_dpa1.get_dim_out(), - mixed_types=ds_dpa1.mixed_types(), - seed=GLOBAL_SEED, - ) - model_dpa1 = EnergyModel(ds_dpa1, ft_dpa1, type_map=cls.type_map) - model_dpa1 = model_dpa1.to(torch.float64) - model_dpa1.eval() - pte_dpa1 = os.path.join(cls._tmpdir, "dpa1.pte") - deserialize_to_file(pte_dpa1, {"model": model_dpa1.serialize()}) - cls.dp_dpa1 = DeepPot(pte_dpa1) - cls.dim_descrpt_dpa1 = ds_dpa1.get_dim_out() + pte_sea = _set_up_introspection(cls) # se_e2_a model with fparam (dim_fparam=1, no default; swap _dpmodel # because se_e2_a + fparam hits GuardOnDataDependentSymNode in export) @@ -1818,18 +1766,10 @@ def setUpClass(cls) -> None: seed=GLOBAL_SEED, ) model_fp = EnergyModel(ds_fp, ft_fp, type_map=cls.type_map) - pte_fp = os.path.join(cls._tmpdir, "fp.pte") - deserialize_to_file(pte_fp, {"model": model_sea.serialize()}) - cls.dp_fp = DeepPot(pte_fp) + cls.dp_fp = DeepPot(pte_sea) cls.dp_fp.deep_eval._dpmodel = model_fp cls.dim_descrpt_fp = ds_fp.get_dim_out() - @classmethod - def tearDownClass(cls) -> None: - import shutil - - shutil.rmtree(cls._tmpdir, ignore_errors=True) - def _make_inputs(self): nframes = 1 natoms = 6 @@ -1914,54 +1854,9 @@ class TestEvalFittingLastLayer(unittest.TestCase): @classmethod def setUpClass(cls) -> None: - cls.rcut = 4.0 - cls.rcut_smth = 0.5 - cls.sel = [8, 6] - cls.nt = 2 - cls.type_map = ["foo", "bar"] + pte_sea = _set_up_introspection(cls) cls.neuron = [120, 120, 120] # default fitting net neurons - # se_e2_a model (mixed_types=False) - ds_sea = DescrptSeA(cls.rcut, cls.rcut_smth, cls.sel) - ft_sea = EnergyFittingNet( - cls.nt, - ds_sea.get_dim_out(), - mixed_types=ds_sea.mixed_types(), - seed=GLOBAL_SEED, - ) - model_sea = EnergyModel(ds_sea, ft_sea, type_map=cls.type_map) - model_sea = model_sea.to(torch.float64) - model_sea.eval() - cls._tmpdir = tempfile.mkdtemp() - pte_sea = os.path.join(cls._tmpdir, "sea.pte") - deserialize_to_file(pte_sea, {"model": model_sea.serialize()}) - cls.dp_sea = DeepPot(pte_sea) - - # DPA1 model (mixed_types=True) - from deepmd.pt_expt.descriptor.dpa1 import ( - DescrptDPA1, - ) - - ds_dpa1 = DescrptDPA1( - cls.rcut, - cls.rcut_smth, - cls.sel, - ntypes=cls.nt, - seed=GLOBAL_SEED, - ) - ft_dpa1 = EnergyFittingNet( - cls.nt, - ds_dpa1.get_dim_out(), - mixed_types=ds_dpa1.mixed_types(), - seed=GLOBAL_SEED, - ) - model_dpa1 = EnergyModel(ds_dpa1, ft_dpa1, type_map=cls.type_map) - model_dpa1 = model_dpa1.to(torch.float64) - model_dpa1.eval() - pte_dpa1 = os.path.join(cls._tmpdir, "dpa1.pte") - deserialize_to_file(pte_dpa1, {"model": model_dpa1.serialize()}) - cls.dp_dpa1 = DeepPot(pte_dpa1) - # se_e2_a model with fparam and aparam (swap _dpmodel because # se_e2_a + fparam hits GuardOnDataDependentSymNode in export) ds_fp = DescrptSeA(cls.rcut, cls.rcut_smth, cls.sel) @@ -1974,17 +1869,9 @@ def setUpClass(cls) -> None: seed=GLOBAL_SEED, ) model_fp = EnergyModel(ds_fp, ft_fp, type_map=cls.type_map) - pte_fp = os.path.join(cls._tmpdir, "fp.pte") - deserialize_to_file(pte_fp, {"model": model_sea.serialize()}) - cls.dp_fp = DeepPot(pte_fp) + cls.dp_fp = DeepPot(pte_sea) cls.dp_fp.deep_eval._dpmodel = model_fp - @classmethod - def tearDownClass(cls) -> None: - import shutil - - shutil.rmtree(cls._tmpdir, ignore_errors=True) - def _make_inputs(self): nframes = 1 natoms = 6 @@ -2242,28 +2129,8 @@ def setUpClass(cls) -> None: cls.nt = 2 cls.type_map = ["foo", "bar"] - ds = DescrptSeA(cls.rcut, cls.rcut_smth, cls.sel) - ft = EnergyFittingNet( - cls.nt, - ds.get_dim_out(), - mixed_types=ds.mixed_types(), - seed=GLOBAL_SEED, - ) - model = EnergyModel(ds, ft, type_map=cls.type_map) - model = model.to(torch.float64) - model.eval() - cls.dim_descrpt = ds.get_dim_out() - - cls._tmpdir = tempfile.mkdtemp() - pte_path = os.path.join(cls._tmpdir, "sea.pte") - deserialize_to_file(pte_path, {"model": model.serialize()}) - cls.dp_native = DeepPot(pte_path) - - @classmethod - def tearDownClass(cls) -> None: - import shutil - - shutil.rmtree(cls._tmpdir, ignore_errors=True) + cls.pte_path, cls.dim_descrpt = _introspection_archive("se_e2_a") + cls.dp_native = DeepPot(cls.pte_path) @unittest.skipUnless( importlib.util.find_spec("ase") is not None, "ase not installed" @@ -2272,9 +2139,8 @@ def test_eval_descriptor_ase_vs_native(self) -> None: """eval_descriptor with ASE nlist matches native nlist.""" import ase.neighborlist - pte_path = os.path.join(self._tmpdir, "sea.pte") dp_ase = DeepPot( - pte_path, + self.pte_path, neighbor_list=ase.neighborlist.NewPrimitiveNeighborList( cutoffs=self.rcut, bothways=True ), @@ -2299,9 +2165,8 @@ def test_eval_fitting_last_layer_ase_vs_native(self) -> None: """eval_fitting_last_layer with ASE nlist matches native nlist.""" import ase.neighborlist - pte_path = os.path.join(self._tmpdir, "sea.pte") dp_ase = DeepPot( - pte_path, + self.pte_path, neighbor_list=ase.neighborlist.NewPrimitiveNeighborList( cutoffs=self.rcut, bothways=True ), diff --git a/source/tests/pt_expt/infer/test_deep_eval_metadata_only.py b/source/tests/pt_expt/infer/test_deep_eval_metadata_only.py index e8ccdea7da..370ef7a961 100644 --- a/source/tests/pt_expt/infer/test_deep_eval_metadata_only.py +++ b/source/tests/pt_expt/infer/test_deep_eval_metadata_only.py @@ -212,33 +212,26 @@ def test_eval_embedding_requires_dpmodel(self) -> None: ): self.dp_meta.deep_eval.eval_embedding(self.coord, self.cell, self.atype) - -class TestDeepEvalMetadataOnlyGuards(unittest.TestCase): - """Error-path coverage that is independent of the .pte fixture.""" - def test_missing_metadata_json_is_rejected(self) -> None: """A ``.pte`` stripped of ``metadata.json`` must raise on load. Metadata is the minimum contract — unlike ``model.json`` it must always be present. """ - torch.manual_seed(0) - ds = DescrptSeA(4.0, 0.5, [6, 6]) - ft = EnergyFittingNet(2, ds.get_dim_out(), mixed_types=ds.mixed_types(), seed=1) - model = EnergyModel(ds, ft, type_map=["a", "b"]).to(torch.float64).eval() + # Keep a real exported program in the broken archive. Reuse the + # immutable full fixture instead of tracing another identical graph + # merely to remove its metadata; all other entries are copied intact. with tempfile.TemporaryDirectory() as tmp: - full = Path(tmp) / "full.pte" broken = Path(tmp) / "no_metadata.pte" - deserialize_to_file(str(full), {"model": model.serialize()}) with ( - zipfile.ZipFile(full, "r") as zin, + zipfile.ZipFile(self.full_path, "r") as zin, zipfile.ZipFile(broken, "w") as zout, ): for info in zin.infolist(): if info.filename.endswith("extra/metadata.json"): continue zout.writestr(info, zin.read(info.filename)) - with self.assertRaises(ValueError): + with self.assertRaisesRegex(ValueError, "missing 'metadata.json'"): DeepPot(str(broken)) diff --git a/source/tests/pt_expt/model/test_dpa4_export.py b/source/tests/pt_expt/model/test_dpa4_export.py index a164c5080f..a00d799aac 100644 --- a/source/tests/pt_expt/model/test_dpa4_export.py +++ b/source/tests/pt_expt/model/test_dpa4_export.py @@ -887,6 +887,9 @@ def test_bridged_default_freeze_routes_to_graph(tmp_path) -> None: the graph-lower capability, which covers both. """ import copy + from unittest import ( + mock, + ) from deepmd.pt_expt.entrypoints.main import ( freeze, @@ -908,13 +911,17 @@ def test_bridged_default_freeze_routes_to_graph(tmp_path) -> None: torch.save({"model": wrapper.state_dict()}, ckpt) output = tmp_path / "frozen_bridged" # suffixless: default CLI form - freeze(model=str(ckpt), output=str(output)) - - pt2 = output.with_suffix(".pt2") - assert pt2.exists(), "default suffix must follow the resolved graph kind" - with zipfile.ZipFile(pt2) as z: - md = json.loads(z.read("model/extra/metadata.json").decode("utf-8")) - assert md["lower_input_kind"] == "graph" + # This test pins the public entry point's route and default suffix. The + # bridged with-comm export test exercises real tracing and AOTI packaging. + with mock.patch("deepmd.pt_expt.utils.serialization.deserialize_to_file") as export: + freeze(model=str(ckpt), output=str(output)) + + export.assert_called_once() + args, kwargs = export.call_args + assert args[0] == str(output.with_suffix(".pt2")), ( + "default suffix must follow the resolved graph kind" + ) + assert kwargs["lower_kind"] == "graph" def test_virtual_spin_graph_freeze_still_rejected(tmp_path) -> None: diff --git a/source/tests/pt_expt/model/test_dpa4_graph_lower.py b/source/tests/pt_expt/model/test_dpa4_graph_lower.py index 48788934bc..2b4febcf66 100644 --- a/source/tests/pt_expt/model/test_dpa4_graph_lower.py +++ b/source/tests/pt_expt/model/test_dpa4_graph_lower.py @@ -434,22 +434,18 @@ def _spy(self_, *args: object, **kwargs: object) -> object: model.forward_common(self.coord.clone().requires_grad_(True), self.atype, box) assert calls["n"] == 0, "disabled route must not call DescrptDPA4.call_graph" - def test_graph_lower_symbolic_trace(self) -> None: - """``make_fx`` symbolic trace of ``forward_lower_graph_exportable`` - reproduces the eager graph lower bit-tight, on a message-sensitive - (jittered) model. - - ``forward_common_lower_graph`` computes force/virial via a single - ``torch.autograd.grad`` backward through its own ``edge_vec`` leaf - (see ``edge_transform_output.py:106``); tracing the whole exportable - wrapper with ``make_fx`` therefore traces that backward pass too -- - this is what makes the DPA4 SO(3)/GridMLP compute graph, including - its analytic force/virial, ``.pt2``-exportable. ``model.to("cpu")`` - before tracing mirrors the real ``.pt2`` export path (make_fx traces - on CPU by design, ``serialization.py:924``) and the dpa1 CUDA lesson - (traced inputs and params must share a device). + def test_graph_lower_torch_export(self) -> None: + """``torch.export.export`` the traced graph lower with the + production dynamic shapes (``_build_graph_dynamic_shapes``): the + edge axis ``E``, the flat node axis ``N``, and the frame axis ``nf`` + are all dynamic. Must export without ``GuardOnDataDependentSymNode`` + and the resulting exported program must reproduce the eager graph + lower AND generalize to a different (smaller) system size than the + one it was traced/exported on -- proving the dynamism is real, not + an artifact baked to the trace-time shapes. """ from deepmd.pt_expt.utils.serialization import ( + _build_graph_dynamic_shapes, build_synthetic_graph_inputs, ) @@ -483,6 +479,8 @@ def test_graph_lower_symbolic_trace(self) -> None: tracing_mode="symbolic", _allow_non_fake_inputs=True, ) + # Validate the symbolic trace before exporting the same graph. This + # keeps same-shape parity and dynamic replay without tracing twice. out = traced(atype, n_node, n_local, ei, ev, em, do, drp, so, srp, fp, ap, cs) ref = model.forward_common_lower_graph( atype, @@ -511,51 +509,6 @@ def test_graph_lower_symbolic_trace(self) -> None: out["virial"], ref["energy_derv_c_redu"].reshape(out["virial"].shape), **tol ) - def test_graph_lower_torch_export(self) -> None: - """``torch.export.export`` the traced graph lower with the - production dynamic shapes (``_build_graph_dynamic_shapes``): the - edge axis ``E``, the flat node axis ``N``, and the frame axis ``nf`` - are all dynamic. Must export without ``GuardOnDataDependentSymNode`` - and the resulting exported program must reproduce the eager graph - lower AND generalize to a different (smaller) system size than the - one it was traced/exported on -- proving the dynamism is real, not - an artifact baked to the trace-time shapes. - """ - from deepmd.pt_expt.utils.serialization import ( - _build_graph_dynamic_shapes, - build_synthetic_graph_inputs, - ) - - model = _make_message_sensitive_model(self.device).to("cpu") - model.eval() - sample = build_synthetic_graph_inputs( - model, - e_max=175, - nframes=2, - nloc=7, - dtype=torch.float64, - device=torch.device("cpu"), - ) - atype, n_node, n_local, ei, ev, em, do, drp, so, srp, fp, ap, cs = sample - traced = model.forward_lower_graph_exportable( - atype, - n_node, - n_local, - ei, - ev, - em, - do, - drp, - so, - srp, - fparam=fp, - aparam=ap, - do_atomic_virial=True, - charge_spin=cs, - destination_sorted=True, - tracing_mode="symbolic", - _allow_non_fake_inputs=True, - ) dynamic_shapes = _build_graph_dynamic_shapes( atype, n_node, n_local, ei, ev, em, do, drp, so, srp, fp, ap, cs ) diff --git a/source/tests/pt_expt/model/test_dpa4_native_spin.py b/source/tests/pt_expt/model/test_dpa4_native_spin.py index 2510855e8f..eb91f41498 100644 --- a/source/tests/pt_expt/model/test_dpa4_native_spin.py +++ b/source/tests/pt_expt/model/test_dpa4_native_spin.py @@ -587,11 +587,11 @@ class TestDPA4NativeSpinGraphLowerExportable: mirror this ABI. """ - def test_graph_lower_exportable_symbolic_trace(self) -> None: - """``make_fx`` traces the graph-spin closure on CPU; the traced - output matches the eager ``forward_common_lower_graph`` reference - (same graph inputs -- the same physical system) bit-tight, and - includes a genuinely non-trivial ``force_mag``. + def test_graph_lower_exportable_torch_export(self) -> None: + """``torch.export.export`` succeeds with a dynamic ``nedge`` (and + ``N``/``nframes``) axis; the exported program reproduces the eager + graph lower AND generalizes to a different (smaller) system size + than the one it was traced/exported on. """ model = _build_native_spin_model_cpu() sample = _build_spin_graph_sample(model) @@ -616,6 +616,9 @@ def test_graph_lower_exportable_symbolic_trace(self) -> None: tracing_mode="symbolic", _allow_non_fake_inputs=True, ) + + # Validate the symbolic trace before exporting the same graph. This + # keeps same-shape parity and dynamic replay without tracing twice. out = traced( atype, n_node, n_local, ei, ev, em, do, drp, so, srp, spin, fp, ap, cs ) @@ -672,36 +675,6 @@ def test_graph_lower_exportable_symbolic_trace(self) -> None: **tol, ) - def test_graph_lower_exportable_torch_export(self) -> None: - """``torch.export.export`` succeeds with a dynamic ``nedge`` (and - ``N``/``nframes``) axis; the exported program reproduces the eager - graph lower AND generalizes to a different (smaller) system size - than the one it was traced/exported on. - """ - model = _build_native_spin_model_cpu() - sample = _build_spin_graph_sample(model) - atype, n_node, n_local, ei, ev, em, do, drp, so, srp, spin, fp, ap, cs = sample - - traced = model.forward_lower_graph_exportable( - atype, - n_node, - n_local, - ei, - ev, - em, - do, - drp, - so, - srp, - spin, - fparam=fp, - aparam=ap, - do_atomic_virial=True, - destination_sorted=True, - tracing_mode="symbolic", - _allow_non_fake_inputs=True, - ) - nframes_dim = torch.export.Dim("nframes", min=1) n_node_total_dim = torch.export.Dim("n_node_total", min=1) nedge_dim = torch.export.Dim("nedge", min=2) diff --git a/source/tests/pt_expt/model/test_dpa4_zbl_parallel.py b/source/tests/pt_expt/model/test_dpa4_zbl_parallel.py index b5442c4b99..31ba13cc6c 100644 --- a/source/tests/pt_expt/model/test_dpa4_zbl_parallel.py +++ b/source/tests/pt_expt/model/test_dpa4_zbl_parallel.py @@ -290,19 +290,27 @@ def test_make_fx_traces_with_comm(self) -> None: ) def test_freeze_embeds_with_comm_artifact(self, tmp_path) -> None: - """Freezing the bridged model to a graph ``.pt2`` embeds the nested - with-comm artifact (mirrors the plain-DPA4 embed test). - """ + """Default public freeze embeds the bridged with-comm graph artifact.""" import json import zipfile - from deepmd.pt_expt.utils.serialization import ( - deserialize_to_file, + from deepmd.pt_expt.entrypoints.main import ( + freeze, + ) + from deepmd.pt_expt.train.wrapper import ( + ModelWrapper, ) - data = {"model": self.model.serialize()} - p = str(tmp_path / "m_dpa4_zbl_graph.pt2") - deserialize_to_file(p, copy.deepcopy(data), lower_kind="graph") + wrapper = ModelWrapper(self.model, model_params=copy.deepcopy(ZBL_CONFIG)) + checkpoint = tmp_path / "model.pt" + torch.save({"model": wrapper.state_dict()}, checkpoint) + + # Cover checkpoint loading, default graph routing, and real AOTI + # packaging together instead of compiling again in the route test. + output = tmp_path / "m_dpa4_zbl_graph" + freeze(model=str(checkpoint), output=str(output)) + p = output.with_suffix(".pt2") + assert p.exists(), "default suffix must follow the resolved graph kind" with zipfile.ZipFile(p, "r") as zf: names = zf.namelist() meta = json.loads(zf.read("model/extra/metadata.json")) diff --git a/source/tests/pt_expt/model/test_model_compression.py b/source/tests/pt_expt/model/test_model_compression.py index 95a66b528d..995261d9f8 100644 --- a/source/tests/pt_expt/model/test_model_compression.py +++ b/source/tests/pt_expt/model/test_model_compression.py @@ -35,6 +35,25 @@ class TestModelCompression(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls._frozen_path = None + + def _frozen_model_path(self) -> str: + """Freeze the identical seeded input once; compression outputs stay private.""" + cls = type(self) + if cls._frozen_path is None: + model = self._make_model().eval() + model.min_nbor_dist = 0.5 + with tempfile.NamedTemporaryFile(suffix=".pte", delete=False) as f: + frozen_path = f.name + cls.addClassCleanup(os.unlink, frozen_path) + deserialize_to_file( + frozen_path, {"model": model.serialize(), "min_nbor_dist": 0.5} + ) + cls._frozen_path = frozen_path + return cls._frozen_path + def setUp(self) -> None: from deepmd.pt.cxx_op import ( ENABLE_CUSTOMIZED_OP, @@ -120,14 +139,10 @@ def test_freeze_compress_eval(self) -> None: md.eval() ret_frozen = self._eval_model(md) - model_data = {"model": md.serialize(), "min_nbor_dist": 0.5} - with tempfile.NamedTemporaryFile(suffix=".pte", delete=False) as f: - frozen_path = f.name + frozen_path = self._frozen_model_path() with tempfile.NamedTemporaryFile(suffix=".pte", delete=False) as f: compressed_path = f.name try: - deserialize_to_file(frozen_path, model_data) - # 2. Compress via entry point (same as `dp --pt_expt compress`) compress_entry( input_file=frozen_path, @@ -158,7 +173,6 @@ def test_freeze_compress_eval(self) -> None: ret_frozen[key], ret_compressed[key], atol=1e-7, err_msg=key ) finally: - os.unlink(frozen_path) os.unlink(compressed_path) def test_descriptor_preserved_in_model(self) -> None: @@ -177,15 +191,9 @@ def test_min_nbor_dist_roundtrip(self) -> None: self.assertAlmostEqual(md.get_min_nbor_dist(), 0.5) # Freeze to .pte - model_data = {"model": md.serialize(), "min_nbor_dist": 0.5} - with tempfile.NamedTemporaryFile(suffix=".pte", delete=False) as f: - frozen_path = f.name - try: - deserialize_to_file(frozen_path, model_data) - loaded_data = serialize_from_file(frozen_path) - self.assertAlmostEqual(loaded_data["min_nbor_dist"], 0.5) - finally: - os.unlink(frozen_path) + frozen_path = self._frozen_model_path() + loaded_data = serialize_from_file(frozen_path) + self.assertAlmostEqual(loaded_data["min_nbor_dist"], 0.5) def test_compress_state_serialized(self) -> None: """Test that compression state persists through serialize/deserialize. @@ -259,18 +267,10 @@ def test_compress_cli_entry_point(self) -> None: main, ) - md = self._make_model() - md.min_nbor_dist = 0.5 - md.eval() - - model_data = {"model": md.serialize(), "min_nbor_dist": 0.5} - with tempfile.NamedTemporaryFile(suffix=".pte", delete=False) as f: - frozen_path = f.name + frozen_path = self._frozen_model_path() with tempfile.NamedTemporaryFile(suffix=".pte", delete=False) as f: compressed_path = f.name try: - deserialize_to_file(frozen_path, model_data) - # Call via CLI entry point main( [ @@ -286,7 +286,6 @@ def test_compress_cli_entry_point(self) -> None: compressed_data = serialize_from_file(compressed_path) self.assertIn("model", compressed_data) finally: - os.unlink(frozen_path) if os.path.exists(compressed_path): os.unlink(compressed_path) @@ -309,14 +308,10 @@ def test_freeze_compress_eval_pt2(self) -> None: md.eval() ret_frozen = self._eval_model(md) - model_data = {"model": md.serialize(), "min_nbor_dist": 0.5} - with tempfile.NamedTemporaryFile(suffix=".pte", delete=False) as f: - frozen_path = f.name + frozen_path = self._frozen_model_path() with tempfile.NamedTemporaryFile(suffix=".pt2", delete=False) as f: compressed_pt2_path = f.name try: - deserialize_to_file(frozen_path, model_data) - # 2. Compress with .pt2 output compress_entry( input_file=frozen_path, @@ -348,7 +343,6 @@ def test_freeze_compress_eval_pt2(self) -> None: ret_frozen["virial"], v_pt2, atol=1e-7, err_msg="virial" ) finally: - os.unlink(frozen_path) if os.path.exists(compressed_pt2_path): os.unlink(compressed_pt2_path) diff --git a/source/tests/pt_expt/test_cuda_fixture_reuse.py b/source/tests/pt_expt/test_cuda_fixture_reuse.py new file mode 100644 index 0000000000..b62e2af72b --- /dev/null +++ b/source/tests/pt_expt/test_cuda_fixture_reuse.py @@ -0,0 +1,98 @@ +# SPDX-License-Identifier: LGPL-3.0-or-later +"""CPU checks of CUDA test setup reuse and per-case isolation.""" + +import copy +import dataclasses +from types import ( + SimpleNamespace, +) + +import pytest +import torch + +from .descriptor import test_dpa4c_cuda as dpa4c + + +@pytest.fixture +def graph_cache(): + dpa4c._graph_template.cache_clear() + yield dpa4c._graph_template + dpa4c._graph_template.cache_clear() + + +def _assert_same_graph(left, right): + for field in dataclasses.fields(left[0]): + actual, expected = getattr(left[0], field.name), getattr(right[0], field.name) + if isinstance(actual, torch.Tensor): + torch.testing.assert_close(actual, expected, atol=0, rtol=0) + else: + assert actual == expected + torch.testing.assert_close(left[1], right[1], atol=0, rtol=0) + + +@pytest.mark.parametrize( + "index,replacement", + [ + (0, 2.5), + (1, False), + (2, 25), + (3, True), + (4, 6.0), + (5, 2), + (6, (0, 2, 3)), + (7, torch.device("cpu:0")), + ], + ids=[ + "cutoff", + "canonical", + "nodes", + "one-type", + "side", + "frames", + "types", + "device", + ], +) +def test_graph_cache_keys_every_geometry_input(graph_cache, index, replacement): + """Every geometry input misses the cache and agrees with a fresh build.""" + arguments = [3.0, True, 24, False, 5.0, 1, (0, 1), torch.device("cpu")] + before = torch.random.get_rng_state().clone() + first = graph_cache(*arguments) + assert graph_cache(*arguments) is first + assert graph_cache.cache_info().hits == 1 + arguments[index] = replacement + changed = graph_cache(*arguments) + assert graph_cache.cache_info().misses == 2 + assert graph_cache.cache_info().currsize == 1 + _assert_same_graph(changed, graph_cache.__wrapped__(*arguments)) + torch.testing.assert_close(torch.random.get_rng_state(), before, atol=0, rtol=0) + + +def test_graph_cache_returns_independent_tensors(graph_cache, monkeypatch): + """Mutating one caller's graph cannot change the template or next caller.""" + devices = [] + + def on_cpu(*arguments): + devices.append(arguments[-1]) + return graph_cache(*arguments[:-1], torch.device("cpu")) + + monkeypatch.setattr(dpa4c, "_graph_template", on_cpu) + monkeypatch.setattr(torch.cuda, "current_device", lambda: 0) + descriptor = SimpleNamespace(rcut=3.0) + first = dpa4c._build_graph(descriptor, canonical=True) + expected = copy.deepcopy(first) + for field in dataclasses.fields(first[0]): + tensor = getattr(first[0], field.name) + if isinstance(tensor, torch.Tensor): + tensor.zero_() + first[1].fill_(7) + second = dpa4c._build_graph(descriptor, canonical=True) + _assert_same_graph(second, expected) + assert devices == [torch.device("cuda:0"), torch.device("cuda:0")] + assert graph_cache.cache_info().misses == graph_cache.cache_info().hits == 1 + second[0].edge_vec.requires_grad_(True) + second[0].edge_vec.square().sum().backward() + third = dpa4c._build_graph(descriptor, canonical=True) + assert not third[0].edge_vec.requires_grad + assert third[0].edge_vec.grad is None + _assert_same_graph(third, expected) diff --git a/source/tests/pt_expt/test_multitask.py b/source/tests/pt_expt/test_multitask.py index 2842be6dde..85ca79078d 100644 --- a/source/tests/pt_expt/test_multitask.py +++ b/source/tests/pt_expt/test_multitask.py @@ -2267,11 +2267,11 @@ def test_compiled_varying_nframes_with_case_embd(self) -> None: self.assertIsNotNone(ce, f"case_embd not set on {mk}") self.assertEqual(int(ce.shape[0]), 2) - # Drive 6 steps alternating (task, system_index) so each branch's - # compiled graph sees both nframes=2 (sys0) and nframes=3 (sys1). + # Alternate branches while each sees nframes=2, then 3, then 2 + # again, covering both dynamic shapes and cached graph reuse. trainer.wrapper.train() task_sequence = ["model_1", "model_2"] * 3 - sys_sequence = [0, 1, 0, 1, 0, 1] + sys_sequence = [0, 0, 1, 1, 0, 0] sys_iter = iter(sys_sequence) original_choice = dp_random.choice @@ -2283,12 +2283,14 @@ def task_or_system_choice(a, size=None, replace=True, p=None): return next(sys_iter) return original_choice(a, size=size, replace=replace, p=p) - seen_nframes: set[int] = set() + seen_nframes: dict[str, set[int]] = { + key: set() for key in ("model_1", "model_2") + } with patch.object(dp_random, "choice", side_effect=task_or_system_choice): for task_key in task_sequence: trainer.optimizer.zero_grad(set_to_none=True) inp, lab = trainer.get_data(is_train=True, task_key=task_key) - seen_nframes.add(int(inp["coord"].shape[0])) + seen_nframes[task_key].add(int(inp["coord"].shape[0])) lr = trainer.scheduler.get_last_lr()[0] _, loss, _ = trainer.wrapper( **inp, cur_lr=lr, label=lab, task_key=task_key @@ -2298,14 +2300,15 @@ def task_or_system_choice(a, size=None, replace=True, p=None): self.assertFalse(torch.isnan(loss), "loss is NaN") self.assertFalse(torch.isinf(loss), "loss is Inf") - self.assertEqual( - seen_nframes, - {2, 3}, - msg=( - f"nframes did not vary across steps: {seen_nframes}. " - "Expected both 2 and 3 (matching and not matching dim_case_embd=2)." - ), - ) + for task_key, nframes in seen_nframes.items(): + self.assertEqual( + nframes, + {2, 3}, + msg=( + f"nframes did not vary for {task_key}: {nframes}. " + "Expected both 2 and 3 (matching and not matching dim_case_embd=2)." + ), + ) finally: os.chdir(old_cwd) shutil.rmtree(tmpdir, ignore_errors=True) diff --git a/source/tests/pt_expt/utils/test_graph_pt2_metadata.py b/source/tests/pt_expt/utils/test_graph_pt2_metadata.py index 4d7c5f3751..c71492a092 100644 --- a/source/tests/pt_expt/utils/test_graph_pt2_metadata.py +++ b/source/tests/pt_expt/utils/test_graph_pt2_metadata.py @@ -239,6 +239,22 @@ def dpa1_dpmodel_data() -> dict: return _build_dpa1_data() +@pytest.fixture(scope="module") +def dpa1_dense_pt2(dpa1_dpmodel_data, tmp_path_factory) -> str: + """Compile the read-only dense artifact once for its metadata consumers. + + CI groups module-level tests from this file on the same shard, so both + consumers share the artifact without changing their independent checks. + """ + model_file = str(tmp_path_factory.mktemp("dpa1_dense") / "m_dense.pt2") + deserialize_to_file( + model_file, + copy.deepcopy(dpa1_dpmodel_data), + do_atomic_virial=True, + ) + return model_file + + def test_convert_regular_pt_dpa1_preserves_dense_semantics(tmp_path) -> None: """A nonzero-davg PT artifact remains numerically dense after conversion.""" from deepmd.infer import ( @@ -481,23 +497,16 @@ class _Model: assert _supports_graph_export(_Model()) is (statistics_dtype == torch.float32) -def test_dense_pt2_has_lower_input_kind_nlist(dpa1_dpmodel_data) -> None: +def test_dense_pt2_has_lower_input_kind_nlist(dpa1_dense_pt2) -> None: """Default (``lower_kind="nlist"``) -> metadata ``lower_input_kind == "nlist"``.""" - with tempfile.TemporaryDirectory() as d: - p = os.path.join(d, "m_dense.pt2") - deserialize_to_file( - p, - copy.deepcopy(dpa1_dpmodel_data), - do_atomic_virial=True, - ) - meta = _read_metadata(p) + meta = _read_metadata(dpa1_dense_pt2) assert meta["lower_input_kind"] == "nlist" assert meta["graph_edge_dtype"] == "float64" # edge_capacity is a graph-only artifact constant; the dense path omits it. assert "edge_capacity" not in meta -def test_neighbor_graph_method_rejected_on_nlist_artifact(dpa1_dpmodel_data) -> None: +def test_neighbor_graph_method_rejected_on_nlist_artifact(dpa1_dense_pt2) -> None: """A non-default ``neighbor_graph_method`` on a NLIST-form artifact raises. The knob is consumed only by the artifacts whose inputs the evaluator @@ -510,17 +519,10 @@ def test_neighbor_graph_method_rejected_on_nlist_artifact(dpa1_dpmodel_data) -> DeepPot, ) - with tempfile.TemporaryDirectory() as d: - p = os.path.join(d, "m_dense.pt2") - deserialize_to_file( - p, - copy.deepcopy(dpa1_dpmodel_data), - do_atomic_virial=True, - ) - with pytest.raises(ValueError, match="use nlist_backend"): - DeepPot(p, neighbor_graph_method="vesin") - # The default remains valid for nlist-form artifacts. - DeepPot(p) + with pytest.raises(ValueError, match="use nlist_backend"): + DeepPot(dpa1_dense_pt2, neighbor_graph_method="vesin") + # The default remains valid for nlist-form artifacts. + DeepPot(dpa1_dense_pt2) @pytest.mark.parametrize( diff --git a/source/tests/test_cc_local.py b/source/tests/test_cc_local.py index f003bf55d1..ae33f10a06 100644 --- a/source/tests/test_cc_local.py +++ b/source/tests/test_cc_local.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: LGPL-3.0-or-later """Exercise the C++ CI entry point without compiling backend libraries.""" +import csv import json import os import shutil @@ -39,6 +40,10 @@ "gen_dpa4c_canonical.py", "gen_dpa4c_long_range.py", } +REPORTS = {Path(model).stem for model in MODELS} - {"gen_spin"} | { + "gen_spin_dpa3", + "gen_spin_reuse", +} @pytest.fixture @@ -69,16 +74,77 @@ def build_tree(tmp_path): import os import subprocess import sys +import time from pathlib import Path name = Path(sys.argv[0]).name args = sys.argv[1:] -record = {{"name": name, "args": args, "ld": os.environ.get("LD_LIBRARY_PATH", "")}} +dpa1_ready = Path(os.environ["MOCK_DPA1_READY"]) +dpa3_ready = Path(os.environ["MOCK_SPIN_DPA3_READY"]) +dpa3_mpi_ready = Path(os.environ["MOCK_SPIN_DPA3_MPI_READY"]) +model0_ready = Path(os.environ["MOCK_MODEL0_READY"]) +schedule_dir = Path(os.environ["MOCK_SCHEDULE_DIR"]) + +def schedule_event(event, model): + with open(os.environ["MOCK_SCHEDULE_LOG"], "a") as stream: + stream.write(json.dumps({{"event": event, "model": model}}) + "\\n") + (schedule_dir / (model + "." + event)).touch() + +def wait_for_event(event, model): + deadline = time.monotonic() + 10 + while not (schedule_dir / (model + "." + event)).exists(): + if time.monotonic() > deadline: + raise RuntimeError("Generator pipeline did not release " + model + "." + event) + time.sleep(0.01) + +record = {{ + "name": name, + "args": args, + "ld": os.environ.get("LD_LIBRARY_PATH", ""), + "gtest_output": os.environ.get("GTEST_OUTPUT", ""), + "dpa1_ready": dpa1_ready.exists(), + "dpa3_ready": dpa3_ready.exists() and dpa3_mpi_ready.exists(), + "model0_ready": model0_ready.exists(), +}} with open(os.environ["MOCK_LOG"], "a") as stream: stream.write(json.dumps(record) + "\\n") if os.environ.get("MOCK_FAIL") and any(os.environ["MOCK_FAIL"] == Path(a).name for a in [name, *args]): sys.exit(17) if name == "python" and args[0] == "-c": sys.exit(subprocess.call([sys.executable, "-S", *args])) +if name == "python" and args[0] == "-u": + model = Path(args[1]).name + schedule_event("start", model) + if os.environ.get("MOCK_CHECK_SCHEDULE"): + # Hold DPA2 open until both replacement jobs complete. This proves + # actual overlap without relying on timing or machine speed. + if model == "gen_sea.py": + wait_for_event("start", "gen_dpa1.py") + wait_for_event("start", "gen_dpa2.py") + elif model == "gen_dpa1.py": + wait_for_event("start", "gen_dpa4.py") + elif model == "gen_dpa2.py": + wait_for_event("end", "gen_dpa4.py") + wait_for_event("end", "gen_dpa3.py") + elif model == "gen_dpa4.py": + wait_for_event("start", "gen_dpa3.py") + if Path(args[1]).name == "gen_dpa1.py": + # Make a missing wait on this producer visible to the reuse consumer. + time.sleep(0.05) + dpa1_ready.touch() + if "--reuse-dpa1" in args and not dpa1_ready.exists(): + sys.exit(23) + if "--dpa3-only" in args: + time.sleep(0.05) + dpa3_ready.touch() + dpa3_mpi_ready.touch() + if Path(args[1]).name == "gen_spin_model_devi.py": + time.sleep(0.05) + model0_ready.touch() + if "--reuse-model-devi" in args and not (dpa3_ready.exists() and dpa3_mpi_ready.exists() and model0_ready.exists()): + sys.exit(23) + schedule_event("end", model) +if name == "ctest": + Path(args[args.index("--output-junit") + 1]).write_text("") """ for name in ("cmake", "python", "ctest"): executable = bin_dir / name @@ -95,10 +161,19 @@ def build_tree(tmp_path): "LD_LIBRARY_PATH": "/existing/lib", # Do not inherit sanitizer flags from the caller. "CXXFLAGS": "", + "GTEST_OUTPUT": "", "MOCK_LOG": str(tmp_path / "commands.jsonl"), + "MOCK_DPA1_READY": str(infer / "deeppot_dpa1_graph.pt2"), + "MOCK_SPIN_DPA3_READY": str(infer / "deeppot_dpa3_spin.pt2"), + "MOCK_SPIN_DPA3_MPI_READY": str(infer / "deeppot_dpa3_spin_mpi.pt2"), + "MOCK_MODEL0_READY": str(infer / "deeppot_dpa_spin_md0.pt2"), "MOCK_SHARED_LIB_DIR": str(tmp_path / "installed_ops"), "MOCK_FAIL": "", + "MOCK_SCHEDULE_DIR": str(tmp_path / "schedule"), + "MOCK_SCHEDULE_LOG": str(tmp_path / "schedule.jsonl"), + "MOCK_CHECK_SCHEDULE": "", } + Path(env["MOCK_SCHEDULE_DIR"]).mkdir() return root, script, env @@ -123,12 +198,45 @@ def run_script(build_tree, *args, **overrides): def generated_models(commands): return [ - Path(c["args"][0]).name + Path(c["args"][1]).name for c in commands - if c["name"] == "python" and c["args"][0] != "-c" + if c["name"] == "python" and c["args"][0] == "-u" ] +def generator_reports(root): + reports = {} + for path in (root / "source/build_tests/generator-reports").glob("run.*/*.tsv"): + with path.open() as stream: + rows = list(csv.DictReader(stream, delimiter="\t")) + assert len(rows) == 1 + row = rows[0] + assert set(row) == {"generator", "seconds", "exit_status"} + assert row["generator"] == path.stem + assert int(row["seconds"]) >= 0 + reports[path] = row + return reports + + +def check_ctest_report(root, command, gtest_output=None): + assert command["name"] == "ctest" + assert command["args"][:2] == ["--output-on-failure", "--output-junit"] + assert len(command["args"]) == 3 + junit = Path(command["args"][2]).resolve() + assert junit.name == "ctest.xml" + assert junit.parent.parent == root / "source/build_tests/gtest-reports" + assert junit.parent.name.startswith("run.") + assert junit.is_file() + if gtest_output is None: + kind, path = command["gtest_output"].split(":", 1) + assert kind == "json" + assert path.endswith("/") + assert Path(path).resolve() == junit.parent + else: + assert command["gtest_output"] == gtest_output + return junit + + def test_default_still_builds_all_models_and_runs_ctest(build_tree): root, _, env = build_tree stale = root / "source/tests/infer/stale.pt2" @@ -139,16 +247,81 @@ def test_default_still_builds_all_models_and_runs_ctest(build_tree): assert [c["name"] for c in commands[:4]] == ["cmake", "cmake", "cmake", "python"] assert commands[1]["args"][:2] == ["--build", "."] assert commands[2]["args"] == ["--install", "."] - assert commands[-1]["name"] == "ctest" - assert commands[-1]["args"] == ["--output-on-failure"] + check_ctest_report(root, commands[-1]) assert set(generated_models(commands)) == MODELS - assert len(generated_models(commands)) == len(MODELS) + assert len(generated_models(commands)) == len(MODELS) + 1 + assert generated_models(commands).count("gen_spin.py") == 2 + reports = generator_reports(root) + assert {path.stem for path in reports} == REPORTS + assert len(reports) == len(REPORTS) + assert {row["exit_status"] for row in reports.values()} == {"0"} + pair_exclude = next(c for c in commands if "--reuse-dpa1" in c["args"]) + assert Path(pair_exclude["args"][1]).name == "gen_dpa1_pairexcl.py" + assert pair_exclude["dpa1_ready"] + spin_reuse = next(c for c in commands if "--reuse-model-devi" in c["args"]) + assert spin_reuse["dpa3_ready"] and spin_reuse["model0_ready"] + dpa3 = next(c for c in commands if "--dpa3-only" in c["args"]) + model_devi = next( + c for c in commands if "gen_spin_model_devi.py" in generated_models([c]) + ) + assert commands.index(dpa3) < commands.index(spin_reuse) + assert commands.index(model_devi) < commands.index(spin_reuse) + assert all("--compressed-only" not in c["args"] for c in commands) assert not stale.exists() assert ( Path(env["MOCK_SHARED_LIB_DIR"]) / "libdeepmd_op_pt.so" ).read_text() == "custom op from this build" +@pytest.mark.parametrize("variant", ["cpu", "cuda"]) +def test_long_generators_refill_completed_slots_before_dpa2_finishes( + build_tree, variant +): + root, _, env = build_tree + result, commands = run_script( + build_tree, DP_VARIANT=variant, MOCK_CHECK_SCHEDULE="1" + ) + assert result.returncode == 0, result.stderr + events = [ + json.loads(line) + for line in Path(env["MOCK_SCHEDULE_LOG"]).read_text().splitlines() + ] + + def position(event, model): + return events.index({"event": event, "model": model}) + + assert position("end", "gen_sea.py") < position("start", "gen_dpa4.py") + assert position("end", "gen_dpa1.py") < position("start", "gen_dpa3.py") + for model in ("gen_dpa3.py", "gen_dpa4.py"): + assert position("end", model) < position("end", "gen_dpa2.py") + first_phase = { + "gen_sea.py", + "gen_dpa1.py", + "gen_dpa2.py", + "gen_dpa3.py", + "gen_dpa4.py", + } + active = set() + peak = 0 + for entry in events: + if entry["model"] not in first_phase: + continue + if entry["event"] == "start": + active.add(entry["model"]) + else: + active.remove(entry["model"]) + peak = max(peak, len(active)) + assert not active + assert peak == 3 + for model in ("gen_fparam_aparam.py", "gen_model_devi.py", "gen_chg_spin.py"): + assert position("end", "gen_dpa2.py") < position("start", model) + assert position("end", "gen_dpa1.py") < position("start", "gen_dpa1_pairexcl.py") + assert position("end", "gen_dpa1_pairexcl.py") < position("start", "gen_spin.py") + for model in first_phase: + assert generated_models(commands).count(model) == 1 + check_ctest_report(root, commands[-1]) + + @pytest.mark.parametrize("pytorch", ["TRUE", "FALSE"]) def test_build_only_installs_without_generating_models_or_running_ctest( build_tree, pytorch @@ -162,6 +335,8 @@ def test_build_only_installs_without_generating_models_or_running_ctest( assert not generated_models(commands) assert all(c["name"] != "ctest" for c in commands) assert stale.exists() + assert not (root / "source/build_tests/generator-reports").exists() + assert not (root / "source/build_tests/gtest-reports").exists() assert (Path(env["MOCK_SHARED_LIB_DIR"]) / "libdeepmd_op_pt.so").exists() == ( pytorch == "TRUE" ) @@ -183,6 +358,13 @@ def test_kokkos_models_reuse_build_and_preserve_other_fixtures(build_tree): assert [c["name"] for c in commands] == ["python", "python"] assert commands[0]["args"][0] == "-c" assert generated_models(commands) == ["gen_dpa4c_long_range.py"] + assert commands[1]["args"][0] == "-u" + assert commands[1]["args"][2:] == ["--compressed-only"] + reports = generator_reports(root) + assert len(reports) == 1 + assert {path.stem for path in reports} == {"gen_dpa4c_long_range"} + assert {row["exit_status"] for row in reports.values()} == {"0"} + assert not (root / "source/build_tests/gtest-reports").exists() assert ( Path(commands[1]["ld"].split(os.pathsep)[0]).resolve() == root / "dp_test/lib" ) @@ -211,18 +393,93 @@ def test_kokkos_models_require_the_existing_build(build_tree, missing): assert not commands -@pytest.mark.parametrize("model", ["gen_sea.py", "gen_dpa4c_long_range.py"]) +@pytest.mark.parametrize( + "model", + [ + "gen_sea.py", + "gen_dpa1.py", + "gen_dpa2.py", + "gen_dpa3.py", + "gen_dpa4.py", + "gen_dpa1_pairexcl.py", + "gen_dpa4c_long_range.py", + ], +) def test_default_propagates_generator_failures(build_tree, model): + root, _, _ = build_tree result, commands = run_script(build_tree, MOCK_FAIL=model) - assert result.returncode != 0 + assert result.returncode == 17 assert all(c["name"] != "ctest" for c in commands) + failed = [ + row for path, row in generator_reports(root).items() if path.stem == model[:-3] + ] + assert len(failed) == 1 + assert failed[0]["exit_status"] == "17" + if model == "gen_dpa1.py": + assert all("--reuse-dpa1" not in c["args"] for c in commands) + if model in {"gen_dpa2.py", "gen_dpa3.py", "gen_dpa4.py"}: + assert "gen_fparam_aparam.py" not in generated_models(commands) + assert "gen_corrupt_with_comm.py" not in generated_models(commands) def test_kokkos_models_propagate_generator_failure(build_tree): + root, _, _ = build_tree result, _ = run_script( build_tree, "--models-only=kokkos", MOCK_FAIL="gen_dpa4c_long_range.py" ) - assert result.returncode != 0 + assert result.returncode == 17 + reports = generator_reports(root) + assert len(reports) == 1 + assert {row["exit_status"] for row in reports.values()} == {"17"} + + +@pytest.mark.parametrize( + "failure,report", + [ + ("--dpa3-only", "gen_spin_dpa3"), + ("gen_spin_model_devi.py", "gen_spin_model_devi"), + ("--reuse-model-devi", "gen_spin_reuse"), + ], +) +def test_spin_reuse_propagates_each_phase_failure(build_tree, failure, report): + root, _, _ = build_tree + result, commands = run_script(build_tree, MOCK_FAIL=failure) + assert result.returncode == 17 + assert all(c["name"] != "ctest" for c in commands) + reports = {path.stem: row for path, row in generator_reports(root).items()} + assert reports[report]["exit_status"] == "17" + if failure != "--reuse-model-devi": + assert all("--reuse-model-devi" not in c["args"] for c in commands) + + +def test_each_invocation_keeps_separate_generator_and_ctest_reports(build_tree): + root, _, _ = build_tree + first, commands = run_script(build_tree) + assert first.returncode == 0, first.stderr + first_junit = check_ctest_report(root, commands[-1]) + first_reports = generator_reports(root) + second, commands = run_script(build_tree) + assert second.returncode == 0, second.stderr + second_junit = check_ctest_report(root, commands[-1]) + assert first_junit != second_junit + assert first_junit.is_file() + reports = generator_reports(root) + assert len(reports) == 2 * len(REPORTS) + assert len({path.parent for path in reports}) == 2 + assert {path: reports[path] for path in first_reports} == first_reports + + +@pytest.mark.parametrize( + "gtest_output", ["json:/custom/reports/", "xml:/custom/result.xml"] +) +def test_ctest_preserves_explicit_gtest_output(build_tree, gtest_output): + root, _, _ = build_tree + result, commands = run_script( + build_tree, ENABLE_PYTORCH="FALSE", GTEST_OUTPUT=gtest_output + ) + assert result.returncode == 0, result.stderr + check_ctest_report(root, commands[-1], gtest_output) + assert not generator_reports(root) @pytest.mark.parametrize( diff --git a/source/tests/test_cpp_ci_reports.py b/source/tests/test_cpp_ci_reports.py new file mode 100644 index 0000000000..0d78ccb9cc --- /dev/null +++ b/source/tests/test_cpp_ci_reports.py @@ -0,0 +1,319 @@ +# SPDX-License-Identifier: LGPL-3.0-or-later +"""Check C++ CI report wiring without launching builds or GitHub workflows.""" + +import csv +import json +import os +import re +import shutil +import signal +import subprocess +import sys +from pathlib import ( + Path, +) + +import pytest +import yaml + +ROOT = Path(__file__).parents[2] +COMMON_REPORTS = { + "source/build_tests/generator-reports/**", + "source/build_tests/gtest-reports/**", + "source/build_tests/pytest-reports/**", +} + + +@pytest.fixture(params=[("test_cc.yml", "testcc"), ("test_cuda.yml", "test_cc")]) +def workflow(request): + filename, job_name = request.param + config = yaml.safe_load((ROOT / ".github/workflows" / filename).read_text()) + job = config["jobs"][job_name] + uploads = [s for s in job["steps"] if s.get("name") == "Upload C++ test reports"] + assert len(uploads) == 1 + return filename, job, uploads[0] + + +def test_report_upload_runs_after_failure_only_when_files_exist(workflow): + filename, job, upload = workflow + assert upload["uses"].startswith("actions/upload-artifact@") + assert "always()" in upload["if"] + assert " != ''" in upload["if"] + condition_paths = set(re.findall(r"'([^']+)'", upload["if"])) + paths = set(upload["with"]["path"].splitlines()) + expected = COMMON_REPORTS.copy() + if filename == "test_cuda.yml": + expected.add("source/build_lammps_kokkos/test-reports/**") + assert paths == expected + assert condition_paths == expected + assert "hashFiles(" in upload["if"] + assert upload["with"]["if-no-files-found"] == "ignore" + assert upload["with"]["retention-days"] == 14 + assert job["steps"][-1] == upload + + +def test_report_upload_cannot_replace_test_failure_with_success(workflow): + _, job, upload = workflow + # An artifact-service failure is non-blocking, but actual test steps keep + # their normal failure outcome and the existing required-job gate. + assert upload["continue-on-error"] is True + test_steps = [ + step + for step in job["steps"] + if "source/install/test_cc_local.sh" in step.get("run", "") + or "source/install/test_lammps_kokkos.sh" in step.get("run", "") + or "source/install/pytest_with_junit.sh" in step.get("run", "") + ] + assert test_steps + for step in test_steps: + assert not step.get("continue-on-error", False) + assert "|| true" not in step["run"] + + +def test_matrix_jobs_have_distinct_artifact_names(workflow): + _, job, upload = workflow + names = [] + for row in job["strategy"]["matrix"]["include"]: + name = upload["with"]["name"] + for key, value in row.items(): + name = name.replace("${{ matrix." + key + " }}", str(value).lower()) + assert "${{" not in name + names.append(name) + assert len(set(names)) == len(names) + + +def test_ordinary_pytest_reporting_preserves_commands_and_failure_handlers(workflow): + filename, job, _ = workflow + commands = [ + line.strip() + for step in job["steps"] + for line in step.get("run", "").splitlines() + if "source/install/pytest_with_junit.sh" in line + ] + if filename == "test_cc.yml": + assert commands == [ + "source/install/retry_on_sigterm.sh 3 source/install/pytest_with_junit.sh " + "lammps pytest --cov=deepmd source/lmp/tests", + "source/install/pytest_with_junit.sh ipi pytest --cov=deepmd source/ipi/tests", + ] + else: + assert commands == [ + "source/install/pytest_with_junit.sh lammps python -m pytest -s " + "source/lmp/tests || (cat log.lammps && exit 1)", + "source/install/pytest_with_junit.sh ipi python -m pytest source/ipi/tests", + ] + + +@pytest.fixture +def ordinary_pytest_command(tmp_path): + # Copy the real helper to a fake checkout so no reports touch the source tree. + install_dir = tmp_path / "source/install" + install_dir.mkdir(parents=True) + helper = install_dir / "pytest_with_junit.sh" + shutil.copy2(ROOT / "source/install/pytest_with_junit.sh", helper) + command = tmp_path / "pytest-command" + command.write_text( + f"#!{sys.executable}\n" + "import json, os, signal, sys\n" + "from pathlib import Path\n" + "with open('calls.jsonl', 'a') as stream: stream.write(json.dumps(sys.argv[1:]) + '\\n')\n" + "report = Path(sys.argv[-1].removeprefix('--junitxml='))\n" + "assert sys.argv[-1].startswith('--junitxml=')\n" + "statuses = os.environ['MOCK_STATUSES'].split(',')\n" + "count = len(Path('calls.jsonl').read_text().splitlines())\n" + "status = statuses[min(count, len(statuses)) - 1]\n" + "if status == 'SIGTERM': os.kill(os.getpid(), signal.SIGTERM)\n" + "report.write_text('')\n" + "sys.exit(int(status))\n" + ) + command.chmod(0o755) + return helper, command + + +@pytest.mark.skipif(sys.platform != "linux", reason="Requires GNU/Linux shell tools") +@pytest.mark.parametrize("status", [0, 1, 5, 17, 143, "SIGTERM"]) +def test_ordinary_pytest_reports_preserve_status_arguments_and_invocations( + tmp_path, ordinary_pytest_command, status +): + helper, command = ordinary_pytest_command + arguments = ["-m", "pytest", "--cov=deepmd", "test directory", "-k", "one or two"] + for invocation, name in enumerate(["lammps", "ipi", "lammps"], start=1): + result = subprocess.run( + [str(helper), name, str(command), *arguments], + cwd=tmp_path, + env={**os.environ, "MOCK_STATUSES": str(status)}, + capture_output=True, + text=True, + check=False, + ) + expected_status = -signal.SIGTERM if status == "SIGTERM" else status + assert result.returncode == expected_status, result.stderr + calls = [ + json.loads(line) + for line in (tmp_path / "calls.jsonl").read_text().splitlines() + ] + assert len(calls) == invocation + assert all(args[:-1] == arguments for args in calls) + report_root = tmp_path / "source/build_tests/pytest-reports" + reports = list(report_root.glob("run.*/*.xml")) + # A killed pytest process may never finish writing its XML report. + assert len(reports) == (0 if status == "SIGTERM" else invocation) + assert len(list(report_root.glob("run.*"))) == invocation + assert Path(calls[-1][-1].split("=", 1)[1]).name == f"{name}.xml" + + +@pytest.mark.skipif(sys.platform != "linux", reason="Requires GNU/Linux shell tools") +@pytest.mark.parametrize( + ("statuses", "status", "attempts", "report_count"), + [ + ("143,0", 0, 2, 2), + ("143", 143, 3, 3), + ("17", 17, 1, 1), + ("SIGTERM,0", 0, 2, 1), + ("SIGTERM", 143, 3, 0), + ], +) +def test_ordinary_pytest_retry_preserves_each_attempt( + tmp_path, ordinary_pytest_command, statuses, status, attempts, report_count +): + helper, command = ordinary_pytest_command + # Skip only the retry delay, without replacing the actual retry script. + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + sleep = bin_dir / "sleep" + sleep.write_text("#!/bin/bash\nexit 0\n") + sleep.chmod(0o755) + result = subprocess.run( + [ + str(ROOT / "source/install/retry_on_sigterm.sh"), + "3", + str(helper), + "lammps", + str(command), + "--cov=deepmd", + "source/lmp/tests", + ], + cwd=tmp_path, + env={ + **os.environ, + "PATH": str(bin_dir) + os.pathsep + os.environ["PATH"], + "MOCK_STATUSES": statuses, + }, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == status, result.stderr + report_root = tmp_path / "source/build_tests/pytest-reports" + reports = list(report_root.glob("run.*/lammps.xml")) + assert len(reports) == report_count + assert len(list(report_root.glob("run.*"))) == attempts + assert len((tmp_path / "calls.jsonl").read_text().splitlines()) == attempts + + +def test_kokkos_pytest_processes_write_distinct_reports(): + script = (ROOT / "source/install/test_lammps_kokkos.sh").read_text() + assert ( + 'TEST_REPORT_DIR=$(mktemp -d "${BUILD_ROOT}/test-reports/run.XXXXXX")' in script + ) + assert re.findall(r'--junitxml="([^\"]+)"', script) == [ + "${TEST_REPORT_DIR}/spin.xml", + "${TEST_REPORT_DIR}/long-range.xml", + ] + assert script.startswith("#!/bin/bash\nset -euxo pipefail\n") + + +@pytest.mark.skipif(sys.platform != "linux", reason="Requires GNU/Linux shell tools") +@pytest.mark.parametrize("status", [0, 17]) +def test_kokkos_spin_generator_reports_preserve_status_and_invocations( + tmp_path, status +): + script = (ROOT / "source/install/test_lammps_kokkos.sh").read_text() + command = script[ + script.index("# Record the spin fixture") : script.index("# The wheel's") + ] + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + python = bin_dir / "python" + python.write_text( + f"#!{sys.executable}\n" + "import os, sys\n" + "from pathlib import Path\n" + "assert sys.argv[1:] == ['-u', str(Path(os.environ['REPO_ROOT']) / 'source/tests/infer/gen_dpa4c_spin_lmp_kokkos.py')]\n" + "with open('calls.txt', 'a') as stream: stream.write('generator\\n')\n" + "sys.exit(int(os.environ['MOCK_STATUS']))\n" + ) + python.chmod(0o755) + build = tmp_path / "build" + for invocation in (1, 2): + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", command], + cwd=tmp_path, + env={ + **os.environ, + "PATH": str(bin_dir) + os.pathsep + os.environ["PATH"], + "REPO_ROOT": str(tmp_path), + "BUILD_ROOT": str(build), + "MOCK_STATUS": str(status), + }, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == status, result.stderr + assert (tmp_path / "calls.txt").read_text() == "generator\n" * invocation + reports = list((build / "test-reports").glob("run.*/*.tsv")) + assert len(reports) == invocation + for report in reports: + assert report.name == "gen_dpa4c_spin_lmp_kokkos.tsv" + with report.open() as stream: + rows = list(csv.DictReader(stream, delimiter="\t")) + assert len(rows) == 1 + assert set(rows[0]) == {"generator", "seconds", "exit_status"} + assert rows[0]["generator"] == report.stem + assert int(rows[0]["seconds"]) >= 0 + assert int(rows[0]["exit_status"]) == status + + +@pytest.mark.skipif(sys.platform != "linux", reason="Requires GNU/Linux shell tools") +@pytest.mark.parametrize("failure", ["", "spin.xml", "long-range.xml"]) +def test_kokkos_report_commands_preserve_pytest_status(tmp_path, failure): + # Execute the unmodified test-command tail with a tiny pytest stand-in. + # This tests exit-status/report wiring, not the CUDA/LAMMPS computation. + script = (ROOT / "source/install/test_lammps_kokkos.sh").read_text() + tail = script[script.index("# Keep each invocation and each pytest process") :] + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + python = bin_dir / "python" + python.write_text( + f"#!{sys.executable}\n" + "import os, sys\n" + "from pathlib import Path\n" + "assert sys.argv[1:3] == ['-m', 'pytest']\n" + "report = Path(next(a.split('=', 1)[1] for a in sys.argv if a.startswith('--junitxml=')))\n" + "report.write_text('')\n" + "sys.exit(17 if report.name == os.environ['MOCK_FAIL'] else 0)\n" + ) + python.chmod(0o755) + build = tmp_path / "build" + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", tail], + env={ + **os.environ, + "PATH": str(bin_dir) + os.pathsep + os.environ["PATH"], + "REPO_ROOT": str(tmp_path), + "BUILD_ROOT": str(build), + "MPI_ROOT": str(tmp_path), + "MOCK_FAIL": failure, + }, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == (17 if failure else 0), result.stderr + directories = list((build / "test-reports").glob("run.*")) + assert len(directories) == 1 + expected = {"spin.xml"} + if failure != "spin.xml": + expected.add("long-range.xml") + assert {path.name for path in directories[0].iterdir()} == expected diff --git a/source/tests/test_cuda_ci_reports.py b/source/tests/test_cuda_ci_reports.py new file mode 100644 index 0000000000..dfa1e34046 --- /dev/null +++ b/source/tests/test_cuda_ci_reports.py @@ -0,0 +1,122 @@ +# SPDX-License-Identifier: LGPL-3.0-or-later +"""Check CUDA Python timing reports without launching a GPU workflow.""" + +import os +import shlex +import subprocess +import sys +from pathlib import ( + Path, +) + +import pytest +import yaml + +ROOT = Path(__file__).parents[2] +SHARDS = { + "pt_expt-model": ["source/tests/pt_expt/model"], + "pt_expt-other": ["source/tests/pt_expt", "--ignore=source/tests/pt_expt/model"], + "other": ["source/tests", "--ignore=source/tests/pt_expt"], +} + + +@pytest.fixture +def python_job(): + config = yaml.safe_load((ROOT / ".github/workflows/test_cuda.yml").read_text()) + return config["jobs"]["test_python"] + + +def _test_command(job, shard): + rows = {row["shard"]: row for row in job["strategy"]["matrix"]["include"]} + assert set(rows) == set(SHARDS) + steps = [step for step in job["steps"] if "-m pytest " in step.get("run", "")] + assert len(steps) == 1 # Reporting must not duplicate the test invocation. + step = steps[0] + assert not step.get("continue-on-error", False) + command = step["run"] + for key, value in rows[shard].items(): + command = command.replace("${{ matrix." + key + " }}", str(value)) + assert "${{" not in command + return command + + +@pytest.mark.parametrize("shard", SHARDS) +def test_python_shards_keep_selection_and_report_all_phases(python_job, shard): + # pytest's total mode includes setup, call, and teardown in each case time. + assert shlex.split(_test_command(python_job, shard)) == [ + "python", + "-m", + "pytest", + *SHARDS[shard], + "--ignore=source/tests/pd", + f"--junitxml=test-reports/python-{shard}.xml", + "-o", + "junit_duration_report=total", + ] + + +def test_python_report_upload_runs_after_failure_when_reports_exist(python_job): + uploads = [ + step + for step in python_job["steps"] + if step.get("name") == "Upload Python test reports" + ] + assert len(uploads) == 1 + upload = uploads[0] + assert python_job["steps"][-1] == upload + assert upload["uses"].startswith("actions/upload-artifact@") + assert upload["if"] == ( + "${{ always() && hashFiles('test-reports/python-*.xml') != '' }}" + ) + assert upload["with"]["path"] == "test-reports/python-*.xml" + assert upload["with"]["if-no-files-found"] == "ignore" + assert upload["with"]["retention-days"] == 14 + # An artifact-service failure is non-blocking, not an actual test failure. + assert upload["continue-on-error"] is True + names = { + upload["with"]["name"].replace("${{ matrix.shard }}", shard) for shard in SHARDS + } + assert len(names) == len(SHARDS) + assert all(name.startswith("python-cuda-") and "${{" not in name for name in names) + + +@pytest.mark.skipif(sys.platform != "linux", reason="Requires GNU/Linux shell tools") +@pytest.mark.parametrize("shard", SHARDS) +@pytest.mark.parametrize("status", [0, 17]) +def test_python_report_command_preserves_exit_status( + python_job, tmp_path, shard, status +): + # Execute the actual workflow command with a lightweight pytest stand-in. + # Both success and failure write one report from exactly one invocation. + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + python = bin_dir / "python" + python.write_text( + f"#!{sys.executable}\n" + "import os, sys\n" + "from pathlib import Path\n" + "assert sys.argv[1:3] == ['-m', 'pytest']\n" + "with open('calls.txt', 'a') as stream: stream.write('pytest\\n')\n" + "report = Path(next(a.split('=', 1)[1] for a in sys.argv if a.startswith('--junitxml=')))\n" + "report.parent.mkdir(parents=True, exist_ok=True)\n" + "report.write_text('')\n" + "sys.exit(int(os.environ['MOCK_STATUS']))\n" + ) + python.chmod(0o755) + result = subprocess.run( + ["bash", "-euo", "pipefail", "-c", _test_command(python_job, shard)], + cwd=tmp_path, + env={ + **os.environ, + "PATH": str(bin_dir) + os.pathsep + os.environ["PATH"], + "MOCK_STATUS": str(status), + }, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == status, result.stderr + assert (tmp_path / "calls.txt").read_text() == "pytest\n" + assert {path.name for path in (tmp_path / "test-reports").iterdir()} == { + f"python-{shard}.xml" + }