cleanup_model.lua 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. require './lib/portable'
  2. require './lib/LeakyReLU'
  3. torch.setdefaulttensortype("torch.FloatTensor")
  4. -- ref: https://github.com/torch/nn/issues/112#issuecomment-64427049
  5. local function zeroDataSize(data)
  6. if type(data) == 'table' then
  7. for i = 1, #data do
  8. data[i] = zeroDataSize(data[i])
  9. end
  10. elseif type(data) == 'userdata' then
  11. data = torch.Tensor():typeAs(data)
  12. end
  13. return data
  14. end
  15. -- Resize the output, gradInput, etc temporary tensors to zero (so that the
  16. -- on disk size is smaller)
  17. local function cleanupModel(node)
  18. if node.output ~= nil then
  19. node.output = zeroDataSize(node.output)
  20. end
  21. if node.gradInput ~= nil then
  22. node.gradInput = zeroDataSize(node.gradInput)
  23. end
  24. if node.finput ~= nil then
  25. node.finput = zeroDataSize(node.finput)
  26. end
  27. if tostring(node) == "nn.LeakyReLU" then
  28. if node.negative ~= nil then
  29. node.negative = zeroDataSize(node.negative)
  30. end
  31. end
  32. if tostring(node) == "nn.Dropout" then
  33. if node.noise ~= nil then
  34. node.noise = zeroDataSize(node.noise)
  35. end
  36. end
  37. -- Recurse on nodes with 'modules'
  38. if (node.modules ~= nil) then
  39. if (type(node.modules) == 'table') then
  40. for i = 1, #node.modules do
  41. local child = node.modules[i]
  42. cleanupModel(child)
  43. end
  44. end
  45. end
  46. collectgarbage()
  47. end
  48. local cmd = torch.CmdLine()
  49. cmd:text()
  50. cmd:text("cleanup model")
  51. cmd:text("Options:")
  52. cmd:option("-model", "./model.t7", 'path of model file')
  53. cmd:option("-iformat", "binary", 'input format')
  54. cmd:option("-oformat", "binary", 'output format')
  55. local opt = cmd:parse(arg)
  56. local model = torch.load(opt.model, opt.iformat)
  57. if model then
  58. cleanupModel(model)
  59. torch.save(opt.model, model, opt.oformat)
  60. else
  61. error("model not found")
  62. end