-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
test_rasa_train.py
627 lines (497 loc) · 18.6 KB
/
test_rasa_train.py
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
import os
import sys
from pathlib import Path
from _pytest.capture import CaptureFixture
import pytest
from typing import Callable, List
from _pytest.pytester import RunResult
from _pytest.tmpdir import TempPathFactory
import rasa.shared.utils.io
from rasa.constants import NUMBER_OF_TRAINING_STORIES_FILE
from rasa.core.policies.policy import Policy
from rasa.engine.storage.local_model_storage import LocalModelStorage
from rasa.engine.storage.resource import Resource
from rasa.shared.core.domain import Domain
from rasa.model_training import CODE_NEEDS_TO_BE_RETRAINED, CODE_FORCED_TRAINING
from rasa.shared.constants import (
LATEST_TRAINING_DATA_FORMAT_VERSION,
)
from rasa.shared.nlu.training_data.training_data import (
DEFAULT_TRAINING_DATA_OUTPUT_PATH,
)
import rasa.utils.io
from tests.cli.conftest import RASA_EXE
@pytest.mark.parametrize(
"optional_arguments",
[
["--endpoints", "endpoints.yml"],
["--endpoints", "non_existent_endpoints.yml"],
[],
],
)
def test_train(
run_in_simple_project: Callable[..., RunResult],
tmp_path: Path,
optional_arguments: List,
):
temp_dir = os.getcwd()
run_in_simple_project(
"train",
"-c",
"config.yml",
"-d",
"domain.yml",
"--data",
"data",
"--out",
"train_models",
"--fixed-model-name",
"test-model",
*optional_arguments,
)
models_dir = Path(temp_dir, "train_models")
assert models_dir.is_dir()
models = list(models_dir.glob("*"))
assert len(models) == 1
model = models[0]
assert model.name == "test-model.tar.gz"
_, metadata = LocalModelStorage.from_model_archive(tmp_path, model)
assert metadata.model_id
assert (
metadata.domain.as_dict() == Domain.load(Path(temp_dir, "domain.yml")).as_dict()
)
def test_train_finetune(
run_in_simple_project: Callable[..., RunResult], capsys: CaptureFixture
):
run_in_simple_project("train", "--finetune")
output = capsys.readouterr().out
assert "No model for finetuning found" in output
def test_train_persist_nlu_data(
run_in_simple_project: Callable[..., RunResult], tmp_path: Path
):
temp_dir = os.getcwd()
run_in_simple_project(
"train",
"-c",
"config.yml",
"-d",
"domain.yml",
"--data",
"data",
"--out",
"train_models",
"--fixed-model-name",
"test-model",
"--persist-nlu-data",
)
models_dir = Path(temp_dir, "train_models")
assert models_dir.is_dir()
models = list(models_dir.glob("*"))
assert len(models) == 1
model = models[0]
assert model.name == "test-model.tar.gz"
storage, _ = LocalModelStorage.from_model_archive(tmp_path, model)
with storage.read_from(Resource("nlu_training_data_provider")) as directory:
assert (directory / DEFAULT_TRAINING_DATA_OUTPUT_PATH).exists()
def test_train_no_domain_exists(
run_in_simple_project: Callable[..., RunResult], tmp_path: Path
) -> None:
os.remove("domain.yml")
run_in_simple_project(
"train",
"--skip-validation",
"-c",
"config.yml",
"--data",
"data",
"--out",
"train_models_no_domain",
"--fixed-model-name",
"nlu-model-only",
)
model_file = Path("train_models_no_domain", "nlu-model-only.tar.gz")
assert model_file.is_file()
_, metadata = LocalModelStorage.from_model_archive(tmp_path, model_file)
assert not any(
issubclass(component.uses, Policy)
for component in metadata.train_schema.nodes.values()
)
assert not any(
issubclass(component.uses, Policy)
for component in metadata.predict_schema.nodes.values()
)
def test_train_skip_on_model_not_changed(
run_in_simple_project_with_model: Callable[..., RunResult],
tmp_path_factory: TempPathFactory,
):
temp_dir = os.getcwd()
models_dir = Path(temp_dir, "models")
model_files = list(models_dir.glob("*"))
assert len(model_files) == 1
old_model = model_files[0]
run_in_simple_project_with_model("train")
model_files = list(sorted(models_dir.glob("*")))
assert len(model_files) == 2
new_model = model_files[1]
assert old_model != new_model
old_dir = tmp_path_factory.mktemp("old")
_, old_metadata = LocalModelStorage.from_model_archive(old_dir, old_model)
new_dir = tmp_path_factory.mktemp("new")
_, new_metadata = LocalModelStorage.from_model_archive(new_dir, new_model)
assert old_metadata.model_id != new_metadata.model_id
assert old_metadata.trained_at < new_metadata.trained_at
assert old_metadata.domain.as_dict() == new_metadata.domain.as_dict()
assert rasa.utils.io.are_directories_equal(old_dir, new_dir)
def test_train_force(
run_in_simple_project_with_model: Callable[..., RunResult],
tmp_path_factory: TempPathFactory,
):
temp_dir = os.getcwd()
assert os.path.exists(os.path.join(temp_dir, "models"))
files = rasa.shared.utils.io.list_files(os.path.join(temp_dir, "models"))
assert len(files) == 1
run_in_simple_project_with_model("train", "--force")
assert os.path.exists(os.path.join(temp_dir, "models"))
files = rasa.shared.utils.io.list_files(os.path.join(temp_dir, "models"))
assert len(files) == 2
old_dir = tmp_path_factory.mktemp("old")
_ = LocalModelStorage.from_model_archive(old_dir, files[0])
new_dir = tmp_path_factory.mktemp("new")
_ = LocalModelStorage.from_model_archive(new_dir, files[1])
assert not rasa.utils.io.are_directories_equal(old_dir, new_dir)
def test_train_dry_run(run_in_simple_project_with_model: Callable[..., RunResult]):
temp_dir = os.getcwd()
assert os.path.exists(os.path.join(temp_dir, "models"))
files = rasa.shared.utils.io.list_files(os.path.join(temp_dir, "models"))
assert len(files) == 1
output = run_in_simple_project_with_model("train", "--dry-run")
assert [s for s in output.outlines if "No training of components required" in s]
assert output.ret == 0
def test_train_dry_run_failure(run_in_simple_project: Callable[..., RunResult]):
temp_dir = os.getcwd()
domain = (
"version: '" + LATEST_TRAINING_DATA_FORMAT_VERSION + "'\n"
"session_config:\n"
" session_expiration_time: 60\n"
" carry_over_slots_to_new_session: true\n"
"actions:\n"
"- utter_greet\n"
"- utter_cheer_up"
)
with open(os.path.join(temp_dir, "domain.yml"), "w") as f:
f.write(domain)
output = run_in_simple_project("train", "--dry-run")
assert not any([s for s in output.outlines if "No training required." in s])
assert (output.ret & CODE_NEEDS_TO_BE_RETRAINED == CODE_NEEDS_TO_BE_RETRAINED) and (
output.ret & CODE_FORCED_TRAINING != CODE_FORCED_TRAINING
)
def test_train_dry_run_force(
run_in_simple_project_with_model: Callable[..., RunResult]
):
temp_dir = os.getcwd()
assert os.path.exists(os.path.join(temp_dir, "models"))
files = rasa.shared.utils.io.list_files(os.path.join(temp_dir, "models"))
assert len(files) == 1
output = run_in_simple_project_with_model("train", "--dry-run", "--force")
assert [s for s in output.outlines if "The training was forced." in s]
assert output.ret == CODE_FORCED_TRAINING
def test_train_with_only_nlu_data(run_in_simple_project: Callable[..., RunResult]):
temp_dir = Path.cwd()
for core_file in ["stories.yml", "rules.yml"]:
assert (temp_dir / "data" / core_file).exists()
(temp_dir / "data" / core_file).unlink()
run_in_simple_project("train", "--fixed-model-name", "test-model")
assert os.path.exists(os.path.join(temp_dir, "models"))
files = rasa.shared.utils.io.list_files(os.path.join(temp_dir, "models"))
assert len(files) == 1
assert os.path.basename(files[0]) == "test-model.tar.gz"
def test_train_with_only_core_data(run_in_simple_project: Callable[..., RunResult]):
temp_dir = os.getcwd()
assert os.path.exists(os.path.join(temp_dir, "data/nlu.yml"))
os.remove(os.path.join(temp_dir, "data/nlu.yml"))
run_in_simple_project("train", "--fixed-model-name", "test-model")
assert os.path.exists(os.path.join(temp_dir, "models"))
files = rasa.shared.utils.io.list_files(os.path.join(temp_dir, "models"))
assert len(files) == 1
assert os.path.basename(files[0]) == "test-model.tar.gz"
def test_train_core(run_in_simple_project: Callable[..., RunResult]):
run_in_simple_project(
"train",
"core",
"-c",
"config.yml",
"-d",
"domain.yml",
"--stories",
"data",
"--out",
"train_rasa_models",
"--fixed-model-name",
"rasa-model",
)
assert os.path.exists("train_rasa_models/rasa-model.tar.gz")
assert os.path.isfile("train_rasa_models/rasa-model.tar.gz")
def test_train_core_no_domain_exists(run_in_simple_project: Callable[..., RunResult]):
os.remove("domain.yml")
run_in_simple_project(
"train",
"core",
"--config",
"config.yml",
"--domain",
"domain1.yml",
"--stories",
"data",
"--out",
"train_rasa_models_no_domain",
"--fixed-model-name",
"rasa-model",
)
assert not list(Path("train_rasa_models_no_domain").glob("*"))
def test_train_core_compare(
run_in_simple_project: Callable[..., RunResult], tmp_path: Path
):
run_in_simple_project(
"train",
"core",
"-c",
"config.yml",
"config.yml",
"-d",
"domain.yml",
"--stories",
"data",
"--out",
str(tmp_path),
"--runs",
"2",
"--percentages",
"50",
"100",
)
for run in range(1, 2):
assert (tmp_path / f"run_{run}" / "config__percentage__50.tar.gz").exists()
assert (tmp_path / f"run_{run}" / "config__percentage__100.tar.gz").exists()
num_stories = rasa.shared.utils.io.read_yaml_file(
tmp_path / NUMBER_OF_TRAINING_STORIES_FILE
)
assert num_stories == [3, 0]
def test_train_nlu(run_in_simple_project: Callable[..., RunResult], tmp_path: Path):
run_in_simple_project(
"train",
"nlu",
"-c",
"config.yml",
"--nlu",
"data/nlu.yml",
"--out",
"train_models",
)
model_dir = Path("train_models")
assert model_dir.is_dir()
models = list(model_dir.glob("*.tar.gz"))
assert len(models) == 1
model_file = models[0]
assert model_file.name.startswith("nlu-")
_, metadata = LocalModelStorage.from_model_archive(tmp_path, model_file)
assert not any(
issubclass(component.uses, Policy)
for component in metadata.train_schema.nodes.values()
)
assert not any(
issubclass(component.uses, Policy)
for component in metadata.predict_schema.nodes.values()
)
def test_train_nlu_persist_nlu_data(
run_in_simple_project: Callable[..., RunResult], tmp_path: Path
) -> None:
run_in_simple_project(
"train",
"nlu",
"-c",
"config.yml",
"--nlu",
"data/nlu.yml",
"--out",
"train_models",
"--persist-nlu-data",
)
models_dir = Path("train_models")
assert models_dir.is_dir()
models = list(models_dir.glob("*"))
assert len(models) == 1
model = models[0]
assert model.name.startswith("nlu-")
storage, _ = LocalModelStorage.from_model_archive(tmp_path, model)
with storage.read_from(Resource("nlu_training_data_provider")) as directory:
assert (directory / DEFAULT_TRAINING_DATA_OUTPUT_PATH).exists()
def test_train_help(run: Callable[..., RunResult]):
output = run("train", "--help")
help_text = f"""usage: {RASA_EXE} train [-h] [-v] [-vv] [--quiet]
[--logging-config-file LOGGING_CONFIG_FILE]
[--data DATA [DATA ...]] [-c CONFIG] [-d DOMAIN] [--out OUT]
[--dry-run] [--skip-validation]
[--fail-on-validation-warnings]
[--validation-max-history VALIDATION_MAX_HISTORY]
[--augmentation AUGMENTATION] [--debug-plots]
[--num-threads NUM_THREADS]
[--fixed-model-name FIXED_MODEL_NAME] [--persist-nlu-data]
[--force] [--finetune [FINETUNE]]
[--epoch-fraction EPOCH_FRACTION] [--endpoints ENDPOINTS]
{{core,nlu}} ..."""
lines = help_text.split("\n")
# expected help text lines should appear somewhere in the output
printed_help = {line.strip() for line in output.outlines}
for line in lines:
assert line.strip() in printed_help
def test_train_nlu_help(run: Callable[..., RunResult]):
output = run("train", "nlu", "--help")
help_text = f"""usage: {RASA_EXE} train nlu [-h] [-v] [-vv] [--quiet]
[--logging-config-file LOGGING_CONFIG_FILE] [-c CONFIG]
[-d DOMAIN] [--out OUT] [-u NLU]
[--num-threads NUM_THREADS]
[--fixed-model-name FIXED_MODEL_NAME]
[--persist-nlu-data] [--finetune [FINETUNE]]
[--epoch-fraction EPOCH_FRACTION]"""
lines = help_text.split("\n")
# expected help text lines should appear somewhere in the output
printed_help = {line.strip() for line in output.outlines}
for line in lines:
assert line.strip() in printed_help
def test_train_core_help(run: Callable[..., RunResult]):
output = run("train", "core", "--help")
if sys.version_info.minor >= 9:
# This is required because `argparse` behaves differently on
# Python 3.9 and above. The difference is the changed formatting of help
# output for CLI arguments with `nargs="*"
help_text = f"""usage: {RASA_EXE} train core [-h] [-v] [-vv] [--quiet]
[--logging-config-file LOGGING_CONFIG_FILE]
[-s STORIES] [-d DOMAIN] [-c CONFIG [CONFIG ...]]
[--out OUT] [--augmentation AUGMENTATION]
[--debug-plots] [--force]
[--fixed-model-name FIXED_MODEL_NAME]
[--percentages [PERCENTAGES ...]] [--runs RUNS]
[--finetune [FINETUNE]]
[--epoch-fraction EPOCH_FRACTION]"""
else:
help_text = f"""usage: {RASA_EXE} train core [-h] [-v] [-vv] [--quiet]
[--logging-config-file LOGGING_CONFIG_FILE]
[-s STORIES] [-d DOMAIN] [-c CONFIG [CONFIG ...]]
[--out OUT] [--augmentation AUGMENTATION]
[--debug-plots] [--force]
[--fixed-model-name FIXED_MODEL_NAME]
[--percentages [PERCENTAGES [PERCENTAGES ...]]]
[--runs RUNS] [--finetune [FINETUNE]]
[--epoch-fraction EPOCH_FRACTION]"""
lines = help_text.split("\n")
# expected help text lines should appear somewhere in the output
printed_help = {line.strip() for line in output.outlines}
for line in lines:
assert line.strip() in printed_help
def test_train_nlu_finetune_with_model(
run_in_simple_project_with_model: Callable[..., RunResult]
):
temp_dir = os.getcwd()
files = rasa.shared.utils.io.list_files(os.path.join(temp_dir, "models"))
assert len(files) == 1
model_name = os.path.relpath(files[0])
output = run_in_simple_project_with_model("train", "--finetune", model_name)
assert any(
"Your Rasa model is trained and saved at" in line for line in output.outlines
)
def test_train_validation_warnings(
run_in_simple_project: Callable[..., RunResult], request: pytest.FixtureRequest
):
test_data_dir = Path(request.config.rootdir, "data", "test_validation", "data")
test_domain = Path(request.config.rootdir, "data", "test_validation", "domain.yml")
result = run_in_simple_project(
"train",
"--data",
str(test_data_dir),
"--domain",
str(test_domain),
"-c",
"config.yml",
)
assert result.ret == 0
for warning in [
"The intent 'goodbye' is not used in any story or rule.",
"The utterance 'utter_chatter' is not used in any story or rule.",
]:
assert warning in str(result.stderr)
def test_train_validation_fail_on_warnings(
run_in_simple_project_with_warnings: Callable[..., RunResult],
request: pytest.FixtureRequest,
):
test_data_dir = Path(request.config.rootdir, "data", "test_moodbot", "data")
test_domain = Path(request.config.rootdir, "data", "test_domains", "default.yml")
result = run_in_simple_project_with_warnings(
"train",
"--fail-on-validation-warnings",
"--data",
str(test_data_dir),
"--domain",
str(test_domain),
"-c",
"config.yml",
)
assert "Project validation completed with errors." in str(result.outlines)
assert result.ret == 1
def test_train_validation_fail_to_load_domain(
run_in_simple_project: Callable[..., RunResult],
):
result = run_in_simple_project(
"train",
"--domain",
"not_existing_domain.yml",
)
assert "Encountered empty domain during validation." in str(result.outlines)
assert result.ret == 1
def test_train_validation_max_history_1(
run_in_simple_project_with_warnings: Callable[..., RunResult],
request: pytest.FixtureRequest,
):
test_data_dir = Path(
request.config.rootdir,
"data",
"test_yaml_stories",
"stories_conflicting_at_1.yml",
)
test_domain = Path(request.config.rootdir, "data", "test_domains", "default.yml")
result = run_in_simple_project_with_warnings(
"train",
"--validation-max-history",
"1",
"--data",
str(test_data_dir),
"--domain",
str(test_domain),
"-c",
"config.yml",
)
assert "Story structure conflict" in str(result.errlines)
assert result.ret == 0
def test_train_validation_max_history_2(
run_in_simple_project_with_warnings: Callable[..., RunResult],
request: pytest.FixtureRequest,
):
test_data_dir = Path(
request.config.rootdir,
"data",
"test_yaml_stories",
"stories_conflicting_at_1.yml",
)
test_domain = Path(request.config.rootdir, "data", "test_domains", "default.yml")
result = run_in_simple_project_with_warnings(
"train",
"--validation-max-history",
"2",
"--data",
str(test_data_dir),
"--domain",
str(test_domain),
"-c",
"config.yml",
)
assert "Story structure conflict" not in str(result.errlines)
assert result.ret == 0