Manuscript Offprint
arXiv:2610.30388A Transformer-based Approach for Real-time Multi-agent Path Planning with Varying Initial/Final Conditions
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
QIAN ZHANG, SHANQING LIU, JEROME DARBON, AND GEORGE KARNIADAKIS
ABSTRACT. We address the problem of real-time multi-agent path planning under prescribed initial and final configurations, formulated as a high-dimensional optimal control problem subject to inter-agent collision avoidance and obstacle constraints. Classical solvers based on the Hamilton–Jacobi–Bellman equation or Pontryagin's maximum principle (PMP) become computationally intractable as the number of agents grows, due to the curse of dimensionality and the non-convexity introduced by interaction constraints. We propose OCFformer, a transformer-based neural network that parameterizes the inverse of a coordinate transformation mapping a simple, analytically tractable latent space, in which agents evolve independently under a decoupled Hamiltonian, to the physical space of the coupled, interacting system. The model is trained by minimizing a physics-informed loss comprising the Hamiltonian ODE residual from the PMP and a boundary matching term, without requiring pre-computed trajectory data. The self-attention mechanism endows OCFformer with permutation equivariance over agents, a structural symmetry that prior symplectic network approaches do not natively enforce. When trained on a distribution of boundary conditions, the amortized OCFformer produces near-optimal trajectories for unseen initial and final configurations in a single forward pass ( 220 ms), enabling real-time inference without retraining. We further introduce a lightweight transfer learning framework that adapts a pretrained OCFformer to out-of-distribution perturbations in seconds via L-BFGS fine-tuning. Numerical experiments on two- and three-dimensional multi-agent navigation with up to 128 agents demonstrate the scalability and efficiency of the proposed approach.
1. INTRODUCTION
1.1. Motivation and Context. Optimal control problems arise in a wide range of applications, from robotics and autonomous navigation to multi-agent coordination and financial optimization. The goal is to steer a dynamical system from prescribed initial conditions to a desired final state while minimizing a cost functional. Two complementary theoretical frameworks underpin numerical approaches to these problems: Bellman's dynamic programming principle [Bel57], which characterizes the value function as the unique viscosity solution of the Hamilton–Jacobi–Bellman (HJB) equation, and Pontryagin's maximum principle (PMP) [AS13, Tré05], which gives first-order necessary optimality conditions through the introduction of a co-state variable. Despite their theoretical power, both frameworks face severe computational challenges as the state dimension grows. Grid-based methods for the HJB equation suffer from the curse of dimensionality [Bel57]: their complexity scales exponentially with the number of state variables, making them infeasible beyond a few dimensions. Indirect shooting methods based on the PMP avoid explicit gridding of the state space but require repeated numerical integration of the Hamiltonian system and are highly
Division of Applied Mathematics, Brown University, Providence, RI 02912, USA.
QIAN ZHANG, SHANQING LIU, JEROME DARBON, AND GEORGE KARNIADAKIS
sensitive to the initial guess of the co-state, often failing to converge without a careful initialization [Tré05]. In multi-agent path planning, where M agents with individual state dimension yield a joint state of dimension , these difficulties are compounded by the need to enforce inter-agent collision avoidance constraints that introduce non-convexity and long-range coupling among the agents, rendering classical solvers impractical for real-time use at scale.
To overcome these scalability limits, deep learning has motivated mesh-free methods that parametrize solutions directly with neural networks, avoiding explicit state-space discretization. Building on early residual-based parametrizations of differential equations [LLF98], high-dimensional extensions such as the Deep Ritz method [EY18] and backward-stochastic-differential-equation reformulations [HJE18] scaled these ideas to hundreds of dimensions, and physics-informed neural networks (PINNs) [RPK19] unified them by encoding governing equations and boundary conditions as soft loss constraints, a paradigm that has since grown into the broader field of scientific machine learning [ZSX+22, ZKKS24, TZK+24, ZWK+25, ZKK25, KZGK26, WZK26, ZK26]. In the optimal control setting, the PMP's Hamiltonian ODE system provides a natural PINN residual; SympOCNet [MZDK22] pioneered this for multi-agent path planning by pairing a symplectic architecture [JZZ+20] with PINN training, later extended to time-dependent and non-convex settings [ZWL+24]. However, these architectures process agents in a fixed sequential order and impose a possibly-unnecessary symplectic constraint. Neither property reflects the permutation symmetry inherent to multi-agent problems.
Beyond the symplectic-PINN line of work, several alternative paradigms merit mention: optimal-transport-based continuous normalizing flows for mean-field control [OWFLR21], adaptive deep learning for the HJB equation [NZGK21], and Hopf–Lax representation formulas that solve Hamilton–Jacobi equations without spatial gridding [DO16, LCO18]. In the multi-robot community, graph neural networks [LGRP20] target decentralized collision avoidance with a similar permutation-equivariance motivation but distributed rather than centralized optimality. Classical planners such as ORCA [VDBGLM11], conflict-based search [SSFS15], and sequential convex programming [ASD12] remain practical workhorses that trade global optimality for tractability.
The transformer architecture [VSP 17] directly addresses this gap. Its self-attention mechanism computes pairwise interactions among all sequence elements simultaneously, capturing long-range dependencies and permutation symmetries that convolutional or recurrent architectures handle only approximately, and it is theoretically a universal approximator of continuous, permutation-equivariant sequence-to-sequence functions [YBR 19], consistent with its empirical dominance across NLP [DCLT19, BMR 20] and vision [DBK 21]. This permutation-equivariant structure is especially relevant for multi-agent problems, where agents are interchangeable and a solution method should be invariant to their indexing, allowing a transformer to learn collective, collision-avoidance behaviors that generalize across agent configurations without a fixed ordering.
1.2. Contribution. In this work we propose OCFormer, a transformer-based framework that addresses multi-agent optimal control by combining the structural inductive biases of attention with physics-informed training. The central idea is to learn a parameterized inverse coordinate transformation that maps analytically tractable latent trajectories, corresponding to non-interacting agents with a decoupled Hamiltonian, to the physical trajectories of the interacting system. OCFormer is built from alternating transformer blocks that mirror the leapfrog structure of Störmer–Verlet integration [JZZ 20], and is trained by minimizing a physics-informed loss comprising the Hamiltonian ODE residual from the PMP together with a boundary matching term enforcing prescribed initial and final configurations. Unlike SympOCNet [MZDK22], OCFormer is not constrained to be symplectic; instead, it achieves permutation equivariance through the self-attention mechanism, which is essential for generalization over varying agent counts and configurations. Once trained on a distribution of boundary conditions, OCFormer infers near-optimal trajectories for unseen initial and final configurations in a single forward pass ( 220 ms), enabling real-time multi-agent path planning. We further develop a transfer learning strategy that efficiently adapts a pretrained OCFormer to perturbed boundary conditions, avoiding costly retraining from scratch. The framework is validated on two- and three-dimensional multi-agent navigation benchmarks, demonstrating competitive trajectory quality and significantly reduced inference time compared to existing methods.
2.1. Problem setup. We are interested in a class of multi-agent path planning problems. A similar problem has been explored by the authors in [ZWL 24]. Here, we give a brief overview of the setup. We consider a system consists of elementary sub-systems in interaction, and evolves in time horizon 0 to . The state and the control of each sub-system have dimension and , respectively, leading to a concatenated state and a concatenated control , for every . Each sub-system has its individual potential energy functional, , associated with the state , and individual kinetic energy functional, , associated with control . Moreover, we assume that the individual kinetic energy functional is convex w.r.t . Each sub-system is governed by a dynamical system of the form
(1)
i.e., the individual dynamical system is linear w.r.t control . The interaction (collision and obstacle avoidance) between the sub-systems will be represented by , that imposes a constraint on the state variable such that
(2)
This constraint can be converted to the Lagrangian of the system (see details in [MZDK22], and a variant in [ZWL 24]), by introducing a soft penalty function , defined by
(3a)
QIAN ZHANG, SHANQING LIU, JEROME DARBON, AND GEORGE KARNIADAKIS

FIGURE 1. Flowchart of the OCFormer framework. For a pair of prescribed initial and terminal configurations, boundary data are first encoded into latent variables , which serve as the input to the transformer-based inverse coordinate map . The network predicts the physical position and momentum trajectories over the time grid without solving an ODE at inference time. During training, the predicted trajectories are differentiated with respect to time and evaluated in the Hamiltonian system so that the model satisfies the physics-informed residual loss associated with Pontryagin's maximum principle, while a boundary matching term enforces the initial and final constraints. The total loss is minimized over the network parameters, yielding a model that directly maps varying boundary conditions to feasible multi-agent trajectories in real time.
where for every , is defined by
(3b)
The two branches of (3b) are designed to meet at with continuity: both the value and the derivative match, ensuring smooth gradients during optimization. The max over constraints in (3a) penalizes only the most violated constraint at each collocation point, which makes the barrier numerically tractable with small (we use , throughout). We note two consequences: (i) the log-barrier is not Lipschitz continuous at the constraint boundary, so the standing regularity assumptions on the Lagrangian in Appendix A must be understood to hold on the interior of the feasible set; (ii) the -penalized solution is biased away from the exact constrained optimum, and the values of and control the cost–feasibility trade-off. In this way, the reduced Lagrangian of the system is given by the sum of the potential and kinetic energies of the individual sub-systems, together with the penalty term (3). Moreover, the initial and final conditions of the system are constrained to two sets, and , which are compact convex subsets of , i.e.,
(4)
2.2. From Maximum Principle to Hamiltonian ODE system. In what follows, we denote
We seek a trajectory , that minimizes the total action functional of the system, while satisfying the initial/final constraints (4) and state constraints (2). By employing the soft penalty method as in (3) for the state constraints, this problem can be reformulated within the optimal control framework introduced in (24) (Appendix A), by setting
(5)
for every in (24a) and (24b), and be the identity map with
Let us denote
(6)
where denotes the Legendre-Fenchel transformation of , and we use the property that is linear w.r.t . For sake of presentation, we consider are two point sets respectively, and the extension to general sets is straightforward. In that case, following the maximum principle (25) (Appendix A), we have that the optimal trajectory together with the co-state satisfy the following condition: for every ,
(7a)
with respect to the initial, final conditions
(7b)
and is taking the value such that the maximum in (6) is obtained. Notice that, since the initial and final conditions are two points, and the terminal cost is zero, there are no constraints on and . Our focus in the remainder of this paper is to solve the system (7) associated with the multi-agent path planning optimal control problems.
QIAN ZHANG, SHANQING LIU, JEROME DARBON, AND GEORGE KARNIADAKIS

FIGURE 2. Coordinate-transformation view of the proposed trajectory representation. The forward map sends the physical trajectory pair to a simpler latent trajectory pair associated with a decoupled Hamiltonian system, while the inverse map reconstructs the interacting multi-agent trajectories in physical space.
3. THE OCFORMER FRAMEWORK
3.1. Trajectory Representation by Coordinate Transformation in Latent Space. In the context of multi-agent path planning problems, the individual potential energy function and the individual kinetic energy function are typically well-behaved convex functions, often of quadratic form. Moreover, the state and control dimensions and of the sub-systems are generally small, typically equal to 2 or 3 in practical physical scenarios. Consequently, (one of) the principal challenges arises from the interactions among the sub-systems, represented by h in the system's Lagrangian and converted to the Lagrangian through the soft penalty term , which effectively serves as an “interaction” potential energy. These interactions render the overall system non-convex in the dimension .
The key idea of our method is employing a change of variable operator, , in the physical space, transforming the trajectory functional satisfying the (PMP) system (7) of the original interaction system, to a “simpler” one (see Figure 2), that is,
(8)
This trajectory is simpler in the sense that it corresponds to the solution of a PMP system consisting of M non-interacting sub-systems, i.e., a system having same time horizon, state/control space, dynamics, initial/final constraints as the original one, but with Lagrangian taking the form
(9)
Thanks to the convexity and low dimensionality, the system (7) with Lagrangian (9) can be easily solved, by solving the low dimensional sub-systems separately. We call the trajectory functional in latent space. To be more precise, the two maps , are the solutions of the following system: for every
(10a)
where we match the initial, final conditions of to , that is
(10b)
and the Hamiltonian is defined by
(10c)
3.2. Parameterize the Inverse Operator by Transformer Based Neural Network
Assumption 1. There exists a diffeomorphism such that the latent trajectory satisfies the decoupled Hamiltonian system (10) with Lagrangian (9). Although the existence of such a map is not guaranteed in full generality and requires further study, this assumption is the working hypothesis that motivates the neural parameterization of .
Remark 1 (Straight-line latent trajectories and the residual inductive bias). For the specific problems considered in this work, the dynamics are and the individual kinetic energy is quadratic, so . Moreover, , , and the initial/final constraints fix , as singletons. The latent system (10) then reduces to a constant-velocity straight line:
Consequently, the ansatz (14) collapses to a neural parameterization of a curve in t,
where denotes the learned correction (the non-identity part of ). The residual structure means the ansatz is initialized exactly at the non-interacting optimal solution, the straight-line, constant-velocity paths that solve the unconstrained problem, and learns the collision-avoiding correction on top. This is a strong inductive bias: the network only needs to model the deviation from the trivial solution. We also note that in the per-instance training regime, the network only ever sees a one-dimensional line segment of its input domain (the set ), which explains both why the fit is easy and why it does not directly generalize to new boundary conditions.
In this section, we approximate and parameterize the inverse of the operator by , where represents the unknown parameters to be learned through a transformer-based architecture.
Definition 1. The OCFormer is defined as the following neural network:
(11)
where I is the identity mapping, are tokenwise deembedding MLPs, is the tokenwise embedding layer, are the transformer blocks defined below in terms of the standard self-attention operation [VSP 17]:
(12)
QIAN ZHANG, SHANQING LIU, JEROME DARBON, AND GEORGE KARNIADAKIS
(13)
for every , where is the embedding dimension. We use for numerical examples.
To accommodate the sequence-to-sequence nature, the inputs and are first reshaped into (treating each of the agents as a token of dimension ) and the outputs are reshaped back into . The details of the OCFformer structure are illustrated in Figure 3.

FIGURE 3. Architecture of OCFformer. are first reshaped into . are tokenwise embedding layers, which are applied on the last axis of reshaped input. . Partial transformer blocks and are depicted by the dashed rounded rectangle. is identity mapping in . ( ) are the transformer blocks. are tokenwise deembedding MLPs, whose output are flattened back into . is the identity mapping in , serving as residual connection.
Remark 2 (Symplecticity, permutation equivariance, and limitations). Unlike SympOCNet[MZDK22], OCFformer is not constrained to be symplectic and is only invertible in the latent space. As shown in Proposition 1, the PINN loss directly enforces the Hamiltonian dynamics, making a structural symplectic guarantee unnecessary.
OCFormer is permutation equivariant over agents: any permutation of the agent indices applied to the input produces the same permutation of the output. This follows directly from the architecture: the tokenwise embeddings and deembedding MLPs are applied independently to each agent via , the self-attention mechanism in is permutation-equivariant by construction, and the residual connection I preserves equivariance. Formally, if denotes the permutation matrix corresponding to , then .
A notable failure mode arises from this design: with no positional encoding, two agents that share identical latent inputs produce identical outputs and can never be separated. This symmetry-breaking limitation is particularly relevant for the symmetric benchmark in §5, where symmetry breaking must be driven by random weight initialization alone. For problems where agents are not interchangeable (e.g. the 3D room with role-differentiated targets in §5), we use PositionalOCFormer, a variant with per-agent weight matrices that deliberately breaks permutation equivariance.
3.3. The OCFormer Method and Training procedure. Let us recall that the state and co-state functionals are obtained by applying the inverse of the coordinate transformation operator , to the latent state and co-state functionals . Approximating this inverse of transformation by , one obtain an approximation of the state and co-state functionals
(14)
which depends on the learnable parameters . Then, one can compute the derivative of w.r.t s by
(15)
where Jac denotes the Jacobian matrix. In order to learn the parameters , we construct and minimize a physics-informed loss function of . In particular, a set of collocation points is randomly sampled in . Then, together with can be computed by numerically solving the latent system (10). The physics-informed loss function is then defined by
(16a)
where
(16b)
and
(16c)
where denotes the first components of . For 3D experiments we additionally include a velocity bound penalty
(16d)
where is the finite-difference velocity computed from the predicted trajectory and , which enforces a soft box constraint on the control magnitude. For the ball-3D problem we further add an explicit obstacle penetration penalty
(16e)
where is the signed squared-distance constraint for the spherical obstacle; this term directly penalizes penetration at collocation points, supplementing the log-barrier inside .
Proposition 1 (Zero-loss implies extremality). If on a dense set of collocation points and , then, assuming the neural ansatz is continuously differentiable, the trajectory satisfies the Hamiltonian ODE system (7) on and is therefore a normal extremal of the penalized problem. In practice, the loss is driven
QIAN ZHANG, SHANQING LIU, JEROME DARBON, AND GEORGE KARNIADAKIS
to a small but nonzero value; the proposition guarantees that driving it toward zero yields an increasingly accurate approximation of an extremal. This holds regardless of whether is symplectic, so the symplectic constraint of prior work [MZDK22] can be dropped.
A full pseudocode listing of the training procedure sketched above is given in Algorithm 1, Appendix C.
4. A REAL TIME LEARNING FRAMEWORK FOR PERTURBATION ON INITIAL AND TERMINAL CONDITIONS
4.1. Perturbation on Initial and Terminal Conditions. We introduce the following optimal control problem with perturbation on initial and terminal conditions:
(17)
where are perturbations on the initial and terminal conditions. If the perturbation is structurally simple (e.g., a rigid body transformation) or sufficiently small, solving the entire optimal control problem from scratch is computationally redundant, as the complex multi-agent collision avoidance logic remains largely consistent. To enable real-time path planning under varying conditions, we propose a transfer learning framework that exploits a pre-trained reference model.
4.2. Transfer Learning Framework. Suppose we have a base transformer model, , already trained on a reference setup (unperturbed problem). We freeze its parameters and introduce lightweight, trainable coordinate transformation modules before and after the base model:
(18)
where is a trainable global affine transformation and is a trainable per-agent bounded correction, defined below. Depending on the type of perturbation, one or both modules are activated.
Affine module . and act on the phase space coordinates as , with a learnable matrix applied to both position and momentum, and a learnable translation vector applied only to position. The residual form initializes at the identity at . We note that is a general linear transformation, not constrained to , and and are trained independently without enforcing ; in practice, the two modules learn approximately inverse transformations from the data. Because the total parameter count is (e.g., 8 parameters for ), the network adapts rapidly via L-BFGS, typically converging in under 100 iterations.
Correction module . and apply per-agent, per-dimension corrections, parameterized by learnable parameters (one scalar per agent per spatial dimension), acting as , where the sine nonlinearity bounds each correction component to . The parameter (set to 0.04 in our experiments, giving ) controls the maximum correction magnitude; it is chosen independently of the perturbation magnitude and provides a conservative envelope that accommodates the required trajectory adjustments. and are time-independent parameters. The time-varying correction to the trajectory is generated by perturbing the latent input , which then propagates nonlinearly through the frozen base model \phi^\theta^*. The forward correction adds a residual adjustment at the output. Both modules together contain trainable parameters, which is negligible compared to the frozen base model.
Two operating regimes. When the initial and terminal conditions are transformed by an element of the SE(2) or SE(3) group (i.e., a global rotation and translation), the global affine module already provides the correct symmetry class, so we set (equivalently ) and train only . When boundary conditions are instead subjected to random, unstructured noise, a global affine transformation alone may not provide sufficient degrees of freedom to satisfy all local constraints, so we additionally activate to supply the missing per-agent corrections. In both regimes, the new transfer parameters are optimized using the original physics-informed loss function (16). Training is performed on boundary data within a room of size , which is twice the linear dimension of the room used for the base model. This enlarged transfer domain ensures that the adapted trajectories remain well within the feasible region during optimization. The lightweight parameterization accelerates convergence compared to training from scratch, typically requiring only seconds of L-BFGS fine-tuning.
5. NUMERICAL EXPERIMENTS
5.1. Optimal Path Planning for Multiple Drones in a 2D Room. In this section, we consider the path planning problem for multiple drones in a 2D room. The drones are expected to reach the target positions at the same time without collision. The room is a square . The radius of the drones are . The time horizon is . The problem can be formulated as
(19)
5.1.1. Symmetry Setup. We apply the base OCFormer (permutation-equivariant) to drones. For , all drones are placed on a single circle of radius 0.5. For , drones are distributed across two concentric circles (16 agents each, radii 0.33 and 0.5). For , two concentric circles with 32 agents each (radii 0.33, 0.5) are used, with drone radius . For , four concentric circles with 32 agents each (radii 0.35, 0.40, 0.45, 0.50) are used with . In all cases targets are the antipodal points of the initial positions.
QIAN ZHANG, SHANQING LIU, JEROME DARBON, AND GEORGE KARNIADAKIS*
TABLE 1. Quantitative results for the 2D room symmetry setup, and direct comparison against SympOCNet (JAX implementation) on the identical circle benchmarks, using the same boundary data, parameters , room size, , , ), and training budget (100k–500k Adam + L-BFGS on an NVIDIA RTX A6000). is the analytic lower bound (unconstrained optimum). Cost is evaluated via trapezoidal integration of ; Gap is relative to . SympOCNet was not evaluated at . For every configuration, OCFformer's fine-grid constraint minimum is positive, in the narrow range , confirming collision-free trajectories throughout.
| M | Layout | r | OCFormer | Gap | SympOCNet | Feasible? | |
|---|---|---|---|---|---|---|---|
| 4 | 1 × 4 | 0.02 | 0.200 | 0.2003 | 0.2% | 0.2001 | Yes |
| 8 | 1 × 8 | 0.02 | 0.400 | 0.4036 | 0.9% | 0.4046 | Yes |
| 16 | 1 × 16 | 0.02 | 0.800 | 0.8307 | 3.8% | 0.8345 | Yes |
| 32 | 2 × 16 | 0.02 | 1.156 | 1.2531 | 8.4% | 1.4413 | Yes |
| 64 | 2 × 32 | 0.01 | 2.297 | 2.448 | 6.6% | — | — |
| 128 | 4 × 32 | 0.01 | 4.704 | 5.1424 | 9.3% | No |
The optimality gap increases with agent density but remains under for all cases, and for the OCFformer cost is within of the true optimum obtained via pseudospectral direct transcription (NLP ground truth). A seed-sensitivity study across 5 random seeds for yields cost (mean std), confirming stability. For , OCFformer and SympOCNet achieve near-identical costs, confirming that OCFformer matches the state of the art on small problems. At , OCFformer reduces the cost by relative to SympOCNet, and at , OCFformer converges to a feasible solution while SympOCNet fails to converge. We attribute this advantage to the permutation-equivariant attention mechanism, which shares parameters across agents and provides a better-conditioned optimization landscape at larger , compared to SympOCNet's fixed-ordering gradient modules.



FIGURE 4. Predicted trajectories at for drones, the largest and most demanding configuration in Table 1. Drones shown as colored circles with paths as gray curves.
5.1.2. Symmetry Setup with Rigid Body Transformation. The running cost , the pairwise distance constraints, and the free dynamics are all invariant under simultaneous rotation and translation of all agent coordinates (the group). Consequently, if
SympOCNet did not converge for M = 128; the best cost achieved was 13.3 with constraint violation -0.002, compared to OCFformer's 5.14 with constraint .
is the optimal trajectory for the reference boundary conditions, then is the exact optimal solution for the transformed problem (20). We use this analytically tractable setting as a verification experiment: the rigid-body transfer method should recover the known exact solution without error. The problem can be formulated as
(20)
where
(21)
are the rotation matrix and translation vector respectively, are the initial and terminal positions of the drones in the reference symmetric setup. We apply the rigid-body transfer method to the cases with drones, where the base OCFormer is trained with the reference setup. The affine module uses a general matrix (not constrained to ) and the forward and inverse modules are trained independently, providing additional flexibility at the cost of not strictly enforcing . We report the trajectory error against the exact solution . The learned affine parameters recover the exact transformation to within numerical precision (trajectory error ), confirming that the transfer framework correctly handles the SE(2)-invariant case.
5.1.3. Random Perturbation on Initial Conditions. We perturb the initial conditions by adding a uniformly distributed random noise to the initial positions of the drones. The perturbation magnitude is and the target positions are the antipodal points of the unperturbed initial positions. Unlike the SE(2) case, the resulting boundary conditions are not related by any global symmetry transformation, so no closed-form solution exists; the perturbations are local and unstructured, so the new problem cannot be matched by a single global rotation or translation, which motivates the addition of bounded correction layers on top of the pre-trained base model. The perturbed initial and prescribed terminal configurations are shown in panels (a) and (d) of Figure 5 below. We apply the random-perturbation transfer method to the cases with drones. The results are depicted in Figure 5.
QIAN ZHANG, SHANQING LIU, JEROME DARBON, AND GEORGE KARNIADAKIS*

(a)
(b)
(c)
(d)
FIGURE 5. Predicted multi-agent trajectories for the random-perturbation experiment with drones at times from left to right. Starting from the perturbed initial condition, the transferred model generates collision-free paths that progressively reorganize the swarm toward the prescribed terminal arrangement. The intermediate snapshots show that the learned corrections adapt the reference solution while preserving the overall interaction structure encoded by the original OCFformer.
Across 100 independent random-perturbation trials, fine-tuning consistently reaches a low residual loss (), the trajectory cost concentrates around 1.26, and the constraint minimum remains strictly positive throughout (), confirming that the transfer learning framework reliably produces feasible, near-optimal solutions under random unstructured perturbations.
5.2. Amortized OCFformer: Training on a Distribution of Boundary Conditions. The per-instance training in §5.1.1 solves one pair of boundary conditions at a time. We now demonstrate that OCFformer can be amortized: trained on a distribution of boundary conditions and evaluated zero-shot on unseen pairs, without any architectural change. The key observation is that the latent pair is a bijective encoding of : given boundary conditions, the straight-line latent trajectory is computed analytically and fed to the same OCFformer architecture. Amortization therefore requires only a batched training loop: at each iteration we sample boundary pairs, build the straight-line latent for each, and average the PINN and boundary losses over the batch.
We train on 100 boundary pairs generated by applying random 2D rotations (angles uniformly drawn from ) to the and antipodal circle configurations, and test zero-shot on 20 held-out rotation angles. Training uses the same Adam + L-BFGS pipeline as Algorithm 1, with batch size . Results are reported in Table 2.
TABLE 2. Zero-shot amortized inference results. Trained on 100 rotated boundary pairs, tested on 20 held-out rotations. Inference time is the wall-clock time for a single forward pass (JIT-compiled, averaged over 100 runs).
| M | Test cost (mean ± std) | Gap vs. | Feasibility | Inference (ms) |
|---|---|---|---|---|
| 8 | 1.3% | 100% | ||
| 16 | 5.0% | 75% |
For M = 8, the amortized model achieves near-perfect zero-shot generalization: trajectories for all 20 held-out boundary pairs are collision-free, and the cost is within 1.3% of the analytic lower bound. For M = 16, the cost gap increases to 5.0% and feasibility drops to 75%, indicating that the denser agent configuration pushes the limits of the current training setup. Inference requires a single forward pass through OCFformer, taking approximately 220 ms on an NVIDIA RTX A6000 regardless of M. This is three orders of magnitude faster than per-instance training (~20 minutes for Adam + L-BFGS) and directly substantiates the “real-time” label for in-distribution boundary conditions.
5.3. Path Planning for Multiple Drones in a 3D Room. In this section, we consider the path planning problem for multiple drones in a 3D room. The drones are expected to reach the target positions at the same time without collision. The room is a box with two internal axis-aligned barrier obstacles (positioned as specified in the code release). The radius of the drones is and the time horizon is . Unlike the symmetric 2D circle setup, the 3D room has fixed geometry with role-differentiated start and target positions, so the agents are not interchangeable under permutation. We therefore use PositionalOCFormer, a variant of OCFformer in which the tokenwise embeddings and decoders carry per-agent weights (via PositionalLinear layers with parameters ), explicitly breaking permutation equivariance in favor of agent-specific representations. The problem can be formulated as
(22)
where the box constraint is enforced through the penalty function together with the inter-agent collision constraint. We apply the PositionalOCFormer to the cases with drones. The results are depicted in Figure 6.
QIAN ZHANG, SHANQING LIU, JEROME DARBON, AND GEORGE KARNIADAKIS

(a)
(b)
(c)
(d)
FIGURE 6. Predicted trajectories for the 3D room experiment with n = 100 drones at times from left to right. The snapshots illustrate how the learned model coordinates a large collection of agents in a confined three-dimensional domain, moving them from their initial configuration to the terminal one while maintaining collision-free motion throughout the room. The intermediate frames highlight the scalability of OCFormer to high-dimensional multi-agent path-planning problems.
5.4. Ball 3D Example. In this section, we consider the path planning problem for multiple agents navigating around a spherical obstacle in 3D space. The agents are expected to reach the target positions at the same time without collision and while avoiding the ball-shaped obstacle. The problem can be formulated as
(23)
where is the center of the spherical obstacle and is its radius, with time horizon . We apply OCFormer to the cases with and drones. The results of drones are depicted in Figure 7.

(a)
(b)
(c)
(d)
FIGURE 7. Predicted trajectories for the 3D ball-obstacle experiment at times from left to right. The figure shows the agents moving from their initial to terminal positions while simultaneously avoiding pairwise collisions and steering around the spherical obstacle. The intermediate configurations make clear that the learned dynamics capture both inter-agent avoidance and obstacle-avoidance behavior in a genuinely three-dimensional setting.
6. CONCLUSION AND FUTURE WORK
We have presented OCFformer, a transformer-based neural network for multi-agent optimal control that parameterizes the inverse of a coordinate transformation from a decoupled latent space to the physical interacting system. Trained with a physics-informed loss combining Hamiltonian ODE residuals and boundary matching, OCFformer solves the two-point boundary value problem for fixed initial and final configurations without requiring pre-computed trajectory data. A lightweight transfer-learning framework adapts a pretrained model to rigid-body transformations and random perturbations of the boundary conditions, requiring only seconds of L-BFGS fine-tuning rather than full retraining.
Our numerical experiments demonstrate that OCFformer produces collision-free trajectories on 2D and 3D multi-agent benchmarks with up to 128 agents, achieving costs within a few percent of rigorous lower bounds. The permutation-equivariant architecture provides a useful inductive bias for symmetric problems, while its positional variant handles asymmetric settings.
The amortized OCFformer demonstrated in §5.2 confirms that zero-shot generalization is achievable with no architectural change, but the current training is limited to rotated versions of a fixed configuration. Scaling amortized training to broader distributions (e.g., arbitrary start/goal pairs, varying agent counts) and improving feasibility at higher densities are natural next steps. Other directions include development of a symplecticity-preserving OCFformer variant, extension to general nonlinear dynamics beyond the current setting and integration with feedback control for online replanning.
REFERENCES
[AS13] Andrei A Agrachev and Yuri Sachkov. Control theory from the geometric viewpoint, volume 87. Springer Science & Business Media, 2013.
[ASD12] Federico Augugliaro, Angela P Schoellig, and Raffaello D'Andrea. Generation of collision-free trajectories for a quadrocopter fleet: A sequential convex programming approach. In 2012 IEEE/RSJ International Conference on Intelligent Robots and Systems, pages 1917–1922. IEEE, 2012.
QIAN ZHANG, SHANQING LIU, JEROME DARBON, AND GEORGE KARNIADAKIS
[Bel57] Richard Bellman. Dynamic Programming. Princeton University Press, Princeton, NJ, 1957.
[BMR 20] Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. Language models are few-shot learners. Advances in Neural Information Processing Systems, 33:1877–1901, 2020.
[DBK 21] Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, et al. An image is worth words: Transformers for image recognition at scale. In International Conference on Learning Representations, 2021.
[DCLT19] Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. BERT: Pre-training of deep bidirectional transformers for language understanding. In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 4171–4186. Association for Computational Linguistics, 2019.
[DO16] Jérôme Darbon and Stanley Osher. Algorithms for overcoming the curse of dimensionality for certain Hamilton–Jacobi equations arising in control theory and elsewhere. Research in the Mathematical Sciences, 3(1):19, 2016.
[EY18] Weinan E and Bing Yu. The deep Ritz method: A deep learning-based numerical algorithm for solving variational problems. Communications in Mathematics and Statistics, 6(1):1–12, 2018.
[HJE18] Jiequn Han, Arnulf Jentzen, and Weinan E. Solving high-dimensional partial differential equations using deep learning. Proceedings of the National Academy of Sciences, 115(34):8505–8510, 2018.
[HSV95] Richard F Hartl, Suresh P Sethi, and Raymond G Vickson. A survey of the maximum principles for optimal control problems with state constraints. SIAM Review, 37(2):181–218, 1995.
[JZZ 20] Pengzhan Jin, Zhen Zhang, Aiqing Zhu, Yifa Tang, and George Em Karniadakis. Sympnets: Intrinsic structure-preserving symplectic networks for identifying hamiltonian systems. Neural Networks, 132:166–179, 2020.
[KZGK26] Adar Kahana, Qian Zhang, Leonard Gleyzer, and George Em Karniadakis. Spiking neural operators for scientific machine learning. Communications in Computational Physics, 40(3):573–596, 2026.
[LCO18] Alex Tong Lin, Yat Tin Chow, and Stanley Osher. A splitting method for overcoming the curse of dimensionality in Hamilton–Jacobi equations arising from nonlinear optimal control and differential games with applications to trajectory generation. Communications in Mathematical Sciences, 16(7):1933–1973, 2018.
[LGRP20] Qingbiao Li, Fernando Gama, Alejandro Ribeiro, and Amanda Prorok. Graph neural networks for decentralized multi-robot path planning. In 2020 IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS), pages 11785–11792. IEEE, 2020.
[LLF98] Isaac E Lagaris, Aristidis Likas, and Dimitrios I Fotiadis. Artificial neural networks for solving ordinary and partial differential equations. IEEE Transactions on Neural Networks, 9(5):987–1000, 1998.
[Mau77] Helmut Maurer. On optimal control problems with bounded state variables and control appearing linearly. SIAM Journal on Control and Optimization, 15(3):345–362, 1977.
[MZDK22] Tingwei Meng, Zhen Zhang, Jerome Darbon, and George Karniadakis. Sympocnet: Solving optimal control problems with applications to high-dimensional multiagent path planning problems. SIAM Journal on Scientific Computing, 44(6):B1341–B1368, 2022.
[NZGK21] Tenavi Nakamura-Zimmerer, Qi Gong, and Wei Kang. Adaptive deep learning for high-dimensional Hamilton–Jacobi–Bellman equations. SIAM Journal on Scientific Computing, 43(2):A1221–A1247, 2021.
[OWFLR21] Derek Onken, Samy Wu Fung, Xingjian Li, and Lars Ruthotto. Ot-flow: Fast and accurate continuous normalizing flows via optimal transport. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 35, pages 9223–9232, 2021.
[RPK19] Maziar Raissi, Paris Perdikaris, and George E Karniadakis. Physics-informed neural networks: A deep learning framework for solving forward and inverse problems involving nonlinear partial differential equations. Journal of Computational Physics, 378:686–707, 2019.
[SSFS15] Guni Sharon, Roni Stern, Ariel Felner, and Nathan R Sturtevant. Conflict-based search for optimal multi-agent pathfinding. Artificial Intelligence, 219:40–66, 2015.
[Tré05] Emmanuel Trélat. Contrôle optimal: théorie & applications, volume 36. Vuibert Paris, 2005.
[TZK 24] Bradley H. Theilman, Qian Zhang, Adar Kahana, Eric C. Cyr, Nathaniel Trask, James B. Aimone, and George Em Karniadakis. Spiking physics-informed neural networks on Loihi 2. In 2024 Neuro Inspired Computational Elements Conference (NICE), pages 1–6, 2024.
[VDBGLM11] Jur Van Den Berg, Stephen J Guy, Ming Lin, and Dinesh Manocha. Reciprocal n-body collision avoidance. In Robotics Research: The 14th International Symposium ISRR, pages 3–19. Springer, 2011.
[VSP 17] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. Attention is all you need. Advances in neural information processing systems, 30, 2017.
[WZK26] Ruyin Wan, Qian Zhang, and George Em Karniadakis. Randomized forward mode gradient for spiking neural networks in scientific machine learning. Neural Networks, 201:108978, 2026.
[YBR 19] Chulhee Yun, Srinadh Bhojanapalli, Ankit Singh Rawat, Sashank J Reddi, and Sanjiv Kumar. Are transformers universal approximators of sequence-to-sequence functions? arXiv preprint arXiv:1912.10077, 2019.
[ZK26] Qian Zhang and George Em Karniadakis. Operator learning for reconstructing flow fields from sparse measurements: a language model approach. arXiv preprint arXiv:2605.23712, 2026.
[ZKK25] Qian Zhang, Dmitry Krotov, and George Em Karniadakis. Operator learning for reconstructing flow fields from sparse measurements: An energy transformer approach. Journal of Computational Physics, 538:114148, 2025.
[ZKKS24] Qian Zhang, Adar Kahana, George Em Karniadakis, and Panos Stinis. SMS: Spiking marching scheme for efficient long time integration of differential equations. Journal of Computational Physics, 516:113363, 2024.
[ZSX 22] Qian Zhang, Konstantina Sampani, Mengjia Xu, Shengze Cai, Yixiang Deng, He Li, Jennifer K. Sun, and George Em Karniadakis. AOSLO-net: A deep learning-based method for automatic segmentation of retinal microaneurysms from adaptive optics scanning laser ophthalmoscopy images. Translational Vision Science & Technology, 11(8):7, 2022.
[ZWK 25] Qian Zhang, Chenxi Wu, Adar Kahana, George Em Karniadakis, Youngeun Kim, Yuhang Li, and Priyadarshini Panda. Artificial to spiking neural networks conversion with calibration in scientific machine learning. SIAM Journal on Scientific Computing, 47(3):C559–C577, 2025.
[ZWL 24] Zhen Zhang, Chenye Wang, Shanqing Liu, Jérôme Darbon, and George Em Karniadakis. A time-dependent symplectic network for non-convex path planning problems with linear and nonlinear dynamics. arXiv preprint arXiv:2408.03785, 2024.
APPENDIX A. GENERAL PONTRYAGIN'S MAXIMUM PRINCIPLE WITH STATE CONSTRAINTS
We are interested in the finite horizon deterministic optimal control problem as follows:
(24a)
over satisfying
(24b)
QIAN ZHANG, SHANQING LIU, JEROME DARBON, AND GEORGE KARNIADAKIS
for all , with a particular initial/final constraint
(24c)
Here, is the time horizon, is the state set and is the control set. is measurable} is the space of admissible controls. The running cost , the dynamics are given functions, with basic regular properties: continuous, Lipschitz continuous w.r.t all variables. Moreover, the initial and final conditions are subject to a particular constraint (24c), where and is a nonempty closed convex subset of . We also assume basic regular properties on : with Lipschitz derivatives. Then, the system (24b), subject to (24c), admits a unique, continuous solution for every (see for instance [Tré05]), and we denote this solution.
Let us denote the state space of the control problem (24). We call a trajectory if . A necessary optimality condition for the control problem (24) is given by the Pontryagin's maximum principle (PMP), by introducing the co-state in the topological dual space of , the cost multiplier and the initial/final constraints multiplier . Here, for simplicity, we assume further regularity property that is . Then, any optimal trajectory satisfies the following system (see for instance [AS13])
(25a)
with the pre-Hamiltonian defined by
(25b)
Moreover, the Pontryagin multiplier satisfies
(25c)
with the initial/final Lagrangian defined by
(25d)
as well as
(25e)
and the following Hamiltonian inequality holds: for every
(25f)
In (25e), denotes the normal cone to at . Recall that for any closed convex subset of a Banach space , the normal cone to at is defined by
(26)
We note that pure state constraints , as used in the main text (2), generally induce measure-valued multipliers in the PMP framework [HSV95, Mau77]. The standard
(absolutely continuous) PMP presented above does not directly cover state constraints; the soft penalty reformulation (3) used throughout the main text is what allows us to apply it.
APPENDIX B. CLASSICAL INDIRECT SHOOTING METHOD
Up to rare cases, the system (25) can only be solved approximately using numerical methods. Despite its fairly comprehensive theoretical characterization, its numerical approximation remains a challenging task. One classical numerical approach is the shooting method. For simplicity, we assume the data of the control problem (24) are with Lipschitz second order derivatives, and we consider equality initial/final constraints . Consider the shooting parameter , and the shooting function , defined by
(27)
where is the solution of system (25) with the initial/final condition replaced by the initial condition , and . Notice that there are an equal number of equations and unknown variables in (27). Then, is a regular zero of . Therefore, we convert the initial-final system (25) into a root finding problem, which is typically solved by a (quasi-)Newton method. However, one can find that this method is highly sensitive to the initial guess of shooting parameter, which may cause it to fail to converge. This ill-conditioning is precisely the practical motivation for the learning-based approach developed in the main text, which avoids repeated numerical integration and root-finding altogether.
APPENDIX C. TRAINING ALGORITHM
Algorithm 1 gives a full pseudocode listing of the training procedure sketched in §3.3, for a fixed K iterations.
QIAN ZHANG, SHANQING LIU, JEROME DARBON, AND GEORGE KARNIADAKIS*
Algorithm 1 OCFormer Training Procedure
Require: Boundary conditions ; Hamiltonian with soft-penalty parameters ; boundary weight ; Adam iterations ; L-BFGS iterations ; optional velocity bound (3D only); optional auxiliary penalty weight (ball-3D only).
Ensure: Learned physical trajectories .
1: Pre-solve the non-interacting latent system (10) analytically: for each agent , compute (constant) and .
2: Initialize the trainable parameters of OCFormer.
3: for to do
4: Sample collocation points uniformly at random in .
5: Evaluate the latent trajectories analytically at using the precomputed closed-form expressions from Step 1.
6: Compute physical trajectories and time derivatives via (14)–(15) using the Jacobian-vector product (JVP) through OCFormer.
7: Compute total loss from (16).
8: Update with one Adam gradient step.
9: end for
10: Fine-tune for iterations using L-BFGS on a fixed uniform grid with the same loss.
11: return Learned trajectories .