train.lua 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. return nn.MSECriterion():cuda()
  79. end
  80. end
  81. local function transformer(x, is_validation, n, offset)
  82. x = compression.decompress(x)
  83. n = n or settings.patches
  84. if is_validation == nil then is_validation = false end
  85. local random_color_noise_rate = nil
  86. local random_overlay_rate = nil
  87. local active_cropping_rate = nil
  88. local active_cropping_tries = nil
  89. if is_validation then
  90. active_cropping_rate = 0
  91. active_cropping_tries = 0
  92. random_color_noise_rate = 0.0
  93. random_overlay_rate = 0.0
  94. else
  95. active_cropping_rate = settings.active_cropping_rate
  96. active_cropping_tries = settings.active_cropping_tries
  97. random_color_noise_rate = settings.random_color_noise_rate
  98. random_overlay_rate = settings.random_overlay_rate
  99. end
  100. if settings.method == "scale" then
  101. return pairwise_transform.scale(x,
  102. settings.scale,
  103. settings.crop_size, offset,
  104. n,
  105. {
  106. random_half_rate = settings.random_half_rate,
  107. random_color_noise_rate = random_color_noise_rate,
  108. random_overlay_rate = random_overlay_rate,
  109. random_unsharp_mask_rate = settings.random_unsharp_mask_rate,
  110. max_size = settings.max_size,
  111. active_cropping_rate = active_cropping_rate,
  112. active_cropping_tries = active_cropping_tries,
  113. rgb = (settings.color == "rgb")
  114. })
  115. elseif settings.method == "noise" then
  116. return pairwise_transform.jpeg(x,
  117. settings.style,
  118. settings.noise_level,
  119. settings.crop_size, offset,
  120. n,
  121. {
  122. random_half_rate = settings.random_half_rate,
  123. random_color_noise_rate = random_color_noise_rate,
  124. random_overlay_rate = random_overlay_rate,
  125. random_unsharp_mask_rate = settings.random_unsharp_mask_rate,
  126. max_size = settings.max_size,
  127. jpeg_chroma_subsampling_rate = settings.jpeg_chroma_subsampling_rate,
  128. active_cropping_rate = active_cropping_rate,
  129. active_cropping_tries = active_cropping_tries,
  130. nr_rate = settings.nr_rate,
  131. rgb = (settings.color == "rgb")
  132. })
  133. end
  134. end
  135. local function resampling(x, y, train_x, transformer, input_size, target_size)
  136. print("## resampling")
  137. for t = 1, #train_x do
  138. xlua.progress(t, #train_x)
  139. local xy = transformer(train_x[t], false, settings.patches)
  140. for i = 1, #xy do
  141. local index = (t - 1) * settings.patches + i
  142. x[index]:copy(xy[i][1])
  143. y[index]:copy(xy[i][2])
  144. end
  145. if t % 50 == 0 then
  146. collectgarbage()
  147. end
  148. end
  149. end
  150. local function train()
  151. local LR_MIN = 1.0e-5
  152. local model = srcnn.create(settings.method, settings.backend, settings.color)
  153. local offset = reconstruct.offset_size(model)
  154. local pairwise_func = function(x, is_validation, n)
  155. return transformer(x, is_validation, n, offset)
  156. end
  157. local criterion = create_criterion(model)
  158. local x = torch.load(settings.images)
  159. local train_x, valid_x = split_data(x, math.floor(settings.validation_rate * #x))
  160. local adam_config = {
  161. learningRate = settings.learning_rate,
  162. xBatchSize = settings.batch_size,
  163. }
  164. local lrd_count = 0
  165. local ch = nil
  166. if settings.color == "y" then
  167. ch = 1
  168. elseif settings.color == "rgb" then
  169. ch = 3
  170. end
  171. local best_score = 100000.0
  172. print("# make validation-set")
  173. local valid_xy = make_validation_set(valid_x, pairwise_func,
  174. settings.validation_crops,
  175. settings.patches)
  176. valid_x = nil
  177. collectgarbage()
  178. model:cuda()
  179. print("load .. " .. #train_x)
  180. local x = torch.Tensor(settings.patches * #train_x,
  181. ch, settings.crop_size, settings.crop_size)
  182. local y = torch.Tensor(settings.patches * #train_x,
  183. ch * (settings.crop_size - offset * 2) * (settings.crop_size - offset * 2)):zero()
  184. for epoch = 1, settings.epoch do
  185. model:training()
  186. print("# " .. epoch)
  187. resampling(x, y, train_x, pairwise_func)
  188. for i = 1, settings.inner_epoch do
  189. print(minibatch_adam(model, criterion, x, y, adam_config))
  190. model:evaluate()
  191. print("# validation")
  192. local score = validate(model, criterion, valid_xy)
  193. if score < best_score then
  194. local test_image = image_loader.load_float(settings.test) -- reload
  195. lrd_count = 0
  196. best_score = score
  197. print("* update best model")
  198. torch.save(settings.model_file, model)
  199. if settings.method == "noise" then
  200. local log = path.join(settings.model_dir,
  201. ("noise%d_best.png"):format(settings.noise_level))
  202. save_test_jpeg(model, test_image, log)
  203. elseif settings.method == "scale" then
  204. local log = path.join(settings.model_dir,
  205. ("scale%.1f_best.png"):format(settings.scale))
  206. save_test_scale(model, test_image, log)
  207. end
  208. else
  209. lrd_count = lrd_count + 1
  210. if lrd_count > 2 and adam_config.learningRate > LR_MIN then
  211. adam_config.learningRate = adam_config.learningRate * 0.8
  212. print("* learning rate decay: " .. adam_config.learningRate)
  213. lrd_count = 0
  214. end
  215. end
  216. print("current: " .. score .. ", best: " .. best_score)
  217. collectgarbage()
  218. end
  219. end
  220. end
  221. if settings.gpu > 0 then
  222. cutorch.setDevice(settings.gpu)
  223. end
  224. torch.manualSeed(settings.seed)
  225. cutorch.manualSeed(settings.seed)
  226. print(settings)
  227. train()