Repository: pytorch
Issue: RuntimeError: /pytorch/torch/csrc/jit/tracer.h:117: getTracingState: Assertion `var_state == state` failed.
Labels: oncall: jit

I did train Resnet152 model and I want to export onnx.
this error occurs
I did run programming with GPU on jupyter 
## Error message
```
RuntimeErrorTraceback (most recent call last)
<ipython-input-15-f5f241afd3b5> in <module>()
----> 1 torch.onnx.export(model_ft, dummy_input, "resnet152.onnx",export_params=True)

/usr/local/lib/python3.6/dist-packages/torch/onnx/__init__.py in export(*args, **kwargs)
     23 def export(*args, **kwargs):
     24     from torch.onnx import utils
---> 25     return utils.export(*args, **kwargs)
     26 
     27 

/usr/local/lib/python3.6/dist-packages/torch/onnx/utils.py in export(model, args, f, export_params, verbose, training, input_names, output_names, aten)
     82             as ATen ops.
     83     """
---> 84     _export(model, args, f, export_params, verbose, training, input_names, output_names)
     85 
     86 

/usr/local/lib/python3.6/dist-packages/torch/onnx/utils.py in _export(model, args, f, export_params, verbose, training, input_names, output_names, aten, export_type)
    132     # training mode was.)
    133     with set_training(model, training):
--> 134         trace, torch_out = torch.jit.get_trace_graph(model, args)
    135 
    136     if orig_state_dict_keys != _unique_state_dict(model).keys():

/usr/local/lib/python3.6/dist-packages/torch/jit/__init__.py in get_trace_graph(f, args, kwargs, nderivs)
    253     if not isinstance(args, tuple):
    254         args = (args,)
--> 255     return LegacyTracedModule(f, nderivs=nderivs)(*args, **kwargs)
    256 
    257 

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
    487             hook(self, input)
    488         if torch.jit._tracing:
--> 489             result = self._slow_forward(*input, **kwargs)
    490         else:
    491             result = self.forward(*input, **kwargs)

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in _slow_forward(self, *input, **kwargs)
    465     def _slow_forward(self, *input, **kwargs):
    466         input_vars = tuple(torch.autograd.function._iter_tensors(input))
--> 467         tracing_state = torch.jit.get_tracing_state(input_vars)
    468         if not tracing_state:
    469             return self.forward(*input, **kwargs)

/usr/local/lib/python3.6/dist-packages/torch/jit/__init__.py in get_tracing_state(args)
     33     if not torch._C._is_tracing(args):
     34         return None
---> 35     return torch._C._get_tracing_state(args)
     36 
     37 

RuntimeError: /pytorch/torch/csrc/jit/tracer.h:117: getTracingState: Assertion `var_state == state` failed.

```
## this is my export onnx code
```
dummy_input = Variable(torch.randn(1, 3, 224, 224))
torch.onnx.export(model_ft, dummy_input, "resnet152.onnx",export_params=True)
```

## this is my training model code
```
def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
    since = time.time()

    best_model_wts = copy.deepcopy(model.state_dict())
    best_acc = 0.0

    for epoch in range(num_epochs):
        print('Epoch {}/{}'.format(epoch, num_epochs - 1))
        print('-' * 10)

        # Each epoch has a training and validation phase
        for phase in ['train', 'val']:
            if phase == 'train':
                scheduler.step()
                model.train()  # Set model to training mode
            else:
                model.eval()   # Set model to evaluate mode

            running_loss = 0.0
            running_corrects = 0

            # Iterate over data.
            for inputs, labels in dataloaders[phase]:
                inputs = inputs.to(device)
                labels = labels.to(device)

                # zero the parameter gradients
                optimizer.zero_grad()

                # forward
                # track history if only in train
                with torch.set_grad_enabled(phase == 'train'):
                    outputs = model(inputs)
                    _, preds = torch.max(outputs, 1)
                    loss = criterion(outputs, labels)

                    # backward + optimize only if in training phase
                    if phase == 'train':
                        loss.backward()
                        optimizer.step()

                # statistics
                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels.data)

            epoch_loss = running_loss / dataset_sizes[phase]
            epoch_acc = running_corrects.double() / dataset_sizes[phase]

            print('{} Loss: {:.4f} Acc: {:.4f}'.format(
                phase, epoch_loss, epoch_acc))

            # deep copy the model
            if phase == 'val' and epoch_acc > best_acc:
                best_acc = epoch_acc
                best_model_wts = copy.deepcopy(model.state_dict())

        print()

    time_elapsed = time.time() - since
    print('Training complete in {:.0f}m {:.0f}s'.format(
        time_elapsed // 60, time_elapsed % 60))
    print('Best val Acc: {:4f}'.format(best_acc))

    # load best model weights
    model.load_state_dict(best_model_wts)
    return model

data_transforms = {
    'train': transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'val': transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
}

data_dir = 'data'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
                                          data_transforms[x])
                  for x in ['train', 'val']}
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4,
                                             shuffle=True, num_workers=4)
              for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_names = image_datasets['train'].classes

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

use_gpu = torch.cuda.is_available()

# get model and replace the original fc layer with your fc layer
model_ft = torchvision.models.resnet152(pretrained=True)
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, 3) 

if use_gpu:
    model_ft = model_ft.cuda()

# define loss function
criterion = nn.CrossEntropyLoss()

# Observe that all parameters are being optimized
optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)

# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)

model_ft = train_model(model=model_ft,
                           criterion=criterion,
                           optimizer=optimizer_ft,
                           scheduler=exp_lr_scheduler,
                           num_epochs=2)
```
I want training a resnet model to predict threes classes

I use pip to install pytorch
GPU : GeForce GTX 1080 Ti
Python  3.6.3
Pytorch  0.4.0
CUDA Version  9.0.176
GCC Version  5.4.0
Cmake version 3.5.1 

Could you please advice how to solve out this error
Thank you