keenon / nimblephysics

Nimble: Physics Engine for Biomechanics and Deep Learning
http://www.nimblephysics.org
Other
390 stars 43 forks source link

Calculating Loss from Contact Forces #196

Open cdagher opened 10 months ago

cdagher commented 10 months ago

I would like to use contact forces to calculate a loss, and then calculate a gradient from the loss. The specific problem I'm trying to solve with this is simulating two bouncing balls. One ball has a known mass, and the other has a guessed mass. The simulation results would then be used to learn the known mass. This requires calling something like loss.backward(), then optimizing the guessed mass to match the known mass. However, when I call loss.backward(), I get "RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn."

My method for calculating loss is as follows:

  1. Create two lists of tensors, one for each ball.
  2. Append the Z component of the ball's contact forces at each state for the respective lists.
  3. Take the dot product of each list with itself, and add the results. Store this result in a new tensor.
  4. Sum the elements of this resultant tensor, and divide by the total simulation timesteps.

The problem occurs when I get the forces. While step has a grad_fn defined, the forces do not have a grad_fn. To get the forces, I am calling getConstraintForces() for each ball's skeleton, and using only the index for the Z component of the contact force.

Is there a way to retain the differentiability of this, or is there a better way to approach this?