title
stringlengths 15
126
| category
stringclasses 3
values | posts
list | answered
bool 2
classes |
---|---|---|---|
[resolved] Has anyone noticed significant slowdown after upgrading to v0.1.11? | null | [
{
"contents": "Yesterday I upgraded my pytorch to v0.1.11. I ran the same training script. I noticed that the time for each batch has increased from 0.8 seconds to 2.9 seconds. Nothing is changed except the pytorch. My old version is 0.1.9+67f9455. Now I am trying to upgrade to cudnn v6 to see whether it could solve my isse. I wonder whether anyone had the same problem with me. Yaozong",
"isAccepted": false,
"likes": null,
"poster": "gaoking132"
},
{
"contents": "Problem solved! After I used the pre-built binary install, everything works as fast as usual. Before that, I was building the pytorch manually pulled from the master branch.",
"isAccepted": false,
"likes": null,
"poster": "gaoking132"
},
{
"contents": "If I had to guess, you’re running on CPU and when compiled from source it wasn’t being linked properly with MKL.",
"isAccepted": false,
"likes": 1,
"poster": "jekbradbury"
}
] | false |
How to demonstrate (or teach) learning theory using PyTorch | null | [
{
"contents": "Hi, There’s a lot of beautiful theory on function approximation, for example, is quite readable.",
"isAccepted": false,
"likes": 1,
"poster": "AjayTalati"
},
{
"contents": "I’d be interested in implementing them in PyTorch - I’ll be doing some DL theory teaching/demos over the summer. This would also be very helpful to others who are giving DL demos/teaching. Thanks a lot for your help, Aj",
"isAccepted": false,
"likes": null,
"poster": "AjayTalati"
},
{
"contents": "In general, to give you my completely honest and regularized opinion, teaching something like “Learning Real and Boolean Functions” is way more valuable to teach in numpy than in pytorch. I wont pretend, numpy is much more accessible. Unless you need to really teach / showcase a gradient based learning method (SVM-SGD?) or teach GPU based whatever, you can maybe just stick to numpy.",
"isAccepted": false,
"likes": 2,
"poster": "smth"
},
{
"contents": "Best regards Thomas",
"isAccepted": false,
"likes": 3,
"poster": "tom"
},
{
"contents": "",
"isAccepted": false,
"likes": 1,
"poster": "Bhavya_Bhatt"
}
] | false |
Mysterious nn.Parameter behavior | null | [
{
"contents": "<SCODE>import torch\nfrom torch import nn\n\nclass Model(nn.Module):\n def __init__(self, deg):\n\tsuper(Model, self).__init__()\n\tself.deg = deg + 1\n\n\tself.theta = nn.Parameter(torch.ones(self.deg), 1)\n\n def forward(self, xs):\n\tphi = torch.cat([xs**i for i in range(self.deg)], 1)\n\tres = phi @ self.theta \n # phi.mv(self.theta) # if not python 3.5 or later\n\tprint(res)\n\treturn res\n\nmodel = Model(2)\n#print(list(model.parameters()))\nx = FloatTensor([1, 2,3, 4]).unfold(0,1,1)\n\nprint(model(x))\n<ECODE> Here is the error that I get: <SCODE>Traceback (most recent call last):\n File \"01-polynomial-fitting.py\", line 40, in <module>\n print(model(x))\n File \"/home/arseni/.anaconda/envs/mlt/lib/python3.6/site-packages/torch/nn/modules/module.py\", line 206, in __call__\n result = self.forward(*input, **kwargs)\n File \"01-polynomial-fitting.py\", line 29, in forward\n res = phi @ self.theta\n File \"/home/arseni/.anaconda/envs/mlt/lib/python3.6/site-packages/torch/tensor.py\", line 357, in __matmul__\n return self.mv(other)\nTypeError: mv received an invalid combination of arguments - got (Parameter), but expected (torch.FloatTensor vec)\n<ECODE> <SCODE>Traceback (most recent call last):\n File \"01-polynomial-fitting.py\", line 40, in <module>\n print(model(x))\n File \"/home/arseni/.anaconda/envs/mlt/lib/python3.6/site-packages/torch/nn/modules/module.py\", line 215, in __call__\n var = var[0]\nTypeError: 'float' object is not subscriptable\n<ECODE> <SCODE>Traceback (most recent call last):\n File \"01-polynomial-fitting.py\", line 41, in <module>\n print(model(x))\n File \"/home/arseni/.anaconda/envs/mlt/lib/python3.6/site-packages/torch/nn/modules/module.py\", line 206, in __call__\n result = self.forward(*input, **kwargs)\n File \"01-polynomial-fitting.py\", line 29, in forward\n res = (self.theta @ phi.t())\n File \"/home/arseni/.anaconda/envs/mlt/lib/python3.6/site-packages/torch/autograd/variable.py\", line 770, in __matmul__\n return self.unsqueeze(0).mm(other).squeeze(0)\n File \"/home/arseni/.anaconda/envs/mlt/lib/python3.6/site-packages/torch/autograd/variable.py\", line 523, in mm\n output = Variable(self.data.new(self.data.size(0), matrix.data.size(1)))\nAttributeError: 'FloatTensor' object has no attribute 'data'\n<ECODE> What am I doing wrong ?",
"isAccepted": false,
"likes": null,
"poster": "username1"
},
{
"contents": "<SCODE>print(model(Variable(x)))\n<ECODE>",
"isAccepted": false,
"likes": 2,
"poster": "fmassa"
},
{
"contents": "Thanks for your answer. Now its working.",
"isAccepted": false,
"likes": null,
"poster": "username1"
}
] | false |
RuntimeError: Assertion `THCTensor_(checkGPU)(state, 3, dst, src, indices)’ failed | null | [
{
"contents": "I have trained a simple sequence to sequence model and saved the model in file. Now when I loaded the model and trying to do the testing, I am getting the following error. I am getting error at the following line. embedded = self.embedding(input).view(1, 1, -1) I am guessing the problem is not in that line but rather in saving and loading process. I am running the code in the same server, in the same GPU where I have trained the model. Does anyone know what the error means? Any suggestion to resolve this issue?",
"isAccepted": false,
"likes": null,
"poster": "Samrat_Hasan"
},
{
"contents": "i cant think of what is going on. Any chance you can give a script that reproduces this problem?",
"isAccepted": false,
"likes": null,
"poster": "smth"
},
{
"contents": "I don’t have a small script to share with you. But I am sharing the saving and loading function. <SCODE>def save_model(model, loss, epoch, tag):\n snapshot_prefix = os.path.join(args.save_path, tag)\n snapshot_path = snapshot_prefix + '_loss_{:.6f}_epoch_{}_model.pt'.format(loss, epoch)\n torch.save(model, snapshot_path)\n for f in glob.glob(snapshot_prefix + '*'):\n if f != snapshot_path:\n os.remove(f)\n\ndef load_model(tag):\n filename = os.path.join(args.save_path, tag)\n # model = torch.load(filename, map_location=lambda storage, location: storage.cuda(args.gpu))\n model = torch.load(filename)\n return model\n<ECODE> <SCODE>def evaluate(encoder, decoder, dictionary, sentence):\n \"\"\"Generates word sequence and their attentions\"\"\"\n input_variable = helper.sequence_to_variable(dictionary, sentence)\n input_length = input_variable.size()[0]\n encoder_hidden = encoder.init_weights(1)\n\n encoder_outputs = Variable(torch.zeros(args.max_length, encoder.hidden_size))\n if args.cuda:\n encoder_outputs = encoder_outputs.cuda()\n\n for ei in range(input_length):\n encoder_output, encoder_hidden = encoder(input_variable[ei], encoder_hidden)\n encoder_outputs[ei] = encoder_output[0][0]\n<ECODE> Forward function of the encoder: (in the very first line, I am getting the error) <SCODE>def forward(self, input, hidden):\n \"\"\"\"Defines the forward computation of the encoder\"\"\"\n embedded = self.embedding(input).view(1, 1, -1)\n embedded = self.drop(embedded)\n output = embedded\n for i in range(self.n_layers):\n output, hidden = self.rnn(output, hidden)\n output = self.drop(output)\n return output, hidden\n<ECODE> I am stuck here for more than one day and tried different things to find out the reason but failed. Any help would be highly appreciated. Thanks.",
"isAccepted": false,
"likes": null,
"poster": "Samrat_Hasan"
},
{
"contents": "I have updated pytorch and tried to run again. After updating, I am getting the following error. Now, I guess the problem is: when I trained the model, I didn’t set any specific GPU and as a result, pytorch used all available GPUs and now when I am trying to load the trained model and run, its giving me this error. Is my understanding correct? Isn’t it possible to add some support in Pytorch to avoid these kind of circumstances? OR, do we need to set (using CUDA_VISIBLE_DEVICES) the gpu devices while training and then load the trained model on the same GPU to do the testing?",
"isAccepted": false,
"likes": null,
"poster": "Samrat_Hasan"
},
{
"contents": "",
"isAccepted": false,
"likes": null,
"poster": "apaszke"
},
{
"contents": "thanks for your reply. If by default everything is put on device 0, why I am getting that error? because while running, I didn’t set any cuda device specifically. By the way, I have two questions. Sometimes, I get some weird errors because of these GPU issues and I don’t know how to solve it. It would be very helpful, if anyone can write some notes/blogs on the problems that one can make in these cases.",
"isAccepted": false,
"likes": null,
"poster": "Samrat_Hasan"
},
{
"contents": "No idea, you must be using more devices somehow.",
"isAccepted": false,
"likes": null,
"poster": "apaszke"
},
{
"contents": "<SCODE>decoder_input = inputs[:, :-1]\n decoder_output, decoder_hidden, attn = self.forward_step(decoder_input, decoder_hidden, encoder_outputs,\n function=function)\n indices = torch.arange(inputs.size(0))\n if torch.cuda.is_available():\n indices = indices.to(device)\n probabilities = probabilities.to(device)\n for t in range(1, probabilities.size(1)):\n inputs = inputs.to(device)\n\n probabilities[indices, t] = decoder_output[indices, t-1, inputs[indices, t].view(-1)].exp().view(-1)\n<ECODE> <SCODE> def forward(self, inputs=None, encoder_hidden=None, encoder_outputs=None,\n function=F.log_softmax, teacher_forcing_ratio=0, sample=False):\n ret_dict = dict()\n if self.use_attention:\n ret_dict[DecoderRNN.KEY_ATTN_SCORE] = list()\n\n inputs, batch_size, max_length = self._validate_args(inputs, encoder_hidden, encoder_outputs,\n function, teacher_forcing_ratio)\n decoder_hidden = self._init_state(encoder_hidden)\n\n use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False\n\n decoder_outputs = []\n sequence_symbols = []\n lengths = np.array([max_length] * batch_size)\n\n def decode(step, step_output, step_attn, sample=False):\n decoder_outputs.append(step_output)\n if self.use_attention:\n ret_dict[DecoderRNN.KEY_ATTN_SCORE].append(step_attn)\n if sample:\n symbols = torch.multinomial(torch.exp(decoder_outputs[-1]), 1)\n probs = torch.exp(decoder_outputs[-1])[np.arange(symbols.size(0)), symbols.squeeze(1)]\n else:\n symbols = decoder_outputs[-1].topk(1)[1]\n sequence_symbols.append(symbols)\n\n eos_batches = symbols.data.eq(self.eos_id)\n if eos_batches.dim() > 0:\n eos_batches = eos_batches.cpu().view(-1).numpy()\n update_idx = ((lengths > step) & eos_batches) != 0\n lengths[update_idx] = len(sequence_symbols)\n if sample:\n return symbols, probs\n return symbols\n\n # Manual unrolling is used to support random teacher forcing.\n # If teacher_forcing_ratio is True or False instead of a probability, the unrolling can be done in graph\n if use_teacher_forcing:\n probabilities = torch.ones(inputs.size(0), max_length + 1)\n samples_sent = torch.ones(inputs.size(0), max_length + 1) * self.sos_id\n hiddens = torch.zeros(max_length + 1, 2, batch_size, self.hidden_size)\n hiddens[0] = decoder_hidden\n decoder_input = inputs[:, :-1]\n decoder_output, decoder_hidden, attn = self.forward_step(decoder_input, decoder_hidden, encoder_outputs,\n function=function)\n indices = torch.arange(inputs.size(0))\n if torch.cuda.is_available():\n indices = indices.to(device)\n probabilities = probabilities.to(device)\n for t in range(1, probabilities.size(1)):\n\n probabilities[indices, t] = decoder_output[indices, t-1, inputs[indices, t].view(-1)].exp().view(-1)\n<ECODE>",
"isAccepted": false,
"likes": null,
"poster": "Liu_Su"
},
{
"contents": "",
"isAccepted": false,
"likes": null,
"poster": "ptrblck"
},
{
"contents": "<SCODE>probabilities[indices, t] = decoder_output[indices, t-1, inputs[indices, t].view(-1)].exp().view(-1)\n<ECODE> the specific description of the problem is : <SCODE>RuntimeError: arguments are located on different GPUs at /opt/conda/conda-bld/pytorch_1535490206202/work/aten/src/THC/generic/THCTensorIndex.cu:250\n<ECODE> encoder of the seq2seq part works well.the problem is in the decoder part. I guess input of the encoder is just one ,however it is not the same at the decoder.Here is the forward function of the seq2seq class. <SCODE> def forward(self, input_variable, input_lengths=None, target_variable=None,\n teacher_forcing_ratio=0, sample=False):\n encoder_outputs, encoder_hidden = self.encoder(input_variable, input_lengths)\n result = self.decoder(inputs=target_variable,\n encoder_hidden=encoder_hidden,\n encoder_outputs=encoder_outputs,\n function=self.decode_function,\n teacher_forcing_ratio=teacher_forcing_ratio,\n sample=sample)\n<ECODE>",
"isAccepted": false,
"likes": null,
"poster": "Liu_Su"
},
{
"contents": "<SCODE>if torch.cuda.is_available():\n indices = indices.to(device)\n probabilities = probabilities.to(device)\n<ECODE> <SCODE>indices = indices.to(decoder_output.device)\nprobabilities = ...\n<ECODE>",
"isAccepted": false,
"likes": null,
"poster": "ptrblck"
},
{
"contents": "<SCODE> indices = indices.to(decoder_output.device)\nprobabilities = probabilities.to(decoder_output.device)\n<ECODE> I am a little curious and confused.the \"probabilities = \" also takes the variable “inputs” as input.should I add the following code. <SCODE>inputs = inputs.to(decoder_output.device).<ECODE>",
"isAccepted": false,
"likes": null,
"poster": "Liu_Su"
},
{
"contents": "<SCODE>probabilities = probabilities.to(inputs.device)\n<ECODE> <SCODE>probabilities = torch.ones(inputs.size(0), max_length + 1)\n<ECODE>",
"isAccepted": false,
"likes": null,
"poster": "ptrblck"
},
{
"contents": "<SCODE>indices = indices.to(decoder_output.device)\nprobabilities = probabilities.to(inputs.device)\n<ECODE> <SCODE>actor = Generator(SOS,EOU, VOCAB_SIZE, GEN_HIDDEN_DIM, GEN_EMBEDDING_DIM,\\\n MAX_SEQ_LEN)\nactor = (nn.DataParallel(actor)).to(device)\n<ECODE>",
"isAccepted": false,
"likes": null,
"poster": "Liu_Su"
}
] | false |
Argmax with PyTorch | null | [
{
"contents": "How can I use argmax with PyTorch? Meta: How could I have answered my own question? I searched the PyTorch docs and the PyTorch repo for “argmax” but got no results. Does it make sense to use argmax with a GPU?",
"isAccepted": true,
"likes": 8,
"poster": "MatthewKleinsmith"
},
{
"contents": "<SCODE>values, indices = tensor.max(0)\nvalues, indices = torch.max(tensor, 0)\n<ECODE>",
"isAccepted": true,
"likes": 32,
"poster": "fmassa"
},
{
"contents": "",
"isAccepted": true,
"likes": 3,
"poster": "platero"
},
{
"contents": "",
"isAccepted": true,
"likes": 10,
"poster": "Andre_Holzner"
},
{
"contents": "Thank you very much!",
"isAccepted": true,
"likes": 1,
"poster": "platero"
},
{
"contents": "Any ideas for how to use this max function in a differentiable way? A custom loss function i’m writing has to do with the indices of max values. Not sure how to redo the loss function such that it uses differentiable components.",
"isAccepted": true,
"likes": null,
"poster": "bgenchel"
},
{
"contents": "I am not sure if I understand your problem. Do you want to have gradients with respect to indices? Well, indices are integers by definition and you cannot take derivatives of a function with respect to a variable that is defined over the integers only…",
"isAccepted": true,
"likes": null,
"poster": "dpernes"
},
{
"contents": "what does the 0 do in the indexing?",
"isAccepted": true,
"likes": null,
"poster": "Brando_Miranda"
},
{
"contents": "",
"isAccepted": true,
"likes": 1,
"poster": "BlakeWest"
},
{
"contents": "you can now do torch.argmax(preds, dim=1) in version 0.4.0",
"isAccepted": true,
"likes": 7,
"poster": "jchillin"
},
{
"contents": "",
"isAccepted": true,
"likes": null,
"poster": "chenchr"
},
{
"contents": "what about argmax from the tensor itself like: <SCODE>import torch\n\nx = torch.randn(3)\nx.argmax(-1)\n<ECODE> probably useful: Calculating accuracy of the current minibatch? 8 https://stackoverflow.com/questions/51503851/calculate-the-accuracy-every-epoch-in-pytorch 2 https://towardsdatascience.com/understanding-dimensions-in-pytorch-6edf9972d3be 3 How does one get the predicted classification label from a pytorch model? 6",
"isAccepted": true,
"likes": null,
"poster": "Brando_Miranda"
},
{
"contents": "",
"isAccepted": true,
"likes": null,
"poster": "Brando_Miranda"
}
] | true |
Constructing a matrix variable from other variables | null | [
{
"contents": "I’m trying to construct a rotation matrix from the Euler angles. As simple as I feel this should be, I’m not sure what the best approach is in PyTorch. Is there a way to do this without spamming torch.cat? Essentially I just to want to stack some existing tensor variables into a matrix for convenience. Something like <SCODE>angles = Variable(torch.zeros(3))\na, b, c = angles[0], angles[1], angles[2]\nrot_mat1 = Variable([\n (1, 0, 0),\n (0, a.cos(), a.sin()),\n (0, -a.sin(), a.cos()),\n])\nrot_mat2 = ...\nrot_mat3 = ...\nrot_mat = rot_mat1 @ rot_mat2 @ rot_mat3\n<ECODE>",
"isAccepted": false,
"likes": 2,
"poster": "kpar"
},
{
"contents": "You can index the variables as you want <SCODE>rot_mat1 = Variable(torch.zeros(3, 3), requires_grad=False)\nrot_mat1[1, 1] = a.cos()\n...\n<ECODE>",
"isAccepted": false,
"likes": 2,
"poster": "fmassa"
},
{
"contents": "Okay that seems like a better solution that what I came up with. Thanks for the solution. Glad to know assigning indices like that works. It seemed like it wouldn’t since I’ve had errors from setting values with masks etc. Here’s the messy torch.cat solution in case anyone is interested. <SCODE>def rotation_tensor(theta, phi, psi, n_comps):\n one = Variable(torch.ones(n_comps, 1, 1))\n zero = Variable(torch.zeros(n_comps, 1, 1))\n rot_x = torch.cat((\n torch.cat((one, zero, zero), 1),\n torch.cat((zero, theta.cos(), theta.sin()), 1),\n torch.cat((zero, -theta.sin(), theta.cos()), 1),\n ), 2)\n rot_y = torch.cat((\n torch.cat((phi.cos(), zero, -phi.sin()), 1),\n torch.cat((zero, one, zero), 1),\n torch.cat((phi.sin(), zero, phi.cos()), 1),\n ), 2)\n rot_z = torch.cat((\n torch.cat((psi.cos(), -psi.sin(), zero), 1),\n torch.cat((psi.sin(), psi.cos(), zero), 1),\n torch.cat((zero, zero, one), 1)\n ), 2)\n return torch.bmm(rot_z, torch.bmm(rot_y, rot_x))\n\nn_comps = 5\ntheta = Variable(torch.zeros(n_comps, 1, 1), requires_grad=True)\nphi = Variable(torch.zeros(n_comps, 1, 1), requires_grad=True)\npsi = Variable(torch.zeros(n_comps, 1, 1), requires_grad=True)\n\nrotation_mat = rotation_tensor(theta, phi, psi, n_comps)\n<ECODE>",
"isAccepted": false,
"likes": 1,
"poster": "kpar"
},
{
"contents": "I’m might be doing it soon to?",
"isAccepted": false,
"likes": null,
"poster": "AjayTalati"
},
{
"contents": "Nothing so fancy, I’m just trying to optimize for a color transformation and I’m parameterizing part it as a vector rotation.",
"isAccepted": false,
"likes": 1,
"poster": "kpar"
},
{
"contents": "",
"isAccepted": false,
"likes": null,
"poster": "AjayTalati"
},
{
"contents": "I’m not sure if it’s a different issue, but using a matrix constructed like this to optimize the base variables is causing a second backwards pass to fail. I’ve removed the unrelated code. The optimization works without the rotation matrix but gives <SCODE>RuntimeError: Trying to backward through the graph second time, but the buffers have already been freed. Please specify retain_variables=True when calling backward for the first time.\n<ECODE> when run with the rotation matrix. Any insight as to why this might be? Here’s the cruft of the optimization that’s causing the issue. <SCODE>def rotation_tensor(theta, phi, psi, n_comps):\n rot_x = Variable(torch.zeros(n_comps, 3, 3).cuda(), requires_grad=False)\n rot_y = Variable(torch.zeros(n_comps, 3, 3).cuda(), requires_grad=False)\n rot_z = Variable(torch.zeros(n_comps, 3, 3).cuda(), requires_grad=False)\n rot_x[:, 0, 0] = 1\n rot_x[:, 0, 1] = 0\n rot_x[:, 0, 2] = 0\n rot_x[:, 1, 0] = 0\n rot_x[:, 1, 1] = theta.cos()\n rot_x[:, 1, 2] = theta.sin()\n rot_x[:, 2, 0] = 0\n rot_x[:, 2, 1] = -theta.sin()\n rot_x[:, 2, 2] = theta.cos()\n \n rot_y[:, 0, 0] = phi.cos()\n rot_y[:, 0, 1] = 0\n rot_y[:, 0, 2] = -phi.sin()\n rot_y[:, 1, 0] = 0\n rot_y[:, 1, 1] = 1\n rot_y[:, 1, 2] = 0\n rot_y[:, 2, 0] = phi.sin()\n rot_y[:, 2, 1] = 0\n rot_y[:, 2, 2] = phi.cos()\n \n rot_z[:, 0, 0] = psi.cos()\n rot_z[:, 0, 1] = -psi.sin()\n rot_z[:, 0, 2] = 0\n rot_z[:, 1, 0] = psi.sin()\n rot_z[:, 1, 1] = psi.cos()\n rot_z[:, 1, 2] = 0\n rot_z[:, 2, 0] = 0\n rot_z[:, 2, 1] = 0\n rot_z[:, 2, 2] = 1\n return torch.bmm(rot_z, torch.bmm(rot_y, rot_x))\n\noptimizer = optim.LBFGS([diff_theta, diff_phi, diff_psi], lr=lr)\ndiff_theta = Variable(torch.zeros(n_diff_comps, 1, 1).cuda(), requires_grad=True)\ndiff_phi = Variable(torch.zeros(n_diff_comps, 1, 1).cuda(), requires_grad=True)\ndiff_psi = Variable(torch.zeros(n_diff_comps, 1, 1).cuda(), requires_grad=True)\n\ndiff_rot = rotation_tensor(diff_theta, diff_phi, diff_psi, n_diff_comps).cuda()\n\nfor i in range(3000):\n def closure():\n optimizer.zero_grad()\n new_diff = Variable(torch.zeros(*alb_diff_batch_init.size()).cuda())\n for comp in range(n_diff_comps):\n new_diff += (diff_rot[comp] @ diff_base_vars[comp].view(3, -1)).view(*diff_base_vars[comp].size())\n loss = new_diff.sum()\n loss.backward()\n return loss\n optimizer.step(closure)\n<ECODE> Edit: It looks like you need to re-create the intermediate matrix again every iteration. Moving <SCODE>diff_rot = rotation_tensor(diff_theta, diff_phi, diff_psi, n_diff_comps).cuda()\n<ECODE> to the inner loop fixed the issue.",
"isAccepted": false,
"likes": 1,
"poster": "kpar"
},
{
"contents": "Can we do it in a batch version?",
"isAccepted": false,
"likes": null,
"poster": "Zhipeng_Fan"
}
] | false |