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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
TP / FSDP2 saves: pass results between ranks as JSON, not pickle (#15510)
Daniel Hanc5b13a0d6eac
diff --git a/scripts/risky_loaders_baseline.json b/scripts/risky_loaders_baseline.jsonindex dafd344f0fe..0eeba1c7a2a 100644--- a/scripts/risky_loaders_baseline.json+++ b/scripts/risky_loaders_baseline.json@@ -674,14 +674,6 @@"count": 1,"reason": "Standalone import fallback loads only unsloth/kernels/fp8_lora.py beside this shipped module, from __file__; no model metadata or caller input selects the module name or path."},- {- "file": "unsloth/models/fsdp2_save.py",- "rule": "unsafe-deserialize",- "sink": "pickle.loads",- "digest": "bf2d3c412d57fd50",- "count": 1,- "reason": "_share_from_writer: unpickles only what the export's writer rank stored under an unsloth_fsdp2_export_* key in the job's own default c10d store; a party able to write that store already controls the job's collectives."- },{"file": "unsloth/models/loader.py","rule": "dynamic-import",@@ -746,14 +738,6 @@"count": 1,"reason": "Reached only after the trust_remote_code gate in _resolve_module_class raises for an untrusted non sentence_transformers class."},- {- "file": "unsloth/models/tp_replica.py",- "rule": "unsafe-deserialize",- "sink": "pickle.loads",- "digest": "bf2d3c412d57fd50",- "count": 1,- "reason": "Reads the result rank 0 published to this job's own torch.distributed c10d store (the same trust boundary as broadcast_object_list); no file or network payload from outside the process group."- },{"file": "unsloth/save.py","rule": "trust-remote-code",diff --git a/tests/test_distributed_store_codec.py b/tests/test_distributed_store_codec.pynew file mode 100644index 00000000000..a510a375615--- /dev/null+++ b/tests/test_distributed_store_codec.py@@ -0,0 +1,152 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Store payloads are JSON, never pickle: the TCPStore is unauthenticated."""++from __future__ import annotations++import ast+import importlib.util+import os+import pathlib+import pickle+import sys+import types++import pytest++REPO = pathlib.Path(__file__).resolve().parents[1]+MODELS = REPO / "unsloth" / "models"++codec = None # absent before the codec existed: the store tests below still run the old functions+if (MODELS / "_store_codec.py").is_file():+ _spec = importlib.util.spec_from_file_location("_store_codec", MODELS / "_store_codec.py")+ codec = importlib.util.module_from_spec(_spec)+ _spec.loader.exec_module(codec)+++ "value",+ [+ ("ok", None),+ ("ok", ("a/tokenizer_config.json", "a/vocab.json")),+ ("error", "OSError: disk full"),+ ("ok", ["x.gguf"]),+ ("ok", {"path": "out", "n": 3, "f": [1.5, True]}),+ None,+ ],+)+def test_plain_results_round_trip(value):+ assert codec.decode(codec.encode(value)) == value+++def test_a_path_arrives_as_its_string():+ assert codec.decode(codec.encode(("ok", pathlib.Path("/tmp/x")))) == ("ok", os.fspath("/tmp/x"))+++def test_an_object_that_is_not_plain_data_arrives_as_none():+ class CommitInfo:+ pass++ assert codec.decode(codec.encode(("ok", CommitInfo()))) == ("ok", None)+++class _Planted:+ ran = False++ def __reduce__(self):+ return (setattr, (_Planted, "ran", True))+++def test_planted_pickle_bytes_are_refused_without_running():+ with pytest.raises(ValueError):+ codec.decode(pickle.dumps(_Planted()))+ assert _Planted.ran is False+++class _Store:+ """The c10d store calls the save paths make: set / get / wait."""++ def __init__(self):+ self.data = {}++ def set(self, key, value):+ self.data[key] = bytes(value)++ def get(self, key):+ return self.data[key]++ def wait(+ self,+ keys,+ timeout = None,+ ):+ assert all(k in self.data for k in keys), keys+++def _store_functions(module, monkeypatch, store):+ """The real store functions of `module`, run against `store` without importing unsloth."""+ names = {"_publish", "_wait", "_share_from_writer"}+ tree = ast.parse((MODELS / module).read_text(encoding = "utf-8"))+ nodes = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in names]+ package = types.ModuleType("_store_codec_test_pkg")+ package._store_codec = codec+ monkeypatch.setitem(sys.modules, "_store_codec_test_pkg", package)+ dist = types.SimpleNamespace(+ distributed_c10d = types.SimpleNamespace(_get_default_store = lambda: store),+ barrier = lambda: None,+ )+ namespace = {+ "__package__": "_store_codec_test_pkg",+ "_store_codec": codec,+ "pickle": pickle,+ "_dist": lambda: dist,+ "_store": lambda: store,+ "_timeout": lambda: None,+ "_save_timeout": lambda: None,+ "_EXPORT_COUNTER": {},+ }+ exec(compile(ast.Module(body = nodes, type_ignores = []), str(MODELS / module), "exec"), namespace)+ return namespace, dist+++def test_tp_rank_waiting_on_planted_pickle_bytes_does_not_run_them(monkeypatch):+ store = _Store()+ tp, _ = _store_functions("tp_replica.py", monkeypatch, store)+ store.set("unsloth_tp_save_1", pickle.dumps(("ok", _Planted())))+ result = tp["_wait"]("unsloth_tp_save_1")+ assert _Planted.ran is False+ assert result[0] == "error", result+++def test_fsdp2_rank_waiting_on_planted_pickle_bytes_does_not_run_them(monkeypatch):+ store = _Store()+ fsdp2, dist = _store_functions("fsdp2_save.py", monkeypatch, store)+ store.set("unsloth_fsdp2_export_r0_result_1", pickle.dumps(("ok", _Planted())))+ result = fsdp2["_share_from_writer"](dist, False, 0, "result")+ assert _Planted.ran is False+ assert result is None or result[0] == "error", result+++ "payload, expected",+ [+ (("ok", None), ("ok", None)),+ (("ok", ("out/tokenizer_config.json", "out/tokenizer.json")), None),+ (("ok", {"gguf_files": ["out/m.Q8_0.gguf"], "is_vlm": False}), None),+ (("error", "OSError: disk full"), None),+ (("ok", object()), ("ok", None)),+ ],+ ids = ["none", "tokenizer_files", "gguf_dict", "error", "not_plain_data"],+)+def test_waiting_ranks_get_what_rank0_returned(monkeypatch, payload, expected):+ """What every caller passes today arrives unchanged; a value that is not plain data arrives as None, as before."""+ store = _Store()+ tp, _ = _store_functions("tp_replica.py", monkeypatch, store)+ tp["_publish"]("unsloth_tp_save_1", payload)+ assert tuple(tp["_wait"]("unsloth_tp_save_1"))[:2] == (expected or payload)+ fsdp2, dist = _store_functions("fsdp2_save.py", monkeypatch, store)+ fsdp2["_share_from_writer"](dist, True, 0, "result", payload)+ fsdp2["_EXPORT_COUNTER"].clear()+ got = fsdp2["_share_from_writer"](dist, False, 0, "result")+ assert got == (expected or payload) or (payload[1].__class__ is object and got == ("ok", None))diff --git a/unsloth/models/_store_codec.py b/unsloth/models/_store_codec.pynew file mode 100644index 00000000000..9832b73348f--- /dev/null+++ b/unsloth/models/_store_codec.py@@ -0,0 +1,43 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Cross-rank values via the c10d store: JSON, never pickle (TCPStore is unauthenticated).+Non-plain values arrive as None."""++import json+import os+++def _plain(value):+ if value is None or isinstance(value, (bool, int, float, str)):+ return value+ if isinstance(value, os.PathLike):+ return os.fspath(value)+ if isinstance(value, (list, tuple)):+ items = [_plain(v) for v in value]+ return {"t": items} if isinstance(value, tuple) else items+ if isinstance(value, dict) and all(isinstance(k, str) for k in value):+ return {"d": {k: _plain(v) for k, v in value.items()}}+ return None+++def _unplain(value):+ if isinstance(value, list):+ return [_unplain(v) for v in value]+ if isinstance(value, dict):+ if isinstance(value.get("t"), list):+ return tuple(_unplain(v) for v in value["t"])+ inner = value.get("d")+ return {k: _unplain(v) for k, v in inner.items()} if isinstance(inner, dict) else None+ return value+++def encode(value) -> bytes:+ return json.dumps(_plain(value)).encode("utf-8")+++def decode(data):+ try:+ return _unplain(json.loads(bytes(data).decode("utf-8")))+ except UnicodeDecodeError as exc:+ raise ValueError(str(exc)) from Nonediff --git a/unsloth/models/fsdp2_save.py b/unsloth/models/fsdp2_save.pyindex 7d233687c34..ef4aab0cf76 100644--- a/unsloth/models/fsdp2_save.py+++ b/unsloth/models/fsdp2_save.py@@ -736,7 +736,7 @@ def _share_from_writer():"""The writer's `payload` on every rank, passed through the default store (not a collective,so a rank may wait for it as long as an export takes). Without a store, None off the writer."""- import pickle+ from . import _store_codectry:store = dist.distributed_c10d._get_default_store()@@ -748,14 +748,17 @@ def _share_from_writer(counter[tag] = counter.get(tag, 0) + 1key = f"unsloth_fsdp2_export_r{writer_rank}_{tag}_{counter[tag]}"if writer:- try:- data = pickle.dumps(payload)- except Exception:- data = pickle.dumps(None)- store.set(key, data)+ store.set(key, _store_codec.encode(payload))return payloadstore.wait([key], _save_timeout())- return pickle.loads(store.get(key))+ try:+ return _store_codec.decode(store.get(key))+ except ValueError:+ return (+ ("error", "the writer left an unreadable result in the store")+ if tag == "result"+ else None+ )@contextlib.contextmanagerdiff --git a/unsloth/models/tp_replica.py b/unsloth/models/tp_replica.pyindex f4c97d9230b..172c2317325 100644--- a/unsloth/models/tp_replica.py+++ b/unsloth/models/tp_replica.py@@ -9,12 +9,12 @@ from __future__ import annotationsimport datetimeimport gcimport os-import pickleimport typesimport torchimport torch.nn as nn+from . import _store_codecfrom . import tp_native as tpn__all__ = [@@ -543,11 +543,7 @@ def _publish(key, payload):if store is None:_dist().barrier()return- try:- data = pickle.dumps(payload)- except Exception:- data = pickle.dumps((payload[0], None) + tuple(payload[2:]))- store.set(key, data)+ store.set(key, _store_codec.encode(tuple(payload)))def _wait(key):@@ -556,7 +552,13 @@ def _wait(key):_dist().barrier()return ("ok", None)store.wait([key], _timeout())- return pickle.loads(store.get(key))+ try:+ payload = _store_codec.decode(store.get(key))+ except ValueError:+ payload = None+ if not isinstance(payload, tuple) or len(payload) < 2 or payload[0] not in ("ok", "error"):+ return ("error", "rank 0 left an unreadable result in the store")+ return payloaddef _keep_tree(root):