code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def __mul__(self, other: SupportsIndex) -> "_lstr": """ Perform a multiplication operation between this lstr instance and an integer or another lstr, tracing the operation by logging the operands and the result. Args: other (Union[SupportsIndex, "lstr"]): The right operand i...
Perform a multiplication operation between this lstr instance and an integer or another lstr, tracing the operation by logging the operands and the result. Args: other (Union[SupportsIndex, "lstr"]): The right operand in the multiplication operation. Returns: l...
__mul__
python
MadcowD/ell
src/ell/types/_lstr.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/_lstr.py
MIT
def __getitem__(self, key: Union[SupportsIndex, slice]) -> "_lstr": """ Get a slice or index of this lstr instance. Args: key (Union[SupportsIndex, slice]): The index or slice to retrieve. Returns: lstr: A new lstr instance containing the sliced or indexed conte...
Get a slice or index of this lstr instance. Args: key (Union[SupportsIndex, slice]): The index or slice to retrieve. Returns: lstr: A new lstr instance containing the sliced or indexed content, with theorigin_trace(s) preserved.
__getitem__
python
MadcowD/ell
src/ell/types/_lstr.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/_lstr.py
MIT
def __getattribute__(self, name: str) -> Union[Callable, Any]: """ Get an attribute from this lstr instance. Args: name (str): The name of the attribute to retrieve. Returns: Union[Callable, Any]: The requested attribute, which may be a method or a value. ...
Get an attribute from this lstr instance. Args: name (str): The name of the attribute to retrieve. Returns: Union[Callable, Any]: The requested attribute, which may be a method or a value.
__getattribute__
python
MadcowD/ell
src/ell/types/_lstr.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/_lstr.py
MIT
def join(self, iterable: Iterable[Union[str, "_lstr"]]) -> "_lstr": """ Join a sequence of strings or lstr instances into a single lstr instance. Args: iterable (Iterable[Union[str, "lstr"]]): The sequence of strings or lstr instances to join. Returns: lstr: A n...
Join a sequence of strings or lstr instances into a single lstr instance. Args: iterable (Iterable[Union[str, "lstr"]]): The sequence of strings or lstr instances to join. Returns: lstr: A new lstr instance containing the joined content, with theorigin_trace(s) updated...
join
python
MadcowD/ell
src/ell/types/_lstr.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/_lstr.py
MIT
def split( self, sep: Optional[Union[str, "_lstr"]] = None, maxsplit: SupportsIndex = -1 ) -> List["_lstr"]: """ Split this lstr instance into a list of lstr instances based on a separator. Args: sep (Optional[Union[str, "lstr"]], optional): The separator to split on. De...
Split this lstr instance into a list of lstr instances based on a separator. Args: sep (Optional[Union[str, "lstr"]], optional): The separator to split on. Defaults to None. maxsplit (SupportsIndex, optional): The maximum number of splits to perform. Defaults to -1. Re...
split
python
MadcowD/ell
src/ell/types/_lstr.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/_lstr.py
MIT
def rsplit( self, sep: Optional[Union[str, "_lstr"]] = None, maxsplit: SupportsIndex = -1 ) -> List["_lstr"]: """ Split this lstr instance into a list of lstr instances based on a separator, starting from the right. Args: sep (Optional[Union[str, "lstr"]], optional): The...
Split this lstr instance into a list of lstr instances based on a separator, starting from the right. Args: sep (Optional[Union[str, "lstr"]], optional): The separator to split on. Defaults to None. maxsplit (SupportsIndex, optional): The maximum number of splits to perform. De...
rsplit
python
MadcowD/ell
src/ell/types/_lstr.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/_lstr.py
MIT
def splitlines(self, keepends: bool = False) -> List["_lstr"]: """ Split this lstr instance into a list of lstr instances based on line breaks. Args: keepends (bool, optional): Whether to include the line breaks in the resulting lstr instances. Defaults to False. Returns: ...
Split this lstr instance into a list of lstr instances based on line breaks. Args: keepends (bool, optional): Whether to include the line breaks in the resulting lstr instances. Defaults to False. Returns: List["lstr"]: A list of lstr instances containing the split con...
splitlines
python
MadcowD/ell
src/ell/types/_lstr.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/_lstr.py
MIT
def _partition_helper( self, method, sep: Union[str, "_lstr"] ) -> Tuple["_lstr", "_lstr", "_lstr"]: """ Helper method for partitioning this lstr instance based on a separator. Args: method (Callable): The partitioning method to use (either partition or rpartition). ...
Helper method for partitioning this lstr instance based on a separator. Args: method (Callable): The partitioning method to use (either partition or rpartition). sep (Union[str, "lstr"]): The separator to partition on. Returns: Tuple["lstr", "lstr", "lstr"]...
_partition_helper
python
MadcowD/ell
src/ell/types/_lstr.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/_lstr.py
MIT
def _split_helper( self, method, sep: Optional[Union[str, "_lstr"]] = None, maxsplit: SupportsIndex = -1, ) -> List["_lstr"]: """ Helper method for splitting this lstr instance based on a separator. Args: method (Callable): The splitting method to...
Helper method for splitting this lstr instance based on a separator. Args: method (Callable): The splitting method to use (either split or rsplit). sep (Optional[Union[str, "lstr"]], optional): The separator to split on. Defaults to None. maxsplit (SupportsIndex, op...
_split_helper
python
MadcowD/ell
src/ell/types/_lstr.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/_lstr.py
MIT
def lexical_closure( func: Any, already_closed: Set[int] = None, initial_call: bool = False, recursion_stack: list = None, forced_dependencies: Optional[Dict[str, Any]] = None ) -> Tuple[str, Tuple[str, str], Set[str]]: """ Generate a lexical closure for a given function or callable. Ar...
Generate a lexical closure for a given function or callable. Args: func: The function or callable to process. already_closed: Set of already processed function hashes. initial_call: Whether this is the initial call to the function. recursion_stack: Stack to keep track of the re...
lexical_closure
python
MadcowD/ell
src/ell/util/closure.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/closure.py
MIT
def _format_source(source: str) -> str: """Format the source code using Black.""" try: return black.format_str(source, mode=black.Mode()) except: # If Black formatting fails, return the original source return source
Format the source code using Black.
_format_source
python
MadcowD/ell
src/ell/util/closure.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/closure.py
MIT
def _get_globals_and_frees(func: Callable) -> Dict[str, Dict]: """Get global and free variables for a function.""" globals_dict = collections.OrderedDict(globalvars(func)) frees_dict = collections.OrderedDict(dill.detect.freevars(func)) if isinstance(func, type): for name, method in collect...
Get global and free variables for a function.
_get_globals_and_frees
python
MadcowD/ell
src/ell/util/closure.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/closure.py
MIT
def _process_default_kwargs(func, dependencies, already_closed, recursion_stack, uses): """Process default keyword arguments and annotations of a function.""" ps = inspect.signature(func).parameters for name, param in ps.items(): if param.default is not inspect.Parameter.empty: _process_...
Process default keyword arguments and annotations of a function.
_process_default_kwargs
python
MadcowD/ell
src/ell/util/closure.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/closure.py
MIT
def _process_callable(var_name, var_value, dependencies, already_closed, recursion_stack, uses): """Process a callable (function, method, or class).""" try: module_is_ell = 'ell' in inspect.getmodule(var_value).__name__ except: module_is_ell = False if var_name not in FORBIDDEN_NAMES a...
Process a callable (function, method, or class).
_process_callable
python
MadcowD/ell
src/ell/util/closure.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/closure.py
MIT
def _process_other_variable(var_name, var_value, dependencies, uses): """Process variables that are not callables or modules.""" if isinstance(var_value, str) and '\n' in var_value: dependencies.append(f"{var_name} = '''{var_value}'''") elif is_immutable_variable(var_value): dependencies.app...
Process variables that are not callables or modules.
_process_other_variable
python
MadcowD/ell
src/ell/util/closure.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/closure.py
MIT
def _dereference_module_names(cur_src, mname, attrs_to_extract): """Dereference module names in the source code.""" for attr in attrs_to_extract: cur_src = cur_src.replace(f"{mname}.{attr}", attr) return cur_src
Dereference module names in the source code.
_dereference_module_names
python
MadcowD/ell
src/ell/util/closure.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/closure.py
MIT
def _raise_error(message, exception, recursion_stack): """Raise an error with detailed information.""" error_msg = f"{message}. Error: {str(exception)}\n" error_msg += f"Recursion stack: {' -> '.join(recursion_stack)}" # print(error_msg) raise Exception(error_msg)
Raise an error with detailed information.
_raise_error
python
MadcowD/ell
src/ell/util/closure.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/closure.py
MIT
def get_referenced_names(code: str, module_name: str): """ This function takes a block of code and a module name as input. It parses the code into an Abstract Syntax Tree (AST) and walks through the tree to find all instances where an attribute of the module is referenced in the code. Parameters: c...
This function takes a block of code and a module name as input. It parses the code into an Abstract Syntax Tree (AST) and walks through the tree to find all instances where an attribute of the module is referenced in the code. Parameters: code (str): The block of code to be parsed. module_name (st...
get_referenced_names
python
MadcowD/ell
src/ell/util/closure.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/closure.py
MIT
def lexically_closured_source(func, forced_dependencies: Optional[Dict[str, Any]] = None): """ Generate a lexically closured source for a given function. This function takes a callable object (function, method, or class) and generates a lexically closured source code. It captures all the dependencies, ...
Generate a lexically closured source for a given function. This function takes a callable object (function, method, or class) and generates a lexically closured source code. It captures all the dependencies, including global variables, free variables, and nested functions, to create a self-contained ...
lexically_closured_source
python
MadcowD/ell
src/ell/util/closure.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/closure.py
MIT
def is_function_called(func_name, source_code): """ Check if a function is called in the given source code. Parameters: func_name (str): The name of the function to check. source_code (str): The source code to check. Returns: bool: True if the function is called, False otherwise. """ ...
Check if a function is called in the given source code. Parameters: func_name (str): The name of the function to check. source_code (str): The source code to check. Returns: bool: True if the function is called, False otherwise.
is_function_called
python
MadcowD/ell
src/ell/util/closure.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/closure.py
MIT
def globalvars(func, recurse=True, builtin=False): """get objects defined in global scope that are referred to by func return a dict of {name:object}""" while hasattr(func, "__ell_func__"): func = func.__ell_func__ if inspect.ismethod(func): func = func.__func__ while hasattr(func, "__ell_f...
get objects defined in global scope that are referred to by func return a dict of {name:object}
globalvars
python
MadcowD/ell
src/ell/util/closure.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/closure.py
MIT
def should_import(module_name : str): """ This function checks if a module should be imported based on its origin. It returns False if the module is in the local directory or if the module's spec is None. Otherwise, it returns True. Returns: bool: True if the module should be imported, False ot...
This function checks if a module should be imported based on its origin. It returns False if the module is in the local directory or if the module's spec is None. Otherwise, it returns True. Returns: bool: True if the module should be imported, False otherwise.
should_import
python
MadcowD/ell
src/ell/util/closure_util.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/closure_util.py
MIT
def plot_ascii( image: Image.Image, width: int = 100, color: bool = True, ): """ Convert a PIL Image to ASCII art using pre-rendered character bitmaps and print it to the console with optional coloring. """ num_chars = len(ASCII_CHARS) # Adjust the s...
Convert a PIL Image to ASCII art using pre-rendered character bitmaps and print it to the console with optional coloring.
plot_ascii
python
MadcowD/ell
src/ell/util/plot_ascii.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/plot_ascii.py
MIT
def is_immutable_variable(value): """ Check if a value is immutable. This function determines whether the given value is of an immutable type in Python. Immutable types are objects whose state cannot be modified after they are created. Args: value: Any Python object to check for immutabili...
Check if a value is immutable. This function determines whether the given value is of an immutable type in Python. Immutable types are objects whose state cannot be modified after they are created. Args: value: Any Python object to check for immutability. Returns: bool: True if t...
is_immutable_variable
python
MadcowD/ell
src/ell/util/serialization.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/serialization.py
MIT
def should_import(module_name: str, raise_on_error: bool = False) -> bool: """ Determines whether a module should be imported based on its origin. Excludes local modules and standard library modules. Args: module_name (str): The name of the module to check. Returns: bool: True if t...
Determines whether a module should be imported based on its origin. Excludes local modules and standard library modules. Args: module_name (str): The name of the module to check. Returns: bool: True if the module should be imported (i.e., it's a third-party module), False otherwise. ...
should_import
python
MadcowD/ell
src/ell/util/should_import.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/should_import.py
MIT
def compute_color(invoking_lmp: LMP) -> str: """Compute and cache a consistent color for a given LMP.""" name_hash = hashlib.md5(invoking_lmp.__name__.encode()).hexdigest() color_index = int(name_hash, 16) % len(ELL_COLORS) return list(ELL_COLORS.values())[color_index]
Compute and cache a consistent color for a given LMP.
compute_color
python
MadcowD/ell
src/ell/util/verbosity.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/verbosity.py
MIT
def format_arg(arg: Any, max_length: int = 8) -> str: """Format an argument for display with customizable max length.""" str_arg = str(arg) return f"{Fore.MAGENTA}{str_arg[:max_length]}..{Style.RESET_ALL}" if len(str_arg) > max_length else f"{Fore.MAGENTA}{str_arg}{Style.RESET_ALL}"
Format an argument for display with customizable max length.
format_arg
python
MadcowD/ell
src/ell/util/verbosity.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/verbosity.py
MIT
def get_terminal_width() -> int: """Get the terminal width, defaulting to 80 if it can't be determined.""" try: return shutil.get_terminal_size((80, 20)).columns except Exception: logger.warning("Unable to determine terminal size. Defaulting to 80 columns.") return 80
Get the terminal width, defaulting to 80 if it can't be determined.
get_terminal_width
python
MadcowD/ell
src/ell/util/verbosity.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/verbosity.py
MIT
def wrap_text_with_prefix(message, width: int, prefix: str, subsequent_prefix: str, text_color: str) -> List[str]: """Wrap text while preserving the prefix and color for each line.""" result = [] for i, content in enumerate(message.content): wrapped_lines = [] if content.image and content.im...
Wrap text while preserving the prefix and color for each line.
wrap_text_with_prefix
python
MadcowD/ell
src/ell/util/verbosity.py
https://github.com/MadcowD/ell/blob/master/src/ell/util/verbosity.py
MIT
def get_table_metadata(engine, exclude_tables=None): """Helper to get table metadata in a consistent format""" inspector = inspect(engine) metadata = {} exclude_tables = exclude_tables or set() for table_name in inspector.get_table_names(): if table_name in exclude_tables: c...
Helper to get table metadata in a consistent format
get_table_metadata
python
MadcowD/ell
tests/test_migrations.py
https://github.com/MadcowD/ell/blob/master/tests/test_migrations.py
MIT
def test_empty_db_migration(temp_db_url): """Test migrating an empty database creates same schema as SQLModel metadata""" # Create engine for empty database engine = create_engine(temp_db_url) # Initialize database using migrations init_or_migrate_database(engine) # Get schema created ...
Test migrating an empty database creates same schema as SQLModel metadata
test_empty_db_migration
python
MadcowD/ell
tests/test_migrations.py
https://github.com/MadcowD/ell/blob/master/tests/test_migrations.py
MIT
def test_existing_tables_no_alembic(temp_db_url): """Test database with existing tables but no alembic version table""" engine = create_engine(temp_db_url) # Create tables using SQLModel SQLModel.metadata.create_all(engine) # Initialize/migrate database init_or_migrate_database(engine)...
Test database with existing tables but no alembic version table
test_existing_tables_no_alembic
python
MadcowD/ell
tests/test_migrations.py
https://github.com/MadcowD/ell/blob/master/tests/test_migrations.py
MIT
def test_multiple_migrations(temp_db_url): """Test running multiple migrations in sequence""" engine = create_engine(temp_db_url) # Get alembic config alembic_cfg = get_alembic_config(str(engine.url)) # Start with empty database init_or_migrate_database(engine) # Verify we're ...
Test running multiple migrations in sequence
test_multiple_migrations
python
MadcowD/ell
tests/test_migrations.py
https://github.com/MadcowD/ell/blob/master/tests/test_migrations.py
MIT
def test_migration_idempotency(temp_db_url): """Test that running migrations multiple times is idempotent""" engine = create_engine(temp_db_url) # Initial migration init_or_migrate_database(engine) initial_metadata = get_table_metadata(engine) # Run migration again init_or_migrate_...
Test that running migrations multiple times is idempotent
test_migration_idempotency
python
MadcowD/ell
tests/test_migrations.py
https://github.com/MadcowD/ell/blob/master/tests/test_migrations.py
MIT
def test_pure_migration_matches_metadata(temp_db_url): """ Test that running just the initial migration (without SQLModel.metadata) creates the same schema as SQLModel.metadata """ # Create first empty database for migration engine1 = create_engine(temp_db_url) # Get alembic config and...
Test that running just the initial migration (without SQLModel.metadata) creates the same schema as SQLModel.metadata
test_pure_migration_matches_metadata
python
MadcowD/ell
tests/test_migrations.py
https://github.com/MadcowD/ell/blob/master/tests/test_migrations.py
MIT
def test_translate_to_provider_unregistered_model(self, provider, ell_call_params): """ Test that translate_to_provider does not fail when the model is not registered. It should retain default streaming parameters. """ # Set up the EllCallParams with a model that is not registere...
Test that translate_to_provider does not fail when the model is not registered. It should retain default streaming parameters.
test_translate_to_provider_unregistered_model
python
MadcowD/ell
tests/test_openai_provider.py
https://github.com/MadcowD/ell/blob/master/tests/test_openai_provider.py
MIT
def mock_project_root(monkeypatch): """ Fixture to mock the ELL_PROJECT_ROOT environment variable. """ project_root = Path("/mock/project/root").resolve() monkeypatch.setenv("ELL_PROJECT_ROOT", str(project_root)) return project_root
Fixture to mock the ELL_PROJECT_ROOT environment variable.
mock_project_root
python
MadcowD/ell
tests/test_should_import.py
https://github.com/MadcowD/ell/blob/master/tests/test_should_import.py
MIT
def mock_find_spec(module_name, raise_value): """ Helper function to create a mock spec object. """ mock_spec = MagicMock() mock_spec.origin = raise_value["origin"] mock_spec.has_location = raise_value["has_location"] return mock_spec
Helper function to create a mock spec object.
mock_find_spec
python
MadcowD/ell
tests/test_should_import.py
https://github.com/MadcowD/ell/blob/master/tests/test_should_import.py
MIT
def test_should_import_exception_handling(mock_project_root, mock_sysconfig_paths, mock_site_packages, monkeypatch, capsys): """ Test the function's behavior when importlib.util.find_spec raises an exception. """ with patch("importlib.util.find_spec", side_effect=Exception("Test Exception")), \ ...
Test the function's behavior when importlib.util.find_spec raises an exception.
test_should_import_exception_handling
python
MadcowD/ell
tests/test_should_import.py
https://github.com/MadcowD/ell/blob/master/tests/test_should_import.py
MIT
def test_should_import_raise_on_error(mock_project_root, mock_sysconfig_paths, mock_site_packages, monkeypatch): """ Test the function's behavior when raise_on_error is True and an exception is raised. """ with patch("importlib.util.find_spec", side_effect=Exception("Test Exception")), \ patch(...
Test the function's behavior when raise_on_error is True and an exception is raised.
test_should_import_raise_on_error
python
MadcowD/ell
tests/test_should_import.py
https://github.com/MadcowD/ell/blob/master/tests/test_should_import.py
MIT
def test_should_import_without_origin(mock_project_root, mock_sysconfig_paths, mock_site_packages, monkeypatch): """ Test behavior when the module spec exists but has no origin. Typically for built-in modules. """ with patch("importlib.util.find_spec") as mock_find_spec_func, \ patch("site....
Test behavior when the module spec exists but has no origin. Typically for built-in modules.
test_should_import_without_origin
python
MadcowD/ell
tests/test_should_import.py
https://github.com/MadcowD/ell/blob/master/tests/test_should_import.py
MIT
def test_should_import_with_no_spec(mock_project_root, mock_sysconfig_paths, mock_site_packages, monkeypatch): """ Test behavior when find_spec returns None, indicating the module cannot be found. """ with patch("importlib.util.find_spec", return_value=None), \ patch("site.getsitepackages", ret...
Test behavior when find_spec returns None, indicating the module cannot be found.
test_should_import_with_no_spec
python
MadcowD/ell
tests/test_should_import.py
https://github.com/MadcowD/ell/blob/master/tests/test_should_import.py
MIT
def test_should_import_standard_library(): """ Test importing a standard library module without mocking. """ import importlib module_name = "json" result = should_import(module_name) assert result == True, f"Failed to import standard library module: {module_name}"
Test importing a standard library module without mocking.
test_should_import_standard_library
python
MadcowD/ell
tests/test_should_import.py
https://github.com/MadcowD/ell/blob/master/tests/test_should_import.py
MIT
def test_should_import_third_party(): """ Test importing a third-party module without mocking. Ensures that the module is installed in the environment. """ import importlib module_name = "requests" result = should_import(module_name) assert result == True, f"Failed to import third-party...
Test importing a third-party module without mocking. Ensures that the module is installed in the environment.
test_should_import_third_party
python
MadcowD/ell
tests/test_should_import.py
https://github.com/MadcowD/ell/blob/master/tests/test_should_import.py
MIT
def test_should_import_local_module(): """ Test importing a local module within the project without mocking. Assumes that 'src.ell.util.local_module' exists. """ module_name = "src.ell.util.local_module" result = should_import(module_name) assert result == False, f"Local module should not be...
Test importing a local module within the project without mocking. Assumes that 'src.ell.util.local_module' exists.
test_should_import_local_module
python
MadcowD/ell
tests/test_should_import.py
https://github.com/MadcowD/ell/blob/master/tests/test_should_import.py
MIT
def test_should_import_nonexistent_module(): """ Test importing a non-existent module without mocking. """ module_name = "this_module_does_not_exist" result = should_import(module_name) assert result == False, f"Non-existent module should not be imported: {module_name}"
Test importing a non-existent module without mocking.
test_should_import_nonexistent_module
python
MadcowD/ell
tests/test_should_import.py
https://github.com/MadcowD/ell/blob/master/tests/test_should_import.py
MIT
def test_should_import_multiple_standard_library_modules(module_name, expected): """ Test importing multiple standard library modules without mocking. """ result = should_import(module_name) assert result == expected, f"Failed to import standard library module: {module_name}"
Test importing multiple standard library modules without mocking.
test_should_import_multiple_standard_library_modules
python
MadcowD/ell
tests/test_should_import.py
https://github.com/MadcowD/ell/blob/master/tests/test_should_import.py
MIT
def test_should_import_windows_specific_module(): """ Test importing a Windows-specific module without mocking. """ module_name = "msvcrt" # Windows-specific module result = should_import(module_name) assert result == True, f"Failed to import Windows-specific module: {module_name}"
Test importing a Windows-specific module without mocking.
test_should_import_windows_specific_module
python
MadcowD/ell
tests/test_should_import.py
https://github.com/MadcowD/ell/blob/master/tests/test_should_import.py
MIT
def test_should_import_unix_specific_module(): """ Test importing a Unix-specific module without mocking. """ module_name = "pwd" # Unix-specific module result = should_import(module_name) assert result == True, f"Failed to import Unix-specific module: {module_name}"
Test importing a Unix-specific module without mocking.
test_should_import_unix_specific_module
python
MadcowD/ell
tests/test_should_import.py
https://github.com/MadcowD/ell/blob/master/tests/test_should_import.py
MIT
def extract_json_object(text, json_type="dict"): """ Extracts a JSON object from a text string. Parameters: - text (str): The text containing the JSON data. - json_type (str): The type of JSON structure to look for ("dict" or "list"). Returns: - dict or list: The extracted JSON object, or ...
Extracts a JSON object from a text string. Parameters: - text (str): The text containing the JSON data. - json_type (str): The type of JSON structure to look for ("dict" or "list"). Returns: - dict or list: The extracted JSON object, or None if parsing fails.
extract_json_object
python
X-PLUG/MobileAgent
Mobile-Agent-E/MobileAgentE/agents.py
https://github.com/X-PLUG/MobileAgent/blob/master/Mobile-Agent-E/MobileAgentE/agents.py
MIT
def track_usage(res_json, api_key): """ {'id': 'chatcmpl-AbJIS3o0HMEW9CWtRjU43bu2Ccrdu', 'object': 'chat.completion', 'created': 1733455676, 'model': 'gpt-4o-2024-11-20', 'choices': [...], 'usage': {'prompt_tokens': 2731, 'completion_tokens': 235, 'total_tokens': 2966, 'prompt_tokens_details': {'cached_tokens':...
{'id': 'chatcmpl-AbJIS3o0HMEW9CWtRjU43bu2Ccrdu', 'object': 'chat.completion', 'created': 1733455676, 'model': 'gpt-4o-2024-11-20', 'choices': [...], 'usage': {'prompt_tokens': 2731, 'completion_tokens': 235, 'total_tokens': 2966, 'prompt_tokens_details': {'cached_tokens': 0, 'audio_tokens': 0}, 'completion_tokens_...
track_usage
python
X-PLUG/MobileAgent
Mobile-Agent-E/MobileAgentE/api.py
https://github.com/X-PLUG/MobileAgent/blob/master/Mobile-Agent-E/MobileAgentE/api.py
MIT
def save_screenshot_to_file(adb_path, file_path="screenshot.png"): """ Captures a screenshot from an Android device using ADB, saves it locally, and removes the screenshot from the device. Args: adb_path (str): The path to the adb executable. Returns: str: The path to the saved screens...
Captures a screenshot from an Android device using ADB, saves it locally, and removes the screenshot from the device. Args: adb_path (str): The path to the adb executable. Returns: str: The path to the saved screenshot, or raises an exception on failure.
save_screenshot_to_file
python
X-PLUG/MobileAgent
Mobile-Agent-E/MobileAgentE/controller.py
https://github.com/X-PLUG/MobileAgent/blob/master/Mobile-Agent-E/MobileAgentE/controller.py
MIT
def box_iou(boxes1: np.ndarray, boxes2: np.ndarray) -> np.ndarray: """ Fast vectorized IOU implementation using only NumPy boxes1: [N, 4] array of boxes boxes2: [M, 4] array of boxes Returns: [N, M] array of IOU values """ # Calculate areas of boxes1 area1 = (boxes1[:, 2] - boxes1[:, 0])...
Fast vectorized IOU implementation using only NumPy boxes1: [N, 4] array of boxes boxes2: [M, 4] array of boxes Returns: [N, M] array of IOU values
box_iou
python
X-PLUG/MobileAgent
PC-Agent/pymac.py
https://github.com/X-PLUG/MobileAgent/blob/master/PC-Agent/pymac.py
MIT
def filter_ocr_elements( self, ocr_bboxes, # [(content, bbox), ] preserved_nodes: List[Dict], ) -> Tuple[List[str], List[Dict]]: """ Add OCR-detected elements to the accessibility tree if they don't overlap with existing elements Uses opti...
Add OCR-detected elements to the accessibility tree if they don't overlap with existing elements Uses optimized NumPy implementation
filter_ocr_elements
python
X-PLUG/MobileAgent
PC-Agent/pymac.py
https://github.com/X-PLUG/MobileAgent/blob/master/PC-Agent/pymac.py
MIT
def click( self, element_id: int, num_clicks: int = 1, button_type: str = "left", hold_keys: List = [], ): """Click on the element Args: element_id:int, ID of the element to click on num_clicks:int, number of times to click the element ...
Click on the element Args: element_id:int, ID of the element to click on num_clicks:int, number of times to click the element button_type:str, which mouse button to press can be "left", "middle", or "right" hold_keys:List, list of keys to hold while clicking ...
click
python
X-PLUG/MobileAgent
PC-Agent/pymac.py
https://github.com/X-PLUG/MobileAgent/blob/master/PC-Agent/pymac.py
MIT
def type( self, element_id: int = None, text: str = "", overwrite: bool = False, enter: bool = False, ): """Type text into the element Args: element_id:int ID of the element to type into. If not provided, typing will start at the current cursor loc...
Type text into the element Args: element_id:int ID of the element to type into. If not provided, typing will start at the current cursor location. text:str the text to type overwrite:bool Assign it to True if the text should overwrite the existing text, otherwise assign it to...
type
python
X-PLUG/MobileAgent
PC-Agent/pymac.py
https://github.com/X-PLUG/MobileAgent/blob/master/PC-Agent/pymac.py
MIT
def drag_and_drop(self, drag_from_id: int, drop_on_id: int, hold_keys: List = []): """Drag element1 and drop it on element2. Args: drag_from_id:int ID of element to drag drop_on_id:int ID of element to drop on hold_keys:List list of keys to hold while dragging ...
Drag element1 and drop it on element2. Args: drag_from_id:int ID of element to drag drop_on_id:int ID of element to drop on hold_keys:List list of keys to hold while dragging
drag_and_drop
python
X-PLUG/MobileAgent
PC-Agent/pymac.py
https://github.com/X-PLUG/MobileAgent/blob/master/PC-Agent/pymac.py
MIT
def scroll(self, element_id: int, clicks: int): """Scroll in the specified direction inside the specified element Args: element_id:int ID of the element to scroll in clicks:int the number of clicks to scroll can be positive (up) or negative (down). """ try: ...
Scroll in the specified direction inside the specified element Args: element_id:int ID of the element to scroll in clicks:int the number of clicks to scroll can be positive (up) or negative (down).
scroll
python
X-PLUG/MobileAgent
PC-Agent/pymac.py
https://github.com/X-PLUG/MobileAgent/blob/master/PC-Agent/pymac.py
MIT
def hotkey(self, keys: List): """Press a hotkey combination Args: keys:List the keys to press in combination in a list format (e.g. ['shift', 'c']) """ # Normalize any 'cmd' to 'command' keys = [_normalize_key(k) for k in keys] # add quotes around the keys ...
Press a hotkey combination Args: keys:List the keys to press in combination in a list format (e.g. ['shift', 'c'])
hotkey
python
X-PLUG/MobileAgent
PC-Agent/pymac.py
https://github.com/X-PLUG/MobileAgent/blob/master/PC-Agent/pymac.py
MIT
def hold_and_press(self, hold_keys: List, press_keys: List): """Hold a list of keys and press a list of keys Args: hold_keys:List, list of keys to hold press_keys:List, list of keys to press in a sequence """ # Normalize any 'cmd' to 'command' in both lists ...
Hold a list of keys and press a list of keys Args: hold_keys:List, list of keys to hold press_keys:List, list of keys to press in a sequence
hold_and_press
python
X-PLUG/MobileAgent
PC-Agent/pymac.py
https://github.com/X-PLUG/MobileAgent/blob/master/PC-Agent/pymac.py
MIT
def type( self, element_id: int = None, text: str = "", overwrite: bool = False, enter: bool = False, ): """Type text into the element Args: element_id:int ID of the element to type into. If not provided, typing will start at the current cursor loc...
Type text into the element Args: element_id:int ID of the element to type into. If not provided, typing will start at the current cursor location. text:str the text to type overwrite:bool Assign it to True if the text should overwrite the existing text, otherwise assign it to...
type
python
X-PLUG/MobileAgent
PC-Agent/pywin.py
https://github.com/X-PLUG/MobileAgent/blob/master/PC-Agent/pywin.py
MIT
def hotkey(self, keys: List[str]): """Press a hotkey combination Args: keys:List[str] the keys to press in combination in a list format (e.g. ['shift', 'c']) """ keys = [_normalize_key(k) for k in keys] keys = [f"'{key}'" for key in keys] command = f"import py...
Press a hotkey combination Args: keys:List[str] the keys to press in combination in a list format (e.g. ['shift', 'c'])
hotkey
python
X-PLUG/MobileAgent
PC-Agent/pywin.py
https://github.com/X-PLUG/MobileAgent/blob/master/PC-Agent/pywin.py
MIT
def hold_and_press(self, hold_keys: List[str], press_keys: List[str]): """Hold a list of keys and press a list of keys Args: hold_keys:List[str], list of keys to hold press_keys:List[str], list of keys to press in a sequence """ hold_keys = [_normalize_key(k) for ...
Hold a list of keys and press a list of keys Args: hold_keys:List[str], list of keys to hold press_keys:List[str], list of keys to press in a sequence
hold_and_press
python
X-PLUG/MobileAgent
PC-Agent/pywin.py
https://github.com/X-PLUG/MobileAgent/blob/master/PC-Agent/pywin.py
MIT
def compute_iou(box1, box2): """ Compute the Intersection over Union (IoU) of two bounding boxes. Parameters: - box1: list or array [x1, y1, x2, y2] - box2: list or array [x1, y1, x2, y2] Returns: - iou: float, IoU value """ x1_inter = max(box1[0], box2[0]) y1_inter = max(box1[...
Compute the Intersection over Union (IoU) of two bounding boxes. Parameters: - box1: list or array [x1, y1, x2, y2] - box2: list or array [x1, y1, x2, y2] Returns: - iou: float, IoU value
compute_iou
python
X-PLUG/MobileAgent
PC-Agent/PCAgent/merge_strategy.py
https://github.com/X-PLUG/MobileAgent/blob/master/PC-Agent/PCAgent/merge_strategy.py
MIT
def merge_boxes_and_texts(texts, boxes, iou_threshold=0): """ Merge bounding boxes and their corresponding texts based on IoU threshold. Parameters: - boxes: List of bounding boxes, with each box represented as [x1, y1, x2, y2]. - texts: List of texts corresponding to each bounding box. - iou_t...
Merge bounding boxes and their corresponding texts based on IoU threshold. Parameters: - boxes: List of bounding boxes, with each box represented as [x1, y1, x2, y2]. - texts: List of texts corresponding to each bounding box. - iou_threshold: Intersection-over-Union threshold for merging boxes. ...
merge_boxes_and_texts
python
X-PLUG/MobileAgent
PC-Agent/PCAgent/merge_strategy.py
https://github.com/X-PLUG/MobileAgent/blob/master/PC-Agent/PCAgent/merge_strategy.py
MIT
def get_parser(cls) -> ConfigParser: """Get a parser for post-training quantization of a diffusion model. Returns: `ConfigParser`: A parser for post-training quantization of a diffusion model. """ parser = ConfigParser("Diffusion Run configuration") D...
Get a parser for post-training quantization of a diffusion model. Returns: `ConfigParser`: A parser for post-training quantization of a diffusion model.
get_parser
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/config.py
Apache-2.0
def ptq( # noqa: C901 model: DiffusionModelStruct, config: DiffusionQuantConfig, cache: DiffusionPtqCacheConfig | None = None, load_dirpath: str = "", save_dirpath: str = "", copy_on_save: bool = False, save_model: bool = False, ) -> DiffusionModelStruct: """Post-training quantization o...
Post-training quantization of a diffusion model. Args: model (`DiffusionModelStruct`): The diffusion model. config (`DiffusionQuantConfig`): The diffusion model post-training quantization configuration. cache (`DiffusionPtqCacheConfig`, *optional*, defaults to `None`...
ptq
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/ptq.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/ptq.py
Apache-2.0
def main(config: DiffusionPtqRunConfig, logging_level: int = tools.logging.DEBUG) -> DiffusionPipeline: """Post-training quantization of a diffusion model. Args: config (`DiffusionPtqRunConfig`): The diffusion model post-training quantization configuration. logging_level (`int`, *op...
Post-training quantization of a diffusion model. Args: config (`DiffusionPtqRunConfig`): The diffusion model post-training quantization configuration. logging_level (`int`, *optional*, defaults to `logging.DEBUG`): The logging level. Returns: `DiffusionPipeline`...
main
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/ptq.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/ptq.py
Apache-2.0
def info( self, name: str, module: nn.Module, tensors: dict[int | str, torch.Tensor], cache: TensorsCache, ) -> None: """Update cache information. Args: name (`str`): Module name. module (`nn.Module`): M...
Update cache information. Args: name (`str`): Module name. module (`nn.Module`): Module. tensors (`dict[int | str, torch.Tensor]`): Tensors to cache. cache (`TensorsCache`): Cache.
info
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/dataset/calib.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/dataset/calib.py
Apache-2.0
def __init__(self, config: DiffusionCalibCacheLoaderConfig) -> None: """Initialize the cache for the diffusion calibration dataset. Args: config (`DiffusionCalibCacheLoaderConfig`): Configuration for the calibration cache loader. """ super().__init__(dataset=...
Initialize the cache for the diffusion calibration dataset. Args: config (`DiffusionCalibCacheLoaderConfig`): Configuration for the calibration cache loader.
__init__
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/dataset/calib.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/dataset/calib.py
Apache-2.0
def _init_cache(self, name: str, module: nn.Module) -> IOTensorsCache: """Initialize cache. Args: name (`str`): Module name. module (`nn.Module`): Module. Returns: `IOTensorsCache`: Cache for inputs and outputs...
Initialize cache. Args: name (`str`): Module name. module (`nn.Module`): Module. Returns: `IOTensorsCache`: Cache for inputs and outputs.
_init_cache
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/dataset/calib.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/dataset/calib.py
Apache-2.0
def _convert_layer_inputs( self, m: nn.Module, args: tuple[tp.Any, ...], kwargs: dict[str, tp.Any], save_all: bool = False ) -> ModuleForwardInput: """Convert layer inputs to module forward input. Args: m (`nn.Module`): Layer. args (`tuple[Any, ...]`)...
Convert layer inputs to module forward input. Args: m (`nn.Module`): Layer. args (`tuple[Any, ...]`): Layer input arguments. kwargs (`dict[str, Any]`): Layer input keyword arguments. save_all (`bool`, *optional*, de...
_convert_layer_inputs
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/dataset/calib.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/dataset/calib.py
Apache-2.0
def _convert_layer_outputs(self, m: nn.Module, outputs: tp.Any) -> dict[str | int, tp.Any]: """Convert layer outputs to dictionary for updating the next layer inputs. Args: m (`nn.Module`): Layer. outputs (`Any`): Layer outputs. Returns: ...
Convert layer outputs to dictionary for updating the next layer inputs. Args: m (`nn.Module`): Layer. outputs (`Any`): Layer outputs. Returns: `dict[str | int, Any]`: Dictionary for updating the next layer inputs. ...
_convert_layer_outputs
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/dataset/calib.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/dataset/calib.py
Apache-2.0
def iter_layer_activations( # noqa: C901 self, model: nn.Module | DiffusionModelStruct, *args, needs_inputs_fn: tp.Callable[[str, nn.Module], bool], needs_outputs_fn: tp.Callable[[str, nn.Module], bool] | None = None, action: CacheAction | None = None, skip_pre_m...
Iterate over model activations in layers. Args: model (`nn.Module`): Model. action (`CacheAction`): Action for caching activations. needs_inputs_fn (`Callable[[str, nn.Module], bool]` or `bool` or `None`, *optional*, defaults to `True`): ...
iter_layer_activations
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/dataset/calib.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/dataset/calib.py
Apache-2.0
def categorize_metrics(metrics: tuple[str, ...]) -> tuple[list[str], list[str], list[str]]: """ Categorize metrics into multimodal, similarity, and other metrics. Args: metrics (tuple[str, ...]): List of metrics. Returns: tuple[list[str], list[str], list[str]]: Tuple of multimodal, sim...
Categorize metrics into multimodal, similarity, and other metrics. Args: metrics (tuple[str, ...]): List of metrics. Returns: tuple[list[str], list[str], list[str]]: Tuple of multimodal, similarity, and other metrics.
categorize_metrics
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/eval/metrics/__init__.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/eval/metrics/__init__.py
Apache-2.0
def replace_up_block_conv_with_concat_conv(model: nn.Module) -> None: """Replace up_block convolutions in UNet with ConcatConv.""" model_struct = DiffusionModelStruct.construct(model) if not isinstance(model_struct, UNetStruct): return logger = tools.logging.getLogger(__name__) logger.info("...
Replace up_block convolutions in UNet with ConcatConv.
replace_up_block_conv_with_concat_conv
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/nn/patch.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/nn/patch.py
Apache-2.0
def replace_fused_linear_with_concat_linear(model: nn.Module) -> None: """Replace fused Linear in FluxSingleTransformerBlock with ConcatLinear.""" logger = tools.logging.getLogger(__name__) logger.info("Replacing fused Linear with ConcatLinear.") tools.logging.Formatter.indent_inc() for name, module...
Replace fused Linear in FluxSingleTransformerBlock with ConcatLinear.
replace_fused_linear_with_concat_linear
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/nn/patch.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/nn/patch.py
Apache-2.0
def shift_input_activations(model: nn.Module) -> None: """Shift input activations of convolutions and linear layers if their lowerbound is negative. Args: model (nn.Module): model to shift input activations. """ logger = tools.logging.getLogger(__name__) model_struct = DiffusionModelStruct....
Shift input activations of convolutions and linear layers if their lowerbound is negative. Args: model (nn.Module): model to shift input activations.
shift_input_activations
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/nn/patch.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/nn/patch.py
Apache-2.0
def get_iter_layer_activations_args( self, skip_pre_modules: bool, skip_post_modules: bool, **input_kwargs ) -> tuple[list[nn.Module], list[DiffusionModuleStruct | DiffusionBlockStruct], list[bool], list[bool]]: """ Get the arguments for iterating over the layers and their activations. ...
Get the arguments for iterating over the layers and their activations. Args: skip_pre_modules (`bool`): Whether to skip the pre-modules skip_post_modules (`bool`): Whether to skip the post-modules Returns: `tuple[list[nn.Modu...
get_iter_layer_activations_args
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/nn/struct.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/nn/struct.py
Apache-2.0
def _simplify_keys(keys: tp.Iterable[str], *, key_map: dict[str, set[str]]) -> list[str]: """Simplify the keys based on the key map. Args: keys (`Iterable[str]`): The keys to simplify. key_map (`dict[str, set[str]]`): The key map. Returns...
Simplify the keys based on the key map. Args: keys (`Iterable[str]`): The keys to simplify. key_map (`dict[str, set[str]]`): The key map. Returns: `list[str]`: The simplified keys.
_simplify_keys
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/nn/struct.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/nn/struct.py
Apache-2.0
def filter_kwargs(self, kwargs: dict) -> dict: """Filter layer kwargs to attn kwargs.""" if isinstance(self.parent.module, BasicTransformerBlock): if kwargs.get("cross_attention_kwargs", None) is None: attn_kwargs = {} else: attn_kwargs = dict(kwar...
Filter layer kwargs to attn kwargs.
filter_kwargs
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/nn/struct.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/nn/struct.py
Apache-2.0
def build( self, *, dtype: str | torch.dtype | None = None, device: str | torch.device | None = None ) -> DiffusionPipeline: """Build the diffusion pipeline. Args: dtype (`str` or `torch.dtype`, *optional*): The data type of the pipeline. device (`str...
Build the diffusion pipeline. Args: dtype (`str` or `torch.dtype`, *optional*): The data type of the pipeline. device (`str` or `torch.device`, *optional*): The device of the pipeline. Returns: `DiffusionPipeline`: The...
build
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/pipeline/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/pipeline/config.py
Apache-2.0
def extract_text_encoders( self, pipeline: DiffusionPipeline, supported: tuple[type[PreTrainedModel], ...] = (T5EncoderModel,) ) -> list[tuple[str, PreTrainedModel, PreTrainedTokenizer]]: """Extract the text encoders and tokenizers from the pipeline. Args: pipeline (`DiffusionPi...
Extract the text encoders and tokenizers from the pipeline. Args: pipeline (`DiffusionPipeline`): The diffusion pipeline. supported (`tuple[type[PreTrainedModel], ...]`, *optional*, defaults to `(T5EncoderModel,)`): The supported text encoder types. If no...
extract_text_encoders
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/pipeline/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/pipeline/config.py
Apache-2.0
def register_pipeline_factory( cls, names: str | tuple[str, ...], /, factory: tp.Callable[[str, str, torch.dtype, torch.device, bool], DiffusionPipeline], *, overwrite: bool = False, ) -> None: """Register a pipeline factory. Args: names (...
Register a pipeline factory. Args: names (`str` or `tuple[str, ...]`): The name of the pipeline. factory (`Callable[[str, str,torch.dtype, torch.device, bool], DiffusionPipeline]`): The pipeline factory function. overwrite (`bool`, *optional*,...
register_pipeline_factory
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/pipeline/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/pipeline/config.py
Apache-2.0
def register_text_extractor( cls, names: str | tuple[str, ...], /, extractor: tp.Callable[ [DiffusionPipeline, tuple[type[PreTrainedModel], ...]], list[tuple[str, PreTrainedModel, PreTrainedTokenizer]], ], *, overwrite: bool = False, ) ...
Register a text extractor. Args: names (`str` or `tuple[str, ...]`): The name of the pipeline. extractor (`Callable[[DiffusionPipeline], list[tuple[str, PreTrainedModel, PreTrainedTokenizer]]`): The text extractor function. overwrite (`bool`, ...
register_text_extractor
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/pipeline/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/pipeline/config.py
Apache-2.0
def quantize_diffusion_block_activations( # noqa: C901 layer: DiffusionBlockStruct | DiffusionModuleStruct, config: DiffusionQuantConfig, quantizer_state_dict: dict[str, dict[str, torch.Tensor | float | None]], layer_cache: dict[str, IOTensorsCache] | None = None, layer_kwargs: dict[str, tp.Any] | ...
Quantize the activations of a diffusion model block. Args: layer (`DiffusionBlockStruct` or `DiffusionModuleStruct`): The diffusion model block. config (`DiffusionQuantConfig`): The quantization configuration. quantizer_state_dict (`dict[str, dict[str, torch.Tensor |...
quantize_diffusion_block_activations
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/activation.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/activation.py
Apache-2.0
def quantize_diffusion_activations( model: nn.Module | DiffusionModelStruct, config: DiffusionQuantConfig, quantizer_state_dict: dict[str, dict[str, torch.Tensor | float | None]] | None = None, orig_state_dict: dict[str, torch.Tensor] | None = None, ) -> dict[str, dict[str, torch.Tensor | float | None]]...
Quantize the activations of a diffusion model. Args: model (`nn.Module` or `DiffusionModelStruct`): The diffusion model. config (`DiffusionQuantConfig`): The quantization configuration. quantizer_state_dict (`dict[str, dict[str, torch.Tensor | float | None]]`, *optio...
quantize_diffusion_activations
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/activation.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/activation.py
Apache-2.0
def needs_acts_quantizer_cache(self) -> bool: """Whether to cache the activations quantizer settings.""" if self.enabled_ipts and self.ipts.needs_calib_data: return True if self.enabled_opts and self.opts.needs_calib_data: return True return False
Whether to cache the activations quantizer settings.
needs_acts_quantizer_cache
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/config.py
Apache-2.0
def generate_cache_dirpath( self, *, root: str, shift: bool, default_dtype: torch.dtype = torch.float16 ) -> DiffusionQuantCacheConfig: # noqa: C901 """Generate the cache paths for the module quantization configuration.""" quant_names = self.generate_dirnames(default_dtype=default_dtype) ...
Generate the cache paths for the module quantization configuration.
generate_cache_dirpath
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/config.py
Apache-2.0
def generate_default_dirname(self) -> str: # noqa: C901 """Generate output directory name for evaluating a large language model.""" key_map = type(self)._key_map def simplify_skips(skips): return set( DiffusionQuantCacheConfig.simplify_path("skip.[{}]".format("+".jo...
Generate output directory name for evaluating a large language model.
generate_default_dirname
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/config.py
Apache-2.0
def organize(self) -> dict[str, bool]: # noqa: C901 """Organize the flags for the diffusion model quantization configuration. Returns: dict[str, bool]: The organized flags. """ key_map = type(self)._key_map wgts_skip_set, ipts_skip_set, opts_skip_set = set(), set(),...
Organize the flags for the diffusion model quantization configuration. Returns: dict[str, bool]: The organized flags.
organize
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/config.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/config.py
Apache-2.0
def rotate_diffusion( # noqa: C901 model: DiffusionModelStruct, /, config: DiffusionQuantConfig ): """Rotate the weights of the diffusion model. Args: model (`PreTrainedModel` or `LlmStruct`): Model to be rotated. config (`QuantRotationConfig`): Rotation configurati...
Rotate the weights of the diffusion model. Args: model (`PreTrainedModel` or `LlmStruct`): Model to be rotated. config (`QuantRotationConfig`): Rotation configuration.
rotate_diffusion
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/rotate.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/rotate.py
Apache-2.0
def smooth_diffusion_layer( layer: DiffusionBlockStruct, config: DiffusionQuantConfig, smooth_cache: dict[str, torch.Tensor], layer_cache: dict[str, IOTensorsCache] | None = None, layer_kwargs: dict[str, tp.Any] | None = None, ) -> None: """Smooth a single diffusion model block. Args: ...
Smooth a single diffusion model block. Args: layer (`DiffusionBlockStruct`): The diffusion block. config (`DiffusionQuantConfig`): The quantization configuration. smooth_cache (`dict[str, torch.Tensor]`): The smoothing scales cache. layer_cache (`...
smooth_diffusion_layer
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/smooth.py
Apache-2.0
def smooth_diffusion( model: nn.Module | DiffusionModelStruct, config: DiffusionQuantConfig, smooth_cache: dict[str, torch.Tensor] | None = None, ) -> dict[str, torch.Tensor]: """Smooth the diffusion model. Args: model (`nn.Module` or `DiffusionModelStruct`): The diffusion model...
Smooth the diffusion model. Args: model (`nn.Module` or `DiffusionModelStruct`): The diffusion model. config (`DiffusionQuantConfig`): The quantization configuration. smooth_cache (`dict[str, torch.Tensor]`, *optional*): The smoothing scales cache. R...
smooth_diffusion
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/smooth.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/smooth.py
Apache-2.0
def get_needs_inputs_fn( model: DiffusionModelStruct, config: DiffusionQuantConfig ) -> tp.Callable[[str, nn.Module], bool]: """Get function that checks whether the module needs to cache inputs. Args: model (`DiffusionModelStruct`): The diffused model. config (`DiffusionQuantCon...
Get function that checks whether the module needs to cache inputs. Args: model (`DiffusionModelStruct`): The diffused model. config (`DiffusionQuantConfig`): The quantization configuration. Returns: `Callable[[str, nn.Module], bool]`: The function th...
get_needs_inputs_fn
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/utils.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/utils.py
Apache-2.0
def get_needs_outputs_fn( model: DiffusionModelStruct, config: DiffusionQuantConfig ) -> tp.Callable[[str, nn.Module], bool]: """Get function that checks whether the module needs to cache outputs. Args: model (`DiffusionModelStruct`): The diffused model. config (`DiffusionQuantC...
Get function that checks whether the module needs to cache outputs. Args: model (`DiffusionModelStruct`): The diffused model. config (`DiffusionQuantConfig`): The quantization configuration. Returns: `Callable[[str, nn.Module], bool]`: The function t...
get_needs_outputs_fn
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/utils.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/utils.py
Apache-2.0
def calibrate_diffusion_block_low_rank_branch( # noqa: C901 layer: DiffusionModuleStruct | DiffusionBlockStruct, config: DiffusionQuantConfig, branch_state_dict: dict[str, dict[str, torch.Tensor]], layer_cache: dict[str, IOTensorsCache] = None, layer_kwargs: dict[str, tp.Any] = None, ) -> None: ...
Calibrate low-rank branches for a block of a diffusion model. Args: layer (`DiffusionModuleStruct` or `DiffusionBlockStruct`): The block to calibrate. config (`DiffusionQuantConfig`): The quantization configuration. branch_state_dict (`dict[str, dict[str, torch.Tenso...
calibrate_diffusion_block_low_rank_branch
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/weight.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/weight.py
Apache-2.0
def update_diffusion_block_weight_quantizer_state_dict( layer: DiffusionModuleStruct | DiffusionBlockStruct, config: DiffusionQuantConfig, quantizer_state_dict: dict[str, dict[str, torch.Tensor | float | None]], layer_cache: dict[str, IOTensorsCache], layer_kwargs: dict[str, tp.Any], ): """Updat...
Update the state dict of the weight quantizers for a block of a diffusion model. Args: layer (`DiffusionModuleStruct` or `DiffusionBlockStruct`): The block to update. config (`DiffusionQuantConfig`): The quantization configuration. quantizer_state_dict (`dict[str, di...
update_diffusion_block_weight_quantizer_state_dict
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/weight.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/weight.py
Apache-2.0
def quantize_diffusion_block_weights( layer: DiffusionModuleStruct | DiffusionBlockStruct, config: DiffusionQuantConfig, quantizer_state_dict: dict[str, dict[str, torch.Tensor | float | None]], layer_cache: dict[str, IOTensorsCache] = None, return_with_scale_state_dict: bool = False, ) -> dict[str, ...
Quantize the weights of a block of a diffusion model. Args: layer (`DiffusionModuleStruct` or `DiffusionBlockStruct`): The block to quantize. config (`DiffusionQuantConfig`): The quantization configuration. quantizer_state_dict (`dict[str, dict[str, torch.Tensor | fl...
quantize_diffusion_block_weights
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/weight.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/weight.py
Apache-2.0
def quantize_diffusion_weights( model: nn.Module | DiffusionModelStruct, config: DiffusionQuantConfig, quantizer_state_dict: dict[str, dict[str, torch.Tensor | float | None]] | None = None, branch_state_dict: dict[str, dict[str, torch.Tensor]] | None = None, return_with_scale_state_dict: bool = Fals...
Quantize the weights of a diffusion model. Args: model (`nn.Module` or `DiffusionModelStruct`): The diffusion model to quantize. config (`DiffusionQuantConfig`): The quantization configuration. quantizer_state_dict (`dict[str, dict[str, torch.Tensor | float | None]]`...
quantize_diffusion_weights
python
mit-han-lab/deepcompressor
deepcompressor/app/diffusion/quant/weight.py
https://github.com/mit-han-lab/deepcompressor/blob/master/deepcompressor/app/diffusion/quant/weight.py
Apache-2.0