Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem Description
This PR addresses two related issues with Unsloth's module importing mechanism:
Slow/hanging imports when called from entry points: When importing Unsloth via Python entry points (defined in pyproject.toml), import times can exceed 60 seconds or even hang indefinitely (Slow Import Times (60+ seconds) When Using Unsloth via Entry Points unsloth#1859) due to an improper retry mechanism. This occurs because the module import system fails differently depending on how Python is invoked.
Inconsistent cache locations: Previously, the
UNSLOTH_COMPILE_LOCATION
was set as a relative path ("unsloth_compiled_cache"
), which would create different cache directories depending on the working directory where a script was launched.Root Cause Analysis
The core issue was in the
create_new_function
method's module loading mechanism:It tried to import modules using
importlib.import_module(UNSLOTH_COMPILE_LOCATION + "." + name)
, but this fails when the directory is not insys.path
(common when running through entry points).The fallback mechanism used a
while True
loop that could potentially run indefinitely, with each iteration adding another sleep delay (Slow Import Times (60+ seconds) When Using Unsloth via Entry Points unsloth#1859 (comment)).Solution
Standardized cache location using
appdirs.user_data_dir()
for consistency across sessions.Fixed module importing by temporarily adding the cache directory to
sys.path
.Eliminated the infinite loop in the fallback mechanism with proper exception handling.
Added clearer error messages to simplify troubleshooting.
Testing
Tested the changes with both direct module invocation (
python -m
) and through entry points, confirming: