X-Git-Url: https://fleuret.org/cgi-bin/gitweb/gitweb.cgi?a=blobdiff_plain;f=test-dagnn.lua;h=cec37d246451b3eb7f639edbf946e22716d6d979;hb=501034fda227664ac04ab5dd2d912f768bcd70e4;hp=5d8a309ce9769b547de0fa104b4b5f0b99157fe1;hpb=59490d9da93f28283c79d44a5e7c791cbd623b24;p=dagnn.git diff --git a/test-dagnn.lua b/test-dagnn.lua index 5d8a309..cec37d2 100755 --- a/test-dagnn.lua +++ b/test-dagnn.lua @@ -21,15 +21,18 @@ require 'torch' require 'nn' + +-- require 'cunn' + require 'dagnn' torch.setdefaulttensortype('torch.DoubleTensor') torch.manualSeed(1) -function checkGrad(model, criterion, input, target) +function checkGrad(model, criterion, input, target, epsilon) local params, gradParams = model:getParameters() - local epsilon = 1e-5 + local epsilon = epsilon or 1e-5 local output = model:forward(input) local loss = criterion:forward(output, target) @@ -57,7 +60,7 @@ function checkGrad(model, criterion, input, target) local num = (loss1 - loss0) / (2 * epsilon) if num ~= ana then - err = math.max(err, math.abs(num - ana) / math.abs(num)) + err = math.max(err, math.abs(num - ana) / math.max(epsilon, math.abs(num))) end end @@ -109,15 +112,25 @@ model = nn.Sequential() :add(dag) :add(nn.CAddTable()) +criterion = nn.MSECriterion() + +if cunn then + print("Using CUDA") + model:cuda() + criterion:cuda() + torch.setdefaulttensortype('torch.CudaTensor') + epsilon = 1e-3 +end + local input = torch.Tensor(30, 50):uniform() local output = model:updateOutput(input):clone() output:uniform() -- Check that DAG:accGradParameters and friends work okay -print('Gradient estimate error ' .. checkGrad(model, nn.MSECriterion(), input, output)) +print('Gradient estimate error ' .. checkGrad(model, criterion, input, output, epsilon)) -- Check that we can save and reload the model model:clearState() torch.save('/tmp/test.t7', model) local otherModel = torch.load('/tmp/test.t7') -print('Gradient estimate error ' .. checkGrad(otherModel, nn.MSECriterion(), input, output)) +print('Gradient estimate error ' .. checkGrad(otherModel, criterion, input, output, epsilon))