export_model.lua 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 meta_data(model)
  8. local meta = {}
  9. for k, v in pairs(model) do
  10. if k:match("w2nn_") then
  11. meta[k:gsub("w2nn_", "")] = v
  12. end
  13. end
  14. return meta
  15. end
  16. function includes(s, a)
  17. for i = 1, #a do
  18. if s == a[i] then
  19. return true
  20. end
  21. end
  22. return false
  23. end
  24. function export(model, output)
  25. local targets = {"nn.SpatialConvolutionMM",
  26. "cudnn.SpatialConvolution",
  27. "nn.SpatialFullConvolution",
  28. "cudnn.SpatialFullConvolution"
  29. }
  30. local jmodules = {}
  31. local model_config = meta_data(model)
  32. local first_layer = true
  33. for k = 1, #model.modules do
  34. local mod = model.modules[k]
  35. local name = torch.typename(mod)
  36. if includes(name, targets) then
  37. local weight = mod.weight:float()
  38. if name:match("FullConvolution") then
  39. weight = torch.totable(weight:reshape(mod.nInputPlane, mod.nOutputPlane, mod.kH, mod.kW))
  40. else
  41. weight = torch.totable(weight:reshape(mod.nOutputPlane, mod.nInputPlane, mod.kH, mod.kW))
  42. end
  43. local jmod = {
  44. class_name = name,
  45. kW = mod.kW,
  46. kH = mod.kH,
  47. dH = mod.dH,
  48. dW = mod.dW,
  49. padW = mod.padW,
  50. padH = mod.padH,
  51. nInputPlane = mod.nInputPlane,
  52. nOutputPlane = mod.nOutputPlane,
  53. bias = torch.totable(mod.bias:float()),
  54. weight = weight
  55. }
  56. if first_layer then
  57. first_layer = false
  58. jmod.model_config = model_config
  59. end
  60. table.insert(jmodules, jmod)
  61. end
  62. end
  63. local fp = io.open(output, "w")
  64. if not fp then
  65. error("IO Error: " .. output)
  66. end
  67. fp:write(cjson.encode(jmodules))
  68. fp:close()
  69. end
  70. local cmd = torch.CmdLine()
  71. cmd:text()
  72. cmd:text("waifu2x export model")
  73. cmd:text("Options:")
  74. cmd:option("-i", "input.t7", 'Specify the input torch model')
  75. cmd:option("-o", "output.json", 'Specify the output json file')
  76. cmd:option("-iformat", "ascii", 'Specify the input format (ascii|binary)')
  77. local opt = cmd:parse(arg)
  78. if not path.isfile(opt.i) then
  79. cmd:help()
  80. os.exit(-1)
  81. end
  82. local model = torch.load(opt.i, opt.iformat)
  83. export(model, opt.o)