Genesis
AGENTS.md30k starsChanged 4 months agoApache-2.0View on GitHub
1 other project uses a version of this.
Trending
Less talk lately.about the whole repository
Most recently taken up by
- Genesis-Embodied-AI/genesis-worldword for word, first seen Nov 16, 2026
Who's talking about Genesis-Embodied-AI/Genesis
- Wes Roth“Genesis Project Just UNLEASHED Legions of Robots from SIMULATION to REALITY...”YouTube · Dec 19, 2024 · 118k views
- Daniel Pikl“Genesis project | DANIEL PIKL”YouTube · Dec 19, 2024 · 26k views
- Nerding I/O with Jd Fiscus“Set Up Genesis Locally: Power Your Robotics and AI Simulations”YouTube · Dec 26, 2024 · 18k views
- Sukhad Anand“Genesis is here.....”YouTube · Jan 10, 2025 · 17k views
- Champion Edtech“Genesis: The AI Physics Simulator That Changes Everything | 43 Million FPS on a Single GPU”YouTube · Dec 23, 2024 · 3.6k views
The biggest 5 of 80 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 80
Talked about on GitHub, YouTube, Bluesky, Hacker News and the web (80 times).
On GitHub · 39
- Dec 19, 2024[feature] Integration with ROS framework. — Genesis-Embodied-AI/genesis-world24 reactions · 16 comments
- Dec 31, 2024Visualizer does not work on macOS — Genesis-Embodied-AI/genesis-world6 reactions · 6 comments
- Dec 19, 2024Nothing happens/ no GUI launched after running demo on M-series Mac — Genesis-Embodied-AI/genesis-world6 reactions · 10 comments
- Jun 25, 2025[FEATURE] Batched path plan — Genesis-Embodied-AI/genesis-world5 reactions · 5 comments
- Dec 3, 2025[FEATURE] Add support of USD import for Rigid Body. — Genesis-Embodied-AI/genesis-world4 reactions · 15 comments
34 more on GitHub
- Jul 25, 2025[FEATURE] Add Reinforcement Learning Environment for Manipulation — Genesis-Embodied-AI/genesis-world4 reactions · 2 comments
- Jul 25, 2025[FEATURE] Enhance SAP coupler for coupling between Rigid body and Fem object. — Genesis-Embodied-AI/genesis-world4 reactions · 3 comments
- May 17, 2025[Bug]: 'too many values to unpack' error due to breaking changes of libigl from 2.6.0 — Genesis-Embodied-AI/genesis-world4 reactions · 15 comments
- Jan 7, 2026[FEATURE] Add batched simulation of heterogeneous objects. — Genesis-Embodied-AI/genesis-world3 reactions · 11 comments
- Sep 17, 2025[FEATURE] Add Raycaster, Lidar, DepthCamera and sensor.draw_debug methods. — Genesis-Embodied-AI/genesis-world3 reactions
- Feb 5, 2025SplashSurf on TaiChi — InteractiveComputerGraphics/splashsurf3 reactions
- Jan 14, 2025[BUG FIX][FEATURE] Rework backend & device selection logic — Genesis-Embodied-AI/genesis-world3 reactions · 3 comments
- Mar 31, 2026[FEATURE] add ComFree solver — Genesis-Embodied-AI/genesis-world2 reactions · 1 comment
- Mar 16, 2026[BUG FIX] Fix batched env separated rendering with Rasterizer and add support of MacOS. — Genesis-Embodied-AI/genesis-world2 reactions
- Feb 26, 2026[BUG FIX] Fix merge fixed links (cont'd). — Genesis-Embodied-AI/genesis-world2 reactions
- Jan 30, 2026[FEATURE] #2332 Implement Local Offset in Inverse Kinematics — Genesis-Embodied-AI/genesis-world2 reactions
- Dec 22, 2025[Feature] Support Fisheye BatchCamera. — Genesis-Embodied-AI/genesis-world2 reactions
- Dec 5, 2025[FEATURE] WIP: Make rigid body simulation fully differentiable — Genesis-Embodied-AI/genesis-world2 reactions · 1 comment
- Nov 19, 2025[FEATURE] Leverage GsTaichi zero-copy in data accessors. — Genesis-Embodied-AI/genesis-world2 reactions · 3 comments
- Nov 19, 2025[FEATURE] Add rasterizer, batch renderer, and raytracer as sensor — Genesis-Embodied-AI/genesis-world2 reactions · 4 comments
- Nov 2, 2025[MISC] Add 'parse_glb_with_zup' option to all file-based Morph. — Genesis-Embodied-AI/genesis-world2 reactions · 3 comments
- Sep 10, 2025[FEATURE] Differentiable contact detection, Part 1 — Genesis-Embodied-AI/genesis-world2 reactions · 3 comments
- Sep 5, 2025[BUG FIX] Fix entity idx to be always int when loading terrain with batch_links_info. — Genesis-Embodied-AI/genesis-world2 reactions · 1 comment
- Aug 12, 2025[BUG FIX] Fix backend fallback mechanism causing deadlock in Rasterizer. — Genesis-Embodied-AI/genesis-world2 reactions
- Nov 10, 2026[MISC] Add guidelines for agents in production workflow. — Genesis-Embodied-AI/genesis-world1 reaction · 2 comments
- Sep 15, 2026Yiling/260903 merge qipc — Genesis-Embodied-AI/genesis-world1 reaction · 1 comment
- Sep 3, 2026[MISC] Add non-batched anymal_random cpu benchmark. — Genesis-Embodied-AI/genesis-worldsays it tested it1 reaction · 2 comments
- Aug 12, 2026[MISC] Add DeepWiki badge to README — Genesis-Embodied-AI/genesis-world1 reaction · 1 comment
- Apr 7, 2026[Feature]: Tactile sensors based on object point cloud — Genesis-Embodied-AI/genesis-world1 reaction
- Jan 20, 2026[Bug]: Scenes with more than 2 raytracers return no data for the sensors — Genesis-Embodied-AI/genesis-world1 reaction · 2 comments
- Dec 2, 2025[Bug]: LuisaRender build failure with newer CMake (PyTorch 2.8+ Docker image) — Genesis-Embodied-AI/genesis-world1 reaction
- Sep 11, 2025[Bug]: A small typo in the drone example — Genesis-Embodied-AI/genesis-world1 reaction
- Sep 3, 2025[Bug]: A typo in the drone example — Genesis-Embodied-AI/genesis-world1 reaction
- Aug 18, 2025[MISC] Depth camera scaling issue — Genesis-Embodied-AI/genesis-world1 reaction · 4 comments
- Jul 13, 2025Upgrade taichi to support LLVM20 — Genesis-Embodied-AI/quadrants1 reaction · 8 comments
- Jun 23, 2025[Feature]: FEM Vertex Constraints — Genesis-Embodied-AI/genesis-world1 reaction
- Apr 18, 2025[Bug]: difference between control_dofs_position and set_dofs_position — Genesis-Embodied-AI/genesis-world1 reaction · 4 comments
- Jan 14, 2025[FEATURE] Add Pytorch 2.5+ Intel XPU support — Genesis-Embodied-AI/genesis-world1 reaction
- Jan 2, 2025CUDA Error CUDA_ERROR_NOT_SUPPORTED: operation not supported while calling malloc_async_impl (cuMemAllocAsync) — Genesis-Embodied-AI/genesis-world1 reaction · 1 comment
On YouTube · 21
- Dec 19, 2024Genesis Project Just UNLEASHED Legions of Robots from SIMULATION to REALITY... — Wes Roth118k views · 561 comments
- Dec 19, 2024Genesis project | DANIEL PIKL — Daniel Pikl26k views · 49 comments
- Dec 26, 2024Set Up Genesis Locally: Power Your Robotics and AI Simulations — Nerding I/O with Jd Fiscus18k views · 36 comments
- Jan 10, 2025Genesis is here..... — Sukhad Anand17k views · 6 comments
- Dec 23, 2024Genesis: The AI Physics Simulator That Changes Everything | 43 Million FPS on a Single GPU — Champion Edtech3.6k views · 1 comment
16 more on YouTube
- Dec 23, 2024Genesis: The AI Physics Simulator That Changes Everything | 43 Million FPS on a Single GPU — Champion Edtech2k views
- Dec 19, 2024🚀 Genesis: A Revolutionary Open-Source Physics AI Engine 🌌 — Developer Arvind1.7k views · 17 comments
- Dec 23, 2024The Game-Changing Physics Engine for AI and Robotics — ChiefAIOfficer949 views
- Dec 23, 2024What If You Could Create Fully Interactive 4D Worlds in Minutes? #aitools — Tip Voyage459 views · 1 comment
- Dec 19, 2024"Genesis: The Future of Robotics & AI Simulation — 430,000x Faster Than Real-Time!" #ai — Insider Entiretysays it tested it363 views · 1 comment
- Dec 21, 2024GitHub - Genesis-Embodied-AI/Genesis: A generative world for general-purpose robotics & embodied ... — GitHub Daily Trend AI Podcast308 views
- Jan 5, 2025first setup and most basic example demo with genesis for robotics world simulation — Kevin Huang306 views
- Dec 22, 2024AI人工智能革命性的物理引擎和仿真平台-------Genesis — AI探索198 views
- Dec 19, 2024Genesis Go2 backflip — Kyoung Choe188 views
- Dec 21, 2024Genesis-Embodied-AI/Genesis - Gource visualisation — Gourcer164 views · 1 comment
- Dec 21, 2024#opensource physics engine for #ai and #robotics — gAI ventures144 views
- Dec 31, 2024World Model Open source Genesis project — WonLabAI132 views
- Jan 11, 2026Mirror Worlds v5.0.1 - [Short Digital Horror Film] — historia abreviada de la tecnología portatil101 views
- Dec 21, 2024Genesis – CMU 联合 20 多所研究机构开源的生成式物理引擎 #shorts #科技#人工智能 #模型 — 寰宇智潮42 views · 1 comment
- Dec 19, 2024AI News 19 Dec 2024 — AI Daily News Digest41 views
- May 19, 2025ロボティクス向け物理エンジン「Genesis」 — こち亀大好き32 views
On Bluesky · 15
- Dec 20, 2024Genesis: startling fast Python multiple physics cross-platform engine. Currently open source project — but looks like the key… — @craigreynolds.bsky.social18 likes and reposts · 2 replies
- Dec 18, 2024Open Source Code: github.com/Genesis-Embo... Project webpage: genesis-embodied-ai.github.io Documentation: genesis-world.readthedocs.io — @sungkim.bsky.social12 likes and reposts · 1 reply
- Dec 19, 2024The next isaac sim/lab? github.com/Genesis-Embo... — @giulioturrisi.bsky.social9 likes and reposts · 1 reply
- Dec 19, 2024Genesis, an (amazing) open source generative physic engine able to generate 4D worlds github.com/Genesis-Embo... #gamedev #gamedevelopment… — @fronkongames.bsky.social8 likes and reposts
- Dec 21, 2024Genesis (not the band) is a "looks good but what's the point & who's the audience exactly" kind of library. if the "LLM to 4D world"… — @nicoptere.bsky.social7 likes and reposts · 1 reply
10 more on Bluesky
- Dec 21, 2024Genesis has a lot going for it: delightful dev experience, clean implementation, many useful features and solid performance. And yet, the… — @cstathis.bsky.social3 likes and reposts
- Dec 22, 2024今日のGitHubトレンド Genesis-Embodied-AI/Genesis このリポジトリは、汎用的なロボティクス、具現化AI、物理AIアプリケーション向けの物理プラットフォーム「Genesis」を開発しています。… — @dailygithubtrends.bsky.social2 likes and reposts
- Dec 19, 2024Fully open sourced Apache 2.0 licensed physics engine is brawndo (it's got what robots crave) github.com/Genesis-Embo... — @markcollier.me2 likes and reposts
- Dec 19, 2024Open Source Platform: The Genesis physics engine and simulation platform have been fully open-sourced and can be accessed via GitHub, with… — @luok.ai2 likes and reposts · 1 reply
- Dec 18, 2024🔥DON’T MISS IT! GENESIS is here! 🔥Genesis is a highly efficient, user-friendly, and versatile simulation platform with comprehensive… — @frankzydou.bsky.social2 likes and reposts · 1 reply
- Jan 26, 2025Genesis-Embodied-AI / Genesis A generative world for general-purpose robotics & embodied AI learning.… — @pythonhub.dev1 likes and repost
- Dec 22, 2024github.com/Genesis-Embo... — @ivorscott.com1 likes and repost
- Dec 20, 20247/ The Future is Embodied Genesis paves the way for realistic, intelligent agents that could reshape industries—from robotics and gaming to… — @matthew-berman.bsky.social1 likes and repost
- Dec 20, 2024github.com/Genesis-Embo... — @tomyear.bsky.social1 likes and repost
- Dec 20, 2024💎 Hidden Gem! 💎 (1000+ new stars) 📦 Genesis-Embodied-AI / Genesis ⭐ 13,470 (+7,187) 🗒 Python A generative world for general-purpose… — @github-trending.bsky.social1 likes and repost
On Hacker News · 4
- Dec 21, 2024Genesis – Generative world for general-purpose robotics and embodied AI learning3 points
- Dec 19, 2024Genesis3 points
- Dec 20, 2024Genesis, the AI enabled physics platform2 points
- Dec 19, 2024A generative world for general-purpose robotics and embodied AI learning2 points
On the web · 1
- Dec 27, 2024A generative world for general-purpose robotics &... — forums.unrealengine.com
Other versions1 project uses a version of this.
Word for word · 1
- Genesis-Embodied-AI/genesis-world★ 30k100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,266 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repositoryOne other file it gives its agents.
- CLAUDE.mdCLAUDE.md
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
30 rules. About 0 are common, 17 are distinctive, and 13 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈17
Distinctive · estimate
This author's own choices. Worth a look.
13
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 6
Never add attributes on the fly to external / non-owned instances.
- Distinctive: line 8
Keep interop data as torch tensors or numpy arrays from the start instead of Quadrants kernels operating on CPU numpy arrays.
- Distinctive: line 10
Never reallocate a quadrants data structure.
- Distinctive: line 15
No commented-out prints. Convert them to logging debug traces.
- Distinctive: line 19
Never add a cast (float() / int() / .astype() / np.asarray() / dtype=) unless strictly necessary.
- Very specific: line 20
Use the helpers defined in genesis/utils/misc.py and genesis/utils/geom.py.
- Distinctive: line 29
Every NaN or inf, in the forward or the backward pass, is reported through the existing errno mechanism (define a new error code if …
- Distinctive: line 30
Remove all legacy code. No deprecation / legacy compatibility layers.
- Distinctive: line 32
Prefer the dev getters/setters API of solvers over directly accessing quadrants fields.
- Distinctive: line 36
Avoid generic 'all_' prefix/suffix for containers if possible but rather be specific, eg 'joints_xanchor', 'links_inertia_i', 'geoms_pos', …
- Distinctive: line 37
Avoid pure variable name assignment, eg 'mass_mat_env = mass_mat_all'.
- Distinctive: line 38
Prefer clear over fresh allocation for mutable containers, eg 'self.abd_data_by_link.clear()' instead of 'self.abd_data_by_link = {}'.
- Very specific: line 39
Never use flatten(), reshape((-1,)), or ravel() in place of squashing.
- Distinctive: line 40
Don't use np.asarray unless strictly necessary, ie for public API with no control on the data source.
- Very specific: line 44
Code quality over source consistency: When refactoring or porting code from PRs, external projects, or prior implementations, Genesis …
- Very specific: line 52
Runtime: Use qd_to_numpy / qd_to_torch (from genesis.utils.misc) for bulk GPU-CPU transfer.
- Very specific: line 54
Hoist conversions before loops: Call qd_to_numpy / qd_to_torch once, then index the local array.
- Very specific: line 59
Metal stream sync is the caller's job: after a batch of torch zero-copy writes, call torch.mps.synchronize() once before the next quadrants …
- Very specific: line 65
Never use
np.asarrayon torch tensors: Use tensor_to_array from genesis.utils.misc instead, which properly handles GPU->CPU transfer via … - Distinctive: line 113
No semicolon in prose, and no dash as a parenthesis: Write two sentences, or use parentheses.
- Distinctive: line 116
Never document a contract the code does not offer: No array shape and no memory layout in a docstring unless the API guarantees it.
- Distinctive: line 118
Never write to a third-party object's private state: Keep our own record beside the object and expose it through a property.
- Very specific: line 129
No import aliasing (Cloth not ClothMaterial).
- Very specific: line 130
No temporary variables for isinstance checks.
- Very specific: line 144
No redundant or circular comments: Do not restate what names/types/control-flow already convey, and never write tautologies ("dt is the …
- Distinctive: line 153
Bug fix PRs: must include a regression test that fails on main and passes with the fix, added to the test already covering the capability …
- Distinctive: line 157
No deprecation tests: Do not add unit tests that verify deprecation warnings are emitted.
- Very specific: line 165
Non-regression fallback: If no analytical expectation is available, run the simulation once to get reference values, hardcode them, and …
- Very specific: line 240
Run with the same flags as macOS CI: PYTHONPATH=<dir-with-force_sw.py> PYOPENGL_PLATFORM=pyglet GS_TORCH_FORCE_CPU_DEVICE=1 pytest -p …
- Very specific: line 241
Verify it took effect: Genesis logs "Software rendering context detected" and scene.visualizer.is_software is True.
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Genesis Development Guidelines
Miscellaneous
- getattr / hasattr are prohibited. Use None initialization and isinstance checks instead. The one exception is code whose consumers are unknown by design: serialization, generic reflection over the fields of a dataclass, static analysis of source code. Anywhere else, use isinstance.
- Never add attributes on the fly to external / non-owned instances.
object.__setattr__is prohibited outside the constructor of the object it writes. A frozen object changes through a fork (dataclasses.replace,model_copy), never in place.- Keep interop data as torch tensors or numpy arrays from the start instead of Quadrants kernels operating on CPU numpy arrays. Numpy implementations must be fully vectorized. Use Numba (single thread, CPU backend) for computation-heavy "kernels".
- Allocate the exact memory size needed. Preallocation based on max size is prohibited.
- Never reallocate a quadrants data structure. Size it once, when everything that determines its size is known.
- An array never stores a quantity it is not meant to store, however idle it looks. Storing the same quantity in another context is allowed: the inverse weights are computed in the
gradandMgradof the constraint solver, a cost gradient and its mass-matrix solve. The single exception isnt_H, bound to the tiled mass-matrix scratch through_bindsin the struct constructor, never by passing the arrays of another component to a kernel. - Plain dicts for packing attributes are prohibited. Use strongly typed named data structures instead, either dataclasses or simple NamedTuples. The one exception is the parsed info a rigid asset parser produces, a plain dict confined to the parser and the resolution that consumes it. No built object holds one.
- A named structure exists so that the meaning of each element cannot get lost. A plain tuple is fine wherever that meaning stays in sight: a multi-value return that every caller unpacks into named locals at the call, whichever module the helper lives in, or a small container filled and unpacked a few lines apart. Use a NamedTuple or a dataclass once the value travels far enough for its meaning to get lost: shared by several modules, carried through a stateful algorithm, indexed by position, or returned by public API.
- Local imports in functions are prohibited, unless strictly necessary to avoid circular dependencies.
- No commented-out prints. Convert them to logging debug traces.
- No code duplication.
- Variable naming follows the Rigid engine conventions. See also the description of PR#1053 (https://github.com/Genesis-Embodied-AI/Genesis/pull/1053).
- Domain objects are only 'entity', 'link', or 'geom'. Never invent a new noun ('body', 'object', 'piece') when one of these fits. This is also a correctness cue: the rigid-body unit is the link, so group geoms per link (iterate entity.links then link.geoms), not per entity.
- Never add a cast (float() / int() / .astype() / np.asarray() / dtype=) unless strictly necessary. Cast only where an external interface forces the dtype (igl float64/int64, native Python for kernel args), and never re-cast what a later step already casts.
- Use the helpers defined in genesis/utils/misc.py and genesis/utils/geom.py. 'detach().cpu().numpy()' is prohibited. Use 'tensor_to_array'.
- Calling the Quadrants data instance method 'to_numpy()' is forbidden. Use 'qd_to_(torch|numpy)' instead. Take advantage of torch-based zero-copy as much as possible to update the internal state of other solvers. numpy-based zero-copy is only supported on CPU backend, so prefer torch.
- Catch-all exceptions are prohibited, except for exception forwarding in a multi-processing process, and for code paths we do not control that must never crash (a destructor, a fallback around an external library such as loading a mesh without its textures). An exception is raised on what a user can hand in. A condition internal to the code flow, which no public API exposes, is an
assert. Critical errors must never be replaced by warnings: if something breaks the physics, raise an exception, eventually via re-raise to clarify the error message. - Direct use of numpy / torch / quadrants data types is prohibited, unless strictly necessary due to external interfaces enforcing specific dtypes. Our types are defined in genesis/init.py, and the quadrants data structs of each component, with their dtypes, are declared in its own module.
- A Genesis dtype (
gs.tc_bool,gs.tc_int,gs.np_float...) is the storage type of the simulation, which varies with the backend and the precision (gs.tc_boolis an integer on Metal). Code that relies on a specific dtype names it explicitly:torch.boolfor a mask that indexes or selects,torch.int32for an int32, as for any other one. - Defining local-scope functions should be avoided unless very well motivated, such as a callback built once at init or build time (see the API surface rule below).
- Recursion only when its depth is guaranteed to be bounded and it needs neither a new private helper nor extra arguments tracking the context (path prefixes, inherited values). Otherwise walk the tree with an explicit stack of pending items (see 'iter_data' in genesis/utils/data.py).
- Attribute-like instance methods (eg has_any_rigid_coupling) should be converted to properties.
- scene.sim.coupler is private API, and users cannot be expected to call 'set_link_ipc_collision'. Expose such controls as entity-level material options.
- Every NaN or inf, in the forward or the backward pass, is reported through the existing errno mechanism (define a new error code if necessary): never an exception raised by hand, and never a warning.
- Remove all legacy code. No deprecation / legacy compatibility layers.
- Remove unused helpers (eg has_coupling_type). Do not implement private helpers proactively if they would be easy to add later on. This applies to internal code: an interface for users or for external extensions (sensor and solver plugins, renderer plugins) is complete when introduced, even where nothing in Genesis reads part of it.
- Prefer the dev getters/setters API of solvers over directly accessing quadrants fields.
- A quantity derived from several raw solver fields belongs in a single vectorized solver getter, not assembled by the consumer nor extracted via a bespoke per-element
@qd.kernelthat the caller then re-indexes. - Batching based on batched / non-batched should be avoided. Deal with it at argument-level 'envs_idx=env_idx if batched else None'.
- Do not call getters/setters repeatedly per env idx. Deal with all envs at once, even if a for-loop fallback is necessary for IPC-related getters/setters. Calling 'qd_to_numpy' in a tight loop is not acceptable: call it once, and when a subset is needed, pass the slice as an input argument of 'qd_to_numpy' instead of slicing afterward.
- Avoid generic 'all_' prefix/suffix for containers if possible but rather be specific, eg 'joints_xanchor', 'links_inertia_i', 'geoms_pos', 'entities_quat', 'verts_idx'.
- Avoid pure variable name assignment, eg 'mass_mat_env = mass_mat_all'.
- Prefer clear over fresh allocation for mutable containers, eg 'self.abd_data_by_link.clear()' instead of 'self.abd_data_by_link = {}'.
- Never use
flatten(),reshape((-1,)), orravel()in place of squashing. Moreover, prefer[..., 0, :]oversquash(axis=-2). - Don't use np.asarray unless strictly necessary, ie for public API with no control on the data source. Never in internal or private code paths.
Priorities
- Code quality over source consistency. When refactoring or porting code from PRs, external projects, or prior implementations, Genesis conventions always take priority over the original code's patterns. Use the original logic as reference, not the implementation style.
- Build/init time: maintainability first (as long as performance is reasonable). Use public APIs.
- Runtime hot paths: efficiency first. Minimize GPU-CPU transfers, use bulk operations.
- The backend never changes the physics. It only selects the device that runs the code. Every code path a backend takes (the CPU monolithic narrowphase, the GPU split one, cooperative kernels, graphs) implements the same model and the same algorithm, so a scene simulated on CPU and on GPU differs by rounding alone. A feature, a fix or a heuristic that one backend lacks is not done, whatever its cost in compile time or runtime on the other: find a design that holds on every backend.
Data Access
- Build/init time: Iterate via entity/link/geom public API (
entity.links,link.geoms,geom.init_verts,link.get_pos(), etc.). Only fall back to low-level solver field access when efficiency, conciseness, or maintainability specifically requires it. - Runtime: Use
qd_to_numpy/qd_to_torch(fromgenesis.utils.misc) for bulk GPU-CPU transfer. Never use.to_numpy()/.to_torch()directly. Never item-access qd fields (field[i]). - Always pass
transpose=Truetoqd_to_numpy/qd_to_torchto move the batch dimension to front ([B, n, dim]), aligning with public getter conventions. This applies to engine code only, unit tests being exempt. - Hoist conversions before loops. Call
qd_to_numpy/qd_to_torchonce, then index the local array. qd_to_numpywithcopy=Falsefails on CUDA. GPU data always requires a copy to numpy.- A
qd_to_torch/qd_to_numpyview that gets written binds to a named local first (flags_t = qd_to_torch(..., copy=False)thenflags_t[mask] = ...), never mutating through an anonymous chain. Read-only use is the opposite: chain as many operations as needed inline (qd_to_torch(f).T.reshape(...).gather(...)). When the chain overflows the line, split it at a natural intermediate into named single-line statements (knots = qd_to_torch(f).T.reshape(...)thenknots_best = knots.gather(...)), never into a parenthesized multi-line chain. - A zero-copy accessor passes the selection on untouched. A setter whose write is a copy (one vector, one flag, one row per environment) goes through the view when
gs.use_zerocopyholds and returns there, the kernel path being the fallback. On the view pathScene._sanitize_envs_idxis prohibited: pass the selection toindices_to_maskas it came, without branching on its type, then the value as it came toassign_indexed_tensorfor the write. The view path still owes the caller two checks: a scalar naming no environment of the scene, and any selection at all where there are no parallel environments. Negative bounds counted from the end are a known gap ofindices_to_mask, to be closed there and never worked around one accessor at a time. - Never call
.fillon the hot path (the step and every accessor, getters and setters included), from Python or inside a kernel: it is slow and compiles one kernel per distinct value. Write the values in a small dedicated kernel instead, or in the loop of a kernel that already runs over the data, above all when the value is a constant. Build time and anything else off the hot path may use it. - Metal stream sync is the caller's job: after a batch of torch zero-copy writes, call
torch.mps.synchronize()once before the next quadrants kernel reads the buffers. Helpers performing such writes (e.g.qd_zero_grad) never sync internally. - Branch zero-copy paths on
gs.use_zerocopyalone, without try/except probing. - Do not pass
copy=at all toqd_to_torch/qd_to_numpywhen the value returned to the caller is fresh arithmetic (nothing internal aliases out). Let it zero-copy or copy only as needed. Reservecopy=Truefor when a raw field view would otherwise escape and could be mutated. - Entity getters return by value, solver getters as the caller asks. A solver getter returning what it reads takes a keyword-only
copy: bool | None = True, forwarded toqd_to_torch/qd_to_numpy: the default is a copy, andcopy=Nonea view where zero-copy allows it (advanced use: the view is never refreshed, a setter or a step changing it under the caller). A getter computing its result takes no such keyword. Entity getters always return a copy. - Store Python references at build time (entity, link objects in dicts) for runtime lookup, rather than re-deriving from solver fields every step.
- Never pass numpy scalar types (e.g.,
numpy.float64) to kernel arguments. Always cast to native Python types (float(),int()). - Never use
np.asarrayon torch tensors. Usetensor_to_arrayfromgenesis.utils.miscinstead, which properly handles GPU->CPU transfer viatensor_to_cpufirst. Pass itsdtypeargument (tensor_to_array(x, dtype=...)) rather than chaining.astype, and convert once inside the consuming function, not at each call site.
Kernels
- Every kernel is written so that quadrants' autodiff can reverse it: no
continue, nowhile, the top level of the kernel made offorloops alone. A gate is a flag set under the static condition and tested by anif, never an earlycontinue. A walk over blocks is aforover the dof range with a block-start test, a lane stride isfor i_chunk_ in range((n + BLOCK_DIM - 1) // BLOCK_DIM)withi = i_chunk_ * BLOCK_DIM + tidgated byif i < n(arangein a kernel takes one or two arguments), never awhile. A hand-written backward kernel is strongly discouraged and demands a very good motivation, such as reversing an iterative algorithm (a constraint solve, an inverse kinematics) that autodiff cannot unroll. - No augmented assignment (
+=,-=, ...) on a field in a kernel or func. An accumulation that several threads may race on is an explicitqd.atomic_add(a[i], b). One that a single thread owns is the explicita[i] = a[i] + b. - A numerical constant a kernel reads is a scalar info field, never a module global. A threshold, rate or tolerance (
INFLUENCE_MIN) is stored once at build in an info field and read as data: a global is baked into the compiled kernel, which ndarray mode and its fastcache cannot support. Compile-time structure (a block dimension or lane count used underqd.static) stays a constant, declared as an UPPERCASE local at the top of the kernel or func that uses it (TILE_DIM = qd.static(32)), never a module global: quadrants flags a module global read in a kernel, which the test suite turns into a compile error. A static config entry is reserved for a value that varies, or that derives from a machine-specific formula (GPU core count) shared across the codebase. A universal constant such as the warp size stays a local. - An index read from a field is bound to a temporary before it indexes another field (
i_r = rigid_info.links_root_rank[i_l]thenrigid_info.roots_link_end[i_r]). Nested indirect indexing (a[b[i]]) is prohibited in kernels and funcs. - The environment is the last index of every per-environment tensor, whatever its memory order. A kernel that reads the entries of an environment from neighbouring addresses (one block per environment) asks for an environment-first memory order through
env_firstorlayoutof the struct constructor (seeDatain genesis/utils/data.py), which leaves every index of every access unchanged. - Solver data is declared, never allocated by hand. A struct subclasses
Data(genesis/utils/data.py) and declares each array once withfield(dtype, shape=...)over namedSizes, the defaults of its fields as class keywords. The solver builds it once withsizes,valuesand the property tablesenv_first,layoutandunused, keyed by labels or field references. NoV(...)call and noget_*allocator for solver data. - Each kind of structured value has one tool. Pre-allocated data goes through the data management system (a
Datastruct, genesis/utils/data.py), neverqd.types.struct(...).field()or a hand-made container. A call-scoped input or output is a torch tensor on device, numpy arrays being tolerated in legacy code. A structured value passed in registers between kernels and funcs is aqd.Structwhen the interface stays internal to the implementation (the in-kernel counterpart of a NamedTuple), and aqd.types.structdeclared next to the rest of the interface when the interface reaches users or developers, even at implementation level (the data of a handler or visitor others define, e.g. the query a BVH visitor receives). Never a flat vector indexed by slot constants or per-item scratch arrays. - A per-environment state array added to a
Datastruct is appended after its existing fields, never inserted among them. This covers STATE and the per-env SCRATCH/DERIVED arrays the step reads and writes, unused placeholders included: field order sets the memory layout, and an insertion shifts the arrays after it, slowing kernels that never read it. Info fields (CONSTANT/INFO) keep their semantic grouping. - Every array has one owner. A component nests the structs it alone builds and reads. The struct of another component reaches a kernel as a separate argument. A struct used only by some scenes is opted in by each component using it (
opt_in) before its first instance is built, and is a placeholder otherwise._bindsis reserved fornt_H, never a way to share data. - A component holds one struct per kind of data. Several instances of a struct it owns (the scratch states of each pass of a narrowphase) are members of one holder, whose fields other components opt in and size by reference (
opt_in(GJKScratch.contact0, envs=...)). The component may expose the members as attributes, but never allocates them apart. - A handler owns the data it builds and reads. A polymorphic handler (a closure such as a contact handler of a coupler) is a component of its own: it holds the structs it alone builds and reads as attributes, and its parent owns the handler, never its data, reaching that data only through the funcs of the handler. Fields shared by several handlers are declared once in a base
Datastruct that each handler subclasses, appending its own fields after the inherited ones. - New code: Free function
@qd.kernel(see the@qd.data_orientedrule under Style). A kernel parameter that receives aqd.Tensoris annotatedqd.Tensor. - Kernel and func calls pass self-named arguments positionally and anonymous ones by keyword, relying on the canonical parameter order below. An anonymous argument is an inlined constant or computed expression (
scale=0.5 * dt, a trailing static flag), while a variable or a nested access (self.elements_i[i_e].mu) is named and goes positionally. Every argument after the first keyword one is keyword too. A func call that passes a struct member alongside its parent struct stays keyword-only, because quadrants' positional func-argument expansion duplicates the member. - A static config holds bounded choices alone: booleans, enums and integers from a small fixed set. An integer that can take any value (the environment count, a leaf or face count, a bit width derived from them) is runtime information: a tensor shape read in the kernel, an info tensor, or a plain integer argument, exactly as the rigid solver keys nothing on its environment count. A user-specified integer option may stay static. An integer the engine derives from the scene that must stay static, because it sizes a shared array or a register tile, snaps to a bounded set derived from the device (see get_gpu_shared_tile_sizes in genesis/utils/misc.py), never to the scene value rounded up.
- The
State/Info/Configsuffix names a high-level container, one instantiated directly and passed as aqd.kernelargument. A member struct that reaches funcs alone carries no suffix (ContactData,BVHLeaves). - Canonical parameter order, for every kernel and func: indices of any kind first (loop indices, index tensors like
envs_idx, index-valued scalars likejoint_idxor range starts/ends), then dynamic native Python scalars and fixed-size quadrants vectors (per-call values: positions, quaternions, penetrations), then the kernel/func-specific tensors, then all state structs, then all info structs, then the static configs, then the kernel/func-specific constants-in-practice (shape integers, eps, tolerances, which are info by nature even when not declared as such), and the kernel/func-specific compilation flags at the very end, first the static ones (qd.template()booleans, an integer of flag bits packing several of them right before those passed one by one), then the native booleans passed at runtime (write_L: bool), which stay dynamic.errnoalone follows them, in the last position. Within the state/info/config groups the component order is fixed (dyn, rigid, collider with mpr, gjk, support_field and sdf, then constraint), with leaf structs at their aggregate's slot in its declared field order. Call sites pass arguments in signature order. - Rigid solver is the reference implementation for kernel and code quality standards.
- Every kernel and func parameter is typed. A scalar takes its native Python type (
int,float,bool) and a fixed-size vector or matrixqd.types.vector(n)/qd.types.matrix(n, m), on top of the array, struct andqd.template()annotations. The annotation states what the parameter holds and casts it to the Genesis dtype. A parameter that takes values of several Quadrants types stays untyped: fixed-size vectors of any size, vectors and matrices alike (e.g.qd_isfinitein genesis/utils/misc.py), or the query structs a shared BVH traversal hands to its visitors. - No Genesis dtype in annotations:
gs.qd_float,gs.qd_int,gs.qd_vec3and every other dtype or type alias thatgs.initdefines never appear in an annotation or a default value. A float vector or matrix takes no dtype (qd.types.vector(3), neverqd.types.vector(3, dtype=gs.qd_float)orgs.qd_vec3), and an integer one takes the quadrants dtype (qd.types.vector(3, dtype=qd.i32)). - Pure read-write data accessors on the hot path go through zero-copy views, keeping the kernel only as fallback. For a tiny kernel that merely shuffles or rewrites a field (payload remap, flag sweep), when
gs.use_zerocopyholds, do it in place through aqd_to_torch(..., copy=False)/qd_to_numpy(..., copy=False)view, and fall back to the kernel otherwise. Reserve dedicated kernels for genuine computation. - One inlined instance of a
qd.funcper kernel. Everyqd.funca kernel calls is inlined, its static branches pruned, then compiled: calling the same helper from two runtime branches with different arguments compiles it twice, a template argument taking two values compiles the callee twice, and a heavy body underqd.static(range(R))compiles R times. Pick the arguments in runtime branches and call once, loop items at runtime with a runtime count (recompute a cheap per-item value rather than carry per-item registers), and where an early exit is needed use a single-iterationforwithbreakso one call follows (the collider's pattern), or anifgate around the body of the top-level loop in a differentiable kernel, wherebreakandcontinueare rejected. Reserve static unrolls for tiny bodies. Some readability may go, as long as the code stays plain to follow. The measured compile time of the CI benchmarks decides: below 2% it does not matter, at 8% and above it is critical, in between it is a judgment call.
API Design
- Don't force users to set options with a single correct value. If an option has only one valid value in a given context (e.g.,
enable_collision=Falseis always required with IPCCoupler), set it automatically and raise an error if the user explicitly provides the wrong value. The right pattern is: default toNone, resolve to the correct value at init time, raise on conflicting explicit value. The resolution logic can be based on other options, scene contents, or even runtime state, as long as it is well documented. - Do not wrap a few lines of straightforward logic in a helper, and never a single expression, however many callers it has: inline it, as a local where the expression needs a name. A helper earns its place by carrying logic a reader would rather not check twice, not by saving lines.
- A helper specific to its single caller is folded into it, even when that caller invokes it several times: calls differing only by their arguments become a loop over those arguments around one copy of the body. The constraints are no code duplication and code that reads plainly. A helper stays where inlining it would obscure the block: a small helper naming a gating condition (
if func_is_pair_valid(...)), or a body that would land deeply nested, its statements wrapped over several lines. A standalone generic helper is covered by the rule below. - No single user helper. Do not introduce any extra helper if it is used at one single place for one specific context. A new single-use helper is only acceptable if it is standalone and completely generic, like a math function or conversion utility. Avoid private instance methods.
- No avoidable growth of the API surface of a class, public or private alike. Inline the code wherever that duplicates nothing, and pass a callback as a local closure (capturing implicitly, or bound through
functools.partial), built once at init or build time and never on a runtime hot path. A new method or attribute is warranted when it rigorously follows an established pattern (the rasterizer context, the build stages of a solver), typically to keep long blocks of unrelated responsibilities out of one top-level function. - A standalone helper never takes the object whose internals it works on. A function reading or writing the fields of one class, or calling its methods, is a method of that class, never a standalone function taking the object as first argument. A standalone helper takes the derived data it needs (arrays, indices, values), never their owner.
- Ownership flows downward: a component never reaches up to its owner or any ancestor. A solver, a sensor, a scoped render context, an entity, a link, a geom or a description never reads or calls the scene, the simulator or a renderer above it (
._sim.scene,.scene.visualizer,entity._sim): the owner passes what it needs at construction or as an argument, and a consumer learns of a change through a subscription. A reach upward is a critical violation, sufficient grounds for rejecting the entire PR. - Infrastructure stays generic. A tool serving every solver (the differentiable-simulation bridge, the checkpoints, the caches) knows no specific solver: it works from the solver protocol and the data structures alone, and a solver plugs in through hooks of that protocol.
- Cache in a decentralized way, never in the owning class. A cache that is an optimization lives at module level next to the tool computing its values, keyed on the objects it describes and released with them through
OwnedCache(see genesis/utils/cache.py), rather than as an attribute of the scene, the simulator or a solver (see 'disable_owned_cache_release' for a scene rebuilt in place). Data that other components rely on as a property of the system is no cache: it is a record, stored explicitly in the class that owns it, under a name that says what it holds. A small cached property of one object, which lives as long as that object and has no reason to be shared (the digest of a scene, the bounding box of a geometry), is stored explicitly as an attribute of its class too. - A unit-valued return must not be wrapped in a named structure. Never return a one-field NamedTuple/dataclass where a bare value suffices. Only introduce a named structure for genuinely multi-field returns.
- Option fields for index/array inputs must use the project's array-like type aliases (
IArrayType/OptionalIArrayType/FArrayType/Vec3FType, etc. fromgenesis.typing), never a baretuple[int, ...]/list[...]. A bare typed-collection field of the strictOptionsrejects the lists and numpy arrays users pass (dofs_idx_local=[0, 1]), which the aliases coerce to a tuple. Match how sibling option fields are typed (e.g.filter_link_idx: OptionalIArrayType).
Style
- Write plain declaratives: subject, verb, object. Name the operation with the standard simulation vocabulary (mass matrix, Jacobian, inverse weight, kinematic tree, substep). Never invent a verb for an ordinary operation ("weigh a link", "quote a value at", "hold a rate"), and never write a clause of the form "X is what Y does". A docstring states what the function does, what each argument means and what the caller gets back. A comment states why the code is the way it is.
- Docstrings describe the current state, not history. Write what a function does now, not what it used to do or what was added. Do not write "Preserves the original X scenario" or "Added Y for Z". If a behavior is required for a bug fix, explain why in terms of the current invariant (e.g., "Must handle Z case to avoid Y").
- User-facing option docs state the tradeoff, stand alone, and stay behavioral. An option's doc must let the user decide: give cost and benefit and when to pick each value, not just what it does (if one setting looks strictly better, the downside is missing). State the real cost in user terms (if speed is not it, say what is, e.g. numerical robustness). Explain it in Genesis terms only, with no external-engine references (e.g. MuJoCo) and no internal/implementation mechanism (constraint "rows", "coupling", "cone projection", kernels, factor paths). Those belong in dev code comments. Keep it compact.
- Docstrings address the users of an API, comments its maintainers. A docstring states what users and casual developers need to use it correctly: behavior, arguments, return value, contracts, costs. Implementation details, design rationale and pitfalls go in comments at the code block they concern.
- Comments justify, generically. A comment's purpose is to explain why the code is the way it is: the invariant it preserves, the failure mode the tempting alternative runs into. Write for a maintainer reading the code with fresh eyes who would otherwise redo a past mistake, never to restate what the code shows. Keep the justification generic and present-tense. Never anchor it to perishable specifics (measured values, benchmark figures, particular unit tests or examples), which go stale long before the mechanism does.
- Each fact lives in exactly one comment, and other sites cross-reference it. Mechanics belong at the data/declaration they describe, motivation and gating rationale at the decision site that owns them. Never restate the same information at several sites, but every dependent site keeps a one-liner with an explicit pointer to the source of truth (e.g. "see nt_H in constraint/data.py").
- No semicolon in prose, and no dash as a parenthesis. Write two sentences, or use parentheses.
- Name a local after what it is, not after the property under test. A scene is
scene_from_substeps, nevershorthand,inheritingoridle. - A known upstream bug is a
# FIXME:naming the issue. Two lines at most, with the tracker reference (# FIXME: quadrants#887 - ...) and what the workaround costs. - Never document a contract the code does not offer. No array shape and no memory layout in a docstring unless the API guarantees it.
- Compare floats with a tolerance.
==and!=on floating-point values are prohibited, host-side values included: usenp.allclose(a, b, atol=gs.EPS)or an explicit bound. - Never write to a third-party object's private state. Keep our own record beside the object and expose it through a property.
- State what is, never what is not. In comments, docstrings, and reports, drop "not X", "unlike Y", "does not ...", "it is X, not Y" unless the negation was explicitly asked for or is the literal spec. If a property is not mentioned, it does not exist, and defending against an unraised concern is noise. Say the positive fact and stop. The one exception is an expectation the reader would naively hold: where the naive reading is the wrong one, saying so is the fact, and the negation earns its place.
- A docstring opens with one short summary sentence of at most 200 characters, naming no parameter. Anything more follows a blank line, in paragraphs. The summary says what the function does in words (
Fit the box of an internal node over its children.), the parameters being documented in the section that follows. - The arguments of a documented function go in a numpy-style
Parameterssection, one entry per argument with its type, its meaning and, for an optional one, its default (Defaults to ...), never folded into the prose of the description. Its return value goes in aReturnssection when its meaning is not plain from the summary. - Function-level description goes in a docstring, never a block of leading
#comments at the top of the body. Reserve inline comments for non-obvious implementation details at their point of use (e.g. a constraint-layout invariant a few lines rely on). A getter/method that opens with a paragraph of#prose is wrong: that prose is its docstring. - An attribute is documented by a docstring of its own, never in the docstring of its class. A public field of a dataclass or a NamedTuple, or a public class attribute, takes a string literal on the line after its declaration, and the class docstring states what the class is and what holds for all its fields. The options classes keep their
Parameterssection, which the user documentation renders. - Private helpers are undocumented by default. A private function, method or class gets a docstring only when it holds information useful for maintenance that its code does not make immediately obvious (a non-obvious contract, an invariant, a reason). Otherwise it gets none, and never a
#comment standing in for a docstring. - Comments go on their own line above the code they annotate, never trailing inline, whenever possible.
- No local imports unless strictly necessary (e.g., circular dependency avoidance). All imports at module top level.
- Imports are grouped, blank-line separated, alphabetical within each group, in this order: standard library, then ubiquitous third-party (
numpy,torch,tqdm, ...), then other third-party, then our own libraries (quadrants, ...), thengenesisitself, absolute then relative. Nothing enforces this, so it is done by hand. - Touching one import means fixing the whole module's imports: any addition, removal or replacement obliges regrouping and re-sorting every import in that file, and deleting the ones no longer used.
- No import aliasing (
ClothnotClothMaterial). - No temporary variables for
isinstancechecks. Useisinstance(...)directly inifstatements. - Pass an anonymous literal by keyword so its meaning shows at the call site (
_adaptive_params(verts, faces, aggressiveness=7), not a bare7). Positional is fine for self-named variables. This holds in every kernel and func call too: anonymous arguments, inlined constants or expressions (and everything after them), go by keyword, and only self-named arguments are positional. Exception: numeric constants in module-local qd.func calls stay positional, keeping those internal call chains compact. - Line wrapping is all-or-nothing, per nesting level. A call that fits on one line at its indent (<= 120 chars, counted before wrapping) is written on one line. When it overflows, all the arguments move together onto a single hugged continuation line whenever they fit there, even though the whole call does not: an argument list that fits on one line is never exploded. Before wrapping at all, an argument expression that pushes the call past the limit (a
qd.static(...)evaluation, a nested call, an arithmetic expression) binds to a self-named local, passed positionally, kernels and funcs included. When the call still overflows, every argument goes on its own line. Inside an exploded outer call, a nested call that fits stays on one line (trees_levels_links=np.count_nonzero(solver._links_tree_root_idx >= 0)inside an explodeddict(...)). ruff never collapses an exploded call (magic trailing comma), so write the compact forms by hand and drop the trailing comma, which would make ruff explode the call again. Nested data literals (matrices, coordinate/edge tables) are the exception: keep one row per line even when the whole literal fits on one. - One
ifclause holds either static conditions or dynamic ones, never both. A dynamic operand makes the whole clause dynamic, so a static gate chained with a runtime test compiles both branches: nest the staticifoutside, or carry the runtime test in a flag set under it. Several static conditions of one clause are packed in a singleqd.static(...). - A block's shared-memory array (
qd.simt.block.SharedArray) takes thesh_prefix. - Booleans read as predicates: every boolean variable/field/attribute takes an
is_orhas_prefix, present tense preferred (is_fixed,is_convex,has_multi_island_structure).was_only for a genuine past-tense flag (preferis_cached_loadedoverwas_cached). A bare name (hibernated,placed) or adid_prefix (did_fuse) is not valid. Public API takes no prefix: a boolean parameter of a function, method or kernel names what the caller asks for (refresh_position,scale_inertia,in_place), and a public property keeps the plain adjective (active). - A variable name starts with a noun naming the kind of object it holds, so what it refers to reads without the surrounding code (
rejected_kinds,links_offset_pos), never a bare adjective or participle (rejected,left_out,named). The exceptions are booleans, which take theis_/has_prefix above, and indices and loop variables, which follow thei_<type>convention. - Never detect state changes by comparing state snapshots for equality. Genesis has dedicated change-detection facilities (solver StateChange subscriptions and friends), and caching runtime data to poll it against a fresh copy is prohibited. A missing facility or missing granularity is extended in the mechanism, never replaced by snapshot comparison. Sufficient grounds on its own for rejecting the entire PR.
@qd.data_orientedis reserved for closures: pure data classes, and the polymorphic handlers whoseqd.funcmethods a kernel dispatches over at compile time (materials, the constraint handlers of a coupler). Kernels stay free functions, and no solver, coupler or entity class is@qd.data_oriented.- Naming consistency within directories (e.g.,
ipc_*.pyfor all IPC examples). - ASCII only. No non-ASCII characters anywhere in source (code, comments, docstrings): write
taurather than the Greek letter,qddotrather than q with a double dot,*rather than a middle dot,-or--rather than an em dash, and plain# ---rather than box-drawing separators. - Spell out acronyms on first use in each docstring, verbatim with the acronym in parentheses, e.g. "positive semi-definite (PSD)", "second-order cone (SOC)". After that first spell-out the acronym alone is fine within the same docstring. Code comments use the acronym alone.
- No unverifiable / stale external references. Do not justify a design by citing external projects a reader cannot verify. When porting a known feature (e.g. MuJoCo's elliptic cone), reference it at the right granularity (name the feature, optionally the official doc section, and/or the math formula), but never the external repo's specific file / function / constant names (they are cross-repo and go stale). "matches MuJoCo's elliptic cone" is good, "matches MuJoCo's
ellipticCostDif" is bad. - No torch dtype casts (
.long(),.to(torch.int64), etc.). For advanced indexing useindices_to_mask(fromgenesis.utils.misc). For atorch.gatherindex, letcumsumover a boolean mask yield int64 instead of casting. - No redundant or circular comments. Do not restate what names/types/control-flow already convey, and never write tautologies ("
dtis the timestep, so it must match the simulated timestep"). - Audit any comment or docstring paragraph beyond a couple of lines: every sentence must be essential. Comments keep only what cannot be reasonably deduced from reading the associated code in isolation. Docstrings are higher-level (the reader never opens the body), so they state everything needed to use the function correctly and determine precisely whether it is relevant. Fill lines to the 120-char width so the surviving facts take the fewest lines.
- A paragraph of more than two lines never ends with a line holding a single word. Reflow or tighten the last sentence so the closing line carries at least two words.
- Match the established sibling pattern, and do not invent structure. Before adding any helper, fixture, option, cast, comment, or file layout, confirm a sibling in the same directory already does it that way and copy it (e.g.
imu.py/imu_franka.py/tests/sensors/test_imu.py/tests/rigid/).
Testing Guidelines
- Never filter or truncate test output inline (no
pytest ... | tail/| grep). Redirect the full output to a log file, then extract from the file. - Never remove or weaken an existing assertion or measurement to silence a failure (local or CI). Report the failure with the data and ask. A threshold that only holds on one machine is a calibration problem.
- Bug fix PRs must include a regression test that fails on
mainand passes with the fix, added to the test already covering the capability that broke. - Never write a test that pins a known defect. Tests assert observable physics and public API behavior, never implementation details.
- Never test a limitation, but do test that an invalid input is refused. A capability Genesis does not offer yet gets no test, even when the code refuses it (weld equalities under the SAP coupler): that refusal is a temporary gap, not a specification. A test asserts a refusal only for an input that is invalid by nature (contradictory options, values outside their domain), whose refusal stays required once every feature exists.
- The source code never changes to accommodate a test. A test configures what it needs through the public options before building the scene, never by writing solver attributes of a built scene. When a test breaks because the engine changed, the test is fixed.
- No deprecation tests. Do not add unit tests that verify deprecation warnings are emitted.
- Feature tests exercise the new behavior, not the internal warning machinery.
- Unit tests have no docstrings. A good test name spares writing the short docstring. A code comment is acceptable only when strongly motivated, i.e. it explains something the test body cannot convey. Never state regressions or history.
- Tests are organized per component, then per capability. Each component has a folder under
tests/(rigid/,deformable/,particles/,ipc/,coupling/,sensors/,rendering/,parsers/,core/,integration/,benchmarks/) holding one file per capability (e.g.tests/rigid/test_collision.py,tests/sensors/test_imu.py). Add new tests to the existing capability file. A new file is only warranted for a genuinely new capability, never a freshtest_<one_thing>.pyfor a single feature. Complements "One capability, one test" below. - One capability, one test. A test validates one capability of the public API, never a code block or an internal logic path, and every test asserting that capability is gathered into it: it reads as the full specification of the capability, like a comprehensive example script. New coverage for a capability goes into the test already covering it, by extending its scene and its assertions or by adding a
@pytest.mark.parametrizedimension, never through a sibling function. An unrelated feature or bug path gets a dedicated test, never a graft onto an existing one. - One scene build per test. A test builds a single scene unless a second one is strictly necessary: options that cannot coexist in one scene, or a comparison between two scenes that is the point of the test. A scene written to be rejected as it is built does not count: several of them in one test are fine. Configurations fit into the one scene in this order of preference: diverse entities and options in one comprehensive scene, then differently-configured entities, then setups that must not interact placed far enough apart, then configurations swept through
n_envs, then a reference simulation folded in beside what it is compared against. - Name tests after the feature they validate, never after the scene being simulated. A test exercising off-axis contact rejection through a stacking-tower scene is
test_reject_offaxis_contact_on_authored_decomp, nottest_stacking_tower_stability: the scene is how, the feature is what. Names never repeat their module or folder name as a prefix (tests/sensors/test_temperature.py::test_grid_sensor_contact_and_reset, nevertest_temperature_grid_...). - Assert physics, not just execution. "Simulation runs without error" is not a test. Check quantities with physical meaning: free-fall displacement (
z = z0 - 0.5*g*t^2), no ground penetration (min_z > -d_hat), velocity -> 0 at rest, contact stops fall. - Non-regression fallback. If no analytical expectation is available, run the simulation once to get reference values, hardcode them, and assert with a loose tolerance. Add a
FIXMEcomment asking to replace with physics-informed assertions later. - Use
assert_allclose/assert_equalfromtests/utils/assertions.py. Preferassert_equalfor exact comparisons over framework-specific forms (torch.equal,np.array_equal). tol=sets bothatolandrtol. Passatol=for quantities whose scale is fixed and far from 1 (pixel channels in0..255). Reservetol=for quantities of order 1.- Break the implementation on purpose and watch the assertion fail before committing a test written to catch a specific defect.
- Assert observables, never internals. Validate rendered arrays (image, segmentation map, frame differences), poses, velocities, forces, never private fields, draw orders, call counts or rebuild counts. Derive the expected value analytically and design the scene so a broken mechanism moves it: two overlapping same-size semi-transparent surfaces along the view axis compose as
near + (1 - alpha) * (far - background). - When a swept comparison has cases that legitimately differ, group them by the property responsible, never by listing their positions in the sweep (
msaa_mask = [0, 1, 2, 4, 5, 6]). Bound how far the groups may differ instead of skipping the comparison between them. - A scene that needs contacts needs a movable body. Both-fixed geom pairs are dropped at build time, so sinking a fixed entity below a surface yields no contact and permanently buries its geometry in the render.
- Every assertion is a specification. Assert only behavior we genuinely want to commit to, and drop any assert already implied by a stricter one nearby.
- Assert what can break, never what holds by construction. Every assertion answers a real concern of failure: a mechanism that could break and that the assertion would catch. A shape or dtype the API guarantees, a value read back through the path that wrote it, a type check of a returned object or an
is not Noneon what cannot be None widens the apparent surface of failure and buries the checks that matter. - FEM entity positions:
entity.get_state().poshas shape[B, n_verts, 3]. Use[..., 2]to select z across all envs and vertices. - Rigid entity positions:
entity.get_pos()returns[B, 3]or[3]. Usenp.atleast_1d(...)[..., 2]and.all()for multi-env checks. - Validate both environment layouts where they differ, without redundancy. Batched and non-batched scenes may take distinct code paths. A capability whose code path differs between them is validated in both, one way or another, typically by parametrizing its test over
n_envs=[0, 2], or over other batch sizes where the size itself matters. Any other test runs batched only, which also checks that parallel environments do not contaminate each other. - Pick the backends of a test on purpose. The CI matrix covers the backends without guaranteeing that a given test runs on each. A test leaves its backend unspecified by default. It parametrizes over CPU and GPU when their code paths differ enough that it could pass on one and fail on the other, and over a single backend when it only applies to that one.
- Step budget (hard). Use the strict minimum steps needed, measured not guessed. If the checked quantity is floating-point (FP) sensitive, pad by whichever is larger: +10% or round up to 50. Per-test horizon tiers:
<100fine,100-300needs justification,>300near-prohibited (only 4-5 such tests in the whole suite). Also bound total env-steps (steps * n_envs): a 500-step x 16-env settle (8000) is unacceptable, so delete it or fit the budget. - Validate the math, not scale. One constraint proves the theory (works for 1 => works for 1k), and no large/high-DOF scene is needed for correctness. A real multi-body scene earns its steps only when it validates something a single constraint cannot (end-to-end stability, e.g. the bowl tower).
- Prefer FP-robust checks. A single constraint-solve comparison (one step from a fixed state) is robust. A multi-step trajectory comparison across numerically-distinct codepaths (different solver arms/factor paths) is not. Compare a single solve, or an analytical physical property. Cross-engine (MuJoCo) consistency is the real-world check, and an analytical closed form is the math check. Regression tests are reactive (add when a bug surfaces), not speculative.
- Every test bound is pinned to a measured worst case: measure the checked quantity on every platform at hand (cpu and both GPU archs, with and without --dev), then set the bound at 1.5x-5x the worst value, taking the tightest one from {1, 2, 5}e-X. Report the measured worst and the margin. A bound derived analytically (a physical law, a solver tolerance) needs no measurement but stays in {1, 2, 5}e-X too.
- Gradient-vs-finite-difference (FD) tolerances follow the rule above, applied to the FD floor: the floor T = max|ana - fd| / (1 + |fd|) at the configured eps. The do-not-chase floors are 1e-10 (fp64) and 5e-5 (fp32). eps is set per precision (large for fp32, small for fp64). A floor of exactly 0 means a vacuous check: fix the loss, not the tolerance. An eps-independent residual is an analytical bug, never an FD artifact.
- Tighten toward physically-exact conditions. A padded safety factor or generous tolerance that makes a scenario pass trivially also masks real behavioral differences (across backends/arms/factor paths). Prefer the tightest thresholds the physics justifies. When tightening a test makes it start failing, investigate the root, don't back off. Verify a fix against the exact assertion path (full horizon, all phases), never a cheaper proxy.
- Bound by the specified convergence, never by luck. A tolerance a test asserts follows from the solver options the test runs with, so the result is guaranteed by their specification, not met by chance. Where that needs a solver tolerance tighter than the default, a few selected tests checking convergence or exact physics set it themselves, while every other test runs the defaults so that their accuracy stays covered.
Scene construction in tests and examples
- Keyword arguments follow the declaration order of the callee, e.g.
add_entity(morph=..., material=..., surface=...). Keywords never license reordering. - One option per line for every
scene.add_entity/scene.add_sensor/gs.morphs.*/gs.options.*call, even with a single option. ruff does not enforce this. It must be done by hand. It is asked of the scenes a test simulates: a scene written to be rejected as it is built is read for the one option that makes it invalid, so its options stay on one line, morph included, and no comment is owed for that. - Every test calling
scene.step()takes theshow_viewerfixture and setsViewerOptionswith a camera viewpoint tuned to frame the simulated scene, so running it with the viewer enabled is immediately usable for debugging. - Only strictly-required options, at default values unless a reason forces otherwise. Never set redundant or default-valued options (
align=False,ProfilingOptions(show_FPS=False)), and never pick a non-default value without a reason that requires it (e.g. use a smallerdtthan the default only if precision or stability actually needs it). The one exception: an option whose value the test/example computation reads (gravity,dt) must be set explicitly even when it equals the default, so the simulated value matches the asserted one. - Pass scalars / lists directly. Setters and IK accept array-like and broadcast a scalar across DOFs. Never wrap in
np.full,np.array, or a single-element[...](control_dofs_force(TAU),set_dofs_kp([...]),inverse_kinematics(pos=[...], quat=[...])). Inline one-shot target vectors instead of naming them. - Custom MJCF/URDF models: build them with
xml.etree.ElementTreein a fixture that returnsET.tostring(mjcf, encoding="unicode"), and pass that straight to the morphfile=.FileMorph.fileaccepts inline XML content (string) for both MJCF and URDF morphs, so never write a temporary XML file just to load a model. Followtests/rigid/conftest.py. Never assemble XML viawrite_text/textwrap.dedentstring literals or f-string concatenation. - Temporary assets that must be stored on disk use the session-scoped
asset_tmp_pathfixture (shared across tests), whiletmp_pathis per-test. - No module-level test constants, helpers, or parametrize scenario-lists. Put constants inside the test, build the scene inline, pack diverse configs into one scene (follow
tests/sensors/test_imu.py::test_sensor). Read derived params back from the built model (get_dofs_armature,get_dofs_damping, ...) rather than duplicating literals between fixture and assertions. - Parametrize over plain values, never over built objects, and never name the cases. A
@pytest.mark.parametrizedimension takes the plain values that select a case (light_typein["directional", "point", "spot"]), whose default ids read on their own, and the test body builds the objects they select (the light options). Explicitid=andids=are prohibited. - Hide recurring boilerplate in fixtures, and never add indirection without a payoff. The test body must show only what is being validated. Recurring model construction and asset resolution go into fixtures. Scene setup stays in the test body (a unit test reads like an example script), even at the cost of duplication. A fixture that improves neither readability nor factorization is prohibited. Otherwise stay explicit and self-contained. No premature factorization.
- Do not gate per-step asserts with
float(...)/.item()casts on tensor reductions. Design the scenario (e.g. a warmup loop that spins joints up) so the assertion holds unconditionally, then assert on the full tensor with.all(). - Exact analytical dynamics checks: force
gs.integrator.Eulerso the finite-differencedqaccequals the solver's, and account for both rigid-body rotational inertia and the implicit-damping first-order correction (effective_inertia = I + damping*dt, as intest_position_control) rather than loosening tolerances or distorting geometry.
Running Tests From a Git Worktree
The package is installed in editable mode pointing at the primary checkout, so a worktree's genesis/ is not what gets imported by default. This silently tests the wrong engine: the worktree's tests/ run against the primary checkout's genesis/, so engine edits appear to have no effect and every result is void.
- Always pass
PYTHONPATH=$PWDwhen invoking pytest from a worktree, e.g.cd <worktree> && PYTHONPATH=$PWD pytest -n 8 tests/rigid. Same for the cluster:PYTHONPATH=$WORKTREE pytest .... - Verify it once per session, do not assume.
PYTHONPATH=$PWD pytest -n 0 -s -k <any test>with aprint(genesis.__file__), or simply check that the path printed starts with the worktree. - Plain
python script.pyfrom a worktree does pick up the worktree (cwd precedes the editable path), so a script and a pytest run in the same directory can exercise different engines. Never compare their results. - Symptoms that mean this is happening: an engine edit changes nothing, a kernel
print()added to the worktree emits nothing, an A/B over engine variants returns bit-identical numbers for every arm. Check this cause first, before any physics explanation. - Give each worktree its own compile cache when several of them run test suites at the same time, e.g.
QD_OFFLINE_CACHE_FILE_PATH=<scratch>/<worktree>/quadrants GS_CACHE_FILE_PATH=<scratch>/<worktree>/genesis. The concurrent runs compile different engines and race to write the same entries of the shared~/.cache, which corrupts them: hundreds ofQuadrantsNameErroron names that are in scope, spread over tests that pass one at a time, and more of them on a second run as the bad entries persist. Keep that cache for the life of the worktree, so its kernels compile once, and pass an absolute path, since a relative one resolves against the cwd of each test. A single run,-nworkers included, uses the default cache.
Testing on Cluster
- SSH:
ssh genesis-coreweave - Path:
/mnt/home/duburcqa/workspace/src/genesis - Git operations (fetch, checkout, pull) must be done on the login node, not inside
gs-srun. The compute node container cannot reach GitHub. - Always use
gs-srun(Slurm wrapper) to allocate a GPU node. Never run pytest or python directly on the login node. - Always use the
rtx-midpartition (gs-srun --partition=rtx-mid).rtx-highis forbidden.rtx-midjobs can be preempted, so a long run relaunches a job whose output lacks its end marker, and runs in a tmux session on the login node so it survives a closed laptop. - Requesting CPUs or memory is forbidden (
--cpus-per-task,-c,--mem,--mem-per-cpu, and the like). Request--nodes=1 --gpus=<n>alone and take the CPUs and memory the job is given, reading the CPU count fromnprocinside the job. - Never source a venv manually. The container image already has the correct environment. The
bash -lclogin shell sets everything up automatically. - Pattern for git + run:
ssh genesis-coreweave 'bash -lc "cd /mnt/home/duburcqa/workspace/src/genesis && git pull && gs-srun --partition=rtx-mid --nodes=1 --gpus=1 bash -ilc \"cd /mnt/home/duburcqa/workspace/src/genesis && pytest -n 10 tests/ipc -v --no-header 2>&1\""' - Example tests need
-m examplesto override the default marker filter inpyproject.toml. - Copy local files to cluster:
scp <local_path> genesis-coreweave:<remote_path>. Then run withgs-srun. - The compute container mounts
/mnt/home, not the login node's/tmp. A script, patch, or output dir placed under/tmpon the login node is invisible undergs-srun. Stage everything under/mnt/home/duburcqa. - The interactive login shell (
bash -ilc) setsnoclobber:cmd > fileaborts with "cannot overwrite existing file" whenfilealready exists, silently producing no output for that run.rm -f filefirst (or redirect with>| file) whenever re-generating a log at a fixed path. - Run a staged script with
bash -ilc "source script.sh", neverbash -l script.sh. The container's Python env only initializes in an interactive login shell, and a non-interactivebash -l script.shundergs-srunruns without the venv (ModuleNotFoundError: genesis). Stage the script under/mnt/homeand source it, e.g.gs-srun ... bash -ilc "source /mnt/home/duburcqa/run.sh".
Reproducing Apple Software Renderer Failures Locally
All GitHub Apple Silicon macOS runners are VMs whose virtualized GPU has no OpenGL, so rendering falls back to the Apple Software Renderer, which has several known defects. macOS-only rendering failures come from tests tripping one of its failure modes, so be careful about which rendering features unit tests rely on. To force it locally on any Mac, override the two pixel-format attributes that pyglet unconditionally appends, before any GL context is created:
# force_sw.py - import before any GL context is created, e.g. 'pytest -p force_sw' with PYTHONPATH set
from pyglet.libs.darwin import cocoapy
cocoapy.NSOpenGLPFAAllRenderers = 70 # NSOpenGLPFARendererID
cocoapy.NSOpenGLPFAMaximumPolicy = 0x00020400 # kCGLRendererGenericFloatID- This reaches pyglet-created contexts only, so offscreen rendering must be routed back through the pyglet platform with
PYOPENGL_PLATFORM=pyglet. Its own default on macOS is CGL, which pyglet knows nothing about. - Run with the same flags as macOS CI:
PYTHONPATH=<dir-with-force_sw.py> PYOPENGL_PLATFORM=pyglet GS_TORCH_FORCE_CPU_DEVICE=1 pytest -p force_sw --dev --logical --backend cpu --forked <tests>(CI additionally selects-m 'required and not slow'). - Verify it took effect: Genesis logs "Software rendering context detected" and
scene.visualizer.is_softwareis True. - Known failure mode: any geometry with vertices outside the camera frustum is misrasterized, breaking pixel comparisons. In practice this affects ground planes, whose default
plane_sizeis effectively infinite (1 km x 1 km): give them a finite size and a position that puts every vertex inside the view. - Known failure mode: geometry thinner than a pixel is rasterized differently by every renderer, and thousands of overlapping sub-pixel primitives turn that into noise above the pixel-matching thresholds. This affects particles (
debug_vis_mode="particle"in the debug view, with a smallparticle_size) and wireframes such as the solver boundaries (ParticleVisOptions(boundary=True), 4 mm thick). Keep every visible feature at least 2 pixels wide, a pixel spanning2 * distance * tan(fov / 2) / res_heightat the given distance from the camera, or leave the feature out of the snapshot. - Validating a new snapshot: generate it on hardware GL with
pytest -n 0 --snapshot-update <test>(serial, without--forked), then run the test with the software renderer forced as above. - Publishing a snapshot:
tests/snapshots.lockholds one line per snapshot file, its path relative totests/and the commit of theGenesis-Intelligence/snapshotsdataset to download it at, sorted by path, which the pre-commit hooks enforce.--snapshot-updatemarks every regenerated file whose bytes changed aspending, and the tests read a pending file from the local copy.pytest --snapshot-sync <tests>uploads the pending files to a draft pull request of the dataset whose title names the genesis-world pull request of the branch (Update snapshots for genesis-world#<n>), adding a commit to it if one is already open. Open the genesis-world pull request first, sinceghlooks it up. Once a maintainer merges the dataset pull request, run--snapshot-syncagain: it pins each pending file to the merge commit. CI fails on a pending line until then. Never rewrite the history of the dataset'smainbranch, since the lock pins commits in it. - A snapshot test failing on the generic CI uploads the image it rendered as the
failure-artifacts-*artifact of the job (--failure-artifacts-dir). Compare it with the snapshot before guessing at the cause.
Tooling & Contributing
- Lint/format: ruff (check + format, line length 120) via pre-commit. Install hooks with
pre-commit install, and they run on every commit. - PR titles carry a main bracket tag,
[BUG FIX],[FEATURE]or[MISC], preceded by[CHANGING](the simulated physics change by default: a different model, or different default parameters, while solver-internal restructuring that keeps the model and its defaults takes the main tag alone) or[BREAKING](API break) when it applies. These two never stand alone and never go together. Commit titles are plain single-line sentences without the tag. Both PR and commit titles end with a period. - PR titles state the benefit for end users, not the implementation. Implementation details go in the PR description.
- A GitHub text never cites a commit outside
main(a pull request description, a review reply, an issue comment): amends, rebases and squash merges rewrite the commits of a branch, so their SHA goes stale at once. Say what changed instead (Done: '_box_to_particles' raises on an unknown sampler.). A commit ofmainstays valid and may be cited. - Contributors must follow
CODING_GUIDELINES.mdand the reference docs in.github/contributing/: ARCHITECTURE, TESTING, CODING_CONVENTIONS, EXAMPLES, PULL_REQUESTS, USD_PARSER. On conflict, ask.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

