instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
PyTorch MNIST Model RuntimeError: mat1 and mat2 shapes cannot be multiplied (3584x28 and 784x10)
I'm trying to build a simple MNIST Model and this is what I've built - training_loader = DataLoader(training_dataset, 128, shuffle = True) validation_loader = DataLoader(validation_dataset, 128) class mnistmodel(nn.Module): def __init__(self): super().__init__() self.linear1 = nn.Linear(784, 10) self.linear2 = nn.Linear(10, 5) self.linear3 = nn.Linear(5, 10) def forward(self, xb): xb.reshape(-1, 784) predicted = F.relu(self.linear1(xb)) predicted.reshape(-1, 10) predicted = F.relu(self.linear2(predicted)) predicted.reshape(-1, 5) predicted = self.linear3(predicted) return predicted def training_step(self, batch): images, labels = batch predicted = self(images) loss = F.cross_entropy(predicted, labels) return loss def validation_step(self, batch): images, labels = batch predicted = self(images) loss = F.cross_entropy(predicted, labels) _, preds = torch.max(predicted, dim=1) accuracy = torch.tensor(torch.sum(preds == labels).item() / len(preds)) return {'validation_loss': loss, 'validation_accuracy': accuracy} def validation_epoch_end(self, outputs): batch_losses = [x['validation_loss'] for x in outputs] epoch_loss = torch.stack(batch_losses).mean() batch_accs = [x['validation_acc'] for x in outputs] epoch_acc = torch.stack(batch_accs).mean() return {'validation_loss': epoch_loss.item(), 'validation_accuracy': epoch_acc.item()} def epoch_end(self, epoch, result): print(f"Epoch [{epoch}], val_loss: {result['validation_loss']}, val_acc: {result['validation_acc']}") model = mnistmodel() def fit_mnist(epochs, lr, model, training_loader, validation_loader, optimizer_function=torch.optim.SGD): optimizer = optimizer_function(model.parameters(), lr) history = [] for epoch in range(epochs): for batch in training_loader: loss = model.training_step(batch) loss.backward() optimizer.step() optimizer.zero_grad() result = evaluate(model, validation_loader) model.epoch_end(epoch, result) history.append(result) return history history1 = fit_mnist(5, 0.001, model, training_loader, validation_loader) I get the following error - --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-162-48e4fe0cc2d9> in <module>() ----> 1 history1 = fit_mnist(5, 0.001, model, training_loader, validation_loader) 6 frames /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py in linear(input, weight, bias) 1751 if has_torch_function_variadic(input, weight): 1752 return handle_torch_function(linear, (input, weight), input, weight, bias=bias) -> 1753 return torch._C._nn.linear(input, weight, bias) 1754 1755 RuntimeError: mat1 and mat2 shapes cannot be multiplied (3584x28 and 784x10) I'm new to pytorch but as far as I understand the shapes seem to be fine, what is going wrong here? I've checked manually and the dimensions seem to be fine. I even tried multiple things removing adding reshape commands but this error persists
I've found the mistake I need to reassign the reshape which I missed and spent the rest of the time debugging.
https://stackoverflow.com/questions/67695980/
ValueError: Expected more than 1 value per channel when training in pytorch 1.8
The input tensor size is [1, 512] and I feed it in a GroupNorm layer. The layer is self.fc_bn1 = nn.GroupNorm(512 // reduction, 512 // reduction) and the input is x = self.fc_bn1(x) The error is visible in this image: That will be worked when I run it in pytorch 1.1, but now I got a machine with pytorch 1.8 and it doesn't work. Since GPUs in this machine cannot use pytorch 1.1, I want to know how to solve this. I already set model.eval(), so I guess it's not this reason.
This code does work in pytorch1.1. But I think this is a bug, because the output after GroupNorm is all 0, which is consistent with the mathematical formula. In subsequent versions, this bug has been fixed, so an error is reported.
https://stackoverflow.com/questions/67697702/
pytorch cyclegann gives a Missing key error when testing
I have trained a model using the pix2pix pytorch implementation and would like to test it. However when I test it I get the error model [CycleGANModel] was created loading the model from ./checkpoints/cycbw50/latest_net_G_A.pth Traceback (most recent call last): File "test.py", line 47, in <module> model.setup(opt) # regular setup: load and print networks; create schedulers File "/media/bitlockermount/SmartImageToDigitalTwin/SmartImageToDigitalTwin/bin/python/cyclegann/pytorch-CycleGAN-and-pix2pix/models/base_model.py", line 88, in setup self.load_networks(load_suffix) File "/media/bitlockermount/SmartImageToDigitalTwin/SmartImageToDigitalTwin/bin/python/cyclegann/pytorch-CycleGAN-and-pix2pix/models/base_model.py", line 199, in load_networks net.load_state_dict(state_dict) File "/home/bst/.local/lib/python3.8/site-packages/torch/nn/modules/module.py", line 846, in load_state_dict raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format( RuntimeError: Error(s) in loading state_dict for ResnetGenerator: Missing key(s) in state_dict: "model.1.bias", "model.4.bias", "model.7.bias", "model.10.conv_block.1.bias", "model.10.conv_block.5.bias", "model.11.conv_block.1.bias", "model.11.conv_block.5.bias", "model.12.conv_block.1.bias", "model.12.conv_block.5.bias", "model.13.conv_block.1.bias", "model.13.conv_block.5.bias", "model.14.conv_block.1.bias", "model.14.conv_block.5.bias", "model.15.conv_block.1.bias", "model.15.conv_block.5.bias", "model.16.conv_block.1.bias", "model.16.conv_block.5.bias", "model.17.conv_block.1.bias", "model.17.conv_block.5.bias", "model.18.conv_block.1.bias", "model.18.conv_block.5.bias", "model.19.bias", "model.22.bias". Unexpected key(s) in state_dict: "model.2.weight", "model.2.bias", "model.5.weight", "model.5.bias", "model.8.weight", "model.8.bias", "model.10.conv_block.2.weight", "model.10.conv_block.2.bias", "model.10.conv_block.6.weight", "model.10.conv_block.6.bias", "model.11.conv_block.2.weight", "model.11.conv_block.2.bias", "model.11.conv_block.6.weight", "model.11.conv_block.6.bias", "model.12.conv_block.2.weight", "model.12.conv_block.2.bias", "model.12.conv_block.6.weight", "model.12.conv_block.6.bias", "model.13.conv_block.2.weight", "model.13.conv_block.2.bias", "model.13.conv_block.6.weight", "model.13.conv_block.6.bias", "model.14.conv_block.2.weight", "model.14.conv_block.2.bias", "model.14.conv_block.6.weight", "model.14.conv_block.6.bias", "model.15.conv_block.2.weight", "model.15.conv_block.2.bias", "model.15.conv_block.6.weight", "model.15.conv_block.6.bias", "model.16.conv_block.2.weight", "model.16.conv_block.2.bias", "model.16.conv_block.6.weight", "model.16.conv_block.6.bias", "model.17.conv_block.2.weight", "model.17.conv_block.2.bias", "model.17.conv_block.6.weight", "model.17.conv_block.6.bias", "model.18.conv_block.2.weight", "model.18.conv_block.2.bias", "model.18.conv_block.6.weight", "model.18.conv_block.6.bias", "model.20.weight", "model.20.bias", "model.23.weight", "model.23.bias". The opt file for the training: ----------------- Options --------------- batch_size: 1 beta1: 0.5 checkpoints_dir: ./checkpoints continue_train: False crop_size: 256 dataroot: ./datasets/datasets/boundedwalls_50_0.1/ [default: None] dataset_mode: aligned [default: unaligned] direction: AtoB display_env: main display_freq: 400 display_id: 1 display_ncols: 4 display_port: 8097 display_server: http://localhost display_winsize: 256 epoch: latest epoch_count: 1 gan_mode: lsgan gpu_ids: 0 init_gain: 0.02 init_type: normal input_nc: 3 isTrain: True [default: None] lambda_A: 10.0 lambda_B: 10.0 lambda_identity: 0.5 load_iter: 0 [default: 0] load_size: 286 lr: 0.0002 lr_decay_iters: 50 lr_policy: linear max_dataset_size: inf model: cycle_gan n_epochs: 100 n_epochs_decay: 100 n_layers_D: 3 name: cycbw50 [default: experiment_name] ndf: 64 netD: basic netG: resnet_9blocks ngf: 64 no_dropout: True no_flip: False no_html: False norm: batch [default: instance] num_threads: 4 output_nc: 3 phase: train pool_size: 50 preprocess: resize_and_crop print_freq: 100 save_by_iter: False save_epoch_freq: 5 save_latest_freq: 5000 serial_batches: False suffix: update_html_freq: 1000 verbose: False ----------------- End ------------------- And when testing it I used the following testing settings python3 test.py --dataroot ./datasets/datasets/boundedwalls_50_0.1 --name cycbw50 --model pix2pix --netG resnet_9blocks --direction BtoA --dataset_mode aligned --norm batch --load_size 286 ----------------- Options --------------- aspect_ratio: 1.0 batch_size: 1 checkpoints_dir: ./checkpoints crop_size: 256 dataroot: ./datasets/datasets/boundedwalls_50_0.1/ [default: None] dataset_mode: unaligned direction: AtoB display_winsize: 256 epoch: latest eval: False gpu_ids: 0 init_gain: 0.02 init_type: normal input_nc: 3 isTrain: False [default: None] load_iter: 0 [default: 0] load_size: 256 max_dataset_size: inf model: cycle_gan [default: test] n_layers_D: 3 name: cycbw50 [default: experiment_name] ndf: 64 netD: basic netG: resnet_9blocks ngf: 64 no_dropout: True no_flip: False norm: instance num_test: 50 num_threads: 4 output_nc: 3 phase: test preprocess: resize_and_crop results_dir: ./results/ serial_batches: False suffix: verbose: False ----------------- End ------------------- Does anybody see what I'm doing wrong here? I would like to run this network such that I get results for individual images, so far the test function seems the most promising but it just crashes on this neural network.
I think the problem here is some layer the bias=None but in testing the model required this, you should check the code for details. After I check your config in train and test, the norm is different. For the code in GitHub, the norm difference may set the bias term is True or False. if type(norm_layer) == functools.partial: use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d model = [nn.ReflectionPad2d(3), nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias), norm_layer(ngf), nn.ReLU(True)] You can check it here.
https://stackoverflow.com/questions/67701029/
XLM/BERT sequence outputs to pooled output with weighted average pooling
Let's say I have a tokenized sentence of length 10, and I pass it to a BERT model. bert_out = bert(**bert_inp) hidden_states = bert_out[0] hidden_states.shape >>>torch.Size([1, 10, 768]) This returns me a tensor of shape: [batch_size, seq_length, d_model] where each word in sequence is encoded as a 768-dimentional vector In TensorFlow BERT also returns a so called pooled output which corresponds to a vector representation of a whole sentence. I want to obtain it by taking a weighted average of sequence vectors and the way I do it is: hidden_states.view(-1, 10).shape >>> torch.Size([768, 10]) pooled = nn.Linear(10, 1)(hidden_states.view(-1, 10)) pooled.shape >>> torch.Size([768, 1]) Is it the right way to proceed, or should I just flatten the whole thing and then apply linear? Any other ways to obtain a good sentence representation?
There are two simple ways to get a sentence representation: Get the vector for the CLS token. Get the pooler_output Assuming the input is [batch_size, seq_length, d_model], where batch_size is the number of sentences, then to get the CLS token for every sentence: bert_out = bert(**bert_inp) hidden_states = bert_out['last_hidden_state'] cls_tokens = hidden_states[:, 0, :] # 0 for the CLS token for every sentence. You will have a tensor with shape (batch_size, d_model). To get the pooler_output: bert_out = bert(**bert_inp) pooler_output = bert_out['pooler_output'] Again you get a tensor with shape (batch_size, d_model).
https://stackoverflow.com/questions/67703260/
AttributeError: 'Model' object has no attribute 'parameters'
I am using a modified Resnet18, with my own pooling function at the end of the Resnet. Here is my code: resnet = resnet18().cuda() #a modified resnet class Model(): def __init__(self, model, pool): self.model = model self.pool= pool #my own pool class which has trainable layers def forward(self, sample): output = self.model(sample) output = self.pool(output) output = F.normalize(output, p=2, dim=1) return output Now, obviously I need to train not only the resnet part, but also the pool part. But, when I check: model = Model(model=resnet, pool= pool) print(list(model.parameters())) It gives: AttributeError: 'Model' object has no attribute 'parameters' Can anyone help?
You need you Model to inherit torch.nn.Module: class Model(torch.nn.Module): def __init__(self, model, pool): super(Model, self).__init__() ...
https://stackoverflow.com/questions/67706793/
In Pytorch how to slice tensor across multiple dims with BoolTensor masks?
I want to use BoolTensor indices to slice a multidimensional tensor in Pytorch. I expect for the indexed tensor, the parts where the indices are true are kept, while the parts where the indices are false are sliced out. My code is like import torch a = torch.zeros((5, 50, 5, 50)) tr_indices = torch.zeros((50), dtype=torch.bool) tr_indices[1:50:2] = 1 val_indices = ~tr_indices print(a[:, tr_indices].shape) print(a[:, tr_indices, :, val_indices].shape) I expect a[:, tr_indices, :, val_indices] to be of shape [5, 25, 5, 25], however it returns [25, 5, 5]. The result is torch.Size([5, 25, 5, 50]) torch.Size([25, 5, 5]) I'm very confused. Can anyone explain why?
PyTorch inherits its advanced indexing behaviour from Numpy. Slicing twice like so should achieve your desired output: a[:, tr_indices][..., val_indices]
https://stackoverflow.com/questions/67708191/
Vectorize for-loop - need to average slices of varying size
I am trying to average subword embeddings to form a word-level representation. Each word has a corresponding start and end index, indicating which subwords make up that word. sequence_output is a tensor of B * 3 * 2, where 3 is the max sequence length, and 2 is the number of features. all_token_mapping is a tensor of B * 3 * 2, which contains a start and end index. initial_reps is a tensor of num_nodes * 2, num_nodes is the sum of all the number of words (not subwords) in the different samples. sequence_output = torch.arange(2*3*2).float().reshape(2, 3, 2) tensor([[[ 0., 1.], [ 2., 3.], [ 4., 5.]], [[ 6., 7.], [ 8., 9.], [10., 11.]]]) all_token_mapping = torch.tensor([[[0,0],[1,2],[-1,-1]], [[0,2],[-1,-1],[-1,-1]]]) tensor([[[ 0, 0], [ 1, 2], [-1, -1]], [[ 0, 2], [-1, -1], [-1, -1]]]) num_nodes = 0 for sample in all_token_mapping: for mapping in sample: if mapping[0] != -1: num_nodes += 1 3 initial_reps = torch.empty((num_nodes, 2), dtype=torch.float32) current_idx = 0 for i, feature_tokens_mapping in enumerate(all_token_mapping): for j, token_mapping in enumerate(feature_tokens_mapping): if token_mapping[0] == -1: # reached the end for this particular sequence break initial_reps[current_idx] = torch.mean(sequence_output[i][token_mapping[0]:token_mapping[-1] + 1], 0, keepdim=True) current_idx += 1 initial_reps tensor([[0., 1.], [3., 4.], [8., 9.]]) In the example above, initial_reps[0] will be the mean of sequence_output[0][0:1], initial_reps[1] will be the mean of sequence_output[0][1:3], and initial_reps[2] will be the mean of sequence_output[1][0:3]. My current code will create an empty tensor of length num_nodes, and a for loop will calculate the values at each index, by checking token_mapping[0] and token_mapping[1] for the correct slice of sequence_output to average. Is there a way to vectorize this code? In addition, I have a list that holds the number of words for each sample. i.e. the sum of all the elements in the list == num_nodes
I figured out a way with the help of someone over at https://discuss.pytorch.org/t/vectorize-for-loop-need-to-average-slices-of-varying-size/122618/2 initial_reps_list = [] for i, sample_output in enumerate(sequence_output): token_mapping = all_token_mapping[i] token_mapping = token_mapping[token_mapping != -1] non_padded_outputs = sample_output[:num_bert_tokens[i]] initial_reps_list.append(torch_scatter.segment_coo(non_padded_outputs, token_mapping, reduce="mean")) initial_reps = torch.cat(initial_reps_list) token_mapping is a list of indices in ascending order up to the max sequence length, padded with -1. I loop through the batch, for each sample, I get the token mapping, and only keep the non-negative indices. num_bert_tokens is a list that holds, for each sample, the number of tokens (no padding). I get the non-padded outputs, use segment_coo to reduce them according to the token_mapping, and append them all to a list. After the loop, I concatenate all the tensors in the list together. The method segment_coo reduces all values from the src tensor into out at the indices specified in the index tensor along the last dimension of index. More details can be found at: https://pytorch-scatter.readthedocs.io/en/latest/functions/segment_coo.html Runs much faster now!
https://stackoverflow.com/questions/67708447/
Rearranging PyTorch tensor in a windowed manner
So I have a tensor A = torch.tensor([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]) and I was hoping to rearrange it in sliding windows, that is, f(A) = torch.tensor([[1,2,5,6],[3,4,7,8],[9,10,13,14],[11,12,15,16]]) by viewing every tensor in A as a 2-by-2 small window, and then arranging the "window"s in a 2-by-2 matrix. This operation is similar to ArrayFlatten of Mathematica, but I couldn' find a way to do it in PyTorch. Any help is welcome.
I can't think of a neat way to do this off the top of my head, but you can achieve it with a few choice slices and concatenations: A_ = A.reshape(4,2,2) torch.cat([torch.cat([*A_[:2]],1), torch.cat([*A_[2:]],1)],0) Alternative approaches: A.unfold(1,2,2).unfold(0,2,2).reshape(*A.shape).index_select(1, torch.LongTensor([0,2,1,3])) torch.cat([*A_],1).reshape(*A.shape).index_select(0, torch.LongTensor([0,2,1,3]))
https://stackoverflow.com/questions/67708606/
How to write a fast PyTorch training loop?
I've encountered a bad regression in performance after porting a machine learning algorithm from Keras to PyTorch. The following construction in Keras: model.compile(loss="binary_crossentropy", optimizer=SGD(learning_rate=0.01)) . . . model.fit(states, actions) is ~15x faster than the following verbose version in Pytorch: def train_network(model, optimizer, train_loader, num_epochs=16, pbar_update_interval=200, print_logs=True): criterion = nn.BCELoss() model.train() for i in range(num_epochs): for k, batch_data in enumerate(train_loader): optimizer.zero_grad() batch_x = batch_data[:, :-1] batch_y = batch_data[:, -1] y_pred = model(batch_x) loss = criterion(y_pred, batch_y.unsqueeze(1)) loss.backward() optimizer.step() optimizer = torch.optim.SGD(model.parameters(), lr=LEARNING_RATE) train_data = torch.from_numpy(np.column_stack((states, actions))) train_data = train_data.to(torch.float) train_loader = torch.utils.data.DataLoader(train_data, shuffle=True, batch_size=32) train_network(model, optimizer, train_loader) Am I writing the PyTorch code wrong? The variable model in the PyTorch code is an nn.Module, and states and actions are NumPy arrays. The code is running on 4 CPU cores.
It seems that keras.model.fit has default parameter value epochs=1. So this exactly explains the performance factor.
https://stackoverflow.com/questions/67711470/
How to extract tensors to numpy arrays or lists from a larger pytorch tensor
I have a list of pytorch tensors as shown below: data = [[tensor([0, 0, 0]), tensor([1, 2, 3])], [tensor([0, 0, 0]), tensor([4, 5, 6])]] Now this is just a sample data, the actual one is quite large but the structure is similar. Question: I want to extract the tensor([1, 2, 3]), tensor([4, 5, 6]) i.e., the index 1 tensors from data to either a numpy array or a list in flattened form. Expected Output: out = array([1, 2, 3, 4, 5, 6]) OR out = [1, 2, 3, 4, 5, 6] I have tried several ways one including map function like: map(lambda x: x[1].numpy(), data) This gives: [array([1, 2, 3]), array([4, 5, 6])] And I'm unable to get the desired result with any other method I'm using.
OK, you can just do this. out = np.concatenate(list(map(lambda x: x[1].numpy(), data)))
https://stackoverflow.com/questions/67711752/
Creating a custom BCE with logit loss function
I want to create a custom loss function for multi-label classification. The idea is to weigh the positive and negative labels differently. For this, I am making use of this custom code implementation. class WeightedBCEWithLogitLoss(nn.Module): def __init__(self, pos_weight, neg_weight): super(WeightedBCEWithLogitLoss, self).__init__() self.register_buffer('neg_weight', neg_weight) self.register_buffer('pos_weight', pos_weight) def forward(self, input, target): assert input.shape == target.shape, "The loss function received invalid input shapes" y_hat = torch.sigmoid(input + 1e-8) loss = -1.0 * (self.pos_weight * target * torch.log(y_hat + 1e-6) + self.neg_weight * (1 - target) * torch.log(1 - y_hat + 1e-6)) # Account for 0 times inf which leads to nan loss[torch.isnan(loss)] = 0 # We average across each of the extra attribute dimensions to generalize it loss = loss.mean(dim=1) # We use mean reduction for our task return loss.mean() I started getting nan values which I realized happened because of 0 times inf multiplication. I handled it as shown in the figure. Next, I again saw getting inf as the error value and corrected it by adding 1e-6 to the log (I tried with 1e-8 but that still gave me inf error value). It would be great if someone can take a look and suggest further improvements and rectify any more bugs visible here.
You don't have to implement it. It is already done. The BCEWithLogits accepts parameter pos_weight which, according to documentation, is used as pos_weight ( Tensor , optional ) – a weight of positive examples. Must be a vector with length equal to the number of classes
https://stackoverflow.com/questions/67713632/
Execution block when calling DataLoader with self-defined functions on the dataset class
I am running my code in Colab. I use Dataloader to load my dataset as batches for training and validation, and tqdm to visualize the training process. But every time I execute my code, I get stuck at a random point (in epoch 0, meaning the dataset has never been traversed), saying that the program is still running but the progress bar is frozen. An interesting phenomenon lies in the self-defined transformation functions of the inputs since once I drop these transformations, everything went smoothly. The functions are: class Sharpen(object): def __init__(self, p=0.5): self.p = p def __call__(self, sample): if random.uniform(0.0, 1.0) < self.p: return sample kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32) for i in range(len(sample['img_list'])): sample['img_list'][i] = cv2.filter2D(sample['img_list'][i], -1, kernel=kernel) return sample class Rotation(object): def __init__(self, angle=5, fill_value=0, p=0.5): self.angle = angle self.fill_value = fill_value self.p = p def __call__(self, sample): if random.uniform(0.0, 1.0) < self.p: return sample for i in range(len(sample['img_list'])): ang_rot = np.random.uniform(self.angle) - self.angle / 2 h, w, _ = sample["img_list"][i].shape if h*w == 0: continue transform = cv2.getRotationMatrix2D((w / 2, h / 2), ang_rot, 1) sample["img_list"][i] = cv2.warpAffine(sample["img_list"][i], transform, (w, h), borderValue=self.fill_value) return sample class Translation(object): def __init__(self, fill_value=0, p=0.5): self.fill_value = fill_value self.p = p self.SIGMA = 1e-3 def __call__(self, sample): rand_num = random.uniform(0.0, 1.0) if rand_num <= self.p: return sample for i in range(len(sample['img_list'])): h, w, _ = sample["img_list"][i].shape if h*w == 0: continue trans_range = (w / 10, h / 10) tr_x = trans_range[0] * rand_num - trans_range[0] / 2 + self.SIGMA tr_y = trans_range[1] * rand_num - trans_range[1] / 2 + self.SIGMA transform = np.float32([[1, 0, tr_x], [0, 1, tr_y]]) sample["img_list"][i] = cv2.warpAffine(sample["img_list"][i], transform, (w, h), borderValue=self.fill_value) return sample class Normalization(object): def __init__(self, mean=(0,0,0), std=(255,255,255)): self.mean = mean self.std = std def __call__(self, sample): # norm_func = transforms.Normalize(self.mean, self.std) for i in range(len(sample['img_list'])): for j in range(3): # for colored image sample['img_list'][i][:,:,j] = np.array(list(map(lambda x: (x-self.mean[j])/self.std[j], sample['img_list'][i][:,:,j])), dtype=np.float32) # sample['img_list'][i] = norm_func(torch.Tensor(sample['img_list'][i])) return sample The parameter sample is a dictionary, and the key: img_list represents a list of images (numpy.ndarray) processed by cv2.imread. The shape of each image is (h, w, c) and the size is not equal across images. I created a Dataset Class and proceeded input images with Compose([Sharpen(), Rotation(), Translation(), Normalization()]). Now I don't know what's wrong with the transformation code. Any kind of help is appreciated!
Problem solved. It is because of the data. If the input image is an empty one, the loading procedure will get stuck.
https://stackoverflow.com/questions/67716029/
Downloading Big Packages using conda in batches
I am curious whether I can download big packages in batches using conda (like in web browsers where we can resume interrupted downloads). I wanted to update my pytorch package but the size is too big for my limited mobile data. The following packages will be downloaded: package | build ---------------------------|----------------- libuv-1.40.0 | he774522_0 255 KB pytorch-1.8.1 |py3.7_cuda10.1_cudnn7_0 836.4 MB pytorch torchvision-0.9.1 | py37_cu101 7.3 MB pytorch ------------------------------------------------------------ Total: 843.9 MB The following NEW packages will be INSTALLED: libuv pkgs/main/win-64::libuv-1.40.0-he774522_0 The following packages will be UPDATED: pytorch 1.4.0-py3.7_cuda101_cudnn7_0 --> 1.8.1-py3.7_cuda10.1_cudnn7_0 torchvision 0.5.0-py37_cu101 --> 0.9.1-py37_cu101
No this is not possible in conda. Completely downloaded files will not be redownloaded, but files which are only partially downloaded before interruption will need to be redownloaded: https://github.com/conda/conda/issues/800
https://stackoverflow.com/questions/67716945/
How to check the output gradient by each layer in pytorch in my code?
I am working on the pytorch to learn. And There is a question how to check the output gradient by each layer in my code. My code is below #import the nescessary libs import numpy as np import torch import time # Loading the Fashion-MNIST dataset from torchvision import datasets, transforms # Get GPU Device device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)) ]) # Download and load the training data trainset = datasets.FashionMNIST('MNIST_data/', download = True, train = True, transform = transform) testset = datasets.FashionMNIST('MNIST_data/', download = True, train = False, transform = transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size = 32, shuffle = True, num_workers=4) testloader = torch.utils.data.DataLoader(testset, batch_size = 32, shuffle = True, num_workers=4) # Examine a sample dataiter = iter(trainloader) images, labels = dataiter.next() # Define the network architecture from torch import nn, optim import torch.nn.functional as F model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10), nn.LogSoftmax(dim = 1) ) model.to(device) # Define the loss criterion = nn.CrossEntropyLoss() # Define the optimizer optimizer = optim.Adam(model.parameters(), lr = 0.001) # Define the epochs epochs = 5 train_losses, test_losses = [], [] # start = time.time() for e in range(epochs): running_loss = 0 for images, labels in trainloader: # Flatten Fashion-MNIST images into a 784 long vector images = images.to(device) labels = labels.to(device) images = images.view(images.shape[0], -1) # Training pass optimizer.zero_grad() output = model.forward(images) loss = criterion(output, labels) loss.backward() # print(loss.grad) optimizer.step() running_loss += loss.item() else: print(model[0].grad) If I print model[0].grad after back-propagation, Is it going to be the output gradient by each layer for every epoches? Or, If I want to know the output gradient by each layer, where and what am I should print? Thank you!! Thank you for reading
Well, this is a good question if you need to know the inner computation within your model. Let me explain to you! So firstly when you print the model variable you'll get this output: Sequential( (0): Linear(in_features=784, out_features=128, bias=True) (1): ReLU() (2): Linear(in_features=128, out_features=10, bias=True) (3): LogSoftmax(dim=1) ) And if you choose model[0], that means you have selected the first layer of the model. that is Linear(in_features=784, out_features=128, bias=True). If you will look at the documentation of torch.nn.Linear here, you will find that there are two variables to this class that you can access. One is Linear.weight and the other is Linear.bias which will give you the weights and biases of that corresponding layer respectively. Remember you cannot use model.weight to look at the weights of the model as your linear layers are kept inside a container called nn.Sequential which doesn't has a weight attribute. So coming back to looking at weights and biases, you can access them per layer. So model[0].weight and model[0].bias are the weights and biases of the first layer. And similarly to access the gradients of the first layer model[0].weight.grad and model[0].bias.grad will be the gradients.
https://stackoverflow.com/questions/67722328/
tqdm notebook - 2 inner bars
I'm trying to print training progress bar using tqdm. I'd like to track the progress of the epochs, and for each epoch i have 2 progress bars: the train_loader minibatches, and validation_loader minibatches. The code is something like that: for epoch in tqdm(range(epochs_num)): for inputs, labels in tqdm(train_loader, "Train progress", leave=False): # train... with torch.no_grad(): for inputs, labels in tqdm(validation_loader, "Validation progress", leave=False): # calc validation loss Using the leave argument, the progress bars deleted every epoch, but I'd like to delete them togather, right after the validation process ends. There's any way to do it? Thanks
You can reuse your progress bars and do the updates manually like this: epochs = tqdm(range(epochs_num), desc="Epochs") training_progress = tqdm(total=training_batch_size, desc="Training progress") validation_progress = tqdm(total=validation_batch_size, desc="Validation progress") for epoch in epochs: training_progress.reset() validation_progress.reset() for inputs, labels in train_loader: # train... training_progress.update() with torch.no_grad(): for inputs, labels in validation_loader: # calc validation loss validation_progress.update() If the batch sizes are not always the same, you can calculate them on the fly and call reset(total=new_size).
https://stackoverflow.com/questions/67723652/
How to access pytorch embeddings lookup table as a tensor
I want to show my embeddings with the tensorboard projector. I would like to access the embeddings matrix (lookup table) of one of my layers so I can write it to the logs. I instantiate my layer as this: self.embeddings_user = torch.nn.Embedding(30,300) And I'm looking for the tensor with shape (30,300) of 30 users with embedding on 300 to dimensions to replace it with the vectors variable in this sample code: import numpy as np import tensorflow as tf import tensorboard as tb tf.io.gfile = tb.compat.tensorflow_stub.io.gfile from torch.utils.tensorboard import SummaryWriter vectors = np.array([[0,0,1], [0,1,0], [1,0,0], [1,1,1]]) metadata = ['001', '010', '100', '111'] # labels writer = SummaryWriter() writer.add_embedding(vectors, metadata) writer.close()
Embeddings layers have weight attributes corresponding to the lookup table. You can access it as follows. vectors = self.embeddings_user.weight So now you can visualize it with tensorboard. import numpy as np import tensorflow as tf import tensorboard as tb tf.io.gfile = tb.compat.tensorflow_stub.io.gfile from torch.utils.tensorboard import SummaryWriter vectors = self.embeddings_user.weight metadata = ['001', '010', '100', '111', ...] # labels writer = SummaryWriter() writer.add_embedding(vectors, metadata) writer.close()
https://stackoverflow.com/questions/67725175/
Pytorch BCELoss function different outputs for same inputs
I am trying to calculate cross entropy loss using pytorch's BCELoss Function for a binary classification problem. While tinkering I found this weird behaviour. from torch import nn sigmoid = nn.Sigmoid() loss = nn.BCELoss(reduction="sum") target = torch.tensor([0., 1.]) input1 = torch.tensor([1., 1.], requires_grad=True) input2 = sigmoid(torch.tensor([10., 10.], requires_grad=True)) print(input2) #tensor([1.0000, 1.0000], grad_fn=<SigmoidBackward>) print(loss(input1, target)) #tensor(100., grad_fn=<BinaryCrossEntropyBackward>) print(loss(input2, target)) #tensor(9.9996, grad_fn=<BinaryCrossEntropyBackward>) Since both input1 and input2 have same value, shouldn't it return the same loss value instead of 100 and 9.9996. The correct loss value should be 100 since I am multiplying log(0) ~-infinity which is capped at -100 in pytorch. https://pytorch.org/docs/stable/generated/torch.nn.BCELoss.html What is going on here and where am I going wrong?
sigmoid(10) is not exactly equal to 1: >>> 1 / (1 + torch.exp(-torch.tensor(10.))).item() 0.9999545833234493 In your case: >>> sigmoid(torch.tensor([10., 10.], requires_grad=True)).tolist() [0.9999545812606812, 0.9999545812606812] Thus input1 is not the same as input2: [1.0, 1.0] vs [0.9999545812606812, 0.9999545812606812], Let's compute BCE manually: def bce(x, y): return - (y * torch.log(x) + (1 - y) * torch.log(1 - x)).item() # input1 x1 = torch.tensor(1.) x2 = torch.tensor(1.) y1 = torch.tensor(0.) y2 = torch.tensor(1.) print("input1:", sum([bce(x1, y1), bce(x2, y2)])) # input2 x1 = torch.tensor(0.9999545812606812) x2 = torch.tensor(0.9999545812606812) y1 = torch.tensor(0.) y2 = torch.tensor(1.) print("input2:", sum([bce(x1, y1), bce(x2, y2)])) input1: nan input2: 9.999631525119185 For input1 we get nan, but according to docs: Our solution is that BCELoss clamps its log function outputs to be greater than or equal to -100. This way, we can always have a finite loss value and a linear backward method. That's why we have 100 in a final pytorch's BCE output.
https://stackoverflow.com/questions/67725538/
Pytorch data.random_split() doesn't split randomly
I am trying to split my custom dataset randomly into test and train. The code runs and outputs the test and train folders successfully, but I need the test and train sets to be different each time I ran the code. Isn't this what randomly splitting supposed to mean/do? p.s. just for clarification, the data is images, so I expect to see different images chosen for test and train sets each time I execute the code. #Set the random seeds for reproducibility SEED = 1234 random.seed(SEED) np.random.seed(SEED) torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) torch.backends.cudnn.deterministic = True TRAIN_RATIO = 0.9 data_dir = 'Data Set 1' images_dir = os.path.join(data_dir, 'images') train_dir = os.path.join(data_dir, 'train') test_dir = os.path.join(data_dir, 'test') if os.path.exists(train_dir): shutil.rmtree(train_dir) if os.path.exists(test_dir): shutil.rmtree(test_dir) os.makedirs(train_dir) os.makedirs(test_dir) classes = os.listdir(images_dir) for c in classes: class_dir = os.path.join(images_dir, c) images = os.listdir(class_dir) n_train = int(len(images) * TRAIN_RATIO) n_test = len(images) - n_train train_images, test_images = data.random_split(images, [n_train, n_test]) os.makedirs(os.path.join(train_dir, c), exist_ok=True) os.makedirs(os.path.join(test_dir, c), exist_ok=True) for image in train_images: image_src = os.path.join(class_dir, image) image_dst = os.path.join(train_dir, c, image) shutil.copyfile(image_src, image_dst) for image in test_images: image_src = os.path.join(class_dir, image) image_dst = os.path.join(test_dir, c, image) shutil.copyfile(image_src, image_dst)
It's not random because you set the random seed. Think of the seed as a random number - if you define the seed, the number is not random anymore. If you don't define it, you will get a random seed every time. Just comment out these lines :) SEED = 1234 random.seed(SEED) np.random.seed(SEED) torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) Alternatively, just do this: SEED = random.randint(1, 1000) to get a random number between 1 and 1000. This will let you print the value of SEED, if you need that for some reason. You can see how the seed function works here: https://www.w3schools.com/python/ref_random_seed.asp
https://stackoverflow.com/questions/67728748/
How to make prediction on pytorch emotion detection model
I made a CNN model for emotion recognition on 5 emotions. I wanted to test it on an single image to get the individual class predictions for each emotion. Evaluating the model works, but I can't seem to find how to make a prediction with a single image. How can I do that? The Model def conv_block(in_channels, out_channels, pool=False): layers = [nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1), nn.BatchNorm2d(out_channels), nn.ELU(inplace=True)] if pool: layers.append(nn.MaxPool2d(2)) return nn.Sequential(*layers) class ResNet(ImageClassificationBase): def __init__(self, in_channels, num_classes): super().__init__() self.conv1 = conv_block(in_channels, 128) self.conv2 = conv_block(128, 128, pool=True) self.res1 = nn.Sequential(conv_block(128, 128), conv_block(128, 128)) self.drop1 = nn.Dropout(0.5) self.conv3 = conv_block(128, 256) self.conv4 = conv_block(256, 256, pool=True) self.res2 = nn.Sequential(conv_block(256, 256), conv_block(256, 256)) self.drop2 = nn.Dropout(0.5) self.conv5 = conv_block(256, 512) self.conv6 = conv_block(512, 512, pool=True) self.res3 = nn.Sequential(conv_block(512, 512), conv_block(512, 512)) self.drop3 = nn.Dropout(0.5) self.classifier = nn.Sequential(nn.MaxPool2d(6), nn.Flatten(), nn.Linear(512, num_classes)) def forward(self, xb): out = self.conv1(xb) out = self.conv2(out) out = self.res1(out) + out out = self.drop1(out) out = self.conv3(out) out = self.conv4(out) out = self.res2(out) + out out = self.drop2(out) out = self.conv5(out) out = self.conv6(out) out = self.res3(out) + out out = self.drop3(out) out = self.classifier(out) return out The fit_one_cycle function is called to train the model @torch.no_grad() def evaluate(model, val_loader): model.eval() outputs = [model.validation_step(batch) for batch in val_loader] return model.validation_epoch_end(outputs) def get_lr(optimizer): for param_group in optimizer.param_groups: return param_group['lr'] def fit_one_cycle(epochs, max_lr, model, train_loader, val_loader, weight_decay=0, grad_clip=None, opt_func=torch.optim.SGD): torch.cuda.empty_cache() history = [] # Set up custom optimizer with weight decay optimizer = opt_func(model.parameters(), max_lr, weight_decay=weight_decay) # Set up one-cycle learning rate scheduler sched = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr, epochs=epochs, steps_per_epoch=len(train_loader)) for epoch in range(epochs): # Training Phase model.train() train_losses = [] lrs = [] for batch in train_loader: loss = model.training_step(batch) train_losses.append(loss) loss.backward() # Gradient clipping if grad_clip: nn.utils.clip_grad_value_(model.parameters(), grad_clip) optimizer.step() optimizer.zero_grad() # Record & update learning rate lrs.append(get_lr(optimizer)) sched.step() # Validation phase result = evaluate(model, val_loader) result['train_loss'] = torch.stack(train_losses).mean().item() result['lrs'] = lrs model.epoch_end(epoch, result) history.append(result) return history This returns the accuracy and loss, i want to change this so it returns prediction percentages for each class. def accuracy(outputs, labels): _, preds = torch.max(outputs, dim=1) return torch.tensor(torch.sum(preds == labels).item() / len(preds)) class ImageClassificationBase(nn.Module): def training_step(self, batch): images, labels = batch out = self(images) loss = F.cross_entropy(out, labels) return loss def validation_step(self, batch): images, labels = batch out = self(images) loss = F.cross_entropy(out, labels) acc = accuracy(out, labels) return {'val_loss': loss, 'val_acc': acc} def validation_epoch_end(self, outputs): batch_losses = [x['val_loss'] for x in outputs] epoch_loss = torch.stack(batch_losses).mean() batch_accs = [x['val_acc'] for x in outputs] epoch_acc = torch.stack(batch_accs).mean() return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()} def epoch_end(self, epoch, result): print("Epoch [{}], last_lr: {:.5f}, train_loss: {:.4f}, val_loss: {:.4f}, val_acc: {:.4f}".format( epoch, result['lrs'][-1], result['train_loss'], result['val_loss'], result['val_acc']))
Evaluating the model works, but I can't seem to find how to make a prediction with a single image. How can I do that? Simply, if you have a single image make sure to: use additional 1 dimension at the beginning make sure to use CHW format instead of HWC (or specify that within pytorch, check out how to do that here) For example: my_model = CNN(...) random_image = torch.randn(1, 3, 100, 100) # 3 channels, 100x100 img BTW. Your accuracy could be written a little simpler like this: def accuracy(outputs, labels): preds = torch.argmax(outputs, dim=1) return torch.sum(preds == labels) / len(preds) Getting class probability Similar to argmax you can use softmax which transforms logits (unnormalized probability outputted by your network) into probabilities: def probability(outputs): return torch.nn.functional.softmax(outputs, dim=1)
https://stackoverflow.com/questions/67735651/
"RuntimeError: mat1 dim 1 must match mat2 dim 0" PyTorch
I've been trying to build a simple neural network with linear layers: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.lin1 = nn.Linear(64 * 1 * 28 * 28, 6) self.lin2 = nn.Linear(6, 4) self.out = nn.Linear(4, 10) def forward(self, x): print(x.shape) x = self.lin1(x) x = F.relu(x) x = self.lin2(x) x = F.relu(x) x = self.out(x) x = F.softmax(x) return x However I run into the error: mat1 dim 1 must match mat2 dim 0 for the line x = self.lin1(x) I tried flattening x before lin1 or changing the lin1 input size, but nothing worked. The output of the print statement is: torch.Size([64, 1, 28, 28])
Problem was solved by flattening (in a different way than i did before) the input. import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net,self).__init__() self.lin1 = nn.Linear(784,6) self.lin2 = nn.Linear(6,4) self.out = nn.Linear(4,10) def forward(self,x): x = torch.flatten(x,start_dim = 1) #This is new x = self.lin1(x) x = F.relu(x) x = self.lin2(x) x = F.relu(x) x = self.out(x) return x
https://stackoverflow.com/questions/67735718/
Huggingface Electra - Load model trained with google implementation error: 'utf-8' codec can't decode byte 0x80 in position 64: invalid start byte
I have trained an electra model from scratch using google implementation code. python run_pretraining.py --data-dir gc://bucket-electra/dataset/ --model-name greek_electra --hparams hparams.json with this json hyperparams: { "embedding_size": 768, "max_seq_length": 512, "train_batch_size": 128, "vocab_size": 100000, "model_size": "base", "num_train_steps": 1500000 } After having trained the model, I used the convert_electra_original_tf_checkpoint_to_pytorch.py script from transformers library to convert the checkpoint. python convert_electra_original_tf_checkpoint_to_pytorch.py --tf_checkpoint_path output/models/transformer/greek_electra --config_file resources/hparams.json --pytorch_dump_path output/models/transformer/discriminator --discriminator_or_generator "discriminator" Now I am trying to load the model: from transformers import ElectraForPreTraining model = ElectraForPreTraining.from_pretrained('discriminator') but I get the following error: Traceback (most recent call last): File "~/.local/lib/python3.9/site-packages/transformers/configuration_utils.py", line 427, in get_config_dict config_dict = cls._dict_from_json_file(resolved_config_file) File "~/.local/lib/python3.9/site-packages/transformers/configuration_utils.py", line 510, in _dict_from_json_file text = reader.read() File "/usr/lib/python3.9/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 64: invalid start byte Any ideas what's causing this & how to solve it?
It seems that @npit is right. The output of the convert_electra_original_tf_checkpoint_to_pytorch.py does not contain the configuration that I gave (hparams.json), therefore I created an ElectraConfig object -- with the same parameters -- and provided it to the from_pretrained function. That solved the issue.
https://stackoverflow.com/questions/67740498/
How can/should we weight classes in HuggingFace token classification (entity recognition)?
I'm training a token classification (AKA named entity recognition) model with the HuggingFace Transformers library, with a customized data loader. Like most NER datasets (I'd imagine?) there's a pretty significant class imbalance: A large majority of tokens are other - i.e. not an entity - and of course there's a little variation between the different entity classes themselves. As we might expect, my "accuracy" metrics are getting distorted quite a lot by this: It's no great achievement to get 80% token classification accuracy if 90% of your tokens are other... A trivial model could have done better! I can calculate some additional and more insightful evaluation metrics - but it got me wondering... Can/should we somehow incorporate these weights into the training loss? How would this be done using a typical *ForTokenClassification model e.g. BERTForTokenClassification?
This is actually a really interesting question, since it seems there is no intention (yet) to modify losses in the models yourself. Specifically for BertForTokenClassification, I found this code segment: loss_fct = CrossEntropyLoss() # ... loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) To actually change the loss computation and add other parameters, e.g., the weights you mention, you can go about either one of two ways: You can modify a copy of transformers locally, and install the library from there, which makes this only a small change in the code, but potentially quite a hassle to change parts during different experiments, or You return your logits (which is the case by default), and calculate your own loss outside of the actual forward pass of the huggingface model. In this case, you need to be aware of any potential propagation from the loss calculated within the forward call, but this should be within your power to change.
https://stackoverflow.com/questions/67743498/
set variable network layers based on parameters in pytorch
I want to make the following network definition to a parametric one. The number of continuous and discrete columns varies for different data. I first pass the whole input data, which in this case is 110 dimensional , from a linear with a relu activation. The output of each categorical field of my data varies based on a previous one-hot encoding data transformation. I need to define a nn.Linear(110, number of encodings) for each of them. class Generator(nn.Module): def __init__(self): super(Generator, self).__init__(110) self.lin1 = nn.Linear(110,110) self.lin_numerical = nn.Linear(110, 6) self.lin_cat_job = nn.Linear(110, 9) self.lin_cat_sex = nn.Linear(110, 2) self.lin_cat_incomeclass = nn.Linear(110, 7) def forward(self, x): x = torch.relu(self.lin1(x)) x_numerical = f.leaky_relu(self.lin_numerical(x)) x_cat1 = f.gumbel_softmax(self.lin_cat_job(x), tau=0.2) x_cat2 = f.gumbel_softmax(self.lin_cat_sex(x), tau=0.2) x_cat3 = f.gumbel_softmax(self.lin_cat_incomeclass(x), tau=0.2) x_final = torch.cat((x_numerical, x_cat1, x_cat2, x_cat3),1) return x_final I have managed to change the init part, using discrete_columns input which is an ordereddict that has the name and number of one-hot-encoding of each categorical field of my data as key and values, and continuous_columns which is only a list with the names of the continuous columns. But I have no idea how to edit the forward part: class Generator(nn.Module): def __init__(self, input_dim, continuous_columns, discrete_columns): super(Generator, self).__init__() self._input_dim = input_dim self._discrete_columns = discrete_columns self._num_continuous_columns = len(continuous_columns) self.lin1 = nn.Linear(self._input_dim, self._input_dim) self.lin_numerical = nn.Linear(self._input_dim, self._num_continuous_columns) for key, value in self._discrete_columns.items(): setattr(self, "lin_cat_{}".format(key), nn.Linear(self._input_dim, value)) def forward(self, x): x = torch.relu(self.lin1(x)) x_numerical = f.leaky_relu(self.lin_numerical(x)) #### This is the problematic part ##### return x
You don't need to use setattr and honestly should not since you'd need getattr, it brings more trouble than it solves if there's any other ways to do the job. Now this is what I'd do for this task self.lin_cat = nn.ModuleDict() for key, value in self._discrete_columns.items(): self.lin_cat[key] = nn.Linear(self._input_dim, value) # setattr(self, "lin_cat_{}".format(key), nn.Linear(self._input_dim, value)) def forward(self, x): x = torch.relu(self.lin1(x)) x_numerical = f.leaky_relu(self.lin_numerical(x)) x_cat = [] for key in self.lin_cat: x_cat.append(f.gumbel_softmax(self.lin_cat[key](x), tau=0.2)) x_final = torch.cat((x_numerical, *x_cat), 1) return x
https://stackoverflow.com/questions/67744231/
Setting a minimum learning rate on "Reduce On Plateau"
I'm currently using PyTorch's ReduceLROnPlateau learning rate scheduler using: learning_rate = 1e-3 optimizer = optim.Adam(model.params, lr = learning_rate) model.optimizer = optimizer scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(model.optimizer, factor=0.9, patience = 5000, verbose=True) My issue is that the loss will get really low within a few minutes, then jumps really high and start decreasing steadily. Hence, ReduceLROnPlateau will just continuously decrease the learning rate to a point that the model can't learn anything (because it takes the lowest loss into acount). Is there a way to set a minimum learning rate using this scheduler so that it won't go to almost 0? Say to set it at minimum of 1e8
Yes, from the documentation: min_lr (float or list) – A scalar or a list of scalars. A lower bound on the learning rate of all param groups or each group respectively. Default: 0. You can simply go for: scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( model.optimizer, factor=0.9, patience=5000, verbose=True, min_lr=1e-8, )
https://stackoverflow.com/questions/67746083/
torch.Tensor() new() received an invalid combination of arguments - got (list, dtype=torch.dtype)
I am facing a very weird error when I am trying to run the following simple line : a = torch.Tensor([0,0,0],dtype = torch.int64) TypeError: new() received an invalid combination of arguments - got (list, dtype=torch.dtype), but expected one of: * (*, torch.device device) didn't match because some of the keywords were incorrect: dtype * (torch.Storage storage) * (Tensor other) * (tuple of ints size, *, torch.device device) * (object data, *, torch.device device) whereas if we look at official documentation torch.tensor(data, dtype=None, device=None, requires_grad=False, pin_memory=False) → Tensor Parameters data (array_like) – Initial data for the tensor. Can be a list, tuple, NumPy ndarray, scalar, and other types. dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, infers data type from data. Why is the code snippet not working even though the official documentation supports it?
Capitalization matters -- in your top example, you have Tensor with uppercase T, but the documentation excerpt is talking about tensor with lowercase t.
https://stackoverflow.com/questions/67746193/
Can’t train a multilabel classifier on a small dataset
I have a dataset of 3 classes animals, landscapes, and buildings. It is only a 100 images per dataset and I am trying to train a classifier using ResNet34 + fastai but I'm running into several issues. The first one is that I don't think my model is training properly. When I use the lr_finder, my validation loss is na, unless this is expected: Then I run 10 epochs. It looks either like its learning well or its overfitting like hell. Then I unfreeze to find another learning rate and my validation loss is still na: And now when I train 10 epochs, the graph starts to oscillate so that tells me that it can't learn anymore. The accuracy looks good (unless its overfitting) so then I decide to use my validation set to see how my model is actually doing: Because I have 300 images, 240 are in the train folder and 60 are in the test folder. My test images are labelled because I want to run an accuracy score on it. This is the cell that I run: path = '/content/dataset/' data_test = ImageList.from_folder(path).split_by_folder(train='train', valid='test').label_from_re(file_parse).transform(size=512).databunch().normalize(imagenet_stats) learn = cnn_learner(data, models.resnet50, metrics=[accuracy, top_1],callback_fns=ShowGraph) learn.load('stage-2') And this is the error that I am met with: RuntimeError Traceback (most recent call last) <ipython-input-28-f1232eb8cf47> in <module>() 4 5 learn = cnn_learner(data, models.resnet50, metrics=[accuracy, top_1],callback_fns=ShowGraph) ----> 6 learn.load('stage-2') 1 frames /usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py in load_state_dict(self, state_dict, strict) 828 if len(error_msgs) > 0: 829 raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format( --> 830 self.__class__.__name__, "\n\t".join(error_msgs))) 831 return _IncompatibleKeys(missing_keys, unexpected_keys) 832 RuntimeError: Error(s) in loading state_dict for Sequential: Missing key(s) in state_dict: "0.4.0.conv3.weight", "0.4.0.bn3.weight", "0.4.0.bn3.bias", "0.4.0.bn3.running_mean", "0.4.0.bn3.running_var", "0.4.0.downsample.0.weight", "0.4.0.downsample.1.weight", "0.4.0.downsample.1.bias", "0.4.0.downsample.1.running_mean", "0.4.0.downsample.1.running_var", "0.4.1.conv3.weight", "0.4.1.bn3.weight", "0.4.1.bn3.bias", "0.4.1.bn3.running_mean", "0.4.1.bn3.running_var", "0.4.2.conv3.weight", "0.4.2.bn3.weight", "0.4.2.bn3.bias", "0.4.2.bn3.running_mean", "0.4.2.bn3.running_var", "0.5.0.conv3.weight", "0.5.0.bn3.weight", "0.5.0.bn3.bias", "0.5.0.bn3.running_mean", "0.5.0.bn3.running_var", "0.5.1.conv3.weight", "0.5.1.bn3.weight", "0.5.1.bn3.bias", "0.5.1.bn3.running_mean", "0.5.1.bn3.running_var", "0.5.2.conv3.weight", "0.5.2.bn3.weight", "0.5.2.bn3.bias", "0.5.2.bn3.running_mean", "0.5.2.bn3.running_var", "0.5.3.conv3.weight", "0.5.3.bn3.weight", "0.5.3.bn3.bias", "0.5.3.bn3.running_mean", "0.5.3.bn3.running_var", "0.6.0.conv3.weight", "0.6.0.bn3.weight", "0.6.0.bn3.bias", "0.6.0.bn3.running_mean", "0.6.0.bn3.running_var", "0.6.1.conv3.weight", "0.6.1.bn3.weight", "0.6.1.bn3.bias", "0.6.1.bn3.running_mean", "0.6.1.bn3.running_var", "0.6.2.conv3.weight", "0.6.2.bn3.weight", "0.6.2.bn3.bias", "0.6.2.bn3.running_mean", "0.6.2.bn3.running_var", "0.6.3.conv3.weight", "0.6.3.bn3.weight", "0.6.3.bn3.bias", "0.6.3.bn3.running_mean", "0.6.3.bn3.running_var", "0.6.4.conv3.weight", "0.6.4.bn3.weight", "0.6.4.bn3.bias", "0.6.4.bn3.running_mean", "0.6.... size mismatch for 0.4.0.conv1.weight: copying a param with shape torch.Size([64, 64, 3, 3]) from checkpoint, the shape in current model is torch.Size([64, 64, 1, 1]). size mismatch for 0.4.1.conv1.weight: copying a param with shape torch.Size([64, 64, 3, 3]) from checkpoint, the shape in current model is torch.Size([64, 256, 1, 1]). size mismatch for 0.4.2.conv1.weight: copying a param with shape torch.Size([64, 64, 3, 3]) from checkpoint, the shape in current model is torch.Size([64, 256, 1, 1]). size mismatch for 0.5.0.conv1.weight: copying a param with shape torch.Size([128, 64, 3, 3]) from checkpoint, the shape in current model is torch.Size([128, 256, 1, 1]). size mismatch for 0.5.0.downsample.0.weight: copying a param with shape torch.Size([128, 64, 1, 1]) from checkpoint, the shape in current model is torch.Size([512, 256, 1, 1]). size mismatch for 0.5.0.downsample.1.weight: copying a param with shape torch.Size([128]) from checkpoint, the shape in current model is torch.Size([512]). size mismatch for 0.5.0.downsample.1.bias: copying a param with shape torch.Size([128]) from checkpoint, the shape in current model is torch.Size([512]). size mismatch for 0.5.0.downsample.1.running_mean: copying a param with shape torch.Size([128]) from checkpoint, the shape in current model is torch.Size([512]). size mismatch for 0.5.0.downsample.1.running_var: copying a param with shape torch.Size([128]) from checkpoint, the shape in current model is torch.Size([512]). size mismatch for 0.5.1.conv1.weight: copying a param with shape torch.Size([128, 128, 3, 3]) from checkpoint, the shape in current model is torch.Size([128, 512, 1, 1]). size mismatch for 0.5.2.conv1.weight: copying a param with shape torch.Size([128, 128, 3, 3]) from checkpoint, the shape in current model is torch.Size([128, 512, 1, 1]). size mismatch for 0.5.3.conv1.weight: copying a param with shape torch.Size([128, 128, 3, 3]) from checkpoint, the shape in current model is torch.Size([128, 512, 1, 1]). size mismatch for 0.6.0.conv1.weight: copying a param with shape torch.Size([256, 128, 3, 3]) from checkpoint, the shape in current model is torch.Size([256, 512, 1, 1]). size mismatch for 0.6.0.downsample.0.weight: copying a param with shape torch.Size([256, 128, 1, 1]) from checkpoint, the shape in current model is torch.Size([1024, 512, 1, 1]). size mismatch for 0.6.0.downsample.1.weight: copying a param with shape torch.Size([256]) from checkpoint, the shape in current model is torch.Size([1024]). size mismatch for 0.6.0.downsample.1.bias: copying a param with shape torch.Size([256]) from checkpoint, the shape in current model is torch.Size([1024]). size mismatch for 0.6.0.downsample.1.running_mean: copying a param with shape torch.Size([256]) from checkpoint, the shape in current model is torch.Size([1024]). size mismatch for 0.6.0.downsample.1.running_var: copying a param with shape torch.Size([256]) from checkpoint, the shape in current model is torch.Size([1024]). size mismatch for 0.6.1.conv1.weight: copying a param with shape torch.Size([256, 256, 3, 3]) from checkpoint, the shape in current model is torch.Size([256, 1024, 1, 1]). size mismatch for 0.6.2.conv1.weight: copying a param with shape torch.Size([256, 256, 3, 3]) from checkpoint, the shape in current model is torch.Size([256, 1024, 1, 1]). size mismatch for 0.6.3.conv1.weight: copying a param with shape torch.Size([256, 256, 3, 3]) from checkpoint, the shape in current model is torch.Size([256, 1024, 1, 1]). size mismatch for 0.6.4.conv1.weight: copying a param with shape torch.Size([256, 256, 3, 3]) from checkpoint, the shape in current model is torch.Size([256, 1024, 1, 1]). size mismatch for 0.6.5.conv1.weight: copying a param with shape torch.Size([256, 256, 3, 3]) from checkpoint, the shape in current model is torch.Size([256, 1024, 1, 1]). size mismatch for 0.7.0.conv1.weight: copying a param with shape torch.Size([512, 256, 3, 3]) from checkpoint, the shape in current model is torch.Size([512, 1024, 1, 1]). size mismatch for 0.7.0.downsample.0.weight: copying a param with shape torch.Size([512, 256, 1, 1]) from checkpoint, the shape in current model is torch.Size([2048, 1024, 1, 1]). size mismatch for 0.7.0.downsample.1.weight: copying a param with shape torch.Size([512]) from checkpoint, the shape in current model is torch.Size([2048]). size mismatch for 0.7.0.downsample.1.bias: copying a param with shape torch.Size([512]) from checkpoint, the shape in current model is torch.Size([2048]). size mismatch for 0.7.0.downsample.1.running_mean: copying a param with shape torch.Size([512]) from checkpoint, the shape in current model is torch.Size([2048]). size mismatch for 0.7.0.downsample.1.running_var: copying a param with shape torch.Size([512]) from checkpoint, the shape in current model is torch.Size([2048]). size mismatch for 0.7.1.conv1.weight: copying a param with shape torch.Size([512, 512, 3, 3]) from checkpoint, the shape in current model is torch.Size([512, 2048, 1, 1]). size mismatch for 0.7.2.conv1.weight: copying a param with shape torch.Size([512, 512, 3, 3]) from checkpoint, the shape in current model is torch.Size([512, 2048, 1, 1]). size mismatch for 1.2.weight: copying a param with shape torch.Size([1024]) from checkpoint, the shape in current model is torch.Size([4096]). size mismatch for 1.2.bias: copying a param with shape torch.Size([1024]) from checkpoint, the shape in current model is torch.Size([4096]). size mismatch for 1.2.running_mean: copying a param with shape torch.Size([1024]) from checkpoint, the shape in current model is torch.Size([4096]). size mismatch for 1.2.running_var: copying a param with shape torch.Size([1024]) from checkpoint, the shape in current model is torch.Size([4096]). size mismatch for 1.4.weight: copying a param with shape torch.Size([512, 1024]) from checkpoint, the shape in current model is torch.Size([512, 4096]).
There are few issues with your approach : You mentioned that you used resnet 34 for training and then saving its weights. Yet while testing, you are using resnet 50 and trying to load the weights of resnet 34 which will not work due to different arch (layers & parameters). In case you are doing the testing in the same NB , you cold have added test dataset while creating the train & valid dataset itself and get predictions on the whole dataset with 2 lines of code. a quick sample : test_imgs = (path/'cars_test/').ls() data.add_test(test_imgs) learn.data = data preds = learn.get_preds(ds_type=DatasetType.Test) If you are going to use it in different nb , try model.export to save model, its weights, data and all the info . I think jeremy did that in his NB and course.
https://stackoverflow.com/questions/67746783/
Difference between Tensor and tensor
I am working with Pytorch. But when I use tensor I got an error while I don't get any error when I use Tensor. What is the difference between Tensor and tensor? This is my example: tns = torch.tensor([91,21,34,56]) tns.mean() I got this error: RuntimeError: Can only calculate the mean of floating types. Got Long instead. Thanks in advance.
If you don't specify a dtype in torch.tensor() it infers this from the data. Since your data is all integers, it used Long. torch.mean() can only be calculated for floats. By default, torch.Tensor is an alias for torch.FloatTensor hence it automatically has dtype float (unless you change the default behaviour).
https://stackoverflow.com/questions/67749866/
Is reshape() same as contiguous().view()?
In PyTorch, for a tensor x is x.reshape(shape) always equivalent to x.contiguous().view(shape)?
No. There are some circumstances where .reshape(shape) can create a view, but .contiguous().view(shape) will create a copy. Here is an example: x = torch.zeros(8, 10) y = x[:, ::2] z0 = y.reshape(40) # Makes a new view z1 = y.contiguous().view(40) # Makes a copy We can confirm that z0 is a new view of x, but z1 is a copy: > x.data_ptr() == z0.data_ptr() True > x.data_ptr() == z1.data_ptr() False
https://stackoverflow.com/questions/67751088/
Torch argmax for N highest values
I would like to do something like an argmax but with multiple top values. I know how to use the normal torch.argmax >>> a = torch.randn(4, 4) >>> a tensor([[ 1.3398, 1.2663, -0.2686, 0.2450], [-0.7401, -0.8805, -0.3402, -1.1936], [ 0.4907, -1.3948, -1.0691, -0.3132], [-1.6092, 0.5419, -0.2993, 0.3195]]) >>> torch.argmax(a) tensor(0) But now I need to find the indices for the top N values. So something like this >>> a = torch.randn(4, 4) >>> a tensor([[ 1.3398, 1.2663, -0.2686, 0.2450], [-0.7401, -0.8805, -0.3402, -1.1936], [ 0.4907, -1.3948, -1.0691, -0.3132], [-1.6092, 0.5419, -0.2993, 0.3195]]) >>> torch.argmax(a,top_n=2) tensor([0,1]) I haven't found any function capable of doing this in pytorch, does anyone know?
Great! So you need the first k largest elements of a tensor. [Answer 1] You need the first k largest of all the elements irrespective of the dimension. So, flatten the tensor and use the torch.topk function to get indices of top-3 (for example) elements: >>> a = torch.randn(5,4) >>> a tensor([[ 0.8292, -0.5123, -0.0741, -0.3043], [-0.4340, -0.7763, 1.9716, -0.5620], [ 0.1582, -1.2000, 1.0202, -1.5202], [-0.3617, -0.2479, 0.6204, 0.2575], [ 1.8025, 1.9864, -0.8013, -0.7508]]) >>> torch.topk(a.flatten(), 3).indices tensor([17, 6, 16]) [Answer 2] You need k largest elements of the given input tensor along a given dimension. So for this refer to the PyTorch documentation of the function torch.topk given here.
https://stackoverflow.com/questions/67752619/
Batchnormalization over which dimension?
Over which dimension do we calculate the mean and std? Is it over the hidden dimensions of the NN Layer, or over all the samples in the batch for every hidden dimension separately? In the paper it says we normalize over the batch. In torch.nn.BatchNorm1d however the input argument is num_features, which makes no sense to me. Why does pytorch not follow the original paper on Batchnormalization?
over which dimension do we calculate the mean and std? Over 0th dimension, for 1D input of shape (batch, num_features) it would be: batch = 64 features = 12 data = torch.randn(batch, features) mean = torch.mean(data, dim=0) var = torch.var(data, dim=0) In torch.nn.BatchNorm1d hower the input argument is "num_features", which makes no sense to me. It is not related to normalization but reparametrization of mean and var via gamma and beta learnable parameters. From the paper: Both parameters used in scale and shift phase are of shape num_features, hence we have to pass this value in order to initialize them with specific shape. Below is an example from scratch implementation for reference: class BatchNorm1d(torch.nn.Module): def __init__(self, num_features, momentum: float = 0.9, eps: float = 1e-7): super().__init__() self.num_features = num_features self.gamma = torch.nn.Parameter(torch.ones(1, self.num_features)) self.beta = torch.nn.Parameter(torch.zeros(1, self.num_features)) self.register_buffer("running_mean", torch.ones(1, self.num_features)) self.register_buffer("running_var", torch.ones(1, self.num_features)) self.momentum = momentum self.eps = eps def forward(self, X): if not self.training: X_hat = X - self.running_mean / torch.sqrt(self.running_var + self.eps) else: mean = X.mean(dim=0).unsqueeze(dim=0) var = ((X - mean) ** 2).mean(dim=0).unsqueeze(dim=0) # Update running mean and variance self.running_mean *= self.momentum self.running_mean += (1 - self.momentum) * mean self.running_var *= self.momentum self.running_var += (1 - self.momentum) * var X_hat = X - mean / torch.sqrt(var + self.eps) return X_hat * self.gamma + self.beta Why does pytorch not follow the original paper on Batchnormalization? It does as one can see
https://stackoverflow.com/questions/67754435/
How to correctly set input image size for LPRNet model? 'RuntimeError: Sizes of tensors must match except in dimension 1..'
Trying to adapt the LPRNet model for my own dataset. The original model was set for Chinese license plate images with dimensions 24x94 pixels. My dataset consists of plates with only numbers, images come with dimensions 64x128. I got an error when I try to replace 'summary(lprnet, (3,24,94), device="cpu")' to 'summary(lprnet, (3,64,128), device="cpu")'. The first code is working well, the second gets 'RuntimeError: Sizes of tensors must match except in dimension 1. Got 25 and 24 in dimension 3 (The offending index is 1)', this is the last line of code. I don't see where else in the code I should change parameters. Will be thankful for any clue! Original: https://github.com/xuexingyu24/License_Plate_Detection_Pytorch/blob/master/LPRNet/model/LPRNET.py # LPRNET model import torch import torch.nn as nn from torchsummary import summary class small_basic_block(nn.Module): def __init__(self, ch_in, ch_out): super(small_basic_block, self).__init__() self.block = nn.Sequential( nn.Conv2d(ch_in, ch_out // 4, kernel_size=1), nn.ReLU(), nn.Conv2d(ch_out // 4, ch_out // 4, kernel_size=(3, 1), padding=(1, 0)), nn.ReLU(), nn.Conv2d(ch_out // 4, ch_out // 4, kernel_size=(1, 3), padding=(0, 1)), nn.ReLU(), nn.Conv2d(ch_out // 4, ch_out, kernel_size=1), ) def forward(self, x): return self.block(x) class LPRNet(nn.Module): def __init__(self, class_num, dropout_rate): super(LPRNet, self).__init__() self.class_num = class_num self.backbone = nn.Sequential( nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, stride=1), # 0 nn.BatchNorm2d(num_features=64), nn.ReLU(), # 2 nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1, 1, 1)), small_basic_block(ch_in=64, ch_out=128), # *** 4 *** nn.BatchNorm2d(num_features=128), nn.ReLU(), # 6 nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(2, 1, 2)), small_basic_block(ch_in=64, ch_out=256), # 8 nn.BatchNorm2d(num_features=256), nn.ReLU(), # 10 small_basic_block(ch_in=256, ch_out=256), # *** 11 *** nn.BatchNorm2d(num_features=256), # 12 nn.ReLU(), nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(4, 1, 2)), # 14 nn.Dropout(dropout_rate), nn.Conv2d(in_channels=64, out_channels=256, kernel_size=(1, 4), stride=1), # 16 nn.BatchNorm2d(num_features=256), nn.ReLU(), # 18 nn.Dropout(dropout_rate), nn.Conv2d(in_channels=256, out_channels=class_num, kernel_size=(13, 1), stride=1), # 20 nn.BatchNorm2d(num_features=class_num), nn.ReLU(), # *** 22 *** ) self.container = nn.Sequential( nn.Conv2d(in_channels=256+class_num+128+64, out_channels=self.class_num, kernel_size=(1,1), stride=(1,1)), # nn.BatchNorm2d(num_features=self.class_num), # nn.ReLU(), # nn.Conv2d(in_channels=self.class_num, out_channels=self.lpr_max_len+1, kernel_size=3, stride=2), # nn.ReLU(), ) def forward(self, x): keep_features = list() for i, layer in enumerate(self.backbone.children()): x = layer(x) if i in [2, 6, 13, 22]: # [2, 4, 8, 11, 22] keep_features.append(x) global_context = list() for i, f in enumerate(keep_features): if i in [0, 1]: f = nn.AvgPool2d(kernel_size=5, stride=5)(f) if i in [2]: f = nn.AvgPool2d(kernel_size=(4, 10), stride=(4, 2))(f) f_pow = torch.pow(f, 2) f_mean = torch.mean(f_pow) f = torch.div(f, f_mean) global_context.append(f) x = torch.cat(global_context, 1) x = self.container(x) logits = torch.mean(x, dim=2) return logits CHARS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] if __name__ == "__main__": lprnet = LPRNet(class_num=len(CHARS), dropout_rate=0) print(lprnet) summary(lprnet, (3,24,94), device="cpu") #summary(lprnet, (3,64,128), device="cpu")
The problem with your code is that the shapes of four tensors in global_context are different for (64, 128) input size. For shape (24, 94), in LRPNet, the authors make all the tensors of (4, 18) sized with average pooling which doesn't apply to your image size. To make them same-sized, you need to change the configurations of nn.AvgPool2d while enumerating keep_features. You may update them in various ways. I updated the avgpool with the below configurations and it worked: if i in [0, 1]: f = nn.AvgPool2d(kernel_size=(11, 24), stride=(7, 4))(f) elif i == 2: f = nn.AvgPool2d(kernel_size=(9, 11), stride=(7, 2))(f) elif i == 3: f = nn.AvgPool2d(kernel_size=(7, 2), stride=(5, 1))(f) f_pow = torch.pow(f, 2) f_mean = torch.mean(f_pow) f = torch.div(f, f_mean) global_context.append(f)```
https://stackoverflow.com/questions/67756113/
How to load a saved model defined in a function in PyTorch in Colab?
Here is a sample code of my training function(unnecessary parts are deleted): I am trying to save my model data_gen in the torch.save(), and after running the train_dmc function, I can find the checkpoint file in the directory. def train_dmc(loader,loss): data_gen = DataGenerator().to(device) data_gen_optimizer = optim.Rprop(para_list, lr=lrate) savepath='/content/drive/MyDrive/'+loss+'checkpoint.t7' state = { 'epoch': epoch, 'model_state_dict': data_gen.state_dict(), 'optimizer_state_dict': data_gen_optimizer.state_dict(), 'data loss': data_loss, 'latent_loss':latent_loss } torch.save(state,savepath) My question is that how to load the checkpoint file to continue training if Google Colab disconnects. Should I load data_gen or train_dmc(), it is my first time using this and I am really confused because the data_gen is defined inside another function. Hope someone can help me with explanation data_gen.load_state_dict(torch.load(PATH)) data_gen.eval() #or train_dmc.load_state_dict(torch.load(PATH)) train_dmc.eval()
As the state variable is a dictionary, So try saving it as: with open('/content/checkpoint.t7', 'wb') as handle: pickle.dump(state, handle, protocol=pickle.HIGHEST_PROTOCOL) Initiate your model class as data_gen = DataGenerator().to(device). And load the checkpoint file as: import pickle file = open('/content/checkpoint.t7', 'rb') loaded_state = pickle.load(file) Then you can load the state_dict using data_gen = loaded_state['model_state_dict']. This will load the state_dict to the model class!
https://stackoverflow.com/questions/67759230/
How to use MSELoss function for Fashion_MNIST in pytorch?
I want to get through Fashion_Mnist data, I would like to see the output gradient which might be mean squared sum between first and second layer My code first below #import the nescessary libs import numpy as np import torch import time # Loading the Fashion-MNIST dataset from torchvision import datasets, transforms # Get GPU Device device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") torch.cuda.get_device_name(0) # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)) ]) # Download and load the training data trainset = datasets.FashionMNIST('MNIST_data/', download = True, train = True, transform = transform) testset = datasets.FashionMNIST('MNIST_data/', download = True, train = False, transform = transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size = 128, shuffle = True, num_workers=4) testloader = torch.utils.data.DataLoader(testset, batch_size = 128, shuffle = True, num_workers=4) # Examine a sample dataiter = iter(trainloader) images, labels = dataiter.next() # Define the network architecture from torch import nn, optim import torch.nn.functional as F model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10), nn.LogSoftmax(dim = 1) ) model.to(device) # Define the loss criterion = nn.MSELoss() # Define the optimizer optimizer = optim.Adam(model.parameters(), lr = 0.001) # Define the epochs epochs = 5 train_losses, test_losses = [], [] squared_sum = [] # start = time.time() for e in range(epochs): running_loss = 0 for images, labels in trainloader: # Flatten Fashion-MNIST images into a 784 long vector images = images.to(device) labels = labels.to(device) images = images.view(images.shape[0], -1) optimizer.zero_grad() output = model[0].forward(images) loss = criterion(output[0], labels.float()) loss.backward() optimizer.step() running_loss += loss.item() else: print(running_loss) test_loss = 0 accuracy = 0 # Turn off gradients for validation, saves memory and computation with torch.no_grad(): # Set the model to evaluation mode model.eval() # Validation pass for images, labels in testloader: images = images.to(device) labels = labels.to(device) images = images.view(images.shape[0], -1) ps = model(images[0]) test_loss += criterion(ps, labels) top_p, top_class = ps.topk(1, dim = 1) equals = top_class == labels.view(*top_class.shape) accuracy += torch.mean(equals.type(torch.FloatTensor)) model.train() print("Epoch: {}/{}..".format(e+1, epochs), "Training loss: {:.3f}..".format(running_loss/len(trainloader)), "Test loss: {:.3f}..".format(test_loss/len(testloader)), "Test Accuracy: {:.3f}".format(accuracy/len(testloader))) What I want to get, for e in range(epochs): running_loss = 0 for images, labels in trainloader: # Flatten Fashion-MNIST images into a 784 long vector images = images.to(device) labels = labels.to(device) images = images.view(images.shape[0], -1) optimizer.zero_grad() output = model[0].forward(images) loss = criterion(output[0], labels.float()) loss.backward() optimizer.step() running_loss += loss.item() In here, model[0] (This might be the first layer nn.Linear(784, 128)), I would love to get the mean square errors only for first and second layer, If I run this code, I receive this error below RuntimeError: The size of tensor a (128) must match the size of tensor b (96) at non-singleton dimension 0 If I want to run this code correctly to get the MSELoss, what I need to do?
The error is caused by the number of samples in the dataset and the batch size. In more detail, the training MNIST dataset includes 60,000 samples, your current batch_size is 128 and you will need 60000/128=468.75 loops to finish training on one epoch. So the problem comes from here, for 468 loops, your data will have 128 samples but the last loop just contains 60000 - 468*128 = 96 samples. To solve this problem, I think you need to find the suitable batch_size and the number of neural in your model as well. I think it should work for computing loss trainloader = torch.utils.data.DataLoader(trainset, batch_size = 96, shuffle = True, num_workers=0) testloader = torch.utils.data.DataLoader(testset, batch_size = 96, shuffle = True, num_workers=0) model = nn.Sequential(nn.Linear(784, 96), nn.ReLU(), nn.Linear(96, 10), nn.LogSoftmax(dim = 1) )
https://stackoverflow.com/questions/67760590/
Importing fastai in GoogleColab
I am trying to import this module in googlecolab for my code. As I want to run my code with GPU but even when I do pip install fastai or pip3 intall fastai , it says requirement satisfied but gives me error when I run these: from fastai.vision.all import * import gc ModuleNotFoundError: No module named 'fastai.vision.all'
You need to upgrade fastai. Run the following instead: !pip install fastai --upgrade Then, check if the installed version is 2.0 or higher: import fastai print(fastai.__version__)
https://stackoverflow.com/questions/67761905/
Apply stochastic depth by Pytorch
The definition of Stochastic depth was first mentioned in this paper. In short, it's similar to drop-out but instead of node, it will terminate the connection of the Skip connection structure (residual block) in ResNet paper. My question: is there any fast, easy way to implement Stochastic depth in transfer learning by Pytorch such as drop-out (simply add torch.nn.DropOut(p) into the classifier block).
Basic StochasticDepth Yes, one could do something like this pretty easily: class StochasticDepth(torch.nn.Module): def __init__(self, module: torch.nn.Module, p: float = 0.5): super().__init__() if not 0 < p < 1: raise ValueError( "Stochastic Depth p has to be between 0 and 1 but got {}".format(p) ) self.module: torch.nn.Module = module self.p: float = p self._sampler = torch.Tensor(1) def forward(self, inputs): if self.training and self._sampler.uniform_(): return inputs return self.p * self.module(inputs) Please notice that: inputs shape has to be the same as self.module(inputs) shape You can pass any block inside this function (see below) Example usage: layer = StochasticDepth( torch.nn.Sequential( torch.nn.Linear(10, 10), torch.nn.ReLU(), torch.nn.Linear(10, 10), torch.nn.ReLU(), ), p=0.5, ) Adding to existing models First, you should print the model that you want and analyze the weights and outputs. What you're looking for to apply this module easiest (in case of Conv{1,2,3}d layers): same number of in_channels and out_channels within the block for different number of in_channels and out_channels some kind of projection would be needed StochasticDepth with projection Version with projection of StochasticDepth: class StochasticDepth(torch.nn.Module): def __init__( self, module: torch.nn.Module, p: float = 0.5, projection: torch.nn.Module = None, ): super().__init__() if not 0 < p < 1: raise ValueError( "Stochastic Depth p has to be between 0 and 1 but got {}".format(p) ) self.module: torch.nn.Module = module self.p: float = p self.projection: torch.nn.Module = projection self._sampler = torch.Tensor(1) def forward(self, inputs): if self.training and self._sampler.uniform_(): if self.projection is not None: return self.projection(inputs) return inputs return self.p * self.module(inputs) projection could be Conv2d(256, 512, kernel_size=1, stride=2) in case of resnet modules as it would increase number of channels and make the image smaller via stride=2 as in original paper. Applying StochasticDepth If you print torchvision.models.resnet18() you would see repeating blocks like this: (layer2): Sequential( (0): BasicBlock( (conv1): Conv2d(64, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (downsample): Sequential( (0): Conv2d(64, 128, kernel_size=(1, 1), stride=(2, 2), bias=False) (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): BasicBlock( (conv1): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) Each layer is a larger colored block you may want to randomly skip. For resnet18 and layer specifically one could do this: model = torchvision.models.resnet18() model.layer1 = StochasticDepth(model.layer1) model.layer2 = StochasticDepth( model.layer2, projection=torch.nn.Conv2d( 64, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False ), ) model.layer3 = StochasticDepth( model.layer3, projection=torch.nn.Conv2d( 128, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False ), ) model.layer4 = StochasticDepth( model.layer4, projection=torch.nn.Conv2d( 256, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False ), ) First block's channels stay the same hence no projection is needed Second, third and fourth up number of channels and make the image smaller via stride hence simple projection is used You can modify any part of the neural network using this approach, just remember to test whether the shapes agree. Simpler projections One could also tie weights between first conv layer in specific block and use that module as a projection, see below: model = torchvision.models.resnet18() model.layer1 = StochasticDepth(model.layer1) model.layer2 = StochasticDepth(model.layer2, projection=model.layer2[0].conv1) model.layer3 = StochasticDepth(model.layer3, projection=model.layer3[0].conv1) model.layer4 = StochasticDepth(model.layer4, projection=model.layer4[0].conv1) Upsides: weights are not randomly initialized easier to write Downsides: weights are tied and one layer will have to do two tasks: be first in the block (without dropping) be the only in the block (with dropping) this might not end up too well as it is responsible for conflicting tasks You may also copy this module instead of sharing weights, probably best idea.
https://stackoverflow.com/questions/67762024/
Pytorch: Creating a tensor mask based of rate/percentage/ratio
How can I generate a mask tensor that has a specific ratio of 0 and 1? For example 70:30 of 0s and 1s in a 5 by 10 tensor will generate: [[0,0,0,0,0,0,0,0,1,0], [1,1,1,0,0,0,1,1,0,0], [0,0,1,0,0,1,1,0,1,0], [0,1,0,1,0,1,1,0,0,0], [0,0,0,1,0,0,0,0,0,0]]
You can approximate the ratio using random sampling: import torch mask = torch.rand(5, 10) # uniformly distributed between 0 and 1 mask = mask < 0.3 # 30% pixels "on" On average, mask will have the right amount of "on" pixels. Alternatively, if you must have exactly 30% of "on" pixels, you can use torch.randperm to randomly permute a mask with exactly the number of "on" pixels: raw = torch.zeros((5*10,)) raw[:int(0.3 * 5 * 10)] = 1. # set EXACTLY 30% of the pixels in the mask ridx = torch.randperm(5*10) # a random permutation of the entries mask = torch.reshape(raw[ridx], (5, 10))
https://stackoverflow.com/questions/67767693/
How can I generate lots of FC layer in a simple way?
I would like to make 640 fc layer. (in def init) self.fc0 = nn.Linear(120, M) self.fc1 = nn.Linear(120, M) ..... self.fc638 = nn.Linear(120, M) self.fc639 = nn.Linear(120, M) (in def forward) x[:,:,0,:] = self.fc0(x[:,:,0,:]) x[:,:,1,:] = self.fc0(x[:,:,1,:]) ....... x[:,:,639,:] = self.fc639(x[:,:,639,:]) How can I execute the code above in simpler way ?
Use containers: class MultipleFC(nn.Module): def __init__(self, num_layers, M): self.layers = nn.ModuleList([nn.Linear(120, M) for _ in range(num_layers)]) def forward(self, x): y = torch.empty_like(x) # up to third dim should be M for i, fc in enumerate(self.layers): y[..., i, :] = fc(x[..., i, :]) return y
https://stackoverflow.com/questions/67769150/
Difference between MultiplicativeLR and LambdaLR
Can someone explain difference between torch.optim.lr_scheduler.LambdaLR(https://pytorch.org/docs/stable/optim.html) and torch.optim.lr_scheduler.MultiplicativeLR(https://pytorch.org/docs/stable/optim.html)? Here is brief description of MultiplicativeLR: and LambdaLR
The main difference is that they use a different function for computing the learning rate of the function. LambdaLR's function is: While MultiplicativeLR's function is: Thus they would have a different result for the learning rate. Both are useful for a variety of scenarios.
https://stackoverflow.com/questions/67770232/
How to use "model.trt" in Python
I have a pytorch model that I exported to ONNX and converted to a tensorflow model with the following command: trtexec --onnx=model.onnx --batch=400 --saveEngine=model.trt All of this works, but how do I now load this model.trt in python and run the inference?
The official documentation has a lot of examples. The basic steps to follow are: ONNX parser: takes a trained model in ONNX format as input and populates a network object in TensorRT Builder: takes a network in TensorRT and generates an engine that is optimized for the target platform Engine: takes input data, performs inferences and emits inference output Logger: object associated with the builder and engine to capture errors, warnings and other information during the build and inference phases An example for the engine is: import tensorrt as trt import pycuda.autoinit import pycuda.driver as cuda from onnx import ModelProto import onnx import numpy as np import matplotlib.pyplot as plt from time import time TRT_LOGGER = trt.Logger(trt.Logger.WARNING) trt_runtime = trt.Runtime(TRT_LOGGER) #batch_size = 1 explicit_batch = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) #inp_shape = [batch_size, 3, 1024, 1024] # the shape I was using def build_engine(onnx_path, shape = inp_shape): with trt.Builder(TRT_LOGGER) as builder,builder.create_builder_config() as config,\ builder.create_network(explicit_batch) as network, trt.OnnxParser(network, TRT_LOGGER) as parser: if builder.platform_has_fast_fp16: builder.fp16_mode = True builder.max_workspace_size = (1 << 30) #builder.max_workspace_size = (3072 << 20) #profile = builder.create_optimization_profile() #config.max_workspace_size = (3072 << 20) #config.add_optimization_profile(profile) print("parsing") with open(onnx_path, 'rb') as model: print("onnx found") if not parser.parse(model.read()): print("parse failed") for error in range(parser.num_errors): print(parser.get_error(error)) #parser.parse(model.read()) last_layer = network.get_layer(network.num_layers - 1) # Check if last layer recognizes it's output if not last_layer.get_output(0): # If not, then mark the output using TensorRT API network.mark_output(last_layer.get_output(0)) network.get_input(0).shape = shape engine = builder.build_cuda_engine(network) return engine def save_engine(engine, file_name): buf = engine.serialize() with open(file_name, 'wb') as f: f.write(buf) def load_engine(trt_runtime, plan_path): with open(engine_path, 'rb') as f: engine_data = f.read() engine = trt_runtime.deserialize_cuda_engine(engine_data) return engine if __name__ == "__main__": onnx_path = "./path/to/your/model.onnx" engine_name = "./path/to/engine.plan" model = ModelProto() with open(onnx_path, "rb") as f: model.ParseFromString(f.read()) d0 = model.graph.input[0].type.tensor_type.shape.dim[1].dim_value d1 = model.graph.input[0].type.tensor_type.shape.dim[2].dim_value d2 = model.graph.input[0].type.tensor_type.shape.dim[3].dim_value shape = [batch_size , d0, d1 ,d2] print(shape) print("trying to build engine") engine = build_engine(onnx_path,shape) save_engine(engine,engine_name) print("finished") Follow this page for another example and information.
https://stackoverflow.com/questions/67771469/
Text to Image generation using torch model/path file
I trained a text to image generation model based on https://github.com/aelnouby/Text-to-Image-Synthesis. Now I have 2 path files (one for generator , another for discriminator) . How to generate images using this path files?
You need to pass your generator path file here. self.generator.load_state_dict(torch.load(pre_trained_gen)) Refer line 28 of trainer.py
https://stackoverflow.com/questions/67772795/
how to calculate relative pose given two 4x4 affine matrix
I have two 4x4 affine matrix, A and B. They represent the pose of two objects in the world coordinate system. How could I calculate their relative pose via matrix multiplication ? (Actually, I want to know the position(x_A,y_A) in the coordinate system of object B) I've tried with relative pose = A * B^-1 relative_pose = torch.multiply(A, torch.inverse(B)). However, the relative translation is way too big. (A and B are pretty close to each other, while they are far away from origin point in world coordinate.) test data for pytorch: import torch A = torch.tensor([[-9.3793e-01, -3.4481e-01, -3.7340e-02, -4.6983e+03], [ 3.4241e-01, -9.3773e-01, 5.8526e-02, 1.0980e+04], [-5.5195e-02, 4.2108e-02, 9.9759e-01, -2.3445e+01], [ 0.0000e+00, 0.0000e+00, 0.0000e+00, 1.0000e+00]]) B = torch.tensor([[-9.7592e-01, -2.1022e-01, -5.8136e-02, -4.6956e+03], [ 2.0836e-01, -9.7737e-01, 3.6429e-02, 1.0979e+04], [-6.4478e-02, 2.3438e-02, 9.9764e-01, -2.3251e+01], [ 0.0000e+00, 0.0000e+00, 0.0000e+00, 1.0000e+00]])
So I assume you are using solid transformation matrices M in homogeneous coordinates, in other words 4x4 matrices containing a 3x3 rotation matrix R, a 3x1 translation vector T and a [0,0,0,1] homogeneous "padding" row vector. And you want to find the transformation to go from one pose to the other (I don't know how to write matrices by block, but that would be something like (R | T \\ 0 | 1) Then I think your formula is wrong : if Y_1 = M_1 X and Y_2 = M_2 X, then you have Y_2 = M_2 M_1^-1 X, and your relative pose matrix is M_rel = M_2 M_1^-1 So you need to invert your solid transformation matrix M_1 = (R_1 | T_1 \\ 0 | 1) If you write the equations, and if we note P = R_1^-1, then you'll find that M_1^-1 = (P | -PT \\ 0 | 1)
https://stackoverflow.com/questions/67773919/
From two Tensors (labels, inputs) to DataLoader
I'm working with two tensors, inputs and labels, and I want to have them together to train a model. I'm using torch 1.7, but I can't use the function TensorDataset() and then apply DataLoader(), due to some incompatibilities with other packages when I use TensorDataset(). There is another solution to my problem? Summary: 2 Tensors --> DataLoader without using TensorDataset()
You can construct your own custom DataSet: class MyDataSet(torch.utils.data.Dataset): def __init__(self, x, y): super(MyDataSet, self).__init__() # store the raw tensors self._x = x self._y = y def __len__(self): # a DataSet must know it size return self._x.shape[0] def __getitem__(self, index): x = self._x[index, :] y = self._y[index, :] return x, y
https://stackoverflow.com/questions/67774088/
TensorBoard: Combine two graphs into one graph
I accidentally ran a model where the training loss goes to "Cos_BN Loss", and the validation loss go to "Gen Cos_BN Loss", that means that I have two separate graphs for train and validation (for the same type of loss). I want to see them together on the same plot. How? NOTE: I know I can just run again the model by calling the validation loss - the same name as the training loss, BUT it took around 3 days to ran, on 3 GPUs and I really don't want to train it again all over. Current state Thank you
On the bottom there is a download data link that let's you save the data as a CSV file. You may need to enable it first (top left in following picture): You can then import this e.g. using pandas and plot it to your liking using `matplotlib.
https://stackoverflow.com/questions/67774279/
Turn the two highest values of a pytorch tensor / numpy array to 1 and the others to zero
I have some pytorch tensors (or numpy arrays) and want to turn the two highest numbers to a 1 and every other number to a zero. So this tensor tensor([0.9998, 0.9997, 0.9991, 0.9998, 0.9996, 0.9996, 0.9997, 0.9995], dtype=torch.float64) Should become this: tensor([1, 0, 0, 1, 0, 0, 0, 0], dtype=torch.float64) There are some ways to turn the highest number to 1 and the others to 0, but I need the two highest numbers to become 1. Why isn't there a built in function for that? I have a classification problem where I know that two objects belong to class 1. So shouldn't this be a quite common problem?
You can do this with topk: x = tensor([0.9998, 0.9997, 0.9991, 0.9998, 0.9996, 0.9996, 0.9997, 0.9995], dtype=torch.float64) _, idx = x.topk(2) x.fill_(0) x[idx] = 1
https://stackoverflow.com/questions/67775508/
Tensorflow equivalent to torch.Tensor.index_copy
I am implementing the tensorflow equivalent of the model here originally implemented using pytorch. Everything was going smoothly until I encountered this particular line of code. batch_current = Variable(torch.zeros(size, self.embedding_dim)) # self.embedding and self.W_c are pytorch network layers I have created batch_current = self.W_c(batch_current.index_copy(0, Variable(torch.LongTensor(index)), self.embedding(Variable(self.th.LongTensor(current_node))))) If search for the documentation of index_copy and it seems all it does is to copy a group of elements at a certain index and on a common axis and assign it to another tensor. But I don't really want to write some buggy code, so before attempting any self-implementation, I wish to know if you folks have an idea of how I can go about implementing it. The model is from this paper and yes, I have searched other tensorflow implementations, but they don't seem to make so much sense to me.
What you need is the tf.tensor_scatter_nd_update in tensorflow to get equivalent operation like Tensor.index_copy_ of pytorch. Here is one demonstration shown below. In pytorch, you have import torch tensor = torch.zeros(5, 3) indices = torch.tensor([0, 4, 2]) updates= torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) tensor.index_copy_(0, indices, updates) tensor([[1., 2., 3.], [0., 0., 0.], [7., 8., 9.], [0., 0., 0.], [4., 5., 6.]]) And in tensorflow, you can do import tensorflow as tf tensor = tf.zeros([5,3]) indices = tf.constant([[0], [4], [2]]) updates = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=tf.float32) tensor = tf.tensor_scatter_nd_update(tensor, indices, updates) tensor.numpy() array([[1., 2., 3.], [0., 0., 0.], [7., 8., 9.], [0., 0., 0.], [4., 5., 6.]], dtype=float32)
https://stackoverflow.com/questions/67777344/
DQN Pytorch Loss keeps increasing
I am implementing simple DQN algorithm using pytorch, to solve the CartPole environment from gym. I have been debugging for a while now, and I cant figure out why the model is not learning. Observations: using SmoothL1Loss performs worse than MSEloss, but loss increases for both smaller LR in Adam does not work, I have tested using 0.0001, 0.00025, 0.0005 and default Notes: I have debugged various parts of the algorithm individually, and can say with good confidence that the issue is in the learn function. I am wondering if this bug is due to me misunderstanding detach in pytorch or some other framework mistake im making. I am trying to stick as close to the original paper as possible (linked above) References: example: GitHub gist example: pytroch official import torch as T import torch.nn as nn import torch.nn.functional as F import gym import numpy as np class ReplayBuffer: def __init__(self, mem_size, input_shape, output_shape): self.mem_counter = 0 self.mem_size = mem_size self.input_shape = input_shape self.actions = np.zeros(mem_size) self.states = np.zeros((mem_size, *input_shape)) self.states_ = np.zeros((mem_size, *input_shape)) self.rewards = np.zeros(mem_size) self.terminals = np.zeros(mem_size) def sample(self, batch_size): indices = np.random.choice(self.mem_size, batch_size) return self.actions[indices], self.states[indices], \ self.states_[indices], self.rewards[indices], \ self.terminals[indices] def store(self, action, state, state_, reward, terminal): index = self.mem_counter % self.mem_size self.actions[index] = action self.states[index] = state self.states_[index] = state_ self.rewards[index] = reward self.terminals[index] = terminal self.mem_counter += 1 class DeepQN(nn.Module): def __init__(self, input_shape, output_shape, hidden_layer_dims): super(DeepQN, self).__init__() self.input_shape = input_shape self.output_shape = output_shape layers = [] layers.append(nn.Linear(*input_shape, hidden_layer_dims[0])) for index, dim in enumerate(hidden_layer_dims[1:]): layers.append(nn.Linear(hidden_layer_dims[index], dim)) layers.append(nn.Linear(hidden_layer_dims[-1], *output_shape)) self.layers = nn.ModuleList(layers) self.loss = nn.MSELoss() self.optimizer = T.optim.Adam(self.parameters()) def forward(self, states): for layer in self.layers[:-1]: states = F.relu(layer(states)) return self.layers[-1](states) def learn(self, predictions, targets): self.optimizer.zero_grad() loss = self.loss(input=predictions, target=targets) loss.backward() self.optimizer.step() return loss class Agent: def __init__(self, epsilon, gamma, input_shape, output_shape): self.input_shape = input_shape self.output_shape = output_shape self.epsilon = epsilon self.gamma = gamma self.q_eval = DeepQN(input_shape, output_shape, [64]) self.memory = ReplayBuffer(10000, input_shape, output_shape) self.batch_size = 32 self.learn_step = 0 def move(self, state): if np.random.random() < self.epsilon: return np.random.choice(*self.output_shape) else: self.q_eval.eval() state = T.tensor([state]).float() action = self.q_eval(state).max(axis=1)[1] return action.item() def sample(self): actions, states, states_, rewards, terminals = \ self.memory.sample(self.batch_size) actions = T.tensor(actions).long() states = T.tensor(states).float() states_ = T.tensor(states_).float() rewards = T.tensor(rewards).view(self.batch_size).float() terminals = T.tensor(terminals).view(self.batch_size).long() return actions, states, states_, rewards, terminals def learn(self, state, action, state_, reward, done): self.memory.store(action, state, state_, reward, done) if self.memory.mem_counter < self.batch_size: return self.q_eval.train() self.learn_step += 1 actions, states, states_, rewards, terminals = self.sample() indices = np.arange(self.batch_size) q_eval = self.q_eval(states)[indices, actions] q_next = self.q_eval(states_).detach() q_target = rewards + self.gamma * q_next.max(axis=1)[0] * (1 - terminals) loss = self.q_eval.learn(q_eval, q_target) self.epsilon *= 0.9 if self.epsilon > 0.1 else 1.0 return loss.item() def learn(env, agent, episodes=500): print('Episode: Mean Reward: Last Loss: Mean Step') rewards = [] losses = [0] steps = [] num_episodes = episodes for episode in range(num_episodes): done = False state = env.reset() total_reward = 0 n_steps = 0 while not done: action = agent.move(state) state_, reward, done, _ = env.step(action) loss = agent.learn(state, action, state_, reward, done) state = state_ total_reward += reward n_steps += 1 if loss: losses.append(loss) rewards.append(total_reward) steps.append(n_steps) if episode % (episodes // 10) == 0 and episode != 0: print(f'{episode:5d} : {np.mean(rewards):5.2f} ' f': {np.mean(losses):5.2f}: {np.mean(steps):5.2f}') rewards = [] losses = [0] steps = [] print(f'{episode:5d} : {np.mean(rewards):5.2f} ' f': {np.mean(losses):5.2f}: {np.mean(steps):5.2f}') return losses, rewards if __name__ == '__main__': env = gym.make('CartPole-v1') agent = Agent(1.0, 1.0, env.observation_space.shape, [env.action_space.n]) learn(env, agent, 500)
The main problem I think is the discount factor, gamma. You are setting it to 1.0, which mean that you are giving the same weight to the future rewards as the current one. Usually in reinforcement learning we care more about the immediate reward than the future, so gamma should always be less than 1. Just to give it a try I set gamma = 0.99 and run your code: Episode: Mean Reward: Last Loss: Mean Step 100 : 34.80 : 0.34: 34.80 200 : 40.42 : 0.63: 40.42 300 : 65.58 : 1.78: 65.58 400 : 212.06 : 9.84: 212.06 500 : 407.79 : 19.49: 407.79 As you can see the loss still increases (even if not as much as before), but so does the reward. You should consider that loss here is not a good metric for the performance, because you have a moving target. You can reduce the instability of the target by using a target network. With additional parameter tuning and a target network one could probably make the loss even more stable. Also generally note that in reinforcement learning the loss value is not as important as it is in supervised; a decrease in loss does not always imply an improvement in performance, and vice versa. The problem is that the Q target is moving while the training steps happen; as the agent plays, predicting the correct sum of rewards gets extremely hard (e.g. more states and rewards explored means higher reward variance), so the loss increases. This is even clearer in more complex the environments (more states, variated rewards, etc). At the same time the Q network is getting better at approximating the Q values for each action, so the rewards (could) increase.
https://stackoverflow.com/questions/67789148/
How to discard a branch after training a pytorch model
I am trying to implement a FCN in pytorch with the overall structure as below: The code so far looks like below: class SNet(nn.Module): def __init__(self): super(SNet, self).__init__() self.enc_a = encoder(...) self.dec_a = decoder(...) self.enc_b = encoder(...) self.dec_b = decoder(...) def forward(self, x1, x2): x1 = self.enc_a(x1) x2 = self.enc_b(x2) x2 = self.dec_b(x2) x1 = self.dec_a(torch.cat((x1, x2), dim=-1) return x1, x2 In keras it is relatively easy to do this using the functional API. However, I could not find any concrete example / tutorial to do this in pytorch. How can I discard the dec_a (decoder part of autoencoder branch) after training? During joint training the loss will be sum (optionally weighted) of the loss from both the branch?
You can also define separate modes for your model for training and inference: class SNet(nn.Module): def __init__(self): super(SNet, self).__init__() self.enc_a = encoder(...) self.dec_a = decoder(...) self.enc_b = encoder(...) self.dec_b = decoder(...) self.training = True def forward(self, x1, x2): if self.training: x1 = self.enc_a(x1) x2 = self.enc_b(x2) x2 = self.dec_b(x2) x1 = self.dec_a(torch.cat((x1, x2), dim=-1) return x1, x2 else: x1 = self.enc_a(x1) x2 = self.enc_b(x2) x2 = self.dec_b(x2) return x2 These blocks are examples and may not do exactly what you want because I think there is a bit of ambiguity between how you define the training and inference operations in your block chart vs. your code, but in any case you get the idea of how you can use some modules only during training mode. Then you can just set this variable accordingly.
https://stackoverflow.com/questions/67789463/
how can I connect models in pytorch?
I made 2 classes: class Preprocess(): def __init ..... def forward .... class Model (): def __init ..... def forward I would like to do Preprocess before putting them into Model. Could you kindly tell me how can I achieve that ?
One could also use torch.nn.Sequential which has the following upsides: easier on the eyes one has to just pass the inputs instead of remembering to call Preprocess before it Code being: model = torch.nn.Sequential(Preprocess(), Model())
https://stackoverflow.com/questions/67793025/
Pytorch TypeError: forward() takes 2 positional arguments but 4 were given
from torch.nn.parameter import Parameter from torch.nn.modules.module import Module class Graphconvlayer(nn.Module): def __init__(self,adj,input_feature_neurons,output_neurons): super(Graphconvlayer, self).__init__() self.adj=adj self.input_feature_neurons=input_feature_neurons self.output_neurons=output_neurons self.weights=Parameter(torch.normal(mean=0.0,std=torch.ones(input_feature_neurons,output_neurons))) self.bias=Parameter(torch.normal(mean=0.0,std=torch.ones(input_feature_neurons))) def forward(self,inputfeaturedata): output1= torch.mm(self.adj,inputfeaturedata) print(output1.shape) print(self.weights.shape) print(self.bias.shape) output2= torch.matmul(output1,self.weights.t())+ self.bias return output2 class GCN(nn.Module): def __init__(self,lr,dropoutvalue,adjmatrix,inputneurons,hidden,outputneurons): super(GCN, self).__init__() self.lr=lr self.dropoutvalue=dropoutvalue self.adjmatrix=adjmatrix self.inputneurons=inputneurons self.hidden=hidden self.outputneurons=outputneurons self.gcn1 = Graphconvlayer(adjmatrix,inputneurons,hidden) self.gcn2 = Graphconvlayer(adjmatrix,hidden,outputneurons) def forward(self,x,adj): x= F.relu(self.gcn1(adj,x,64)) x= F.dropout(x,self.dropoutvalue) x= self.gcn2(adj,x,7) return F.log_softmax(x,dim=1) a=GCN(lr=0.001,dropoutvalue=0.5,adjmatrix=adj,inputneurons=features.shape[1],hidden=64,outputneurons=7) a.forward(adj,features) TypeError Traceback (most recent call last) <ipython-input-85-7d1a2a73ecad> in <module>() 37 38 a=GCN(lr=0.001,dropoutvalue=0.5,adjmatrix=adj,inputneurons=features.shape[1],hidden=64,outputneurons=7) ---> 39 a.forward(adj,features) 1 frames /usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs) 887 result = self.forward(*input, **kwargs) 888 for hook in itertools.chain( --> 889 _global_forward_hooks.values(), 890 self._forward_hooks.values()): 891 hook_result = hook(self, input, result) TypeError: forward() takes 2 positional arguments but 4 were given print(a) >>> GCN( (gcn1): Graphconvlayer() (gcn2): Graphconvlayer() ) This is a graph neural network. What I am trying to get is the output from the forward layer. I am not sure why I am getting the above error and what I should change for the code to work. Can anyone guide me through this? Also I am if I pass class graphconvlayer to class GCN, do I have to now separately pass each of it's parameters also to the object ä of class GCN?
Your GCN is composed of two Graphconvlayer. As defined in the code you posted, Graphconvlayer's forward method expects only one input argument: inputfeaturedata. However, when GCN calls self.gcn1 or self.gcn2 (in its forward method) it passes 3 arguments: self.gcn1(adj,x,64) and self.gcn2(adj,x,7). Hence, instead of a single input argument, self.gcn1 and self.gcn2 are receiving 3 -- this is the error you are getting.
https://stackoverflow.com/questions/67800090/
Cuda out of memory issue with pytorch when training two networks jointly
I try to train two DNN jointly, The model is trained and goes to the validation phase after every 5 epochs, the problem is after the 5 epochs it is okay and no problem with memory, but after 10 epochs the model complains about Cuda memory. Any help to solve the memory issue. class Trainer(BaseTrainer): def __init__(self, config, resume: bool, model, loss_function, optimizer, train_dataloader, validation_dataloader): super(Trainer, self).__init__(config, resume, model, loss_function, optimizer) self.train_data_loader = train_dataloader self.validation_data_loader = validation_dataloader self.model = self.model.double() def _train_epoch(self, epoch): #loss_total = 0.0 for i, (mixture, clean, name, label) in enumerate(self.train_data_loader): mixture = mixture.to(self.device, dtype=torch.double) clean = clean.to(self.device, dtype=torch.double) enhanced = self.model(mixture).to(self.device) front_loss = self.loss_function(clean, enhanced) front_loss.backward(retain_graph=True) torch.cuda.empty_cache() model_back.train() y = model_back(enhanced.double().to(device2)) back_loss = backend_loss(y[0], label[0].to(device2)) print("Iteration %d in epoch%d--> loss = %f" % (i, epoch, back_loss.item()), end='\r') #optimizer_back.zero_grad() back_loss.backward(retain_graph=True) self.optimizer.zero_grad() self.optimizer.step() #optimizer_back.step() torch.cuda.empty_cache() #loss_total += float(front_loss.item() + back_loss.item()) dl_len = len(self.train_data_loader) #self.writer.add_scalar(f"Train/Loss", loss_total / dl_len, epoch) @torch.no_grad() def _validation_epoch(self, epoch): #visualize_audio_limit = self.validation_custom_config["visualize_audio_limit"] #visualize_waveform_limit = self.validation_custom_config["visualize_waveform_limit"] #visualize_spectrogram_limit = self.validation_custom_config["visualize_spectrogram_limit"] sample_length = self.validation_custom_config["sample_length"] stoi_c_n = [] # clean and noisy stoi_c_e = [] # clean and enhanced stoi_e_n = [] pesq_c_n = [] pesq_c_e = [] pesq_e_n = [] correct = [] for i, (mixture, clean, name, label) in enumerate(self.validation_data_loader): #assert len(name) == 1, "Only support batch size is 1 in enhancement stage." name = name[0] padded_length = 0 mixture = mixture.to(self.device) if mixture.size(-1) % sample_length != 0: padded_length = sample_length - (mixture.size(-1) % sample_length) mixture = torch.cat([mixture, torch.zeros(1, 1, padded_length, device=self.device)], dim=-1) assert mixture.size(-1) % sample_length == 0 and mixture.dim() == 3 mixture_chunks = list(torch.split(mixture, sample_length, dim=-1)) enhanced_chunks = [] for chunk in mixture_chunks: enhanced_chunks.append(self.model(chunk.double()).detach().cpu()) enhanced = torch.cat(enhanced_chunks, dim=-1) # [1, 1, T] enhanced = enhanced.to(self.device) #print(enhanced) if padded_length != 0: enhanced = enhanced[:, :, :-padded_length] mixture = mixture[:, :, :-padded_length] torch.cuda.empty_cache() model_back.eval() y_pred = model_back(enhanced.double().to(self.device)) pred = torch.argmax(y_pred[0].detach().cpu(), dim=1) intent_pred = pred correct.append((intent_pred == label[0]).float()) torch.cuda.empty_cache() acc = np.mean(np.hstack(correct)) intent_acc = acc iter_acc = '\n iteration %d epoch %d -->' %(i, epoch) print(iter_acc, acc, best_accuracy) if intent_acc > best_accuracy: improved_accuracy = 'Current accuracy {}, {}'.format(intent_acc, best_accuracy) print(improved_accuracy) torch.save(model_back.state_dict(), '/home/mnabih/jt/best_model.pkl') Some solutions I have tried are to use a garbage collector tool (gc library) and to add torch.Cuda.empty_cache() randomly in the training and validation.
Don't use retain_graph = True on the second backwards pass. This flag is making your code store the computation graphs for each batch, conceivably in perpetuity. You should only use retain_graph for all but the last call to backward() that back-propagate through the same variables/parameters.
https://stackoverflow.com/questions/67800627/
fastaiv2 to pytorch for torchserver
I usually use fastai (v2 or v1) for fast prototyping. Now I'd like to deploy one of my models, trained with fastai, to torchserver. Let's say that we have a simple model like this one: learn = cnn_learner(data, models.resnet34, metrics=[accuracy, error_rate, score]) # after the training torch.save(learn.model.state_dict(), "./test1.pth") state = torch.load("./test1.pth") model_torch_rep = models.resnet34() model_torch_rep.load_state_dict(state) I've tried many different things with the same result RuntimeError Traceback (most recent call last) <ipython-input-284-e4dbdce23d43> in <module> ----> 1 model_torch_rep.load_state_dict(state); /opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in load_state_dict(self, state_dict, strict) 837 if len(error_msgs) > 0: 838 raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format( --> 839 self.__class__.__name__, "\n\t".join(error_msgs))) 840 return _IncompatibleKeys(missing_keys, unexpected_keys) 841 RuntimeError: Error(s) in loading state_dict for ResNet: Missing key(s) in state_dict: "conv1.weight", "bn1.weight", "bn1.bias", "bn1.running_mean", "bn1.running_var", "layer1.0.conv1.weight", "layer1.0.bn1.weight" This is happening with fastai 1.0.6 or fastai 2.3.1 + pytorch 1.8.1 ...
Just figured this out. For some reason the way you save the state_dict adds a string "module." to each key in the loaded state_dict. (This is because you aren't using Learner class from FastAI to save the model, I assume). Simply remove the "module." substring from the state_dict and you're all good. learn = cnn_learner(data, models.resnet34, metrics=[accuracy, error_rate, score]) # after the training torch.save(learn.model.state_dict(), "./test1.pth") state = torch.load("./test1.pth") # fix dict keys new_state = OrderedDict([(k.partition('module.')[2], v) for k, v in state.items()]) model_torch_rep = models.resnet34() model_torch_rep.load_state_dict(new_state)
https://stackoverflow.com/questions/67804598/
Why does my convolutional model does not learn?
I am currently working on building a CNN for sound classification. The problem is relatively simple: I need my model to detect whether there is human speech on an audio record. I made a train / test set containing records of 3 seconds on which there is human speech (speech) or not (no_speech). From these 3 seconds fragments I get a mel-spectrogram of dimension 128 x 128 that is used to feed the model. Since it is a simple binary problem I thought the a CNN would easily detect human speech but I may have been too cocky. However, it seems that after 1 or 2 epoch the model doesn’t learn anymore, i.e. the loss doesn’t decrease as if the weights do not update and the number of correct prediction stays roughly the same. I tried to play with the hyperparameters but the problem is still the same. I tried a learning rate of 0.1, 0.01 … until 1e-7. I also tried to use a more complex model but the same occur. Then I thought it could be due to the script itself but I cannot find anything wrong: the loss is computed, the gradients are then computed with backward() and the weights should be updated. I would be glad you could have a quick look at the script and let me know what could go wrong! If you have other ideas of why this problem may occur I would also be glad to receive some advice on how to best train my CNN. I based the script on the LunaTrainingApp from “Deep learning in PyTorch” by Stevens as I found the script to be elegant. Of course I modified it to match my problem, I added a way to compute the precision and recall and some other custom metrics such as the % of correct predictions. Here is the script: import torch import torch.nn as nn import argparse import numpy as np import logging logging.basicConfig(level = logging.INFO) log = logging.getLogger(__name__) from torch.optim import SGD from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DataLoader from sklearn.metrics import confusion_matrix from dataset_loader.audiodataset import AudioDataset from models.vadnet import VADNet from utils.earlystopping import EarlyStopping class VADTrainingApp: def __init__(self, sys_argv=None): parser = argparse.ArgumentParser() parser.add_argument("--train_path", help='Path to the training set', required=True, type=str, ) parser.add_argument("--test_path", help='Path to the testing set', required=True, type=str, ) parser.add_argument("--save_path", help='Path to saving the model', required=True, type=str, ) parser.add_argument("--save_es", help='Save the checkpoints of early stopping call', default="checkpoint.pt", type=str, ) parser.add_argument('--num-workers', help='Number of worker processes for background data loading', default=8, type=int, ) parser.add_argument("--batch_size", help='Batch size to use for training', default=32, type=int,) parser.add_argument('--epochs', help='Number of epochs to train for', default=50, type=int, ) parser.add_argument('--lr', help='Learning rate for th stochastic gradient descent', default=0.001, type=float, ) self.cli_args = parser.parse_args(sys_argv) # related to the hardware self.use_cuda = torch.cuda.is_available() self.device = torch.device("cuda" if self.use_cuda else "cpu") # directly related to the neural network self.model = self.initModel() self.optimizer = self.initOptimizer() # For early stopping self.patience = 7 # For metrics self.METRICS_LABELS_NDX = 0 self.METRICS_PREDS_NDX = 1 self.METRICS_LOSS_NDX = 2 self.METRICS_SIZE = 3 def initModel(self): """Initialize the model, if GPU available computation done there""" model = VADNet() model = model.double() if self.use_cuda: log.info("Using CUDA; {} devices".format(torch.cuda.device_count())) if torch.cuda.device_count() > 1: model = nn.DataParallel(model) model = model.to(self.device) return model def initOptimizer(self): return SGD(self.model.parameters(), lr=self.cli_args.lr)#, momentum=0.8, weight_decay=0.01) def adjust_learning_rate(self): """Sets the learning rate to the initial LR decayed by a factor of 10 every 20 epochs""" self.cli_args.lr = self.cli_args.lr * (0.1 ** (self.cli_args.epochs // 20)) for param_group in self.optimizer.param_groups: param_group['lr'] = self.cli_args.lr def initTrainDL(self): trainingset = AudioDataset(self.cli_args.train_path, n_fft=1024, hop_length=376, n_mels=128) batch_size = self.cli_args.batch_size if self.use_cuda: batch_size *= torch.cuda.device_count() trainLoader = DataLoader(trainingset, batch_size = batch_size, shuffle=True, num_workers=self.cli_args.num_workers, pin_memory=self.use_cuda) return trainLoader def initTestDL(self): testset = AudioDataset(self.cli_args.test_path, n_fft=1024, hop_length=376, n_mels=128) batch_size = self.cli_args.batch_size if self.use_cuda: batch_size *= torch.cuda.device_count() testLoader = DataLoader(testset, batch_size = batch_size, shuffle=True, num_workers=self.cli_args.num_workers, pin_memory=self.use_cuda) return testLoader def main(self): log.info("Start training, {}".format(self.cli_args)) train_dl = self.initTrainDL() test_dl = self.initTestDL() trn_writer = SummaryWriter(log_dir='runs' + '-trn') val_writer = SummaryWriter(log_dir='runs' + '-val') early_stopping = EarlyStopping(patience=self.patience, path=self.cli_args.save_es, verbose=True) for epoch_ndx in range(1, self.cli_args.epochs + 1): log.info("Epoch {} / {}".format(epoch_ndx, self.cli_args.epochs)) # Adjust the new learning rate self.adjust_learning_rate() # Train the model's parameters metrics_t = self.do_training(train_dl) self.logMetrics(metrics_t, trn_writer, epoch_ndx) # Test the model metrics_v = self.do_val(test_dl, val_writer) self.logMetrics(metrics_v, val_writer, epoch_ndx, train=False) # Add the mean loss of the val for the epoch early_stopping(metrics_v[self.METRICS_LOSS_NDX].mean(), self.model) if early_stopping.early_stop: print("Early stopping") break # Save the model once all epochs have been completed torch.save(self.model.state_dict(), self.cli_args.save_path) def do_training(self, train_dl): """Training loop""" self.model.train() # Initiate a 3 dimension tensor to store loss, labels and prediction trn_metrics = torch.zeros(self.METRICS_SIZE, len(train_dl.dataset), device=self.device) for batch_ndx, batch_tup in enumerate(train_dl): if batch_ndx%100==0: log.info("TRAINING --> Batch {} / {}".format(batch_ndx, len(train_dl))) self.optimizer.zero_grad() loss = self.ComputeBatchLoss(batch_ndx, batch_tup, self.cli_args.batch_size, trn_metrics) loss.backward() self.optimizer.step() return trn_metrics.to('cpu') def do_val(self, test_dl, early_stop): """Validation loop""" with torch.no_grad(): self.model.eval() val_metrics = torch.zeros(self.METRICS_SIZE, len(test_dl.dataset), device=self.device) for batch_ndx, batch_tup in enumerate(test_dl): if batch_ndx%100==0: log.info("VAL --> Batch {} / {}".format(batch_ndx, len(test_dl))) loss = self.ComputeBatchLoss(batch_ndx, batch_tup, self.cli_args.batch_size, val_metrics) return val_metrics.to('cpu') def ComputeBatchLoss(self, batch_ndx, batch_tup, batch_size, metrics_mat): """ Return a tensor the loss of the batch """ imgs, labels = batch_tup imgs = imgs.to(device=self.device, non_blocking=True) labels = labels.to(device=self.device, non_blocking=True) outputs = self.model(imgs) _, predicted = torch.max(outputs, dim=1) loss_func = nn.CrossEntropyLoss(reduction="none") loss = loss_func(outputs, labels) start_ndx = batch_ndx * self.cli_args.batch_size end_ndx = start_ndx + labels.size(0) metrics_mat[self.METRICS_LABELS_NDX, start_ndx:end_ndx] = labels.detach() metrics_mat[self.METRICS_PREDS_NDX, start_ndx:end_ndx] = predicted.detach() metrics_mat[self.METRICS_LOSS_NDX, start_ndx:end_ndx] = loss.detach() return loss.mean() def logMetrics(self, metrics_mat, writer, epoch_ndx, train=True): """ Function to compute custom metrics: accurracy and recall for both classes and % of correct predictions. Log the metrics in a tensorboard writer """ # Confusion matrix to compute precision / recall for each class tn, fp, fn, tp = torch.tensor(confusion_matrix(metrics_mat[self.METRICS_LABELS_NDX], metrics_mat[self.METRICS_PREDS_NDX], labels=[0,1]).ravel()) precision_no_speech = tp / (tp + fp) recall_no_speech = tp / (tp + fn) # class speech is labelled 0, so true positive = true negative for speech precision_speech = tn / (tn + fn) recall_speech = tn / (fp + tn) # % of correct predictions - optional metrics that are nice no_speech_count = (metrics_mat[self.METRICS_LABELS_NDX] == 0).sum() speech_count = (metrics_mat[self.METRICS_LABELS_NDX] == 1).sum() no_speech_correct = ((metrics_mat[self.METRICS_PREDS_NDX] == 0) & (metrics_mat[self.METRICS_LABELS_NDX] == 0)).sum() speech_correct = ((metrics_mat[self.METRICS_PREDS_NDX] == 1) & (metrics_mat[self.METRICS_LABELS_NDX] == 1)).sum() correct_all = (speech_correct + no_speech_correct) / float(speech_count + no_speech_count) * 100 correct_speech = speech_correct / float(speech_count) * 100 correct_no_speech = no_speech_correct / float(no_speech_count) * 100 loss = metrics_mat[self.METRICS_LOSS_NDX].mean() writer.add_scalar("loss", loss, epoch_ndx) writer.add_scalar("precision/no_speech", precision_no_speech, epoch_ndx) writer.add_scalar("recall/no_speech", recall_no_speech, epoch_ndx) writer.add_scalar("precision/speech", precision_speech, epoch_ndx) writer.add_scalar("recall/speech", recall_speech, epoch_ndx) writer.add_scalar("correct/all", correct_all, epoch_ndx) writer.add_scalar("correct/speech", correct_speech, epoch_ndx) writer.add_scalar("correct/no_speech", correct_no_speech, epoch_ndx) if train: log.info("[TRAINING] loss: {}, correct/all: {}% , correct/speech: {}%, correct/no_speech: {}%".format(loss, correct_all, correct_speech, correct_no_speech)) else: log.info("[VAL] loss: {}, correct/all: {}% , correct/speech: {}%, correct/no_speech: {}%".format(loss, correct_all, correct_speech, correct_no_speech)) if __name__ == "__main__": VADTrainingApp().main() Regarding the model I am using a simple CNN: import torch import torch.nn as nn import torch.nn.functional as F import math class VADNet(nn.Module): def __init__(self, in_channels=1, conv_channels=8): super().__init__() self.tail_batchnorm = nn.BatchNorm2d(1) self.block1 = ConvBlock(in_channels, conv_channels) self.block2 = ConvBlock(conv_channels, conv_channels * 2) self.block3 = ConvBlock(conv_channels * 2, conv_channels * 4) self.block4 = ConvBlock(conv_channels * 4, conv_channels * 8) self.head_linear = nn.Linear(8 * 8 * conv_channels * 8, 2) self._init_weights() def _init_weights(self): for m in self.modules(): if type(m) in { nn.Linear, nn.Conv3d, nn.Conv2d, nn.ConvTranspose2d, nn.ConvTranspose3d, }: nn.init.kaiming_normal_( m.weight.data, a=0, mode='fan_out', nonlinearity='relu', ) if m.bias is not None: fan_in, fan_out = \ nn.init._calculate_fan_in_and_fan_out(m.weight.data) bound = 1 / math.sqrt(fan_out) nn.init.normal_(m.bias, -bound, bound) def forward(self, input_batch): bn_output = self.tail_batchnorm(input_batch) block_out = self.block1(bn_output) block_out = self.block2(block_out) block_out = self.block3(block_out) block_out = self.block4(block_out) conv_flat = block_out.view(block_out.size(0),-1) linear_output = self.head_linear(conv_flat) return linear_output class ConvBlock(nn.Module): def __init__(self, in_channels, conv_channels): super().__init__() self.conv1 = nn.Conv2d( in_channels, conv_channels, kernel_size=3, padding=1, bias=True, ) self.relu1 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d( conv_channels, conv_channels, kernel_size=3, padding=1, bias=True, ) self.relu2 = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(2, 2) def forward(self, input_batch): block_out = self.conv1(input_batch) block_out = self.relu1(block_out) block_out = self.conv2(block_out) block_out = self.relu2(block_out) return self.maxpool(block_out) Thank you in advance for your help!
You are applying 2D 3x3 convolutions to spectrograms. Read it once more and let it sink. Do you understand now what is the problem? A convolution layer learns a static/fixed local patterns and tries to match it everywhere in the input. This is very cool and handy for images where you want to be equivariant to translation and where all pixels have the same "meaning". However, in spectrograms, different locations have different meanings - pixels at the top part of the spectrograms mean high frequencies while the lower indicates low frequencies. Therefore, if you have matched some local pattern to a local region in the spectrogram, it may mean a completely different thing if it is matched to the upper or lower part of the spectrogram. You need a different kind of model to process spectrograms. Maybe convert the spectrogram to a 1D signal with 128 channels (frequencies) and apply 1D convolutions to it?
https://stackoverflow.com/questions/67804707/
ValueError: not enough values to unpack (expected 3, got 2) in Pytorch
this is my Define validate function when I load the model and start prediction using this code I have received the error using PyTorch.and after this, I am iterating through the epoch loop and batch loop and I landed with this error. def validate_epoch(net, val_loader,loss_type='CE'): net.train(False) running_loss = 0.0 sm = nn.Softmax(dim=1) truth = [] preds = [] bar = tqdm(total=len(val_loader), desc='Processing', ncols=90) names_all = [] n_batches = len(val_loader) for i, (batch, targets, names) in enumerate(val_loader): if loss_type == 'CE': labels = Variable(targets.float()) inputs = Variable(batch) elif loss_type == 'MSE': labels = Variable(targets.float()) inputs = Variable(batch) outputs = net(inputs) labels = labels.long() loss = criterion(outputs, labels) if loss_type =='CE': probs = sm(outputs).data.cpu().numpy() elif loss_type =='MSE': probs = outputs probs[probs < 0] = 0 probs[probs > 4] = 4 probs = probs.view(1,-1).squeeze(0).round().data.cpu().numpy() preds.append(probs) truth.append(targets.cpu().numpy()) names_all.extend(names) running_loss += loss.item() bar.update(1) gc.collect() gc.collect() bar.close() if loss_type =='CE': preds = np.vstack(preds) else: preds = np.hstack(preds) truth = np.hstack(truth) return running_loss / n_batches, preds, truth, names_all And this is the main function where I call validate function get the error when model is loaded and start prediction on the test loader criterion = nn.CrossEntropyLoss() model.eval() test_losses = [] test_mse = [] test_kappa = [] test_acc = [] test_started = time.time() test_loss, probs, truth, file_names = validate_epoch(model, test_iterator) as you can see in traceback error it gives some Terminal shows error: ValueError Traceback (most recent call last) <ipython-input-27-d2b4a1ca3852> in <module> 12 test_started = time.time() 13 ---> 14 test_loss, probs, truth, file_names = validate_epoch(model, test_iterator) 15 preds = probs.argmax(1) 16 <ipython-input-25-34e29e0ff6ed> in validate_epoch(net, val_loader, loss_type) 9 names_all = [] 10 n_batches = len(val_loader) ---> 11 for i, (batch, targets, names) in enumerate(val_loader): 12 if loss_type == 'CE': 13 labels = Variable(targets.float()) ValueError: not enough values to unpack (expected 3, got 2)
From torchvision.datasets.ImageFolder documentation: "Returns: (sample, target) where target is class_index of the target class." So, quite simply, the dataset object you're currently using returns a tuple with 2 items. You'll get an error if you try to store this tuple in 3 variables. The correct line would be: for i, (batch, targets) in enumerate(val_loader): If you really need the names (which I assume is the file path for each image) you can define a new dataset object that inherits from the ImageFolder dataset and overload the __getitem__ function to also return this information.
https://stackoverflow.com/questions/67815772/
I want to train the CSRNet model on UCF_CC_50 dataset which has total number of images 50. and face a problem like
I want to train the CSRNet model on UCF_CC_50 dataset but occurring this problem KeyError Traceback (most recent call last) <ipython-input-11-78e054690de5> in <module> 4 img= plt.imread(img_path) 5 k = np.zeros((img.shape[0],img.shape[1])) ***----> 6 gt = mat["image_info"][0,0][0,0][0]*** 7 for i in range(0,len(gt)): 8 if int(gt[i][1])<img.shape[0] and int(gt[i][0])<img.shape[1]: **KeyError: 'image_info'** ---------- enter for img_path in img_paths: print (img_path) mat = io.loadmat(img_path.replace('.jpg','.mat').replace('images','ground_truth').replace('IMG_','GT_IMG_')) img= plt.imread(img_path) k = np.zeros((img.shape[0],img.shape[1])) gt = mat["image_info"][0,0][0,0][0] for i in range(0,len(gt)): if int(gt[i][1])<img.shape[0] and int(gt[i][0])<img.shape[1]: k[int(gt[i][1]),int(gt[i][0])]=1 k = gaussian_filter_density(k) with h5py.File(img_path.replace('.jpg','.h5').replace('images','groundtruth'), 'w') as hf: hf['density'] = kcode here --------- The file path is C:\Users\Gigabyte pc\Desktop\COUNTING\CSRNet-pytorch-master\UCF_CC_50\part_A_final/train_data\images\IMG_1.jpg
Your code does not comply with the structure of the annotation file you are trying to read. Annotations in UCF-50 CC dataset can simply be read by getting the values of the key "annPoints". You could apply the following changes to your code to read the x and y coordinates of pointwise human-head annotations: 4 img= plt.imread(img_path) 5 k = np.zeros((img.shape[0],img.shape[1])) 6 gt = mat["annPoints"] 7 for i in range(0,len(gt)):
https://stackoverflow.com/questions/67815809/
Enforce pad_sequence to a certain length
I have a set of tensors that I'm padding with pad_sequence but I need to guarantee a fixed length for them. I can't do it right now as pad_sequence will extend the shorter tensors up to the longest, if that longest tensor doesn't reach the length I want them I'm screwed. I thought a solution could be adding zeros to one of the tensors to padd up to the length I want so the result of that padding will have my desired length. I don't know how to do it So lets say I have a tensor with shape torch.Size([44]) and a desired length 50, how can I add zeros to it to reach a shape of torch.Size([50])? This needs to hold regardless of the initial tensor shape.
You can achieve your logic like so: from torch.nn.utils.rnn import pad_sequence # Desired max length max_len = 50 # 100 seqs of variable length (< max_len) seq_lens = torch.randint(low=10,high=44,size=(100,)) seqs = [torch.rand(n) for n in seq_lens] # pad first seq to desired length seqs[0] = nn.ConstantPad1d((0, max_len - seqs[0].shape[0]), 0)(seqs[0]) # pad all seqs to desired length seqs = pad_sequence(seqs)
https://stackoverflow.com/questions/67819858/
convert State integers to onehotvector
I have a function that I use to convert two states into a one-hot vector and combine it all, and it works fine, but if I have a large L, for example, 3000, it will take time. The function works like this with L=3. def OH3(x,end=2,len=3): x = T.LongTensor([[x]]) end = T.LongTensor([[end]]) one_hot_x = T.FloatTensor(len,l) one_hot_end = T.FloatTensor(len,l) first=one_hot_x.zero_().scatter_(1,x,1) second=one_hot_end.zero_().scatter_(1,end,1) vector=T.cat((one_hot_x,one_hot_end),dim=1) return vector the output: OH3(1) tensor([[0., 1., 0., 0., 0., 1.]]) as I mentioned, the function works fine but slower for a large number of states, and I sent multiple states at once, like 500 states, it will take 4 second Is there a faster way to do it?
Provided the assumptions made in the comments above are correct, this should be about as fast as you can get it done, one allocation of a new array and 2 assignment operations. Let me know if I'm missing something. def OH3(x,end=2,len=3): vector = torch.zeros(2*len,dtype = int) vector[[x,len+end] = 1 return vector
https://stackoverflow.com/questions/67820762/
Is it possible to run multiple CUDA version on windows?
I am doing an experiment on a chest x-ray Project. and I want multiple versions of the CUDA toolkit but the problem is that my system put the latest version which I installed lastly is appearing. Is it possible to run any of CUDA like 9.0, 10.2, 11.0 as required to GitHub code? I have done all the initial steps like path added to an environment variable and added CUDNN copied file and added to the environment. Now the problem is that I want to use Cuda 9.0 as per my code but my default setting put cuda.11.0 what is the solution or script to switch easily between these version
You may set CUDA_PATH_V9_0, CUDA_PATH_V10_0, etc properly, then set CUDA_PATH to any one of them (e.g. CUDA_PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0). Then in your VS project, set your cuda library path using the CUDA_PATH (e.g. $CUDA_PATH\lib). To switch, just set the CUDA_PATH to another version, and clean & rebuild your VS project(s).
https://stackoverflow.com/questions/67821588/
Using 3-channel (RGB) PyTorch model for classification 4-channel (RGBY) images
I have labeled dataset with 4-channel images (RGBY). I want to use pretrained classification model (using pytorch and ResNet50 as a model). All of pytorch models for 3 channels though. So, the question is: How can I use 3-channel pretrained models for 4-channels data? I'm loading the model next way: import torchvision.models as models resnet50 = models.resnet50(pretrained=True)
You can modify the first layer of the CNN such that it expects 4 input channels instead of 3. In your case, the first layer is resnet50.conv1. So: import torchvision.models as models resnet50 = models.resnet50(pretrained=True) # modify first layer so it expects 4 input channels; all other parameters unchanged resnet50.conv1 = torch.nn.Conv2d(4,64,kernel_size = (7,7),stride = (2,2), padding = (3,3), bias = False) # test inp = torch.rand([1,4,512,512]) resnet50.eval() resnet50.training = False out = resnet50(inp) # should evaluate without error The simplicity of this change is made possible by the following implementation detail: For a 2D convolution (also true for other dimensional convolutions), pytorch convolves one kernel for each desired output plane (feature map) with each input plane. This results in n_input_planes x n_output_planes total feature maps (in this case 4 and 64, respectively). Pytorch then sums across all input planes for each output plane, yielding a total of n_output_planes planes regardless of the number of input planes. The good news is that this means you can add additional input planes (maps) with no modification of the network past the first layer. The (perhaps in some cases) unfavorable part of this is that all of your input feature maps are treated identically and the information from each is fully incorporated by the end of the first convolution. In some cases it might be desirable to treat the input feature maps differently at the beginning, in which case you'd need to define two separate CNN branches so that the features were not added together at each layer.
https://stackoverflow.com/questions/67821830/
PyTorch preserving gradient using external libraries
I have a GAN that returns a predicted torch.tensor. To guide this network, I have a loss function which is a summation of binary cross entropy loss (BCELoss) and Wasserstein distance. However, in order to calculate Wasserstein distance, I am using scipy.stats.wasserstein_distance function from SciPy library. As you might know, this function requires two NumPy arrays as input. So, to use this function, I am converting my predicted tensor and ground-truth tensor to NumPy arrays as follows pred_np = pred_tensor.detach().cpu().clone().numpy().ravel() target_np = target_tensor.detach().cpu().clone().numpy().ravel() W_loss = wasserstein_distance(pred_np, target_np) Then, total loss is obtained by adding W_loss to BCELoss. I am now showing this part because it is a bit unnecessary and not related to my question. My concern is I am detaching gradient so I suppose that while optimizing and updating model parameters it will not consider W_loss. I am a bit newbie so I hope my question is clear and appreciate for answers in advance.
Adding an object that is not a tensor that requires_grad to your loss is essentially adding a constant. The derivative of a constant is zero, so this added term is not doing anything to your network's weights. tl;dr: You need to rewrite the loss computation in pytorch (or just find an existing implementation, there's numerous on the internets).
https://stackoverflow.com/questions/67825139/
How to get argmax for indices in a matrix/tensor?
Is there any way to perform a top-k operation on a matrix or tensor so that the relevant indices are returned? For example: >>> import torch >>> matrix = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> print(matrix) tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> indices = max_index_function(matrix) >>> print(indices) tensor([2, 2]) Something like this. If I use torch.argmax it's a little tricky to get what I want. I want to be able to effectively return the indices because I want to extend an argmax to a top-k function as well. Right now I have something like this: >>> column_max_idx = torch.unique(torch.argmax(matrix, dim=0)) >>> row_max_idx = torch.unique(torch.argmax(matrix, dim=1)) >>> idx_pairs = torch.cartesian_prod(column_max_idx, row_max_idx) It does what I want but I'm sure there's a better way. Thanks! Edit Another thing I've tried is using two for loops and sorting, but I also am wondering if there's a function I could use without loops. >>> idxs_and_values = [] >>> for col_idx, col_element in enumerate(matrix): ... for row_idx, row_element in enumerate(col_element): ... idxs_and_values.append(((col_idx, row_idx), row_element.item()) >>> sorted(idxs_and_values, key=lambda x: x[-1], reverse=True) [((2, 2), 9), ((2, 1), 8), ((2, 0), 7), ((1, 2), 6), ((1, 1), 5), \ ((1, 0), 4), ((0, 2), 3), ((0, 1), 2), ((0, 0), 1)]
how about topk? import torch matrix = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) values, indices = matrix.flatten().topk(k=3) print(values) # tensor([9, 8, 7]) print(indices) # tensor([8, 7, 6]) Note that the indices are now pointing to the flattened vector. You can recover the original d-dimensional indexing with numpy's unravel_index: indices = [np.unravel_index(i, matrix.shape) for i in indices] print(indices) # [(2, 2), (2, 1), (2, 0)] Nicely wrapped in a function for any tensor order: from torch import Tensor from numpy import unravel_index def mytopk(x: Tensor, k: int) -> list[tuple[int,...]]: values, indices = x.flatten().topk(k) return [unravel_index(i, x.shape) for i in indices]
https://stackoverflow.com/questions/67833218/
Child process hangs when performing inference with PyTorch model
I have a PyTorch model (class Net), together with its saved weights / state dict (net.pth), and I want to perform inference in a multiprocessing environment. I noticed that I cannot simply create a model instance, load the weights, then share the model with a child process (though I'd have assumed this is possible due to copy-on-write). What happens is that the child hangs on y = model(x), and finally the whole program hangs (due to parent's waitpid). The following is a minimal reproducible example: def handler(): with torch.no_grad(): x = torch.rand(1, 3, 32, 32) y = model(x) return y model = Net() model.load_state_dict(torch.load("./net.pth")) pid = os.fork() if pid == 0: # this doesn't get printed as handler() hangs for the child process print('child:', handler()) else: # everything is fine here print('parent:', handler()) os.waitpid(pid, 0) If the model loading is done independently for parent & child, i.e. no sharing, then everything works as expected. I have also tried calling share_memory_ on model's tensors, but to no avail. Am I doing something obviously wrong here?
Seems that sharing the state dict and performing the loading operation in each process solves the problem: LOADED = False def handler(): global LOADED if not LOADED: # each process loads state independently model.load_state_dict(state) LOADED = True with torch.no_grad(): x = torch.rand(1, 3, 32, 32) y = model(x) return y model = Net() # share the state rather than loading the state dict in parent # model.load_state_dict(torch.load("./net.pth")) state = torch.load("./net.pth") pid = os.fork() if pid == 0: print('child:', handler()) else: print('parent:', handler()) os.waitpid(pid, 0)
https://stackoverflow.com/questions/67836858/
Why this PyTorch regression program reaches zero loss with periodic oscillations?
There is one x and one t with with dimensions 3x1. I am trying to find the w (3x3) and b (3,1) so they can please this equation: t = w*x + b The program below does oscillate. I tried to debug it with no success. Can someone else take a look? What did I miss? class fit(): def __init__(self, w, b): self.w = w self.b = b def forward(self, x): return torch.mm(self.w, x) + self.b w = torch.tensor([[1., 1.1, 1.2], [1., 1.1, 1.2], [1., 1.1, 1.2]], requires_grad=True) b = torch.tensor([[10.], [11.], [12.]], requires_grad=True) x = torch.tensor([[1.], [2.], [3.]], requires_grad=False) t = torch.tensor([[0.], [0.9], [0.1]], requires_grad=False) model = fit(w, b) alpha = 0.001 loss = [] arange = np.arange(200) for i in arange: z = model.forward(x) l = (z - t)**2 l = l.sum() loss.append(l) l.backward() model.w.data = model.w.data - alpha * model.w.grad model.b.data = model.b.data - alpha * model.b.grad plt.plot(arange, loss) If I use the other tools (torch.nn.Linear, torch.optim.sgd, torch.nn.smeloss) from PyTorch everything goes as expected.
You need to reset the gradient to 0 after each backprop. By default, pytorch accumulates gradients when you call loss.backward(). Replacing the last 2 instructions of your loop with the following lines should fix the issue : with torch.no_grad(): model.w.data = model.w.data - alpha * model.w.grad model.b.data = model.b.data - alpha * model.b.grad model.w.grad.zero_() model.b.grad.zero_()
https://stackoverflow.com/questions/67837239/
PyTorch NN does not learn or learns poorly
I'm working with PyTorch tutorial, slightly modified to use Titanic dataset. I'm using very simple network of Linear(Dense) with ReLU... I'd like to predict survival status based on age, fare and sex for example. I experienced a strange behavior with a simple neural network (I'm experimenting on Google Colab). Sometimes when I execute training, the accuracy doesn't change at all. It's strange because I'm recreating the model... Accuracy: 59.4%, Avg loss: 0.693147 [...50 or more lines like this...] Accuracy: 59.4%, Avg loss: 0.693147 Sometimes the accuracy is slowly increasing from 60% to 80%. The other thing is, the accuracy is very low (varies from 60-80%), despite the fact I'm validating with... the very same training set! I've tried several different combinations of learning rate, batch size and epochs count and also number of neurons, but it still behaves very... unpredictably and weak. Could you point me why sometimes the network doesn't learn at all? And if I rerun it a few times it starts learning somehow. And what should be done to this network to improve it? This is my Python notebook: https://colab.research.google.com/drive/1-50BTqnMgiz_dozv1DjXS9advD1Rxd-B?usp=sharing Thanks in advance!
As this is a classification problem, your neural network's last layer should not have a relu activation function. Code Snippet: class NeuralNetwork(nn.Module): def __init__(self): super(NeuralNetwork, self).__init__() self.fun = nn.Sequential( nn.Linear(3, 32), nn.ReLU(), nn.Linear(32, 1) ) def forward(self, x): return self.fun(x)
https://stackoverflow.com/questions/67840919/
Division in batches of a 3D tensor (Pytorch)
I have a 3D tensor of size say 100x5x2 and mean of the tensor across axis=1 which gives shape 100x2. 100 here is the batch size. Normally without batch, the division of tensor of shape 5x2 and 2 works perfectly but in the case of the 3D tensor with batch, I’m receiving error. a = torch.rand(5,2) b = torch.rand(2) z=a/b gives me expected answer. a = torch.rand(100,5,2) b = torch.rand(100,2) z=a/b Gives me the following error. The size of tensor a (5) must match the size of tensor b (100) at non-singleton dimension 1. How to divide these tensors such that my output is of shape 100x5x2 ? Something like bmm for division?
Simply do: z = a / b.unsqueeze(1) This adds an extra dimension in b and makes it of shape (100, 1, 2) which is compatible for broadcasting with a.
https://stackoverflow.com/questions/67844575/
IndexError: Target 1 is out of bounds
When I run the program below, it gives me an error. The problem seems to be in the loss function but I can't find it. I have read the Pytorch Documentation for nn.CrossEntropyLoss but still can't find the problem. Image size is (1 x 256 x 256), Batch size is 1 I am new to PyTorch, thanks. import torch import torch.nn as nn from PIL import Image import numpy as np torch.manual_seed(0) x = np.array(Image.open("cat.jpg")) x = np.expand_dims(x, axis = 0) x = np.expand_dims(x, axis = 0) x = torch.from_numpy(x) x = x.type(torch.FloatTensor) # shape = (1, 1, 256, 256) def Conv(in_channels, out_channels, kernel=3, stride=1, padding=0): return nn.Conv2d(in_channels, out_channels, kernel, stride, padding) class model(nn.Module): def __init__(self): super(model, self).__init__() self.sequential = nn.Sequential( Conv(1, 3), Conv(3, 5), nn.Flatten(), nn.Linear(317520, 1), nn.Sigmoid() ) def forward(self, x): y = self.sequential(x) return y def compute_loss(y_hat, y): return nn.CrossEntropyLoss()(y_hat, y) model = model() y_hat = model(x) loss = compute_loss(y_hat, torch.tensor([1])) Error: Traceback (most recent call last): File "D:/Me/AI/Models/test.py", line 38, in <module> **loss = compute_loss(y, torch.tensor([1]))** File "D:/Me/AI/Models/test.py", line 33, in compute_loss return nn.CrossEntropyLoss()(y_hat, y) File "D:\Softwares\Anaconda\envs\deeplearning\lib\site-packages\torch\nn\modules\module.py", line 1054, in _call_impl return forward_call(*input, **kwargs) File "D:\Softwares\Anaconda\envs\deeplearning\lib\site-packages\torch\nn\modules\loss.py", line 1120, in forward return F.cross_entropy(input, target, weight=self.weight, File "D:\Softwares\Anaconda\envs\deeplearning\lib\site-packages\torch\nn\functional.py", line 2824, in cross_entropy return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index) **IndexError: Target 1 is out of bounds.** Process finished with exit code 1
This looks like a binary classifier model: cat or not cat. But you are using CrossEntropyLoss which is used when you have more than 2 target classes. So what you should use is Binary Cross Entropy Loss. def compute_loss(y_hat, y): return nn.BCELoss()(y_hat, y)
https://stackoverflow.com/questions/67845882/
How to calculate the percentage of which kind the given image is after machine learning in pytorch?
I trained my machine with custom vgg model with CIFAR10 data set, and tested with some images in same data set. airplane : -16.972412 automobile : -18.719894 bird : -6.989656 cat : -3.8386667 deer : -7.622768 dog : 0.37765026 frog : -8.165334 horse : -7.4519434 sheep : -21.241518 truck : -18.978928 This is one of how I got the value of what kind the test image is. Below is what I implemented to print above: kind = ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "sheep", "truck"] for k in kind: print(k,": ", output.cpu().detach().numpy()[0][kind.index(k)]) Here, it is correct that given test image is dog, which is the highest value, yet I want to print every values as percentage, which the sum of all is 100. How could I do this? I used pytorch for code.
These values are logits, you should apply softmax on them to get the probability values between 0 - 1 and then you can multiply them by 100. Code Snippet: pred = output.cpu().detach().numpy() def softmax(x): "Function computes the softmax values for the each element in the given numpy array" return np.exp(x) / np.sum(np.exp(x), axis=0) def probability(x): "Function applies softmax for the given logit and returns the classification probability" return softmax(x) * 100 output_probs = probability(preds) or you can use softmax function from scipy from scipy.special import softmax output_probs = softmax(preds)
https://stackoverflow.com/questions/67851209/
How can I change the default image shape in PyTorch?
I've noticed that PyTorch uses images with shape (channels, width, height). How can I change it to (width, height, channels)? I am looking for a switch kind of think which switches between the two modes.
You can use torch.permute: tt = torch.tensor([[[0, 0], [1,1]], [[0,1], [1,0]], [[2, 2], [2, 2]]]) # > tensor([[[0, 0], [1, 1]], # [[0, 1], [1, 0]], # [[2, 2], [2, 2]]]) print(tt.shape) # > torch.Size([3, 2, 2]) tt2 = tt.permute(1, 2, 0) # > tensor([[[0, 0, 2], [0, 1, 2]], # [[1, 1, 2], [1, 0, 2]]]) print(tt2.shape) # > torch.Size([2, 2, 3])
https://stackoverflow.com/questions/67863036/
Get max value and its index in numpy array
I have this torch array. tensor([[8.22266e-01, 1.34659e-03, 9.85146e-04, 8.11100e-04], [9.35547e-01, 1.22261e-03, 8.70228e-04, 1.25122e-03], [9.48730e-01, 1.21975e-03, 9.28402e-04, 8.44955e-04], [7.97363e-01, 9.16004e-04, 9.16004e-04, 8.53539e-04], [9.26270e-01, 7.69138e-04, 8.47816e-04, 1.12724e-03], [9.43848e-01, 7.44820e-04, 8.53539e-04, 8.60691e-04], [7.89062e-01, 6.50406e-04, 9.23634e-04, 8.44479e-04], [9.29688e-01, 7.02858e-04, 7.60078e-04, 1.19591e-03], [9.47266e-01, 5.88894e-04, 8.36849e-04, 9.37462e-04], [8.27637e-01, 1.92642e-03, 1.73283e-03, 2.53105e-03], [9.22363e-01, 2.23160e-03, 1.37615e-03, 2.46811e-03], [9.31641e-01, 1.92928e-03, 1.49632e-03, 2.53296e-03], [8.25684e-01, 1.89209e-03, 1.70994e-03, 2.39944e-03], [9.21875e-01, 1.90926e-03, 1.28174e-03, 2.44904e-03], [9.25781e-01, 1.65272e-03, 1.45912e-03, 2.44141e-03], [8.39844e-01, 3.17955e-03, 4.02832e-03, 5.22614e-03], [9.17480e-01, 3.13759e-03, 3.37982e-03, 4.72260e-03], [9.37012e-01, 2.63405e-03, 3.57056e-03, 4.70734e-03]], device='cuda:0', dtype=torch.float16) I like to get its max value and index for each row in Torch is conf, j = x[:, 5:].max(1, keepdim=True) How can I implement in numpy if I have 2D numpy array?
You are looking for numpy.argmax
https://stackoverflow.com/questions/67867477/
Rowwise numpy.isin for 2D arrays
I have two arrays: A = np.array([[3, 1], [4, 1], [1, 4]]) B = np.array([[0, 1, 5], [2, 4, 5], [2, 3, 5]]) Is it possible to use numpy.isin rowwise for 2D arrays? I want to check if A[i,j] is in B[i] and return this result into C[i,j]. At the end I would get the following C: np.array([[False, True], [True, False], [False, False]]) It would be great, if this is also doable with the == operator, then I could use it also with PyTorch. Edit: I also considered check for identical rows in different numpy arrays. The question is somehow similar, but I am not able to apply its solutions to this slightly different problem.
Not sure that my code solves your problem perfectly. please run it on more test cases to confirm. but i would do smth like i've done in the following code taking advantage of numpys vector outer operations ability (similar to vector outer product). If it works as intended it should work with pytorch as well. import numpy as np A = np.array([[3, 1], [4, 1], [1, 4]]) B = np.array([[0, 1, 5], [2, 4, 5], [2, 3, 5]]) AA = A.reshape(3, 2, 1) BB = B.reshape(3, 1, 3) (AA == BB).sum(-1).astype(bool) output: array([[False, True], [ True, False], [False, False]])
https://stackoverflow.com/questions/67870579/
Trouble understanding behaviour of modified VGG16 forward method (Pytorch)
I have modified VGG16 in pytorch to insert things like BN and dropout within the feature extractor. By chance I now noticed something strange when I changed the definition of the forward method from: def forward(self, x): x = self.model(x) return x to: def forward(self, x): x = self.model.features(x) x = self.model.avgpool(x) x = self.model.classifier(x) return x In the second method I am now getting an error that the sizes of the matrices don't match (mat1 dim 1 must match mat2 dim 0) Below is the entire code For the editted version of VGG that I've been using. class Vgg(nn.Module): def __init__(self, n_classes, bias= None, dropout = 0.3): super().__init__() self.model = models.vgg16() #self.bn64 = nn.BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) #self.bn128 = nn.BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) #self.bn256 = nn.BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) #self.bn512 = nn.BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) # change to allow 4 channels input self.model.features[0] = nn.Conv2d(4, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3)) # remove/edit some of the first layers to make it more similar to Resnet del self.model.features[2] del self.model.features[2] del self.model.features[-1] self.model.features[2] = nn.MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False) # add dropout for m in self.model.modules(): if isinstance(m, nn.Dropout): m.p = dropout else: pass self.dropout = nn.Dropout(p=dropout) self.r = nn.ReLU(inplace=True) modules = nn.Sequential(*[self.model.features[0], #self.bn64, self.model.features[1:3], #self.bn64, self.model.features[3:5], #self.dropout, self.model.features[5], #self.bn128, self.model.features[6:8], #self.bn128, self.model.features[8:10], #self.dropout, self.model.features[10], #self.bn256, self.model.features[11:13], #self.bn256, self.model.features[13:15], #self.bn256, self.model.features[15:17], #self.dropout, self.model.features[17], #self.bn512, self.model.features[18:20], #self.bn512, self.model.features[20:22], #self.bn512, self.model.features[22:24], #self.dropout, self.model.features[24], #self.bn512, self.model.features[25:27], #self.bn512, self.model.features[27:29], #self.bn512, #self.dropout nn.MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) ]) self.model.features = modules # change the pooling layer self.model.avgpool = nn.AdaptiveAvgPool2d(output_size=(1, 1)) # set output to correct num classes self.model.classifier = nn.Linear(in_features=512, out_features=n_classes, bias=True) # use predefined bias if bias is not None: assert isinstance(bias, torch.Tensor), 'bias must be tensor' self.model.classifier.bias = nn.Parameter(bias) def forward(self, x): x = self.model.features(x) x = self.model.avgpool(x) x = self.model.classifier(x) return x I know it is very ugly and hacky looking. I have tried to re-write it but the re-written version does not work either for some reason, and I am assuming that this current issue is related to that as well. I think that the input is not being fed through the forward method the way I think it is. My assumption is that calling x = self.model(x) does not run 'x' through all of the editted layers I have made, otherwise I would get the same behaviour with the two version of the forward method above. But my question is then, what is happening when I call self.model(x) in forward? Is it running the input through the original vgg16 from pytorch? Because when I print self.model in my console it shows the changes I made to the architecture of self.model.features as well as self.model.avgpool and self.model.classifier. Edit: Below is the entire trace of the error. Some extra information. t is a class I made to deal with the training steps (so looping through training and validation modes, ect) --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-7-0b3983ae9702> in <module> 77 print_cl_met = True 78 ) ---> 79 model = t.run() 80 t.save_to_json() 81 print(np.max(np.array(t.f1_tracker))) /home/stevea/treesat/TreeSat/TreeSat/trainers/basetrainer.py in run(self) 342 for phase in ['training', 'testing']: 343 self.phase = phase --> 344 self.model_mode() 345 346 if self.phase == 'testing': /home/stevea/treesat/TreeSat/TreeSat/trainers/basetrainer.py in model_mode(self) 154 if self.phase == 'training': 155 print('*********TRAINING PHASE*********') --> 156 self.trainModel() 157 else: 158 print('*********VALIDATION PHASE*********') /home/stevea/treesat/TreeSat/TreeSat/trainers/basetrainer.py in trainModel(self) 234 # loop through all batches to perform an epoch 235 for loaded in self.loaders[self.phase]: --> 236 epoch_loss = self.train_step(loaded, epoch_loss) 237 238 mean_loss = np.mean(np.array(epoch_loss)) /home/stevea/treesat/TreeSat/TreeSat/trainers/basetrainer.py in train_step(self, loaded, epoch_loss) 262 263 # process batch through network --> 264 self.out = self.model(self.img_batch.float()) 265 266 # get loss value /usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs) 887 result = self._slow_forward(*input, **kwargs) 888 else: --> 889 result = self.forward(*input, **kwargs) 890 for hook in itertools.chain( 891 _global_forward_hooks.values(), /home/stevea/treesat/TreeSat/TreeSat/models/vgg.py in forward(self, x) 143 x = self.model.features(x) 144 x = self.model.avgpool(x) --> 145 x = self.model.classifier(x) 146 return x 147 /usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs) 887 result = self._slow_forward(*input, **kwargs) 888 else: --> 889 result = self.forward(*input, **kwargs) 890 for hook in itertools.chain( 891 _global_forward_hooks.values(), /usr/local/lib/python3.6/dist-packages/torch/nn/modules/linear.py in forward(self, input) 92 93 def forward(self, input: Tensor) -> Tensor: ---> 94 return F.linear(input, self.weight, self.bias) 95 96 def extra_repr(self) -> str: /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias) 1751 if has_torch_function_variadic(input, weight): 1752 return handle_torch_function(linear, (input, weight), input, weight, bias=bias) -> 1753 return torch._C._nn.linear(input, weight, bias) 1754 1755 RuntimeError: mat1 dim 1 must match mat2 dim 0 I also tried to print off the shape of x at each step of the forward method: def forward(self, x): x = self.model.features(x) print(x.shape) x = self.model.avgpool(x) print(x.shape) x = self.model.classifier(x) print(x.shape) return x And it shows me that the shapes seem to be fine as the classifier should be taking in 512 features: torch.Size([64, 512, 4, 4]) torch.Size([64, 512, 1, 1])
I can't run your code, but I believe the issue is because linear layers expect 2d data input (as it is really a matrix multiplication), while you provide 4d input (with dims 2 and 3 of size 1). Please try squeeze def forward(self, x): x = self.model.features(x) x = self.model.avgpool(x) x = torch.squeeze(x) x = self.model.classifier(x) return x For less hacky-looking code in the squeeze part, see torch einops.
https://stackoverflow.com/questions/67870887/
Colab pro does not provide more than 16 gb of ram
Today i upgraded my account to Colab pro. Although it prints the ram as: Your runtime has 27.3 gigabytes of available RAM You are using a high-RAM runtime! when I start training my model, it gives the error below. RuntimeError: CUDA out of memory. Tried to allocate 88.00 MiB (GPU 0; 15.90 GiB total capacity; 14.75 GiB already allocated; 75.75 MiB free; 14.95 GiB reserved in total by PyTorch) Hyperparameters of my model: args_dict = dict( #data_dir="", # path for data files output_dir="", # path to save the checkpoints model_name_or_path='t5-large', tokenizer_name_or_path='t5-large', max_seq_length=600, learning_rate=3e-4, weight_decay=0.0, adam_epsilon=1e-8, warmup_steps=0, train_batch_size=4, eval_batch_size=4, num_train_epochs=2, gradient_accumulation_steps=16, n_gpu=1, early_stop_callback=False, fp_16=True, # if you want to enable 16-bit training then install apex and set this to true opt_level='O1', # you can find out more on optimisation levels here https://nvidia.github.io/apex/amp.html#opt-levels-and-properties max_grad_norm=1.0, # if you enable 16-bit training then set this to a sensible value, 0.5 is a good default seed=42, ) Colab pro not providing all ram. My code only works if train_batch_size = 1. What causes this? Any ideas? Note: I get the same error when I run the code in Kaggle (16Gb). So, what I get with colab pro?
Looking at your error, the 16 GB are referring to the graphics card, not the ram. As far as I know, using colab-pro enables you to use a graphics card with up to 16GB of VRAM. You can check the VRAM amount by running the following code. gpu_info = !nvidia-smi gpu_info = '\n'.join(gpu_info) if gpu_info.find('failed') >= 0: print('Select the Runtime > "Change runtime type" menu to enable a GPU accelerator, ') print('and then re-execute this cell.') else: print(gpu_info) Maybe you use a smaller batch size than 4?
https://stackoverflow.com/questions/67872054/
Two models ( with similar hyperparameters) loaded from same checkpoint giving different training results in PYTORCH
I trained a model (Lenet-5) for 10 epochs and saved the model. loaded into 2 models ‘new_model’, ‘new_model2’ below is the colab link https://colab.research.google.com/drive/1qQhyTWNzCgMYn8t0ZtIZilLgk4JptbJG?usp=sharing trained the new models for 5 epochs, but ended up with different train and test accuracies for each epoch, in spite of loading from same model and setting reproducibility settings. When I continue training the original model for 5 more epochs, the results are also different from the training results of 2 new models. Is it possible that the test and train accuracies of original model (15 epochs), 2 new models (5 epochs after loading from the checkpoint) will be same? (After loaded checkpoint I'm getting same test accuracy for all 3 models, but results are deviating on further training of each of models.)
You should reset all the seeds to a fixed value right before launching your experiments every time you launch an experiment. In short, this should be the order: Set Seed Train new model #1 Set Seed (again) to the same value. Train new model #2 Reusing some of your code, we could define a function to set the seed, that should be called with the same value in steps 1 and 3: def set_seed(s): th.manual_seed(s) th.cuda.manual_seed_all(s) th.backends.cudnn.deterministic = True th.backends.cudnn.benchmark = False np.random.seed(s) random.seed(s) os.environ['PYTHONHASHSEED'] = str(s)
https://stackoverflow.com/questions/67872389/
Multiply a 3d tensor with a 2d matrix using torch.matmul
I have two tensors in PyTorch, z is a 3d tensor of shape (n_samples, n_features, n_views) in which n_samples is the number of samples in the dataset, n_features is the number of features for each sample, and n_views is the number of different views that describe the same (n_samples, n_features) feature matrix, but with other values. I have another 2d tensor b, of shape (n_samples, n_views), which purpose is to rescale all the features of the samples across the different views. In other words, it encapsulates the importance of the features of each view for the same sample. For example: import torch z = torch.Tensor(([[2,3], [1,1], [4,5]], [[2,2], [1,2], [7,7]], [[2,3], [1,1], [4,5]], [[2,3], [1,1], [4,5]])) b = torch.Tensor(([1, 0], [0, 1], [0.2, 0.8], [0.5, 0.5])) print(z.shape, b.shape) >>>torch.Size([4, 3, 2]) torch.Size([4, 2]) I want to obtain a third tensor r of shape (n_samples, n_features) as a result of operations between z and b. One possible solution is: b = b.unsqueeze(1) r = z * b r = torch.sum(r, dim=-1) print(r, r.shape) >>>tensor([[2.0000, 1.0000, 4.0000], [2.0000, 2.0000, 7.0000], [2.8000, 1.0000, 4.8000], [2.5000, 1.0000, 4.5000]]) torch.Size([4, 3]) Is it possible to achieve that same result using torch.matmul()?. I've tried many times to permute the dimensions of the two vector, but to no avail.
Yes that's possible. If you have mutiple batch dimensions in both operatns, you can use the broadcasting. In this case the last two dimensions of each operand are interpreted as a matrix size. (I recommend looking it up in the documentation.) So you need an additional dimension for your vectors b, to make them a n x 1 "matrix" (column vector): # original implementation b1 = b.unsqueeze(1) r1 = z * b1 r1 = torch.sum(r1, dim=-1) print(r1.shape) # using torch.matmul r2 = torch.matmul(z, b.unsqueeze(2))[...,0] print(r2.shape) print((r1-r2).abs().sum()) # should be zero if we do the same operation Alternatively, torch.einsum also makes this very straightforward. # using torch.einsum r3 = torch.einsum('ijk,ik->ij', z, b) print((r1-r3).abs().sum()) # should be zero if we do the same operation einsum is a very powerful operation that can do a lot of things: you can permute tensor dimensions, sum along them, or perform scalar products, all with or without broadcasting. It is derived from the Einstein summation convention mostly used in physics. The rough idea is that you give every dimension of your operans a name, and then, using these names define what the output should look like. I think it is best to read the documentation. In our case we have a 4 x 3 x 2 tensor as well as a 4 x 2 tensor. So the let's call the dimensions of the first tensor ijk. Here i and k should be considered the same as the dimensions of the second tensor, so this one can be described as ik. Finally the output should have clearly be ij (it mus be a 4 x 3 tensor). From this "signature" ijk, ik -> ij it is clear that the dimension i is preserved, and the dimensions k must be "summe/multiplied" away (scalar product).
https://stackoverflow.com/questions/67872716/
Is it possible to combine 2 neural networks?
I have a NET like (exemple from here) class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) # an affine operation: y = Wx + b self.fc1 = nn.Linear(16 * 5 * 5, 120) # 5*5 from image dimension self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): # Max pooling over a (2, 2) window x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # If the size is a square, you can specify with a single number x = F.max_pool2d(F.relu(self.conv2(x)), 2) x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x net = Net() and another net like (exemple from here) class binaryClassification(nn.Module): def __init__(self): super(binaryClassification, self).__init__() # Number of input features is 12. self.layer_1 = nn.Linear(12, 64) self.layer_2 = nn.Linear(64, 64) self.layer_out = nn.Linear(64, 1) self.relu = nn.ReLU() self.dropout = nn.Dropout(p=0.1) self.batchnorm1 = nn.BatchNorm1d(64) self.batchnorm2 = nn.BatchNorm1d(64) def forward(self, inputs): x = self.relu(self.layer_1(inputs)) x = self.batchnorm1(x) x = self.relu(self.layer_2(x)) x = self.batchnorm2(x) x = self.dropout(x) x = self.layer_out(x) return x I'd like to change, for exemple "self.fc2 = nn.Linear(120, 84)" in order to have 121 inputs, where the 121th is the x (output) of the binaryClassification network. The idea is: I'd like to use in the same time, CNN network, and not-CNN network, to train both, with influence one on the other. Is it possible? How can I perform that? (Keras or Pytorch examples are both ok). Or maybe the idea is crazy and there is easier way to mix data and image as input of an unique network?
It is a perfectly valid approach, you are taking two different input data sources, processing them and combining the result to solve a common goal (in this case it seems like a 10-class image classification). You can define the input to your Net network to be a tuple of the image you need for the original Net and the features 12-value vector for your BinaryClassificator. An example code would be: import torch import torch.nn as nn class binaryClassification(nn.Module): #> ...same as above class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) # an affine operation: y = Wx + b self.fc1 = nn.Linear(16 * 5 * 5, 120) # 5*5 from image dimension self.binClas = binaryClassification() self.fc2 = nn.Linear(121, 84) self.fc3 = nn.Linear(84, 10) def forward(self, inputs): x, features = inputs # split tuple # Max pooling over a (2, 2) window x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # If the size is a square, you can specify with a single number x = F.max_pool2d(F.relu(self.conv2(x)), 2) x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension # Concatenate with BinaryClassification x = torch.cat([F.relu(self.fc1(x)), self.binClas(features)]) x = F.relu(self.fc2(x)) x = self.fc3(x) return x net = Net() However! Be careful about training them together, it is hard to balance both branches in the network to make them learn. I would recommend you to train them separately for a while before plugging them together (generally speaking, the hyperparameters of one part of the network will probably not be optimal for the other). To do this, you could freeze one part of the network while training the other, and viceversa. (check this link to see how to freeze parts of a torch nn)
https://stackoverflow.com/questions/67872719/
Convert Pytorch Float Model into Double
I'm trying to solve cartpole from Gym. It turns out that the states are in double floating point precision whereas the pytorch by default creates model in single floating point precision. class QNetworkMLP(Module): def __init__(self,state_dim,num_actions): super(QNetworkMLP,self).__init__() self.l1 = Linear(state_dim,64) self.l2 = Linear(64,64) self.l3 = Linear(64,128) self.l4 = Linear(128,num_actions) self.relu = ReLU() self.lrelu = LeakyReLU() def forward(self,x) : x = self.lrelu(self.l1(x)) x = self.lrelu(self.l2(x)) x = self.lrelu(self.l3(x)) x = self.l4(x) return x I tried to convert it via model = QNetworkMLP(4,2).double() But it still doesn't work I get the same error. File ".\agent.py", line 117, in update_online_network predicted_Qval = self.online_network(states_batch).gather(1,actions_batch) File "C:\Users\27abh\anaconda3\envs\gym\lib\site-packages\torch\nn\modules\module.py", line 722, in _call_impl result = self.forward(*input, **kwargs) File "C:\Users\27abh\Desktop\OpenAI Gym\Cartpole\agent_model.py", line 16, in forward x = self.lrelu(self.l1(x)) File "C:\Users\27abh\anaconda3\envs\gym\lib\site-packages\torch\nn\modules\module.py", line 722, in _call_impl result = self.forward(*input, **kwargs) File "C:\Users\27abh\anaconda3\envs\gym\lib\site-packages\torch\nn\modules\linear.py", line 91, in forward return F.linear(input, self.weight, self.bias) File "C:\Users\27abh\anaconda3\envs\gym\lib\site-packages\torch\nn\functional.py", line 1674, in linear ret = torch.addmm(bias, input, weight.t()) RuntimeError: Expected object of scalar type Double but got scalar type Float for argument #2 'mat1' in call to _th_addmm
Can you try this after initializing your model: model.to(torch.double) Also be sure to check if all your inputs to the model are of torch.double data type
https://stackoverflow.com/questions/67874282/
unable to mmap 1024 bytes - Cannot allocate memory - even though there is more than enough ram
I'm currently working on a seminar paper on nlp, summarization of sourcecode function documentation. I've therefore created my own dataset with ca. 64000 samples (37453 is the size of the training dataset) and I want to fine tune the BART model. I use for this the package simpletransformers which is based on the huggingface package. My dataset is a pandas dataframe. An example of my dataset: My code: train_df = pd.read_csv(train_path, index_col=0) train_df.rename(columns={'text':'input_text', 'summary':'target_text'}, inplace=True) # Logging logging.basicConfig(level=logging.INFO) transformers_logger = logging.getLogger("transformers") transformers_logger.setLevel(logging.WARNING) # Hyperparameters model_args = Seq2SeqArgs() model_args.num_train_epochs = 10 # bart-base = 32, bart-large-cnn = 16 model_args.train_batch_size = 16 # model_args.no_save = True # model_args.evaluate_generated_text = True model_args.evaluate_during_training = True model_args.evaluate_during_training_verbose = True model_args.overwrite_output_dir = True model_args.save_model_every_epoch = False model_args.save_eval_checkpoints = False model_args.save_optimizer_and_scheduler = False model_args.save_steps = -1 best_model_dir = 'drive/MyDrive/outputs/bart-large-cnn/best_model/' model_args.best_model_dir = best_model_dir # Initialize model model = Seq2SeqModel( encoder_decoder_type="bart", encoder_decoder_name="facebook/bart-base", args=model_args, use_cuda=True, ) # Train the model model.train_model( train_df, # eval_data=eval_df, # matches=count_matches, ) everything is fine so far BUT I get this error when I start the training. Here the error from a run I did on a colab notebook: Exception in thread Thread-14: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python3.7/multiprocessing/pool.py", line 470, in _handle_results task = get() File "/usr/lib/python3.7/multiprocessing/connection.py", line 251, in recv return _ForkingPickler.loads(buf.getbuffer()) File "/usr/local/lib/python3.7/dist-packages/torch/multiprocessing/reductions.py", line 287, in rebuild_storage_fd storage = cls._new_shared_fd(fd, size) RuntimeError: unable to mmap 1024 bytes from file <filename not specified>: Cannot allocate memory (12) One would think that I simply have not enough memory but this were my System Monitor ca. 3 sec. after the error: and this was the lowest my available or free memory get in the time between starting the training and getting the error: After a lot of tuning I found out that for some reason every thing works fine when I train the model only with a dataset of the size of max. 21000. I doesn't madder if I train the "base" version or the "large-cnn" version of the BART model. I just depends on size of my dataset. The error always occurs in the "Creating features from dataset file at cache_dir/" time. So what have I already tried: I added a lot of swap memory (as you can see in the screenshot of my System Monitor) reduced the numbers of workers to 1 I increased the hard- as well as the softmax of my systems open files limit (-n) to 86000 I also tried to train the model in a google colab notebook but I had the same issue; if the dataset size gets over ca. 21000 the training fails. Even after I doubled the memory of my colab session but still keeping the datset size just a little bit over the 21000 limit. Desktop: transformers 4.6.0 simpletransformers 0.61.4 ubuntu 20.04.2 LTS After trying to solve this by myself for literally weeks I would me more than happy if anyone of you guys have an idea how I can solve this :) (I am aware of this post mmap returns can not allocate memory, even though there is enough even though there is enough unfortunately it couldn't solve my problem. My vm.max_map_count is at 860000)
So I just found a simple workaround. You can just set use_multiprocessing of the model to False: model_args.use_multiprocessing = False Now I can run with my whole dataset.
https://stackoverflow.com/questions/67876741/
Understanding Pytorch filter function
I was going through the documentation of PyTorch framework and found lots of instances where a variable is assigned a function but when it calls the function the parameters change. Not sure on how this works, any pointers would be helpful. What I do understand - def func1(word): print("hello", word) var1 = func1 Now in this scenario, var1("world") would print the string hello world. But what I dont understand is some lines from PyTorch like: def __init__(self, input_size, num_classes): super(NN,self).__init__() self.fc1 = nn.Linear(input_size, 50) self.fc2 = nn.Linear(50, num_classes) def forward(self,x): x = F.relu(self.fc1(x)) x = self.fc2(x) return x How do we know that only 1 param should be passed to self.fc2. It seems to be independent of the number of params defined in nn.Linear Does nn.Linear return a function like func1 that we store in var1 from the earlier example? If so is there any documentation on what is being returned? I do find the usage for each function in the nn module but is there something that gives more details on how exactly this works?
nn.Linear is not a function (and neither are all the other layers, like the convolution layers, batchnorms...), but a functor, which means it is a class which implements the __call__ method/operator which is called when you write something like self.fc2(x). The __call__ operator is implemented in the nn.Module base class, and it's a call to another method _call_impl which itself calls (basically) the forward method. Therefore, thanks to inheritance magic, when you make a class derive from nn.Module, you only need to implement the forward method. The signature of this method is kinda up to you, but in most cases it will take a tensor as input and return another tensor. In summary : # calls the constructor of nn.Linear. self.fc1 is now a functor self.fc1 = nn.Linear(20, 10) # calls the fc1 functor on an input y = self.fc1(torch.randn(2, 10)) # which is basically doing y = self.fc1.forward(torch.randn(2, 10))
https://stackoverflow.com/questions/67877136/
Gradient with respect to the parameters of a specific layer in Pytorch
I am building a model in pytorch with multiple networks. For example let's consider netA and netB. In the loss function I need to work with the composition netA(netB). In different parts of the optimization I need to calculate the gradient of loss_func(netA(netB)) with respect to only the parameters of netA and in another situation I need to calculate the gradients wrt the parameters of netB. How one should approach the problem? My approach: In the case of calculating the gradient wrt the parameters of netA I use loss_func(netA(netB.detach())). If I write loss_func(netA(netB).detach()) it seems that the both parameters of netA and netB are detached. I tried to use loss_func(netA.detach(netB)) in order to only detach the parameters of netA but it doesn't work. (I get the error that netA doesn't have attribute detach.)
The gradients are properties of tensors not networks. Therefore, you can only .detach a tensor. You can have different optimizers for each network. This way you can compute gradients for all networks all the time, but only update weights (calling step of the relevant optimizer) for the relevant network.
https://stackoverflow.com/questions/67878928/
Calculate variance with a kernel size in a tensor
Like what nn.Conv2d or nn.AvgPool2d do with a tensor and a kernel size, I would like to calculate the variances of a tensor with a kernel size. How can I achieve this? I guess maybe source code of pytorch should be touched?
If it's only the variance you are after, you can use the fact that var(x) = E[x^2] - E[x]^2 Using avg_pool2d you can estimate the local average of x and of x squared: import torch.nn.functional as nnf running_var = nnf.avg_pool2d(x**2, kernel_size=2, stride=1) - nnf.avg_pool2d(x, kernel_size=2,stride=1)**2 However, if you want a more general method of performing "sliding window" operations, you should become familiarized with unfold and fold: u = nnf.unfold(x, kernel_size=2, stride=1) # get all kernel_size patches as vectors running_var2 = torch.var(u, unbiased=False, dim=1) # reshape back to original shape ("folding") running_var2 = running_var2.reshape(x.shape[0], 1, x.shape[2]-1, x.shape[3]-1)
https://stackoverflow.com/questions/67885487/
Pytorch load data in mini batches
I have a folder of images as such Images | |__img1 | |__img1_b01.tiff | |__img1_b02.tiff | |__img1_b03.tiff | |__img1_b04.tiff | |__img1_b05.tiff | |__img2 | |__img2_b02.tiff | |__img2_b02.tiff | |__img2_b03.tiff | |__img2_b04.tiff | |__img2_b05.tiff | |.. img1000 Each folder represents an image. Each file in the folders represents a band channel of the image. Hence each image would have a I am stuck writting the pytorch custom dataloader to load in batches of 64 So I could have Feature batch shape: torch.Size([64,5, 256, 256]) I have tried the following code from torchvision import datasets, transforms from torch.utils import data dataset = datasets.ImageFolder(root = Images/, transform = transforms.ToTensor()) loader = data.DataLoader(dataset, batch_size = 64, shuffle = True) But it is not giving the results I want which is Feature batch shape: torch.Size([64, 5, 256, 256])
Using datasets.ImageFolder will make PyTorch treat each "band" image independently and treat the folder names (e.g., img1, img2...) as "class labels". In order to load 5 image files as different bands/channels of the same image, you'll need to write your own custom Dataset. This custom Dataset may look something like this: import torch import os from PIL import Image import numpy as np class MultiBandDataset(torch.utils.data.Dataset): def __init__(self, root, num_bands): self.root = root self.num_bands = num_bands self.imgs = os.listdir(root) # all `imgNN` folders def __len__(self): return len(self.imgs) # number of images = number of subfolders def __getitem__(self, index): multi_band = [] # get the subfolder subf = os.path.join(self.root, self.imgs[index]) for band in range(self.num_bands): b = Image.open(os.path.join(subf, f'{self.imgs[index]}_b{band+1:02d}.tiff')).convert("F") # make sure you are reading a single channel from each image. you need to verify this part. multi_band.append(np.array(b).astype(np.float32)[None,...]) # add singleton channel dimension return np.concatenate(numti_band, axis=0) Note that you would probably need to re-implement augmentations as well.
https://stackoverflow.com/questions/67887705/
regarding a design of Train() function
I once saw the following implementation of neural network. I am confused about the model.train() in the function of Train() . In class CNN_ForecastNet, I do not find the method of train, class CNN_ForecastNet(nn.Module): def __init__(self): super(CNN_ForecastNet,self).__init__() self.conv1d = nn.Conv1d(3,64,kernel_size=1) self.relu = nn.ReLU(inplace=True) self.fc1 = nn.Linear(64*2,50) self.fc2 = nn.Linear(50,1) def forward(self,x): x = self.conv1d(x) x = self.relu(x) x = x.view(-1) #print('x size',x.size()) x = self.fc1(x) x = self.relu(x) x = self.fc2(x) return x device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model = CNN_ForecastNet().to(device) def Train(): running_loss = .0 model.train() for idx, (inputs,labels) in enumerate(train_loader): inputs = inputs.to(device) labels = labels.to(device) optimizer.zero_grad() preds = model(inputs.float()) loss = criterion(preds,labels.float()) loss.backward() optimizer.step() running_loss += loss train_loss = running_loss/len(train_loader) train_losses.append(train_loss.detach().numpy()) print(f'train_loss {train_loss}')
As you can find in the documentation, the module train function just set a flag in the model to True (you can use model.eval() to set the flag to False). This flag is used by some layers for which the behavior changes in eval mode, most notably the dropout and batchnorm layers.
https://stackoverflow.com/questions/67894213/
How can I load my dataset including the labels in jupyter notebook using anaconda?
can someone help me with load both datasets, the main dataset with the labeled dataset to be load on my Jupiter notebook.
To load a dataset, depending on what file type the dataset is in, you can use functions such as: df1 = pd.read_csv("#FileNameHere") Then concatenate the two dataframes into one with all the attributes and labels. df = pd.concat([df1, df2], axis=1)
https://stackoverflow.com/questions/67896034/
what if the size of training set is not the integer multiple of batch size
I am running the following code against the dataset of PV_Elec_Gas3.csv, the network architecture is designed as follows class CNN_ForecastNet(nn.Module): def __init__(self): super(CNN_ForecastNet,self).__init__() self.conv1d = nn.Conv1d(3,64,kernel_size=1) self.relu = nn.ReLU(inplace=True) self.fc1 = nn.Linear(64*2,50) self.fc2 = nn.Linear(50,1) def forward(self,x): x = self.conv1d(x) x = self.relu(x) x = x.view(-1) #print('x size',x.size()) x = self.fc1(x) x = self.relu(x) x = self.fc2(x) return x The train function is defined as follows, def Train(): running_loss = .0 model.train() for idx, (inputs,labels) in enumerate(train_loader): inputs = inputs.to(device) labels = labels.to(device) optimizer.zero_grad() #print('inputs ',inputs) preds = model(inputs.float()) loss = criterion(preds,labels.float()) loss.backward() optimizer.step() running_loss += loss train_loss = running_loss/len(train_loader) train_losses.append(train_loss.detach().numpy()) print(f'train_loss {train_loss}') the train_loader is defined as train_loader = torch.utils.data.DataLoader(train,batch_size=2,shuffle=False) here the batch_size is set as 2. When running the train function, I got error message as follows. The reason is becaause when the code iterate through the train_loader, the last iteration only have one training point instead of two as batch_size requires. For this kind of scenario, besides changing the batch size, are there any other options? This is the error message. I also include the full code to reproduce the error RuntimeError Traceback (most recent call last) <ipython-input-82-78a49fb8c068> in <module> 99 for epoch in range(epochs): 100 print('epochs {}/{}'.format(epoch+1,epochs)) --> 101 Train() 102 gc.collect() <ipython-input-82-78a49fb8c068> in Train() 81 optimizer.zero_grad() 82 #print('inputs ',inputs) ---> 83 preds = model(inputs.float()) 84 loss = criterion(preds,labels.float()) 85 loss.backward() ~\Anaconda3\envs\pytorchenv\lib\site-packages\torch\nn\modules\module.py in _call_impl(self, *input, **kwargs) 725 result = self._slow_forward(*input, **kwargs) 726 else: --> 727 result = self.forward(*input, **kwargs) 728 for hook in itertools.chain( 729 _global_forward_hooks.values(), <ipython-input-82-78a49fb8c068> in forward(self, x) 57 x = x.view(-1) 58 #print('x size',x.size()) ---> 59 x = self.fc1(x) 60 x = self.relu(x) 61 x = self.fc2(x) ~\Anaconda3\envs\pytorchenv\lib\site-packages\torch\nn\modules\module.py in _call_impl(self, *input, **kwargs) 725 result = self._slow_forward(*input, **kwargs) 726 else: --> 727 result = self.forward(*input, **kwargs) 728 for hook in itertools.chain( 729 _global_forward_hooks.values(), ~\Anaconda3\envs\pytorchenv\lib\site-packages\torch\nn\modules\linear.py in forward(self, input) 91 92 def forward(self, input: Tensor) -> Tensor: ---> 93 return F.linear(input, self.weight, self.bias) 94 95 def extra_repr(self) -> str: ~\Anaconda3\envs\pytorchenv\lib\site-packages\torch\nn\functional.py in linear(input, weight, bias) 1690 ret = torch.addmm(bias, input, weight.t()) 1691 else: -> 1692 output = input.matmul(weight.t()) 1693 if bias is not None: 1694 output += bias RuntimeError: mat1 dim 1 must match mat2 dim 0 the following is the code for reproduction of error import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from numpy import array import torch import gc import torch.nn as nn from tqdm import tqdm_notebook as tqdm from torch.utils.data import Dataset,DataLoader solar_power = pd.read_csv('PV_Elec_Gas3.csv').rename(columns={'date':'timestamp'}).set_index('timestamp') train_set = solar_power[:'8/10/2016'] def split_sequence(sequence, n_steps): x, y = list(), list() for i in range(len(sequence)): end_ix = i + n_steps if end_ix > len(sequence)-1: break seq_x, seq_y = sequence[i:end_ix], sequence[end_ix] x.append(seq_x) y.append(seq_y) return array(x), array(y) n_steps = 3 train_x,train_y = split_sequence(train_set.loc[:,"kWh electricity/day"].values,n_steps) class ElecDataset(Dataset): def __init__(self,feature,target): self.feature = feature self.target = target def __len__(self): return len(self.feature) def __getitem__(self,idx): item = self.feature[idx] label = self.target[idx] return item,label class CNN_ForecastNet(nn.Module): def __init__(self): super(CNN_ForecastNet,self).__init__() self.conv1d = nn.Conv1d(3,64,kernel_size=1) self.relu = nn.ReLU(inplace=True) self.fc1 = nn.Linear(64*2,50) self.fc2 = nn.Linear(50,1) def forward(self,x): x = self.conv1d(x) x = self.relu(x) x = x.view(-1) #print('x size',x.size()) x = self.fc1(x) x = self.relu(x) x = self.fc2(x) return x device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model = CNN_ForecastNet().to(device) optimizer = torch.optim.Adam(model.parameters(), lr=1e-5) criterion = nn.MSELoss() train_losses = [] def Train(): running_loss = .0 model.train() for idx, (inputs,labels) in enumerate(train_loader): inputs = inputs.to(device) labels = labels.to(device) optimizer.zero_grad() #print('inputs ',inputs) preds = model(inputs.float()) loss = criterion(preds,labels.float()) loss.backward() optimizer.step() running_loss += loss train_loss = running_loss/len(train_loader) train_losses.append(train_loss.detach().numpy()) print(f'train_loss {train_loss}') train = ElecDataset(train_x.reshape(train_x.shape[0],train_x.shape[1],1),train_y) train_loader = torch.utils.data.DataLoader(train,batch_size=2,shuffle=False) epochs = 1 for epoch in range(epochs): print('epochs {}/{}'.format(epoch+1,epochs)) Train() gc.collect()
NO!!!! In your forward method you x.view(-1) before passing it to a nn.Linear layer. This "flattens" not only the spatial dimensions on x, but also the batch dimension! You basically mix together all samples in the batch, making your model dependant on the batch size and in general making the predictions depend on the batch as a whole rather than on the individual data points. Instead, you should: ... def forward(self, x): x = self.conv1d(x) x = self.relu(x) x = x.flatten(start_dim=1) # flatten all BUT batch dimension x = self.fc1(x) # you'll probably have to modify in_features of fc1 now x = self.relu(x) x = self.fc2(x) return x Please see flatten() for more details. If, for some reason, you must process only "full batches", you can tell DataLoader to drop the last batch by changing the argument drop_last from the default False to True: train_loader = torch.utils.data.DataLoader(train, batch_size=2, shuffle=False, drop_last=True)
https://stackoverflow.com/questions/67896539/
How do I use the exported 'best.pt" file from yolov5 colab file to run the trained weights locally?
I have trained my model using yoloV5 on google colab, following the provided tutorial and walkthrough provided for training any custom model: Colab file for training your own custom model. I now have an exported best.pt file after running the last cell in the link provided. Now, I want to make use of this trained weight to run a detection locally on any python script. Is this possible? If so, how do I go about doing this?
You should follow this step: Create an empty folder in desktop called ObjectDetection Open command prompt and change directory to that new folder using cd ObjectDetection. Clone yolov5 repo using command - git clone https://github.com/ultralytics/yolov5.git. It will create a new folder called yolov5 inside ObjectDetection folder. yolov5 folder contains important python file called detect.py which is responsible to detect the objects. After cloning the repo, enter into yolov5 folder using cd yolov5 Install all the necessary requirements using - pip install -r requirements.txt Download best.pt from colab and manually paste it inside yolov5 folder. Also copy the image that you want to test inside yolov5 folder. Before running inference, make sure that image.png, best.pt and detect.py should be in inside yolov5 folder. You can then run inference inside yolov5 folder by using this command: python detect.py --weights best.pt --source image.png After the process is completed, you can check the result inside path ObjectDetection/yolov5/runs/detect/exp
https://stackoverflow.com/questions/67897188/
Taking sample from Categorical distribution pytorch
I'm currently working on a Deep reinforcement learning problem, and I'm using the categorical distribution to help the agent get random action. This is the code. def choose_action(self,enc_current_node,goal_node): #print('nn') #vector=self.convert_vector(observation,end) state=T.tensor([[enc_current_node,goal_node]],dtype=T.float) pi,v=self.forward(state) probs=T.softmax(pi,dim=1) print(probs) dist=Categorical(probs) action=dist.sample().numpy()[0]#take a sample from the categorical dist from 1-22 return action the output of the Categorical(props) like this: probs=T.tensor([[1.5857e-03, 8.9753e-01, 2.8500e-03, 9.0585e-03, 3.6661e-04, 6.8342e-08, 7.2956e-04, 3.3966e-05, 3.7150e-04, 1.8317e-05, 4.1543e-04, 4.7550e-05, 5.2323e-05, 1.1337e-03, 1.6356e-05, 6.9848e-03, 2.2993e-03, 1.0874e-06, 2.0343e-04, 2.3616e-03, 1.3477e-02, 6.1464e-02]]) c=Categorical(probs) c >>> output: >>> Categorical(probs: torch.Size([1, 22])) now in the function, I sued dist.sample to take a sample of the 22 elements in it but I notice something that a lot of time the sample method that used in PyTorch result in the same number 90% of the time as you can see here: list=[] for i in range(100): list.append(c.sample()[0].item()) >>> output: >>> [1, 1, 1, 21, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 21, 1, 3, 1, 1, 1, 1, 1, 1, 21, 1, 1, 21, 1, 1, 1, 1, 1, 1, 1, 21, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 21, 1, 3, 1, 1, 1, 1, 1, 18, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 21, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3] as you can see above, the sample method output a lot of 1 my question is there a way to choose a random sample from the Categorical distribution rather than this?
If you look at your probabilities for sampling probs, you see that the 1th class has the largest probability, and almost all others are < 1%. If you are not familiar with scientific notation, here it is formatted as rounded percentages: for label, p in enumerate(probs[0]): print(f'{label:2}: {100*p:5.2f}%') 0: 0.16% 1: 89.75% <--- 2: 0.28% 3: 0.91% 4: 0.04% 5: 0.00% 6: 0.07% 7: 0.00% 8: 0.04% 9: 0.00% 10: 0.04% 11: 0.00% 12: 0.01% 13: 0.11% 14: 0.00% 15: 0.70% 16: 0.23% 17: 0.00% 18: 0.02% 19: 0.24% 20: 1.35% 21: 6.15% Hence ~90% of samples drawn from this will be 1.
https://stackoverflow.com/questions/67901636/
Does it make sense to backpropagate a loss calculated from an earlier layer through the entire network?
Suppose you have a neural network with 2 layers A and B. A gets the network input. A and B are consecutive (A's output is fed into B as input). Both A and B output predictions (prediction1 and prediction2) Picture of the described architecture You calculate a loss (loss1) directly after the first layer (A) with a target (target1). You also calculate a loss after the second layer (loss2) with its own target (target2). Does it make sense to use the sum of loss1 and loss2 as the error function and back propagate this loss through the entire network? If so, why is it "allowed" to back propagate loss1 through B even though it has nothing to do with it? This question is related to this question https://datascience.stackexchange.com/questions/37022/intuition-importance-of-intermediate-supervision-in-deep-learning but it does not answer my question sufficiently. In my case, A and B are unrelated modules. In the aforementioned question, A and B would be identical. The targets would be the same, too. (Additional information) The reason why I'm asking is that I'm trying to understand LCNN (https://github.com/zhou13/lcnn) from this paper. LCNN is made up of an Hourglass backbone, which then gets fed into MultiTask Learner (creates loss1), which in turn gets fed into a LineVectorizer Module (loss2). Both loss1 and loss2 are then summed up here and then back propagated through the entire network here. Even though I've visited several deep learning lectures, I didn't know this was "allowed" or makes sense to do. I would have expected to use two loss.backward(), one for each loss. Or is the pytorch computational graph doing something magical here? LCNN converges and outperforms other neural networks which try to solve the same task.
Yes, It is "allowed" and also makes sense. From the question, I believe you have understood most of it so I'm not going to details about why this multi-loss architecture can be useful. I think the main part that has made you confused is why does "loss1" back-propagate through "B"? and the answer is: It doesn't. The fact is that loss1 is calculated using this formula: loss1 = SOME_FUNCTION(label, y_hat) and y_hat(prediction1) is only dependent on layers before it. Hence, the gradient of this loss only flows through layers before this section (A) and not the ones after it (B). To better understand this, you could again check the mathematics of artificial neural networks. The loss2, on the other hand, back-propagates through all of the network (including part A). When you use a cumulative loss (Loss = loss1 + loss2), a framework like Pytorch will automatically follow the gradient of every predicted label to the first layer.
https://stackoverflow.com/questions/67902284/
pytorch different versions with "pip3 show torch" VS "torch.__version__"
When checking the installed pytorch version you can do that in two ways: pip3 show torch (or similar python3 -m pip freeze for all packages) import torch; torch.__version__ Interestingly the first option (using pip3) returns 1.8.1+cu111, while the second option (torch.__version__) returns 1.7.1 (without the cuda version support string, but cuda is available). Why do these two methods show different results and which one is the "valid" one? Important When I installed pytorch with cuda support I installed the latest version, but downgraded a few weeks ago for different reasons. Some info: OS: ubuntu python installed natively (not in conda, also not using jupyter)
This typically happens when you have multiple versions of the same library installed for some reason (normally mixing conda install and pip install in my experience). I recommend uninstalling oldest versions using the appropriate package manager until you see the expected behavior.
https://stackoverflow.com/questions/67903040/
How to generate a tensor representing, for each pair of rows in a matrix, whether elements at the same position both = 1?
I'm trying to compare every row in a matrix to every other row in the same matrix, yielding, for each pair, a row showing whether each element of those two rows both equal 1. Example: if I have this matrix as input: [[1,0,1], [0,1,1], [0,0,0]] I'd want to get this tensor: [[[1,0,1], [0,0,1], [0,0,0]], [[0,0,1], [0,1,1] [0,0,0]], [[0,0,0], [0,0,0], [0,0,0]]] Alternatively, if it's easier, my eventual goal is to reduce this tensor down to a matrix where each row represents whether ANY elements in a pair of rows from the original matrix both =1. So, the tensor above would get reduced to: [[1,1,0], [1,1,0], [0,0,0]] If it's easier to go straight to that without going through the intermediate tensor, let me know.
This is somewhat a partial answer, but it solves the first step which seems to be the question at hand: import numpy as np x = np.array([[1,0,1], [0,1,1], [0,0,0]]) output = x * np.repeat(x[:, np.newaxis, :], 3, axis=1) output # array([[[1, 0, 1], # [0, 0, 1], # [0, 0, 0]], # [[0, 0, 1], # [0, 1, 1], # [0, 0, 0]], # [[0, 0, 0], # [0, 0, 0], # [0, 0, 0]]]) In PyTorch, it would be: import torch x = torch.tensor([[1,0,1], [0,1,1], [0,0,0]]) output = x * x.unsqueeze(1).repeat_interleave(3, dim=1)
https://stackoverflow.com/questions/67906876/
How can I avoid a loop if I need to do a matrix multiplication?
I have the following code: import numpy as np import torch y = torch.ones((1000,10)) #This is the output of a neural network which does not matter here theta_min = 0; theta_max = np.pi; K = 10; sigma = 10; z = torch.zeros(y.shape) for i in range(0,y.shape[0]): theta = np.random.uniform(theta_min, theta_max) vector = np.reshape(np.exp(-1j * np.arange(0,K) * np.pi * np.sin(theta)),(-1,1)) vector = torch.tensor(vector) alpha = sigma * np.random.randn() z[i,:] = alpha * vector @ vector.T @ y[i,:].T How can I avoid the loop to make the code faster?
Following the solution of Megan Hardy, I have tried instead of make use of 3d arrays. We will make some useless operations, but it is better than the for loop. The code would look like this: y = torch.ones((1000,10)).type(torch.complex64) theta_min = 0; theta_max = np.pi; K = 10; sigma = 10; theta = torch.rand(y.shape[0],1,1) * np.pi #Each slice in the 0 dimension will be treated separately temp = torch.reshape(torch.arange(0,K),(-1,1)) #Necessary so that it doesn't have dimensions (10,), but (10,1) vector = torch.exp(-1j * temp * np.pi * torch.sin(theta)) matrix = vector @ torch.transpose(vector,1,2) #Maintain the 0 dimension but exchange dimension 1 and 2 alpha = sigma * torch.rand(1) z = alpha * matrix @ y.T #This makes more operations that necessary temp = range(0,y.shape[0]) z = alpha * z[temp,:,temp] #Take only the desired columns
https://stackoverflow.com/questions/67907491/
Dimension out of range (expected to be in range of [-1, 0], but got 1) (pytorch)
I have a very simple feed forward neural network (pytorch) import torch import torch.nn.functional as F import numpy as np class Net_1(nn.Module): def __init__(self): super(Net_1, self).__init__() self.fc1 = nn.Linear(5*5, 64) self.fc2 = nn.Linear(64, 32) self.fc3 = nn.Linear(32, 3) def forward(self,x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return F.log_softmax(x, dim=1) net = Net_1() and the input is this 5x5 numpy array state = [[0, 0, 3, 0, 0], [0, 0, 0, 0, 0], [0, 2, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] state = torch.Tensor(state).view(-1) net(state) throws the following error Dimension out of range (expected to be in range of [-1, 0], but got 1) the problem is when F.log_softmax() is applied
at the point when you call return F.log_softmax(x, dim=1), x is a 1-dimensional tensor with shape torch.Size([3]). dimension indexing in pytorch starts at 0, so you cannot use dim=1 for a 1-dimensional tensor, you will need to use dim=0. replace return F.log_softmax(x, dim=1) with return F.log_softmax(x, dim=0) and you'll be good to go. in the future you can check tensor sizes by adding print(x.shape) in forward.
https://stackoverflow.com/questions/67909708/
Updating a register_buffer in PyTorch?
Correct way to update a register_buffer in PyTorch I'm trying to determine the recommended way to update a register buffer which preserves the buffer's attributes. One "hacky" way to do this is shown below: import torch import torch.nn as nn class SomeModule(nn.Module): def __init__(self): super().__init__() self.register_buffer("A", torch.tensor(2.0)) def forward(self, x): return x * self.A def update_buffer(self, v): A = getattr(self, "A") setattr(self, "A", torch.tensor(v, dtype=A.dtype, device=A.device)) if __name__ == "__main__": model = SomeModule() model.to(torch.float64) print(model(1.0).dtype) model.update_buffer(3.0) print(model(1.0).dtype) When updating many buffers this gets a bit messy. Is there a recommended / better method to accomplish this?
Generally: self.A = new_tensor To copy the dtype and device from the previous tensor: self.A = new_tensor.type_as(self.A) If the new tensor has the same shape as the old, or you want to overwrite the current tensor's data with a new value, you can do: self.A[:] = new_value Examples: >>> mod.A = torch.tensor([3, 2, 1], dtype=int, device="cuda") >>> mod.A tensor([3, 2, 1], device='cuda:0') >>> mod.A = torch.Tensor([1.5, 2, 3.5]).type_as(mod.A) >>> mod.A tensor([1, 2, 3], device='cuda:0') >>> mod.A[:] = torch.Tensor([3, 4, 5]) >>> mod.A tensor([3, 4, 5], device='cuda:0') >>> mod.A[:] = 7 >>> mod.A tensor([7, 7, 7], device='cuda:0') >>> mod.state_dict() OrderedDict([('A', tensor([7, 7, 7], device='cuda:0'))])
https://stackoverflow.com/questions/67909883/
No module named 'torch'
I'm trying to solve this Error: ModuleNotFoundError: No module named 'torch' I did the installation of Pytorch using this command: conda install pytorch -c pytorch but when I import torch I got the message above.
You might be on another conda environment. try: conda env list and find the environment that you have installed pytorch on. then use: conda activate NAME_OF_YOUR_ENV to swtich to that environment and run your program there.
https://stackoverflow.com/questions/67911289/
Why would a Torchscript trace return different looking encoded_inputs compared to the original Transformer model?
Background I'm working with a finetuned Mbart50 model that I need sped up for inferencing because using the HuggingFace model as-is is fairly slow with my current hardware. I wanted to use TorchScript because I couldn't get onnx to export this particular model as it seems it will be supported at a later time (I would be glad to be wrong otherwise). Convert Transformer to a Pytorch trace: import torch """ Model data """ from transformers import MBartForConditionalGeneration, MBart50TokenizerFast device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50-one-to-many-mmt", torchscript= True) tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-one-to-many-mmt") tokenizer.src_lang = 'en_XX' dummy = "To celebrate World Oceans Day, we're swimming through a shoal of jack fish just off the coast of Baja, California, in Cabo Pulmo National Park. This Mexican marine park in the Sea of Cortez is home to the northernmost and oldest coral reef on the west coast of North America, estimated to be about 20,000 years old. Jacks are clearly plentiful here, but divers and snorkelers in Cabo Pulmo can also come across many other species of fish and marine mammals, including several varieties of sharks, whales, dolphins, tortoises, and manta rays." model.config.forced_bos_token_id=250006 myTokenBatch = tokenizer(dummy, max_length=192, padding='max_length', truncation = True, return_tensors="pt") torch.jit.save(torch.jit.trace(model, [myTokenBatch.input_ids,myTokenBatch.attention_mask]), "././traced-model/mbart-many.pt") Inference Step: import torch """ Model data """ from transformers import MBart50TokenizerFast device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-one-to-many-mmt") model = torch.jit.load('././traced-model/mbart-many.pt') MAX_LENGTH = 192 tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-one-to-many-mmt") model.to(device) model.eval() tokenizer.src_lang = 'en_XX' dummy = "To celebrate World Oceans Day, we're swimming through a shoal of jack fish just off the coast of Baja, California, in Cabo Pulmo National Park. This Mexican marine park in the Sea of Cortez is home to the northernmost and oldest coral reef on the west coast of North America, estimated to be about 20,000 years old. Jacks are clearly plentiful here, but divers and snorkelers in Cabo Pulmo can also come across many other species of fish and marine mammals, including several varieties of sharks, whales, dolphins, tortoises, and manta rays." myTokenBatch = tokenizer(dummy, max_length=192, padding='max_length', truncation = True, return_tensors="pt") encode, pool , norm = model(myTokenBatch.input_ids,myTokenBatch.attention_mask) Expected Encoding Output: These are tokens that can be decoded to words with MBart50TokenizerFast. tensor([[250004, 717, 176016, 6661, 55609, 7, 10013, 4, 642, 25, 107, 192298, 8305, 10, 15756, 289, 111, 121477, 67155, 1660, 5773, 70, 184085, 111, 118191, 4, 39897, 4, 23, 143740, 21694, 432, 9907, 5227, 5, 3293, 181815, 122084, 9201, 23, 70, 27414, 111, 48892, 169, 83, 5368, 47, 70, 144477, 9022, 840, 18, 136, 10332, 525, 184518, 456, 4240, 98, 70, 65272, 184085, 111, 23924, 21629, 4, 25902, 3674, 47, 186, 1672, 6, 91578, 5369, 10332, 5, 21763, 7, 621, 123019, 32328, 118, 7844, 3688, 4, 1284, 41767, 136, 120379, 2590, 1314, 23, 143740, 21694, 432, 831, 2843, 1380, 36880, 5941, 3789, 114149, 111, 67155, 136, 122084, 21968, 8080, 4, 26719, 40368, 285, 68794, 111, 54524, 1224, 4, 148, 50742, 7, 4, 13111, 19379, 1779, 4, 43807, 125216, 7, 4, 136, 332, 102, 62656, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) Actual Output: I don't know what this is... print(encode) (tensor([[[[-9.3383e-02, -2.0395e-01, 4.8226e-03, ..., 1.8068e+00, 1.1528e-01, 7.0406e-02], [-4.4630e-02, -2.2453e-01, 9.5264e-02, ..., 1.6921e+00, 1.4607e-01, 4.8238e-02], [-7.8206e-01, 1.2699e-01, 1.6467e+00, ..., -1.7057e+00, 8.7768e-01, 8.2230e-01], ..., [-1.2145e-02, -2.1855e-03, -6.0966e-03, ..., 2.9296e-02, 2.2141e-03, 3.2074e-02], [-1.4671e-02, -2.8995e-03, -5.8610e-03, ..., 2.8525e-02, 2.4620e-03, 3.1593e-02], [-1.5877e-02, -3.5165e-03, -4.8743e-03, ..., 2.8930e-02, 2.9877e-03, 3.3892e-02]]]], grad_fn=<CopyBackwards>))
Found the answer here: https://stackoverflow.com/a/66117248/13568346 You can't directly convert a seq2seq model (encoder-decoder model) using this method. To convert a seq2seq model (encoder-decoder) you have to split them and convert them separately, an encoder to onnx and a decoder to onnx. you can follow this guide (it was done for T5 which is also a seq2seq model). you need to provide a dummy variable to both encoder and to the decoder separately. by default when converting using this method it provides the encoder the dummy variable.
https://stackoverflow.com/questions/67924216/
PyTorch's CrossEntropyLoss - how to deal with the sequence length dimension with transformers?
I'm training a transformer model for text generation. let's assume: vocab size = 100 embbeding size = 50 max sequence length = 30 batch size = 32 loss = cross entropy loss the last layer in the model is a fully connected layer, mapping from shape [30, 32, 50] to [30, 32, 100]. the idea is that each of the last 30 sequences in the first dimension, I have a target vector I want to calculate loss with. the issue is that based on the docs, this loss only excepts 2 dims on the prediction and one on the target - so how can I fit my 3D prediction into it? (and 2D target?)
Use torch.BCELoss() instead (Binary cross entropy). This expects input and target to be the same size but they can be any size, and should fall within the range [0,1]. It performs cross-entropy loss element-wise. EDIT: if you expect only one element from the vocab to be output, then you should use CrossEntropyLoss and instead encode your labels as a 1D vector rather than a 2D vector (i.e. do 1-hot decoding). BCE treats each element in the output for a single example as independent from the others, which is not a valid assumption for a multi-class style problem. I originally misread and thought the final output was an embedding, rather than an element from the vocabulary, hence my original suggestion.
https://stackoverflow.com/questions/67926524/
Why does unet have classes?
import torch import torch.nn as nn import torch.nn.functional as F class double_conv(nn.Module): '''(conv => BN => ReLU) * 2''' def __init__(self, in_ch, out_ch): super(double_conv, self).__init__() self.conv = nn.Sequential( nn.Conv2d(in_ch, out_ch, 3, padding=1), nn.BatchNorm2d(out_ch), nn.ReLU(inplace=True), nn.Conv2d(out_ch, out_ch, 3, padding=1), nn.BatchNorm2d(out_ch), nn.ReLU(inplace=True) ) def forward(self, x): x = self.conv(x) return x class inconv(nn.Module): def __init__(self, in_ch, out_ch): super(inconv, self).__init__() self.conv = double_conv(in_ch, out_ch) def forward(self, x): x = self.conv(x) return x class down(nn.Module): def __init__(self, in_ch, out_ch): super(down, self).__init__() self.mpconv = nn.Sequential( nn.MaxPool2d(2), double_conv(in_ch, out_ch) ) def forward(self, x): x = self.mpconv(x) return x class up(nn.Module): def __init__(self, in_ch, out_ch, bilinear=True): super(up, self).__init__() # would be a nice idea if the upsampling could be learned too, # but my machine do not have enough memory to handle all those weights if bilinear: self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) else: self.up = nn.ConvTranspose2d(in_ch//2, in_ch//2, 2, stride=2) self.conv = double_conv(in_ch, out_ch) def forward(self, x1, x2): x1 = self.up(x1) diffX = x1.size()[2] - x2.size()[2] diffY = x1.size()[3] - x2.size()[3] x2 = F.pad(x2, (diffX // 2, int(diffX / 2), diffY // 2, int(diffY / 2))) x = torch.cat([x2, x1], dim=1) x = self.conv(x) return x class outconv(nn.Module): def __init__(self, in_ch, out_ch): super(outconv, self).__init__() self.conv = nn.Conv2d(in_ch, out_ch, 1) def forward(self, x): x = self.conv(x) return x class UNet(nn.Module): def __init__(self, n_channels, n_classes): super(UNet, self).__init__() self.inc = inconv(n_channels, 64) self.down1 = down(64, 128) self.down2 = down(128, 256) self.down3 = down(256, 512) self.down4 = down(512, 512) self.up1 = up(1024, 256) self.up2 = up(512, 128) self.up3 = up(256, 64) self.up4 = up(128, 64) self.outc = outconv(64, n_classes) def forward(self, x): self.x1 = self.inc(x) self.x2 = self.down1(self.x1) self.x3 = self.down2(self.x2) self.x4 = self.down3(self.x3) self.x5 = self.down4(self.x4) self.x6 = self.up1(self.x5, self.x4) self.x7 = self.up2(self.x6, self.x3) self.x8 = self.up3(self.x7, self.x2) self.x9 = self.up4(self.x8, self.x1) self.y = self.outc(self.x9) return self.y When I was reading UNet architecture I have found that it has n_classes as output. class UNet(nn.Module): def __init__(self, n_channels, n_classes): but why does it have n_classes as it is used for image segmentation? I am trying to use this code for image denoising and I couldn't figure out what will should the n_classes parameter be, because I don't have any classes. Does n_classes signify multiclass segmentation? If so, what is the output of binary UNet segmentation?
Answer Does n_classes signify multiclass segmentation? Yes, if you specify n_classes=4 it will output a (batch, 4, width, height) shaped tensor, where each pixel can be segmented as one of 4 classes. Also one should use torch.nn.CrossEntropyLoss for training. If so, what is the output of binary UNet segmentation? If you want to use binary segmentation you'd specify n_classes=1 (either 0 for black or 1 for white) and use torch.nn.BCEWithLogitsLoss I am trying to use this code for image denoising and I couldn't figure out what will should the n_classes parameter be It should be equal to n_channels, usually 3 for RGB or 1 for grayscale. If you want to teach this model to denoise an image you should: Add some noise to the image (e.g. using torchvision.transforms) Use sigmoid activation at the end as the pixels will have value between 0 and 1 (unless normalized) Use torch.nn.MSELoss for training Why sigmoid? Because [0,255] pixel range is represented as [0, 1] pixel value (without normalization at least). sigmoid does exactly that - squashes value into [0, 1] range, hence linear outputs (logits) can have a range from -inf to +inf. Why not a linear output and a clamp? In order for the Linear layer to be in [0, 1] range after clamp possible output values from Linear would have to be greater than 0 (logits range to fit the target: [0, +inf]) Why not a linear output without a clamp? Logits outputted would have to be within [0, 1] range Why not some other method? You could do that, but the idea of sigmoid is: help neural network (any logit value can be outputted) first derivative of sigmoid is gaussian standard normal, hence it models the probability of many real-life occurring phenomena (see also here for more)
https://stackoverflow.com/questions/67932624/
Pytorch CPU CUDA device load without gpu
I found this nice code Pytorch mobilenet which I cant get running on a CPU. https://github.com/rdroste/unisal I am new to Pytorch so I am not shure what to do. In line 174 of the module train.py the device is set: device = 'cuda:0' if torch.cuda.is_available() else 'cpu' which is correct as far as I know about Pytorch. Do I have to change the torch.load too? I tried with no success. class BaseModel(nn.Module): """Abstract model class with functionality to save and load weights""" def forward(self, *input): raise NotImplementedError def save_weights(self, directory, name): torch.save(self.state_dict(), directory / f'weights_{name}.pth') def load_weights(self, directory, name): self.load_state_dict(torch.load(directory / f'weights_{name}.pth')) def load_best_weights(self, directory): self.load_state_dict(torch.load(directory / f'weights_best.pth')) def load_epoch_checkpoint(self, directory, epoch): """Load state_dict from a Trainer checkpoint at a specific epoch""" chkpnt = torch.load(directory / f"chkpnt_epoch{epoch:04d}.pth") self.load_state_dict(chkpnt['model_state_dict']) def load_checkpoint(self, file): """Load state_dict from a specific Trainer checkpoint""" """Load """ chkpnt = torch.load(file) self.load_state_dict(chkpnt['model_state_dict']) def load_last_chkpnt(self, directory): """Load state_dict from the last Trainer checkpoint""" last_chkpnt = sorted(list(directory.glob('chkpnt_epoch*.pth')))[-1] self.load_checkpoint(last_chkpnt) I don’t get it. Where do I have to tell pytorch there is no gpu ? complete error: Traceback (most recent call last): File "run.py", line 99, in <module> fire.Fire() File "/home/b256/anaconda3/envs/unisal36/lib/python3.6/site-packages/fire/core.py", line 138, in Fire component_trace = _Fire(component, args, parsed_flag_args, context, name) File "/home/b256/anaconda3/envs/unisal36/lib/python3.6/site-packages/fire/core.py", line 471, in _Fire target=component.__name__) File "/home/b256/anaconda3/envs/unisal36/lib/python3.6/site-packages/fire/core.py", line 675, in _CallAndUpdateTrace component = fn(*varargs, **kwargs) File "run.py", line 95, in predict_examples example_folder, is_video, train_id=train_id, source=source) File "run.py", line 72, in predictions_from_folder folder_path, is_video, source=source, model_domain=model_domain) File "/home/b256/Data/saliency_models/unisal-master/unisal/train.py", line 871, in generate_predictions_from_path self.model.load_best_weights(self.train_dir) File "/home/b256/Data/saliency_models/unisal-master/unisal/train.py", line 1057, in model self._model = model_cls(**self.model_cfg) File "/home/b256/Data/saliency_models/unisal-master/unisal/model.py", line 190, in __init__ self.cnn = MobileNetV2(**self.cnn_cfg) File "/home/b256/Data/saliency_models/unisal-master/unisal/models/MobileNetV2.py", line 156, in __init__ Path(__file__).resolve().parent / 'weights/mobilenet_v2.pth.tar') File "/home/b256/anaconda3/envs/unisal36/lib/python3.6/site-packages/torch/serialization.py", line 367, in load return _load(f, map_location, pickle_module) File "/home/b256/anaconda3/envs/unisal36/lib/python3.6/site-packages/torch/serialization.py", line 538, in _load result = unpickler.load() File "/home/b256/anaconda3/envs/unisal36/lib/python3.6/site-packages/torch/serialization.py", line 504, in persistent_load data_type(size), location) File "/home/b256/anaconda3/envs/unisal36/lib/python3.6/site-packages/torch/serialization.py", line 113, in default_restore_location result = fn(storage, location) File "/home/b256/anaconda3/envs/unisal36/lib/python3.6/site-packages/torch/serialization.py", line 94, in _cuda_deserialize device = validate_cuda_device(location) File "/home/b256/anaconda3/envs/unisal36/lib/python3.6/site-packages/torch/serialization.py", line 78, in validate_cuda_device raise RuntimeError('Attempting to deserialize object on a CUDA ' RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location='cpu' to map your storages to the CPU.
In https://pytorch.org/tutorials/beginner/saving_loading_models.html#save-on-gpu-load-on-cpu you'll see there's a map_location keyword argument to send weights to the proper device: model.load_state_dict(torch.load(PATH, map_location=device)) From the docs https://pytorch.org/docs/stable/generated/torch.load.html#torch.load torch.load() uses Python’s unpickling facilities but treats storages, which underlie tensors, specially. They are first deserialized on the CPU and are then moved to the device they were saved from. If this fails (e.g. because the run time system doesn’t have certain devices), an exception is raised. However, storages can be dynamically remapped to an alternative set of devices using the map_location argument. If map_location is a callable, it will be called once for each serialized storage with two arguments: storage and location. The storage argument will be the initial deserialization of the storage, residing on the CPU. Each serialized storage has a location tag associated with it which identifies the device it was saved from, and this tag is the second argument passed to map_location. The builtin location tags are 'cpu' for CPU tensors and 'cuda:device_id' (e.g. 'cuda:2') for CUDA tensors. map_location should return either None or a storage. If map_location returns a storage, it will be used as the final deserialized object, already moved to the right device. Otherwise, torch.load() will fall back to the default behavior, as if map_location wasn’t specified. If map_location is a torch.device object or a string containing a device tag, it indicates the location where all tensors should be loaded. Otherwise, if map_location is a dict, it will be used to remap location tags appearing in the file (keys), to ones that specify where to put the storages (values).
https://stackoverflow.com/questions/67934005/
Pytorch Inferencing form the model is giving me different results every time
I have created and trained one very simple network in pytorch as shown below: self.task_layers[task][task_layer_key]; TaskLayerManager( (taskLayers): ModuleList( (0): lc_hidden( (dropout_layer): Dropout(p=0.0, inplace=False) (layer_norm): LayerNorm((768,), eps=1e-05, elementwise_affine=True) ) (1): cnn( (cnn_layer): CNN_Text( (dropout): Dropout(p=0.1, inplace=False) (fc1): Linear(in_features=300, out_features=2, bias=True) (convs1): ModuleList( (0): Conv2d(1, 300, kernel_size=(5, 768), stride=(1, 1), padding=(4, 0)) ) ) ) ) ) Layer descriptions: taskLayers.0.linear_weights torch.Size([13]) taskLayers.0.layer_norm.weight torch.Size([768]) taskLayers.0.layer_norm.bias torch.Size([768]) taskLayers.1.cnn_layer.fc1.weight torch.Size([2, 300]) taskLayers.1.cnn_layer.fc1.bias torch.Size([2]) taskLayers.1.cnn_layer.convs1.0.weight torch.Size([300, 1, 5, 768]) taskLayers.1.cnn_layer.convs1.0.bias torch.Size([300]) It is a binary classification network that take a 3d tensor as input [N,K,768] and gives output [N,2] tensor I am not able to figure out "Why at every run it is giving me different results"? Please help me with this - I am new to pytorch. And let me know if any other information is needed.
I suspect this is due to you not having set the model to inference mode with model.eval() If you don't do this, your dropout layer(s) will remain activated and randomly dropout p proportion of neurons on each call.
https://stackoverflow.com/questions/67934643/
How to read this modified unet?
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision from PIL import Image import matplotlib.pyplot as plt class Model_Down(nn.Module): """ Convolutional (Downsampling) Blocks. nd = Number of Filters kd = Kernel size """ def __init__(self,in_channels, nd = 128, kd = 3, padding = 1, stride = 2): super(Model_Down,self).__init__() self.padder = nn.ReflectionPad2d(padding) self.conv1 = nn.Conv2d(in_channels = in_channels, out_channels = nd, kernel_size = kd, stride = stride) self.bn1 = nn.BatchNorm2d(nd) self.conv2 = nn.Conv2d(in_channels = nd, out_channels = nd, kernel_size = kd, stride = 1) self.bn2 = nn.BatchNorm2d(nd) self.relu = nn.LeakyReLU() def forward(self, x): x = self.padder(x) x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.padder(x) x = self.conv2(x) x = self.bn2(x) x = self.relu(x) return x class Model_Skip(nn.Module): """ Skip Connections ns = Number of filters ks = Kernel size """ def __init__(self,in_channels = 128, ns = 4, ks = 1, padding = 0, stride = 1): super(Model_Skip, self).__init__() self.conv = nn.Conv2d(in_channels = in_channels, out_channels = ns, kernel_size = ks, stride = stride, padding = padding) self.bn = nn.BatchNorm2d(ns) self.relu = nn.LeakyReLU() def forward(self,x): x = self.conv(x) x = self.bn(x) x = self.relu(x) return x class Model_Up(nn.Module): """ Convolutional (Downsampling) Blocks. nd = Number of Filters kd = Kernel size """ def __init__(self, in_channels = 132, nu = 128, ku = 3, padding = 1): super(Model_Up, self).__init__() self.bn1 = nn.BatchNorm2d(in_channels) self.padder = nn.ReflectionPad2d(padding) self.conv1 = nn.Conv2d(in_channels = in_channels, out_channels = nu, kernel_size = ku, stride = 1, padding = 0) self.bn2 = nn.BatchNorm2d(nu) self.conv2 = nn.Conv2d(in_channels = nu, out_channels = nu, kernel_size = 1, stride = 1, padding = 0) #According to supmat.pdf ku = 1 for second layer self.bn3 = nn.BatchNorm2d(nu) self.relu = nn.LeakyReLU() def forward(self,x): x = self.bn1(x) x = self.padder(x) x = self.conv1(x) x = self.bn2(x) x = self.relu(x) x = self.conv2(x) x = self.bn3(x) x = self.relu(x) x = F.interpolate(x, scale_factor = 2, mode = 'bilinear') return x class Model(nn.Module): def __init__(self, length = 5, in_channels = 32, out_channels = 3, nu = [128,128,128,128,128] , nd = [128,128,128,128,128], ns = [4,4,4,4,4], ku = [3,3,3,3,3], kd = [3,3,3,3,3], ks = [1,1,1,1,1]): super(Model,self).__init__() assert length == len(nu), 'Hyperparameters do not match network depth.' self.length = length self.downs = nn.ModuleList([Model_Down(in_channels = nd[i-1], nd = nd[i], kd = kd[i]) if i != 0 else Model_Down(in_channels = in_channels, nd = nd[i], kd = kd[i]) for i in range(self.length)]) self.skips = nn.ModuleList([Model_Skip(in_channels = nd[i], ns = ns[i], ks = ks[i]) for i in range(self.length)]) self.ups = nn.ModuleList([Model_Up(in_channels = ns[i]+nu[i+1], nu = nu[i], ku = ku[i]) if i != self.length-1 else Model_Up(in_channels = ns[i], nu = nu[i], ku = ku[i]) for i in range(self.length-1,-1,-1)]) #Elements ordered backwards self.conv_out = nn.Conv2d(nu[0],out_channels,1,padding = 0) self.sigm = nn.Sigmoid() def forward(self,x): s = [] #Skip Activations #Downpass for i in range(self.length): x = self.downs[i].forward(x) s.append(self.skips[i].forward(x)) #Uppass for i in range(self.length): if (i == 0): x = self.ups[i].forward(s[-1]) else: x = self.ups[i].forward(torch.cat([x,s[self.length-1-i]],axis = 1)) x = self.sigm(self.conv_out(x)) #Squash to RGB ([0,1]) format return x This code is a modified UNet I am working on. I am facing hard to read and understand code and how the skip connections are connected to upsampling. can anyone please explain it or can it be written in simple more understandable way without nn.ModuleList. can some one show how this network looks using a diagram? This is the github link repo link from where i took this code and trying to understand it.
Here is a functional equivalent of the main Model forward(x) method. It is much more verbose, but it is "unravelling" the flow of operations, making it more easily understandable. I assumed that the length of the list-arguments are always 5 (i is in the [0, 4] range, inclusive) so I could unpack properly (and it follows the default set of parameters). def unet_function(x, in_channels = 32, out_channels = 3, nu = [128,128,128,128,128], nd = [128,128,128,128,128], ns = [4,4,4,4,4], ku = [3,3,3,3,3], kd = [3,3,3,3,3], ks = [1,1,1,1,1]): ################################ # DOWN PASS #################### ################################ ######### # i = 0 # ######### # First Down # Model_Down(in_channels = in_channels, nd = nd[i], kd = kd[i]) x = nn.ReflectionPad2d(padding=1)(x) x = nn.Conv2D(in_channels=in_channels, out_channels=nd[0], kernel_size=kd[0], stride=2)(x) x = nn.BatchNorm2d(nd[0])(x) x = nn.LeakyRelu()(x) x = nn.ReflectionPad2d(padding=1)(x) x = nn.Conv2d(in_channels = nd[0], out_channels=nd[0], kernel_size = kd[0], stride=1)(x) x = nn.BatchNorm2d(nd[0])(x) x = nn.LeakyRelu()(x) # First skip # Model_Skip(in_channels = nd[i], ns = ns[i], ks = ks[i]) s0 = nn.Conv2D(in_channels=nd[0], out_channels=ns[0])(x) s0 = nn.BatchNorm2d(ns[0])(s0) s0 = nn.LeakyreLU()(s0) ######### # i = 1 # ######### # Second Down # Model_Down(in_channels = nd[i-1], nd = nd[i], kd = kd[i]) x = nn.ReflectionPad2d(padding=1)(x) x = nn.Conv2D(in_channels=nd[0], out_channels=nd[0], kernel_size=kd[1], stride=2)(x) x = nn.BatchNorm2d(nd[0])(x) x = nn.LeakyRelu()(x) x = nn.ReflectionPad2d(padding=1)(x) x = nn.Conv2d(in_channels = nd[0], out_channels=nd[0], kernel_size = kd[1], stride=1)(x) x = nn.BatchNorm2d(nd[0])(x) x = nn.LeakyRelu()(x) # Second skip # Model_Skip(in_channels = nd[i], ns = ns[i], ks = ks[i]) s1 = nn.Conv2D(in_channels=nd[1], out_channels=ns[1])(x) s1 = nn.BatchNorm2d(ns[1])(s1) s1 = nn.LeakyreLU()(s1) ######### # i = 2 # ######### # Third Down # Model_Down(in_channels = nd[i-1], nd = nd[i], kd = kd[i]) x = nn.ReflectionPad2d(padding=1)(x) x = nn.Conv2D(in_channels=nd[1], out_channels=nd[1], kernel_size=kd[2], stride=2)(x) x = nn.BatchNorm2d(nd[1])(x) x = nn.LeakyRelu()(x) x = nn.ReflectionPad2d(padding=1)(x) x = nn.Conv2d(in_channels = nd[1], out_channels=nd[0], kernel_size = kd[2], stride=1)(x) x = nn.BatchNorm2d(nd[1])(x) x = nn.LeakyRelu()(x) # Third skip # Model_Skip(in_channels = nd[i], ns = ns[i], ks = ks[i]) s2 = nn.Conv2D(in_channels=nd[2], out_channels=ns[2])(x) s2 = nn.BatchNorm2d(ns[2])(s2) s2 = nn.LeakyreLU()(s2) ######### # i = 3 # ######### # Fourth Down # Model_Down(in_channels = nd[i-1], nd = nd[i], kd = kd[i]) x = nn.ReflectionPad2d(padding=1)(x) x = nn.Conv2D(in_channels=nd[2], out_channels=nd[2], kernel_size=kd[3], stride=2)(x) x = nn.BatchNorm2d(nd[2])(x) x = nn.LeakyRelu()(x) x = nn.ReflectionPad2d(padding=1)(x) x = nn.Conv2d(in_channels = nd[2], out_channels=nd[2], kernel_size = kd[3], stride=1)(x) x = nn.BatchNorm2d(nd[2])(x) x = nn.LeakyRelu()(x) # Fourth skip # Model_Skip(in_channels = nd[i], ns = ns[i], ks = ks[i]) s3 = nn.Conv2D(in_channels=nd[3], out_channels=ns[3])(x) s3 = nn.BatchNorm2d(ns[3])(s3) s3 = nn.LeakyreLU()(s3) ######### # i = 4 # ######### # Fifth Down # Model_Down(in_channels = nd[i-1], nd = nd[i], kd = kd[i]) x = nn.ReflectionPad2d(padding=1)(x) x = nn.Conv2D(in_channels=nd[3], out_channels=nd[3], kernel_size=kd[4], stride=2)(x) x = nn.BatchNorm2d(nd[3])(x) x = nn.LeakyRelu()(x) x = nn.ReflectionPad2d(padding=1)(x) x = nn.Conv2d(in_channels = nd[3], out_channels=nd[3], kernel_size = kd[4], stride=1)(x) x = nn.BatchNorm2d(nd[2])(x) x = nn.LeakyRelu()(x) # Fifth skip # Model_Skip(in_channels = nd[i], ns = ns[i], ks = ks[i]) x = nn.Conv2D(in_channels=nd[4], out_channels=ns[4])(x) x = nn.BatchNorm2d(ns[4])(x) x = nn.LeakyreLU()(x) ################################ # UP PASS ###################### ################################ ######### # i = 4 # ######### # First Up # Model_Up(in_channels = ns[i], nu = nu[i], ku = ku[i]) x = nn.BatchNorm2d(in_channel=ns[4])(x) x = nn.ReflectionPad2d(padding)(x) x = nn.Conv2d(in_channels=ns[4], out_channels=nu[4], kernel_size=ku[4], stride=1, padding=0)(x) x = nn.BatchNorm2d(nu[4])(x) x = nn.LeakyReLU()(x) x = nn.Conv2d(in_channels = nu[4], out_channels=nu[4], kernel_size = 1, stride = 1, padding = 0)(x) x = nn.BatchNorm2d(nu[4])(x) x = nn.LeakyReLU()(x) x = F.interpolate(x, scale_factor = 2, mode = 'bilinear') ######### # i = 3 # ######### # Second Up # self.ups[i].forward(torch.cat([x,s[self.length-1-i]],axis = 1)) x = torch.cat([x,s3], axis=1) # IMPORTANT HERE # Model_Up(in_channels = ns[i]+nu[i+1], nu = nu[i], ku = ku[i]) x = nn.BatchNorm2d(in_channel=ns[3]+nu[4])(x) x = nn.ReflectionPad2d(padding)(x) x = nn.Conv2d(in_channels=ns[3]+nu[4], out_channels=nu[3], kernel_size=ku[3], stride=1, padding=0)(x) x = nn.BatchNorm2d(nu[3])(x) x = nn.LeakyReLU()(x) x = nn.Conv2d(in_channels = ns[3]+nu[4], out_channels=nu[3], kernel_size = 1, stride = 1, padding = 0)(x) x = nn.BatchNorm2d(nu[3])(x) x = nn.LeakyReLU()(x) x = F.interpolate(x, scale_factor = 2, mode = 'bilinear') ######### # i = 2 # ######### # Third Up # self.ups[i].forward(torch.cat([x,s[self.length-1-i]],axis = 1)) x = torch.cat([x,s2], axis=1) # IMPORTANT HERE # Model_Up(in_channels = ns[i]+nu[i+1], nu = nu[i], ku = ku[i]) x = nn.BatchNorm2d(in_channel=ns[2]+nu[3])(x) x = nn.ReflectionPad2d(padding)(x) x = nn.Conv2d(in_channels=ns[2]+nu[3], out_channels=nu[2], kernel_size=ku[2], stride=1, padding=0)(x) x = nn.BatchNorm2d(nu[2])(x) x = nn.LeakyReLU()(x) x = nn.Conv2d(in_channels = ns[2]+nu[3], out_channels=nu[2], kernel_size = 1, stride = 1, padding = 0)(x) x = nn.BatchNorm2d(nu[2])(x) x = nn.LeakyReLU()(x) x = F.interpolate(x, scale_factor = 2, mode = 'bilinear') ######### # i = 1 # ######### # Fourth Up # self.ups[i].forward(torch.cat([x,s[self.length-1-i]],axis = 1)) x = torch.cat([x,s1], axis=1) # IMPORTANT HERE # Model_Up(in_channels = ns[i]+nu[i+1], nu = nu[i], ku = ku[i]) x = nn.BatchNorm2d(in_channel=ns[1]+nu[2])(x) x = nn.ReflectionPad2d(padding)(x) x = nn.Conv2d(in_channels=ns[1]+nu[2], out_channels=nu[1], kernel_size=ku[1], stride=1, padding=0)(x) x = nn.BatchNorm2d(nu[1])(x) x = nn.LeakyReLU()(x) x = nn.Conv2d(in_channels = ns[1]+nu[2], out_channels=nu[1], kernel_size = 1, stride = 1, padding = 0)(x) x = nn.BatchNorm2d(nu[1])(x) x = nn.LeakyReLU()(x) x = F.interpolate(x, scale_factor = 2, mode = 'bilinear') ######### # i = 0 # ######### # Fifth Up # self.ups[i].forward(torch.cat([x,s[self.length-1-i]],axis = 1)) x = torch.cat([x,s0], axis=1) # IMPORTANT HERE # Model_Up(in_channels = ns[i]+nu[i+1], nu = nu[i], ku = ku[i]) x = nn.BatchNorm2d(in_channel=ns[0]+nu[1])(x) x = nn.ReflectionPad2d(padding)(x) x = nn.Conv2d(in_channels=ns[0]+nu[1], out_channels=nu[0], kernel_size=ku[0], stride=1, padding=0)(x) x = nn.BatchNorm2d(nu[0])(x) x = nn.LeakyReLU()(x) x = nn.Conv2d(in_channels = nu[0], out_channels=nu[0], kernel_size = 1, stride = 1, padding = 0)(x) x = nn.BatchNorm2d(nu[0])(x) x = nn.LeakyReLU()(x) x = F.interpolate(x, scale_factor = 2, mode = 'bilinear') ################################ # OUT ########################## ################################ x = nn.Conv2d(in_channels=nu[0], out_channels=out_channels, kernel_size=1, padding = 0) return nn.Sigmoid()(x) #Squash to RGB ([0,1]) format The two most important parts are: The skips where the tensor x is processed in a parallel part of the code, not to disturb the main x "pathway". The produced tensors from the skip parts are then fed back to the "main pathway" starting from the last one. I kept those tensor as individual variables s0 to s3, so that it is more obvious. From this picture, you can clearly see the down part feeding latter parts. s0 is the longest grey arrow, it is concatenated to the "main pathway" just before the last convolution layers group. (Not the same U-Net) You can also understand from it why we don't need to store a s4 : it is directly fed to the next layer, therefore there is no need to store it as a separate variable. The Module version does store it, but only because it is conveniently stored in a list read in reverse order at the end. Another obvious reason to store them in a list is so we can have any number of Up and Down parts, by changing the parameters accordingly.
https://stackoverflow.com/questions/67936380/
How and where can i freeze classifier layer?
If I need to freeze the output layer of this model which is doing the classification as I don't need it.
You are confusing a few things here (I think) Freezing layers You freeze the layer if you don't want them to be trained (and don't want them to be part of the graph also). Usually we freeze part of the network creating features, in your case it would be everything up to self.head. After that, we usually only train bottleneck (self.head in this case) to fine-tune it for the task at hand. In case of your model it would be: def gradient(model, freeze: bool): for parameter in transformer.parameters(): parameter.requires_grad_(not freeze) transformer = VisionTransformer() gradient(model, freeze=True) gradient(model.head, freeze=False) I only want the features In this case you have the following line: self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() If you specify num_classes as 0 the model will only return the features, e.g.: transformer = VisionTransformer(num_classes=0) I want specific head for my task Simply override the self.head attribute, for example: transformer.head = nn.Sequential( nn.Linear(embed_dim, 100), nn.ReLU(), nn.Linear(100, num_classes) ) Or, if you want different number of classes you can specify num_classes to the number of classes you have in your task. Question in the comment No, you should freeze everything except head and specify that you want features out, this would do the trick: def gradient(model, freeze: bool): for parameter in transformer.parameters(): parameter.requires_grad_(not freeze) transformer = VisionTransformer(num_classes=0) gradient(model, freeze=True) Due to that, learned features by VisionTransformer will be preserved (probably what you are after), you don't need self.head at all in this case!
https://stackoverflow.com/questions/67939448/
Serving service from kfserving github examples created with kubectl, but can not infere
I have installed minikube cluster and kfserving on a linux desktop. Then I have followed two tutorials https://github.com/kubeflow/kfserving/tree/master/docs/samples/v1beta1/custom/torchserve https://github.com/kubeflow/kfserving/tree/master/docs/samples/v1alpha2/custom/kfserving-custom-model In the second tutorial I have needed to move "name: custom" from "custom:" section to "container:" section in the yaml file. I expected that serving service was working and responding to serving requests and pods of the service where in kubernetes. I use the newest stable versions from May 2021. But I have same bug in both tutorials. Bellow commands are from the first tutorial. When I prepare docker images with models and run $ kubectl apply -f torchserve-custom.yaml command. I see output like inferenceservice.serving.kubeflow.org/torchserve-custom created But I can not run a prediction, because service I get 404 not found. When I run $ kubectl get pods --all-namespaces I do not see any new pods. But I can deleted service with $ kubectl delete -f torchserve-custom When I have followed other tutorials like: https://github.com/kubeflow/kfserving/tree/master/docs/samples/v1beta1/torchserve everything worked fine and I could run predictions. Why can`t I run a prediction? Why any new pods are created? How to setup serving in kfserving using docker image, if the above tutorials did not worked?
It turned out that my local docker registry wasn't visible from kubernetes. kubectl get events shows InternalError "Unable to fetch image ... "
https://stackoverflow.com/questions/67939827/