uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
98d9491fb739f7e60be13704 | train | function | @RunIf(min_gpus=1)
def test_trainer_predict_1_gpu(tmpdir):
predict(tmpdir, accelerator="gpu", devices=1)
| @RunIf(min_gpus=1)
def test_trainer_predict_1_gpu(tmpdir):
| predict(tmpdir, accelerator="gpu", devices=1)
| 2},
{"strategy": "ddp", "devices": 2},
],
)
def test_trainer_predict_standalone(tmpdir, kwargs):
predict(tmpdir, accelerator="gpu", **kwargs)
@RunIf(min_gpus=1)
def test_trainer_predict_1_gpu(tmpdir):
| 64 | 64 | 32 | 19 | 45 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_predict_1_gpu | test_trainer_predict_1_gpu | 1,403 | 1,405 | 1,403 | 1,404 | dff6ed4b11134dd66929d9856fe4ac6bd36bceff | bigcode/the-stack | train |
a20710591fe2fd3d7fd28a12 | train | function | def test_model_checkpoint_only_weights(tmpdir):
"""Tests use case where ModelCheckpoint is configured to save only model weights, and user tries to load
checkpoint to resume training."""
model = BoringModel()
trainer = Trainer(
default_root_dir=tmpdir,
max_epochs=1,
limit_train_... | def test_model_checkpoint_only_weights(tmpdir):
| """Tests use case where ModelCheckpoint is configured to save only model weights, and user tries to load
checkpoint to resume training."""
model = BoringModel()
trainer = Trainer(
default_root_dir=tmpdir,
max_epochs=1,
limit_train_batches=1,
limit_val_batches=1,
... | trainer.lightning_module)
trainer.fit_loop.epoch_progress.current.completed = i # sets `trainer.current_epoch`
file_lists = set(os.listdir(tmpdir))
assert len(file_lists) == len(
expected_files
), f"Should save {len(expected_files)} models when save_top_k={save_top_k} but found={file_lis... | 103 | 103 | 344 | 9 | 93 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_model_checkpoint_only_weights | test_model_checkpoint_only_weights | 349 | 386 | 349 | 349 | e4265db9122fb6065ee04378b1db805bacf4aa24 | bigcode/the-stack | train |
6c2293debb0dbec9714ea5fe | train | function | def test_trainer_pickle(tmpdir):
trainer = Trainer(max_epochs=1, default_root_dir=tmpdir)
pickle.dumps(trainer)
cloudpickle.dumps(trainer)
| def test_trainer_pickle(tmpdir):
| trainer = Trainer(max_epochs=1, default_root_dir=tmpdir)
pickle.dumps(trainer)
cloudpickle.dumps(trainer)
| mock.patch("torch.cuda.is_available", return_value=True)
@mock.patch("torch.cuda.device_count", return_value=1)
def test_trainer_omegaconf(_, __, trainer_params):
config = OmegaConf.create(trainer_params)
Trainer(**config)
def test_trainer_pickle(tmpdir):
| 64 | 64 | 37 | 8 | 56 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_pickle | test_trainer_pickle | 1,207 | 1,210 | 1,207 | 1,207 | e4dd3c5fd2e98c1ad2df3b3d56ce84430a860544 | bigcode/the-stack | train |
75e28a64e2133567da44f445 | train | function | @pytest.mark.parametrize("url_ckpt", [True, False])
def test_fit_ckpt_path_epoch_restored(monkeypatch, tmpdir, tmpdir_server, url_ckpt):
"""Verify resuming from checkpoint runs the right number of epochs."""
# set $TORCH_HOME, which determines torch hub's cache path, to tmpdir
monkeypatch.setenv("TORCH_HOME... | @pytest.mark.parametrize("url_ckpt", [True, False])
def test_fit_ckpt_path_epoch_restored(monkeypatch, tmpdir, tmpdir_server, url_ckpt):
| """Verify resuming from checkpoint runs the right number of epochs."""
# set $TORCH_HOME, which determines torch hub's cache path, to tmpdir
monkeypatch.setenv("TORCH_HOME", tmpdir)
class TestModel(BoringModel):
# Model that tracks epochs and batches seen
num_epochs_end_seen = 0
... | model weights"
# assert restoring train state fails
with pytest.raises(KeyError, match="checkpoint contains only the model"):
trainer._checkpoint_connector.restore(new_weights_path)
def test_model_freeze_unfreeze():
model = BoringModel()
model.freeze()
assert not model.training
for p... | 147 | 147 | 490 | 37 | 110 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_fit_ckpt_path_epoch_restored | test_fit_ckpt_path_epoch_restored | 403 | 457 | 403 | 404 | d4bd35775076ebcf7ba3c0341464a9a06a9404d8 | bigcode/the-stack | train |
09bf9627d483289c3e6e1caa | train | function | @RunIf(min_gpus=1)
def test_gpu_choice():
num_gpus = torch.cuda.device_count()
Trainer(accelerator="gpu", devices=num_gpus, auto_select_gpus=True)
with pytest.raises(MisconfigurationException, match=r".*But your machine only has.*"):
Trainer(accelerator="gpu", devices=num_gpus + 1, auto_select_gpus... | @RunIf(min_gpus=1)
def test_gpu_choice():
| num_gpus = torch.cuda.device_count()
Trainer(accelerator="gpu", devices=num_gpus, auto_select_gpus=True)
with pytest.raises(MisconfigurationException, match=r".*But your machine only has.*"):
Trainer(accelerator="gpu", devices=num_gpus + 1, auto_select_gpus=True)
| 1, 2))
def test_invalid_gradient_clip_algo(tmpdir):
with pytest.raises(MisconfigurationException, match="`gradient_clip_algorithm` norm2 is invalid"):
Trainer(default_root_dir=tmpdir, gradient_clip_algorithm="norm2")
@RunIf(min_gpus=1)
def test_gpu_choice():
| 64 | 64 | 84 | 13 | 51 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_gpu_choice | test_gpu_choice | 1,039 | 1,045 | 1,039 | 1,040 | 4e4eeb416ddf10022c8fb22d36e0500b1e57ac40 | bigcode/the-stack | train |
d2a956004a47d7ef982db235 | train | function | def test_invalid_gradient_clip_algo(tmpdir):
with pytest.raises(MisconfigurationException, match="`gradient_clip_algorithm` norm2 is invalid"):
Trainer(default_root_dir=tmpdir, gradient_clip_algorithm="norm2")
| def test_invalid_gradient_clip_algo(tmpdir):
| with pytest.raises(MisconfigurationException, match="`gradient_clip_algorithm` norm2 is invalid"):
Trainer(default_root_dir=tmpdir, gradient_clip_algorithm="norm2")
| assert model.assertion_called
def test_invalid_gradient_clip_value(tmpdir):
with pytest.raises(TypeError, match="`gradient_clip_val` should be an int or a float"):
Trainer(default_root_dir=tmpdir, gradient_clip_val=(1, 2))
def test_invalid_gradient_clip_algo(tmpdir):
| 64 | 64 | 46 | 9 | 55 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_invalid_gradient_clip_algo | test_invalid_gradient_clip_algo | 1,034 | 1,036 | 1,034 | 1,034 | 34d903393abf55e59b2c86f3c2c5f282cd5b9c04 | bigcode/the-stack | train |
811f9d8f65cb9ebaed2883d2 | train | function | def test_trainer_metrics_reset_before_each_task(tmpdir):
"""Test that callback, logged and progress bar metrics are reset before each task starts."""
class TestMetricRestartCallback(Callback):
def _make_assertions(self, trainer):
assert trainer.callback_metrics == {}
assert trai... | def test_trainer_metrics_reset_before_each_task(tmpdir):
| """Test that callback, logged and progress bar metrics are reset before each task starts."""
class TestMetricRestartCallback(Callback):
def _make_assertions(self, trainer):
assert trainer.callback_metrics == {}
assert trainer.progress_bar_metrics == {}
assert trainer... | (model)
assert counter.exceptions == 1
with pytest.raises(Exception, match=r"Error during validation"):
trainer.validate(model)
assert counter.exceptions == 2
with pytest.raises(Exception, match=r"Error during test"):
trainer.test(model)
assert counter.exceptions == 3
with pyt... | 109 | 109 | 365 | 12 | 96 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_metrics_reset_before_each_task | test_trainer_metrics_reset_before_each_task | 1,896 | 1,939 | 1,896 | 1,896 | 0b87593c0b9784ecfbfff62ca1129387281def13 | bigcode/the-stack | train |
3c2b0f6b1d4d75af8c6a2ec3 | train | function | def test_trainer_min_steps_and_epochs(tmpdir):
"""Verify model trains according to specified min steps."""
num_train_samples = math.floor(len(BoringModel().train_dataloader()) * 0.5)
class CustomModel(BoringModel):
def training_step(self, *args, **kwargs):
# try to force stop right afte... | def test_trainer_min_steps_and_epochs(tmpdir):
| """Verify model trains according to specified min steps."""
num_train_samples = math.floor(len(BoringModel().train_dataloader()) * 0.5)
class CustomModel(BoringModel):
def training_step(self, *args, **kwargs):
# try to force stop right after first step
if self.global_step > ... | _loop_done(max_epochs, max_steps, is_done, correct_trainer_epochs):
trainer = Trainer(max_epochs=max_epochs, max_steps=max_steps)
assert trainer.max_epochs == correct_trainer_epochs
assert trainer.max_steps == max_steps
assert trainer.fit_loop.done is is_done
# Make sure there is no timer
time... | 107 | 107 | 359 | 11 | 95 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_min_steps_and_epochs | test_trainer_min_steps_and_epochs | 542 | 582 | 542 | 542 | 57a8aed040371ea2459469d8f21b366a14dee24e | bigcode/the-stack | train |
18d605f57580efd15780e293 | train | function | def test_exception_when_lightning_module_is_not_set_on_trainer():
trainer = Trainer()
with pytest.raises(MisconfigurationException, match=r"`model` must be provided.*validate"):
trainer.validate()
with pytest.raises(MisconfigurationException, match=r"`model` must be provided.*test"):
traine... | def test_exception_when_lightning_module_is_not_set_on_trainer():
| trainer = Trainer()
with pytest.raises(MisconfigurationException, match=r"`model` must be provided.*validate"):
trainer.validate()
with pytest.raises(MisconfigurationException, match=r"`model` must be provided.*test"):
trainer.test()
with pytest.raises(MisconfigurationException, match=r... | _root_dir=tmpdir, fast_dev_run=1, enable_checkpointing=False, logger=False)
trainer.fit(model)
assert model._current_fx_name is None
trainer.test(model)
assert model._current_fx_name is None
def test_exception_when_lightning_module_is_not_set_on_trainer():
| 64 | 64 | 91 | 14 | 49 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_exception_when_lightning_module_is_not_set_on_trainer | test_exception_when_lightning_module_is_not_set_on_trainer | 1,748 | 1,756 | 1,748 | 1,748 | 94b233463451671018e1052fe157ea208db54749 | bigcode/the-stack | train |
643523e6e9bed302ef525705 | train | function | def test_invalid_gradient_clip_value(tmpdir):
with pytest.raises(TypeError, match="`gradient_clip_val` should be an int or a float"):
Trainer(default_root_dir=tmpdir, gradient_clip_val=(1, 2))
| def test_invalid_gradient_clip_value(tmpdir):
| with pytest.raises(TypeError, match="`gradient_clip_val` should be an int or a float"):
Trainer(default_root_dir=tmpdir, gradient_clip_val=(1, 2))
| = torch.max(torch.stack(grad_max_list))
torch.testing.assert_allclose(grad_max.abs(), torch.tensor(1e-10))
self.assertion_called = True
model = TestModel()
trainer.fit(model)
assert model.assertion_called
def test_invalid_gradient_clip_value(tmpdir):
| 64 | 64 | 49 | 9 | 54 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_invalid_gradient_clip_value | test_invalid_gradient_clip_value | 1,029 | 1,031 | 1,029 | 1,029 | d8986463faa01c3ca498ff290ef0da1a431a020b | bigcode/the-stack | train |
d76c40e8f03e5363381be631 | train | function | def test_trainer_min_steps_and_min_epochs_not_reached(tmpdir, caplog):
"""Test that min_epochs/min_steps in Trainer are enforced even if EarlyStopping is triggered."""
class TestModel(BoringModel):
training_step_invoked = 0
def training_step(self, batch, batch_idx):
output = super(... | def test_trainer_min_steps_and_min_epochs_not_reached(tmpdir, caplog):
| """Test that min_epochs/min_steps in Trainer are enforced even if EarlyStopping is triggered."""
class TestModel(BoringModel):
training_step_invoked = 0
def training_step(self, batch, batch_idx):
output = super().training_step(batch, batch_idx)
output["loss"] = output["... | .floor(num_train_samples * 1.5)
trainer = Trainer(**trainer_kwargs)
trainer.fit(model)
assert trainer.state.finished, f"Training failed with {trainer.state}"
assert trainer.current_epoch > 0
assert trainer.global_step >= math.floor(num_train_samples * 1.5), "Model did not train for at least min_ste... | 93 | 93 | 312 | 18 | 75 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_min_steps_and_min_epochs_not_reached | test_trainer_min_steps_and_min_epochs_not_reached | 585 | 616 | 585 | 585 | 6220327a152281646982c6b15d2376471dcca167 | bigcode/the-stack | train |
ac960638dd8b8e0b6310bf94 | train | function | def test_detect_anomaly_nan(tmpdir):
class NanModel(BoringModel):
def training_step(self, batch, batch_idx):
output = super().training_step(batch, batch_idx)
output["loss"] = output["loss"] * torch.tensor(float("nan"))
return output
model = NanModel()
trainer = T... | def test_detect_anomaly_nan(tmpdir):
| class NanModel(BoringModel):
def training_step(self, batch, batch_idx):
output = super().training_step(batch, batch_idx)
output["loss"] = output["loss"] * torch.tensor(float("nan"))
return output
model = NanModel()
trainer = Trainer(default_root_dir=tmpdir, detec... | **kwargs)
model = CustomBoringModel()
trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=4, callbacks=[TestMetricRestartCallback()])
trainer.fit(model)
trainer.validate(model)
trainer.test(model)
trainer.predict(model)
def test_detect_anomaly_nan(tmpdir):
| 64 | 64 | 140 | 9 | 55 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_detect_anomaly_nan | test_detect_anomaly_nan | 1,942 | 1,955 | 1,942 | 1,942 | 396a712fa804e2b0f8ba9f610e7dbf89d6f698c9 | bigcode/the-stack | train |
cccd5efea6f87da6160f49d0 | train | function | @pytest.mark.parametrize("train_batches, max_steps, log_interval", [(10, 10, 1), (3, 10, 1), (3, 10, 5)])
@patch("pytorch_lightning.loggers.tensorboard.TensorBoardLogger.log_metrics")
def test_log_every_n_steps(log_metrics_mock, tmpdir, train_batches, max_steps, log_interval):
class TestModel(BoringModel):
... | @pytest.mark.parametrize("train_batches, max_steps, log_interval", [(10, 10, 1), (3, 10, 1), (3, 10, 5)])
@patch("pytorch_lightning.loggers.tensorboard.TensorBoardLogger.log_metrics")
def test_log_every_n_steps(log_metrics_mock, tmpdir, train_batches, max_steps, log_interval):
| class TestModel(BoringModel):
def training_step(self, *args, **kwargs):
self.log("foo", -1)
return super().training_step(*args, **kwargs)
model = TestModel()
trainer = Trainer(
default_root_dir=tmpdir,
log_every_n_steps=log_interval,
limit_train_batch... | @pytest.mark.parametrize("train_batches, max_steps, log_interval", [(10, 10, 1), (3, 10, 1), (3, 10, 5)])
@patch("pytorch_lightning.loggers.tensorboard.TensorBoardLogger.log_metrics")
def test_log_every_n_steps(log_metrics_mock, tmpdir, train_batches, max_steps, log_interval):
| 79 | 64 | 214 | 79 | 0 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_log_every_n_steps | test_log_every_n_steps | 1,241 | 1,259 | 1,241 | 1,243 | 692427619d8117bf5a871f3bb9176afcefb38071 | bigcode/the-stack | train |
218684c82947635722717cc4 | train | function | @pytest.mark.parametrize(
["accumulate_grad_batches", "limit_train_batches"],
[
({1: 2, 3: 4}, 1.0),
({1: 2, 3: 4}, 0.5), # not to be divisible by accumulate_grad_batches on purpose
(3, 1.0),
(3, 0.8), # not to be divisible by accumulate_grad_batches on purpose
(4, 1.0)... | @pytest.mark.parametrize(
["accumulate_grad_batches", "limit_train_batches"],
[
({1: 2, 3: 4}, 1.0),
({1: 2, 3: 4}, 0.5), # not to be divisible by accumulate_grad_batches on purpose
(3, 1.0),
(3, 0.8), # not to be divisible by accumulate_grad_batches on purpose
(4, 1.0)... | """Verify optimizer.step() applied to last batch while grad accumulation."""
class TestModel(BoringModel):
def state_dict(self, *args, **kwargs):
return deepcopy(super().state_dict(*args, **kwargs))
def check(self, d1, d2, equal=True):
keys = d1.keys() | d2.keys()
... | an instance.*"
):
Trainer(default_root_dir=tmpdir, accumulate_grad_batches=7, callbacks=[GradientAccumulationScheduler({0: 2})])
@pytest.mark.parametrize(
["accumulate_grad_batches", "limit_train_batches"],
[
({1: 2, 3: 4}, 1.0),
({1: 2, 3: 4}, 0.5), # not to be divisible by accumu... | 187 | 187 | 624 | 153 | 34 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_gradient_accumulation_scheduling_last_batch | test_gradient_accumulation_scheduling_last_batch | 176 | 246 | 176 | 187 | 6ca0e0da752b9570e45aaeca97cd3f47c64d5642 | bigcode/the-stack | train |
f1c9f796f6561a3894b9c759 | train | function | def test_loading_yaml(tmpdir):
hparams = {
"batch_size": 32,
"learning_rate": 0.001 * 8,
"optimizer_name": "adam",
}
# save tags
logger = tutils.get_default_logger(tmpdir)
logger.log_hyperparams(Namespace(some_str="a_str", an_int=1, a_float=2.0))
logger.log_hyperparams(h... | def test_loading_yaml(tmpdir):
| hparams = {
"batch_size": 32,
"learning_rate": 0.001 * 8,
"optimizer_name": "adam",
}
# save tags
logger = tutils.get_default_logger(tmpdir)
logger.log_hyperparams(Namespace(some_str="a_str", an_int=1, a_float=2.0))
logger.log_hyperparams(hparams)
logger.save()
... | # save as legacy meta_tags.csv
tags_path = os.path.join(path_expt_dir, "meta_tags.csv")
save_hparams_to_tags_csv(tags_path, hparams)
tags = load_hparams_from_tags_csv(tags_path)
assert hparams == tags
def test_loading_yaml(tmpdir):
| 64 | 64 | 174 | 7 | 56 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_loading_yaml | test_loading_yaml | 277 | 295 | 277 | 277 | 795bda3c9253a1dd4ec8220f361c61184875fd95 | bigcode/the-stack | train |
52b2f8ddb9e2381f88186c0a | train | class | class TestDummyModelForCheckpoint(BoringModel):
def validation_step(self, batch, batch_idx):
output = self.layer(batch)
loss = self.loss(batch, output)
self.log("x", loss)
def validation_epoch_end(self, outputs) -> None:
pass
| class TestDummyModelForCheckpoint(BoringModel):
| def validation_step(self, batch, batch_idx):
output = self.layer(batch)
loss = self.loss(batch, output)
self.log("x", loss)
def validation_epoch_end(self, outputs) -> None:
pass
| Model()
trainer = Trainer(default_root_dir=tmpdir, strategy=strategy, num_processes=num_processes, fast_dev_run=True)
trainer.fit(model)
trainer.validate(model)
trainer.test(model)
trainer.predict(model, model.val_dataloader())
class TestDummyModelForCheckpoint(BoringModel):
| 64 | 64 | 60 | 10 | 54 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | TestDummyModelForCheckpoint | TestDummyModelForCheckpoint | 1,693 | 1,700 | 1,693 | 1,693 | 8bce63d6f6ce54b39905940408ab59651a12c860 | bigcode/the-stack | train |
5d241741adb21601f76a2412 | train | function | @RunIf(omegaconf=True)
@pytest.mark.parametrize(
"trainer_params",
[{"max_epochs": 1, "accelerator": "gpu", "devices": 1}, {"max_epochs": 1, "accelerator": "gpu", "devices": [0]}],
)
@mock.patch("torch.cuda.is_available", return_value=True)
@mock.patch("torch.cuda.device_count", return_value=1)
def test_trainer... | @RunIf(omegaconf=True)
@pytest.mark.parametrize(
"trainer_params",
[{"max_epochs": 1, "accelerator": "gpu", "devices": 1}, {"max_epochs": 1, "accelerator": "gpu", "devices": [0]}],
)
@mock.patch("torch.cuda.is_available", return_value=True)
@mock.patch("torch.cuda.device_count", return_value=1)
def test_trainer... | config = OmegaConf.create(trainer_params)
Trainer(**config)
| @RunIf(omegaconf=True)
@pytest.mark.parametrize(
"trainer_params",
[{"max_epochs": 1, "accelerator": "gpu", "devices": 1}, {"max_epochs": 1, "accelerator": "gpu", "devices": [0]}],
)
@mock.patch("torch.cuda.is_available", return_value=True)
@mock.patch("torch.cuda.device_count", return_value=1)
def test_trainer... | 103 | 64 | 118 | 103 | 0 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_omegaconf | test_trainer_omegaconf | 1,195 | 1,204 | 1,195 | 1,202 | bd8b6935f1fddef0a3af05c5d78bc6a0d84341e4 | bigcode/the-stack | train |
b81064d905e55de265370506 | train | function | @pytest.mark.parametrize("precision", [32, pytest.param(16, marks=RunIf(min_gpus=1))])
def test_gradient_clipping_by_value(tmpdir, precision):
"""Test gradient clipping by value."""
tutils.reset_seed()
trainer = Trainer(
default_root_dir=tmpdir,
max_steps=1,
max_epochs=1,
ac... | @pytest.mark.parametrize("precision", [32, pytest.param(16, marks=RunIf(min_gpus=1))])
def test_gradient_clipping_by_value(tmpdir, precision):
| """Test gradient clipping by value."""
tutils.reset_seed()
trainer = Trainer(
default_root_dir=tmpdir,
max_steps=1,
max_epochs=1,
accelerator="auto",
devices=1,
precision=precision,
gradient_clip_algorithm="value",
gradient_clip_val=1e-10,
... | .05))
self.assertion_called = True
model = TestModel()
trainer.fit(model, ClassifDataModule())
assert model.assertion_called
@pytest.mark.parametrize("precision", [32, pytest.param(16, marks=RunIf(min_gpus=1))])
def test_gradient_clipping_by_value(tmpdir, precision):
| 71 | 71 | 237 | 37 | 33 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_gradient_clipping_by_value | test_gradient_clipping_by_value | 998 | 1,026 | 998 | 999 | bcc890d357c6915869b148fe9d5ac38f134c2dee | bigcode/the-stack | train |
51cf8abcdb83848c3c969a6c | train | function | def test_trainer_subclassing():
model = BoringModel()
# First way of pulling out args from signature is to list them
class TrainerSubclass(Trainer):
def __init__(self, custom_arg, *args, custom_kwarg="test", **kwargs):
super().__init__(*args, **kwargs)
self.custom_arg = cust... | def test_trainer_subclassing():
| model = BoringModel()
# First way of pulling out args from signature is to list them
class TrainerSubclass(Trainer):
def __init__(self, custom_arg, *args, custom_kwarg="test", **kwargs):
super().__init__(*args, **kwargs)
self.custom_arg = custom_arg
self.custom_k... | "] in (None, "ddp_cpu"):
trainer = Trainer(**trainer_kwargs)
else:
with pytest.deprecated_call(match=r"accelerator='.*'\)` has been deprecated in v1.5"):
trainer = Trainer(**trainer_kwargs)
assert isinstance(trainer.strategy, strategy_cls)
assert strategy_cls.strategy_name == st... | 101 | 101 | 338 | 8 | 92 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_subclassing | test_trainer_subclassing | 1,159 | 1,192 | 1,159 | 1,159 | 1c925e0552891758464d3ff52d2dc31ad342f3d4 | bigcode/the-stack | train |
cc3acaa6106b4fcd5bc89fb3 | train | function | @pytest.mark.parametrize("precision", [32, pytest.param(16, marks=RunIf(min_gpus=1))])
def test_gradient_clipping_by_norm(tmpdir, precision):
"""Test gradient clipping by norm."""
tutils.reset_seed()
trainer = Trainer(
default_root_dir=tmpdir,
max_steps=1,
max_epochs=1,
acce... | @pytest.mark.parametrize("precision", [32, pytest.param(16, marks=RunIf(min_gpus=1))])
def test_gradient_clipping_by_norm(tmpdir, precision):
| """Test gradient clipping by norm."""
tutils.reset_seed()
trainer = Trainer(
default_root_dir=tmpdir,
max_steps=1,
max_epochs=1,
accelerator="auto",
devices=1,
precision=precision,
gradient_clip_algorithm="norm",
gradient_clip_val=0.05,
)
... | deprecated in v1.5"
):
trainer.test(model)
assert trainer.interrupted
assert isinstance(handle_interrupt_callback.exception, MisconfigurationException)
@pytest.mark.parametrize("precision", [32, pytest.param(16, marks=RunIf(min_gpus=1))])
def test_gradient_clipping_by_norm(tmpdir, precision):
| 69 | 69 | 233 | 37 | 32 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_gradient_clipping_by_norm | test_gradient_clipping_by_norm | 968 | 995 | 968 | 969 | c7a049d058b16c30e380c895c39dc789257bab6b | bigcode/the-stack | train |
74ca700fdb7f1643f31d630b | train | function | @pytest.mark.parametrize("dataset_cls", [RandomDataset, RandomIterableDatasetWithLen, RandomIterableDataset])
def test_index_batch_sampler_wrapper_with_iterable_dataset(dataset_cls, tmpdir):
ds = dataset_cls(32, 8)
loader = DataLoader(ds)
is_iterable_dataset = isinstance(ds, IterableDataset)
class Cus... | @pytest.mark.parametrize("dataset_cls", [RandomDataset, RandomIterableDatasetWithLen, RandomIterableDataset])
def test_index_batch_sampler_wrapper_with_iterable_dataset(dataset_cls, tmpdir):
| ds = dataset_cls(32, 8)
loader = DataLoader(ds)
is_iterable_dataset = isinstance(ds, IterableDataset)
class CustomPredictionWriter(BasePredictionWriter):
def __init__(self, output_dir: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self.output_dir = output_dir
... | ainer_predict_ddp_spawn(tmpdir):
predict(tmpdir, strategy="ddp_spawn", accelerator="auto", devices=2)
@pytest.mark.parametrize("dataset_cls", [RandomDataset, RandomIterableDatasetWithLen, RandomIterableDataset])
def test_index_batch_sampler_wrapper_with_iterable_dataset(dataset_cls, tmpdir):
| 64 | 64 | 199 | 37 | 27 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_index_batch_sampler_wrapper_with_iterable_dataset | test_index_batch_sampler_wrapper_with_iterable_dataset | 1,413 | 1,431 | 1,413 | 1,415 | bb61c00fedf72745b13187ae43e555c3582676cc | bigcode/the-stack | train |
57533f1239cdf3a6b4631ec5 | train | function | @pytest.mark.parametrize("strategy", [None, pytest.param("ddp_spawn", marks=RunIf(skip_windows=True))])
def test_error_handling_all_stages(tmpdir, strategy):
model = TrainerStagesErrorsModel()
counter = ExceptionCounter()
trainer = Trainer(
default_root_dir=tmpdir,
strategy=strategy,
... | @pytest.mark.parametrize("strategy", [None, pytest.param("ddp_spawn", marks=RunIf(skip_windows=True))])
def test_error_handling_all_stages(tmpdir, strategy):
| model = TrainerStagesErrorsModel()
counter = ExceptionCounter()
trainer = Trainer(
default_root_dir=tmpdir,
strategy=strategy,
devices=1,
callbacks=counter,
fast_dev_run=True,
)
with pytest.raises(Exception, match=r"Error during train"):
trainer.fit(... | ExceptionCounter(Callback):
exceptions = 0
def on_exception(self, *_):
self.exceptions += 1
@pytest.mark.parametrize("strategy", [None, pytest.param("ddp_spawn", marks=RunIf(skip_windows=True))])
def test_error_handling_all_stages(tmpdir, strategy):
| 64 | 64 | 201 | 38 | 25 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_error_handling_all_stages | test_error_handling_all_stages | 1,866 | 1,893 | 1,866 | 1,867 | 0aaa801b9338340f0651904c8c3afa5eee13de66 | bigcode/the-stack | train |
cddc8466af88a951c07ef9fa | train | function | @RunIf(min_gpus=1)
def test_multiple_trainer_constant_memory_allocated(tmpdir):
"""This tests ensures calling the trainer several times reset the memory back to 0."""
class TestModel(BoringModel):
def training_step(self, batch, batch_idx):
loss = super().training_step(batch, batch_idx)
... | @RunIf(min_gpus=1)
def test_multiple_trainer_constant_memory_allocated(tmpdir):
| """This tests ensures calling the trainer several times reset the memory back to 0."""
class TestModel(BoringModel):
def training_step(self, batch, batch_idx):
loss = super().training_step(batch, batch_idx)
self.log("train_loss", loss["loss"])
return loss
de... | (
default_root_dir=tmpdir,
max_epochs=1,
limit_train_batches=5,
num_sanity_val_steps=0,
accelerator="gpu",
devices=2,
strategy="ddp",
)
# simulate random failure in training_step on rank 0
with pytest.raises(DeadlockDetectedException, match="CustomExc... | 102 | 102 | 342 | 20 | 82 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_multiple_trainer_constant_memory_allocated | test_multiple_trainer_constant_memory_allocated | 1,792 | 1,842 | 1,792 | 1,793 | 2c1bafedb0c6ea43b38655951f58a444b5bf39a8 | bigcode/the-stack | train |
0f6b9d63bd056599c9f03459 | train | function | def test_on_load_checkpoint_missing_callbacks(tmpdir):
"""Test a warning appears when callbacks in the checkpoint don't match callbacks provided when resuming."""
model = BoringModel()
chk = ModelCheckpoint(dirpath=tmpdir, save_last=True)
trainer = Trainer(default_root_dir=tmpdir, max_epochs=3, callba... | def test_on_load_checkpoint_missing_callbacks(tmpdir):
| """Test a warning appears when callbacks in the checkpoint don't match callbacks provided when resuming."""
model = BoringModel()
chk = ModelCheckpoint(dirpath=tmpdir, save_last=True)
trainer = Trainer(default_root_dir=tmpdir, max_epochs=3, callbacks=[chk, CustomCallbackOnLoadCheckpoint()])
traine... | )
assert os.path.exists(checkpoint.best_model_path), f"Could not find checkpoint at rank {trainer.global_rank}"
trainer.test()
class CustomCallbackOnLoadCheckpoint(Callback):
def state_dict(self) -> dict:
return {"a": None}
def test_on_load_checkpoint_missing_callbacks(tmpdir):
| 64 | 64 | 128 | 10 | 54 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_on_load_checkpoint_missing_callbacks | test_on_load_checkpoint_missing_callbacks | 1,722 | 1,733 | 1,722 | 1,722 | 8fe43905d174a8882c0aff1c71ec6d3e7d736ce1 | bigcode/the-stack | train |
853fbbc41b02e324c1ef76d9 | train | function | def test_spawn_predict_return_predictions(tmpdir):
"""Test that `return_predictions=True` raise a MisconfigurationException with spawn strategies."""
model = BoringModel()
trainer = Trainer(default_root_dir=tmpdir, accelerator="cpu", strategy="ddp_spawn", devices=2, fast_dev_run=True)
assert isinstance(... | def test_spawn_predict_return_predictions(tmpdir):
| """Test that `return_predictions=True` raise a MisconfigurationException with spawn strategies."""
model = BoringModel()
trainer = Trainer(default_root_dir=tmpdir, accelerator="cpu", strategy="ddp_spawn", devices=2, fast_dev_run=True)
assert isinstance(trainer.strategy, DDPSpawnStrategy)
with pytest... | able_dataset else batch_indices
cb = CustomPredictionWriter(tmpdir)
trainer = Trainer(default_root_dir=tmpdir, callbacks=cb)
predictions = trainer.predict(BoringModel(), dataloaders=loader)
assert len(predictions) == 8
def test_spawn_predict_return_predictions(tmpdir):
| 64 | 64 | 115 | 9 | 54 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_spawn_predict_return_predictions | test_spawn_predict_return_predictions | 1,434 | 1,440 | 1,434 | 1,434 | 3cfc4768935862aa61913b00a172265f54c5b025 | bigcode/the-stack | train |
b8d0ae60e9456c80d0e74b5d | train | class | class CustomCallbackOnLoadCheckpoint(Callback):
def state_dict(self) -> dict:
return {"a": None}
| class CustomCallbackOnLoadCheckpoint(Callback):
| def state_dict(self) -> dict:
return {"a": None}
| _epochs=2, strategy="ddp_spawn", num_processes=2, callbacks=[checkpoint]
)
trainer.fit(model)
assert os.path.exists(checkpoint.best_model_path), f"Could not find checkpoint at rank {trainer.global_rank}"
trainer.test()
class CustomCallbackOnLoadCheckpoint(Callback):
| 64 | 64 | 25 | 9 | 55 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | CustomCallbackOnLoadCheckpoint | CustomCallbackOnLoadCheckpoint | 1,717 | 1,719 | 1,717 | 1,717 | 73516ec5046c151910c11617aca8f173e6d06a38 | bigcode/the-stack | train |
0daa3a5fcd210feca89089aa | train | function | def test_check_val_every_n_epoch_exception(tmpdir):
with pytest.raises(MisconfigurationException, match="should be an integer."):
Trainer(default_root_dir=tmpdir, max_epochs=1, check_val_every_n_epoch=1.2)
| def test_check_val_every_n_epoch_exception(tmpdir):
| with pytest.raises(MisconfigurationException, match="should be an integer."):
Trainer(default_root_dir=tmpdir, max_epochs=1, check_val_every_n_epoch=1.2)
| ",
"training_step",
"backward",
# 3
"training_step",
"zero_grad",
"backward",
# 4
"step",
"training_step",
"backward",
]
def test_check_val_every_n_epoch_exception(tmpdir):
| 63 | 64 | 52 | 11 | 52 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_check_val_every_n_epoch_exception | test_check_val_every_n_epoch_exception | 1,650 | 1,653 | 1,650 | 1,651 | b4e15bd79e9246ac88772a6aea2ab1323fb95267 | bigcode/the-stack | train |
0ad189ac6f59c9992d84cc00 | train | function | @pytest.mark.parametrize("enable_progress_bar", [False, True])
@pytest.mark.parametrize("datamodule", [False, True])
def test_trainer_predict_cpu(tmpdir, datamodule, enable_progress_bar):
predict(tmpdir, datamodule=datamodule, enable_progress_bar=enable_progress_bar)
| @pytest.mark.parametrize("enable_progress_bar", [False, True])
@pytest.mark.parametrize("datamodule", [False, True])
def test_trainer_predict_cpu(tmpdir, datamodule, enable_progress_bar):
| predict(tmpdir, datamodule=datamodule, enable_progress_bar=enable_progress_bar)
| .zeros(1, requires_grad=True)
assert x.expand_as(x).grad_fn is not None
@pytest.mark.parametrize("enable_progress_bar", [False, True])
@pytest.mark.parametrize("datamodule", [False, True])
def test_trainer_predict_cpu(tmpdir, datamodule, enable_progress_bar):
| 64 | 64 | 64 | 43 | 20 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_predict_cpu | test_trainer_predict_cpu | 1,384 | 1,387 | 1,384 | 1,386 | ef329e7ed77a7d96775e0dd2e323a0d4f4a7e53b | bigcode/the-stack | train |
dee229667ffe5917720ade5e | train | function | @pytest.mark.parametrize(
["benchmark_", "deterministic", "expected"],
[
(None, False, True),
(None, True, False),
(True, False, True),
(True, True, True),
(False, True, False),
(False, False, False),
],
)
def test_benchmark_option(benchmark_, deterministic, e... | @pytest.mark.parametrize(
["benchmark_", "deterministic", "expected"],
[
(None, False, True),
(None, True, False),
(True, False, True),
(True, True, True),
(False, True, False),
(False, False, False),
],
)
def test_benchmark_option(benchmark_, deterministic, e... | """Verify benchmark option."""
original_val = torch.backends.cudnn.benchmark
if benchmark_ and deterministic:
with pytest.warns(UserWarning, match="You passed `deterministic=True` and `benchmark=True`"):
trainer = Trainer(benchmark=benchmark_, deterministic=deterministic)
else:
... | @pytest.mark.parametrize(
["benchmark_", "deterministic", "expected"],
[
(None, False, True),
(None, True, False),
(True, False, True),
(True, True, True),
(False, True, False),
(False, False, False),
],
)
def test_benchmark_option(benchmark_, deterministic, e... | 81 | 64 | 199 | 81 | 0 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_benchmark_option | test_benchmark_option | 640 | 664 | 640 | 651 | 1e31800f401353410ec349f9c4879541fa837cb3 | bigcode/the-stack | train |
0365fe9d756372eb6fc6bedd | train | class | class ExceptionCounter(Callback):
exceptions = 0
def on_exception(self, *_):
self.exceptions += 1
| class ExceptionCounter(Callback):
| exceptions = 0
def on_exception(self, *_):
self.exceptions += 1
| Error during train")
def on_validation_start(self) -> None:
raise Exception("Error during validation")
def on_test_start(self) -> None:
raise Exception("Error during test")
def on_predict_start(self) -> None:
raise Exception("Error during predict")
class ExceptionCounter(Callback)... | 64 | 64 | 27 | 6 | 58 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | ExceptionCounter | ExceptionCounter | 1,859 | 1,863 | 1,859 | 1,859 | 91abf150e2908c77ba2435ff1ba5c6ef48873a14 | bigcode/the-stack | train |
6763525cc12a03614345284d | train | function | @pytest.mark.parametrize(
"strategy,num_processes", [(None, 1), pytest.param("ddp_spawn", 1, marks=RunIf(skip_windows=True))]
)
def test_model_in_correct_mode_during_stages(tmpdir, strategy, num_processes):
model = TrainerStagesModel()
trainer = Trainer(default_root_dir=tmpdir, strategy=strategy, num_proces... | @pytest.mark.parametrize(
"strategy,num_processes", [(None, 1), pytest.param("ddp_spawn", 1, marks=RunIf(skip_windows=True))]
)
def test_model_in_correct_mode_during_stages(tmpdir, strategy, num_processes):
| model = TrainerStagesModel()
trainer = Trainer(default_root_dir=tmpdir, strategy=strategy, num_processes=num_processes, fast_dev_run=True)
trainer.fit(model)
trainer.validate(model)
trainer.test(model)
trainer.predict(model, model.val_dataloader())
| .model.training
assert not self.training
@pytest.mark.parametrize(
"strategy,num_processes", [(None, 1), pytest.param("ddp_spawn", 1, marks=RunIf(skip_windows=True))]
)
def test_model_in_correct_mode_during_stages(tmpdir, strategy, num_processes):
| 64 | 64 | 114 | 55 | 8 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_model_in_correct_mode_during_stages | test_model_in_correct_mode_during_stages | 1,681 | 1,690 | 1,681 | 1,684 | 8d862ad8b8b066597b97868f0b6027b83570b792 | bigcode/the-stack | train |
c72e105f7a24c7568df9768f | train | function | def test_exception_when_testing_or_validating_with_fast_dev_run():
trainer = Trainer(fast_dev_run=True)
trainer.state.fn = TrainerFn.TESTING
with pytest.raises(MisconfigurationException, match=r"with `fast_dev_run=True`. .* pass an exact checkpoint path"):
trainer._Trainer__set_ckpt_path(ckpt_path="... | def test_exception_when_testing_or_validating_with_fast_dev_run():
| trainer = Trainer(fast_dev_run=True)
trainer.state.fn = TrainerFn.TESTING
with pytest.raises(MisconfigurationException, match=r"with `fast_dev_run=True`. .* pass an exact checkpoint path"):
trainer._Trainer__set_ckpt_path(ckpt_path="best", model_provided=False, model_connected=True)
| test_check_val_every_n_epoch_exception(tmpdir):
with pytest.raises(MisconfigurationException, match="should be an integer."):
Trainer(default_root_dir=tmpdir, max_epochs=1, check_val_every_n_epoch=1.2)
def test_exception_when_testing_or_validating_with_fast_dev_run():
| 64 | 64 | 84 | 13 | 51 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_exception_when_testing_or_validating_with_fast_dev_run | test_exception_when_testing_or_validating_with_fast_dev_run | 1,656 | 1,660 | 1,656 | 1,656 | ba22595bec0d7da03d88f11eb9c7def5f49e9462 | bigcode/the-stack | train |
74f228718882b9094c79b29d | train | function | @pytest.mark.parametrize("limit_val_batches", [0.0, 1, 1.0, 0.3])
def test_num_sanity_val_steps_neg_one(tmpdir, limit_val_batches):
"""Test that `num_sanity_val_steps=-1` runs through all validation data once, and as many batches as limited by
`limit_val_batches` Trainer argument."""
class CustomModel(Bori... | @pytest.mark.parametrize("limit_val_batches", [0.0, 1, 1.0, 0.3])
def test_num_sanity_val_steps_neg_one(tmpdir, limit_val_batches):
| """Test that `num_sanity_val_steps=-1` runs through all validation data once, and as many batches as limited by
`limit_val_batches` Trainer argument."""
class CustomModel(BoringModel):
def validation_step(self, batch, batch_idx, dataloader_idx):
return super().validation_step(batch, bat... | epoch_loop._evaluation_step,
) as mocked:
trainer.fit(model)
assert mocked.call_count == sum(
min(num_sanity_val_steps, num_batches) for num_batches in trainer.num_val_batches
)
@pytest.mark.parametrize("limit_val_batches", [0.0, 1, 1.0, 0.3])
def test_num_sanity_val_steps_neg_on... | 88 | 88 | 296 | 42 | 46 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_num_sanity_val_steps_neg_one | test_num_sanity_val_steps_neg_one | 1,089 | 1,116 | 1,089 | 1,090 | 10c91a721d02fc848a40d8d6acc3ce90ace04530 | bigcode/the-stack | train |
c8a4349b9cdcfc048bbd5ee6 | train | function | def test_loading_meta_tags(tmpdir):
"""test for backward compatibility to meta_tags.csv."""
hparams = {
"batch_size": 32,
"learning_rate": 0.001 * 8,
"optimizer_name": "adam",
}
# save tags
logger = tutils.get_default_logger(tmpdir)
logger.log_hyperparams(Namespace(some_... | def test_loading_meta_tags(tmpdir):
| """test for backward compatibility to meta_tags.csv."""
hparams = {
"batch_size": 32,
"learning_rate": 0.001 * 8,
"optimizer_name": "adam",
}
# save tags
logger = tutils.get_default_logger(tmpdir)
logger.log_hyperparams(Namespace(some_str="a_str", an_int=1, a_float=2.0))... | Model()
trainer = Trainer(
accumulate_grad_batches=accumulate_grad_batches,
max_epochs=2,
limit_train_batches=limit_train_batches,
limit_val_batches=0,
default_root_dir=tmpdir,
enable_progress_bar=False,
)
trainer.fit(model)
def test_loading_meta_tags(tmpdir)... | 68 | 68 | 229 | 8 | 60 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_loading_meta_tags | test_loading_meta_tags | 249 | 274 | 249 | 249 | 247809910c8a69141617028671171ce5568c6502 | bigcode/the-stack | train |
b1e5c8fc62fd18c997176abd | train | function | def test_trainer_accumulate_grad_batches_incorrect_value(tmpdir):
with pytest.raises(MisconfigurationException, match=".*should be an int or a dict.*"):
Trainer(default_root_dir=tmpdir, accumulate_grad_batches=(2, 5))
| def test_trainer_accumulate_grad_batches_incorrect_value(tmpdir):
| with pytest.raises(MisconfigurationException, match=".*should be an int or a dict.*"):
Trainer(default_root_dir=tmpdir, accumulate_grad_batches=(2, 5))
| point_path=ckpt_path, hparams_file=hparams_path, strict=False)
# todo: specify the possible exception
except Exception:
failed = True
assert not failed, "Model should be loaded due to strict=False."
def test_trainer_accumulate_grad_batches_incorrect_value(tmpdir):
| 64 | 64 | 53 | 14 | 50 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_accumulate_grad_batches_incorrect_value | test_trainer_accumulate_grad_batches_incorrect_value | 164 | 166 | 164 | 164 | 0c72eb88760d858231f3fcd3a8eed8d87b6a5fa0 | bigcode/the-stack | train |
fea388b31a8957adb6c47d3c | train | function | def test_trainer_max_steps_accumulate_batches(tmpdir):
"""Verify model trains according to specified max steps with grad accumulated batches."""
model = BoringModel()
num_train_samples = math.floor(len(model.train_dataloader()) * 0.5)
# define less train steps than epochs
trainer = Trainer(
... | def test_trainer_max_steps_accumulate_batches(tmpdir):
| """Verify model trains according to specified max steps with grad accumulated batches."""
model = BoringModel()
num_train_samples = math.floor(len(model.train_dataloader()) * 0.5)
# define less train steps than epochs
trainer = Trainer(
limit_train_batches=0.5,
default_root_dir=tmpd... | not been met. Training will continue"
num_messages = sum(1 for record in caplog.records if message in record.message)
assert num_messages == min_epochs - 2
assert model.training_step_invoked == min_epochs * 2
def test_trainer_max_steps_accumulate_batches(tmpdir):
| 64 | 64 | 158 | 12 | 51 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_max_steps_accumulate_batches | test_trainer_max_steps_accumulate_batches | 619 | 637 | 619 | 619 | 769a8412c5d164812903ad1b899aec689864018e | bigcode/the-stack | train |
ff2da76b057dc1c7d4052dc1 | train | function | @pytest.mark.parametrize("limit_val_batches", [0.0, 1, 1.0, 0.5, 5])
def test_num_sanity_val_steps(tmpdir, limit_val_batches):
"""Test that the number of sanity check batches is clipped to `limit_val_batches`."""
class CustomModel(BoringModel):
def validation_step(self, batch, batch_idx, dataloader_idx... | @pytest.mark.parametrize("limit_val_batches", [0.0, 1, 1.0, 0.5, 5])
def test_num_sanity_val_steps(tmpdir, limit_val_batches):
| """Test that the number of sanity check batches is clipped to `limit_val_batches`."""
class CustomModel(BoringModel):
def validation_step(self, batch, batch_idx, dataloader_idx):
return super().validation_step(batch, batch_idx)
def val_dataloader(self):
return [DataLoad... | ()
Trainer(accelerator="gpu", devices=num_gpus, auto_select_gpus=True)
with pytest.raises(MisconfigurationException, match=r".*But your machine only has.*"):
Trainer(accelerator="gpu", devices=num_gpus + 1, auto_select_gpus=True)
@pytest.mark.parametrize("limit_val_batches", [0.0, 1, 1.0, 0.5, 5])
def ... | 105 | 105 | 351 | 43 | 62 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_num_sanity_val_steps | test_num_sanity_val_steps | 1,048 | 1,086 | 1,048 | 1,049 | 70faf2a2c96e38e0fab91512ed58fbdd5e0885bb | bigcode/the-stack | train |
d23b77934f1255e55f2fbb1a | train | function | @pytest.mark.parametrize(
["trainer_kwargs", "strategy_cls", "strategy_name", "accelerator_cls", "devices"],
[
({"accelerator": None}, SingleDeviceStrategy, "single_device", CPUAccelerator, 1),
({"accelerator": "dp"}, DDPStrategy, "ddp", CPUAccelerator, 1),
({"accelerator": "ddp"}, DDPSt... | @pytest.mark.parametrize(
["trainer_kwargs", "strategy_cls", "strategy_name", "accelerator_cls", "devices"],
[
({"accelerator": None}, SingleDeviceStrategy, "single_device", CPUAccelerator, 1),
({"accelerator": "dp"}, DDPStrategy, "ddp", CPUAccelerator, 1),
({"accelerator": "ddp"}, DDPSt... | if trainer_kwargs.get("gpus") is not None:
monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
monkeypatch.setattr(torch.cuda, "device_count", lambda: trainer_kwargs["gpus"])
if trainer_kwargs["accelerator"] in (None, "ddp_cpu"):
trainer = Trainer(**trainer_kwargs)
else:
... | @pytest.mark.parametrize(
["trainer_kwargs", "strategy_cls", "strategy_name", "accelerator_cls", "devices"],
[
({"accelerator": None}, SingleDeviceStrategy, "single_device", CPUAccelerator, 1),
({"accelerator": "dp"}, DDPStrategy, "ddp", CPUAccelerator, 1),
({"accelerator": "ddp"}, DDPSt... | 620 | 230 | 769 | 620 | 0 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_config_accelerator | test_trainer_config_accelerator | 1,119 | 1,156 | 1,119 | 1,142 | c7e49b47075a275770853f9ce73e66b0cacb277b | bigcode/the-stack | train |
1580ba297f7f3a849e99eb79 | train | class | class TestLightningDataModule(LightningDataModule):
def __init__(self, dataloaders):
super().__init__()
self._dataloaders = dataloaders
def test_dataloader(self):
return self._dataloaders
def predict_dataloader(self):
return self._dataloaders
| class TestLightningDataModule(LightningDataModule):
| def __init__(self, dataloaders):
super().__init__()
self._dataloaders = dataloaders
def test_dataloader(self):
return self._dataloaders
def predict_dataloader(self):
return self._dataloaders
| ,
max_steps=max_steps,
)
trainer.fit(model)
expected_calls = [call(metrics=ANY, step=s) for s in range(log_interval - 1, max_steps, log_interval)]
log_metrics_mock.assert_has_calls(expected_calls)
class TestLightningDataModule(LightningDataModule):
| 64 | 64 | 71 | 11 | 53 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | TestLightningDataModule | TestLightningDataModule | 1,262 | 1,271 | 1,262 | 1,262 | fe7b003799cf733738f83a4f00a2a92dd1802a9f | bigcode/the-stack | train |
b980cd9adf7968b70ba0ec87 | train | function | @pytest.mark.parametrize(
"save_top_k,save_last,expected_files",
[
pytest.param(-1, False, [f"epoch={i}.ckpt" for i in range(5)], id="CASE K=-1 (all)"),
pytest.param(1, False, {"epoch=4.ckpt"}, id="CASE K=1 (2.5, epoch 4)"),
pytest.param(2, False, [f"epoch={i}.ckpt" for i in (2, 4)], id... | @pytest.mark.parametrize(
"save_top_k,save_last,expected_files",
[
pytest.param(-1, False, [f"epoch={i}.ckpt" for i in range(5)], id="CASE K=-1 (all)"),
pytest.param(1, False, {"epoch=4.ckpt"}, id="CASE K=1 (2.5, epoch 4)"),
pytest.param(2, False, [f"epoch={i}.ckpt" for i in (2, 4)], id... | """Test ModelCheckpoint options."""
def mock_save_function(filepath, *args):
open(filepath, "a").close()
# simulated losses
losses = [10, 9, 2.8, 5, 2.5]
checkpoint_callback = ModelCheckpoint(
dirpath=tmpdir,
filename="{epoch}",
monitor="checkpoint_on",
sav... | @pytest.mark.parametrize(
"save_top_k,save_last,expected_files",
[
pytest.param(-1, False, [f"epoch={i}.ckpt" for i in range(5)], id="CASE K=-1 (all)"),
pytest.param(1, False, {"epoch=4.ckpt"}, id="CASE K=1 (2.5, epoch 4)"),
pytest.param(2, False, [f"epoch={i}.ckpt" for i in (2, 4)], id... | 288 | 174 | 580 | 288 | 0 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_model_checkpoint_options | test_model_checkpoint_options | 298 | 346 | 298 | 309 | de0104b3a84cf4fa605f7fbf8743c1e951310b78 | bigcode/the-stack | train |
a4ec26ea5f426fe7df235730 | train | function | @RunIf(min_gpus=2, standalone=True)
@pytest.mark.parametrize(
"kwargs",
[
{"strategy": "dp", "devices": 1},
{"strategy": "dp", "devices": 2},
{"strategy": "ddp", "devices": 2},
],
)
def test_trainer_predict_standalone(tmpdir, kwargs):
predict(tmpdir, accelerator="gpu", **kwargs)
| @RunIf(min_gpus=2, standalone=True)
@pytest.mark.parametrize(
"kwargs",
[
{"strategy": "dp", "devices": 1},
{"strategy": "dp", "devices": 2},
{"strategy": "ddp", "devices": 2},
],
)
def test_trainer_predict_standalone(tmpdir, kwargs):
| predict(tmpdir, accelerator="gpu", **kwargs)
| @RunIf(min_gpus=2, standalone=True)
@pytest.mark.parametrize(
"kwargs",
[
{"strategy": "dp", "devices": 1},
{"strategy": "dp", "devices": 2},
{"strategy": "ddp", "devices": 2},
],
)
def test_trainer_predict_standalone(tmpdir, kwargs):
| 77 | 64 | 89 | 77 | 0 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_predict_standalone | test_trainer_predict_standalone | 1,390 | 1,400 | 1,390 | 1,399 | b5c38b6667cdfc4442befbebb9eb63be05457787 | bigcode/the-stack | train |
68361c09245bd680e746cd54 | train | function | def test_trainer_predict_grad(tmpdir):
class CustomBoringModel(BoringModel):
def predict_step(self, batch, batch_idx, dataloader_idx=0):
assert batch.expand_as(batch).grad_fn is None
return super().predict_step(batch, batch_idx, dataloader_idx)
predict(tmpdir, model=CustomBoring... | def test_trainer_predict_grad(tmpdir):
| class CustomBoringModel(BoringModel):
def predict_step(self, batch, batch_idx, dataloader_idx=0):
assert batch.expand_as(batch).grad_fn is None
return super().predict_step(batch, batch_idx, dataloader_idx)
predict(tmpdir, model=CustomBoringModel(), use_callbacks=False)
x = ... | 2 == 0:
return
return super().predict_step(batch, batch_idx, dataloader_idx)
with pytest.warns(UserWarning, match="predict returned None"):
predict(tmpdir, model=CustomBoringModel(), use_callbacks=False)
def test_trainer_predict_grad(tmpdir):
| 64 | 64 | 106 | 9 | 55 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_predict_grad | test_trainer_predict_grad | 1,372 | 1,381 | 1,372 | 1,372 | 6705dce32230cccd1b9bfdd5e5c462b4103a2844 | bigcode/the-stack | train |
a8824d5198056df6d5c35a72 | train | function | @pytest.mark.parametrize("url_ckpt", [True, False])
def test_strict_model_load(monkeypatch, tmpdir, tmpdir_server, url_ckpt):
"""Tests use case where trainer saves the model, and user loads it from tags independently."""
# set $TORCH_HOME, which determines torch hub's cache path, to tmpdir
monkeypatch.seten... | @pytest.mark.parametrize("url_ckpt", [True, False])
def test_strict_model_load(monkeypatch, tmpdir, tmpdir_server, url_ckpt):
| """Tests use case where trainer saves the model, and user loads it from tags independently."""
# set $TORCH_HOME, which determines torch hub's cache path, to tmpdir
monkeypatch.setenv("TORCH_HOME", tmpdir)
model = BoringModel()
# Extra layer
model.c_d3 = torch.nn.Linear(10, 12)
# logger fi... | = os.path.join(hparams_path, "hparams.yaml")
ckpt_path = (
f"http://{tmpdir_server[0]}:{tmpdir_server[1]}/{os.path.basename(new_weights_path)}"
if url_ckpt
else new_weights_path
)
model_2 = CustomModel.load_from_checkpoint(checkpoint_path=ckpt_path, hparams_file=hparams_path)
as... | 130 | 130 | 434 | 34 | 95 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_strict_model_load | test_strict_model_load | 111 | 161 | 111 | 112 | ac4d65567c047a69d3507fb1a3e6b2a3452cc28b | bigcode/the-stack | train |
0e9b50d5bbe4b3dd8d071c93 | train | function | @pytest.mark.parametrize("stage", ("fit", "validate", "test"))
def test_trainer_setup_call(tmpdir, stage):
"""Test setup call gets the correct stage."""
class CurrentModel(BoringModel):
def setup(self, stage):
self.stage = stage
class CurrentCallback(Callback):
def setup(self, ... | @pytest.mark.parametrize("stage", ("fit", "validate", "test"))
def test_trainer_setup_call(tmpdir, stage):
| """Test setup call gets the correct stage."""
class CurrentModel(BoringModel):
def setup(self, stage):
self.stage = stage
class CurrentCallback(Callback):
def setup(self, trainer, model, stage):
assert model is not None
self.stage = stage
model = Cu... | )
def test_trainer_pickle(tmpdir):
trainer = Trainer(max_epochs=1, default_root_dir=tmpdir)
pickle.dumps(trainer)
cloudpickle.dumps(trainer)
@pytest.mark.parametrize("stage", ("fit", "validate", "test"))
def test_trainer_setup_call(tmpdir, stage):
| 64 | 64 | 171 | 26 | 38 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_setup_call | test_trainer_setup_call | 1,213 | 1,238 | 1,213 | 1,214 | 182df1a611eccde46c93ddb2f7e5367251823c67 | bigcode/the-stack | train |
5758f315f3eb0945c6f54c54 | train | function | def test_trainer_accumulate_grad_batches_with_grad_acc_callback(tmpdir):
with pytest.raises(
MisconfigurationException, match=".*set both `accumulate_grad_batches` and passed an instance.*"
):
Trainer(default_root_dir=tmpdir, accumulate_grad_batches=7, callbacks=[GradientAccumulationScheduler({0... | def test_trainer_accumulate_grad_batches_with_grad_acc_callback(tmpdir):
| with pytest.raises(
MisconfigurationException, match=".*set both `accumulate_grad_batches` and passed an instance.*"
):
Trainer(default_root_dir=tmpdir, accumulate_grad_batches=7, callbacks=[GradientAccumulationScheduler({0: 2})])
| _accumulate_grad_batches_incorrect_value(tmpdir):
with pytest.raises(MisconfigurationException, match=".*should be an int or a dict.*"):
Trainer(default_root_dir=tmpdir, accumulate_grad_batches=(2, 5))
def test_trainer_accumulate_grad_batches_with_grad_acc_callback(tmpdir):
| 64 | 64 | 72 | 15 | 49 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_accumulate_grad_batches_with_grad_acc_callback | test_trainer_accumulate_grad_batches_with_grad_acc_callback | 169 | 173 | 169 | 169 | da0c6f8d3a66fb2094e0008dfedc2e1c098f3ab5 | bigcode/the-stack | train |
942575eb676a96104bfd47ef | train | function | def test_best_ckpt_evaluate_raises_warning_with_multiple_ckpt_callbacks():
"""Test that a warning is raised if best ckpt callback is used for evaluation configured with multiple
checkpoints."""
ckpt_callback1 = ModelCheckpoint()
ckpt_callback1.best_model_path = "foo_best_model.ckpt"
ckpt_callback2 ... | def test_best_ckpt_evaluate_raises_warning_with_multiple_ckpt_callbacks():
| """Test that a warning is raised if best ckpt callback is used for evaluation configured with multiple
checkpoints."""
ckpt_callback1 = ModelCheckpoint()
ckpt_callback1.best_model_path = "foo_best_model.ckpt"
ckpt_callback2 = ModelCheckpoint()
ckpt_callback2.best_model_path = "bar_best_model.ck... | Checkpoint` is not configured."):
trainer_fn(ckpt_path="best")
with pytest.raises(MisconfigurationException, match="`ModelCheckpoint` is not configured."):
trainer_fn(model, ckpt_path="best")
def test_best_ckpt_evaluate_raises_warning_with_multiple_ckpt_callbacks():
| 64 | 64 | 160 | 16 | 48 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_best_ckpt_evaluate_raises_warning_with_multiple_ckpt_callbacks | test_best_ckpt_evaluate_raises_warning_with_multiple_ckpt_callbacks | 782 | 794 | 782 | 782 | b9fafec5ea46b27f9b8d4aaef2668156f0de9e8b | bigcode/the-stack | train |
6a7b9f6f62064d7dd0a48712 | train | function | @pytest.mark.parametrize(
"max_epochs,max_steps,is_done,correct_trainer_epochs",
[
(None, -1, False, 1000),
(-1, -1, False, -1),
(5, -1, False, 5),
(-1, 10, False, -1),
(None, 0, True, -1),
(0, -1, True, 0),
(-1, 0, True, -1),
(0, -1, True, 0),
... | @pytest.mark.parametrize(
"max_epochs,max_steps,is_done,correct_trainer_epochs",
[
(None, -1, False, 1000),
(-1, -1, False, -1),
(5, -1, False, 5),
(-1, 10, False, -1),
(None, 0, True, -1),
(0, -1, True, 0),
(-1, 0, True, -1),
(0, -1, True, 0),
... | trainer = Trainer(max_epochs=max_epochs, max_steps=max_steps)
assert trainer.max_epochs == correct_trainer_epochs
assert trainer.max_steps == max_steps
assert trainer.fit_loop.done is is_done
# Make sure there is no timer
timer_callbacks = [c for c in trainer.callbacks if isinstance(c, Timer)]... | @pytest.mark.parametrize(
"max_epochs,max_steps,is_done,correct_trainer_epochs",
[
(None, -1, False, 1000),
(-1, -1, False, -1),
(5, -1, False, 5),
(-1, 10, False, -1),
(None, 0, True, -1),
(0, -1, True, 0),
(-1, 0, True, -1),
(0, -1, True, 0),
... | 145 | 67 | 225 | 145 | 0 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_max_steps_and_epochs_fit_loop_done | test_trainer_max_steps_and_epochs_fit_loop_done | 517 | 539 | 517 | 530 | 5d2b4bfda1ac9279b9ab555f06b182264a46bbf9 | bigcode/the-stack | train |
b2e9abbf07c09caa836470fa | train | function | @pytest.mark.parametrize("url_ckpt", [True, False])
def test_no_val_module(monkeypatch, tmpdir, tmpdir_server, url_ckpt):
"""Tests use case where trainer saves the model, and user loads it from tags independently."""
# set $TORCH_HOME, which determines torch hub's cache path, to tmpdir
monkeypatch.setenv("T... | @pytest.mark.parametrize("url_ckpt", [True, False])
def test_no_val_module(monkeypatch, tmpdir, tmpdir_server, url_ckpt):
| """Tests use case where trainer saves the model, and user loads it from tags independently."""
# set $TORCH_HOME, which determines torch hub's cache path, to tmpdir
monkeypatch.setenv("TORCH_HOME", str(tmpdir))
class CustomModel(BoringModel):
def __init__(self, lr=1e-2):
super().__i... | from pytorch_lightning.utilities.seed import seed_everything
from tests.helpers import BoringModel, RandomDataset
from tests.helpers.boring_model import RandomIterableDataset, RandomIterableDatasetWithLen
from tests.helpers.datamodules import ClassifDataModule
from tests.helpers.runif import RunIf
from tests.helpers.si... | 123 | 123 | 411 | 33 | 89 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_no_val_module | test_no_val_module | 68 | 108 | 68 | 69 | 267c1d0b10205524f97e2ce14dc665395e28bd6f | bigcode/the-stack | train |
6657c3cbcd31cd1588d614ec | train | function | def test_on_exception_hook(tmpdir):
"""Test the on_exception callback hook and the trainer interrupted flag."""
model = BoringModel()
class InterruptCallback(Callback):
def __init__(self):
super().__init__()
def on_train_batch_start(self, trainer, pl_module, batch, batch_idx):... | def test_on_exception_hook(tmpdir):
| """Test the on_exception callback hook and the trainer interrupted flag."""
model = BoringModel()
class InterruptCallback(Callback):
def __init__(self):
super().__init__()
def on_train_batch_start(self, trainer, pl_module, batch, batch_idx):
raise KeyboardInterrupt... | _run=True`"
assert model.validation_epoch_end_invoked, "did not run `validation_epoch_end` with `fast_dev_run=True`"
@pytest.mark.parametrize("track_grad_norm", [0, torch.tensor(1), "nan"])
def test_invalid_track_grad_norm(tmpdir, track_grad_norm):
with pytest.raises(MisconfigurationException, match="`track_g... | 113 | 113 | 377 | 8 | 105 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_on_exception_hook | test_on_exception_hook | 913 | 965 | 913 | 913 | 97f4bf0402c387c87e348c23a02873d027a0cefa | bigcode/the-stack | train |
9521e75e9351699f2d766190 | train | function | def test_disabled_validation(tmpdir):
"""Verify that `limit_val_batches=0` disables the validation loop unless `fast_dev_run=True`."""
class CurrentModel(BoringModel):
validation_step_invoked = False
validation_epoch_end_invoked = False
def validation_step(self, *args, **kwargs):
... | def test_disabled_validation(tmpdir):
| """Verify that `limit_val_batches=0` disables the validation loop unless `fast_dev_run=True`."""
class CurrentModel(BoringModel):
validation_step_invoked = False
validation_epoch_end_invoked = False
def validation_step(self, *args, **kwargs):
self.validation_step_invoked =... | trainer.fit(model)
after_state_dict = model.state_dict()
for key in before_state_dict.keys():
assert not torch.all(torch.eq(before_state_dict[key], after_state_dict[key]))
assert trainer.state.finished, f"Training failed with {trainer.state}"
assert trainer.current_epoch == 1
assert m... | 121 | 121 | 405 | 7 | 114 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_disabled_validation | test_disabled_validation | 859 | 904 | 859 | 859 | dbb0ff5a4459a6a01eff76636641e675e6113a18 | bigcode/the-stack | train |
ee51ad0e33ffe817a16a8031 | train | function | def test_trainer_predict_no_return(tmpdir):
"""Test trainer.predict warns when nothing is returned."""
class CustomBoringModel(BoringModel):
def predict_step(self, batch, batch_idx, dataloader_idx=0):
if (batch_idx + 1) % 2 == 0:
return
return super().predict_st... | def test_trainer_predict_no_return(tmpdir):
| """Test trainer.predict warns when nothing is returned."""
class CustomBoringModel(BoringModel):
def predict_step(self, batch, batch_idx, dataloader_idx=0):
if (batch_idx + 1) % 2 == 0:
return
return super().predict_step(batch, batch_idx, dataloader_idx)
wi... | num_samples = 1 if strategy == "ddp" else 2
assert len(results) == 2
assert len(results[0]) == num_samples
assert results[0][0].shape == torch.Size([1, 2])
def test_trainer_predict_no_return(tmpdir):
| 64 | 64 | 114 | 10 | 54 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_predict_no_return | test_trainer_predict_no_return | 1,358 | 1,369 | 1,358 | 1,358 | a0b01c5b032c2b62f3217043bdb7c25624e4d5c3 | bigcode/the-stack | train |
a99d5017727ab261e923f297 | train | function | @pytest.mark.parametrize(
["trainer_kwargs", "expected_device_ids"],
[
({}, [0]),
({"devices": 1}, [0]),
({"devices": 1}, [0]),
({"devices": "1"}, [0]),
({"devices": 2}, [0, 1]),
({"accelerator": "gpu", "devices": 1}, [0]),
({"accelerator": "gpu", "devices... | @pytest.mark.parametrize(
["trainer_kwargs", "expected_device_ids"],
[
({}, [0]),
({"devices": 1}, [0]),
({"devices": 1}, [0]),
({"devices": "1"}, [0]),
({"devices": 2}, [0, 1]),
({"accelerator": "gpu", "devices": 1}, [0]),
({"accelerator": "gpu", "devices... | if trainer_kwargs.get("accelerator") == "gpu":
monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
monkeypatch.setattr(torch.cuda, "device_count", lambda: 4)
elif trainer_kwargs.get("accelerator") == "ipu":
monkeypatch.setattr(pytorch_lightning.accelerators.ipu.IPUAccelerator, ... | @pytest.mark.parametrize(
["trainer_kwargs", "expected_device_ids"],
[
({}, [0]),
({"devices": 1}, [0]),
({"devices": 1}, [0]),
({"devices": "1"}, [0]),
({"devices": 2}, [0, 1]),
({"accelerator": "gpu", "devices": 1}, [0]),
({"accelerator": "gpu", "devices... | 274 | 123 | 413 | 274 | 0 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_config_device_ids | test_trainer_config_device_ids | 2,140 | 2,169 | 2,140 | 2,159 | 20864fd33e51b66f33f410bec71bf0ed06740790 | bigcode/the-stack | train |
fe6432437eaefbf9b37bf830 | train | function | @pytest.mark.parametrize(
["trainer_kwargs", "strategy_cls", "strategy_name", "accelerator_cls", "devices"],
[
({"strategy": None}, SingleDeviceStrategy, "single_device", CPUAccelerator, 1),
({"strategy": "dp"}, DDPStrategy, "ddp", CPUAccelerator, 1),
({"strategy": "ddp"}, DDPStrategy, "... | @pytest.mark.parametrize(
["trainer_kwargs", "strategy_cls", "strategy_name", "accelerator_cls", "devices"],
[
({"strategy": None}, SingleDeviceStrategy, "single_device", CPUAccelerator, 1),
({"strategy": "dp"}, DDPStrategy, "ddp", CPUAccelerator, 1),
({"strategy": "ddp"}, DDPStrategy, "... | if trainer_kwargs.get("accelerator") == "gpu":
monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
monkeypatch.setattr(torch.cuda, "device_count", lambda: trainer_kwargs["devices"])
trainer = Trainer(**trainer_kwargs)
assert isinstance(trainer.strategy, strategy_cls)
assert s... | @pytest.mark.parametrize(
["trainer_kwargs", "strategy_cls", "strategy_name", "accelerator_cls", "devices"],
[
({"strategy": None}, SingleDeviceStrategy, "single_device", CPUAccelerator, 1),
({"strategy": "dp"}, DDPStrategy, "ddp", CPUAccelerator, 1),
({"strategy": "ddp"}, DDPStrategy, "... | 1,435 | 256 | 1,683 | 1,435 | 0 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_config_strategy | test_trainer_config_strategy | 1,958 | 2,118 | 1,958 | 2,092 | b74a9a1e7aac4f2b88fa1310e513ff3a99be606f | bigcode/the-stack | train |
c23b3466da2cadecd6fc6db9 | train | class | class CustomException(Exception):
pass
| class CustomException(Exception):
| pass
| ` must be provided.*validate"):
trainer.validate()
with pytest.raises(MisconfigurationException, match=r"`model` must be provided.*test"):
trainer.test()
with pytest.raises(MisconfigurationException, match=r"`model` must be provided.*predict"):
trainer.predict()
class CustomException(Exc... | 64 | 64 | 8 | 5 | 59 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | CustomException | CustomException | 1,759 | 1,760 | 1,759 | 1,759 | 5532562fb5d30ffb0157b261acc843c12c8794ae | bigcode/the-stack | train |
5c56e17569a8f00394c83288 | train | function | @pytest.mark.parametrize("ckpt_path", (None, "best", "specific"))
@pytest.mark.parametrize("save_top_k", (-1, 0, 1, 2))
@pytest.mark.parametrize("fn", ("validate", "test", "predict"))
def test_checkpoint_path_input(tmpdir, ckpt_path, save_top_k, fn):
class TestModel(BoringModel):
def validation_step(self, b... | @pytest.mark.parametrize("ckpt_path", (None, "best", "specific"))
@pytest.mark.parametrize("save_top_k", (-1, 0, 1, 2))
@pytest.mark.parametrize("fn", ("validate", "test", "predict"))
def test_checkpoint_path_input(tmpdir, ckpt_path, save_top_k, fn):
| class TestModel(BoringModel):
def validation_step(self, batch, batch_idx):
self.log("foo", -batch_idx)
return super().validation_step(batch, batch_idx)
def test_step(self, *args):
return self.validation_step(*args)
def predict_step(self, batch, *_):
... | (False, False, False),
],
)
def test_benchmark_option(benchmark_, deterministic, expected):
"""Verify benchmark option."""
original_val = torch.backends.cudnn.benchmark
if benchmark_ and deterministic:
with pytest.warns(UserWarning, match="You passed `deterministic=True` and `benchmark... | 211 | 211 | 704 | 70 | 140 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_checkpoint_path_input | test_checkpoint_path_input | 667 | 736 | 667 | 670 | 6c1d311b35f8a0dc8ab8adc132666b8201019ba6 | bigcode/the-stack | train |
718d9ee735f9c673db09c0c6 | train | function | @RunIf(skip_windows=True)
def test_fit_test_synchronization(tmpdir):
"""Test that the trainer synchronizes processes before returning control back to the caller."""
tutils.set_random_main_port()
model = TestDummyModelForCheckpoint()
checkpoint = ModelCheckpoint(dirpath=tmpdir, monitor="x", mode="min", s... | @RunIf(skip_windows=True)
def test_fit_test_synchronization(tmpdir):
| """Test that the trainer synchronizes processes before returning control back to the caller."""
tutils.set_random_main_port()
model = TestDummyModelForCheckpoint()
checkpoint = ModelCheckpoint(dirpath=tmpdir, monitor="x", mode="min", save_top_k=1)
trainer = Trainer(
default_root_dir=tmpdir, ... | validation_step(self, batch, batch_idx):
output = self.layer(batch)
loss = self.loss(batch, output)
self.log("x", loss)
def validation_epoch_end(self, outputs) -> None:
pass
@RunIf(skip_windows=True)
def test_fit_test_synchronization(tmpdir):
| 64 | 64 | 144 | 16 | 47 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_fit_test_synchronization | test_fit_test_synchronization | 1,703 | 1,714 | 1,703 | 1,704 | d4c70cfb4cc84caa923657cc2e6921eafe9316d5 | bigcode/the-stack | train |
832806c4684e264db3989874 | train | function | @pytest.mark.parametrize(
"max_epochs,max_steps,incorrect_variable",
[
(-100, -1, "max_epochs"),
(1, -2, "max_steps"),
],
)
def test_trainer_max_steps_and_epochs_validation(max_epochs, max_steps, incorrect_variable):
"""Don't allow max_epochs or max_steps to be less than -1 or a float.""... | @pytest.mark.parametrize(
"max_epochs,max_steps,incorrect_variable",
[
(-100, -1, "max_epochs"),
(1, -2, "max_steps"),
],
)
def test_trainer_max_steps_and_epochs_validation(max_epochs, max_steps, incorrect_variable):
| """Don't allow max_epochs or max_steps to be less than -1 or a float."""
with pytest.raises(
MisconfigurationException,
match=f"`{incorrect_variable}` must be a non-negative integer or -1",
):
Trainer(max_epochs=max_epochs, max_steps=max_steps)
| _step == 3
@pytest.mark.parametrize(
"max_epochs,max_steps,incorrect_variable",
[
(-100, -1, "max_epochs"),
(1, -2, "max_steps"),
],
)
def test_trainer_max_steps_and_epochs_validation(max_epochs, max_steps, incorrect_variable):
| 64 | 64 | 120 | 59 | 4 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_max_steps_and_epochs_validation | test_trainer_max_steps_and_epochs_validation | 501 | 514 | 501 | 508 | 0e5e38804c92cde361773d058e68ecd0f1a5bb04 | bigcode/the-stack | train |
e8c370734b1ef7fe00288f9c | train | function | @RunIf(min_gpus=1)
def test_setup_hook_move_to_device_correctly(tmpdir):
"""Verify that if a user defines a layer in the setup hook function, this is moved to the correct device."""
class TestModel(BoringModel):
def setup(self, stage: str) -> None:
self.new_layer = torch.nn.Linear(2, 2)
... | @RunIf(min_gpus=1)
def test_setup_hook_move_to_device_correctly(tmpdir):
| """Verify that if a user defines a layer in the setup hook function, this is moved to the correct device."""
class TestModel(BoringModel):
def setup(self, stage: str) -> None:
self.new_layer = torch.nn.Linear(2, 2)
def training_step(self, batch, batch_idx):
output = sel... | = torch.utils.data.DataLoader(RandomDataset(32, 64))
model = TestModel()
trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=True)
trainer.fit(model, train_data)
@RunIf(min_gpus=1)
def test_setup_hook_move_to_device_correctly(tmpdir):
| 64 | 64 | 195 | 20 | 44 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_setup_hook_move_to_device_correctly | test_setup_hook_move_to_device_correctly | 1,543 | 1,564 | 1,543 | 1,544 | a2c9ebc6739397c0495b917b71bebe8a3fcbbb60 | bigcode/the-stack | train |
47496747c7879f39fdfd5359 | train | class | class CustomPredictionWriter(BasePredictionWriter):
write_on_batch_end_called = False
write_on_epoch_end_called = False
def __init__(self, output_dir: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self.output_dir = output_dir
def write_on_batch_end(self, trainer, pl_module,... | class CustomPredictionWriter(BasePredictionWriter):
| write_on_batch_end_called = False
write_on_epoch_end_called = False
def __init__(self, output_dir: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self.output_dir = output_dir
def write_on_batch_end(self, trainer, pl_module, prediction, batch_indices, *args, **kwargs):
... | log_metrics_mock.assert_has_calls(expected_calls)
class TestLightningDataModule(LightningDataModule):
def __init__(self, dataloaders):
super().__init__()
self._dataloaders = dataloaders
def test_dataloader(self):
return self._dataloaders
def predict_dataloader(self):
... | 89 | 89 | 299 | 8 | 80 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | CustomPredictionWriter | CustomPredictionWriter | 1,274 | 1,301 | 1,274 | 1,275 | 2038e60ccad44c10b2f7e21a9a8322f1473b78fd | bigcode/the-stack | train |
d5529bf63d5425b737a13103 | train | function | def test_trainer_max_steps_and_epochs(tmpdir):
"""Verify model trains according to specified max steps."""
model = BoringModel()
num_train_samples = math.floor(len(model.train_dataloader()) * 0.5)
# define less train steps than epochs
trainer_kwargs = {
"limit_train_batches": 0.5,
"... | def test_trainer_max_steps_and_epochs(tmpdir):
| """Verify model trains according to specified max steps."""
model = BoringModel()
num_train_samples = math.floor(len(model.train_dataloader()) * 0.5)
# define less train steps than epochs
trainer_kwargs = {
"limit_train_batches": 0.5,
"default_root_dir": tmpdir,
"max_epochs"... | == max_epochs
for ckpt in checkpoints:
model = TestModel()
state = pl_load(ckpt)
# Resume training
trainer = Trainer(default_root_dir=tmpdir, max_epochs=2, enable_progress_bar=False)
trainer.fit(model, ckpt_path=ckpt)
assert state["global_step"] + model.num_batches_s... | 104 | 104 | 348 | 11 | 92 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_max_steps_and_epochs | test_trainer_max_steps_and_epochs | 460 | 498 | 460 | 460 | b023380012a55b3273037291c18a77b48cc50001 | bigcode/the-stack | train |
8962d60d34b7509b14939f08 | train | function | @pytest.mark.parametrize(
["limit_train_batches", "global_step", "num_training_batches", "current_epoch", "should_train"],
[(0.2, 0, 0, 0, False), (0.5, 10, 2, 5, True)],
)
def test_disabled_training_for_insufficient_limit_train_batches(
tmpdir, limit_train_batches, global_step, num_training_batches, curren... | @pytest.mark.parametrize(
["limit_train_batches", "global_step", "num_training_batches", "current_epoch", "should_train"],
[(0.2, 0, 0, 0, False), (0.5, 10, 2, 5, True)],
)
def test_disabled_training_for_insufficient_limit_train_batches(
tmpdir, limit_train_batches, global_step, num_training_batches, curren... | """Verify when `limit_train_batches` is float & between [0.0, 1.0] and.
`int(self.num_training_batches * self.limit_train_batches) == 0`, the training loop is disabled.
"""
class CurrentModel(BoringModel):
training_step_invoked = False
training_epoch_end_invoked = False
def t... | None:
assert len(preds) == 1
assert preds[0].shape == torch.Size([1, 2])
assert preds[0].dtype == (torch.float64 if precision == 64 else torch.float32)
@pytest.mark.parametrize(
["limit_train_batches", "global_step", "num_training_batches", "current_epoch", "should_train"],
[(0.2, 0, 0,... | 144 | 144 | 481 | 94 | 50 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_disabled_training_for_insufficient_limit_train_batches | test_disabled_training_for_insufficient_limit_train_batches | 1,458 | 1,507 | 1,458 | 1,464 | d73e73d52f7929b2f89d952c5890c99ffb1ac5ee | bigcode/the-stack | train |
0c3854359c71d4ba90f9c182 | train | function | def test_trainer_access_in_configure_optimizers(tmpdir):
"""Verify that the configure optimizer function can reference the trainer."""
class TestModel(BoringModel):
def configure_optimizers(self):
assert self.trainer is not None, "Expect to have access to the trainer within `configure_optim... | def test_trainer_access_in_configure_optimizers(tmpdir):
| """Verify that the configure optimizer function can reference the trainer."""
class TestModel(BoringModel):
def configure_optimizers(self):
assert self.trainer is not None, "Expect to have access to the trainer within `configure_optimizers`"
train_data = torch.utils.data.DataLoader(Ran... | _root_dir=tmpdir, max_steps=max_steps, max_epochs=max_epochs)
trainer.fit(model, train_data)
assert trainer.global_step == global_step
trainer.fit(model, train_data)
assert trainer.global_step == global_step
def test_trainer_access_in_configure_optimizers(tmpdir):
| 64 | 64 | 115 | 14 | 49 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_trainer_access_in_configure_optimizers | test_trainer_access_in_configure_optimizers | 1,529 | 1,540 | 1,529 | 1,529 | cdbd813862d1b53932c4b785a4035c23932aa429 | bigcode/the-stack | train |
03776e361878e0a62250e807 | train | function | def test_model_freeze_unfreeze():
model = BoringModel()
model.freeze()
assert not model.training
for param in model.parameters():
assert not param.requires_grad
model.unfreeze()
assert model.training
for param in model.parameters():
assert param.requires_grad
| def test_model_freeze_unfreeze():
| model = BoringModel()
model.freeze()
assert not model.training
for param in model.parameters():
assert not param.requires_grad
model.unfreeze()
assert model.training
for param in model.parameters():
assert param.requires_grad
| only model weights"
assert "lr_schedulers" not in checkpoint, "checkpoint should contain only model weights"
# assert restoring train state fails
with pytest.raises(KeyError, match="checkpoint contains only the model"):
trainer._checkpoint_connector.restore(new_weights_path)
def test_model_freeze_... | 64 | 64 | 62 | 8 | 56 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_model_freeze_unfreeze | test_model_freeze_unfreeze | 389 | 399 | 389 | 389 | 2aa32ef53c36571893c96fe6dad791707b33295a | bigcode/the-stack | train |
9b21b3c21022c5394ef6bdb0 | train | function | @pytest.mark.parametrize("track_grad_norm", [0, torch.tensor(1), "nan"])
def test_invalid_track_grad_norm(tmpdir, track_grad_norm):
with pytest.raises(MisconfigurationException, match="`track_grad_norm` must be a positive number or 'inf'"):
Trainer(default_root_dir=tmpdir, track_grad_norm=track_grad_norm)
| @pytest.mark.parametrize("track_grad_norm", [0, torch.tensor(1), "nan"])
def test_invalid_track_grad_norm(tmpdir, track_grad_norm):
| with pytest.raises(MisconfigurationException, match="`track_grad_norm` must be a positive number or 'inf'"):
Trainer(default_root_dir=tmpdir, track_grad_norm=track_grad_norm)
| fast_dev_run=True`"
assert model.validation_epoch_end_invoked, "did not run `validation_epoch_end` with `fast_dev_run=True`"
@pytest.mark.parametrize("track_grad_norm", [0, torch.tensor(1), "nan"])
def test_invalid_track_grad_norm(tmpdir, track_grad_norm):
| 64 | 64 | 75 | 32 | 32 | catalys1/pytorch-lightning | tests/trainer/test_trainer.py | Python | test_invalid_track_grad_norm | test_invalid_track_grad_norm | 907 | 910 | 907 | 908 | 410aaf0c4785ea0609bcd5c80c69e520c21e3515 | bigcode/the-stack | train |
a784667be720ba7cc1d0960d | train | class | class RecordClickView(RedirectView):
model=None
def get_redirect_url(self, **kwargs):
try:
prom = self.model.objects.get(pk=kwargs['pk'])
except self.model.DoesNotExist:
return reverse('promotions:home')
if prom.promotion.has_link:
prom.re... | class RecordClickView(RedirectView):
| model=None
def get_redirect_url(self, **kwargs):
try:
prom = self.model.objects.get(pk=kwargs['pk'])
except self.model.DoesNotExist:
return reverse('promotions:home')
if prom.promotion.has_link:
prom.record_click()
return prom.link_... | from django.http import HttpResponseRedirect
from django.views.generic import TemplateView, RedirectView
from django.core.urlresolvers import reverse
class HomeView(TemplateView):
template_name = 'promotions/home.html'
class RecordClickView(RedirectView):
| 55 | 64 | 86 | 10 | 45 | endgame/django-oscar | oscar/apps/promotions/views.py | Python | RecordClickView | RecordClickView | 10 | 23 | 10 | 11 | 2ed419d2f5dd92eb8cc894c7c3b1fea621acb55a | bigcode/the-stack | train |
aa265e7e22b411889b163b23 | train | class | class HomeView(TemplateView):
template_name = 'promotions/home.html'
| class HomeView(TemplateView):
| template_name = 'promotions/home.html'
| from django.http import HttpResponseRedirect
from django.views.generic import TemplateView, RedirectView
from django.core.urlresolvers import reverse
class HomeView(TemplateView):
| 35 | 64 | 17 | 7 | 27 | endgame/django-oscar | oscar/apps/promotions/views.py | Python | HomeView | HomeView | 6 | 7 | 6 | 6 | 414e708c0b8c557cf6dca8a044efe628b4fec2cd | bigcode/the-stack | train |
a96be5dcd7ee79295b96b3fa | train | function | def load_loadable_repository_symbols(loadable_target_origin):
if loadable_target_origin:
loadable_targets = get_loadable_targets(
loadable_target_origin.python_file,
loadable_target_origin.module_name,
loadable_target_origin.package_name,
loadable_target_origi... | def load_loadable_repository_symbols(loadable_target_origin):
| if loadable_target_origin:
loadable_targets = get_loadable_targets(
loadable_target_origin.python_file,
loadable_target_origin.module_name,
loadable_target_origin.package_name,
loadable_target_origin.working_directory,
loadable_target_origin.attrib... | loadable_repository_symbols
)
@property
def loadable_repository_symbols(self):
return self._loadable_repository_symbols
@property
def code_pointers_by_repo_name(self):
return self._code_pointers_by_repo_name
def load_loadable_repository_symbols(loadable_target_origin):
| 64 | 64 | 128 | 11 | 52 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | load_loadable_repository_symbols | load_loadable_repository_symbols | 106 | 125 | 106 | 106 | 730f32801e97547f4102cb29ac604aacc3cbe133 | bigcode/the-stack | train |
66d3200c7d47b40085f39b90 | train | class | class DagsterApiServer(DagsterApiServicer):
# The loadable_target_origin is currently Noneable to support instaniating a server.
# This helps us test the ping methods, and incrementally migrate each method to
# the target passed in here instead of passing in a target in the argument.
def __init__(
... | class DagsterApiServer(DagsterApiServicer):
# The loadable_target_origin is currently Noneable to support instaniating a server.
# This helps us test the ping methods, and incrementally migrate each method to
# the target passed in here instead of passing in a target in the argument.
| def __init__(
self,
server_termination_event,
loadable_target_origin=None,
heartbeat=False,
heartbeat_timeout=30,
lazy_load_user_code=False,
fixed_server_id=None,
):
super(DagsterApiServer, self).__init__()
check.bool_param(heartbeat, "hea... | _pointers_by_repo_name(loadable_target_origin, loadable_repository_symbols):
repository_code_pointer_dict = {}
for loadable_repository_symbol in loadable_repository_symbols:
if loadable_target_origin.python_file:
repository_code_pointer_dict[
loadable_repository_symbol.reposi... | 256 | 256 | 4,286 | 66 | 189 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | DagsterApiServer | DagsterApiServer | 157 | 740 | 157 | 160 | 7cf82be0b4483aadf4840c52cb6bbaa87206b87a | bigcode/the-stack | train |
1503dbe2973cc8c805241638 | train | function | def open_server_process(
port,
socket,
loadable_target_origin=None,
max_workers=None,
heartbeat=False,
heartbeat_timeout=30,
fixed_server_id=None,
startup_timeout=20,
):
check.invariant((port or socket) and not (port and socket), "Set only port or socket")
check.opt_inst_param(lo... | def open_server_process(
port,
socket,
loadable_target_origin=None,
max_workers=None,
heartbeat=False,
heartbeat_timeout=30,
fixed_server_id=None,
startup_timeout=20,
):
| check.invariant((port or socket) and not (port and socket), "Set only port or socket")
check.opt_inst_param(loadable_target_origin, "loadable_target_origin", LoadableTargetOrigin)
check.opt_int_param(max_workers, "max_workers")
from dagster.core.test_utils import get_mocked_system_timezone
mocked_... | \"{' '.join(subprocess_args)}\". Most recent connection error: {str(last_error)}"
)
if server_process.poll() != None:
raise Exception(
f"gRPC server exited with return code {server_process.returncode} while starting up with the command: \"{' '.join(subprocess_args)}\""
... | 124 | 124 | 416 | 46 | 78 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | open_server_process | open_server_process | 950 | 1,006 | 950 | 959 | 265692e99bc471ca6c302bc061ed3c3297668faf | bigcode/the-stack | train |
69a322ab981c17bd595c5bbe | train | class | @whitelist_for_serdes
class GrpcServerLoadErrorEvent(namedtuple("GrpcServerLoadErrorEvent", "error_info")):
def __new__(cls, error_info):
return super(GrpcServerLoadErrorEvent, cls).__new__(
cls,
check.inst_param(error_info, "error_info", SerializableErrorInfo),
)
| @whitelist_for_serdes
class GrpcServerLoadErrorEvent(namedtuple("GrpcServerLoadErrorEvent", "error_info")):
| def __new__(cls, error_info):
return super(GrpcServerLoadErrorEvent, cls).__new__(
cls,
check.inst_param(error_info, "error_info", SerializableErrorInfo),
)
| StartedEvent", "")):
pass
@whitelist_for_serdes
class GrpcServerFailedToBindEvent(namedtuple("GrpcServerStartedEvent", "")):
pass
@whitelist_for_serdes
class GrpcServerLoadErrorEvent(namedtuple("GrpcServerLoadErrorEvent", "error_info")):
| 64 | 64 | 72 | 28 | 35 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | GrpcServerLoadErrorEvent | GrpcServerLoadErrorEvent | 753 | 759 | 753 | 754 | c9d265f182c98339756cde72b5ea6672fb232c4f | bigcode/the-stack | train |
d4d4132a48ba28495aefa45a | train | class | class DagsterGrpcServer:
def __init__(
self,
host="localhost",
port=None,
socket=None,
max_workers=None,
loadable_target_origin=None,
heartbeat=False,
heartbeat_timeout=30,
lazy_load_user_code=False,
ipc_output_file=None,
fixed_... | class DagsterGrpcServer:
| def __init__(
self,
host="localhost",
port=None,
socket=None,
max_workers=None,
loadable_target_origin=None,
heartbeat=False,
heartbeat_timeout=30,
lazy_load_user_code=False,
ipc_output_file=None,
fixed_server_id=None,
):
... | )
def _get_current_image(self):
return os.getenv("DAGSTER_CURRENT_IMAGE")
def GetCurrentImage(self, request, _context):
return api_pb2.GetCurrentImageReply(
serialized_current_image=serialize_dagster_namedtuple(
GetCurrentImageResult(
current_im... | 256 | 256 | 1,386 | 6 | 250 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | DagsterGrpcServer | DagsterGrpcServer | 768 | 910 | 768 | 768 | b07c53693c3ca9069fb8de91ad7384e191e78c1e | bigcode/the-stack | train |
0a04c4424f7013b85b821b6d | train | class | @whitelist_for_serdes
class GrpcServerStartedEvent(namedtuple("GrpcServerStartedEvent", "")):
pass
| @whitelist_for_serdes
class GrpcServerStartedEvent(namedtuple("GrpcServerStartedEvent", "")):
| pass
| Reply(
serialized_current_image=serialize_dagster_namedtuple(
GetCurrentImageResult(
current_image=self._get_current_image(), serializable_error_info=None
)
)
)
@whitelist_for_serdes
class GrpcServerStartedEvent(namedtuple("GrpcServerSt... | 64 | 64 | 26 | 23 | 41 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | GrpcServerStartedEvent | GrpcServerStartedEvent | 743 | 745 | 743 | 744 | 4b833439fb1fb4de204210e1487647eac87c5148 | bigcode/the-stack | train |
b879e54c28b0db965c747387 | train | function | def wait_for_grpc_server(server_process, client, subprocess_args, timeout=60):
start_time = time.time()
last_error = None
while True:
try:
client.ping("")
return
except grpc._channel._InactiveRpcError: # pylint: disable=protected-access
last_error = ser... | def wait_for_grpc_server(server_process, client, subprocess_args, timeout=60):
| start_time = time.time()
last_error = None
while True:
try:
client.ping("")
return
except grpc._channel._InactiveRpcError: # pylint: disable=protected-access
last_error = serializable_error_info_from_exc_info(sys.exc_info())
if time.time() - st... | __(
"Could not start server with "
+ (
"port {port}".format(port=port)
if port is not None
else "socket {socket}".format(socket=socket)
)
)
def wait_for_grpc_server(server_process, client, subprocess_args, timeout=60):
| 64 | 64 | 188 | 18 | 46 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | wait_for_grpc_server | wait_for_grpc_server | 925 | 947 | 925 | 925 | f852d59aed85edd5dbd7c4dc79820438c7249b92 | bigcode/the-stack | train |
fea3f9d0931cd119820d4e93 | train | class | @whitelist_for_serdes
class GrpcServerFailedToBindEvent(namedtuple("GrpcServerStartedEvent", "")):
pass
| @whitelist_for_serdes
class GrpcServerFailedToBindEvent(namedtuple("GrpcServerStartedEvent", "")):
| pass
| (), serializable_error_info=None
)
)
)
@whitelist_for_serdes
class GrpcServerStartedEvent(namedtuple("GrpcServerStartedEvent", "")):
pass
@whitelist_for_serdes
class GrpcServerFailedToBindEvent(namedtuple("GrpcServerStartedEvent", "")):
| 64 | 64 | 28 | 25 | 38 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | GrpcServerFailedToBindEvent | GrpcServerFailedToBindEvent | 748 | 750 | 748 | 749 | 21ec8dce061f566bdcf23dc00e9bbbaf6a34dbec | bigcode/the-stack | train |
086b5569f6f495b464466838 | train | class | class CouldNotBindGrpcServerToAddress(Exception):
pass
| class CouldNotBindGrpcServerToAddress(Exception):
| pass
| ,
ShutdownServerResult,
StartRunResult,
)
from .utils import get_loadable_targets
EVENT_QUEUE_POLL_INTERVAL = 0.1
CLEANUP_TICK = 0.5
STREAMING_CHUNK_SIZE = 4000000
class CouldNotBindGrpcServerToAddress(Exception):
| 64 | 64 | 13 | 10 | 53 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | CouldNotBindGrpcServerToAddress | CouldNotBindGrpcServerToAddress | 79 | 80 | 79 | 79 | 61cb391297dd1519a5f89dd12e6f6eb302c927a6 | bigcode/the-stack | train |
e9c3c1a938bc30a7d454fc3f | train | class | class GrpcServerProcess:
def __init__(
self,
loadable_target_origin=None,
force_port=False,
max_retries=10,
max_workers=None,
heartbeat=False,
heartbeat_timeout=30,
fixed_server_id=None,
startup_timeout=20,
):
self.port = None
... | class GrpcServerProcess:
| def __init__(
self,
loadable_target_origin=None,
force_port=False,
max_retries=10,
max_workers=None,
heartbeat=False,
heartbeat_timeout=30,
fixed_server_id=None,
startup_timeout=20,
):
self.port = None
self.socket = None
... | loadable_target_origin=None,
max_workers=None,
heartbeat=False,
heartbeat_timeout=30,
fixed_server_id=None,
startup_timeout=20,
):
server_process = None
retries = 0
while server_process is None and retries < max_retries:
port = find_free_port()
try:
server... | 166 | 166 | 554 | 6 | 159 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | GrpcServerProcess | GrpcServerProcess | 1,041 | 1,114 | 1,041 | 1,041 | fb376be1f110a62b5999e8521ce41f851f33162f | bigcode/the-stack | train |
1eac2923c9b2a6abf167a120 | train | class | class CouldNotStartServerProcess(Exception):
def __init__(self, port=None, socket=None):
super(CouldNotStartServerProcess, self).__init__(
"Could not start server with "
+ (
"port {port}".format(port=port)
if port is not None
else "sock... | class CouldNotStartServerProcess(Exception):
| def __init__(self, port=None, socket=None):
super(CouldNotStartServerProcess, self).__init__(
"Could not start server with "
+ (
"port {port}".format(port=port)
if port is not None
else "socket {socket}".format(socket=socket)
... | termination_event, self.server],
name="grpc-server-termination",
)
server_termination_thread.daemon = True
server_termination_thread.start()
self.server.wait_for_termination()
server_termination_thread.join()
self._api_servicer.cleanup()
class CouldNotSta... | 64 | 64 | 79 | 8 | 56 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | CouldNotStartServerProcess | CouldNotStartServerProcess | 913 | 922 | 913 | 913 | ebd94b20b656b085f1a7ebe7ef8c197761f5a678 | bigcode/the-stack | train |
8df0ac15c55520fcafd3e1f4 | train | function | def open_server_process_on_dynamic_port(
max_retries=10,
loadable_target_origin=None,
max_workers=None,
heartbeat=False,
heartbeat_timeout=30,
fixed_server_id=None,
startup_timeout=20,
):
server_process = None
retries = 0
while server_process is None and retries < max_retries:
... | def open_server_process_on_dynamic_port(
max_retries=10,
loadable_target_origin=None,
max_workers=None,
heartbeat=False,
heartbeat_timeout=30,
fixed_server_id=None,
startup_timeout=20,
):
| server_process = None
retries = 0
while server_process is None and retries < max_retries:
port = find_free_port()
try:
server_process = open_server_process(
port=port,
socket=None,
loadable_target_origin=loadable_target_origin,
... | server_process.terminate()
raise
return server_process
def open_server_process_on_dynamic_port(
max_retries=10,
loadable_target_origin=None,
max_workers=None,
heartbeat=False,
heartbeat_timeout=30,
fixed_server_id=None,
startup_timeout=20,
):
| 64 | 64 | 175 | 50 | 13 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | open_server_process_on_dynamic_port | open_server_process_on_dynamic_port | 1,009 | 1,038 | 1,009 | 1,017 | 3e849b1b59f9e15e3e3d5d364a1f6c50bebcf631 | bigcode/the-stack | train |
495b6a4125bbca942ec6b7cc | train | function | def server_termination_target(termination_event, server):
termination_event.wait()
# We could make this grace period configurable if we set it in the ShutdownServer handler
server.stop(grace=5)
| def server_termination_target(termination_event, server):
| termination_event.wait()
# We could make this grace period configurable if we set it in the ShutdownServer handler
server.stop(grace=5)
| LoadErrorEvent", "error_info")):
def __new__(cls, error_info):
return super(GrpcServerLoadErrorEvent, cls).__new__(
cls,
check.inst_param(error_info, "error_info", SerializableErrorInfo),
)
def server_termination_target(termination_event, server):
| 64 | 64 | 43 | 11 | 53 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | server_termination_target | server_termination_target | 762 | 765 | 762 | 762 | a11338309e3025b7495de5167a8801021bae2691 | bigcode/the-stack | train |
407154747587a9d9cd4e292e | train | class | class RepositorySymbolsAndCodePointers:
def __init__(self, loadable_target_origin):
self._loadable_target_origin = loadable_target_origin
self._loadable_repository_symbols = None
self._code_pointers_by_repo_name = None
def load(self):
self._loadable_repository_symbols = load_loa... | class RepositorySymbolsAndCodePointers:
| def __init__(self, loadable_target_origin):
self._loadable_target_origin = loadable_target_origin
self._loadable_repository_symbols = None
self._code_pointers_by_repo_name = None
def load(self):
self._loadable_repository_symbols = load_loadable_repository_symbols(
se... | ,
)
from .utils import get_loadable_targets
EVENT_QUEUE_POLL_INTERVAL = 0.1
CLEANUP_TICK = 0.5
STREAMING_CHUNK_SIZE = 4000000
class CouldNotBindGrpcServerToAddress(Exception):
pass
class RepositorySymbolsAndCodePointers:
| 64 | 64 | 164 | 7 | 56 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | RepositorySymbolsAndCodePointers | RepositorySymbolsAndCodePointers | 83 | 103 | 83 | 83 | 6c770ef7fe7e58d905e36c22d96e71af202bda0b | bigcode/the-stack | train |
e0a2a425d0a221509ec93eac | train | function | def build_code_pointers_by_repo_name(loadable_target_origin, loadable_repository_symbols):
repository_code_pointer_dict = {}
for loadable_repository_symbol in loadable_repository_symbols:
if loadable_target_origin.python_file:
repository_code_pointer_dict[
loadable_repository... | def build_code_pointers_by_repo_name(loadable_target_origin, loadable_repository_symbols):
| repository_code_pointer_dict = {}
for loadable_repository_symbol in loadable_repository_symbols:
if loadable_target_origin.python_file:
repository_code_pointer_dict[
loadable_repository_symbol.repository_name
] = CodePointer.from_python_file(
loada... | able_target.attribute,
repository_name=repository_def_from_target_def(
loadable_target.target_definition
).name,
)
for loadable_target in loadable_targets
]
else:
return []
def build_code_pointers_by_repo_name(loadable_targe... | 63 | 64 | 193 | 18 | 45 | alexismanuel/dagster | python_modules/dagster/dagster/grpc/server.py | Python | build_code_pointers_by_repo_name | build_code_pointers_by_repo_name | 128 | 154 | 128 | 128 | 6d553e62bd05ee9999c82c503edf8eef37bedec4 | bigcode/the-stack | train |
84d5e2c3b93e911bdd2ac912 | train | function | def make_palindrome(string, k):
if k<0: return None
N = len(string)
mid = N//2
i = 0
while i<mid:
if string[i]==string[N-i-1]:
if i==mid-1:
return string
i += 1
else:
break
inner_palindrome = []
s = make_palindrome(str... | def make_palindrome(string, k):
| if k<0: return None
N = len(string)
mid = N//2
i = 0
while i<mid:
if string[i]==string[N-i-1]:
if i==mid-1:
return string
i += 1
else:
break
inner_palindrome = []
s = make_palindrome(string[i:N-i-1], k-1)
if s is n... | was asked by Google.
Given a string which we can delete at most k, return whether you can make a palindrome.
For example, given 'waterrfetawx' and a k of 2, you could delete f and x to get 'waterretaw'.
'''
import unittest
def make_palindrome(string, k):
| 67 | 67 | 224 | 8 | 58 | loghmanb/daily-coding-problem | problem121_google_make_palindrome.py | Python | make_palindrome | make_palindrome | 11 | 37 | 11 | 11 | 10aefcfcac0c8049e913c1ff2538d8f387f93b78 | bigcode/the-stack | train |
fd5c26ba4421da514387e795 | train | class | class MakePalindromeTest(unittest.TestCase):
def test_make_palindrome_1(self):
result = make_palindrome('waterrfetawx', 2)
expected = 'waterretaw'
self.assertEqual(result, expected)
| class MakePalindromeTest(unittest.TestCase):
| def test_make_palindrome_1(self):
result = make_palindrome('waterrfetawx', 2)
expected = 'waterretaw'
self.assertEqual(result, expected)
| -2)
if s is not None:
inner_palindrome.append((len(s), s))
if inner_palindrome:
inner_palindrome.sort(reverse=True)
return string[:i] + inner_palindrome[0][1] + string[N-i:]
class MakePalindromeTest(unittest.TestCase):
| 63 | 64 | 50 | 8 | 55 | loghmanb/daily-coding-problem | problem121_google_make_palindrome.py | Python | MakePalindromeTest | MakePalindromeTest | 40 | 45 | 40 | 41 | 5cb0b953cb86437fe95bebf0889a21546202af68 | bigcode/the-stack | train |
f3d3abb11134ed4fedd30817 | train | function | def plot_replicates_from_df(df, my_quantity, plot_ci=True, myci=68.,
estimator=np.mean, color='m', ls='-',
err_alpha=0.25, err_lw=2.5,
identifier='replicate'):
""" Plot a given quantity from the Dataframe, averaging across
all replicates in that Dataframe.
Param... | def plot_replicates_from_df(df, my_quantity, plot_ci=True, myci=68.,
estimator=np.mean, color='m', ls='-',
err_alpha=0.25, err_lw=2.5,
identifier='replicate'):
| """ Plot a given quantity from the Dataframe, averaging across
all replicates in that Dataframe.
Parameters
----------
df : DataFrame
Dataframe containing table of results from DLS microrheology
analysis for a single condition
my_quantity : str
Name of variable t... | _freq_sweep(df, quantity, replicate_identifier,
n_bootstrap, estimator=estimator)
ci_low = np.percentile(M_bootstrap, 50.-ci/2., axis=0)
ci_high = np.percentile(M_bootstrap, 50.+ci/2., axis=0)
return [ci_low, ci_high]
def plot_replicates_from_df(df, my_quantity, plot_ci=True, m... | 132 | 132 | 441 | 60 | 72 | bkrajina/dlsmicro | dlsmicro/backend/plot_tools.py | Python | plot_replicates_from_df | plot_replicates_from_df | 153 | 197 | 153 | 157 | 3eaf65c89a4ac012afa98ff13d854ceffbbbd34b | bigcode/the-stack | train |
72357f18a685e3e2b32f81ec | train | function | def bootstrap_matrix_byrows(M, n_bootstrap, estimator):
""" Gets bootstrap samples of an estimator for frequency (or time)
sweep data from a matrix containing all vectors for a given quantity
over all replicates.
Parameters
----------
M : 2-d array
Matrix of all values for a given quantity over... | def bootstrap_matrix_byrows(M, n_bootstrap, estimator):
| """ Gets bootstrap samples of an estimator for frequency (or time)
sweep data from a matrix containing all vectors for a given quantity
over all replicates.
Parameters
----------
M : 2-d array
Matrix of all values for a given quantity over all replicates
n_bootstrap : int
Number of ... | M_list.append(xi)
# Ensure all rows are the same length
limit = np.min(np.array(list_len))
M_list = list(m[0:limit] for m in M_list)
M = np.vstack(M_list)
return M
def bootstrap_matrix_byrows(M, n_bootstrap, estimator):
| 66 | 66 | 220 | 13 | 52 | bkrajina/dlsmicro | dlsmicro/backend/plot_tools.py | Python | bootstrap_matrix_byrows | bootstrap_matrix_byrows | 40 | 67 | 40 | 41 | 1a78ef139cf2835481d8e9dddd547f5d1448ebcb | bigcode/the-stack | train |
230b06590e2d763123d0f68b | train | function | def add_w_scaling(omega, scaling, w_b, placement):
""" Plot a given scaling on complex modulus plot to compared
against the complex modulus of a sample.
Parameters
----------
omega : 1-d array
Vector of frequency range covered by the complex modulus
plotted in the plot
scaling : list of ... | def add_w_scaling(omega, scaling, w_b, placement):
| """ Plot a given scaling on complex modulus plot to compared
against the complex modulus of a sample.
Parameters
----------
omega : 1-d array
Vector of frequency range covered by the complex modulus
plotted in the plot
scaling : list of float
List of 2 floats, where the first... | _quantity, identifier, 10000,
myci, estimator=estimator)
ci_low = ci[0]
ci_high = ci[1]
y_mu = estimator(y_matrix, axis=0)
plt.plot(time, y_mu, color=color, ls=ls)
if plot_ci:
plt.fill_between(time, ci_low, ci_high, color=color,
alpha=err_alpha, ... | 109 | 109 | 364 | 15 | 94 | bkrajina/dlsmicro | dlsmicro/backend/plot_tools.py | Python | add_w_scaling | add_w_scaling | 199 | 231 | 199 | 200 | a0a51c59bd6aefc1e0a44fc18d00a47859e7b5df | bigcode/the-stack | train |
ee3b069187eb7e67a6376a33 | train | function | def df_to_matrix(df, quantity, replicate_identifier):
""" Construct a matrix from a Dataframe for a given vector-valued
quantity in which each vector replicate is labeled by a unique
replicate identifier.
Parameters
----------
df : DataFrame
Dataframe containing table of results from DLS mic... | def df_to_matrix(df, quantity, replicate_identifier):
| """ Construct a matrix from a Dataframe for a given vector-valued
quantity in which each vector replicate is labeled by a unique
replicate identifier.
Parameters
----------
df : DataFrame
Dataframe containing table of results from DLS microrheology
analysis for a single condition
... | import numpy as np
import matplotlib.pyplot as plt
def df_to_matrix(df, quantity, replicate_identifier):
| 22 | 78 | 260 | 11 | 10 | bkrajina/dlsmicro | dlsmicro/backend/plot_tools.py | Python | df_to_matrix | df_to_matrix | 4 | 38 | 4 | 5 | cbf463815d0c7e0709584ae16daac7aea9d1083b | bigcode/the-stack | train |
42682c6f5025905453a69e4c | train | function | def bootstrap_freq_sweep_ci(df, quantity, replicate_identifier,
n_bootstrap, ci, estimator=np.mean):
""" Gets bootstrap confidence interval for an estimator of
frequency sweep (or time sweep) data. Boot strap can be either a
percentile bootstrap of an estimator of a studentized bootstra... | def bootstrap_freq_sweep_ci(df, quantity, replicate_identifier,
n_bootstrap, ci, estimator=np.mean):
| """ Gets bootstrap confidence interval for an estimator of
frequency sweep (or time sweep) data. Boot strap can be either a
percentile bootstrap of an estimator of a studentized bootstrap
of the mean
Parameters
----------
df : DataFrame
Dataframe containing table of results from DLS microrheo... | )
limit = np.min(np.array(list_len))
M_list = list(m[0:limit] for m in M_list)
M = np.vstack(M_list)
# Get a matrix of bootstrapped row-wise averages given by the estimator
M_bootstrap = bootstrap_matrix_byrows(M, n_bootstrap, estimator)
return M_bootstrap
def bootstrap_freq_sweep_ci(df, quantity, replicate... | 97 | 97 | 324 | 24 | 72 | bkrajina/dlsmicro | dlsmicro/backend/plot_tools.py | Python | bootstrap_freq_sweep_ci | bootstrap_freq_sweep_ci | 113 | 151 | 113 | 115 | 545301ca059e0d4a1b4aae3a73f2c56683536b88 | bigcode/the-stack | train |
7a5ee67bf28b4dc6b0206841 | train | function | def bootstrap_freq_sweep(df, quantity, replicate_identifier,
n_bootstrap, estimator=np.mean):
""" Gets bootstrap samples of an estimator for frequency (or time)
sweep data from a Dataframe. The Dataframe is assumed to contain a
vector for a given quantity in which each vector replicate is ... | def bootstrap_freq_sweep(df, quantity, replicate_identifier,
n_bootstrap, estimator=np.mean):
| """ Gets bootstrap samples of an estimator for frequency (or time)
sweep data from a Dataframe. The Dataframe is assumed to contain a
vector for a given quantity in which each vector replicate is
labeled by a unique replicate identifier.
Parameters
----------
df : DataFrame
Dataframe contain... | ]
M_bootstrap = np.zeros((n_bootstrap, M.shape[1]))
M_sample = np.zeros(M.shape)
for i in range(n_bootstrap):
inds = np.random.randint(0, n_rep, n_rep)
M_sample = M[inds, :]
M_bootstrap[i, :] = estimator(M_sample, axis=0)
return M_bootstrap
def bootstrap_freq_sweep(df, quantity, replicate_identifier,... | 99 | 99 | 332 | 21 | 77 | bkrajina/dlsmicro | dlsmicro/backend/plot_tools.py | Python | bootstrap_freq_sweep | bootstrap_freq_sweep | 69 | 111 | 69 | 71 | 65efa71010df2c3149ee54cff2a8fef33852da5e | bigcode/the-stack | train |
470e8f036833575a904a3301 | train | class | class TestTransactionsConvenientAPI(TransactionsBase):
TEST_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'transactions-convenient-api')
@client_context.require_transactions
def test_callback_raises_custom_error(self):
class _MyException(Exception):pa... | class TestTransactionsConvenientAPI(TransactionsBase):
| TEST_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'transactions-convenient-api')
@client_context.require_transactions
def test_callback_raises_custom_error(self):
class _MyException(Exception):pass
def raise_error(_):
raise _MyEx... | Assert commands were constructed properly.
self.assertEqual(['insert', 'insert', 'insert', 'commitTransaction'],
listener.started_command_names())
first_cmd = listener.results['started'][0].command
self.assertTrue(first_cmd['startTransaction'])
lsid = first_cmd[... | 256 | 256 | 1,058 | 10 | 245 | hipacloud/mongo-python-driver | test/test_transactions.py | Python | TestTransactionsConvenientAPI | TestTransactionsConvenientAPI | 334 | 486 | 334 | 334 | 447fa31181574368fe6e992365e45518d91a97f7 | bigcode/the-stack | train |
c75f5d4dca2c69f0b8ac3331 | train | class | class TestTransactions(TransactionsBase):
RUN_ON_SERVERLESS = True
@client_context.require_transactions
def test_transaction_options_validation(self):
default_options = TransactionOptions()
self.assertIsNone(default_options.read_concern)
self.assertIsNone(default_options.write_concer... | class TestTransactions(TransactionsBase):
| RUN_ON_SERVERLESS = True
@client_context.require_transactions
def test_transaction_options_validation(self):
default_options = TransactionOptions()
self.assertIsNone(default_options.read_concern)
self.assertIsNone(default_options.write_concern)
self.assertIsNone(default_optio... | os.environ.get('TRANSACTION_TESTS_DEBUG')
# Max number of operations to perform after a transaction to prove unpinning
# occurs. Chosen so that there's a low false positive rate. With 2 mongoses,
# 50 attempts yields a one in a quadrillion chance of a false positive
# (1/(0.5^50)).
UNPIN_TEST_MAX_ATTEMPTS = 50
clas... | 256 | 256 | 2,164 | 7 | 249 | hipacloud/mongo-python-driver | test/test_transactions.py | Python | TestTransactions | TestTransactions | 78 | 317 | 78 | 78 | d1bb32880ed6c5304cc675c64394c3a80808c6b9 | bigcode/the-stack | train |
e0e5db91bf1b786ea0d92670 | train | class | class PatchSessionTimeout(object):
"""Patches the client_session's with_transaction timeout for testing."""
def __init__(self, mock_timeout):
self.real_timeout = client_session._WITH_TRANSACTION_RETRY_TIME_LIMIT
self.mock_timeout = mock_timeout
def __enter__(self):
client_session._W... | class PatchSessionTimeout(object):
| """Patches the client_session's with_transaction timeout for testing."""
def __init__(self, mock_timeout):
self.real_timeout = client_session._WITH_TRANSACTION_RETRY_TIME_LIMIT
self.mock_timeout = mock_timeout
def __enter__(self):
client_session._WITH_TRANSACTION_RETRY_TIME_LIMIT = ... | ['started'][1:]:
self.assertNotIn('startTransaction', event.command)
self.assertEqual(lsid, event.command['lsid'])
self.assertEqual(txn_number, event.command['txnNumber'])
self.assertEqual(10, coll.count_documents({}))
class PatchSessionTimeout(object):
| 63 | 64 | 110 | 6 | 57 | hipacloud/mongo-python-driver | test/test_transactions.py | Python | PatchSessionTimeout | PatchSessionTimeout | 320 | 331 | 320 | 320 | 96860a219115020fb9d6b730b68afd0559f2651c | bigcode/the-stack | train |
b7b9a21572ff679e5eb6e45d | train | function | def create_test(scenario_def, test, name):
@client_context.require_test_commands
@client_context.require_transactions
def run_scenario(self):
self.run_scenario(scenario_def, test)
return run_scenario
| def create_test(scenario_def, test, name):
@client_context.require_test_commands
@client_context.require_transactions
| def run_scenario(self):
self.run_scenario(scenario_def, test)
return run_scenario
| self.assertTrue(session.in_transaction)
with client.start_session() as s:
self.assertFalse(s.in_transaction)
s.with_transaction(callback)
self.assertFalse(s.in_transaction)
def create_test(scenario_def, test, name):
@client_context.require_test_commands
@client_conte... | 64 | 64 | 50 | 26 | 38 | hipacloud/mongo-python-driver | test/test_transactions.py | Python | create_test | create_test | 489 | 495 | 489 | 491 | 205789336e8eb08a4bed5622fd3cca04d7d3a6f6 | bigcode/the-stack | train |
24fc0b5dcffe3f76b8aec636 | train | class | class TransactionsBase(SpecRunner):
@classmethod
def setUpClass(cls):
super(TransactionsBase, cls).setUpClass()
if client_context.supports_transactions():
for address in client_context.mongoses:
cls.mongos_clients.append(single_client('%s:%s' % address))
@classme... | class TransactionsBase(SpecRunner):
@classmethod
| def setUpClass(cls):
super(TransactionsBase, cls).setUpClass()
if client_context.supports_transactions():
for address in client_context.mongoses:
cls.mongos_clients.append(single_client('%s:%s' % address))
@classmethod
def tearDownClass(cls):
for client i... | so that there's a low false positive rate. With 2 mongoses,
# 50 attempts yields a one in a quadrillion chance of a false positive
# (1/(0.5^50)).
UNPIN_TEST_MAX_ATTEMPTS = 50
class TransactionsBase(SpecRunner):
@classmethod
| 64 | 64 | 165 | 11 | 52 | hipacloud/mongo-python-driver | test/test_transactions.py | Python | TransactionsBase | TransactionsBase | 56 | 75 | 56 | 57 | d9d25e18646c07e92833fc3807efa161a4732f70 | bigcode/the-stack | train |
22a9a2893d2f68c995aff914 | train | class | class CimcvmediaMountConfigPolicyConsts():
INT_ID_NONE = "none"
POLICY_OWNER_LOCAL = "local"
POLICY_OWNER_PENDING_POLICY = "pending-policy"
POLICY_OWNER_POLICY = "policy"
POLICY_OWNER_UNSPECIFIED = "unspecified"
| class CimcvmediaMountConfigPolicyConsts():
| INT_ID_NONE = "none"
POLICY_OWNER_LOCAL = "local"
POLICY_OWNER_PENDING_POLICY = "pending-policy"
POLICY_OWNER_POLICY = "policy"
POLICY_OWNER_UNSPECIFIED = "unspecified"
| """This module contains the general information for CimcvmediaMountConfigPolicy ManagedObject."""
from ...ucscentralmo import ManagedObject
from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta
from ...ucscentralmeta import VersionMeta
class CimcvmediaMountConfigPolicyConsts():
| 63 | 64 | 54 | 9 | 53 | ragupta-git/ucscentralsdk | ucscentralsdk/mometa/cimcvmedia/CimcvmediaMountConfigPolicy.py | Python | CimcvmediaMountConfigPolicyConsts | CimcvmediaMountConfigPolicyConsts | 8 | 13 | 8 | 8 | 5feb78279cef811c670dded49b73f139253e7a9e | bigcode/the-stack | train |
55bef38c37d32da7fecab75c | train | class | class CimcvmediaMountConfigPolicy(ManagedObject):
"""This is CimcvmediaMountConfigPolicy class."""
consts = CimcvmediaMountConfigPolicyConsts()
naming_props = set([u'name'])
mo_meta = MoMeta("CimcvmediaMountConfigPolicy", "cimcvmediaMountConfigPolicy", "mnt-cfg-policy-[name]", VersionMeta.Version121e,... | class CimcvmediaMountConfigPolicy(ManagedObject):
| """This is CimcvmediaMountConfigPolicy class."""
consts = CimcvmediaMountConfigPolicyConsts()
naming_props = set([u'name'])
mo_meta = MoMeta("CimcvmediaMountConfigPolicy", "cimcvmediaMountConfigPolicy", "mnt-cfg-policy-[name]", VersionMeta.Version121e, "InputOutput", 0x7f, [], ["admin", "ls-compute", ... | """This module contains the general information for CimcvmediaMountConfigPolicy ManagedObject."""
from ...ucscentralmo import ManagedObject
from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta
from ...ucscentralmeta import VersionMeta
class CimcvmediaMountConfigPolicyConsts():
INT_ID_NONE ... | 119 | 256 | 951 | 11 | 108 | ragupta-git/ucscentralsdk | ucscentralsdk/mometa/cimcvmedia/CimcvmediaMountConfigPolicy.py | Python | CimcvmediaMountConfigPolicy | CimcvmediaMountConfigPolicy | 16 | 61 | 16 | 16 | 8a5e6c0030307cdb96a517f30942cff9a2212b58 | bigcode/the-stack | train |
fb7c52f4cffab9d511eb5c8d | train | class | class Contact(Model):
__table__ = 'contact'
id = StringField(primary_key=True,updatable=False,default=next_id,dll='varchar(50)')
name = StringField(ddl='varchar(50)')
tel = StringField(ddl='varchar(50)')
work_tel = StringField(ddl='varchar(50)')
sex = StringField(ddl='varchar(50)')
college ... | class Contact(Model):
| __table__ = 'contact'
id = StringField(primary_key=True,updatable=False,default=next_id,dll='varchar(50)')
name = StringField(ddl='varchar(50)')
tel = StringField(ddl='varchar(50)')
work_tel = StringField(ddl='varchar(50)')
sex = StringField(ddl='varchar(50)')
college = StringField(ddl='var... | # -*- coding: utf-8 -*-
import time,uuid
from transwarp.db import next_id
from transwarp.orm import Model,StringField,BooleanField,FloatField,TextField
class Contact(Model):
| 43 | 64 | 117 | 4 | 38 | felixlnog/contact | www/models.py | Python | Contact | Contact | 7 | 17 | 7 | 7 | 44889d3aa81b0c909b779e5cee8279f2055294dc | bigcode/the-stack | train |
e1f0ed4290e1bc9db4c4258a | train | class | class TestCoilHeatingWaterToAirHeatPumpParameterEstimation(unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfile.mkstemp()
def tearDown(self):
os.remove(self.path)
def test_create_coilheatingwatertoairheatpumpparameterestimation(self):
pyidf.validation_level = Valida... | class TestCoilHeatingWaterToAirHeatPumpParameterEstimation(unittest.TestCase):
| def setUp(self):
self.fd, self.path = tempfile.mkstemp()
def tearDown(self):
os.remove(self.path)
def test_create_coilheatingwatertoairheatpumpparameterestimation(self):
pyidf.validation_level = ValidationLevel.error
obj = CoilHeatingWaterToAirHeatPumpParameterEstimation(... | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.coils import CoilHeatingWaterToAirHeatPumpParameterEstimation
log = logging.getLogger(__name__)
class TestCoilHeatingWaterToAirHeatPumpParameterEstimation(unittest.TestCase):
| 74 | 256 | 1,881 | 17 | 57 | marcelosalles/pyidf | tests/test_coilheatingwatertoairheatpumpparameterestimation.py | Python | TestCoilHeatingWaterToAirHeatPumpParameterEstimation | TestCoilHeatingWaterToAirHeatPumpParameterEstimation | 12 | 130 | 12 | 13 | b479fb0f80c6a167b736e01d9148c65771182787 | bigcode/the-stack | train |
e6a1ccb9622e69d5600c73bd | train | class | class NodeAttributeEnum(StringChoiceEnum):
"""Available node attributes."""
COLOR = "COLOR"
SIZE = "SIZE"
EXTRA_LABEL = "EXTRA_LABEL"
LABEL = "LABEL"
SOURCE = "SOURCE"
| class NodeAttributeEnum(StringChoiceEnum):
| """Available node attributes."""
COLOR = "COLOR"
SIZE = "SIZE"
EXTRA_LABEL = "EXTRA_LABEL"
LABEL = "LABEL"
SOURCE = "SOURCE"
| from rpasdt.common.enums import StringChoiceEnum
class NodeAttributeEnum(StringChoiceEnum):
| 19 | 64 | 47 | 8 | 10 | damianfraszczak/rpasdt | src/rpasdt/network/taxonomies.py | Python | NodeAttributeEnum | NodeAttributeEnum | 4 | 11 | 4 | 4 | 4310f7ab004732a8ade194440d1ed5666a5b1ad7 | bigcode/the-stack | train |
2817fc79a707634688ffaaf1 | train | class | class DistanceMeasureOptionEnum(StringChoiceEnum):
pass
| class DistanceMeasureOptionEnum(StringChoiceEnum):
| pass
| dt.common.enums import StringChoiceEnum
class NodeAttributeEnum(StringChoiceEnum):
"""Available node attributes."""
COLOR = "COLOR"
SIZE = "SIZE"
EXTRA_LABEL = "EXTRA_LABEL"
LABEL = "LABEL"
SOURCE = "SOURCE"
class DistanceMeasureOptionEnum(StringChoiceEnum):
| 64 | 64 | 12 | 9 | 55 | damianfraszczak/rpasdt | src/rpasdt/network/taxonomies.py | Python | DistanceMeasureOptionEnum | DistanceMeasureOptionEnum | 14 | 15 | 14 | 14 | f318aa6d046bd1f1eebfff27318766392aced01a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.