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.

6.5 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

from datasets import Dataset, load_dataset

from utils.datasets import convert_alpaca_to_chatml, format_and_template_dataset
from utils.datasets.cells import cell_text


class _Tokenizer:
    chat_template = "{{ messages }}"
    eos_token = "</s>"


def _format_result(dataset, tokenizer = None):
    result = format_and_template_dataset(
        dataset,
        model_name = "Qwen2ForCausalLM",
        tokenizer = tokenizer or _Tokenizer(),
        batch_size = 2,
        num_proc = 1,
    )
    assert result["success"] is True
    assert result["final_format"] == "alpaca"
    return result


def _format(dataset, tokenizer = None):
    return list(_format_result(dataset, tokenizer)["dataset"]["text"])


def test_missing_alpaca_values_are_formatted_as_empty_text():
    dataset = Dataset.from_dict(
        {
            "instruction": ["Say hi", None],
            "input": [None, "context"],
            "output": ["hi", None],
        }
    )

    texts = _format(dataset)

    assert texts[0].endswith("### Instruction:\nSay hi\n\n### Input:\n\n\n### Response:\nhi</s>")
    assert texts[1].endswith("### Instruction:\n\n\n### Input:\ncontext\n\n### Response:\n</s>")
    assert all("None" not in text for text in texts)


def test_blank_csv_cells_are_not_trained_as_none(tmp_path):
    csv_path = tmp_path / "train.csv"
    csv_path.write_text('instruction,input,output\nSay hi,,hi\nSay bye,"",\n')
    dataset = load_dataset("csv", data_files = str(csv_path), split = "train")

    texts = _format(dataset)

    assert texts[0].endswith("### Input:\n\n\n### Response:\nhi</s>")
    assert texts[1].endswith("### Input:\n\n\n### Response:\n</s>")
    assert all("None" not in text for text in texts)


def test_alpaca_rows_do_not_get_a_second_eos():
    dataset = Dataset.from_dict({"instruction": ["Echo"], "input": [""], "output": ["done</s>"]})

    assert _format(dataset)[0].endswith("### Response:\ndone</s>")


def test_alpaca_rows_take_eos_from_a_processors_tokenizer():
    class _Processor:
        chat_template = "{{ messages }}"
        tokenizer = _Tokenizer()

    dataset = Dataset.from_dict({"instruction": ["Add 2+2"], "input": [""], "output": ["4"]})

    assert _format(dataset, _Processor())[0].endswith("### Response:\n4</s>")


def test_alpaca_warns_when_tokenizer_has_no_eos():
    class _NoEosTokenizer:
        chat_template = "{{ messages }}"

    dataset = Dataset.from_dict({"instruction": ["Add 2+2"], "input": [""], "output": ["4"]})
    result = _format_result(dataset, _NoEosTokenizer())

    assert result["dataset"][0]["text"].endswith("### Response:\n4")
    assert any("no eos_token" in warning for warning in result["warnings"])


def test_blank_csv_cells_are_not_converted_to_none_for_chatml(tmp_path):
    csv_path = tmp_path / "train.csv"
    csv_path.write_text("instruction,input,output\nSay bye,,\n,context,answer\n")
    dataset = load_dataset("csv", data_files = str(csv_path), split = "train")

    conversations = convert_alpaca_to_chatml(dataset, batch_size = 2, num_proc = 1)["conversations"]

    assert conversations[0] == [
        {"role": "user", "content": "Say bye"},
        {"role": "assistant", "content": ""},
    ]
    assert conversations[1] == [
        {"role": "user", "content": "context"},
        {"role": "assistant", "content": "answer"},
    ]


def test_a_blank_cell_in_a_numeric_column_still_converts_to_chatml(tmp_path):
    csv_path = tmp_path / "train.csv"
    csv_path.write_text("instruction,input,output\nA,1,x\nB,,y\nC,3,\n")
    dataset = load_dataset("csv", data_files = str(csv_path), split = "train")

    conversations = convert_alpaca_to_chatml(dataset, batch_size = 3, num_proc = 1)["conversations"]

    assert conversations[0] == [
        {"role": "user", "content": "A\n\n1.0"},
        {"role": "assistant", "content": "x"},
    ]
    assert conversations[1] == [
        {"role": "user", "content": "B"},
        {"role": "assistant", "content": "y"},
    ]
    assert conversations[2] == [
        {"role": "user", "content": "C\n\n3.0"},
        {"role": "assistant", "content": ""},
    ]
    assert all(
        isinstance(message["content"], str)
        for conversation in conversations
        for message in conversation
    )


def test_every_cell_reaches_a_chat_template_as_text():
    dataset = Dataset.from_dict({"instruction": ["a"], "input": [True], "output": [7]})

    conversations = convert_alpaca_to_chatml(dataset, batch_size = 1, num_proc = 1)["conversations"]

    assert conversations[0] == [
        {"role": "user", "content": "a\n\nTrue"},
        {"role": "assistant", "content": "7"},
    ]


def test_cell_text_maps_every_empty_spelling_to_empty_text():
    assert cell_text(None) == ""
    assert cell_text(float("nan")) == ""
    assert cell_text("") == ""

    assert cell_text("None") == "None"
    assert cell_text(0) == "0"
    assert cell_text(False) == "False"
    assert cell_text("0") == "0"
    assert cell_text(" ") == " "


def test_alpaca_without_input_column_formats_empty_input_on_every_row():
    dataset = Dataset.from_dict(
        {
            "instruction": ["a", "b", "c", "d", "e"],
            "output": ["1", None, "3", "4", "5"],
        }
    )

    texts = _format(dataset)

    assert len(texts) == 5
    for instruction, output, text in zip("abcde", ["1", "", "3", "4", "5"], texts):
        assert text.endswith(
            f"### Instruction:\n{instruction}\n\n### Input:\n\n\n### Response:\n{output}</s>"
        )


def test_alpaca_input_column_is_read_per_row_across_batches():
    dataset = Dataset.from_dict(
        {
            "instruction": [f"i{n}" for n in range(5)],
            "input": [f"x{n}" if n % 2 else None for n in range(5)],
            "output": [f"o{n}" for n in range(5)],
        }
    )

    texts = _format(dataset)

    for n, text in enumerate(texts):
        expected_input = f"x{n}" if n % 2 else ""
        assert text.endswith(
            f"### Instruction:\ni{n}\n\n### Input:\n{expected_input}\n\n### Response:\no{n}</s>"
        )


def test_alpaca_system_column_formats_from_a_numpy_formatted_dataset():
    dataset = Dataset.from_dict(
        {
            "instruction": ["a", "b"],
            "output": ["1", "2"],
            "system": ["Be brief.", ""],
        }
    ).with_format("numpy")

    texts = _format(dataset)

    assert texts[0].startswith("Be brief.\n\n### Instruction:\na\n")
    assert texts[1].endswith("### Instruction:\nb\n\n### Input:\n\n\n### Response:\n2</s>")