intel / intel-extension-for-pytorch

A Python package for extending the official PyTorch that can easily obtain performance on Intel platform
Apache License 2.0
1.63k stars 253 forks source link

Using XPU training actually increases the training time and sharply reduces the accuracy. #565

Closed SoldierWz closed 5 months ago

SoldierWz commented 8 months ago

Describe the issue

When I wanted to try using a graphics card to train my classification model I made changes to the following code device = 'xpu' X_tensor = torch.tensor(X_processed, dtype=torch.float).to(device) y_tensor = torch.tensor(y, dtype=torch.long).to(device) model = FCN(X_train.shape[1], len(np.unique(y))).to(device) model, optimizer = ipex.optimize(model, optimizer=optimizer) features, labels = features.to(device), labels.to(device) X_test = X_test.to(device) What I am doing is a prediction and classification task on a small data set. The sample size is only a few hundred.I know this task is not suitable for running on GPU but I just tried it. I am using A770 graphics card and the processor is 12400. I have successfully installed all the necessary according to the tutorial. My training time using CPU was 24 seconds with an accuracy of 0.94 But when I sent all the data to the XPU, the same training took 1 minute and 40 seconds and the accuracy was only 0.34 This is not an important issue, but I still want to report this unusual phenomenon.

wangkl2 commented 8 months ago

Hi @SoldierWz, thanks for reporting this issue. Could you please help provide the env info via the following commands:

wget https://raw.githubusercontent.com/intel/intel-extension-for-pytorch/master/scripts/collect_env.py
# For security purposes, please check the contents of collect_env.py before running it.
python collect_env.py

Besides, please also provide us the minimum code reproducer for this issue training on A770 as well as the dataset? Thanks.

jgong5 commented 8 months ago

If possible, please also provide the torch profiler info so that we can know the breakdown and what ops take most time.

SoldierWz commented 8 months ago

Hi @SoldierWz, thanks for reporting this issue. Could you please help provide the env info via the following commands:

wget https://raw.githubusercontent.com/intel/intel-extension-for-pytorch/master/scripts/collect_env.py
# For security purposes, please check the contents of collect_env.py before running it.
python collect_env.py

Besides, please also provide us the minimum code reproducer for this issue training on A770 as well as the dataset? Thanks.

This is environmental information Collecting environment information... PyTorch version: N/A PyTorch CXX11 ABI: N/A IPEX version: N/A IPEX commit: N/A Build type: N/A

OS: Ubuntu 22.04.4 LTS (x86_64) GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 Clang version: N/A IGC version: 2024.1.0 (2024.1.0.20240308) CMake version: version 3.22.1 Libc version: glibc-2.35

Python version: 3.11.8 | packaged by conda-forge | (main, Feb 16 2024, 20:53:32) [GCC 12.3.0] (64-bit runtime) Python platform: Linux-6.5.0-26-generic-x86_64-with-glibc2.35 Is XPU available: N/A DPCPP runtime version: 2024.1 MKL version: 2024.1 GPU models and configuration: N/A Intel OpenCL ICD version: 23.35.27191.42-775~22.04 Level Zero version: 1.3.27191.42-775~22.04

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 39 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 12 On-line CPU(s) list: 0-11 Vendor ID: GenuineIntel Model name: 12th Gen Intel(R) Core(TM) i5-12400 CPU family: 6 Model: 151 Thread(s) per core: 2 Core(s) per socket: 6 Socket(s): 1 Stepping: 5 CPU max MHz: 4400.0000 CPU min MHz: 800.0000 BogoMIPS: 4992.00 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 cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl est tm2 ssse3 sdbg fma cx16 xtpr pdcm sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities L1d cache: 288 KiB (6 instances) L1i cache: 192 KiB (6 instances) L2 cache: 7.5 MiB (6 instances) L3 cache: 18 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-11 Vulnerability Gather data sampling: Not affected Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Versions of relevant libraries: [pip3] cjm-pytorch-utils==0.0.6 [pip3] intel-extension-for-pytorch==2.1.10+xpu [pip3] mypy-extensions==1.0.0 [pip3] numpy==1.26.4 [pip3] torch==2.1.0a0+cxx11.abi [pip3] torchaudio==2.1.0a0+cxx11.abi [pip3] torcheval==0.0.7 [pip3] torchtnt==0.2.3 [pip3] torchvision==0.16.0a0+cxx11.abi [conda] cjm-pytorch-utils 0.0.6 pypi_0 pypi [conda] intel-extension-for-pytorch 2.1.10+xpu pypi_0 pypi [conda] numpy 1.26.4 py311h64a7726_0 conda-forge [conda] torch 2.1.0a0+cxx11.abi pypi_0 pypi [conda] torchaudio 2.1.0a0+cxx11.abi pypi_0 pypi [conda] torcheval 0.0.7 pypi_0 pypi [conda] torchtnt 0.2.3 pypi_0 pypi [conda] torchvision 0.16.0a0+cxx11.abi pypi_0 pypi Below is the reproducible code and the dataset is at the link from sklearnex import patch_sklearn patch_sklearn() from sklearn.model_selection import KFold from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn.compose import ColumnTransformer import modin.pandas as pd import numpy as np import torch import intel_extension_for_pytorch as ipex import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.optim.lr_scheduler import StepLR from torch.utils.data import DataLoader, Dataset device = 'xpu' data = pd.read_excel('/home/wangzhen/Documents/porcelains/data/xing_ding_gonyi_combine.xlsx') X = data.drop(['kiln'], axis=1) y, unique_labels = pd.factorize(data['kiln']) numeric_features = X.select_dtypes(include=['int64', 'float64']).columns categorical_features = ['type', 'dynasty']
preprocessor = ColumnTransformer( transformers=[ ('num', StandardScaler(), numeric_features), ('cat', OneHotEncoder(), categorical_features) ]) class CustomDataset(Dataset): def init(self, features, labels): self.features = features self.labels = labels

def __len__(self):
    return len(self.labels)

def __getitem__(self, idx):
    return self.features[idx], self.labels[idx]

class MLP(nn.Module): def init(self, input_size): super(MLP, self).init() self.fc1 = nn.Linear(input_size, 128)

self.attention = SelfAttention(128)

    self.fc2 = nn.Linear(128, 64)  
    self.fc3 = nn.Linear(64, 32)   
    self.fc4 = nn.Linear(32, 3)    
    self.relu = nn.ReLU()

    self._initialize_weights()

def _initialize_weights(self):
    for m in self.modules():
        if isinstance(m, nn.Linear):
            nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            nn.init.constant_(m.bias, 0)

def forward(self, x):
    out = self.fc1(x)
    out = self.relu(out)
    # out = self.attention(out)
    out = self.fc2(out)
    out = self.relu(out)
    out = self.fc3(out)
    out = self.relu(out)
    out = self.fc4(out)
    return F.log_softmax(out, dim=1)

X_processed = preprocessor.fit_transform(X) X_tensor = torch.tensor(X_processed, dtype=torch.float) y_tensor = torch.tensor(y, dtype=torch.long) X_tensor = torch.tensor(X_processed, dtype=torch.float).to(device) y_tensor = torch.tensor(y, dtype=torch.long).to(device)

kf = KFold(n_splits=20, shuffle=True, random_state=42) scores = [] for train_idx, test_idx in kf.split(X_tensor): X_train, X_test = X_tensor[train_idx], X_tensor[test_idx] y_train, y_test = y_tensor[train_idx], y_tensor[test_idx]

train_dataset = CustomDataset(X_train, y_train)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)

model = MLP(X_train.shape[1])  
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
scheduler = StepLR(optimizer, step_size=30, gamma=0.1)  

model = model.to("xpu")
criterion = criterion.to("xpu")
model, optimizer = ipex.optimize(model, optimizer=optimizer)
for epoch in range(500):
    model.train()  
   for features, labels in train_loader:
        features, labels = features.to('xpu'), labels.to('xpu')
        optimizer.zero_grad()
        outputs = model(features)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
with torch.no_grad():
    X_test = X_test.to(device)  
    outputs = model(X_test)
    _, predicted = torch.max(outputs, 1)
    correct = (predicted == y_test).sum().item()
    accuracy = correct / len(y_test)
    scores.append(accuracy)

I think these are enough to run. [Uploading xing_ding_gonyi_combine.xlsx…]()

SoldierWz commented 8 months ago

If possible, please also provide the torch profiler info so that we can know the breakdown and what ops take most time.

I want to provide information, but a new problem occurred when I was running it today. When I started the computer today, I found that the oneAPI suite seemed to be updated. After I updated it, I ran my code and the following problem occurred.

ImportError Traceback (most recent call last) Cell In[4], line 8 6 import modin.pandas as pd 7 import numpy as np ----> 8 import torch 9 import intel_extension_for_pytorch as ipex 10 import torch.nn as nn

File ~/mambaforge/envs/pytorch-arc/lib/python3.11/site-packages/torch/init.py:235 233 if USE_GLOBAL_DEPS: 234 _load_global_deps() --> 235 from torch._C import * # noqa: F403 237 # Appease the type checker; ordinarily this binding is inserted by the 238 # torch._C module initialization code in C 239 if TYPE_CHECKING:

ImportError: /home/wangzhen/mambaforge/envs/pytorch-arc/lib/python3.11/site-packages/torch/lib/libtorch_cpu.so: undefined symbol: iJIT_NotifyEvent

wangkl2 commented 8 months ago

@SoldierWz XPU seems not be detected by IPEX in your environment. IPEX 2.1.10+xpu works with oneAPI 2024.0, please help downgrade the dpcpp and mkl version via sudo apt install -y intel-oneapi-dpcpp-cpp-2024.0 intel-oneapi-mkl-devel=2024.0.0-49656 or the online/offline installer in https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit-download.html?operatingsystem=linux. Then please collect the sys info and try the workloads again.

SoldierWz commented 8 months ago

@SoldierWz XPU seems not be detected by IPEX in your environment. IPEX 2.1.10+xpu works with oneAPI 2024.0, please help downgrade the dpcpp and mkl version via sudo apt install -y intel-oneapi-dpcpp-cpp-2024.0 intel-oneapi-mkl-devel=2024.0.0-49656 or the online/offline installer in https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit-download.html?operatingsystem=linux. Then please collect the sys info and try the workloads again.

No, the GPU could be detected before, and I successfully ran the code on the XPU. I think the unavailability of the GPU this time was caused by the oneAPI update this morning. I'll try downgrading, thanks.

Shr1ftyy commented 8 months ago

Hi @SoldierWz - did downgrading work? I literally just got my arc a770 today and spun it up on Ubuntu 23 and faced the same issue you did. Thanks beforehand.

wangkl2 commented 7 months ago

@SoldierWz @Shr1ftyy For the undefined symbol issue caused by the mismatch between IPEX 2.1.10+xpu and oneAPI 2024.1, we recently released IPEX 2.1.20+xpu, which is compatible with oneAPI base toolkit 2024.1, please refer to https://intel.github.io/intel-extension-for-pytorch/index.html#installation?platform=gpu&version=v2.1.20%2bxpu&os=linux%2fwsl2&package=pip.

wangkl2 commented 7 months ago

@SoldierWz BTW, the dataset you shared seems not successfully uploaded. Please help check.

wangkl2 commented 5 months ago

There is no response on this issue for over 1 month. Close the issue now. If you still have issues, feel free to reopen it. Thanks.