pytorch
182 строки · 5.1 Кб
1#!/usr/bin/env python3
2import os3import sys4from importlib.util import module_from_spec, spec_from_file_location5from itertools import chain6from pathlib import Path7
8
9# Manually importing the shape function module based on current directory
10# instead of torch imports to avoid needing to recompile Pytorch before
11# running the script
12
13file_path = Path.cwd() / "torch" / "jit" / "_shape_functions.py"14module_name = "torch.jit._shape_functions"15
16err_msg = """Could not find shape functions file, please make sure17you are in the root directory of the Pytorch git repo"""
18if not file_path.exists():19raise Exception(err_msg) # noqa: TRY00220
21spec = spec_from_file_location(module_name, file_path)22assert spec is not None23module = module_from_spec(spec)24sys.modules[module_name] = module25assert spec.loader is not None26assert module is not None27spec.loader.exec_module(module)28
29bounded_compute_graph_mapping = module.bounded_compute_graph_mapping30shape_compute_graph_mapping = module.shape_compute_graph_mapping31
32
33SHAPE_HEADER = r"""34/**
35* @generated
36* This is an auto-generated file. Please do not modify it by hand.
37* To re-generate, please run:
38* cd ~/pytorch && python
39* torchgen/shape_functions/gen_jit_shape_functions.py
40*/
41#include <torch/csrc/jit/jit_log.h>
42#include <torch/csrc/jit/passes/inliner.h>
43#include <torch/csrc/jit/runtime/operator.h>
44#include <torch/csrc/jit/runtime/serialized_shape_function_registry.h>
45
46// clang-format off
47
48namespace torch {
49namespace jit {
50
51
52std::string shape_funcs = ""
53"""
54
55
56DECOMP_CENTER = r"""57
58
59const std::string& GetSerializedShapeFunctions() {
60return shape_funcs;
61}
62
63"""
64
65DECOMP_END = r"""66// clang-format on
67
68} // namespace jit
69} // namespace torch
70"""
71
72
73SERIALIZED_SHAPE_UTIL_FILE_NAME = "serialized_shape_function_registry.cpp"74
75
76def gen_serialized_decompisitions() -> str:77already_serialized_names = set()78unique_funcs = []79all_funcs = chain(80shape_compute_graph_mapping.values(), *bounded_compute_graph_mapping.values()81)82for scripted_func in all_funcs:83if scripted_func.name in already_serialized_names:84continue85already_serialized_names.add(scripted_func.name)86unique_funcs.append(scripted_func)87
88output_strs = []89curr_str = ""90for scripted_func in unique_funcs:91serialized_code = scripted_func.code92# technically its higher but give a buffer bc there are weird rules93# around some characters94# TODO: this was the limit I found by googling but it seems way95# too short ?96MAX_MSFT_STR_LEN = 200097if len(curr_str) + len(serialized_code) <= MAX_MSFT_STR_LEN:98curr_str += "\n" + serialized_code99else:100output_strs.append(curr_str)101curr_str = scripted_func.code102output_strs.append(curr_str)103
104final_output = ""105# Windows compiler doesnt correctly handle adjacent106# string literals107for output_str in output_strs:108start = '+ std::string(R"=====('109end = '\n)=====")\n'110final_output += start + output_str + end111final_output += ";"112return final_output113
114
115SHAPE_SCHEMA_START = r"""116const OperatorMap<std::string>& GetShapeFunctionMappings() {
117static const OperatorMap<std::string> shape_mappings {
118"""
119
120SHAPE_SCHEMA_END = r"""121};
122
123return shape_mappings;
124}
125"""
126
127
128def gen_shape_mappings() -> str:129shape_mappings = []130for schema, scripted_func in shape_compute_graph_mapping.items():131shape_mappings.append(' {"' + schema + '", "' + scripted_func.name + '"},')132return SHAPE_SCHEMA_START + "\n".join(shape_mappings) + SHAPE_SCHEMA_END133
134
135BOUNDED_SCHEMA_START = r"""136const OperatorMap<std::pair<std::string, std::string>>& GetBoundedShapeMappings() {
137static const OperatorMap<std::pair<std::string, std::string>> shape_mappings {
138"""
139
140
141def gen_bounded_mappings() -> str:142bounded_mappings = []143for schema, (lower_func, upper_func) in bounded_compute_graph_mapping.items():144map_str = (145' {"'146+ schema147+ '", {"'148+ lower_func.name149+ '", "'150+ upper_func.name151+ '"}},'152)153bounded_mappings.append(map_str)154return BOUNDED_SCHEMA_START + "\n".join(bounded_mappings) + SHAPE_SCHEMA_END155
156
157def write_decomposition_util_file(path: str) -> None:158decomposition_str = gen_serialized_decompisitions()159shape_mappings = gen_shape_mappings()160bounded_mappings = gen_bounded_mappings()161file_components = [162SHAPE_HEADER,163decomposition_str,164DECOMP_CENTER,165shape_mappings,166bounded_mappings,167DECOMP_END,168]169print("writing file to : ", path + "/" + SERIALIZED_SHAPE_UTIL_FILE_NAME)170with open(os.path.join(path, SERIALIZED_SHAPE_UTIL_FILE_NAME), "wb") as out_file:171final_output = "".join(file_components)172out_file.write(final_output.encode("utf-8"))173
174
175def main() -> None:176pytorch_dir = Path(__file__).resolve().parents[2]177upgrader_path = pytorch_dir / "torch" / "csrc" / "jit" / "runtime"178write_decomposition_util_file(str(upgrader_path))179
180
181if __name__ == "__main__":182main()183