intel-extension-for-pytorch icon indicating copy to clipboard operation
intel-extension-for-pytorch copied to clipboard

ValueError: not enough values to unpack, when loading transformer model using bfloat16/float16

Open Nehereus opened this issue 2 years ago • 2 comments

Describe the bug

Thank you all for your great work. I'm trying to do llm inference using IPEX, the code using is below

import sys
import transformers
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch,intel_extension_for_pytorch as ipex

model_name = "/root/text-generation-webui/models/minichat-3b"
tokenizer = AutoTokenizer.from_pretrained(model_name,  use_fast=False,output_hidden_states=True)
model = ipex.optimize(AutoModelForCausalLM.from_pretrained(model_name, use_cache=True,device_map=torch.device("xpu"))
                      .eval(),dtype=torch.bfloat16)

device=torch.device("xpu")
question = "hi"
conv = get_default_conv_template("minichat")
conv.append_message(conv.roles[0], question)
conv.append_message(conv.roles[1], None)
prompt = conv.get_prompt()
input_ids = tokenizer([prompt]).input_ids

        output_ids = model.generate(
            torch.as_tensor(input_ids).to(device),
            do_sample=True,
            temperature=0.7,
            max_new_tokens=1024,
        )

output_ids = output_ids[0][len(input_ids[0]):]
output = tokenizer.decode(output_ids, skip_special_tokens=True).strip()
print(output)

As you can see, this is a simple use case using IPEX. The problem is when model is loaded in either bfloat16 or float 16, it won't work, raising value error. The detailed error log is:

File /usr/local/lib/python3.10/dist-packages/transformers/models/llama/modeling_llama.py:329, in LlamaAttention.forward(self, hidden_states, attention_mask, position_ids, past_key_value, output_attentions, use_cache, padding_mask)
    319 def forward(
    320     self,
    321     hidden_states: torch.Tensor,
   (...)
    327     padding_mask: Optional[torch.LongTensor] = None,
    328 ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
--> 329     bsz, q_len, _ = hidden_states.size()
    331     if self.config.pretraining_tp > 1:
    332         key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp

ValueError: not enough values to unpack (expected 3, got 2)

However, it works perfect fine when the model is loaded in float32. Please pardon my ignorance if this is an issue unrelated to this repo

Versions

Collecting environment information...
PyTorch version: 2.0.1a0+cxx11.abi
PyTorch CXX11 ABI: Yes
IPEX version: 2.0.110+xpu
IPEX commit: ba7f6c127
Build type: Release

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

Python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.5.11-6-pve-x86_64-with-glibc2.35
Is XPU available: True
DPCPP runtime version: 2023.2.0
MKL version: 2024.0
GPU models and configuration:
[0] _DeviceProperties(name='Intel(R) Arc(TM) A770 Graphics', platform_name='Intel(R) Level-Zero', dev_type='gpu, support_fp64=0, total_memory=15473MB, max_compute_units=512, gpu_eu_count=512)
Intel OpenCL ICD version: 23.30.26918.50-736~22.04
Level Zero version: 1.3.26918.50-736~22.04

CPU:
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Address sizes:                      43 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             24
On-line CPU(s) list:                0,5-8,11,14,18,19,21-23
Off-line CPU(s) list:               1-4,9,10,12,13,15-17,20
Vendor ID:                          AuthenticAMD
BIOS Vendor ID:                     Advanced Micro Devices, Inc.
Model name:                         AMD Ryzen 9 3900X 12-Core Processor
BIOS Model name:                    AMD Ryzen 9 3900X 12-Core Processor
CPU family:                         23
Model:                              113
Thread(s) per core:                 2
Core(s) per socket:                 12
Socket(s):                          1
Stepping:                           0
Frequency boost:                    enabled
CPU max MHz:                        4672.0698
CPU min MHz:                        2200.0000
BogoMIPS:                           7585.28
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr rdpru wbnoinvd arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl umip rdpid overflow_recov succor smca sev sev_es
Virtualization:                     AMD-V
L1d cache:                          384 KiB (12 instances)
L1i cache:                          384 KiB (12 instances)
L2 cache:                           6 MiB (12 instances)
L3 cache:                           64 MiB (4 instances)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-23
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:             Mitigation; untrained return thunk; SMT enabled with STIBP protection
Vulnerability Spec rstack overflow: Mitigation; safe RET
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; Retpolines, IBPB conditional, STIBP always-on, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] intel-extension-for-pytorch==2.0.110+xpu
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.2
[pip3] torch==2.0.1a0+cxx11.abi
[pip3] torch-grammar==0.3.3
[pip3] torcheval==0.0.7
[pip3] torchtnt==0.2.1
[pip3] torchvision==0.15.2a0+cxx11.abi
[conda] N/A

Nehereus avatar Dec 12 '23 01:12 Nehereus

@Nehereus you called ipex.optimize and set the device to xpu, but your actual inference needs to be called using auto-mixed precision in order to run with BF16/FP16. Take a look at this example to run LLM inference on Intel GPUs: https://github.com/intel/intel-extension-for-pytorch/blob/v2.1.10%2Bxpu/examples/gpu/inference/python/llm/run_generation.py

Look for this block of code starting at line 380: with torch.inference_mode(), torch.no_grad(), torch.autocast( device_type=args.device, enabled=amp_enabled, dtype=amp_dtype if amp_enabled else None, ):

Note that this example is verified on Max Series 1550/1100 GPU, but you are using A770. No guarantee this will work, but let's see if this helps.

alexsin368 avatar Dec 18 '23 20:12 alexsin368

@Nehereus have you tried the above and if so, does it resolve your issue?

alexsin368 avatar Jan 24 '24 17:01 alexsin368