Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(migrate): read Unsloth notebooks that carry IPython magics (#1579) (#1583)

Srinivasan Rb85efa908ad7
diff --git a/changelog.d/0.75.1/1583.fixed.md b/changelog.d/0.75.1/1583.fixed.md
new file mode 100644
index 00000000..d08687cb
--- /dev/null
+++ b/changelog.d/0.75.1/1583.fixed.md
@@ -0,0 +1 @@
+- **`soup migrate --from unsloth` reads a notebook that carries IPython magics (#1579 by @Srinivasan8888 in #1583).** Every code cell was concatenated and parsed as one Python module, so the first `!pip install ...` or `%%capture` line made the whole notebook a `SyntaxError` with no cell and no line, and every official Unsloth notebook starts with such a cell. A `%%` cell magic whose body IPython runs as Python (`%%capture`, `%%time`, `%%timeit`, `%%prun`) now loses only its header and its body is read; any other cell magic (`%%bash`, `%%writefile`, ...) is skipped whole. A line whose first non-blank character is `!` or `%` is treated as a magic only at statement level, so a `%` operator or a `!=` at the start of a continuation line is untouched, and a magic that is the only statement of an `if` / `for` / `with` body leaves a valid block behind. A cell that parses today is read byte for byte. A real syntax error is now reported with its code cell and line.
diff --git a/docs/data.md b/docs/data.md
index 2a45c93f..0fef5f97 100644
--- a/docs/data.md
+++ b/docs/data.md
@@ -613,6 +613,10 @@ soup migrate --from llamafactory config.yaml --dry-run
```
Automatically maps model, LoRA, training params, quantization, and task type. Warns about unsupported features.
+IPython lines in a notebook are skipped, so an unmodified Unsloth notebook reads as the Python it
+contains: `!pip install ...` and `%env ...` lines (a `!` line continued with a trailing backslash counts
+as one line), a `%%capture` header (its body is still read), and a `%%bash` cell whole; a real syntax
+error is reported with its code cell and line.
An axolotl `rl:` value with no Soup task (for example `rl: ebft`) stops the migration: `soup migrate` exits 1 and names the value instead of writing a `task: sft` config.
diff --git a/src/soup_cli/migrate/unsloth.py b/src/soup_cli/migrate/unsloth.py
index 76021a98..74eeb311 100644
--- a/src/soup_cli/migrate/unsloth.py
+++ b/src/soup_cli/migrate/unsloth.py
@@ -5,6 +5,7 @@ Uses AST parsing only — never exec/eval on notebook code.
import ast
import json
+import warnings
from pathlib import Path
from typing import Any, Dict, List, Optional
@@ -53,6 +54,84 @@ _TASK_FORMAT_MAP = {
}
+def _parses(source: str) -> bool:
+ # Only the real parse reports an invalid escape in the notebook; the probes
+ # would repeat each SyntaxWarning with a cell-local line number (#1583 review).
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", SyntaxWarning)
+ try:
+ ast.parse(source)
+ except SyntaxError:
+ return False
+ return True
+
+
+# Cell magics whose body is Python that IPython goes on to execute; the header goes,
+# the body stays. Any other cell magic (%%bash, %%writefile, %%html, ...) is not Python.
+_PYTHON_BODY_CELL_MAGICS = ("%%capture", "%%time", "%%timeit", "%%prun")
+
+
+def _blank(line: str) -> str:
+ return "\n" if line.endswith("\n") else ""
+
+
+def _neutralise_magic(line: str, prefix: str) -> Optional[str]:
+ """What replaces a ``!`` / ``%`` line at statement level, or ``None`` when it is not
+ one. After complete statements the line is blanked. After a header waiting for its
+ suite (``if x:``, or nested headers) it becomes a ``pass`` at the magic's own
+ indentation, which is what makes the probe parse, so a suite whose only statements
+ were magics stays a valid block. Inside an open bracket or after a backslash neither
+ parses, so the line is Python and stays."""
+ if _parses(prefix):
+ return _blank(line)
+ indent = line[: len(line) - len(line.lstrip())]
+ if _parses(prefix + indent + "pass\n"):
+ return indent + "pass" + _blank(line)
+ return None
+
+
+def _strip_ipython_magics(cell_source: str) -> str:
+ """Blank the IPython-only lines of one cell so the Python in it parses (#1579).
+
+ A cell that already parses is returned unchanged. A ``%%`` cell magic whose body
+ IPython executes as Python (``%%capture``, ``%%time``, ...) loses only its header
+ line; any other cell magic is not Python and is blanked whole. A line whose first
+ non-blank character is ``!`` or ``%`` is a magic only at statement level, decided by
+ whether the lines before it already form complete statements (a complete header
+ such as ``if x:`` counts, and the magic under it becomes an indented ``pass`` so the
+ block stays valid), so a ``%`` operator or a ``!=`` at the start of a continuation
+ line is left alone. Replaced lines keep their newline, so line numbers (which the
+ source-order logic relies on) do not move.
+ """
+ if _parses(cell_source):
+ return cell_source
+ lines = cell_source.splitlines(keepends=True)
+ first_index = next((i for i, line in enumerate(lines) if line.strip()), None)
+ out: list[str] = []
+ if first_index is not None and lines[first_index].lstrip().startswith("%%"):
+ header = lines[first_index].lstrip()
+ if not header.startswith(_PYTHON_BODY_CELL_MAGICS):
+ return "".join(_blank(line) for line in lines)
+ out = [_blank(line) for line in lines[: first_index + 1]]
+ lines = lines[first_index + 1 :]
+ continued = False
+ for line in lines:
+ if continued:
+ # IPython joins a magic line ending in a backslash with the next line
+ # (18 of the 82 public Unsloth GRPO notebooks install that way).
+ out.append(_blank(line))
+ continued = line.rstrip("\r\n").endswith("\\")
+ continue
+ replacement = None
+ if line.lstrip().startswith(("!", "%")):
+ # ponytail: re-parsing the prefix per magic line is O(n^2) in a cell's
+ # lines; notebook cells are short. Track bracket depth if that ever matters.
+ replacement = _neutralise_magic(line, "".join(out))
+ continued = replacement is not None and line.rstrip("\r\n").endswith("\\")
+ out.append(line if replacement is None else replacement)
+ return "".join(out)
+
+
def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:
"""Parse an Unsloth .ipynb notebook and return a Soup config dict.
@@ -75,20 +154,27 @@ def migrate_unsloth(notebook_path: Path) -> Dict[str, Any]:
if not code_cells:
raise ValueError("No code cells found in notebook")
- # Combine all code cell sources for AST parsing
+ # Combine all code cell sources for AST parsing, remembering where each cell
+ # starts so a syntax error can name its cell and line (#1579).
all_source = ""
+ cell_starts: list[int] = []
for cell in code_cells:
source = cell.get("source", [])
if isinstance(source, list):
- all_source += "".join(source) + "\n"
- else:
- all_source += source + "\n"
+ source = "".join(source)
+ cell_starts.append(all_source.count("\n") + 1)
+ all_source += _strip_ipython_magics(source) + "\n"
# Parse AST - safe, no execution
try:
tree = ast.parse(all_source)
- except SyntaxError:
- raise ValueError("Could not parse notebook code (SyntaxError)")
+ except SyntaxError as exc:
+ lineno = exc.lineno or 1
+ cell_index = max(i for i, start in enumerate(cell_starts) if start <= lineno)
+ raise ValueError(
+ f"Could not parse notebook code: {exc.msg} (code cell {cell_index + 1}, "
+ f"line {lineno - cell_starts[cell_index] + 1})"
+ ) from exc
warnings: List[str] = []
base: Optional[str] = None
diff --git a/tests/test_issue1579_notebook_magics.py b/tests/test_issue1579_notebook_magics.py
new file mode 100644
index 00000000..76873b89
--- /dev/null
+++ b/tests/test_issue1579_notebook_magics.py
@@ -0,0 +1,190 @@
+"""#1579: ``soup migrate --from unsloth`` reads a notebook that carries IPython magics.
+
+Every code cell was concatenated and parsed as one Python module, so the first ``!pip``
+or ``%%capture`` line made ``ast.parse`` raise and the whole notebook was refused with
+"Could not parse notebook code (SyntaxError)", no cell, no line. Every official Unsloth
+notebook starts with such a cell.
+
+A leading ``!`` / ``%`` line is a magic only at statement level, which is decided by
+whether the lines before it in the cell already parse, so a ``%`` operator or a ``!=`` at
+the start of a continuation line is left alone (the maintainer's fourth criterion). A
+cell whose first line starts with ``%%`` is skipped whole. Replaced lines become blank,
+so line numbers stay stable for the source-order logic. A cell that parses today is
+returned byte for byte.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from soup_cli.migrate.unsloth import _strip_ipython_magics, migrate_unsloth
+
+_LOAD = (
+ "from unsloth import FastLanguageModel\n"
+ "model, tokenizer = FastLanguageModel.from_pretrained(model_name='m', max_seq_length=2048,"
+ " load_in_4bit=True)\n"
+)
+_GRPO = (
+ "from trl import GRPOTrainer, GRPOConfig\n"
+ "cfg = GRPOConfig(per_device_train_batch_size=4, learning_rate=5e-6)\n"
+ "trainer = GRPOTrainer(model=model, reward_funcs=[f], args=cfg)\n"
+)
+
+
+def _migrate(tmp_path: Path, *cells: str) -> dict:
+ nb = {"cells": [{"cell_type": "code", "source": [c]} for c in cells]}
+ path = tmp_path / "nb.ipynb"
+ path.write_text(json.dumps(nb), encoding="utf-8")
+ return migrate_unsloth(path)
+
+
+def _summary(result: dict) -> tuple:
+ return result["task"], result["training"].get("lr"), result["training"].get("batch_size")
+
+
+class TestMagicsAreSkipped:
+ def test_the_issue_notebook_migrates_as_grpo(self, tmp_path: Path) -> None:
+ result = _migrate(tmp_path, "%%capture\n!pip install unsloth trl\n", _LOAD, _GRPO)
+ assert _summary(result) == ("grpo", 5e-6, 4)
+
+ def test_line_magics_between_statements_change_nothing(self, tmp_path: Path) -> None:
+ clean = _migrate(tmp_path, _LOAD, _GRPO)
+ with_magics = _migrate(
+ tmp_path,
+ "%env HF_HUB_OFFLINE=1\n" + _LOAD + "!nvidia-smi\n",
+ "%load_ext autoreload\n" + _GRPO + " %time print(1)\n",
+ )
+ assert with_magics == clean
+
+ def test_a_non_python_cell_magic_cell_is_skipped_whole(self, tmp_path: Path) -> None:
+ clean = _migrate(tmp_path, _LOAD, _GRPO)
+ with_cell_magic = _migrate(tmp_path, _LOAD, "%%bash\necho hi\nls -la | wc -l\n", _GRPO)
+ assert with_cell_magic == clean
+
+ @pytest.mark.parametrize("magic", ["%%capture", "%%time", "%%timeit", "%%prun"])
+ def test_a_python_body_cell_magic_keeps_its_body(self, tmp_path: Path, magic: str) -> None:
+ # Unsloth wraps real cells in %%capture; the GRPO config lives inside one here.
+ result = _migrate(tmp_path, _LOAD, f"{magic}\n!pip install trl\n" + _GRPO)
+ assert _summary(result) == ("grpo", 5e-6, 4)
+
+ def test_a_magic_as_the_first_line_of_a_suite_is_still_a_magic(self, tmp_path: Path) -> None:
+ # The header `if ...:` does not parse alone, but it is a complete statement
+ # boundary, so the magic under it is blanked; the operator case below is not.
+ cell = (
+ "import os\n"
+ "if os.environ.get('COLAB'):\n"
+ " !pip install unsloth\n"
+ " %env HF_HUB_OFFLINE=1\n"
+ "for i in range(2):\n"
+ " %time print(i)\n"
+ )
+ clean = _migrate(tmp_path, _LOAD, _GRPO)
+ assert _migrate(tmp_path, _LOAD, cell, _GRPO) == clean
+
+
+ def test_a_backslash_continued_magic_is_one_magic(self, tmp_path: Path) -> None:
+ # IPython joins a `!` line ending in a backslash with the lines after it;
+ # 18 of the 82 official Unsloth GRPO notebooks (gpt-oss among them) install
+ # that way, and only the first line was blanked (maintainer's review).
+ cell = (
+ "%%capture\n"
+ "import os\n"
+ "if 'COLAB_' in ''.join(os.environ):\n"
+ " !uv pip install -qqq \\\n"
+ " \"torch>=2.8.0\" {_numpy} \\\n"
+ " unsloth\n"
+ "!uv pip install --no-deps -qqq \\\n"
+ " trl==0.22.2\n"
+ )
+ clean = _migrate(tmp_path, _LOAD, _GRPO)
+ assert _migrate(tmp_path, cell, _LOAD, _GRPO) == clean
+ assert _strip_ipython_magics(cell).count("\n") == cell.count("\n")
+
+ def test_a_magic_under_nested_headers_is_still_a_magic(self, tmp_path: Path) -> None:
+ # CodeRabbit on the first head: a one-space probe satisfies `if a:` but not the
+ # nested ` if b:`; probing at the magic's own indentation does.
+ cell = (
+ "import os\n"
+ "if os.environ.get('COLAB'):\n"
+ " if not os.path.exists('/content/x'):\n"
+ " !pip install unsloth\n"
+ " with open('log') as fh:\n"
+ " for line in fh:\n"
+ " %time print(line)\n"
+ )
+ clean = _migrate(tmp_path, _LOAD, _GRPO)
+ assert _migrate(tmp_path, _LOAD, cell, _GRPO) == clean
+
+
+class TestContinuationLinesAreNotMagics:
+ # The maintainer's fourth criterion: a `%` operator or a `!=` at the start of a
+ # continuation line is Python, not a magic, and must survive untouched.
+ _CONT = (
+ "count, size, a, b = 7, 3, 1, 2\n"
+ "total = (count\n"
+ " % size)\n"
+ "flag = (a\n"
+ " != b)\n"
+ "rest = count \\\n"
+ " % 2\n"
+ )
+
+ def test_a_parsing_cell_is_returned_byte_for_byte(self, monkeypatch) -> None:
+ # The parse-first shortcut is the whole guarantee here: a cell that parses is
+ # never probed line by line (pinned per the review; removing the shortcut
+ # gives the same output, so only this catches it).
+ from soup_cli.migrate import unsloth as mod
+
+ def never(*args, **kwargs):
+ raise AssertionError("a parsing cell was probed line by line")
+
+ monkeypatch.setattr(mod, "_neutralise_magic", never)
+ assert _strip_ipython_magics(self._CONT) == self._CONT
+
+ def test_continuations_survive_even_in_a_cell_that_needs_transforming(self) -> None:
+ cell = "!pip install x\n" + self._CONT
+ out = _strip_ipython_magics(cell)
+ assert out == "\n" + self._CONT # the magic blanked, the operators kept
+ assert out.count("\n") == cell.count("\n") # line numbers stable
+
+ def test_a_backslash_after_a_continuation_operator_is_not_a_magic(self) -> None:
+ # `% 7 \` is Python (a continuation line), not a magic, so the line after it
+ # stays Python even though it follows a backslash (review of #1583: without the
+ # `replacement is not None` guard, `+ warmup` was blanked and silently lost).
+ body = "steps, warmup = 9, 1\ntotal = steps \\\n % 7 \\\n + warmup\n"
+ cell = "!pip install x\n" + body
+ assert _strip_ipython_magics(cell) == "\n" + body
+
+ def test_the_probes_do_not_repeat_an_invalid_escape_warning(self) -> None:
+ # The real parse reports an invalid escape once; the per-line probes must not
+ # repeat it with cell-local line numbers (SyntaxWarning on 3.12; earlier
+ # Pythons emit a DeprecationWarning, where this passes either way).
+ import warnings
+
+ cell = "s = '\\{'\n!pip install x\n"
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ assert _strip_ipython_magics(cell) == "s = '\\{'\n\n"
+ assert not [w for w in caught if issubclass(w.category, SyntaxWarning)]
+
+ def test_the_notebook_migrates_exactly_as_today(self, tmp_path: Path) -> None:
+ clean = _migrate(tmp_path, _LOAD, _GRPO)
+ with_cont = _migrate(tmp_path, _LOAD, self._CONT, _GRPO)
+ assert with_cont == clean
+
+
+class TestRealSyntaxErrors:
+ def test_a_real_error_is_refused_naming_the_cell_and_line(self, tmp_path: Path) -> None:
+ with pytest.raises(ValueError, match=r"cell 2.*line 2") as info:
+ _migrate(tmp_path, _LOAD, "ok = 1\ndef broken(:\n", _GRPO)
+ assert "Could not parse" in str(info.value)
+
+ def test_a_magic_line_inside_an_open_bracket_is_still_a_syntax_error(
+ self, tmp_path: Path
+ ) -> None:
+ # Not statement level, so not a magic: refused, as today.
+ with pytest.raises(ValueError, match="Could not parse"):
+ _migrate(tmp_path, _LOAD, "x = [\n!pip install y\n]\n", _GRPO)