train.lua 15 KB

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