train.lua 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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, eval_metric, data, batch_size)
  60. local loss = 0
  61. local mse = 0
  62. local loss_count = 0
  63. local inputs_tmp = torch.Tensor(batch_size,
  64. data[1].x:size(1),
  65. data[1].x:size(2),
  66. data[1].x:size(3)):zero()
  67. local targets_tmp = torch.Tensor(batch_size,
  68. data[1].y:size(1),
  69. data[1].y:size(2),
  70. data[1].y:size(3)):zero()
  71. local inputs = inputs_tmp:clone():cuda()
  72. local targets = targets_tmp:clone():cuda()
  73. for t = 1, #data, batch_size do
  74. if t + batch_size -1 > #data then
  75. break
  76. end
  77. for i = 1, batch_size do
  78. inputs_tmp[i]:copy(data[t + i - 1].x)
  79. targets_tmp[i]:copy(data[t + i - 1].y)
  80. end
  81. inputs:copy(inputs_tmp)
  82. targets:copy(targets_tmp)
  83. local z = model:forward(inputs)
  84. loss = loss + criterion:forward(z, targets)
  85. mse = mse + eval_metric:forward(z, targets)
  86. loss_count = loss_count + 1
  87. if loss_count % 10 == 0 then
  88. xlua.progress(t, #data)
  89. collectgarbage()
  90. end
  91. end
  92. xlua.progress(#data, #data)
  93. return {loss = loss / loss_count, MSE = mse / loss_count, PSNR = 10 * math.log10(1 / (mse / loss_count))}
  94. end
  95. local function create_criterion(model, loss)
  96. if reconstruct.is_rgb(model) then
  97. local offset = reconstruct.offset_size(model)
  98. local output_w = settings.crop_size - offset * 2
  99. local weight = torch.Tensor(3, output_w * output_w)
  100. if loss == "y" then
  101. weight[1]:fill(0.29891 * 3) -- R
  102. weight[2]:fill(0.58661 * 3) -- G
  103. weight[3]:fill(0.11448 * 3) -- B
  104. else
  105. weight:fill(1)
  106. end
  107. return w2nn.ClippedWeightedHuberCriterion(weight, 0.1, {0.0, 1.0}):cuda()
  108. else
  109. local offset = reconstruct.offset_size(model)
  110. local output_w = settings.crop_size - offset * 2
  111. local weight = torch.Tensor(1, output_w * output_w)
  112. weight[1]:fill(1.0)
  113. return w2nn.ClippedWeightedHuberCriterion(weight, 0.1, {0.0, 1.0}):cuda()
  114. end
  115. end
  116. local function transformer(model, x, is_validation, n, offset)
  117. local meta = {data = {}}
  118. if type(x) == "table" and type(x[2]) == "table" then
  119. meta = x[2]
  120. x = compression.decompress(x[1])
  121. else
  122. x = compression.decompress(x)
  123. end
  124. n = n or settings.patches
  125. if is_validation == nil then is_validation = false end
  126. local random_color_noise_rate = nil
  127. local random_overlay_rate = nil
  128. local active_cropping_rate = nil
  129. local active_cropping_tries = nil
  130. if is_validation then
  131. active_cropping_rate = settings.active_cropping_rate
  132. active_cropping_tries = settings.active_cropping_tries
  133. random_color_noise_rate = 0.0
  134. random_overlay_rate = 0.0
  135. else
  136. active_cropping_rate = settings.active_cropping_rate
  137. active_cropping_tries = settings.active_cropping_tries
  138. random_color_noise_rate = settings.random_color_noise_rate
  139. random_overlay_rate = settings.random_overlay_rate
  140. end
  141. if settings.method == "scale" then
  142. local conf = tablex.update({
  143. downsampling_filters = settings.downsampling_filters,
  144. upsampling_filter = settings.upsampling_filter,
  145. random_half_rate = settings.random_half_rate,
  146. random_color_noise_rate = random_color_noise_rate,
  147. random_overlay_rate = random_overlay_rate,
  148. random_unsharp_mask_rate = settings.random_unsharp_mask_rate,
  149. max_size = settings.max_size,
  150. active_cropping_rate = active_cropping_rate,
  151. active_cropping_tries = active_cropping_tries,
  152. rgb = (settings.color == "rgb"),
  153. gamma_correction = settings.gamma_correction,
  154. x_upsampling = not reconstruct.has_resize(model),
  155. resize_blur_min = settings.resize_blur_min,
  156. resize_blur_max = settings.resize_blur_max}, meta)
  157. return pairwise_transform.scale(x,
  158. settings.scale,
  159. settings.crop_size, offset,
  160. n, conf)
  161. elseif settings.method == "noise" then
  162. local conf = tablex.update({
  163. random_half_rate = settings.random_half_rate,
  164. random_color_noise_rate = random_color_noise_rate,
  165. random_overlay_rate = random_overlay_rate,
  166. random_unsharp_mask_rate = settings.random_unsharp_mask_rate,
  167. max_size = settings.max_size,
  168. jpeg_chroma_subsampling_rate = settings.jpeg_chroma_subsampling_rate,
  169. active_cropping_rate = active_cropping_rate,
  170. active_cropping_tries = active_cropping_tries,
  171. nr_rate = settings.nr_rate,
  172. rgb = (settings.color == "rgb")}, meta)
  173. return pairwise_transform.jpeg(x,
  174. settings.style,
  175. settings.noise_level,
  176. settings.crop_size, offset,
  177. n, conf)
  178. elseif settings.method == "noise_scale" then
  179. local conf = tablex.update({
  180. downsampling_filters = settings.downsampling_filters,
  181. upsampling_filter = settings.upsampling_filter,
  182. random_half_rate = settings.random_half_rate,
  183. random_color_noise_rate = random_color_noise_rate,
  184. random_overlay_rate = random_overlay_rate,
  185. random_unsharp_mask_rate = settings.random_unsharp_mask_rate,
  186. max_size = settings.max_size,
  187. jpeg_chroma_subsampling_rate = settings.jpeg_chroma_subsampling_rate,
  188. nr_rate = settings.nr_rate,
  189. active_cropping_rate = active_cropping_rate,
  190. active_cropping_tries = active_cropping_tries,
  191. rgb = (settings.color == "rgb"),
  192. gamma_correction = settings.gamma_correction,
  193. x_upsampling = not reconstruct.has_resize(model),
  194. resize_blur_min = settings.resize_blur_min,
  195. resize_blur_max = settings.resize_blur_max}, meta)
  196. return pairwise_transform.jpeg_scale(x,
  197. settings.scale,
  198. settings.style,
  199. settings.noise_level,
  200. settings.crop_size, offset,
  201. n, conf)
  202. end
  203. end
  204. local function resampling(x, y, train_x, transformer, input_size, target_size)
  205. local c = 1
  206. local shuffle = torch.randperm(#train_x)
  207. for t = 1, #train_x do
  208. xlua.progress(t, #train_x)
  209. local xy = transformer(train_x[shuffle[t]], false, settings.patches)
  210. for i = 1, #xy do
  211. x[c]:copy(xy[i][1])
  212. y[c]:copy(xy[i][2])
  213. c = c + 1
  214. if c > x:size(1) then
  215. break
  216. end
  217. end
  218. if c > x:size(1) then
  219. break
  220. end
  221. if t % 50 == 0 then
  222. collectgarbage()
  223. end
  224. end
  225. xlua.progress(#train_x, #train_x)
  226. end
  227. local function get_oracle_data(x, y, instance_loss, k, samples)
  228. local index = torch.LongTensor(instance_loss:size(1))
  229. local dummy = torch.Tensor(instance_loss:size(1))
  230. torch.topk(dummy, index, instance_loss, k, 1, true)
  231. print("MSE of all data: " ..instance_loss:mean() .. ", MSE of oracle data: " .. dummy:mean())
  232. local shuffle = torch.randperm(k)
  233. local x_s = x:size()
  234. local y_s = y:size()
  235. x_s[1] = samples
  236. y_s[1] = samples
  237. local oracle_x = torch.Tensor(table.unpack(torch.totable(x_s)))
  238. local oracle_y = torch.Tensor(table.unpack(torch.totable(y_s)))
  239. for i = 1, samples do
  240. oracle_x[i]:copy(x[index[shuffle[i]]])
  241. oracle_y[i]:copy(y[index[shuffle[i]]])
  242. end
  243. return oracle_x, oracle_y
  244. end
  245. local function remove_small_image(x)
  246. local new_x = {}
  247. for i = 1, #x do
  248. local xe, meta, x_s
  249. xe = x[i]
  250. if type(xe) == "table" and type(xe[2]) == "table" then
  251. x_s = compression.size(xe[1])
  252. else
  253. x_s = compression.size(xe)
  254. end
  255. if x_s[2] / settings.scale > settings.crop_size + 32 and
  256. x_s[3] / settings.scale > settings.crop_size + 32 then
  257. table.insert(new_x, x[i])
  258. end
  259. if i % 100 == 0 then
  260. collectgarbage()
  261. end
  262. end
  263. print(string.format("%d small images are removed", #x - #new_x))
  264. return new_x
  265. end
  266. local function plot(train, valid)
  267. gnuplot.plot({
  268. {'training', torch.Tensor(train), '-'},
  269. {'validation', torch.Tensor(valid), '-'}})
  270. end
  271. local function train()
  272. local hist_train = {}
  273. local hist_valid = {}
  274. local model
  275. if settings.resume:len() > 0 then
  276. model = torch.load(settings.resume, "ascii")
  277. else
  278. model = srcnn.create(settings.model, settings.backend, settings.color)
  279. end
  280. local offset = reconstruct.offset_size(model)
  281. local pairwise_func = function(x, is_validation, n)
  282. return transformer(model, x, is_validation, n, offset)
  283. end
  284. local criterion = create_criterion(model, settings.loss)
  285. local eval_metric = w2nn.ClippedMSECriterion(0, 1):cuda()
  286. local x = remove_small_image(torch.load(settings.images))
  287. local train_x, valid_x = split_data(x, math.max(math.floor(settings.validation_rate * #x), 1))
  288. local adam_config = {
  289. xLearningRate = settings.learning_rate,
  290. xBatchSize = settings.batch_size,
  291. xLearningRateDecay = settings.learning_rate_decay
  292. }
  293. local ch = nil
  294. if settings.color == "y" then
  295. ch = 1
  296. elseif settings.color == "rgb" then
  297. ch = 3
  298. end
  299. local best_score = 1000.0
  300. print("# make validation-set")
  301. local valid_xy = make_validation_set(valid_x, pairwise_func,
  302. settings.validation_crops,
  303. settings.patches)
  304. valid_x = nil
  305. collectgarbage()
  306. model:cuda()
  307. print("load .. " .. #train_x)
  308. local x = nil
  309. local y = torch.Tensor(settings.patches * #train_x,
  310. ch * (settings.crop_size - offset * 2) * (settings.crop_size - offset * 2)):zero()
  311. if reconstruct.has_resize(model) then
  312. x = torch.Tensor(settings.patches * #train_x,
  313. ch, settings.crop_size / settings.scale, settings.crop_size / settings.scale)
  314. else
  315. x = torch.Tensor(settings.patches * #train_x,
  316. ch, settings.crop_size, settings.crop_size)
  317. end
  318. local instance_loss = nil
  319. for epoch = 1, settings.epoch do
  320. model:training()
  321. print("# " .. epoch)
  322. if adam_config.learningRate then
  323. print("learning rate: " .. adam_config.learningRate)
  324. end
  325. print("## resampling")
  326. if instance_loss then
  327. -- active learning
  328. local oracle_k = math.min(x:size(1) * (settings.oracle_rate * (1 / (1 - settings.oracle_drop_rate))), x:size(1))
  329. local oracle_n = math.min(x:size(1) * settings.oracle_rate, x:size(1))
  330. if oracle_n > 0 then
  331. local oracle_x, oracle_y = get_oracle_data(x, y, instance_loss, oracle_k, oracle_n)
  332. resampling(x:narrow(1, oracle_x:size(1) + 1, x:size(1)-oracle_x:size(1)),
  333. y:narrow(1, oracle_x:size(1) + 1, x:size(1) - oracle_x:size(1)), train_x, pairwise_func)
  334. x:narrow(1, 1, oracle_x:size(1)):copy(oracle_x)
  335. y:narrow(1, 1, oracle_y:size(1)):copy(oracle_y)
  336. local draw_n = math.floor(math.sqrt(oracle_x:size(1), 0.5))
  337. if draw_n > 100 then
  338. draw_n = 100
  339. end
  340. image.save(path.join(settings.model_dir, "oracle_x.png"),
  341. image.toDisplayTensor({
  342. input = oracle_x:narrow(1, 1, draw_n * draw_n),
  343. padding = 2,
  344. nrow = draw_n,
  345. min = 0,
  346. max = 1}))
  347. else
  348. resampling(x, y, train_x, pairwise_func)
  349. end
  350. else
  351. resampling(x, y, train_x, pairwise_func)
  352. end
  353. collectgarbage()
  354. instance_loss = torch.Tensor(x:size(1)):zero()
  355. for i = 1, settings.inner_epoch do
  356. model:training()
  357. local train_score, il = minibatch_adam(model, criterion, eval_metric, x, y, adam_config)
  358. instance_loss:copy(il)
  359. print(train_score)
  360. model:evaluate()
  361. print("# validation")
  362. local score = validate(model, criterion, eval_metric, valid_xy, adam_config.xBatchSize)
  363. table.insert(hist_train, train_score.loss)
  364. table.insert(hist_valid, score.loss)
  365. if settings.plot then
  366. plot(hist_train, hist_valid)
  367. end
  368. if score.MSE < best_score then
  369. local test_image = image_loader.load_float(settings.test) -- reload
  370. best_score = score.MSE
  371. print("* Best model is updated")
  372. if settings.save_history then
  373. torch.save(settings.model_file_best, model:clearState(), "ascii")
  374. torch.save(string.format(settings.model_file, epoch, i), model:clearState(), "ascii")
  375. if settings.method == "noise" then
  376. local log = path.join(settings.model_dir,
  377. ("noise%d_best.%d-%d.png"):format(settings.noise_level,
  378. epoch, i))
  379. save_test_jpeg(model, test_image, log)
  380. elseif settings.method == "scale" then
  381. local log = path.join(settings.model_dir,
  382. ("scale%.1f_best.%d-%d.png"):format(settings.scale,
  383. epoch, i))
  384. save_test_scale(model, test_image, log)
  385. elseif settings.method == "noise_scale" then
  386. local log = path.join(settings.model_dir,
  387. ("noise%d_scale%.1f_best.%d-%d.png"):format(settings.noise_level,
  388. settings.scale,
  389. epoch, i))
  390. save_test_scale(model, test_image, log)
  391. end
  392. else
  393. torch.save(settings.model_file, model:clearState(), "ascii")
  394. if settings.method == "noise" then
  395. local log = path.join(settings.model_dir,
  396. ("noise%d_best.png"):format(settings.noise_level))
  397. save_test_jpeg(model, test_image, log)
  398. elseif settings.method == "scale" then
  399. local log = path.join(settings.model_dir,
  400. ("scale%.1f_best.png"):format(settings.scale))
  401. save_test_scale(model, test_image, log)
  402. elseif settings.method == "noise_scale" then
  403. local log = path.join(settings.model_dir,
  404. ("noise%d_scale%.1f_best.png"):format(settings.noise_level,
  405. settings.scale))
  406. save_test_scale(model, test_image, log)
  407. end
  408. end
  409. end
  410. print("Batch-wise PSNR: " .. score.PSNR .. ", loss: " .. score.loss .. ", MSE: " .. score.MSE .. ", Minimum MSE: " .. best_score)
  411. collectgarbage()
  412. end
  413. end
  414. end
  415. if settings.gpu > 0 then
  416. cutorch.setDevice(settings.gpu)
  417. end
  418. torch.manualSeed(settings.seed)
  419. cutorch.manualSeed(settings.seed)
  420. print(settings)
  421. train()