-
Notifications
You must be signed in to change notification settings - Fork 5
Register locally defined BaseModels in a module to work with PyObjectPath #169
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
58b4650
Register locally defined CallableModels and Contexts in a module to w…
NeejWeej 7d85243
Try to improve code coverage
NeejWeej 9fb2a92
Only register <locals> not __main__
NeejWeej 32ae219
Add dummy example with CallableModel making callable models
NeejWeej 7504a89
Add tests for pickling and unpickling local callable models and contexts
NeejWeej dea6dae
Utilize finder/loader pattern for dynamic module, add subprocess test…
NeejWeej 9e52ab9
Make dynamic module functions private
NeejWeej ff6acf1
Adjust local module persistence to work with cloudpickle across proce…
NeejWeej b06ea00
Don't create dynamic module, add more tests for locally defined models
NeejWeej f0f3262
Simplify logic, restrict scope to not include create_model, which is …
NeejWeej b3644a1
Add wrapper around create_model from pydantic that also does registra…
NeejWeej 137985d
Register classes with module that is __main__, add a test
NeejWeej 36f6ba2
Utilize parametrization to reduce the subprocess tests
NeejWeej 51534f2
Use register_ccflow_import_path for local persistence
NeejWeej a56d526
Update docstrings
NeejWeej 52578f2
Merge branch 'main' into nk/local_model_context_registration
NeejWeej File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| """Register local-scope classes on a module so PyObjectPath can import them. | ||
|
|
||
| Classes defined in functions (with '<locals>' in __qualname__) aren't normally importable. | ||
| We give them a unique name and register them on this module (ccflow.local_persistence). | ||
| We keep __module__ and __qualname__ unchanged so cloudpickle can still serialize the | ||
| class definition. | ||
|
|
||
| This module provides: | ||
| - register_ccflow_import_path(cls): Register a local class with a unique import path | ||
| - sync_to_module(cls): Ensure a class with __ccflow_import_path__ is on the module | ||
| (used for cross-process unpickle scenarios) | ||
| - create_ccflow_model: Wrapper around pydantic.create_model that registers the created model | ||
| """ | ||
|
|
||
| import re | ||
| import sys | ||
| import uuid | ||
| from typing import Any, Type | ||
|
|
||
| __all__ = ("LOCAL_ARTIFACTS_MODULE_NAME", "create_ccflow_model") | ||
|
|
||
| LOCAL_ARTIFACTS_MODULE_NAME = "ccflow.local_persistence" | ||
|
|
||
|
|
||
| def _register_on_module(cls: Type[Any], module_name: str) -> None: | ||
| """Register cls on the specified module with a unique name. | ||
|
|
||
| This sets __ccflow_import_path__ on the class without modifying __module__ or | ||
| __qualname__, preserving cloudpickle's ability to serialize the class definition. | ||
|
|
||
| Args: | ||
| cls: The class to register. | ||
| module_name: The fully-qualified module name to register on (must be in sys.modules). | ||
| """ | ||
| # Sanitize the class name to be a valid Python identifier | ||
| name = re.sub(r"[^0-9A-Za-z_]", "_", cls.__name__ or "Model").strip("_") or "Model" | ||
| if name[0].isdigit(): | ||
| name = f"_{name}" | ||
| unique = f"_Local_{name}_{uuid.uuid4().hex[:12]}" | ||
|
|
||
| setattr(sys.modules[module_name], unique, cls) | ||
| cls.__ccflow_import_path__ = f"{module_name}.{unique}" | ||
|
|
||
|
|
||
| def register_ccflow_import_path(cls: Type[Any]) -> None: | ||
| """Give cls a unique name and register it on ccflow.local_persistence. | ||
|
|
||
| This sets __ccflow_import_path__ on the class without modifying __module__ or | ||
| __qualname__, preserving cloudpickle's ability to serialize the class definition. | ||
| """ | ||
| _register_on_module(cls, LOCAL_ARTIFACTS_MODULE_NAME) | ||
|
|
||
|
|
||
| def sync_to_module(cls: Type[Any]) -> None: | ||
| """Ensure cls is registered on the artifacts module in this process. | ||
|
|
||
| This handles cross-process unpickle scenarios where cloudpickle recreates the class | ||
| with __ccflow_import_path__ already set (from the original process), but the class | ||
| isn't yet registered on ccflow.local_persistence in the new process. | ||
| """ | ||
| path = getattr(cls, "__ccflow_import_path__", "") | ||
| if path.startswith(LOCAL_ARTIFACTS_MODULE_NAME + "."): | ||
| name = path.rsplit(".", 1)[-1] | ||
| base = sys.modules[LOCAL_ARTIFACTS_MODULE_NAME] | ||
| if getattr(base, name, None) is not cls: | ||
| setattr(base, name, cls) | ||
|
|
||
|
|
||
| def create_ccflow_model(__model_name: str, *, __base__: Any = None, **field_definitions: Any) -> Type[Any]: | ||
| """Create a dynamic ccflow model and register it for PyObjectPath serialization. | ||
|
|
||
| Wraps pydantic's create_model and registers the model so it can be serialized | ||
| via PyObjectPath, including across processes (e.g., with Ray). | ||
|
|
||
| Example: | ||
| >>> from ccflow import ContextBase, create_ccflow_model | ||
| >>> MyContext = create_ccflow_model( | ||
| ... "MyContext", | ||
| ... __base__=ContextBase, | ||
| ... name=(str, ...), | ||
| ... value=(int, 0), | ||
| ... ) | ||
| >>> ctx = MyContext(name="test", value=42) | ||
| """ | ||
| from pydantic import create_model as pydantic_create_model | ||
|
|
||
| model = pydantic_create_model(__model_name, __base__=__base__, **field_definitions) | ||
|
|
||
| # Register if it's a ccflow BaseModel subclass | ||
| from ccflow.base import BaseModel | ||
|
|
||
| if isinstance(model, type) and issubclass(model, BaseModel): | ||
| register_ccflow_import_path(model) | ||
|
|
||
| return model |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.