Files
Mujoco_WASM/test/xml/xml_write_read_test.cc
T
Alessio 55d13aec5f Replace the flex metric factorization with a block preconditioner
Every step, the flex block of the implicit effective metric M + K was
factorized by sparse Cholesky, because K depends on the configuration. On
model/flex/bag.xml, added here, that is roughly half the step, against a
comparable share for the constraint solve it exists to accelerate.

Keep only the metric's per-vertex 3x3 diagonal blocks, prefactored. Neither
consumer needs the exact inverse: the CG constraint solver only wants a
preconditioner, and qacc_smooth can come from an iterative solve using those
blocks. They are O(n) to build and to apply, but weaker, so CG runs about twice
the iterations and qacc_smooth becomes an iteration rather than a direct solve.
Net, the bag model steps roughly twice as fast.

The preconditioner, by metric state. Inactive, meaning no flex elasticity or an
explicit integrator: M^-1, unchanged. Bending only (nefmK == 0): M^-1 plus the
exact constant bending factor from mj_setConst on the dofs it covers,
unchanged; that factor is built at model compile time and costs nothing per
step. Per-step stiffness: M^-1 plus the 3x3 blocks, where before it was a
per-step sparse Cholesky, or, when M couples across the flex block, an inner
PCG of up to 50 iterations run once per outer CG iteration.

Only models carrying per-step stretch stiffness change in wall-clock. Both
ponchos hold their timing and take slightly fewer CG iterations than before,
because the preconditioner is now symmetric: it applies M^-1 and the covered
blocks to disjoint sets of dofs, where previously the two overlapped and the
operator was not symmetric, which PCG requires.

mjd_effSolve is the accurate solve of (M + K)x = b; what used to carry that
name only preconditions and is now mjd_effPrec. Its CG guarded the division by
pAp with mjMINVAL, an absolute floor on a quantity that scales with the square
of the right-hand side, so a small b aborted the solve while the curvature was
healthy: four flex models were quietly left short of tolerance. For an SPD
metric the guard is positivity, and with that the same solves converge. The qacc_smooth call site in
mj_fwdAcceleration is textually unchanged but now reaches the iterative solve,
which converges on opt.tolerance rather than a hardcoded threshold, floored in
mjUSESINGLE builds where the squared target is unreachable in float. Reaching
the iteration cap names the ill-conditioned flex stiffness and then reports it
through mjWARN_INERTIA, rather than returning an under-converged result.
Covered dofs are located by walking the covered rows of the stiffness matrix,
as they need not be 3-aligned from dof 0: any joint declared before a flexcomp
shifts them.

mjData.efm_L_rownnz, efm_L_rowadr and efm_L_colind described the sparsity of
the deleted factorization and are removed: left NULL with nonzero mjxmacro
extents they made the Python bindings hand back uninitialized arrays.
efm_active loses the value 2 for the same reason, nothing selects a solve path
on preconditioner exactness any more. Both are recorded under breaking changes.

model/flex/bag.xml is added because no shipped model carried per-step stretch
stiffness. The ponchos are bending-only and trampoline.xml uses an explicit
integrator, so the metric never activates there. It is excluded from
WriteReadCompareTest: stretch stiffness amplifies rest geometry that XML rounds
on save.
2026-07-29 14:36:15 +01:00

193 lines
6.4 KiB
C++

// Copyright 2026 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Tests for loading and saving multiple files.
#include <algorithm>
#include <array>
#include <cctype>
#include <cstddef>
#include <filesystem> // NOLINT(build/c++17)
#include <string>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <absl/strings/match.h>
#include <mujoco/mjmodel.h>
#include <mujoco/mujoco.h>
#include "src/xml/xml_numeric_format.h"
#include "test/compare_model.h"
#include "test/fixture.h"
namespace mujoco {
namespace {
using ::testing::NotNull;
using XMLWriterTest = MujocoTest;
std::vector<std::string> GetWriteReadTestModels() {
std::vector<std::string> models;
std::string ext(".xml");
for (const auto& path : {GetTestDataFilePath("."), GetModelPath(".")}) {
for (const auto& p : std::filesystem::recursive_directory_iterator(path)) {
if (p.path().extension() == ext) {
std::string xml = p.path().string();
if ( // if file is meant to fail, skip it
absl::StrContains(xml, "malformed_") ||
absl::StrContains(xml, "_fail") ||
// exclude files that are too slow to load
absl::StrContains(xml, "cow") || absl::StrContains(xml, "gmsh_") ||
absl::StrContains(xml, "shark_") ||
absl::StrContains(xml, "perf") ||
// exclude files that fail the comparison test
absl::StrContains(xml, "rfcamera") ||
absl::StrContains(xml, "tactile") ||
absl::StrContains(xml, "makemesh") ||
absl::StrContains(xml, "carousel") ||
absl::StrContains(xml, "many_dependencies") ||
absl::StrContains(xml, "usd") ||
absl::StrContains(xml, "torus_maxhull") ||
absl::StrContains(xml, "fitmesh_") ||
absl::StrContains(xml, "lengthrange") ||
absl::StrContains(xml, "hfield_xml") ||
absl::StrContains(xml, "fromto_convex") ||
absl::StrContains(xml, "cube_skin") ||
absl::StrContains(xml, "cube_3x3x3") ||
// flex_stiffness: stretch amplifies geometry XML rounds on save
absl::StrContains(xml, "flex/bag") ||
// exclude files that fail since we do not save pinned flex nodes
absl::StrContains(xml, "gripper_trilinear") ||
absl::StrContains(xml, "strain") ||
// exclude conflict tests (known option conflict warnings/errors)
absl::StrContains(xml, "xml/testdata/parent_")) {
continue;
}
models.push_back(xml);
}
}
}
return models;
}
class WriteReadCompareTest : public XMLWriterTest,
public ::testing::WithParamInterface<std::string> {
public:
};
TEST_P(WriteReadCompareTest, WriteReadCompare) {
std::string xml = GetParam();
// full precision float printing
FullFloatPrecision increase_precision;
// load model
std::array<char, 1000> error;
mjSpec* s =
mj_parseXML(xml.c_str(), nullptr, error.data(), error.size());
if (!s) {
GTEST_SKIP() << "Failed to load " << xml.c_str() << ": " << error.data();
}
mjModel* m = mj_compile(s, nullptr);
if (!m) {
mj_deleteSpec(s);
GTEST_SKIP() << "Failed to compile " << xml.c_str() << ": " << error.data();
}
// make data
mjData* d = mj_makeData(m);
ASSERT_THAT(d, testing::NotNull()) << "Failed to create data\n";
// save and load back
auto abs_path = std::filesystem::path(xml);
mjSpec* stemp = mj_parseXMLString(SaveAndReadXml(s).c_str(), 0, error.data(),
error.size());
ASSERT_THAT(stemp, NotNull())
<< "Failed to load " << xml.c_str() << ": " << error.data();
mjs_setString(stemp->modelfiledir,
abs_path.remove_filename().string().c_str());
mjModel* mtemp = mj_compile(stemp, nullptr);
ASSERT_THAT(mtemp, NotNull()) << error.data() << " from " << xml.c_str();
mjtNum tol = 0;
// for particularly sensitive models, relax the tolerance
if (absl::StrContains(xml, "belt.xml") ||
absl::StrContains(xml, "cable.xml")) {
tol = 1e-13;
}
// compare and delete
std::string field = "";
mjtNum result = CompareModel(m, mtemp, field);
EXPECT_LE(result, tol) << "Loaded and saved models are different!\n"
<< "Affected file " << xml << '\n'
<< "Different field: " << field << '\n';
mj_deleteModel(mtemp);
// check for stack memory leak
mj_step(m, d);
EXPECT_EQ(d->pstack, 0) << "mjData stack memory leak detected in " <<
xml << '\n';
// delete data
mj_deleteData(d);
// allocate buffer, save m into it
size_t sz = mj_sizeModel(m);
void* buffer = mju_malloc(sz);
mj_saveModel(m, nullptr, buffer, sz);
// make new VFS add buffer to it
mjVFS* vfs = (mjVFS*)mju_malloc(sizeof(mjVFS));
mj_defaultVFS(vfs);
int failed = mj_addBufferVFS(vfs, "model.mjb", buffer, sz);
EXPECT_EQ(failed, 0) << "Failed to add buffer to VFS";
// load model from VFS
mtemp = mj_loadModel("model.mjb", vfs);
ASSERT_THAT(mtemp, NotNull());
// compare with 0 tolerance
field = "";
result = CompareModel(m, mtemp, field);
EXPECT_EQ(result, 0) << "Loaded and saved binary models are different!\n"
<< "Affected file " << xml << '\n'
<< "Different field: " << field << '\n';
// clean up
mj_deleteSpec(s);
mj_deleteSpec(stemp);
mj_deleteModel(m);
mj_deleteModel(mtemp);
mj_deleteVFS(vfs);
mju_free(vfs);
mju_free(buffer);
}
INSTANTIATE_TEST_SUITE_P(
AllModels, WriteReadCompareTest,
::testing::ValuesIn(GetWriteReadTestModels()),
[](const ::testing::TestParamInfo<std::string>& info) {
std::string name = std::filesystem::path(info.param).filename().string();
std::replace_if(
name.begin(), name.end(),
[](char c) { return !std::isalnum(c); }, '_');
return name + "_" + std::to_string(info.index);
});
} // namespace
} // namespace mujoco