Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug fix for space leak on too frequent calls to performGC #660

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions hasktorch/hasktorch.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ library
, megaparsec
, half
, constraints
, auto-update

default-extensions: Strict
, StrictData
Expand Down
13 changes: 12 additions & 1 deletion hasktorch/src/Torch/Optim.hs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import Torch.Autograd
import Torch.Functional
import Torch.Internal.GC (mallocTrim)
import Torch.NN
import System.IO.Unsafe (unsafePerformIO)
import Control.Debounce
import Torch.Tensor
import Torch.TensorFactories
import Prelude hiding (sqrt)
Expand All @@ -23,6 +25,15 @@ newtype OptimizerState option = OptimizerState option
grad' :: Loss -> [Parameter] -> Gradients
grad' t p = Gradients (grad t p)

-- | Action that performs garbage collection with a minimum waiting time between calls to `performGC`. This prevents a space leak, that occurs when calling `performGC` too frequently.
performGC' :: IO ()
performGC' = unsafePerformIO $ do
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think unsafePerformIO should not be added.
It may disappear these codes.

mkDebounce defaultDebounceSettings
{ debounceAction = performGC
, debounceEdge = leadingEdge
, debounceFreq = 1000000
}

class Optimizer optimizer where
step :: LearningRate -> Gradients -> [Tensor] -> optimizer -> ([Tensor], optimizer)

Expand All @@ -33,7 +44,7 @@ class Optimizer optimizer where
-- | run a single iteration of an optimizer, returning new parameters and updated optimizer state
runStep' :: (Parameterized model) => model -> optimizer -> Gradients -> LearningRate -> IO (model, optimizer)
runStep' paramState optState gradients lr = do
performGC
performGC'
mallocTrim 0
let (flatParameters', optState') = step lr gradients depParameters optState
newFlatParam <- mapM makeIndependent flatParameters'
Expand Down