-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmir_runtime.py
More file actions
708 lines (575 loc) · 28.6 KB
/
Copy pathmir_runtime.py
File metadata and controls
708 lines (575 loc) · 28.6 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
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
"""
Standalone Runtime for ITC Optimized Models
==========================================
Lightweight, dependency-minimal runtime for executing optimized models.
Supports ONNX, TorchScript, and native MIR formats.
Designed for production deployment without ITC framework dependencies.
Performance Optimizations:
- im2col-based convolution (10x faster than naive)
- Fused operations (Conv+ReLU, Linear+ReLU, etc.)
- Vectorized operations using NumPy
"""
import json
import os
from typing import Dict, List, Any, Optional, Union
import numpy as np
from pathlib import Path
# Import optimized kernels
try:
from runtime.kernels.conv2d_optimized import conv2d_im2col
from runtime.kernels.fused_ops import conv2d_relu, conv2d_bn_relu, linear_relu
OPTIMIZED_KERNELS_AVAILABLE = True
except ImportError:
# Fallback if module structure is different
try:
from kernels.conv2d_optimized import conv2d_im2col
from kernels.fused_ops import conv2d_relu, conv2d_bn_relu, linear_relu
OPTIMIZED_KERNELS_AVAILABLE = True
except ImportError:
OPTIMIZED_KERNELS_AVAILABLE = False
print("⚠️ Optimized kernels not available - using fallback (slower)")
# Optional imports - runtime adapts based on available libraries
try:
import torch
TORCH_AVAILABLE = True
except ImportError:
TORCH_AVAILABLE = False
print("⚠️ PyTorch not available - TorchScript runtime disabled")
try:
import onnxruntime as ort
ONNX_AVAILABLE = True
except ImportError:
ONNX_AVAILABLE = False
print("⚠️ ONNX Runtime not available - ONNX runtime disabled")
class MIRRuntime:
"""Standalone runtime for ITC optimized models"""
def __init__(self, model_path: str, runtime_type: str = 'auto'):
"""
Initialize runtime with model
Args:
model_path: Path to exported model file
runtime_type: 'auto', 'torch', 'onnx', or 'mir'
"""
self.model_path = model_path
self.runtime_type = self._detect_runtime_type(model_path, runtime_type)
self.model = None
self.metadata = None
self.input_shape = None
# Load model and metadata
self._load_model()
self._load_metadata()
print(f"✅ MIR Runtime initialized")
print(f" Runtime type: {self.runtime_type}")
print(f" Model: {os.path.basename(model_path)}")
print(f" Input shape: {self.input_shape}")
def _detect_runtime_type(self, model_path: str, runtime_type: str) -> str:
"""Detect appropriate runtime type"""
if runtime_type != 'auto':
return runtime_type
ext = Path(model_path).suffix.lower()
if ext == '.onnx' and ONNX_AVAILABLE:
return 'onnx'
elif ext == '.pt' and TORCH_AVAILABLE:
return 'torch'
elif ext == '.json':
return 'mir'
else:
raise RuntimeError(f"Cannot determine runtime type for {model_path}")
def _load_model(self):
"""Load model based on runtime type"""
if self.runtime_type == 'onnx':
self._load_onnx_model()
elif self.runtime_type == 'torch':
self._load_torch_model()
elif self.runtime_type == 'mir':
self._load_mir_model()
else:
raise RuntimeError(f"Unsupported runtime type: {self.runtime_type}")
def _load_onnx_model(self):
"""Load ONNX model"""
if not ONNX_AVAILABLE:
raise RuntimeError("ONNX Runtime not available")
self.model = ort.InferenceSession(self.model_path)
# Get input shape from ONNX model
input_info = self.model.get_inputs()[0]
self.input_shape = [dim if isinstance(dim, int) else 1 for dim in input_info.shape]
print(f"📦 ONNX model loaded: {os.path.basename(self.model_path)}")
def _load_torch_model(self):
"""Load TorchScript model"""
if not TORCH_AVAILABLE:
raise RuntimeError("PyTorch not available")
self.model = torch.jit.load(self.model_path, map_location='cpu')
self.model.eval()
# Try to get input shape from metadata first
if self.metadata and 'input_shape' in self.metadata:
self.input_shape = self.metadata['input_shape']
else:
# Fallback: try to infer from model graph or use default
try:
# Get input shape from the model's graph
graph = self.model.graph
for node in graph.inputs():
if hasattr(node.type(), 'sizes') and node.type().sizes():
sizes = [int(s) for s in node.type().sizes() if s is not None]
if sizes:
self.input_shape = sizes
break
else:
# Default fallback for common CNN input
self.input_shape = [1, 3, 16, 16]
print(f"⚠️ Could not infer input shape, using default: {self.input_shape}")
except Exception as e:
# Final fallback
self.input_shape = [1, 3, 16, 16]
print(f"⚠️ Shape inference failed ({e}), using default: {self.input_shape}")
print(f"📦 TorchScript model loaded: {os.path.basename(self.model_path)}")
def _load_mir_model(self):
"""Load MIR JSON model"""
with open(self.model_path, 'r') as f:
model_data = json.load(f)
self.model = model_data['mir_graph']
self.input_shape = model_data['input_shape']
print(f"📦 MIR model loaded: {os.path.basename(self.model_path)}")
def _load_metadata(self):
"""Load model metadata if available"""
metadata_path = self.model_path.replace('.onnx', '_metadata.json') \
.replace('.pt', '_metadata.json') \
.replace('.json', '_metadata.json')
if os.path.exists(metadata_path):
with open(metadata_path, 'r') as f:
self.metadata = json.load(f)
print(f"📋 Metadata loaded: {os.path.basename(metadata_path)}")
def predict(self, input_data: Union[np.ndarray, List, torch.Tensor]) -> np.ndarray:
"""
Run inference on input data
Args:
input_data: Input tensor/array
Returns:
Prediction as numpy array
"""
# Prepare input
input_tensor = self._prepare_input(input_data)
# Run inference
if self.runtime_type == 'onnx':
output = self._predict_onnx(input_tensor)
elif self.runtime_type == 'torch':
output = self._predict_torch(input_tensor)
elif self.runtime_type == 'mir':
output = self._predict_mir(input_tensor)
else:
raise RuntimeError(f"Unsupported runtime: {self.runtime_type}")
return output
def predict_batch(self, input_batch: Union[np.ndarray, List, torch.Tensor]) -> np.ndarray:
"""
Run batch inference
Args:
input_batch: Batch of input tensors
Returns:
Batch predictions as numpy array
"""
# For now, use simple loop - can be optimized later
results = []
for input_data in input_batch:
result = self.predict(input_data)
results.append(result)
return np.array(results)
def _prepare_input(self, input_data: Union[np.ndarray, List, torch.Tensor]) -> np.ndarray:
"""Prepare input data for inference"""
if isinstance(input_data, list):
input_array = np.array(input_data, dtype=np.float32)
elif hasattr(input_data, 'numpy'): # torch.Tensor
input_array = input_data.numpy().astype(np.float32)
else:
input_array = np.array(input_data, dtype=np.float32)
# Ensure correct shape
if len(input_array.shape) == len(self.input_shape) - 1:
# Add batch dimension
input_array = np.expand_dims(input_array, axis=0)
return input_array
def _predict_onnx(self, input_tensor: np.ndarray) -> np.ndarray:
"""Run ONNX inference"""
input_name = self.model.get_inputs()[0].name
outputs = self.model.run(None, {input_name: input_tensor})
return outputs[0]
def _predict_torch(self, input_tensor: np.ndarray) -> np.ndarray:
"""Run TorchScript inference"""
torch_tensor = torch.from_numpy(input_tensor)
with torch.no_grad():
output = self.model(torch_tensor)
return output.numpy()
def _predict_mir(self, input_tensor: np.ndarray) -> np.ndarray:
"""Run MIR native inference"""
return self._execute_mir_graph(self.model, input_tensor)
def _execute_mir_graph(self, mir_graph: Dict[str, Any], input_tensor: np.ndarray) -> np.ndarray:
"""Execute MIR graph using NumPy backend"""
# Storage for intermediate tensors
tensors = {'input': input_tensor}
# Handle different MIR graph structures
if 'nodes' in mir_graph:
nodes = mir_graph['nodes']
elif 'graph' in mir_graph and 'nodes' in mir_graph['graph']:
nodes = mir_graph['graph']['nodes']
else:
raise RuntimeError("Could not find nodes in MIR graph structure")
# Execute nodes in order
for node in nodes:
node_type = node['op_type']
node_id = node['id']
if node_type == 'conv2d':
output = self._execute_conv2d(node, tensors)
elif node_type == 'linear':
output = self._execute_linear(node, tensors)
elif node_type == 'relu':
output = self._execute_relu(node, tensors)
elif node_type == 'batchnorm2d':
output = self._execute_batchnorm2d(node, tensors)
elif node_type in ['maxpool2d', 'max_pool2d']:
output = self._execute_maxpool2d(node, tensors)
elif node_type in ['adaptiveavgpool2d', 'adaptive_avg_pool2d']:
output = self._execute_adaptiveavgpool2d(node, tensors)
elif node_type == 'flatten':
output = self._execute_flatten(node, tensors)
else:
# Handle fused operations
if 'fused_relu' in node_type or '_relu_fused' in node_type or 'relu_fused' in node_type:
if 'conv2d' in node_type:
output = self._execute_conv2d(node, tensors)
output = np.maximum(0, output) # ReLU
elif 'linear' in node_type:
output = self._execute_linear(node, tensors)
output = np.maximum(0, output) # ReLU
else:
raise NotImplementedError(f"Fused operation not implemented: {node_type}")
elif 'bn' in node_type and 'relu' in node_type:
# Handle Conv+BN+ReLU fused operations
if 'conv' in node_type:
output = self._execute_conv2d(node, tensors)
output = self._execute_batchnorm2d(node, tensors)
output = np.maximum(0, output) # ReLU
else:
raise NotImplementedError(f"Fused operation not implemented: {node_type}")
else:
raise NotImplementedError(f"Operation not implemented: {node_type}")
tensors[node_id] = output
# Also store by output names if specified
if 'outputs' in node and node['outputs']:
for output_name in node['outputs']:
tensors[output_name] = output
# Return the final output
output_nodes = [n for n in nodes if not any(n['id'] in inp for inp in [n2.get('inputs', []) for n2 in nodes])]
if output_nodes:
return tensors[output_nodes[-1]['id']]
else:
return tensors[nodes[-1]['id']]
def _execute_conv2d(self, node: Dict[str, Any], tensors: Dict[str, np.ndarray]) -> np.ndarray:
"""
Execute Conv2D operation using optimized im2col implementation.
This provides 10-20x speedup over the naive triple-nested-loop approach.
"""
input_tensor = tensors[node['inputs'][0]]
# Check if weights are available (optimized MIR has weights, baseline doesn't)
if 'weights' not in node or not node['weights']:
# For baseline MIR without weights, return zeros (placeholder)
# This shouldn't happen in production - MIR runtime requires optimized models
params = node.get('params', node.get('parameters', {}))
out_channels = params.get('out_channels', 16)
batch_size, in_channels, in_height, in_width = input_tensor.shape
kernel_size = params.get('kernel_size', [3, 3])
stride = params.get('stride', [1, 1])
padding = params.get('padding', [0, 0])
out_height = (in_height + 2 * padding[0] - kernel_size[0]) // stride[0] + 1
out_width = (in_width + 2 * padding[1] - kernel_size[1]) // stride[1] + 1
print(f"⚠️ Warning: Conv2D node '{node['id']}' has no weights - returning zeros")
return np.zeros((batch_size, out_channels, out_height, out_width))
# Get weights and bias
weights = np.array(node['weights']['weight'])
bias = np.array(node['weights']['bias']) if 'bias' in node['weights'] else None
# Handle empty/scalar weights (bug in optimization passes)
if weights.size == 0 or weights.ndim == 0:
# Try to get dimensions from params
params = node.get('params', node.get('parameters', {}))
if 'out_channels' in params and 'in_channels' in params:
out_channels = params['out_channels']
batch_size = input_tensor.shape[0]
kernel_size = params.get('kernel_size', [3, 3])
stride = params.get('stride', [1, 1])
padding = params.get('padding', [0, 0])
in_height, in_width = input_tensor.shape[2:]
out_height = (in_height + 2 * padding[0] - kernel_size[0]) // stride[0] + 1
out_width = (in_width + 2 * padding[1] - kernel_size[1]) // stride[1] + 1
if weights.ndim == 0:
print(f"⚠️ Warning: Conv2D node '{node['id']}' has scalar weights - returning zeros")
else:
print(f"⚠️ Warning: Conv2D node '{node['id']}' has empty weights - returning zeros")
return np.zeros((batch_size, out_channels, out_height, out_width))
else:
raise ValueError(f"Conv2D node '{node['id']}' has empty/scalar weights and no dimension info")
# Get parameters (handle different structures)
if 'parameters' in node:
params = node['parameters']
elif 'params' in node:
params = node['params']
elif 'attrs' in node:
params = node['attrs']
else:
# Default parameters for Conv2D
params = {'stride': [1, 1], 'padding': [0, 0]}
stride = params.get('stride', [1, 1])
padding = params.get('padding', [0, 0])
# Ensure stride and padding are single values (not lists)
stride_val = stride[0] if isinstance(stride, (list, tuple)) else stride
padding_val = padding[0] if isinstance(padding, (list, tuple)) else padding
# Handle different weight shapes
if len(weights.shape) == 4:
# Standard shape: [out_channels, in_channels, kernel_h, kernel_w]
pass
elif len(weights.shape) == 2:
# Flattened weights - need to reshape
params_check = node.get('params', node.get('parameters', {}))
out_channels = params_check.get('out_channels', weights.shape[0])
in_channels_check = params_check.get('in_channels', input_tensor.shape[1])
kernel_size = params_check.get('kernel_size', [3, 3])
kernel_h, kernel_w = kernel_size if isinstance(kernel_size, list) else [kernel_size, kernel_size]
# Reshape weights
weights = weights.reshape(out_channels, in_channels_check, kernel_h, kernel_w)
else:
raise ValueError(f"Unexpected weight shape: {weights.shape}")
# ✨ USE OPTIMIZED im2col CONVOLUTION (10-20x faster!)
if OPTIMIZED_KERNELS_AVAILABLE:
output = conv2d_im2col(
input_tensor,
weights,
bias,
stride=stride_val,
padding=padding_val
)
else:
# Fallback to naive implementation (SLOW - only for when optimized kernels unavailable)
batch_size, in_channels, in_height, in_width = input_tensor.shape
out_channels, _, kernel_h, kernel_w = weights.shape
# Calculate output dimensions
out_height = (in_height + 2 * padding_val - kernel_h) // stride_val + 1
out_width = (in_width + 2 * padding_val - kernel_w) // stride_val + 1
# Initialize output
output = np.zeros((batch_size, out_channels, out_height, out_width))
# Apply padding if needed
if padding_val > 0:
input_tensor = np.pad(
input_tensor,
((0, 0), (0, 0), (padding_val, padding_val), (padding_val, padding_val)),
mode='constant'
)
# Perform convolution (naive - SLOW!)
for b in range(batch_size):
for oc in range(out_channels):
for oh in range(out_height):
for ow in range(out_width):
h_start = oh * stride_val
w_start = ow * stride_val
h_end = h_start + kernel_h
w_end = w_start + kernel_w
output[b, oc, oh, ow] = np.sum(
input_tensor[b, :, h_start:h_end, w_start:w_end] * weights[oc]
)
if bias is not None:
output[b, oc, oh, ow] += bias[oc]
return output
def _execute_linear(self, node: Dict[str, Any], tensors: Dict[str, np.ndarray]) -> np.ndarray:
"""
Execute Linear (fully connected) operation.
Uses optimized matrix multiplication from NumPy's BLAS backend.
"""
input_tensor = tensors[node['inputs'][0]]
# Flatten input if needed (auto-flatten before linear layers)
if input_tensor.ndim > 2:
batch_size = input_tensor.shape[0]
input_tensor = input_tensor.reshape(batch_size, -1)
# Check if weights are available
if 'weights' not in node or not node['weights']:
# For baseline MIR without weights, return zeros
params = node.get('params', node.get('parameters', {}))
out_features = params.get('out', params.get('out_features', 10))
batch_size = input_tensor.shape[0]
print(f"⚠️ Warning: Linear node '{node['id']}' has no weights - returning zeros")
return np.zeros((batch_size, out_features))
# Get weights and bias
weights = np.array(node['weights']['weight'])
bias = np.array(node['weights']['bias']) if 'bias' in node['weights'] else None
# Handle empty/scalar weights
if weights.size == 0 or weights.ndim == 0:
params = node.get('params', node.get('parameters', {}))
out_features = params.get('out', params.get('out_features', 10))
batch_size = input_tensor.shape[0]
if weights.ndim == 0:
print(f"⚠️ Warning: Linear node '{node['id']}' has scalar weights - returning zeros")
else:
print(f"⚠️ Warning: Linear node '{node['id']}' has empty weights - returning zeros")
return np.zeros((batch_size, out_features))
# ✨ Optimized linear transformation: y = xW^T + b
# NumPy uses highly optimized BLAS for matrix multiplication
output = np.dot(input_tensor, weights.T)
if bias is not None:
output += bias
return output
def _execute_relu(self, node: Dict[str, Any], tensors: Dict[str, np.ndarray]) -> np.ndarray:
"""Execute ReLU operation"""
input_tensor = tensors[node['inputs'][0]]
return np.maximum(0, input_tensor)
def _execute_batchnorm2d(self, node: Dict[str, Any], tensors: Dict[str, np.ndarray]) -> np.ndarray:
"""Execute BatchNorm2D operation"""
input_tensor = tensors[node['inputs'][0]]
# Check if weights are available
if 'weights' not in node or not node['weights']:
# For baseline MIR without weights, return input unchanged
print(f"⚠️ Warning: BatchNorm2D node '{node['id']}' has no weights - returning input unchanged")
return input_tensor
# Get BatchNorm parameters
weights = node['weights']
weight = np.array(weights.get('weight', np.ones(input_tensor.shape[1])))
bias = np.array(weights.get('bias', np.zeros(input_tensor.shape[1])))
running_mean = np.array(weights.get('running_mean', np.zeros(input_tensor.shape[1])))
running_var = np.array(weights.get('running_var', np.ones(input_tensor.shape[1])))
# Get epsilon from params
params = node.get('params', node.get('parameters', {}))
eps = params.get('eps', 1e-5)
# Reshape for broadcasting
# BatchNorm operates on channel dimension
batch_size, num_channels, height, width = input_tensor.shape
running_mean = running_mean.reshape(1, num_channels, 1, 1)
running_var = running_var.reshape(1, num_channels, 1, 1)
weight = weight.reshape(1, num_channels, 1, 1)
bias = bias.reshape(1, num_channels, 1, 1)
# Apply BatchNorm: (x - mean) / sqrt(var + eps) * weight + bias
output = (input_tensor - running_mean) / np.sqrt(running_var + eps)
output = output * weight + bias
return output
def _execute_maxpool2d(self, node: Dict[str, Any], tensors: Dict[str, np.ndarray]) -> np.ndarray:
"""Execute MaxPool2D operation"""
input_tensor = tensors[node['inputs'][0]]
# Get parameters (handle different structures)
params = node.get('params', node.get('parameters', {}))
kernel_size = params.get('kernel_size', [2, 2])
stride = params.get('stride', kernel_size)
batch_size, channels, in_height, in_width = input_tensor.shape
out_height = (in_height - kernel_size[0]) // stride[0] + 1
out_width = (in_width - kernel_size[1]) // stride[1] + 1
output = np.zeros((batch_size, channels, out_height, out_width))
for b in range(batch_size):
for c in range(channels):
for oh in range(out_height):
for ow in range(out_width):
h_start = oh * stride[0]
w_start = ow * stride[1]
h_end = h_start + kernel_size[0]
w_end = w_start + kernel_size[1]
output[b, c, oh, ow] = np.max(
input_tensor[b, c, h_start:h_end, w_start:w_end]
)
return output
def _execute_adaptiveavgpool2d(self, node: Dict[str, Any], tensors: Dict[str, np.ndarray]) -> np.ndarray:
"""Execute AdaptiveAvgPool2D operation"""
input_tensor = tensors[node['inputs'][0]]
# Get parameters (handle different structures)
params = node.get('params', node.get('parameters', {}))
output_size = params.get('output_size', [1, 1])
batch_size, channels, in_height, in_width = input_tensor.shape
out_height, out_width = output_size
output = np.zeros((batch_size, channels, out_height, out_width))
for b in range(batch_size):
for c in range(channels):
for oh in range(out_height):
for ow in range(out_width):
h_start = (oh * in_height) // out_height
h_end = ((oh + 1) * in_height) // out_height
w_start = (ow * in_width) // out_width
w_end = ((ow + 1) * in_width) // out_width
output[b, c, oh, ow] = np.mean(
input_tensor[b, c, h_start:h_end, w_start:w_end]
)
return output
def _execute_flatten(self, node: Dict[str, Any], tensors: Dict[str, np.ndarray]) -> np.ndarray:
"""Execute Flatten operation"""
input_tensor = tensors[node['inputs'][0]]
# Get parameters
params = node['parameters']
start_dim = params.get('start_dim', 1)
# Flatten from start_dim onwards
shape = list(input_tensor.shape)
new_shape = shape[:start_dim] + [-1]
return input_tensor.reshape(new_shape)
def get_model_info(self) -> Dict[str, Any]:
"""Get comprehensive model information"""
info = {
'model_path': self.model_path,
'runtime_type': self.runtime_type,
'input_shape': self.input_shape,
'metadata': self.metadata
}
if self.runtime_type == 'onnx' and self.model:
info['onnx_info'] = {
'inputs': [(inp.name, inp.shape, inp.type) for inp in self.model.get_inputs()],
'outputs': [(out.name, out.shape, out.type) for out in self.model.get_outputs()]
}
return info
def benchmark(self, num_iterations: int = 100) -> Dict[str, float]:
"""
Benchmark model performance
Args:
num_iterations: Number of inference iterations
Returns:
Performance metrics
"""
import time
# Create dummy input
if self.runtime_type == 'torch':
dummy_input = torch.randn(*self.input_shape)
else:
dummy_input = np.random.randn(*self.input_shape).astype(np.float32)
# Warmup
for _ in range(10):
self.predict(dummy_input)
# Benchmark
start_time = time.time()
for _ in range(num_iterations):
self.predict(dummy_input)
end_time = time.time()
total_time = end_time - start_time
avg_time = total_time / num_iterations
throughput = num_iterations / total_time
metrics = {
'total_time_ms': total_time * 1000,
'avg_time_ms': avg_time * 1000,
'throughput_fps': throughput,
'iterations': num_iterations
}
print(f"📊 Benchmark Results ({num_iterations} iterations):")
print(f" Average time: {avg_time * 1000:.2f} ms")
print(f" Throughput: {throughput:.1f} FPS")
return metrics
class ModelLoader:
"""Utility class for loading different model formats"""
@staticmethod
def load_onnx(model_path: str) -> MIRRuntime:
"""Load ONNX model"""
return MIRRuntime(model_path, 'onnx')
@staticmethod
def load_torchscript(model_path: str) -> MIRRuntime:
"""Load TorchScript model"""
return MIRRuntime(model_path, 'torch')
@staticmethod
def load_mir_json(model_path: str) -> MIRRuntime:
"""Load MIR JSON model"""
return MIRRuntime(model_path, 'mir')
@staticmethod
def auto_load(model_path: str) -> MIRRuntime:
"""Auto-detect and load model"""
return MIRRuntime(model_path, 'auto')
def load_optimized_model(model_path: str) -> MIRRuntime:
"""
Convenience function to load optimized model
Args:
model_path: Path to exported model
Returns:
Initialized runtime instance
"""
return ModelLoader.auto_load(model_path)