mjbatch-uni 0.2.2__tar.gz → 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,91 @@
1
+ cmake_minimum_required(VERSION 3.15...3.30)
2
+ project(${SKBUILD_PROJECT_NAME} LANGUAGES CXX)
3
+
4
+ find_package(Python 3.10 COMPONENTS Interpreter Development.Module REQUIRED)
5
+
6
+ execute_process(
7
+ COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
8
+ OUTPUT_STRIP_TRAILING_WHITESPACE
9
+ OUTPUT_VARIABLE nanobind_ROOT)
10
+ find_package(nanobind CONFIG REQUIRED)
11
+
12
+ # Headers and libmujoco come from the installed mujoco wheel.
13
+ execute_process(
14
+ COMMAND "${Python_EXECUTABLE}" -c
15
+ "import mujoco, pathlib; print(pathlib.Path(mujoco.__file__).parent)"
16
+ OUTPUT_STRIP_TRAILING_WHITESPACE
17
+ OUTPUT_VARIABLE MUJOCO_PKG_DIR
18
+ COMMAND_ERROR_IS_FATAL ANY)
19
+ if(WIN32)
20
+ set(MUJOCO_DLL "${MUJOCO_PKG_DIR}/mujoco.dll")
21
+ if(NOT EXISTS "${MUJOCO_DLL}")
22
+ message(FATAL_ERROR "Could not find mujoco.dll in ${MUJOCO_PKG_DIR}")
23
+ endif()
24
+
25
+ # The MuJoCo wheel exports the C API from mujoco.dll but does not ship an
26
+ # MSVC import library. Generate one at build time; it is not installed.
27
+ get_filename_component(MSVC_TOOL_BIN_DIR "${CMAKE_CXX_COMPILER}" DIRECTORY)
28
+ find_program(MSVC_LIB_EXECUTABLE NAMES lib HINTS "${MSVC_TOOL_BIN_DIR}")
29
+ if(NOT MSVC_LIB_EXECUTABLE)
30
+ message(FATAL_ERROR "Could not find MSVC lib.exe")
31
+ endif()
32
+ find_program(MSVC_DUMPBIN_EXECUTABLE NAMES dumpbin HINTS "${MSVC_TOOL_BIN_DIR}")
33
+ if(NOT MSVC_DUMPBIN_EXECUTABLE)
34
+ message(FATAL_ERROR "Could not find MSVC dumpbin.exe")
35
+ endif()
36
+
37
+ execute_process(
38
+ COMMAND "${MSVC_DUMPBIN_EXECUTABLE}" "/EXPORTS" "${MUJOCO_DLL}"
39
+ OUTPUT_VARIABLE MUJOCO_EXPORTS
40
+ COMMAND_ERROR_IS_FATAL ANY)
41
+ string(REGEX MATCHALL
42
+ " +[0-9]+ +[0-9A-Fa-f]+ +[0-9A-Fa-f]+ +([^ \r\n]+)"
43
+ MUJOCO_EXPORT_MATCHES "${MUJOCO_EXPORTS}")
44
+ if(NOT MUJOCO_EXPORT_MATCHES)
45
+ message(FATAL_ERROR "Could not parse exports from ${MUJOCO_DLL}")
46
+ endif()
47
+
48
+ set(MUJOCO_DEF_FILE "${CMAKE_CURRENT_BINARY_DIR}/mujoco.def")
49
+ file(WRITE "${MUJOCO_DEF_FILE}" "LIBRARY mujoco.dll\nEXPORTS\n")
50
+ foreach(export_match IN LISTS MUJOCO_EXPORT_MATCHES)
51
+ string(REGEX REPLACE ".* +([^ \r\n]+)$" "\\1" export_symbol "${export_match}")
52
+ file(APPEND "${MUJOCO_DEF_FILE}" " ${export_symbol}\n")
53
+ endforeach()
54
+
55
+ set(MUJOCO_LIBRARY "${CMAKE_CURRENT_BINARY_DIR}/mujoco.lib")
56
+ execute_process(
57
+ COMMAND "${MSVC_LIB_EXECUTABLE}" "/def:${MUJOCO_DEF_FILE}" "/machine:x64"
58
+ "/out:${MUJOCO_LIBRARY}"
59
+ COMMAND_ERROR_IS_FATAL ANY)
60
+ else()
61
+ file(GLOB MUJOCO_LIBRARY "${MUJOCO_PKG_DIR}/libmujoco*${CMAKE_SHARED_LIBRARY_SUFFIX}*")
62
+ if(NOT MUJOCO_LIBRARY)
63
+ message(FATAL_ERROR "Could not find libmujoco in ${MUJOCO_PKG_DIR}")
64
+ endif()
65
+ list(GET MUJOCO_LIBRARY 0 MUJOCO_LIBRARY)
66
+ endif()
67
+
68
+ nanobind_add_module(_bindings FREE_THREADED NOMINSIZE src/mjbatch/csrc/bindings.cpp)
69
+ if(WIN32)
70
+ # Windows headers are nested one directory deeper than the Unix wheels.
71
+ target_include_directories(_bindings PRIVATE "${MUJOCO_PKG_DIR}/include/mujoco")
72
+ else()
73
+ target_include_directories(_bindings PRIVATE "${MUJOCO_PKG_DIR}/include")
74
+ endif()
75
+ target_link_libraries(_bindings PRIVATE "${MUJOCO_LIBRARY}")
76
+
77
+ # Find libmujoco next to the installed extension, <site-packages>/mujoco. The
78
+ # macOS wheel's install name is a framework path that does not exist, so point
79
+ # our load command at the plain file name instead.
80
+ if(APPLE)
81
+ get_filename_component(MUJOCO_LIB_NAME "${MUJOCO_LIBRARY}" NAME)
82
+ execute_process(COMMAND otool -D "${MUJOCO_LIBRARY}" OUTPUT_VARIABLE _otool)
83
+ string(REGEX MATCH "@rpath[^\n]*" MUJOCO_INSTALL_NAME "${_otool}")
84
+ add_custom_command(TARGET _bindings POST_BUILD COMMAND install_name_tool -change
85
+ "${MUJOCO_INSTALL_NAME}" "@rpath/${MUJOCO_LIB_NAME}" $<TARGET_FILE:_bindings>)
86
+ set_target_properties(_bindings PROPERTIES INSTALL_RPATH "@loader_path/../mujoco")
87
+ elseif(NOT WIN32)
88
+ set_target_properties(_bindings PROPERTIES INSTALL_RPATH "$ORIGIN/../mujoco")
89
+ endif()
90
+
91
+ install(TARGETS _bindings DESTINATION mjbatch)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mjbatch-uni
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: A Python library for running thousands of MuJoCo simulations in parallel on CPU (unilabsim fork).
5
5
  Keywords: mujoco,physics,simulation,batched,reinforcement-learning
6
6
  Author-Email: Kevin Zakka <zakka@berkeley.edu>, Yufei Jia <jyf23@mails.tsinghua.edu.cn>
@@ -11,6 +11,7 @@ Classifier: Intended Audience :: Developers
11
11
  Classifier: Intended Audience :: Science/Research
12
12
  Classifier: Operating System :: MacOS
13
13
  Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Operating System :: Microsoft :: Windows
14
15
  Classifier: Programming Language :: C++
15
16
  Classifier: Programming Language :: Python :: 3.10
16
17
  Classifier: Programming Language :: Python :: 3.11
@@ -4,7 +4,7 @@ build-backend = "scikit_build_core.build"
4
4
 
5
5
  [project]
6
6
  name = "mjbatch-uni"
7
- version = "0.2.2"
7
+ version = "0.2.3"
8
8
  description = "A Python library for running thousands of MuJoCo simulations in parallel on CPU (unilabsim fork)."
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -20,6 +20,7 @@ classifiers = [
20
20
  "Intended Audience :: Science/Research",
21
21
  "Operating System :: MacOS",
22
22
  "Operating System :: POSIX :: Linux",
23
+ "Operating System :: Microsoft :: Windows",
23
24
  "Programming Language :: C++",
24
25
  "Programming Language :: Python :: 3.10",
25
26
  "Programming Language :: Python :: 3.11",
@@ -79,9 +80,7 @@ testpaths = ["tests"]
79
80
 
80
81
  [tool.cibuildwheel]
81
82
  build = "cp310-* cp311-* cp312-* cp313-*"
82
- # Windows: the mujoco wheel ships mujoco.dll with no import library, and the
83
- # extension finds libmujoco by rpath, which Windows has no equivalent of.
84
- skip = "*-musllinux_* *-win* *_i686"
83
+ skip = "*-musllinux_* *_i686"
85
84
  test-requires = "pytest"
86
85
  test-command = "pytest {project}/tests"
87
86
 
@@ -11,8 +11,8 @@
11
11
  #include <nanobind/ndarray.h>
12
12
 
13
13
  #include <algorithm>
14
- #include <csetjmp>
15
14
  #include <cstdint>
15
+ #include <csetjmp>
16
16
  #include <cstdio>
17
17
  #include <cstdlib>
18
18
  #include <cstring>
@@ -26,6 +26,7 @@
26
26
  #include <string_view>
27
27
  #include <thread>
28
28
  #include <unordered_map>
29
+ #include <utility>
29
30
  #include <vector>
30
31
 
31
32
  #ifdef __linux__
@@ -390,19 +391,69 @@ inline void SampleHfield(const mjModel* m, const mjData* d, const QueryCtx& ctx)
390
391
  }
391
392
  }
392
393
 
393
- // mju_error trap for worker threads: record the message and unwind to the
394
- // worker's setjmp; everything else goes to the handler that was active before.
395
- inline thread_local std::jmp_buf* tls_jmp = nullptr;
396
- inline thread_local std::string tls_error;
397
- inline mjfLogHandler prev_log_handler = nullptr;
394
+ // MuJoCo error handlers must not return. A thread-local handler and longjmp
395
+ // keep the unwind within the worker's C++ frame, matching the official Python
396
+ // bindings, without changing handlers owned by other threads.
397
+ inline thread_local std::jmp_buf tls_jmp_buf = {};
398
+ inline thread_local bool tls_jmp_active = false;
399
+ inline thread_local char tls_error[1024] = {};
400
+ inline thread_local mjfLogHandler tls_prev_handler = nullptr;
401
+
402
+ // Declared in MuJoCo's internal engine header but omitted from the installed
403
+ // public header. The Python dependency is pinned, so these exported symbols
404
+ // have a stable ABI for this build.
405
+ extern "C" mjfLogHandler _mjPRIVATE_setTlsLogHandler(mjfLogHandler handler);
406
+ extern "C" mjfLogHandler _mjPRIVATE_getGlobalLogHandler(void);
407
+
398
408
  inline void LogTrap(const mjLogMessage* msg) {
399
- if (msg->level == mjLOG_ERROR && tls_jmp) {
400
- tls_error = msg->subject;
401
- std::longjmp(*tls_jmp, 1);
409
+ if (msg->level == mjLOG_ERROR && tls_jmp_active) {
410
+ std::snprintf(tls_error, sizeof(tls_error), "%s", msg->subject);
411
+ std::longjmp(tls_jmp_buf, 1);
412
+ }
413
+ // MuJoCo dispatches to this TLS handler instead of the global one. Preserve
414
+ // an existing TLS handler when present; otherwise keep official bindings'
415
+ // behavior of not forwarding while a scoped wrapper is active.
416
+ if (tls_prev_handler) {
417
+ tls_prev_handler(msg);
418
+ } else if (mjfLogHandler previous = _mjPRIVATE_getGlobalLogHandler(); previous) {
419
+ previous(msg);
420
+ }
421
+ }
422
+
423
+ // A fatal MuJoCo callback cannot safely throw or return through C. Jump only
424
+ // back to this tight wrapper, then throw from C++ after the C frames are gone.
425
+ struct MjError : std::exception {
426
+ const char* what() const noexcept override { return tls_error; }
427
+ };
428
+
429
+ template <typename Return, typename... Args, typename... CallArgs>
430
+ #if defined(_MSC_VER)
431
+ __forceinline
432
+ #endif
433
+ Return TrapCall(Return (*fn)(Args...), CallArgs&&... args) {
434
+ mjfLogHandler previous = _mjPRIVATE_setTlsLogHandler(LogTrap);
435
+ tls_prev_handler = previous;
436
+ tls_jmp_active = true;
437
+ if (setjmp(tls_jmp_buf) == 0) {
438
+ if constexpr (std::is_void_v<Return>) {
439
+ fn(std::forward<CallArgs>(args)...);
440
+ } else {
441
+ Return result = fn(std::forward<CallArgs>(args)...);
442
+ tls_jmp_active = false;
443
+ _mjPRIVATE_setTlsLogHandler(previous);
444
+ tls_prev_handler = nullptr;
445
+ return result;
446
+ }
447
+ tls_jmp_active = false;
448
+ _mjPRIVATE_setTlsLogHandler(previous);
449
+ tls_prev_handler = nullptr;
450
+ return;
402
451
  }
403
- prev_log_handler(msg);
452
+ tls_jmp_active = false;
453
+ _mjPRIVATE_setTlsLogHandler(previous);
454
+ tls_prev_handler = nullptr;
455
+ throw MjError{};
404
456
  }
405
- inline void InstallLogTrap() { prev_log_handler = mju_setLogHandler(LogTrap); }
406
457
 
407
458
  // The Batch whose step callback is running on this thread: a reentrant call
408
459
  // from inside it raises instead of deadlocking on mu_.
@@ -663,7 +714,7 @@ class Batch {
663
714
  bool ParseDtype(const FieldInfo& f, std::optional<nb::object>& dtype) {
664
715
  if (!dtype || dtype->is_none()) return false;
665
716
  nb::object np = nb::module_::import_("numpy");
666
- std::string name = nb::cast<std::string>(nb::str(np.attr("dtype")(*dtype).attr("name")));
717
+ std::string name = nb::cast<std::string>(np.attr("dtype")(*dtype).attr("name"));
667
718
  if (name == DtypeName(f.elem)) return false;
668
719
  if (name == "float32" && f.elem == Elem::Num) return true;
669
720
  throw nb::value_error((std::string(f.name) + " cannot be " + name).c_str());
@@ -841,7 +892,7 @@ class Batch {
841
892
  if (op == Op::SetConst) Restore(m);
842
893
  for (auto& s : expanded_) FromBuf(s->info->get(m), s->buf.get() + i * s->row, *s);
843
894
  if (op == Op::SetConst) {
844
- mj_setConst(m, d);
895
+ TrapCall(mj_setConst, m, d);
845
896
  for (auto& s : expanded_) ToBuf(s->buf.get() + i * s->row, s->info->get(m), *s);
846
897
  scalars_[i] = Scalars::Of(m);
847
898
  for (const FieldInfo* f : restorable_) {
@@ -856,12 +907,12 @@ class Batch {
856
907
  if (!models_.empty()) scalars_[i].Apply(m);
857
908
  if (op == Op::Reset) {
858
909
  if (arg >= 0) {
859
- mj_resetDataKeyframe(m, d, arg);
910
+ TrapCall(mj_resetDataKeyframe, m, d, arg);
860
911
  } else {
861
- mj_resetData(m, d);
912
+ TrapCall(mj_resetData, m, d);
862
913
  }
863
914
  } else {
864
- mj_setState(m, d, State(i), mjSTATE_INTEGRATION);
915
+ TrapCall(mj_setState, m, d, State(i), mjSTATE_INTEGRATION);
865
916
  std::memcpy(d->warning, Warning(i), sizeof(d->warning));
866
917
  }
867
918
  for (auto& s : bound_) {
@@ -874,12 +925,13 @@ class Batch {
874
925
  switch (op) {
875
926
  case Op::Step: {
876
927
  for (int k = 0; k < arg; ++k) {
877
- mj_step(m, d);
928
+ TrapCall(mj_step, m, d);
878
929
  if (hist) {
879
- mj_getState(m, d, hist + static_cast<size_t>(k) * nstate_, mjSTATE_INTEGRATION);
930
+ TrapCall(mj_getState, m, d, hist + static_cast<size_t>(k) * nstate_,
931
+ mjSTATE_INTEGRATION);
880
932
  }
881
933
  }
882
- if (forward_) mj_forward(m, d); // derived fields current with the new state
934
+ if (forward_) TrapCall(mj_forward, m, d); // derived fields current with new state
883
935
  break;
884
936
  }
885
937
  case Op::Substep: {
@@ -893,12 +945,12 @@ class Batch {
893
945
  }
894
946
  bool tail = cctx->tail_only;
895
947
  if (!cctx->tail_only) {
896
- mj_step(m, d);
948
+ TrapCall(mj_step, m, d);
897
949
  if (cctx->hist) {
898
- mj_getState(m, d, cctx->hist + static_cast<size_t>(cctx->k) * nstate_,
899
- mjSTATE_INTEGRATION);
950
+ TrapCall(mj_getState, m, d,
951
+ cctx->hist + static_cast<size_t>(cctx->k) * nstate_, mjSTATE_INTEGRATION);
900
952
  }
901
- mj_getState(m, d, State(i), mjSTATE_INTEGRATION);
953
+ TrapCall(mj_getState, m, d, State(i), mjSTATE_INTEGRATION);
902
954
  std::memcpy(Warning(i), d->warning, sizeof(d->warning));
903
955
  if (cctx->k + 1 == cctx->nstep) tail = true;
904
956
  }
@@ -906,7 +958,7 @@ class Batch {
906
958
  cctx->done[0] = 1;
907
959
  // A tail after an exception always forwards, so derived fields are current
908
960
  // with the state the sim stopped at rather than one substep behind.
909
- if (forward_ || cctx->tail_only) mj_forward(m, d);
961
+ if (forward_ || cctx->tail_only) TrapCall(mj_forward, m, d);
910
962
  if (cctx->tail_only) std::memcpy(Warning(i), d->warning, sizeof(d->warning));
911
963
  for (auto& s : bound_) CopyOut(*s, d, i);
912
964
  return;
@@ -914,7 +966,7 @@ class Batch {
914
966
  case Op::Substep1: {
915
967
  // Position- and velocity-stage sensors are current with State(i) here.
916
968
  // Input mirrors stay stale because Substep2 applies the callback writes.
917
- mj_step1(m, d);
969
+ TrapCall(mj_step1, m, d);
918
970
  CopySensorRange(*cctx->sensor, d, i, cctx->sensor_start, cctx->sensor_width);
919
971
  return;
920
972
  }
@@ -923,35 +975,35 @@ class Batch {
923
975
  // per-sim snapshot. Stage one is recomputed after State(i) and the
924
976
  // callback writes have been loaded; the sensor view copied above is
925
977
  // still the fresh result at x_k. Sync mirrors only after mj_step2.
926
- mj_step1(m, d);
978
+ TrapCall(mj_step1, m, d);
927
979
  for (auto& s : bound_) {
928
980
  if (s->mirror) {
929
981
  std::memcpy(s->mirror.get() + i * s->row, s->buf.get() + i * s->row, s->row);
930
982
  }
931
983
  }
932
- mj_step2(m, d);
984
+ TrapCall(mj_step2, m, d);
933
985
  if (cctx->hist) {
934
- mj_getState(m, d, cctx->hist + static_cast<size_t>(cctx->k) * nstate_,
935
- mjSTATE_INTEGRATION);
986
+ TrapCall(mj_getState, m, d,
987
+ cctx->hist + static_cast<size_t>(cctx->k) * nstate_, mjSTATE_INTEGRATION);
936
988
  }
937
- mj_getState(m, d, State(i), mjSTATE_INTEGRATION);
989
+ TrapCall(mj_getState, m, d, State(i), mjSTATE_INTEGRATION);
938
990
  std::memcpy(Warning(i), d->warning, sizeof(d->warning));
939
991
  if (cctx->k + 1 != cctx->nstep) return;
940
992
  cctx->done[0] = 1;
941
- if (forward_) mj_forward(m, d);
993
+ if (forward_) TrapCall(mj_forward, m, d);
942
994
  for (auto& s : bound_) CopyOut(*s, d, i);
943
995
  return;
944
996
  }
945
997
  case Op::Forward:
946
998
  case Op::Reset:
947
- mj_forward(m, d);
999
+ TrapCall(mj_forward, m, d);
948
1000
  break;
949
1001
  case Op::RefreshSensor:
950
- mj_kinematics(m, d);
951
- mj_comPos(m, d);
952
- mj_comVel(m, d);
953
- mj_sensorPos(m, d);
954
- mj_sensorVel(m, d);
1002
+ TrapCall(mj_kinematics, m, d);
1003
+ TrapCall(mj_comPos, m, d);
1004
+ TrapCall(mj_comVel, m, d);
1005
+ TrapCall(mj_sensorPos, m, d);
1006
+ TrapCall(mj_sensorVel, m, d);
955
1007
  for (int j = 0; j < static_cast<int>(ctx->sensor_ranges->size()); j += 2) {
956
1008
  CopySensorRange(*ctx->sensor, d, i, (*ctx->sensor_ranges)[j],
957
1009
  (*ctx->sensor_ranges)[j + 1] - (*ctx->sensor_ranges)[j]);
@@ -963,18 +1015,18 @@ class Batch {
963
1015
  // derived fields into the bound views; the outputs are the
964
1016
  // caller-allocated rows.
965
1017
  case Op::JacSite:
966
- mj_kinematics(m, d);
967
- mj_comPos(m, d);
968
- mj_jacSite(m, d, ctx->jacp, ctx->jacr, ctx->site);
1018
+ TrapCall(mj_kinematics, m, d);
1019
+ TrapCall(mj_comPos, m, d);
1020
+ TrapCall(mj_jacSite, m, d, ctx->jacp, ctx->jacr, ctx->site);
969
1021
  return;
970
1022
  case Op::SampleHfield:
971
- mj_kinematics(m, d);
1023
+ TrapCall(mj_kinematics, m, d);
972
1024
  SampleHfield(m, d, *ctx);
973
1025
  return;
974
1026
  case Op::SetConst:
975
1027
  break;
976
1028
  }
977
- mj_getState(m, d, State(i), mjSTATE_INTEGRATION);
1029
+ TrapCall(mj_getState, m, d, State(i), mjSTATE_INTEGRATION);
978
1030
  std::memcpy(Warning(i), d->warning, sizeof(d->warning));
979
1031
  for (auto& s : bound_) CopyOut(*s, d, i);
980
1032
  }
@@ -1007,22 +1059,22 @@ class Batch {
1007
1059
  return out;
1008
1060
  }
1009
1061
 
1010
- void Guarded(int t, int i, Op op, int arg, mjtNum* hist, const QueryCtx* ctx,
1062
+ // TrapCall throws only after its short longjmp has returned to C++, so the
1063
+ // exception can unwind RunSim normally instead of crossing MuJoCo C frames.
1064
+ bool Guarded(int t, int i, Op op, int arg, mjtNum* hist, const QueryCtx* ctx,
1011
1065
  const CallbackCtx* cctx) {
1012
- std::jmp_buf jb;
1013
- tls_jmp = &jb;
1014
- if (setjmp(jb) == 0) {
1066
+ try {
1015
1067
  RunSim(t, i, op, arg, hist, ctx, cctx);
1016
- } else {
1068
+ } catch (const MjError&) {
1017
1069
  // The sim's state was not written back; the worker's mjData, left
1018
1070
  // mid-call with its stack and arena in use, serves other sims next.
1019
- tls_jmp = nullptr;
1020
1071
  if (op == Op::SetConst) Restore(models_[t]);
1021
1072
  mj_resetData(template_, data_[t]);
1022
1073
  std::lock_guard<std::mutex> lock(changed_mu_);
1023
1074
  if (error_.empty()) error_ = "sim " + std::to_string(i) + ": " + tls_error;
1075
+ return false;
1024
1076
  }
1025
- tls_jmp = nullptr;
1077
+ return true;
1026
1078
  }
1027
1079
 
1028
1080
  void Run(Op op, std::optional<std::vector<int>> sel, int arg, mjtNum* hist = nullptr,
@@ -1031,7 +1083,9 @@ class Batch {
1031
1083
  std::lock_guard<std::mutex> lock(mu_);
1032
1084
  error_.clear();
1033
1085
  RunLocked(op, sel, arg, hist, ctx);
1034
- if (!error_.empty()) throw std::runtime_error(error_);
1086
+ if (!error_.empty()) {
1087
+ throw std::runtime_error(error_);
1088
+ }
1035
1089
  }
1036
1090
 
1037
1091
  // A per-sim enableflags must not switch on what the constructor refused. Raised
@@ -1086,8 +1140,10 @@ class Batch {
1086
1140
  if (row_ctx.out) row_ctx.out += static_cast<size_t>(j) * row_ctx.npoint;
1087
1141
  c = &row_ctx;
1088
1142
  }
1089
- Guarded(t, p ? p[j] : j, op, arg,
1090
- hist ? hist + static_cast<size_t>(j) * arg * nstate_ : nullptr, c, nullptr);
1143
+ if (!Guarded(t, p ? p[j] : j, op, arg,
1144
+ hist ? hist + static_cast<size_t>(j) * arg * nstate_ : nullptr, c, nullptr)) {
1145
+ return;
1146
+ }
1091
1147
  };
1092
1148
  if (pool_->size() == 1) {
1093
1149
  for (int j = 0; j < n; ++j) fn(0, j);
@@ -1112,7 +1168,7 @@ class Batch {
1112
1168
  CallbackCtx row = base;
1113
1169
  if (hist) row.hist = hist + static_cast<size_t>(j) * nstep * nstate_;
1114
1170
  row.done = done + j;
1115
- Guarded(t, p ? p[j] : j, op, k, nullptr, nullptr, &row);
1171
+ if (!Guarded(t, p ? p[j] : j, op, k, nullptr, nullptr, &row)) return;
1116
1172
  };
1117
1173
  if (pool_->size() == 1) {
1118
1174
  for (int j = 0; j < n; ++j) fn(0, j);
@@ -13,7 +13,6 @@ using namespace nb::literals;
13
13
  NB_MODULE(_bindings, m) {
14
14
  // Bound arrays keep their Batch alive by design, often until exit.
15
15
  nb::set_leak_warnings(false);
16
- InstallLogTrap();
17
16
  if (mj_version() != mjVERSION_HEADER) {
18
17
  throw std::runtime_error("mjbatch was built against MuJoCo " +
19
18
  std::to_string(mjVERSION_HEADER) + " but " +
@@ -60,8 +59,9 @@ changed, so derived constants are per simulation too; mjModel scalars it writes
60
59
  Derived constants follow expanded inputs only after set_const, as with
61
60
  mj_setConst on one model. A MuJoCo error on a worker raises RuntimeError naming
62
61
  the first failing simulation; the others still ran, and the failing one keeps the
63
- state it had before the call, its writes still pending. The trap is a MuJoCo log
64
- handler installed at import; installing another handler later disables it.)")
62
+ state it had before the call, its writes still pending. Errors are trapped with a
63
+ thread-local MuJoCo handler scoped to each worker call, so process-global handlers
64
+ remain available to the application.)")
65
65
  .def(nb::init<nb::object, int, int, bool, std::optional<std::vector<int>>>(), "model"_a,
66
66
  "num_sims"_a, "num_threads"_a = 0, "forward"_a = false, "cpu_ids"_a = nb::none(),
67
67
  "num_threads=0 uses every logical CPU, clamped to num_sims. forward=True ends "
@@ -52,7 +52,18 @@ _SHARED_PARAMETER_PREFIXES = (
52
52
  "qpos0",
53
53
  "qpos_spring",
54
54
  )
55
- _IGNORED_COMPILER_FLAGS = frozenset({"body_sameframe", "geom_sameframe"})
55
+ # Compiler-derived fields, not structure: ``body_simple``/``dof_simplenum``
56
+ # are fast-path flags/counts the compiler derives from each variant's own
57
+ # inertial frames, and ``light_poscom0`` is derived from the model's center of
58
+ # mass. They legitimately differ across same-layout variants whose allowed
59
+ # per-variant fields (``body_mass``/``body_ipos``/``body_iquat``/
60
+ # ``body_inertia``, geom pose/size) already carry the underlying physics, and
61
+ # none of them changes the dynamics computed with the canonical model's
62
+ # flags. Treating them as shared skeleton parameters falsely rejects
63
+ # mass-varying pools (unilabsim/mjbatch_uni#33).
64
+ _IGNORED_COMPILER_FLAGS = frozenset(
65
+ {"body_sameframe", "geom_sameframe", "body_simple", "dof_simplenum", "light_poscom0"}
66
+ )
56
67
  _IGNORED_COMPILER_METADATA_PREFIXES = ("body_geom", "body_bvh", "geom_bvh")
57
68
 
58
69
  _LAYOUT_SCALARS = (
@@ -142,6 +153,7 @@ class VariantPack:
142
153
  mesh_names[mesh.name] = pooled_name
143
154
  mesh_names_by_variant.append(mesh_names)
144
155
 
156
+ _disable_simple_where_variants_break_inertial_frame(canonical_spec, reference_models, canonical_index)
145
157
  canonical = canonical_spec.compile()
146
158
  _validate_layout(reference_models, canonical)
147
159
  geom_maps = _validate_names_and_build_geom_maps(reference_models, canonical)
@@ -349,6 +361,44 @@ def _validate_shared_parameters(
349
361
  raise ValueError(f"variant {variant} changes shared field {name}")
350
362
 
351
363
 
364
+ def _disable_simple_where_variants_break_inertial_frame(
365
+ canonical_spec: mujoco.MjSpec,
366
+ references: Sequence[mujoco.MjModel],
367
+ canonical_index: int,
368
+ ) -> None:
369
+ """Force the general (non-simple) code path where variant inertia requires it.
370
+
371
+ The compiler marks a body ``simple`` when its inertial frame coincides with
372
+ the body frame (zero ``ipos``, identity ``iquat``), and the batch executor
373
+ refuses per-variant inertial writes that break that invariant on a simple
374
+ canonical body ("compiled as simple but sameframe no longer holds").
375
+ Variant pools legitimately differ in exactly those allowed variant fields,
376
+ so the canonical model must not carry the fast-path flag on such bodies.
377
+ ``simple=False`` is a codegen hint only; the compiled dynamics are
378
+ numerically identical.
379
+ """
380
+ canonical = references[canonical_index]
381
+ # MjSpec.bodies is the flattened depth-first list, aligned with the compiled
382
+ # model's body ids (world first in both).
383
+ spec_bodies = list(canonical_spec.bodies)[1:]
384
+ if len(spec_bodies) != canonical.nbody - 1:
385
+ raise ValueError(
386
+ f"canonical spec has {len(spec_bodies)} bodies but its compiled model has "
387
+ f"{canonical.nbody - 1}; cannot map the simple flags"
388
+ )
389
+ zero = np.zeros(3)
390
+ identity = np.array([1.0, 0.0, 0.0, 0.0])
391
+ for spec_body, body_id in zip(spec_bodies, range(1, canonical.nbody), strict=True):
392
+ if not canonical.body_simple[body_id]:
393
+ continue
394
+ for reference in references:
395
+ if not np.array_equal(reference.body_ipos[body_id], zero) or not np.array_equal(
396
+ reference.body_iquat[body_id], identity
397
+ ):
398
+ spec_body.simple = False
399
+ break
400
+
401
+
352
402
  def _validate_shared_options(
353
403
  references: Sequence[mujoco.MjModel],
354
404
  canonical: mujoco.MjModel,
@@ -1,43 +0,0 @@
1
- cmake_minimum_required(VERSION 3.15...3.30)
2
- project(${SKBUILD_PROJECT_NAME} LANGUAGES CXX)
3
-
4
- find_package(Python 3.10 COMPONENTS Interpreter Development.Module REQUIRED)
5
-
6
- execute_process(
7
- COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
8
- OUTPUT_STRIP_TRAILING_WHITESPACE
9
- OUTPUT_VARIABLE nanobind_ROOT)
10
- find_package(nanobind CONFIG REQUIRED)
11
-
12
- # Headers and libmujoco come from the installed mujoco wheel.
13
- execute_process(
14
- COMMAND "${Python_EXECUTABLE}" -c
15
- "import mujoco, pathlib; print(pathlib.Path(mujoco.__file__).parent)"
16
- OUTPUT_STRIP_TRAILING_WHITESPACE
17
- OUTPUT_VARIABLE MUJOCO_PKG_DIR
18
- COMMAND_ERROR_IS_FATAL ANY)
19
- file(GLOB MUJOCO_LIBRARY "${MUJOCO_PKG_DIR}/libmujoco*${CMAKE_SHARED_LIBRARY_SUFFIX}*")
20
- if(NOT MUJOCO_LIBRARY)
21
- message(FATAL_ERROR "Could not find libmujoco in ${MUJOCO_PKG_DIR}")
22
- endif()
23
- list(GET MUJOCO_LIBRARY 0 MUJOCO_LIBRARY)
24
-
25
- nanobind_add_module(_bindings FREE_THREADED NOMINSIZE src/mjbatch/csrc/bindings.cpp)
26
- target_include_directories(_bindings PRIVATE "${MUJOCO_PKG_DIR}/include")
27
- target_link_libraries(_bindings PRIVATE "${MUJOCO_LIBRARY}")
28
-
29
- # Find libmujoco next to the installed extension, <site-packages>/mujoco. The
30
- # macOS wheel's install name is a framework path that does not exist, so point
31
- # our load command at the plain file name instead.
32
- if(APPLE)
33
- get_filename_component(MUJOCO_LIB_NAME "${MUJOCO_LIBRARY}" NAME)
34
- execute_process(COMMAND otool -D "${MUJOCO_LIBRARY}" OUTPUT_VARIABLE _otool)
35
- string(REGEX MATCH "@rpath[^\n]*" MUJOCO_INSTALL_NAME "${_otool}")
36
- add_custom_command(TARGET _bindings POST_BUILD COMMAND install_name_tool -change
37
- "${MUJOCO_INSTALL_NAME}" "@rpath/${MUJOCO_LIB_NAME}" $<TARGET_FILE:_bindings>)
38
- set_target_properties(_bindings PROPERTIES INSTALL_RPATH "@loader_path/../mujoco")
39
- else()
40
- set_target_properties(_bindings PROPERTIES INSTALL_RPATH "$ORIGIN/../mujoco")
41
- endif()
42
-
43
- install(TARGETS _bindings DESTINATION mjbatch)
File without changes
File without changes