Thread local

This series of commits make torch thread-safe.