Skip to content

AssertionError: Pieces mismatches: [{804, 805}],I ran the official sample program but got an error . #1862

Closed

Description

@luojueling

from unsloth import is_bfloat16_supported
import torch
max_seq_length = 512 # Can increase for longer reasoning traces
lora_rank = 32 # Larger rank = smarter, but slower

model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "/root/model_weight/LLM-Research/Meta-Llama-3___1-8B-Instruct",
max_seq_length = max_seq_length,
load_in_4bit = True, # False for LoRA 16bit
# fast_inference = True, # Enable vLLM fast inference
max_lora_rank = lora_rank,
gpu_memory_utilization = 0.6, # Reduce if out of memory
)

model = FastLanguageModel.get_peft_model(
model,
r = lora_rank, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
target_modules = [
"q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",
], # Remove QKVO if out of memory
lora_alpha = lora_rank,
use_gradient_checkpointing = "unsloth", # Enable long context finetuning
random_state = 3407,
)

import os
os.environ["NCCL_P2P_DISABLE"] = "1"
os.environ["NCCL_IB_DISABLE"] = "1"

import re
from datasets import load_dataset, Dataset

Load and prep dataset

SYSTEM_PROMPT = """
Respond in the following format:

...


...

"""

XML_COT_FORMAT = """

{reasoning}


{answer}

"""

def extract_xml_answer(text: str) -> str:
answer = text.split("")[-1]
answer = answer.split("")[0]
return answer.strip()

def extract_hash_answer(text: str) -> str | None:
if "####" not in text:
return None
return text.split("####")[1].strip()

uncomment middle messages for 1-shot prompting

def get_gsm8k_questions(split = "train") -> Dataset:
# data = load_dataset('openai/gsm8k', 'main')[split] # type: ignore
data = load_dataset('/root/dataset/swulling/gsm8k_chinese')
data = data.map(lambda x: { # type: ignore
'prompt': [
{'role': 'system', 'content': SYSTEM_PROMPT},
{'role': 'user', 'content': x['question']}
],
'answer': extract_hash_answer(x['answer'])
}) # type: ignore
return data # type: ignore

dataset = get_gsm8k_questions()

Reward functions

def correctness_reward_func(prompts, completions, answer, **kwargs) -> list[float]:
responses = [completion[0]['content'] for completion in completions]
q = prompts[0][-1]['content']
extracted_responses = [extract_xml_answer(r) for r in responses]
print('-'*20, f"Question:\n{q}", f"\nAnswer:\n{answer[0]}", f"\nResponse:\n{responses[0]}", f"\nExtracted:\n{extracted_responses[0]}")
return [2.0 if r == a else 0.0 for r, a in zip(extracted_responses, answer)]

def int_reward_func(completions, **kwargs) -> list[float]:
responses = [completion[0]['content'] for completion in completions]
extracted_responses = [extract_xml_answer(r) for r in responses]
return [0.5 if r.isdigit() else 0.0 for r in extracted_responses]

def strict_format_reward_func(completions, **kwargs) -> list[float]:
"""Reward function that checks if the completion has a specific format."""
pattern = r"^\n.?\n\n\n.?\n\n$"
responses = [completion[0]["content"] for completion in completions]
matches = [re.match(pattern, r) for r in responses]
return [0.5 if match else 0.0 for match in matches]

def soft_format_reward_func(completions, **kwargs) -> list[float]:
"""Reward function that checks if the completion has a specific format."""
pattern = r".?\s.*?"
responses = [completion[0]["content"] for completion in completions]
matches = [re.match(pattern, r) for r in responses]
return [0.5 if match else 0.0 for match in matches]

def count_xml(text) -> float:
count = 0.0
if text.count("\n") == 1:
count += 0.125
if text.count("\n\n") == 1:
count += 0.125
if text.count("\n\n") == 1:
count += 0.125
count -= len(text.split("\n\n")[-1])*0.001
if text.count("\n") == 1:
count += 0.125
count -= (len(text.split("\n")[-1]) - 1)*0.001
return count

def xmlcount_reward_func(completions, **kwargs) -> list[float]:
contents = [completion[0]["content"] for completion in completions]
return [count_xml(c) for c in contents]

from trl import GRPOConfig, GRPOTrainer
training_args = GRPOConfig(
use_vllm = True, # use vLLM for fast inference!
learning_rate = 5e-6,
adam_beta1 = 0.9,
adam_beta2 = 0.99,
weight_decay = 0.1,
warmup_ratio = 0.1,
lr_scheduler_type = "cosine",
optim = "paged_adamw_8bit",
logging_steps = 1,
bf16 = is_bfloat16_supported(),
# fp16 = not is_bfloat16_supported(),
per_device_train_batch_size = 1,
gradient_accumulation_steps = 1, # Increase to 4 for smoother training
num_generations = 6, # Decrease if out of memory
max_prompt_length = 256,
max_completion_length = 200,
# num_train_epochs = 1, # Set to 1 for a full training run
max_steps = 250,
save_steps = 250,
max_grad_norm = 0.1,
report_to = "none", # Can use Weights & Biases
output_dir = "outputs",
)

The following code reports an error
trainer = GRPOTrainer(
model = model,
processing_class = tokenizer,
reward_funcs = [
xmlcount_reward_func,
soft_format_reward_func,
strict_format_reward_func,
int_reward_func,
correctness_reward_func,
],
args = training_args,
train_dataset = dataset,
)
trainer.train()

Unexpected exception formatting exception. Falling back to standard exception
Traceback (most recent call last):
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/peft/peft_model.py", line 824, in getattr
return super().getattr(name) # defer to nn.Module's logic
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1928, in getattr
raise AttributeError(
AttributeError: 'PeftModelForCausalLM' object has no attribute 'vllm_engine'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/peft/tuners/lora/model.py", line 371, in getattr
return super().getattr(name) # defer to nn.Module's logic
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1928, in getattr
raise AttributeError(
AttributeError: 'LoraModel' object has no attribute 'vllm_engine'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/interactiveshell.py", line 3577, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "/tmp/ipykernel_390947/2401788477.py", line 1, in
trainer = GRPOTrainer(
^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/unsloth/trainer.py", line 203, in new_init
original_init(self, *args, **kwargs)
File "/root/xiesi/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 1336, in init
super().init(
File "/root/xiesi/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 804, in init
self.llm = model.vllm_engine; self._last_loaded_step = 0; self.sampling_params = SamplingParams(
^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/peft/peft_model.py", line 828, in getattr
return getattr(self.base_model, name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/peft/tuners/lora/model.py", line 375, in getattr
return getattr(self.model, name)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1928, in getattr
raise AttributeError(
AttributeError: 'LlamaForCausalLM' object has no attribute 'vllm_engine'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/interactiveshell.py", line 2168, in showtraceback
stb = self.InteractiveTB.structured_traceback(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/ultratb.py", line 1457, in structured_traceback
return FormattedTB.structured_traceback(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/ultratb.py", line 1348, in structured_traceback
return VerboseTB.structured_traceback(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/ultratb.py", line 1195, in structured_traceback
formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/ultratb.py", line 1110, in format_exception_as_a_whole
frames.append(self.format_record(record))
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/ultratb.py", line 992, in format_record
frame_info.lines, Colors, self.has_colors, lvals
^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/ultratb.py", line 804, in lines
return self._sd.lines
^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/utils.py", line 145, in cached_property_wrapper
value = obj.dict[self.func.name] = self.func(obj)
^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/core.py", line 698, in lines
pieces = self.included_pieces
^^^^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/utils.py", line 145, in cached_property_wrapper
value = obj.dict[self.func.name] = self.func(obj)
^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/core.py", line 645, in included_pieces
scope_pieces = self.scope_pieces
^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/utils.py", line 145, in cached_property_wrapper
value = obj.dict[self.func.name] = self.func(obj)
^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/core.py", line 585, in scope_pieces
for piece in self.source.pieces
^^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/utils.py", line 145, in cached_property_wrapper
value = obj.dict[self.func.name] = self.func(obj)
^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/core.py", line 90, in pieces
return list(self._clean_pieces())
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/core.py", line 114, in _clean_pieces
raise AssertionError("Pieces mismatches: %s" % mismatches)
AssertionError: Pieces mismatches: [{804, 805}]

Activity

  1. luojueling commented on Mar 1, 2025

    @luojueling
    Author

    just in my server get AssertionError: Pieces mismatches: [{804, 805}],but in google colab is ok

  2. luojueling commented on Mar 1, 2025

    @luojueling
    Author

    my gpu is 4090*2

  3. CYoungG06 commented on Mar 2, 2025

    @CYoungG06

    I just got a similar error:

    Unexpected exception formatting exception. Falling back to standard exception
    Traceback (most recent call last):
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/interactiveshell.py", line 3577, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
    File "/tmp/ipykernel_1640/2401788477.py", line 14, in <module>
    trainer.train()
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/transformers/trainer.py", line 2241, in train
    return inner_training_loop(
    ^^^^^^^^^^^^^^^^^^^^
    File "<string>", line 329, in _fast_inner_training_loop
    File "<string>", line 25, in _unsloth_training_step
    File "/root/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 881, in _prepare_inputs
    prompts_text = [maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in inputs]
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/root/unsloth_compiled_cache/UnslothGRPOTrainer.py", line 881, in <listcomp>
    prompts_text = [maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in inputs]
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/trl/data_utils.py", line 219, in maybe_apply_chat_template
    return apply_chat_template(example, tokenizer, tools)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/trl/data_utils.py", line 103, in apply_chat_template
    prompt = tokenizer.apply_chat_template(
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/transformers/tokenization_utils_base.py", line 1629, in apply_chat_template
    chat_template = self.get_chat_template(chat_template, tools)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/transformers/tokenization_utils_base.py", line 1805, in get_chat_template
    raise ValueError(
    ValueError: Cannot use chat template functions because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/interactiveshell.py", line 2168, in showtraceback
    stb = self.InteractiveTB.structured_traceback(
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/ultratb.py", line 1457, in structured_traceback
    return FormattedTB.structured_traceback(
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/ultratb.py", line 1348, in structured_traceback
    return VerboseTB.structured_traceback(
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/ultratb.py", line 1195, in structured_traceback
    formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/ultratb.py", line 1110, in format_exception_as_a_whole
    frames.append(self.format_record(record))
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/ultratb.py", line 992, in format_record
    frame_info.lines, Colors, self.has_colors, lvals
    ^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/IPython/core/ultratb.py", line 804, in lines
    return self._sd.lines
    ^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/utils.py", line 145, in cached_property_wrapper
    value = obj.dict[self.func.name] = self.func(obj)
    ^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/core.py", line 698, in lines
    pieces = self.included_pieces
    ^^^^^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/utils.py", line 145, in cached_property_wrapper
    value = obj.dict[self.func.name] = self.func(obj)
    ^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/core.py", line 645, in included_pieces
    scope_pieces = self.scope_pieces
    ^^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/utils.py", line 145, in cached_property_wrapper
    value = obj.dict[self.func.name] = self.func(obj)
    ^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/core.py", line 585, in scope_pieces
    for piece in self.source.pieces
    ^^^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/utils.py", line 145, in cached_property_wrapper
    value = obj.dict[self.func.name] = self.func(obj)
    ^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/core.py", line 90, in pieces
    return list(self._clean_pieces())
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/root/miniconda3/envs/unsloth_env/lib/python3.11/site-packages/stack_data/core.py", line 114, in _clean_pieces
    raise AssertionError("Pieces mismatches: %s" % mismatches)
    AssertionError: Pieces mismatches: [{804, 805}]
    

    and the AssertionError: Pieces mismatches: [{804, 805}] is not important, the real error for me is ValueError: Cannot use chat template functions because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating.

    So your real error may be AttributeError: 'PeftModelForCausalLM' object has no attribute 'vllm_engine'

  4. danielhanchen commented on Jun 18, 2026

    @danielhanchen
    Member

    This should be fixed now - sorry on the delay - please update with uv pip install --upgrade unsloth unsloth_zoo --force-reinstall --no-cache-dir - if it's not fixed yet, it'll be in the next pip / PyPI release - if it's still not working after that, please open another issue - appreciate it again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions