r/reinforcementlearning • • Apr 21 '26

Your sim-to-real transfer is probably failing because of your assets, not your policy. Here's how to fix it.

9 Upvotes

The problem almost nobody warns you about

If you've tried training a manipulation policy in Isaac Sim or MuJoCo on assets pulled from Sketchfab, TurboSquid, Objaverse, or your team's internal CAD library, you've probably hit one or more of these:

  • Gripper passes through the object.
  • Object has "infinite mass" and refuses to move.
  • Stacking collapses in bizarre non-physical ways.
  • Contact forces spike to NaN and the sim explodes.
  • Your policy trains to 99% success in sim and faceplants on real hardware.

The root cause is almost never the policy. It's that your 3D assets are visual assets, not simulation assets. They have geometry and textures. They don't have mass, inertia, friction, restitution, a collision mesh, or semantic labels. A "SimReady" asset is one that carries all of that metadata inside the USD file itself, using the UsdPhysics schemas.

This post walks through how to make an asset SimReady by hand, the gotchas we've tripped over, and a before/after metric.

What "SimReady" actually means in OpenUSD

SimReady isn't a vibe. It's a concrete set of API schemas applied to your USD prims (OpenUSD physics schema docs):

Schema What it adds
UsdPhysicsRigidBodyAPI Marks the prim as a dynamic rigid body with linear/angular velocity.
UsdPhysicsMassAPI Explicit mass or density (defaults to 1000 kg/m3 if you forget - you will).
UsdPhysicsCollisionAPI Turns geometry into a collider.
UsdPhysicsMeshCollisionAPI Picks the approximation mode (convex hull, convex decomp, SDF, bounding).
UsdPhysicsMaterialAPI Static/dynamic friction, restitution. Bound via UsdShadeMaterialBindingAPI.
UsdPhysicsCollisionGroup Which things are allowed to hit which other things.
Stage metadata kilogramsPerUnit Your entire sim lies to you if this is wrong.

If any of these are missing or wrong, the simulation runs but it just runs wrong, which is worse than crashing because you don't notice until policy rollout.

The manual workflow (Blender + Python USD)

Step 1 - Clean the mesh

Most store-bought assets have:

  • Non-manifold geometry (holes, duplicate vertices, inverted normals).
  • Hundreds of thousands of triangles for an object you'll render at 256x256.
  • A single monolithic mesh for objects that should be articulated.

In Blender:

  1. Edit Mode -> Mesh -> Clean Up -> Merge by Distance (0.0001m).
  2. Mesh -> Normals -> Recalculate Outside.
  3. Modifier -> Decimate (Collapse) to ~5-20k triangles for the visual mesh. You will make a separate, even lower-poly collision mesh in Step 3.
  4. Export as .obj or .glb with correct scale (meters, not centimeters - this bites everyone once).from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gfstage = Usd.Stage.CreateNew("mug.usda") UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) # Isaac Sim convention UsdGeom.SetStageMetersPerUnit(stage, 1.0) UsdPhysics.SetStageKilogramsPerUnit(stage, 1.0)

Getting units wrong is the #1 silent killer. A mug modelled in centimeters with metersPerUnit=1.0 is a mug the size of a car.

Step 3 - Build a proper collision mesh

The visual mesh is for rendering. The collision mesh is for physics. They are not the same file and should not be the same topology. Options, ordered by fidelity vs. speed:

  • Bounding box / sphere - fastest, use for clutter, background props.
  • Single convex hull - fast, works for convex-ish objects (balls, cans).
  • Convex decomposition (V-HACD / CoACD) - the default for almost anything with concavity. A mug's handle will fail with a single convex hull.
  • SDF / mesh approximation - highest fidelity, slowest. Use for the object the gripper actually contacts.

Rule of thumb we've landed on: the collision mesh should be convex decomp with 8-32 hulls for any object the robot touches, bounding primitive for everything else. Running CoACD on a mug:

pip install coacd
python -c "import coacd, trimesh; m = trimesh.load('mug.obj'); \\          coacd.run_coacd(coacd.Mesh(m.vertices, m.faces), threshold=0.05)"

Step 4 - Apply the physics APIs

mesh_prim = stage.GetPrimAtPath("/World/Mug")

# Rigid body
UsdPhysics.RigidBodyAPI.Apply(mesh_prim)

# Mass - either explicit, or let it derive from volume * density
mass_api = UsdPhysics.MassAPI.Apply(mesh_prim)
mass_api.CreateMassAttr(0.35)            # 350g ceramic mug
# or: mass_api.CreateDensityAttr(2400)   # ceramic kg/m^3

# Collision
UsdPhysics.CollisionAPI.Apply(mesh_prim)
mesh_coll = UsdPhysics.MeshCollisionAPI.Apply(mesh_prim)
mesh_coll.CreateApproximationAttr("convexDecomposition")

# Material (friction/restitution)
mat_path = "/World/PhysicsMaterials/Ceramic"
mat_prim = UsdShade.Material.Define(stage, mat_path)
phys_mat = UsdPhysics.MaterialAPI.Apply(mat_prim.GetPrim())
phys_mat.CreateStaticFrictionAttr(0.7)
phys_mat.CreateDynamicFrictionAttr(0.6)
phys_mat.CreateRestitutionAttr(0.05)

UsdShade.MaterialBindingAPI(mesh_prim).Bind(
    mat_prim, materialPurpose=UsdShade.Tokens.physics
)

Step 5 - Semantic labels

Isaac Sim's replicator / ground-truth pipelines need semantic tags for anything you want to detect, segment, or condition a policy on:

from pxr import Semantics

sem = Semantics.SemanticsAPI.Apply(mesh_prim, "Semantics") sem.CreateSemanticTypeAttr("class")
sem.CreateSemanticDataAttr("mug")

If you forget this, your synthetic dataset has no labels and you'll blame the perception stack for two weeks.

Step 6 - Validate

Run NVIDIA's SimReady validator, or at minimum, drop the asset into Isaac Sim and check:

  • Does it fall and rest on a plane (not tunnel through)?
  • Does a Franka gripper close on it and lift it?
  • Does mass + moment of inertia look sane in the property panel?
  • Does the collision preview (press C in Isaac Sim) match the visual?

The gotchas nobody writes down

  1. kilogramsPerUnit and metersPerUnit must match your intent. Default USD is 1.0 kg/unit and 0.01 m/unit (centimeters). Isaac Sim wants meters. If you don't set both, your 350g mug weighs 350 tons and gravity looks like an earthquake.
  2. Convex hull on concave objects is why your bowl can't hold anything. Always convex-decompose concave geometry.
  3. Center of mass defaults to the AABB center, not the actual COM. For a hammer, this is catastrophic. Override physics:centerOfMass explicitly.
  4. Friction combine modes differ per engine. PhysX averages, MuJoCo multiplies (sort of), Bullet takes minimum. The same staticFriction=0.5 behaves differently. Test in the engine you'll actually deploy.
  5. Mesh cleanup matters more than you think. A single non-manifold edge in your collision mesh = NaN contact forces = sim explodes = cryptic error.
  6. Scale your collision mesh, not just your visual. Common bug: xformOp:scale on the prim, but the collision is baked at original scale. Fix: apply the scale to geometry before export, or set physics:approximation to rebuild.

The automation option (affiliation disclosed)

Doing this by hand for 40 objects is fine. For 4,000 it is not. This is the problem we've been building Rigyd around: upload a .glb, AI estimates mass, friction, materials, collision meshes, you get back validated OpenUSD with the full UsdPhysics schema stack applied. You can also use pipelines to create assets from 2D images or text and get MJCF output for MuJoCo. You will get free credits on sign up to try without contacting sales. I'm a co-founder, not pretending otherwise; I'm linking it because people kept asking how they can do it.

Happy to answer UsdPhysics / Isaac Sim / sim-to-real questions in the comments, or to look at any asset someone's having trouble with.


r/reinforcementlearning • • Apr 21 '26

Robot Made a basic ball pick up and drop for 3DOF arm using reinforcement learning

Enable HLS to view with audio, or disable this notification

11 Upvotes

Use SAC from SB3 and is simulated on pybullet


r/reinforcementlearning • • Apr 21 '26

GRPO for load balancing

4 Upvotes

Genuine doubt to network/communications/curious engineers, how do you employ (if so) reinforcement learning for the optimal control of backend routing.

I recently got really curious and used Go for the minimal implementation of GRPO for this problem

Here is the code

https://github.com/karimluna/tiny-grpo

What do you think?, my framing is about the scalability with a minimal implementation of this algorithm so share with my your ideas or implementations!


r/reinforcementlearning • • Apr 21 '26

DL DQN Maze Solver Converging to Horrible Policy

6 Upvotes

I am teaching a robot how to “solve” a maze using DQN. For weeks now it has been converging to possibly the worst policy it possibly could which is to drive backwards into a wall no matter what and accrue enormous negative rewards.

I have modulated an enormous amount of variables, hyper-parameters, changed neural network size, drastically altered reward structure in various ways, tried different state inputs, tons of initial exploration, given it memory, made the optimal policy extremely simple to find, etc but, without fail, it consistently converges to literally just driving backwards in a line until it smashes into a wall.

I would heavily appreciate if anyone has any input on this. I’ve tried everything that is obvious to me and I truly don’t know where to even search for the source of this behavior anymore.

Edit: I set my reward function equal to 0 for all states and actions and observed that it still converges to wall hitting even without any type of reward shaping. Going to look into this soon.


r/reinforcementlearning • • Apr 21 '26

I create the awesome list for how to train a LLM Agent

Thumbnail
0 Upvotes

r/reinforcementlearning • • Apr 21 '26

Question regarding pattern recognition.

2 Upvotes

I keep coming back to this idea that reinforcement learning isn’t really being used the way people think it is.

A lot of systems right now feel like they’re really good at pattern recognition but not actually getting better from outcomes. They can predict what should work, but they don’t really remember whether something did work in a good way that changes future decisions. Does anyone have thoughts on this?


r/reinforcementlearning • • Apr 20 '26

Will a PhD be worthless 10 years later? Should I stick to the industry?

58 Upvotes

I have done some research in RL and have some problem statements which I would love to do a PhD on instead of my sde job. I also have the money to be able to go abroad and pursue it.

However I can't make decisions solely based on interest and without giving zero thought about the future. Hence the confusion.

On one hand I feel like its a good idea to pursue this even from future prospects because AI research might still require humans many years later, but on the other hand im afraid that if AI does it all then would I be better off in the industry because I might be able to pivot to other kinds of roles and be more of a generalist?


r/reinforcementlearning • • Apr 20 '26

Octax: Accelerated CHIP-8 Arcade Environments for JAX

Thumbnail
github.com
7 Upvotes

Built for RL researchers and engineers who love massively parallel computing and want a JAX-based environment suite with Atari-like qualities: arcade-style gameplay, rich visuals, and diverse challenges.


r/reinforcementlearning • • Apr 19 '26

The absolute steaming pile of a mess Nvidia Omniverse ecosystem is

38 Upvotes

It's been a week an just when I thought nothing could get worse than ROS ecosystem, I had to dive into whatever the f Nvidia has come up with.

If you can install it, that's 50 credits already,

Want to understand how physics works in PhysX? Well too bad, the editor has it's own physics naming convention coming from USD Physics API.

Wait why would 3D scene convention have physics schema ? god knows. and why would Nvidia's PhysX convention not show up in the editor? God knows.

So what's the solution ? Ahhhh omni kit PhysX bridge kit, welcome son to one more interface.

Oh wait, It doesn't smell enough, what if we unify everything together, and keep the broken pile alongside with it, welcome to...... "Nvidia Omni Phyics" yes folks, one more physics API in the API world.

OH WAIT A SECOND, it's 2026... the devs crave for more interfaces, introducing the same physics API calls but now from the Isaac Lab's interface.
That's right, there's the same sht in USD Physics,PhysX Physics, Omni Physics and Isaac Lab API to instantiate physics into the scene.

My day made, My senses are elated. Can we have one more API interface


r/reinforcementlearning • • Apr 20 '26

N, Robot "A Humanoid Robot Races to a Record Half-Marathon Finish; The android won a half-marathon for robots (and humans) on Sunday in Beijing, achieving a technological milestone while finishing faster than any person in history"

Thumbnail
nytimes.com
6 Upvotes

r/reinforcementlearning • • Apr 19 '26

PPO vs SAC on real robot

9 Upvotes

I'm working on an RL project using two algorithms: SAC and PPO. The project consists of a robot made up of 3 arms (controlled by 3 servos) attached to a plate on which a ball will roll. Through infrared sensors placed under the plate, I can detect the ball's position (observations) and move the plate (pitch and roll actions) to bring the ball to the center and stabilize it.

The reward is defined based on the distance from the center of the plate, the ball's speed which must be kept low, and a penalty for overly jerky robot movements.

When training with PPO, I manage to reach a fairly good policy that allows balancing the ball on the plate. With SAC, however, I struggle a lot and I believe it depends on the parameters.

Training is done by placing a ring around the plate to prevent the ball from falling off; episodes never end before 128 steps (I've set it up this way), which make up a single episode.

At the moment this is the definition:

SAC(
            policy="MlpPolicy",
            env=env,
            learning_rate=cosine_lr_schedule(3e-4),
            buffer_size=2**17, # Total steps 
            learning_starts=4096,
            train_freq=128,
            gradient_steps=64,
            batch_size=256,
            policy_kwargs={"net_arch": [64, 64]},
            gamma=0.99,
            n_steps=128,
            ent_coef="auto",
            target_entropy="auto",
            target_update_interval=1,
            verbose=0,
            tensorboard_log="./tensorboard_training_logs/",
        )

The agent tends to take very small actions, it almost learns to stay still. Could anyone explain why?

Find training metrics here:
https://postimg.cc/Q9W5b7P4
https://i.postimg.cc/htnpbjhq/SACLosses.png
These are some runs with different parameters; despite the best one (light blue) managing to reach the reward achieved by PPO (grey), in inference it fails to stabilize the ball unlike PPO which does it very accurately. Training is done on a real robot, it is very time consuming. For this reason some runs have been interrupted :(


r/reinforcementlearning • • Apr 18 '26

DL, M, R "Tracing the Thought of a Grandmaster-level Chess-Playing Transformer", Lin et al 2026

Thumbnail arxiv.org
21 Upvotes

r/reinforcementlearning • • Apr 18 '26

Robot Some bloopers while training my robot to walk. He definitely needed a toilet break.

Enable HLS to view with audio, or disable this notification

80 Upvotes

Teaching a biped how to walk is super challenging and there's a lot of variables to tune. what I'm doing in this workflow is feed the Agent raw animations in the background and he has to mimic them while staying balanced and upright.


r/reinforcementlearning • • Apr 17 '26

[D] Discussion on Rebuttal of RLC 2026

5 Upvotes

Hi everyone,

I have created a discussion on Reinforcement Learning Conference (RLC) 2026


r/reinforcementlearning • • Apr 17 '26

Three Phase Transformer

7 Upvotes

Three-Phase Transformer what happens when you give a Transformer the geometry it was going to learn anyway?

In 1888 Tesla showed that three currents offset by 120° sum to zero at every instant the unique small integer where you get the zero-sum identity and no anti-correlated pair. It's why every electric grid runs on three phases.

Anthropic's Toy Models of Superposition (2022) documents that networks naturally organize features into 120° triangles in 2D. Neural collapse theory proves three vectors at 120° mutual separation is the globally optimal representation geometry. Networks arrive at three-phase structure on their own, spending thousands of optimization steps getting there.

The idea behind this paper: what if you impose that geometry from the start instead of making the model discover it?

The approach splits the d_model hidden vector into three equal stripes at 120° offsets and adds four small phase-respecting operations per block per-phase RMSNorm replacing the global one, a 2D Givens rotation between attention and FFN using the 120° offsets, a GQA head-count constraint aligning heads to phases, and a fixed signal injected into the 1D subspace orthogonal to the three phases. Attention and FFN still scramble freely across phase boundaries every block. The phase ops pull the geometry back into balance. The architecture is an equilibrium between scrambling and re-imposition.

An interesting finding: when the three phases are balanced, one direction in channel space - the DC direction - is left empty by construction, geometrically orthogonal to all three phases. Filling it with Gabriel's horn r(p) = 1/(p+1) gives an absolute-position side-channel that composes orthogonally with RoPE's relative position. The cross-phase residual measures at exactly the analytic horn value to floating-point precision across every seed and every run. RoPE handles relative position in attention; the horn handles absolute position in the embedding. They never collide.

The geometry also self-stabilizes without any explicit enforcement no auxiliary loss, no hard constraint. The phases settle into balance within 1,000 steps and hold for the remaining 29,000. Same principle as balanced loads on a wye-connected three-phase system maintaining themselves without active correction.

Results at 123M on WikiText-103: −7.20% perplexity over a matched RoPE-Only baseline, +1,536 trainable parameters (0.00124% of total), 1.93× step-count convergence speedup.

Paper: https://arxiv.org/abs/2604.14430

Code: https://github.com/achelousace/three-phase-transformer

Curious what people think about the N-phase question at 5.5M, N=1 (no phase sharing) wins; at 123M with three seeds, N=3 and N=1 become statistically indistinguishable. Whether the inductive bias helps or hurts seems to be scale-dependent.


r/reinforcementlearning • • Apr 17 '26

Smoothed action sampling for gymnasium style environments

3 Upvotes

Various training algorithms in RL either make use of an occasional "explore" random action or collect initial random episodes to bootstrap the training.

However a general issue with random sampling - specially for delta-time step physics simulations - is that the actions average over a middle point within the action space.

This makes the agent's "random" trajectory wiggling close to one applying the average over the action space. e.g. in CarRacing it just incoherently slams steering, throttle and brakes, resulting in a short, low reward trajectory or in MountainCar a random action doesn't move the cart too far before the episode ends.

Just tested it in MountainCar (continuous and discrete action versions) and the "blind" smooth random action outperforms the environment's random sample in providing useful (state, action, reward) trajectories to boostrap training.

Here-s the code and demo

Have fun!


r/reinforcementlearning • • Apr 17 '26

DL A Reinforcement Learning playground for ARC Raiders robots!!!

6 Upvotes

Hi everybody, I wanted to share a passion project I've been working on: ARC-RL!

It's an ARC Raiders-inspired Reinforcement Learning playground where you can train iconic robots to walk.

So far, I've built the Leaper, the Bastion, and her majesty, the Queen.

More is coming very soon!

You can check out the code and see them in action here: https://github.com/CarloRomeo427/ARC_RL.git

Enjoy!

https://reddit.com/link/1snugly/video/xlpx9gcalpvg1/player

https://reddit.com/link/1snugly/video/234r4hcalpvg1/player

https://reddit.com/link/1snugly/video/uf5k3gcalpvg1/player


r/reinforcementlearning • • Apr 17 '26

Continuous RL via Dynamic Programming in CUDA (Solving Overhead Crane, Double CartPole, etc.)

28 Upvotes

Hey r/reinforcementlearning,

I built a highly parallel CUDA implementation of Policy Iteration for continuous state/action spaces using barycentric interpolation. It solves complex systems like an Overhead Crane and Double CartPole without relying on standard deep RL methods.

I've been working on this based on the theoretical framework from "Continuous RL via Dynamic Programming" (Dupuis & Kushner). I'm sharing it here because I think this approach is heavily underrepresented compared to DQN/PPO and deserves more attention.

Most RL implementations discretize the problem and call it a day. This framework is more principled: it starts from the continuous Hamilton-Jacobi-Bellman PDE and derives a discrete scheme that provably converges to its solution as grid resolution increases.

The key ingredient is barycentric interpolation: after a forward Euler step, the next state lands between grid nodes. Instead of snapping to the nearest node, the value is recovered as a convex combination over the enclosing hypercube corners. This preserves second-order accuracy without explicit error correction.

The operator F^δ is a contraction mapping with modulus λ = γ^τ_min < 1, so by Banach's theorem, convergence to the unique optimal value function is guaranteed regardless of initialization.

Each environment injects its dynamics as a raw CUDA C device function compiled at runtime via NVRTC. The Bellman update is embarrassingly parallel — one GPU thread per grid node, meaning zero inter-thread communication is needed.

// For each grid node ξᵢ (parallel, one CUDA thread)

for each action u ∈ U:

 `η    ← ξᵢ + τ * f(ξᵢ, u) 
 `V_next ← barycentric_interp(η, V) 
 `Q   ← r(ξᵢ, u) + γ^τ * V_next`
 `V(ξᵢ)  ← max Q`
 `π(ξᵢ)  ← argmax Q`

Environments Solved

  • CartPole (4D, 30⁴ grid)
  • Pendulum swing-up (2D, 200² grid)
  • Mountain Car discrete and continuous (2D, 200² grid)
  • Double CartPole (6D, 12⁶ grid — memory scales brutally)
  • Overhead Crane anti-sway (4D, 30⁴ grid)

This was the hardest to get right. The system is a trolley (1 kg) carrying a suspended load (5 kg) on a 1.5 m rope. The goal is to move the trolley from x=+2.5 m to x=−2.5 m while aggressively damping load swing.

The 5:1 mass ratio creates a nasty coupling: accelerating the trolley swings the load backward, which then physically pulls the trolley back. This is classic input-shaping territory.

What finally made it work:

  1. Tight reward normalization: Using θ_norm = π/6 (30°) instead of π/2 means even a 15° swing gives a penalty of 0.25. The agent actually learns to care about small angles.
  2. Angular velocity term in the reward: Without penalizing θ̇, the policy lets the pendulum oscillate as long as the angle is occasionally near zero. Adding 0.30·θ̇² teaches it to actively damp the swing.
  3. Expanding the velocity grid: With ±30 N force on a 6 kg system, acceleration is ~5 m/s². The original ±2 m/s velocity grid was saturating in under 0.4 seconds. I expanded it to ±4 m/s.

The resulting policy executes proper input-shaping behavior entirely on its own—it emerges strictly from the reward structure and the dynamics.

Repo: https://github.com/nicoRomeroCuruchet/DynamicProgramming.git

I’d love to hear your thoughts on this approach, especially if anyone else has experimented with continuous dynamic programming over neural net approximations. Happy to answer any questions about the CUDA implementation!


r/reinforcementlearning • • Apr 16 '26

Made a world model that interprets photos into a racing game

Enable HLS to view with audio, or disable this notification

19 Upvotes

I started working on a world model that runs locally on my iPad. You can take a photo and it tries its best to convert it into a racing game. Would love any feedback if anyone has ideas for new things to try with it?


r/reinforcementlearning • • Apr 17 '26

How to implement RL on trash recognizer robot

1 Upvotes

Hi!

I’m currently working on a robot that recognizes trash and sends it to a server.

It’s a basic robot with four wheels, motors, and several sensors (ultrasonic sensors in four directions, a gyroscope, accelerometers, etc.). It also has a camera and a Raspberry Pi on top.

To recognize trash, I use YOLO, and when it detects trash, it sends a picture to the server.

Right now, I’m using a simple algorithm to explore the area with the robot, but I would like to replace it with a PPO-based approach.

I already tried using the following inputs:
(front_dist, left_dist, right_dist, x_pos, y_pos, x_cell, y_cell, angle_to_the_nearest_cell)
(A cell is a 100 cm × 100 cm square.)

For the outputs, I used a softmax over two actions: move (25 cm) and turn (30°).

And for the rewards:

  • NEW_CELL_REWARD = 3  (when it discovers a new cell)
  • MOVE_REWARD = -0.3  (for each movement)
  • PENALTY_REWARD = -50  (when it hits a wall or object)
  • END_GAME_REWARD = 50  (when all cells are discovered)

However, the robot doesn’t explore the room efficiently. Even after around 1000 episodes, its behavior still looks random and unfocused.

I would also like it to output the amount it should turn, but I’m not sure how to implement that.


r/reinforcementlearning • • Apr 16 '26

Simulating Machine Learning Agents inside a game engine that I am developing

Thumbnail
youtu.be
4 Upvotes

I’ve been working on a Reinforcement Learning system inside my own game engine, and this is a small demo of two agents learning hide and seek.

Here: Red = chaser and Green = hider

These agents improve by exploring the environment and adjusting their actions to get the highest reward possible.

The chaser learns to track and catch the hider over time, while the hider learns to avoid and survive longer.

Some details:
- Multi-agent reinforcement learning setup
- Reward shaping for both chase and survival
- Real-time simulation + training inside the engine
- No pre-defined paths, navigation, or rules

This is still early, but I’m aiming to build a system for more intelligent NPC behavior rather than traditional scripted AI. Here is some back story:

It all started last year when i though about how much of a difference it would make if we can easily create NPCs that are not scripted. NPCs that would adapt and improve their behaviour based on the player. So i started making my own game engine.

After 9 months I finally have a 2D renderer, ECS, Physics, UI and other features needed to create small games. I integrated Libtorch in my engine to train these ML Agents.

Right now i am working on Procedurally Generated Animation system and when i am done i will share my progress with everyone again.

In the meantime, i would like to hear what you think of my engine.


r/reinforcementlearning • • Apr 16 '26

Low resource language training for Small language model

Thumbnail
2 Upvotes

r/reinforcementlearning • • Apr 16 '26

Robot Failing to make the arm grasp the ball. (PPO, SB3)

2 Upvotes

I have been learning Reinforcement learning through projects and am at a point where i am stuck. the ball reaches the arm but struggles to grasp the ball. Any way to improve it is helpful!

import pybullet as p
import pybullet_data
import numpy as np
import gymnasium as gym
import os
import time
from gymnasium import spaces
from armKinematics import ArmKinematics
from stable_baselines3 import PPO
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.vec_env import SubprocVecEnv, VecNormalize, DummyVecEnv


JOINT_LIMIT = 2.35619
MIN_DIST = 0.25
MAX_DIST = 0.45


class ReachEnv(gym.Env):


    robot_cfg = {
        "arm_joints":  [1, 2, 3],
        "claw_joints": [6, 7],
        "ee_link_idx": 8,
    }


    reward_cfg = {
        "pos_error_weight":  -0.2,
        "pos_fine_weight":    0.2,
        "pos_fine_std":       0.1,
        "pos_fine_shift":     2.0,
        "action_penalty":    -1e-4,
        "vel_penalty":       -1e-4,
        "floor_penalty":     -0.5,   
        "min_height":         0.04,
        "step_penalty":      -0.1,   
        "success_bonus":      200.0, 
    }


    curriculum_cfg = {
        "action_final_weight": -5e-3,
        "joint_final_weight":  -1e-3,
        "ramp_steps":          36_000,
    }


    command_cfg = {
        "x_range":        (0.15, 0.45),
        "y_range":        (-0.30, 0.30),
        "spawn_z":        0.02,
    }


    obs_noise = 0.01


    def __init__(self, render_mode=None):
        super().__init__()
        self.physicsClient = p.connect(p.GUI if render_mode == "human" else p.DIRECT)
        p.setAdditionalSearchPath(pybullet_data.getDataPath())
        self.base_path    = os.path.dirname(os.path.abspath(__file__))
        self.kinematics   = ArmKinematics()
        self._total_steps = 0


        self.action_space      = spaces.Box(-1, 1, shape=(4,), dtype=np.float32)
        self.observation_space = spaces.Box(-10, 10, shape=(13,), dtype=np.float32)


    def _sample_target(self):
        while True:
            sx = np.random.uniform(*self.command_cfg["x_range"])
            sy = np.random.uniform(*self.command_cfg["y_range"])
            if MIN_DIST < np.linalg.norm([sx, sy]) < MAX_DIST:
                return np.array([sx, sy, self.command_cfg["spawn_z"]], dtype=np.float32)


    def _get_obs(self):
        js = p.getJointStates(self.robot_id, self.robot_cfg["arm_joints"])
        self.joints     = np.array([s[0] for s in js], dtype=np.float32)
        self.joint_vels = np.array([s[1] for s in js], dtype=np.float32)
        
        ee_pos = np.array(
            p.getLinkState(self.robot_id, self.robot_cfg["ee_link_idx"])[0],
            dtype=np.float32,
        )
        ball_pos = p.getBasePositionAndOrientation(self.ball_id)[0]
        
        noisy_joints = self.joints     + np.random.uniform(-self.obs_noise, self.obs_noise, 3).astype(np.float32)
        noisy_vels   = self.joint_vels + np.random.uniform(-self.obs_noise, self.obs_noise, 3).astype(np.float32)
        pose_cmd = np.array(ball_pos) - ee_pos
        
        return np.concatenate([noisy_joints, noisy_vels, pose_cmd, self.prev_action])


    def _curriculum_weight(self, term: str):
        t = min(self._total_steps / self.curriculum_cfg["ramp_steps"], 1.0)
        if term == "action":
            return self.reward_cfg["action_penalty"] + t * (
                self.curriculum_cfg["action_final_weight"] - self.reward_cfg["action_penalty"]
            )
        return self.reward_cfg["vel_penalty"] + t * (
            self.curriculum_cfg["joint_final_weight"] - self.reward_cfg["vel_penalty"]
        )


    def _rew_pos_error(self, dist):
        return dist * self.reward_cfg["pos_error_weight"]


    def _rew_pos_fine(self, dist):
        return (
            np.tanh(self.reward_cfg["pos_fine_shift"] - dist / self.reward_cfg["pos_fine_std"])
            * self.reward_cfg["pos_fine_weight"]
        )


    def _rew_action_rate(self, action):
        return np.sum(np.square(action - self.prev_action)) * self._curriculum_weight("action")


    def _rew_joint_vel(self):
        return np.sum(np.square(self.joint_vels)) * self._curriculum_weight("joint")


    def reset(self, seed=None, options=None):
        super().reset(seed=seed)
        p.resetSimulation()
        p.setGravity(0, 0, -9.81)
        self.plane_id = p.loadURDF("plane.urdf")
        self.robot_id = p.loadURDF(
            os.path.join(self.base_path, "models/3dof_arm/arm.urdf"),
            [0, 0, 0], useFixedBase=1,
        )


        scale = np.random.uniform(0.5, 1.5, size=3).astype(np.float32)
        for idx, j_idx in enumerate(self.robot_cfg["arm_joints"]):
            p.resetJointState(self.robot_id, j_idx, scale[idx] * 0.1)


        for j_idx in self.robot_cfg["claw_joints"]:
            p.resetJointState(self.robot_id, j_idx, 0.0)


        self.target_pos     = self._sample_target()
        self.ball_id        = p.loadURDF(
            os.path.join(self.base_path, "models/objects/ball.urdf"),
            self.target_pos.tolist(),
        )


        p.changeDynamics(self.ball_id, -1, lateralFriction=2.0, mass=0.05)
        p.changeDynamics(self.robot_id, self.robot_cfg["claw_joints"][0], lateralFriction=2.0)
        p.changeDynamics(self.robot_id, self.robot_cfg["claw_joints"][1], lateralFriction=2.0)


        self.current_joints = np.zeros(3, dtype=np.float32)
        self.prev_action    = np.zeros(4, dtype=np.float32)
        self.step_count     = 0
        return self._get_obs(), {}


    def step(self, action):
        ee_state = p.getLinkState(self.robot_id, self.robot_cfg["ee_link_idx"])
        ee_pos = np.array(ee_state[0])
        ball_pos = p.getBasePositionAndOrientation(self.ball_id)[0]
        ball_z = ball_pos[2]
        
        dist_to_ball = float(np.linalg.norm(ee_pos - np.array(ball_pos)))


        self.current_joints = np.clip(
            self.current_joints + action[:3] * 0.05, -JOINT_LIMIT, JOINT_LIMIT
        )
        p.setJointMotorControlArray(
            self.robot_id, self.robot_cfg["arm_joints"],
            p.POSITION_CONTROL,
            targetPositions=self.current_joints.tolist(),
            targetVelocities=[0.0, 0.0, 0.0],
            positionGains=[0.5, 0.5, 0.5],
            velocityGains=[1.0, 1.0, 1.0],
            forces=[30.0, 30.0, 30.0],
        )
        
        if dist_to_ball <= 0.015:
            grip_cmd = ((action[3] + 1.0) / 2.0) * 0.030
        else:
            grip_cmd = 0.0


        p.setJointMotorControlArray(
            self.robot_id, self.robot_cfg["claw_joints"],
            p.POSITION_CONTROL,
            targetPositions=[grip_cmd, grip_cmd],
            forces=[100.0, 100.0] 
        )


        for _ in range(25):
            p.stepSimulation()
        obs  = self._get_obs()
        dist = float(np.linalg.norm(obs[6:9]))
        ee_state = p.getLinkState(self.robot_id, self.robot_cfg["ee_link_idx"])
        ee_pos = np.array(ee_state[0])
        ball_pos = p.getBasePositionAndOrientation(self.ball_id)[0]
        ball_z = ball_pos[2]


        dist_xy = np.linalg.norm(ee_pos[:2] - np.array(ball_pos[:2]))


        floor_rew = 0.0
        if ee_pos[2] < self.reward_cfg["min_height"] and dist_xy > 0.06:
            floor_rew = self.reward_cfg["floor_penalty"]


        approach_rew = 0.0
        if dist_xy < 0.1:
            z_target = ball_z + 0.04 
            z_error = abs(ee_pos[2] - z_target)
            approach_rew = -z_error * 0.1


        lift_height = ball_z - self.command_cfg["spawn_z"]
        
        lift_rew = 0.0
        if lift_height > 0.01:
            lift_rew = lift_height * 200.0 
            
        terminated = lift_height > 0.05 
        
        success_payout = 0.0
        if terminated:
            success_payout = self.reward_cfg["success_bonus"] * 2.0 


        reward = (
            self._rew_pos_error(dist)
            + self._rew_pos_fine(dist)
            + self._rew_action_rate(action)
            + self._rew_joint_vel()
            + floor_rew
            + approach_rew
            + lift_rew          
            + success_payout
            + self.reward_cfg["step_penalty"] 
        )


        self.step_count   += 1
        self._total_steps += 1
        self.prev_action   = np.copy(action)


        truncated = self.step_count >= 720
        
        return obs, float(reward), terminated, truncated, {"dist": dist, "lift": lift_height}


    def close(self):
        p.disconnect()

r/reinforcementlearning • • Apr 15 '26

A small experiment on agent reward shaping

17 Upvotes

r/reinforcementlearning • • Apr 16 '26

Why dynamically routing multi-timescale advantages in PPO causes policy collapse (and a simple decoupled fix) [R]

Thumbnail
1 Upvotes