-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexport.ts
More file actions
319 lines (285 loc) · 8.98 KB
/
Copy pathexport.ts
File metadata and controls
319 lines (285 loc) · 8.98 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
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
import { Tensor } from './tensor';
import { TorchFunction } from './functions/base';
import { Module } from './nn/base';
import { no_grad } from './grad_mode';
import { eventBus, events } from './util';
/**
* A graph node in the exported program, matching PyTorch's FX node format.
*/
export interface GraphNode {
/** Node type: 'placeholder' for inputs/params, 'call_function' for ops, 'output' for result */
op: 'placeholder' | 'call_function' | 'output';
/** Unique name for this node (e.g. "add", "linear_1") */
name: string;
/** Operation target (e.g. "aten.add.default") */
target: string;
/** References to input node names */
args: (string | string[])[];
/** Output tensor shape, if available */
val_shape?: number[];
}
export interface InputSpec {
kind: 'PARAMETER' | 'USER_INPUT';
name: string;
target?: string;
}
export interface OutputSpec {
kind: 'USER_OUTPUT';
name: string;
}
export interface GraphSignature {
input_specs: InputSpec[];
output_specs: OutputSpec[];
}
/**
* Maps our internal op names to PyTorch's aten operator names.
* See: https://docs.pytorch.org/docs/2.10/user_guide/torch_compiler/torch.compiler_ir.html
*/
export const _atenMap: Record<string, string> = {
'add': 'aten.add.Tensor',
'sub': 'aten.sub.Tensor',
'mul': 'aten.mul.Tensor',
'div': 'aten.div.Tensor',
'pow': 'aten.pow.Tensor_Tensor',
'powint': 'aten.pow.Tensor_Scalar',
'fmod': 'aten.fmod.Tensor',
'maximum': 'aten.maximum.default',
'minimum': 'aten.minimum.default',
'log': 'aten.log.default',
'sqrt': 'aten.sqrt.default',
'exp': 'aten.exp.default',
'square': 'aten.square.default',
'abs': 'aten.abs.default',
'sign': 'aten.sign.default',
'neg': 'aten.neg.default',
'reciprocal': 'aten.reciprocal.default',
'nan_to_num': 'aten.nan_to_num.default',
'reshape': 'aten.reshape.default',
'flatten': 'aten.flatten.using_ints',
'squeeze': 'aten.squeeze.dim',
'unsqueeze': 'aten.unsqueeze.default',
'expand': 'aten.expand.default',
'sin': 'aten.sin.default',
'cos': 'aten.cos.default',
'tan': 'aten.tan.default',
'tanh': 'aten.tanh.default',
'sum': 'aten.sum.default',
'mean': 'aten.mean.default',
'min': 'aten.min.default',
'max': 'aten.max.default',
'transpose': 'aten.transpose.int',
'matmul': 'aten.matmul.default',
'relu': 'aten.relu.default',
'sigmoid': 'aten.sigmoid.default',
'lt': 'aten.lt.Tensor',
'gt': 'aten.gt.Tensor',
'le': 'aten.le.Tensor',
'ge': 'aten.ge.Tensor',
'eq': 'aten.eq.Tensor',
'ne': 'aten.ne.Tensor',
'conv1d': 'aten.conv1d.default',
'conv2d': 'aten.conv2d.default',
'conv3d': 'aten.conv3d.default',
'linear': 'aten.linear.default',
'cross_entropy_loss': 'aten.cross_entropy_loss.default',
'nll_loss': 'aten.nll_loss_forward.default',
'cat': 'aten.cat.default',
'softmax': 'aten._softmax.default',
'clamp': 'aten.clamp.default',
'leaky_relu': 'aten.leaky_relu.default',
'max_pool2d': 'aten.max_pool2d.default',
};
/**
* Maps our internal op names to PyTorch's aten operator names with default value.
*/
function toAtenTarget(opName: string): string {
return _atenMap[opName] || `aten.${opName}.default`;
}
/**
* Manages unique node name generation with PyTorch-style deduplication.
* E.g. first "add" -> "add", second "add" -> "add_1"
*/
class NameGenerator {
private counts = new Map<string, number>();
generate(baseName: string): string {
const count = this.counts.get(baseName) || 0;
this.counts.set(baseName, count + 1);
return count === 0 ? baseName : `${baseName}_${count}`;
}
}
/**
* An exported program, matching PyTorch's ExportedProgram structure.
*/
export class ExportedProgram {
constructor(
public graph: GraphNode[],
public graph_signature: GraphSignature,
public parameters: Map<string, { data: number[], shape: number[] }>
) { }
toString(): string {
const lines: string[] = ['ExportedProgram:'];
// Format forward signature
const inputArgs = this.graph
.filter(n => n.op === 'placeholder')
.map(n => {
const shape = n.val_shape ? JSON.stringify(n.val_shape) : '?';
return `${n.name}: "${shape}"`;
})
.join(', ');
lines.push(` class GraphModule(torch.nn.Module):`);
lines.push(` def forward(self, ${inputArgs}):`);
// Operations
for (const node of this.graph) {
if (node.op === 'call_function') {
const args = node.args.join(', ');
lines.push(` ${node.name} = ${node.target}(${args})`);
} else if (node.op === 'output') {
lines.push(` return (${node.args.join(', ')},)`);
}
}
lines.push('');
lines.push('Graph signature:');
lines.push(' # inputs');
for (const spec of this.graph_signature.input_specs) {
const target = spec.target ? ` target='${spec.target}'` : '';
lines.push(` ${spec.name}: ${spec.kind}${target}`);
}
lines.push(' # outputs');
for (const spec of this.graph_signature.output_specs) {
lines.push(` ${spec.name}: ${spec.kind}`);
}
return lines.join('\n');
}
}
/**
* Export a module's forward pass as an ExportedProgram.
*
* This traces the module's forward() with the given sample inputs
* and captures the computation graph. Similar to PyTorch's torch.export.export().
*
* Named `export_` to avoid conflict with the JavaScript `export` keyword.
*
* @param module The nn.Module to export
* @param sampleInputs Sample input tensors for tracing
* @returns An ExportedProgram containing the traced graph
*/
export function export_(
module: Module,
sampleInputs: Tensor[]
): ExportedProgram {
const graph: GraphNode[] = [];
const nameGen = new NameGenerator();
// Map tensor IDs to their graph node names
const tensorIdToName = new Map<number, string>();
// 1. Create placeholder nodes for parameters
const namedParams = module.named_parameters();
const paramTensorIds = new Set<number>();
const inputSpecs: InputSpec[] = [];
for (const [paramPath, param] of namedParams) {
// Convert "linear.weight" -> "p_linear_weight" (PyTorch convention)
const placeholderName = 'p_' + paramPath.replace(/\./g, '_');
const nodeName = nameGen.generate(placeholderName);
tensorIdToName.set(param.id, nodeName);
paramTensorIds.add(param.id);
graph.push({
op: 'placeholder',
name: nodeName,
target: nodeName,
args: [],
val_shape: param.shape,
});
inputSpecs.push({
kind: 'PARAMETER',
name: nodeName,
target: paramPath,
});
}
// 2. Create placeholder nodes for user inputs
for (let i = 0; i < sampleInputs.length; i++) {
const baseName = 'input';
const nodeName = nameGen.generate(baseName);
tensorIdToName.set(sampleInputs[i].id, nodeName);
graph.push({
op: 'placeholder',
name: nodeName,
target: nodeName,
args: [],
val_shape: sampleInputs[i].shape,
});
inputSpecs.push({
kind: 'USER_INPUT',
name: nodeName,
});
}
// 3. Trace the forward pass, recording operations
const handler = (e: CustomEvent) => {
const { operation, args, result } = e.detail as {
operation: TorchFunction;
args: (Tensor | number | number[] | boolean)[];
result: Tensor;
};
const opName = operation.opName;
if (!opName) return; // Skip if no opName (shouldn't happen)
// Build arg references
const nodeArgs: (string | string[])[] = [];
for (const arg of args) {
if (arg instanceof Tensor) {
const name = tensorIdToName.get(arg.id);
if (name) {
nodeArgs.push(name);
}
// If not found, it's an intermediate constant — skip
}
// Numbers and arrays are non-tensor args; we don't include them
// in the graph node args to match PyTorch's behavior for simple cases
}
// Generate node name from opName
const nodeName = nameGen.generate(opName);
tensorIdToName.set(result.id, nodeName);
graph.push({
op: 'call_function',
name: nodeName,
target: toAtenTarget(opName),
args: nodeArgs,
val_shape: result.shape,
});
};
eventBus.addEventListener(
events.OPERATION_AFTER_FORWARD,
handler as EventListener
);
let output: Tensor;
try {
output = no_grad(() => module.forward(...sampleInputs));
} finally {
eventBus.removeEventListener(
events.OPERATION_AFTER_FORWARD,
handler as EventListener
);
}
// 4. Add output node
const outputName = tensorIdToName.get(output.id) || 'output';
graph.push({
op: 'output',
name: 'output',
target: 'output',
args: [outputName],
});
const outputSpecs: OutputSpec[] = [{
kind: 'USER_OUTPUT',
name: outputName,
}];
// 5. Collect parameters
const parameters = new Map<string, { data: number[], shape: number[] }>();
for (const [paramPath, param] of namedParams) {
parameters.set(paramPath, {
data: [...param.data],
shape: [...param.shape],
});
}
return new ExportedProgram(
graph,
{ input_specs: inputSpecs, output_specs: outputSpecs },
parameters
);
}