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
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
/**
 * ONNX Model Inferencer (Frontend/Backend Common)
 *
 * Platform-agnostic inference logic that accepts ONNX session from platform-specific code.
 * No direct dependency on onnxruntime packages - uses dependency injection pattern.
 *
 * Adapted from Node.js test_inference.js for cross-platform use
 * Provides causal language model inference using GPT-2 ONNX model
 */

/**
 * Minimal ONNX Tensor interface (platform-agnostic)
 */
export interface OnnxTensor {
	readonly data: number[] | Float32Array | Int32Array | BigInt64Array | Uint8Array;
	readonly dims: readonly number[];
	readonly type: string;
}

/**
 * Minimal ONNX Session interface (platform-agnostic)
 */
export interface OnnxSession {
	readonly inputNames: readonly string[];
	readonly outputNames: readonly string[];
	run(feeds: Record<string, OnnxTensor>): Promise<Record<string, OnnxTensor>>;
}

/**
 * Tensor constructor interface (platform-specific)
 */
export interface TensorConstructor {
	new (
		type: string,
		data: BigInt64Array | Float32Array | Int32Array | Uint8Array,
		dims: number[]
	): OnnxTensor;
}

/**
 * Configuration for the inferencer
 */
export interface InferencerConfig {
	vocabSize: number;
	seqLen: number;
	modelPath?: string; // Optional, for reference
}

/**
 * Inference result containing generated tokens and metadata
 */
export interface InferenceResult {
	tokens: number[];
	text: string;
	logits: Float32Array;
	inferenceTime: number;
}

/**
 * Evaluation mode inputs for tree attention
 */
export interface EvaluationInputs {
	prefixIds: number[]; // Prefix sequence (causal context)
	evaluatedIds: number[]; // Tokens to evaluate in tree
	evaluatedMask: number[]; // Attention mask [m×m] flattened
}

/**
 * Evaluation mode output
 */
export interface EvaluationOutput {
	logits: Float32Array; // [m+1, vocab_size] flattened
	numEvaluated: number; // m
}

/**
 * Model Inferencer for Causal Language Model
 * Compatible with both frontend (onnxruntime-web) and backend (onnxruntime-node)
 */
export class ModelInferencer {
	private session: OnnxSession | null = null;
	private config: InferencerConfig;
	private TensorClass: TensorConstructor;

	// TGN tokenizer: byte-level (0-255) + PAD(256) + START(257) + END(258)
	private readonly PAD_TOKEN = 256;
	private readonly START_TOKEN = 257;
	private readonly END_TOKEN = 258;

	constructor(TensorClass: TensorConstructor, config: Partial<InferencerConfig> = {}) {
		this.TensorClass = TensorClass;
		this.config = {
			vocabSize: 259,
			seqLen: 256,
			...config
		};
	}

	/**
	 * Set the inference session (created by platform-specific code)
	 */
	setSession(session: OnnxSession): void {
		this.session = session;
		console.log("[ModelInferencer] ✓ Session set successfully");
		this.printModelInfo();
	}

	/**
	 * Run basic inference test
	 */
	async testBasicInference(): Promise<InferenceResult> {
		if (!this.session) {
			throw new Error("Inferencer not initialized. Call setSession() first.");
		}

		console.log("[ModelInferencer] Running basic inference test...");

		const batchSize = 1;
		const seqLen = this.config.seqLen;

		// Create random input
		const inputIds = this.createRandomInput(batchSize, seqLen);
		const inputTensor = new this.TensorClass("int64", inputIds, [batchSize, seqLen]);

		// Run inference
		const startTime = performance.now();
		const results = await this.session.run({ input_ids: inputTensor });
		const inferenceTime = performance.now() - startTime;

		// Get logits
		const logits = results.logits;

		// Validate output
		this.validateOutput(logits, batchSize, seqLen);

		// Get predictions
		const predictions = this.getPredictions(logits.data as Float32Array, batchSize * seqLen);

		// Convert tokens to text
		const text = String.fromCharCode(...predictions.slice(0, 100));

		console.log("[ModelInferencer] Inference completed:");
		console.log(`  Input shape: [${inputTensor.dims.join(", ")}]`);
		console.log(`  Output shape: [${logits.dims.join(", ")}]`);
		console.log(`  Output dtype: ${logits.type}`);
		console.log(`  Inference time: ${inferenceTime.toFixed(2)}ms`);
		console.log(`  Sample predictions: [${predictions.slice(0, 10).join(", ")}]`);

		const logitsArray = Array.from(logits.data as Float32Array);
		console.log(
			`  Logits range: [${Math.min(...logitsArray).toFixed(3)}, ${Math.max(...logitsArray).toFixed(3)}]`
		);

		return {
			tokens: predictions,
			text,
			logits: logits.data as Float32Array,
			inferenceTime
		};
	}

	/**
	 * Generate tokens autoregressively from a prompt
	 */
	async generateText(prompt: string, numTokens: number = 10): Promise<InferenceResult> {
		if (!this.session) {
			throw new Error("Inferencer not initialized. Call setSession() first.");
		}

		console.log(`[ModelInferencer] Generating ${numTokens} tokens from prompt: "${prompt}"`);

		// Convert prompt to token IDs (byte values)
		const promptTokens = Array.from(prompt).map((c) => c.charCodeAt(0));
		console.log(`  Prompt tokens (${promptTokens.length}): [${promptTokens.join(", ")}]`);

		// Start with prompt tokens
		const sequence = [...promptTokens];
		const times: number[] = [];

		// Generate tokens
		for (let i = 0; i < numTokens; i++) {
			// Pad sequence to fixed length
			const paddedSequence = this.padSequence(sequence, this.config.seqLen);

			// Create input tensor
			const inputIds = new BigInt64Array(paddedSequence.map((t) => BigInt(t)));
			const inputTensor = new this.TensorClass("int64", inputIds, [1, this.config.seqLen]);

			// Run inference
			const startTime = performance.now();
			const results = await this.session.run({ input_ids: inputTensor });
			times.push(performance.now() - startTime);

			// Get prediction at the last non-padded position
			const logits = results.logits.data as Float32Array;
			const lastPos = sequence.length - 1; // Position before padding
			const offset = lastPos * this.config.vocabSize;

			// Find token with highest logit
			let maxIdx = 0;
			let maxVal = logits[offset];
			for (let j = 1; j < this.config.vocabSize; j++) {
				if (logits[offset + j] > maxVal) {
					maxVal = logits[offset + j];
					maxIdx = j;
				}
			}

			sequence.push(maxIdx);

			// Stop if END token is generated
			if (maxIdx === this.END_TOKEN) {
				console.log("  Generated END token, stopping...");
				break;
			}
		}

		// Convert generated tokens to text
		const generatedText = String.fromCharCode(...sequence);

		const avgTime = times.reduce((a, b) => a + b, 0) / times.length;
		console.log(`[ModelInferencer] Generation complete:`);
		console.log(`  Generated text: "${generatedText}"`);
		console.log(`  Token sequence (${sequence.length}): [${sequence.join(", ")}]`);
		console.log(`  Avg inference time: ${avgTime.toFixed(2)}ms`);
		console.log(`  Tokens/sec: ${(1000 / avgTime).toFixed(2)}`);

		return {
			tokens: sequence,
			text: generatedText,
			logits: new Float32Array(), // Not returning full logits for generation
			inferenceTime: avgTime
		};
	}

	/**
	 * Get model information
	 */
	getModelInfo(): { inputs: string[]; outputs: string[] } | null {
		if (!this.session) return null;

		return {
			inputs: [...this.session.inputNames],
			outputs: [...this.session.outputNames]
		};
	}

	/**
	 * Get configuration
	 */
	getConfig(): InferencerConfig {
		return this.config;
	}

	/**
	 * Run inference with token array input
	 * Returns raw logits as Float32Array
	 */
	async runInference(tokens: number[]): Promise<Float32Array> {
		if (!this.session) {
			throw new Error("Inferencer not initialized. Call setSession() first.");
		}

		const seqLen = this.config.seqLen;

		// Prepend START_TOKEN to input
		const tokensWithStart = [this.START_TOKEN, ...tokens];

		// Pad to fixed length
		const paddedTokens = new BigInt64Array(seqLen);
		for (let i = 0; i < seqLen; i++) {
			paddedTokens[i] =
				i < tokensWithStart.length ? BigInt(tokensWithStart[i]) : BigInt(this.PAD_TOKEN);
		}

		// Create input tensor
		const inputTensor = new this.TensorClass("int64", paddedTokens, [1, seqLen]);

		// Run inference
		const results = await this.session.run({ input_ids: inputTensor });
		return results.logits.data as Float32Array;
	}


	/**
	 * Run tree attention inference (evaluation mode)
	 * For models exported with --evaluation flag
	 * @param inputs - Prefix, evaluated tokens, and attention mask
	 * @returns Logits for each evaluated position
	 */
	async runEvaluationInference(inputs: EvaluationInputs): Promise<EvaluationOutput> {
		if (!this.session) {
			throw new Error("Inferencer not initialized. Call setSession() first.");
		}

		const { prefixIds, evaluatedIds, evaluatedMask } = inputs;
		const batchSize = 1;
		const prefixLen = prefixIds.length;
		const m = evaluatedIds.length;

		// Convert to BigInt64Array for ONNX int64 tensors
		const prefixIdsArray = new BigInt64Array(batchSize * prefixLen);
		for (let i = 0; i < prefixLen; i++) {
			prefixIdsArray[i] = BigInt(prefixIds[i]);
		}

		const evaluatedIdsArray = new BigInt64Array(batchSize * m);
		for (let i = 0; i < m; i++) {
			evaluatedIdsArray[i] = BigInt(evaluatedIds[i]);
		}

		// Mask is Float32Array
		const maskArray = new Float32Array(m * m);
		for (let i = 0; i < m * m; i++) {
			maskArray[i] = evaluatedMask[i];
		}

		// Create ONNX tensors
		const prefixIdsTensor = new this.TensorClass("int64", prefixIdsArray, [
			batchSize,
			prefixLen
		]);
		const evaluatedIdsTensor = new this.TensorClass("int64", evaluatedIdsArray, [batchSize, m]);
		const evaluatedMaskTensor = new this.TensorClass("float32", maskArray, [1, m, m]);

		// Run inference
		const results = await this.session.run({
			prefix_ids: prefixIdsTensor,
			evaluated_ids: evaluatedIdsTensor,
			evaluated_mask: evaluatedMaskTensor
		});

		// Extract logits
		const logits = results.logits.data as Float32Array;

		// Output shape: [batch, m+1, vocab_size]
		// We return flattened array and num_evaluated for reshaping
		return {
			logits,
			numEvaluated: m
		};
	}


	/**
	 * Compute softmax for a single position's logits
	 * @param logits - Full logits array
	 * @param position - Which evaluated position (0 = last prefix, 1-m = evaluated tokens)
	 * @returns Probability distribution over vocabulary
	 */
	softmax(logits: Float32Array, position: number): Float32Array {
		const vocabSize = this.config.vocabSize;
		const offset = position * vocabSize;
		const probs = new Float32Array(vocabSize);

		// Find max for numerical stability
		let maxLogit = -Infinity;
		for (let i = 0; i < vocabSize; i++) {
			maxLogit = Math.max(maxLogit, logits[offset + i]);
		}

		// Compute exp and sum
		let sumExp = 0;
		for (let i = 0; i < vocabSize; i++) {
			probs[i] = Math.exp(logits[offset + i] - maxLogit);
			sumExp += probs[i];
		}

		// Normalize
		for (let i = 0; i < vocabSize; i++) {
			probs[i] /= sumExp;
		}

		return probs;
	}


	/**
	 * Check if inferencer is ready
	 */
	isReady(): boolean {
		return this.session !== null;
	}

	/**
	 * Destroy the session and free resources
	 */
	destroy(): void {
		this.session = null;
		console.log("[ModelInferencer] Session destroyed");
	}

	// Private helper methods

	private printModelInfo(): void {
		if (!this.session) return;

		console.log("[ModelInferencer] Model Information:");
		console.log("  Inputs:");
		this.session.inputNames.forEach((name, i) => {
			console.log(`    [${i}] ${name}`);
		});
		console.log("  Outputs:");
		this.session.outputNames.forEach((name, i) => {
			console.log(`    [${i}] ${name}`);
		});
	}

	private createRandomInput(batchSize: number, seqLen: number): BigInt64Array {
		const size = batchSize * seqLen;
		const data = new BigInt64Array(size);
		for (let i = 0; i < size; i++) {
			data[i] = BigInt(Math.floor(Math.random() * this.config.vocabSize));
		}
		return data;
	}

	private padSequence(tokens: number[], targetLen: number): number[] {
		const padded = [...tokens];
		while (padded.length < targetLen) {
			padded.push(this.PAD_TOKEN);
		}
		return padded.slice(0, targetLen); // Truncate if too long
	}

	private validateOutput(logits: OnnxTensor, batchSize: number, seqLen: number): void {
		const expectedShape = [batchSize, seqLen, this.config.vocabSize];

		if (logits.dims.length !== 3) {
			throw new Error(`Expected 3D output, got ${logits.dims.length}D`);
		}

		if (
			logits.dims[0] !== expectedShape[0] ||
			logits.dims[1] !== expectedShape[1] ||
			logits.dims[2] !== expectedShape[2]
		) {
			throw new Error(
				`Shape mismatch! Expected [${expectedShape.join(", ")}], ` +
					`got [${logits.dims.join(", ")}]`
			);
		}

		if (logits.type !== "float32") {
			throw new Error(`Expected float32 output, got ${logits.type}`);
		}
	}

	private getPredictions(logitsData: Float32Array, numPositions: number): number[] {
		const predictions: number[] = [];
		for (let i = 0; i < numPositions; i++) {
			let maxIdx = 0;
			let maxVal = logitsData[i * this.config.vocabSize];
			for (let j = 1; j < this.config.vocabSize; j++) {
				const val = logitsData[i * this.config.vocabSize + j];
				if (val > maxVal) {
					maxVal = val;
					maxIdx = j;
				}
			}
			predictions.push(maxIdx);
		}
		return predictions;
	}
}