train.lua 17 KB

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