-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathtest_api.py
More file actions
1920 lines (1558 loc) · 71.8 KB
/
Copy pathtest_api.py
File metadata and controls
1920 lines (1558 loc) · 71.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
from configparser import ConfigParser
from dataclasses import dataclass, field
from typing import Annotated, List, Optional, Union, TYPE_CHECKING
from unittest.mock import Mock, patch
import fiddle as fdl
import pytest
import typer
from importlib_metadata import EntryPoint, EntryPoints
from typer.testing import CliRunner
from rich.console import Console
import nemo_run as run
from nemo_run import cli, config
from nemo_run.cli import api as cli_api
from nemo_run.config import Config
from nemo_run.cli.lazy import LazyEntrypoint
from nemo_run.cli.api import (
Entrypoint,
RunContext,
EntrypointCommand,
add_global_options,
create_cli,
_search_workspace_file,
_load_workspace_file,
_load_workspace,
main as cli_main,
extract_constituent_types,
)
from test.dummy_factory import DummyModel, dummy_entrypoint
import nemo_run.cli.cli_parser # Import the module to mock its function
if TYPE_CHECKING:
from test.dummy_type import RealType
_RUN_FACTORIES_ENTRYPOINT: str = """
[nemo_run.cli]
dummy = test.dummy_factory
"""
# Helper methods taken from https://github.com/pytorch/torchx/blob/main/torchx/util/test/entrypoints_test.py
def EntryPoint_from_config(config: ConfigParser) -> list[EntryPoint]:
# from stdlib, Copyright (c) Python Authors
return [
EntryPoint(name, value, group)
for group in config.sections()
for name, value in config.items(group)
]
def EntryPoint_from_text(text: str) -> list[EntryPoint]:
# from stdlib, Copyright (c) Python Authors
config = ConfigParser(delimiters="=")
config.read_string(text)
return EntryPoint_from_config(config)
_ENTRY_POINTS: EntryPoints = EntryPoints(EntryPoint_from_text(_RUN_FACTORIES_ENTRYPOINT))
@dataclass
class Optimizer:
learning_rate: float = 0.1
weight_decay: float = 1e-5
betas: List[float] = field(default_factory=lambda: [0.9, 0.999])
@cli.factory
@run.autoconvert
def dummy_model() -> DummyModel:
return DummyModel()
@cli.factory
def _dummy_model_config() -> run.Config[DummyModel]:
return run.Config(DummyModel, hidden=2000, activation="tanh")
@cli.factory
@run.autoconvert
def optimizer() -> Optimizer:
return Optimizer()
class TestRunContext:
@pytest.fixture
def sample_function(self):
def func(a: int, b: str, c: float = 1.0):
return a, b, c
return func
@pytest.fixture
def sample_experiment(self):
def func(ctx, a: int, b: str, c: float = 1.0):
return a, b, c
return func
def test_run_context_initialization(self):
ctx = RunContext(name="test_run")
assert ctx.name == "test_run"
assert not ctx.direct
assert not ctx.dryrun
assert ctx.factory is None
assert ctx.load is None
assert not ctx.repl
assert not ctx.detach
assert not ctx.skip_confirmation
assert not ctx.tail_logs
def test_run_context_parse_args(self):
ctx = RunContext(name="test_run")
ctx.parse_args(
["executor=local_executor", "executor.ntasks_per_node=2", "plugins=dummy_plugin"]
)
assert isinstance(ctx.executor, run.LocalExecutor)
assert ctx.executor.ntasks_per_node == 2
assert ctx.plugins[0].some_arg == 20
def test_run_context_plugin_list_factory(self):
ctx = RunContext(name="test_run")
ctx.parse_args(
[
"executor=local_executor",
"executor.ntasks_per_node=2",
"plugins=plugin_list",
"plugins[0].some_arg=50",
]
)
assert isinstance(ctx.executor, run.LocalExecutor)
assert ctx.executor.ntasks_per_node == 2
assert len(ctx.plugins) == 2
assert ctx.plugins[0].some_arg == 50
def test_run_context_parse_fn(self, sample_function):
ctx = RunContext(name="test_run")
partial = ctx.parse_fn(sample_function, ["a=10", "b=hello"])
assert partial.a == 10
assert partial.b == "hello"
assert partial.c == 1.0 # Default value
@patch("nemo_run.dryrun_fn")
@patch("nemo_run.run")
def test_run_context_execute_task(self, mock_run, mock_dryrun_fn, sample_function):
ctx = RunContext(name="test_run", skip_confirmation=True)
ctx.cli_execute(sample_function, ["a=10", "b=hello"])
mock_dryrun_fn.assert_called_once()
mock_run.assert_called_once()
def test_run_context_to_config(self):
ctx = RunContext(name="test_run")
config = ctx.to_config()
assert isinstance(config, run.Config)
assert config.name == "test_run"
def test_run_context_parse_executor(self):
ctx = RunContext(name="test_run")
executor = ctx.parse_executor("local_executor", "ntasks_per_node=4")
assert isinstance(executor, run.Config)
assert executor.__fn_or_cls__ == run.LocalExecutor
assert executor.ntasks_per_node == 4
def test_run_context_parse_plugin(self):
ctx = RunContext(name="test_run")
plugin = ctx.parse_plugin("dummy_plugin", "some_arg=30")
assert isinstance(plugin, run.Config)
assert plugin.__fn_or_cls__.__name__ == "DummyPlugin"
assert plugin.some_arg == 30
def test_run_context_parse_args_with_invalid_executor(self):
ctx = RunContext(name="test_run")
with pytest.raises(ValueError, match="Executor invalid_executor not found"):
ctx.parse_args(["executor=invalid_executor"])
def test_run_context_parse_args_with_invalid_plugin(self):
ctx = RunContext(name="test_run")
with pytest.raises(ValueError, match="Plugin invalid_plugin not found"):
ctx.parse_args(["plugins=invalid_plugin"])
@patch("nemo_run.dryrun_fn")
@patch("nemo_run.run")
def test_run_context_execute_task_with_dryrun(self, mock_run, mock_dryrun_fn, sample_function):
ctx = RunContext(name="test_run", dryrun=True, skip_confirmation=True)
ctx.cli_execute(sample_function, ["a=10", "b=hello"])
mock_dryrun_fn.assert_called_once()
mock_run.assert_not_called()
@patch("nemo_run.dryrun_fn")
@patch("nemo_run.run")
@patch("typer.confirm", return_value=False)
def test_run_context_execute_task_with_confirmation_denied(
self, mock_confirm, mock_run, mock_dryrun_fn, sample_function
):
ctx = RunContext(name="test_run")
cli_api.NEMORUN_SKIP_CONFIRMATION = None
ctx.cli_execute(sample_function, ["a=10", "b=hello"])
mock_dryrun_fn.assert_called_once()
mock_confirm.assert_called_once()
mock_run.assert_not_called()
@patch("IPython.embed")
def test_run_context_execute_task_with_repl(self, mock_embed, sample_function):
ctx = RunContext(name="test_run", repl=True, skip_confirmation=True)
ctx.cli_execute(sample_function, ["a=10", "b=hello"])
mock_embed.assert_called_once()
def test_run_context_parse_fn_with_factory(self, sample_function):
ctx = RunContext(name="test_run", factory="dummy_factory")
with patch("nemo_run.cli.cli_parser.parse_factory") as mock_parse_factory:
mock_parse_factory.return_value = run.Partial(sample_function, a=20, b="world")
partial = ctx.parse_fn(sample_function, [])
assert partial.a == 20
assert partial.b == "world"
assert partial.c == 1.0 # Default value
mock_parse_factory.assert_called_once()
def test_run_context_with_invalid_entrypoint_type(self, sample_function):
ctx = RunContext(name="test_run")
with pytest.raises(ValueError, match="Unknown entrypoint type: invalid_type"):
ctx.cli_execute(sample_function, [], entrypoint_type="invalid_type")
@patch("nemo_run.cli.api.RunContext.cli_execute")
def test_run_context_run_task(self, mock_run):
ctx = RunContext(name="test_run")
def sample_function(a, b):
return None
ctx.cli_execute(sample_function, ["a=10", "b=hello"])
mock_run.assert_called_once_with(sample_function, ["a=10", "b=hello"])
def test_run_context_run_with_detach(self):
ctx = RunContext(name="test_run", skip_confirmation=True)
def sample_function(a, b):
return None
ctx.cli_execute(sample_function, ["a=10", "b=hello", "run.detach=False"])
assert not ctx.detach
def test_run_context_cli_execute_load_not_implemented(self, sample_function):
ctx = RunContext(name="test_run", load="some_dir")
with pytest.raises(NotImplementedError, match="Load is not implemented yet"):
ctx.cli_execute(sample_function, [])
@patch("nemo_run.cli.api._serialize_configuration")
def test_run_context_execute_task_export(self, mock_serialize, sample_function):
ctx = RunContext(name="test_run", to_yaml="config.yaml", skip_confirmation=True)
with patch("nemo_run.dryrun_fn"): # Mock dryrun as it's called before export check
ctx.cli_execute(sample_function, ["a=10"])
mock_serialize.assert_called_once()
assert mock_serialize.call_args[0][1] == "config.yaml" # Check to_yaml path
@patch("nemo_run.run")
@patch("nemo_run.cli.api._serialize_configuration")
def test_execute_lazy_export(self, mock_serialize, mock_run):
# Mock sys.argv for lazy execution context
original_argv = sys.argv
sys.argv = ["nemo_run", "--lazy", "lazy_test", "arg1=1", "--to-yaml", "output.yaml"]
os.environ["LAZY_CLI"] = "true" # Ensure lazy mode is active
# Create a dummy entrypoint for LazyEntrypoint
@cli.entrypoint(namespace="test_lazy")
def lazy_test_fn(arg1: int):
pass
# Directly test the execute_lazy method's export behavior
ctx = RunContext(name="lazy_test", to_yaml="output.yaml", skip_confirmation=True)
# We need executor and plugins initialized even if None, as execute_lazy accesses them
ctx.executor = None
ctx.plugins = []
lazy_entry = LazyEntrypoint("test_lazy.lazy_test_fn arg1=1")
# Mock parse_args as it's called within execute_lazy
with patch("nemo_run.cli.api.RunContext.parse_args", return_value=["arg1=1"]):
# Mock _should_continue to avoid interaction/torchrun checks
with patch("nemo_run.cli.api.RunContext._should_continue", return_value=True):
ctx.execute_lazy(lazy_entry, sys.argv, "lazy_test")
mock_serialize.assert_called_once()
# Check arguments passed to _serialize_configuration
assert isinstance(mock_serialize.call_args[0][0], LazyEntrypoint) # Check config object
assert mock_serialize.call_args[0][1] == "output.yaml" # Check to_yaml path
assert mock_serialize.call_args[1].get("is_lazy") is True # Check is_lazy kwarg
mock_run.assert_not_called() # Should not run if exporting
del os.environ["LAZY_CLI"]
sys.argv = original_argv # Restore original argv
def test_execute_lazy_error_cases(self):
lazy_entry = LazyEntrypoint("dummy")
# Dry run
ctx_dry = RunContext(name="lazy_test", dryrun=True)
with pytest.raises(ValueError, match="Dry run is not supported for lazy execution"):
ctx_dry.execute_lazy(lazy_entry, [], "lazy_test")
# REPL
ctx_repl = RunContext(name="lazy_test", repl=True)
with pytest.raises(
ValueError, match="Interactive mode is not supported for lazy execution"
):
ctx_repl.execute_lazy(lazy_entry, [], "lazy_test")
# Direct
ctx_direct = RunContext(name="lazy_test", direct=True)
with pytest.raises(
ValueError, match="Direct execution is not supported for lazy execution"
):
ctx_direct.execute_lazy(lazy_entry, [], "lazy_test")
@patch("nemo_run.cli.api._serialize_configuration")
@patch("fiddle.build")
def test_execute_experiment_export(self, mock_build, mock_serialize, sample_experiment):
ctx = RunContext(name="test_exp", to_json="exp_config.json", skip_confirmation=True)
with patch("nemo_run.dryrun_fn"): # Mock dryrun
ctx.cli_execute(sample_experiment, ["a=5"], entrypoint_type="experiment")
mock_serialize.assert_called_once()
assert mock_serialize.call_args[0][3] == "exp_config.json" # Check to_json path
assert "is_lazy" in mock_serialize.call_args[1]
assert mock_serialize.call_args[1]["is_lazy"] is False
mock_build.assert_not_called() # Should not build if exporting
@patch("fiddle.build")
def test_execute_experiment_normal(self, mock_build, sample_experiment):
ctx = RunContext(name="test_exp", skip_confirmation=True)
# Mock the build process to avoid actual execution
mock_partial = Mock()
mock_build.return_value = mock_partial
with (
patch("nemo_run.dryrun_fn"),
patch("typer.confirm", return_value=True),
): # Mock dryrun and confirmation
ctx.cli_execute(sample_experiment, ["a=5", "b='exp'"], entrypoint_type="experiment")
mock_build.assert_called_once()
mock_partial.assert_called_once_with() # Check that the built object is called
def test_run_context_get_help(self):
help_text = RunContext.get_help()
assert "Represents the context for executing a run" in help_text
def test_run_context_cli_command_defaults(self):
app = typer.Typer()
defaults = {"dryrun": True, "verbose": True}
# Mock the actual execution logic inside the command
with patch.object(RunContext, "cli_execute") as mock_cli_execute:
# Create the command with defaults
RunContext.cli_command(app, "testcmd", lambda: None, cmd_defaults=defaults)
# Simulate calling the command with no overrides
runner = CliRunner()
runner.invoke(app, ["testcmd"])
# Check that cli_execute was called with the context reflecting defaults
mock_cli_execute.assert_called_once()
# Can't directly check ctx_instance attributes as it's created inside the closure,
# but we can check if the options passed to _configure_global_options reflect defaults
with patch("nemo_run.cli.api._configure_global_options") as mock_configure:
runner.invoke(app, ["testcmd"])
mock_configure.assert_called_with(
app, False, True, True, None, True
) # verbose=True expected
@dataclass
class SomeObject:
value_1: int
value_2: int
value_3: int
class TestFactoryAndResolve:
@patch("nemo_run.cli.api.metadata.entry_points", return_value=_ENTRY_POINTS)
def test_factory_without_arguments(self, mock_entry_points):
@cli.factory
@run.autoconvert
def commonly_used_object() -> SomeObject:
return SomeObject(
value_1=5,
value_2=10,
value_3=15,
)
obj = run.cli.resolve_factory(SomeObject, "commonly_used_object")()
assert isinstance(obj, run.Config)
obj = fdl.build(obj)
assert isinstance(obj, SomeObject)
assert obj.value_1 == 5
assert obj.value_2 == 10
assert obj.value_3 == 15
def test_factory_with_target_and_arg(self):
@dataclass
class ChildObject:
value: str
@dataclass
class ParentObject:
child: Union[ChildObject, str]
@cli.factory(target=ParentObject, target_arg="child")
def common_factory(value="random") -> ChildObject:
return ChildObject(value=value)
cfg = cli.parse_config(ParentObject, "child=common_factory")
assert fdl.build(cfg).child.value == "random"
cfg = cli.parse_config(ParentObject, "child=common_factory(custom)")
assert fdl.build(cfg).child.value == "custom"
def test_factory_default(self):
@dataclass
class DefaultObject:
value: str = "default"
@dataclass
class ParentObject:
obj: DefaultObject
@cli.factory(is_target_default=True)
@run.autoconvert
def default_factory() -> DefaultObject:
return DefaultObject()
cfg = cli.parse_config(ParentObject, "obj=default")
assert fdl.build(cfg).obj.value == "default"
def test_factory_raises_error_without_return_annotation(self):
with pytest.raises(TypeError, match="Missing return type annotation"):
@cli.factory
def no_return_annotation_function():
pass
def test_factory_raises_error_without_parent_when_arg_is_used(self):
@dataclass
class TestObject:
pass
with pytest.raises(
ValueError, match="`target_arg` cannot be used without specifying a `target`."
):
@cli.factory(target_arg="test")
def test_function() -> TestObject:
return TestObject()
def test_factory_with_unsupported_input(self):
@dataclass
class TestObject:
pass
with pytest.raises(TypeError):
obj = TestObject()
obj.__name__ = "abcd"
cli.factory(fn=obj)
def test_factory_with_namespace(self):
@dataclass
class CustomObject:
value: str
@cli.factory(target=CustomObject, namespace="custom_namespace")
@run.autoconvert
def custom_factory() -> CustomObject:
return CustomObject(value="custom")
assert run.cli.resolve_factory("custom_namespace", "custom_factory")().value == "custom"
def test_resolve(self):
dummy_model = run.cli.resolve_factory(DummyModel, "dummy_model")()
assert dummy_model.hidden == 100
assert dummy_model.activation == "relu"
assert isinstance(dummy_model, run.Config)
dummy_model_config = run.cli.resolve_factory(DummyModel, "dummy_model_config")()
assert dummy_model_config.hidden == 2000
assert dummy_model_config.activation == "tanh"
assert isinstance(dummy_model_config, run.Config)
def test_resolve_optional(self):
optim = run.cli.resolve_factory(Optional[Optimizer], "optimizer")
assert optim() == optimizer()
def test_resolve_union(self):
model = run.cli.resolve_factory(Union[DummyModel, Optimizer], "dummy_model")
assert model() == dummy_model()
with pytest.raises(ValueError):
run.cli.resolve_factory(Union[DummyModel, Optimizer], "dummy_model_123")
def test_resolve_entrypoints(self):
assert run.cli.resolve_factory(DummyModel, "dummy_factory_for_entrypoint")().hidden == 1000
def test_help(self):
registry_details = []
for t in config.get_underlying_types(Optional[Optimizer]):
namespace = config.get_type_namespace(t)
registry_details.extend(run.cli.list_factories(namespace))
assert len(registry_details) == 2
assert optimizer in registry_details
def test_factory_for_entrypoint(self):
cfg = run.cli.resolve_factory(dummy_entrypoint, "dummy_recipe")()
assert cfg.dummy.hidden == 2000
def test_forward_ref_with_real_type_factory(self):
"""Test that ForwardRef works when factory is registered for the actual type."""
# Function that uses ForwardRef to the module-level RealType class
def func(param: Optional["RealType"] = None):
pass
from test.dummy_type import RealType as _RealType
# Register the factory in the module's global namespace
# The factory returns a RealType instance with a specific value
@run.cli.factory
@run.autoconvert
def real_type_factory() -> _RealType:
return _RealType(value=100)
@run.cli.factory(target=func, target_arg="param")
@run.autoconvert
def other_factory() -> _RealType:
return _RealType(value=200)
try:
# Now test parsing works using the factory name
result = cli_api.parse_cli_args(func, ["param=real_type_factory"])
assert isinstance(result.param, run.Config)
assert result.param.value == 100
result = cli_api.parse_cli_args(func, ["param=other_factory"])
assert isinstance(result.param, run.Config)
assert result.param.value == 200
finally:
# Clean up - remove the factory from registry
if hasattr(sys.modules[__name__], "real_type_factory"):
delattr(sys.modules[__name__], "real_type_factory")
class TestListEntrypoints:
@dataclass
class DummyTask:
path: str
@pytest.fixture
def mock_get_all(self):
mock_get_all = Mock()
mock_get_all.return_value = {
"namespace1.task1": self.DummyTask(path="namespace1.task1"),
"namespace2.task1": self.DummyTask(path="namespace2.task1"),
"namespace2.task2": self.DummyTask(path="namespace2.task2"),
}
return mock_get_all
def test_list_entrypoints_without_namespace(self, mocker, mock_get_all):
mocker.patch("catalogue._get_all", mock_get_all)
result = cli.list_entrypoints()
mock_get_all.assert_called_once_with(("nemo_run.cli.entrypoints",))
expected_result = {
"namespace1": {"task1": self.DummyTask(path="namespace1.task1")},
"namespace2": {
"task1": self.DummyTask(path="namespace2.task1"),
"task2": self.DummyTask(path="namespace2.task2"),
},
}
assert result == expected_result
def test_list_entrypoints_with_namespace(self, mocker, mock_get_all):
mocker.patch("catalogue._get_all", mock_get_all)
result = cli.list_entrypoints(namespace="hello")
mock_get_all.assert_called_once_with(("nemo_run.cli.entrypoints", "hello"))
expected_result = {
"namespace1": {"task1": self.DummyTask(path="namespace1.task1")},
"namespace2": {
"task1": self.DummyTask(path="namespace2.task1"),
"task2": self.DummyTask(path="namespace2.task2"),
},
}
assert result == expected_result
@dataclass
class Model:
"""Dummy model config"""
hidden_size: int
num_layers: int
activation: str
@dataclass
class Trainer:
"""Dummy trainer config"""
model: Model
learning_rate: float = 0.001
@run.cli.factory
@run.autoconvert
def my_model(hidden_size: int = 256, num_layers: int = 3, activation: str = "relu") -> Model:
"""Create a model configuration."""
return Model(hidden_size=hidden_size, num_layers=num_layers, activation=activation)
@run.cli.factory
@run.autoconvert
def my_other_model(hidden_size: int = 512, num_layers: int = 3, activation: str = "relu") -> Model:
"""Create a model configuration."""
return Model(hidden_size=hidden_size, num_layers=num_layers, activation=activation)
@run.cli.factory
def my_optimizer(
learning_rate: float = 0.001, weight_decay: float = 1e-5, betas: List[float] = [0.9, 0.999]
) -> run.Config[Optimizer]:
"""Create an optimizer configuration."""
return run.Config(
Optimizer, learning_rate=learning_rate, weight_decay=weight_decay, betas=betas
)
def defaults() -> run.Partial["train_model"]:
return run.Partial(
train_model,
model=my_model(),
optimizer=my_optimizer(),
epochs=40,
batch_size=1024,
)
@run.cli.entrypoint(
default_factory=defaults,
namespace="my_llm",
skip_confirmation=True,
)
def train_model(
model: Model,
optimizer: Optimizer,
epochs: int = 10,
batch_size: int = 32,
):
"""
Train a model using the specified configuration.
Args:
model (Model): Configuration for the model.
optimizer (Optimizer): Configuration for the optimizer.
epochs (int, optional): Number of training epochs. Defaults to 10.
batch_size (int, optional): Batch size for training. Defaults to 32.
"""
print("Training model with the following configuration:")
print(f"Model: {model}")
print(f"Optimizer: {optimizer}")
print(f"Epochs: {epochs}")
print(f"Batch size: {batch_size}")
# Simulating model training
for epoch in range(epochs):
print(f"Epoch {epoch + 1}/{epochs}")
print("Training completed!")
return {"model": model, "optimizer": optimizer, "epochs": epochs, "batch_size": batch_size}
@run.cli.entrypoint(
namespace="my_llm",
skip_confirmation=True,
)
def train_model_default_optimizer(
model: Model,
optimizer: Annotated[Optional[Optimizer], run.Config[Optimizer]] = None,
epochs: int = 10,
batch_size: int = 32,
):
if optimizer is None:
optimizer = Optimizer()
return train_model(model, optimizer, epochs, batch_size)
@run.cli.factory(target=train_model)
def custom_defaults() -> run.Partial["train_model"]:
return run.Partial(
train_model,
model=my_model(),
optimizer=my_optimizer(),
epochs=10,
batch_size=1024,
)
class TestEntrypointRunner:
@pytest.fixture
def runner(self):
return CliRunner()
@pytest.fixture
def app(self):
return create_cli(add_verbose_callback=False, nested_entrypoints_creation=False)
def test_parse_partial_function_call(self):
entrypoint = Entrypoint(dummy_entrypoint, namespace="test")
partial = entrypoint.parse_partial(["dummy=my_dummy_model(hidden=100)"])
assert isinstance(partial, run.Partial)
assert partial.dummy.hidden == 100
assert partial.dummy.activation == "tanh"
def test_with_factory(self, runner, app):
# Test CLI execution with default factory
result = runner.invoke(
app,
[
"my_llm",
"train_model",
"--factory",
"custom_defaults",
"model.hidden_size=200",
"--yes",
],
env={"INCLUDE_WORKSPACE_FILE": "false"},
)
assert result.exit_code == 0
output = result.stdout
assert "Training model with the following configuration:" in output
assert "Model: Model(hidden_size=200, num_layers=3, activation='relu')" in output
def test_with_defaults(self, runner, app):
# Test CLI execution with default factory
result = runner.invoke(
app,
[
"my_llm",
"train_model",
"model.hidden_size=1024",
"optimizer.learning_rate=0.005",
"epochs=30",
"run.skip_confirmation=True",
],
env={"INCLUDE_WORKSPACE_FILE": "false"},
)
assert result.exit_code == 0
# Parse the output to check the values
output = result.stdout
assert "Training model with the following configuration:" in output
assert "Model: Model(hidden_size=1024, num_layers=3, activation='relu')" in output
assert (
"Optimizer: Optimizer(learning_rate=0.005, weight_decay=1e-05, betas=[0.9, 0.999])"
in output
)
assert "Epochs: 30" in output
assert "Batch size: 1024" in output
assert "Training completed!" in output
# Check that all epochs were simulated
for i in range(1, 31):
assert f"Epoch {i}/30" in output
def test_with_defaults_no_optimizer(self, runner, app):
# Test CLI execution with default factory
result = runner.invoke(
app,
[
"my_llm",
"train_model_default_optimizer",
"model=my_model(hidden_size=1024)",
"epochs=30",
"run.skip_confirmation=True",
],
env={"INCLUDE_WORKSPACE_FILE": "false"},
)
assert result.exit_code == 0
# Parse the output to check the values
output = result.stdout
assert "Training model with the following configuration:" in output
assert "Model: Model(hidden_size=1024, num_layers=3, activation='relu')" in output
assert "Epochs: 30" in output
assert "Batch size: 32" in output
assert "Training completed!" in output
# Check that all epochs were simulated
for i in range(1, 31):
assert f"Epoch {i}/30" in output
def test_experiment_entrypoint(self):
def dummy_pretrain(log_dir: str):
pass
def dummy_finetune(log_dir: str):
pass
@run.cli.entrypoint(namespace="llm", type="experiment")
def my_experiment(
ctx: run.cli.RunContext,
pretrain: run.Partial[dummy_pretrain] = run.Partial(
dummy_pretrain, log_dir="/pretrain"
),
finetune: run.Partial[dummy_finetune] = run.Partial(
dummy_finetune, log_dir="/finetune"
),
):
pretrain.log_dir = f"/{ctx.experiment.name}/checkpoints"
finetune.log_dir = f"/{ctx.experiment.name}/checkpoints"
for i in range(1):
ctx.experiment.add(
pretrain,
executor=ctx.executor,
name=ctx.experiment.name,
tail_logs=True if isinstance(ctx.executor, run.LocalExecutor) else False,
)
ctx.experiment.add(
finetune,
executor=ctx.executor,
name=ctx.experiment.name,
tail_logs=True if isinstance(ctx.executor, run.LocalExecutor) else False,
)
return ctx.experiment
# Mock the necessary objects and methods
mock_experiment = Mock(spec=run.Experiment)
mock_experiment.name = "test_experiment"
mock_executor = Mock(spec=run.LocalExecutor)
mock_ctx = Mock(spec=run.cli.RunContext)
mock_ctx.experiment = mock_experiment
mock_ctx.executor = mock_executor
mock_pretrain = Mock(spec=dummy_pretrain)
mock_pretrain.log_dir = "/pretrain"
mock_finetune = Mock(spec=dummy_finetune)
mock_finetune.log_dir = "/finetune"
# Call the entrypoint function
result = my_experiment(ctx=mock_ctx, pretrain=mock_pretrain, finetune=mock_finetune)
# Assert that the experiment methods were called correctly
assert result == mock_experiment
assert mock_experiment.add.call_count == 2
mock_experiment.add.assert_any_call(
mock_pretrain, executor=mock_executor, name=mock_experiment.name, tail_logs=True
)
mock_experiment.add.assert_any_call(
mock_finetune, executor=mock_executor, name=mock_experiment.name, tail_logs=True
)
assert mock_pretrain.log_dir == f"/{mock_experiment.name}/checkpoints"
assert mock_finetune.log_dir == f"/{mock_experiment.name}/checkpoints"
@dataclass
class SomeObject:
value_1: int
value_2: int
def test_with_factory_and_overwrite(self, runner, app):
# Test CLI execution with factory and parameter overwrite
result = runner.invoke(
app,
[
"my_llm",
"train_model",
"model=my_other_model",
"model.num_layers=10",
"--yes",
],
env={"INCLUDE_WORKSPACE_FILE": "false"},
)
assert result.exit_code == 0
output = result.stdout
assert "Training model with the following configuration:" in output
# Check that my_model_2's default hidden_size (512) is used
assert "Model: Model(hidden_size=512, num_layers=10, activation='relu')" in output
class TestDefaultFactory:
def test_default_factory(self):
# Test that the default factory is applied correctly
partial = run.cli.resolve_factory(train_model, "default")()
assert isinstance(partial, run.Partial)
# Check that the default values are set correctly
assert partial.model.hidden_size == 256
assert partial.model.num_layers == 3
assert partial.model.activation == "relu"
assert partial.optimizer.learning_rate == 0.001
assert partial.optimizer.weight_decay == 1e-5
assert partial.optimizer.betas == [0.9, 0.999]
assert partial.epochs == 40
assert partial.batch_size == 1024
def test_build_from_default_factory(self):
# Test that we can build the configuration from the default factory
partial = run.cli.resolve_factory(train_model, "default")()
result = fdl.build(partial)()
assert isinstance(result["model"], Model)
assert isinstance(result["optimizer"], Optimizer)
assert result["epochs"] == 40
assert result["batch_size"] == 1024
@pytest.fixture
def runner():
return CliRunner()
class TestGlobalOptions:
@pytest.fixture(autouse=True)
def _setup(self):
"""Setup for all test cases"""
# Store original environment for cleanup
self.original_env = os.environ.copy()
yield
# Restore environment after each test
os.environ.clear()
os.environ.update(self.original_env)
@pytest.fixture
def app(self):
app = typer.Typer()
# Add test command that throws an error
@app.command()
def error_command():
"""Command that throws a test exception"""
raise ValueError("Test error for exception handling")
# Add global options to test app
add_global_options(app)
return app
def test_verbose_logging(self, runner, app):
"""Test verbose logging functionality"""
with patch("nemo_run.cli.api.configure_logging") as mock_configure:
# Test enabled
runner.invoke(app, ["-v", "error-command"])
mock_configure.assert_called_once_with(True)
# Test disabled
mock_configure.reset_mock()
runner.invoke(app, ["error-command"])
mock_configure.assert_called_once_with(False)
class TestTorchrunAndConfirmation:
"""Test torchrun detection and confirmation behavior."""
@patch("os.environ", {"WORLD_SIZE": "2"})
def test_is_torchrun_true(self):
"""Test that _is_torchrun returns True when WORLD_SIZE > 1."""
from nemo_run.cli.api import _is_torchrun
assert _is_torchrun() is True
@patch("os.environ", {})
def test_is_torchrun_false_no_env(self):
"""Test that _is_torchrun returns False when WORLD_SIZE not in environment."""
from nemo_run.cli.api import _is_torchrun
assert _is_torchrun() is False
@patch("os.environ", {"WORLD_SIZE": "1"})
def test_is_torchrun_false_size_one(self):
"""Test that _is_torchrun returns False when WORLD_SIZE = 1."""