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 _compare_weights(fsdp1_weights: dict, fsdp2_weights: dict, tolerance: float = 1e-4): """Helper function to compare weights between two models.""" assert len(fsdp1_weights) == len(fsdp2_weights), 'Number of parameters should match between FSDP1 and FSDP2' # Note that the names are not guaran...
Helper function to compare weights between two models.
_compare_weights
python
mosaicml/composer
tests/trainer/test_fsdp2.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2.py
Apache-2.0
def test_fsdp2_sync_module_state_error_when_rank_0_has_meta_params( self, world_size: int, device: str, ): """Test that FSDP2 raises an error when rank 0 has meta parameters and other ranks have CUDA parameters.""" del world_size resolved_device = 'meta' if dist.get_l...
Test that FSDP2 raises an error when rank 0 has meta parameters and other ranks have CUDA parameters.
test_fsdp2_sync_module_state_error_when_rank_0_has_meta_params
python
mosaicml/composer
tests/trainer/test_fsdp2.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2.py
Apache-2.0
def test_fsdp2_syncs_module_states_when_multiple_devices_are_used( self, world_size: int, device: str, ): """Test that FSDP2 syncs module states when multiple devices are used.""" del world_size resolved_device = device if dist.get_local_rank() == 0 else 'meta' ...
Test that FSDP2 syncs module states when multiple devices are used.
test_fsdp2_syncs_module_states_when_multiple_devices_are_used
python
mosaicml/composer
tests/trainer/test_fsdp2.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2.py
Apache-2.0
def test_fsdp2_mixed_init_does_not_break_weight_tying( self, world_size: int, device: str, model_class: type, ): """Test that FSDP2 syncs module states and doesn't break weight tying.""" del world_size resolved_device = device if dist.get_local_rank() == 0 els...
Test that FSDP2 syncs module states and doesn't break weight tying.
test_fsdp2_mixed_init_does_not_break_weight_tying
python
mosaicml/composer
tests/trainer/test_fsdp2.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2.py
Apache-2.0
def test_fsdp2_sync_module_state_aligns_with_optimizer_state( self, world_size: int, device: str, model_class: type, ): """Test that FSDP2 syncs module states and doesn't break optimizer state.""" del world_size resolved_device = device if dist.get_local_rank(...
Test that FSDP2 syncs module states and doesn't break optimizer state.
test_fsdp2_sync_module_state_aligns_with_optimizer_state
python
mosaicml/composer
tests/trainer/test_fsdp2.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2.py
Apache-2.0
def test_fsdp2_sync_module_states_mixed_init_weight_equivalence( self, world_size: int, device: str, ): """Test that FSDP2 sync_module_states produces equivalent weights to FSDP1 with mixed initialization.""" del world_size fsdp1_model = self._create_model_with_mixed...
Test that FSDP2 sync_module_states produces equivalent weights to FSDP1 with mixed initialization.
test_fsdp2_sync_module_states_mixed_init_weight_equivalence
python
mosaicml/composer
tests/trainer/test_fsdp2.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2.py
Apache-2.0
def test_fsdp2_config(): """Test that FSDP2Config read-only properties work as expected.""" # Create a config instance config = FSDP2Config() # Test reading properties (should succeed) assert config.auto_wrap is False assert config.load_monolith_rank0_only is False assert config.sync_module...
Test that FSDP2Config read-only properties work as expected.
test_fsdp2_config
python
mosaicml/composer
tests/trainer/test_fsdp2_config.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_config.py
Apache-2.0
def test_fsdp2config_from_fsdp1_multiple_invalid_attributes(): """Test FSDP2Config.from_compatible_attrs with multiple invalid attributes issues warnings for each.""" mixed_attrs = { 'activation_checkpointing': True, 'invalid_attribute1': 'value1', 'invalid_attribute2': 'value2', ...
Test FSDP2Config.from_compatible_attrs with multiple invalid attributes issues warnings for each.
test_fsdp2config_from_fsdp1_multiple_invalid_attributes
python
mosaicml/composer
tests/trainer/test_fsdp2_config.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_config.py
Apache-2.0
def test_fsdp2_with_gradscaler_inf(world_size: int): """Test FSDP2 with GradScaler can handle inf in grad.""" # Setup GradScaler for mixed precision training scaler = GradScaler(enabled=True) # Choose dtype dtype = torch.float16 model = SimpleModel().to('cuda') optimizer = torch.optim.SGD(...
Test FSDP2 with GradScaler can handle inf in grad.
test_fsdp2_with_gradscaler_inf
python
mosaicml/composer
tests/trainer/test_fsdp2_gradscaler.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_gradscaler.py
Apache-2.0
def _context(func: Callable) -> Optional[Callable]: """Decorator to run tests with models initialized on the meta device for torch version 2.6+.""" def wrapper(*args, **kwargs): with torch.device('meta'): return func(*args, **kwargs) return wrapper
Decorator to run tests with models initialized on the meta device for torch version 2.6+.
_context
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_no_tied_params(): """Test when there are no tied parameters.""" module1 = nn.Linear(10, 20) module2 = nn.Linear(20, 30) module3 = nn.Linear(30, 10) modules_to_shard, modules_with_tied_params = get_standalone_and_tied_modules([module1, module2, module3]) assert len(modules_to_shard) ==...
Test when there are no tied parameters.
test_no_tied_params
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_with_tied_params_in_single_module(): """Test when there are tied parameters within a single module.""" module = ModuleWithTiedParams() modules_to_shard, modules_with_tied_params = get_standalone_and_tied_modules([module]) # The module has tied parameters internally, but there's only one modul...
Test when there are tied parameters within a single module.
test_with_tied_params_in_single_module
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_with_tied_params_across_modules(): """Test when there are tied parameters across different modules.""" model = MultiLinearTiedModel(share_weights=True) modules: list[nn.Module] = [model.module1, model.module2, model.module3] modules_to_shard, modules_with_tied_params = get_standalone_and_tied_...
Test when there are tied parameters across different modules.
test_with_tied_params_across_modules
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_empty_module_list(): """Test with an empty list of modules.""" modules_to_shard, modules_with_tied_params = get_standalone_and_tied_modules([]) assert len(modules_to_shard) == 0 assert len(modules_with_tied_params) == 0
Test with an empty list of modules.
test_empty_module_list
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_modules_with_no_params(): """Test with modules that have no parameters.""" module1 = nn.ReLU() module2 = nn.ReLU() modules_to_shard, modules_with_tied_params = get_standalone_and_tied_modules([module1, module2]) assert len(modules_to_shard) == 0 # No modules with parameters assert le...
Test with modules that have no parameters.
test_modules_with_no_params
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_mixed_param_and_no_param_modules(): """Test with a mix of modules with and without parameters.""" module1 = nn.Linear(10, 10) module2 = nn.ReLU() module3 = nn.Linear(10, 10) modules_to_shard, modules_with_tied_params = get_standalone_and_tied_modules([module1, module2, module3]) asser...
Test with a mix of modules with and without parameters.
test_mixed_param_and_no_param_modules
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_mixed_tied_and_untied_modules(): """Test with a mix of modules with and without tied parameters.""" module1 = nn.Linear(10, 20) module2 = nn.Linear(20, 30) module3 = nn.Linear(10, 20) # Tie weights between module1 and module3 module3.weight = module1.weight module4 = nn.Linear(30, 4...
Test with a mix of modules with and without tied parameters.
test_mixed_tied_and_untied_modules
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_tied_bias_only(): """Test when only bias parameters are tied.""" module1 = nn.Linear(10, 20) module2 = nn.Linear(10, 20) # Only tie bias parameters module2.bias = module1.bias modules_to_shard, modules_with_tied_params = get_standalone_and_tied_modules([module1, module2]) assert l...
Test when only bias parameters are tied.
test_tied_bias_only
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_complex_nested_tied_params(): """Test with complex nested modules with tied parameters.""" nested1 = NestedModule() nested2 = NestedModule() # Tie a parameter between the nested modules nested2.submodule1.weight = nested1.submodule1.weight # We're testing the modules at the top level ...
Test with complex nested modules with tied parameters.
test_complex_nested_tied_params
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_legalize_param_sharing_no_sharing(): """Test when there's no parameter sharing between modules_to_shard and other modules.""" model = MultiLinearTiedModel(share_weights=False) # No sharing between these modules, so should pass without error modules_to_shard: list[nn.Module] = [model.module1, mo...
Test when there's no parameter sharing between modules_to_shard and other modules.
test_legalize_param_sharing_no_sharing
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_legalize_param_sharing_with_illegal_sharing(): """Test when there's parameter sharing between modules_to_shard and other modules.""" model = MultiLinearTiedModel(share_weights=True) # Only include module1 in modules_to_shard, not module3 modules_to_shard: list[nn.Module] = [model.module1] ...
Test when there's parameter sharing between modules_to_shard and other modules.
test_legalize_param_sharing_with_illegal_sharing
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_legalize_param_sharing_with_nested_modules(): """Test with nested modules and parameter sharing.""" model = RootModelWithNestedSharing() # Only include nested1 but not nested2 modules_to_shard: list[nn.Module] = [model.nested1] # Should raise a ValueError with pytest.raises(ValueError)...
Test with nested modules and parameter sharing.
test_legalize_param_sharing_with_nested_modules
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_legalize_param_sharing_empty_modules_to_shard(): """Test with an empty list of modules_to_shard.""" model = MultiLinearTiedModel(share_weights=False) modules_to_shard: list[nn.Module] = [] # Should not raise an error legalize_param_sharing_between_modules(model, modules_to_shard)
Test with an empty list of modules_to_shard.
test_legalize_param_sharing_empty_modules_to_shard
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_legalize_param_sharing_all_modules_to_shard(): """Test when all modules that share parameters are in modules_to_shard.""" model = MultiLinearTiedModel(share_weights=True) # Include both module1 and module3 (which share parameters) modules_to_shard: list[nn.Module] = [model.module1, model.module...
Test when all modules that share parameters are in modules_to_shard.
test_legalize_param_sharing_all_modules_to_shard
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_legalize_param_sharing_with_nested_shared_module(): """Test where a module B is a submodule of both the root model and another module A.""" class ModuleB(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(10, 15) class ModuleA(nn.Module): ...
Test where a module B is a submodule of both the root model and another module A.
test_legalize_param_sharing_with_nested_shared_module
python
mosaicml/composer
tests/trainer/test_fsdp2_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_helpers.py
Apache-2.0
def test_fsdp_wrap_separate_modules(world_size: int): """Test FSDP wrapping applied to separate, non-overlapping modules (M2, M5).""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1._fsdp_wrap = True # type: ignore m1.m2._fsdp_wrap = True # type: ignore m1.m5._fsdp_wrap = True # type: ...
Test FSDP wrapping applied to separate, non-overlapping modules (M2, M5).
test_fsdp_wrap_separate_modules
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_error_tied_siblings(world_size: int): """Test error when siblings (M3, M4) with tied weights are both marked for FSDP wrapping.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1._fsdp_wrap = True # type: ignore m1.m2.m4.weight = m1.m2.m3.weight m1.m2.m3._fsdp_wrap = T...
Test error when siblings (M3, M4) with tied weights are both marked for FSDP wrapping.
test_fsdp_wrap_error_tied_siblings
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_error_tied_sibling_one_wrapped(world_size: int): """Test error when one module (M3) marked for FSDP wrap shares weights with a sibling (M4).""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1._fsdp_wrap = True # type: ignore m1.m2.m4.weight = m1.m2.m3.weight m1.m2.m3._...
Test error when one module (M3) marked for FSDP wrap shares weights with a sibling (M4).
test_fsdp_wrap_error_tied_sibling_one_wrapped
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_ancestor_with_tied_children(world_size: int): """Test wrapping an ancestor (M2) whose children (M3, M4) have tied weights. Should succeed.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1._fsdp_wrap = True # type: ignore m1.m2._fsdp_wrap = True # type: ignore m1.m2....
Test wrapping an ancestor (M2) whose children (M3, M4) have tied weights. Should succeed.
test_fsdp_wrap_ancestor_with_tied_children
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_error_tied_across_branches_ancestor_wrap(world_size: int): """Test error when a wrapped module (M2) has a child (M3) tied to a module (M6) in another branch.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1._fsdp_wrap = True # type: ignore m1.m2._fsdp_wrap = True # type...
Test error when a wrapped module (M2) has a child (M3) tied to a module (M6) in another branch.
test_fsdp_wrap_error_tied_across_branches_ancestor_wrap
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_root_with_tied_descendants(world_size: int): """Test wrapping the root (M1) when descendants (M3, M6) have tied weights. Should succeed.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1._fsdp_wrap = True # type: ignore m1.m2.m3.weight = m1.m5.m6.weight # type: ignore ...
Test wrapping the root (M1) when descendants (M3, M6) have tied weights. Should succeed.
test_fsdp_wrap_root_with_tied_descendants
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_manual_policy_submodule_only(world_size: int): """Test manual policy application where only a submodule (M3) is wrapped.""" m1 = DeepNestedModel() m1._fsdp_wrap = False # type: ignore # Ensure root is not wrapped by default policy m1.m2._fsdp_wrap = False # type: ignore # Ensure intermed...
Test manual policy application where only a submodule (M3) is wrapped.
test_fsdp_manual_policy_submodule_only
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_parent_shares_with_child_parent_wrap(world_size: int): """Test wrapping a parent (M2) that shares weights with its child (M3). Should succeed.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1._fsdp_wrap = True # type: ignore m1.m2._fsdp_wrap = True # type: ignore m1...
Test wrapping a parent (M2) that shares weights with its child (M3). Should succeed.
test_fsdp_wrap_parent_shares_with_child_parent_wrap
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_error_parent_child_share_both_wrap(world_size: int): """Test error when parent (M2) and child (M3) share weights and both are marked for wrapping.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1._fsdp_wrap = True # type: ignore m1.m2._fsdp_wrap = True # type: ignore ...
Test error when parent (M2) and child (M3) share weights and both are marked for wrapping.
test_fsdp_wrap_error_parent_child_share_both_wrap
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_error_parent_child_share_child_wrap(world_size: int): """Test error when parent (M2) and child (M3) share weights and only the child is marked for wrapping.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1._fsdp_wrap = True # type: ignore m1.m2._fsdp_wrap = False # type...
Test error when parent (M2) and child (M3) share weights and only the child is marked for wrapping.
test_fsdp_wrap_error_parent_child_share_child_wrap
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_error_complex_sharing_parent_wrap(world_size: int): """Test error with complex sharing: parent (M2) shares with child (M3), child shares with other branch (M6), parent is wrapped.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1._fsdp_wrap = True # type: ignore m1.m2._fs...
Test error with complex sharing: parent (M2) shares with child (M3), child shares with other branch (M6), parent is wrapped.
test_fsdp_wrap_error_complex_sharing_parent_wrap
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_error_tied_across_branches_one_wrap(world_size: int): """Test error (as noted in original comments) when weights are tied (M3, M6) but only one (M6) is marked for wrap.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1._fsdp_wrap = True # type: ignore m1.m2.m3._fsdp_wrap ...
Test error (as noted in original comments) when weights are tied (M3, M6) but only one (M6) is marked for wrap.
test_fsdp_wrap_error_tied_across_branches_one_wrap
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_fn_base(world_size: int): """Test that a custom wrap function can be provided to the FSDP2Config.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() def wrap_fn(module: nn.Module): return True m1.fsdp_wrap_fn = wrap_fn # type: ignore opt = torch.optim.Adam(m1.pa...
Test that a custom wrap function can be provided to the FSDP2Config.
test_fsdp_wrap_fn_base
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_fn_invalid_keys(world_size: int): """Test that an error is raised if the wrap function returns a dict with invalid keys.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() def wrap_fn(module: nn.Module): return {'tacos': False} m1.fsdp_wrap_fn = wrap_fn # type: igno...
Test that an error is raised if the wrap function returns a dict with invalid keys.
test_fsdp_wrap_fn_invalid_keys
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_fn_target_module(world_size: int): """Test that if root module is not wrapped, the wrap function will wrap the target module.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1._fsdp_wrap = False # type: ignore def wrap_fn(module: nn.Module): return module == m1.m...
Test that if root module is not wrapped, the wrap function will wrap the target module.
test_fsdp_wrap_fn_target_module
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_fn_error_tied_siblings(world_size: int): """Test that if weights are tied and wrapped incorrectly, an error is raised.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() def wrap_fn(module: nn.Module): return module == m1.m2 m1.fsdp_wrap_fn = wrap_fn # type: ignore ...
Test that if weights are tied and wrapped incorrectly, an error is raised.
test_fsdp_wrap_fn_error_tied_siblings
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_fn_reshard_after_forward(world_size: int): """Test if the wrap function can correctly return a dictionary of kwargs.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() def wrap_fn(module: nn.Module): return {'reshard_after_forward': False} m1.fsdp_wrap_fn = wrap_fn ...
Test if the wrap function can correctly return a dictionary of kwargs.
test_fsdp_wrap_fn_reshard_after_forward
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_check_param_tying(): """Test that if weights are tied different before and after the context, an error is raised.""" m1 = DeepNestedModel() m1.m2.m3.weight = m1.m2.m4.weight def update_model(m1): m1.m2.m3.weight = m1.m5.m6.weight with pytest.raises(RuntimeError, match='Parameter t...
Test that if weights are tied different before and after the context, an error is raised.
test_check_param_tying
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_attribute_warning(world_size: int): """Test that only one warning is raised if _fsdp_wrap is set in the model instead of fsdp_wrap_fn.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1._fsdp_wrap = True # type: ignore m1.m2._fsdp_wrap = True # type: ignore m1.m5._fsd...
Test that only one warning is raised if _fsdp_wrap is set in the model instead of fsdp_wrap_fn.
test_fsdp_wrap_attribute_warning
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_wrap_attribute_not_raised_when_using_fsdp_wrap_fn(world_size: int): """Test that a warning is not raised when using fsdp_wrap_fn.""" fsdp2_config = FSDP2Config() m1 = DeepNestedModel() m1.fsdp_wrap_fn = lambda x: True # type: ignore opt = torch.optim.Adam(m1.parameters(), lr=0.01) ...
Test that a warning is not raised when using fsdp_wrap_fn.
test_fsdp_wrap_attribute_not_raised_when_using_fsdp_wrap_fn
python
mosaicml/composer
tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2_wrap_fsdp_attribute.py
Apache-2.0
def test_fsdp_with_param_groups(mixed_precision: str, device: str, reentrant: bool, world_size: int): """ Test whether an optimizer with multiple param groups maintains the same param groups when wrapped with FSDP. We assert that the model is FSDP, and that the shapes and LRs of each FSDP wrapped-pa...
Test whether an optimizer with multiple param groups maintains the same param groups when wrapped with FSDP. We assert that the model is FSDP, and that the shapes and LRs of each FSDP wrapped-parameter match the unwrapped parameter, while pointing to different underlying weight tensors
test_fsdp_with_param_groups
python
mosaicml/composer
tests/trainer/test_fsdp_param_groups.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp_param_groups.py
Apache-2.0
def test_fsdp_with_param_groups_with_subset_of_params_in_opt( mixed_precision: str, device: str, reentrant: bool, world_size: int, ): """ Test whether an optimizer with param groups and a subset of model variables in the param groups is correctly fsdp wrapped. """ num_classes = 10 #...
Test whether an optimizer with param groups and a subset of model variables in the param groups is correctly fsdp wrapped.
test_fsdp_with_param_groups_with_subset_of_params_in_opt
python
mosaicml/composer
tests/trainer/test_fsdp_param_groups.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp_param_groups.py
Apache-2.0
def get_base_trainer( parallelism_config: Optional[ParallelismConfig] = None, size: int = 4, batch_size: int = 1, num_classes: int = 2, num_features: int = 2, seed: int = 44, device: Union[torch.device, str] = 'cuda', replication: Optional[int] = None, ): """Trainer for a simple mode...
Trainer for a simple model with any parallelism_config.
get_base_trainer
python
mosaicml/composer
tests/trainer/test_tp.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_tp.py
Apache-2.0
def test_tp_forwards_backwards_correctness(world_size: int, replication: int): """Test that training with DDP, FSDP, TP-FSDP results in the same: - initial weights - forward pass - gradients - updated weights after training for a single step via manually doing forward, backward p...
Test that training with DDP, FSDP, TP-FSDP results in the same: - initial weights - forward pass - gradients - updated weights after training for a single step via manually doing forward, backward pass.
test_tp_forwards_backwards_correctness
python
mosaicml/composer
tests/trainer/test_tp.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_tp.py
Apache-2.0
def test_tp_fit_correctness(world_size: int, batch_size: int, replication: int): """Test that training with DDP, FSDP, TP-FSDP results in the same: - updated weights - loss - accuracy after training for multiple steps via trainer.fit(). """ # Initialize number of samples in the ...
Test that training with DDP, FSDP, TP-FSDP results in the same: - updated weights - loss - accuracy after training for multiple steps via trainer.fit().
test_tp_fit_correctness
python
mosaicml/composer
tests/trainer/test_tp.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_tp.py
Apache-2.0
def test_multiple_calls_to_fit( self, train_dataloader: DataLoader, model: ComposerModel, max_duration: Time[int], ): """Test that the trainer supports multiple calls to fit.""" # Note that callbacks are tested separately in tests/callbacks/test_callbacks.py #...
Test that the trainer supports multiple calls to fit.
test_multiple_calls_to_fit
python
mosaicml/composer
tests/trainer/test_trainer.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer.py
Apache-2.0
def test_wct_consistency_across_ranks( self, train_dataloader: DataLoader, model: ComposerModel, ): """Test that the wct is the same across multiple ranks""" trainer = Trainer( model=model, train_dataloader=train_dataloader, max_duration='1...
Test that the wct is the same across multiple ranks
test_wct_consistency_across_ranks
python
mosaicml/composer
tests/trainer/test_trainer.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer.py
Apache-2.0
def test_training_duration_unit( self, train_dataloader: DataLoader, model: ComposerModel, unit: TimeUnit, ): """Test that the time is correctly set, and events fire correctly, with multiple calls to fit, regardless of the time unit""" # Construct the trainer...
Test that the time is correctly set, and events fire correctly, with multiple calls to fit, regardless of the time unit
test_training_duration_unit
python
mosaicml/composer
tests/trainer/test_trainer.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer.py
Apache-2.0
def test_iteration( self, train_dataloader: DataLoader, model: ComposerModel, ): """Tests iteration is properly incremented during training when _iteration_length is set.""" # Train with max_duration set to 5 epochs with 2 epoch per iteration trainer = Trainer( ...
Tests iteration is properly incremented during training when _iteration_length is set.
test_iteration
python
mosaicml/composer
tests/trainer/test_trainer.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer.py
Apache-2.0
def create_reference_model(self, config, tmp_path_factory: pytest.TempPathFactory, *args): """Trains the reference model, and saves checkpoints.""" config = copy.deepcopy(config) # ensure the reference model is not passed to tests save_folder = tmp_path_factory.mktemp('{device}-{precision}'.fo...
Trains the reference model, and saves checkpoints.
create_reference_model
python
mosaicml/composer
tests/trainer/test_trainer.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer.py
Apache-2.0
def get_logger( self, tmp_path: pathlib.Path, num_concurrent_uploads: int = 1, file_path_format_string: Optional[str] = None, ): """Returns an object store logger that saves locally.""" remote_dir = str(tmp_path / 'object_store') os.makedirs(remote_dir, exist_...
Returns an object store logger that saves locally.
get_logger
python
mosaicml/composer
tests/trainer/test_trainer.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer.py
Apache-2.0
def test_empty_train_dataloader(self): """Test the case where the train dataset has no samples.""" with pytest.raises(UserWarning, match='No batches were trained for global rank'): train_dataloader = self._get_dataloader(0) model = SimpleModel() trainer = Trainer( ...
Test the case where the train dataset has no samples.
test_empty_train_dataloader
python
mosaicml/composer
tests/trainer/test_trainer.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer.py
Apache-2.0
def test_empty_eval_dataloader(self): """Test the case where the eval dataset has no samples.""" with pytest.raises(UserWarning, match='No batches were evaluated for global rank'): train_dataloader = self._get_dataloader(1) eval_dataloader = self._get_dataloader(0) mo...
Test the case where the eval dataset has no samples.
test_empty_eval_dataloader
python
mosaicml/composer
tests/trainer/test_trainer.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer.py
Apache-2.0
def test_eval_token_interval( tiny_bert_tokenizer, eval_interval: str, batch_size: int, sequence_length: int, tmp_path: pathlib.Path, ): """Tests that the trainer evaluates the model at the correct intervals when using token-based intervals.""" tokens_per_batch = batch_size * sequence_length...
Tests that the trainer evaluates the model at the correct intervals when using token-based intervals.
test_eval_token_interval
python
mosaicml/composer
tests/trainer/test_trainer_eval.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer_eval.py
Apache-2.0
def test_eval_sample_interval( tiny_bert_tokenizer, eval_interval: str, batch_size: int, sequence_length: int, tmp_path: pathlib.Path, ): """Tests that the trainer evaluates the model at the correct intervals when using sample-based intervals.""" max_duration_time = Time.from_timestring('5ba...
Tests that the trainer evaluates the model at the correct intervals when using sample-based intervals.
test_eval_sample_interval
python
mosaicml/composer
tests/trainer/test_trainer_eval.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer_eval.py
Apache-2.0
def test_eval_dur_interval_token_max( tiny_bert_tokenizer, eval_interval: str, max_duration: str, batch_size: int, sequence_length: int, ): """Tests that the trainer evaluates the model at the correct intervals when using duration-based intervals, with max_duration in tokens.""" max_duration...
Tests that the trainer evaluates the model at the correct intervals when using duration-based intervals, with max_duration in tokens.
test_eval_dur_interval_token_max
python
mosaicml/composer
tests/trainer/test_trainer_eval.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer_eval.py
Apache-2.0
def test_eval_at_fit_end( eval_interval: Union[str, Time, int], max_duration: str, eval_at_fit_end: bool, expected_eval_start_calls: int, expected_eval_batch_start_calls: int, ): """Test the `eval_subset_num_batches` and `eval_interval` works when specified on init.""" # Construct the train...
Test the `eval_subset_num_batches` and `eval_interval` works when specified on init.
test_eval_at_fit_end
python
mosaicml/composer
tests/trainer/test_trainer_eval.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer_eval.py
Apache-2.0
def test_eval_params_evaluator(): """Test the `eval_subset_num_batches` and `eval_interval` works when specified as part of an evaluator.""" # Construct the trainer train_dataset = RandomClassificationDataset() train_dataloader = DataLoader(train_dataset, sampler=dist.get_sampler(train_dataset)) eva...
Test the `eval_subset_num_batches` and `eval_interval` works when specified as part of an evaluator.
test_eval_params_evaluator
python
mosaicml/composer
tests/trainer/test_trainer_eval.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer_eval.py
Apache-2.0
def test_infinite_eval_dataloader(eval_subset_num_batches, success): """Test the `eval_subset_num_batches` is required with infinite dataloader.""" # Construct the trainer train_dataset = RandomClassificationDataset() train_dataloader = DataLoader(train_dataset, sampler=dist.get_sampler(train_dataset)) ...
Test the `eval_subset_num_batches` is required with infinite dataloader.
test_infinite_eval_dataloader
python
mosaicml/composer
tests/trainer/test_trainer_eval.py
https://github.com/mosaicml/composer/blob/master/tests/trainer/test_trainer_eval.py
Apache-2.0
def test_safe_format_name_with_dist(monkeypatch: pytest.MonkeyPatch, world_size): """node rank deleted, but not in format string, so format should complete.""" vars = ['run_name', 'world_size'] format_str = ','.join(f'{x}={{{x}}}' for x in vars) expected_str = 'run_name=awesome_run,world_size=2' mo...
node rank deleted, but not in format string, so format should complete.
test_safe_format_name_with_dist
python
mosaicml/composer
tests/utils/test_file_helpers.py
https://github.com/mosaicml/composer/blob/master/tests/utils/test_file_helpers.py
Apache-2.0
def mock_mlflow_client_list_artifacts(*args, **kwargs): """Mock behavior for MlflowClient.list_artifacts(). Behaves as if artifacts are stored under the following structure: - dir1/ - a.txt - b.txt - dir2/ - c.txt - dir3/ -...
Mock behavior for MlflowClient.list_artifacts(). Behaves as if artifacts are stored under the following structure: - dir1/ - a.txt - b.txt - dir2/ - c.txt - dir3/ - d.txt
mock_mlflow_client_list_artifacts
python
mosaicml/composer
tests/utils/object_store/test_mlflow_object_store.py
https://github.com/mosaicml/composer/blob/master/tests/utils/object_store/test_mlflow_object_store.py
Apache-2.0
def test_s3_object_store_multi_threads(tmp_path: pathlib.Path, s3_bucket: str): """Test to verify that we do not hit https://github.com/boto/boto3/issues/1592.""" pytest.importorskip('boto3') threads = [] # Manually tried fewer threads; it seems that 100 is needed to reliably re-produce the bug for ...
Test to verify that we do not hit https://github.com/boto/boto3/issues/1592.
test_s3_object_store_multi_threads
python
mosaicml/composer
tests/utils/object_store/test_s3_object_store.py
https://github.com/mosaicml/composer/blob/master/tests/utils/object_store/test_s3_object_store.py
Apache-2.0
def _get_raw_movielens_data(): """ Return the raw lines of the train and test files. """ path = _get_movielens_path() if not os.path.isfile(path): _download_movielens(path) with zipfile.ZipFile(path) as datafile: return ( datafile.read("ml-100k/ua.base").decode().s...
Return the raw lines of the train and test files.
_get_raw_movielens_data
python
lyst/lightfm
examples/movielens/data.py
https://github.com/lyst/lightfm/blob/master/examples/movielens/data.py
Apache-2.0
def _build_interaction_matrix(rows, cols, data): """ Build the training matrix (no_users, no_items), with ratings >= 4.0 being marked as positive and the rest as negative. """ mat = sp.lil_matrix((rows, cols), dtype=np.int32) for uid, iid, rating, timestamp in data: if rating >= 4....
Build the training matrix (no_users, no_items), with ratings >= 4.0 being marked as positive and the rest as negative.
_build_interaction_matrix
python
lyst/lightfm
examples/movielens/data.py
https://github.com/lyst/lightfm/blob/master/examples/movielens/data.py
Apache-2.0
def _get_movie_raw_metadata(): """ Get raw lines of the genre file. """ path = _get_movielens_path() if not os.path.isfile(path): _download_movielens(path) with zipfile.ZipFile(path) as datafile: return datafile.read("ml-100k/u.item").decode(errors="ignore").split("\n")
Get raw lines of the genre file.
_get_movie_raw_metadata
python
lyst/lightfm
examples/movielens/data.py
https://github.com/lyst/lightfm/blob/master/examples/movielens/data.py
Apache-2.0
def get_movielens_item_metadata(use_item_ids): """ Build a matrix of genre features (no_items, no_features). If use_item_ids is True, per-item features will also be used. """ features = {} genre_set = set() for line in _get_movie_raw_metadata(): if not line: continue ...
Build a matrix of genre features (no_items, no_features). If use_item_ids is True, per-item features will also be used.
get_movielens_item_metadata
python
lyst/lightfm
examples/movielens/data.py
https://github.com/lyst/lightfm/blob/master/examples/movielens/data.py
Apache-2.0
def random_train_test_split(interactions, test_percentage=0.2, random_state=None): """ Randomly split interactions between training and testing. This function takes an interaction set and splits it into two disjoint sets, a training set and a test set. Note that no effort is made to make sure that ...
Randomly split interactions between training and testing. This function takes an interaction set and splits it into two disjoint sets, a training set and a test set. Note that no effort is made to make sure that all items and users with interactions in the test set also have interactions in the ...
random_train_test_split
python
lyst/lightfm
lightfm/cross_validation.py
https://github.com/lyst/lightfm/blob/master/lightfm/cross_validation.py
Apache-2.0
def fit(self, users, items, user_features=None, item_features=None): """ Fit the user/item id and feature name mappings. Calling fit the second time will reset existing mappings. Parameters ---------- users: iterable of user ids items: iterable of item ids ...
Fit the user/item id and feature name mappings. Calling fit the second time will reset existing mappings. Parameters ---------- users: iterable of user ids items: iterable of item ids user_features: iterable of user features, optional item_features: it...
fit
python
lyst/lightfm
lightfm/data.py
https://github.com/lyst/lightfm/blob/master/lightfm/data.py
Apache-2.0
def fit_partial( self, users=None, items=None, user_features=None, item_features=None ): """ Fit the user/item id and feature name mappings. Calling fit the second time will add new entries to existing mappings. Parameters ---------- users: iterable of user...
Fit the user/item id and feature name mappings. Calling fit the second time will add new entries to existing mappings. Parameters ---------- users: iterable of user ids, optional items: iterable of item ids, optional user_features: iterable of user features, o...
fit_partial
python
lyst/lightfm
lightfm/data.py
https://github.com/lyst/lightfm/blob/master/lightfm/data.py
Apache-2.0
def build_interactions(self, data): """ Build an interaction matrix. Two matrices will be returned: a (num_users, num_items) COO matrix with interactions, and a (num_users, num_items) matrix with the corresponding interaction weights. Parameters ---------- ...
Build an interaction matrix. Two matrices will be returned: a (num_users, num_items) COO matrix with interactions, and a (num_users, num_items) matrix with the corresponding interaction weights. Parameters ---------- data: iterable of (user_id, item_id) or (us...
build_interactions
python
lyst/lightfm
lightfm/data.py
https://github.com/lyst/lightfm/blob/master/lightfm/data.py
Apache-2.0
def build_user_features(self, data, normalize=True): """ Build a user features matrix out of an iterable of the form (user id, [list of feature names]) or (user id, {feature name: feature weight}). Parameters ---------- data: iterable of the form (user id, [...
Build a user features matrix out of an iterable of the form (user id, [list of feature names]) or (user id, {feature name: feature weight}). Parameters ---------- data: iterable of the form (user id, [list of feature names]) or (user id, {feature name: ...
build_user_features
python
lyst/lightfm
lightfm/data.py
https://github.com/lyst/lightfm/blob/master/lightfm/data.py
Apache-2.0
def build_item_features(self, data, normalize=True): """ Build a item features matrix out of an iterable of the form (item id, [list of feature names]) or (item id, {feature name: feature weight}). Parameters ---------- data: iterable of the form (item id, [...
Build a item features matrix out of an iterable of the form (item id, [list of feature names]) or (item id, {feature name: feature weight}). Parameters ---------- data: iterable of the form (item id, [list of feature names]) or (item id, {feature name: ...
build_item_features
python
lyst/lightfm
lightfm/data.py
https://github.com/lyst/lightfm/blob/master/lightfm/data.py
Apache-2.0
def mapping(self): """ Return the constructed mappings. Invert these to map internal indices to external ids. Returns ------- (user id map, user feature map, item id map, item feature map): tuple of dictionaries """ return ( self._user_id_m...
Return the constructed mappings. Invert these to map internal indices to external ids. Returns ------- (user id map, user feature map, item id map, item feature map): tuple of dictionaries
mapping
python
lyst/lightfm
lightfm/data.py
https://github.com/lyst/lightfm/blob/master/lightfm/data.py
Apache-2.0
def fit( self, interactions, user_features=None, item_features=None, sample_weight=None, epochs=1, num_threads=1, verbose=False, ): """ Fit the model. For details on how to use feature matrices, see the documentation on...
Fit the model. For details on how to use feature matrices, see the documentation on the :class:`lightfm.LightFM` class. Arguments --------- interactions: np.float32 coo_matrix of shape [n_users, n_items] the matrix containing user-item intera...
fit
python
lyst/lightfm
lightfm/lightfm.py
https://github.com/lyst/lightfm/blob/master/lightfm/lightfm.py
Apache-2.0
def fit_partial( self, interactions, user_features=None, item_features=None, sample_weight=None, epochs=1, num_threads=1, verbose=False, ): """ Fit the model. Fit the model. Unlike fit, repeated calls to this method will ...
Fit the model. Fit the model. Unlike fit, repeated calls to this method will cause training to resume from the current model state. For details on how to use feature matrices, see the documentation on the :class:`lightfm.LightFM` class. Arguments --------- ...
fit_partial
python
lyst/lightfm
lightfm/lightfm.py
https://github.com/lyst/lightfm/blob/master/lightfm/lightfm.py
Apache-2.0
def predict( self, user_ids, item_ids, item_features=None, user_features=None, num_threads=1 ): """ Compute the recommendation score for user-item pairs. For details on how to use feature matrices, see the documentation on the :class:`lightfm.LightFM` class. Argumen...
Compute the recommendation score for user-item pairs. For details on how to use feature matrices, see the documentation on the :class:`lightfm.LightFM` class. Arguments --------- user_ids: integer or np.int32 array of shape [n_pairs,] single user id or an...
predict
python
lyst/lightfm
lightfm/lightfm.py
https://github.com/lyst/lightfm/blob/master/lightfm/lightfm.py
Apache-2.0
def predict_rank( self, test_interactions, train_interactions=None, item_features=None, user_features=None, num_threads=1, check_intersections=True, ): """ Predict the rank of selected interactions. Computes recommendation rankings acro...
Predict the rank of selected interactions. Computes recommendation rankings across all items for every user in interactions and calculates the rank of all non-zero entries in the recommendation ranking, with 0 meaning the top of the list (most recommended) and n_items - 1 being ...
predict_rank
python
lyst/lightfm
lightfm/lightfm.py
https://github.com/lyst/lightfm/blob/master/lightfm/lightfm.py
Apache-2.0
def get_item_representations(self, features=None): """ Get the latent representations for items given model and features. Arguments --------- features: np.float32 csr_matrix of shape [n_items, n_item_features], optional Each row contains that item's weights over fe...
Get the latent representations for items given model and features. Arguments --------- features: np.float32 csr_matrix of shape [n_items, n_item_features], optional Each row contains that item's weights over features. An identity matrix will be used if not su...
get_item_representations
python
lyst/lightfm
lightfm/lightfm.py
https://github.com/lyst/lightfm/blob/master/lightfm/lightfm.py
Apache-2.0
def get_user_representations(self, features=None): """ Get the latent representations for users given model and features. Arguments --------- features: np.float32 csr_matrix of shape [n_users, n_user_features], optional Each row contains that user's weights over fe...
Get the latent representations for users given model and features. Arguments --------- features: np.float32 csr_matrix of shape [n_users, n_user_features], optional Each row contains that user's weights over features. An identity matrix will be used if not su...
get_user_representations
python
lyst/lightfm
lightfm/lightfm.py
https://github.com/lyst/lightfm/blob/master/lightfm/lightfm.py
Apache-2.0
def get_params(self, deep=True): """ Get parameters for this estimator. Arguments --------- deep: boolean, optional If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- ...
Get parameters for this estimator. Arguments --------- deep: boolean, optional If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- params : mapping of string to any ...
get_params
python
lyst/lightfm
lightfm/lightfm.py
https://github.com/lyst/lightfm/blob/master/lightfm/lightfm.py
Apache-2.0
def set_params(self, **params): """ Set the parameters of this estimator. Returns ------- self """ valid_params = self.get_params() for key, value in params.items(): if key not in valid_params: raise ValueError( ...
Set the parameters of this estimator. Returns ------- self
set_params
python
lyst/lightfm
lightfm/lightfm.py
https://github.com/lyst/lightfm/blob/master/lightfm/lightfm.py
Apache-2.0
def fetch_movielens( data_home=None, indicator_features=True, genre_features=False, min_rating=0.0, download_if_missing=True, ): """ Fetch the `Movielens 100k dataset <http://grouplens.org/datasets/movielens/100k/>`_. The dataset contains 100,000 interactions from 1000 users on 1700 mov...
Fetch the `Movielens 100k dataset <http://grouplens.org/datasets/movielens/100k/>`_. The dataset contains 100,000 interactions from 1000 users on 1700 movies, and is exhaustively described in its `README <http://files.grouplens.org/datasets/movielens/ml-100k-README.txt>`_. Parameters --------...
fetch_movielens
python
lyst/lightfm
lightfm/datasets/movielens.py
https://github.com/lyst/lightfm/blob/master/lightfm/datasets/movielens.py
Apache-2.0
def fetch_stackexchange( dataset, test_set_fraction=0.2, min_training_interactions=1, data_home=None, indicator_features=True, tag_features=False, download_if_missing=True, ): """ Fetch a dataset from the `StackExchange network <http://stackexchange.com/>`_. The datasets contain...
Fetch a dataset from the `StackExchange network <http://stackexchange.com/>`_. The datasets contain users answering questions: an interaction is defined as a user answering a given question. The following datasets from the StackExchange network are available: - CrossValidated: From stats.stackex...
fetch_stackexchange
python
lyst/lightfm
lightfm/datasets/stackexchange.py
https://github.com/lyst/lightfm/blob/master/lightfm/datasets/stackexchange.py
Apache-2.0
def test_movielens_both_accuracy(): """ Accuracy with both genre metadata and item-specific features should be no worse than with just item-specific features (though more training may be necessary). """ item_features = fetch_movielens(indicator_features=True, genre_features=True)[ "item...
Accuracy with both genre metadata and item-specific features should be no worse than with just item-specific features (though more training may be necessary).
test_movielens_both_accuracy
python
lyst/lightfm
tests/test_movielens.py
https://github.com/lyst/lightfm/blob/master/tests/test_movielens.py
Apache-2.0
def setModelPath(self, path: str): """ 'setModelPath()' function is required and is used to set the file path to the model adopted from the list of the available 4 model types. The model path must correspond to the model type set for the classification instance object. :param model_path:...
'setModelPath()' function is required and is used to set the file path to the model adopted from the list of the available 4 model types. The model path must correspond to the model type set for the classification instance object. :param model_path: :return:
setModelPath
python
OlafenwaMoses/ImageAI
imageai/Classification/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Classification/__init__.py
MIT
def setModelTypeAsResNet50(self): """ 'setModelTypeAsResNet50()' is used to set the model type to the ResNet50 model. :return: """ if self.__model_type == None: self.__model_type = "resnet50"
'setModelTypeAsResNet50()' is used to set the model type to the ResNet50 model. :return:
setModelTypeAsResNet50
python
OlafenwaMoses/ImageAI
imageai/Classification/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Classification/__init__.py
MIT
def setModelTypeAsDenseNet121(self): """ 'setModelTypeAsDenseNet121()' is used to set the model type to the DenseNet121 model. :return: """ if self.__model_type == None: self.__model_type = "densenet121"
'setModelTypeAsDenseNet121()' is used to set the model type to the DenseNet121 model. :return:
setModelTypeAsDenseNet121
python
OlafenwaMoses/ImageAI
imageai/Classification/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Classification/__init__.py
MIT
def setModelTypeAsInceptionV3(self): """ 'setModelTypeAsInceptionV3()' is used to set the model type to the InceptionV3 model. :return: """ if self.__model_type == None: self.__model_type = "inceptionv3"
'setModelTypeAsInceptionV3()' is used to set the model type to the InceptionV3 model. :return:
setModelTypeAsInceptionV3
python
OlafenwaMoses/ImageAI
imageai/Classification/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Classification/__init__.py
MIT
def setModelTypeAsMobileNetV2(self): """ 'setModelTypeAsMobileNetV2()' is used to set the model type to the MobileNetV2 model. :return: """ if self.__model_type == None: self.__model_type = "mobilenetv2"
'setModelTypeAsMobileNetV2()' is used to set the model type to the MobileNetV2 model. :return:
setModelTypeAsMobileNetV2
python
OlafenwaMoses/ImageAI
imageai/Classification/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Classification/__init__.py
MIT
def useCPU(self): """ Used to force classification to be done on CPU. By default, classification will occur on GPU compute if available else CPU compute. """ self.__device = "cpu" if self.__model_loaded: self.__model_loaded = False self.loadModel()
Used to force classification to be done on CPU. By default, classification will occur on GPU compute if available else CPU compute.
useCPU
python
OlafenwaMoses/ImageAI
imageai/Classification/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Classification/__init__.py
MIT
def loadModel(self): """ 'loadModel()' function is used to load the model weights into the model architecture from the file path defined in the setModelPath() function. :return: """ if not self.__model_loaded: try: if self.__model_path == None:...
'loadModel()' function is used to load the model weights into the model architecture from the file path defined in the setModelPath() function. :return:
loadModel
python
OlafenwaMoses/ImageAI
imageai/Classification/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Classification/__init__.py
MIT
def classifyImage(self, image_input: Union[str, np.ndarray, Image.Image], result_count: int=5) -> Tuple[List[str], List[float]]: """ 'classifyImage()' function is used to classify a given image by receiving the following arguments: * image_input: file path, numpy array or PIL image of the i...
'classifyImage()' function is used to classify a given image by receiving the following arguments: * image_input: file path, numpy array or PIL image of the input image. * result_count (optional) , the number of classifications to be sent which must be whole numbers between ...
classifyImage
python
OlafenwaMoses/ImageAI
imageai/Classification/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Classification/__init__.py
MIT
def setDataDirectory(self, data_directory : str = "") -> None: """ Sets the directory that contains the training and test dataset. The data directory should contain 'train' and 'test' subdirectories for the training and test datasets. In each of these subdirectories, each object must ha...
Sets the directory that contains the training and test dataset. The data directory should contain 'train' and 'test' subdirectories for the training and test datasets. In each of these subdirectories, each object must have a dedicated folder and the folder containing images for the object. ...
setDataDirectory
python
OlafenwaMoses/ImageAI
imageai/Classification/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Classification/Custom/__init__.py
MIT
def setModelTypeAsDenseNet121(self) -> None: """ 'setModelTypeAsDenseNet()' is used to set the model type to the DenseNet model. :return: """ self.__model_type = "densenet121" self.__training_params = densenet121_train_params()
'setModelTypeAsDenseNet()' is used to set the model type to the DenseNet model. :return:
setModelTypeAsDenseNet121
python
OlafenwaMoses/ImageAI
imageai/Classification/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Classification/Custom/__init__.py
MIT
def trainModel( self, num_experiments : int = 100, batch_size : int = 8, model_directory : str = None, transfer_from_model: str = None, verbose : bool = True ) -> None: """ 'trainModel()...
'trainModel()' function starts the model actual training. It accepts the following values: - num_experiments: Also known as epochs, is the number of times the network will process all the images in the training dataset - batch_size: The number of image data that will be loaded into memory at on...
trainModel
python
OlafenwaMoses/ImageAI
imageai/Classification/Custom/__init__.py
https://github.com/OlafenwaMoses/ImageAI/blob/master/imageai/Classification/Custom/__init__.py
MIT