Running inference with model.compile gives us wrong predictions on a X3D regression model trained using PyTorch 1.0
Labels: high priority, triage review, triaged, module: correctness (silent), oncall: pt2

### 🐛 Describe the bug

I am using an X3D model modified for regression outputting values between 10 and 60. This model was trained with a 1.x version of PyTorch. I am now using `PyTorch Version: 2.1.0.dev20230726+cu118` 

Here are expected predictions : 
```
        [[42.1592]],

        [[32.6108]],

        [[31.3136]],

        [[35.6934]],

        [[30.8296]],

        [[58.7482]],

        [[28.8940]],

        [[32.3956]],

        [[22.5576]],

        [[52.4671]],
```
        
If I add model.compile after loading the model, I get erroneous predictions such as 

`-1.1, 0.1,1.2,1.3.`

If I remove the model.compile line, outputs are predicted normally.

Here is my code for performing inference:


```
import os
from collections import OrderedDict

import numpy as np
import pandas as pd
import torch
import tqdm

from oread import datasets
from oread.models import stam, timesformer, vivit, x3d


def run_inference(
    chkpt_path,
    data_filename,
    root,
    num_classes,
    mean,
    std,
    split="inference",
    modelname="x3d",
    device="default",
    datapoint_loc_label="filepath",
    batch_size=8,
    frames=64,
    task="class",
    save_to_file="view_pred.csv",
    save_freq=20,
    append_to_previous=True,
    apply_mask=False,
    transforms=[],
    resize=224,
    target_label="Outcome",
):
    """Runs test epoch, computes metrics, and plots test set results.

    Args:
        data_filename ([str]): [name of csv to load]
        num_classes ([str]): [number of classes to predict]
        chkpt_path ([str]): [path to folder containing "best.pt"]
        modelname (str, optional): [name of model architecture to use]. Defaults to 'x3d'.
        datapoint_loc_label (str, optional): [name of column in csv with paths to data]. Defaults to 'filepath'.
        batch_size (int, optional): [batch size]. Defaults to 8.
        frames (int, optional): [number of frames to use per video]. Defaults to 64.
    """

    # This mean and STD is for CathEF ONLY

    ####mean = [120.953316, 120.953316, 120.953316]
    ####std = [39.573166, 39.573166, 39.573166]

    kwargs = {
        "num_classes": num_classes,
        "mean": mean,
        "std": std,
        "length": frames,
        "period": 1,
        "data_filename": data_filename,
        "root": root,
        "datapoint_loc_label": datapoint_loc_label,
        "apply_mask": apply_mask,
        "video_transforms": transforms,
        "resize": resize,
        "target_label": target_label,
    }

    if device == "default":
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    # One-hot encode target, detect number of classes
    dataset = pd.read_csv(os.path.join(data_filename), sep="µ")

    # build model, load state_dict
    # specify model
    if modelname == "x3d":
        model = x3d(num_classes=num_classes, task=task)
    if modelname == "timesformer":
        model = timesformer(num_classes=num_classes)
    if modelname == "stam":
        model = stam(num_classes=num_classes)
    elif modelname == "vivit":
        model = vivit(num_classes=num_classes)
    if modelname in [
        "c2d_r50",
        "i3d_r50",
        "slow_r50",
        "slowfast_r50",
        "slowfast_r101",
        "slowfast_16x8_r101_50_50",
        "csn_r101",
        "r2plus1d_r50",
        "x3d_xs",
        "x3d_s",
        "x3d_m",
        "x3d_l",
        "mvit_base_16x4",
        "mvit_base_32x3",
        "efficient_x3d_xs",
        "efficient_x3d_s",
    ]:
        from oread.models import pytorchvideo_model

        model = pytorchvideo_model(modelname, num_classes)
    if device.type == "cuda":
        model = torch.nn.DataParallel(model)
    ### If PyTorch 2.0 is used, the following line is needed to load the model
    # model = torch.compile(model)

    model.to(device)

    if device == torch.device("cuda"):
        print("Loading checkpoint from: ", os.path.join(chkpt_path, "best.pt"))
        checkpoint = torch.load(os.path.join(chkpt_path, "best.pt"))
    else:
        checkpoint = torch.load(
            os.path.join(chkpt_path, "best.pt"), map_location=torch.device("cpu")
        )

    # check if checkpoint was created with torch.nn.parallel
    key, value = list(checkpoint["state_dict"].items())[0]

    is_parallel = "module." in key
    is_parallel

    print("Is_parallel: ", is_parallel)

    # if created with torch.nn.parallel and we are using cpu, we want to remove the "module." from key names
    if device == torch.device("cpu") and is_parallel:
        state_dict = torch.load(
            os.path.join(chkpt_path, "best.pt"), map_location=torch.device("cpu")
        )["state_dict"]
        new_state_dict = OrderedDict()

        for k, v in state_dict.items():
            name = k[7:]  # remove `module.`
            new_state_dict[name] = v
        # load params
        model.load_state_dict(new_state_dict)
    else:
        try:
            model.load_state_dict(checkpoint["state_dict"])
        except:
            state_dict = torch.load(os.path.join(chkpt_path, "best.pt"))["state_dict"]

            new_state_dict = OrderedDict()
            print("Keys don't match, removing _orig_mod.")
            for k, v in state_dict.items():
                name = k[10:]  # remove `_orig_mod.`
                new_state_dict[name] = v

    model.eval()
    # pdb.set_trace()
    dataset = datasets.Echo_Inference(split=split, **kwargs)

    dataloader = torch.utils.data.DataLoader(
        dataset,
        batch_size=batch_size,
        num_workers=15,
        shuffle=False,
        pin_memory=(device.type == "cuda"),
    )

    print("Starting inference epoch...")
    run_inference_epoch(
        model,
        modelname,
        dataloader,
        "inference",
        device=device,
        save_to_file=save_to_file,
        save_freq=save_freq,
        root=root,
        append_to_previous=append_to_previous,
        num_classes=num_classes,
    )


def run_inference_epoch(
    model,
    modelname,
    dataloader,
    phase,
    device,
    blocks=None,
    save_to_file="view_pred.csv",
    save_freq=20,
    append_to_previous=False,
    root="",
    num_classes=21,
):
    yhat_for_save = []
    fns_for_save = []
    save_count = 0
    nbatch = len(dataloader)
    preds_df = None

    with torch.set_grad_enabled(False):
        with tqdm.tqdm(total=len(dataloader)) as pbar:
            for (i, (X, filenames)) in enumerate(dataloader):
                X = X.to(device)
                average = len(X.shape) == 6
                if average:
                    batch, n_crops, c, f, h, w = X.shape
                    X = X.view(-1, c, f, h, w)

                if modelname in ["vivit", "timesformer", "stam"]:
                    X = X.permute(0, 2, 1, 3, 4)
                if blocks is None:
                    outputs = model(X)
                else:
                    outputs = torch.cat(
                        [model(X[j : (j + blocks), ...]) for j in range(0, X.shape[0], blocks)]
                    )

                if average:
                    outputs = outputs.view(batch, n_crops, -1).mean(1)
                if modelname in [
                    "c2d_r50",
                    "i3d_r50",
                    "slow_r50",
                    "slowfast_r50",
                    "slowfast_r101",
                    "slowfast_16x8_r101_50_50",
                    "csn_r101",
                    "r2plus1d_r50",
                    "x3d_xs",
                    "x3d_s",
                    "x3d_m",
                    "x3d_l",
                    "mvit_base_16x4",
                    "mvit_base_32x3",
                    "efficient_x3d_xs",
                    "efficient_x3d_s",
                ]:
                    outputs = outputs[:, 1].float()
                elif outputs.shape[0] == 1:
                    reshaped = outputs.squeeze(2)
                    print("outputs", outputs)
                    print("reshaped", reshaped)
                else:
                    reshaped = outputs.squeeze()
                    print("outputs", outputs)
                    print("reshaped squeeze", reshaped)
                

                yhat_for_save.append(outputs.squeeze().to("cpu").detach().numpy())
                fns_for_save.append(filenames)
                # pdb.set_trace()

                if (i + 1) % save_freq == 0 or i == nbatch - 1:
                    # pdb.set_trace()
                    flatten_yhat_for_save = [
                        item for sublist in yhat_for_save for item in sublist
                    ]

                    if num_classes == 1:
                        # pdb.set_trace()
                        this_preds = pd.DataFrame(flatten_yhat_for_save)
                    elif num_classes == 2:
                        this_preds = pd.DataFrame(np.hstack(yhat_for_save))
                    else:
                        this_preds = pd.DataFrame(np.row_stack(yhat_for_save))

                    flattened_list = [item for sublist in fns_for_save for item in sublist]
                    this_preds["filename"] = flattened_list

                    # Assuming this_preds is your DataFrame
                    integer_columns = [
                        col for col in this_preds.columns if isinstance(col, int) or col.isdigit()
                    ]

                    # Select the columns with integer names
                    selected_columns = this_preds[integer_columns]

                    # Find the index of the maximum value in each row using idxmax
                    y_pred_cat = selected_columns.idxmax(axis=1)

                    # You can now assign y_pred_cat to a new column in this_preds if needed
                    this_preds["y_pred_cat"] = y_pred_cat

                    if save_count == 0:
                        if append_to_previous:
                            if os.path.exists(save_to_file):
                                # File exists, read it
                                preds_df = pd.read_csv(save_to_file)
                            else:
                                # File does not exist, create an empty DataFrame with the same columns as this_preds
                                preds_df = pd.DataFrame(columns=this_preds.columns)

                            # Concatenate this_preds to preds_df
                            preds_df = pd.concat([preds_df, this_preds], axis=0)
                        else:
                            preds_df = this_preds
                    else:
                        preds_df = pd.concat([preds_df, this_preds], axis=0)

                    preds_df.to_csv(save_to_file, index=False)
                    print(f"Saved round {save_count}")
                    yhat_for_save = []
                    fns_for_save = []
                    save_count += 1

                ## Save file only if preds_df is not None
                if preds_df is not None:
                    preds_df.to_csv(save_to_file, index=False)
                #                 pdb.set_trace()
                pbar.update()
```

### Versions

PyTorch version: 2.1.0.dev20230726+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.1 LTS (x86_64)
GCC version: (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Clang version: Could not collect
CMake version: version 3.25.0
Libc version: glibc-2.31

Python version: 3.8.15 | packaged by conda-forge | (default, Nov 22 2022, 08:49:35)  [GCC 10.4.0] (64-bit runtime)
Python platform: Linux-3.10.0-1160.62.1.el7.x86_64-x86_64-with-glibc2.10
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA GeForce RTX 3090
GPU 1: NVIDIA GeForce RTX 3090

Nvidia driver version: 525.60.13
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.0.5
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.0.5
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.0.5
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.0.5
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.0.5
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.0.5
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.0.5
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   46 bits physical, 48 bits virtual
CPU(s):                          48
On-line CPU(s) list:             0-47
Thread(s) per core:              2
Core(s) per socket:              12
Socket(s):                       2
NUMA node(s):                    2
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           85
Model name:                      Intel(R) Xeon(R) Gold 5118 CPU @ 2.30GHz
Stepping:                        4
CPU MHz:                         2699.945
CPU max MHz:                     3200.0000
CPU min MHz:                     1000.0000
BogoMIPS:                        4600.00
Virtualization:                  VT-x
L1d cache:                       768 KiB
L1i cache:                       768 KiB
L2 cache:                        24 MiB
L3 cache:                        33 MiB
NUMA node0 CPU(s):               0-11,24-35
NUMA node1 CPU(s):               12-23,36-47
Vulnerability Itlb multihit:     KVM: Mitigation: Split huge pages
Vulnerability L1tf:              Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds:               Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown:          Mitigation; PTI
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:        Mitigation; Load fences, usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Full retpoline, IBPB
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Mitigation; Clear CPU buffers; SMT vulnerable
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 invpcid_single intel_ppin intel_pt ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke md_clear spec_ctrl intel_stibp flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] numpy==1.23.5
[pip3] pytorch-triton==2.1.0+9e3e10c5ed
[pip3] pytorchvideo==0.1.0
[pip3] pytorchvideo-nightly==0.0.3
[pip3] stam-pytorch==0.0.4
[pip3] timesformer-pytorch==0.3.2
[pip3] torch==2.1.0.dev20230726+cu118
[pip3] torchaudio==2.1.0.dev20230726+cu118
[pip3] torchsummary==1.5.1
[pip3] torchtriton==2.0.0+0d7e753227
[pip3] torchvision==0.16.0.dev20230726+cu118
[pip3] triton==2.0.0
[conda] cudatoolkit               11.8.0              h37601d7_11    conda-forge
[conda] numpy                     1.24.1                   pypi_0    pypi
[conda] pytorch-triton            2.1.0+9e3e10c5ed          pypi_0    pypi
[conda] pytorchvideo              0.1.0                    pypi_0    pypi
[conda] pytorchvideo-nightly      0.0.3                    pypi_0    pypi
[conda] stam-pytorch              0.0.4                    pypi_0    pypi
[conda] timesformer-pytorch       0.3.2                    pypi_0    pypi
[conda] torch                     2.1.0.dev20230726+cu118          pypi_0    pypi
[conda] torchaudio                2.1.0.dev20230726+cu118          pypi_0    pypi
[conda] torchsummary              1.5.1                    pypi_0    pypi
[conda] torchtriton               2.0.0+0d7e753227          pypi_0    pypi
[conda] torchvision               0.16.0.dev20230726+cu118          pypi_0    pypi
[conda] triton                    2.0.0                    pypi_0    pypi

cc @ezyang @gchanan @zou3519 @kadeng @msaroufim @wconstab @bdhirsh @anijain2305