id
stringlengths
3
8
text
stringlengths
1
115k
st46668
MPI is not necessary here, torch.distributed package now provides MPI style and rpc style distributed apis. Moreover it also supports gloo mpi and nccl backends (MPI style only), so if you don’t want more hassles, they should be sufficient.
st46669
Still confused with this problem. Which method will be ok for it? asyncio? Could you provide some code or useful post?
st46670
Here is my implementation of CycleGAN 8, where I parallelize training by making use of 4 GPUs. CycleGAN consists of 4 models: Generator+Discriminator for type A images, and Generator+Discriminator for type B images. I train the first pair of G and D on one device and the second pair on the other. netG_B2A = Generator().to(device1) netD_A = Discriminator().to(device1) netG_A2B = Generator().to(device2) netD_B = Discriminator().to(device2) cycle_loss1 = torch.nn.L1Loss().to(device1) cycle_loss2 = torch.nn.L1Loss().to(device2) identity_loss1 = torch.nn.L1Loss().to(device1) identity_loss2 = torch.nn.L1Loss().to(device2) adversarial_loss1 = torch.nn.MSELoss().to(device1) adversarial_loss2 = torch.nn.MSELoss().to(device2) I also have 2 copies of input data and 2 copies of each loss functions that I calculate on different devise. real_image_A1 = data[0].to(device1) real_image_B1 = data[1].to(device1) real_image_A2 = data[0].to(device2) real_image_B2 = data[1].to(device2) Moreover, I have to copy the resulting images (which will be feed into the second pair of G and D) of one G to another device. # ... fake_image_B = netG_A2B(real_image_A2) # ... recovered_image_A = netG_B2A(fake_image_B.to(device1)) The final loss is calculated on the CPU. errG = loss_identity_A.cpu() + loss_identity_B.cpu() + loss_GAN_A2B.cpu() + loss_GAN_B2A.cpu() + loss_cycle_ABA.cpu() + loss_cycle_BAB.cpu() Besides, I have 2 classification model which are allocated on their own devices.
st46671
Hi, so I want to detect anomal peaks in ECG signal using 1d convolution by sliding normal looking ECG peak across the signal. Here is function that I’m using. def convolve(signal, filt, stride): signalt = torch.from_numpy(signal).float().view(1,1,-1) filt = torch.from_numpy(filt).view(1,1,-1) output = F.conv1d(input=signalt, weight=filt, stride=stride, padding=0) return output.numpy().ravel() The output I get is an ecg signal that has reduced anomaly peaks - I want to know which one those are so I was trying to get the difference between the original and the output, however the length does not match. ef explain_anomalies(y, fil, stride, sigma=1.0): avg = convolve(y, fil, stride).tolist() residual = y - avg # Calculate the variation in the distribution of the residual std = np.std(residual) return {'standard_deviation': round(std, 3), 'anomalies_dict': collections.OrderedDict([(index, y_i) for index, y_i, avg_i in zip(count(), y, avg) if (y_i > avg_i + (sigma*std)) | (y_i < avg_i - (sigma*std))])} after calling explain_anomalies(ecg[‘signal’], sig_filt, stride=1) where sig_filt is normal QRS peak that I want to do convolution with I get <ipython-input-115-71fe810b0625> in explain_anomalies(y, fil, stride, sigma) 25 26 avg = convolve(y, fil, stride).tolist() ---> 27 residual = y - avg 28 # Calculate the variation in the distribution of the residual 29 std = np.std(residual) ValueError: operands could not be broadcast together with shapes (71006,) (70977,) Why does convolution reduce the numer of samples even though I have stride set to 1?
st46672
not sure what you data and filter looks like, but padding may also change your output size
st46673
thank you for your answer @klory here is my signal with length of 71006 array([ -152., -330., -306., ..., -2522., -2724., -2886.], dtype=float32) and filter length is 30 array([ -320., -322., -340., -410., -678., -1100., -712., 1580., 5190., 8574., 11104., 12664., 12998., 12104., 10110., 7030., 3232., -574., -3596., -4724., -3832., -2558., -2184., -2416., -2560., -2474., -2374., -2394., -2434., -2394.], dtype=float32) So padding param pads signal on both sides - it changes the data to compensate for filtering, am I getting this right?
st46674
Hi, I need to use a modified version of data loader in my study. Assume that I have a basic train loader like this: train_data = datasets.MNIST(root='../../Data', train=True, download=False, transform=transforms.ToTensor()) train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=False) First I use it in the beginning. But then for a different task, I need to add a noise to all samples in train dataset. And then I should be able use the noisy data, using a new data loader. I can update all samples with noise using below code, but I don’t know how to save that modified train dataset as a data loader and use it later in different code sections. def noise(x, eps, clip_min, clip_max): eta = torch.FloatTensor(*x.shape).normal_(mean=0,std=eps).to(x.device) adv_x = x + eta if clip_min is not None and clip_max is not None: adv_x = torch.clamp(adv_x, min=clip_min, max=clip_max) return adv_x my_noisy_train_loader = train_loader for i, (image,label) in enumerate(my_noisy_train_loader): image = noise(image,0.3,0,1) #How to update noisy train loader? Could you please suggest how can I modify the data loader and use afterwards? Or; Maybe I need to create a custom modified dataset(noisy MNIST dataset lets say), and load this new modified dataset using a new data loader, but I also do not know how to modify and save datasets.MNIST so that I can use it later on.
st46675
Hi, I think that the simplest solution is to create a custom transform that adds this noise. You can them pass that transform when you create your Dataset and keep using the Dataloader as before.
st46676
Thanks for your prompt reply. The point is I will not only need noise dataset, but later I will also use perturbed dataset. For example all the data in dataset will need to be perturbed with different adversarial attack types like FGSM, BIM, CW etc. Thats why I thought that I can create a custom dataset for all different cases like noisy_MNIST_dataset , BIM_MNIST dataset etc. I can not meet this need this using transform…
st46677
To just add to what @albanD mentioned, here is an excellent resource for custom datasets and transforms: Writing Custom Datasets, DataLoaders and Transforms — PyTorch Tutorials 1.6.0 documentation 94
st46678
If you want these to be “permanent” datasets, then you might be able to modify the dataset and save it again on disk. You can later load it again as a TensorDataset (for mnist it shouldn’t be too large).
st46679
Actually i do not know how to modify and save as a new dataset. Is it possible to share some piece of code to guide me on this?
st46680
Is there any reason that these perturbations can’t be in the form of a custom transform? As far as I know, what you are describing is the exact use case of transforms.
st46681
The mnist dataset is actually a file with two Tensors, one for images and one for labels. You can see how it’s loaded here: https://github.com/pytorch/vision/blob/74de51d6d478e289135d9274e6af550a9bfba137/torchvision/datasets/mnist.py#L89 23 So you can just modify these two Tensors and save them again.
st46682
In order to have flexibility to play with the noise, I wouldn’t save a noise-added dataset. As for your case where you want to add more perturbations, that transform approach also works here. You can have several conditional transforms if needed, ie to add or not add noise, followed by other perturbations as needed. Here’s one example from one of my projects: train_transform = transforms.Compose([ ImageThinning(p = cf.thinning_threshold) if cf.thinning_threshold < 1 else NoneTransform(), OverlayImage(cf) if cf.overlay_image else NoneTransform(), # Add random image background here, to mimic painting PadImage((cf.MAX_IMAGE_WIDTH, cf.MAX_IMAGE_HEIGHT)) if cf.pad_images else NoneTransform(), transforms.Resize(cf.input_size) if cf.resize_images else NoneTransform(), transforms.ToTensor(), transforms.Lambda(lambda x: x.repeat(3, 1, 1)) if not(RGB_img) else NoneTransform(), # in case the image has a single channel transforms.Normalize( mu, std ) if cf.normalize_images else NoneTransform(), ]) ImageThinning, OverlayImage, and, PadImage are custom transforms. You still need to code your customized transforms (if you can’t find one from PyTorch that works for you)… Here’s an example for the (custom) ImageThinning transform shown above. class ImageThinning(object): """ Image input as PIL and output as PIL To be used as part of torchvision.transforms Args: p, a threshold value to control image thinning """ def __init__(self, p = 0.2): self.p = p def __call__(self, image): image = image_thinning(image, self.p) return image The other approach (as Wesley mentioned) is to define a custom dataset 7 class and have train_data = datasets.MNIST... as the object of that class, and then, play with the noise or any other perturbations at the __getitem__ level. Either ways, you’d have to get your hands dirty with coding. Good luck!
st46683
Hi friends, I have read a paper named " ACNet: Strengthening the Kernel Skeletons for Powerful CNN via Asymmetric Convolution Blocks". Is there anyone have idea how this picture drawn? Like each curve with different colors in different painting palette? Sorry I don’t know how to describe this but looks fancy, and wanna get some ideas how to plot similar to this style. image465×630 67.8 KB
st46684
I’m trying to recreate the learning rate schedules in Bert/Roberta, which start with a particular optimizer with specific args, linearly increase to a certain learning rate, and then decay with a specific rate decay. Say that I am trying to reproduce the Roberta pretraining, described below: BERT is optimized with Adam (Kingma and Ba, 2015) using the following parameters: β1 = 0.9, β2 = 0.999, ǫ = 1e-6 and L2 weight decay of 0.01. The learning rate is warmed up over the first 10,000 steps to a peak value of 1e-4, and then linearly decayed. BERT trains with a dropout of 0.1 on all layers and attention weights, and a GELU activation function (Hendrycks and Gimpel, 2016). Models are pretrained for S = 1,000,000 updates, with minibatches containing B = 256 sequences of maximum length T = 512 tokens. I would need to start with a learning rate of 1e-6 , warmup to 1e-4 in 1000 steps, then let the weight decay continue for the rest of the training. I see that there are some learning rate scheduler here, pytorch.org torch.optim — PyTorch 1.7.0 documentation 10 But they don’t seem to have the two phases as described in the passage above, or start/stop at certain learning rates. Is there another way to reproduce the roberta learningrate schedule? I’m looking at the fairseq repo, but I’m having a tricky time following the code, and I’m not sure how to copy specific parts into the trainer code I am working on pytorch.org torch.optim — PyTorch 1.7.0 documentation 10
st46685
I have looked into how Fairseq does the warmup https://github.com/pytorch/fairseq/blob/master/examples/roberta/README.pretraining.md 8 I am having a tricky time following the code, but it looks like the warmup is handled with PolynomialDecaySchedule (since there is a ‘@register_lr_scheduler(“polynomial_decay”)’, and ‘polynomial_decay’ is an arg for the pretraining command) , by passing an optimizer object, and specific args I can deduce most of the args from the ‘Train Roberta Base’ command here https://github.com/pytorch/fairseq/blob/master/examples/roberta/README.pretraining.md#2-train-roberta-base 1 Except for power, which I am guessing will just be left to the default of 1. I am also wondering the decay is ‘and then linearly decayed’ as mentioned in the Roberta paper. I see that there is already a decay happening with AdamW, since its decay rate is set at 0.01, but I don’t think that’s a linear decrease, and the paper does mention that there is a linear decrease. Also, the PolynomialDecaySchedule class mentions that its supposed to be for decaying the learning rate (“Decay the LR on a fixed schedule.”). So it sounds like the class is also handling this linear decay, based on the end_learning_rate arg. It seems to be that no arg is passed in for that, so it uses the default of zero. I’m not so sure of this though, I feel like it may have been mentioned in the paper, and its a little tricky to see what exactly is being passed into PolynomialDecaySchedule , because it doesn’t seem like that class is being instantiated in the code. It seems to be instantiated a different way which I am not able to figure out. Maybe the end learning rate is zero after all, since that’s how it’s done in Bert, which Roberta is based on. github.com google-research/bert/blob/master/optimization.py#L36 """Creates an optimizer training op."""global_step = tf.train.get_or_create_global_step()learning_rate = tf.constant(value=init_lr, shape=[], dtype=tf.float32)# Implements linear decay of the learning rate.learning_rate = tf.train.polynomial_decay( learning_rate, global_step, num_train_steps, end_learning_rate=0.0, power=1.0, cycle=False)# Implements linear warmup. I.e., if global_step < num_warmup_steps, the# learning rate will be `global_step/num_warmup_steps * init_lr`.if num_warmup_steps: global_steps_int = tf.cast(global_step, tf.int32) warmup_steps_int = tf.constant(num_warmup_steps, dtype=tf.int32) global_steps_float = tf.cast(global_steps_int, tf.float32) Which also shows power =1.
st46686
I am attempting to make a custom scheduler which replicates the Roberta warmup, so far I came up with this, based on Huggingface’s linear warmup scheduler github.com huggingface/transformers/blob/master/src/transformers/optimization.py#L71 4 """ def lr_lambda(current_step: int): if current_step < num_warmup_steps: return float(current_step) / float(max(1.0, num_warmup_steps)) return 1.0 return LambdaLR(optimizer, lr_lambda, last_epoch=last_epoch)def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1): """ Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer. Args: optimizer (:class:`~torch.optim.Optimizer`): The optimizer for which to schedule the learning rate. num_warmup_steps (:obj:`int`): The number of steps for the warmup phase. num_training_steps (:obj:`int`): def get_linear_schedule_with_warmup_with_peak(optimizer, num_warmup_steps, num_training_steps, init_lr, peak_lr, last_epoch=-1): def lr_lambda(current_step: int): if current_step < num_warmup_steps: return (float(current_step) / float(max(1, num_warmup_steps)))*(peak_lr/init_lr) return max( 0.0, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)) ) return LambdaLR(optimizer, lr_lambda, last_epoch) Which is not quite exact, since the optimizer is AdamW, which has its own weight decay. For it to be exact, I need init_lr to be replaced by the current optimizer learning rate, but from the documentation on LambdaLR, lr_lambda seems to only take in an int. pytorch.org torch.optim — PyTorch 1.7.0 documentation 5 So I need a way to adjust the optimizer’s learning rate based on its current learning rate.
st46687
Hello, I am creating a RNN for binary classification. The goal is to look at binary arrays of length 60 in which arrays containing 2 0r more consecutive 1s are not a part of the grammar (target = 0) and those that do not are a part of the grammar (target = 1). I am attempting to modify this model for my data set: https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html. here is my model: class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RNN, self).__init__() self.hidden_size = hidden_size self.i2h = nn.Linear(input_size + hidden_size, hidden_size) self.i2o = nn.Linear(input_size + hidden_size, output_size) self.softmax = nn.LogSoftmax(dim=1) def forward(self, input, hidden): print(input) print(input.size()) print(hidden.size()) input = torch.unsqueeze(input, 0) print(input.size()) combined = torch.cat((input, hidden), 1) hidden = self.i2h(combined) output = self.i2o(combined) output = self.softmax(output) return output, hidden def initHidden(self): return torch.zeros(1, self.hidden_size) n_elements = 60 n_hidden = 128 n_categories = 2 rnn = RNN(n_elements, n_hidden, n_categories) train function: criterion = nn.NLLLoss() learning_rate = 0.005 def train(category_tensor, line_tensor): hidden = rnn.initHidden() rnn.zero_grad() for i in range(line_tensor.size()[0]): output, hidden = rnn(line_tensor[i], hidden) loss = criterion(output, category_tensor) loss.backward() # Add parameters' gradients to their values, multiplied by learning rate for p in rnn.parameters(): p.data.add_(p.grad.data, alpha=-learning_rate) return output, loss.item() training loop: import time import math n_iters = 1000 print_every = 5000 plot_every = 1000 # Keep track of losses for plotting current_loss = 0 all_losses = [] def timeSince(since): now = time.time() s = now - since m = math.floor(s / 60) s -= m * 60 return '%dm %ds' % (m, s) start = time.time() for iter in range(1, n_iters + 1): line_tensor = x_train[iter - 1, :] #print(line_tensor) category_tensor = y_train[iter - 1] #print(category_tensor) output, loss = train(category_tensor, line_tensor) current_loss += loss # Print iter number, loss, name and guess if iter % print_every == 0: #guess, guess_i = categoryFromOutput(output) guess = output.data.max(1, keepdim = True)[1] correct = '✓' if guess == category else '✗ (%s)' % category print('%d %d%% (%s) %.4f %s / %s %s' % (iter, iter / n_iters * 100, timeSince(start), loss, line, guess, correct)) # Add current loss avg to list of losses if iter % plot_every == 0: all_losses.append(current_loss / plot_every) current_loss = 0 Error: IndexError Traceback (most recent call last) <ipython-input-17-5369f07dfbd7> in <module> 26 category_tensor = y_train[iter - 1] 27 #print(category_tensor) ---> 28 output, loss = train(category_tensor, line_tensor) 29 current_loss += loss 30 <ipython-input-16-be1621d99dcf> in train(category_tensor, line_tensor) 9 10 for i in range(line_tensor.size()[0]): ---> 11 output, hidden = rnn(line_tensor[i], hidden) 12 13 loss = criterion(output, category_tensor) ~\anaconda3\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs) 530 result = self._slow_forward(*input, **kwargs) 531 else: --> 532 result = self.forward(*input, **kwargs) 533 for hook in self._forward_hooks.values(): 534 hook_result = hook(self, input, result) <ipython-input-13-d9c935b3b378> in forward(self, input, hidden) 15 input = torch.unsqueeze(input, 0) 16 print(input.size()) ---> 17 combined = torch.cat((input, hidden), 1) 18 hidden = self.i2h(combined) 19 output = self.i2o(combined) IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1) I have tried messing with the dimensions of the inputs to self.forward() and it prints the following: tensor(0, dtype=torch.int32) torch.Size([]) torch.Size([1, 128]) torch.Size([1]) I am not sure how to fix this issue, can anyone help?
st46688
Is the shape of input variable and return the posted values or is the output referring to multiple tensors?
st46689
my tensor shape is 8 X 5 X 512 (N X C X L) and i want to apply batchnorm on L how to do it??
st46690
You should try using torch.nn.BatchNorm1d(). Please find the relevant info on this pytorch page. pytorch.org BatchNorm1d — PyTorch 1.7.0 documentation 1
st46691
You could permute the input tensor and swap C with L before applying the batchnorm and swap it back afterwards.
st46692
Hi there, I have a Pytorch Bert model was originally trained with 1 GPU. Now i moved it to 4GPU due to memory issue. However, when I moved it to 4GPU. I got an error message as below during the validation part: RuntimeError: Caught RuntimeError in replica 1 on device 1. Original Traceback (most recent call last): File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/parallel/parallel_apply.py", line 60, in _worker output = module(*input, **kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 550, in __call__ result = self.forward(*input, **kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/parallel/data_parallel.py", line 155, in forward outputs = self.parallel_apply(replicas, inputs, kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/parallel/data_parallel.py", line 165, in parallel_apply return parallel_apply(replicas, inputs, kwargs, self.device_ids[:len(replicas)]) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/parallel/parallel_apply.py", line 85, in parallel_apply output.reraise() File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/_utils.py", line 395, in reraise raise self.exc_type(msg) RuntimeError: Caught RuntimeError in replica 0 on device 0. Original Traceback (most recent call last): File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/parallel/parallel_apply.py", line 60, in _worker output = module(*input, **kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 550, in __call__ result = self.forward(*input, **kwargs) File "/home/ec2-user/SageMaker/Anecdotes/model.py", line 117, in forward inputs_embeds=None, File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 550, in __call__ result = self.forward(*input, **kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/transformers/modeling_bert.py", line 727, in forward input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 550, in __call__ result = self.forward(*input, **kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/transformers/modeling_bert.py", line 174, in forward inputs_embeds = self.word_embeddings(input_ids) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 550, in __call__ result = self.forward(*input, **kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/modules/sparse.py", line 114, in forward self.norm_type, self.scale_grad_by_freq, self.sparse) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/functional.py", line 1724, in embedding return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse) RuntimeError: arguments are located on different GPUs at /pytorch/aten/src/THC/generic/THCTensorIndex.cu:403 My model.py is as below: import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import MultiheadAttention, EmbeddingBag, CrossEntropyLoss, MultiLabelSoftMarginLoss, BCEWithLogitsLoss from transformers import BertPreTrainedModel, BertModel, BertTokenizer, AdamW from utils import LABEL_NAME class ReviewClassification(BertPreTrainedModel): def __init__(self, config, add_agent_text, agent_text_heads): """ :param config: Bert configuration, can set up some parameters, like output_attention, output_hidden_states :param add_agent_text: whether to use the non text feature, and how. It can have three options: None, "concat" and "attention" :param agent_text_heads: number of the heads in agent attention mechanism. Only useful if add_agent_text are set to "attention" """ super().__init__(config) # self.num_labels = 2 self.add_agent_text = add_agent_text self.bert = BertModel(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) embedding_size = config.hidden_size if self.add_agent_text == "concat": embedding_size = 2 * embedding_size elif self.add_agent_text == "attention": self.agent_attention = nn.MultiheadAttention(embedding_size, num_heads=agent_text_heads) else: # don't use the information in Agent text pass self.classifier = nn.Linear(embedding_size, 1) # self.classifier = nn.Linear(embedding_size, len(LABEL_NAME)) # bias: If set to False, the layer will not learn an additive bias self.init_weights() print( """ add agent text :{} agent text multi-head :{} """.format(self.add_agent_text, agent_text_heads) ) def forward( self, review_input_ids=None, review_attention_mask=None, review_token_type_ids=None, agent_input_ids=None, agent_attention_mask=None, agent_token_type_ids=None, labels=None, ): """ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`): Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ..., config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss), If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy). Returns: :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs: loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`label` is provided): Classification (or regression if config.num_labels==1) loss. logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (before SoftMax). hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``): Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape :obj:`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``): Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. Examples:: from transformers import BertTokenizer, BertForSequenceClassification import torch tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertForSequenceClassification.from_pretrained('bert-base-uncased') input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1 labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 outputs = model(input_ids, labels=labels) loss, logits = outputs[:2] """ review_outputs = self.bert( review_input_ids, attention_mask=review_attention_mask, token_type_ids=review_token_type_ids, position_ids=None, head_mask=None, inputs_embeds=None, ) if self.add_agent_text is not None: # means that self.add_agent_text is "concat" or "attention" # TODO: we can try that agent_outputs do not share the same parameter agent_outputs = self.bert( agent_input_ids, attention_mask=agent_attention_mask, token_type_ids=agent_token_type_ids, position_ids=None, head_mask=None, inputs_embeds=None, ) if self.add_agent_text == "attention": review_hidden_states = review_outputs[0].transpose(0, 1) # before trans: (bs, seq_len, hidden_size) agent_hidden_states = agent_outputs[0].mean(axis=1).unsqueeze(dim=0) # (1, batch_size, hidden_size) attn_output, _ = self.agent_attention(agent_hidden_states, review_hidden_states, review_hidden_states) feature = attn_output.squeeze() # (batch_size, seq_len) else: feature = review_outputs[1] # (batch_size, seq_len) -? Should it be (batch_size, hidden_size) if self.add_agent_text == "concat": feature = torch.cat([feature, agent_outputs[1]], axis=1) # nn.CrossEntropyLoss applies F.log_softmax and nn.NLLLoss internally on your input, # so you should pass the raw logits to it. # torch.nn.functional.binary_cross_entropy takes logistic sigmoid values as inputs # torch.nn.functional.binary_cross_entropy_with_logits takes logits as inputs # torch.nn.functional.cross_entropy takes logits as inputs (performs log_softmax internally) # torch.nn.functional.nll_loss is like cross_entropy but takes log-probabilities (log-softmax) values as inputs # CrossEntropyLoss takes prediction logits (size: (N,D)) and target labels (size: (N,)) # CrossEntropyLoss expects logits i.e whereas BCELoss expects probability value logits = self.classifier(feature).squeeze() outputs = (logits,) # + outputs[2:] # add hidden states and attention if they are here if labels is not None: ##### original # loss_fct = MultiLabelSoftMarginLoss() # loss = loss_fct(logits, labels) # outputs = (loss,) + outputs #### Version 1 try # pos_weight = dataset.label_proportion.iloc[0]/dataset.label_proportion.iloc[1] # Version 1.1 for weight # weight = torch.tensor([0.101521, 0.898479]) # hard code from entire training dataset # pos_weight = weight[labels.data.view(-1).long()].view_as(labels) # Version 1.2 for weight pos_weight=torch.tensor(1) # Version 1.3 for weight #weight = torch.tensor([1.0, 8.85]) # hard code from entire training dataset #pos_weight = weight[labels.data.view(-1).long()].view_as(labels) loss_fct = nn.BCEWithLogitsLoss(pos_weight=pos_weight).cuda() loss = loss_fct(logits, labels) # loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1, self.num_labels)) outputs = (loss,) + outputs ### Version 2 try # loss_fct = nn.CrossEntropyLoss() # loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) # outputs = (loss,) + outputs return outputs # (loss, logits, hidden_states, attentions) And my train_valid_test.py for the training, validation, test process is as below: import time import pickle from path import Path import numpy as np import pandas as pd from sklearn.metrics import precision_recall_fscore_support, classification_report, confusion_matrix import torch import torch.nn as nn from utils import LABEL_NAME, isnotebook, set_seed, format_time if isnotebook(): from tqdm.notebook import tqdm else: from tqdm import tqdm set_seed(seed=228) def model_train(model, train_data_loader, valid_data_loader, test_data_loader, logger, optimizer, scheduler, num_epochs, seed, out_dir): # move model to gpu device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device) if torch.cuda.device_count() > 1: model = nn.DataParallel(model) num_gpus = torch.cuda.device_count() logger.info("Let's use {} GPUs!".format(num_gpus)) # Set the seed value all over the place to make this reproducible. # set_seed(seed=seed) # We'll store a number of quantities such as training and validation loss, # validation accuracy, and timings. training_stats = [] print_interval = 100 # Measure the total training time for the whole run. total_t0 = time.time() batch_size = train_data_loader.batch_size num_batch = len(train_data_loader) best_f1_score = { "weighted": 0, "averaged": 0 } best_test_f1_score = 0 # For each epoch... for epoch_i in range(0, num_epochs): # ======================================== # Training # ======================================== # Perform one full pass over the training set. logger.info("") logger.info('======== Epoch {:} / {:} ========'.format(epoch_i + 1, num_epochs)) logger.info('Training...') # Reset the total loss for this epoch. total_train_loss = 0 # Measure how long the training epoch takes. t_train = time.time() model.train() # For each batch of training data... for step, batch in tqdm(enumerate(train_data_loader), desc="Training Iteration", total=num_batch): # Progress update every 100 batches. if step % print_interval == 0 and not step == 0: # Calculate elapsed time in minutes. elapsed = format_time(time.time() - t_train) avg_train_loss = total_train_loss / print_interval # Report progress. logger.info('| epoch {:3d} | {:5d}/{:5d} batches | lr {:.3e} | loss {:5.3f} | Elapsed {:s}'.format( epoch_i+1, step, num_batch, scheduler.get_last_lr()[0], avg_train_loss, elapsed) ) total_train_loss = 0 training_stats.append( { 'epoch': epoch_i + 1, 'step': step, 'train loss': avg_train_loss, } ) # Unpack this training batch from our dataloader. # # As we unpack the batch, we'll also copy each tensor to the GPU using the # `to` method. # # `batch` contains four pytorch tensors: # "input_ids" # "attention_mask" # "token_type_ids" # "binarized_labels" b_review_input_ids = batch["review_input_ids"].to(device) b_review_attention_mask = batch["review_attention_mask"].to(device) b_review_token_type_ids = batch["review_token_type_ids"].to(device) b_agent_input_ids = batch["agent_input_ids"].to(device) b_agent_attention_mask = batch["agent_attention_mask"].to(device) b_agent_token_type_ids = batch["agent_token_type_ids"].to(device) b_binarized_label = batch["binarized_label"].to(device) model.zero_grad() (loss, _) = model(review_input_ids=b_review_input_ids, review_attention_mask=b_review_attention_mask, review_token_type_ids=b_review_token_type_ids, agent_input_ids=b_agent_input_ids, agent_attention_mask=b_agent_attention_mask, agent_token_type_ids=b_agent_token_type_ids, labels=b_binarized_label ) # Accumulate the training loss over all of the batches so that we can # calculate the average loss at the end. `loss` is a Tensor containing a # single value; the `.item()` function just returns the Python value # from the tensor. if num_gpus > 1: total_train_loss += loss.mean().item() loss.mean().backward() # use loss.mean().backward() instead of loss.backward() for multiple gpu trainings else: total_train_loss += loss.item() loss.backward() # Clip the norm of the gradients to 1.0. # This is to help prevent the "exploding gradients" problem. torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) # Update parameters and take a step using the computed gradient. # The optimizer dictates the "update rule"--how the parameters are # modified based on their gradients, the learning rate, etc. optimizer.step() scheduler.step() # End of training epoch # Measure how long this epoch took. training_time = format_time(time.time() - t_train) logger.info("") logger.info(" Training epoch took: {:s}".format(training_time)) # evaluate the model after one epoch. # ======================================== # Validation # ======================================== # After the completion of each training epoch, measure our performance on # our validation set. logger.info("") logger.info("Validating...") t_valid = time.time() model.eval() ave_valid_loss, valid_f1_table, cm_table, f1_score = model_validate(model=model, data_loader=valid_data_loader) # Measure how long this epoch took. validation_time = format_time(time.time() - t_valid) logger.info("") logger.info('| loss {:5.3f} | Elapsed {:s}'.format(ave_valid_loss, validation_time)) logger.info(" \n{:s}".format(valid_f1_table.to_string())) logger.info("") logger.info(" \n{:s}".format(cm_table.to_string())) # need to store the best model for key in best_f1_score.keys(): if best_f1_score[key] < f1_score[key]: # remove the old model: file_list = [f for f in out_dir.files() if f.name.endswith(".pt") and f.name.startswith(key)] for f in file_list: Path.remove(f) model_file = out_dir.joinpath('{:s}_epoch_{:02d}-f1_{:.3f}.pt'.format( key, epoch_i + 1, f1_score[key]) ) best_f1_score[key] = f1_score[key] if num_gpus > 1: torch.save(model.module.state_dict(), model_file) else: torch.save(model.state_dict(), model_file) # ======================================== # Test # ======================================== logger.info("") logger.info("Testing...") result_df = model_test(model=model, data_loader=test_data_loader) y_true = np.array(result_df["review_label"], dtype=np.bool) # This part may need double check y_pred = result_df["Probability"] > 0.5 report = classification_report(y_true, y_pred, output_dict=True) metrics_df = pd.DataFrame(report).transpose() metrics_df = metrics_df.sort_index() weighted_f1_score = metrics_df.loc['weighted avg', 'f1-score'] averaged_f1_score = metrics_df.loc['macro avg', 'f1-score'] best_test_f1_score = metrics_df.loc['weighted avg', 'f1-score'] \ if best_test_f1_score < metrics_df.loc['weighted avg', 'f1-score'] else best_test_f1_score metrics_df = metrics_df.astype(float).round(3) # Calculate confusion matrix tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel() cm_df = pd.DataFrame(columns = ['Predicted No', 'Predicted Yes'], index = ['Actual No', 'Actual Yes']) # adding rows to an empty # dataframe at existing index cm_df.loc['Actual No'] = [tn,fp] cm_df.loc['Actual Yes'] = [fn,tp] logger.info("use model: {} batch / {} step".format(epoch_i + 1, step)) logger.info("\n" + "=" * 50) logger.info("\n" + metrics_df.to_string()) logger.info("\n" + "=" * 50) logger.info("\n" + cm_df.to_string()) logger.info("best test F1 score: {}".format(best_test_f1_score)) logger.info("\n" + "=" * 50) # Below is to save the result files # result_filename = "result_df_epoch_" + str(epoch_i + 1) + ".xlsx" # result_df.to_excel(out_dir.joinpath(result_filename), index=False) logger.info("") logger.info("Training complete!") logger.info("Total training took {:} (h:mm:ss)".format(format_time(time.time() - total_t0))) # Save training_stats to csv file pd.DataFrame(training_stats).to_csv(out_dir.joinpath("model_train.log"), index=False) return model, optimizer, scheduler def model_validate(model, data_loader): # Put the model in evaluation mode--the dropout layers behave differently # during evaluation. model.eval() device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device) if torch.cuda.device_count() > 1: model = nn.DataParallel(model) label_prop = data_loader.dataset.dataset.label_prop() total_valid_loss = 0 batch_size = data_loader.batch_size num_batch = len(data_loader) y_pred, y_true = [], [] # Evaluate data for step, batch in tqdm(enumerate(data_loader), desc="Validation...", total=num_batch): b_review_input_ids = batch["review_input_ids"].to(device) b_review_attention_mask = batch["review_attention_mask"].to(device) b_review_token_type_ids = batch["review_token_type_ids"].to(device) b_agent_input_ids = batch["agent_input_ids"].to(device) b_agent_attention_mask = batch["agent_attention_mask"].to(device) b_agent_token_type_ids = batch["agent_token_type_ids"].to(device) b_binarized_label = batch["binarized_label"].to(device) # Tell pytorch not to bother with constructing the compute graph during # the forward pass, since this is only needed for backprop (training). with torch.no_grad(): (loss, logits,) = model(review_input_ids=b_review_input_ids, review_attention_mask=b_review_attention_mask, review_token_type_ids=b_review_token_type_ids, agent_input_ids=b_agent_input_ids, agent_attention_mask=b_agent_attention_mask, agent_token_type_ids=b_agent_token_type_ids, labels=b_binarized_label) total_valid_loss += loss.item() ### The sigmoid function is used for the two-class logistic regression, ### whereas the softmax function is used for the multiclass logistic regression # Version 1 # numpy_probas = logits.detach().cpu().numpy() # y_pred.extend(np.argmax(numpy_probas, axis=1).flatten()) # y_true.extend(b_binarized_label.cpu().numpy()) # Version 2 # transfored_logits = F.log_softmax(logits,dim=1) # numpy_probas = transfored_logits.detach().cpu().numpy() # y_pred.extend(np.argmax(numpy_probas, axis=1).flatten()) # y_true.extend(b_binarized_label.cpu().numpy()) # Version 3 # transfored_logits = torch.sigmoid(logits) # numpy_probas = transfored_logits.detach().cpu().numpy() # y_pred.extend(np.argmax(numpy_probas, axis=1).flatten()) # y_true.extend(b_binarized_label.cpu().numpy()) # New version - for num_label = 1 transfored_logits = torch.sigmoid(logits) numpy_probas = transfored_logits.detach().cpu().numpy() y_pred.extend(numpy_probas) y_true.extend(b_binarized_label.cpu().numpy()) # End of an epoch of validation # put model to train mode again. model.train() ave_loss = total_valid_loss / (num_batch * batch_size) y_pred = np.array(y_pred) y_pred[y_pred < 0.5] = 0 y_pred[y_pred >= 0.5] = 1 # Below is in case the input and target are not the same data format y_pred = np.array(y_pred, dtype=np.bool) y_true = np.array(y_true, dtype=np.bool) # compute the various f1 score for each label report = classification_report(y_true, y_pred, output_dict=True) metrics_df = pd.DataFrame(report).transpose() # metrics_df = pd.DataFrame(0, index=LABEL_NAME, columns=["Precision", "Recall", "F1","support"]) # metrics_df.Precision = precision_recall_fscore_support(y_true, y_pred)[0] # metrics_df.Recall = precision_recall_fscore_support(y_true, y_pred)[1] # metrics_df.F1 = precision_recall_fscore_support(y_true, y_pred)[2] # metrics_df.support = precision_recall_fscore_support(y_true, y_pred)[3] # y_pred = np.array(y_pred) # y_pred[y_pred < 0] = 0 # y_pred[y_pred > 0] = 1 # y_pred = np.array(y_pred, dtype=np.bool) # y_true = np.array(y_true, dtype=np.bool) # metrics_df = pd.DataFrame(0, index=LABEL_NAME, columns=["Precision", "Recall", "F1"], dtype=np.float) # # or_y_pred = np.zeros(y_pred.shape[0], dtype=np.bool) # # or_y_true = np.zeros(y_true.shape[0], dtype=np.bool) # for i in range(len(LABEL_NAME)): # metrics_df.iloc[i] = precision_recall_fscore_support( # y_true=y_true[:, i], y_pred=y_pred[:, i], average='binary', zero_division=0)[0:3] # or_y_pred = or_y_pred | y_pred[:, i] # or_y_true = or_y_true | y_true[:, i] metrics_df = metrics_df.sort_index() # metrics_df.loc['Weighted Average'] = metrics_df.transpose().dot(label_prop) # metrics_df.loc['Average'] = metrics_df.mean() # metrics_df.loc['Weighted Average', 'F1'] = 2 / (1/metrics_df.loc['Weighted Average', "Recall"] + # 1/metrics_df.loc['Weighted Average', "Precision"]) # metrics_df.loc['Average', 'F1'] = 2 / (1/metrics_df.loc['Average', "Recall"] + # 1/metrics_df.loc['Average', "Precision"]) weighted_f1_score = metrics_df.loc['weighted avg', 'f1-score'] averaged_f1_score = metrics_df.loc['macro avg', 'f1-score'] # Calculate confusion matrix tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel() cm_df = pd.DataFrame(columns = ['Predicted No', 'Predicted Yes'], index = ['Actual No', 'Actual Yes']) # adding rows to an empty # dataframe at existing index cm_df.loc['Actual No'] = [tn,fp] cm_df.loc['Actual Yes'] = [fn,tp] # pooled_f1_score = f1_score(y_pred=or_y_pred, y_true=or_y_true) return ave_loss, metrics_df, cm_df,{ "weighted": weighted_f1_score, "averaged": averaged_f1_score, } def model_test(model, data_loader): # Put the model in evaluation mode--the dropout layers behave differently # during evaluation. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.eval() model.to(device) if torch.cuda.device_count() > 1: model = nn.DataParallel(model) num_batch = len(data_loader) # Below need to modify if change the input review_id, review_label, hmd_text, head_cust_text = [], [], [], [] agent = [] pred_logits = [] # Evaluate data for step, batch in tqdm(enumerate(data_loader), desc="Inference...", total=num_batch): if "anecdote_lead_final" in batch.keys(): review_label.extend(batch["anecdote_lead_final"]) review_id.extend(batch["_id"].tolist()) hmd_text.extend(batch["hmd_comments"]) head_cust_text.extend(batch["head_cust"]) agent.extend(batch["new_transcript_agent"]) b_review_input_ids = batch["review_input_ids"].to(device) b_review_attention_mask = batch["review_attention_mask"].to(device) b_review_token_type_ids = batch["review_token_type_ids"].to(device) b_agent_input_ids = batch["agent_input_ids"].to(device) b_agent_attention_mask = batch["agent_attention_mask"].to(device) b_agent_token_type_ids = batch["agent_token_type_ids"].to(device) # Tell pytorch not to bother with constructing the compute graph during # the forward pass, since this is only needed for backprop (training). with torch.no_grad(): (logits,) = model(review_input_ids=b_review_input_ids, review_token_type_ids=b_review_token_type_ids, review_attention_mask=b_review_attention_mask, agent_input_ids=b_agent_input_ids, agent_token_type_ids=b_agent_token_type_ids, agent_attention_mask=b_agent_attention_mask ) if logits.detach().cpu().numpy().size == 1: pred_logits.extend(logits.detach().cpu().numpy().reshape(1,)) else: pred_logits.extend(logits.detach().cpu().numpy()) # End of an epoch of validation # put model to train mode again. model.train() pred_logits = np.array(pred_logits) pred_prob = np.exp(pred_logits) pred_prob = pred_prob / (1 + pred_prob) pred_label = pred_prob.copy() pred_label[pred_label < 0.5] = 0 pred_label[pred_label >= 0.5] = 1 # compute the f1 score for each tags d = {'Probability':pred_prob,'Anecdotes Prediction':pred_label} pred_df = pd.DataFrame(d, columns=['Probability','Anecdotes Prediction']) result_df = pd.DataFrame( { "review_id": review_id, "hmd_text": hmd_text, "head_cust_text": head_cust_text, "agent": agent } ) if len(review_label) != 0: result_df["review_label"] = [x.item() for x in review_label] return pd.concat([result_df, pred_df], axis=1).set_index("review_id") Can anyone help me how to fix this issue? Thank you so much!!!
st46693
Apparently an nn.Embedding layer is pushed to the wrong device. Based on the posted code I cannot see where the issue might be, so could you try to narrow down the error by removing working parts of the code? The loss_fct in the forward method might create issues, since you are pushing the pos_weight to the default device in: loss_fct = nn.BCEWithLogitsLoss(pos_weight=pos_weight).cuda() Use .to(outputs.device) instead.
st46694
Hi ptrblck, Thanks so much for your response. I tried to change the loss_fct part but it gives me error: AttributeError: 'tuple' object has no attribute 'device' The error message shows up with model_train function. This is a function I define that includes train/validate/test. I can see from the progress bar that the training part can be done without any issues. The problem starts with the validation part – which is calling this line: ave_valid_loss, valid_f1_table, cm_table, f1_score = model_validate(model=model, data_loader=valid_data_loader) And model_validate function is defined as below: def model_validate(model, data_loader): model.eval() device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device) if torch.cuda.device_count() > 1: model = nn.DataParallel(model) label_prop = data_loader.dataset.dataset.label_prop() total_valid_loss = 0 batch_size = data_loader.batch_size num_batch = len(data_loader) y_pred, y_true = [], [] # Evaluate data for step, batch in tqdm(enumerate(data_loader), desc="Validation...", total=num_batch): b_review_input_ids = batch["review_input_ids"].to(device) b_review_attention_mask = batch["review_attention_mask"].to(device) b_review_token_type_ids = batch["review_token_type_ids"].to(device) b_agent_input_ids = batch["agent_input_ids"].to(device) b_agent_attention_mask = batch["agent_attention_mask"].to(device) b_agent_token_type_ids = batch["agent_token_type_ids"].to(device) b_binarized_label = batch["binarized_label"].to(device) with torch.no_grad(): (loss, logits,) = model(review_input_ids=b_review_input_ids, review_attention_mask=b_review_attention_mask, review_token_type_ids=b_review_token_type_ids, agent_input_ids=b_agent_input_ids, agent_attention_mask=b_agent_attention_mask, agent_token_type_ids=b_agent_token_type_ids, labels=b_binarized_label) total_valid_loss += loss.item() transfored_logits = torch.sigmoid(logits) numpy_probas = transfored_logits.detach().cpu().numpy() y_pred.extend(numpy_probas) y_true.extend(b_binarized_label.cpu().numpy()) # End of an epoch of validation # put model to train mode again. model.train() ave_loss = total_valid_loss / (num_batch * batch_size) y_pred = np.array(y_pred) y_pred[y_pred < 0.5] = 0 y_pred[y_pred >= 0.5] = 1 # Below is in case the input and target are not the same data format y_pred = np.array(y_pred, dtype=np.bool) y_true = np.array(y_true, dtype=np.bool) # compute the various f1 score for each label report = classification_report(y_true, y_pred, output_dict=True) metrics_df = pd.DataFrame(report).transpose() metrics_df = metrics_df.sort_index() weighted_f1_score = metrics_df.loc['weighted avg', 'f1-score'] averaged_f1_score = metrics_df.loc['macro avg', 'f1-score'] # Calculate confusion matrix tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel() cm_df = pd.DataFrame(columns = ['Predicted No', 'Predicted Yes'], index = ['Actual No', 'Actual Yes']) cm_df.loc['Actual No'] = [tn,fp] cm_df.loc['Actual Yes'] = [fn,tp] return ave_loss, metrics_df, cm_df,{ "weighted": weighted_f1_score, "averaged": averaged_f1_score, } The traceback: RuntimeError Traceback (most recent call last) <ipython-input-14-7ca45d5cff01> in <module> 7 model_train(model=model, train_data_loader=data_loader["train"], valid_data_loader=data_loader["valid"], 8 test_data_loader=data_loader["test"], optimizer=optimizer, scheduler=scheduler, ----> 9 num_epochs=args.num_epochs, seed=args.seed, logger=logger, out_dir=out_dir) ~/SageMaker/Anecdotes/train_valid_test.py in model_train(model, train_data_loader, valid_data_loader, test_data_loader, logger, optimizer, scheduler, num_epochs, seed, out_dir) 162 t_valid = time.time() 163 model.eval() --> 164 ave_valid_loss, valid_f1_table, cm_table, f1_score = model_validate(model=model, data_loader=valid_data_loader) 165 # Measure how long this epoch took. 166 validation_time = format_time(time.time() - t_valid) ~/SageMaker/Anecdotes/train_valid_test.py in model_validate(model, data_loader) 280 agent_token_type_ids=b_agent_token_type_ids, 281 --> 282 labels=b_binarized_label) 283 284 if num_gpus > 1: ~/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 548 result = self._slow_forward(*input, **kwargs) 549 else: --> 550 result = self.forward(*input, **kwargs) 551 for hook in self._forward_hooks.values(): 552 hook_result = hook(self, input, result) ~/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/parallel/data_parallel.py in forward(self, *inputs, **kwargs) 153 return self.module(*inputs[0], **kwargs[0]) 154 replicas = self.replicate(self.module, self.device_ids[:len(inputs)]) --> 155 outputs = self.parallel_apply(replicas, inputs, kwargs) 156 return self.gather(outputs, self.output_device) 157 ~/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/parallel/data_parallel.py in parallel_apply(self, replicas, inputs, kwargs) 163 164 def parallel_apply(self, replicas, inputs, kwargs): --> 165 return parallel_apply(replicas, inputs, kwargs, self.device_ids[:len(replicas)]) 166 167 def gather(self, outputs, output_device): ~/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/parallel/parallel_apply.py in parallel_apply(modules, inputs, kwargs_tup, devices) 83 output = results[i] 84 if isinstance(output, ExceptionWrapper): ---> 85 output.reraise() 86 outputs.append(output) 87 return outputs ~/anaconda3/envs/python3/lib/python3.6/site-packages/torch/_utils.py in reraise(self) 393 # (https://bugs.python.org/issue2651), so we work around it. 394 msg = KeyErrorMessage(msg) --> 395 raise self.exc_type(msg) Thank you again for your help!
st46695
I missed that outputs is a tuple, so use outputs[0].device instead or any other tensor, which was pushed to the right device.
st46696
Hi, Supposing that I have L = [1 1 1 0 0 2 2], where each number indicates a different class. Using MATLAB, I can write: A = zeros(numel(L)); A = bsxfun(@eq,L,L.'); A(~L,~L) = 0; which gives A = 1 1 1 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 Please, how can I do this in pytorch and with no loops? Thanks This question is similar to this stackoverflow question 7
st46697
jpainam: A = zeros(numel(L)); A = bsxfun(@eq,L,L.'); A(~L,~L) = 0; Even this way doesn’t work as expected L = torch.tensor([1, 1, 1, 0, 0, 2, 2]) A = (L == L.view(-1, 1)).long() tensor([[1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1]]) T = ~ (L != 0) A[T, T] = 0 tensor([[1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1]]) >>> which is a little bit different. Any help will be useful
st46698
I trained Transformer model for mask word prediction but my model output always same for every class tensor([[[-2.3026, -2.3026, -2.3026, ..., -2.3026, -2.3026, -2.3026], [-2.3026, -2.3026, -2.3026, ..., -2.3026, -2.3026, -2.3026], [-2.3026, -2.3026, -2.3026, ..., -2.3026, -2.3026, -2.3026], ..., [-2.3026, -2.3026, -2.3026, ..., -2.3026, -2.3026, -2.3026], [-2.3026, -2.3026, -2.3026, ..., -2.3026, -2.3026, -2.3026], [-2.3026, -2.3026, -2.3026, ..., -2.3026, -2.3026, -2.3026]]], device='cuda:0', grad_fn=<LogSoftmaxBackward>) After torch.exp() tensor([[[0.1000, 0.1000, 0.1000, ..., 0.1000, 0.1000, 0.1000], [0.1000, 0.1000, 0.1000, ..., 0.1000, 0.1000, 0.1000], [0.1000, 0.1000, 0.1000, ..., 0.1000, 0.1000, 0.1000], ..., [0.1000, 0.1000, 0.1000, ..., 0.1000, 0.1000, 0.1000], [0.1000, 0.1000, 0.1000, ..., 0.1000, 0.1000, 0.1000], [0.1000, 0.1000, 0.1000, ..., 0.1000, 0.1000, 0.1000]]], device='cuda:0', grad_fn=<ExpBackward>) What can be wrong here? Thanks in advance
st46699
I have 1-hour resolution temperature data with the following sample input-1 format. I use the LSTM to find anomalies with this format successfully. But I am not sure if LSTM’s learn any temporal dependencies with this type of format. Do I need to use the format as shown in input-2 where I create subsequences for each day? input1 2020-01-01 01:00:00,100 2020-01-01 02:00:00,200 2020-01-01 03:00:00,900 2020-01-01 04:00:00,300 2020-01-02 01:00:00,100 2020-01-02 02:00:00,200 2020-01-02 03:00:00 100 2020-01-02 04:00:00 300 input2 ,1,2,3,4 2020-01-01,100,200,900,300 2020-01-02,100,200,100,300
st46700
Currently, I am creating a neural network using bindsnet. I’m having trouble with the error “softmax” not implemented for’Long’. I converted a 1x64 array for x and a tensor type for y for 1x6, but I get an error. Does anyone know the correct way to write it? import torch from bindsnet.network import Network from bindsnet.network.nodes import Input, LIFNodes from bindsnet.network.topology import Connection from bindsnet.network.monitors import Monitor import numpy as np time = 25 network = Network() inpt = Input(n=64,shape=[1,64], sum_input=True) middle = LIFNodes(n=40, trace=True, sum_input=True) center = LIFNodes(n=40, trace=True, sum_input=True) final = LIFNodes(n=40, trace=True, sum_input=True) out = LIFNodes(n=6, sum_input=True) inpt_middle = Connection(source=inpt, target=middle, wmin=0, wmax=1e-1) middle_center = Connection(source=middle, target=center, wmin=0, wmax=1e-1) center_final = Connection(source=center, target=final, wmin=0, wmax=1e-1) final_out = Connection(source=final, target=out, wmin=0, wmax=1e-1) network.add_layer(inpt, name='A') network.add_layer(middle, name='B') network.add_layer(center, name='C') network.add_layer(final, name='D') network.add_layer(out, name='E') foward_connection = Connection(source=inpt, target=middle, w=0.05 + 0.1*torch.randn(inpt.n, middle.n)) network.add_connection(connection=foward_connection, source="A", target="B") foward_connection = Connection(source=middle, target=center, w=0.05 + 0.1*torch.randn(middle.n, center.n)) network.add_connection(connection=foward_connection, source="B", target="C") foward_connection = Connection(source=center, target=final, w=0.05 + 0.1*torch.randn(center.n, final.n)) network.add_connection(connection=foward_connection, source="C", target="D") foward_connection = Connection(source=final, target=out, w=0.05 + 0.1*torch.randn(final.n, out.n)) network.add_connection(connection=foward_connection, source="D", target="E") recurrent_connection = Connection(source=out, target=out, w=0.025*(torch.eye(out.n)-1),) network.add_connection(connection=recurrent_connection, source="E", target="E") inpt_monitor = Monitor(obj=inpt, state_vars=("s","v"), time=500,) middle_monitor = Monitor(obj=inpt, state_vars=("s","v"), time=500,) center_monitor = Monitor(obj=inpt, state_vars=("s","v"), time=500,) final_monitor = Monitor(obj=inpt, state_vars=("s","v"), time=500,) out_monitor = Monitor(obj=inpt, state_vars=("s","v"), time=500,) # Monitorをネットワークに接続 network.add_monitor(monitor=inpt_monitor, name="A") network.add_monitor(monitor=middle_monitor, name="B") network.add_monitor(monitor=center_monitor, name="C") network.add_monitor(monitor=final_monitor, name="D") network.add_monitor(monitor=out_monitor, name="E") for l in network.layers: m = Monitor(network.layers[l], state_vars=['s'], time=time) network.add_monitor(m, name=l) npzfile = np.load("C:/Users/name/Desktop/myo-python-1.0.4/myo-armband-nn-master/data/train_set.npz") x = npzfile['x'] #1×64 y = npzfile['y'] #1×6 # tensor x = torch.from_numpy(x).clone() y = torch.from_numpy(y).clone() grads = {} lr, lr_decay = 1e-2, 0.95 criterion = torch.nn.CrossEntropyLoss() spike_ims, spike_axes, weight_im = None, None, None for i,(x,y) in enumerate(zip(x.view(-1,64), y)): inputs = {'A': x.repeat(time, 1),'E_b': torch.ones(time, 1)} network.run(inputs=inputs, time=time) y = torch.tensor(y).long() spikes = {l: network.monitors[l].get('s') for l in network.layers} summed_inputs = {l: network.layers[l].summed for l in network.layers} # softmax output = spikes['E'].sum(-1).softmax(0).view(1,-1) ☚ error predicted = output.argmax(1).item() grads['dl/df'] = summed_inputs['E'].softmax(0) grads['dl/df'][y] -= 1 grads['dl/dw'] = torch.ger(summed_inputs['A'], grads['dl/df']) network.connections['A','E'].w -= lr*grads['dl/dw'] if i > 0 and i % 500 == 0: lr = lr_decay network.reset_()
st46701
The softmax method cannot be applied to LongTensors, as it would round them (and thus wouldn’t really make sense), so you should transform the incoming tensor to a FloatTensor via tensor = tensor.float().
st46702
Hi, I have a very specific use case of PyTorch and I am not sure what would be the suggested way to implement it. So, I will first describe what I want to do. Then, how I attempted to do it. Goal: Let say I have a model called net which has trainable parameters from those I am interested in say only in convolutional layers: for module in net.modules(): if is_conv_layer(module): module.weight # This is the weight I am interested in. Now, what I want to do is to replace module.weight’s with another set of Parameter’s let us call weight_new where weight_new=weight*weight2 Here, the important thing is that I want to update weight2 values and only use the initial values of module.weight. Attempt: for module in net.modules(): if is_conv_layer(module): data = module.weight.data module.weight = weight2 module.weight.data *= data So, basically, I replace trainable parameters with new Parameters weight2 and only after that, I updated .data term so that it is the multiplication of weight and weight2. This is because I cannot modify Parameter before assigning it to module.weight. When I minimize the losses for these, I realized that weight2 is not really updating itself. Am I doing it wrong, what would be the suggested way of doing this? If I am not mistaken, I read that overwriting weight.data is not a suggested way to do things in PyTorch and it may be the reason behind the weird behaviors. Is it really the case?
st46703
I have some vectors which I create by reading a CSV (using rapidcsv.h) and I was wondering how I can get it to an input tensor so that I can use this as my model input. I have: std::vector<float> some_a = doc.GetColumn<float>(0); std::vector<float> some_b = doc.GetColumn<float>(1); std::vector<float> some_c = doc.GetColumn<float>(2); std::cout << "Read " << some_a.size() << " values." << std::endl; //out: 512 std::cout << "Read " << some_b.size() << " values." << std::endl; //out: 512 std::cout << "Read " << some_c.size() << " values." << std::endl; //out:512 std::vector<torch::jit::IValue> inputs; inputs.push_back(torch::zeros({1, 3, 512})); I would like to assign some_a, some_b and some_c to the 3 tensors in inputs [0,1,:], [0,2,:], [0,3,:]. how does one go about achieving this?
st46704
What can I do to mitigate this? Is it a version issue? I have the newest version of pytorch and python. Is it an issue with -the code (refrain from saving all variables, making the mini-batch smaller?) -the operating system (I use ubuntu 20.04) The specific error I get when running dmesg in the terminal is “Out of memory: Killed process”
st46705
Hi, It is very hard to say with no information about what you were doing. Is it actually your python process that was eating up all the memory or something else? If it was the python process, what were you doing when it happened?
st46706
I’m working on some wrappers for Pytorch functions with the goal of extending the Tensor class, and am running into an issue with functions like torch.mode (among many others) that return function-specific types like torch.return_types.mode. I’d like to replace the values attribute of the output object with a different tensor before returning it, but the output is immutable and I can’t find the constructors for the classes in torch.return_types anywhere. Any idea where these constructors are located (assuming they’re implemented somewhere in Python)? I’d be alright with returning a plain tuple instead, but would love if there is a means of handling this that’s more faithful to the original Pytorch behavior. Thanks!
st46707
Solved by albanD in post #2 Hi, You can re-use the original result to create a new instance of the same class: out = torch.mode(inp) final_out = out.__class__(new_values)
st46708
Hi, You can re-use the original result to create a new instance of the same class: out = torch.mode(inp) final_out = out.__class__(new_values)
st46709
I’m trying to fit this very simple data with targets in the range (0, 1), but even when two values are far apart, like .2 and .45, the loss is very small. So I end up with a very small loss, but the predictions are very wrong. How can improve my predictions? Here’s my data and the model predictions after training for 1000 epochs with Adam, MSE, and a learning rate of .001. Trying BCELoss didn’t improve the results. Inputs = [[14.0110, 2.0000], [18.9990, 3.0000], [12.0110, 0.0000], [16.9990, 1.0000]] Targets = [0.6774895, 0.12747164, 0.02246823, 0.00056751847] Predictions = [0.37114963, 0.31669545, 0.1016788, 0.09256815] The last sample’s prediction is 163 times bigger than its target, but the loss is tiny (0.0084). Here’s my model: class Net(torch.nn.Module): def __init__(self, num_features): super().__init__() self.linear_hidden_1 = torch.nn.Linear(num_features, num_features * 2) self.linear_out = torch.nn.Linear(num_features * 2, 1) def forward(self, inputs): hidden = torch.nn.ReLU()(self.linear_hidden_1(inputs)) out = torch.nn.Sigmoid()(self.linear_out(hidden)).flatten() return out I would really appreciate any suggestions how to get it to predict properly.
st46710
If your target values have a small values range and are thus also yielding a small loss, you could try to e.g. increase the learning rate. Alternatively, you could also normalize the targets to a “proper” range during training and “unnormalize” the model predictions during evaluation to get the real prediction values again.
st46711
If the target range is so small, does it really matter that the loss is small too? Since updates to the weights have to be small since the values are packed together in such a small range, I feel like the small loss might not be a problem (e.g. if the range was (0,10), the weights & loss might just be scaled up by 10 & 10^2 without changing learning performance much). I tried to train with targets scaled up to (0,100) but it didn’t noticeably improve performance.
st46712
Hello Everyone, How could I freeze some parts of the layer weights to zero and not the entire layer. I tried below code, but it doesn’t freeze the specific parts(1:10 array in 2nd dimension) of the layer weights. I am new to ML & started with Pytorch. Appreciate any help. Thanks. for child in model_ft.children(): print(“Freezing Parameters(1->10) on the Convolution Layer”,child) for param in child.parameters(): param.data[:,1:10,:,:].zero_() param.data[:,1:10,:,:].requires_grad = False optimizer_ft = OPTIM.SGD(filter(lambda p: p.requires_grad, model_ft.parameters()), lr=0.001, momentum=0.9)
st46713
I think freezing specific parts of a parameter is not possible in PyTorch because requires_grad flag is set on each Parameter(collection of weights), not each weight. One possible approach is manually zeroing gradient before you call optimizer function. After you calculate gradient using backward() function, call param.grad[:, 1:10, :, :] = 0 to achieve you want. Further, you can automatize this method using backward_hook in PyTorch. You can check this link if you want. http://pytorch.org/tutorials/beginner/former_torchies/nn_tutorial.html 433
st46714
Thanks Sonsang, This works, I can see the required weights are set to zero after training, but the training accuracy has come down. Initializing(xavier_normal) the non-zero weights didn’t help. Not sure if I am missing something else in my setup. Does this approach work same as the freezing the weights to zero in the beginning?
st46715
Do you mean that training accuracy is going down while training, or the training accuracy decreased after you zeroing-out some gradients? In the first case, I’m not sure what is happening. Maybe full code will help the understanding of that situation. In the second case, it is natural because you use less parameters than the original model. Thank you.
st46716
Just to double check, how is this mathematically correct? Since the chain rule involves products (and sums) couldn’t it lead to earlier layers having gradient zero even though they should not? Consider just a simple 3 number abc and the derivative would be the product of each a’*b’*c’. Then set b’=0 yields the wrong derivative when it should be a’*b’, no?
st46717
It does not mean that we set the gradient of b to zero. param.grad[:, 1:10, :, :] = 0 This line indicates that we just ignore the calculated gradient w.r.t loss so that the parameters are not updated. You do not have to worry about your example because all gradients are calculated with backward() call. We modify the gradient after the backward(), so other parameters are safe.
st46718
sonsang: param.grad[:, 1:10, :, :] = 0 This works, thanks a lot. But what if I want to set different learning rate to the first 10 rows of embedding ? Can I just grad *= 0.1 like this ?
st46719
Sure. You can do anything you want with those gradients between backward() and optimizer.step() calls.
st46720
Your suggestion works, and might really be useful in a lot of cases, but it may not have the same effect with (requires_grad=false) It works since it sets the selected gradients to zero and ensure thats there will be no changes for some certain weights, but the gradients will still be calculated for all the weights, including the ones that have been frozen. I am concerned about the outcome of that since I am not sure if it would create the same kind of result as setting a requires_grad flag to false. Because I think =not sure tho= that the loss calculation might be omitting the participation of frozen parameters in the inference when we set requires_grad to false and this would create a focus on the parameters with requires_grad set to true during loss calculation and may eventually let these parameters to be penalized as they are responsible for all the losses of the network. Please correct me if I am wrong, I know I am assuming a lot of things but, maybe these thoughts can help someone.
st46721
From the perspective of mathematics, they are the same. Freezing means no updating. Equivalently, the gradients to be updated on are zeros.
st46722
sonsang: backward I run like this and no error. Can I use like this? This way doesnt requires manually zeroing grad like your method: decoder.linear.weight[:100].require_grad = False
st46723
I have this model class my_model(nn.Module): def __init__(self): super(my_model,self).__init__() self.conv1 = nn.Conv2d(3,16,kernel_size=3,stride=1,padding=1) self.conv2 = nn.Conv2d(16,32,kernel_size=3,stride=1,padding=1) self.conv3 = nn.Conv2d(32,64,kernel_size=3,stride=1,padding=1) self.pool = nn.MaxPool2d(2, 2) self.fc1 = nn.Linear(4*4*64,64) self.fc2 = nn.Linear(64,10) def forward(self,inp): ab = self.pool(F.relu(self.conv1(inp))) ab = self.pool(F.relu(self.conv2(ab))) ab = self.pool(F.relu(self.conv3(ab))) ab = ab.view(ab.shape[0],-1) ab = F.relu(self.fc1(ab)) ab = F.relu(self.fc2(ab)) return ab can you tell how can i set the gradients of first filter of the conv1 layer to be zero using backward hook
st46724
What does this mean, that the first 100 will be frozen? I proved this, and it’s certainly not wrong, but I don’t really understand what weights are frozen, because they are not the first 100?
st46725
Hi, Let me ask you a quick question: When I have a model which has total 5 layer, if I want to freeze 3rd layer from the beginning layer, then the gradient of 3rd layer will affect updating 2nd and 1st layer, but the effect of 3rd layer’s gradients is consistent, and thus there won’t be problem, is my understanding correct?
st46726
Yes, you only need to remember this: calculating the gradients and update the weights using the computed gradients are two different operations.
st46727
Hi, I see this issue is going on for a really long time, so I wrote this 131 simple repo in PyTorch. I hope someone may find it useful. It supports only partial freezing of Conv2d, Conv3d and Linear layers, but these are the most common anyway. If you want me to extend it to other layers, feel free to send me a message.
st46728
Hi, I created a model with 2 embeddings and an lstm module like below. My input is of the shape (batch_size, window_size, feature_len), so a 3-dimension matrix. class model (nn.Module): def __init__(self, some parameters): self.embed1 = nn.Embedding(len1, 10) self.embed2 = nn.Embedding(len2, 10) def forward(self, vec_seq): # vec_seq.size() --> (batch_size, window_size, feature_len) # vec_seq.type() --> torch.cuda.FloatTensor var1 = autograd.Variable(vec_seq[:,:,0].type(torch.cuda.LongTensor)) var2 = autograd.Variable(vec_seq[:,:,1].type(torch.cuda.LongTensor)) var1_emb = self.embed1(var1) var2_emb = self.embed2(var2) var_embed = torch.cat((var1_emb, var2_emb, autograd.Variable(vec_seq[:,:,2].contiguous().view(batch_size, window_size, -1)), autograd.Variable(vec_seq[:,:,3].contiguous().view(batch_size, window_size, -1)), 2) # following some LSTM operations. However, when I debug my program, I found all the values of var1_embed and var2_embed are nan, which is quite weird. In some cases, they are not all nan, instead part of the embedding is nan and the remaining is a float. like the image below. The corresponding embedding is like below. ipembed.png692×437 17 KB I used DataLoader to load the data with following statement. train_dataloader = DataLoader(train_data,batch_size=opt.batch_size,shuffle=True,num_workers=opt.num_workers). where batch_size=4 and num_workers=4. What’s leading to this error? Thanks.
st46729
Hard to say. It would be better if you could provide a minimal scripts that I reproduce your problem directly in my laptop.
st46730
Dear Yun, Thanks for your help! I finally found out where the error came from. When I did normalization on my data, some value divides 0 and got np.nan and when more and more data were fed to the model, the nan error propagates through the network. Thanks very much for your help!
st46731
So the problem was not about Embedding layer? Also, i cannot find normalization part in your code attached
st46732
This answer didn’t help me but I found the problem I had. My db was so small compare to the dimensions of the tutorial I was following and my embeddings were way to big for my data available, so eventually the NaN propagates through the network. Making my embedding nets smaller (smaller number of factors / columns in the matrix) solved the NaN problem for me.
st46733
Greetings! I just started using pytorch and so far I’ve been really impressed with the software and grateful for how over-the-top helpful the community has been. I wrote up a pollen forecaster with RNNs using pytorch here 21. There’s not too much that’s novel given all the code examples and documentation, but I thought perhaps someone could find it useful (assuming this is the correct forum for such things) Thanks!
st46734
Hi All, I am getting an error - File “c:\Users\Paritosh\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py”, line 232, in return [default_collate(samples) for samples in transposed] File “c:\Users\Paritosh\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py”, line 218, in default_collate return torch.stack([torch.from_numpy(b) for b in batch], 0) RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 5 and 8 in dimension 1 at c:\a\w\1\s\tmp_conda_3.6_122405\conda\conda-bld\pytorch_1549283197917\work\aten\src\th\generic/THTensorMoreMath.cpp:1307 While I am using batchsize=1 then I am not getting any error. Could anybody help me with the issue?
st46735
You should check the size of all data returned in your Dataset, and you will find the one with different shapes (5 or 8).
st46736
Could I ask the stupid question, what’s the meaning of “different shapes (5 or 8).” ? For e.g., My input shape is (3,512,512)(chw) and the outpust shape is (80, 128,128), if some data get shape 5 or 8, which dimension of the data is 5 or 8
st46737
I am having the same error which also doesn’t occur when I use a batch size of 1. Looped through the dataset and can confirm all images are 3x224x224 and all annotations are 1x224x224. RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 224 and 244 in dimension 2 at /tmp/pip-req-build-9oilk29k/aten/src/TH/generic/THTensor.cpp:689 How is that happening? It even says 224 and 224 in dimension 2 which doesn’t make sense. Shouldn’t this exception occur when they aren’t matching?
st46738
The error states that the shapes are 224 vs. 244 (note the changed 2 and 4), so I guess you might have a similar typo somewhere in your code?
st46739
Thanks a lot! I already solved this. I asked this as a separate question here and on SO. Then I noticed that it is not 224x224 but 224x244 and got mad. I am so blind. Anyways changing that one image manually in my case (or using a resize transformation) did the job. PS: I have noticed how much you help on this forum even before signing up. You are the real MVP.
st46740
for batch_id, (data, target) in enumerate(tqdm(train_loader)): print(target) print('Entered for loop') target = torch.sparse.torch.eye(10).index_select(dim=0, index=target) data, target = Variable(data), Variable(target) The line which contains the index_select function gives this error and I am not able to find a solution to it anywhere. The target variable on printing looks like this: tensor([[4], [1], [8], [5], [9], [5], [5], [8], [4], [6]]) How do I convert the target variable into a vector? Isn’t it already a vector?
st46741
Solved by raoashish10 in post #5 I want to update my answer because the previous solution was a little misleading. You can use the flatten() function. In my case, I used it as target = torch.sparse.torch.eye(10).index_select(dim=0, index=target.long().flatten()) The problem with the previous solution is that it erases the error b…
st46742
Yes I did! I think the index attribute expects a tensor of all the classes for example if I have 10 classes, then it expects a tensor([0,1,2,3,4,5,6,7,8,9]). So I declared a tensor in this manner and it worked for me. Let me know if it works for you too.
st46743
I want to update my answer because the previous solution was a little misleading. You can use the flatten() function. In my case, I used it as target = torch.sparse.torch.eye(10).index_select(dim=0, index=target.long().flatten()) The problem with the previous solution is that it erases the error but will decrease your accuracy considerably.
st46744
Hi. When I use nn.DataParallel for training my model, I have a problem with the number of threads. Even though I set then number of threads for the process (by using torch.set_num_threads), it takes a lot of threads. I checked that the torch.set_num_threads works well for using single gpu. Is there any setting that I missed? How can I deal with the problem? Thank you
st46745
Are you sure these threads are used by nn.DataParallel or could e.g. the DataLoader spawn new workers in your setup?
st46746
I have used pickle to store my tensors in a database. I am trying to get them out and un-serialize them using pickle again. pickle.loads(val[3]) Where val represents the pytorch tensor in serialized string form. I get this error: TypeError: a bytes-like object is required, not 'str' Are any of you storing your tensors in a database? How do you do this?
st46747
You could try to decode the string first via: unpickled = pickle.loads(codecs.decode(pickled, "base64")) using the right encoding.
st46748
I recently test MLPerf , and use pytorch as runtime. I found there’s only 1 core could be used the mutlthread scenario. It’s said that py::gil_scoped_release release is needed to enable python multithread. Does anybody know how to enable multi thread in pytorch.
st46749
Could you explain what “MLPerf multi threads” are and where you are using multi-threading in your code?
st46750
Hi. I’m using transformer for audio classification. but there is problem with multi_head_attention_forward function. /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in multi_head_attention_forward(query, key, value, embed_dim_to_check, num_heads, in_proj_weight, in_proj_bias, bias_k, bias_v, add_zero_attn, dropout_p, out_proj_weight, out_proj_bias, training, key_padding_mask, need_weights, attn_mask, use_separate_proj_weight, q_proj_weight, k_proj_weight, v_proj_weight, static_k, static_v) 4132 q_proj_weight=q_proj_weight, k_proj_weight=k_proj_weight, 4133 v_proj_weight=v_proj_weight, static_k=static_k, static_v=static_v) -> 4134 tgt_len, bsz, embed_dim = query.size() 4135 assert embed_dim == embed_dim_to_check 4136 # allow MHA to have different sizes for the feature dimension ValueError: too many values to unpack (expected 3) please help.
st46751
The nn.MultiHeadAttention module returns attn_outpu and attn_output_weights as described in the docs 16. Based on the error message it seems you might be trying to unpack a wrong number of return values.
st46752
I am trying to do semantic segmentation with two classes. I have 224x224x3 images and 224x224 binary segmentation masks. I am reshaping the masks to be 224x224x1 (I read somewhere that this is the format that I should pass to the model). When I try to loop through the train data loader it either runs without errors or I get the following error: Traceback (most recent call last): File "/Users/nikolaykolibarov/Desktop/GATE/rooftop-recognition/rooftop-edge-segmentation-ml/main.py", line 43, in <module> for i, sample in enumerate(train_loader): File "/Users/nikolaykolibarov/opt/anaconda3/envs/dtcc/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 346, in __next__ data = self._dataset_fetcher.fetch(index) # may raise StopIteration File "/Users/nikolaykolibarov/opt/anaconda3/envs/dtcc/lib/python3.7/site-packages/torch/utils/data/_utils/fetch.py", line 47, in fetch return self.collate_fn(data) File "/Users/nikolaykolibarov/opt/anaconda3/envs/dtcc/lib/python3.7/site-packages/torch/utils/data/_utils/collate.py", line 79, in default_collate return [default_collate(samples) for samples in transposed] File "/Users/nikolaykolibarov/opt/anaconda3/envs/dtcc/lib/python3.7/site-packages/torch/utils/data/_utils/collate.py", line 79, in <listcomp> return [default_collate(samples) for samples in transposed] File "/Users/nikolaykolibarov/opt/anaconda3/envs/dtcc/lib/python3.7/site-packages/torch/utils/data/_utils/collate.py", line 55, in default_collate return torch.stack(batch, 0, out=out) RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 224 and 244 in dimension 2 at /tmp/pip-req-build-9oilk29k/aten/src/TH/generic/THTensor.cpp:689 Most of the issues with the same exception I found online don’t have matching numbers like I do (Got 224 and 224). I don’t understand, this exception should occur when they aren’t equal (if I am not wrong). When I run it, occasionally I get this error a few times, and then it doesn’t occur a few times. I am not sure if I messed something up with the data types and shapes or it is something else. Here is the code: roof_edges_dataset.py: import os import cv2 as cv from torch.utils.data import Dataset from torchvision.transforms import transforms from utils import create_binary_mask, get_labelme_shapes, plot_segmentation_dataset class RoofEdgesDataset(Dataset): def __init__(self, im_path, ann_path, transform=None): self.im_path = im_path self.ann_path = ann_path self.transform = transform self.im_fn_list = sorted(os.listdir(im_path), key=lambda x: int(x.split('.')[0])) self.ann_fn_list = sorted(os.listdir(ann_path), key=lambda x: int(x.split('.')[0])) def __len__(self): return len(self.im_fn_list) def __getitem__(self, index): im_path = os.path.join(self.im_path, self.im_fn_list[index]) im = cv.imread(im_path) ann_path = os.path.join(self.ann_path, self.ann_fn_list[index]) ann = create_binary_mask(im, get_labelme_shapes(ann_path)) ann = ann.reshape(ann.shape[0], ann.shape[1], 1) ann = transforms.ToTensor()(ann) # ann = torch.tensor(ann) # ann = ann.permute(2, 0, 1) if self.transform: im = self.transform(im) return im, ann main.py import torch import torchvision.transforms as transforms from torch.utils.data import DataLoader from roof_edges_dataset import RoofEdgesDataset # Device device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Hyperparameters in_im_shape = (3, 224, 224) num_classes = 2 # Edge / Non-edge learning_rate = 0.001 batch_size = 4 n_epochs = 10 # Data - 60% Train - 20% Val - 20% Test transformations = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) dataset = RoofEdgesDataset(im_path='data/images', ann_path='data/annotations', transform=transformations) train_size = int(0.8 * len(dataset)) test_size = len(dataset) - train_size train_dataset, test_dataset = torch.utils.data.random_split(dataset, [train_size, test_size]) train_size = int(0.8 * len(train_dataset)) val_size = len(train_dataset) - train_size train_dataset, val_dataset = torch.utils.data.random_split(train_dataset, [train_size, val_size]) train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) val_loader = DataLoader(dataset=val_dataset, batch_size=batch_size, shuffle=True) test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True) print(len(train_loader)) print(len(val_loader)) print(len(test_loader)) # Model # Loss and Optimizer # Train for epoch in range(n_epochs): for batch_idx, (image, annotation) in enumerate(train_loader): image = image.to(device=device) annotation = annotation.to(device=device) print(image.shape) print(annotation.shape) break # Evaluate I would be also very thankful if you let me know if something is done in a wrong or stupid way and how to do it better. Thanks in advance!
st46753
Solved by codearts in post #2 Never mind. I am blind. I thought it says 224x224 but it says 224x244 (which makes sense now). I used a resize transformation which fixes the issue in case of more images with unmatching dimensions. In my case I had just one image which was 224x244 so I fixed it manually and removed the resize tran…
st46754
Never mind. I am blind. I thought it says 224x224 but it says 224x244 (which makes sense now). I used a resize transformation which fixes the issue in case of more images with unmatching dimensions. In my case I had just one image which was 224x244 so I fixed it manually and removed the resize transformation.
st46755
I’m working on building a transformer that translates polynomials into specific sequences of numbers. However, I’m running into a lot of trouble with the loss function. I understand that when you use nnTransformer, the source input needs to be size (S,N,E) (where S is the length of the input) and the corresponding target needs to be (T,N,E) (where T is the target length). The transformer returns an output of size (T,N,E). I tried to implement nn.CrossEntropyLoss to calculate the loss, but when I do I get this error: IndexError: Target -1 is out of bounds. I don’t understand what is causing this error. Could anyone help me understand what it means so I can fix the problem? The tensors that I am sending to nn.CrossEntropyLoss are sizes [25, 32, 512] and [25, 512]. What could be causing this error? Any help is appreciated! Thanks!
st46756
Make sure that the target vocab is created correctly. The target labels for a batch are as expected. Also, if you’ve created your custom loss function that might have an issue. Is possible share your code.
st46757
Hello, I am implementing DQN for Reinforcement learning in pytorch I am getting for all actions the same Q Values for different states and actions What could be the reason ? Thank you for your help
st46758
Yesterday, I discovered pynvml doesn’t respect CUDA_VISIBLE_DEVICES, so the ids of torch.cuda and nvml don’t match if you need to change which gpus are used via CUDA_VISIBLE_DEVICES, which breaks the software that uses pynvml. I wrote a re-mapper to solve the problem: github.com stas00/ipyexperiments/blob/a60a23141e2ecb11c0554f8be535fe6ccb831604/ipyexperiments/utils/mem.py#L33-L44 def get_nvml_gpu_id(torch_gpu_id): """ Remap torch device id to nvml device id, respecting CUDA_VISIBLE_DEVICES. If the latter isn't set return the same id """ # if CUDA_VISIBLE_DEVICES is used automagically remap the id since pynvml ignores this env var if "CUDA_VISIBLE_DEVICES" in os.environ: ids = list(map(int, os.environ.get("CUDA_VISIBLE_DEVICES", "").split(","))) return ids[torch_gpu_id] # remap else: return torch_gpu_id may be it might be of use to others. Usage: [...] torch_gpu_id = torch.cuda.current_device() nvml_gpu_id = get_nvml_gpu_id(torch_gpu_id) handle = pynvml.nvmlDeviceGetHandleByIndex(nvml_gpu_id) [....] I also suggested for pynvml to integrate it directly https://github.com/gpuopenanalytics/pynvml/issues/28 6
st46759
Hi, I know there is KL divergence loss in pytorch. but the limitation with KL divergence is that sum of the distribution should be 1. however, my target distribution is like 1d-Gaussian distributions where the sum of the distribution is not equal to1. for example, {0,0,0,0.01,0.02,...0.8,0.9,1.0,0.9,0.8........0.02,0.01,0,0,0,0} I tried to model this as a multi-label sigmoid cross entropy. for example, target * (pred) + 1 - target(1-pred) however, I found out this is not a good loss to model this problem. for example, say that one of the target probability is 0.6. when pred is approaching to 0.6, the loss is not approaching to 0. -(0.6 * (torch.log(0.6)) + 0.4 * (torch.log(0.4)))= 0.9163 I tried to model this problem as L1 loss, but the result is pretty bad. any good advice for modeling this problem?
st46760
May be you could use KL Div loss on the normalized data (instead of applying it on the original data). So that the sum is always 1.
st46761
How would we run a “partial” backwards on one subgraph, pause, then continue upward on a previous subgraph in the same overall backward pass? My current idea, which works to some extent, is to freeze all but one subgraph, call backwards, then refreeze it, unfreeze the next section, and recall backwards. So essentially repeated backwards calls to compose a part-by-part overall backwards call. However, this necessitates the use of retain_graph. Due to memory constraints, I’d prefer not to do this - instead I’d like to figure out a way for all of these to be part of the same backward pass. Is this possible? I thought perhaps it might require rewriting the execution engine, but is it possible with the higher-level APIs?
st46762
Hello everyone, I am currently doing a project using instance normalization as my batch size is 1. However, whenever I start training, I get the following error below: ValueError: InstanceNorm1d returns 0-filled tensor to 2D tensor.This is because InstanceNorm1d reshapes inputs to(1, N * C, …) from (N, C,…) and this makesvariances 0. I know that this error occurs as my input shape after max pooling is (bs * C) while instancenorm1d only allows input shape (bs * C * N). Does anyone have any idea how to solve this issue? Or is there any way to train my model in batch size 1 with batch norm instead? Thank you.
st46763
I am working on a linear model to make predictions. The problem I am having is that my loss is higher than my actual values to be predicted. To see if it is a problem with the data I have printed at several spots throughout trying to find if there are any disparities in the data but I find none. I have even tried leaking the expected values, making the inputs and labels the same. Loss is still extremely high. Hoping for some guidance. Below is the code for my model. train_target = th.tensor(df["Label"].values.astype(np.float32)) train = th.tensor(df.drop("Label",axis=1).values.astype(np.float32)) train_data = TensorDataset(train, train_target) train_dl = DataLoader(train_data, batch_size = batch_size, shuffle=True) print(train_target.shape) class LinReg(nn.Module): # Init layers def __init__( self, in_dim: int = 13, out_dim: int = 1, latent_base: int = 128, dropout: float = 0.5): super(LinReg, self).__init__() self.net = nn.Sequential( nn.Dropout(dropout), nn.Linear(in_dim, latent_base), nn.PReLU(), nn.Dropout(dropout), nn.Linear(latent_base, 1) ) # Forward def forward(self, x: th.Tensor) -> th.Tensor: return self.net(x) model = LinReg() model.cuda() optimizer = th.optim.RMSprop(model.parameters(), lr = 1e-3) criterion = nn.L1Loss() for i in range(epochs): for inputs, labels in train_dl: y_pred = model(inputs.to(device)) loss = criterion(y_pred, labels.to(device)) loss.backward() optimizer.zero_grad() optimizer.step() if i == (epochs-1): pred = y_pred y = labels if i%1==0: print('Epoch {}, Loss: {}'.format(i, loss.item()))
st46764
Solved by pchandrasekaran in post #3 optimizer.zero_grad() loss.backward() optimizer.step() I believe this may fix your issue. You need to clear all the gradients before you perform a backward pass again. Also as Alex mentioned, using L1Loss() may exacerbate the issue in some cases.
st46765
I’m not sure that such use of dropout is correct. And use of L1Loss instead of MSELoss may aggravate the issue.
st46766
optimizer.zero_grad() loss.backward() optimizer.step() I believe this may fix your issue. You need to clear all the gradients before you perform a backward pass again. Also as Alex mentioned, using L1Loss() may exacerbate the issue in some cases.
st46767
Try as suggested by @pchandrasekaran Also, how’s your model behaving when you try to run it on CPU? In my personal experience running some models on GPU resulted in exploding loss sometimes (the reason for which is still unclear to me). Try running it on CPU once.