Skip to content

Fix dill pickling whole modules by value on an off-prefix install - #9791

Merged
danielhanchen merged 14 commits into
mainfrom
fix/dill-module-by-value-pickling
Aug 27, 2026
Merged

danielhanchen merged 14 commits into
mainfrom
fix/dill-module-by-value-pickling

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The bug

datasets fingerprints every Dataset through dill, and dill decides whether to pickle a module by reference or by value with dill._dill._is_builtin_module, which answers yes only if the module's __file__:

  • starts with a sys prefix, or
  • ends with an extension suffix, or
  • contains the literal string site-packages.

An install that satisfies none of the three gets every one of its packages pickled by value. That includes pip install --target <dir>, a PYTHONPATH overlay, a Lambda-style layer and a vendored tree.

On such an install this is enough to crash:

from datasets import Dataset
Dataset.from_dict({"text": ["a", "b"]})
File "datasets/utils/_dill.py", line 164, in _save_arrowTable
    pickler.save_reduce(create_arrowTable, args, obj=obj)
...
File "dill/_dill.py", line 1745, in save_module
    pickler.save_reduce(_import_module, (mod_name,), obj=obj, state=main_dict)
...
_pickle.PicklingError: Can't pickle <class 'MonthDayNano'>: it's not found as builtins.MonthDayNano

create_arrowTable is nested inside _save_arrowTable, so dill cannot locate it by qualname and saves it by value, walks its globals with recurse=True, reaches the pyarrow module, pickles that by value too, and dies on pyarrow's Cython MonthDayNano, whose __module__ is builtins where it is not found.

Nothing in the traceback names the install layout, and every training path in unsloth builds a dataset, so this is the first thing such a user sees.

The fix

Widen dill's predicate to also accept modules that are importable by name right now. That is precisely when pickling by reference is valid, and it is what an ordinary site-packages install already does for these same modules.

It is deliberately narrow:

  • Gated. Unless datasets or pyarrow actually resolve to somewhere dill would pickle by value, nothing is patched at all. An ordinary install keeps dill's behaviour byte for byte, fingerprints included.
  • The gate's copy of dill's rule is only a gate: dill's real predicate is consulted before anything is patched, so a stale copy can cost one import and never a wrong patch.
  • The widening covers only modules that are the live sys.modules entry under their own name with a file-backed spec. __main__ and __mp_main__ are excluded outright, because python -m pkg gives __main__ a real __spec__ and dill's by-value contract for the user's own code has to stand.
  • dill.session binds the name at import time, so both bindings are updated. Patching only the defining module leaves session pickling on the old predicate.
  • UNSLOTH_DISABLE_DILL_FIX=1 turns it off.

Measured

Real package trees, with the directory name as the only variable.

tree datasets dill from_dict map
--target dir, fix off 5.0.1 0.4.1 PicklingError not reached
same tree, fix on 5.0.1 0.4.1 ok ok
same tree, fix on 5.0.1 0.3.8 ok ok
same tree, either way 4.3.0 0.4.1 ok, identical fingerprints ok, identical
ordinary site-packages 4.3.0 0.3.8 gate False, untouched untouched

datasets 4.3.0 does not reach that reducer and is unaffected either way, and its fingerprints are identical with and without the patch, so nothing invalidates a cache where the old path already worked. dill 0.3.8 and 0.4.1 carry the same _is_builtin_module, and the fix was verified on both.

Tests

Eight, in tests/test_dill_module_by_value_fix.py. The tree is written to disk and run in a subprocess against a throwaway venv, so the overlay is genuinely off-prefix wherever the suite runs rather than wherever tmp happens to live. That detail is not cosmetic: on a box whose virtualenv root is an ancestor of tmp, the tree sits under sys.prefix, dill is perfectly happy with it, and every subprocess test passes while reproducing nothing.

The first test is the negative control, asserting the unpatched crash still reproduces, so if dill changes its own rule this file says so rather than quietly guarding nothing.

Five mutations reintroduced, five caught. One only failed after a vacuous __main__ assertion in my own test was replaced: under pytest, sys.modules["__main__"] is a console script whose __spec__ is None, so it was already refused by an earlier clause and the exclusion was never exercised.

`datasets` fingerprints every Dataset through dill, and dill decides whether to
pickle a module by reference or by value with `_is_builtin_module`, which
answers yes only if the module's `__file__` starts with a sys prefix, ends with
an extension suffix, or contains the literal string `site-packages`.

An install that satisfies none of the three, such as `pip install --target
<dir>`, a PYTHONPATH overlay or a Lambda-style layer, therefore gets every one
of its packages pickled by value. `Dataset.from_dict({"text": ["a", "b"]})`
then walks `datasets/utils/_dill.py:_save_arrowTable` into the nested
`create_arrowTable`, whose globals reach the pyarrow module, and dies on
pyarrow's Cython `MonthDayNano`, whose `__module__` is `builtins`:

    PicklingError: Can't pickle <class 'MonthDayNano'>:
        it's not found as builtins.MonthDayNano

Nothing in the traceback names the install layout, and every training path
here builds a dataset, so this is the first thing such a user sees.

The fix widens dill's predicate to also accept modules that are importable by
name right now, which is precisely when pickling by reference is valid, and is
what an ordinary site-packages install already does for these modules.

Narrow on purpose:

- It is gated. Unless `datasets` or `pyarrow` actually resolve to somewhere
  dill would pickle by value, nothing is patched and dill's behaviour,
  fingerprints included, is unchanged byte for byte. Measured on an ordinary
  install: gate False, patch not installed.
- The gate's copy of dill's rule is only a gate. dill's real predicate is
  consulted before anything is patched, so a stale copy can cost one import
  and never a wrong patch.
- The widening covers only modules that are the live `sys.modules` entry under
  their own name with a file-backed spec. `__main__` and `__mp_main__` are
  excluded outright, because `python -m pkg` gives `__main__` a real `__spec__`
  and dill's by-value contract for the user's own code has to stand.
- `dill.session` binds the name at import time, so both bindings are updated.
- `UNSLOTH_DISABLE_DILL_FIX=1` turns it off.

Measured against real package trees, with the directory name as the only
variable:

| tree | datasets | dill | from_dict | map |
|---|---|---|---|---|
| `--target` dir, fix off | 5.0.1 | 0.4.1 | PicklingError | not reached |
| same tree, fix on | 5.0.1 | 0.4.1 | ok | ok |
| same tree, fix on | 5.0.1 | 0.3.8 | ok | ok |
| same tree, either way | 4.3.0 | 0.4.1 | ok, identical fingerprints | ok, identical |
| ordinary site-packages | 4.3.0 | 0.3.8 | gate False, untouched | untouched |

datasets 4.3.0 does not reach that reducer and is unaffected either way, and
its fingerprints are identical with and without the patch, so no cache is
invalidated where the old path already worked.

Eight tests. The tree is written to disk and run in a subprocess against a
throwaway venv, so the overlay is genuinely off-prefix wherever the suite runs
rather than wherever tmp happens to live. The first test is the negative
control: it asserts the unpatched crash still reproduces, so if dill changes
its rule this file says so instead of quietly guarding nothing. Five mutations
were reintroduced and all five were caught, including one that only failed
after a vacuous `__main__` assertion in my own test was replaced with a
synthesised module carrying a real spec.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Aug 26, 2026
…ill can read it

The Default leg passed 3 of 3 in one arm of a same-commit A/B and failed 3 of 3
in the other, on `PicklingError: Can't pickle <class 'MonthDayNano'>`. Two
defects, and the first one produces the second.

**The venv interpreter was never pinned.** uv's default python-preference is
`managed`, so once any managed CPython exists under ~/.local/share/uv/python a
bare `uv venv` builds on that instead of the image's. `--system-site-packages`
is still honoured and still inherits nothing, because a 3.13 venv cannot see a
3.12 site-packages. Measured, deterministic per arm:

| arm | Default leg python | torch | datasets | verdict |
|---|---|---|---|---|
| A, 3 runs | 3.12.13 | 2.10.0+cu128 | 4.3.0 | pass 3/3 |
| B, 3 runs | 3.13.13 | 2.12.1+cu130 | 5.0.1 | fail 3/3 |

Every other leg in both arms stayed on 3.12.13. The overlay resolve on the 3.13
runs found nothing satisfied and pulled 44 packages, including pyarrow,
datasets and dill, where arm A resolved 3. So the leg was also testing a stack
no Kaggle user has, and paying minutes for it, with nothing red.

**The overlay directory was hostile to dill**, which is what turned the wrong
interpreter into a crash. dill pickles a module by reference only if its
`__file__` starts with a sys prefix, ends with an extension suffix, or contains
the literal string `site-packages`. `pip install --target
/tmp/t4ci_venvs/overlay_X` satisfies none of the three, so everything in the
overlay is pickled by value; `Dataset.from_dict` fingerprints through dill,
reaches the pyarrow module, and dies on pyarrow's Cython `MonthDayNano`.

Reproduced on CPU in seconds against a byte-identical package tree with the
directory name as the only variable: the plain `--target` directory raised, the
copy named site-packages returned a fingerprint.

Both fixed here: `--python sys.executable` on the venv, the resulting version
reported in the `_VENV` record so the next wrong interpreter is visible rather
than inferred, and the overlay installed into a `site-packages` directory.

The upstream half is unslothai#9791, which makes the same crash
survivable for any user on a `--target` or PYTHONPATH install. This change is
not conditional on that one.

Seven guards, four mutations reintroduced and caught. The dill rule is asserted
by evaluating the driver's own `_ov_dir` expression and feeding the result to
dill's real `_is_builtin_module`, with a negative control on the old path so
the rule fails if dill ever changes its mind.
…ule reject a conditional

Both from review, and both were real.

**A project module's state was dropping out of the fingerprint.** The predicate
widened to every live file-backed module, so on an affected install a user's own
project module was pickled by reference too. Those modules normally sit outside
site-packages, where dill pickles them BY VALUE and their mutable state
participates in a `recurse=True` fingerprint, so the patch would have made
`config.VALUE = 2` stop changing the fingerprint while `datasets` served a stale
cached result.

Measured on a real off-prefix tree, with a transform reading `myproj.VALUE`:

    un-narrowed:  project module by reference,  fingerprint 5d7c0f62 -> 5d7c0f62
    narrowed:     project module by value,      fingerprint 16f369d8 -> 23234ad9

The widening now applies only inside the install ROOTS that made the
environment dill-hostile, derived from where `datasets` and `pyarrow` actually
resolved. Only the misplaced libraries move back to the behaviour they would
have in an ordinary install; everything else keeps dill's.

**The placement rule passed on the placement it exists to reject.** It walked
every descendant of each module-body node, so moving the import inside
`if _IS_MLX:` still satisfied it, leaving the GPU path unpatched. It now
inspects unconditional top-level statements plus a top-level `try` body, which
is how every other fix in `__init__` is guarded, and carries a negative control
asserting a one-sided conditional is refused.

That control shares the real walker rather than carrying its own copy: a
control with a private copy passes when the thing it guards regresses.

Four hostile trees re-verified after the narrowing (datasets 5.0.1 and 4.3.0,
dill 0.4.1 and 0.3.8) with fingerprints unchanged from before it, and the
ordinary install still gates out with the patch never installed. Nine tests;
both reviewed defects reintroduced as mutations and both caught.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed the gate in unsloth/import_fixes.py only fires when datasets or pyarrow resolve outside a prefix or site-packages, and the narrowing to the offending install roots in d7c1ada keeps fingerprints unchanged elsewhere. Will get this reviewed.

Root containment alone treats the whole install directory as dependency-owned.
pip install --target . and a Lambda deployment bundle put dependencies into the
application's own directory, so the root is shared with the user's project, and
a module such as myproj.config moved to by-reference along with the libraries.
Its mutable state would then leave the recurse=True fingerprint, and datasets
would serve a stale cached result after config.VALUE changed, silently, which
is worse than the crash this patch exists to prevent.

Read the top-level names that dist-info and egg-info directories under the root
claim, from top_level.txt where pip wrote one and from RECORD otherwise, and
require membership in addition to containment. A root carrying no installed
metadata at all cannot tell a dependency from the user's own file, so the patch
declines rather than guess.

The hostile tree now carries the metadata pip would have written, plus the
user's own module beside it, and asks dill's live predicate which side each
landed on.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

A top-level name cannot answer the question under a shared namespace: metadata
for an installed google or opentelemetry distribution claimed the first
component of a co-located google.myconfig that nothing installed, so its
mutable state left the recurse=True fingerprint and datasets could serve a
stale cached result. It also forced a guess about leading underscores that
discarded _soundfile and _multiprocess along with __pycache__. Ownership now
comes from the paths RECORD and installed-files.txt actually list, with
top_level.txt as the fallback for a distribution that recorded no file list at
all, and the paths are absolute so several roots can be collected without one
vouching for another.

The install root is derived from any __init__ suffix rather than __init__.py
alone. A deployment shipping bytecode only gives pyarrow/__init__.pyc, which
left the root a level too deep, no sibling metadata was found, and the fix
declined on exactly the stripped layers it was written for.

The affected-environment gate searched the RESOLVED path for site-packages.
dill reads 'site-packages' in module.__file__, the literal one, and resolves
only for the sys-prefix comparisons, so a PYTHONPATH entry symlinked into a
directory whose name contains site-packages was reported unaffected while dill
went on pickling it by value. Since that gate decides whether dill's own
predicate is ever consulted, the crash simply stood.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits August 27, 2026 11:09
A distribution whose only metadata is top_level.txt cannot say which of a
directory's contents it installed, so adding the directory put a co-located
google/myconfig.py on the dependency side of an installed google distribution:
the same hole a top-level name leaves anywhere else, arriving through the
fallback instead. Its mutable state would then leave the recurse=True
fingerprint and datasets could serve a stale cached result.

The fallback is now honoured only where the name really is one file on disk,
which is unambiguous. A package name claims nothing, so the worst outcome for
those installs is the original loud PicklingError rather than a silently
pinned fingerprint. Directory ownership is gone entirely, and with it the
containment helper it needed.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

os.path.realpath("/opt/layer/python") is D:\\opt\\layer\\python on Windows, so
comparing it against a POSIX literal took the cross-platform lane red while
the code under test was correct on every platform. The paths are derived from
tmp_path now, and the expected value from os.path.realpath, so the assertion
still checks the dirname stripping rather than restating it.

Found by the windows-latest leg of the staging cross-platform run; ubuntu and
macos-14 were green.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 27, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 79d9c6a512

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/import_fixes.py Outdated
if not origin or not files:
return False
try:
return os.path.realpath(origin) in files

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep parents with unowned child modules by value

When a recorded regular package such as pkg/__init__.py contains a co-located, unrecorded application module such as pkg/myconfig.py, a transform using import pkg.myconfig has only pkg in its globals. This test marks that recorded parent package by reference, so dill never encounters the child module whose own predicate would correctly return false; changing pkg.myconfig.VALUE then produces an identical recurse=True pickle and can reuse stale dataset output. Fresh evidence beyond the earlier shared-namespace finding is that the new file-level ownership check protects an unowned child only when dill reaches it directly; keep a parent by value when it exposes loaded, unowned child modules, or otherwise include those children in the fingerprint.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one, and the measurement is the reason.

The idiomatic shared-namespace case is already safe, and not by accident. A namespace package has origin = None (checked empirically against importlib.util.find_spec, not inferred from the docs), so _dill_module_is_importable_by_name returns False for it before ownership is ever consulted, and a project module under a shared namespace stays by value. That is test_a_project_module_under_a_shared_namespace_stays_by_value.

What is left is narrower than the item describes: a user's own module placed inside an installed distribution's REGULAR package directory, in an off-prefix root. That module is by-value today and stays by-value under this patch, because ownership is per file and its file is not in any RECORD. The parent package being by-reference is the same answer a normal site-packages install gives, where dill returns True for the whole tree.

The proposed remedy also has a cost I am not willing to pay here: it needs a sys.modules scan inside a predicate dill calls during fingerprinting, on every module it considers, so the answer would depend on what happened to be imported at that moment. That is a worse property than the one it fixes.

Comment thread unsloth/import_fixes.py Outdated
if not origin or not files:
return False
try:
return os.path.realpath(origin) in files

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Do not classify packaged application wheels as dependencies

When an application is itself installed as a wheel into the off-prefix bundle, its myapp-*.dist-info/RECORD legitimately lists project files such as myapp/config.py. This exact ownership test consequently serializes those application modules by reference, so mutable state read by a dataset transform no longer participates in its recurse=True fingerprint and stale cached output can be reused. Fresh evidence beyond the earlier co-located-project finding is that the new metadata criterion distinguishes only recorded from unrecorded files, not dependency distributions from the packaged application distribution; avoid widening modules merely because the application's own installation metadata records them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one either, for the same kind of reason.

I checked what dill does with a wheel-installed application in an ordinary environment rather than reasoning about it. _is_builtin_module returns True for /venv/lib/python3.12/site-packages/myapp/config.py, purely because site-packages is in the path, and False for /bundle/myapp/config.py. So a pip install-ed application is ALREADY pickled by reference everywhere, and treating one in an off-prefix bundle the same way is parity with a normal install rather than a regression. The behaviour this item is protecting is the one an off-prefix root diverges from.

There is also no marker that separates "the app's own dist-info" from a dependency's. Both are pip install --target output with a RECORD; anything I could key off would be a heuristic on the project name, which is exactly the kind of rule that goes wrong quietly on the first user whose layout differs.

If someone genuinely wants their application by value in a bundle, the existing escape hatch is dill.settings["byref"] / an explicit register on their side, which is unchanged by this patch.

danielhanchen and others added 2 commits August 27, 2026 11:38
…prefix root

A deployment that compiles to adjacent bytecode and drops the sources leaves
the wheel RECORD naming pkg/__init__.py while the live spec points at
pkg/__init__.pyc, so an exact match left the installed package by value and the
original PicklingError stood on exactly the stripped layers this is for. A .pyc
or .pyo now answers to the .py its own metadata recorded, and to nothing else.

Roots came only from wherever datasets or pyarrow happened to live. A
deployment can spread its layers, and a transform reaching a dependency in a
second one hit the same failure. Every sys.path entry that is off-prefix by
dill's own rule and carries installed metadata is searched now. The ownership
rule is unchanged, so a wider search admits more dependencies and nothing else,
and the off-prefix test is what keeps site-packages out of the scan.

The hostile tree grows a second layer holding one recorded dependency and one
unrecorded project module, and the driver reports which side each landed on.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 27, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: ab4cf6e6b1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Same rules, fewer lines. The one substantive edit is the block above the roots
search, which had two stacked paragraphs from separate rounds saying
overlapping things about why a root with no metadata contributes nothing; it is
one paragraph now, with the read-once note at the end where it belongs.

No code, and the AST gate says so.
@danielhanchen
danielhanchen merged commit fdce180 into main Aug 27, 2026
5 of 39 checks passed
@danielhanchen
danielhanchen deleted the fix/dill-module-by-value-pickling branch August 27, 2026 12:08
danielhanchen added a commit that referenced this pull request Aug 27, 2026
pre-commit.ci has been failing on main since #9842 and #9791, which landed
asserts written in the parenthesize-the-message style that a newer ruff
produces. The kwarg-spacing hook pins ruff==0.6.9, which writes the message
unparenthesized and the condition parenthesized instead, so it rewrote both
files on every run and the job reported 'files were modified by this hook'.

Formatting only: the AST of each file is unchanged and both still pass.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant