Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(train): step profiler on each step so --profile writes trace (#1448) (#1639)
Nurkhan Esenbek19074e2f17af
diff --git a/changelog.d/0.75.1/1639.fixed.md b/changelog.d/0.75.1/1639.fixed.mdnew file mode 100644index 00000000..7d5b9dd1--- /dev/null+++ b/changelog.d/0.75.1/1639.fixed.md@@ -0,0 +1 @@+- **Step PyTorch profiler on each training step so `soup train --profile` writes traces (#1448 by @kok-o in #1639).** `soup train --profile` previously announced writing a trace upon completion but left `<output_dir>/profiles/` empty because `torch.profiler.profile` schedule state only advances when `profiler.step()` is invoked per step. Added `ProfileStepCallback` lazily subclassing HuggingFace `TrainerCallback` via PEP 562 to step the profiler on `on_step_end` without importing `transformers` at CLI startup, and wired it into `soup_cli.commands.train` when profiling is enabled.diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.pyindex c86d287c..f2b8186b 100644--- a/src/soup_cli/commands/train.py+++ b/src/soup_cli/commands/train.py@@ -1863,7 +1863,15 @@ def train(raisetry:- with profiler_ctx, energy_ctx:+ with profiler_ctx as profiler, energy_ctx:+ if profile_run and profiler is not None:+ from soup_cli.utils.profiling import attach_profile_callback++ if not attach_profile_callback(trainer_wrapper, profiler):+ console.print(+ "[yellow]--profile:[/] this trainer has no step hook, "+ "so no trace will be written"+ )result = trainer_wrapper.train(display=display, tracker=tracker, run_id=run_id,resume_from_checkpoint=resume_from,diff --git a/src/soup_cli/utils/profiling.py b/src/soup_cli/utils/profiling.pyindex f00f5343..378bc14a 100644--- a/src/soup_cli/utils/profiling.py+++ b/src/soup_cli/utils/profiling.py@@ -12,7 +12,13 @@ import contextlibimport osfrom dataclasses import dataclassfrom pathlib import Path-from typing import Iterator, Optional+from typing import TYPE_CHECKING, Any, Iterator, Optional++if TYPE_CHECKING:+ from transformers import TrainerCallback++ class ProfileStepCallback(TrainerCallback):+ passfrom soup_cli.utils.paths import is_under_cwd@@ -136,3 +142,107 @@ def profile_training(with_stack=False,) as profiler:yield profiler+++def _try_import_callback_base():+ """Return HF ``TrainerCallback`` (or ``object`` when transformers is absent).++ Imported inside the function so the module has no top-level transformers+ dependency; the class below still inherits every no-op event stub the HF+ dispatch loop requires.+ """+ try:+ from transformers import TrainerCallback # noqa: PLC0415++ return TrainerCallback+ except Exception: # noqa: BLE001+ return object+++class _ProfileStepCallback_body: # type: ignore[misc] # noqa: N801+ """HF TrainerCallback that steps the torch profiler on each training step.++ Subclasses the lazily-resolved ``TrainerCallback`` so it inherits the no-op+ default for every Trainer event. Only ``on_step_end`` is overridden.+ """++ def __init__(self, profiler: Optional[object]) -> None:+ self.profiler = profiler+ self._step_warned: bool = False++ def on_step_end(+ self,+ args: Any = None,+ state: Any = None,+ control: Any = None,+ **kwargs: Any,+ ) -> Any:+ if self.profiler is not None and hasattr(self.profiler, "step"):+ try:+ self.profiler.step()+ except Exception as exc:+ # Profiling must never crash a real training run.+ if not getattr(self, "_step_warned", False):+ import logging++ logging.getLogger(__name__).warning(+ "--profile: stepping profiler failed (%s); "+ "trace may be incomplete or empty",+ exc,+ )+ self._step_warned = True+ return control+++def build_profile_callback(profiler: Optional[object]) -> Optional[object]:+ """Return a ProfileStepCallback for ``profiler``, or None if profiler is None."""+ if profiler is None:+ return None+ from soup_cli.utils.profiling import ProfileStepCallback++ return ProfileStepCallback(profiler)+++def attach_profile_callback(trainer_wrapper: Any, profiler: Optional[object]) -> bool:+ """Register a ProfileStepCallback on the wrapper's HF trainer; False if impossible."""+ callback = build_profile_callback(profiler)+ hf_trainer = getattr(trainer_wrapper, "trainer", None)+ if callback is None or not hasattr(hf_trainer, "add_callback"):+ return False+ hf_trainer.add_callback(callback)+ return True+++_LAZY_CALLBACKS = {+ "ProfileStepCallback": _ProfileStepCallback_body,+}+_BODY_SKIP = frozenset(("__dict__", "__weakref__"))+++def __getattr__(name: str): # PEP 562+ body = _LAZY_CALLBACKS.get(name)+ if body is not None:+ base = _try_import_callback_base()+ ns = {k: v for k, v in vars(body).items() if k not in _BODY_SKIP}+ cls = type(name, (base,), ns)+ cls.__module__ = __name__+ cls.__qualname__ = name+ globals()[name] = cls+ return cls+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+++__all__ = [+ "DEFAULT_ACTIVE_STEPS",+ "DEFAULT_REPEAT",+ "DEFAULT_WAIT_STEPS",+ "DEFAULT_WARMUP_STEPS",+ "MAX_ACTIVE_STEPS",+ "ProfileStepCallback",+ "ProfilerSchedule",+ "attach_profile_callback",+ "build_profile_callback",+ "profile_training",+ "resolve_trace_path",+]+diff --git a/tests/test_issue1448_train_profile_trace.py b/tests/test_issue1448_train_profile_trace.pynew file mode 100644index 00000000..4494a098--- /dev/null+++ b/tests/test_issue1448_train_profile_trace.py@@ -0,0 +1,246 @@+"""#1448 - `soup train --profile` says it is writing a trace, and writes none.++The command enters the `profile_training` context around training, but+the profiler was never bound or stepped, and nothing passed it to+`trainer_wrapper.train()`. `torch.profiler`'s schedule advances only on+`step()`, so the trace was never written.++This file pins:+* `ProfileStepCallback` steps the profiler on `on_step_end` and swallows errors;+* `build_profile_callback` builds the callback or returns None when profiler is None;+* `soup train --profile` writes a valid Chrome trace JSON file in `<output>/profiles/`;+* `soup train` without `--profile` creates no `profiles/` directory;+* Mutation check: dropping the profiler callback wiring produces no trace.+"""++from __future__ import annotations++import json+from pathlib import Path+from unittest.mock import MagicMock++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.utils.profiling import (+ ProfileStepCallback,+ build_profile_callback,+)+++def _tiny_llama_dir(root: Path, vocab: int = 64, hidden: int = 64) -> str:+ import torch+ from safetensors.torch import save_file+ from tokenizers import Tokenizer, models, pre_tokenizers+ from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast++ torch.manual_seed(7)+ config = LlamaConfig(+ vocab_size=vocab,+ hidden_size=hidden,+ intermediate_size=hidden * 2,+ num_hidden_layers=2,+ num_attention_heads=4,+ num_key_value_heads=2,+ tie_word_embeddings=True,+ max_position_embeddings=128,+ )+ model = LlamaForCausalLM(config).to(torch.float32).eval()+ weights = root / "model"+ weights.mkdir(parents=True, exist_ok=True)+ state = {k: v.contiguous() for k, v in model.state_dict().items()}+ state.pop("lm_head.weight", None)+ save_file(state, str(weights / "model.safetensors"))+ config.save_pretrained(str(weights))++ raw = Tokenizer(models.WordLevel(vocab={f"t{i}": i for i in range(vocab)}, unk_token="t0"))+ raw.pre_tokenizer = pre_tokenizers.Whitespace()+ tok = PreTrainedTokenizerFast(+ tokenizer_object=raw,+ bos_token="t1",+ eos_token="t2",+ pad_token="t0",+ unk_token="t0",+ )+ tok.save_pretrained(str(weights))+ return str(weights)+++class TestProfileStepCallback:+ def test_callback_steps_profiler(self):+ profiler = MagicMock()+ cb = ProfileStepCallback(profiler)+ control = MagicMock()++ res = cb.on_step_end(args=None, state=None, control=control)++ assert profiler.step.call_count == 1+ assert res is control++ def test_callback_swallows_step_exception(self):+ profiler = MagicMock()+ profiler.step.side_effect = RuntimeError("step failure")+ cb = ProfileStepCallback(profiler)+ control = MagicMock()++ res = cb.on_step_end(args=None, state=None, control=control)++ assert profiler.step.call_count == 1+ assert res is control++ def test_callback_handles_none_or_missing_step(self):+ cb_none = ProfileStepCallback(None)+ res = cb_none.on_step_end(args=None, state=None, control="ctrl")+ assert res == "ctrl"++ cb_obj = ProfileStepCallback(object())+ res2 = cb_obj.on_step_end(args=None, state=None, control="ctrl2")+ assert res2 == "ctrl2"++ def test_build_profile_callback(self):+ assert build_profile_callback(None) is None++ profiler = MagicMock()+ cb = build_profile_callback(profiler)+ assert isinstance(cb, ProfileStepCallback)+ assert cb.profiler is profiler++ def test_attach_registers_on_the_hf_trainer(self):+ from types import SimpleNamespace++ from soup_cli.utils.profiling import attach_profile_callback++ hf_trainer, profiler = MagicMock(), MagicMock()+ assert attach_profile_callback(SimpleNamespace(trainer=hf_trainer), profiler) is True+ (callback,), _ = hf_trainer.add_callback.call_args+ assert isinstance(callback, ProfileStepCallback)+ assert callback.profiler is profiler++ def test_attach_reports_a_wrapper_without_a_trainer(self):+ from types import SimpleNamespace++ from soup_cli.utils.profiling import attach_profile_callback++ assert attach_profile_callback(SimpleNamespace(trainer=None), MagicMock()) is False++ def test_callback_logs_warning_on_step_failure(self, caplog: pytest.LogCaptureFixture):+ import logging++ profiler = MagicMock()+ profiler.step.side_effect = RuntimeError("step failure")+ cb = ProfileStepCallback(profiler)+ control = MagicMock()++ with caplog.at_level(logging.WARNING):+ cb.on_step_end(args=None, state=None, control=control)+ cb.on_step_end(args=None, state=None, control=control)++ assert "stepping profiler failed" in caplog.text+ assert caplog.text.count("stepping profiler failed") == 1+++class TestTrainProfileCLI:+ def _setup_run(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, num_rows: int = 8+ ) -> Path:+ monkeypatch.chdir(tmp_path)+ weights = _tiny_llama_dir(tmp_path)+ rows = [+ {+ "messages": [+ {"role": "user", "content": f"t3 t4 {i}"},+ {"role": "assistant", "content": "t5 t6"},+ ]+ }+ for i in range(num_rows)+ ]+ data_path = tmp_path / "chat.jsonl"+ data_path.write_text(+ "\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8"+ )+ cfg_path = tmp_path / "soup.yaml"+ cfg_path.write_text(+ f"base: {json.dumps(weights)}\n"+ "task: sft\n"+ "data:\n"+ " train: chat.jsonl\n"+ " format: chatml\n"+ " chat_template: chatml\n"+ " max_length: 64\n"+ "training:\n"+ " epochs: 1\n"+ " batch_size: 2\n"+ " gradient_accumulation_steps: 1\n"+ " logging_steps: 1\n"+ " save_steps: 1000\n"+ " quantization: none\n"+ " lora:\n"+ " r: 4\n"+ " alpha: 8\n"+ " target_modules: [q_proj, v_proj]\n"+ "output: ./out\n",+ encoding="utf-8",+ )+ return cfg_path++ def test_train_with_profile_writes_trace(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ):+ cfg_path = self._setup_run(tmp_path, monkeypatch, num_rows=8)+ result = CliRunner().invoke(+ app, ["train", "--config", str(cfg_path), "--profile", "--yes"]+ )+ assert result.exit_code == 0, (result.output, repr(result.exception))++ profiles_dir = tmp_path / "out" / "profiles"+ assert profiles_dir.is_dir(), f"profiles dir not found in {list(tmp_path.glob('*'))}"++ traces = list(profiles_dir.glob("*.trace.json"))+ assert len(traces) == 1, f"expected 1 trace, found {traces}"+ trace_data = json.loads(traces[0].read_text(encoding="utf-8"))+ assert "traceEvents" in trace_data++ def test_train_without_profile_writes_no_trace(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ):+ cfg_path = self._setup_run(tmp_path, monkeypatch, num_rows=4)+ result = CliRunner().invoke(+ app, ["train", "--config", str(cfg_path), "--yes"]+ )+ assert result.exit_code == 0, (result.output, repr(result.exception))++ profiles_dir = tmp_path / "out" / "profiles"+ assert not profiles_dir.exists(), "profiles dir should not exist without --profile"++ def test_mutation_dropping_callback_writes_no_trace(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ):+ cfg_path = self._setup_run(tmp_path, monkeypatch, num_rows=8)+ # Simulate dropping the callback wiring (the bug before this fix)+ import soup_cli.utils.profiling as profiling_mod++ monkeypatch.setattr(profiling_mod, "build_profile_callback", lambda prof: None)++ result = CliRunner().invoke(+ app, ["train", "--config", str(cfg_path), "--profile", "--yes"]+ )+ assert result.exit_code == 0, (result.output, repr(result.exception))++ profiles_dir = tmp_path / "out" / "profiles"+ trace_files = list(profiles_dir.glob("*.trace.json")) if profiles_dir.exists() else []+ assert len(trace_files) == 0, "trace should not be written when callback is dropped"++ def test_train_says_no_trace_when_the_trainer_has_no_hook(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ):+ import re++ import soup_cli.utils.profiling as profiling_mod++ cfg_path = self._setup_run(tmp_path, monkeypatch, num_rows=4)+ monkeypatch.setattr(profiling_mod, "attach_profile_callback", lambda *a: False)+ result = CliRunner().invoke(app, ["train", "--config", str(cfg_path), "--profile", "--yes"])+ assert result.exit_code == 0, (result.output, repr(result.exception))+ plain = " ".join(re.sub(r"\x1b\[[0-9;]*m", "", result.output).split())+ assert "no trace will be written" in plain