forked from graphcore-research/unit-scaling-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dev
executable file
·173 lines (136 loc) · 4.57 KB
/
dev
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
#!/usr/bin/env python3
# Copyright (c) 2023 Graphcore Ltd. All rights reserved.
"""Dev task launcher for scmm."""
import argparse
import subprocess
import sys
from pathlib import Path
from typing import Any, Callable, Iterable, Optional, TypeVar
# Utilities
def run(command: Iterable[Any]) -> None:
"""Run a command, terminating on failure."""
cmd = [str(arg) for arg in command if arg is not None]
print("$ " + " ".join(cmd), file=sys.stderr)
exit_code = subprocess.call(cmd)
if exit_code:
sys.exit(exit_code)
T = TypeVar("T")
def cli(*args: Any, **kwargs: Any) -> Callable[[T], T]:
"""Declare a CLI command / arguments for that command."""
def wrap(func: T) -> T:
if not hasattr(func, "cli_args"):
setattr(func, "cli_args", [])
if args or kwargs:
getattr(func, "cli_args").append((args, kwargs))
return func
return wrap
# Commands
SOURCE = [Path(f) for f in ["scmm", "dev", "run_experiment.py", "run_sweep.py"]]
def _sources(core: bool, script: bool, tests: bool) -> Iterable[Path]:
"""Find all sources of the given type."""
for root in SOURCE:
if root.is_file() and script:
yield root
if root.is_dir():
for child in root.glob("**/*.py"):
is_test = "tests" in child.parts
if (is_test and tests) or (not is_test and core):
yield child
PYLINT_TEST_DISABLE = [
"missing-module-docstring",
"missing-function-docstring",
"missing-class-docstring",
"redefined-outer-name",
"unused-argument",
"blacklisted-name",
]
@cli("-c", "--check", dest="no_format", action="store_true")
def format(no_format: bool) -> None:
"""run autoformatters (e.g. black)"""
run(["isort", "--check" if no_format else None, *SOURCE])
run(["black", "--check" if no_format else None, *SOURCE])
@cli()
def types() -> None:
"""run mypy to check types"""
run(["mypy", "--strict", *_sources(core=True, script=True, tests=False)])
run(
[
"mypy",
"--cache-dir=.mypy_cache_tests",
*_sources(core=False, script=False, tests=True),
]
)
@cli()
def lint() -> None:
"""run code linting (static checks)"""
run(["flake8", *SOURCE])
run(["pylint", "-j 16", *_sources(core=True, script=True, tests=False)])
run(
[
"pylint",
"-j 16",
*_sources(core=False, script=False, tests=True),
f"--disable={','.join(PYLINT_TEST_DISABLE)}",
]
)
@cli("-k", "--only", help="only run tests matching")
@cli("-s", dest="capture", action="store_false", help="suppress capture")
def test(only: Optional[str], capture: bool) -> None:
"""run unit tests"""
run(
[
"pytest",
"scmm",
None if only else "--cov=scmm",
None if capture else "--capture=no",
f"-k {only}" if only else None,
]
)
@cli()
def check_copyright_headers() -> None:
"""check for Graphcore copyright headers on relevant files"""
command = (
"find scmm/ dev *.py -type f"
" | grep -Ev '(.pyc|.txt|.json)$'"
" | xargs grep -L 'Copyright (c) 202. Graphcore Ltd[.] All rights reserved[.]'"
)
print(f"$ {command}", file=sys.stderr)
# Note: grep exit codes are not consistent between versions, so we don't use check=True
output = (
subprocess.run(
command,
shell=True,
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
.stdout.decode()
.strip()
)
if output:
print(output, file=sys.stderr)
sys.exit(1)
@cli("--no-format", action="store_true", help="don't run the formatter")
def check(no_format: bool) -> None:
"""run all checks and optionally autoformat the code"""
test(only=None, capture=True)
format(no_format=no_format)
types()
lint()
check_copyright_headers()
# Script
def _main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.set_defaults(action=lambda: check(no_format=False))
subs = parser.add_subparsers()
for key, value in globals().items():
if hasattr(value, "cli_args"):
sub = subs.add_parser(key.replace("_", "-"), help=value.__doc__)
for args, kwargs in value.cli_args:
sub.add_argument(*args, **kwargs)
sub.set_defaults(action=value)
cli_args = vars(parser.parse_args())
action = cli_args.pop("action")
action(**cli_args)
if __name__ == "__main__":
_main()