-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexpr_trace.py
More file actions
245 lines (185 loc) · 6.81 KB
/
expr_trace.py
File metadata and controls
245 lines (185 loc) · 6.81 KB
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
import struct
import sympy
def reinterpret_int64_as_double(int_value):
"""
Reinterprets the bits of a 64-bit integer as a double-precision float.
Args:
int_value (int): The 64-bit integer to reinterpret.
Returns:
float: The double-precision float with the same bit representation.
"""
# Pack the 64-bit integer into its 8-byte binary representation
# 'Q' represents an unsigned long long (64-bit integer)
packed_bytes = struct.pack('Q', int_value)
# Unpack the 8-byte binary representation as a double-precision float
# 'd' represents a double-precision float
reinterpreted_double = struct.unpack('d', packed_bytes)[0]
return reinterpreted_double
class Node:
def __init__(self, node_id, operation, value, inputs=[]):
self.node_id = node_id
self.operation = operation
self.value = value
self.inputs = inputs
def __repr__(self):
return f"Node({self.operation}, {self.value})"
def display(self, depth):
if depth == 0 or self.operation == 'constant':
return f'{self.value}'
args = ' '.join([inp.display(depth - 1) for inp in self.inputs])
result = f'({self.operation} {args})'
return result
# id (int) -> Node
nodes = {}
constants = {}
with open('expressions.trace') as f:
for i, line in enumerate(f):
parts = line.split()
node_id = int(parts[0][1:])
operation = parts[1]
value = reinterpret_int64_as_double(int(parts[2][1:]))
inputs = []
for inp in parts[3:]:
if inp.startswith('n'):
n = nodes[int(inp[1:])]
inputs.append(n)
elif inp.startswith('c'):
# constant double precision float encoded as the bits of a 64-bit integer
constant_value = reinterpret_int64_as_double(int(inp[1:]))
if constant_value not in constants:
n = Node(len(constants), 'constant', constant_value)
constants[constant_value] = n
inputs.append(constants[constant_value])
n = Node(node_id, operation, value, inputs)
nodes[node_id] = n
# Now we have all nodes in the `nodes` dictionary
# lets do some basic analysis
inputs = []
outputs = []
for node in nodes.values():
if node.operation.startswith("input."):
inputs.append(node)
if node.operation.startswith("output."):
outputs.append(node)
class SympyGenerator:
def __init__(self):
self.bindings = {} # node -> sympy expression
def codegen(self, node):
if node.operation == 'constant':
return node.value
# generate a sympy expression for this node
if node in self.bindings:
return self.bindings[node]
xs = []
infix = None
for inp in node.inputs:
xs.append(self.codegen(inp))
if '.' in node.operation:
return xs[0]
if node.operation == 'add':
return xs[0] + xs[1]
elif node.operation == 'sub':
return xs[0] - xs[1]
elif node.operation == 'mul':
return xs[0] * xs[1]
elif node.operation == 'div':
return xs[0] / xs[1]
elif node.operation == 'neg':
return -xs[0]
elif node.operation == 'cos':
return sympy.cos(xs[0])
elif node.operation == 'sin':
return sympy.sin(xs[0])
elif node.operation == 'exp':
return sympy.exp(xs[0])
elif node.operation == 'log':
return sympy.log(xs[0])
raise ValueError(f'Unhandled operation: {node.operation}')
# else:
# if len(arguments) != 2:
# raise ValueError(f'Expected 2 arguments for {node.operation}, got {len(arguments)}')
# print(f' double {name} = {arguments[0]} {infix} {arguments[1]};')
def generate(self, nodes, inputs, outputs):
print(len(inputs), len(outputs))
for inp in inputs:
# create a sympy symbol for each input in the binding table
input_id = inp.operation.split('.')[1]
sym = sympy.symbols(f'i{input_id}')
self.bindings[inp] = sym
for out in outputs:
expr = self.codegen(out.inputs[0])
expr = sympy.simplify(expr)
print(f'{out.operation} = {expr}')
# solve expr so it equals some value
# print(f"Solving for {out.operation} = 0")
# s = sympy.solve(expr)
# print(s)
pass # ...
sg = SympyGenerator()
sg.generate(nodes, inputs, outputs)
exit(0)
variables = {} # name -> Node
names = {} # Node -> name
def bind(node, name):
names[node] = name
variables[name] = node
print(f'void compute(double inputs[{len(inputs)}], double outputs[{len(outputs)}]) {{')
# codegen the input extraction
print(' // bind inputs')
for i, inp in enumerate(inputs):
name = f'input_{i}'
bind(inp, name)
print(f' double {names[inp]} = inputs[{i}];')
# going from each output, codegen the computation as a recursive function
# over the graph, not re-evaluating nodes that have already been computed (bound)
def codegen(node):
if node.operation == 'constant':
return node.value
# if the node has already been computed, return its name
if node in names:
return names[node]
name = f'node_{node.node_id}'
bind(node, name)
arguments = []
infix = None
for inp in node.inputs:
arguments.append(codegen(inp))
if node.operation.startswith('output.'):
return codegen(node.inputs[0])
if node.operation == 'add':
infix = '+'
elif node.operation == 'sub':
infix = '-'
elif node.operation == 'mul':
infix = '*'
elif node.operation == 'div':
infix = '/'
if infix is None:
function_name = node.operation;
if function_name == "neg":
function_name = "-"
arg_string = ', '.join(map(str, arguments))
print(f' double {name} = {function_name}({arg_string});')
else:
if len(arguments) != 2:
raise ValueError(f'Expected 2 arguments for {node.operation}, got {len(arguments)}')
print(f' double {name} = {arguments[0]} {infix} {arguments[1]};')
return name
# assign outputs
for i, out in enumerate(outputs):
print(f' outputs[{i}] = {codegen(out.inputs[0])};')
print('}')
exit()
print('digraph {')
print(' rankdir=LR;')
print(' node [shape=box];')
for node in nodes.values():
print(f' n{node.node_id} [label="{node.operation} = {node.value}"];')
for inp in node.inputs:
pfx = 'n'
if inp.operation == 'constant':
pfx = 'c'
print(f' {pfx}{inp.node_id} [label="{inp.value:.6f}"];')
print(f' {pfx}{inp.node_id} -> n{node.node_id};')
print('}')
# find the longest chain of nodes