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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
| namespace torch::jit {
// Script编译器核心实现(基于编译器前端分析)
class ScriptCompiler {
private:
// 编译上下文
struct CompilationContext {
std::shared_ptr<CompilationUnit> compilation_unit;
std::unordered_map<std::string, TypePtr> type_table;
std::vector<std::string> error_messages;
// 作用域管理
std::vector<std::unordered_map<std::string, Value*>> symbol_table_stack;
CompilationContext(std::shared_ptr<CompilationUnit> cu)
: compilation_unit(cu) {
push_scope();
}
void push_scope() {
symbol_table_stack.emplace_back();
}
void pop_scope() {
symbol_table_stack.pop_back();
}
// 符号查找
Value* lookup_symbol(const std::string& name) {
for (auto it = symbol_table_stack.rbegin(); it != symbol_table_stack.rend(); ++it) {
auto found = it->find(name);
if (found != it->end()) {
return found->second;
}
}
return nullptr;
}
// 符号绑定
void bind_symbol(const std::string& name, Value* value) {
symbol_table_stack.back()[name] = value;
}
};
public:
// 编译Python函数为TorchScript
std::shared_ptr<ScriptFunction> compile_function(
py::function py_func,
const std::string& name) {
// 1. 解析Python源码
auto source_code = extract_source_code(py_func);
auto ast = parse_python_source(source_code);
// 2. 创建编译上下文
auto compilation_unit = std::make_shared<CompilationUnit>();
CompilationContext ctx(compilation_unit);
// 3. 类型推导
auto function_schema = infer_function_schema(py_func, ast);
// 4. 编译为图
auto graph = std::make_shared<Graph>();
compile_ast_to_graph(ast, graph, ctx);
// 5. 创建ScriptFunction
auto script_func = std::make_shared<ScriptFunction>(
name, graph, function_schema
);
compilation_unit->register_function(script_func);
return script_func;
}
// 编译Python类为ScriptModule
std::shared_ptr<ScriptModule> compile_class(
py::class_ py_class) {
// 1. 提取类定义
auto class_def = extract_class_definition(py_class);
// 2. 分析类成员
auto [methods, attributes] = analyze_class_members(py_class);
// 3. 编译类型定义
auto class_type = compile_class_type(class_def, attributes);
// 4. 编译方法
std::vector<std::shared_ptr<ScriptFunction>> compiled_methods;
for (const auto& [method_name, method_func] : methods) {
auto compiled_method = compile_function(method_func, method_name);
compiled_methods.push_back(compiled_method);
}
// 5. 创建ScriptModule
auto script_module = std::make_shared<ScriptModule>(class_type);
// 绑定编译后的方法
for (auto& method : compiled_methods) {
script_module->_ivalue()->compilation_unit()->register_function(method);
}
return script_module;
}
private:
// Python AST到Graph的编译
void compile_ast_to_graph(const py::object& ast,
std::shared_ptr<Graph> graph,
CompilationContext& ctx) {
// 创建图的输入节点
auto input_values = create_input_values(graph, ast);
// 编译函数体
auto output_values = compile_statements(ast.attr("body"), graph, ctx);
// 创建图的输出节点
graph->registerOutputs(output_values);
}
// 编译语句列表
std::vector<Value*> compile_statements(const py::list& statements,
std::shared_ptr<Graph> graph,
CompilationContext& ctx) {
std::vector<Value*> results;
for (const auto& stmt : statements) {
auto stmt_results = compile_statement(stmt, graph, ctx);
results.insert(results.end(), stmt_results.begin(), stmt_results.end());
}
return results;
}
// 编译单个语句
std::vector<Value*> compile_statement(const py::object& stmt,
std::shared_ptr<Graph> graph,
CompilationContext& ctx) {
auto stmt_type = py::str(stmt.attr("__class__").attr("__name__"));
if (stmt_type.cast<std::string>() == "Assign") {
return compile_assign_statement(stmt, graph, ctx);
} else if (stmt_type.cast<std::string>() == "Return") {
return compile_return_statement(stmt, graph, ctx);
} else if (stmt_type.cast<std::string>() == "If") {
return compile_if_statement(stmt, graph, ctx);
} else if (stmt_type.cast<std::string>() == "For") {
return compile_for_statement(stmt, graph, ctx);
} else if (stmt_type.cast<std::string>() == "While") {
return compile_while_statement(stmt, graph, ctx);
}
throw std::runtime_error("Unsupported statement type: " + stmt_type.cast<std::string>());
}
// 编译赋值语句
std::vector<Value*> compile_assign_statement(const py::object& stmt,
std::shared_ptr<Graph> graph,
CompilationContext& ctx) {
// 获取赋值目标和值
auto targets = stmt.attr("targets");
auto value_expr = stmt.attr("value");
// 编译右侧表达式
auto value = compile_expression(value_expr, graph, ctx);
// 处理左侧目标
for (const auto& target : targets) {
auto target_name = extract_target_name(target);
ctx.bind_symbol(target_name, value);
}
return {value};
}
// 编译表达式
Value* compile_expression(const py::object& expr,
std::shared_ptr<Graph> graph,
CompilationContext& ctx) {
auto expr_type = py::str(expr.attr("__class__").attr("__name__"));
auto expr_type_str = expr_type.cast<std::string>();
if (expr_type_str == "Name") {
// 变量引用
auto name = expr.attr("id").cast<std::string>();
auto value = ctx.lookup_symbol(name);
if (!value) {
throw std::runtime_error("Undefined variable: " + name);
}
return value;
} else if (expr_type_str == "Call") {
// 函数调用
return compile_function_call(expr, graph, ctx);
} else if (expr_type_str == "BinOp") {
// 二元操作
return compile_binary_op(expr, graph, ctx);
} else if (expr_type_str == "Constant") {
// 常量
return compile_constant(expr, graph, ctx);
} else if (expr_type_str == "Attribute") {
// 属性访问
return compile_attribute_access(expr, graph, ctx);
}
throw std::runtime_error("Unsupported expression type: " + expr_type_str);
}
// 编译函数调用
Value* compile_function_call(const py::object& call_expr,
std::shared_ptr<Graph> graph,
CompilationContext& ctx) {
// 获取函数和参数
auto func_expr = call_expr.attr("func");
auto args = call_expr.attr("args");
auto kwargs = call_expr.attr("keywords");
// 编译参数
std::vector<Value*> arg_values;
for (const auto& arg : args) {
arg_values.push_back(compile_expression(arg, graph, ctx));
}
// 处理关键字参数
std::vector<std::pair<std::string, Value*>> kwarg_values;
for (const auto& kwarg : kwargs) {
auto key = kwarg.attr("arg").cast<std::string>();
auto value = compile_expression(kwarg.attr("value"), graph, ctx);
kwarg_values.emplace_back(key, value);
}
// 确定函数类型
if (is_torch_function(func_expr)) {
// torch函数调用
return compile_torch_function_call(func_expr, arg_values, kwarg_values, graph, ctx);
} else if (is_method_call(func_expr)) {
// 方法调用
return compile_method_call(func_expr, arg_values, kwarg_values, graph, ctx);
} else {
// 用户定义函数
return compile_user_function_call(func_expr, arg_values, kwarg_values, graph, ctx);
}
}
// 编译torch函数调用
Value* compile_torch_function_call(const py::object& func_expr,
const std::vector<Value*>& args,
const std::vector<std::pair<std::string, Value*>>& kwargs,
std::shared_ptr<Graph> graph,
CompilationContext& ctx) {
// 提取函数名
auto func_name = extract_torch_function_name(func_expr);
// 查找对应的算子Schema
auto schema = find_operator_schema(func_name);
if (!schema) {
throw std::runtime_error("Unknown torch function: " + func_name);
}
// 创建图节点
auto node = graph->create(Symbol::fromQualString(func_name));
// 添加输入
for (auto* arg : args) {
node->addInput(arg);
}
// 处理关键字参数
for (const auto& [key, value] : kwargs) {
node->addInput(value);
}
// 设置输出类型
auto output_types = schema->return_types();
for (const auto& type : output_types) {
node->addOutput()->setType(type);
}
// 插入节点到图中
graph->insertNode(node);
return node->outputs()[0]; // 简化:假设单输出
}
};
// 类型推导系统(基于静态分析)
class TypeInferenceEngine {
private:
// 类型环境
struct TypeEnvironment {
std::unordered_map<std::string, TypePtr> variable_types;
std::unordered_map<std::string, c10::IValue> constant_values;
TypePtr lookup_type(const std::string& name) {
auto it = variable_types.find(name);
return (it != variable_types.end()) ? it->second : nullptr;
}
void bind_type(const std::string& name, TypePtr type) {
variable_types[name] = type;
}
void bind_constant(const std::string& name, c10::IValue value) {
constant_values[name] = value;
variable_types[name] = value.type();
}
};
public:
// 推导函数类型
FunctionSchema infer_function_type(const py::function& func) {
// 1. 分析函数签名
auto signature = inspect_function_signature(func);
// 2. 分析函数体,推导返回类型
auto source = inspect::getsource(func);
auto ast = ast::parse(source);
TypeEnvironment type_env;
// 3. 分析参数类型
std::vector<Argument> arguments;
for (const auto& param : signature.parameters) {
auto arg_type = infer_parameter_type(param);
arguments.emplace_back(param.name, arg_type);
type_env.bind_type(param.name, arg_type);
}
// 4. 分析返回类型
auto return_types = infer_return_types(ast, type_env);
std::vector<Argument> returns;
for (size_t i = 0; i < return_types.size(); ++i) {
returns.emplace_back("", return_types[i]);
}
return FunctionSchema(
signature.name,
std::move(arguments),
std::move(returns)
);
}
// 推导表达式类型
TypePtr infer_expression_type(const py::object& expr, TypeEnvironment& env) {
auto expr_type = py::str(expr.attr("__class__").attr("__name__"));
if (expr_type.cast<std::string>() == "Name") {
// 变量引用
auto name = expr.attr("id").cast<std::string>();
return env.lookup_type(name);
} else if (expr_type.cast<std::string>() == "Call") {
// 函数调用
return infer_call_type(expr, env);
} else if (expr_type.cast<std::string>() == "BinOp") {
// 二元操作
return infer_binary_op_type(expr, env);
} else if (expr_type.cast<std::string>() == "Constant") {
// 常量
return infer_constant_type(expr);
}
return nullptr;
}
private:
// 推导函数调用的返回类型
TypePtr infer_call_type(const py::object& call_expr, TypeEnvironment& env) {
auto func_expr = call_expr.attr("func");
auto args = call_expr.attr("args");
// 推导参数类型
std::vector<TypePtr> arg_types;
for (const auto& arg : args) {
arg_types.push_back(infer_expression_type(arg, env));
}
// 查找函数签名
if (is_torch_function(func_expr)) {
auto func_name = extract_torch_function_name(func_expr);
auto schema = find_operator_schema(func_name);
if (schema) {
// 使用Schema推导返回类型
return schema->return_types()[0]; // 简化:取第一个返回类型
}
}
// 回退到动态类型
return TensorType::get();
}
// 推导二元操作类型
TypePtr infer_binary_op_type(const py::object& binop_expr, TypeEnvironment& env) {
auto left = binop_expr.attr("left");
auto right = binop_expr.attr("right");
auto op = binop_expr.attr("op");
auto left_type = infer_expression_type(left, env);
auto right_type = infer_expression_type(right, env);
// 类型提升规则
return promote_types(left_type, right_type);
}
// 类型提升
TypePtr promote_types(TypePtr left, TypePtr right) {
// 张量和标量的提升
if (left->kind() == TypeKind::TensorType && right->kind() == TypeKind::NumberType) {
return left; // 张量优先
}
if (left->kind() == TypeKind::NumberType && right->kind() == TypeKind::TensorType) {
return right;
}
// 数值类型的提升
if (left->kind() == TypeKind::IntType && right->kind() == TypeKind::FloatType) {
return right; // float优先于int
}
if (left->kind() == TypeKind::FloatType && right->kind() == TypeKind::IntType) {
return left;
}
// 默认:返回左侧类型
return left;
}
};
} // namespace torch::jit
|