"docs/vscode:/vscode.git/clone" did not exist on "45c7d05ad3a0ac938762be938a58b3bd60388006"
run.py 11.2 KB
Newer Older
Antoine Kaufmann's avatar
Antoine Kaufmann committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Copyright 2021 Max Planck Institute for Software Systems, and
# National University of Singapore
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
23
"""This is the top-level module of the SimBricks orchestration framework that
users interact with."""
Antoine Kaufmann's avatar
Antoine Kaufmann committed
24

25
import argparse
26
import asyncio
Jonas Kaufmann's avatar
Jonas Kaufmann committed
27
import fnmatch
28
import importlib
Hejing Li's avatar
Hejing Li committed
29
import importlib.util
30
import json
Jonas Kaufmann's avatar
Jonas Kaufmann committed
31
import os
32
import pickle
33
import signal
Jonas Kaufmann's avatar
Jonas Kaufmann committed
34
import sys
35
36
import typing as tp

37
from simbricks.orchestration import exectools
38
39
40
from simbricks.orchestration import experiments as exps
from simbricks.orchestration import runtime
from simbricks.orchestration.experiment import experiment_environment
Jonas Kaufmann's avatar
Jonas Kaufmann committed
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
def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    # general arguments for experiments
    parser.add_argument(
        'experiments',
        metavar='EXP',
        type=str,
        nargs='+',
        help='Python modules to load the experiments from'
    )
    parser.add_argument(
        '--list',
        action='store_const',
        const=True,
        default=False,
        help='List available experiment names'
    )
    parser.add_argument(
        '--filter',
        metavar='PATTERN',
        type=str,
        nargs='+',
        help='Only run experiments matching the given Unix shell style patterns'
    )
    parser.add_argument(
        '--pickled',
        action='store_const',
        const=True,
        default=False,
        help='Interpret experiment modules as pickled runs instead of .py files'
    )
    parser.add_argument(
        '--runs',
        metavar='N',
        type=int,
        default=1,
        help='Number of repetition of each experiment'
    )
    parser.add_argument(
        '--firstrun', metavar='N', type=int, default=1, help='ID for first run'
    )
    parser.add_argument(
        '--force',
        action='store_const',
        const=True,
        default=False,
        help='Run experiments even if output already exists (overwrites output)'
    )
    parser.add_argument(
        '--verbose',
        action='store_const',
        const=True,
        default=False,
        help='Verbose output, for example, print component simulators\' output'
    )
    parser.add_argument(
        '--pcap',
        action='store_const',
        const=True,
        default=False,
        help='Dump pcap file (if supported by component simulator)'
    )
105

106
107
108
109
110
111
    # arguments for the experiment environment
    g_env = parser.add_argument_group('Environment')
    g_env.add_argument(
        '--repo',
        metavar='DIR',
        type=str,
112
        default=os.path.dirname(__file__) + '/..',
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
        help='SimBricks repository directory'
    )
    g_env.add_argument(
        '--workdir',
        metavar='DIR',
        type=str,
        default='./out/',
        help='Work directory base'
    )
    g_env.add_argument(
        '--outdir',
        metavar='DIR',
        type=str,
        default='./out/',
        help='Output directory base'
    )
    g_env.add_argument(
        '--cpdir',
        metavar='DIR',
        type=str,
        default='./out/',
        help='Checkpoint directory base'
    )
    g_env.add_argument(
        '--hosts',
        metavar='JSON_FILE',
        type=str,
        default=None,
        help='List of hosts to use (json)'
    )
    g_env.add_argument(
        '--shmdir',
        metavar='DIR',
        type=str,
        default=None,
        help='Shared memory directory base (workdir if not set)'
    )
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
    # arguments for the parallel runtime
    g_par = parser.add_argument_group('Parallel Runtime')
    g_par.add_argument(
        '--parallel',
        dest='runtime',
        action='store_const',
        const='parallel',
        default='sequential',
        help='Use parallel instead of sequential runtime'
    )
    g_par.add_argument(
        '--cores',
        metavar='N',
        type=int,
        default=len(os.sched_getaffinity(0)),
        help='Number of cores to use for parallel runs'
    )
    g_par.add_argument(
        '--mem',
        metavar='N',
        type=int,
        default=None,
        help='Memory limit for parallel runs (in MB)'
    )
175

176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    # arguments for the slurm runtime
    g_slurm = parser.add_argument_group('Slurm Runtime')
    g_slurm.add_argument(
        '--slurm',
        dest='runtime',
        action='store_const',
        const='slurm',
        default='sequential',
        help='Use slurm instead of sequential runtime'
    )
    g_slurm.add_argument(
        '--slurmdir',
        metavar='DIR',
        type=str,
        default='./slurm/',
        help='Slurm communication directory'
    )
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
    # arguments for the distributed runtime
    g_dist = parser.add_argument_group('Distributed Runtime')
    g_dist.add_argument(
        '--dist',
        dest='runtime',
        action='store_const',
        const='dist',
        default='sequential',
        help='Use sequential distributed runtime instead of local'
    )
    g_dist.add_argument(
        '--auto-dist',
        action='store_const',
        const=True,
        default=False,
        help='Automatically distribute non-distributed experiments'
    )
    g_dist.add_argument(
        '--proxy-type',
        metavar='TYPE',
        type=str,
        default='sockets',
        help='Proxy type to use (sockets,rdma) for auto distribution'
    )
218

219
    return parser.parse_args()
220

221
222

def load_executors(path: str) -> tp.List[exectools.Executor]:
Jonas Kaufmann's avatar
Jonas Kaufmann committed
223
    """Load hosts list from json file and return list of executors."""
224
    with open(path, 'r', encoding='utf-8') as f:
225
226
227
228
229
        hosts = json.load(f)

        exs = []
        for h in hosts:
            if h['type'] == 'local':
230
                ex = exectools.LocalExecutor()
231
            elif h['type'] == 'remote':
232
                ex = exectools.RemoteExecutor(h['host'], h['workdir'])
233
234
235
236
                if 'ssh_args' in h:
                    ex.ssh_extra_args += h['ssh_args']
                if 'scp_args' in h:
                    ex.scp_extra_args += h['scp_args']
237
238
            else:
                raise RuntimeError('invalid host type "' + h['type'] + '"')
239
240
            ex.ip = h['ip']
            exs.append(ex)
241
242
    return exs

Jonas Kaufmann's avatar
Jonas Kaufmann committed
243

244
def warn_multi_exec(executors: tp.List[exectools.Executor]):
245
    if len(executors) > 1:
Jonas Kaufmann's avatar
Jonas Kaufmann committed
246
247
248
249
250
        print(
            'Warning: multiple hosts specified, only using first one for now',
            file=sys.stderr
        )

251

252
def add_exp(
253
254
    e: exps.Experiment,
    rt: runtime.Runtime,
Jonas Kaufmann's avatar
Jonas Kaufmann committed
255
    run: int,
256
    prereq: tp.Optional[runtime.Run],
Jonas Kaufmann's avatar
Jonas Kaufmann committed
257
258
    create_cp: bool,
    restore_cp: bool,
259
260
    no_simbricks: bool,
    args: argparse.Namespace
261
):
262
    outpath = f'{args.outdir}/{e.name}-{run}.json'
263
    if os.path.exists(outpath) and not args.force:
264
        print(f'skip {e.name} run {run}')
265
266
        return None

267
268
    workdir = f'{args.workdir}/{e.name}/{run}'
    cpdir = f'{args.cpdir}/{e.name}/0'
269
    if args.shmdir is not None:
270
        shmdir = f'{args.shmdir}/{e.name}/{run}'
271

272
    env = experiment_environment.ExpEnv(args.repo, workdir, cpdir)
273
274
    env.create_cp = create_cp
    env.restore_cp = restore_cp
Jonas Kaufmann's avatar
Jonas Kaufmann committed
275
    env.no_simbricks = no_simbricks
276
277
    env.pcap_file = ''
    if args.pcap:
Jonas Kaufmann's avatar
Jonas Kaufmann committed
278
        env.pcap_file = workdir + '/pcap'
279
280
    if args.shmdir is not None:
        env.shm_base = os.path.abspath(shmdir)
281

282
    run = runtime.Run(e, run, env, outpath, prereq)
283
284
285
    rt.add_run(run)
    return run

Jonas Kaufmann's avatar
Jonas Kaufmann committed
286

287
288
289
290
291
292
293
294
295
296
def main():
    args = parse_args()
    if args.hosts is None:
        executors = [exectools.LocalExecutor()]
    else:
        executors = load_executors(args.hosts)

    # initialize runtime
    if args.runtime == 'parallel':
        warn_multi_exec(executors)
297
        rt = runtime.LocalParallelRuntime(
298
299
300
301
302
303
            cores=args.cores,
            mem=args.mem,
            verbose=args.verbose,
            executor=executors[0]
        )
    elif args.runtime == 'slurm':
304
        rt = runtime.SlurmRuntime(args.slurmdir, args, verbose=args.verbose)
305
    elif args.runtime == 'dist':
306
        rt = runtime.DistributedSimpleRuntime(executors, verbose=args.verbose)
307
308
    else:
        warn_multi_exec(executors)
309
310
311
        rt = runtime.LocalSimpleRuntime(
            verbose=args.verbose, executor=executors[0]
        )
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335

    # load experiments
    if not args.pickled:
        # default: load python modules with experiments
        experiments = []
        for path in args.experiments:
            modname, _ = os.path.splitext(os.path.basename(path))

            class ExperimentModuleLoadError(Exception):
                pass

            spec = importlib.util.spec_from_file_location(modname, path)
            if spec is None:
                raise ExperimentModuleLoadError('spec is None')
            mod = importlib.util.module_from_spec(spec)
            if spec.loader is None:
                raise ExperimentModuleLoadError('spec.loader is None')
            spec.loader.exec_module(mod)
            experiments += mod.experiments

        if args.list:
            for e in experiments:
                print(e.name)
            sys.exit(0)
336

337
        for e in experiments:
338
339
            if args.auto_dist and not isinstance(e, exps.DistributedExperiment):
                e = runtime.auto_dist(e, executors, args.proxy_type)
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
            # apply filter if any specified
            if (args.filter) and (len(args.filter) > 0):
                match = False
                for f in args.filter:
                    match = fnmatch.fnmatch(e.name, f)
                    if match:
                        break

                if not match:
                    continue

            # if this is an experiment with a checkpoint we might have to create
            # it
            no_simbricks = e.no_simbricks
            if e.checkpoint:
                prereq = add_exp(
                    e, rt, 0, None, True, False, no_simbricks, args
                )
            else:
                prereq = None
360

361
362
363
364
365
366
367
368
369
            for run in range(args.firstrun, args.firstrun + args.runs):
                add_exp(
                    e, rt, run, prereq, False, e.checkpoint, no_simbricks, args
                )
    else:
        # otherwise load pickled run object
        for path in args.experiments:
            with open(path, 'rb') as f:
                rt.add_run(pickle.load(f))
370

371
    # register interrupt handler
372
    signal.signal(signal.SIGINT, lambda *_: rt.interrupt())
373
374
375
376
377
378
379

    # invoke runtime to run experiments
    asyncio.run(rt.start())


if __name__ == '__main__':
    main()