Skip to content

Commit 161490d

Browse files
suofacebook-github-bot
authored andcommittedSep 16, 2020
Move torch/version.py generation to cmake (pytorch#44577)
Summary: Pull Request resolved: pytorch#44577 I would like to to move this to cmake so that I can depend on it happening from other parts of the build. This PR pulls out the logic for determining the version string and writing the version file into its own module. `setup.py` still receives the version string and uses it as before, but now the code for writing out `torch/version.py` lives in a custom command in torch/CMakeLists.txt I noticed a small inconsistency in how version info is populated. `TORCH_BUILD_VERSION` is populated from `setup.py` at configuration time, while `torch/version.py` is written at build time. So if, e.g. you configured cmake on a certain git rev, then built it in on another, the two versions would be inconsistent. This does not appear to matter, so I opted to preserve the existing behavior. Test Plan: Imported from OSS Reviewed By: bertmaher Differential Revision: D23734781 Pulled By: suo fbshipit-source-id: 4002c9ec8058503dc0550f8eece2256bc98c03a4
1 parent ffe127e commit 161490d

File tree

3 files changed

+77
-29
lines changed

3 files changed

+77
-29
lines changed
 

‎setup.py

+2-29
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,6 @@
192192
import distutils.command.clean
193193
import distutils.sysconfig
194194
import filecmp
195-
import subprocess
196195
import shutil
197196
import os
198197
import json
@@ -203,6 +202,7 @@
203202
from tools.setup_helpers.env import (IS_WINDOWS, IS_DARWIN, IS_LINUX,
204203
check_env_flag, build_type)
205204
from tools.setup_helpers.cmake import CMake
205+
from tools.generate_torch_version import get_torch_version
206206

207207
################################################################################
208208
# Parameters parsed from environment
@@ -276,22 +276,7 @@ def report(*args):
276276
# Version, create_version_file, and package_name
277277
################################################################################
278278
package_name = os.getenv('TORCH_PACKAGE_NAME', 'torch')
279-
version = open('version.txt', 'r').read().strip()
280-
sha = 'Unknown'
281-
282-
try:
283-
sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=cwd).decode('ascii').strip()
284-
except Exception:
285-
pass
286-
287-
if os.getenv('PYTORCH_BUILD_VERSION'):
288-
assert os.getenv('PYTORCH_BUILD_NUMBER') is not None
289-
build_number = int(os.getenv('PYTORCH_BUILD_NUMBER'))
290-
version = os.getenv('PYTORCH_BUILD_VERSION')
291-
if build_number > 1:
292-
version += '.post' + str(build_number)
293-
elif sha != 'Unknown':
294-
version += '+' + sha[:7]
279+
version = get_torch_version()
295280
report("Building wheel {}-{}".format(package_name, version))
296281

297282
cmake = CMake()
@@ -330,18 +315,6 @@ def check_file(f):
330315
cmake_only=CMAKE_ONLY,
331316
cmake=cmake)
332317

333-
version_path = os.path.join(cwd, 'torch', 'version.py')
334-
with open(version_path, 'w') as f:
335-
f.write("__version__ = '{}'\n".format(version))
336-
# NB: This is not 100% accurate, because you could have built the
337-
# library code with DEBUG, but csrc without DEBUG (in which case
338-
# this would claim to be a release build when it's not.)
339-
f.write("debug = {}\n".format(repr(build_type.is_debug())))
340-
cmake_cache_vars = defaultdict(lambda: None, cmake.get_cmake_cache_variables())
341-
f.write("cuda = {}\n".format(repr(cmake_cache_vars['CUDA_VERSION'])))
342-
f.write("git_version = {}\n".format(repr(sha)))
343-
f.write("hip = {}\n".format(repr(cmake_cache_vars['HIP_VERSION'])))
344-
345318
if CMAKE_ONLY:
346319
report('Finished running cmake. Run "ccmake build" or '
347320
'"cmake-gui build" to adjust build options and '

‎tools/generate_torch_version.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import argparse
2+
import os
3+
import subprocess
4+
from pathlib import Path
5+
6+
def get_sha():
7+
try:
8+
return subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=pytorch_root).decode('ascii').strip()
9+
except Exception:
10+
return 'Unknown'
11+
12+
def get_torch_version(sha=None):
13+
pytorch_root = Path(__file__).parent.parent
14+
version = open('version.txt', 'r').read().strip()
15+
if sha is None:
16+
sha = get_sha()
17+
18+
if os.getenv('PYTORCH_BUILD_VERSION'):
19+
assert os.getenv('PYTORCH_BUILD_NUMBER') is not None
20+
build_number = int(os.getenv('PYTORCH_BUILD_NUMBER'))
21+
version = os.getenv('PYTORCH_BUILD_VERSION')
22+
if build_number > 1:
23+
version += '.post' + str(build_number)
24+
elif sha != 'Unknown':
25+
version += '+' + sha[:7]
26+
return version
27+
28+
if __name__ == "__main__":
29+
parser = argparse.ArgumentParser(description="Generate torch/version.py from build and environment metadata.")
30+
parser.add_argument("--is_debug", type=bool, help="Whether this build is debug mode or not.")
31+
parser.add_argument("--cuda_version", type=str)
32+
parser.add_argument("--hip_version", type=str)
33+
34+
args = parser.parse_args()
35+
36+
assert args.is_debug is not None
37+
args.cuda_version = None if args.cuda_version == '' else args.cuda_version
38+
args.hip_version = None if args.hip_version == '' else args.hip_version
39+
40+
pytorch_root = Path(__file__).parent.parent
41+
version_path = pytorch_root / "torch" / "version.py"
42+
sha = get_sha()
43+
version = get_torch_version(sha)
44+
45+
with open(version_path, 'w') as f:
46+
f.write("__version__ = '{}'\n".format(version))
47+
# NB: This is not 100% accurate, because you could have built the
48+
# library code with DEBUG, but csrc without DEBUG (in which case
49+
# this would claim to be a release build when it's not.)
50+
f.write("debug = {}\n".format(repr(args.is_debug)))
51+
f.write("cuda = {}\n".format(repr(args.cuda_version)))
52+
f.write("git_version = {}\n".format(repr(sha)))
53+
f.write("hip = {}\n".format(repr(args.hip_version)))

‎torch/CMakeLists.txt

+22
Original file line numberDiff line numberDiff line change
@@ -284,3 +284,25 @@ if(NOT TORCH_PYTHON_LINK_FLAGS STREQUAL "")
284284
endif()
285285

286286
install(TARGETS torch_python DESTINATION "${TORCH_INSTALL_LIB_DIR}")
287+
288+
# Generate torch/version.py from the appropriate CMake cache variables.
289+
if(${CMAKE_BUILD_TYPE} STREQUAL "Debug")
290+
set(TORCH_VERSION_DEBUG 1)
291+
else()
292+
set(TORCH_VERSION_DEBUG 0)
293+
endif()
294+
295+
add_custom_command(
296+
OUTPUT ${TORCH_SRC_DIR}/version.py
297+
COMMAND
298+
"${PYTHON_EXECUTABLE}" ${TOOLS_PATH}/generate_torch_version.py
299+
--is_debug=${TORCH_VERSION_DEBUG}
300+
--cuda_version=${CUDA_VERSION}
301+
--hip_version=${HIP_VERSION}
302+
WORKING_DIRECTORY ${TORCH_ROOT}
303+
)
304+
add_custom_target(
305+
gen_torch_version ALL
306+
DEPENDS ${TORCH_SRC_DIR}/version.py
307+
)
308+
add_dependencies(torch_python gen_torch_version)

0 commit comments

Comments
 (0)
Please sign in to comment.