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.

Preserve input prompts in to_sharegpt when merged_prompt is omitted (#8277)

Vineeth Sai Varikuntla74371a326e49
diff --git a/tests/python/test_to_sharegpt_optional_none.py b/tests/python/test_to_sharegpt_optional_none.py
index 05fcb8a6a83..6b122d4e89a 100644
--- a/tests/python/test_to_sharegpt_optional_none.py
+++ b/tests/python/test_to_sharegpt_optional_none.py
@@ -95,3 +95,110 @@ def test_optional_block_falsy_but_present_gating_value_still_renders():
merged_prompt = "Count: [[{n}]]!"
out = _render(merged_prompt, ["n"], {"n": [0]})
assert out[0] == "Count: 0!"
+
+
+def _load_to_sharegpt():
+ # Same trick as above: pull to_sharegpt and the two helpers it calls out of
+ # the source without importing unsloth.
+ source = Path(__file__).parents[2] / "unsloth" / "chat_templates.py"
+ tree = ast.parse(source.read_text(encoding = "utf-8"))
+ wanted = {"_parse_combined_prompt", "_create_formatter", "to_sharegpt"}
+ funcs = [
+ node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in wanted
+ ]
+ namespace = {"re": re}
+ module = ast.Module(body = funcs, type_ignores = [])
+ ast.fix_missing_locations(module)
+ exec(compile(module, str(source), "exec"), namespace)
+ return namespace["to_sharegpt"]
+
+
+def _alpaca():
+ from datasets import Dataset
+ return Dataset.from_dict(
+ {
+ "instruction": ["What is 2+2?", "Capital of France?"],
+ "output": ["4", "Paris"],
+ }
+ )
+
+
+def test_default_merged_prompt_keeps_the_input_column():
+ # merged_prompt is optional: without one, merged_column_name names a column
+ # that is already there. The merging map used to run anyway and overwrite it
+ # with empty strings, so every human turn came out blank.
+ to_sharegpt = _load_to_sharegpt()
+ converted = to_sharegpt(_alpaca())
+ users = [row["conversations"][0]["value"] for row in converted]
+ assert users == ["What is 2+2?", "Capital of France?"]
+
+
+def test_default_merged_prompt_with_renamed_columns():
+ from datasets import Dataset
+
+ to_sharegpt = _load_to_sharegpt()
+ dataset = Dataset.from_dict({"Query": ["123?"], "Answer": ["456"]})
+ converted = to_sharegpt(
+ dataset,
+ merged_column_name = "Query",
+ output_column_name = "Answer",
+ )
+ assert converted[0]["conversations"] == [
+ {"from": "human", "value": "123?"},
+ {"from": "gpt", "value": "456"},
+ ]
+
+
+def test_explicit_merged_prompt_still_merges():
+ from datasets import Dataset
+
+ to_sharegpt = _load_to_sharegpt()
+ dataset = Dataset.from_dict({"instruction": ["Sum"], "input": ["2+2"], "output": ["4"]})
+ converted = to_sharegpt(dataset, merged_prompt = "{instruction}\n{input}")
+ assert converted[0]["conversations"][0]["value"] == "Sum\n2+2"
+
+
+def test_missing_input_column_says_which_column_is_missing():
+ from datasets import Dataset
+
+ to_sharegpt = _load_to_sharegpt()
+ dataset = Dataset.from_dict({"prompt": ["hi"], "output": ["yo"]})
+ try:
+ to_sharegpt(dataset)
+ except KeyError as error:
+ assert "instruction" in str(error)
+ assert "prompt" in str(error)
+ else:
+ raise AssertionError("expected a KeyError naming the missing input column")
+
+
+def test_conversation_extension_keeps_the_real_prompts():
+ to_sharegpt = _load_to_sharegpt()
+ converted = to_sharegpt(_alpaca(), conversation_extension = 2)
+ values = [turn["value"] for turn in converted[0]["conversations"]]
+ assert "" not in values
+ assert len(converted[0]["conversations"]) == 4
+
+
+def test_null_cells_do_not_render_as_the_word_none():
+ from datasets import Dataset
+
+ to_sharegpt = _load_to_sharegpt()
+ dataset = Dataset.from_dict({"instruction": ["ok", None], "output": [None, "fine"]})
+ converted = to_sharegpt(dataset)
+ values = [turn["value"] for row in converted for turn in row["conversations"]]
+
+ assert "None" not in values
+ assert values == ["ok", "", "", "fine"]
+
+
+def test_null_cells_match_the_merged_prompt_path():
+ from datasets import Dataset
+
+ to_sharegpt = _load_to_sharegpt()
+ rows = {"instruction": ["ok", None], "output": ["a", "b"]}
+
+ merged = to_sharegpt(Dataset.from_dict(rows), merged_prompt = "{instruction}")
+ plain = to_sharegpt(Dataset.from_dict(rows))
+
+ assert [r["conversations"] for r in merged] == [r["conversations"] for r in plain]
diff --git a/unsloth/chat_templates.py b/unsloth/chat_templates.py
index 34710c4812c..317b4106ac5 100644
--- a/unsloth/chat_templates.py
+++ b/unsloth/chat_templates.py
@@ -2312,9 +2312,19 @@ def to_sharegpt(
if type(convo) is list:
raise TypeError("Unsloth: Your dataset is probably already in ShareGPT format!")
- possible_columns, final_optional_prompts = _parse_combined_prompt(merged_prompt, dataset)
- formatter = _create_formatter(possible_columns, final_optional_prompts, merged_column_name)
- dataset = dataset.map(formatter, batched = True, desc = "Merging columns")
+ if merged_prompt:
+ possible_columns, final_optional_prompts = _parse_combined_prompt(merged_prompt, dataset)
+ formatter = _create_formatter(possible_columns, final_optional_prompts, merged_column_name)
+ dataset = dataset.map(formatter, batched = True, desc = "Merging columns")
+ elif merged_column_name not in dataset.column_names:
+ # Without a merged_prompt there is nothing to build the input from, so the
+ # column has to be there already. Running the formatter anyway would fill
+ # merged_column_name with empty strings and silently blank every human turn.
+ raise KeyError(
+ f"Unsloth: `to_sharegpt` needs an input column named '{merged_column_name}', "
+ f"but the dataset has {dataset.column_names}. Pass `merged_column_name` to "
+ "name the existing column, or `merged_prompt` to build the input from several."
+ )
def __convert_to_sharegpt__(examples):
users = examples[merged_column_name]
@@ -2324,10 +2334,14 @@ def to_sharegpt(
"Unsloth: Input and output columns must have matching batch lengths. "
f"Got {len(users)} {merged_column_name} rows and {len(assistants)} {output_column_name} rows."
)
+ # A null cell is an absent value, not the word "None". _create_formatter
+ # already coalesces it on the merged path, and skipping the merge must
+ # not reintroduce it; the output column never went through that path at
+ # all, so it leaked here either way.
texts = [
[
- {"from" : "human", "value" : str(user) },
- {"from" : "gpt", "value" : str(assistant)},
+ {"from" : "human", "value" : "" if user is None else str(user) },
+ {"from" : "gpt", "value" : "" if assistant is None else str(assistant)},
] \
for user, assistant in zip(users, assistants)
]