train.lua 16 KB

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