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

Run finetune.py on Xeon but failed - no attribute "weight"

Open JamieVC opened this issue 1 year ago • 10 comments

Describe the bug

To finetune model on Xeon CPU, we are following the ai-reference-models/models_v2/pytorch/llama/training/cpu at main · intel/ai-reference-models (github.com) · Base model: meta-llama/llama-2-7b-hf · Dataset: raw.githubusercontent.com/tloen/alpaca-lora/main/alpaca_data.json

Versions

image

image

Collecting environment information... PyTorch version: 2.4.1+cu121 PyTorch CXX11 ABI: No IPEX version: 2.4.0+cpu IPEX commit: 5880201 Build type: Release

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: N/A CMake version: version 3.28.4 Libc version: glibc-2.35

Python version: 3.10.12 (main, Jul 29 2024, 16:56:48) [GCC 11.4.0] (64-bit runtime) Python platform: Linux-5.15.0-118-generic-x86_64-with-glibc2.35 Is XPU available: False DPCPP runtime version: N/A MKL version: N/A GPU models and configuration:

Intel OpenCL ICD version: N/A Level Zero version: N/A

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 52 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 224 On-line CPU(s) list: 0-223 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Platinum 8480+ CPU family: 6 Model: 143 Thread(s) per core: 2 Core(s) per socket: 56 Socket(s): 2 Stepping: 6 CPU max MHz: 3800.0000 CPU min MHz: 800.0000 BogoMIPS: 4000.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 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 cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 5.3 MiB (112 instances) L1i cache: 3.5 MiB (112 instances) L2 cache: 224 MiB (112 instances) L3 cache: 210 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-55,112-167 NUMA node1 CPU(s): 56-111,168-223 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 Reg file data sampling: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp 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; BHI BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Versions of relevant libraries: [pip3] intel_extension_for_pytorch==2.4.0 [pip3] mypy-extensions==1.0.0 [pip3] numpy==2.1.1 [pip3] torch==2.4.1 [pip3] torchaudio==2.4.1 [pip3] torchvision==0.19.1 [conda] N/A

JamieVC avatar Sep 10 '24 10:09 JamieVC

Hi @JamieVC , what's the version of transformers in your environment? Did you run ./setup.sh as described in readme?

huiyan2021 avatar Sep 11 '24 02:09 huiyan2021

Hi @JamieVC , what's the version of transformers in your environment? Did you run ./setup.sh as described in readme?

hi @huiyan2021 , In my environment, the version of transformers: transformers **4.38.1** /home/jamie/models/models_v2/pytorch/llama/training/cpu/transformers

When I run ./setup.sh today, it got warning messages. image

After running ./setup.sh as described in readme, I try to run again "python finetune.py" but it still failed on the same issue. image

JamieVC avatar Sep 11 '24 05:09 JamieVC

Got it. Let me try to reproduce and come back later.

huiyan2021 avatar Sep 11 '24 07:09 huiyan2021

Hi @JamieVC , I have reproduced this issue, seems a bug in ipex, working in progress...

huiyan2021 avatar Sep 12 '24 05:09 huiyan2021

Thanks for reporting this. It's suspicious that it's due to a model state_dict definition conflict among different transformers versions. Our dev peer is on the issue.

ZailiWang avatar Sep 13 '24 07:09 ZailiWang

Thanks for reporting this. It's suspicious that it's due to a model state_dict definition conflict among different transformers versions. Our dev peer is on the issue.

Thanks for your response. Do we have a plan schedule for this issue fix?

JamieVC avatar Sep 20 '24 02:09 JamieVC

It is an issue in the official finetune script, not intel_extension_for_pytorch issue. This issue is same as Why add the following code snippet since it would bring some errors? · Issue #319 · tloen/alpaca-lora (github.com)

model.state_dict = ( lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict()) ).__get__(model, type(model))

This code is root cause. This code delete default in state_dict "base_model.model.model.layers.0.self_attn.q_proj.lora_A.default.weight".

Our model: [0] (k_proj): _IPEXLinear()
[0] (v_proj): lora.Linear(
[0] (base_layer): _IPEXLinear()
[0] (lora_dropout): ModuleDict(
[0] (default): Dropout(p=0.05, inplace=False)
[0] )
[0] (lora_A): ModuleDict(
[0] (default): _IPEXLinear()
[0] )
[0] (lora_B): ModuleDict(
[0] (default): _IPEXLinear()
[0] )
When saving weight lora_A, lora_A.weight cannot be getten because lora_A.default.weight is what we want to get but default was deleted by this code.

A possible workaround is the latest commit on Why add the following code snippet since it would bring some errors? · Issue #319 · tloen/alpaca-lora (github.com)

shiyang-weng avatar Sep 20 '24 08:09 shiyang-weng

It is an issue in the official finetune script, not intel_extension_for_pytorch issue. This issue is same as Why add the following code snippet since it would bring some errors? · Issue #319 · tloen/alpaca-lora (github.com)

model.state_dict = ( lambda self, *_, **__: get_peft_model_state_dict(self, old_state_dict()) ).__get__(model, type(model))

This code is root cause. This code delete default in state_dict "base_model.model.model.layers.0.self_attn.q_proj.lora_A.default.weight".

Our model: [0] (k_proj): _IPEXLinear() [0] (v_proj): lora.Linear( [0] (base_layer): _IPEXLinear() [0] (lora_dropout): ModuleDict( [0] (default): Dropout(p=0.05, inplace=False) [0] ) [0] (lora_A): ModuleDict( [0] (default): _IPEXLinear() [0] ) [0] (lora_B): ModuleDict( [0] (default): _IPEXLinear() [0] ) When saving weight lora_A, lora_A.weight cannot be getten because lora_A.default.weight is what we want to get but default was deleted by this code.

A possible workaround is the latest commit on Why add the following code snippet since it would bring some errors? · Issue #319 · tloen/alpaca-lora (github.com)

Hi @JamieVC , could you try this workaround?

huiyan2021 avatar Sep 27 '24 04:09 huiyan2021

hi @huiyan2021 and @shiyang-weng

sorry, I may need your support. Not sure how to modify. Could you please integrate the possible workaround into my finetune.py ?

The possible workaround: https://github.com/tloen/alpaca-lora/issues/319 in the latest commit

from transformers import Seq2SeqTrainer, TrainerCallback, TrainingArguments, TrainerState, TrainerControl
from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR

class SavePeftModelCallback(TrainerCallback):
    def on_save(
        self,
        args: TrainingArguments,
        state: TrainerState,
        control: TrainerControl,
        **kwargs,
    ):
        checkpoint_folder = os.path.join(args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{state.global_step}")

        peft_model_path = os.path.join(checkpoint_folder, "adapter_model")
        kwargs["model"].save_pretrained(peft_model_path)

        pytorch_model_path = os.path.join(checkpoint_folder, "pytorch_model.bin")
        if os.path.exists(pytorch_model_path):
            os.remove(pytorch_model_path)
        return control


trainer = Seq2SeqTrainer(
    args=training_args,
    model=model,
    train_dataset=common_voice["train"],
    eval_dataset=common_voice["test"],
    data_collator=data_collator,
    # compute_metrics=compute_metrics,
    tokenizer=processor.feature_extractor,
    callbacks=[SavePeftModelCallback],
)
model.config.use_cache = False  # silence the warnings. Please re-enable for inference!

I list my partial code of finetune.py below:

    trainer = transformers.Trainer(
        model=model,
        train_dataset=train_data,
        eval_dataset=val_data,
        args=transformers.TrainingArguments(
            per_device_train_batch_size=micro_batch_size,
            gradient_accumulation_steps=gradient_accumulation_steps,
            warmup_steps=10,
            num_train_epochs=num_epochs,
            learning_rate=learning_rate,
            bf16=bf16,
            #fp16_cpu=fp16,
            #bf32=bf32,
            logging_steps=10,
            optim="adamw_torch",
            evaluation_strategy="steps" if val_set_size > 0 else "no",
            save_strategy="steps",
            eval_steps=200 if val_set_size > 0 else None,
            save_steps=200,
            output_dir=output_dir,
            save_total_limit=3,
            load_best_model_at_end=True if val_set_size > 0 else False,
            ddp_find_unused_parameters=False if ddp else None,
            group_by_length=group_by_length,
            report_to="wandb" if use_wandb else None,
            run_name=wandb_run_name if use_wandb else None,
            no_cuda=True,
            use_ipex=True,
            max_steps=max_steps,
            #xpu_backend="ccl",
            disable_tqdm=disable_tqdm,
        ),
        data_collator=transformers.DataCollatorForSeq2Seq(
            tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
        ),
    )
    model.config.use_cache = False

    old_state_dict = model.state_dict
    model.state_dict = (
        lambda self, *_, **__: get_peft_model_state_dict(
            self, old_state_dict()
        )
    ).__get__(model, type(model))
    print("Start Training")
    trainer.train(resume_from_checkpoint=resume_from_checkpoint)
    print("Finish Training")
    model.save_pretrained(output_dir)

    print(
        "\n If there's a warning about missing keys above, please disregard :)"
    )


if __name__ == "__main__":
    fire.Fire(train)

JamieVC avatar Oct 01 '24 07:10 JamieVC

Hi @JamieVC , sorry I missed this issue.

I made the modification in finetune.py.txt of the sample, please replace your finetune.py with this file and see if it works.

I tried 3 iterations and can see the generated checkpoints for each iteration. image

huiyan2021 avatar Oct 11 '24 06:10 huiyan2021

@JamieVC Did you try the workaround? any updates?

huiyan2021 avatar Nov 12 '24 02:11 huiyan2021

Hi @JamieVC , I checked the latest version of https://github.com/intel/ai-reference-models/tree/main/models_v2/pytorch/llama/training/cpu, finetune.py works with minor changes referring to https://github.com/intel/ai-reference-models/issues/190#issuecomment-2487280907

huiyan2021 avatar Nov 20 '24 05:11 huiyan2021