id
stringlengths
3
8
text
stringlengths
1
115k
st30468
I’m not sure what directly causes (1) but I think there could be reasons behind (2) (2) Did you create any cuda tensors before moving your model to the GPU? If not, then my handwavy explanation for this is that the moment you create a cuda tensor (e.g., directly declaring one or by moving your model to cuda), this does a whole bunch of things like spin up a cuda context and load a bunch of extra library code corresponding to GPU kernels and all of these things will take up memory.
st30469
I did not create any cuda tensors before moving the model so your explanation is certainly possible. Although I am surprised that cuda related libraries will take over a GB of CPU memory.
st30470
Hi, I just made learnable parameter of torch. the tensor name is self.z Here is my neural network’s definition. class LSTM(nn.Module): def __init__(self, n_lstm=2048, n_reduced=128, n_hidden=32): super(LSTM, self).__init__() self.z = nn.Parameter(torch.tensor(1.0), requires_grad=True) In my case, I want to learn the “best kernel size(1 to 12)” of max_pool1d as belows, via training of the learnable parameter, z. def forward(self, input): ... output = F.max_pool1d(torch.cat((min_tensor, input), 2), z, stride=1) z is in the range of 1 to 12. So I can train 12 times, changing z to 1 from 12 And choose the best z value looking for best validation loss. However, I want to learn and decide the z via backpropagation. Cause z should be int, not tensor, I cast-type z to int from tensor as follows. z = (int)(self.z.cpu().detach().numpy()) F.max_pool1d(torch.cat((min_tensor, -QoS), 2), z, stride=1) However, the z value is not change… It always return 1.0, it is static… I’m worrying that the typecast to int from tensor caused un-learnable state. but I want to find best z value via backpropagation. It is possible? What should be edit in my code? Thanks.
st30471
Solved by eqy in post #2 The intent here looks like some kind of differentiable neural architecture search (e.g., DARTS: Differentiable Architecture Search – Google Research) However, the shape parameters to layer declarations like max_pool1d are not differentiable; the output of the model doesn’t directly depend on them! …
st30472
The intent here looks like some kind of differentiable neural architecture search (e.g., DARTS: Differentiable Architecture Search – Google Research 1) However, the shape parameters to layer declarations like max_pool1d are not differentiable; the output of the model doesn’t directly depend on them! For example, it is similar to writing y = a + b + c and expecting to take a derivative to optimize how many variables we are using in our equation. One workaround (as shown in the DARTS paper) is to consider a model with several weighted branches (where the weights are differentiable and learnable), where each branch has a different maxpool_1d configuration. The weights of each branch are updated during the architecture search training process and the branch(es) with the highest weight(s) are chosen.
st30473
Hello, I am training a UNet, and the input and output images are grayscale. When I run it, I don’t know how to fixed the error import torch import torch.nn as nn import torchvision.transforms.functional as TF class DoubleConv(nn.Module): def __init__(self, in_channels, out_channels): super(DoubleConv, self).__init__() self.conv = nn.Sequential( nn.Conv2d(in_channels, out_channels, 3, 1, 1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, 3, 1, 1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), ) def forward(self, x): return self.conv(x) class UNET(nn.Module): def __init__(self, in_channels=3, out_channels=1, features=[64, 128, 256, 512]): super(UNET, self).__init__() self.ups = nn.ModuleList() self.downs = nn.ModuleList() self.pool = nn.MaxPool2d(kernel_size=2, stride=2) # Down part of UNET for feature in features: self.downs.append(DoubleConv(in_channels, feature)) in_channels = feature # Up part of UNET for feature in reversed(features): self.ups.append( nn.ConvTranspose2d(feature * 2, feature, kernel_size=2, stride=2), ) self.ups.append(DoubleConv(feature * 2, feature)) self.bottleneck = DoubleConv(features[-1], features[-1] * 2) self.final_conv = nn.Conv2d(features[0], out_channels, kernel_size=1) def forward(self, x): skip_connections = [] for down in self.downs: x = down(x) skip_connections.append(x) x = self.pool(x) x = self.bottleneck(x) skip_connections = skip_connections[::-1] # reverse sort for idx in range(0, len(self.ups), 2): x = self.ups[idx](x) skip_connection = skip_connections[idx // 2] # floor division if x.shape != skip_connection.shape: x = TF.resize(x, size=skip_connection.shape[2:]) concat_skip = torch.cat((skip_connection, x), dim=1) x = self.ups[idx + 1](concat_skip) return self.final_conv(x) def test(): x = torch.randn((3, 1, 600, 600)) model = UNET(in_channels=1, out_channels=1) preds = model(x) print(x.shape) assert preds.shape == x.shape if __name__ == "__main__": test() It gives the error: `Traceback (most recent call last):` File "C:/DeepLearning/UNet/train.py", line 120, in <module> main() File "C:/DeepLearning/UNet/train.py", line 98, in main check_accuracy(val_loader, model, device=DEVICE) File "C:\DeepLearning\UNet\utils.py", line 62, in check_accuracy for x, y in loader: File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\dataloader.py", line 517, in __next__ data = self._next_data() File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\dataloader.py", line 1199, in _next_data return self._process_data(data) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\dataloader.py", line 1225, in _process_data data.reraise() File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\_utils.py", line 429, in reraise raise self.exc_type(msg) ValueError: Caught ValueError in DataLoader worker process 0. Original Traceback (most recent call last): File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\_utils\worker.py", line 202, in _worker_loop data = fetcher.fetch(index) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\_utils\fetch.py", line 44, in fetch data = [self.dataset[idx] for idx in possibly_batched_index] File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\_utils\fetch.py", line 44, in <listcomp> data = [self.dataset[idx] for idx in possibly_batched_index] File "C:\DeepLearning\UNet\dataset.py", line 24, in __getitem__ augmentations = self.transform(image=image, mask=mask) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\core\composition.py", line 182, in __call__ data = t(force_apply=force_apply, **data) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\core\transforms_interface.py", line 89, in __call__ return self.apply_with_params(params, **kwargs) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\core\transforms_interface.py", line 102, in apply_with_params res[key] = target_function(arg, **dict(params, **target_dependencies)) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\augmentations\transforms.py", line 1496, in apply return F.normalize(image, self.mean, self.std, self.max_pixel_value) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\augmentations\functional.py", line 141, in normalize img -= mean ValueError: operands could not be broadcast together with shapes (600,600,2) (3,) (600,600,2)
st30474
The error source utils.py: import torch import torchvision from dataset import CarvanaDataset from torch.utils.data import DataLoader def save_checkpoint(state, filename="my_checkpoint.pth.tar"): print("=> Saving checkpoint") torch.save(state, filename) def load_checkpoint(checkpoint, model): print("=> Loading checkpoint") model.load_state_dict(checkpoint["state_dict"]) def get_loaders( train_dir, train_maskdir, val_dir, val_maskdir, batch_size, train_transform, val_transform, num_workers=4, pin_memory=True, ): train_ds = CarvanaDataset( image_dir=train_dir, mask_dir=train_maskdir, transform=train_transform, ) train_loader = DataLoader( train_ds, batch_size=batch_size, num_workers=num_workers, pin_memory=pin_memory, shuffle=True, ) val_ds = CarvanaDataset( image_dir=val_dir, mask_dir=val_maskdir, transform=val_transform, ) val_loader = DataLoader( val_ds, batch_size=batch_size, num_workers=num_workers, pin_memory=pin_memory, shuffle=False, ) return train_loader, val_loader def check_accuracy(loader, model, device="cuda"): num_correct = 0 num_pixels = 0 dice_score = 0 model.eval() with torch.no_grad(): for x, y in loader: x = x.to(device) y = y.to(device).unsqueeze(1) preds = torch.sigmoid(model(x)) preds = (preds > 0.5).float() # 0, 1 matrix num_correct += (preds == y).sum() num_pixels += torch.numel(preds) dice_score += (2 * (preds * y).sum())/( (preds+y).sum() + 1e-8 ) print( f"Got {num_correct}/{num_pixels} with acc {num_correct/num_pixels*100:.2f}" ) print(f"Dice score: {dice_score/len(loader)}") model.train() def save_predictions_as_imgs( loader, model, folder="saved_images/", device="cuda" ): model.eval() for idx, (x, y) in enumerate(loader): x = x.to(device=device) with torch.no_grad(): preds = torch.sigmoid(model(x)) preds = (preds > 0.5).float() torchvision.utils.save_image( preds, f"{folder}/pred_{idx}.png" ) torchvision.utils.save_image(y.unsqueeze(1), f"{folder}{idx}.png") model.train()
st30475
Florentino: Original Traceback (most recent call last): File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\_utils\worker.py", line 202, in _worker_loop data = fetcher.fetch(index) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\_utils\fetch.py", line 44, in fetch data = [self.dataset[idx] for idx in possibly_batched_index] File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\_utils\fetch.py", line 44, in <listcomp> data = [self.dataset[idx] for idx in possibly_batched_index] File "C:\DeepLearning\UNet\dataset.py", line 24, in __getitem__ augmentations = self.transform(image=image, mask=mask) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\core\composition.py", line 182, in __call__ data = t(force_apply=force_apply, **data) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\core\transforms_interface.py", line 89, in __call__ return self.apply_with_params(params, **kwargs) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\core\transforms_interface.py", line 102, in apply_with_params res[key] = target_function(arg, **dict(params, **target_dependencies)) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\augmentations\transforms.py", line 1496, in apply return F.normalize(image, self.mean, self.std, self.max_pixel_value) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\augmentations\functional.py", line 141, in normalize img -= mean ValueError: operands could not be broadcast together with shapes (600,600,2) (3,) (600,600,2) The error has already been printed out. Can you please check your transform function?
st30476
@ejguan I have no idea how to adjust it. Hello, here is my Dataset class: from PIL import Image from torch.utils.data import Dataset import numpy as np import os class CarvanaDataset(Dataset): def __init__(self, image_dir, mask_dir, transform=None): self.image_dir = image_dir self.mask_dir = mask_dir self.transform = transform self.images = os.listdir(image_dir) def __len__(self): return len(self.images) def __getitem__(self, index): img_path = os.path.join(self.image_dir, self.images[index]) mask_path = os.path.join(self.mask_dir, self.images[index].replace(".jpq", "_mask.gif")) image = np.array(Image.open(img_path).convert("L")) mask = np.array(Image.open(mask_path).convert("L"), dtype=np.float32) mask[mask == 255.0] = 1.0 if self.transform is not None: augmentations = self.transform(image=image, mask=mask) image = augmentations["image"] mask = augmentations["mask"] return image, mask
st30477
Can you share your transform? The error comes from it. And, can you print out your the shape of image and mask?
st30478
import torch import albumentations as A from albumentations.pytorch import ToTensorV2 from tqdm import tqdm import torch.nn as nn import torch.optim as optim from model import UNET from utils import ( load_checkpoint, save_checkpoint, get_loaders, check_accuracy, save_predictions_as_imgs, ) # Hyperparameters etc. LEARNING_RATE = 1e-4 DEVICE = "cuda" if torch.cuda.is_available() else "cpu" BATCH_SIZE = 16 NUM_EPOCHS = 3 NUM_WORKERS = 2 IMAGE_HEIGHT = 600 # 1280 originally IMAGE_WIDTH = 600 # 1918 originally PIN_MEMORY = True LOAD_MODEL = False TRAIN_IMG_DIR = "C:\DeepLearning\\train\img" TRAIN_MASK_DIR = "C:\DeepLearning\\train\mask" VAL_IMG_DIR = "C:\DeepLearning\\test\img" VAL_MASK_DIR = "C:\DeepLearning\\test\mask" def train_fn(loader, model, optimizer, loss_fn, scalar): loop = tqdm(loader) for batch_idx, (data, targets) in enumerate(loop): data = data.to(DEVICE) targets = targets.float().unsqueeze(1).to(DEVICE) # forward with torch.cuda.amp.autocast(): predictions = model(data) loss = loss_fn(predictions, targets) # backward optimizer.zero_grad() scalar.scale(loss).backward() scalar.step(optimizer) scaler.update() # update tqdm loop loop.set_postfix(loss=loss.item()) def main(): train_transform = A.Compose( [ A.Resize(height=IMAGE_HEIGHT, width=IMAGE_WIDTH), A.Rotate(limit=35, p=1.0), A.HorizontalFlip(p=0.5), A.Normalize( mean=[0.0, 0.0, 0.0], std=[1.0, 1.0, 1.0], max_pixel_value=255.0, ), ToTensorV2(), ] ) val_transforms = A.Compose( [ A.Resize(height=IMAGE_HEIGHT, width=IMAGE_WIDTH), A.Normalize( mean=[0.0, 0.0, 0.0], std=[1.0, 1.0, 1.0], max_pixel_value=255.0, ), ToTensorV2(), ], ) model = UNET(in_channels=1, out_channels=1).to(DEVICE) loss_fn = nn.BCEWithLogitsLoss() # This loss combines a Sigmoid layer and the BCELoss in one single class opimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE) train_loader, val_loader = get_loaders( TRAIN_IMG_DIR, TRAIN_MASK_DIR, VAL_IMG_DIR, VAL_MASK_DIR, BATCH_SIZE, train_transform, val_transforms, NUM_WORKERS, PIN_MEMORY, ) if LOAD_MODEL: load_checkpoint(torch.load("my_checkpoint.pth.tar"), model) check_accuracy(val_loader, model, device=DEVICE) scaler = torch.cuda.amp.GradScaler() for epoch in range(NUM_EPOCHS): train_fn(train_loader, model, opimizer, loss_fn, scaler) # save model checkpoint = { "state_dict": model.state_dict(), "optimizer": optimizer.state_dict(), } save_checkpoint(checkpoint) # check accuracy check_accuracy(val_loader, model, device=DEVICE) # print some examplea to a folder save_predictions_as_imgs( val_loader, model, folder="saved_images/", device=DEVICE ) if __name__ == "__main__": main() from PIL import Image from torch.utils.data import Dataset import numpy as np import os class CarvanaDataset(Dataset): def __init__(self, image_dir, mask_dir, transform=None): self.image_dir = image_dir self.mask_dir = mask_dir self.transform = transform self.images = os.listdir(image_dir) self.masks = os.listdir(mask_dir) def __len__(self): return len(self.images) def __getitem__(self, index): img_path = os.path.join(self.image_dir, self.images[index]) mask_path = os.path.join(self.mask_dir, self.masks[index]) image = np.array(Image.open(img_path).convert("L")) mask = np.array(Image.open(mask_path).convert("L"), dtype=np.float32) mask[mask == 255.0] = 1.0 if self.transform is not None: augmentations = self.transform(image=image, mask=mask) image = augmentations["image"] mask = augmentations["mask"] return image, mask if __name__ == "__main__": data = CarvanaDataset('C:\DeepLearning\\train\img', 'C:\DeepLearning\\train\mask') image, mask = data.__getitem__(0) print(image.shape) print(mask.shape) print(image.shape)
st30479
Florentino: image = np.array(Image.open(img_path).convert("L")) You image has single channel. Florentino: train_transform = A.Compose( [ A.Resize(height=IMAGE_HEIGHT, width=IMAGE_WIDTH), A.Rotate(limit=35, p=1.0), A.HorizontalFlip(p=0.5), A.Normalize( mean=[0.0, 0.0, 0.0], std=[1.0, 1.0, 1.0], max_pixel_value=255.0, ), ToTensorV2(), ] ) But you transform function expects three channel inputs. You should either change your image or your transform function.
st30480
After your advise, the result of the shapes become: from PIL import Image from torch.utils.data import Dataset import numpy as np import os class CarvanaDataset(Dataset): def __init__(self, image_dir, mask_dir, transform=None): self.image_dir = image_dir self.mask_dir = mask_dir self.transform = transform self.images = os.listdir(image_dir) self.masks = os.listdir(mask_dir) def __len__(self): return len(self.images) def __getitem__(self, index): img_path = os.path.join(self.image_dir, self.images[index]) mask_path = os.path.join(self.mask_dir, self.masks[index]) image = np.array(Image.open(img_path).convert("L")) image = np.expand_dims(image, axis=0) mask = np.array(Image.open(mask_path).convert("L"), dtype=np.float32) mask = np.expand_dims(mask, axis=0) mask[mask == 255.0] = 1.0 if self.transform is not None: augmentations = self.transform(image=image, mask=mask) image = augmentations["image"] mask = augmentations["mask"] return image, mask if __name__ == "__main__": data = CarvanaDataset('C:\DeepLearning\\train\img', 'C:\DeepLearning\\train\mask') image, mask = data.__getitem__(0) print(image.shape) print(mask.shape) --> (1, 600, 600) (1, 600, 600) Another new error comes here when run train.py: Traceback (most recent call last): File "C:/DeepLearning/UNet/train.py", line 120, in <module> main() File "C:/DeepLearning/UNet/train.py", line 98, in main check_accuracy(val_loader, model, device=DEVICE) File "C:\DeepLearning\UNet\utils.py", line 62, in check_accuracy for x, y in loader: File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\dataloader.py", line 517, in __next__ data = self._next_data() File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\dataloader.py", line 1199, in _next_data return self._process_data(data) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\dataloader.py", line 1225, in _process_data data.reraise() File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\_utils.py", line 429, in reraise raise self.exc_type(msg) ValueError: Caught ValueError in DataLoader worker process 0. Original Traceback (most recent call last): File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\_utils\worker.py", line 202, in _worker_loop data = fetcher.fetch(index) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\_utils\fetch.py", line 44, in fetch data = [self.dataset[idx] for idx in possibly_batched_index] File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\torch\utils\data\_utils\fetch.py", line 44, in <listcomp> data = [self.dataset[idx] for idx in possibly_batched_index] File "C:\DeepLearning\UNet\dataset.py", line 26, in __getitem__ augmentations = self.transform(image=image, mask=mask) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\core\composition.py", line 182, in __call__ data = t(force_apply=force_apply, **data) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\core\transforms_interface.py", line 89, in __call__ return self.apply_with_params(params, **kwargs) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\core\transforms_interface.py", line 102, in apply_with_params res[key] = target_function(arg, **dict(params, **target_dependencies)) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\augmentations\transforms.py", line 1496, in apply return F.normalize(image, self.mean, self.std, self.max_pixel_value) File "C:\Users\Tsai\anaconda3\envs\tf\lib\site-packages\albumentations\augmentations\functional.py", line 141, in normalize img -= mean ValueError: operands could not be broadcast together with shapes (600,600,600) (3,) (600,600,600) How should I adjust my input or transform content? Thanks
st30481
Emmm. You were changing the wrong part. Two options for you, you should choose ONE of them depending on your use case: Change image to three-channel (RGB rather than L mode) image = np.array(Image.open(img_path).convert("RGB")) Change transform to single-channel train_transform = A.Compose( [ A.Resize(height=IMAGE_HEIGHT, width=IMAGE_WIDTH), A.Rotate(limit=35, p=1.0), A.HorizontalFlip(p=0.5), A.Normalize( mean=[0.0], std=[1.0], max_pixel_value=255.0, ), ToTensorV2(), ] )
st30482
Hi All, A bit of a stupid question but how can I upgrade from my CPU only install to one that has CUDA? I did read this question here 14 but it hasn’t worked. I ran the following command to update to pytorch with CUDA support: conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c nvidia but when I tried to see if cuda is available it doesn’t appear. I.e, torch.cuda.is_available() #returns False I even uninstalled all of pytorch AND anaconda itself, yet to reinstall anaconda but pytorch stills exist in a CPU-only state. I’m sure I’m doing something really stupid but any help would be greatly appreciated! Thank you!
st30483
Could you create a new conda environment and reinstall the PyTorch binary with cudatoolkit? During the installation check the log / terminal output and make sure that the CUDA version is indeed selected and installed. If the GPU still cannot be used, check that you have recent NVIDIA drivers installed on your machine.
st30484
Hi @ptrblck! I’ve managed to get it all working! The only issue I can is that I’m using Python with conda yet python seems to be using my pip install of PyTorch. For example, when I installed it via conda it found conflicts and wouldn’t detect my GPu at all (via torch.cuda.is_available()), but when I installed via pip. It worked and detect my GPU. A little bit strange to me! Is it advisable to run PyTorch from conda rather than pip? Thank you!
st30485
AlphaBetaGamma96: Is it advisable to run PyTorch from conda rather than pip? I don’t think so and it depends on your workflow. While I’m using conda to manage my environments, I’m installing a lot of different conda, pip, and source builds into them to test and debug different setups. I also make sure that my base environment in coda is “clean”, i.e. no additional packages are installed there to avoid any conflicts. I’m also sure that others prefer to use pip more and have valid reasons for it.
st30486
Well, the only reason I’m using pip is because python seems to default to it even though Python says it’s using Anaconda! I assume this is because I’m defaulting to pip even though the Python interpreter says in using Anaconda in the start-up when I use python3 via command line?
st30487
Hello everybody, I am trying to create a new training subset from two dataset, but I have a problem “Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same”. import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torchvision from torchvision import datasets, models, transforms import torch.nn.functional as F import numpy as np import pandas as pd #Agrego para trabajar matriz de resultados import tqdm import pickle # Utilizada para almacenar modelos import os import copy import matplotlib.pyplot as plt %matplotlib inline class CNN(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = torch.flatten(x, 1) # flatten all dimensions except batch x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x cnn = CNN() For example, the two dataset are: ##-----------------## CIFAR10 image_size = 32 batch_size = 4 classes = ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck') transform = transforms.Compose( [transforms.ToTensor(), transforms.Resize(image_size), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) trainset_1 = torchvision.datasets.CIFAR10(root='./data', train=True,download=True, transform=transform) testset_1 = torchvision.datasets.CIFAR10(root='./data', train=False,download=True, transform=transform) trainloader_1 = torch.utils.data.DataLoader(trainset_1, batch_size=batch_size,shuffle=True, num_workers=2) testloader_1 = torch.utils.data.DataLoader(testset_1, batch_size=batch_size,shuffle=False, num_workers=2) ##-----------------## FashionMNIST image_size = 32 batch_size = 4 classes = ('T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot') transform = transforms.Compose( [transforms.ToTensor(), transforms.Resize(image_size), transforms.Lambda(lambda x: x.repeat(3,1,1)), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) trainset_2 = torchvision.datasets.FashionMNIST(root='./data/FashionMNIST', train=True, transform=transform, download=True) testset_2 = torchvision.datasets.FashionMNIST(root='./data/FashionMNIST', train=False, download=True, transform=transform) trainloader_2 = torch.utils.data.DataLoader(trainset_2, batch_size=batch_size, shuffle=True, num_workers=0) testloader_2 = torch.utils.data.DataLoader(testset_2, batch_size=batch_size, shuffle=False, num_workers=0) Here is the problem, when I try to create the new set (now with 20 classes). Taking a subset of one and the other complete. evens = list(range(0, len(trainset_1), 10)) sub_trainset_1 = torch.utils.data.Subset(trainset_1, evens) sub_testset_1 = torch.utils.data.Subset(testset_1, evens) trainset = torch.utils.data.ConcatDataset([sub_trainset_1, trainset_2]) testset = torch.utils.data.ConcatDataset([sub_testset_1, testset_2]) trainloader = torch.utils.data.DataLoader(trainset, shuffle=True, num_workers=0, batch_size=4) testloader = torch.utils.data.DataLoader(testset, shuffle=False, num_workers=0, batch_size=4) For train, I have: criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(cnn.parameters(), lr=0.001) num_epochs = 5 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') for epoch in range(num_epochs): total_loss = 0 total_examples = 0 with tqdm.notebook.tqdm(total=len(trainloader), unit='batch', desc=f'Epoch {epoch+1}/{num_epochs}', position=100, leave=True) as pbar: for X, Y in trainloader: X = X.to(device) Y = Y.to(device) # Forward pass Y_ = cnn(X) loss = criterion(Y_, Y) # Backward pass optimizer.zero_grad() loss.backward() # Gradient descent optimizer.step() total_loss += loss.item()*X.size(0) total_examples += X.size(0) pbar.set_postfix(loss=total_loss/total_examples) pbar.update() My output is: --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-29-2eebc2f5e475> in <module> 14 15 # Forward pass ---> 16 Y_ = cnn(X) 17 loss = criterion(Y_, Y) 18 c:\users\xyz\anaconda3\envs\envgene\lib\site-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(), <ipython-input-2-fbd28d5a9e42> in forward(self, x) 10 11 def forward(self, x): ---> 12 x = self.pool(F.relu(self.conv1(x))) 13 x = self.pool(F.relu(self.conv2(x))) 14 x = torch.flatten(x, 1) # flatten all dimensions except batch c:\users\xyz\anaconda3\envs\envgene\lib\site-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(), c:\users\xyz\anaconda3\envs\envgene\lib\site-packages\torch\nn\modules\conv.py in forward(self, input) 397 398 def forward(self, input: Tensor) -> Tensor: --> 399 return self._conv_forward(input, self.weight, self.bias) 400 401 class Conv3d(_ConvNd): c:\users\xyz\anaconda3\envs\envgene\lib\site-packages\torch\nn\modules\conv.py in _conv_forward(self, input, weight, bias) 394 _pair(0), self.dilation, self.groups) 395 return F.conv2d(input, weight, bias, self.stride, --> 396 self.padding, self.dilation, self.groups) 397 398 def forward(self, input: Tensor) -> Tensor: RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same Do you know this problem? I have tried without good results. Thankful for the feedback K.
st30488
Are you trying to run the model on GPU or CPU? You need to make sure the input and the model device type match (e.g., call input = input.cuda() and model = model.cuda() where necessary).
st30489
Thank @eqy, It works now. now, if you continue running, I have two problems: In the evaluation of the model, with 20 classes… it indicates a problem with “out of bounds”. classes = ['plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck','T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] correct = [0]*len(classes) total = [0]*len(classes) acc = [0]*len(classes) cnn.eval() with tqdm.notebook.tqdm(total=len(testloader), unit='batch', desc=f'Evaluation', position=100, leave=True) as pbar: for X, Y in testloader: X, Y = X.cuda(), Y.cuda() X = X.to(device) Y = Y.to(device) _, Y_ = torch.max(cnn(X.cuda()).data, 1) for y, y_ in zip(Y, Y_): if y == y_: correct[y] += 1 total[y] += 1 acc[y] = correct[y]/total[y] pbar.set_postfix(accuracy=sum(acc)/len(classes)) pbar.update() #--# Results for class_name,class_acc in zip(classes,acc): print(f'Accuracy para la clase {str(class_name):10s}: {class_acc:.2f}') print(f'Accuracy promedio (balanceado): {sum(acc)/len(classes):.2f}') The evaluation-output is: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-48-a5f1fa2cc744> in <module> 8 position=100, leave=True) as pbar: 9 ---> 10 for X, Y in testloader: 11 X, Y = X.cuda(), Y.cuda() 12 X = X.to(device) c:\users\xyz\anaconda3\envs\envgene\lib\site-packages\torch\utils\data\dataloader.py in __next__(self) 515 if self._sampler_iter is None: 516 self._reset() --> 517 data = self._next_data() 518 self._num_yielded += 1 519 if self._dataset_kind == _DatasetKind.Iterable and \ c:\users\xyz\anaconda3\envs\envgene\lib\site-packages\torch\utils\data\dataloader.py in _next_data(self) 555 def _next_data(self): 556 index = self._next_index() # may raise StopIteration --> 557 data = self._dataset_fetcher.fetch(index) # may raise StopIteration 558 if self._pin_memory: 559 data = _utils.pin_memory.pin_memory(data) c:\users\xyz\anaconda3\envs\envgene\lib\site-packages\torch\utils\data\_utils\fetch.py in fetch(self, possibly_batched_index) 42 def fetch(self, possibly_batched_index): 43 if self.auto_collation: ---> 44 data = [self.dataset[idx] for idx in possibly_batched_index] 45 else: 46 data = self.dataset[possibly_batched_index] c:\users\xyz\anaconda3\envs\envgene\lib\site-packages\torch\utils\data\_utils\fetch.py in <listcomp>(.0) 42 def fetch(self, possibly_batched_index): 43 if self.auto_collation: ---> 44 data = [self.dataset[idx] for idx in possibly_batched_index] 45 else: 46 data = self.dataset[possibly_batched_index] c:\users\xyz\anaconda3\envs\envgene\lib\site-packages\torch\utils\data\dataset.py in __getitem__(self, idx) 217 else: 218 sample_idx = idx - self.cumulative_sizes[dataset_idx - 1] --> 219 return self.datasets[dataset_idx][sample_idx] 220 221 @property c:\users\xyz\anaconda3\envs\envgene\lib\site-packages\torch\utils\data\dataset.py in __getitem__(self, idx) 328 329 def __getitem__(self, idx): --> 330 return self.dataset[self.indices[idx]] 331 332 def __len__(self): c:\users\xyz\anaconda3\envs\envgene\lib\site-packages\torchvision\datasets\cifar.py in __getitem__(self, index) 111 tuple: (image, target) where target is index of the target class. 112 """ --> 113 img, target = self.data[index], self.targets[index] 114 115 # doing this so that it is consistent with all other datasets IndexError: index 10000 is out of bounds for axis 0 with size 10000 I do not understand, what is the reason for dimension problems? The classes function does not work the same, why is this? trainset_1.classes ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] trainset_2.classes ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] Is it required to do something in dataset before? trainset = torch.utils.data.ConcatDataset([trainset_1, trainset_2]) trainset.classes --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-51-fe0a9b13bfd7> in <module> 1 trainset = torch.utils.data.ConcatDataset([trainset_1, trainset_2]) ----> 2 trainset.classes AttributeError: 'ConcatDataset' object has no attribute 'classes' Appreciating the comments Greetings K
st30490
I’m not sure that ConcatDataset is intended to be used with two datasets that have completely different classes. You might want to iterate through it without training the model as a sanity check to see you do get 20 classes. After checking that it should be easier to take a look at the TestLoader and see what is causing the mismatch between the reported length and the actual length.
st30491
There are 2 tensors: q with dimension(64, 100, 500) and key with dimension(64, 500). I want to do dot product of key and q along the dimension of 500. Keras has a function dot() where we can give specific axes values. How can I achieve this in pytorch?
st30492
thanks! but I tried bmm and what It says that the 2 tensors should be of the same exact dimension
st30493
x = Tensor(B,C,D) y = Tensor(B,D) If you want simplicity, you can just element-wise multiply them, then sum along that dimension: (x * y.reshape(B,1,D)).sum(dim=2) If you want to save memory, you can either use einsum(): torch.einsum('bcd,bd->bc', x, y) or use bmm(): torch.bmm(x, y.rehsape(B,D,1)).reshape(B,C)
st30494
I am using Model Parallel. Single-Machine Model Parallel Best Practices — PyTorch Tutorials 1.8.1+cu102 documentation In the model, I assign the layers(or model.children()) to separate cuda devices via layer.to('cuda:0'). How can I later call the cuda device which the layer is assigned to? In torch.cuda, I can get the name of the GPU via torch.cuda.get_device_name(layer). https://pytorch.org/docs/stable/cuda.html However, that does not tell me which cuda device it is assigned to. I can even the gpu properties of the device that layer is assigned to. But I cannot get the 'cuda:0'. Any suggestions? TIA
st30495
Found a hackish work around: for layer in model.children(): try: print(getattr(next(layer.parameters()), 'device') except: continue Any better ideas are appreciated.
st30496
Hi!, I am the one who is studying pytorch! I am working on the rock/scissors/papers classification project for study. While, I am doing it, I have no idea how to make it work at all… My train dataset is consisted of generalized png image files, and my validation dataset is consisted of hand jpg images. My code is below for it First, dataset code mport os import numpy as np import torch import torch.nn as nn import natsort from skimage.transform import resize from PIL import Image from skimage.color import rgb2gray import imageio # Data Loader class CustomDataset(torch.utils.data.Dataset): def __init__(self, data_dir, transform=None):#fdir, pdir, sdir, transform=None): # 0: Paper, 1: Rock, 2: Scissors self.paper_dir = os.path.join(data_dir,'paper/') self.rock_dir = os.path.join(data_dir,'rock/') self.scissors_dir = os.path.join(data_dir,'scissors/') self.transform = transform lst_paper = os.listdir(self.paper_dir) lst_rock = os.listdir(self.rock_dir) lst_scissors = os.listdir(self.scissors_dir) lst_paper = [f for f in lst_paper] lst_rock = [f for f in lst_rock] lst_scissors = [f for f in lst_scissors] print(lst_paper) self.lst_dir = [self.paper_dir] * len(lst_paper) + [self.rock_dir] * len(lst_rock) + [self.scissors_dir] * len(lst_scissors) self.lst_prs = natsort.natsorted(lst_paper) + natsort.natsorted(lst_rock) + natsort.natsorted(lst_scissors) def __len__(self): return len(self.lst_prs) def __getitem__(self, index): self.img_dir = self.lst_dir[index] self.img_name = self.lst_prs[index] return [self.img_dir, self.img_name] def custom_collate_fn(self, data): inputImages = [] outputVectors = [] for sample in data: prs_img = imageio.imread(os.path.join(sample[0] + sample[1])) gray_img = rgb2gray(prs_img) if gray_img.ndim == 2: gray_img = gray_img[:, :, np.newaxis] inputImages.append(gray_img.reshape(300, 300, 1)) # 0: Paper, 1: Rock, 2: Scissors dir_split = sample[0].split('/') if dir_split[-2] == 'paper': outputVectors.append(np.array(0)) elif dir_split[-2] == 'rock': outputVectors.append(np.array(1)) elif dir_split[-2] == 'scissors': outputVectors.append(np.array(2)) data = {'input': inputImages, 'label': outputVectors} if self.transform: data = self.transform(data) return data class ToTensor(object): def __call__(self, data): label, input = data['label'], data['input'] input_tensor = torch.empty(len(input),300, 300) label_tensor = torch.empty(len(input)) for i in range(len(input)): input[i] = input[i].transpose((2, 0, 1)).astype(np.float32) input_tensor[i] = torch.from_numpy(input[i]) label_tensor[i] = torch.from_numpy(label[i]) input_tensor = torch.unsqueeze(input_tensor, 1) data = {'label': label_tensor.long(), 'input': input_tensor} return data And here’s train code import os import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader from torchvision import transforms, datasets from copy import copy import warnings warnings.filterwarnings('ignore') num_train = len(os.listdir("./Dataset3/train/paper")) + len(os.listdir("./Dataset3/train/rock")) + len(os.listdir("./Dataset3/train/scissors")) num_val = len(os.listdir("./Dataset3/validation/paper")) + len(os.listdir("./Dataset3/validation/rock")) + len(os.listdir("./Dataset3/validation/scissors")) transform = transforms.Compose([ToTensor()]) dataset_train = CustomDataset("./Dataset3/train/", transform=transform) loader_train = DataLoader(dataset_train, batch_size = 64, \ shuffle=True, collate_fn=dataset_train.custom_collate_fn, num_workers=1) dataset_val = CustomDataset("./Dataset3/validation/", transform=transform) loader_val = DataLoader(dataset_val, batch_size=64, \ shuffle=True, collate_fn=dataset_val.custom_collate_fn, num_workers=1) print(len(dataset_train)) print(len(dataset_val)) print(len(loader_train)) print(len(loader_val), loader_val, type(loader_val)) print(type(dataset_val.custom_collate_fn), dataset_val.custom_collate_fn) # Define Model model = nn.Sequential(nn.Conv2d(1, 32, 2, padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2), nn.Conv2d(32, 64, 2, padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2), nn.Conv2d(64, 128, 2, padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2), nn.Conv2d(128, 256, 2, padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2), nn.Conv2d(256, 256, 2, padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2), nn.Conv2d(256, 128, 2, padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2), nn.Conv2d(128, 64, 2, padding=0), nn.ReLU(), nn.MaxPool2d(kernel_size=1), torch.nn.Flatten(), nn.Linear(64, 1024, bias = True), nn.Dropout(0.75), nn.Linear(1024, 3, bias = True), ) soft = nn.Softmax(dim=1) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print("Current device:", device) model.to(device) # Define the loss criterion = nn.CrossEntropyLoss().to(device) # Define the optimizer optim = torch.optim.Adam(model.parameters(), lr = 0.001) best_epoch = 0 accuracy_save = np.array(0) epochs = 10 for epoch in range(epochs): model.train() train_loss = [] correct_train = 0 correct_val = 0 correct_batch = 0 for batch, data in enumerate(loader_train, 1): label = data['label'].to(device) inputs = data['input'].to(device) output = model(inputs) label_pred = soft(output).argmax(1) optim.zero_grad() loss = criterion(output, label) loss.backward() optim.step() correct_train += (label == label_pred).float().sum() train_loss += [loss.item()] accuracy_train = correct_train / num_train correct_val = 0 accuracy_tmp = np.array(0) with torch.no_grad(): model.eval() val_loss = [] for batch, data in enumerate(loader_val, 1): label_val = data['label'].to(device) input_val = data['input'].to(device) output_val = model(input_val) label_val_pred = soft(output_val).argmax(1) correct_val += (label_val == label_val_pred).float().sum() loss = criterion(output_val, label_val) val_loss += [loss.item()] accuracy_val = correct_val / num_val # Save the best model wrt val accuracy accuracy_tmp = accuracy_val.cpu().numpy() if accuracy_save < accuracy_tmp: best_epoch = epoch accuracy_save = accuracy_tmp.copy() torch.save(model.state_dict(), 'param.data') print(".......model updated (epoch = ", epoch+1, ")") print("epoch: %04d / %04d | train loss: %.5f | train accuracy: %.4f | validation loss: %.5f | validation accuracy: %.4f" % (epoch+1, epochs, np.mean(train_loss), accuracy_train, np.mean(val_loss), accuracy_val)) print("Model with the best validation accuracy is saved.") print("Best epoch: ", best_epoch) print("Best validation accuracy: ", accuracy_save) print("Done.") If I am running this code, "RuntimeError: size mismatch, m1: [64 x 1024], m2: [64 x 1024] at /opt/conda/conda-bld/pytorch_1579022060824/work/aten/src/THC/generic/THCTensorMathBlas.cu:290 " this error occurred Can anyone help me what’s wrong in my code? I am very confusing for now how to make it work… As I said, is it matter to use traindata set as png and validation dataset as jpg? Anyone take a look at it, and please tell me what’s wrong for now? Thank you so much.
st30497
Based on the error message the shape mismatch is created in the first linear layer: torch.nn.Flatten(), nn.Linear(64, 1024, bias = True), so you could set the in_features to 1024 and rerun the script: nn.Linear(1024, 1024, bias = True),
st30498
I have model_output of size [T, N, C] and target of size [N,T]. I won’t have targets of variable length. Is this how I declare the lengths? op_len = torch.full((N,), T, dtype=torch.long) target_len = torch.randint(1,T,(N,), dtype=torch.long) train_loss = ctc_loss(model_output, target, op_len, target_len) I am asking as the train loss is infinity after first iteration. There is no problem with the model. This happens only with CTCLoss( ). Any idea why?
st30499
Having the input size as long as the target size is not a good idea. If your target has repetitions, it won’t be representable and so the loss is infinite. If your target doesn’t have repetitions, there only is one valid alignment, and you might as well use per-sequence item cross entropy instead of CTC. I would recommend staring a bit at the CTC article on Distill.pub 1 to get ideas about your modeling with special attention on the blank token aka ϵ. After reading it, take a sequence (using batch size 1 if your want) that produces inf loss and try to manually find a good alignment for CTC loss. Then you’ll have fully understood what is wrong and have achieved CTC-Zen. Best regards Thomas
st30500
Hi, I am trying to do simple task which is indexing or masking and export it to onnx while using “ONNX_ATEN_FALLBACK” operator at pytorch, I can’t find a way to do it I tried all of the following solutions : The normal masking " [mask]" but it gives an Aten operation during conversion from pytorch to onnx The normal indexing “x[arange()][idx]” but it gives me the same result at the previous one Gather function but it is not supported at TRT yet Maked_select function but it doesn’t work because it is converted to “Nonzero ,Expand” which not supported at TRT So is there any other solutions without using external written c++ functions? Note : I have to use “ONNX_ATEN_FALLBACK” becuase I am using external nms " batchedNMSPlugin 1" So the indexing working in right way without ONNX_ATEN_FALLBACK but I have to use it since I am using external ref . this is simple piece of code to regenerate the error. import torch import torch.nn as nn class TestModel(nn.Module): def __init__(self): super(TestModel, self).__init__() def forward(self,args ): dummy_input,idx=args dummy_input=dummy_input[torch.arange(300)][idx] return dummy_input torch_model = TestModel() dummy_input = torch.randn(( 300, 44)) idx = torch.tensor([1, 2]) torch_model([dummy_input,idx]) torch_out = torch.onnx.export(torch_model, [dummy_input,idx], 'test_model.onnx', verbose=True, opset_version=11, operator_export_type=torch.onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK ) The output using ONNX_ATEN_FALLBACK : graph(%0 : Float(300:44, 44:1, requires_grad=0, device=cpu), %1 : Long(2:1, requires_grad=0, device=cpu)): %2 : Long(300:1, requires_grad=0, device=cpu) = onnx::Constant[value=<Tensor>]() %3 : Tensor[] = onnx::SequenceConstruct(%2) %4 : Float(300:44, 44:1, requires_grad=0, device=cpu) = onnx::ATen[operator="index"](%0, %3) # /volumes1/PycharmProjects/od-release/object_detection_framework/devug_onxx.py:27:0 %5 : Long(2:1, requires_grad=0, device=cpu) = onnx::Cast[to=7](%1) # /volumes1/PycharmProjects/od-release/object_detection_framework/devug_onxx.py:27:0 %6 : Tensor?[] = onnx::SequenceConstruct(%5) %7 : Float(2:44, 44:1, requires_grad=0, device=cpu) = onnx::ATen[operator="index"](%4, %6) # /volumes1/PycharmProjects/od-release/object_detection_framework/devug_onxx.py:27:0 return (%7) The output without using ONNX_ATEN_FALLBACK : Pytorch Version 1.7.1 graph(%0 : Float(300:44, 44:1, requires_grad=0, device=cpu), %1 : Long(2:1, requires_grad=0, device=cpu)): %2 : Long(300:1, requires_grad=0, device=cpu) = onnx::Constant[value=<Tensor>]() %3 : Float(300:44, 44:1, requires_grad=0, device=cpu) = onnx::Gather[axis=0](%0, %2) # /volumes1/PycharmProjects/od-release/object_detection_framework/devug_onxx.py:27:0 %4 : Long(2:1, requires_grad=0, device=cpu) = onnx::Cast[to=7](%1) # /volumes1/PycharmProjects/od-release/object_detection_framework/devug_onxx.py:27:0 %5 : Float(2:44, 44:1, requires_grad=0, device=cpu) = onnx::Gather[axis=0](%3, %4) # /volumes1/PycharmProjects/od-release/object_detection_framework/devug_onxx.py:27:0 return (%5) Environment TensorRT Version: TensorRT 7.2.2.3 GPU Type: GeForce RTX 2080 Ti/PCIe/SSE2 Nvidia Driver Version: release 460.32.03 CUDA Version: NVIDIA CUDA 11.2.1 CUDNN Version: NVIDIA cuDNN 8.1.0 Operating System + Version: Ubuntu 18.04.3 LTS Python Version (if applicable): python 3.6 and 3.8 (respectively) PyTorch Version (if applicable): pytorch 1.7.1 and pytorch 1.8(respectively) Baremetal or Container (if container which image + tag): [TensorRT Release 21.03] OPSET version:10,11,12,13, 9(doesn’t work because of upsamle layer"
st30501
Hello everyone, I am currently implementing a replay buffer and I want to preallocate the tensors for this buffer. One reason is that I want my code to crash early in case that there is not enough memory for the complete replay buffer. Everything is running strictly on CPU However, I am wondering how I can allocate this tensor so that it uses the maximum possible memory size? I tried torch.zeros(*my_shape, dtype=torch.float) and torch.rand(*my_shape, dtype=torch.float) and latter seems to use a lot more memory. I am wondering whether torch is doing some smart memory saving things for former? Best regards
st30502
Solved by tjoseph in post #2 It seems like rand needs additional memory to generate the random numbers, but then uses similar memory to zeros.
st30503
It seems like rand needs additional memory to generate the random numbers, but then uses similar memory to zeros.
st30504
Hi I am trying to implement a CNN for a binary classification in the following way: I have my input which is passed through some CNN layers. After that I have a global pooling layer. The output of the pooling is fed into a fully-connected layer and I get the output. Fairly simple. My question is about the global pooling layer. What I would like to do is: if the input instance is positive, then I want global max pooling, otherwise I want global average pooling. I have implemented it this way: In the forward pass, I have an if condition that decides on the max/avg pool. When I get a batch, I split it into positive and negative batch. I will use the sign of the batches in the if statement. So i will have two outputs (one for the positive and one for the negative batch). I concatenate these and then I continue normally. Everything runs, no error. But I can clearly see that something is going wrong in the predictions. The validation increases a lot. If I ‘force’ both positive and negative batch into only one branch of the pooling layer, then everything works fine. There might be something weird going on with the concatenation and maybe the backward pass. What am I missing? Thanks a lot for the help!
st30505
Hello, everyone I called RoIAlignFunction from RoIAlignAvg but there is an error ‘RoIAlignFunctionBackward’ object has no attribute ‘aligned_height’ How can I solve this problem??? Thank you in advance and have a nice day ############## class RoIAlignAvg(Module): def init(self, aligned_height, aligned_width, spatial_scale): super(RoIAlignAvg, self).init() self.align_function = RoIAlignFunction(aligned_height+1, aligned_width+1, spatial_scale) def forward(self, features, rois): x = self.align_function.apply(features, rois) return avg_pool2d(x, kernel_size=2, stride=1) ############# class RoIAlignFunction(Function): def init(self, aligned_height, aligned_width, spatial_scale): self.aligned_width = int(aligned_width) self.aligned_height = int(aligned_height) self.spatial_scale = float(spatial_scale) self.rois = None self.feature_size = None @staticmethod def forward(self, features, rois): self.rois = rois self.feature_size = features.size() batch_size, num_channels, data_height, data_width = features.size() num_rois = rois.size(0) ######### error occurs here!! output = features.new(num_rois, num_channels, self.aligned_height, self.aligned_width).zero_() roi_align.roi_align_forward(self.aligned_height,self.aligned_width,self.spatial_scale, features,rois, output) return output @staticmethod def backward(self, grad_output): batch_size, num_channels, data_height, data_width = self.feature_size grad_input = self.rois.new(batch_size, num_channels, data_height,data_width).zero_() roi_align.roi_align_backward_cuda(self.aligned_height,self.aligned_width,self.spatial_scale,grad_output,self.rois, grad_input) return grad_input, None
st30506
Solved by tom in post #4 Well, the rename to ctx is a good idea, but really, you would need to find a source for your shape. For example TorchVision’s roi align-function takes some more parameters (vision/roi_align_kernel.cpp at 0013d9314cf1bd83eaf38c3ac6e0e9342fa99683 · pytorch/vision · GitHub), maybe the forward should, …
st30507
morphism: ‘RoIAlignFunctionBackward’ object has no attribute ‘aligned_height’ The thing to know here is that the first argument, which more commonly is called ctx in PyTorch examples because it is NOT a self object is of type RoIAlignFunctionBackward. The code tries to access self.aligned_width but never assigned it. Best regards Thomas
st30508
Dear Thomas Thank you for your explanation But how should I modify the source above? Should I write down like this?? output = features.new(num_rois, num_channels, ctx.aligned_height, ctx.width).zero_()
st30509
Well, the rename to ctx is a good idea, but really, you would need to find a source for your shape. For example TorchVision’s roi align-function takes some more parameters (vision/roi_align_kernel.cpp at 0013d9314cf1bd83eaf38c3ac6e0e9342fa99683 · pytorch/vision · GitHub 2), maybe the forward should, too, and then assign them to ctx members.
st30510
Thank you, Thomas. I will look at the github source you recommended. It will help me a lot. Have a nice weekend and see you again. Take care
st30511
There are also some projects adding more advances sparse functionality (eg. GitHub - huggingface/pytorch_block_sparse: Fast Block Sparse Matrices for Pytorch ) that might be worth checking out.
st30512
I am trying to do convolution on frames videos (like tube of videos). So im reading video frams and make them to have the shape of NxCinxDxHxW, where Cin = 3 (channel size), and W,H= dimension (lets say they are equal) and D is 1. and N is batch size, lets say 1 for simipilicity. then i concatenate them, so my final output is having the size of NxCxDxHxW, where D is the number of frames. now i want to do 3d convolution in a way that i do convolution along the frames, like i have the input of NxCxDxHxW and kernel CxDxKxK. This is an example, m = nn.Conv3d(3, 30, (6,3,3), stride=1,padding=(0, 1, 1)) input = torch.randn(1,3 , 6, 10, 10) output = m(input) output.size() torch.Size([1, 30, 3, 10, 10]) I dont get the concept of padding along D, how does it happen? Can you please tell me how should i do it?
st30513
Check out the Conv3D documentation - https://pytorch.org/docs/stable/nn.html#torch.nn.Conv3d 1.3k According to that link the proper input size is (N, C, D, H, W)
st30514
in the conv3d documentation, we can pad for 3 dimensions like (1,1,1), the first one is pad for D, the last two are for H and W. I cannot get what does it mean to pad for D
st30515
aplassard: (N, C, D, H, W) In N,C,D,H,W… What is D? and why the channels is in the second dimension, not the last dimension?
st30516
SungmanHong: In N,C,D,H,W… What is D? D corresponds to the “depth” of the volume, which is the additional dimension spanning the volume besides the height and width. SungmanHong: and why the channels is in the second dimension, not the last dimension? PyTorch uses the (user-facing) channels-first memory layout by default, so the channel dimension is placed in dim1 (also for 2D layers).
st30517
ptrblck: D corresponds to the “depth” of the volume, which is the additional dimension spanning the volume besides the height and width. Thank you, In my specific case, the D(depth) dimension can be regarded as time dimension. My input data is video.
st30518
Hello, thanks for your attention to this matter. I want to continue to train a model with its pre-trained weights. When I evaluate this pre-trained model with model.eval(), everything is fine and the model will generate some reasonable results, but when I want to further train this model and set the mode with model.train(), the problem will occur. During the forward loop, all generated results will be zero after switching to model.train() statement (batchsize=1). Any ideas about why this happens? Thanks for your answer!
st30519
I have a tensor which represents overlapping chunks (of 2D audio coefficients): >>> x = torch.rand((2, 113, 12, 244)) # 12 blocks of 244 = 2928 >>> x = x.reshape(2, 113, 12*244) >>> print(x.shape) torch.Size([2, 113, 2928]) Each of these 12 blocks of size 244 has a 50% overlap with the next block. I would like to overlap-add on the last dimension with blocks of size 244, hop size of 122. The total coefficients should be 2928/2 = 1464. I have read different forum posts, stackoverflow questions, and the documentation of Fold/Unfold, and still have trouble discovering which parameters I need to get my desired output: >>> desired_output_size = (2, 113, 1464) >>> y = torch.nn.functional.fold(x, kernel_size=(?), stride=(?)) >>> print(y.shape) torch.Size([2, 113, 1464]) Could anybody provide some guidance? Thanks.
st30520
Hello, everyone. In every source file implementing attentions and transformers, I’ve found there is no backward function inside the class of Transformer I wonder why there is no backward method in the class of Transformer ? Also, how to backpropagate the Transformer? In pytorch, will pytorch engine backpropagate the encoder and the decode together up thru all layers? I wonder, as I mentioned, how this works without implementing backward in Transformer class. Thank you in advance
st30521
Solved by ptrblck in post #2 Autograd will use the backward methods of each submodule used in the nn.Transformer.forward method to calculate the gradients so the nn.Transformer module doesn’t necessarily need to implement a custom backward method. You could check these submodules and see, how the backward methods are defined (…
st30522
Autograd will use the backward methods of each submodule used in the nn.Transformer.forward method 1 to calculate the gradients so the nn.Transformer module doesn’t necessarily need to implement a custom backward method. You could check these submodules and see, how the backward methods are defined (i.e. if they are using custom ones or just other PyTorch operations with already defined backwards).
st30523
Dear ptrblck: Thank you for your help and your kind explanation. Have a nice week and see you again. Take care
st30524
I found this Keras implementation on Kaggle. I need to convert it to PyTorch. Can someone please help me? Also, please give an explanation if possible. I need this for my RGB dataset (3,100,100) def build_base_network(input_shape): seq = Sequential() nb_filter = [16, 32, 16] kernel_size = 3 #convolutional layer 1 seq.add(Convolution2D(nb_filter[0], kernel_size, kernel_size, input_shape=input_shape,border_mode='valid', dim_ordering='th')) seq.add(Activation('relu')) seq.add(MaxPooling2D(pool_size=(2, 2))) seq.add(Dropout(.25)) #convolutional layer 2 seq.add(Convolution2D(nb_filter[1], kernel_size, kernel_size, border_mode='valid', dim_ordering='th')) seq.add(Activation('relu')) seq.add(MaxPooling2D(pool_size=(2, 2), dim_ordering='th')) seq.add(Dropout(.25)) #convolutional layer 2 seq.add(Convolution2D(nb_filter[2], kernel_size, kernel_size, border_mode='valid', dim_ordering='th')) seq.add(Activation('relu')) seq.add(MaxPooling2D(pool_size=(2, 2), dim_ordering='th')) seq.add(Dropout(.25)) #flatten seq.add(Flatten()) seq.add(Dense(128, activation='relu')) seq.add(Dropout(0.1)) seq.add(Dense(50, activation='relu')) return seq
st30525
I would recommend to take a look at this tutorial 2 to get familiar with writing custom nn.Modules in PyTorch. Based on the posted Keras model you could define these layers in the __init__ with minor changes (change e.g. Convolution2D to nn.Conv2d) and use these layers in the forward method.
st30526
Hi, I’m working with Huggingface Transformers library to run pegasus model. It appears that the trainer class of transformers automatically handles the multi gpu training when the GPU devices are known (i.e., CUDA_VISIBLE_DEVICES flag). However, when I’m using multi-gpu for training, only one of GPUs is in near to 100% utilization and others are literally zero. Following is the command + nvidia output. I’m using pytoch 1.6.0 cuda 10. CUDA_VISIBLE_DEVICES=0,1,2 python examples/pytorch/summarization/run_summarization.py \ --model_name_or_path google/pegasus-reddit_tifu \ --do_predict \ --train_file $DS_BASE_DIR/train.json \ --validation_file $DS_BASE_DIR/validation.json \ --test_file $DS_BASE_DIR/test.json \ --output_dir /home/code-base/user_space/saved_models/pegasus/ \ --per_device_train_batch_size=2 \ --per_device_eval_batch_size=2 \ --overwrite_output_dir \ --predict_with_generate \ --text_column text \ --summary_column summary \ --num_beams 5 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 460.32.03 Driver Version: 460.32.03 CUDA Version: 11.2 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |===============================+======================+======================| | 0 Tesla V100-SXM2... On | 00000000:00:17.0 Off | 0 | | N/A 76C P0 290W / 300W | 16082MiB / 16160MiB | 100% Default | | | | N/A | +-------------------------------+----------------------+----------------------+ | 1 Tesla V100-SXM2... On | 00000000:00:18.0 Off | 0 | | N/A 43C P0 72W / 300W | 4060MiB / 16160MiB | 0% Default | | | | N/A | +-------------------------------+----------------------+----------------------+ | 2 Tesla V100-SXM2... On | 00000000:00:19.0 Off | 0 | | N/A 43C P0 72W / 300W | 4044MiB / 16160MiB | 0% Default | | | | N/A | +-------------------------------+----------------------+----------------------+ Any hint/advice?
st30527
sajastu: It appears that the trainer class of transformers automatically handles the multi gpu training when the GPU devices are known (i.e., CUDA_VISIBLE_DEVICES flag). Could you link to the trainer code, which would implement this logic? Based on the output of nvidia-smi it doesn’t seem to be the case or work as intended.
st30528
Hi , I am training NN using pytorch 1.7.0 , when i use CrossEntopyLoss() loss function then i dont have any negative loss in any epochs, since this competition evaluation metrics is multi-class logarithmic loss which i believe BCEWithLogitsLoss() in pytorch serve this logarithmic loss for multi class (correct me if i am wrong). My question is why negative loss is coming when using BCEWithLogitsLoss()? How can i prevent it, i dont wanna use CrossEntopyLoss() , Please see below code , for clarity i am showing “y” actual target and “output” prediction of model in first epoch only def get_optimizer(model, lr): optim = torch_optim.Adam(model.parameters(), lr=lr, weight_decay=0.05) return optim batch_size = 2000 def train_loop(model, epochs, lr): total = 0 sum_loss = 0 output = 0 criterion = nn.BCEWithLogitsLoss() optim= get_optimizer(model) for epoch in range(epochs): for cat, y in train_dl: model.train() batch = y.shape[0] output = model(cat) if (epoch) ==1: print(f'y is {y.float}') print(f'y is {output[:,0]}') loss = criterion(output[:,0],y.float()) optim.zero_grad() loss.backward() optim.step() total += batch sum_loss += batch*(loss.item()) valid_ds = ClassifierDataset(X_val,y_val , features) batch_size = X_train.shape[0] valid_dl=DataLoader(valid_ds,batch_size=batch_size,shuffle=False) valid_dl=DeviceDataLoader(valid_dl, device) for cat, y in valid_dl: model.eval() output = model(cat) valid_loss = criterion(output[:,0],y.float()) print(f'epoch:{epoch+1},training loss:{loss},valid loss:{valid_loss} ') train_dl = DataLoader(train_ds, batch_size=batch_size,shuffle=True) train_dl = DeviceDataLoader(train_dl, device) model = multiNet(embedding_sizes) to_device(model, device) model.apply(init_weights) train_loop(model, epochs=120, lr=0.001) epoch : 1,training loss : -127.1643,valid loss : -82.094856 y:tensor([7., 3., 1., ..., 8., 7., 1.], device='cuda:0') output:tensor([ 0.945,0.189,-1.194,...,-1.03,0.80,-1.05],device='cuda:0',grad_fn=<SelectBackward>) epoch : 2,training loss : -298.340728,valid loss : -293.701477 epoch : 3,training loss : -529.159423,valid loss : -535.595520 epoch : 4,training loss : -882.299377,valid loss : -906.745788
st30529
Solved by ptrblck in post #8 You shouldn’t use a softmax on the model outputs when you want to calculate the loss using nn.CrossEntropyLoss, since (as you’ve already said) nn.CrossEntropyLoss applies F.log_softmax and nn.NLLLoss internally, so pass the raw logits to this loss function instead. On the other hand, you can apply …
st30530
nn.BCEWithLogitsLoss expects the targets to be in the range [0, 1] as described in the docs 1. Since your targets contain values outside of this range, the loss could be negative.
st30531
@ptrblck thanks much appreciated , it means i have target between 0 to 8. To get these target between range 1 to 0 , i need to one hot encode them as follows? Class_0 Class_1 Class_2 Class_3 Class_4 Class_5 Class_6 Class_7 Class_8 Class_9 ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- 0 0 1 0 0 0 0 0 0 0
st30532
Based on the output it seems you are working on a multi-class classification (i.e. each sample has one target only), so you could directly use nn.CrossEntropyLoss. On the other hand, if some samples have zero, one, or more active targets you would be working on a multi-label classification, could use nn.BCEWithLogitsLoss and would then multi-hot encode the target.
st30533
@ptrblck why do we use softmax function during prediction of a model which is built on using nn.CrossEntropyLoss() loss function ? As i read somewhere CrossEntropyLoss has already softmax function
st30534
You shouldn’t use a softmax on the model outputs when you want to calculate the loss using nn.CrossEntropyLoss, since (as you’ve already said) nn.CrossEntropyLoss applies F.log_softmax and nn.NLLLoss internally, so pass the raw logits to this loss function instead. On the other hand, you can apply a softmax on the model outputs (logits), if you want to “visualize” the probabilities or use them in any other way besides the input to nn.CrossEntropyLoss.
st30535
I’m confused how attn_output_weights is specified to have shape (N, L, S) regardless of the number of heads. Wouldn’t there be a unique set of weights for each head? https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html 2
st30536
Solved by eqy in post #2 This seems to be because the attention weights are averaged across all of the heads:
st30537
This seems to be because the attention weights are averaged across all of the heads: github.com/pytorch/pytorch nn.MultiHeadAttention should be able to return attention weights for each head. 9 opened Mar 10, 2020 ironcadiz enhancement module: nn oncall: transformer/mha triaged ## 🚀 Feature ## Motivation Currently when using the `nn.MultiHeadAttention` …layer, the `attn_output_weights` consists of an average of the attention weights of each head, therefore the original weights are inaccessible. That makes analysis like the one made in this [paper](https://arxiv.org/abs/1906.04341v1) very difficult. ## Pitch When the `nn.MultiHeadAttention` forward is called with `need_weights=True` (and maybe a second parameter like `nead_attn_heads=True`), `attn_output_weights` should be a tensor of size `[N,num_heads,L,S]`,with the weights of each head, instead of the average of size `[N,L,S]` (following the notation in the [docs](https://pytorch.org/docs/stable/nn.html#multiheadattention)) ## Alternatives ## Additional context A small discussion about this subject with a potential solution was made [here](https://discuss.pytorch.org/t/getting-nn-multiheadattention-attention-weights-for-each-head/72195) If you guys agree, I'll gladly make a PR.
st30538
I have 2 tensor a, b. a.shape = [2, n], b.shape = [n]. The element in b[i] is 0/1, which means we choose a[0][i] or a[1][i]. I want to get tensor c, c.shape = [n], c[i] = a[0][i] or a[1][i], depending on b[i] = 0 or 1. So how can I get c without for loop?
st30539
Solved by eqy in post #2 I think you can use torch.where here: import time import torch n = 2048 a = torch.randn(2, n) b = torch.randn(n) > 0 t1 = time.time() out1 = torch.empty(n) for i in range(n): if b[i]: out1[i] = a[1][i] else: out1[i] = a[0][i] t2 = time.time() out2 = torch.where(b, a[1], a[0…
st30540
I think you can use torch.where here: import time import torch n = 2048 a = torch.randn(2, n) b = torch.randn(n) > 0 t1 = time.time() out1 = torch.empty(n) for i in range(n): if b[i]: out1[i] = a[1][i] else: out1[i] = a[0][i] t2 = time.time() out2 = torch.where(b, a[1], a[0]) t3 = time.time() print(torch.allclose(out1, out2)) print(t2-t1, t3-t2) True 0.0062215328216552734 3.409385681152344e-05
st30541
Hi, I need to calculate the gradient of output of network with respect to the parameters of network ( say with respect to first layer weights). Any suggestion how I can do this. I am doing 3-class classification so output of network is a tensor of length 3.
st30542
Solved by Rahul_Vashisht in post #7 Hi, torch.autograd.functional.jacobian works. Thanks for the reply.
st30543
Usually this is done with some criterion like mean-squared error or cross-entropy loss and an optimizer like stochastic gradient descent. The MNIST example is a good starting point for a typical training loop: examples/main.py at 2639cf050493df9d3cbf065d45e6025733add0f4 · pytorch/examples · GitHub
st30544
Yeah, I am working on the case where I need to calculate gradient of output ( not some loss function) wrt parameters. Is there any way I can do this.
st30545
What happens if you simply define a loss function that is the identity with respect to the output? (assuming that the output is a scalar)
st30546
Hi, So my output is not scalar. Is that case is there any function which I can use.
st30547
In case you want to compute something like a Jacobian, you can take a look at Automatic differentiation package - torch.autograd — PyTorch master documentation 1
st30548
I am running a model that computes the KGE embeddings of triples for a link prediction task. I am faced with a code, that I understand line by line, but I don’t understand how it serves the purpose of ranking predictions. Usually, in link prediction, the model is tested on a triple such as (Obama, spouse, ?), and the model has to predict the tail at (?). What happens is that the model calculates the likelihood score of each entity in the dataset, then ranks all entities based on that score. Afterwards, the rank of the correct answer (in this case, Michelle Obama), is saved, and should be the output of the code I am struggling with. What I don’t understand is the following: Why are they comparing scores in this code, and why are they summing them up?? In the below code, scores is a 2D array where each entry is a list with the likelihood score of each entity in the dataset (size: n_testing_triples x n_dataset_entities). targets is the score of the correct tail for each testing triple (size: n_testing_triples) This seems to sum up the number of entries that have a score >= targets. Why is that useful for the ranking? ranks[0: batch_size] += torch.sum( (scores >= targets).float(), dim=1 .cpu() Full code : KGEmb/base.py at master · HazyResearch/KGEmb · GitHub
st30549
I’m testing two DL models M1, M2 across datasets D1,D2,D3 and D4. When using D1 and D4, M2 is showing a better performance but for both D2 and D3 there is no performance improvement. Is this normal ? Or Do I have to change my architecture So M2 should always produce better performance compared to M1 for all datasets ?
st30550
Hi, I am working with multiple csv files, each containing multiple 1D data. I have about 9000 such files and total combined data is about 40 GB. I have written a dataloader like this: class data_gen(torch.utils.data.Dataset): def __init__(self, files): self.files = files my_data = np.genfromtxt('/data/'+files, delimiter=',') self.dim = my_data.shape[1] self.data = [] def __getitem__(self, i): file1 = self.files my_data = np.genfromtxt('/data/'+file1, delimiter=',') self.dim = my_data.shape[1] for j in range(my_data.shape[1]): tmp = np.reshape(my_data[:,j],(1,my_data.shape[0])) tmp = torch.from_numpy(tmp).float() self.data.append(tmp) return self.data[i] def __len__(self): return self.dim But this is working terribly slow. I was wondering if I could store all of that data in one file but I don’t have enough RAM. So is there a way around it? Let me know if there’s a way.
st30551
I am confused about a few things here. For example, why is all of the file loaded when only a single (column?) is returned at the end? Additionally, why is data repeatedly appended to without checking if a given index has already been retrieved? If you say that all of your data cannot fit in memory, it looks like this solution will keep increasing the amount of data stored in memory without ever deleting anything. Finally, are you using this dataset directly without a DataLoader that provides more parallelism? For the first issue if it turns out that you don’t need to read the entire file, you might want to see if you can use skip_header in the numpy params: numpy.genfromtxt — NumPy v1.20 Manual 1. In case you want to skip columns instead you could consider “transposing” your csv files offline so that you can skip rows at data loading time.
st30552
This is just an example. I am actually using a for loop that iterates over all the csv files. Each column in the file is a datapoint and in the end (self.data[i]), I am returning the column because that’s what I want batches of. This is how I’m implementing the TrainLoader: train_loader = torch.utils.data.DataLoader( train_dl_spec, batch_size=128, shuffle=True, num_workers=8, pin_memory=True) for data in train_loader: This is how I am implementing it in the training process: for x_train in tqdm(train_files): train_dl_spec = data_gen(x_train) train_loader = torch.utils.data.DataLoader( train_dl_spec, batch_size=128, shuffle=True, num_workers=8, pin_memory=True) for data in train_loader:
st30553
If columns are datapoints you might consider preprocessing all of the csv files to move columns to rows offline so that you can seek through files without loading basically the entire file to load a single data point.
st30554
Hello everybody, I am new to Pytorch and I am have a problem, it is probably something basic. I have just trained a simple model for FashionMNIST (as an example), then transfer the learning to a new CIFAR problem. The code for FashionMNIST is: CNN( (conv1): Conv2d(3, 16, kernel_size=(5, 5), stride=(1, 1)) (conv2): Conv2d(16, 32, kernel_size=(3, 3), stride=(1, 1)) (conv3): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1)) (fc): Linear(in_features=512, out_features=64, bias=True) (classifier): Linear(in_features=64, out_features=10, bias=True) ) class_names = trainset.classes dataiter = iter(trainloader) inputs, classes = dataiter.next() device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model_ft = best_model_FashionMNIST num_ftrs = model_ft.fc.in_features model_ft.fc = nn.Linear(num_ftrs, 64) model_ft = model_ft.to(device) criterion = nn.CrossEntropyLoss() optimizer_ft = optim.Adam(model_ft.parameters(), lr=0.0001) model_ft = train_model(model_ft, criterion, optimizer_ft, device, num_epochs=20) I train the new probem with parameters from FashionMNIST: model_ft.eval() classes = testset.classes with tqdm.notebook.tqdm(total=len(testloader), unit='batch', desc=f'Evaluation', position=100, leave=True) as pbar: for X, Y in testloader: X = X.to(device) Y = Y.to(device) _, Y_ = torch.max(model_ft(X).data, 1) for y, y_ in zip(Y, Y): if y == y_: correct[y] += 1 total[y] += 1 acc[y] = correct[y]/total[y] pbar.set_postfix(accuracy=sum(acc)/len(classes)) pbar.update() for class_name,class_acc in zip(classes,acc): print(f'Accuracy for class {class_name:5s}: {class_acc:.2f}') print(f'Accuracy: {sum(acc)/len(classes):.2f}') When trying to solve, I do not understand the reason that I get only two classes in the prediction, could someone tell me why it is due please? The results is: Y_: tensor([0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0], device=‘cuda:0’) Y: tensor([3, 8, 8, 0, 6, 6, 1, 6, 3, 1, 0, 9, 5, 7, 9, 8, 5, 7, 8, 6, 7, 0, 4, 9, 5, 2, 4, 0, 9, 6, 6, 5, 4, 5, 9, 2, 4, 1, 9, 5, 4, 6, 5, 6, 0, 9, 3, 9, 7, 6, 9, 8, 0, 3, 8, 8, 7, 7, 4, 6, 7, 3, 6, 3, 6, 2, 1, 2, 3, 7, 2, 6, 8, 8, 0, 2, 9, 3, 3, 8, 8, 1, 1, 7, 2, 5, 2, 7, 8, 9, 0, 3, 8, 6, 4, 6, 6, 0, 0, 7, 4, 5, 6, 3, 1, 1, 3, 6, 8, 7, 4, 0, 6, 2, 1, 3, 0, 4, 2, 7, 8, 3, 1, 2, 8, 0, 8, 3, 5, 2, 4, 1, 8, 9, 1, 2, 9, 7, 2, 9, 6, 5, 6, 3, 8, 7, 6, 2, 5, 2, 8, 9, 6, 0, 0, 5, 2, 9, 5, 4, 2, 1, 6, 6, 8, 4, 8, 4, 5, 0, 9, 9, 9, 8, 9, 9, 3, 7, 5, 0, 0, 5, 2, 2, 3, 8, 6, 3, 4, 0, 5, 8, 0, 1, 7, 2, 8, 8, 7, 8, 5, 1, 8, 7, 1, 3, 0, 5, 7, 9, 7, 4, 5, 9, 8, 0, 7, 9, 8, 2, 7, 6, 9, 4, 3, 9, 6, 4, 7, 6, 5, 1, 5, 8, 8, 0, 4, 0, 5, 5, 1, 1, 8, 9, 0, 3, 1, 9, 2, 2, 5, 3, 9, 9, 4, 0], device=‘cuda:0’) I appreciate your comments Greetings K.
st30555
Do you see these two-class output only during validation or was it also the case during training? Could you check the unique values of each target tensor during training and make sure it’s containing all expected 10 labels throughout the training?
st30556
Thank you very much for the answer @ptrblck. In train for Fashion MNIST, I have 10 classes. My result is in train: Accuracy para la clase T-shirt/top: 0.85 Accuracy para la clase Trouser: 0.97 Accuracy para la clase Pullover: 0.90 Accuracy para la clase Dress: 0.90 Accuracy para la clase Coat : 0.76 Accuracy para la clase Sandal: 0.97 Accuracy para la clase Shirt: 0.61 Accuracy para la clase Sneaker: 0.95 Accuracy para la clase Bag : 0.97 Accuracy para la clase Ankle boot: 0.95 Accuracy promedio (balanceado): 0.88 If I train for CIFAR with no transfer learning, the result is the same. Accuracy para la clase airplane: 0.69 Accuracy para la clase automobile: 0.78 Accuracy para la clase bird : 0.43 Accuracy para la clase cat : 0.48 Accuracy para la clase deer : 0.46 Accuracy para la clase dog : 0.57 Accuracy para la clase frog : 0.66 Accuracy para la clase horse: 0.70 Accuracy para la clase ship : 0.66 Accuracy para la clase truck: 0.69 Accuracy promedio (balanceado): 0.61 I take the learned model “best_model_FashionMNIST” and try to transfer learning for CIFAR problem. I get two classes as indicated above. I will appreciate the comments Greetings K
st30557
Are these metrics calculated using the validation dataset? If so, did you verify that the targets contain all labels during training?
st30558
Thank you very much @ptrblck for the comments, I was finally able to solve it. There was a problem in assigning the dataloader.
st30559
i have a classifier model and tried to freeze some layers and need to ensure that this layers are already freeze … is there any way to know that ?
st30560
You can check the .requires_grad attribute of all parameters, which should be frozen, and make sure it’s returning False and could additionally check that their .grad attribute is None after a backward operation.
st30561
Hi, in cross validation i use pre-trained model, i need to reset just the weights of Fc layer (classifier layer) , Thanks
st30562
You can simply assign the last layer manually after loading it. e.g., pretrained_model = [some steps that gave me the pretrained model] pretrained_model.fc = nn.Linear(input_channels, num_classes) should work for most pretrained models in torchvision.
st30563
After instantiating a 2D convolution with conv = nn.Conv2d(8, 8, 3, bias=False), whose member bias should be None, is it able to give conv a legal bias again (whether with random initialization or determined values)? I observed that bias in other default convolution modules is of the type Parameter, so I suspect there are extra procedures beyond simply conv.bias = torch.tensor(...).
st30564
I have multiple csv files which contain 1D data and I want to use each row. Each file contains different number of rows. So I have written a dataloader like this: class data_gen(torch.utils.data.Dataset): def __init__(self, files): self.files = files print("FILES: ", type(self.files)) def __getitem__(self, i): print("GETite,") file1 = self.files[i] print("FILE1: ", file1) my_data = np.genfromtxt('/data/'+file1, delimiter=',') # file1 = np.reshape(file1,(1,len(file1))) # file1 = torch.from_numpy(file1).float() # return data print(len(my_data)) return my_data def __len__(self): return len(self.files) However, when I call it like this: train_dl_spec = data_gen(train_files[0]) I get the following output: FILES: <class 'str'> It’s not processing __getitem__ for some reason. What could be the reason?
st30565
You’re likely better off concatenating those CSV files prior to initializing the dataset object. Handle all of that outside of the Dataset.
st30566
Flock1: It’s not processing __getitem__ for some reason. What could be the reason? I’m not sure I understand the issue correctly. The mentioned output is created in the __init__, so it seems the Dataset is initialized properly. What kind of issue are you seeing when calling train_dl_spec[0]?
st30567
You are passing a train_files[0] that is a string to self.files. No sure if I fully understand your question. I guess you want data_gen(train_files)[0] to invoke __getitem__ from data_gen instance.