WorksComputer Science
tmol: a GPU-accelerated implementation of the Rosetta energy function for machine learning
Abstract
Physics-inspired forcefields complement generative machine learning models, showing better generalization beyond the training distribution. However, these forcefields are typically slow to evaluate, and their derivatives are difficult to integrate into ML frameworks. We introduce tmol, a GPU-native PyTorch library implementing the state-of-the-art RosettaGenFF forcefield. tmol supports efficient batched differentiable scoring and whole-structure refinement with up to 362-fold throughput increase (batched). Used as a reward in generative protein design, tmol increases hydrogen bonds and water bridges at designed interfaces.
Introduction
Generative machine learning (ML) models have led to dramatic improvements in our ability to predict and design biomolecular structures1–3. However, such models generalize poorly to underrepresented chemistry: ligand-docking accuracy falls for unfamiliar pockets and ligands, where generated models often show poor stereochemistry4–6; and RNA structure prediction degrades sharply on novel folds7. These limitations make physical forcefields appealing as priors, identifying physically implausible conformations that generative models may miss. Unfortunately, integrating such forcefields has been difficult, as they are often too slow to incorporate into an ML pipeline, and incompatible interfaces makes efforts to do so laborious. GPU-accelerated forcefields10,11 address part of this, accelerating molecular-mechanics simulations, but the Rosetta energy function and its sampling algorithms, including discrete side-chain optimization and torsion-space minimization, have had no differentiable, GPU-native counterpart.
Here we introduce tmol, an open-source PyTorch library that addresses both of these issues by reimplementing the RosettaGenFF forcefield12,13 as highly efficient batched tensor operations. Building on the successful Rosetta software package8,9, we also implement a set of “core algorithms,” including whole-structure and residue-pair scoring, discrete side-chain optimization (packing), Cartesian and torsion-space minimization14, and a general-purpose refinement protocol (relax)15. Scoring, packing and minimization are all native PyTorch operations returning coordinate or torsion derivatives through autograd16, so energies and refinement may compose directly into ML model training and inference.
Results
Figure 1 outlines how tmol is organized. A molecular system is divided into blocks (amino-acid residues or ligands), and energies are computed between pairs of neighboring blocks. Each block pair is assigned to its own GPU thread block, a cooperative thread array (CTA) containing 32 threads (Figure 1b). These threads copy the coordinates and parameters for both blocks into shared memory (a fast scratch space), then evaluate all atom pairs between the blocks (up to ), with each thread handling a subset. Each thread’s computed energy is then summed across the CTA to give one energy per score term for the block pair; each atom pair’s derivative contribution is added directly to a per-atom gradient tensor. Blocks with more than 32 atoms are processed in several such tiles. For minimization over torsion angles, tmol also converts between internal coordinates (bond lengths, angles and torsions) and Cartesian coordinates on the GPU, using a parallel algorithm called a segmented scan (see Methods).

Figure 1. Batched molecular modeling and performance. a, tmol’s shared molecular representation and modeling operations. b, Pairs of interacting molecular blocks (residues) map to GPU thread blocks (cooperative thread arrays, CTAs). Each block-pair’s 32 threads reuse atom data in shared memory to calculate energies and coordinate gradients. c, Throughput of score-plus-gradient and FastRelax as a function of structure size for PyRosetta (one CPU core), tmol on one or 32 CPU threads, and tmol on one GPU at batch sizes B of 1, 10 and 100. Points are medians; brackets give the fold change of tmol (B100) over PyRosetta at 800 residues. d, Agreement with Rosetta on 1,000 high-resolution protein chains: Pearson correlation (left; 95% bootstrap intervals) and tmol minus Rosetta energy per residue (right; mean ± s.d. over chains) for each score term. Shading marks terms affected by the deliberate changes to count-pair weighting, interpolation and double counting.
Within this framework, all the terms of RosettaGenFF were reimplemented. Small changes addressed three issues (details in Methods): inconsistent count-pair weighting, double-counted hydroxyl torsions, and representation of tabulated potentials. We also implemented a widely used Rosetta refinement protocol, FastRelax, with an additional change to improve rotamer recovery metrics (see Methods). Following testing on a diverse set of 1000 high-resolution protein structures, tmol reproduced PyRosetta score terms closely (Pearson for every term and 0.997 for the total; Figure 1d). Further, tmol is significantly faster than Rosetta: over a range of protein sizes, tmol achieves 233–362x speedup for score-plus-gradient calculations, and 38–102x speedup for torsion-space relax relative to single-threaded PyRosetta (Figure 1c). This improvement is despite the fact that relax in tmol considers 60% more rotamers than PyRosetta.
One challenge in using Rosetta and other biomolecular forcefields is that configuring novel chemistry is often only “semi-automated,” requiring users to manually check protonation, charge assignment, and atom and bond types. Proper handling of non-standard residues and metals is quite challenging. tmol includes a fast, fully automatic input-processing pipeline that requires no user input: ligands, modified amino acids, D-amino acids, modified nucleotides and most metallocomplexes are parameterized directly from the deposited chemistry. A new metal-coordination term (see Methods) as well as DNA and RNA torsion potentials—derived with the scheme of Yanover and Bradley17 from DNA and RNA structures, respectively—properly evaluate internal energetics of such complexes.
Evaluating tmol on previously published benchmarks used to optimize and assess energy-function quality12,13,18,19, we observe similar performance across a wide range of modalities, including protein-monomer, protein–protein, and protein–DNA decoy discrimination, side-chain-rotamer recovery, ligand docking, and stability (Figure 2b). All differences fall within run-to-run variation except rotamer recovery, where tmol gains by keeping near-native rotamers that Rosetta’s bump check discards. Ligand docking highlights the strength of the automatic pipeline: generating PyRosetta parameters required several minutes of processing and manual inspection of input models, while tmol took about 1 second to generate parameters for each ligand with no user input.

Figure 2. Molecular energetics and tmol-guided protein design. a, Score-function components; all 26 energy terms appear in Online Methods (Table S1). b, Energy-function benchmark summaries: higher is better. c, Reward-guided beam search with tmol interface energies for 24 protein–protein targets. Bars show the percentage of designs with at least five hydrogen-bonded binder–target residue pairs (tmol hbond ; left) or with strong water bridging (summed tmol lk_bridge energy ; right) for unguided sampling, the best 32 of 128 unguided designs chosen on the plotted quantity (best-of-), and search with a hydrogen-bond or lk_bridge reward; error bars are 95% bootstrap intervals over targets. d, Example search designs (hydrogen-bond reward) with 10 and 9 interface hydrogen bonds, all shown; dashed lines join hydrogen-bonded residue pairs. e, Example search designs (lk_bridge reward) with 6 and 5 water bridges. Spheres are implied waters, each placed 2.7–3.1 Å from both polar atoms of an lk_bridge residue pair () without steric clash.
To demonstrate integration with machine learning frameworks, we used tmol as a reward in beam search with the protein-design model RFD4-Proteina20, scoring candidate binders without gradients (Online Methods). Across 24 protein–protein targets, a hydrogen-bond reward raised the share of designs with at least five interface residue pairs making hydrogen bonds from 16% to 66% (53% for the best 32 of 128 unguided designs chosen on the same quantity), and a lk_bridge “bridging-water” reward raised the share with strong water bridging from 17% to 68% (55% for best-of-) (Figure 2c–Figure 2e). Forward folding in silico success, assessed with OpenFold321, rose from 14.5% to 22.9% (hydrogen-bond reward), matching but not exceeding best-of- selection (25.5%); search designs also had larger interfaces and slightly more clashes.
Discussion
tmol provides a framework that allows generative ML methods, physics-based forcefields, and physics-guided simulations to all naturally interoperate. It is our hope that tmol will enable the rapid development of ML models that incorporate energetics tightly into their networks. Many problems in biomolecular structure prediction7,22 show poor generalization due to limited data: obtaining high-resolution structures is costly and labor-intensive. For these cases, we believe tmol represents a strong “biophysical prior” that should prove valuable in improving model generalizability.
Declarations
Competing interests The authors declare the following competing interests: A.L.-F., J.K. and A.M.W. are employees of Prescient Design, Genentech, a member of the Roche Group. K.D. is an employee of NVIDIA. tmol is distributed under the open-source BSD 3-Clause license, and no patents have been filed on the work described. The remaining authors declare no competing interests.
Author contributions A.L.-F., A.F., D.B. and F.D. conceived the project. A.L.-F., A.F., F.D., K.D., J.F. and H.S. developed the tmol code. G.Z. and H.P. contributed to the ligand and noncanonical-residue processing pipeline, K.D, M.W.K., R.I.B. and N.C. contributed to the AtomWorks integration, and J.K. contributed to supporting method development. F.D., A.L.-F., K.D. and J.F. curated the data and performed the analyses. F.D., D.B., B.K. and A.M.W. supervised the work. A.L.-F., K.D. and F.D. wrote the first draft of the manuscript. All authors edited the manuscript and approved the final version.
Code availability tmol is available at https://github.com/RosettaCommons/tmol; documentation is at https://rosettacommons.github.io/tmol/latest/.
Ethics approval Not applicable.
Online Methods
Software versions and reproducibility
Unless otherwise specified, all comparisons use tmol version 0.2.0, PyTorch 2.14.1, CUDA 13.0 and AtomWorks 3.0.0; Rosetta comparisons use PyRosetta 2026.3+releasequarterly.
PoseStack: a GPU-native molecular representation
Rosetta3 represents molecular topology, coordinates and parameters through an object-oriented molecular model 8; independent trajectories can be parallelized across multiple CPUs. GPU execution, however, requires enough concurrent work to overcome launch overhead, and needs contiguous inputs addressable by every participating thread. Consequently, tmol combines independent systems into a single PoseStack. A PoseStack represents its principal coordinates as a dense tensor of shape [n_poses, max_n_atoms, 3]. In this representation, all model parameters are represented as per-block (see below) padded tensors. Members of a PoseStack may contain multiple unrelated structures with differing residue counts, sequences and chemistries; these structures do not interact with each other. Rather, the role of a PoseStack is to keep the GPU saturated.
The basic unit of calculation in tmol is the block. Each block represents a set of atoms with a corresponding block type, which defines its atoms, intra-block bonds, chemical parameters, and a set of connection points through which it can bond to other blocks. Nothing in this interface assumes a polymer, so the same representation covers polymer residues, small-molecule ligands, and fragments of larger chemical components that have been split across several connected blocks. Blocks play the role in tmol that Residues play in Rosetta: energies are evaluated over blocks and between pairs of blocks.
A PoseStack represents a batch of poses as padded tensors. For each pose it stores 1) a PackedBlockTypes object describing an ordered list of block types, 2) the block-type identity for each block in the PoseStack as an index into the PackedBlockTypes object, 3) a set of coordinates for all atoms in all poses, 4) a per-block offset into the coordinate tensor, and 5) for each connection point on each block, the block and connection point it is bonded to. Poses with fewer blocks or atoms are padded to the largest pose in the batch. (PoseStacks also contain a ConstraintSet, a PDBInfo object for convenient input and output, and the number of chemical bonds separating all pairs of inter-block connection points.)
PackedBlockTypes holds an ordered list of block types. The order is fixed at construction, so a PoseStack can refer to a block type by index. Per-type properties such as atom counts, bonds, torsions and connection atoms are stored as padded tensors with one row per block type. PackedBlockTypes also serves as a persistent cache for the tensors that score terms and algorithms derive from the block types in order to perform their calculations efficiently, an idiom we call annotation. Rather than adding term-specific fields to the chemical database, each term computes its inputs for each block type as CPU arrays, annotates them onto the block type, and then concatenates these per-block annotations, in PackedBlockTypes order, into device-resident tensors annotated onto the PackedBlockTypes. This annotation cost is thus only paid once per set of block types rather than once per pose or once per scoring evaluation. Terms reuse an existing annotation when one is already present, and shared base classes let several terms reuse common annotations such as the bond graph, bond separations, and atom types.
A PoseStack’s chemistry and connectivity are fixed for its lifetime; only its coordinates change. Minimization therefore updates a stack in place, whereas any change to topology, batch membership, or sequence (as in packing or design) produces a new stack. Because a PoseStack’s chemistry is immutable, stacks can be shallow-copied cheaply.
Parameterizing new chemistry
The default database for tmol contains precomputed parameters for: the canonical L-amino acids, including protonation and tautomer variants (HIS_D and HIS_POS, and deprotonated forms of Cys, His, Lys and Tyr for metal coordination) and disulfide-bonded cysteine; D-amino acids, generated as mirror images of the L residues that read the L backbone tables at negated ; DNA and RNA nucleotides; water; and termini variants for both polymer types. It also includes 29 metal-ion residue types, one per combination of ion and coordination geometry, covering 12 elements, and 17 multi-metal cofactors such as iron-sulfur clusters. The default score function is beta_nov2016 extended with nucleic-acid torsion, generic torsion (gen_bonded) and metal-coordination terms.
Any residue other than these basic types is parameterized automatically. Ligands can be supplied as a SMILES string, a MOL2/SDF file or a CIF file, or detected directly in a Biotite [25] structure as residues absent from the active database. Bond orders must come from the input: tmol does not infer bonds from geometry. Prepared residues are added to a new ParameterDatabase (extending the input one) and can be saved to an editable .tmol file for reuse.
Parameterization proceeds in three steps. First, the residue is protonated at the requested pH by Dimorphite-DL [26] (with a few added rules). Second, a reference structure is generated from distance geometry using custom PyTorch code, followed by a short force-field minimization using MMFF94 [27] in Open Babel [28]. MMFF94 partial charges are also assigned from this computation. Third, atoms are typed with a port of Rosetta’s generic-potential classifier 13, and parameters are derived: bond lengths and angles are restrained about their values in the reference structure, and torsions are scored by the generic gen_bonded term.
Covalently linked residues require additional handling. A noncanonical residue within a polymer chain is capped at its polymer connections, parameterized as above, and then uncapped. The backbone atoms of an -amino acid are retyped to the canonical protein types so that the protein-specific backbone terms apply, while its side chain keeps generic types. Residues with other backbones keep generic types throughout. A residue attached through a side chain, such as a glycan or covalent ligand, is joined to its partner by a generated patch that adds a connection at the attachment site.
Chemistry beyond canonical residues
Noncanonical residues.
Noncanonical -amino acids are given hybrid parameters: backbone atoms receive the canonical protein atom types, while side-chain atoms keep the generic types assigned during preparation. Their backbone is scored by the protein backbone torsion terms (Ramachandran and omega ()), using the tables of the most similar canonical amino acid, or alanine if none matches; side-chain torsions are scored by gen_bonded. All other noncanonical amino acids, including - and -amino acids and N-methylated residues, keep generic types throughout and are scored entirely by gen_bonded.
For packing, the side chain of every noncanonical amino acid, or not, is matched against the canonical side chains, and the rotamer library of the most similar one is borrowed. The borrowed library is used only to generate rotamers and never contributes to the score. Side chains with no match, and any torsions beyond those the borrowed library covers, are sampled by enumerating a fixed set of values for each rotatable bond.
Metal coordination.
The coordination geometry around a metal is inferred from the input structure. When a pose is built, candidate donor atoms near each metal are collected, and the coordination geometries allowed for that metal are fitted to the donor directions to find the best match. Two things follow. First, each coordinating residue is patched to bond to the metal and, if needed, switched to a deprotonated variant that can donate. Second, virtual atoms are built around the metal at ideal coordination sites, oriented by the fit. A metal-coordination energy term then restrains each coordinating atom to its site, holding it at the ideal metal–donor distance (median distances from high-resolution structures) and along the site direction. Multi-metal cofactors such as iron-sulfur clusters are handled the same way, with some sites filled by the cofactor’s own atoms.
Ligand fragmentation.
While tmol can only subdivide interaction energies down to the block level, for large ligands it is desirable to further subdivide energies into ligand substructures. tmol provides a mechanism for this: annotating a ligand’s atoms with tmol_fragment_id splits it into separate blocks which are each scored separately, allowing ligand energies to be reported at finer granularity. The ligand is parameterized as a whole before it is split, so the total score is unchanged by fragmentation.
Score functions and scoring modes
A score function in tmol is a weighted list of energy terms. Scoring a PoseStack proceeds in two phases. In the first, rendering, each term annotates the block types and the pose with whatever data it needs; these annotations depend only on the chemistry of the pose, not its coordinates. The result is a scoring module bound to that PoseStack. In the second phase, the module passes coordinates and annotations to the scoring kernels and returns the weighted sum of the term energies. Because rendering does not depend on coordinates, a single rendered module can score any number of conformations of the same PoseStack, as in minimization.
A score function can be rendered in one of three modes, all built on the same block-level calculations. Whole-pose scoring returns one weighted energy per pose, optionally broken down by score term. Block-pair scoring returns one energy per pair of blocks in each pose. This gives per-residue and interface energies directly. Combined with automatic differentiation, it also allows individual interactions to be weighted differently. Block-pair scoring carries a small overhead in runtime and memory. Rotamer scoring is used during packing: it scores every candidate rotamer against every other and returns a sparse rotamer-pair energy tensor, which is traversed during simulated annealing.
The API includes a function beta2016_score_function, which returns a ScoreFunction object with weights and terms analogous to Rosetta’s beta_nov2016_cart, with additional terms for ligand and nucleic-acid torsions and for metal coordination. It is also possible to construct a ScoreFunction from a weights file by using ScoreFunction.from_sfxn_file(...) and passing in the path to that file.
Efficient, autograd-compatible CPU, CUDA, and Metal (MPS) scoring kernels
Individual scoreterm kernels were designed with three goals: efficiency on CPU and on both NVIDIA (CUDA) and Apple-silicon (Metal/MPS) GPUs, a single shared implementation across devices wherever possible, and full compatibility with PyTorch automatic differentiation. The sections below describe how the code is shared between devices, how the principal non-bonded kernels are organized on the GPU, and how derivatives are exposed to PyTorch.
Unified CPU, CUDA and Metal execution
The greatest risk in maintaining separate CPU and GPU versions of a function is that the two (or more!) implementations diverge: a bug is fixed in one but not the other, or a feature is added to only one, and the two begin computing different values. tmol avoids this through heavy use of templates. The lowest-level operations are written once, in a device-agnostic way, as C++ lambda functions, and the same code is then handed to one of several device-specific launchers. On the CPU, the lambda is called in a for loop over all inputs; on the GPU, it is passed to a moderngpu [29] transform operation, which wraps it in a kernel and launches that kernel with threads. Device-specific code is thereby confined to a small execution layer whose two versions can be checked for equivalence by inspection. This layer, the DeviceOperations class, provides kernel launches, scans, and reductions, with its CPU and CUDA versions in separate files.
Each kernel follows the same execution “diamond” (Figure S1). A C++ entry point calls a method of a struct templated on the device holding the tensors. The CPU, CUDA and Metal instantiations of that struct live in separate .cpu.cpp, .cuda.cu and .mps.cpp files, which all include the same generically written .impl.h file along with the corresponding DeviceOperations implementation: the paths diverge by device and then merge again in shared code. Eigen’s tensor module [30] is used as a shared abstraction on CPU and CUDA; code shared with Metal uses a small portable math layer that also compiles as Metal Shading Language.
Figure S1. Device dispatch in tmol. A single device-agnostic implementation is compiled separately for CPU, CUDA and Apple Metal (MPS); only the launch layer differs between devices.
Apple-silicon (MPS) kernels
Metal threadgroups on Apple GPUs execute in 32-wide SIMD groups, just like CUDA CTAs execute in 32-thread warps, so the block-pair tiling used on CUDA (see Block-pair GPU kernels below) runs on Metal largely unchanged (with threadgroup memory in place of CUDA shared memory). The two GPUs are used differently, however. Apple GPUs are slower than CUDA devices, but moving data between host and GPU is cheap. Due to this, on CUDA, all scoreterms and operations stay on the device; on Metal, coordinates and data stay in host tensors and only a handful of compute-intensive operations are offloaded to the device, with results copied back. Offloaded terms include fa_ljatr, fa_ljrep, fa_lk and fa_elec in whole-pose scoring, and additionally lk_ball and hbond in rotamer-pair scoring for packing. Parallel simulated annealing is also carried out on-device. The remaining terms are evaluated on the CPU concurrently. While only limited testing was carried out, on a base M5 processor, we see 3.5-fold speedup using this approach (comparing all-CPU tmol to all-CPU+device). All device paths are nevertheless tested separately, because reduction order and floating-point arithmetic remain device dependent.
Block-pair GPU kernels
The principal non-bonded kernels operate on pairs of blocks. tmol places a bounding sphere of radius around each block and selects block pairs with , where is the interaction reach of the term. Atom-pair evaluation then applies each term’s own cutoff and bond-separation exclusions (e.g., the Lennard–Jones cutoff is 6.0 Å).
On the GPU, a grid of 32-thread cooperative thread arrays (CTAs), each a single warp (on Metal, a 32-thread threadgroup), strides through the list of selected block pairs, with each CTA handling one pair at a time. A CTA stages the coordinates and parameters of up to 32 atoms from each block in shared memory. On a full tile, thread evaluates the flattened atom-pair indices for , so the tile’s 1,024 interactions are spread across 32 threads while reusing the staged atom data. Larger blocks are processed as successive tiles. Each thread’s energy contributions are reduced within the CTA and added to the pose total, and Cartesian derivatives are accumulated atomically at the affected coordinates.
This tiling scheme is written with templates and shared by all four atom-pair energy terms: Lennard–Jones/Lazaridis–Karplus [31], LK-ball, electrostatics and hydrogen bonding. New atom-pair terms can adopt it with little additional code.
Accumulating energies by block pair also improves numerical stability. Early versions of tmol added every atom-pair contribution atomically into a single global total. This proved unstable, with energies varying by between runs on identical inputs because of nondeterministic thread execution order: adding many small numbers to a large one loses their significant figures [32]. Having each warp first compute a block-pair subtotal over roughly 400 atom-pair interactions (about 20 atoms per block) and then accumulating these larger subtotals is substantially more stable, and also reduces global-memory traffic. Because the unit of work is a block pair, whole-pose, block-pair and rotamer scoring all reuse the same atom-pair functions.
Automatic differentiation
Each compiled scoring operator provides an explicit backward function to PyTorch, so a weighted energy can be differentiated with respect to the Cartesian coordinates and combined with other differentiable objectives. This supports Cartesian minimization, gradient-based guidance of generative models, and training losses built from tmol energies. For efficiency, many kernels in whole-pose scoring compute derivatives during the forward pass when gradients are required and cache them for the backward pass, avoiding a second traversal of the interacting atom pairs. Block-pair scoring does not do this, which accounts for its small overhead.
Parallel internal-coordinate kinematics
One key feature of Rosetta is internal-coordinate (or “torsion-space”) refinement. Treating bond lengths and angles as ideal allows optimization in a lower-dimensional space, which gives both faster convergence and less susceptibility to getting stuck in local minima. Molecular dynamics and molecular mechanics packages typically sample in Cartesian space, where the fastest bond and angle vibrations limit the usable step size; Rosetta instead treats these degrees of freedom as ideal and samples in torsion space. It does this by constructing a kinematic tree [33], so that changes to torsional degrees of freedom can be propagated into new Cartesian coordinates by a recursive traversal of the tree. A significant challenge for tmol was that GPUs are poorly suited to recursion.
To solve this, we turn to the GPU algorithm scan [34], which is frequently used to compute prefix sums (e.g. index offsets). In parallel steps, scan can compute
for all (with the identity), and crucially, this works for any binary, associative operator . If we represent the transform from the coordinate frame of a parent atom to that of its child as a homogeneous transform, then the operation to compute that child’s frame is matrix multiplication, and matrix multiplication is binary and associative. Thus, if we break Rosetta’s kinematic tree into a set of paths, we can repeatedly use scan to compute the coordinates for all atoms, and using a variation on scan, segmented scan, can process multiple paths at the same “depth” at once. We call this algorithm generational segmented scan, as each generation reaches a new set of branches in the tree.
For user control over the kinematic tree, tmol represents block-level connectivity with a batched FoldForest (the batched equivalent of Rosetta’s FoldTree) and internally expands this to an atom-level KinForest. FoldForest represents three types of connections between blocks: polymer edges describe connected block ranges, jump edges connect arbitrary blocks with six rigid-body degrees of freedom, and root jump edges connect each molecular tree to a virtual root at the origin, allowing rigid-body orientation of the entire system, necessary for support of anisotropic energy terms. Each pose in the PoseStack must have at least one root jump edge, but may contain arbitrarily many.
The process of converting from the FoldForest to the KinForest is complex. We wanted assembly of this data structure to involve the CPU as little as possible, though it is most readily expressed recursively. We factor the portions of a full KinForest into the several scan-path segments that each block contributes. The number of different variations of scan-path-segment assemblies for each block type is given by the product of the number of input-connection points and the number of output-connection points, and these variations can all be precomputed; we call these stencils. With enough careful construction of offsets, we can assemble the stencils into a full KinForest. The first step, though, involves a post-order, depth-first traversal of the edges in the FoldForest on the CPU that determines the “generational delay” for each edge – the first generation that the blocks of that edge will be traversed – converting the partial order of the edges into a total order. From there forward, everything can be performed on the GPU.
The same forward algorithm that starts at the root and travels down to the leaves to compute coordinates from internal DOFs also works backwards to sum the and derivative vectors [35] (called “f1” and “f2” in Rosetta and tmol) from the leaves up toward the root. tmol can therefore minimize with respect to internal degrees of freedom, just as Rosetta does. The vectors (f2) are the coordinate gradients returned by the backward pass, and the vectors (f1) follow from them as , where is the position of atom . This shortcut lets the backward pass compute only the vectors; the vectors are computed only when using internal-DOF minimization.
tmol uses the work-efficient scan in moderngpu [29], so forward kinematics performs work that is in the number of atoms, with a parallel depth set by the number of nested branches in the kinematic tree rather than by chain length; a single protein chain requires five generations regardless of its size.
Rotamer packing and simulated annealing
Packing is a basic Rosetta operation that finds side-chain conformations optimizing the energy for a given (fixed) backbone. The packing layer in tmol: a) constructs candidate rotamers from pluggable samplers; b) computes a sparse rotamer-pair energy graph using the rotamer scoring mode of the score function; and c) runs a simulated anneal trajectory to find the rotamer assignment minimizing total energy. A PackerTask controls allowed identities and positions. Fixed-sequence repacking and compatible sequence design are implemented. Compiled CPU and CUDA annealers consume the same interaction-graph representation but use device-specific search strategies. Unlike the scoring kernels, which must agree atom pair for atom pair, annealing is a stochastic search: on the GPU many short parallel trajectories reach comparable energies faster than one long trajectory, so the CUDA annealer performs more total work than the CPU annealer while taking less time. The CPU annealer is a faithful reproduction of Rosetta’s standard annealing algorithm [36]: the temperature is lowered from 100 to 0.3 over 20 outer cycles, each of five inner steps per rotamer, followed by a greedy quench from the best assignment found.
The CUDA annealer maps one 32-thread warp to one trajectory. Threads cooperatively score a proposed rotamer substitution; one lane performs the Metropolis decision and broadcasts it across the warp. The default search begins with 500 independently initialized high-temperature trajectories per pose. A short greedy quench provides comparable ranking scores, the best 25% are retained, and each retained state seeds ten lower-temperature trajectories, yielding 1,250 candidates. After a second short quench and 25% retention, 312 trajectories proceed to a full greedy quench. Counter-based Philox [37] random-number streams make the schedule reproducible from the PyTorch CUDA generator state. We do not benchmark the CUDA annealer against Rosetta’s directly. However, two results indicate its equivalence: the energy-function benchmarks above were run on GPU and invoke the packer throughout, and FastRelax energy changes agreed between tmol and PyRosetta within run-to-run variation at every size tested.
Minimization and FastRelax
Rosetta uses a very specific minimization formula: L-BFGS with an Armijo line search [38, 39]. While the use of any torch-compatible minimizer is possible, we have ported this exact minimization strategy to torch. The tmol implementation minimizes every pose in a stack simultaneously but independently: each pose keeps its own L-BFGS history and line search, and converges and stops on its own, so minimizing a batch gives the same result as minimizing each pose separately. The L-BFGS update uses the compact matrix representation of the inverse Hessian [40], so it runs in parallel on the GPU. One small change was made from Rosetta’s default convergence criteria: rather than requiring both gradient magnitude and improvement to be small, tmol requires five consecutive steps with small improvement with no restrictions on gradient magnitude. This shortens some minimization trajectories without increasing energies.
Cartesian and internal coordinate (Torsion-space) minimization are both supported, and both use the same rendered scoring module and kernels. Cartesian minimization optimizes atom coordinates directly. Torsion-space minimization optimizes the selected torsional and rigid-body degrees of freedom : each energy evaluation first passes through the kinematic layer, which rebuilds Cartesian coordinates from by generational segmented scan, and the resulting coordinates are then scored. Because the kinematic layer is itself an autograd operation, whose backward pass accumulates the vectors described above, PyTorch automatically composes with to give . No minimization-specific derivative code is needed.
Finally, fast_relax is Rosetta’s default “refinement” protocol. fast_relax alternates packing and minimization while ramping repulsive and optional constraint weights. Its four default packing/minimization repulsive fractions are 0.040/0.051, 0.265/0.280, 0.559/0.581 and 1.000/1.000, reproducing the Monomer Relax schedule from Maguire et al. 15. It lives in the tmol.relax module as a short Python protocol built directly on the packing and minimization layers described above, so its schedule can be changed by argument and new relax-style protocols can be written in the same way.
Performance benchmarks
We compared tmol with PyRosetta (release 2026.3+releasequarterly) on two tasks using the beta_nov16_cart energy function. The first is a single torsion-space score and gradient evaluation. The second is torsion-space fast-relax with five repeats. Inputs were compact subsets of chain A of PDB 1DP0, from 50 to 800 residues. Hydrogens were placed once by Rosetta, and tmol read these coordinates without further optimization, with both programs started from identical structures. PyRosetta minimized with lbfgs_armijo_nonmonotone, while tmol used its GPU-batched L-BFGS implementation. Both were capped at 200 minimization steps. Although the two protocols are not identical, relax energy changes from the two programs agreed within 5% at every size tested (tmol on average 2% smaller in magnitude).
All timings were run on a 32-core AMD EPYC 9355 processor and H200 NVL GPUs, using PyTorch 2.14.1 with CUDA 13.0. PyRosetta ran on one CPU core. tmol ran on one or 32 CPU cores, and for GPU calculations, one GPU with four host cores. GPU calculations were run with batches of 1, 10 or 100 copies of each structure. Score and gradient times are the median of 20 calls after three warm-up calls; FastRelax times are the median of three runs after one warm-up run. We report throughput as structures processed per second, counting each FastRelax repeat as one step. Note that due to the removal of the “bump check” in packing (see below), tmol considers about 60% more rotamers in relax than PyRosetta.
Differences from Rosetta’s implementation
tmol reproduces the functional forms and parameters of RosettaGenFF13 (beta_nov2016 with gen_bonded), with deliberate changes in two areas. First, count-pair weighting is applied uniformly. Rosetta computes bond separation only between directly bonded residues, so pairs such as and , four bonds apart, receive full weight. It also uses a three-bond rather than four-bond crossover across non-peptide inter-residue bonds. tmol computes shortest bond paths through intermediate blocks and applies a consistent rule for all nonbonded terms: pairs fewer than four bonds apart are excluded, and pairs exactly four bonds apart are scaled by 0.2.
Second, we removed redundant terms and simplified tabulated potentials. Rosetta restrains the Ser, Thr and Tyr hydroxyl hydrogens twice, in both cart_bonded and the hydroxyl-torsion term; tmol restrains them once. Rosetta restrains peptide planarity with impropers centered on N and C, but one of its restraints (–––) is a proper torsion about the – bond that duplicates the term; tmol uses impropers only. The Ramachandran, , , and Dunbrack [41] tables use the same cubic-spline interpolation as Rosetta, except for the Dunbrack chi means and standard deviations, which Rosetta interpolates linearly, while tmol uses cubic-splines. For Ramachandran, , and Dunbrack, these match Rosetta exactly at grid points but differ slightly between them. The term, however, is interpolated at positions off the 0-centered grid points of the other three terms. We thus interpolated the values at the 0-centers and then fit the splines to pass through the interpolated values.
Finally, in packing, we made one small change from Rosetta. When building backbone-dependent rotamers, Rosetta by default applies a “bump check” that discards any candidate rotamer whose repulsive interaction with the surrounding “background” (backbone and non-sampled side chains) exceeds a fixed threshold, before rotamer pair energies are computed. This removes about 40% of candidate rotamers, but it sometimes discards rotamers that would be part of the lowest-energy solution. Because rotamer pair energies are cheaper to compute on the GPU, tmol disables the bump check by default and considers every rotamer during annealing—about 60% more than PyRosetta. The check is still available as an option on the packer task. Energy-function weights were not re-optimized after any of these changes; benchmark performance is unchanged within error (Figure 2b).
Agreement with Rosetta
To compare tmol’s energies with Rosetta’s, we scored a set of high-resolution protein structures with both programs. Starting from a PISCES [42] culled list (X-ray structures at Å resolution, R , pairwise sequence identity, no chain breaks; October 2026), we kept chains of 50–500 residues, additionally requiring R-free , and took the 1,000 most recently deposited chains that extracted cleanly, keeping the first model and highest-occupancy alternate locations for each chain and removing waters, ligands and metals. Hydrogens were added once in PyRosetta. The resulting files were scored without modification (no hydrogen re-optimization) by both Rosetta (beta_nov16_cart) and tmol, summing related Rosetta terms into the matching tmol term (e.g., fa_atr and fa_intra_atr_xover4 for fa_ljatr). Energies are weighted and expressed per residue. For each term we report the Pearson correlation across chains, with a 95% confidence interval from 2,000 bootstrap samples, and the mean and standard deviation of the per-residue difference between the two programs.
Reward-guided design with tmol interface energies
RFD4-Proteina (release checkpoints) designed binders against 24 protein–protein benchmark targets. Reward-guided search used beam search: 16 replicates per target branched into four candidates at denoising steps 30 and 60 (of 60), kept the two highest-reward candidates per replicate and returned 32 designs. Candidates were completed by a rollout and scored without gradients using tmol block-pair energies between binder and target residues. The reward was the number of residue pairs with hbond (hydrogen-bond reward) or lk_bridge (bridge reward), minus 0.5× or 10× the summed pair energy, respectively. Controls were unguided sampling (32 designs) and the best 32 of 128 unguided designs on the plotted quantity (best-of-). All designs were rescored identically with tmol. Reported percentages use criteria fixed independently of the rewards: a design counts as hydrogen bonded when at least five binder–target residue pairs have hbond , and as strongly water bridged when its summed lk_bridge energy over binder–target pairs is . Percentages are per-target means with bootstrap intervals over targets. Designs were refolded with OpenFold21 and judged with the protein-binder criterion (ptm , minimum ipAE , binder RMSD Å).
Energy-function benchmarks
We compared tmol and PyRosetta on benchmarks previously used to develop and validate Rosetta energy functions. From Park et al. 12, we used three tasks. Monomer decoy discrimination (61 proteins) and protein–protein docking decoy discrimination (65 complexes) ask whether the energy function ranks near-native structures below non-native decoys, measured with the Boltzmann-weighted discrimination score of Park et al. 12. Stability (about 1,200 point mutations) compares predicted and experimental changes in folding free energy by Pearson and Spearman correlation. Side-chain-rotamer recovery follows the density-based protocol of Conway and DiMaio [43], on a subset of their benchmark (167 core and 88 interface targets). Side chains are rebuilt by the packer from the backbone alone, and each predicted side chain is compared with an experimental electron density map: a side chain counts as “recovered” when its density correlation falls no more than 0.13 below that of the native conformation and is at least 0.70. Alanine and glycine are excluded, as are positions with maximum side chain B-factor , alternate conformations, possible crystal contacts, or poorly resolved density. Both tmol and PyRosetta predictions are scored by the same PyRosetta density calculation. From Glasscock et al. 18, protein–DNA decoy discrimination (24 complexes) uses the same discrimination score. Following Zhou et al. 19, we used the CASF-2016 protein–ligand set [44] (285 complexes), reporting docking power as the fraction of complexes whose top-ranked pose lies within 2 Å of the crystal pose, and scoring power as the correlation of predicted with experimental binding affinity. In all tasks, both engines relaxed or minimized the same inputs with the same movable residues, using a single-repeat Cartesian FastRelax or, for CASF, a short restrained minimization.
Score-function components and molecular illustrations
Figure 2a groups the implemented score channels by their physical roles. Table S1 gives the complete mapping to code identifiers and documents the representative structures.
| Readable term | Code identifier |
| Amino-acid preferences | |
| Ramachandran backbone preference | rama |
| Peptide omega torsion | omega |
| Dunbrack rotamer probability | dunbrack_rot |
| Dunbrack rotamer deviation | dunbrack_rotdev |
| Dunbrack semi-rotameric term | dunbrack_semirot |
| Amino-acid reference energy | ref |
| Disulfide geometry | disulfide |
| Covalent geometry | |
Cartesian bonded (cart_bonded) | |
| Bond lengths | cart_lengths |
| Bond angles | cart_angles |
| Bond torsions | cart_torsions |
| Improper torsions | cart_impropers |
| Hydroxyl torsions | cart_hxltorsions |
Generic bonded (gen_bonded) | gen_torsions |
| Nonbonded and hydration | |
| Lennard–Jones attraction | fa_ljatr |
| Lennard–Jones repulsion | fa_ljrep |
| Lazaridis–Karplus solvation | fa_lk |
| Electrostatics | fa_elec |
| Hydrogen bonding | hbond |
| Directional implicit hydration | lk_ball |
| Isotropic implicit hydration | lk_ball_iso |
| Coupled water-bridge term | lk_bridge |
| Uncoupled water-bridge term | lk_bridge_uncpl |
| DNA / RNA | |
| Nucleic-acid torsions | na_torsion |
| Nucleic-acid torsional wells | na_torsion_well |
| Metals and restraints | |
| Metal coordination geometry | metal_coordination |
| User-defined constraints | constraint |
Table S1. Score channels represented in Figure 2a. All 26 identifiers in tmol/score/_score_types.py are listed; n_score_types is a count sentinel, not an energy term. The inspected checkout and benchmark source agree on this list.
Figure 1d groups cart_lengths, cart_angles, cart_torsions and cart_impropers as cart_bonded; cart_hxltorsions is plotted separately as hydroxyl torsion. Its gen_bonded comparison uses gen_torsions. These grouped comparison labels are not additional ScoreType identifiers.
References
- [25]Kunzmann, P. & Hamacher, K. Biotite: a unifying open source computational biology framework in Python. BMC Bioinformatics 19, 346 (2018).
- [26]Ropp, P. J., Kaminsky, J. C., Yablonski, S. & Durrant, J. D. Dimorphite-DL: an open-source program for enumerating the ionization states of drug-like small molecules. J. Cheminform. 11, 14 (2019).
- [27]Halgren, T. A. Merck molecular force field. I. Basis, form, scope, parameterization, and performance of MMFF94. J. Comput. Chem. 17, 490–519 (1996).doi.org/10.1002/(sici)1096-987x(199604)17:5/6<490::aid-jcc1>3.0.co;2-p
- [28]O’Boyle, N. M. et al. Open Babel: An open chemical toolbox. J. Cheminform. 3, 33 (2011).DOI
- [29]Baxter, S. moderngpu 2.0 (2016). URL https://github.com/moderngpu/moderngpu/wiki.
- [30]Eigen developers. Eigen Tensors. URL https://eigen.tuxfamily.org/dox/unsupported/eigen_tensors.html. Accessed 10 October 2026.
- [31]Lazaridis, T. & Karplus, M. Effective energy function for proteins in solution. Proteins 35, 133–152 (1999).pubmed.ncbi.nlm.nih.gov/10223287
- [32]Kahan, W. Pracniques: Further remarks on reducing truncation errors. Commun. ACM 8, 40 (1965).DOI
- [33]Wang, C., Bradley, P. & Baker, D. Protein–protein docking with backbone flexibility. J. Mol. Biol. 373, 503–519 (2007).pubmed.ncbi.nlm.nih.gov/17825317
- [34]Harris, M., Sengupta, S. & Owens, J. D. Parallel prefix sum (scan) with CUDA in GPU Gems 3 (ed. Nguyen, H.) 851–876 (Addison-Wesley, 2007).
- [35]Abe, H., Braun, W., Noguti, T. & Gō, N. Rapid calculation of first and second derivatives of conformational energy with respect to dihedral angles for proteins: General recurrent equations. Comput. Chem. 8, 239–247 (1984).
- [36]Kuhlman, B. & Baker, D. Native protein sequences are close to optimal for their structures. Proc. Natl Acad. Sci. USA 97, 10383–10388 (2000).pubmed.ncbi.nlm.nih.gov/10984534
- [37]Salmon, J. K., Moraes, M. A., Dror, R. O. & Shaw, D. E. Parallel random numbers: as easy as 1, 2, 3. in Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis (SC 11) (2011).
- [38]Liu, D. C. & Nocedal, J. On the limited memory BFGS method for large scale optimization. Math. Program. 45, 503–528 (1989).
- [39]Armijo, L. Minimization of functions having Lipschitz continuous first partial derivatives. Pac. J. Math. 16, 1–3 (1966).DOI
- [40]Byrd, R. H., Nocedal, J. & Schnabel, R. B. Representations of quasi-Newton matrices and their use in limited memory methods. Math. Program. 63, 129–156 (1994).
- [41]Shapovalov, M. V. & Dunbrack, J., Roland L. A smoothed backbone-dependent rotamer library for proteins derived from adaptive kernel density estimates and regressions. Structure 19, 844–858 (2011).DOI
- [42]Wang, G. & Dunbrack, J., Roland L. PISCES: a protein sequence culling server. Bioinformatics 19, 1589–1591 (2003).pubmed.ncbi.nlm.nih.gov/12912846
- [43]Conway, P. & DiMaio, F. Improving hybrid statistical and physical forcefields through local structure enumeration. Protein Sci. 25, 1525–1534 (2016).DOI
- [44]Su, M. et al. Comparative assessment of scoring functions: the CASF-2016 update. J. Chem. Inf. Model. 59, 895–913 (2019).DOI
