Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Fix Mistral DPO/preference training crash on non-xformers platforms (e.g. Intel XPU) (#4889)

cheehook7aa442289bac
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index 2f619135509..031cabcd39b 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -1030,6 +1030,7 @@ def LlamaModel_fast_forward(
if (
getattr(self, "_has_no_labels", False) is True
and (attention_mask is not None)
+ and attention_mask.ndim == 2
and (past_key_values is None)
and (not train_embed_tokens)
and self.training
diff --git a/unsloth/models/mistral.py b/unsloth/models/mistral.py
index 83e9ab9486b..d42e9066048 100644
--- a/unsloth/models/mistral.py
+++ b/unsloth/models/mistral.py
@@ -188,6 +188,16 @@ def MistralForCausalLM_fast_forward(
# If attention_mask exists, it will be handled in the attention forward
+ elif self.training:
+ # During training, LlamaModel_fast_forward's DPO embed-masking
+ # block requires a 2D attention_mask (it does
+ # inputs_embeds *= attention_mask.unsqueeze(0).transpose(0, 1).transpose(1, 2)).
+ # Afterwards, LlamaModel_fast_forward sets attention_mask=None
+ # before the attention layers anyway, so leaving the 2D mask
+ # untouched here is safe and avoids converting to 4D (which would
+ # crash the DPO block).
+ pass
+
else:
# Not using xformers - need to create attention masks
if (