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.

TextPreprocessor.add_structure_tokens: leave fenced code blocks alone (#16697)

Vineeth Sai Varikuntla0e241f233a8b
diff --git a/tests/test_raw_text.py b/tests/test_raw_text.py
index a87e6c78051..ca718fc0e71 100644
--- a/tests/test_raw_text.py
+++ b/tests/test_raw_text.py
@@ -823,6 +823,20 @@ def test_chunk_size_one_keeps_the_final_eos_overflow():
assert restored == list(range(count)) + [99]
+def test_add_structure_tokens_leaves_code_blocks_alone():
+ """A `# comment` inside a fenced block is code, not a chapter heading."""
+ text = (
+ "# Title\n\n"
+ "```python\n# install deps\n## not a section\nimport os\n```\n\n"
+ "## Section\n\n### Sub\n#### too deep\n"
+ )
+ assert TextPreprocessor().add_structure_tokens(text) == (
+ "<|chapter|>Title<|/chapter|>\n\n"
+ "<|code|python|># install deps\n## not a section\nimport os<|/code|>\n\n"
+ "<|section|>Section<|/section|>\n\n<|subsection|>Sub<|/subsection|>\n#### too deep\n"
+ )
+
+
if __name__ == "__main__":
success = test_raw_text_loader()
test_clean_text_keeps_text_in_any_script()
@@ -841,4 +855,5 @@ if __name__ == "__main__":
test_tokenized_chunks_reserve_space_for_the_final_eos()
test_text_chunks_reserve_space_for_the_final_eos()
test_chunk_size_one_keeps_the_final_eos_overflow()
+ test_add_structure_tokens_leaves_code_blocks_alone()
sys.exit(0 if success else 1)
diff --git a/unsloth/dataprep/raw_text.py b/unsloth/dataprep/raw_text.py
index fadc923ada0..4aee863c6e1 100644
--- a/unsloth/dataprep/raw_text.py
+++ b/unsloth/dataprep/raw_text.py
@@ -360,10 +360,12 @@ class TextPreprocessor:
_MULTIPLE_SPACES_PATTERN = re.compile(r"[ ]{2,}")
_NEWLINE_SPACES_PATTERN = re.compile(r" *\n *")
_MULTIPLE_NEWLINES_PATTERN = re.compile(r"\n\n\n+")
- _CHAPTER_PATTERN = re.compile(r"^# (.+)$", re.MULTILINE)
- _SECTION_PATTERN = re.compile(r"^## (.+)$", re.MULTILINE)
- _SUBSECTION_PATTERN = re.compile(r"^### (.+)$", re.MULTILINE)
- _CODE_BLOCK_PATTERN = re.compile(r"```(\w*)\n(.*?)\n```", re.DOTALL)
+ # One pass, so a "# comment" inside a fenced block stays code instead of becoming a heading.
+ _STRUCTURE_PATTERN = re.compile(
+ r"```(\w*)\n((?s:.*?))\n```|^(#{1,3}) (.+)$",
+ re.MULTILINE,
+ )
+ _HEADING_TAGS = {1: "chapter", 2: "section", 3: "subsection"}
def clean_text(self, text):
"""Remove unwanted characters, normalize whitespace"""
@@ -386,11 +388,14 @@ class TextPreprocessor:
def add_structure_tokens(self, text):
"""Add special tokens for structure (chapters, sections)"""
- text = self._CHAPTER_PATTERN.sub(r"<|chapter|>\1<|/chapter|>", text)
- text = self._SECTION_PATTERN.sub(r"<|section|>\1<|/section|>", text)
- text = self._SUBSECTION_PATTERN.sub(r"<|subsection|>\1<|/subsection|>", text)
- text = self._CODE_BLOCK_PATTERN.sub(r"<|code|\1|>\2<|/code|>", text)
- return text
+
+ def tag(match):
+ if match[3] is None:
+ return f"<|code|{match[1]}|>{match[2]}<|/code|>"
+ name = self._HEADING_TAGS[len(match[3])]
+ return f"<|{name}|>{match[4]}<|/{name}|>"
+
+ return self._STRUCTURE_PATTERN.sub(tag, text)
def validate_dataset(
self,