train.lua 18 KB

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