train.lua 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. settings.scale * settings.crop_size,
  18. settings.upsampling_filter)
  19. image.save(file, up)
  20. end
  21. local function save_test_jpeg(model, rgb, file)
  22. local im, count = reconstruct.image(model, rgb)
  23. image.save(file, im)
  24. end
  25. local function split_data(x, test_size)
  26. local index = torch.randperm(#x)
  27. local train_size = #x - test_size
  28. local train_x = {}
  29. local valid_x = {}
  30. for i = 1, train_size do
  31. train_x[i] = x[index[i]]
  32. end
  33. for i = 1, test_size do
  34. valid_x[i] = x[index[train_size + i]]
  35. end
  36. return train_x, valid_x
  37. end
  38. local function make_validation_set(x, transformer, n, patches)
  39. n = n or 4
  40. local data = {}
  41. for i = 1, #x do
  42. for k = 1, math.max(n / patches, 1) do
  43. local xy = transformer(x[i], true, patches)
  44. for j = 1, #xy do
  45. table.insert(data, {x = xy[j][1], y = xy[j][2]})
  46. end
  47. end
  48. xlua.progress(i, #x)
  49. collectgarbage()
  50. end
  51. local new_data = {}
  52. local perm = torch.randperm(#data)
  53. for i = 1, perm:size(1) do
  54. new_data[i] = data[perm[i]]
  55. end
  56. data = new_data
  57. return data
  58. end
  59. local function validate(model, criterion, data, batch_size)
  60. local loss = 0
  61. local loss_count = 0
  62. local inputs_tmp = torch.Tensor(batch_size,
  63. data[1].x:size(1),
  64. data[1].x:size(2),
  65. data[1].x:size(3)):zero()
  66. local targets_tmp = torch.Tensor(batch_size,
  67. data[1].y:size(1),
  68. data[1].y:size(2),
  69. data[1].y:size(3)):zero()
  70. local inputs = inputs_tmp:clone():cuda()
  71. local targets = targets_tmp:clone():cuda()
  72. for t = 1, #data, batch_size do
  73. if t + batch_size -1 > #data then
  74. break
  75. end
  76. for i = 1, batch_size do
  77. inputs_tmp[i]:copy(data[t + i - 1].x)
  78. targets_tmp[i]:copy(data[t + i - 1].y)
  79. end
  80. inputs:copy(inputs_tmp)
  81. targets:copy(targets_tmp)
  82. local z = model:forward(inputs)
  83. loss = loss + criterion:forward(z, targets)
  84. loss_count = loss_count + 1
  85. if loss_count % 10 == 0 then
  86. xlua.progress(t, #data)
  87. collectgarbage()
  88. end
  89. end
  90. xlua.progress(#data, #data)
  91. return loss / loss_count
  92. end
  93. local function create_criterion(model)
  94. if reconstruct.is_rgb(model) then
  95. local offset = reconstruct.offset_size(model)
  96. local output_w = settings.crop_size - offset * 2
  97. local weight = torch.Tensor(3, output_w * output_w)
  98. weight[1]:fill(0.29891 * 3) -- R
  99. weight[2]:fill(0.58661 * 3) -- G
  100. weight[3]:fill(0.11448 * 3) -- B
  101. return w2nn.ClippedWeightedHuberCriterion(weight, 0.1, {0.0, 1.0}):cuda()
  102. else
  103. local offset = reconstruct.offset_size(model)
  104. local output_w = settings.crop_size - offset * 2
  105. local weight = torch.Tensor(1, output_w * output_w)
  106. weight[1]:fill(1.0)
  107. return w2nn.ClippedWeightedHuberCriterion(weight, 0.1, {0.0, 1.0}):cuda()
  108. end
  109. end
  110. local function transformer(model, x, is_validation, n, offset)
  111. x = compression.decompress(x)
  112. n = n or settings.patches
  113. if is_validation == nil then is_validation = false end
  114. local random_color_noise_rate = nil
  115. local random_overlay_rate = nil
  116. local active_cropping_rate = nil
  117. local active_cropping_tries = nil
  118. if is_validation then
  119. active_cropping_rate = settings.active_cropping_rate
  120. active_cropping_tries = settings.active_cropping_tries
  121. random_color_noise_rate = 0.0
  122. random_overlay_rate = 0.0
  123. else
  124. active_cropping_rate = settings.active_cropping_rate
  125. active_cropping_tries = settings.active_cropping_tries
  126. random_color_noise_rate = settings.random_color_noise_rate
  127. random_overlay_rate = settings.random_overlay_rate
  128. end
  129. if settings.method == "scale" then
  130. return pairwise_transform.scale(x,
  131. settings.scale,
  132. settings.crop_size, offset,
  133. n,
  134. {
  135. downsampling_filters = settings.downsampling_filters,
  136. upsampling_filter = settings.upsampling_filter,
  137. random_half_rate = settings.random_half_rate,
  138. random_color_noise_rate = random_color_noise_rate,
  139. random_overlay_rate = random_overlay_rate,
  140. random_unsharp_mask_rate = settings.random_unsharp_mask_rate,
  141. max_size = settings.max_size,
  142. active_cropping_rate = active_cropping_rate,
  143. active_cropping_tries = active_cropping_tries,
  144. rgb = (settings.color == "rgb"),
  145. gamma_correction = settings.gamma_correction,
  146. x_upsampling = not reconstruct.has_resize(model),
  147. resize_blur_min = settings.resize_blur_min,
  148. resize_blur_max = settings.resize_blur_max,
  149. })
  150. elseif settings.method == "noise" then
  151. return pairwise_transform.jpeg(x,
  152. settings.style,
  153. settings.noise_level,
  154. settings.crop_size, offset,
  155. n,
  156. {
  157. random_half_rate = settings.random_half_rate,
  158. random_color_noise_rate = random_color_noise_rate,
  159. random_overlay_rate = random_overlay_rate,
  160. random_unsharp_mask_rate = settings.random_unsharp_mask_rate,
  161. max_size = settings.max_size,
  162. jpeg_chroma_subsampling_rate = settings.jpeg_chroma_subsampling_rate,
  163. active_cropping_rate = active_cropping_rate,
  164. active_cropping_tries = active_cropping_tries,
  165. nr_rate = settings.nr_rate,
  166. rgb = (settings.color == "rgb")
  167. })
  168. end
  169. end
  170. local function resampling(x, y, train_x, transformer, input_size, target_size)
  171. local c = 1
  172. local shuffle = torch.randperm(#train_x)
  173. for t = 1, #train_x do
  174. xlua.progress(t, #train_x)
  175. local xy = transformer(train_x[shuffle[t]], false, settings.patches)
  176. for i = 1, #xy do
  177. x[c]:copy(xy[i][1])
  178. y[c]:copy(xy[i][2])
  179. c = c + 1
  180. if c > x:size(1) then
  181. break
  182. end
  183. end
  184. if c > x:size(1) then
  185. break
  186. end
  187. if t % 50 == 0 then
  188. collectgarbage()
  189. end
  190. end
  191. xlua.progress(#train_x, #train_x)
  192. end
  193. local function get_oracle_data(x, y, instance_loss, k, samples)
  194. local index = torch.LongTensor(instance_loss:size(1))
  195. local dummy = torch.Tensor(instance_loss:size(1))
  196. torch.topk(dummy, index, instance_loss, k, 1, true)
  197. print("average loss: " ..instance_loss:mean() .. ", average oracle loss: " .. dummy:mean())
  198. local shuffle = torch.randperm(k)
  199. local x_s = x:size()
  200. local y_s = y:size()
  201. x_s[1] = samples
  202. y_s[1] = samples
  203. local oracle_x = torch.Tensor(table.unpack(torch.totable(x_s)))
  204. local oracle_y = torch.Tensor(table.unpack(torch.totable(y_s)))
  205. for i = 1, samples do
  206. oracle_x[i]:copy(x[index[shuffle[i]]])
  207. oracle_y[i]:copy(y[index[shuffle[i]]])
  208. end
  209. return oracle_x, oracle_y
  210. end
  211. local function remove_small_image(x)
  212. local new_x = {}
  213. for i = 1, #x do
  214. local x_s = compression.size(x[i])
  215. if x_s[2] / settings.scale > settings.crop_size + 16 and
  216. x_s[3] / settings.scale > settings.crop_size + 16 then
  217. table.insert(new_x, x[i])
  218. end
  219. if i % 100 == 0 then
  220. collectgarbage()
  221. end
  222. end
  223. print(string.format("removed %d small images", #x - #new_x))
  224. return new_x
  225. end
  226. local function plot(train, valid)
  227. gnuplot.plot({
  228. {'training', torch.Tensor(train), '-'},
  229. {'validation', torch.Tensor(valid), '-'}})
  230. end
  231. local function train()
  232. local hist_train = {}
  233. local hist_valid = {}
  234. local model = srcnn.create(settings.model, settings.backend, settings.color)
  235. local offset = reconstruct.offset_size(model)
  236. local pairwise_func = function(x, is_validation, n)
  237. return transformer(model, x, is_validation, n, offset)
  238. end
  239. local criterion = create_criterion(model)
  240. local eval_metric = nn.MSECriterion():cuda()
  241. local x = remove_small_image(torch.load(settings.images))
  242. local train_x, valid_x = split_data(x, math.max(math.floor(settings.validation_rate * #x), 1))
  243. local adam_config = {
  244. learningRate = settings.learning_rate,
  245. xBatchSize = settings.batch_size,
  246. }
  247. local lrd_count = 0
  248. local ch = nil
  249. if settings.color == "y" then
  250. ch = 1
  251. elseif settings.color == "rgb" then
  252. ch = 3
  253. end
  254. local best_score = 1000.0
  255. print("# make validation-set")
  256. local valid_xy = make_validation_set(valid_x, pairwise_func,
  257. settings.validation_crops,
  258. settings.patches)
  259. valid_x = nil
  260. collectgarbage()
  261. model:cuda()
  262. print("load .. " .. #train_x)
  263. local x = nil
  264. local y = torch.Tensor(settings.patches * #train_x,
  265. ch * (settings.crop_size - offset * 2) * (settings.crop_size - offset * 2)):zero()
  266. if reconstruct.has_resize(model) then
  267. x = torch.Tensor(settings.patches * #train_x,
  268. ch, settings.crop_size / settings.scale, settings.crop_size / settings.scale)
  269. else
  270. x = torch.Tensor(settings.patches * #train_x,
  271. ch, settings.crop_size, settings.crop_size)
  272. end
  273. local instance_loss = nil
  274. for epoch = 1, settings.epoch do
  275. model:training()
  276. print("# " .. epoch)
  277. print("## resampling")
  278. if instance_loss then
  279. -- active learning
  280. local oracle_k = math.min(x:size(1) * (settings.oracle_rate * (1 / (1 - settings.oracle_drop_rate))), x:size(1))
  281. local oracle_n = math.min(x:size(1) * settings.oracle_rate, x:size(1))
  282. if oracle_n > 0 then
  283. local oracle_x, oracle_y = get_oracle_data(x, y, instance_loss, oracle_k, oracle_n)
  284. resampling(x, y, train_x, pairwise_func)
  285. x:narrow(1, 1, oracle_x:size(1)):copy(oracle_x)
  286. y:narrow(1, 1, oracle_y:size(1)):copy(oracle_y)
  287. else
  288. resampling(x, y, train_x, pairwise_func)
  289. end
  290. else
  291. resampling(x, y, train_x, pairwise_func)
  292. end
  293. collectgarbage()
  294. instance_loss = torch.Tensor(x:size(1)):zero()
  295. for i = 1, settings.inner_epoch do
  296. local train_score, il = minibatch_adam(model, criterion, eval_metric, x, y, adam_config)
  297. instance_loss:copy(il)
  298. print(train_score)
  299. model:evaluate()
  300. print("# validation")
  301. local score = validate(model, eval_metric, valid_xy, adam_config.xBatchSize)
  302. table.insert(hist_train, train_score.MSE)
  303. table.insert(hist_valid, score)
  304. if settings.plot then
  305. plot(hist_train, hist_valid)
  306. end
  307. if score < best_score then
  308. local test_image = image_loader.load_float(settings.test) -- reload
  309. lrd_count = 0
  310. best_score = score
  311. print("* update best model")
  312. if settings.save_history then
  313. torch.save(string.format(settings.model_file, epoch, i), model:clearState(), "ascii")
  314. if settings.method == "noise" then
  315. local log = path.join(settings.model_dir,
  316. ("noise%d_best.%d-%d.png"):format(settings.noise_level,
  317. epoch, i))
  318. save_test_jpeg(model, test_image, log)
  319. elseif settings.method == "scale" then
  320. local log = path.join(settings.model_dir,
  321. ("scale%.1f_best.%d-%d.png"):format(settings.scale,
  322. epoch, i))
  323. save_test_scale(model, test_image, log)
  324. end
  325. else
  326. torch.save(settings.model_file, model:clearState(), "ascii")
  327. if settings.method == "noise" then
  328. local log = path.join(settings.model_dir,
  329. ("noise%d_best.png"):format(settings.noise_level))
  330. save_test_jpeg(model, test_image, log)
  331. elseif settings.method == "scale" then
  332. local log = path.join(settings.model_dir,
  333. ("scale%.1f_best.png"):format(settings.scale))
  334. save_test_scale(model, test_image, log)
  335. end
  336. end
  337. else
  338. lrd_count = lrd_count + 1
  339. if lrd_count > 2 then
  340. adam_config.learningRate = adam_config.learningRate * 0.874
  341. print("* learning rate decay: " .. adam_config.learningRate)
  342. lrd_count = 0
  343. end
  344. end
  345. print("PSNR: " .. 10 * math.log10(1 / score) .. ", MSE: " .. score .. ", Best MSE: " .. best_score)
  346. collectgarbage()
  347. end
  348. end
  349. end
  350. if settings.gpu > 0 then
  351. cutorch.setDevice(settings.gpu)
  352. end
  353. torch.manualSeed(settings.seed)
  354. cutorch.manualSeed(settings.seed)
  355. print(settings)
  356. train()