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 verify_shape_image(orig: Image.Image, new: Image.Image, p_row: float, p_col: float) -> None:
"""Verify the shape of a transformed PIL Image."""
H_o, W_o = orig.height, orig.width
H_n, W_n = new.height, new.width
H_t = int((1 - p_row) * H_o)
W_t = int((1 - p_col) * W_o)
assert (H_n, W_n) ==... | Verify the shape of a transformed PIL Image. | verify_shape_image | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def verify_shape_image_pair(
orig_sample: tuple[Image.Image, Image.Image],
new_sample: tuple[torch.Tensor, torch.Tensor] | tuple[Image.Image, Image.Image],
p_row: float,
p_col: float,
):
"""Verify the shape of a pair of transformed PIL images."""
H_o, W_o = orig_sample[0].height, orig_sample[0].... | Verify the shape of a pair of transformed PIL images. | verify_shape_image_pair | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def verify_shape_tensor(orig: torch.Tensor, new: torch.Tensor, p_row: float, p_col: float) -> None:
"""Verify the shape of a transformed image tensor."""
C, H_o, W_o = orig.shape
H_t = int((1 - p_row) * H_o)
W_t = int((1 - p_col) * W_o)
assert new.shape == (C, H_t, W_t), f'Image tensor shape misma... | Verify the shape of a transformed image tensor. | verify_shape_tensor | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def verify_shape_batch(orig: torch.Tensor, new: torch.Tensor, p_row: float, p_col: float) -> None:
"""Verify the shape of a transformed batch of images."""
N, C, H_o, W_o = orig.shape
H_t = int((1 - p_row) * H_o)
W_t = int((1 - p_col) * W_o)
assert new.shape == (N, C, H_t, W_t), f'Image batch shap... | Verify the shape of a transformed batch of images. | verify_shape_batch | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def test_single_image_drop_size(self, fake_image: Image.Image, p_row: float, p_col: float):
"""Test application to single PIL image."""
transform = ColOutTransform(p_row, p_col)
new_image = transform(fake_image)
assert isinstance(new_image, Image.Image)
verify_shape_image(fake_im... | Test application to single PIL image. | test_single_image_drop_size | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def test_image_pair_drop_size(self, fake_image: Image.Image, p_row: float, p_col: float):
"""Test application to a 2-tuple of PIL images."""
transform = ColOutTransform(p_row, p_col)
orig_sample = (fake_image, fake_image)
new_sample = transform(orig_sample)
assert isinstance(new_... | Test application to a 2-tuple of PIL images. | test_image_pair_drop_size | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def test_rectangular_image(self, fake_image: Image.Image, p_row: float, p_col: float):
"""Test application to a rectangular PIL image."""
transform = ColOutTransform(p_row, p_col)
new_image = transform(fake_image)
verify_shape_image(fake_image, new_image, p_row, p_col) # type: ignore | Test application to a rectangular PIL image. | test_rectangular_image | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def test_single_image_tensor_drop_size(self, fake_image_tensor: torch.Tensor, p_row: float, p_col: float):
"""Test application to a single torch image tensor."""
transform = ColOutTransform(p_row, p_col)
new_image = transform(fake_image_tensor)
verify_shape_tensor(fake_image_tensor, new_... | Test application to a single torch image tensor. | test_single_image_tensor_drop_size | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def test_reproducibility_image(self, fake_image_tensor: torch.Tensor, p_row: float, p_col: float):
"""Test that transform is reproducible given the same seed."""
transform_1 = ColOutTransform(p_row, p_col)
transform_2 = ColOutTransform(p_row, p_col)
torch.manual_seed(42)
new_ima... | Test that transform is reproducible given the same seed. | test_reproducibility_image | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def test_reproducibility_batch(self, fake_image_batch: torch.Tensor, p_row: float, p_col: float):
"""Test that batch augmentation is reproducible given the same seed."""
transform_1 = functools.partial(colout_batch, p_row=p_row, p_col=p_col)
transform_2 = functools.partial(colout_batch, p_row=p_... | Test that batch augmentation is reproducible given the same seed. | test_reproducibility_batch | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def test_batch_drop_size(self, fake_image_batch: torch.Tensor, p_row: float, p_col: float):
"""Test application to a batch of images."""
colout = functools.partial(colout_batch, p_row=p_row, p_col=p_col)
new_batch = colout(fake_image_batch)
assert isinstance(new_batch, torch.Tensor)
... | Test application to a batch of images. | test_batch_drop_size | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def test_rectangle_batch_drop_size(self, fake_image_batch: torch.Tensor, p_row: float, p_col: float):
"""Test that unequal values of p_row and p_col work properly."""
colout = functools.partial(colout_batch, p_row=p_row, p_col=p_col)
new_batch = colout(fake_image_batch)
assert isinstance... | Test that unequal values of p_row and p_col work properly. | test_rectangle_batch_drop_size | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def test_apply_batch(
self,
fake_image_batch: torch.Tensor,
colout_algorithm: ColOut,
minimal_state: State,
empty_logger: Logger,
):
"""Applies the algorithm to a fake batch."""
p_row = colout_algorithm.p_row
p_col = colout_algorithm.p_col
min... | Applies the algorithm to a fake batch. | test_apply_batch | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def test_apply_batch_pair(
self,
fake_image_batch: torch.Tensor,
colout_algorithm: ColOut,
minimal_state: State,
empty_logger: Logger,
):
"""Applies batch ColOut to 2-tuple of images."""
p_row = colout_algorithm.p_row
p_col = colout_algorithm.p_col
... | Applies batch ColOut to 2-tuple of images. | test_apply_batch_pair | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def test_apply_sample(self, colout_algorithm: ColOut, minimal_state: State, empty_logger: Logger):
"""Test that augmentation is added to dataset and functioning properly."""
p_row = colout_algorithm.p_row
p_col = colout_algorithm.p_col
dataset = RandomImageDataset(is_PIL=True)
d... | Test that augmentation is added to dataset and functioning properly. | test_apply_sample | python | mosaicml/composer | tests/algorithms/test_colout.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_colout.py | Apache-2.0 |
def test_factorize_edge_cases(shapes, factorize_task, already_factorized):
"""Test edge cases regarding current and requested matrix shapes."""
C_in, C_latent_now, C_latent_new, C_out = shapes
factorize_task.C_in = C_in
factorize_task.C_latent_now = C_latent_now
factorize_task.C_latent_new = C_laten... | Test edge cases regarding current and requested matrix shapes. | test_factorize_edge_cases | python | mosaicml/composer | tests/algorithms/test_factorize_core.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_factorize_core.py | Apache-2.0 |
def test_factorize_more_dims_better(factorize_task, already_factorized):
"""More latent dimensions should yield nonincreasing error."""
prev_nmse = np.inf
for C_latent_new in [1, 4, 16, 32]:
factorize_task.C_latent_new = C_latent_new
maybe_nmse = _check_factorization(factorize_task, prev_nms... | More latent dimensions should yield nonincreasing error. | test_factorize_more_dims_better | python | mosaicml/composer | tests/algorithms/test_factorize_core.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_factorize_core.py | Apache-2.0 |
def test_factorize_more_iters_better(factorize_task, already_factorized):
"""More optimization iters should yield nonincreasing error."""
prev_nmse = np.inf
for n_iters in [0, 1, 2, 4]:
factorize_task.n_iters = n_iters
maybe_nmse = _check_factorization(factorize_task, prev_nmse, already_fact... | More optimization iters should yield nonincreasing error. | test_factorize_more_iters_better | python | mosaicml/composer | tests/algorithms/test_factorize_core.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_factorize_core.py | Apache-2.0 |
def test_apply_agc_does_not_error(model_with_grads):
"""This test is just to ensure that no errors are raised.
Accuracy of the AGC calculations are tested in other tests.
"""
model = model_with_grads
# Call apply_agc. If this function returns then we know that nothing errored out.
_apply_agc(m... | This test is just to ensure that no errors are raised.
Accuracy of the AGC calculations are tested in other tests.
| test_apply_agc_does_not_error | python | mosaicml/composer | tests/algorithms/test_gradient_clipping.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_gradient_clipping.py | Apache-2.0 |
def _generate_tensors_classification(batch_size: int, num_classes: int):
"""Helper functions to generate input, target pairs for image classification (1d indices)"""
N = batch_size
C = num_classes
target_indices = torch.randint(0, C, [N])
target_onehot = F.one_hot(target_indices, num_classes=C)
... | Helper functions to generate input, target pairs for image classification (1d indices) | _generate_tensors_classification | python | mosaicml/composer | tests/algorithms/test_label_smoothing.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_label_smoothing.py | Apache-2.0 |
def _generate_tensors_segmentation(batch_size: int, num_classes: int, H: int, W: int):
"""Helper functions to generate input, target pairs for image segmentation (2d indices)"""
N = batch_size
C = num_classes
target_indices = torch.randint(0, C, (N, H, W))
target_onehot = F.one_hot(target_indices, ... | Helper functions to generate input, target pairs for image segmentation (2d indices) | _generate_tensors_segmentation | python | mosaicml/composer | tests/algorithms/test_label_smoothing.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_label_smoothing.py | Apache-2.0 |
def _generate_state(request: pytest.FixtureRequest, model_cls, epoch: int, max_epochs: int):
"""Generates a state and fast forwards the timestamp by epochs."""
model = model_cls()
device = None
for item in request.session.items:
device = DeviceCPU() if item.get_closest_marker('gpu') is None else... | Generates a state and fast forwards the timestamp by epochs. | _generate_state | python | mosaicml/composer | tests/algorithms/test_layer_freezing.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_layer_freezing.py | Apache-2.0 |
def check_scaled_shape(orig: torch.Tensor, scaled: torch.Tensor, scale_factor: float) -> bool:
"""Asserts that the scaled shape is correct, given orig shape and scale_factor."""
N, C, H, W = orig.shape
Hc = int(scale_factor * H)
Wc = int(scale_factor * W)
return scaled.shape == (N, C, Hc, Wc) | Asserts that the scaled shape is correct, given orig shape and scale_factor. | check_scaled_shape | python | mosaicml/composer | tests/algorithms/test_progressive_resizing.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_progressive_resizing.py | Apache-2.0 |
def test_resize_noop(self, X, y, mode):
"""Tests that no operation is performed when scale_factor == 1."""
Xc, _ = resize_batch(X, y, 1.0, mode, resize_targets=False)
assert X is Xc | Tests that no operation is performed when scale_factor == 1. | test_resize_noop | python | mosaicml/composer | tests/algorithms/test_progressive_resizing.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_progressive_resizing.py | Apache-2.0 |
def test_without_target(self, X, y):
"""Test that resizing works properly with no target present."""
try:
resize_batch(X, y, 1.0, 'crop', resize_targets=False)
except:
pytest.fail('apply_progressive_resizing failed with y == None') | Test that resizing works properly with no target present. | test_without_target | python | mosaicml/composer | tests/algorithms/test_progressive_resizing.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_progressive_resizing.py | Apache-2.0 |
def test_resize_batch_shape(self, X: torch.Tensor, y: torch.Tensor, mode: str, scale_factor: float):
"""Test scaling works for different input shapes."""
Xc, _ = resize_batch(X, y, scale_factor, mode, resize_targets=False)
assert check_scaled_shape(X, Xc, scale_factor) | Test scaling works for different input shapes. | test_resize_batch_shape | python | mosaicml/composer | tests/algorithms/test_progressive_resizing.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_progressive_resizing.py | Apache-2.0 |
def test_resize_outputs_crop(self, X: torch.Tensor, scale_factor: float):
"""Test that resizing outputs in crop mode gives the right targets."""
xc, yc = resize_batch(X, X, scale_factor, 'crop', resize_targets=True)
assert torch.equal(xc, yc) | Test that resizing outputs in crop mode gives the right targets. | test_resize_outputs_crop | python | mosaicml/composer | tests/algorithms/test_progressive_resizing.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_progressive_resizing.py | Apache-2.0 |
def test_resize_outputs_different_shape(self, X, y, scale_factor: float, mode: str):
"""Test that resizing works when X and y have different shapes."""
_, yc = resize_batch(X, y, scale_factor, mode, resize_targets=True)
assert check_scaled_shape(y, yc, scale_factor) | Test that resizing works when X and y have different shapes. | test_resize_outputs_different_shape | python | mosaicml/composer | tests/algorithms/test_progressive_resizing.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_progressive_resizing.py | Apache-2.0 |
def test_apply(
self,
epoch_frac: float,
X: torch.Tensor,
y: torch.Tensor,
pr_algorithm: ProgressiveResizing,
minimal_state: State,
empty_logger: Logger,
):
"""Test apply at different epoch fractions (fraction of max epochs)"""
assert minimal_s... | Test apply at different epoch fractions (fraction of max epochs) | test_apply | python | mosaicml/composer | tests/algorithms/test_progressive_resizing.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_progressive_resizing.py | Apache-2.0 |
def compare_models(model_1: torch.nn.Module, model_2: torch.nn.Module, is_equal: bool = True):
"""Check if two models are the same.
To check equivalence, we first verify the modules are the same in each model by checking the
list of attributes for each module. This checks if the same set of modules are use... | Check if two models are the same.
To check equivalence, we first verify the modules are the same in each model by checking the
list of attributes for each module. This checks if the same set of modules are used and if any
module has been marked by adding an attribute. Next, we directly iterate over the sta... | compare_models | python | mosaicml/composer | tests/algorithms/test_required_on_load.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_required_on_load.py | Apache-2.0 |
def loss_fun_tuple() -> Callable:
"""Fake loss function that requires a batch tuple."""
def loss(output, batch, reduction='none'):
_, target = batch
return torch.ones_like(target)
return loss | Fake loss function that requires a batch tuple. | loss_fun_tuple | python | mosaicml/composer | tests/algorithms/test_selective_backprop.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_selective_backprop.py | Apache-2.0 |
def bad_loss() -> Callable:
"""Fake loss function that will error."""
def loss(output, target):
return 0
return loss | Fake loss function that will error. | bad_loss | python | mosaicml/composer | tests/algorithms/test_selective_backprop.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_selective_backprop.py | Apache-2.0 |
def state(
minimal_state: State,
conv_model: ComposerClassifier,
loss_fun_tuple: Callable,
epoch: int,
batch: int,
) -> State:
"""State with required values set for Selective Backprop."""
assert minimal_state.dataloader_len is not None
conv_model.loss = loss_fun_tuple
minimal_state.m... | State with required values set for Selective Backprop. | state | python | mosaicml/composer | tests/algorithms/test_selective_backprop.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_selective_backprop.py | Apache-2.0 |
def test_select_using_loss_true(self, epoch: int, batch: int, interrupt: int) -> None:
"""Test functional match when epoch is within interval."""
start = 5
end = 15
is_chosen = should_selective_backprop(epoch, batch, start, end, interrupt)
assert is_chosen | Test functional match when epoch is within interval. | test_select_using_loss_true | python | mosaicml/composer | tests/algorithms/test_selective_backprop.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_selective_backprop.py | Apache-2.0 |
def test_select_using_loss_false(self, epoch: int, batch: int, interrupt: int) -> None:
"""Test functional doesn't match when epoch is outside of interval."""
start = 5
end = 15
is_chosen = should_selective_backprop(epoch, batch, start, end, interrupt)
assert not is_chosen | Test functional doesn't match when epoch is outside of interval. | test_select_using_loss_false | python | mosaicml/composer | tests/algorithms/test_selective_backprop.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_selective_backprop.py | Apache-2.0 |
def test_selective_backprop_interp_dim_error(
self,
X: torch.Tensor,
y: torch.Tensor,
model: torch.nn.Module,
loss_fun: Callable,
) -> None:
"""Ensure that ValueError is raised when input tensor can't be scaled."""
with pytest.raises(ValueError):
s... | Ensure that ValueError is raised when input tensor can't be scaled. | test_selective_backprop_interp_dim_error | python | mosaicml/composer | tests/algorithms/test_selective_backprop.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_selective_backprop.py | Apache-2.0 |
def test_selective_backprop_bad_loss_error(
self,
X: torch.Tensor,
y: torch.Tensor,
model: torch.nn.Module,
bad_loss: Callable,
) -> None:
"""Ensure that ValueError is raised when loss function doesn't have `reduction` kwarg."""
with pytest.raises(TypeError) a... | Ensure that ValueError is raised when loss function doesn't have `reduction` kwarg. | test_selective_backprop_bad_loss_error | python | mosaicml/composer | tests/algorithms/test_selective_backprop.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_selective_backprop.py | Apache-2.0 |
def test_match_correct(self, event: Event, sb_algorithm: SelectiveBackprop, state: State) -> None:
"""Algo should match AFTER_DATALOADER in the right interval."""
state.max_duration = '10ep'
assert sb_algorithm.match(event, state) | Algo should match AFTER_DATALOADER in the right interval. | test_match_correct | python | mosaicml/composer | tests/algorithms/test_selective_backprop.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_selective_backprop.py | Apache-2.0 |
def test_match_incorrect(self, event: Event, sb_algorithm: SelectiveBackprop, state: State) -> None:
"""Algo should NOT match the wrong interval."""
state.max_duration = '10ep'
assert not sb_algorithm.match(event, state) | Algo should NOT match the wrong interval. | test_match_incorrect | python | mosaicml/composer | tests/algorithms/test_selective_backprop.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_selective_backprop.py | Apache-2.0 |
def test_apply(
self,
Ximage: torch.Tensor,
y: torch.Tensor,
sb_algorithm: SelectiveBackprop,
state: State,
empty_logger: Logger,
keep: float,
) -> None:
"""Test apply with image inputs gives the right output shape."""
N, C, H, W = Ximage.shape... | Test apply with image inputs gives the right output shape. | test_apply | python | mosaicml/composer | tests/algorithms/test_selective_backprop.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_selective_backprop.py | Apache-2.0 |
def test_surgery_torchscript_train(input: Any, alg_cls: type[Algorithm]):
"""Tests torchscript model in train mode."""
if alg_cls in (Factorize, GhostBatchNorm, StochasticDepth):
pytest.xfail('Unsupported')
alg_kwargs = get_alg_kwargs(alg_cls)
model = get_alg_model(alg_cls)
surgery_method ... | Tests torchscript model in train mode. | test_surgery_torchscript_train | python | mosaicml/composer | tests/algorithms/test_torch_export.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_torch_export.py | Apache-2.0 |
def test_surgery_torchscript_eval(input: Any, alg_cls: type[Algorithm]):
"""Tests torchscript model in eval mode."""
if alg_cls is Factorize:
pytest.xfail('Unsupported')
surgery_method = get_surgery_method(alg_cls)
alg_kwargs = get_alg_kwargs(alg_cls)
model = get_alg_model(alg_cls)
alg... | Tests torchscript model in eval mode. | test_surgery_torchscript_eval | python | mosaicml/composer | tests/algorithms/test_torch_export.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_torch_export.py | Apache-2.0 |
def test_surgery_torchfx_eval(
input: Any,
alg_cls: type[Algorithm],
):
"""Tests torch.fx model in eval mode."""
alg_kwargs = get_alg_kwargs(alg_cls)
model = get_alg_model(alg_cls)
surgery_method = get_surgery_method(alg_cls)
if alg_cls in (BlurPool, GhostBatchNorm):
pytest.xfail('... | Tests torch.fx model in eval mode. | test_surgery_torchfx_eval | python | mosaicml/composer | tests/algorithms/test_torch_export.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_torch_export.py | Apache-2.0 |
def test_ws_calculation():
"""Check if convolution weights are properly standardized."""
model = SimpleConvModel()
apply_weight_standardization(module=model)
var1, mean1 = torch.var_mean(model.conv1.weight, dim=[1, 2, 3], unbiased=False)
var2, mean2 = torch.var_mean(model.conv2.weight, dim=[1, 2, 3]... | Check if convolution weights are properly standardized. | test_ws_calculation | python | mosaicml/composer | tests/algorithms/test_weight_standardization.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_weight_standardization.py | Apache-2.0 |
def test_ws_replacement(n_last_layers_ignore: int):
"""Check if the proper number of layers have been parametrized."""
model = SimpleConvModel()
apply_weight_standardization(module=model, n_last_layers_ignore=n_last_layers_ignore)
ws_count = _count_parametrize(model)
expected_count = max(2 - n_last_... | Check if the proper number of layers have been parametrized. | test_ws_replacement | python | mosaicml/composer | tests/algorithms/test_weight_standardization.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_weight_standardization.py | Apache-2.0 |
def test_ws_algorithm(n_last_layers_ignore: int, minimal_state: State, empty_logger: Logger):
"""Check if the algorithm is applied at the proper event."""
minimal_state.model = SimpleConvModel()
ws_algorithm = WeightStandardization(n_last_layers_ignore=n_last_layers_ignore)
ws_algorithm.apply(Event.INIT... | Check if the algorithm is applied at the proper event. | test_ws_algorithm | python | mosaicml/composer | tests/algorithms/test_weight_standardization.py | https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_weight_standardization.py | Apache-2.0 |
def test_multiple_fit_start_and_end(self, cb_cls: type[Callback], dummy_state: State):
"""Test that callbacks do not crash when Event.FIT_START and Event.FIT_END is called multiple times."""
maybe_patch_context = get_cb_patches(cb_cls)
with maybe_patch_context:
cb_kwargs = get_cb_kwa... | Test that callbacks do not crash when Event.FIT_START and Event.FIT_END is called multiple times. | test_multiple_fit_start_and_end | python | mosaicml/composer | tests/callbacks/test_callbacks.py | https://github.com/mosaicml/composer/blob/master/tests/callbacks/test_callbacks.py | Apache-2.0 |
def test_idempotent_close(self, cb_cls: type[Callback], dummy_state: State, clean_mlflow_runs):
"""Test that callbacks do not crash when .close() and .post_close() are called multiple times."""
maybe_patch_context = get_cb_patches(cb_cls)
with maybe_patch_context:
cb_kwargs = get_cb_... | Test that callbacks do not crash when .close() and .post_close() are called multiple times. | test_idempotent_close | python | mosaicml/composer | tests/callbacks/test_callbacks.py | https://github.com/mosaicml/composer/blob/master/tests/callbacks/test_callbacks.py | Apache-2.0 |
def test_multiple_init_and_close(self, cb_cls: type[Callback], dummy_state: State, clean_mlflow_runs):
"""Test that callbacks do not crash when INIT/.close()/.post_close() are called multiple times in that order."""
maybe_patch_context = get_cb_patches(cb_cls)
with maybe_patch_context:
... | Test that callbacks do not crash when INIT/.close()/.post_close() are called multiple times in that order. | test_multiple_init_and_close | python | mosaicml/composer | tests/callbacks/test_callbacks.py | https://github.com/mosaicml/composer/blob/master/tests/callbacks/test_callbacks.py | Apache-2.0 |
def test_trains_multiple_calls(
self,
cb_cls: type[Callback],
device_train_microbatch_size: int,
_remote: bool,
clean_mlflow_runs,
):
"""
Tests that training with multiple fits complete. Note: future functional tests should test for idempotency (e.g functional... |
Tests that training with multiple fits complete. Note: future functional tests should test for idempotency (e.g functionally)
| test_trains_multiple_calls | python | mosaicml/composer | tests/callbacks/test_callbacks.py | https://github.com/mosaicml/composer/blob/master/tests/callbacks/test_callbacks.py | Apache-2.0 |
def mlperf_callback(self, monkeypatch, tmp_path) -> MLPerfCallback:
"""Returns a callback with the MockMLLogger patched."""
callback = MLPerfCallback(tmp_path, 0)
monkeypatch.setattr(callback, 'mllogger', MockMLLogger())
return callback | Returns a callback with the MockMLLogger patched. | mlperf_callback | python | mosaicml/composer | tests/callbacks/test_mlperf_callback.py | https://github.com/mosaicml/composer/blob/master/tests/callbacks/test_mlperf_callback.py | Apache-2.0 |
def mock_state(self):
"""Mocks a state at epoch 1 with Accuracy 0.99."""
acc = BinaryAccuracy()
eval_metrics = {'eval': {'BinaryAccuracy': acc}}
acc.update(
torch.tensor([1, 1], dtype=torch.int8),
torch.tensor([1, 1], dtype=torch.int8),
)
state = ... | Mocks a state at epoch 1 with Accuracy 0.99. | mock_state | python | mosaicml/composer | tests/callbacks/test_mlperf_callback.py | https://github.com/mosaicml/composer/blob/master/tests/callbacks/test_mlperf_callback.py | Apache-2.0 |
def generate_submission(self, directory, device, benchmark):
"""Generates submission files by training the benchark n=5 times."""
for run in range(NUM_TRIALS[benchmark]):
mlperf_callback = MLPerfCallback(
benchmark=benchmark,
root_folder=directory,
... | Generates submission files by training the benchark n=5 times. | generate_submission | python | mosaicml/composer | tests/callbacks/test_mlperf_callback.py | https://github.com/mosaicml/composer/blob/master/tests/callbacks/test_mlperf_callback.py | Apache-2.0 |
def run_mlperf_checker(self, directory, monkeypatch):
"""Runs the MLPerf package checker and fails on any errors."""
# monkeypatch the logging so that logging.error raises Exception
def fail_on_error(msg, *args, **kwargs):
print(msg.format(*args))
raise ValueError('MLPer... | Runs the MLPerf package checker and fails on any errors. | run_mlperf_checker | python | mosaicml/composer | tests/callbacks/test_mlperf_callback.py | https://github.com/mosaicml/composer/blob/master/tests/callbacks/test_mlperf_callback.py | Apache-2.0 |
def device(*args, precision=False):
"""Decorator for device and optionally precision.
Input choices are ('cpu', 'gpu'), or if precision=True,
also accept ('gpu-amp', 'gpu-fp32', and 'cpu-fp32').
Returns the parameter "device", or if precision=True,
also returns the parameter "precision".
"""
... | Decorator for device and optionally precision.
Input choices are ('cpu', 'gpu'), or if precision=True,
also accept ('gpu-amp', 'gpu-fp32', and 'cpu-fp32').
Returns the parameter "device", or if precision=True,
also returns the parameter "precision".
| device | python | mosaicml/composer | tests/common/markers.py | https://github.com/mosaicml/composer/blob/master/tests/common/markers.py | Apache-2.0 |
def world_size(*world_sizes: int, param_name: str = 'world_size'):
"""Decorator to mark tests with a given world size. This helper automatically sets the `pytest.mark.world_size`
marker.
Args:
world_sizes (int): The world sizes.
param_name (str, optional): The parameter name for the `world_... | Decorator to mark tests with a given world size. This helper automatically sets the `pytest.mark.world_size`
marker.
Args:
world_sizes (int): The world sizes.
param_name (str, optional): The parameter name for the `world_size` parameter. Defaults to ``'world_size'``.
Example:
>>> @worl... | world_size | python | mosaicml/composer | tests/common/markers.py | https://github.com/mosaicml/composer/blob/master/tests/common/markers.py | Apache-2.0 |
def composer_resnet(
model_name: str,
num_classes: int = 1000,
weights: Optional[str] = None,
groups: int = 1,
width_per_group: int = 64,
initializers: Optional[list[Initializer]] = None,
loss_name: str = 'soft_cross_entropy',
) -> ComposerClassifier:
"""Helper function to create a :clas... | Helper function to create a :class:`.ComposerClassifier` with a torchvision ResNet model.
From `Deep Residual Learning for Image Recognition <https://arxiv.org/abs/1512.03385>`_ (He et al, 2015).
Args:
model_name (str): Name of the ResNet model instance. Either [``"resnet18"``, ``"resnet34"``, ``"resnet... | composer_resnet | python | mosaicml/composer | tests/common/models.py | https://github.com/mosaicml/composer/blob/master/tests/common/models.py | Apache-2.0 |
def assert_state_equivalent(state1: State, state2: State):
"""Assert that ``state1`` is equivalent to ``state2``, ignoring wall clock timestamp fields."""
assert state1.serialized_attributes == state2.serialized_attributes
# Using a loose tolerance for GPU states as GPU determinism does not work properly
... | Assert that ``state1`` is equivalent to ``state2``, ignoring wall clock timestamp fields. | assert_state_equivalent | python | mosaicml/composer | tests/common/state.py | https://github.com/mosaicml/composer/blob/master/tests/common/state.py | Apache-2.0 |
def reset_mlflow_tracking_dir():
"""Reset MLFlow tracking dir so it doesn't persist across tests"""
try:
import mlflow
mlflow.set_tracking_uri(None) # type: ignore
except ModuleNotFoundError:
# MLFlow not installed
pass | Reset MLFlow tracking dir so it doesn't persist across tests | reset_mlflow_tracking_dir | python | mosaicml/composer | tests/fixtures/autouse_fixtures.py | https://github.com/mosaicml/composer/blob/master/tests/fixtures/autouse_fixtures.py | Apache-2.0 |
def cleanup_dist():
"""Ensure all dist tests clean up resources properly."""
yield
# Avoid race condition where a test is still writing to a file on one rank
# while the file system is being torn down on another rank.
dist.barrier() | Ensure all dist tests clean up resources properly. | cleanup_dist | python | mosaicml/composer | tests/fixtures/autouse_fixtures.py | https://github.com/mosaicml/composer/blob/master/tests/fixtures/autouse_fixtures.py | Apache-2.0 |
def seed_all(rank_zero_seed: int, monkeypatch: pytest.MonkeyPatch):
"""Monkeypatch reproducibility get_random_seed to always return the rank zero seed, and set the random seed before
each test to the rank local seed."""
monkeypatch.setattr(reproducibility, 'get_random_seed', lambda: rank_zero_seed)
repr... | Monkeypatch reproducibility get_random_seed to always return the rank zero seed, and set the random seed before
each test to the rank local seed. | seed_all | python | mosaicml/composer | tests/fixtures/autouse_fixtures.py | https://github.com/mosaicml/composer/blob/master/tests/fixtures/autouse_fixtures.py | Apache-2.0 |
def minimal_state(rank_zero_seed: int, request: pytest.FixtureRequest):
"""Most minimally defined state possible.
Tests should configure the state for their specific needs.
"""
device = None
for item in request.session.items:
device = DeviceCPU() if item.get_closest_marker('gpu') is None e... | Most minimally defined state possible.
Tests should configure the state for their specific needs.
| minimal_state | python | mosaicml/composer | tests/fixtures/fixtures.py | https://github.com/mosaicml/composer/blob/master/tests/fixtures/fixtures.py | Apache-2.0 |
def test_session_name(configure_dist: None) -> str:
"""Generate a random name for the test session that is the same on all ranks."""
del configure_dist # unused
generated_session_name = str(int(time.time())) + '-' + coolname.generate_slug(2)
name_list = [generated_session_name]
# ensure all ranks h... | Generate a random name for the test session that is the same on all ranks. | test_session_name | python | mosaicml/composer | tests/fixtures/fixtures.py | https://github.com/mosaicml/composer/blob/master/tests/fixtures/fixtures.py | Apache-2.0 |
def clean_mlflow_runs():
"""Clean up MLflow runs before and after tests.
This fixture ensures no MLflow runs persist between tests,
which prevents "Run already active" errors.
"""
try:
import mlflow
try:
while mlflow.active_run():
mlflow.end_run()
... | Clean up MLflow runs before and after tests.
This fixture ensures no MLflow runs persist between tests,
which prevents "Run already active" errors.
| clean_mlflow_runs | python | mosaicml/composer | tests/fixtures/fixtures.py | https://github.com/mosaicml/composer/blob/master/tests/fixtures/fixtures.py | Apache-2.0 |
def test_comet_ml_log_metrics_and_hyperparameters(monkeypatch, tmp_path):
"""Check metrics logged with CometMLLogger are properly written to offline dump."""
pytest.importorskip('comet_ml', reason='comet_ml is optional')
import comet_ml
# Set some dummy log values.
steps = [0, 1, 2]
metric_valu... | Check metrics logged with CometMLLogger are properly written to offline dump. | test_comet_ml_log_metrics_and_hyperparameters | python | mosaicml/composer | tests/loggers/test_cometml_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_cometml_logger.py | Apache-2.0 |
def test_console_logger_overlapping(console_logger_test_stream, console_logger_test_file_path):
"""
Test that the console logger does not throw away metrics at the end of an epoch, instead logging these
metrics at the typical log period.
Uses OptimizerMonitor as a logger that only logs every 5 batches,... |
Test that the console logger does not throw away metrics at the end of an epoch, instead logging these
metrics at the typical log period.
Uses OptimizerMonitor as a logger that only logs every 5 batches, on a model training for two epochs of
6 batches, with log period of 8 batches. With prior implemen... | test_console_logger_overlapping | python | mosaicml/composer | tests/loggers/test_console_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_console_logger.py | Apache-2.0 |
def test_mlflow_init_unspecified(monkeypatch):
""" Test that MLFlow experiment is set up correctly when no parameters are specified
This mocks the mlflow library to check that the correct calls are made to set up the experiment
"""
mlflow = pytest.importorskip('mlflow')
from mlflow import MlflowCli... | Test that MLFlow experiment is set up correctly when no parameters are specified
This mocks the mlflow library to check that the correct calls are made to set up the experiment
| test_mlflow_init_unspecified | python | mosaicml/composer | tests/loggers/test_mlflow_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_mlflow_logger.py | Apache-2.0 |
def test_mlflow_init_specified(monkeypatch):
""" Test that MLFlow experiment is set up correctly when all parameters are specified
This mocks the mlflow library to check that the correct calls are made to set up the experiment
"""
mlflow = pytest.importorskip('mlflow')
from mlflow import MlflowClie... | Test that MLFlow experiment is set up correctly when all parameters are specified
This mocks the mlflow library to check that the correct calls are made to set up the experiment
| test_mlflow_init_specified | python | mosaicml/composer | tests/loggers/test_mlflow_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_mlflow_logger.py | Apache-2.0 |
def test_mlflow_init_ids(monkeypatch):
""" Test that MLFlow experiment is set up correctly when ids in the environment are specified
This mocks the mlflow library to check that the correct calls are made to set up the experiment
"""
mlflow = pytest.importorskip('mlflow')
set_tracking_uri_spy = Mag... | Test that MLFlow experiment is set up correctly when ids in the environment are specified
This mocks the mlflow library to check that the correct calls are made to set up the experiment
| test_mlflow_init_ids | python | mosaicml/composer | tests/loggers/test_mlflow_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_mlflow_logger.py | Apache-2.0 |
def test_mlflow_init_experiment_name(monkeypatch):
""" Test that MLFlow experiment is set up correctly when experiment name is specified
This mocks the mlflow library to check that the correct calls are made to set up the experiment
"""
mlflow = pytest.importorskip('mlflow')
# Set up client mock
... | Test that MLFlow experiment is set up correctly when experiment name is specified
This mocks the mlflow library to check that the correct calls are made to set up the experiment
| test_mlflow_init_experiment_name | python | mosaicml/composer | tests/loggers/test_mlflow_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_mlflow_logger.py | Apache-2.0 |
def test_mlflow_init_existing_composer_run(monkeypatch):
""" Test that an existing MLFlow run is used if one tagged with `run_name` exists in the experiment for the Composer run.
"""
mlflow = pytest.importorskip('mlflow')
monkeypatch.setattr(mlflow, 'set_tracking_uri', MagicMock())
monkeypatch.seta... | Test that an existing MLFlow run is used if one tagged with `run_name` exists in the experiment for the Composer run.
| test_mlflow_init_existing_composer_run | python | mosaicml/composer | tests/loggers/test_mlflow_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_mlflow_logger.py | Apache-2.0 |
def test_mlflow_logger_uses_env_var_run_name(monkeypatch, mock_mlflow_client):
"""Test that MLFlowLogger uses the 'RUN_NAME' environment variable if set."""
mlflow = pytest.importorskip('mlflow')
monkeypatch.setattr(mlflow, 'set_tracking_uri', MagicMock())
monkeypatch.setattr(mlflow, 'start_run', Magic... | Test that MLFlowLogger uses the 'RUN_NAME' environment variable if set. | test_mlflow_logger_uses_env_var_run_name | python | mosaicml/composer | tests/loggers/test_mlflow_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_mlflow_logger.py | Apache-2.0 |
def test_mlflow_logger_uses_state_run_name_if_no_env_var_set(monkeypatch, mock_mlflow_client):
"""Test that MLFlowLogger uses the state's run name if no 'RUN_NAME' environment variable is set."""
mlflow = pytest.importorskip('mlflow')
monkeypatch.setattr(mlflow, 'set_tracking_uri', MagicMock())
monkeyp... | Test that MLFlowLogger uses the state's run name if no 'RUN_NAME' environment variable is set. | test_mlflow_logger_uses_state_run_name_if_no_env_var_set | python | mosaicml/composer | tests/loggers/test_mlflow_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_mlflow_logger.py | Apache-2.0 |
def test_mlflow_set_up(tmp_path):
""" Test that MLFlow experiment is set up correctly within mlflow
"""
mlflow = pytest.importorskip('mlflow')
mlflow_uri = tmp_path / Path('my-test-mlflow-uri')
mlflow_exp_name = 'my-test-mlflow-exp'
mlflow_run_name = 'my-test-mlflow-run'
test_mlflow_logger... | Test that MLFlow experiment is set up correctly within mlflow
| test_mlflow_set_up | python | mosaicml/composer | tests/loggers/test_mlflow_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_mlflow_logger.py | Apache-2.0 |
def test_logged_data_is_json_serializable(monkeypatch, callback_cls: type[Callback], world_size):
"""Test that all logged data is json serializable, which is a requirement to use MAPI."""
mock_mapi = MockMAPI()
monkeypatch.setenv('MOSAICML_PLATFORM', 'True')
monkeypatch.setattr(mcli, 'update_run_metada... | Test that all logged data is json serializable, which is a requirement to use MAPI. | test_logged_data_is_json_serializable | python | mosaicml/composer | tests/loggers/test_mosaicml_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_mosaicml_logger.py | Apache-2.0 |
def test_logged_data_exception_handling(monkeypatch, world_size: int, ignore_exceptions: bool):
"""Test that exceptions in MAPI are raised properly."""
mock_mapi = MockMAPI(simulate_exception=True)
monkeypatch.setenv('MOSAICML_PLATFORM', 'True')
monkeypatch.setattr(mcli, 'update_run_metadata', mock_mapi... | Test that exceptions in MAPI are raised properly. | test_logged_data_exception_handling | python | mosaicml/composer | tests/loggers/test_mosaicml_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_mosaicml_logger.py | Apache-2.0 |
def test_run_events_logged(monkeypatch):
''''
Current run events include:
1. model initialization time
2. training progress (i.e. [batch=x/xx] at batch end)
'''
mock_mapi = MockMAPI()
monkeypatch.setenv('MOSAICML_PLATFORM', 'True')
monkeypatch.setattr(mcli, 'update_run_metadata', mock_ma... | '
Current run events include:
1. model initialization time
2. training progress (i.e. [batch=x/xx] at batch end)
| test_run_events_logged | python | mosaicml/composer | tests/loggers/test_mosaicml_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_mosaicml_logger.py | Apache-2.0 |
def test_close_on_failure(tmp_path: pathlib.Path, dummy_state: State):
"""Test that .close() and .post_close() does not hang even when a worker crashes."""
with patch('composer.utils.object_store.utils.S3ObjectStore', DummyObjectStore):
# Create the object store logger
remote_uploader_downloade... | Test that .close() and .post_close() does not hang even when a worker crashes. | test_close_on_failure | python | mosaicml/composer | tests/loggers/test_remote_uploader_downloader.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_remote_uploader_downloader.py | Apache-2.0 |
def test_exception_queue_works(tmp_path: pathlib.Path, dummy_state: State):
"""Test that exceptions get put on the exception queue and get thrown"""
with patch('composer.utils.object_store.utils.S3ObjectStore', DummyObjectStore):
# Create the object store logger
remote_uploader_downloader = Rem... | Test that exceptions get put on the exception queue and get thrown | test_exception_queue_works | python | mosaicml/composer | tests/loggers/test_remote_uploader_downloader.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_remote_uploader_downloader.py | Apache-2.0 |
def test_logged_data_is_json_serializable(callback_cls: type[Callback]):
"""Test that all logged data is json serializable, which is a requirement to use wandb."""
pytest.importorskip('wandb', reason='wandb is optional')
from wandb.sdk.data_types.base_types.wb_value import WBValue
callback_kwargs = get_... | Test that all logged data is json serializable, which is a requirement to use wandb. | test_logged_data_is_json_serializable | python | mosaicml/composer | tests/loggers/test_wandb_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_wandb_logger.py | Apache-2.0 |
def test_wandb_artifacts(monkeypatch: MonkeyPatch, rank_zero_only: bool, tmp_path: pathlib.Path, dummy_state: State):
"""Test that wandb artifacts logged on rank zero are accessible by all ranks."""
import wandb
original_wandb_mode = os.environ.get('WANDB_MODE', None)
os.environ['WANDB_MODE'] = 'offline... | Test that wandb artifacts logged on rank zero are accessible by all ranks. | test_wandb_artifacts | python | mosaicml/composer | tests/loggers/test_wandb_logger.py | https://github.com/mosaicml/composer/blob/master/tests/loggers/test_wandb_logger.py | Apache-2.0 |
def _generate_dummy_metric_inputs(self, target_val) -> tuple[torch.Tensor, torch.Tensor]:
"""Generate fake set of predictions and target values to satisfy the given target accuracy value."""
# predictions is a tensor with a ratio of target_val 1s to sub_target 0s
preds_ones = torch.ones(int(targ... | Generate fake set of predictions and target values to satisfy the given target accuracy value. | _generate_dummy_metric_inputs | python | mosaicml/composer | tests/metrics/metric_setter_callback.py | https://github.com/mosaicml/composer/blob/master/tests/metrics/metric_setter_callback.py | Apache-2.0 |
def test_masked_accuracy(ignore_index, num_classes):
"""Sanity check to make sure that masked accuracy has reasonable performance.
Generates random targets and labels, and then ensures that the random targets and labels
must hit at-chance accuracy.
Args:
batch_size (int): how many samples are ... | Sanity check to make sure that masked accuracy has reasonable performance.
Generates random targets and labels, and then ensures that the random targets and labels
must hit at-chance accuracy.
Args:
batch_size (int): how many samples are in each batch
ignore_index (Optional[int]): if prese... | test_masked_accuracy | python | mosaicml/composer | tests/metrics/test_nlp_metrics.py | https://github.com/mosaicml/composer/blob/master/tests/metrics/test_nlp_metrics.py | Apache-2.0 |
def test_cross_entropy(
batch_size: float,
ignore_index: Optional[int],
sequence_length: int,
num_classes: int,
minibatch_size: int,
):
"""Sanity check to make sure that batched CrossEntropyLoss matches the expected performance.
Generates a predicted distribution from a normal distribution,... | Sanity check to make sure that batched CrossEntropyLoss matches the expected performance.
Generates a predicted distribution from a normal distribution, and a ground truth from a normal distribution.
Verifies Cross Entropy Loss against the baseline performance.
Args:
batch_size (int): how many sam... | test_cross_entropy | python | mosaicml/composer | tests/metrics/test_nlp_metrics.py | https://github.com/mosaicml/composer/blob/master/tests/metrics/test_nlp_metrics.py | Apache-2.0 |
def test_binary_f1(batch_size, minibatch_size):
"""Sanity check to make sure that BinaryF1 TorchMetrics implementation matches the sklearn implementation.
Generates a predicted set of labels, and a random set, and compares the resultant Binary F1 score.
Args:
batch_size (int): how many samples are... | Sanity check to make sure that BinaryF1 TorchMetrics implementation matches the sklearn implementation.
Generates a predicted set of labels, and a random set, and compares the resultant Binary F1 score.
Args:
batch_size (int): how many samples are in each batch
minibatch_size (int): the miniba... | test_binary_f1 | python | mosaicml/composer | tests/metrics/test_nlp_metrics.py | https://github.com/mosaicml/composer/blob/master/tests/metrics/test_nlp_metrics.py | Apache-2.0 |
def check_hf_tokenizer_equivalence(tokenizer1, tokenizer2):
"""
WARNING: Parameters are updated within the check so don't call check_hf_tokenizer_equivalence on the same
params more than once
This is a best effort attempt to compare two tokenizers for equivalence
This is not a perfect test, but it... |
WARNING: Parameters are updated within the check so don't call check_hf_tokenizer_equivalence on the same
params more than once
This is a best effort attempt to compare two tokenizers for equivalence
This is not a perfect test, but it should catch most issues. We first check that the vocab is identic... | check_hf_tokenizer_equivalence | python | mosaicml/composer | tests/models/test_hf_model.py | https://github.com/mosaicml/composer/blob/master/tests/models/test_hf_model.py | Apache-2.0 |
def test_activation_checkpointing_cuda_memory_usage(world_size: int, type_of_checkpointing: str):
"""Test FSDP2 activation checkpointing CUDA memory usage."""
del world_size
cuda_memory = {}
for activation_checkpointing in [True, False]:
for activation_cpu_offload in [True, False]:
... | Test FSDP2 activation checkpointing CUDA memory usage. | test_activation_checkpointing_cuda_memory_usage | python | mosaicml/composer | tests/trainer/test_activation_checkpointing.py | https://github.com/mosaicml/composer/blob/master/tests/trainer/test_activation_checkpointing.py | Apache-2.0 |
def test_load_remote_checkpoint(
self,
tmp_path: pathlib.Path,
load_weights_only,
remote_checkpoint_name,
continue_training_dur,
final_checkpoint_name,
uc_volume_read_only,
device='gpu',
):
"""
This test checks if our checkpointing is b... |
This test checks if our checkpointing is backwards compatible.
We should be able to load in a saved checkpoint and continue training.
The checkpoint weight and metrics should match at load time
and should be equivalent after training continues.
| test_load_remote_checkpoint | python | mosaicml/composer | tests/trainer/test_checkpoint.py | https://github.com/mosaicml/composer/blob/master/tests/trainer/test_checkpoint.py | Apache-2.0 |
def test_ddp(device: str, world_size: int, fsdp: bool, tmp_path: pathlib.Path) -> None:
"""test strategy for ddp: 1) Train a dummy model on two gps, for two epochs, using the tracked dataset. 2) The
tracked dataset should record two -- and only two -- accesses for each sample -- one for each epoch If each sampl... | test strategy for ddp: 1) Train a dummy model on two gps, for two epochs, using the tracked dataset. 2) The
tracked dataset should record two -- and only two -- accesses for each sample -- one for each epoch If each sample
is accessed more than this number of times, then the distributed sampler isn't working pr... | test_ddp | python | mosaicml/composer | tests/trainer/test_ddp.py | https://github.com/mosaicml/composer/blob/master/tests/trainer/test_ddp.py | Apache-2.0 |
def _assert_inputs_different(tmp_path, max_epochs, is_train):
"""Checks that each rank's dataloader input is different."""
inputs = []
targets = []
for epoch in range(max_epochs):
file_path = get_batch_file_path(
epoch=epoch if is_train else epoch + 1, # val is 1 ahead
... | Checks that each rank's dataloader input is different. | _assert_inputs_different | python | mosaicml/composer | tests/trainer/test_ddp.py | https://github.com/mosaicml/composer/blob/master/tests/trainer/test_ddp.py | Apache-2.0 |
def test_fsdp_device_initialization(
model: ComposerClassifier,
mixed_precision: str,
reentrant: bool,
world_size: int,
device: str,
):
"""test FSDP device initialization for a simple model with weight tying and a model where two modules
from separate submodules have weight tying applied. Th... | test FSDP device initialization for a simple model with weight tying and a model where two modules
from separate submodules have weight tying applied. This test also covers both 'cpu' and
'meta' devices. This is because 'meta' will result in deferred initialization until FSDP is initialized
| test_fsdp_device_initialization | python | mosaicml/composer | tests/trainer/test_fsdp.py | https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp.py | Apache-2.0 |
def test_fsdp_meta_initialization_none(model: ComposerClassifier, mixed_precision: 'str', world_size: int):
"""
This test is intended to test FSDP for meta initialization when there are attributes
that are `None` and ensure we don't raise nasty UserWarnings.
"""
num_classes = 2
model = model(num... |
This test is intended to test FSDP for meta initialization when there are attributes
that are `None` and ensure we don't raise nasty UserWarnings.
| test_fsdp_meta_initialization_none | python | mosaicml/composer | tests/trainer/test_fsdp.py | https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp.py | Apache-2.0 |
def create_trainer_with_model(
model: ComposerClassifier,
num_classes: int = 10,
max_duration: str = '10ep',
use_fsdp2: bool = True,
optimizer: Optional[torch.optim.Optimizer] = None,
activation_checkpointing: bool = False,
activation_cpu_offload: bool = False,
auto_microbatching: bool =... | Helper function to create a Trainer with a model, dataloader, and FSDP2 configuration. | create_trainer_with_model | 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_initialization_with_tied_params(
model_class: type,
device: str,
world_size: int,
):
"""test FSDP2 initialization for a simple model with weight tying and a model where two modules
from separate submodules have weight tying applied.
"""
model = model_class(num_features=10, dev... | test FSDP2 initialization for a simple model with weight tying and a model where two modules
from separate submodules have weight tying applied.
| test_fsdp2_initialization_with_tied_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_checkpointing(
model_class: type,
device: str,
world_size: int,
tmp_path: pathlib.Path,
):
"""Test FSDP2 checkpointing and weight tying after loading."""
model = model_class(num_features=10, device=device)
model.add_fsdp_wrap_attribute_to_children()
trainer = create_traine... | Test FSDP2 checkpointing and weight tying after loading. | test_fsdp2_checkpointing | 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_optimizer_handling(
world_size: int,
case: str,
device: str,
):
"""Test FSDP2 correctly updates optimizer state for various configurations."""
del world_size
NUM_FEATURES = 10
NUM_CLASSES = 10
model = PartialWeightTiedModel(num_features=NUM_FEATURES, device=device)
mo... | Test FSDP2 correctly updates optimizer state for various configurations. | test_fsdp2_optimizer_handling | 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_optimizer_raises_error_when_optimizer_modules_dont_match(
world_size: int,
):
"""Test FSDP2 raises an error when the optimizer modules don't match the model modules."""
del world_size
NUM_FEATURES = 10
NUM_CLASSES = 10
model = SimpleComposerMLP(num_features=NUM_FEATURES, device='... | Test FSDP2 raises an error when the optimizer modules don't match the model modules. | test_fsdp2_optimizer_raises_error_when_optimizer_modules_dont_match | 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_auto_microbatching_raises_error(
world_size: int,
):
"""Test FSDP2 raises an error when auto microbatching is used."""
del world_size
model = SimpleComposerMLP(num_features=10, device='cuda', num_classes=10)
model.add_fsdp_wrap_attribute_to_children()
with pytest.raises(ValueErro... | Test FSDP2 raises an error when auto microbatching is used. | test_fsdp2_auto_microbatching_raises_error | python | mosaicml/composer | tests/trainer/test_fsdp2.py | https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2.py | Apache-2.0 |
def _create_model_with_mixed_init(model_class: type, num_features: int, device: str, seed: int = 42):
"""Helper function to create a model with mixed initialization (CPU for rank 0, meta for others)."""
TestFSDP2MixedInit._set_deterministic_seed(seed)
resolved_device = device if dist.get_local_... | Helper function to create a model with mixed initialization (CPU for rank 0, meta for others). | _create_model_with_mixed_init | python | mosaicml/composer | tests/trainer/test_fsdp2.py | https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2.py | Apache-2.0 |
def _train_model_and_extract_weights(model, use_fsdp2: bool):
"""Helper function to train a mixed init model and extract its weights."""
optimizer = torch.optim.SGD(model.parameters(), lr=1e-4)
kwargs = {}
# If we're using FSDP1, we need to manually set the
# attribute to sync t... | Helper function to train a mixed init model and extract its weights. | _train_model_and_extract_weights | python | mosaicml/composer | tests/trainer/test_fsdp2.py | https://github.com/mosaicml/composer/blob/master/tests/trainer/test_fsdp2.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.