gx
chenyc
2025-06-12 7b72ac13a83764a662159d4a49b7fffb90476ecb
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
/**
 * @license
 * Copyright 2018 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */
 
import {BackendTimer} from './backends/backend';
import {Tensor} from './tensor';
import {NamedTensorMap} from './tensor_types';
import {DataType, DataTypeMap, TypedArray} from './types';
import * as util from './util';
 
export class Profiler {
  constructor(private backendTimer: BackendTimer, private logger?: Logger) {
    if (logger == null) {
      this.logger = new Logger();
    }
  }
 
  profileKernel(kernelName: string, inputs: NamedTensorMap, f: () => Tensor[]):
      Tensor[] {
    let outputs: Tensor[];
    const holdResultWrapperFn = () => {
      outputs = f();
    };
    const timer = this.backendTimer.time(holdResultWrapperFn);
 
    outputs.forEach(r => {
      // Dangling promise here because we don't want to propagate up
      // asynchronicity.
      r.data().then(vals => {
        checkComputationForErrors(vals, r.dtype, kernelName);
 
        timer.then(timing => {
          let extraInfo = '';
          if (timing.getExtraProfileInfo != null) {
            extraInfo = timing.getExtraProfileInfo();
          }
 
          this.logger.logKernelProfile(
              kernelName, r, vals, timing.kernelMs, inputs, extraInfo);
        });
      });
    });
 
    return outputs;
  }
}
 
export function checkComputationForErrors<D extends DataType>(
    vals: DataTypeMap[D], dtype: D, kernelName: string): boolean {
  if (dtype !== 'float32') {
    // Only floating point computations will generate NaN values
    return false;
  }
  for (let i = 0; i < vals.length; i++) {
    const num = vals[i] as number;
    if (isNaN(num) || !isFinite(num)) {
      // Throwing custom exception so behavior is testable.
      console.warn(`Found ${num} in the result of '${kernelName}'`);
      return true;
    }
  }
  return false;
}
 
export class Logger {
  logKernelProfile(
      name: string, result: Tensor, vals: TypedArray,
      timeMs: number|{error: string}, inputs: NamedTensorMap,
      extraInfo?: string) {
    const time = typeof timeMs === 'number' ? util.rightPad(`${timeMs}ms`, 9) :
                                              timeMs['error'];
    const paddedName = util.rightPad(name, 25);
    const rank = result.rank;
    const size = result.size;
    const shape = util.rightPad(result.shape.toString(), 14);
    let inputShapesDescription = '';
 
    for (const name in inputs) {
      const input = inputs[name];
      // The input might be a non-tensor (e.g HTMLImageElement), in which case
      // we claim the output shape as input shape.
      const inputShape = input.shape || result.shape;
      const inputRank = inputShape.length;
      inputShapesDescription +=
          `${name}: ${inputRank}D ${inputRank > 0 ? inputShape : ''} `;
    }
 
    console.log(
        `%c${paddedName}\t%c${time}\t%c${rank}D ${shape}\t%c${size}\t%c${
            inputShapesDescription}\t%c${extraInfo}`,
        'font-weight:bold', 'color:red', 'color:blue', 'color: orange',
        'color: green', 'color: steelblue');
  }
}