Spaces:
Running
Running
File size: 12,196 Bytes
9bd422a | 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 | /**
* FlopsEstimator - Estimates FLOPs (Floating Point Operations) for ONNX models
* Computes per-node and total FLOPs based on opType and input tensor shapes.
* Requirements: 34.1, 34.2, 34.3, 34.4, 34.5, 34.6
*/
class FlopsEstimator {
/**
* @param {string} containerId - ID of the container element for rendering
*/
constructor(containerId) {
this._containerId = containerId;
this._container = document.getElementById(containerId);
this._result = null;
if (!this._container) {
console.warn(`[FlopsEstimator] Container #${containerId} not found`);
}
}
// βββ FLOPs Formulas βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Supported opType formulas.
* Each function receives (attrs, inputShapes) and returns a FLOPs count.
*/
static get FORMULAS() {
return {
// Conv: 2 * Cout * Hout * Wout * CinPerGroup * Kh * Kw
'Conv': function (attrs, inputShapes) {
const input = inputShapes[0] || [];
const weight = inputShapes[1] || [];
const Cout = weight[0] || 0;
const CinPerGroup = weight[1] || 0;
const Kh = weight[2] || 0;
const Kw = weight[3] || 0;
// Estimate output spatial dims (assume same padding)
const Hout = input[2] || 0;
const Wout = input[3] || 0;
return 2 * Cout * Hout * Wout * CinPerGroup * Kh * Kw;
},
// MatMul: 2 * M * N * K
'MatMul': function (attrs, inputShapes) {
const A = inputShapes[0] || [];
const B = inputShapes[1] || [];
const M = A[A.length - 2] || 0;
const K = A[A.length - 1] || 0;
const N = B[B.length - 1] || 0;
return 2 * M * N * K;
},
// Gemm: 2 * M * N * K + M * N (bias)
'Gemm': function (attrs, inputShapes) {
const A = inputShapes[0] || [];
const B = inputShapes[1] || [];
const M = A[0] || 0;
const K = A[1] || 0;
const N = B[1] || 0;
return 2 * M * N * K + M * N;
},
// BatchNormalization: 4 * elements (mean, var, normalize, scale+shift)
'BatchNormalization': function (attrs, inputShapes) {
const input = inputShapes[0] || [];
if (input.length === 0) return 0;
var elements = 1;
for (var i = 0; i < input.length; i++) {
elements *= (typeof input[i] === 'number' ? input[i] : 0);
}
return 4 * elements;
},
// Relu: 1 comparison per element
'Relu': function (attrs, inputShapes) {
const input = inputShapes[0] || [];
if (input.length === 0) return 0;
var elements = 1;
for (var i = 0; i < input.length; i++) {
elements *= (typeof input[i] === 'number' ? input[i] : 0);
}
return elements;
},
// Add: element-wise
'Add': function (attrs, inputShapes) {
const input = inputShapes[0] || [];
if (input.length === 0) return 0;
var elements = 1;
for (var i = 0; i < input.length; i++) {
elements *= (typeof input[i] === 'number' ? input[i] : 0);
}
return elements;
},
// Mul: element-wise
'Mul': function (attrs, inputShapes) {
const input = inputShapes[0] || [];
if (input.length === 0) return 0;
var elements = 1;
for (var i = 0; i < input.length; i++) {
elements *= (typeof input[i] === 'number' ? input[i] : 0);
}
return elements;
}
};
}
// βββ Shape Lookup βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Build a map of tensor name β shape from all available sources.
* Sources: parsedModel.inputs, parsedModel.outputs, parsedModel.graph.valueInfo, initializers
* @param {Object} parsedModel
* @returns {Object} tensorName β shape array
*/
_buildShapeMap(parsedModel) {
const shapeMap = {};
// Model inputs
const inputs = (parsedModel && parsedModel.inputs) || [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name && inputs[i].shape) {
shapeMap[inputs[i].name] = inputs[i].shape;
}
}
// Model outputs
const outputs = (parsedModel && parsedModel.outputs) || [];
for (var i = 0; i < outputs.length; i++) {
if (outputs[i].name && outputs[i].shape) {
shapeMap[outputs[i].name] = outputs[i].shape;
}
}
// Intermediate value info
const valueInfo = (parsedModel && parsedModel.graph && parsedModel.graph.valueInfo) || {};
const viKeys = Object.keys(valueInfo);
for (var i = 0; i < viKeys.length; i++) {
const vi = valueInfo[viKeys[i]];
if (vi && vi.name && vi.shape) {
shapeMap[vi.name] = vi.shape;
}
}
// Initializers
const initializers = (parsedModel && parsedModel.graph && parsedModel.graph.initializers) || [];
for (var i = 0; i < initializers.length; i++) {
if (initializers[i].name && initializers[i].shape) {
shapeMap[initializers[i].name] = initializers[i].shape;
}
}
return shapeMap;
}
// βββ Public API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Estimate FLOPs for a single node given its opType, attributes, and resolved input shapes.
* @param {{ opType: string, attributes: Object, inputShapes: Array<Array<number>> }} nodeInfo
* @returns {number} Estimated FLOPs, or -1 if opType is unsupported
*/
estimateNodeFlops(nodeInfo) {
const opType = nodeInfo && nodeInfo.opType;
const formula = FlopsEstimator.FORMULAS[opType];
if (!formula) return -1;
const attrs = (nodeInfo && nodeInfo.attributes) || {};
const inputShapes = (nodeInfo && nodeInfo.inputShapes) || [];
const flops = formula(attrs, inputShapes);
return (typeof flops === 'number' && isFinite(flops) && flops >= 0) ? flops : 0;
}
/**
* Compute FLOPs for the entire model.
* @param {Object} parsedModel - The parsed ONNX model
* @returns {FlopsResult}
*/
compute(parsedModel) {
const nodes = (parsedModel && parsedModel.graph && parsedModel.graph.nodes) || [];
const shapeMap = this._buildShapeMap(parsedModel);
const formulas = FlopsEstimator.FORMULAS;
var totalFlops = 0;
const perNode = [];
const opTypeMap = {}; // opType β { totalFlops, count }
const unsupportedSet = {}; // opType β true
for (var i = 0; i < nodes.length; i++) {
const node = nodes[i];
const opType = node.opType || '';
// Resolve input shapes for this node
const inputShapes = [];
const nodeInputs = node.inputs || [];
for (var j = 0; j < nodeInputs.length; j++) {
inputShapes.push(shapeMap[nodeInputs[j]] || []);
}
const flops = this.estimateNodeFlops({
opType: opType,
attributes: node.attributes || {},
inputShapes: inputShapes
});
if (flops < 0) {
// Unsupported op
unsupportedSet[opType] = true;
perNode.push({
nodeId: node.id || '',
nodeName: node.name || '',
opType: opType,
flops: -1,
formattedFlops: 'N/A'
});
} else {
totalFlops += flops;
perNode.push({
nodeId: node.id || '',
nodeName: node.name || '',
opType: opType,
flops: flops,
formattedFlops: this.formatFlops(flops)
});
if (!opTypeMap[opType]) {
opTypeMap[opType] = { totalFlops: 0, count: 0 };
}
opTypeMap[opType].totalFlops += flops;
opTypeMap[opType].count += 1;
}
}
// Build perOpType array sorted descending by totalFlops
const perOpType = [];
const opTypes = Object.keys(opTypeMap);
for (var i = 0; i < opTypes.length; i++) {
const ot = opTypes[i];
const entry = opTypeMap[ot];
perOpType.push({
opType: ot,
totalFlops: entry.totalFlops,
formattedFlops: this.formatFlops(entry.totalFlops),
count: entry.count,
percentage: totalFlops > 0 ? (entry.totalFlops / totalFlops) * 100 : 0
});
}
perOpType.sort(function (a, b) { return b.totalFlops - a.totalFlops; });
const unsupportedOps = Object.keys(unsupportedSet);
this._result = {
totalFlops: totalFlops,
formattedTotal: this.formatFlops(totalFlops),
perNode: perNode,
perOpType: perOpType,
unsupportedOps: unsupportedOps
};
return this._result;
}
/**
* Format a FLOPs number into a human-readable string.
* @param {number} flops
* @returns {string} e.g. "1.20 TFLOPs", "500.00 MFLOPs", "0 FLOPs"
*/
formatFlops(flops) {
if (flops == null || isNaN(flops) || flops < 0) return 'N/A';
if (flops >= 1e12) return (flops / 1e12).toFixed(2) + ' TFLOPs';
if (flops >= 1e9) return (flops / 1e9).toFixed(2) + ' GFLOPs';
if (flops >= 1e6) return (flops / 1e6).toFixed(2) + ' MFLOPs';
if (flops >= 1e3) return (flops / 1e3).toFixed(2) + ' KFLOPs';
return flops + ' FLOPs';
}
/**
* Render the FLOPs estimation result into the container.
* @param {FlopsResult} [result] - If omitted, uses the last computed result
*/
render(result) {
if (!this._container) return;
const data = result || this._result;
if (!data) {
this._container.innerHTML = '<p class="text-muted">No FLOPs estimation available.</p>';
return;
}
var html = '<div class="flops-card">';
// Total FLOPs header
html += '<div class="d-flex align-items-center mb-2">';
html += '<i class="fas fa-calculator me-2"></i>';
html += '<strong>Total FLOPs:</strong> ';
html += '<span class="flops-total">' + this._escapeHtml(data.formattedTotal) + '</span>';
html += '</div>';
// Breakdown by opType
if (data.perOpType && data.perOpType.length > 0) {
html += '<table class="flops-table table table-sm table-bordered mb-2">';
html += '<thead><tr><th>Op Type</th><th>FLOPs</th><th>Count</th><th>%</th></tr></thead>';
html += '<tbody>';
for (var i = 0; i < data.perOpType.length; i++) {
var entry = data.perOpType[i];
html += '<tr>';
html += '<td>' + this._escapeHtml(entry.opType) + '</td>';
html += '<td>' + this._escapeHtml(entry.formattedFlops) + '</td>';
html += '<td>' + entry.count + '</td>';
html += '<td>' + entry.percentage.toFixed(1) + '%</td>';
html += '</tr>';
}
html += '</tbody></table>';
}
// Unsupported ops
if (data.unsupportedOps && data.unsupportedOps.length > 0) {
html += '<div class="small text-muted">';
html += '<i class="fas fa-info-circle me-1"></i>';
html += 'Unsupported ops (N/A): ' + data.unsupportedOps.map(this._escapeHtml).join(', ');
html += '</div>';
}
html += '</div>';
this._container.innerHTML = html;
}
/**
* Get the last computed result.
* @returns {FlopsResult|null}
*/
getResult() {
return this._result;
}
/**
* Clear the display and reset internal state.
*/
clear() {
this._result = null;
if (this._container) {
this._container.innerHTML = '';
}
}
/**
* Destroy and clean up.
*/
destroy() {
this.clear();
this._container = null;
}
// βββ Private Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Escape HTML special characters.
* @param {string} str
* @returns {string}
*/
_escapeHtml(str) {
if (typeof str !== 'string') return String(str);
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
}
window.FlopsEstimator = FlopsEstimator;
|