-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy path_patch.py
375 lines (308 loc) · 11.3 KB
/
_patch.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
import contextlib
import dataclasses
import enum
import functools
import itertools
import optparse
import os
import re
import sys
import unittest.mock
from typing import List, Set
from unittest import mock
import pip._internal.cli.cmdoptions
from pip._internal.index.collector import CollectedSources
from pip._internal.index.package_finder import CandidateEvaluator
from pip._internal.index.sources import build_source
from pip._internal.models.search_scope import SearchScope
import light_the_torch as ltt
from . import _cb as cb
from ._utils import apply_fn_patch
class Channel(enum.Enum):
STABLE = enum.auto()
TEST = enum.auto()
NIGHTLY = enum.auto()
LTS = enum.auto()
@classmethod
def from_str(cls, string):
return cls[string.upper()]
PYTORCH_DISTRIBUTIONS = {
"torch",
"torch_model_archiver",
"torch_tb_profiler",
"torcharrow",
"torchaudio",
"torchcsprng",
"torchdata",
"torchdistx",
"torchserve",
"torchtext",
"torchvision",
}
def patch(pip_main):
@functools.wraps(pip_main)
def wrapper(argv=None):
if argv is None:
argv = sys.argv[1:]
with apply_patches(argv):
return pip_main(argv)
return wrapper
# adapted from https://stackoverflow.com/a/9307174
class PassThroughOptionParser(optparse.OptionParser):
def __init__(self):
super().__init__(add_help_option=False)
def _process_args(self, largs, rargs, values):
while rargs:
try:
super()._process_args(largs, rargs, values)
except (optparse.BadOptionError, optparse.AmbiguousOptionError) as error:
largs.append(error.opt_str)
@dataclasses.dataclass
class LttOptions:
computation_backends: Set[cb.ComputationBackend] = dataclasses.field(
default_factory=lambda: {cb.CPUBackend()}
)
channel: Channel = Channel.STABLE
@staticmethod
def computation_backend_parser_options():
return [
optparse.Option(
"--pytorch-computation-backend",
help=(
"Computation backend for compiled PyTorch distributions, "
"e.g. 'cu102', 'cu115', or 'cpu'. "
"Multiple computation backends can be passed as a comma-separated "
"list, e.g 'cu102,cu113,cu116'. "
"If not specified, the computation backend is detected from the "
"available hardware, preferring CUDA over CPU."
),
),
optparse.Option(
"--cpuonly",
action="store_true",
help=(
"Shortcut for '--pytorch-computation-backend=cpu'. "
"If '--computation-backend' is used simultaneously, "
"it takes precedence over '--cpuonly'."
),
),
]
@staticmethod
def channel_parser_option() -> optparse.Option:
return optparse.Option(
"--pytorch-channel",
help=(
"Channel to download PyTorch distributions from, e.g. 'stable' , "
"'test', 'nightly' and 'lts'. "
"If not specified, defaults to 'stable' unless '--pre' is given in "
"which case it defaults to 'test'."
),
)
@staticmethod
def _parse(argv):
parser = PassThroughOptionParser()
for option in LttOptions.computation_backend_parser_options():
parser.add_option(option)
parser.add_option(LttOptions.channel_parser_option())
parser.add_option("--pre", dest="pre", action="store_true")
opts, _ = parser.parse_args(argv)
return opts
@classmethod
def from_pip_argv(cls, argv: List[str]):
if not argv or argv[0] != "install":
return cls()
opts = cls._parse(argv)
if opts.pytorch_computation_backend is not None:
cbs = {
cb.ComputationBackend.from_str(string.strip())
for string in opts.pytorch_computation_backend.split(",")
}
elif opts.cpuonly:
cbs = {cb.CPUBackend()}
elif "LTT_PYTORCH_COMPUTATION_BACKEND" in os.environ:
cbs = {
cb.ComputationBackend.from_str(string.strip())
for string in os.environ["LTT_PYTORCH_COMPUTATION_BACKEND"].split(",")
}
else:
cbs = cb.detect_compatible_computation_backends()
if opts.pytorch_channel is not None:
channel = Channel.from_str(opts.pytorch_channel)
elif opts.pre:
channel = Channel.TEST
else:
channel = Channel.STABLE
return cls(cbs, channel)
@contextlib.contextmanager
def apply_patches(argv):
options = LttOptions.from_pip_argv(argv)
patches = [
patch_cli_version(),
patch_cli_options(),
patch_link_collection(options.computation_backends, options.channel),
patch_candidate_selection(options.computation_backends),
]
with contextlib.ExitStack() as stack:
for patch in patches:
stack.enter_context(patch)
yield stack
@contextlib.contextmanager
def patch_cli_version():
with apply_fn_patch(
"pip",
"_internal",
"cli",
"main_parser",
"get_pip_version",
postprocessing=lambda input, output: f"ltt {ltt.__version__} from {ltt.__path__[0]}\n{output}",
):
yield
@contextlib.contextmanager
def patch_cli_options():
def postprocessing(input, output):
for option in LttOptions.computation_backend_parser_options():
input.cmd_opts.add_option(option)
index_group = pip._internal.cli.cmdoptions.index_group
with apply_fn_patch(
"pip",
"_internal",
"cli",
"cmdoptions",
"add_target_python_options",
postprocessing=postprocessing,
):
with unittest.mock.patch.dict(index_group):
options = index_group["options"].copy()
options.append(LttOptions.channel_parser_option)
index_group["options"] = options
yield
def get_extra_index_urls(computation_backends, channel):
if channel == Channel.STABLE:
channel_paths = [""]
elif channel == Channel.LTS:
channel_paths = [
f"lts/{major}.{minor}/"
for major, minor in [
(1, 8),
]
]
else:
channel_paths = [f"{channel.name.lower()}/"]
return [
f"https://download.pytorch.org/whl/{channel_path}{backend}"
for channel_path, backend in itertools.product(
channel_paths, sorted(computation_backends)
)
]
@contextlib.contextmanager
def patch_link_collection(computation_backends, channel):
search_scope = SearchScope(
find_links=[],
index_urls=get_extra_index_urls(computation_backends, channel),
no_index=False,
)
@contextlib.contextmanager
def context(input):
if input.project_name not in PYTORCH_DISTRIBUTIONS:
yield
return
with mock.patch.object(input.self, "search_scope", search_scope):
yield
def postprocessing(input, output):
if input.project_name not in PYTORCH_DISTRIBUTIONS:
return output
if channel != Channel.STABLE:
return output
# Some stable binaries are not hosted on the PyTorch indices. We check if this
# is the case for the current distribution.
for remote_file_source in output.index_urls:
candidates = list(remote_file_source.page_candidates())
# Cache the candidates, so `pip` doesn't has to retrieve them again later.
remote_file_source.page_candidates = lambda: iter(candidates)
# If there are any candidates on the PyTorch indices, we continue normally.
if candidates:
return output
# In case the distribution is not present on the PyTorch indices, we fall back
# to PyPI.
_, pypi_file_source = build_source(
SearchScope(
find_links=[],
index_urls=["https://pypi.org/simple"],
no_index=False,
).get_index_urls_locations(input.project_name)[0],
candidates_from_page=input.candidates_from_page,
page_validator=input.self.session.is_secure_origin,
expand_dir=False,
cache_link_parsing=False,
)
return CollectedSources(find_links=[], index_urls=[pypi_file_source])
with apply_fn_patch(
"pip",
"_internal",
"index",
"collector",
"LinkCollector",
"collect_sources",
context=context,
postprocessing=postprocessing,
):
yield
@contextlib.contextmanager
def patch_candidate_selection(computation_backends):
computation_backend_pattern = re.compile(
r"/(?P<computation_backend>(cpu|cu\d+|rocm([\d.]+)))/"
)
def extract_local_specifier(candidate):
local = candidate.version.local
if local is None:
match = computation_backend_pattern.search(candidate.link.path)
local = match["computation_backend"] if match else "any"
# Early PyTorch distributions used the "any" local specifier to indicate a
# pure Python binary. This was changed to no local specifier later.
# Setting this to "cpu" is technically not correct as it will exclude this
# binary if a non-CPU backend is requested. Still, this is probably the
# right thing to do, since the user requested a specific backend and
# although this binary will work with it, it was not compiled against it.
if local == "any":
local = "cpu"
return local
def preprocessing(input):
if not input.candidates:
return
candidates = iter(input.candidates)
candidate = next(candidates)
if candidate.name not in PYTORCH_DISTRIBUTIONS:
# At this stage all candidates have the same name. Thus, if the first is
# not a PyTorch distribution, we don't need to check the rest and can
# return without changes.
return
input.candidates = [
candidate
for candidate in itertools.chain([candidate], candidates)
if extract_local_specifier(candidate) in computation_backends
]
vanilla_sort_key = CandidateEvaluator._sort_key
def patched_sort_key(candidate_evaluator, candidate):
# At this stage all candidates have the same name. Thus, we don't need to
# mirror the exact key structure that the vanilla sort keys have.
return (
vanilla_sort_key(candidate_evaluator, candidate)
if candidate.name not in PYTORCH_DISTRIBUTIONS
else (
cb.ComputationBackend.from_str(extract_local_specifier(candidate)),
candidate.version.base_version,
)
)
with apply_fn_patch(
"pip",
"_internal",
"index",
"package_finder",
"CandidateEvaluator",
"get_applicable_candidates",
preprocessing=preprocessing,
):
with unittest.mock.patch.object(
CandidateEvaluator, "_sort_key", new=patched_sort_key
):
yield