Skip to content

Commit c22e2f8

Browse files
committed
Revert "Remove all deprecated args, kwargs for v0.5.0 (#1396) (#1397)"
This reverts commit a85da62.
1 parent 5ab2eb5 commit c22e2f8

File tree

8 files changed

+92
-20
lines changed

8 files changed

+92
-20
lines changed

ignite/contrib/engines/common.py

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

9296
if idist.get_world_size() > 1:
9397
_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: 12 additions & 0 deletions
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,6 +139,17 @@ def __or__(self, other: Any) -> "EventsList":
138139
return EventsList() | self | other
139140

140141

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+
141153
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.

ignite/handlers/checkpoint.py

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

301303
if global_step_transform is not None and not callable(global_step_transform):
302304
raise TypeError(f"global_step_transform should be a function, got {type(global_step_transform)} instead.")
305+
if archived:
306+
warnings.warn("Argument archived is deprecated and will be removed in 0.5.0")
303307

304308
self.to_save = to_save
305309
self.filename_prefix = filename_prefix
@@ -755,6 +759,11 @@ class ModelCheckpoint(Checkpoint):
755759
756760
Behaviour of this class has been changed since v0.3.0.
757761
762+
Argument ``save_as_state_dict`` is deprecated and should not be used. It is considered as True.
763+
764+
Argument ``save_interval`` is deprecated and should not be used. Please, use events filtering instead, e.g.
765+
:attr:`~ignite.engine.events.Events.ITERATION_STARTED(every=1000)`
766+
758767
There is no more internal counter that has been used to indicate the number of save actions. User could
759768
see its value `step_number` in the filename, e.g. `{filename_prefix}_{name}_{step_number}.pt`. Actually,
760769
`step_number` is replaced by current engine's epoch if `score_function` is specified and current iteration
@@ -785,6 +794,7 @@ class ModelCheckpoint(Checkpoint):
785794
To setup global step from another engine, please use :meth:`~ignite.handlers.global_step_from_engine`.
786795
include_self: Whether to include the `state_dict` of this object in the checkpoint. If `True`, then
787796
there must not be another object in ``to_save`` with key ``checkpointer``.
797+
archived: Deprecated argument as models saved by `torch.save` are already compressed.
788798
kwargs: Accepted keyword arguments for `torch.save` or `xm.save` in `DiskSaver`.
789799
790800
.. versionchanged:: 0.4.2
@@ -812,17 +822,37 @@ def __init__(
812822
self,
813823
dirname: str,
814824
filename_prefix: str,
825+
save_interval: Optional[Callable] = None,
815826
score_function: Optional[Callable] = None,
816827
score_name: Optional[str] = None,
817828
n_saved: Union[int, None] = 1,
818829
atomic: bool = True,
819830
require_empty: bool = True,
820831
create_dir: bool = True,
832+
save_as_state_dict: bool = True,
821833
global_step_transform: Optional[Callable] = None,
834+
archived: bool = False,
822835
include_self: bool = False,
823836
**kwargs: Any,
824837
):
825838

839+
if not save_as_state_dict:
840+
raise ValueError(
841+
"Argument save_as_state_dict is deprecated and should be True."
842+
"This argument will be removed in 0.5.0."
843+
)
844+
if save_interval is not None:
845+
msg = (
846+
"Argument save_interval is deprecated and should be None. This argument will be removed in 0.5.0."
847+
"Please, use events filtering instead, e.g. Events.ITERATION_STARTED(every=1000)"
848+
)
849+
if save_interval == 1:
850+
# Do not break for old version who used `save_interval=1`
851+
warnings.warn(msg)
852+
else:
853+
# No choice
854+
raise ValueError(msg)
855+
826856
disk_saver = DiskSaver(dirname, atomic=atomic, create_dir=create_dir, require_empty=require_empty, **kwargs)
827857

828858
super(ModelCheckpoint, self).__init__(
@@ -833,6 +863,7 @@ def __init__(
833863
score_name=score_name,
834864
n_saved=n_saved,
835865
global_step_transform=global_step_transform,
866+
archived=archived,
836867
include_self=include_self,
837868
)
838869

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
@@ -58,6 +58,9 @@ def test_checkpoint_wrong_input():
5858
with pytest.raises(TypeError, match=r"global_step_transform should be a function."):
5959
Checkpoint(to_save, lambda x: x, score_function=lambda e: 123, score_name="acc", global_step_transform=123)
6060

61+
with pytest.warns(UserWarning, match=r"Argument archived is deprecated"):
62+
Checkpoint(to_save, lambda x: x, score_function=lambda e: 123, score_name="acc", archived=True)
63+
6164
with pytest.raises(ValueError, match=r"Cannot have key 'checkpointer' if `include_self` is True"):
6265
Checkpoint({"checkpointer": model}, lambda x: x, include_self=True)
6366

@@ -547,12 +550,24 @@ def test_model_checkpoint_args_validation(dirname):
547550
with pytest.raises(ValueError, match=r"with extension '.pt' are already present "):
548551
ModelCheckpoint(nonempty, _PREFIX)
549552

553+
with pytest.raises(ValueError, match=r"Argument save_interval is deprecated and should be None"):
554+
ModelCheckpoint(existing, _PREFIX, save_interval=42)
555+
550556
with pytest.raises(ValueError, match=r"Directory path '\S+' is not found"):
551557
ModelCheckpoint(os.path.join(dirname, "non_existing_dir"), _PREFIX, create_dir=False)
552558

559+
with pytest.raises(ValueError, match=r"Argument save_as_state_dict is deprecated and should be True"):
560+
ModelCheckpoint(existing, _PREFIX, create_dir=False, save_as_state_dict=False)
561+
562+
with pytest.raises(ValueError, match=r"If `score_name` is provided, then `score_function` "):
563+
ModelCheckpoint(existing, _PREFIX, create_dir=False, score_name="test")
564+
553565
with pytest.raises(TypeError, match=r"global_step_transform should be a function"):
554566
ModelCheckpoint(existing, _PREFIX, create_dir=False, global_step_transform=1234)
555567

568+
with pytest.warns(UserWarning, match=r"Argument archived is deprecated"):
569+
ModelCheckpoint(existing, _PREFIX, create_dir=False, archived=True)
570+
556571
h = ModelCheckpoint(dirname, _PREFIX, create_dir=False)
557572
assert h.last_checkpoint is None
558573
with pytest.raises(RuntimeError, match=r"No objects to checkpoint found."):

0 commit comments

Comments
 (0)