train.lua 13 KB

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