train.lua 18 KB

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