export_model.lua 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. -- adapted from https://github.com/marcan/cl-waifu2x
  2. require 'pl'
  3. local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)()
  4. package.path = path.join(path.dirname(__FILE__), "..", "lib", "?.lua;") .. package.path
  5. require 'w2nn'
  6. local cjson = require "cjson"
  7. function export(model, output)
  8. local jmodules = {}
  9. local modules = model:findModules("nn.SpatialConvolutionMM")
  10. if #modules == 0 then
  11. -- cudnn model
  12. modules = model:findModules("cudnn.SpatialConvolution")
  13. end
  14. for i = 1, #modules, 1 do
  15. local module = modules[i]
  16. local jmod = {
  17. kW = module.kW,
  18. kH = module.kH,
  19. nInputPlane = module.nInputPlane,
  20. nOutputPlane = module.nOutputPlane,
  21. bias = torch.totable(module.bias:float()),
  22. weight = torch.totable(module.weight:float():reshape(module.nOutputPlane, module.nInputPlane, module.kW, module.kH))
  23. }
  24. table.insert(jmodules, jmod)
  25. end
  26. local fp = io.open(output, "w")
  27. if not fp then
  28. error("IO Error: " .. output)
  29. end
  30. fp:write(cjson.encode(jmodules))
  31. fp:close()
  32. end
  33. local cmd = torch.CmdLine()
  34. cmd:text()
  35. cmd:text("waifu2x export model")
  36. cmd:text("Options:")
  37. cmd:option("-i", "input.t7", 'Specify the input torch model')
  38. cmd:option("-o", "output.json", 'Specify the output json file')
  39. cmd:option("-iformat", "ascii", 'Specify the input format (ascii|binary)')
  40. local opt = cmd:parse(arg)
  41. if not path.isfile(opt.i) then
  42. cmd:help()
  43. os.exit(-1)
  44. end
  45. local model = torch.load(opt.i, opt.iformat)
  46. export(model, opt.o)