train.lua 16 KB

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