export_model.lua 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. jmodules[1].color = "RGB"
  27. jmodules[1].gamma = 0
  28. jmodules[#jmodules].color = "RGB"
  29. jmodules[#jmodules].gamma = 0
  30. local fp = io.open(output, "w")
  31. if not fp then
  32. error("IO Error: " .. output)
  33. end
  34. fp:write(cjson.encode(jmodules))
  35. fp:close()
  36. end
  37. local cmd = torch.CmdLine()
  38. cmd:text()
  39. cmd:text("waifu2x export model")
  40. cmd:text("Options:")
  41. cmd:option("-i", "input.t7", 'Specify the input torch model')
  42. cmd:option("-o", "output.json", 'Specify the output json file')
  43. cmd:option("-iformat", "ascii", 'Specify the input format (ascii|binary)')
  44. local opt = cmd:parse(arg)
  45. if not path.isfile(opt.i) then
  46. cmd:help()
  47. os.exit(-1)
  48. end
  49. local model = torch.load(opt.i, opt.iformat)
  50. export(model, opt.o)