id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st32568
|
I want to make the results of my results to be reproducible between successive independent runs. I have followed the measures in the link Reproducibility — PyTorch 1.8.1 documentation
and used
import numpy as np
inport random
import torch
random.seed(0)
torch.manual_seed(0)
np.random.seed(0)
However I couldnot use,
torch.use_deterministic_algorithms(True)
as all the model blocks does not satisfy deterministic algorithm.
I just wanted to know is there any other step to reduce the dependency on the randomness involved in any general deep laerning algorithm’s implementation?
|
st32569
|
The linked documentation mentions all necessary steps to make the code reproducible.
If your model is using a non-deterministic method and thus raises an error after setting torch.use_deterministic_algorithms(True), you could either try to implement a (slow, but) deterministic approach or try to use the CPU implementation, if absolute necessary. Note that especially the second approach would synchronize the code due to the data transfer and could slow down your code significantly and I would only recommend to use it during debugging.
|
st32570
|
Hi, I want to ask some problem about Callback.
It i need to implement timestopping and earlystopping on native pytorch without pytorch-lightning or ignite.
How do i implement? and why native pytorch does not support Callback object like tensorflow?
I will be appreciate for any answer.
|
st32571
|
Hi,
I have read the other threads related to this, so forgive me if I’ve overlooked something obvious, but I’ve tried to implement according to the advice there given, and am still having a persistent memory leak.
Here’s the code, adapted from Improved Training of Wasserstein GANs 3
class WassGP(torch.nn.Module):
def __init__(self,model,config):
super().__init__()
self.model=model
self.config=config
def gradient_penalty(self,imgs,fake_inp,lyrs,dev):
dev=dev if dev=='cpu' else f'cuda:{dev}'
eps=torch.rand([imgs.size(0),1,1,1],device=dev)
x_hat=eps*imgs+(1-eps)*fake_inp
x_hat.requires_grad=True
outp=self.model(x_hat,lyrs,dev)
gradient,=torch.autograd.grad(outp,x_hat,torch.ones_like(outp),create_graph=True)
grad_loss = self.config.training.lambda_grad*(torch.linalg.norm(gradient.view(outp.size(0),-1),2,dim=1)-1)**2
grad_loss.mean().backward()
def forward(self,real_inpt,fake_inpt,layer,dev,res,alpha):
fake_out=self.model(fake_inpt,layer,dev,res=res,alpha=alpha)
real_out=self.model(real_inpt,layer,dev,res=res,alpha=alpha)
loss_real=self.config.training.lambda_disc_real * real_out
loss_fake=self.config.training.lambda_disc_fake * fake_out
drift_loss=self.config.training.epsilon_drift*real_out.pow(2) if self.config.training.drift_loss else 0.
if self.config.training.use_gradient_penalty:
self.gradient_penalty(real_inpt,fake_inpt,layer,dev)
return (fake_out-real_out+drift_loss).mean()
I implemented this as a module subclass because I was experimenting with some things, hooks etc. but the leak occurs whether gradient_penalty is a regular function, a method in a non-module class, or any other way I can think of. I have also tried returning grad_loss and propagating it backward with the other losses with the same result.
If I leave out create_graph=True in the call to autograd.grad(), there is no leak, but also not the intended behavior, as gradients don’t flow backward properly. There are threads related to memory leaks using create_graph=True in .backward(), and they usually recommend using .autograd.grad() with create_graph=True, so I’m very confused.
I looked at python’s garbage collector tensor list, as prescribed in https://discuss.pytorch.org/t/how-to-debug-causes-of-gpu-memory-leaks/6741/2 1
and it’s unclear what exactly is happening. I see the creation of a lot of non-Parameter tensors (as well as Parameter tensors), but that could be related to the many model submodules not being used in early training (StyleGAN, employing a ProGAN training strategy).
Using torch 1.7.1+cu101
Any help is much appreciated.
|
st32572
|
Solved by delsin in post #2
Solved. I had torch.autograd.detect_anomaly(True) still in the code from a previous debugging effort. Please, for the sake of you and your loved ones, do not ever leave this line in your code without good reason! Why exactly it caused the memory leak I will perhaps investigate when I’ve finished …
|
st32573
|
Solved. I had torch.autograd.detect_anomaly(True) still in the code from a previous debugging effort. Please, for the sake of you and your loved ones, do not ever leave this line in your code without good reason! Why exactly it caused the memory leak I will perhaps investigate when I’ve finished crying over the time lost.
|
st32574
|
Hi,
I have an integer tensor T of shape Nx2 (e.g. [[2,5], [3,7], [1,4]] for N=3) and I want to convert it to a tensor of size NxC such that for every row n, only indices in the interval T[n] are assigned 1 and otherwise 0. I also know that every entry in T is between 0 and C.
Using the example above, when C = 8, the ideal output is:
[[0, 0, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 0, 0, 0]].
Is there a way to do this without explicit loops?
|
st32575
|
Solved by googlebot in post #2
I = torch.arange(C,dtype=T.dtype)
bools = (( I >= T [:,0,None]) & ( I <= T[:,1,None])) # broadcasting (1,C) with (N,1)
ints = bools.long()
|
st32576
|
I = torch.arange(C,dtype=T.dtype)
bools = (( I >= T [:,0,None]) & ( I <= T[:,1,None])) # broadcasting (1,C) with (N,1)
ints = bools.long()
|
st32577
|
Hi guys,
I’m trying to train a model based on HuggingFace (Pytorch backend) and I have a problem and I was hoping that I might get some help here (there was no answer on HF unfortunately). After a certain number of steps (~8000) my checkpoints only contain a rng_state.pth file:
** Marker unrelated **
Why could this be the case? I sync my checkpoints automatically to resum training if Colab Crashes. Unfortually out of 22 Checkpoints (1-23k) only the first 6 (1k - 7k) are valid (all required data included).
TrainingArguments(
output_dir=/share/datasets/output_run,
overwrite_output_dir=True,
do_train=True,
do_eval=True,
do_predict=False,
evaluation_strategy=IntervalStrategy.STEPS,
prediction_loss_only=False,
per_device_train_batch_size=20,
per_device_eval_batch_size=16,
gradient_accumulation_steps=1,
eval_accumulation_steps=None,
learning_rate=0.0001,
weight_decay=0.0,
adam_beta1=0.9,
adam_beta2=0.999,
adam_epsilon=1e-08,
max_grad_norm=1.0,
num_train_epochs=20.0,
max_steps=-1,
lr_scheduler_type=SchedulerType.LINEAR,
warmup_ratio=0.0,
warmup_steps=0,
logging_dir=runs/May12_05-06-46_a600ce861ff7,
logging_strategy=IntervalStrategy.STEPS,
logging_first_step=False,
logging_steps=1000,
save_strategy=IntervalStrategy.STEPS,
save_steps=1000,
save_total_limit=3,
no_cuda=False,
seed=42,
fp16=True,
fp16_opt_level=O1,
fp16_backend=auto,
fp16_full_eval=False,
local_rank=-1,
tpu_num_cores=None,
tpu_metrics_debug=False,
debug=[],
dataloader_drop_last=False,
eval_steps=1000,
dataloader_num_workers=2,
past_index=-1,
run_name=cv_sm_1,
disable_tqdm=False,
remove_unused_columns=True,
label_names=None,
load_best_model_at_end=True,
metric_for_best_model=loss,
greater_is_better=False,
ignore_data_skip=False,
sharded_ddp=[],
deepspeed=None,
label_smoothing_factor=0.0,
adafactor=False,
group_by_length=True,
length_column_name=length,
report_to=['wandb'],
ddp_find_unused_parameters=None,
dataloader_pin_memory=True,
skip_memory_metrics=False,
use_legacy_prediction_loop=False,
push_to_hub=False,
resume_from_checkpoint=None,
_n_gpu=1,
mp_parameters=
)
Ty in advcane
Edit://
According to the Trainer Output the File are created:
Saving model checkpoint to /share/datasets/output_run/checkpoint-24000
Configuration saved in /share/datasets/output_run/checkpoint-24000/config.json
Model weights saved in /share/datasets/output_run/checkpoint-24000/pytorch_model.bin
Configuration saved in /share/datasets/output_run/checkpoint-24000/preprocessor_config.json
But i could not validate that using File Explorer, ls /share/datasets/output_run/checkpoint-24000/.
I also tried to search on the entire Drive !find / -name optimizer.pt but i could only find pytorch_model.bin etc on the “valid” Checkpoints i mentioned above (1-7k), and there fore only for Checkpoints < 7000.
|
st32578
|
Solved by JoeExotic in post #3
There was a pull request for this problem, which as far as it looks solves the problem. Thanks for your time. PR
|
st32579
|
Could you explain the entire use case a bit more, please, as I’m unsure which class is supposed to store the checkpoints and also if the issue is on Colab, HF, or a combination.
Are you able to manually store the desired files using “pure” PyTorch?
|
st32580
|
There was a pull request for this problem, which as far as it looks solves the problem. Thanks for your time. PR 6
|
st32581
|
What is a good loss function between a pair of two matrices that row i in the target matrix does not necessarily correspond to row i in the trained matrix? More specifically, I’m looking to minimize the sum of all errors between target and trained tensors, where row i in the target corresponds to row j in the trained tensor where the sum of all “distances” between (i,j) is minimal, and if j is already matched with i, then it cannot match another k in the target matrix as well (“without replacement”).
Is there a built-in function for this in torch?
I’ve implemented maximum mean discrepancy (MMD) distance metric, but it’s not giving me satisfactory results.
|
st32582
|
i edited .view() to .reshape() but same error still occured…
def accuracy(output, target, topk=(1,)):
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].reshape(-1).float().sum(0)
res.append(correct_k.mul_(100.0/batch_size))
return res
full error sentence:
RuntimeError: view size is not compatible with input tensor’s size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(…) instead.
i don’t know why it still cry an error like this…
|
st32583
|
Solved by ptrblck in post #2
The posted error is raised, if the tensor it not contiguous in memory and thus view will fail.
You could either use .reshape instead as suggested in the error message or .contiguous().view(...) alternatively.
|
st32584
|
The posted error is raised, if the tensor it not contiguous in memory and thus view will fail.
You could either use .reshape instead as suggested in the error message or .contiguous().view(...) alternatively.
|
st32585
|
Hi am using this 35 implementation of DeepLab for PyTorch and would like to perform hyperparameter optimization by training multiple models at the same time.
This implementation uses nn.DataParallel to train a model on multiple GPUs.
I start one training process after executing export CUDA_VISIBLE_DEVICES=0,1. When I want to start the other training process, I get two different errors depending on the GPU ids in CUDA_VISIBLE_DEVICES.
If I type export CUDA_VISIBLE_DEVICES=0,1,2,3 and train the second model on GPU 2 and 3, I receive:
RuntimeError: module must have its parameters and buffers on device cuda:2 (device_ids[0]) but found one of them on device: cuda:0
On the other hand if I execute export CUDA_VISIBLE_DEVICES=2,3 I receive AssertionError: Invalid device id.
How can I train two models at the same time while another process already loaded the input data in a GPU.
Do I have to specify on which device the model should run using .to_device(cuda:x)?
|
st32586
|
Solved by ptrblck in post #2
Yes, I would recommend to use a single script with the DataLoader, create multiple model, push each one to the desired device via to('cuda:id') and just pass the data to each model.
Since the training is done on different devices, it should be executed in parallel.
Your approach of running multip…
|
st32587
|
oezguensi:
How can I train two models at the same time while another process already loaded the input data in a GPU.
Do I have to specify on which device the model should run using .to_device(cuda:x) ?
Yes, I would recommend to use a single script with the DataLoader, create multiple model, push each one to the desired device via to('cuda:id') and just pass the data to each model.
Since the training is done on different devices, it should be executed in parallel.
Your approach of running multiple scripts with CUDA_VISIBLE_DEVICES would make it unnecessary complicated to share the data between these processes.
|
st32588
|
Thank you. As soon as I didn’t use CUDA_VISIBLE_DEVICES and specified ‘.to(device)’ I can train multiple models, each on multiple GPUs, at the same time.
It looks like _check_balance(device_ids) somehow gets the device id 0 even though nn.DataParallel(model, device_ids=[2,3]) has GPU IDs 2 and 3. That was the problem why using CUDA_VISIBLE_DEVICES=2,3 was resulted in an AssertionError: Invalid device id .
|
st32589
|
Hello, Have you solved this problem? I am new at this field. I would like to inference two models on two gpus with same input. Which method do you recommend? cause I saw Distributed Data Parallel is only available on inferencing only one model on multiple gpus.
|
st32590
|
Dear PyTorch development community,
We are developing an application of neural network to run on an embedded device with microprocessor + DSP. Our application will perform the learning process so we need to perform the forward and backward propagation on the embedded device. We are assessing the possibility of using Pytorch and would like to know from you if your experts have any suggestions regarding this task and/or if there is any kind of incompatibility that we can face due to the use o DSPs with the library.
|
st32591
|
Hi,
I am currently trying to get the instruction trace of running ML model inference or training. Then I decided to port these instruction traces to gem5 (architecture simulator). Can I ask how I can do this? This is not clear now because this is not like C, C++, where I can compile the program to get the assembly. I don’t even know whether it is possible to get the instruction trace or assembly from interpreter language like Python.
Many thanks!!
Edward
|
st32592
|
I notice that we have some components in more than one namespace.
Such as torch::Tensor and at::Tensor, or torch::fft::fft and at::_fft_c2c. In general, it seems we have four namaspaces in Aten.
at;
c10;
caffe2 which is empty; and
torch
Questions
Why do we have four of them?
Does each of them have a different purpose that I am not realizing yet?
|
st32593
|
Apparently, at namespace is old, and torch namespace is a new implementation, as per this link 7.
|
st32594
|
In the code below, I’m using property getter and setter to assign a Module (SubNet) to an attribute of another Module (Network). It seems that the setter of Network is not called. Not like I must write the code in this way, but I’m wondering why this is prevent.
import torch.nn as nn
class Network(nn.Module):
def __init__(self):
super(Network, self).__init__()
self._sub_net = None
@property
def sub_net(self):
print("getter")
return self._sub_net
@sub_net.setter
def sub_net(self, net):
print("setter")
self._sub_net = net
class SubNet(nn.Module):
def __init__(self):
super(SubNet, self).__init__()
pass
class Object(object):
def __init__(self):
super(Object, self).__init__()
pass
ss = Network()
ss.sub_net = SubNet() # this prints nothing
# ss.sub_net = Object() # this prints "setter"
|
st32595
|
Is stumbled upon the same issue and found an answer here on Stack Overflow:
stackoverflow.com
Maybe I found something strange on pytorch, which result in property setter not working 25
python, pytorch, setter
asked by
Weiming Xiong
on 07:57AM - 09 Apr 20 UTC
As far as I understand this is the basic cause: Since nn.Module implements a __settatr__() method that doesn’t call the builtin __settattr__ in the case that the attribute you try to set is a itself a nn.Module the property setter is never executed. For other attributes that are not some PyTorch specific types (check the implementation for details: pytorch/module.py at eab59bae15bda508cdfbbc69a1a761b2b2c3780b · pytorch/pytorch · GitHub 7) the setter should work as usual.
|
st32596
|
Hi,I made this U-net code
class DoubleConv(nn.Module):
def __init__(self, in_ch, out_ch):
super(DoubleConv, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 1, 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 = DoubleConv(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),
DoubleConv(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__()
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 = DoubleConv(in_ch, out_ch)
def forward(self, x1, x2):
x1 = self.up(x1)
diffY = x2.size()[2] - x1.size()[2]
diffX = x2.size()[3] - x1.size()[3]
x1 = F.pad(x1, (diffX // 2, diffX - diffX // 2,
diffY // 2, diffY - 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, in_channels, classes):
super(Unet, self).__init__()
self.n_channels = 3
self.n_classes = 2
self.inc = InConv(in_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, classes)
def forward(self, x):
x1 = self.inc(x)
x2 = self.down1(x1)
x3 = self.down2(x2)
x4 = self.down3(x3)
x5 = self.down4(x4)
x = self.up1(x5, x4)
x = self.up2(x, x3)
x = self.up3(x, x2)
x = self.up4(x, x1)
x = self.outc(x)
return x
problem : RuntimeError: Given groups=1, weight of size [64, 4, 1, 1], expected input[6451, 1, 5, 5] to have 4 channels, but got 1 channels instead
help me plzz
|
st32597
|
It looks like there is an n_channels member of the Unet class that is defined but never used, and in_channels is defined when the Unet is created (this value seems like it is set to 4). However, the input has only a single channel? I would check how these parameters are used and whether the input data is correct because the shape seems very strange.
|
st32598
|
Hi @eqy yes a single channel. I prefer to get this architecture
image569×532 28.5 KB
help me plzz eqy
|
st32599
|
Hi @Hmrishav_Bandyopadhy I solved my problem, but I couldn’t do this architecture
can you help me plzz
image569×532 28.5 KB
|
st32600
|
This looks like the Unet architecture with some blocks skipped. You can see an example implementation in this tutorial video here 3
|
st32601
|
Hi @Hmrishav_Bandyopadhy I tested this code but
problem : RuntimeError: only batches of spatial targets supported (3D tensors) but got targets of dimension: 1
I prefer to detect two classes
|
st32602
|
Once again if you have targets of dimension 1 then there is an issue with the data that you are using. UNets are segmentation models which means that the input and output would be 2D data…Add a dimension for batch size and you have 3D tensors
|
st32603
|
When I tested this code
class UNet(nn.Module):
def __init__(self):
super(UNet, self).__init__()
self.max_pool = nn.MaxPool2d(2,2)
self.down_conv1 = doubleconv(1,64)
self.down_conv2= doubleconv(64,128)
self.down_conv3= doubleconv(128,256)
self.down_conv4= doubleconv(256,512)
self.down_conv5= doubleconv(512,1024)
def forward (self,x) :
x1= self.down_conv1(x)
#x2= self.max_pool(x1)
x3= self.down_conv2(x1)
#x4= self.max_pool(x3)
x5= self.down_conv3(x3)
#x6= self.max_pool(x5)
x7= self.down_conv4(x5)
#x8= self.max_pool(x7)
x9= self.down_conv5(x7)
RuntimeError: Given groups=1, weight of size [64, 1, 3, 3], expected input[1481, 128, 1, 1] to have 1 channels, but got 128 channels instead
help me plzz
|
st32604
|
Hi,
So I am running horovod distributed pytorch training on a machine with 16 GPUs. I see that the RAM constantly increases, and once it reaches 300GB horovod just errors out:
image1378×910 41.9 KB
I tried to debug this issue with python memory profiler using only 1 GPU. I did a few training iterations, and here is the output from the profiler:
image1148×970 164 KB
If I interpret this correctly, whenever I do loss = model(...), 63 MiB memory gets used and never gets returned (check increment column). So the problem seems to be this issue? Furthermore even after I included del loss on the bottom, the 63MiB is still not returned.
Can anyone share their insight on the root cause?
Thanks
|
st32605
|
Hello,
I am working on a model which would predict a Normal Distribution of a Vector.
Thats the code
class skilldynamic(nn.Module):
def __init__(self, state_size, obs_size, fix_var=False, fc1_units=256,fc2_units=256, seed=0):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed
fc1_units (int): Number of nodes in first hidden layer
fc2_units (int): Number of nodes in second hidden layer
"""
super(skilldynamic, self).__init__()
self.seed = torch.manual_seed(seed)
self.fc1 = nn.Linear(state_size, fc1_units)
self.fc2 = nn.Linear(fc1_units, fc2_units)
self.mean = nn.Linear(fc2_units, obs_size)
self.std = nn.Linear(fc2_units, obs_size)
self.apply(weights_init_)
self._fix_variance = fix_var
# self.multi_normal = torch.distributions.MultivariateNormal(torch.Tensor([4,3,5]),torch.Tensor([[1,0,0],[0,1,0],[0,0,1]]))
if not self._fix_variance:
self._std_lower_clip = 0.3
self._std_upper_clip = 10.0
def forward(self, state):
"""Build a network that maps state -> action values."""
x = F.relu(self.fc1(state))
x = F.relu(self.fc2(x))
mean = self.mean(x)
logvar = self.std(x).clamp(self._std_lower_clip, self._std_upper_clip)
# state_pre = NormalDistribution(mean, logvar)
return mean, logvar
def reparam(self, mean, logvar):
sigma = (logvar / 2).exp()
epsilon = torch.randn_like(sigma)
return mean + torch.mul(epsilon, sigma)
def sample(self, state):
mean, log_std = self.forward(state)
std = log_std.exp()
normal = Normal(mean, std)
x_t = normal.rsample()
y_t = torch.tanh(x_t)
log_prob = normal.log_prob(x_t)
log_prob = log_prob.sum(0, keepdim=True)
return x_t, log_prob, normal
class SkillDynamicsModell():
def __init__(self, state):
self.dynamic_model = skilldynamic(state.shape[0], state.shape[0])
self.dynamic_optimizer = torch.optim.Adam(self.dynamic_model.parameters(), 0.003)
def predict(self, state):
return self.dynamic_model.sample(state)
def learn(self, state, next_state):
x_t, log_prob, normal = self.dynamic_model.sample(state)
delta = x_next - state
model.dynamic_optimizer.zero_grad()
loss = -normal.log_prob(delta).sum(0, keepdim=True)
loss.backward()
model.dynamic_optimizer.step()
print("Loss :", loss.cpu().detach().numpy())
state = torch.Tensor(state)
next_state = torch.Tensor(next_state)
model = SkillDynamicsModell(state)
print("state", state)
print("next state", x_next)
for i in range(1000):
model.learn(state, next_state)
Does anyone see what I am doing wrong ?
|
st32606
|
Hello. I have a deeply nested list of tensors. It’s returned by an external library which was previously numpy based, which I modified to convert numpy to torch:
a = list(self.nsgt.forward((x,)))
print(type(a))
print(len(a))
print(type(a[0]))
print(len(a[0]))
print(type(a[0][0]))
print(len(a[0][0]))
print(type(a[0][0][0]))
print(len(a[0][0][0]))
print(a[0][0][0].device)
Results in:
class 'list'
59
<class 'list'>
2
<class 'list'>
126
<class 'torch.Tensor'>
304
cuda:0
I would like to convert this into a tensor with the following shape:
(59, 2, 126, 304)
Previously, when this was an np ndarray, achieving what I needed was trivial:
A = np.asarray(a)
print(A.shape)
print(A.dtype)
This would result in the correct ndarray:
(59, 2, 126, 304)
float32
In torch, I’m having trouble achieving the same with torch.tensor or torch.stack.
torch.tensor issues:
A = torch.tensor(a)
ValueError: only one element tensors can be converted to Python scalars
torch.stack issue:
A = torch.stack((a))
TypeError: expected Tensor as element 0 in argument 0, but got list
|
st32607
|
Solved by tom in post #2
For PyTorch you would need to use nested stacks or a for loop
t = torch.stack([torch.stack([torch.stack(l2, dim=0) for l2 in l1], dim=0) for l1 in a], dim=0)
or somesuch (I might have gotten the brackets wrong). But this will copy the tensors several times, so an alternative is just allocate and c…
|
st32608
|
For PyTorch you would need to use nested stacks or a for loop
t = torch.stack([torch.stack([torch.stack(l2, dim=0) for l2 in l1], dim=0) for l1 in a], dim=0)
or somesuch (I might have gotten the brackets wrong). But this will copy the tensors several times, so an alternative is just allocate and copy in a loop:
A = torch.empty(len(a), len(a[0]), len(a[0][0]), a[0][0][0].size(0))
for i, aa in enumerate(a):
assert len(aa) == A.size(1)
for j, aaa in enumerate(aa):
assert len(aaa) == A.size(2)
for k, aaaa in enumerate(aaa):
assert len(aaa) == A.size(3)
A[i, j, k] = aaaa
This will have a lot of looping but only copies data once. Once you do something interesting with the data, you might not care as much about the Python overhead of this even if you heard that Python loops are slow.
Best regards
Tomas
|
st32609
|
Perfect. I ended up using the for loop solution.
I thought of doing something similar, but I had the impression that tensors were immutable.
|
st32610
|
Hi,
I use torchvision.io.read_video to read a video, and the number of frames is based on the intrinsic fps of the video.
I wonder if there is easier way to use this api, but one can feed a specific fps value?
VideoClips 3 class has a frame_rate argument, but the size is fixed by clip_length_in_frames and frames_between_clips.
I want videos with variant duration have their corresponding frames based on the specified fps.
Thanks.
|
st32611
|
Hello, i’m struggling for 2 days to make this work. So i have Geforce GTX 950M, v 388.00 and Python 3.9( i can also do 3.8 if necessary) and Windows 10 and pip for installation. I need home help choosing the right CUDA and pytorch versions for my driver… i tried many combinations but i couldn’t make it work, everytime torch.cuda.is_available() returns False.I checked in Nvidia control panel and it point to CUDA 9.1 version but then i do not know which Pytorch to install, which one is compatible. Many thanks in advance.
|
st32612
|
The binaries for the current PyTorch release 1.8.1 and the nightly ship with CUDA10.2 and CUDA11.1 as given in the install instructions 76.
Your local CUDA9.1 installation won’t be used, if you are installing the conda binaries or pip wheels. Also note that you would need a newer NVIDIA driver, since even CUDA9.1 needs >=390.46 based on Table 1 24.
|
st32613
|
So i can safely remove the installed CUDA 9.1 from the computer and just install 1.8.1 and CUDA 10.2 / 11.1 (using pip) and work fine?
|
st32614
|
I tried pip3 install torch==1.8.1+cu111 torchvision==0.9.1+cu111 torchaudio===0.8.1 -f https://download.pytorch.org/whl/torch_stable.html 18 but when it reaches at the end of downloading everything freezes and I cannot do anything( move mouse or type). Is that normal? do I have to wait for it to recover?
Edit:I uninstalled the CUDA 9.1 from machine.
I managed to install using : pip --no-cache-dir install torch==1.8.1+cu111 torchvision==0.9.1+cu111 torchaudio===0.8.1 -f https://download.pytorch.org/whl/torch_stable.html 18
But now when i try to run the code i receive RuntimeError: CUDA driver initialization failed, you might not have a CUDA gpu. Any idea how to solve this, please?
P.S. I updated the driver and now i have v 398.35 and NVCUDA.dll 9.2. Should I uninstall the above and install something for CUDA 9.2(with pip)?
|
st32615
|
Your NVIDIA diver seems to be too old, since CUDA11.1 needs driver >= 450.80.02 as described in the linked table.
|
st32616
|
Many thanks, I managed to fix that problem but I’ve bumped into another issue, if you could take a look, please. Issues training BERT
|
st32617
|
Hi everyone,i am having some trouble with torch.einsum.Basically i am trying to mutliply two tensors in a certain way:
first = torch.rand(12,8192,2)
weights1 = torch.rand(12,8192,2)
torch.einsum('bix,iox->box',first,weights1)
But i get the following error:
einsum() operands do not broadcast with remapped shapes [original->remapped]: [12, 8192, 2]->[12, 1, 2, 8192] [12, 8192, 2]->[1, 8192, 2, 12]
Can someone explain to me what I am doing wrong?
|
st32618
|
Something is up with the i dimensions: in the first tensor it is 8192, in the second 12.
I must admit the error message isn’t as clear as it could be, so I took the liberty to file an issue with your example: Clarity of error message in einsum regressed in performance improvements · Issue #58380 · pytorch/pytorch · GitHub 127
Thank you for asking this and providing a straightforward example, it gives us a chance to improve the error message.
Best regards
Thomas
|
st32619
|
Hi, I find that after I use the transforms.resize() the value range of the resized image changes.
a = torch.randint(0,255,(500,500), dtype=torch.uint8)
print(a.size())
print(torch.max(a))
a = torch.unsqueeze(a, dim =0)
print(a.size())
compose = transforms.Compose([transforms.ToPILImage(),transforms.Resize((128,128))])
a_trans = compose(a)
print(a_trans.size)
print(a_trans.getextrema())
The result:
torch.Size([500, 500])
tensor(254, dtype=torch.uint8)
torch.Size([1, 500, 500])
(128, 128)
(79, 179)
The original range is [0,255], after the transforms.resize(), the value range change to [79,179]
I want to do the resize without the change of value range, someone could help? Thank you
|
st32620
|
Solved by Xiaoyu_Song in post #2
The problem is solved, the default algorithm for torch.transforms.resize() is BILINEAR
SO just set
transforms.Resize((128,128),interpolation=Image.NEAREST)
Then the value range won’t change!
|
st32621
|
The problem is solved, the default algorithm for torch.transforms.resize() is BILINEAR
SO just set
transforms.Resize((128,128),interpolation=Image.NEAREST)
Then the value range won’t change!
|
st32622
|
@Xiaoyu_Song,
did you get this error?
UserWarning: Argument interpolation should be of type InterpolationMode instead of int. Please, use InterpolationMode enum.
It still trains, not too sure what does this error mean.
|
st32623
|
This warning points to this PR 88, which seems to have introduced the InterpolationMode argument, since torchvision.transforms are supporting PIL.Images as well as tensors now (at least the majority, if I’m not mistaken).
CC @vfdev-5 to correct me.
|
st32624
|
Can you please see this: Regarding transforms.resize and drastic changes in accuracy 137, I have the same question regarding which is better or a preferred way to resize an image. Thanks in advance, Sriram Na.
|
st32625
|
I used the code below to export interpolation operation to onnx file.
repeat = torch.nn.UpsamplingNearest2d(scale_factor=2)
repeat.eval()
torch.onnx.export(repeat, torch.ones((1, 3, 4, 4)), “repeat.onnx”)
And the console output is:
torch.onnx.export(repeat, torch.ones((1, 3, 4, 4)), “repeat.onnx”)
File “D:\ProgramData\Anaconda3\lib\site-packages\torch\onnx_init_.py”, line 25, in export
return utils.export(*args, **kwargs)
File “D:\ProgramData\Anaconda3\lib\site-packages\torch\onnx\utils.py”, line 131, in export
strip_doc_string=strip_doc_string)
File “D:\ProgramData\Anaconda3\lib\site-packages\torch\onnx\utils.py”, line 363, in _export
_retain_param_name, do_constant_folding)
File “D:\ProgramData\Anaconda3\lib\site-packages\torch\onnx\utils.py”, line 278, in _model_to_graph
_disable_torch_constant_prop=_disable_torch_constant_prop)
File “D:\ProgramData\Anaconda3\lib\site-packages\torch\onnx\utils.py”, line 188, in _optimize_graph
graph = torch._C._jit_pass_onnx(graph, operator_export_type)
File “D:\ProgramData\Anaconda3\lib\site-packages\torch\onnx_init_.py”, line 50, in _run_symbolic_function
return utils._run_symbolic_function(*args, **kwargs)
File “D:\ProgramData\Anaconda3\lib\site-packages\torch\onnx\utils.py”, line 589, in _run_symbolic_function
return fn(g, *inputs, **attrs)
File “D:\ProgramData\Anaconda3\lib\site-packages\torch\onnx\symbolic.py”, line 130, in wrapper
args = [_parse_arg(arg, arg_desc) for arg, arg_desc in zip(args, arg_descriptors)]
File “D:\ProgramData\Anaconda3\lib\site-packages\torch\onnx\symbolic.py”, line 130, in
args = [_parse_arg(arg, arg_desc) for arg, arg_desc in zip(args, arg_descriptors)]
File “D:\ProgramData\Anaconda3\lib\site-packages\torch\onnx\symbolic.py”, line 90, in _parse_arg
raise RuntimeError("Failed to export an ONNX attribute, "
RuntimeError: Failed to export an ONNX attribute, since it’s not constant, please try to make things (e.g., kernel size) static if possible
My pytorch version is 1.1.0, py3.6_cuda90_cudnn7_1.
|
st32626
|
Hello ! Im trying to run my CNN but it fails due to memory shortage. I guess the problem is that i have some variables which consume all the memory but i do not see the mistake. It is to say that i am quite new to working with neural networks and worring about memory !
I really appreciate any help.
Here is the code which i guess does the trouble :
Annotation (1)1077×610 37.2 KB
with the following error :
RuntimeError: CUDA out of memory. Tried to allocate 6.60 GiB (GPU 0; 31.75 GiB total capacity; 21.92 GiB already allocated; 1.87 GiB free; 28.56 GiB reserved in total by PyTorch)
|
st32627
|
If i am having say quite a large dataset with around 50k images, will it be efficient to store the paths in a dictionary and read them in the custom dataloader? Or is CSV a better option?
|
st32628
|
A dataset, probably?
This depends on lots of factors (not lest how you intend to read CSVs), but to be honest, I would expect the time for either to be very small compared to the rest of the training. So my advice not worry about it until it becomes the bottleneck.
|
st32629
|
Okay, thanks @tom for the reply, unfortunately its a custom dataset, so i wont be able to sshare it. Thanks
|
st32630
|
The currently built binaries ship with the CUDA10.2 and 11.1 runtime, so you could pick one of these two or alternatively build from source using a locally installed CUDA10.0 toolkit.
|
st32631
|
I have a custom loss function defined and I hit a wall debugging it. It is designed to return loss that is scaled according to the output value:
import torch
from torch import nn
import torch.nn.functional as F
class ConditionalMeanRelativeLoss(nn.Module):
def __init__(self):
super(ConditionalMeanRelativeLoss, self).__init__()
def forward(self, output, target):
# calculate absolute errors
absolute_errors = torch.abs(torch.subtract(output, target))
# where target is too small, use just the absolute errors to avoid divide by 0
loss = torch.where(torch.abs(target) < 0.001, absolute_errors, torch.abs(torch.divide(absolute_errors, target)))
# return mean loss
return torch.mean(loss)
I was conscious that I might create a divide by 0 error, so I use a “where” to try to avoid it. This is the first custom loss function I have ever defined, and when I use it, it returns all nan values. I used the torch anomaly detection and I saw this error:
/opt/miniconda3/envs/torch/lib/python3.8/site-packages/torch/autograd/__init__.py:145: UserWarning: Error detected in DivBackward0. Traceback of forward call that caused the error:
File "HybridMethodConfig1.py", line 322, in <module>
loss = train_model(deriv, derivtrainloader, DE_loss_fn, DE_optim, DEVICE)
File "/Users/henrydikeman/github/CombustTorch/auto_ode/ModelUtilities.py", line 44, in train_model
batch_loss = loss_fn(predictions, batch_results)
File "/opt/miniconda3/envs/torch/lib/python3.8/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "/Users/henrydikeman/github/CombustTorch/auto_ode/CustomLossFunctions.py", line 17, in forward
loss = torch.where(torch.abs(target) < 0.005, absolute_errors, torch.abs(torch.divide(absolute_errors, target)))
(Triggered internally at /Users/distiller/project/conda/conda-bld/pytorch_1614389903258/work/torch/csrc/autograd/python_anomaly_mode.cpp:104.)
Variable._execution_engine.run_backward(
0%| | 0/1483 [00:00<?, ?it/s]
Traceback (most recent call last):
File "HybridMethodConfig1.py", line 322, in <module>
loss = train_model(deriv, derivtrainloader, DE_loss_fn, DE_optim, DEVICE)
File "/Users/henrydikeman/github/CombustTorch/auto_ode/ModelUtilities.py", line 47, in train_model
batch_loss.backward()
File "/opt/miniconda3/envs/torch/lib/python3.8/site-packages/torch/tensor.py", line 245, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs)
File "/opt/miniconda3/envs/torch/lib/python3.8/site-packages/torch/autograd/__init__.py", line 145, in backward
Variable._execution_engine.run_backward(
RuntimeError: Function 'DivBackward0' returned nan values in its 0th output.
Before this I have been using the built-in MSE loss, so I just subbed out the function and treated it as a drop-in replacement. I was fairly sure that torch.where is reverse differentiable, but then again I am not totally sure. You can see I kind of went overboard with the torch operations trying to track down the issue.
I am 1000% sure my code worked before with MSE loss, so unless I need to treat this function different than MSE loss my code besides this should be good.
Edit: I tried while taking out the line with “torch.where” and it worked. So I guess I’m asking if there is any way I can get this elementwise conditional logic to work.
|
st32632
|
Solved by KFrank in post #2
Hi Henry!
It looks like your issue is due to a troublesome bug in the innards of
autograd – not specific to torch.where(), but in lower-level infrastructure.
However, in your use case, you can work around it by clamping the
denominator of your potential divide-by-zero away from zero. Here
is …
|
st32633
|
Hi Henry!
hankdikeman:
I was conscious that I might create a divide by 0 error, so I use a “where” to try to avoid it. This is the first custom loss function I have ever defined, and when I use it, it returns all nan values.
It looks like your issue is due to a troublesome bug in the innards of
autograd – not specific to torch.where(), but in lower-level infrastructure.
However, in your use case, you can work around it by clamping the
denominator of your potential divide-by-zero away from zero. Here
is an illustrative script that contains a modified version of your custom
loss function:
import torch
from torch import nn
import torch.nn.functional as F
print ('torch.__version__', torch.__version__)
torch.manual_seed (2021)
class ConditionalMeanRelativeLoss(nn.Module):
def __init__(self):
super(ConditionalMeanRelativeLoss, self).__init__()
def forward(self, output, target):
# calculate absolute errors
absolute_errors = torch.abs(torch.subtract(output, target))
# where target is too small, use just the absolute errors to avoid divide by 0
loss = torch.where(torch.abs(target) < 0.001, absolute_errors, torch.abs(torch.divide(absolute_errors, target)))
print ('pre-mean loss =', loss)
# return mean loss
return torch.mean(loss)
class ConditionalMeanRelativeLossB(nn.Module):
def __init__(self):
super(ConditionalMeanRelativeLossB, self).__init__()
def forward(self, output, target):
# calculate absolute errors
absolute_errors = torch.abs(torch.subtract(output, target))
# where target is too small, use just the absolute errors to avoid divide by 0
# but clamp abs (target) away from zero to avoid "ghost" divide by 0
abs_target = torch.abs (target).clamp (0.0005)
loss = torch.where(abs_target < 0.001, absolute_errors, torch.divide(absolute_errors, abs_target))
print ('pre-mean loss (B) =', loss)
# return mean loss
return torch.mean(loss)
outputA = torch.randn (5)
outputB = outputA.clone()
outputA.requires_grad = True
outputB.requires_grad = True
target = torch.randn (5)
target[2] = 0.0
target[3] = 0.0
print ('outputA =', outputA)
print ('outputB =', outputB)
print ('target =', target)
ConditionalMeanRelativeLoss() (outputA, target).backward()
print ('outputA.grad =', outputA.grad)
ConditionalMeanRelativeLossB() (outputB, target).backward()
print ('outputB.grad =', outputB.grad)
And here is its output:
torch.__version__ 1.7.1
outputA = tensor([ 2.2871, 0.6413, -0.8615, -0.3649, -0.6931], requires_grad=True)
outputB = tensor([ 2.2871, 0.6413, -0.8615, -0.3649, -0.6931], requires_grad=True)
target = tensor([ 0.9023, -2.7183, 0.0000, 0.0000, 0.4822])
pre-mean loss = tensor([1.5346, 1.2359, 0.8615, 0.3649, 2.4375], grad_fn=<SWhereBackward>)
outputA.grad = tensor([ 0.2216, 0.0736, nan, nan, -0.4148])
pre-mean loss (B) = tensor([1.5346, 1.2359, 0.8615, 0.3649, 2.4375], grad_fn=<SWhereBackward>)
outputB.grad = tensor([ 0.2216, 0.0736, -0.2000, -0.2000, -0.4148])
As to the autograd bug: A cluster of github issues shows that this is a
known problem. I don’t understand the details, but some of the comments
suggest that this bug might be tricky to fix, and perhaps won’t get fixed.
But I think (probably in general, not just in your use case) that if you
understand what is going on, you can work around it.
Here are a few of the relevant github issues:
github.com/pytorch/pytorch
backprop through torch.where backprops nans through path that was not taken 3
opened
Apr 20, 2020
closed
Apr 20, 2020
jonasrauber
I think backprop through `torch.where` is wrong in certain special cases.
## …To Reproduce
```python
t = 0
x = torch.ones(()).requires_grad_()
y = t * (x / t) # just an example; anything that produces nan's works
z = torch.where(x >= t, x, y)
z.backward()
# the forward pass works fine (the `nan`'s in `y` do not affect z)
# NOTE: this is unlike a naive implement of where that does `cond * x + (1 - cond) * y`
print(z)
# tensor(1., grad_fn=<SWhereBackward>)
# but the backward pass backprops the `nan`'s from y into x, even though the y path is never taken in torch.where
print(x.grad)
# tensor(nan)
```
## Expected behavior
```python
print(x.grad)
# tensor(1.)
```
This would be the correct gradient.
In practice, this bug can easily happen if one runs the above code for different t (including 0) and assumes that the `nan`'s for `t = 0` should not matter because the `torch.where` always selects the first path that has no `nan`s (and the forward pass does handle it correctly).
## Environment
- PyTorch Version 1.4
github.com/pytorch/pytorch
Incorrect gradients for torch.where when one of the target tensors contains inf/nan 2
opened
Jul 25, 2019
closed
Jul 25, 2019
egrefen
## 🐛 Bug
The `grad_fn` of `torch.where` returns the gradients of the wrong ar…gument, rather than of the selected tensor, if the other tensor's gradients have infs or nans.
## To Reproduce
Run this code:
```python
x = torch.tensor([16., 0.], requires_grad=True)
y = x/2 # tensor([8., 0.], grad_fn=<DivBackward0>)
z = x.sqrt() + 1 # tensor([5., 1.], grad_fn=<SqrtBackward>)
# Calculate dy/dx, dz/dx
dydx = torch.autograd.grad(y.sum(), x, retain_graph=True)[0] # tensor([0.5000, 0.5000])
dzdx = torch.autograd.grad(z.sum(), x, retain_graph=True)[0] # tensor([0.1250, inf])
# Define w = [w0, w1] == [y0, z1]
w = torch.where(x == 0., y, z) # tensor([5., 0.], grad_fn=<SWhereBackward>)
expected_dw_dx = torch.where(x == 0., dydx, dzdx) # tensor([0.1250, 0.5000])
dwdx = torch.autograd.grad(w.sum(), x, retain_graph=True)[0] # is actually tensor([0.1250, inf])
print("`torch.where` communicates gradients correctly:", torch.equal(expected_dw_dx, dwdx))
```
## Expected behavior
I would expect `expected_dw_dx == dwdx` in the example above.
## Environment
Please copy and paste the output from our
[environment collection script](https://raw.githubusercontent.com/pytorch/pytorch/master/torch/utils/collect_env.py)
(or fill out the checklist below manually).
You can get the script and run it with:
```
wget https://raw.githubusercontent.com/pytorch/pytorch/master/torch/utils/collect_env.py
# For security purposes, please check the contents of collect_env.py before running it.
python collect_env.py
```
PyTorch version: 1.1.0
Is debug build: No
CUDA used to build PyTorch: 9.0.176
OS: Ubuntu 18.04.1 LTS
GCC version: (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0
CMake version: version 3.10.2
Python version: 3.7
Is CUDA available: Yes
CUDA runtime version: 9.0.176
GPU models and configuration:
GPU 0: Quadro GP100
GPU 1: Quadro GP100
Nvidia driver version: 410.79
cuDNN version: Could not collect
Versions of relevant libraries:
[pip] numpy==1.16.4
[pip] torch==1.1.0
[pip] torchvision==0.3.0
[conda] torch 1.1.0 <pip>
[conda] torchvision 0.3.0 <pip>
github.com/pytorch/pytorch
Incorrect NaN gradient from distribution.Normal.log_prob when using subset 3
opened
Dec 12, 2018
closed
Dec 13, 2018
samedii
## 🐛 Bug
When a subset of a log_prob tensor is NaN then you can select the subs…et that is not NaN. This should then result in a finite gradient (in many cases) when doing backprop through the distribution. It does not
## To Reproduce
Steps to reproduce the behavior:
```
import numpy as np
import torch
import torch.nn as nn
import torch.distributions as dist
x = torch.tensor([1.0,2,3,np.nan])
y = torch.tensor([1.0,2,3,4])
k = nn.Parameter(0.01*torch.randn(1))
d = dist.Normal(loc=k*x, scale=1)
log_prob = d.log_prob(y)
print(log_prob)
# tensor([-1.4253, -2.9444, -5.4763, nan], grad_fn=<SubBackward>)
loss = -log_prob[:-1].mean()
print(loss)
# tensor(3.2820, grad_fn=<NegBackward>)
loss.backward()
print(k.grad)
# tensor([nan])
```
## Expected behavior
Should see a finite gradient.
## Environment
PyTorch version: 0.4.1
Is debug build: No
CUDA used to build PyTorch: 9.0
OS: Microsoft Windows 7 Enterprise
GCC version: Could not collect
CMake version: Could not collect
Python version: 3.6
Is CUDA available: No
CUDA runtime version: No CUDA
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
Versions of relevant libraries:
[pip] numpy (1.13.3)
[pip] numpydoc (0.7.0)
[conda] mkl 2018.0.0 h36b65af_4
[conda] mkl-service 1.1.2 py36h57e144c_4
Best.
K. Frank
|
st32634
|
I am getting ValueError: optimizer got an empty parameter list when I run this code. What am I missing? Tried using nn.Parameters and still getting error on model parameters a and b. I just want to track and update these two scalars on this toy problem.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader
class RosenbrockFunction2N(nn.Module):
def __init__(self):
super(RosenbrockFunction2N, self).__init__()
self.a = torch.rand(1, requires_grad=True)
self.b = torch.rand(1, requires_grad=True)
def forward(self, x, y):
return (self.a - x)**2 + self.b(y-x**2)**2
# Dataset
inputs = [[1., 3.], [5., 7.], [2., 4.], [3., 9.]]
targets = []
for i in inputs:
targets.append([(1-i[0]**2) + (i[1] - i[0]**2)**2])
inputs = torch.tensor(inputs)
targets = torch.tensor(targets)
train_ds = TensorDataset(inputs, targets)
train_dl = DataLoader(train_ds)
# Load model
model = RosenbrockFunction2N()
# Loss and Optimizer
loss_fn = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
for i in range(5):
for inputs, target in train_dl:
optimizer.zero_grad()
output = model(inputs[0][0], inputs[0][1])
loss = loss_fn(output, target)
loss.backward()
optimizer.step()
|
st32635
|
Solved by ptrblck in post #4
This error is raised by trying to call the parameter in:
self.b(y-x**2)**2
What kind of operation should be performed in this line of code?
|
st32636
|
Registering the a and b tensors as nn.Parameters should work (alternatively you could also use self.register_parameter). In your current code you are assigning tensors as model attributes, which won’t be registered as parameters internally.
|
st32637
|
Thanks, @ptrblck. Sorry, I’m not used to working with scalars like this. When I change it to this:
self.a = nn.Parameter(torch.tensor(1., requires_grad=True))
self.b = nn.Parameter(torch.tensor(1., requires_grad=True))
I get this:
TypeError: 'Parameter' object is not callable
|
st32638
|
This error is raised by trying to call the parameter in:
self.b(y-x**2)**2
What kind of operation should be performed in this line of code?
|
st32639
|
Such a simple problem. Yeah, it’s just a missing multiplication symbol. Thanks @ptrblck !
|
st32640
|
Hey guys,
I have probabilities as parameters in my model and I wish to normalise them (divide by their norm so they sum up to 1) as they are being optimised. Probably I should impose this constraint during training with:
with torch.no_grad():
However I haven’t found a way to so, as any assignments, like
model.probs = model.probs/model.probs.sum()
don’t work, bc you cannot assign a float to a parameter. Any suggestions?
Thank you in advance,
Nikos
|
st32641
|
I think you could try to apply a similar approach as is used in weight_norm 1, which uses hooks to normalize the parameters.
|
st32642
|
I am trying to create a custom class for my dataset. Can anyone figure out what is wrong in the code given below?
class Map_dataset(Dataset):
def __init__(self,root_dir,transforms=None):
self.transforms=transforms
self.root_dir=root_dir
self.list_dir=os.listdir(self.root_dir)
def __getitem__(self,idx):
img_path=os.path.join(self.root_dir,self.list_dir[idx])
whole_image=np.array(Image.open(img_path))
input_image=torch.tensor(whole_image[:,:600,:])
target_image=torch.tensor(whole_image[:,600:,:])
if (self.transforms):
for t in self.transforms:
input_image=t(input_image)
target_iage=t(target_image)
return input_image,target_image
def __len__(self):
return len(self.list_dir)
img_size=256
batch_size=16
composed=torchvision.transforms.Compose([torchvision.transforms.Resize((img_size,img_size))])
data=Map_dataset("../input/pix2pix-maps/train",composed)
data_loader=DataLoader(data,batch_size,shuffle=True)
input_images,target_images=iter(data_loader).next()
print(input_images.shape,target_images.shape)
|
st32643
|
Solved by ptrblck in post #2
Based on the error message, the issue is in trying to iterate transforms.Compose, which is not working:
for t in self.transforms:
input_image=t(input_image)
target_iage=t(target_image)
transforms.Compose will apply the transformation in the specified order, so you can use it directly:
inp…
|
st32644
|
Based on the error message, the issue is in trying to iterate transforms.Compose, which is not working:
for t in self.transforms:
input_image=t(input_image)
target_iage=t(target_image)
transforms.Compose will apply the transformation in the specified order, so you can use it directly:
input_image = self.transforms(input_image)
|
st32645
|
Hi members,
I am evaluating multi-class classification task using precision, recall, accuracy, and F-Score metrics. In all my experiments accuracy and recall are the same but other two metrics have bit different values. I am calculating average=“weighted” through scikit learn library.
How should I interperate this behavior?
Thanks!
|
st32646
|
Hi everybody!
I am trying to test prediction on my CNN model. I have 2 classes(Noise and Original) and accuracy on test data was ~97-98%. So now, i want to test it with data, which model did not see at all. If i understood correctly, i need to make a folder where will be unseen by model modified with Noise images and non modified images. But i have a problem, i do not really understand how i can give those test images without subfolders(classes). Because when model was learning, there were two subfolders - Noise & Original, but now i want to get an answer from model, which class the image is.
Now code looks like this:
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import os
import pandas as pd
transform = transforms.Compose([
transforms.Resize(32),
transforms.CenterCrop(32),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
exam_data_path = 'D:/RTU/dataset/ready_dataset_2classes/exam'
weigths_path = 'D:/RTU/dataset/weights_done/weights_noise_original037-97%.pt'
exam_data = torchvision.datasets.ImageFolder(root=exam_data_path, transform=transform)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# convolutional layer (sees 32x32x3 image tensor)
self.conv1 = nn.Conv2d(3, 16, 3, padding=1)
# convolutional layer (sees 16x16x16 tensor)
self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
# convolutional layer (sees 8x8x32 tensor)
self.conv3 = nn.Conv2d(32, 64, 3, padding=1)
# max pooling layer
self.pool = nn.MaxPool2d(2, 2)
# linear layer (64 * 4 * 4 -> 500)
self.fc1 = nn.Linear(64 * 4 * 4, 500)
# linear layer (500 -> 10)
self.fc2 = nn.Linear(500, 250)
self.fc3 = nn.Linear(250, 2)
# dropout layer (p=0.25)
self.dropout = nn.Dropout(0.25) #0.25
def forward(self, x):
# add sequence of convolutional and max pooling layers
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = self.pool(F.relu(self.conv3(x)))
# flatten image input
x = x.view(-1, 64 * 4 * 4)
# add dropout layer
x = self.dropout(x)
# add 1st hidden layer, with relu activation function
x = F.relu(self.fc1(x))
# add dropout layer
x = self.dropout(x)
# add 2nd hidden layer, with relu activation function
x = F.relu(self.fc2(x))
x = self.dropout(x)
x = self.fc3(x)
return x
index = -1
# Disable grad
with torch.no_grad():
# Retrieve item
for x in range(10):
index = index + 1
item = exam_data[index]
image = item[0]
true_target = item[1]
mlp = Net()
optimizer = optim.SGD(mlp.parameters(), lr=0.01)
epoch=5
valid_loss_min = np.Inf
checkpoint = torch.load(weigths_path , map_location=torch.device('cpu'))
mlp.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
epoch = checkpoint['epoch']
valid_loss_min = checkpoint['valid_loss_min']
print(image)
image = image.reshape(1 , 3, 32, 32)
mlp.eval()
# Generate prediction
prediction = mlp(image)
# Predicted class value using argmax
predicted_class = np.argmax(prediction)
# Reshape image
image = image.reshape(32, 32, 3)
# Show result
plt.imshow(image)
plt.title(f'Prediction: {predicted_class} - Actual target: {true_target}')
plt.show()
As i understood, i need to make the own dataset. I found some info in PyTorch documentation, but there are a lot of new information, which i do not understand at all and my mind is blowing
Maybe somebody can help me and explain in a lighter language how i can solve it.
|
st32647
|
I am new to the NN and PyTorch, so some things are not obvious to me. I would really appreciate help here. I wanted to use nn.CrossEntropyLoss on a tensor of shape [3, 14, 136], where 3 is a batch_size, 14 is sequence_length and 136 is number of tokens. It is one-hotted by number_of_tokens dimension.
I put this tensor into the nn.CrossEntropyLoss with the reference tensor of shape [3, 14] with correct tokens index in second dimension. However I’ve got an error:
ValueError: Expected target size (3, 136), got torch.Size([3, 14])
As I thought from the documentation, my dimensions were correct, what do I do wrong to receive this error?
|
st32648
|
Solved by ptrblck in post #2
Based on the docs the output of the model should have the shape [batch_size, nb_classes, *], while the target should have the shape [batch_size, *], so you would need to permute the output to the shape [batch_size=3, nb_classes=nb_tokens=136, seq_len=14] (assuming 136 equals the number of classes). …
|
st32649
|
Based on the docs the output of the model should have the shape [batch_size, nb_classes, *], while the target should have the shape [batch_size, *], so you would need to permute the output to the shape [batch_size=3, nb_classes=nb_tokens=136, seq_len=14] (assuming 136 equals the number of classes).
|
st32650
|
Thank you for your help!
I did that before, but my loss becomes very big (4.9) and model generates rubbish of the same letter over and over again could you advise me where to keep attention to beat my problem?
|
st32651
|
I would recommend to try to overfit a small data sample (e.g. just 10 samples) and make sure your current model is able to do so e.g. by playing around with some hyperparameters. Once this is done, you could try to scale up the use case again.
|
st32652
|
Hello everyone !
I have a large dataset about a casting machine and its corresponding process parameters . So basically each row is an observation with about 200 parameters and then the corresponding class label of 0 or 1 where 0 means the part is NOT defective and 1 means the part was badly manufactured. We are trying to map these process parameters to the correct class prediction and right now I am using a feedforward network with 5 layers and the area under ROC curve is 0.76.
What I have been thinking is maybe we lack temporal information in our batches which are now created using stratified train test split and later on balanced from both classes with a WeightedRandomSampler.
So my idea is to first sort the observations in ascending order of time, do not shuffle and then create the batches so that the temporal order is preserved. However when I take this approach, my mini batches become severely imbalanced. Nevertheless, there might be some mini batches where the minority class has a clear majority , for example 8 out of 10 samples in a mini batch belong to minority class. Lets say the IDs of such mini batches are from 40 to 60. So I would like the first iteration of my epoch to take a normal, highly unbalanced mini batch as the input, then the second iteration to take a minority class dominant mini batch as input i.e. a batch from ID between 40 and 60, then the third iteration again takes a normal , unbalanced batch as input and the fourth iteration again samples a minority class dominant batch, and then this process should repeat for a fixed number of iterations. In this way, temporal information would be preserved. I think to implement this strategy, I would have to create a custom generator or Dataloader in Pytorch but I have little idea about that. Could anybody please guide me over this?
|
st32653
|
Solved by ptrblck in post #2
Based on your description I think the proper way to implement this custom sampling strategy would be in a custom sampler. By default the DataLoader would use a SequentialSampler or a RandomSampler, which you could replace with your custom class. This custom sampler could then take the targets and cr…
|
st32654
|
Based on your description I think the proper way to implement this custom sampling strategy would be in a custom sampler. By default the DataLoader would use a SequentialSampler or a RandomSampler, which you could replace with your custom class. This custom sampler could then take the targets and create the batch indices using your sampling logic.
|
st32655
|
Thankyou very much for the idea! Could you please give me an idea of how my custom sampler class should look like ?
|
st32656
|
You could take a look at the sampler implementations and adapt one to your use case. In particular I think you might want to pass the target tensors to the sampler and create the desired sample indices in the __iter__ method.
|
st32657
|
training_patch_loader = zip(training_patch_loader_inp, training_patch_loader_op)
training_patch_loader = list(training_patch_loader)
I want to join two dataloader objects but it throwing keyerror 0 when i am trying to run.
|
st32658
|
Hi,
I would l like to apply torch.bincount on batches of vectors supposing that the maximal possible value is the same for every vector of the batch, how can I do it ? Because bincount does not support batch and a for-loop would not be efficient.
Thank you
|
st32659
|
You can just use scatter_add_(dim, index, other) for batched bincount, where ‘index’ is your input and ‘other’ is just torch.ones(…).
|
st32660
|
Hi, were you ever able to achieve a batched bincount? I’m facing the same issue where looping throughout a dim is not an option.
|
st32661
|
Hi,
This is what I got
def batched_bincount(x, dim, max_value):
target = ch.zeros(x.shape[0], max_value, dtype=x.dtype, device=x.device)
values = ch.ones_like(x)
target.scatter_add_(dim, x, values)
return targe
|
st32662
|
I’m trying to implement the ConOpt optimizer 2 for GANs, which combines stochastic gradient descent for both the generator and discriminator with a gradient penalty regularizer. I know that standard practice is usually to give the generator and discriminator separate optimizers, but for this algorithm it is necessary to add the squared norm of the gradients from both models to each loss. Therefore, it is necessary to have something like the closure argument in the Optimizer.step() method, but somehow have two closures, one for each model. Does anyone have a suggested way of doing this with only one closure?
|
st32663
|
I don’t know if the only way to do it would be to, for example, make a new class GANOptimizer where the step() method requires two closures, one for each loss function. That’s pretty messy but I’m not sure of another solution
|
st32664
|
If you want to implement a min-max loss using a single optimizer, have you tried reverse grad ? Not sure if that would help…
|
st32665
|
I’m not sure I understand your reply. Ideally, I’d like to have separate optimizers for the generator and discriminator, but the loss depends on both for ConOpt, even if the optimizer is only optimizing one set of parameters.
|
st32666
|
Sorry i misinterpreted the question. So as i understand you are trying to make the Consensus Optimizer, but in pytorch. The code would be something like this:
class ConsensusOptimizer(object):
def __init__(self, learning_rate, alpha=0.1, beta=0.9, eps=1e-8):
self.optimizer = torch.optim.RMSPropOptimizer(learning_rate)
self._eps = eps
self._alpha = alpha
self._beta = beta
def conciliate(self, d_loss, g_loss, d_vars, g_vars, global_step=None):
alpha = self._alpha
beta = self._beta
# Compute gradients
d_grads = torch.autograd.grad(d_loss, d_vars)
g_grads = torch.autograd.grad(g_loss, g_vars)
# Merge variable and gradient lists
variables = d_vars + g_vars
grads = d_grads + g_grads
# Reguliarizer
reg = 0.5 * sum(
torch.sum(torch.square(g)) for g in grads
)
# Jacobian times gradiant
Jgrads = torch.autograd.grad(reg, variables)
for param in variables:
param.grad+=self._alpha*Jg
optimizer.step()
I assume you call this after you call loss.backward(). This is untested code and you prob need to make some changes.
See more info here 2
|
st32667
|
That’s more or less what I’ve tried already but it doesn’t work. My understanding is that the best way to implement this is as an optimizer, hence my original post.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.