train.lua 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. require 'pl'
  2. local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)()
  3. package.path = path.join(path.dirname(__FILE__), "lib", "?.lua;") .. package.path
  4. require 'optim'
  5. require 'xlua'
  6. require 'w2nn'
  7. local settings = require 'settings'
  8. local srcnn = require 'srcnn'
  9. local minibatch_adam = require 'minibatch_adam'
  10. local iproc = require 'iproc'
  11. local reconstruct = require 'reconstruct'
  12. local compression = require 'compression'
  13. local pairwise_transform = require 'pairwise_transform'
  14. local image_loader = require 'image_loader'
  15. local function save_test_scale(model, rgb, file)
  16. local up = reconstruct.scale(model, settings.scale, rgb)
  17. image.save(file, up)
  18. end
  19. local function save_test_jpeg(model, rgb, file)
  20. local im, count = reconstruct.image(model, rgb)
  21. image.save(file, im)
  22. end
  23. local function split_data(x, test_size)
  24. local index = torch.randperm(#x)
  25. local train_size = #x - test_size
  26. local train_x = {}
  27. local valid_x = {}
  28. for i = 1, train_size do
  29. train_x[i] = x[index[i]]
  30. end
  31. for i = 1, test_size do
  32. valid_x[i] = x[index[train_size + i]]
  33. end
  34. return train_x, valid_x
  35. end
  36. local function make_validation_set(x, transformer, n, patches)
  37. n = n or 4
  38. local data = {}
  39. for i = 1, #x do
  40. for k = 1, math.max(n / patches, 1) do
  41. local xy = transformer(x[i], true, patches)
  42. local tx = torch.Tensor(patches, xy[1][1]:size(1), xy[1][1]:size(2), xy[1][1]:size(3))
  43. local ty = torch.Tensor(patches, xy[1][2]:size(1), xy[1][2]:size(2), xy[1][2]:size(3))
  44. for j = 1, #xy do
  45. tx[j]:copy(xy[j][1])
  46. ty[j]:copy(xy[j][2])
  47. end
  48. table.insert(data, {x = tx, y = ty})
  49. end
  50. xlua.progress(i, #x)
  51. collectgarbage()
  52. end
  53. return data
  54. end
  55. local function validate(model, criterion, data)
  56. local loss = 0
  57. for i = 1, #data do
  58. local z = model:forward(data[i].x:cuda())
  59. loss = loss + criterion:forward(z, data[i].y:cuda())
  60. if i % 100 == 0 then
  61. xlua.progress(i, #data)
  62. collectgarbage()
  63. end
  64. end
  65. xlua.progress(#data, #data)
  66. return loss / #data
  67. end
  68. local function create_criterion(model)
  69. if reconstruct.is_rgb(model) then
  70. local offset = reconstruct.offset_size(model)
  71. local output_w = settings.crop_size - offset * 2
  72. local weight = torch.Tensor(3, output_w * output_w)
  73. weight[1]:fill(0.29891 * 3) -- R
  74. weight[2]:fill(0.58661 * 3) -- G
  75. weight[3]:fill(0.11448 * 3) -- B
  76. return w2nn.ClippedWeightedHuberCriterion(weight, 0.1, {0.0, 1.0}):cuda()
  77. else
  78. local offset = reconstruct.offset_size(model)
  79. local output_w = settings.crop_size - offset * 2
  80. local weight = torch.Tensor(1, output_w * output_w)
  81. weight[1]:fill(1.0)
  82. return w2nn.ClippedWeightedHuberCriterion(weight, 0.1, {0.0, 1.0}):cuda()
  83. end
  84. end
  85. local function transformer(x, is_validation, n, offset)
  86. x = compression.decompress(x)
  87. n = n or settings.patches
  88. if is_validation == nil then is_validation = false end
  89. local random_color_noise_rate = nil
  90. local random_overlay_rate = nil
  91. local active_cropping_rate = nil
  92. local active_cropping_tries = nil
  93. if is_validation then
  94. active_cropping_rate = settings.active_cropping_rate
  95. active_cropping_tries = settings.active_cropping_tries
  96. random_color_noise_rate = 0.0
  97. random_overlay_rate = 0.0
  98. else
  99. active_cropping_rate = settings.active_cropping_rate
  100. active_cropping_tries = settings.active_cropping_tries
  101. random_color_noise_rate = settings.random_color_noise_rate
  102. random_overlay_rate = settings.random_overlay_rate
  103. end
  104. if settings.method == "scale" then
  105. return pairwise_transform.scale(x,
  106. settings.scale,
  107. settings.crop_size, offset,
  108. n,
  109. {
  110. random_half_rate = settings.random_half_rate,
  111. random_color_noise_rate = random_color_noise_rate,
  112. random_overlay_rate = random_overlay_rate,
  113. random_unsharp_mask_rate = settings.random_unsharp_mask_rate,
  114. max_size = settings.max_size,
  115. active_cropping_rate = active_cropping_rate,
  116. active_cropping_tries = active_cropping_tries,
  117. rgb = (settings.color == "rgb")
  118. })
  119. elseif settings.method == "noise" then
  120. return pairwise_transform.jpeg(x,
  121. settings.style,
  122. settings.noise_level,
  123. settings.crop_size, offset,
  124. n,
  125. {
  126. random_half_rate = settings.random_half_rate,
  127. random_color_noise_rate = random_color_noise_rate,
  128. random_overlay_rate = random_overlay_rate,
  129. random_unsharp_mask_rate = settings.random_unsharp_mask_rate,
  130. max_size = settings.max_size,
  131. jpeg_chroma_subsampling_rate = settings.jpeg_chroma_subsampling_rate,
  132. active_cropping_rate = active_cropping_rate,
  133. active_cropping_tries = active_cropping_tries,
  134. nr_rate = settings.nr_rate,
  135. rgb = (settings.color == "rgb")
  136. })
  137. end
  138. end
  139. local function resampling(x, y, train_x, transformer, input_size, target_size)
  140. print("## resampling")
  141. for t = 1, #train_x do
  142. xlua.progress(t, #train_x)
  143. local xy = transformer(train_x[t], false, settings.patches)
  144. for i = 1, #xy do
  145. local index = (t - 1) * settings.patches + i
  146. x[index]:copy(xy[i][1])
  147. y[index]:copy(xy[i][2])
  148. end
  149. if t % 50 == 0 then
  150. collectgarbage()
  151. end
  152. end
  153. end
  154. local function train()
  155. local LR_MIN = 1.0e-5
  156. local model = srcnn.create(settings.method, settings.backend, settings.color)
  157. local offset = reconstruct.offset_size(model)
  158. local pairwise_func = function(x, is_validation, n)
  159. return transformer(x, is_validation, n, offset)
  160. end
  161. local criterion = create_criterion(model)
  162. local eval_metric = w2nn.PSNRCriterion():cuda()
  163. local x = torch.load(settings.images)
  164. local train_x, valid_x = split_data(x, math.floor(settings.validation_rate * #x))
  165. local adam_config = {
  166. learningRate = settings.learning_rate,
  167. xBatchSize = settings.batch_size,
  168. }
  169. local lrd_count = 0
  170. local ch = nil
  171. if settings.color == "y" then
  172. ch = 1
  173. elseif settings.color == "rgb" then
  174. ch = 3
  175. end
  176. local best_score = 0.0
  177. print("# make validation-set")
  178. local valid_xy = make_validation_set(valid_x, pairwise_func,
  179. settings.validation_crops,
  180. settings.patches)
  181. valid_x = nil
  182. collectgarbage()
  183. model:cuda()
  184. print("load .. " .. #train_x)
  185. local x = torch.Tensor(settings.patches * #train_x,
  186. ch, settings.crop_size, settings.crop_size)
  187. local y = torch.Tensor(settings.patches * #train_x,
  188. ch * (settings.crop_size - offset * 2) * (settings.crop_size - offset * 2)):zero()
  189. for epoch = 1, settings.epoch do
  190. model:training()
  191. print("# " .. epoch)
  192. resampling(x, y, train_x, pairwise_func)
  193. for i = 1, settings.inner_epoch do
  194. print(minibatch_adam(model, criterion, eval_metric, x, y, adam_config))
  195. model:evaluate()
  196. print("# validation")
  197. local score = validate(model, eval_metric, valid_xy)
  198. if score > best_score then
  199. local test_image = image_loader.load_float(settings.test) -- reload
  200. lrd_count = 0
  201. best_score = score
  202. print("* update best model")
  203. if settings.save_history then
  204. torch.save(string.format(settings.model_file, epoch, i), model:clearState(), "ascii")
  205. if settings.method == "noise" then
  206. local log = path.join(settings.model_dir,
  207. ("noise%d_best.%d-%d.png"):format(settings.noise_level,
  208. epoch, i))
  209. save_test_jpeg(model, test_image, log)
  210. elseif settings.method == "scale" then
  211. local log = path.join(settings.model_dir,
  212. ("scale%.1f_best.%d-%d.png"):format(settings.scale,
  213. epoch, i))
  214. save_test_scale(model, test_image, log)
  215. end
  216. else
  217. torch.save(settings.model_file, model:clearState(), "ascii")
  218. if settings.method == "noise" then
  219. local log = path.join(settings.model_dir,
  220. ("noise%d_best.png"):format(settings.noise_level))
  221. save_test_jpeg(model, test_image, log)
  222. elseif settings.method == "scale" then
  223. local log = path.join(settings.model_dir,
  224. ("scale%.1f_best.png"):format(settings.scale))
  225. save_test_scale(model, test_image, log)
  226. end
  227. end
  228. else
  229. lrd_count = lrd_count + 1
  230. if lrd_count > 2 and adam_config.learningRate > LR_MIN then
  231. adam_config.learningRate = adam_config.learningRate * 0.8
  232. print("* learning rate decay: " .. adam_config.learningRate)
  233. lrd_count = 0
  234. end
  235. end
  236. print("current: " .. score .. ", best: " .. best_score)
  237. collectgarbage()
  238. end
  239. end
  240. end
  241. if settings.gpu > 0 then
  242. cutorch.setDevice(settings.gpu)
  243. end
  244. torch.manualSeed(settings.seed)
  245. cutorch.manualSeed(settings.seed)
  246. print(settings)
  247. train()