Manuscript Offprint
arXiv:2610.37557Learning Visuomotor Quadrotor Flight Through Dynamic Narrow Gaps via Differentiable Simulation
Riccardo Bianco Yunfan Ren Jiaxu Xing Davide Scaramuzza
Robotics and Perception Group, University of Zurich

Real World Deployment
Figure 1: Traversal of a narrow moving gap using onboard sensing and inertial measurements. The policy is trained with differentiable simulation and transferred zero-shot in the real world.
Abstract: Threading a quadrotor through a moving narrow gap is a demanding test of agile flight, requiring centimeter-level spatial alignment and precise temporal execution. We address this challenge using a control policy that operates directly on onboard visual and inertial measurements to output collective thrust and body-rate commands. The task is difficult because success lies on a thin feasible manifold: small errors in timing, position, attitude, or visual observability cause collision. Prior planning and learning methods rely on privileged state, teachers, planners, or distillation; learning dynamic narrow-gap traversal directly, from scratch, remains open. We introduce a differentiable moving-gap formulation that gates centering, alignment, and smooth collision terms by signed distance to a time-varying gap plane, turning a sparse traversal event into a dense pathwise objective. We integrate this formulation into a visual-feature-to-command policy trained in one stage from random initialization, without a teacher, planner, or distillation. We validate our approach in both synthetic and real-world experiments. In controlled benchmarks, we demonstrate that pathwise gradients significantly outperform score-function gradients for precision-critical tasks, yielding a 99.3% success rate in simulation after only a few minutes of training on a single GPU. Furthermore, the policy transfers directly to a real quadrotor, successfully crossing a dynamic narrow gap from varied initial conditions using onboard sensing and inertial measurements, achieving an 80% success rate over 10 physical trials.
Video: https://youtu.be/z-txORkhnrg
Code: https://github.com/uzh-rpg/agile_narrow_gap_diffsim
Keywords: Visuomotor Policy, Differentiable Simulation, Agile Quadrotor Flight
These authors contributed equally. Correspondence to: yunfan@ifi.uzh.ch, rbianco@ethz.ch.
10th Conference on Robot Learning (CoRL 2026), Austin, Texas, USA.
1 Introduction
Agile quadrotors can move quickly through confined spaces, but useful motion is often constrained by windows, frames, shelves, machinery, debris, and other structures that leave only narrow passages. Narrow-gap traversal is therefore a representative primitive for agile flight, requiring the vehicle to coordinate speed with whole-body geometric precision. Dynamic gaps make the primitive harder: the quadrotor must fit through the aperture and arrive when it is traversable. We study the onboard visual-inertial version of this problem, learning policies that use vision and inertial measurements to output collective-thrust-and-body-rate (CTBR) commands for static and moving gap traversal.
This setting combines thin spatio-temporal feasibility, partial onboard observations near crossing, and aggressive low-level control. Prior work has made strong progress on agile quadrotor planning and narrow-gap traversal through model-based trajectory optimization [1, 2, 3, 4, 5, 6], learning-based control [7, 8, 9, 10, 11, 12], and differentiable simulation [13, 14, 15, 16]. Yet most of these methods rely on static apertures, privileged geometry, or teacher/planner pipelines. This leaves open whether precision-critical moving-gap traversal can be learned end-to-end from random initialization, without a planner, teacher, or distillation. A moving aperture changes the problem qualitatively: the policy must decide not only how to cross, but also when to commit to the crossing.
We argue that a central bottleneck is the quality of the learning signal. Model-free RL methods such as PPO [17] estimate score-function (SF) gradients by treating the simulator as a black box, which can be too noisy on thin-manifold tasks. Pathwise (PW) gradients differentiate through closed-loop rollouts [18, 19], but can become unreliable under stiffness, discontinuities, contacts, or chaotic dynamics [20, 21, 22]. Our key observation is that narrow-gap flight is unforgiving but still smooth: with differentiable quadrotor dynamics and smooth task costs, even failed rollouts indicate how to adjust centering, attitude, and timing.
We build on this observation with a differentiable moving-gap formulation that gates centering, alignment, and smooth collision terms by signed distance to a time-varying gap plane. Integrated into a visual-feature-to-CTBR policy trained in one stage from random initialization, this formulation turns a sparse traversal event into a dense pathwise objective. The framework supports privileged-state and onboard visual-inertial observations and requires no demonstrations, trajectory labels, privileged teacher, planner, or distillation.
We validate our approach in simulation and real-world flight. In simulation, policies train in 0.4–5.6 minutes on a single GPU and reach ≥ 98.9% success with centimeter-level crossing accuracy. In matched 1,000-environment, five-seed state-task runs, tuned PPO used 19× more transitions and 45.5× more training time than BPTT on moving gaps when averaging its four converged seeds. Controlled benchmarks show that PW optimization succeeds with a single rollout per update, whereas SF optimization fails even with one thousand times more samples. Deployed in the real world, a 10×38 cm quadrotor traverses a 25×80 cm moving gap using onboard sensing and inertial measurements, achieving an 80% success rate over 10 trials.
Contributions: In summary, the contributions of this work are:
• We demonstrate precision-critical vision-based static and moving traversal can be learned end-to-end through differentiable simulation without demonstrations, a teacher, a planner, or distillation.
• We release an open-source differentiable-simulation framework for learning observation-to-CTBR policies under both privileged-state and onboard visual-inertial observations, converging in minutes on a single GPU.
• We show that pathwise gradients provide useful learning signals on thin-manifold tasks where score-function gradients fail even with orders of magnitude more samples.
• We deploy the visual-inertial moving-gap policy on a real quadrotor, closing the loop from differentiable training to physical agile flight.

Static gap randomization
Moving gap randomization


m
Real-world
(a)
(b)

(c)
Figure 2: Task geometry. (a) dimensions, (b) static and moving gap randomization, (c) drone camera view (left) and projected gap on image plane (right).
End-to-End Visuomotor Quadrotor Policies. Vision-conditioned quadrotor control has advanced through policy distillation and large-scale RL: Loquercio et al. [10] fly through cluttered forests by distilling a privileged planner into a vision policy, and Kaufmann et al. [11] reach champion-level racing via deep RL with high-frequency state estimation. Recent work explores lighter perception interfaces [24, 25], onboard sensing for angled narrow gaps [8], and whole-body gap traversal from image masks [26]. These policies can match or surpass model-based methods in time-optimal regimes, but typically require expert demonstrations, privileged teachers, or large sample budgets—which our low-variance pathwise gradients from differentiable simulation avoid.
Differentiable Simulation for Robot Learning. Differentiable simulators optimize control policies directly via analytic gradients. Wiedemann et al. [13] showed that analytic policy gradients can train competitive low-level quadrotor controllers, with extensions to vision-conditioned flight [15, 27, 28, 29], locomotion [30], and high-throughput GPU-accelerated frameworks [31, 32, 33]. The closest concurrent work, Zhang et al. [16], applies differentiable simulation with a depth-image renderer to irregular static gaps. We target a complementary regime—static and dynamic gaps—evaluated against PPO under matched parallelism.

Figure 3: Pipeline overview. Policy outputs are propagated through differentiable quadrotor dynamics. Differentiable costs are accumulated over the closed-loop rollout, and gradients are backpropagated through the trajectory to optimize the observation-to-command policy directly.
3 Methodology
3.1 Problem Formulation
We consider closed-loop quadrotor traversal through narrow rectangular gaps in two settings: (i) static gaps and (ii) moving gaps with time-varying pose. We approximate the quadrotor body as an ellipsoid. A rollout is successful if the ellipsoid projection onto the gap plane is fully contained within the rectangular aperture during traversal.
Control Architecture. We use a hierarchical control stack: a low-level onboard controller runs at 1000 Hz and tracks mass-normalized collective thrust and body-rate commands. A learned policy runs at 60 Hz and maps observations to commands, , where is the collective thrust command and are desired body rates expressed in the body frame. To model command latency, the policy output is applied to the simulated dynamics with a one-step delay, i.e., the dynamics at step use rather than the newly computed .
The quadrotor (approx. cm) must traverse a rectangular gap of size cm without collision (Fig. 2a). A gap frame is centered at the aperture, with normal to the gap plane and aligned with width and height. We consider static gaps, rotated about by , and moving gaps following planar pendulum motion with randomized amplitude and length (Fig. 2b), resulting in a time-varying pose . The task geometry and observation modalities are illustrated in Fig. 2.
Observation Settings. We consider state-based and visual-feature-based observations.
The state-based observation provides privileged quadrotor and gap information:
where flattens rotation matrices, denotes a target behind the gap, and is a queue of past actions. For moving gaps, is defined relative to the nominal pose.
The visual-feature-based observation excludes global pose information and instead uses onboard inertial quantities (R, ) together with normalized 2D gap-corner projections (Fig. 2c) and additional features derived from projected gap corners. These features (e.g., projected center, area, aspect ratio, visibility) are deterministic functions of the corner projections and are augmented with short-term temporal differences. The observation also includes the action history . Full details are provided in Appendix A.5.
3.2 Differentiable Simulation and Objective
We optimize via BPTT through differentiable closed-loop rollouts, with implemented via RK4 integration (Appendix A.8). The objective is
with gradients computed through the unrolled computation graph (Fig. 3).
We use a differentiable per-step cost
and define so maximizing return corresponds to minimizing the time-integral of the cost. Intuitively, the terms enforce: (i) progress through the gap, (ii) centering and refined centering near the gap plane, (iii) attitude alignment with the gap frame at traversal, (iv) collision avoidance using a smooth differentiable penalty, (v) regularization of velocities/accelerations/actions, and (vi) (vision-only) maintaining the gap in the camera field of view. Most of the terms are modulated as a function of the signed distance to the gap plane, increasing geometric precision near traversal, while relaxing stabilization terms during the crossing phase. For moving gaps, the plane and its signed distance are time-varying; consequently, centering, alignment, and smooth collision terms remain coupled to the instantaneous aperture pose throughout the rollout. Full formulations and weights are in Appendix A.7.
3.3 Training Setup
Episodes start 2 m before the gap with random position offsets m and velocity perturbations . Roll and pitch are initialized at zero, and yaw is randomized in . Episodes terminate upon collision or after s. Domain randomization reduces the sim-to-real gap and includes gap rotation (static), pendulum phase, amplitude, and length (moving), perception–actuation delay, thrust scaling, and (for vision) gap-corner noise and dropouts (see Appendix A.9). Policies are trained via BPTT with batched rollouts using a 2-layer MLP (width 512 for state-based and 1024 for visual-feature-based observations), optimized with Adam and a warmup–cosine schedule. Training uses 100 parallel environments for up to 20k epochs, selecting the best validation checkpoint (full hyperparameters in Appendix A.10).
4 Experiments and Results
Evaluation Setup. We evaluate differentiable-simulation training for narrow-gap traversal under full (state-based) and partial (visual-feature-based) observability, considering static and moving gaps. We report success rate, geometric precision at gap crossing, and training efficiency (epochs and wall-clock time), and compare against PPO under varying parallelism. All experiments use a single NVIDIA RTX 4080 SUPER GPU.
Pathwise vs. Score-Function Gradients. Before turning to the quadrotor, we isolate the key property motivating differentiable simulation: the gap between pathwise (PW) and score-function (SF) gradient estimators under matched settings. The comparison is illustrated in Fig. 4. PW closely follows the analytic gradient on a non-convex landscape (Fig. 4a), while SF deteriorates with limited samples; variance scales as for PW vs. for SF on an LQR system (Fig. 4b); and on a neural slit-navigation task (Fig. 4c), PW solves the problem with a single rollout per update, whereas SF fails with up to 4,096 rollouts per update. This sample ratio refers only to the controlled slit task, not to quadrotor PPO transitions.
Non-convex optimization: pathwise (PW) vs score-function (SF) gradients

PW: 1 grad eval/step
SF: N probes/step
(a)
LQR gradient variance vs rollout horizon
(b)
Narrow-slit navigation: PW succeeds with one rollout per update, SF needs orders of magnitude more samples
— PW (DiffSim)
SF (N=4)
SF (N=16)
SF (N=64)
SF (N=256)
(c)
Figure 4: PW vs SF gradient comparison. (a) Non-convex 2D landscape and induced gradients. (b) Gradient variance as a function of the horizon . (c) Slit navigation: episode return and success rate vs training iterations, with example rollouts at different stages.
Efficiency and Performance. In the quadrotor setting, we evaluate convergence speed together with success and geometric accuracy at gap crossing. Convergence is defined as the first evaluation checkpoint (every 500 epochs) starting a streak of at least three consecutive evaluations with success . At crossing, we measure success rate, Euclidean error to the gap center, in-plane errors along the gap-frame axes (), and roll, pitch, and yaw errors. Table 1 summarizes success, Euclidean crossing error (cm), and convergence epochs for all task vari-
ants; per-axis position and attitude errors are omitted for readability. Differentiable simulation achieves near-perfect success and centimeter-level accuracy across all tasks. Performance degrades slightly in the vision-based setting, and convergence requires more optimization steps, reflecting partial observability effects discussed below. Qualitative rollouts illustrating the learned behaviors across task variants are shown in Fig. 5.
| Task | Succ. | Err. | Epochs |
|---|---|---|---|
| State-static | 100.0 | 1.0 | 500 |
| Vision-static | 98.9 | 2.4 | 3500 |
| State-moving | 100.0 | 2.4 | 1500 |
| Vision-moving | 99.3 | 2.3 | 4000 |
Table 1: Task metrics for differentiable-simulation policies. Success (%), crossing error (cm), and convergence epochs.
Static-to-Moving Transfer. Without fine-tuning, the submitted state-static and vision-static checkpoints achieved 31.5% and 6.6% success, respectively, over 1,000 moving-gap rollouts under the Table 1 protocol, compared with 100% and 99.3% after moving-task training. Static-only training therefore did not transfer reliably in our setting. The state and vision tasks also differ in gap-pose distribution, so this experiment does not isolate timing. Unlike the fully observed state policy, the vision policy loses gap feedback near crossing; transfer may therefore depend on gap motion relative to clearance during this blind interval, consistent with its larger drop.
Transfer and Real-World Deployment. The visual-feature-based moving-gap policy achieves 99.3% success over 1 000 simulated rollouts under the training distribution (Table 1). To assess how this checkpoint degrades beyond the training simulator, we additionally evaluate it in a higher-fidelity simulator [34] and on a real quadro-
| Setting | Succ. (%) | Trials |
|---|---|---|
| Train sim. | 99.3 | 1 000 |
| Hi-fi sim. | 81.0 | 100 |
| Real-world | 80.0 | 10 |
Table 2: Sim-to-real transfer results.
(a) State – Static
(b) Vision – Static

(c) State – Moving
(d) Vision – Moving
drone trajectory (color = time)
drone ellipsoid samples
gap at crossing
gap moving
pendulum (moving)
trajectory in gap plane (color = time)
drone ellipsoid at crossing
gap at crossing
crossing point
normalised time t/T
Figure 5: Successful rollouts for static and moving gaps under state- and vision-based observations.

t = 1.00s
t = 2.02s
t = 3.00s
Figure 6: Real-world deployment of the vision-based moving-gap policy. Top: third-person flight sequence; each frame includes an inset with the onboard camera view. Bottom: perception pipeline on one frame — raw image, HSV segmentation mask, quadrilateral fitting, and detected corners.
tor with onboard sensing (Table 2). These transfer eval-
uations are not used for training or checkpoint selection. Success decreases with increasing realism, primarily due to dynamics mismatch, perception noise, and discrepancies in the moving-gap mechanism, but the same policy still performs closed-loop traversal on real hardware. During real-world deployment, LED-illuminated gate edges are detected in onboard images and converted into gap-corner features (Fig. 6, bottom; see Appendix A.6 for details). The resulting visual features are fed directly to the learned policy, which outputs collective-thrust and body-rate commands during real-world moving-gap traversal. We recorded twelve flights; two had onboard logs consistent with success but lacked external video and were excluded. Of the ten verifiable flights, 8/10 succeeded, with a 95% Wilson interval of 49–94%. Failures 03/08 started at and m relative to the nominal gap. Trial 03 was comparable to successful initializations, whereas trial 08 started substantially higher; ten scored trials are insufficient to separate initialization effects from other causes. Both failures fell within the successful-trial ranges of gap-motion amplitude and angular rate at policy start and of gap angle and angular rate at crossing . Both crossed low and hit the bottom edge, with estimated penetrations of 4.6 and 9.3 cm. Together with the drop from 99.3% in training simulation to 81% in high-fidelity simulation, this is consistent with residual dynamics or tracking mismatch affecting vertical accuracy, although the available trials do not isolate it from perception or initialization effects.
Comparison with PPO. We use PPO as a representative on-policy SF baseline to compare full-horizon BPTT with standard model-free policy optimization, not as a pathwise baseline. The PPO baseline uses the same actor and 150-step horizon, but tuned objective weights and a curriculum; we therefore do not attribute the entire pipeline difference to the estimator. At 1,000 environments
| Task | Method | Resources | Speedup | Conv. | ||||
|---|---|---|---|---|---|---|---|---|
| Transitions | Updates | Time (s) | Trans. | Updates | Time | |||
| Static | BPTT | 75 M | 500 | 38.3±0.7 | 2.8× | 6.4× | 5/5 | |
| PPO | 210±34 M | 1.12±0.18 M | 246±39 | 5/5 | ||||
| Moving | BPTT | 135±34 M | 900±224 | 67.5±16.6 | 19.0× | 45.5× | 5/5 | |
| PPO | 2.57±1.10 B | 13.7±5.7 M | 3073±1295 | 4/5 | ||||
Table 3: Matched 1,000-environment state-task budgets on an RTX 4080 SUPER over five seeds. Transition, optimizer-update, and wall-clock speedups are PPO/BPTT ratios computed from the reported means. PPO moving-task statistics average the four converged seeds; seed 2 was censored at 30k epochs (4.5 B transitions, 24 M updates, 5,377 s).

Figure 7: BPTT vs tuned PPO across 10, 100 and 1000 parallel environments (evaluation every 500 epochs over 100 rollouts).
both methods process 150k transitions per epoch, but BPTT takes one full-rollout gradient step whereas PPO takes 800 minibatch steps, so epochs are not compute-equivalent. Table 3 instead reports transitions, optimizer updates, hardware, wall-clock time, and five seeds. On moving gaps, converged-seed means show that PPO uses 19× more transitions and 45.5× more training time than BPTT. Figure 7 retains the submitted parallelism sweep.
Partial Observability in Visual-Feature-Based Policies. Invalid corners are sentinel-marked and their derived geometry is masked, while earlier valid frames remain in the window. Once no valid corners remain, the policy has no gap-relative visual information and uses R, ω, and the four-command queue. The MLP window provides a short explicit history rather than predicting future gap pose (Fig. 8). Table 4 reports the vision-moving results as K varies. Larger K converged earlier while final success varied by 0.7 points; K = 1 removes visual-frame history but retains R, ω, and the command queue. We did not compare an RNN, which may help during longer dropout.
| K | Success (%) | Convergence epoch |
|---|---|---|
| 1 | 99.5 | 6,500 |
| 2 | 98.8 | 4,500 |
| 4 | 99.3 | 4,000 |
| 8 | 98.9 | 3,500 |
Table 4: Vision-moving performance as the temporal window length K varies.
5 Discussion and Limitations
Differentiable simulation achieves near-perfect simulated success and centimeter-level accuracy across the tested static and planar pendulum-driven moving gaps. The controlled studies show informative pathwise gradients in this smooth, locally stable regime, while the complete BPTT pipeline uses fewer transitions and less training time than tuned PPO. Because PPO uses tuned weights and a curriculum, the entire pipeline difference cannot be attributed to the estimator alone.
Gap visibility over time

Figure 8: Gap visibility over one episode. Top: visible gap corners (red) and projected gap area (blue) over time; dashed lines mark the snapshots below. Bottom: onboard image plane (left) and third-person view (right) at three instants, showing the gap exiting the field of view.
Limitations. Training costs use privileged simulator geometry and collision data, and the visual input consists of engineered geometric features rather than raw images. The physical setup relies on LED-based corners and evaluates only planar pendulum motion. Natural openings, abrupt or non-periodic motion, severe or prolonged visual dropout, hard contact, and long-horizon instability remain untested. The ten scored flights yield broad statistical uncertainty, and their two failures do not isolate dynamics/tracking mismatch from perception or initialization effects. Finally, the method requires differentiable components and incurs BPTT memory and compute costs that scale with horizon and fidelity.
Future work. Reducing model mismatch through learnable residual dynamics or more accurate differentiable models is a natural direction. Marker-free perception, recurrent policies for longer dropout, and evaluation under broader gap motions would extend the present controlled proof of concept. Short-horizon pathwise methods with bootstrap values may also be preferable to full-horizon BPTT for longer tasks.
Overall, differentiable simulation offers a strong training paradigm for high-precision flight, enabling fast and stable optimization in regimes where model-free RL is limited by gradient variance and sample complexity.
Acknowledgments
This work was supported by the European Union’s Horizon Europe Research and Innovation Programme under grant agreement No. 101120732 (AUTOASSESS) and the European Research Council (ERC) under grant agreement No. 864042 (AGILEFLIGHT).
References
[1] D. Falanga, E. Mueggler, M. Faessler, and D. Scaramuzza. Aggressive quadrotor flight through narrow gaps with onboard sensing and computing using active vision. In IEEE International Conference on Robotics and Automation (ICRA), pages 5774–5781. IEEE, 2017.
[2] S. Liu, K. Mohta, N. Atanasov, and V. Kumar. Search-based motion planning for aggressive flight in SE(3). IEEE Robotics and Automation Letters, 3(3):2439–2446, 2018.
[3] Z. Wang, X. Zhou, C. Xu, and F. Gao. Geometrically constrained trajectory optimization for multicopters. IEEE Transactions on Robotics, 2022.
[4] Z. Han, Z. Wang, N. Pan, Y. Lin, C. Xu, and F. Gao. Fast-racing: An open-source strong baseline for SE(3) planning in autonomous drone racing. IEEE Robotics and Automation Letters, 6(4):8631–8638, 2021.
[5] S. Yang, B. He, Z. Wang, C. Xu, and F. Gao. Whole-body real-time motion planning for multicopters. In IEEE International Conference on Robotics and Automation (ICRA), pages 9197–9203, 2021.
[6] Y. Ren, S. Liang, F. Zhu, G. Lu, and F. Zhang. Online whole-body motion planning for quadrotor using multi-resolution search. In IEEE International Conference on Robotics and Automation (ICRA), pages 1594–1600, 2023.
[7] J. Lin, L. Wang, F. Gao, S. Shen, and F. Zhang. Flying through a narrow gap using neural network: an end-to-end planning and control approach. In IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS), pages 3526–3533, 2019.
[8] Y. Xie, M. Lu, R. Peng, and P. Lu. Learning agile flights through narrow gaps with varying angles using onboard sensing. IEEE Robotics and Automation Letters, 8(9):5424–5431, 2023.
[9] C. Xiao, P. Lu, and Q. He. Flying through a narrow gap using end-to-end deep reinforcement learning augmented with curriculum learning and sim2real. IEEE Transactions on Neural Networks and Learning Systems, 34(5):2701–2708, 2023.
[10] A. Loquercio, E. Kaufmann, R. Ranftl, M. Müller, V. Koltun, and D. Scaramuzza. Learning high-speed flight in the wild. Science Robotics, 6(59):eabg5810, 2021.
[11] E. Kaufmann, L. Bauersfeld, A. Loquercio, M. Müller, V. Koltun, and D. Scaramuzza. Champion-level drone racing using deep reinforcement learning. Nature, 620(7976):982–987, Aug 2023. ISSN 1476-4687.
[12] T. Wu, G. Xu, Z. Wang, J. Lin, T. Chen, Y. Wu, Z. Han, Z. Liu, and F. Gao. Precise aggressive aerial maneuvers with sensorimotor policies. arXiv preprint arXiv:2604.05828, 2026.
[13] N. Wiedemann, V. Wüest, A. Loquercio, M. Müller, D. Floreano, and D. Scaramuzza. Training efficient controllers via analytic policy gradient. In IEEE International Conference on Robotics and Automation (ICRA), 2023.
[14] J. Heeg, Y. Song, and D. Scaramuzza. Learning quadrotor control from visual features using differentiable simulation. In IEEE International Conference on Robotics and Automation (ICRA), pages 4033–4039, 2025.
[15] Y. Zhang, Y. Hu, Y. Song, D. Zou, and W. Lin. Learning vision-based agile flight via differentiable physics. Nature Machine Intelligence, pages 1–13, 2025.
[16] L. Zhang, Y. Hu, F. Yu, Y. Deng, W. Yu, and D. Zou. Vision-based end-to-end learning for UAV traversal of irregular gaps via differentiable simulation. arXiv preprint arXiv:2604.02779, 2026.
[17] J. Schulman, F. Wolski, P. Dhariwal, A. Radford, and O. Klimov. Proximal policy optimization algorithms. arXiv preprint arXiv:1707.06347, 2017.
[18] D. P. Kingma and M. Welling. Auto-encoding variational Bayes. In International Conference on Learning Representations (ICLR), 2014.
[19] S. Mohamed, M. Rosca, M. Figurnov, and A. Mnih. Monte Carlo gradient estimation in machine learning. Journal of Machine Learning Research, 21(132):1–62, 2020.
[20] M. A. Z. Mora, M. Peychev, S. Ha, M. Vechev, and S. Coros. PODS: Policy optimization via differentiable simulation. In International Conference on Machine Learning (ICML), pages 7805–7817, 2021.
[21] H. J. T. Suh, M. Simchowitz, K. Zhang, and R. Tedrake. Do differentiable simulators give better policy gradients? In International Conference on Machine Learning (ICML), pages 20668–20696, 2022.
[22] L. Metz, C. D. Freeman, S. S. Schoenholz, and T. Kachman. Gradients are not all you need. arXiv preprint arXiv:2111.05803, 2021.
[23] J. Chen, Y. Fu, Y. Lou, L. Kin, and W. Xu. Learning real-time dynamic responsive gap-traversing policy for quadrotors with safety-aware exploration. IEEE Transactions on Intelligent Vehicles, 8(3):2271–2284, 2023.
[24] J. Xing, A. Romero, L. Bauersfeld, and D. Scaramuzza. Bootstrapping reinforcement learning with imitation for vision-based agile flight. In Conference on Robot Learning (CoRL), 2024.
[25] J. Xing, L. Bauersfeld, Y. Song, C. Xing, and D. Scaramuzza. Contrastive learning for enhancing robust scene transfer in vision-based agile flight. In 2024 IEEE international conference on robotics and automation (ICRA). IEEE, 2024.
[26] T. Wu, Y. Chen, T. Chen, G. Zhao, and F. Gao. Whole-body control through narrow gaps from pixels to action. In IEEE International Conference on Robotics and Automation (ICRA), pages 11317–11324, 2025.
[27] J. Pan, J. Xing, R. Reiter, Y. Zhai, E. Aljalbout, and D. Scaramuzza. Learning on the fly: Rapid policy adaptation via differentiable simulation. IEEE Robotics and Automation Letters, 2026.
[28] Y. Ren, Z. Zhu, J. Xing, and D. Scaramuzza. Learning agile quadrotor flight in the real world. arXiv preprint arXiv:2602.10111, 2026.
[29] J. Xing, Z. Zhu, Y. Ren, I. Geles, Y. Zhai, R. Reiter, and D. Scaramuzza. Continual robot policy learning via variational neural dynamics. arXiv preprint arXiv:2606.27353, 2026.
[30] Y. Song, S. Kim, and D. Scaramuzza. Learning quadruped locomotion using differentiable simulation. arXiv preprint arXiv:2403.14864, 2024.
[31] X. Zhang, R. Wang, Y. Ren, J. Sun, H. Fang, J. Chen, and G. Wang. Diffaero: A GPU-accelerated differentiable simulation framework for efficient quadrotor policy learning. arXiv preprint arXiv:2509.10247, 2025.
[32] M. Kulkarni, W. Rehberg, and K. Alexis. Aerial gym simulator: A framework for highly parallelized simulation of aerial robots. IEEE Robotics and Automation Letters, pages 1–8, 2025.
[33] F. Li, F. Sun, T. Zhang, and D. Zou. Visfly: An efficient and versatile simulator for training vision-based flight. In IEEE International Conference on Robotics and Automation (ICRA), pages 11325–11332, 2025.
[34] E. Aljalbout, J. Xing, A. Romero, I. Akinola, C. R. Garrett, E. Heiden, A. Gupta, T. Hermans, Y. Narang, D. Fox, et al. The reality gap in robotics: Challenges, solutions, and best practices. Annual Review of Control, Robotics, and Autonomous Systems, 9, 2025.
A Supplementary Materials
A.1 Gradient Analysis and Properties of Pathwise Estimators
This section complements Fig. 4 by providing a deeper analysis of the structural differences between pathwise (PW) and score-function (SF) gradient estimators. We detail the experimental setup used to probe their behaviour and present two additional analyses that do not fit in the main text: (i) the dependence of estimator variance on the closed-loop stability margin in a controlled dynamical system (App. A.3), and (ii) the behaviour of the score-function estimator as a function of the number of parallel rollouts in a narrow-passage navigation task (App. A.4). All experiments are implemented in PyTorch and reproduced by the scripts released with the codebase. We use full-horizon APG/BPTT rather than proposing a new gradient estimator or optimizer. Full-horizon differentiation fits our smooth 150-step rollout; short-horizon pathwise methods with a bootstrap value may suit longer horizons. We did not compare other pathwise methods.
A.2 Common Setup and Hyperparameters
Estimators. We compare two estimators of under matched optimizer, learning rate, and number of gradient updates:
• Pathwise (PW): , obtained via reverse-mode autodiff through the deterministic rollout.
• Score-function (SF): , where is a leave-one-out baseline and is the number of independent rollouts per update.
The SF estimator is implemented as REINFORCE to isolate estimator-level effects; while methods such as PPO may improve optimization stability, they do not alter the underlying credit assignment mechanism.
Controlled dynamical system. We consider a 1D linear system with , a linear stochastic policy , and quadratic loss . Default parameters are: , , , , , , evaluated at unless stated otherwise.
Narrow-passage navigation. We study a planar control problem with dynamics , , , , and horizon . The start and goal are and respectively. Both estimators optimize the same reward:
with , , and . The policy is an MLP with tanh activations. Both methods use Adam with learning rate and 8 seeds. PW uses a single deterministic rollout per update, while SF is evaluated over rollouts.
Success criterion. At each iteration we evaluate 100 deterministic rollouts with Gaussian perturbations applied to the start. A rollout is successful if it crosses and its final position lies within a radius 0.25 of the goal.
A.3 Variance Scaling: Horizon and Stability Regime
The versus scaling reported in the main text can be derived from a variance decomposition of the estimators. For the SF estimator,
(a) Estimator distribution at T = 20

(b) Failure mode: approach to instability
Figure 9: LQR estimator analysis (extended). (a) Distribution of single-trajectory gradient estimates at horizon , evaluated at . Both estimators are unbiased around the true gradient (black dashed line), but the pathwise (PW) estimator concentrates more than an order of magnitude more tightly than the score-function (SF) one (std 2.38 vs. 27.93 in our setup, i.e. a per-trajectory variance ratio of ). (b) Stability ablation: sweeping the open-loop pole at fixed shifts the closed-loop pole across unity at (shaded region). Both estimators diverge as the system approaches instability, but PW retains variance advantage up to the bifurcation, after which both saturate. This is the regime in which PW loses its asymptotic edge — and the regime that the quadrotor gap-traversal task avoids by design.
a trajectory-level return that grows linearly with T multiplies a sum of T score terms whose residual variance scales as , leading to an overall scaling. In contrast, the PW estimator propagates sensitivities through the dynamics; in the stable regime the resulting Jacobian norm remains bounded by a geometric series, yielding scaling.
Stability ablation. Fig. 9 sweeps at fixed , such that the closed-loop pole crosses unity at . Both estimators degrade near instability, but PW retains a large advantage up to the bifurcation. This highlights a key property: the pathwise estimator is not universally superior; its advantage emerges in regimes with smooth, locally stable, and moderately long-horizon dynamics. This analysis diagnoses the smooth, locally stable regime used in our 150-step quadrotor rollouts; it does not establish a new stability boundary.
A.4 Signal vs. Variance in Narrow-Passage Problems
Parallelism does not compensate for missing signal. Fig. 4c reports ; under the same protocol, additional runs at and 4,096 also fail. All SF configurations plateau at similar success rates ( ), indicating that increasing reduces estimator variance but does not increase the underlying signal, which remains near-zero before the passage is discovered. Under Gaussian exploration, the probability of sampling a successful trajectory is effectively negligible, making the reward signal uninformative regardless of .
Trajectory-level interpretation. The trajectory snapshots make this behaviour explicit. The PW estimator updates the policy using the analytic spatial gradient even before successful trajectories are observed, progressively shaping the trajectory toward the feasible manifold. In contrast, the SF estimator produces trajectories that move in the correct direction but remain outside the success region, reflecting a weak credit signal dominated by sampling noise.
A.5 Observation Details
A.5.1 State-Based Observations
In the state-based setting, the observation vector consists of the full quadrotor state, the gap pose, the goal position, and a short history of past actions:
where , and are the quadrotor position, orientation, linear velocity and body-frame angular velocity, is the gap pose, and is the post-gap waypoint. The operator flattens a rotation matrix into a 9-dimensional row-major vector.
Action history. is a FIFO queue of the last commanded actions, each of the form (collective thrust and body-rate references). The queue is initialized with the hovering action and is updated, at every control step, by removing the oldest entry and appending the latest action. Its length is set to cover the maximum perception–actuation delay,
where in our implementation the per-episode delay is uniformly sampled in s, so that . With nominal values s and s (hence s) we obtain , and contributes additional scalars to the observation. This buffer allows the policy to compensate the randomized control latency and acts as a smoothness regularizer through the action-rate penalty.
A.5.2 Visual-Feature-Based Observations
The visual-feature-based observation combines onboard inertial measurements with features derived from the projection of the gap corners over a short temporal window of K frames (with an optional stride of skip_frames between consecutive frames).
Projected Corner Features. The four 3D corners of the rectangular gap are defined as
where and are the width and height unit vectors of the gap frame. Each corner is projected into the image plane through a (double-sphere) camera model, given the body pose (p, R):
so that valid pixels are normalized to . During training, before normalization, an independent uniform pixel noise (with px) is added to each corner to simulate detection uncertainty (see domain-randomization section). Corners falling outside the field of view are flagged invalid and replaced by a sentinel value . The four corners are then sorted in a consistent clockwise order starting from the top-right corner, removing permutation ambiguity.
Derived Geometric Features. From the (sorted, possibly invalid) projected corners we deterministically compute, per frame:
• the projected center , set to -0.999 if any corner is invalid;
• the normalized projected area
with denoting addition modulo 4 (Shoelace formula), normalized so that the full image area equals 1;
• the projected axes , , where are the midpoints of the right, left, top and bottom edges of the projected quadrilateral;
• the projected aspect ratio ;
• the visibility score ;
• the horizontal-alignment scalar .
All geometric features collapse to 0 when at least one corner is invalid. Earlier valid frames remain in the temporal window after an invalid detection. Once every retained frame is invalid, no gap-relative visual information remains and the policy acts from , and the four-command queue.
Temporal Window and Deltas. The features above are computed over a sliding window of the last frames, producing the stacked tensors , , , etc. Motion cues are encoded as differences between the last two frames of the window:
Final Observation Vector. Concatenating the inertial part, the stacked visual features, the temporal deltas and the action history , the final observation is
with K = 4 in our experiments.
A.6 Perception Pipeline
To extract gap corner observations in real-world experiments, we employ a lightweight detection pipeline based on LED illumination. The gate is equipped with a high-intensity green LED strip along its boundary. Due to the high brightness, the LEDs appear as saturated white regions in the camera image. Images are converted to HSV and thresholded with , , to isolate these bright regions into a binary mask. A morphological closing operation is applied to fill small gaps in the mask, followed by connected component filtering to discard regions with area below 500 px.
The remaining region is assumed to correspond to the gap and is approximated with a quadrilateral via contour fitting. The resulting four vertices are interpreted as the gap corners. When multiple candidates are detected, the one closest to the image center is selected. For temporal consistency,

Figure 10: Gate detection pipeline used for extracting gap corners in real-world experiments. From left to right: raw image, segmentation mask after HSV thresholding and noise removal, quadrilateral fitting, and final detected corners (red dots).
detected corners are matched across frames and sorted in a fixed clockwise order. These corners directly define the visual observation features used by the policy. The perception pipeline is illustrated in Fig. 10.
This simplified perception pipeline isolates the control problem and enables controlled evaluation, although it relies on strong assumptions on the visual structure of the environment.
A.7 Reward Details
We provide the full formulation of the trajectory cost introduced in Sec. 3.2. All terms are differentiable with respect to states and actions and are combined to optimize both geometric precision and dynamic feasibility.
Distance-dependent weighting. Let denote the gap normal and the gap center. The signed distance is
For each cost component , we use a distance-modulated weight
where is a task-specific base weight and is a smooth shaping function. Table 5 reports the base weights used for each task configuration, while Fig. 12 visualizes the shaping functions and weighted costs for BPTT static-state task. For terms that are not distance-modulated we set (progress and camera alignment).
Smooth penalty. All geometric costs use a SmoothL1 penalty to ensure stable gradients:
Scaled as SmoothL1( )/ to control sharpness.
Progress cost. Encourages the quadrotor to reach a goal behind the gap, placed at a distance of 2 m along the gap normal. For moving gaps, is defined relative to the nominal gap pose ( ). The progress cost equation is:
Centering costs. Let
The centering cost penalizes deviation from the gap center:
A second near-gap term enforces higher precision close to traversal:
Their distance shaping functions differ across the two terms:
where is the logistic sigmoid. In our implementation, and , matching , and .
We use to weight the vertical centering term more strongly, reflecting the tighter clearance margin along the gap height (narrow aperture).
Alignment cost. The relative rotation is
We extract the roll, pitch, and yaw angles from using a standard Euler-angle decomposition and normalize them to .
The cost penalizes roll, pitch, and yaw misalignment:
We weight pitch and roll more strongly than yaw, since pitch/roll directly affect the projected clearance through the aperture, while yaw is less critical for collision-free traversal.
Collision cost. To enforce strict geometric feasibility during traversal, the quadrotor is approximated as a rigid ellipsoid and the gap aperture is modeled as a set of planar half-space constraints.
Let be the quadrotor position and its orientation. The ellipsoidal body is defined by a shape matrix describing its principal axes.
The gap is represented in its local frame G by four planar constraints corresponding to the gap boundaries. Let and denote the width and height directions of the gap. We define the outward normals as
and the corresponding offsets such that the feasible region satisfies
Gap Collision Cost Visualization

Figure 11: Collision cost as a function of penetration depth.
To account for the finite size of the quadrotor, we compute a conservative bound on the ellipsoid extent along each constraint normal. The projected radius of the ellipsoid along a direction is approximated by .
The resulting penetration vector is defined as
where the maximum is applied element-wise.
This quantity represents the violation of each half-space constraint after accounting for the quadrotor geometry.
The collision cost is then defined as
(a) Distance-modulated gates

(b) Weighted costs (bptt/static_state)
progress centering alignment near_centering collision stabilization cam
Figure 12: Distance modulation overview. (a) Shaping functions used for distance-dependent weighting. (b) Resulting weighted, distance-modulated costs for the state-static task.
where increases the penalty near the gap plane.
This formulation provides a smooth and differentiable approximation of collision constraints, enabling gradient-based optimization while enforcing that the quadrotor remains within the gap aperture at traversal. The geometric interpretation of collision and alignment cost is shown in Fig. 11.
Stabilization cost. To regularize the dynamics, we penalize velocity, angular velocity, acceleration, control effort:
We downweight stabilization near the gap plane using a smooth sigmoid window with a non-zero floor to allow aggressive maneuvers during crossing:
where is the logistic sigmoid, controls the half-width of the window, and its steepness. In our implementation, , , and , so that far from the gap plane and reaches a minimum of inside the window. We fix the stabilization weight to and the stabilization sub-weights to , , , and across all tasks.
Camera alignment cost (vision only). Encourages the quadrotor to keep the gap in view:
where d is the normalized direction toward the gap.
A.8 Quadrotor Dynamics
The quadrotor state is defined as
where are position and velocity in the world frame, is the rotation from body to world frame, and is the body angular velocity. The policy outputs a collective thrust command and desired body rates . The low-level controller tracks these commands at
| Task | ||||||
|---|---|---|---|---|---|---|
| State-Static | 0.7 | 3.0 | 3.0 | 3.0 | 18.0 | 0.0 |
| Vision-Static | 0.7 | 6.0 | 5.0 | 3.0 | 22.0 | 0.7 |
| State-Moving | 0.5 | 3.0 | 5.0 | 6.0 | 27.0 | 0.0 |
| Vision-Moving | 0.5 | 5.0 | 5.0 | 6.0 | 30.0 | 0.7 |
Table 5: Task-specific base weights used for each cost component. Distance-modulated weights are defined in Eq. (14).
1000 Hz; in simulation, body rates are assumed to be tracked instantaneously, i.e. . To emulate actuator uncertainty, at every step the commanded thrust is perturbed by a multiplicative uniform noise,
before being applied to the dynamics. The translational dynamics are
with and . Position and velocity are integrated using fourth-order Runge–Kutta (RK4). Orientation is updated via the exponential map (Rodrigues formula). For and :
where denotes the skew-symmetric operator. This orientation update is exact for constant angular velocity over the integration step and avoids quaternion normalization issues. The entire discrete-time model is fully differentiable and constitutes the transition function used for BPTT optimization.
A.9 Domain Randomization Distributions
Initial state randomization. Episodes start 2 m before the gap with position offsets , velocity perturbations , and yaw randomized in . Roll and pitch are initialized at zero.
Gap randomization. For static gaps, the gap is rotated about its normal by an angle . For moving gaps, we sample an amplitude and an initial angle . The initial angular velocity is set using energy conservation,
with random sign, and the pendulum length is randomized as m. We exclude the central interval to avoid near-static configurations.
Perception noise. To emulate imperfect perception, we perturb the projected image-plane coordinates with additive noise sampled independently for each coordinate of each corner: , with pixels. Corners that fall outside the field of view are treated as invalid and assigned a fixed sentinel value.
Perception–actuation delay. We introduce a stochastic delay to emulate processing and communication latency. At the beginning of each episode, the delay is sampled as , with s, and kept constant during the rollout. The range is chosen based on measured deployment latency.
Action randomization. To account for actuation uncertainty and modeling inaccuracies, we introduce multiplicative noise on the collective thrust command. At each timestep, the thrust output of the policy is perturbed as , with , corresponding to up to variation in the applied thrust.
A.10 Training Details
Policy architecture. The policy is a 2-hidden-layer MLP with ReLU activations. State-based policies use width 512, visual-feature-based policies use width 1024. Both BPTT and PPO share the same architecture for a given observation setting. Policy weights are initialized with a uniform distribution scaled by a factor of 0.01.
BPTT optimization. We use Adam with a warmup–cosine learning-rate schedule. For state-based tasks, the learning rate is warmed up from to and decayed over 800 steps to . For visual-feature-based tasks, the learning rate is warmed up from to and decayed over 2000 steps to . Training runs for up to 20k epochs with evaluation every 500 epochs over 100 rollouts; the checkpoint with the highest success rate is selected.
PPO hyperparameters. PPO uses the same reward components as BPTT but with independently tuned weights and a reward curriculum (see below). All tasks share the following hyperparameters: discount factor , GAE , clip ratio , 4 update epochs per iteration, minibatch size of 750 transitions, value-function coefficient 0.5, entropy coefficient 0.02, and maximum gradient norm 1.0. The learning rate follows a warmup–cosine schedule from to a peak of , decaying to . The number of minibatches per epoch is derived as , where steps (2.5 s at 60 Hz), ensuring a consistent minibatch size across the three parallelism levels we evaluate (10/100/1000).
Reward curriculum. Without curriculum learning, PPO fails to learn gap traversal entirely under the same full objective used by BPTT: the collision, near-centering, and centering costs penalize any imprecise crossing attempt, causing the policy to avoid the gap plane altogether and resulting in zero success rate. To address this, we linearly anneal these weights from their initial to final values over a task-dependent epoch range (Table 6). This allows the policy to first learn to approach and cross the gap, then progressively improve alignment and geometric precision as the penalties increase, ultimately achieving successful traversal at the cost of slower convergence. BPTT uses fixed task weights throughout training and does not require any curriculum learning, as pathwise gradients provide sufficient signal to optimize all cost components jointly from the start.
| Task | Epoch range | Ramped weights [start → end] | |||
|---|---|---|---|---|---|
| Start | End | ||||
| State-Static | 500 | 2500 | 0 → 18 | 0 → 3 | 3 → 3 |
| State-Moving | 2000 | 6000 | 0 → 70 | 0 → 25 | 3 → 6 |
Table 6: PPO reward curriculum schedule. Weights are linearly annealed over the specified epoch range.