Skip to content

[Bug] SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats #2760

Closed

Description

@hongbo-miao

I am trying to run Unsloth in RTX 5090 (Blackwell).

The code is based on https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_(14B)-Reasoning-Conversational.ipynb

src/main.py

import os
import torch
import pandas as pd
from datasets import load_dataset, Dataset
from unsloth import FastLanguageModel
from unsloth.chat_templates import standardize_sharegpt
from trl import SFTTrainer, SFTConfig
from transformers import TextStreamer

def load_model():
    """Load and configure the Qwen3-14B model"""
    print("Loading Qwen3-14B model...")

    model, tokenizer = FastLanguageModel.from_pretrained(
        model_name="unsloth/Qwen3-14B",
        max_seq_length=2048,
        load_in_4bit=True,
        load_in_8bit=False,
        full_finetuning=False,
    )

    # Add LoRA adapters
    model = FastLanguageModel.get_peft_model(
        model,
        r=32,
        target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
        lora_alpha=32,
        lora_dropout=0,
        bias="none",
        use_gradient_checkpointing="unsloth",
        random_state=3407,
        use_rslora=False,
        loftq_config=None,
    )

    return model, tokenizer

def prepare_datasets(tokenizer, chat_percentage=0.25):
    """Load and prepare training datasets"""
    print("Loading datasets...")

    # Load reasoning and non-reasoning datasets
    reasoning_dataset = load_dataset("unsloth/OpenMathReasoning-mini", split="cot")
    non_reasoning_dataset = load_dataset("mlabonne/FineTome-100k", split="train")

    print(f"Reasoning dataset size: {len(reasoning_dataset)}")
    print(f"Non-reasoning dataset size: {len(non_reasoning_dataset)}")

    # Convert reasoning dataset to conversational format
    def generate_conversation(examples):
        problems = examples["problem"]
        solutions = examples["generated_solution"]
        conversations = []
        for problem, solution in zip(problems, solutions):
            conversations.append([
                {"role": "user", "content": problem},
                {"role": "assistant", "content": solution},
            ])
        return {"conversations": conversations}

    reasoning_conversations = tokenizer.apply_chat_template(
        reasoning_dataset.map(generate_conversation, batched=True)["conversations"],
        tokenize=False,
    )

    # Convert non-reasoning dataset to conversational format
    dataset = standardize_sharegpt(non_reasoning_dataset)
    non_reasoning_conversations = tokenizer.apply_chat_template(
        dataset["conversations"],
        tokenize=False,
    )

    # Sample non-reasoning dataset based on chat percentage
    non_reasoning_subset = pd.Series(non_reasoning_conversations)
    non_reasoning_subset = non_reasoning_subset.sample(
        int(len(reasoning_conversations) * (chat_percentage / (1 - chat_percentage))),
        random_state=2407,
    )

    print(f"Reasoning conversations: {len(reasoning_conversations)}")
    print(f"Non-reasoning subset: {len(non_reasoning_subset)}")
    print(f"Chat percentage: {len(non_reasoning_subset) / (len(non_reasoning_subset) + len(reasoning_conversations))}")

    # Combine datasets
    data = pd.concat([
        pd.Series(reasoning_conversations),
        pd.Series(non_reasoning_subset)
    ])
    data.name = "text"

    combined_dataset = Dataset.from_pandas(pd.DataFrame(data))
    combined_dataset = combined_dataset.shuffle(seed=3407)

    return combined_dataset

def train_model(model, tokenizer, dataset):
    """Train the model using SFTTrainer"""
    print("Starting training...")

    trainer = SFTTrainer(
        model=model,
        tokenizer=tokenizer,
        train_dataset=dataset,
        eval_dataset=None,
        args=SFTConfig(
            dataset_text_field="text",
            per_device_train_batch_size=2,
            gradient_accumulation_steps=4,
            warmup_steps=5,
            max_steps=30,  # Set num_train_epochs=1 for full training
            learning_rate=2e-4,
            logging_steps=1,
            optim="adamw_8bit",
            weight_decay=0.01,
            lr_scheduler_type="linear",
            seed=3407,
            report_to="none",
        ),
    )

    # Show initial memory stats
    gpu_stats = torch.cuda.get_device_properties(0)
    start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
    max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
    print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
    print(f"{start_gpu_memory} GB of memory reserved.")

    # Train the model
    trainer_stats = trainer.train()

    # Show final memory and time stats
    used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
    used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
    used_percentage = round(used_memory / max_memory * 100, 3)
    lora_percentage = round(used_memory_for_lora / max_memory * 100, 3)

    print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
    print(f"{round(trainer_stats.metrics['train_runtime']/60, 2)} minutes used for training.")
    print(f"Peak reserved memory = {used_memory} GB.")
    print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
    print(f"Peak reserved memory % of max memory = {used_percentage} %.")
    print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")

    return trainer_stats

def test_inference(model, tokenizer):
    """Test the trained model with inference examples"""
    print("\n" + "="*50)
    print("Testing inference...")
    print("="*50)

    # Test without thinking
    print("\nTesting without thinking:")
    messages = [
        {"role": "user", "content": "Solve (x + 2)^2 = 0."}
    ]
    text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True,
        enable_thinking=False,
    )

    _ = model.generate(
        **tokenizer(text, return_tensors="pt").to("cuda"),
        max_new_tokens=256,
        temperature=0.7, top_p=0.8, top_k=20,
        streamer=TextStreamer(tokenizer, skip_prompt=True),
    )

    # Test with thinking
    print("\nTesting with thinking:")
    text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True,
        enable_thinking=True,
    )

    _ = model.generate(
        **tokenizer(text, return_tensors="pt").to("cuda"),
        max_new_tokens=1024,
        temperature=0.6, top_p=0.95, top_k=20,
        streamer=TextStreamer(tokenizer, skip_prompt=True),
    )

def save_model(model, tokenizer, save_path="lora_model"):
    """Save the trained model"""
    print(f"\nSaving model to {save_path}...")
    model.save_pretrained(save_path)
    tokenizer.save_pretrained(save_path)
    print("Model saved successfully!")

def main():
    """Main execution function"""
    print("Qwen3 (14B) Reasoning Conversational Fine-tuning")
    print("="*50)

    try:
        # Load model and tokenizer
        model, tokenizer = load_model()

        # Prepare datasets
        combined_dataset = prepare_datasets(tokenizer, chat_percentage=0.25)

        # Train the model
        trainer_stats = train_model(model, tokenizer, combined_dataset)
        print(f"\nTraining completed with metrics: {trainer_stats}")

        # Test inference
        test_inference(model, tokenizer)

        # Save the model
        save_model(model, tokenizer)

        print("\n" + "="*50)
        print("Training completed successfully!")
        print("="*50)

    except Exception as e:
        print(f"Error occurred: {str(e)}")
        raise

if __name__ == "__main__":
    main()

pyproject.toml

[project]
name = "fine-tuning"
version = "1.0.0"
requires-python = "==3.12.0"
dependencies = [
  "unsloth[cu128-torch270]==2025.6.2",
  "torch",
]

[tool.uv]
package = false
required-version = ">=0.6.0"

[tool.uv.sources]
torch = [{ index = "pytorch-cu128" }]

[[tool.uv.index]]
name = "pytorch-cu128"
url = "https://download.pytorch.org/whl/cu128"
explicit = true

Currently uv run python src/main.py fails with error

🦥 Unsloth: Will patch your computer to enable 2x faster free finetuning.
/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth_zoo/compiler.py:1191: SyntaxWarning: invalid escape sequence '\:'
  r"for ([^\s]{1,}) in " + modulelist_item + "\:[\n]" + \
/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth_zoo/compiler.py:1434: SyntaxWarning: invalid escape sequence '\('
  regex_find = f"{call_class}\(([^\)]{{1,}})\)"
/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth_zoo/compiler.py:1434: SyntaxWarning: invalid escape sequence '\)'
  regex_find = f"{call_class}\(([^\)]{{1,}})\)"
/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth_zoo/compiler.py:1440: SyntaxWarning: invalid escape sequence '\('
  regex_find = "def forward\(([^\)]{1,})\)"
/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth_zoo/compiler.py:1573: SyntaxWarning: invalid escape sequence '\)'
  inherited_modules = re.findall(r"class ([^\s]{1,})\(" + inherited_class + "\)", full_source)
/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth_zoo/compiler.py:1627: SyntaxWarning: invalid escape sequence '\('
  called = re.findall(r"[\s]{1,}" + re.escape(function) + "\(.+?\)", full_source, flags = re.DOTALL)
/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth_zoo/peft_utils.py:225: SyntaxWarning: invalid escape sequence '\.'
  name = re.sub("\.([\d]{1,})\.", r"[\1].", name)
🦥 Unsloth Zoo will now patch everything to make training faster!
Qwen3 (14B) Reasoning Conversational Fine-tuning
==================================================
Loading Qwen3-14B model...
==((====))==  Unsloth 2025.6.2: Fast Qwen3 patching. Transformers: 4.52.4.
   \\   /|    NVIDIA GeForce RTX 5090. Num GPUs = 2. Max memory: 31.357 GB. Platform: Linux.
O^O/ \_/ \    Torch: 2.7.0+cu128. CUDA: 12.0. CUDA Toolkit: 12.8. Triton: 3.3.0
\        /    Bfloat16 = TRUE. FA [Xformers = 0.0.30. FA2 = False]
 "-____-"     Free license: http://github.com/unslothai/unsloth
Unsloth: Fast downloading is enabled - ignore downloading bars which are red colored!
Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:01<00:00,  2.31it/s]
Unsloth 2025.6.2 patched 40 layers with 40 QKV layers, 40 O layers and 40 MLP layers.
Loading datasets...
Reasoning dataset size: 19252
Non-reasoning dataset size: 100000
Reasoning conversations: 19252
Non-reasoning subset: 6417
Chat percentage: 0.2499902606256574
Starting training...
Unsloth: Tokenizing ["text"] (num_proc=64): 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 25669/25669 [01:31<00:00, 281.07 examples/s]
GPU = NVIDIA GeForce RTX 5090. Max memory = 31.357 GB.
13.812 GB of memory reserved.
==((====))==  Unsloth - 2x faster free finetuning | Num GPUs used = 1
   \\   /|    Num examples = 25,669 | Num Epochs = 1 | Total steps = 30
O^O/ \_/ \    Batch size per device = 4 | Gradient accumulation steps = 4
\        /    Data Parallel GPUs = 1 | Total batch size (4 x 4 x 1) = 16
 "-____-"     Trainable parameters = 128,450,560/14,000,000,000 (0.92% trained)
  0%|                                                                                                                                                                                                                                                           | 0/30 [00:00<?, ?it/s]Error occurred: PY_SSIZE_T_CLEAN macro must be defined for '#' formats
Traceback (most recent call last):
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/src/main.py", line 225, in <module>
    main()
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/src/main.py", line 207, in main
    trainer_stats = train_model(model, tokenizer, combined_dataset)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/src/main.py", line 129, in train_model
    trainer_stats = trainer.train()
                    ^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/transformers/trainer.py", line 2240, in train
    return inner_training_loop(
           ^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 314, in _fast_inner_training_loop
  File "<string>", line 31, in _unsloth_training_step
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/unsloth_compiled_cache/UnslothSFTTrainer.py", line 746, in compute_loss
    outputs = super().compute_loss(
              ^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth/models/_utils.py", line 1069, in _unsloth_pre_compute_loss
    outputs = self._old_compute_loss(model, inputs, *args, **kwargs)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/transformers/trainer.py", line 3810, in compute_loss
    outputs = model(**inputs)
              ^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1762, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/accelerate/utils/operations.py", line 818, in forward
    return model_forward(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/accelerate/utils/operations.py", line 806, in __call__
    return convert_to_fp32(self.model_forward(*args, **kwargs))
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/amp/autocast_mode.py", line 44, in decorate_autocast
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/_compile.py", line 51, in inner
    return disable_fn(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py", line 838, in _fn
    return fn(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth/models/llama.py", line 1260, in PeftModelForCausalLM_fast_forward
    return self.base_model(
           ^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1762, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/peft/tuners/tuners_utils.py", line 193, in forward
    return self.model.forward(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth/models/llama.py", line 1103, in _CausalLM_fast_forward
    outputs = self.model(
              ^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1762, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth/models/llama.py", line 924, in LlamaModel_fast_forward
    layer_outputs = decoder_layer(
                    ^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/transformers/modeling_layers.py", line 47, in __call__
    return self._gradient_checkpointing_func(partial(super().__call__, **kwargs), *args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/_compile.py", line 51, in inner
    return disable_fn(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py", line 838, in _fn
    return fn(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/utils/checkpoint.py", line 488, in checkpoint
    return CheckpointFunction.apply(function, preserve, *args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/autograd/function.py", line 575, in apply
    return super().apply(*args, **kwargs)  # type: ignore[misc]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth_zoo/gradient_checkpointing.py", line 475, in forward
    outputs = run_function(*args)
              ^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1762, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth/models/llama.py", line 591, in LlamaDecoderLayer_fast_forward
    hidden_states = fast_rms_layernorm(self.input_layernorm, hidden_states)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py", line 838, in _fn
    return fn(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth/kernels/rms_layernorm.py", line 215, in fast_rms_layernorm
    out = Fast_RMS_Layernorm.apply(X, W, eps, gemma)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/torch/autograd/function.py", line 575, in apply
    return super().apply(*args, **kwargs)  # type: ignore[misc]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/unsloth/kernels/rms_layernorm.py", line 160, in forward
    fx[(n_rows,)](
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/triton/runtime/jit.py", line 347, in <lambda>
    return lambda *args, **kwargs: self.run(grid=grid, warmup=False, *args, **kwargs)
                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/triton/runtime/jit.py", line 591, in run
    kernel.run(grid_0, grid_1, grid_2, stream, kernel.function, kernel.packed_metadata,
    ^^^^^^^^^^
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/triton/compiler/compiler.py", line 413, in __getattribute__
    self._init_handles()
  File "/home/hongbo-miao/hongbomiao.com/machine-learning/fine-tuning/.venv/lib/python3.12/site-packages/triton/compiler/compiler.py", line 408, in _init_handles
    self.module, self.function, self.n_regs, self.n_spills = driver.active.utils.load_binary(
                                                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats
  0%|                                                                                                                                                                                                                                                           | 0/30 [00:01<?, ?it/s]
error: Recipe `dev` failed on line 8 with exit code 1

Related issues:

Any guide would be appreciate, thank you! ☺️

Activity

  1. hongbo-miao commented on Jun 19, 2025

    @hongbo-miao
    Author

    Seems this is a potential fix: triton-lang/triton#6928

  2. qingy1337 commented on Jun 24, 2025

    @qingy1337
    Contributor

    I'm using 5090 and I wasn't using unsloth but I was using ktransformers. I got this [PY_SSIZE_T_CLEAN macro must be defined for '#' formats error, so I did:

    1. pip uninstall triton
    2. Git clone the triton repo
    3. Add the line peterbell10 says in the triton pull request: add #define PY_SSIZE_T_CLEAN before those includes. You should add this line to the triton/third_party/nvidia/backend/driver.py file
    4. From the triton folder, pip install -r python/requirements.txt
    5. Run MAX_JOBS=2 python setup.py bdist_wheel
    6. pip install dist/whateverfilethisisjustclicktabtoautocomplete.whl
    7. So now triton is reinstalled with this fix and it worked for me. There's another step but I think that's specific to ktransformers.

    Let me know if it works!

  3. Galois98 commented on Jul 31, 2025

    @Galois98

    Firstly, delete ~/.triton/, then pip install --no-build-isolation --pre -v -U git+https://github.com/facebookresearch/xformers.git@fde5a2fb46e3f83d73e2974a4d12caf526a4203e
    I'm pretty sure that will solve your problem.

  4. danielhanchen commented on Oct 12, 2026

    @danielhanchen
    Member

    Fixed! Sorry on the delay. Triton 3.2 and 3.3 (the versions torch 2.6 and 2.7 use) cache a small compiled helper without recording which Python built it, so a copy built by Python 3.13 got reused by Python 3.12 and crashed on the first kernel launch with this error. Unsloth now keeps a separate cached copy per Python version, fixed in #13409. Until you update, deleting ~/.triton/cache also clears it.
    To update: uv pip install --upgrade unsloth unsloth_zoo --force-reinstall --no-cache-dir (if it's not in the current release yet it'll be in the next one). Reopen if it still happens.

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

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions