cleanup_model.lua 1.9 KB

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