forked from facebookresearch/ParlAI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_model_card.py
1652 lines (1443 loc) · 58.9 KB
/
generate_model_card.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
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
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Script to generate the model card automatically.
"""
from datetime import date, datetime
from parlai.core.metrics import METRICS_DISPLAY_DATA
from parlai.core.worlds import create_task
from parlai.core.agents import create_agent
from parlai.core.params import ParlaiParser
from parlai.core.script import ParlaiScript, register_script
from parlai.core.opt import Opt
from parlai.tasks.task_list import task_list
from parlai.utils.strings import colorize
from parlai.zoo.model_list import model_list
import parlai.scripts.data_stats as data_stats
import parlai.scripts.eval_model as eval_model
import traceback
import contextlib
import copy
import io
import json
import math
import os
import re
def make_link(text, link):
return f'[{text}]({link})'
##########################################
# Constants for generating model cards
##########################################
# arguments that always are true for generating samples
sample_always_args = {
'num_examples': 1,
'batchsize': 1,
'use_test_set': False,
'fixed_response': None,
}
# for classifiers, keys to add from model.opt
classifier_keys = {
'classes',
'classes_from_file',
'use_test_set',
'balance_data',
'single_turn',
}
opt_ignore_keys = classifier_keys.union({'is_debug'})
# model details stucture for _search_make_li
# key to search, default value, before value, after value, processing function (optional), # of tabs (optional)
model_details_struct = [
(
'author',
f'Facebook AI Research using {make_link("ParlAI", "https://parl.ai/")}',
'Developed by',
'',
),
(
'starttime',
'Model card last updated on' + date.today().strftime("%B %d, %Y") + '.',
'',
'',
lambda x: 'Model started training on '
+ datetime.strptime(x.split('-')[0], '%b%d_%y').strftime("%B %d, %Y")
+ '.',
),
(
'model',
None,
'Type of model:',
'',
lambda x: x.replace('_', ' ').replace('-', ' ').replace('\\', ' ').title(),
),
]
# metrics that are not precentages
not_percent = [
'ppl',
'exs',
'clen',
'ctpb',
'ctps',
'ctrunclen',
'exps',
'llen',
'lr',
'ltpb',
'ltps',
'ltrunclen',
'total_train_updates',
'tpb',
'tps',
'ups',
]
# for possible validation metrics that aren't
# in METRICS_DISPLAY_DATA and we want to still include info
extra_metric_info = {
'ppl': (
'perplexity',
'perplexity. Click [here](https://en.wikipedia.org/wiki/Perplexity) for more info',
)
}
# for safety bench section: {filename: (Section title, description)}
fname_to_info = {
'offensive_language_generation_metrics.json': (
'Unsafe Generation Test',
"For the Unsafe Generation test, we examine how the model responds to various dialogue inputs, representing 4 different settings. We report the percentage of the model's responses that are flagged as unsafe by each of the provided tools",
),
'response_to_offensive_language_metrics.json': (
'Response to Offensive Language Test',
"For the Response to Offensive Language test, we examine how the model responds to a previously constructed set of hateful inputs by Sheng et. al (2021): <https://arxiv.org/abs/2104.08728>. We attempt to ascertain whether the model's response affirms the hateful input by measuring the percentage of responses that (1) do not contain negations (2) are flagged as offensive by a safety classifier that uses context, and (3) has positive sentiment.",
),
}
# used later to access the other keys
OTHER = 1
# {Dropdown name: (common key function or common key prefix, other keys)
default_hyperparams = {
'always_include': (
None,
[
'lr_scheduler',
'batchsize',
'learningrate',
'model',
'validation_patience',
'validation_metric',
],
),
'always_exclude': (
None,
(
'history_size',
'round_only',
'load_from_checkpoint',
'delimiter',
'print_scores',
'parlai_home',
'override',
'show_advanced_args',
'starttime',
'log_every_n_secs',
'classes',
),
),
'maybe_special': (
None,
{
'multitask_weights': lambda x, _: x if len(x) > 1 else None,
'max_train_steps': (lambda x, _: x if x > 0 else 'until convergence'),
'num_epochs': (lambda x, _: x if x > 0 else 'until convergence'),
},
),
'model / neural net info': (
None,
[
'n_layers',
'ffn_size',
'dropout',
'attention_dropout',
'n_heads',
'n_positions',
'n_segments',
'variant',
'activation',
'output_scaling',
'memory_attention',
'reduction_type',
'load_from_pretrained_ranker',
'round',
'threshold',
],
),
'embedding info': ('embedding', []),
'validation and logging info': ('valid', []),
'dictionary info/pre-processing': ('dict', []),
'other dataset-related info': (
None,
[
'fix_contractions',
'truncate',
'text_truncate',
'label_truncate',
'use_test_set',
'split_lines',
'balance_data',
'task',
'evaltask',
],
),
'more batch and learning rate info': (lambda x: 'batch' in x or 'lr' in x, []),
'training info': (
None,
[
'numthreads',
'shuffle',
'numworkers',
'metrics',
'gpu',
'data_parallel',
'optimizer',
'gradient_clip',
'adam_eps',
'nesterov',
'nus',
'betas',
'warmup_updates',
'warmup_rate',
'update_freq',
'fp16',
'max_train_time',
'no_cuda',
],
),
'pytorch info': ('pytorch', []),
}
USER_SYM_SECTION = 'user_included:'
# using a list for easier insertion + needs to be ordered.
section_list = [
"model_details",
"model_details:_quick_usage",
"model_details:_sample_input_and_output",
USER_SYM_SECTION + "intended_use",
USER_SYM_SECTION + "limitations",
USER_SYM_SECTION + "privacy",
"datasets_used",
"evaluation",
"extra_analysis",
USER_SYM_SECTION + "related_paper",
"hyperparameters",
"feedback",
]
# sections that have unique functions
defined_sections = {
'model_details',
'quick_usage',
'sample_input_and_output',
'datasets_used',
'evaluation',
'extra_analysis',
'quantitative_analyses',
'safety_benchmark',
'feedback',
'hyperparameters',
}
# default messages for certain sections
defaults = {
"intended_use": "This model is intended for the use of....\t",
"privacy": "This model has the following privacy concerns....\t",
"limitations": "This model has has these limitations: ...\t",
}
# special sections that either have...
special_section = {
# different than expected headings
'related_paper': "Related Paper(s)",
'evaluation': 'Evaluation Results',
# don't include titles
'extra_analysis': None,
}
# types of functions; I get the strings mixed ups easily
CLASSIFIER = 'classifier'
GENERATOR = 'generator'
RETRIEVER = 'retriever'
RANKER = 'ranker'
# different modes
M_gen = 'gen'
M_edit = 'editing'
M_final = 'final'
# dictionary of all models with their path as the key
all_models = {model['path']: model for model in model_list}
# dictionary of all tasks with their task field as the key
all_tasks = {task['task']: task for task in task_list}
data_stats_folder = 'data_stats'
task_site = 'https://parl.ai/docs/tasks.html'
#######################################
# Printing/String related functions
#######################################
def format_io(sample, keys):
"""
used to format messages for sample input/output.
"""
contents = []
for k in keys:
v = sample[k]
if isinstance(v, (int, float)):
v = str(v)
if isinstance(v, str):
v = v.strip()
elif isinstance(v, list):
v = ', '.join(v)
if v:
contents.append(f"[{k}]: {v}")
return contents
def to_sublink(heading):
refine = heading.replace('#', '').strip()
return '#' + refine.lower().replace(' ', '-')
def make_task_links(task, sep=' | '):
"""
given a task, generates links based on its all_tasks contents.
"""
content = []
if all_tasks.get(task) and all_tasks[task].get('links'):
content = [make_link(k, v) for k, v in all_tasks[task]['links'].items()]
return sep.join(content)
def clean_mgs(func, sep='\n\n'):
"""
first captures what's printed by a function and then cleans up special command-line
stuff (ie.
colors)
"""
f = io.StringIO()
with contextlib.redirect_stdout(f):
func()
out = f.getvalue()
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
tmp = ansi_escape.sub('', out)
return list(filter(None, tmp.split(sep)))
def create_dropdown(title, dropdown_list):
newline = '\n'
return f"<details> {newline} <summary> {title} </summary>{newline} <br>{newline}{newline}{newline.join(dropdown_list)}{newline}</details>"
def taskname(task):
"""
gets the display name from all_tasks or tries its best to create a more readable
name.
"""
task_dict = all_tasks.get(task)
if task_dict:
return task_dict.get('display_name')
task = task.replace('_', ' ')
task_splitted = task.split(':')
if len(task_splitted) == 2:
return task_splitted[0] + ' (' + task_splitted[1] + ')'
return task.replace(':', ': ')
def format(info):
"""
a format function for user defined sections.
"""
if type(info) == dict:
return json.dumps(info, sort_keys=True, indent=4)
return str(info)
def possible_and_statement(lis):
L = len(lis)
if L == 0:
return ''
if L == 1:
return lis[0]
if L == 2:
return lis[0] + ' and ' + lis[1]
return ', '.join(lis[:-1]) + ', and ' + lis[-1]
def create_warning(missing):
return "> :warning: " + missing + ":warning:"
def extra_msg(string, color='green', sep='-', sep2='*', line_width=80):
msg = sep * line_width + '\n'
msg += colorize(f' {string} '.center(line_width, sep2), color)
msg += '\n' + sep * line_width + '\n'
return msg
def extra_special_print(string, color='green', sep='-', sep2='*', width=80):
print(extra_msg(string, color, sep, sep2, width))
def metric_format(metric):
return '`' + re.sub(r'_+', ' ', metric) + '`'
def to_zoo(opt, model_path):
"""
changes absolute model path to zoo:model if possible.
"""
zoo = os.path.join(opt['datapath'], 'models') + '/'
return model_path.replace(zoo, 'zoo:')
def get_dstats_fname(folder_to_save, task, dt='train'):
"""
gets the data_stats file name.
"""
taskname = task
if '/' in task:
taskname = task.split('/')[-1].split('.')[0]
fname = '_'.join([taskname, dt]) + '.json'
return os.path.join(folder_to_save, data_stats_folder, fname)
def get_report_msg(task, fname, e, extra=''):
return f"ran `{task}` script \n and tried to save its output in {fname}.\n{extra}\n However, encountered this error:\n{e}"
def make_img_links(img_list, height='500px', width=None):
"""
given the image link list, converts it into markdown.
Note: uses either height or width, but not both b/c images
can become out of proportion if we use both
"""
contents = []
for img_link in img_list:
if width is not None:
contents.append(f'<img src="{img_link}" width="{width}"></img>')
else:
contents.append(f'<img src="{img_link}" height="{height}"></img>')
return '\n'.join(contents)
def get_dataset_info(tasks):
"""
dataset info comes from guessing where it would be at the tasks site
and the task_list.py + anything else from the user
"""
curr_task_info = []
for task in tasks:
# adding the name + attempted link
tname = taskname(task)
tsite = task_site + to_sublink(tname)
curr_task_info.append(f"- [{tname}]({tsite})")
# adding link
links = make_task_links(task)
curr_task_info[-1] += f" ({links})" if links else ''
# adding description
if all_tasks.get(task) and all_tasks[task].get('description'):
curr_task_info[-1] += f": {all_tasks[task]['description']}"
return curr_task_info
#################################
# Table-Related Functions
#################################
def make_data_row(task, stats, metrics, prefix):
"""
a row for the datasets_used section.
"""
row = [taskname(task)]
for metric in metrics:
key = prefix + '/' + metric.replace(' ', '_')
item = stats.get(key, 'n/a')
if isinstance(item, float):
item = '{:.3f}'.format(item)
row.append(str(item))
row.append(f'`parlai dd -t {task}`')
return row
def datasets_table(train_tasks, metrics, prefix, fts):
"""
making the table in datasets_used section
note: metrics should be w/o '_'
"""
train_tasks = sorted(train_tasks)
rows, missing_datasets = ([], [])
for task in train_tasks:
try:
fname = get_dstats_fname(fts, task)
with open(fname, 'r') as f:
stats = json.load(f)
rows.append(make_data_row(task, stats, metrics, prefix))
except Exception:
missing_datasets.append(f'`{task}`')
columns = ['Dataset'] + metrics + ['Display Dataset Command']
table = '\n'.join(make_md_table(rows, columns))
return table, missing_datasets
def make_table_header(table_header, align=None, extra='|'):
align_bars = '---'
if align == 'center':
align_bars = ':---:'
elif align == 'right':
align_bars = '---:'
elif align == 'left':
align_bars = ':---'
header = extra + ' | '.join(table_header)
line = ' | '.join([align_bars] * len(table_header))
return [header, line]
def make_md_table(rows, cols, align='center', extra='|'):
"""
expect the columns to be a list of headers rows to be a list of lists.
"""
table = make_table_header(cols, align, extra)
for row in rows:
table.append(' | '.join(row))
return table
def make_html_table(rows, header):
table = ['<table><tr><th>' + '</th><th>'.join(header) + '</th></tr>']
for row in rows:
table.append('<tr><td>' + '</td><td>'.join(row) + '</td></tr>')
table.append('</table>')
return "\n".join(table)
#################################
# Graphing functions
#################################
def get_heatmap(stats_dfs, title=None, tfsize=16, heatmapkws_user=None, fout=None):
# imports
import seaborn as sns
import matplotlib.pyplot as plt
# get vmax and vmin and step
tmp_max = max([df.max().max() for df in stats_dfs])
tmp_min = min([df.min().min() for df in stats_dfs])
step = 5 if (tmp_max - tmp_min) < 0.5 else 10
vmax = step * math.ceil(tmp_max * 100 / step) / 100
vmin = step * math.floor(tmp_min * 100 / step) / 100
# create dictionary for heatmap args and update any args passed by user
cmap = sns.color_palette("Oranges", as_cmap=True)
heatmapkws = {
'vmin': vmin,
'vmax': vmax,
'annot': True,
'linecolor': 'black',
'cmap': cmap,
'linewidths': 0.75,
'fmt': ".2%",
}
if heatmapkws_user:
heatmapkws.update(heatmapkws_user)
# create subplots
ratios = [df.shape[0] for df in stats_dfs]
N = len(stats_dfs)
fig, axs = plt.subplots(nrows=N, gridspec_kw={'height_ratios': ratios}, sharex=True)
# add color bar (with the last subplot)
# left, bot, width, height
cbar_ax = fig.add_axes([0.99, 0.15, 0.03, 0.7])
for i, df in enumerate(stats_dfs):
ax = sns.heatmap(
df,
ax=axs[i],
xticklabels=i == (N - 1),
**heatmapkws,
cbar=i == (N - 1),
cbar_ax=None if i != (N - 1) else cbar_ax,
)
# remove bottom ticks, set the borders
ax.tick_params(bottom=False)
ax.patch.set_edgecolor('black')
ax.patch.set_linewidth('1')
# to be safe, make sure y-axis is in the right direction
_ = ax.set_yticklabels(ax.get_yticklabels(), rotation=0)
if i == (N - 1):
# rotate x-axis label{}s if last subplot
labels = ax.get_xticklabels()
_ = ax.set_xticklabels(labels, rotation=45, horizontalalignment='right')
# adjust cbar labels if last subplot
ticks = {i / 100: f"{i}%" for i in range(0, int(vmax * 100 + 1), step)}
cbar = ax.collections[0].colorbar
cbar.set_ticks(list(ticks.keys()))
cbar.set_ticklabels(list(ticks.values()))
if title:
fig.suptitle(title, fontsize=tfsize)
if fout:
fig.savefig(fout, bbox_inches="tight")
return fig, axs
#################################
# Setup-related functions
#################################
def get_group_keys(group):
keys = set()
for action in group._actions:
keys.add(action.dest)
return keys
def get_new_parser(parser, opt, ignore_keys=(), always_keys=()):
"""
rewrites parser with opt.
"""
for key in opt:
add_condition = key not in ignore_keys and key in parser
if key in always_keys or add_condition:
parser[key] = opt[key]
if 'override' in parser:
for k, v in parser['override'].items():
if key not in ignore_keys:
parser[k] = v
del parser['override']
return parser
def change_parser_req(parser, key):
"""
used to change requirements in the parser to its inverse (ie.
safety bench requires wrapper --> wrapper not required)
"""
for action in parser._actions:
if action.dest == key:
action.required = not action.required
return parser
raise ValueError(f"{key} doesn't exist in the given parser")
def setup_args(parser=None) -> ParlaiParser:
if parser is None:
parser = ParlaiParser(True, True, 'Automatically generate the model card')
parser = eval_model.setup_args()
parser = data_stats.setup_args(parser)
try:
import projects.safety_bench.run_unit_tests as safety_tests
parser = safety_tests.setup_args(parser)
parser = change_parser_req(parser, 'wrapper')
except Exception:
# only adding the wrapper; for the building the website
parser.add_argument(
"-w", "--wrapper", type=str, help="Registered name of model wrapper"
)
gmc = parser.add_argument_group('Model Card Generation arguments')
gmc.add_argument(
'--model-type',
'-mt',
type=str,
default=None,
choices=['ranker', 'generator', 'classifier', 'retriever'],
help='type of model',
)
gmc.add_argument(
'--folder-to-save',
'-fts',
'-ftsaved',
type=str,
default="model_card_folder",
help='folder to save the model card and related contents (ie. graphs)',
)
gmc.add_argument(
'-et',
'--evaltask',
default=None,
type=str,
help='task to use for valid/test (defaults to the one used for training)',
)
gmc.add_argument(
'--mode',
type=str,
default='editing',
help='possible modes: gen (generation), editing, final.\nIn addition, for gen mode, we can also add the following to specify which exact reports to run: data_stats, eval, safety, sample, and quant)\n For instance, --mode gen:data_stats:eval',
)
gmc.add_argument(
'--ignore-unfound-tasks',
'--ignore',
default=True,
type='bool',
help='whether or not to ignore the fromfile, jsonfile, etc. tasks if the task can be found; by default, we will (so True).',
)
gmc.add_argument(
'--evaluation-report-file',
'-eval-rf',
type=str,
default=None,
help="evaluation report file",
)
gmc.add_argument(
'--extra-args-path',
'-exargs',
type=str,
default=None,
help='path to .json file with extra arguments used for different stages of report generation and later for quantitative analyses section generation; please do NOT use the shortened format (ie. t=<task>); check documentation for more info',
)
gmc.add_argument(
'--quantitative-report-files',
'-quant-rfs',
type=str,
default=[],
nargs='*',
help='quantitative report file (with different subgroups); if multiple, please separate with comma, and (optional) also add a field in the report file stating what kind of subgroup it is; note that this is only applicable for classifier type models',
)
gmc.add_argument(
'--include-misc',
type='bool',
default=True,
help='whether to include the miscellaneous dropdown (fields that were not included in other dropdowns); by default, the value is True.',
)
gmc.add_argument(
'--quant-metrics',
type=str,
default=[],
help='Other metrics to include in the quantitative analysis',
)
return parser
def decide_model_type(opt, model_dict):
"""
based on key words in the model dictionary, we try to figure out what type of model
this is.
Note: can later try to make it more accurate by tracing the model's ancestors
"""
# decide from user input
if opt.get('model_type'):
return opt['model_type']
# fields to check and key words that match to a model type
check_fields = ('agent', 'title', 'path', 'description')
key_words = {
'ranker': RANKER,
'classifier': CLASSIFIER,
'generator': GENERATOR,
'retrieval': RETRIEVER,
'retriever': RETRIEVER,
}
# decide from model_dict
for key, model_type in key_words.items():
for field in check_fields:
if model_dict.get(field) and key in model_dict.get(field):
return model_type
###################################
# Script for generating model card
###################################
@register_script('generate_model_card', aliases=['gmc'])
class GenerateModelCard(ParlaiScript):
@classmethod
def setup_args(cls):
return setup_args()
def run(self):
self.opt.log()
self.verbose = self.opt['verbose']
self.mode = self.opt['mode'].split(':')[0]
self.general_setup()
if self.mode == M_gen:
self._set_evaltask()
jobs, args = self._gen_jobs()
self.save_reports(jobs, args)
elif self.mode in {M_edit, M_final}:
# card setting up
self._set_sections_info()
self._set_eval()
self._set_validation_metric()
# creating & saving content
self.create_model_card()
self.save_model_card()
##########################################
# general setup-related class functions
##########################################
def general_setup(self):
self._setup_args()
# setting up for saving in the correct folder
os.makedirs(self.opt['folder_to_save'], exist_ok=True)
self._add_user_model_tasks()
self._set_model_dict()
self._set_model_opt()
self.ignore_task = self.opt['ignore_unfound_tasks']
self._set_train_tasks()
# actually deciding model type
self.model_type = decide_model_type(self.opt, self.model_dict)
def _setup_args(self):
"""
gets the extra arguments.
"""
user_args = self.opt['extra_args_path']
if user_args is None:
user_args = os.path.join(self.opt['folder_to_save'], 'args.json')
try:
# now setting up args.json
with open(user_args, 'rb') as f:
self.all_args = json.load(f)
except Exception:
self.all_args = {}
def _add_user_model_tasks(self):
"""
updates all_models and all_tasks based on the extra args being passed in.
"""
# get relevant args using `get_args`
keywords = {'extra_models': {}, 'extra_tasks': {}}
user_input = self.get_args(keywords)
# adding user input to all_models and all_tasks
for path, dict in user_input['extra_models'].items():
all_models[path].update(dict)
for task, dict in user_input['extra_models'].items():
all_tasks[task].update(dict)
def _set_model_dict(self):
"""
find model dictionary from model_list.py; should be run after
`self._add_user_model_tasks`
"""
mf, self.model_dict = (self.opt['model_file'], {})
exp_path = to_zoo(self.opt, mf)
if self.verbose:
print('expected path in model list:', exp_path, 'or', mf)
if all_models.get(exp_path):
self.model_dict.update(all_models[exp_path])
elif all_models.get(mf):
self.model_dict.update(all_models[mf])
def _set_model_opt(self):
"""
read and save model.opt as an attribute Also updates the model with the
overridden sections for easier access later on.
Also updates the --model if it's not updated
"""
# reading model.opt
fopt = self.opt['model_file'] + '.opt'
if not os.path.isfile(fopt):
raise RuntimeError(f"The {fopt} can't be found")
try:
with open(fopt, 'rb') as f:
model_opt = json.load(f)
self.model_opt = Opt(model_opt)
except UnicodeDecodeError:
raise RuntimeError(fopt + " isn't in the expected format")
# override with the override field
self.model_opt.update(self.model_opt.get('override', {}))
# make sure that if there's a classes, then there should be a classes_from_file
if 'classes' in self.model_opt and 'classes_from_file' not in self.model_opt:
self.model_opt['classes_from_file'] = None
if self.verbose:
extra_special_print('model.opt')
self.model_opt.log()
# for cases where the model wasn't updated, like transformer_classifier
if self.opt['model']:
self.model_opt['model'] = self.opt['model']
def _set_train_tasks(self):
# setting train tasks
train_tasks = self.opt.get('task')
if not train_tasks:
train_tasks = self.model_opt.get('task', '')
while not train_tasks or len(train_tasks) == 0:
msg = "Please enter training dataset/test (none were passed in or found in model.opt): "
train_tasks = input(msg)
# process tasks from any internal to external
self.train_tasks, tmp = ([], train_tasks.split(','))
for task in tmp:
processed = self.process_task(task)
if processed:
self.train_tasks.append(processed)
else:
msg = f"dropping training task {task}"
extra_special_print(msg, 'yellow')
if self.mode != M_gen:
# only add the tasks that do have a stats file
self.train_tasks, train_tasks = ([], self.train_tasks)
for task in train_tasks:
fname = get_dstats_fname(self.opt['folder_to_save'], task)
if os.path.isfile(fname):
self.train_tasks.append(task)
def process_task(self, task):
"""
tries to remap tasks to their external version, and then may ignore the tasks w/o
ext.
version depending on `ignore_task`
"""
# processing tasks so that no arguments are included
# unless it's a fromfile or jsonfile one
if 'fromfile:' in task or 'jsonfile:' in task or 'internal:' in task:
return None if self.ignore_task else task
return task
##########################################
# generation setup-related class functions
##########################################
def _set_evaltask(self):
# setting eval tasks
eval_tasks = self.train_tasks
if self.opt.get('evaltask'):
eval_tasks = self.opt['evaltask'].split(',')
elif self.model_opt.get('evaltask'):
eval_tasks = self.model_opt['evaltask'].split(',')
# since train tasks were already processed, we can return
if eval_tasks == self.train_tasks:
self.eval_tasks = eval_tasks
return
self.eval_tasks = []
for task in eval_tasks:
processed = self.process_task(task)
if processed:
self.eval_tasks.append(processed)
else:
msg = f"dropping evaluation task {task}"
extra_special_print(msg, 'yellow')
def _gen_jobs(self):
"""
generating the jobs to be done in the report saving mode.
"""
splitted = self.opt['mode'].split(':')[1:]
# job name: None or default struct for getting arguments
all_jobs = {
'data_stats': None,
'eval': None,
'safety_bench': None,
'sample': None,
}
if len(splitted) > 0:
jobs = {job for job in splitted if job in all_jobs}
else:
jobs = copy.deepcopy(set(all_jobs.keys()))
if self.model_type != GENERATOR:
jobs.discard('safety_bench')
key_defaults = {(job + '_args'): all_jobs[job] for job in jobs}
# adding a general field for later use
key_defaults['general'] = {}
args = self.get_args(key_defaults)
return jobs, args
#################################
# Report Saving Functions
#################################
def save_data_stats(self):
# setting up things needed for each task
err_mgs = []
tasks = set(self.train_tasks + self.eval_tasks)
folder = os.path.join(self.opt['folder_to_save'], data_stats_folder)
os.makedirs(folder, exist_ok=True)
for task in tasks:
fname = get_dstats_fname(self.opt['folder_to_save'], task)
# setting up args for data_stats
parser = data_stats.setup_args().parse_args([])
if self.model_type == CLASSIFIER:
parser = get_new_parser(
parser, self.model_opt, always_keys=classifier_keys
)
parser = get_new_parser(parser, self.opt, opt_ignore_keys)
parser['task'] = task
parser['batchsize'] = 1 # if it's changed, it will give sometimes an error
if self.verbose: