Fixed bug which occured when repeatedly switching between cpu and gpu.