Repository navigation
Expand file tree
/
Copy pathmlcompute.js
More file actions
71 lines (56 loc) · 1.66 KB
/
Copy pathmlcompute.js
File metadata and controls
71 lines (56 loc) · 1.66 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
// @ts-check
import "@nativescript/macos-node-api";
objc.import("MLCompute");
const batchSize = 1;
const shape = [batchSize, 28, 28, 1];
const imageSize = shape[1] * shape[2];
const layerSize = 128;
const tInput = MLCTensor.tensorWithShapeDataType(shape, MLCDataType.Float32);
const tWeights = MLCTensor.tensorWithShapeRandomInitializerTypeDataType(
[1, imageSize, layerSize, 1],
MLCRandomInitializerType.GlorotUniform,
MLCDataType.Float32
);
const tBiases = MLCTensor.tensorWithShapeRandomInitializerTypeDataType(
[1, layerSize, 1, 1],
MLCRandomInitializerType.GlorotUniform,
MLCDataType.Float32
);
const input = new Float32Array(imageSize * batchSize).fill(1);
const dataInput = MLCTensorData.dataWithBytesNoCopyLength(
input,
input.byteLength
);
const graph = MLCGraph.new();
const denseLayer = MLCFullyConnectedLayer.layerWithWeightsBiasesDescriptor(
tWeights,
tBiases,
MLCConvolutionDescriptor.descriptorWithKernelWidthKernelHeightInputFeatureChannelCountOutputFeatureChannelCount(
layerSize,
imageSize,
imageSize,
layerSize
)
);
if (!denseLayer) {
throw new Error("denseLayer is null");
}
graph.nodeWithLayerSources(denseLayer, [tInput]);
const device = MLCDevice.gpuDevice();
if (!device) {
throw new Error("device is null");
}
const inference = MLCInferenceGraph.graphWithGraphObjects([graph]);
inference.addInputs({ input: tInput });
inference.compileWithOptionsDevice(
MLCGraphCompilationOptions.DebugLayers,
device
);
inference.executeWithInputsDataBatchSizeOptionsCompletionHandler(
{ input: dataInput },
batchSize,
MLCExecutionOptions.Synchronous,
(output, error, time) => {
console.log(output, error, time);
}
);