Skip to content

Commit 2ed480c

Browse files
committed
Revert "Remove all deprecated args, kwargs for v0.5.0 (#1396) (#1397)"
This reverts commit a85da62.
1 parent 8375e0a commit 2ed480c

File tree

8 files changed

+93
-21
lines changed

8 files changed

+93
-21
lines changed

ignite/contrib/engines/common.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ def setup_common_training_handlers(
4343
with_pbars: bool = True,
4444
with_pbar_on_iters: bool = True,
4545
log_every_iters: int = 100,
46+
device: Optional[Union[str, torch.device]] = None,
4647
stop_on_nan: bool = True,
4748
clear_cuda_cache: bool = True,
4849
save_handler: Optional[Union[Callable, BaseSaveHandler]] = None,
@@ -86,7 +87,10 @@ def setup_common_training_handlers(
8687
class to use to store ``to_save``. See :class:`~ignite.handlers.checkpoint.Checkpoint` for more details.
8788
Argument is mutually exclusive with ``output_path``.
8889
kwargs: optional keyword args to be passed to construct :class:`~ignite.handlers.checkpoint.Checkpoint`.
90+
device: deprecated argument, it will be removed in v0.5.0.
8991
"""
92+
if device is not None:
93+
warnings.warn("Argument device is unused and deprecated. It will be removed in v0.5.0")
9094

9195
if idist.get_world_size() > 1:
9296
_setup_common_distrib_training_handlers(

ignite/engine/engine.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,7 @@ def state_dict_user_keys(self) -> List:
471471
return self._state_dict_user_keys
472472

473473
def state_dict(self) -> OrderedDict:
474-
"""Returns a dictionary containing engine's state: "epoch_length", "max_epochs" and "iteration" and
474+
"""Returns a dictionary containing engine's state: "seed", "epoch_length", "max_epochs" and "iteration" and
475475
other state values defined by `engine.state_dict_user_keys`
476476
477477
.. code-block:: python
@@ -504,8 +504,8 @@ def save_engine(_):
504504
def load_state_dict(self, state_dict: Mapping) -> None:
505505
"""Setups engine from `state_dict`.
506506
507-
State dictionary should contain keys: `iteration` or `epoch`, `max_epochs` and `epoch_length`.
508-
If `engine.state_dict_user_keys` contains keys, they should be also present in the state dictionary.
507+
State dictionary should contain keys: `iteration` or `epoch` and `max_epochs`, `epoch_length` and
508+
`seed`. If `engine.state_dict_user_keys` contains keys, they should be also present in the state dictionary.
509509
Iteration and epoch values are 0-based: the first iteration or epoch is zero.
510510
511511
This method does not remove any custom attributes added by user.
@@ -604,12 +604,13 @@ def run(
604604
max_epochs: Optional[int] = None,
605605
max_iters: Optional[int] = None,
606606
epoch_length: Optional[int] = None,
607+
seed: Optional[int] = None,
607608
) -> State:
608609
"""Runs the ``process_function`` over the passed data.
609610
610611
Engine has a state and the following logic is applied in this function:
611612
612-
- At the first call, new state is defined by `max_epochs`, `max_iters`, `epoch_length`, if provided.
613+
- At the first call, new state is defined by `max_epochs`, `max_iters`, `epoch_length`, `seed`, if provided.
613614
A timer for total and per-epoch time is initialized when Events.STARTED is handled.
614615
- If state is already defined such that there are iterations to run until `max_epochs` and no input arguments
615616
provided, state is kept and used in the function.
@@ -629,6 +630,7 @@ def run(
629630
This argument should not change if run is resuming from a state.
630631
max_iters: Number of iterations to run for.
631632
`max_iters` and `max_epochs` are mutually exclusive; only one of the two arguments should be provided.
633+
seed: Deprecated argument. Please, use `torch.manual_seed` or :meth:`~ignite.utils.manual_seed`.
632634
633635
Returns:
634636
State: output state.
@@ -657,6 +659,12 @@ def switch_batch(engine):
657659
trainer.run(train_loader, max_epochs=2)
658660
659661
"""
662+
if seed is not None:
663+
warnings.warn(
664+
"Argument seed is deprecated. It will be removed in 0.5.0. "
665+
"Please, use torch.manual_seed or ignite.utils.manual_seed"
666+
)
667+
660668
if data is not None and not isinstance(data, Iterable):
661669
raise TypeError("Argument data should be iterable")
662670

ignite/engine/events.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import numbers
2+
import warnings
23
import weakref
34
from enum import Enum
45
from types import DynamicClassAttribute
@@ -138,7 +139,18 @@ def __or__(self, other: Any) -> "EventsList":
138139
return EventsList() | self | other
139140

140141

141-
class EventEnum(CallableEventWithFilter, Enum):
142+
class CallableEvents(CallableEventWithFilter):
143+
# For backward compatibility
144+
def __init__(self, *args: Any, **kwargs: Any) -> None:
145+
super(CallableEvents, self).__init__(*args, **kwargs)
146+
warnings.warn(
147+
"Class ignite.engine.events.CallableEvents is deprecated. It will be removed in 0.5.0. "
148+
"Please, use ignite.engine.EventEnum instead",
149+
DeprecationWarning,
150+
)
151+
152+
153+
class EventEnum(CallableEventWithFilter, Enum): # type: ignore[misc]
142154
"""Base class for all :class:`~ignite.engine.events.Events`. User defined custom events should also inherit
143155
this class.
144156

ignite/handlers/checkpoint.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ class Checkpoint(Serializable):
9494
Input of the function is ``(engine, event_name)``. Output of function should be an integer.
9595
Default is None, global_step based on attached engine. If provided, uses function output as global_step.
9696
To setup global step from another engine, please use :meth:`~ignite.handlers.global_step_from_engine`.
97+
archived: Deprecated argument as models saved by ``torch.save`` are already compressed.
9798
filename_pattern: If ``filename_pattern`` is provided, this pattern will be used to render
9899
checkpoint filenames. If the pattern is not defined, the default pattern would be used. See Note for
99100
details.
@@ -277,6 +278,7 @@ def __init__(
277278
score_name: Optional[str] = None,
278279
n_saved: Union[int, None] = 1,
279280
global_step_transform: Optional[Callable] = None,
281+
archived: bool = False,
280282
filename_pattern: Optional[str] = None,
281283
include_self: bool = False,
282284
greater_or_equal: bool = False,
@@ -308,6 +310,8 @@ def __init__(
308310

309311
if global_step_transform is not None and not callable(global_step_transform):
310312
raise TypeError(f"global_step_transform should be a function, got {type(global_step_transform)} instead.")
313+
if archived:
314+
warnings.warn("Argument archived is deprecated and will be removed in 0.5.0")
311315

312316
self.to_save = to_save
313317
self.filename_prefix = filename_prefix
@@ -864,6 +868,11 @@ class ModelCheckpoint(Checkpoint):
864868
865869
Behaviour of this class has been changed since v0.3.0.
866870
871+
Argument ``save_as_state_dict`` is deprecated and should not be used. It is considered as True.
872+
873+
Argument ``save_interval`` is deprecated and should not be used. Please, use events filtering instead, e.g.
874+
:attr:`~ignite.engine.events.Events.ITERATION_STARTED(every=1000)`
875+
867876
There is no more internal counter that has been used to indicate the number of save actions. User could
868877
see its value `step_number` in the filename, e.g. `{filename_prefix}_{name}_{step_number}.pt`. Actually,
869878
`step_number` is replaced by current engine's epoch if `score_function` is specified and current iteration
@@ -892,6 +901,7 @@ class ModelCheckpoint(Checkpoint):
892901
Input of the function is `(engine, event_name)`. Output of function should be an integer.
893902
Default is None, global_step based on attached engine. If provided, uses function output as global_step.
894903
To setup global step from another engine, please use :meth:`~ignite.handlers.global_step_from_engine`.
904+
archived: Deprecated argument as models saved by `torch.save` are already compressed.
895905
filename_pattern: If ``filename_pattern`` is provided, this pattern will be used to render
896906
checkpoint filenames. If the pattern is not defined, the default pattern would be used.
897907
See :class:`~ignite.handlers.checkpoint.Checkpoint` for details.
@@ -930,19 +940,39 @@ def __init__(
930940
self,
931941
dirname: Union[str, Path],
932942
filename_prefix: str = "",
943+
save_interval: Optional[Callable] = None,
933944
score_function: Optional[Callable] = None,
934945
score_name: Optional[str] = None,
935946
n_saved: Union[int, None] = 1,
936947
atomic: bool = True,
937948
require_empty: bool = True,
938949
create_dir: bool = True,
950+
save_as_state_dict: bool = True,
939951
global_step_transform: Optional[Callable] = None,
952+
archived: bool = False,
940953
filename_pattern: Optional[str] = None,
941954
include_self: bool = False,
942955
greater_or_equal: bool = False,
943956
**kwargs: Any,
944957
):
945958

959+
if not save_as_state_dict:
960+
raise ValueError(
961+
"Argument save_as_state_dict is deprecated and should be True."
962+
"This argument will be removed in 0.5.0."
963+
)
964+
if save_interval is not None:
965+
msg = (
966+
"Argument save_interval is deprecated and should be None. This argument will be removed in 0.5.0."
967+
"Please, use events filtering instead, e.g. Events.ITERATION_STARTED(every=1000)"
968+
)
969+
if save_interval == 1:
970+
# Do not break for old version who used `save_interval=1`
971+
warnings.warn(msg)
972+
else:
973+
# No choice
974+
raise ValueError(msg)
975+
946976
disk_saver = DiskSaver(dirname, atomic=atomic, create_dir=create_dir, require_empty=require_empty, **kwargs)
947977

948978
super(ModelCheckpoint, self).__init__(
@@ -954,6 +984,7 @@ def __init__(
954984
n_saved=n_saved,
955985
global_step_transform=global_step_transform,
956986
filename_pattern=filename_pattern,
987+
archived=archived,
957988
include_self=include_self,
958989
greater_or_equal=greater_or_equal,
959990
)

tests/ignite/contrib/engines/test_common.py

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -148,21 +148,8 @@ def test_asserts_setup_common_training_handlers():
148148
train_sampler = MagicMock(spec=DistributedSampler)
149149
setup_common_training_handlers(trainer, train_sampler=train_sampler)
150150

151-
with pytest.raises(RuntimeError, match=r"This contrib module requires available GPU"):
152-
setup_common_training_handlers(trainer, with_gpu_stats=True)
153-
154-
with pytest.raises(TypeError, match=r"Unhandled type of update_function's output."):
155-
trainer = Engine(lambda e, b: None)
156-
setup_common_training_handlers(
157-
trainer,
158-
output_names=["loss"],
159-
with_pbar_on_iters=False,
160-
with_pbars=False,
161-
with_gpu_stats=False,
162-
stop_on_nan=False,
163-
clear_cuda_cache=False,
164-
)
165-
trainer.run([1])
151+
with pytest.warns(UserWarning, match=r"Argument device is unused and deprecated"):
152+
setup_common_training_handlers(trainer, device="cpu")
166153

167154

168155
def test_no_warning_with_train_sampler(recwarn):

tests/ignite/engine/test_custom_events.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,19 @@
66

77
import ignite.distributed as idist
88
from ignite.engine import Engine, Events
9-
from ignite.engine.events import CallableEventWithFilter, EventEnum, EventsList
9+
from ignite.engine.events import CallableEvents, CallableEventWithFilter, EventEnum, EventsList
10+
11+
12+
def test_deprecated_callable_events_class():
13+
engine = Engine(lambda engine, batch: 0)
14+
15+
with pytest.warns(DeprecationWarning, match=r"Class ignite\.engine\.events\.CallableEvents is deprecated"):
16+
17+
class CustomEvents(CallableEvents, Enum):
18+
TEST_EVENT = "test_event"
19+
20+
with pytest.raises(TypeError, match=r"Value at \d of event_names should be a str or EventEnum"):
21+
engine.register_events(*CustomEvents)
1022

1123

1224
def test_custom_events():

tests/ignite/engine/test_engine.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,9 @@ def test_run_asserts():
362362
with pytest.raises(ValueError, match=r"Input data has zero size. Please provide non-empty data"):
363363
engine.run([])
364364

365+
with pytest.warns(UserWarning, match="Argument seed is deprecated"):
366+
engine.run([0, 1, 2, 3, 4], seed=1234)
367+
365368

366369
def test_state_get_event_attrib_value():
367370
state = State()

tests/ignite/handlers/test_checkpoint.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ def test_checkpoint_wrong_input():
6363
with pytest.raises(TypeError, match=r"global_step_transform should be a function."):
6464
Checkpoint(to_save, lambda x: x, score_function=lambda e: 123, score_name="acc", global_step_transform=123)
6565

66+
with pytest.warns(UserWarning, match=r"Argument archived is deprecated"):
67+
Checkpoint(to_save, lambda x: x, score_function=lambda e: 123, score_name="acc", archived=True)
68+
6669
with pytest.raises(ValueError, match=r"Cannot have key 'checkpointer' if `include_self` is True"):
6770
Checkpoint({"checkpointer": model}, lambda x: x, include_self=True)
6871

@@ -550,12 +553,24 @@ def test_model_checkpoint_args_validation(dirname):
550553
with pytest.raises(ValueError, match=r"with extension '.pt' are already present "):
551554
ModelCheckpoint(nonempty, _PREFIX)
552555

556+
with pytest.raises(ValueError, match=r"Argument save_interval is deprecated and should be None"):
557+
ModelCheckpoint(existing, _PREFIX, save_interval=42)
558+
553559
with pytest.raises(ValueError, match=r"Directory path '\S+' is not found"):
554560
ModelCheckpoint(dirname / "non_existing_dir", _PREFIX, create_dir=False)
555561

562+
with pytest.raises(ValueError, match=r"Argument save_as_state_dict is deprecated and should be True"):
563+
ModelCheckpoint(existing, _PREFIX, create_dir=False, save_as_state_dict=False)
564+
565+
with pytest.raises(ValueError, match=r"If `score_name` is provided, then `score_function` "):
566+
ModelCheckpoint(existing, _PREFIX, create_dir=False, score_name="test")
567+
556568
with pytest.raises(TypeError, match=r"global_step_transform should be a function"):
557569
ModelCheckpoint(existing, _PREFIX, create_dir=False, global_step_transform=1234)
558570

571+
with pytest.warns(UserWarning, match=r"Argument archived is deprecated"):
572+
ModelCheckpoint(existing, _PREFIX, create_dir=False, archived=True)
573+
559574
h = ModelCheckpoint(dirname, _PREFIX, create_dir=False)
560575
assert h.last_checkpoint is None
561576
with pytest.raises(RuntimeError, match=r"No objects to checkpoint found."):

0 commit comments

Comments
 (0)