-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(model-runtime): add tfjs as a backend (#88)
* feat(model): add tfjs bno model This commit adds a tensorflowjs format bno model which is originally developed in pytorch and has the following export path: pytorch->ONNX-> tensorflow SavedModel-> tensorflowjs. Note that the model has not been test yet. This commit also include @tensorflow/tfjs as a dependency. * refactor(modelService): rename it to ONNXService Signed-off-by: Bill ZHANG <[email protected]> * feat(tfjsService): initialize tensorflowjs backend Signed-off-by: Bill ZHANG <[email protected]> * perf(tfjs-runtime): use tensor op instead of array iter Signed-off-by: Bill ZHANG <[email protected]> * feat(model): update modelService interface update it to reflect newest code change for tfjs runtime Signed-off-by: Bill ZHANG <[email protected]> * fix(tfjs-runtime): attempt to fix the memory leak Signed-off-by: Bill ZHANG <[email protected]> * refactor(modelService): add factory method to create model service Signed-off-by: Bill ZHANG <[email protected]> --------- Signed-off-by: Bill ZHANG <[email protected]>
- Loading branch information
Showing
12 changed files
with
571 additions
and
80 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Large diffs are not rendered by default.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,218 @@ | ||
import * as tf from '@tensorflow/tfjs'; | ||
import { type Vector2 } from 'three'; | ||
import { type ModelService } from './modelService'; | ||
|
||
export class TfjsService implements ModelService { | ||
model!: tf.GraphModel; | ||
gridSize: [number, number]; | ||
batchSize: number; | ||
channelSize: number; | ||
outputChannelSize: number; | ||
mass!: tf.Tensor; | ||
fpsLimit: number; | ||
density!: tf.Variable<tf.Rank.R4>; | ||
velocity!: tf.Variable<tf.Rank.R4>; | ||
pressure!: tf.TensorBuffer<tf.Rank.R4>; | ||
|
||
isPaused: boolean; | ||
curFrameCountbyLastSecond: number; | ||
private outputCallback!: (data: Float32Array) => void; | ||
|
||
constructor() { | ||
this.gridSize = [0, 0]; | ||
this.batchSize = 0; | ||
this.isPaused = true; | ||
this.channelSize = 0; | ||
this.outputChannelSize = 0; | ||
this.mass = tf.variable(tf.zeros([0])); | ||
this.fpsLimit = 30; | ||
this.curFrameCountbyLastSecond = 0; | ||
} | ||
|
||
static async createService( | ||
modelPath: string, | ||
gridSize: [number, number] = [64, 64], | ||
batchSize = 1, | ||
channelSize = 5, | ||
outputChannelSize = 3, | ||
fpsLimit = 15, | ||
): Promise<TfjsService> { | ||
const service = new TfjsService(); | ||
service.model = await tf.loadGraphModel(modelPath); | ||
service.gridSize = gridSize; | ||
service.batchSize = batchSize; | ||
service.channelSize = channelSize; | ||
service.outputChannelSize = outputChannelSize; | ||
service.fpsLimit = fpsLimit; | ||
|
||
return service; | ||
} | ||
|
||
loadDataArray(array: number[][][][]): void { | ||
console.log(array); | ||
const arrayTensor = tf.tensor4d( | ||
array, | ||
[this.batchSize, ...this.gridSize, this.channelSize], | ||
'float32', | ||
); | ||
// 0: partial density | ||
// 1, 2: partial velocity | ||
// 3, 4: Pressure | ||
const density = arrayTensor.slice( | ||
[0, 0, 0, 0], | ||
[this.batchSize, ...this.gridSize, 1], | ||
); | ||
const normalizedDensity = TfjsService.normalizeTensor(density); | ||
density.dispose(); | ||
this.density = tf.variable(normalizedDensity.maximum(0)); | ||
const velocityX = arrayTensor.slice( | ||
[0, 0, 0, 1], | ||
[this.batchSize, ...this.gridSize, 1], | ||
); | ||
const velocityY = arrayTensor.slice( | ||
[0, 0, 0, 2], | ||
[this.batchSize, ...this.gridSize, 1], | ||
); | ||
const normalizedVelocityX = TfjsService.normalizeTensor(velocityX); | ||
const normalizedVelocityY = TfjsService.normalizeTensor(velocityY); | ||
velocityX.dispose(); | ||
velocityY.dispose(); | ||
this.velocity = tf.variable( | ||
tf.concat([normalizedVelocityX, normalizedVelocityY], 3), | ||
) as tf.Variable<tf.Rank.R4>; | ||
normalizedVelocityX.dispose(); | ||
normalizedVelocityY.dispose(); | ||
const pressureX = arrayTensor.slice( | ||
[0, 0, 0, 3], | ||
[this.batchSize, ...this.gridSize, 1], | ||
); | ||
const pressureY = arrayTensor.slice( | ||
[0, 0, 0, 4], | ||
[this.batchSize, ...this.gridSize, 1], | ||
); | ||
const normalizedPressureX = TfjsService.normalizeTensor(pressureX); | ||
const normalizedPressureY = TfjsService.normalizeTensor(pressureY); | ||
pressureX.dispose(); | ||
pressureY.dispose(); | ||
this.pressure = tf | ||
.concat([normalizedPressureX, normalizedPressureY], 3) | ||
.bufferSync() as tf.TensorBuffer<tf.Rank.R4>; | ||
normalizedPressureX.dispose(); | ||
|
||
this.density = this.density.maximum(0); | ||
this.mass = this.density.sum(); | ||
this.mass.print(); | ||
} | ||
|
||
static normalizeTensor(tensor: tf.Tensor): tf.Tensor { | ||
return tf.tidy(() => { | ||
const { mean, variance } = tf.moments(tensor); | ||
return tensor.sub(mean).div(variance.sqrt()); | ||
}); | ||
} | ||
|
||
pauseSimulation(): void { | ||
this.isPaused = true; | ||
} | ||
|
||
bindOutput(callback: (data: Float32Array) => void): void { | ||
this.outputCallback = callback; | ||
} | ||
|
||
startSimulation(): void { | ||
this.isPaused = false; | ||
this.curFrameCountbyLastSecond = 0; | ||
this.fpsHeartbeat(); | ||
this.iterate(); | ||
} | ||
|
||
private fpsHeartbeat(): void { | ||
setTimeout(() => { | ||
this.curFrameCountbyLastSecond = 0; | ||
if (this.curFrameCountbyLastSecond >= this.fpsLimit) { | ||
this.startSimulation(); | ||
} else { | ||
this.fpsHeartbeat(); | ||
} | ||
}, 1000); | ||
} | ||
getInput(): tf.Tensor<tf.Rank> { | ||
const pressure = this.pressure.toTensor(); | ||
const input = tf.concat([this.density, this.velocity, pressure], 3); | ||
pressure.dispose(); | ||
return input; | ||
} | ||
private iterate(): void { | ||
if (this.isPaused) { | ||
return; | ||
} | ||
this.curFrameCountbyLastSecond += 1; | ||
const input = this.getInput(); | ||
const energy = this.velocity.square().sum(); | ||
const output = this.model?.predict(input) as tf.Tensor<tf.Rank>; | ||
// update density, velocity | ||
this.density.assign( | ||
output?.slice( | ||
[0, 0, 0, 0], | ||
[this.batchSize, ...this.gridSize, 1], | ||
) as tf.Tensor4D, | ||
); | ||
this.velocity.assign( | ||
output?.slice( | ||
[0, 0, 0, 1], | ||
[this.batchSize, ...this.gridSize, 2], | ||
) as tf.Tensor4D, | ||
); | ||
// update density, velocity | ||
const newEnergy = this.velocity.square().sum(); | ||
const energyScale = energy.div(newEnergy); | ||
energyScale.print(); | ||
|
||
this.velocity = this.velocity.mul(energyScale.sqrt()); | ||
const newMass = this.density.sum(); | ||
const massScale = this.mass.div(newMass); | ||
this.density = this.density.mul(massScale); | ||
massScale.print(); | ||
newMass.dispose(); | ||
newEnergy.dispose(); | ||
energy.dispose(); | ||
energyScale.dispose(); | ||
|
||
this.outputCallback(output?.dataSync() as Float32Array); | ||
output.dispose(); | ||
// set timeout to 0 to allow other tasks to run, like pause and apply force | ||
setTimeout(() => { | ||
this.curFrameCountbyLastSecond += 1; | ||
console.log(this.curFrameCountbyLastSecond); | ||
this.iterate(); | ||
}, 0); | ||
} | ||
|
||
updateForce(pos: Vector2, forceDelta: Vector2, batchIndex = 0): void { | ||
this.pressure.set( | ||
this.pressure.get(batchIndex, pos.x, pos.y, 0) + forceDelta.x, | ||
batchIndex, | ||
pos.x, | ||
pos.y, | ||
3, | ||
); | ||
this.pressure.set( | ||
this.pressure.get(batchIndex, pos.x, pos.y, 1) + forceDelta.y, | ||
batchIndex, | ||
pos.x, | ||
pos.y, | ||
4, | ||
); | ||
} | ||
getInputTensor(): Float32Array { | ||
const input = this.getInput(); | ||
const data = input.dataSync(); | ||
input.dispose(); | ||
return data as Float32Array; | ||
} | ||
dispose(): void { | ||
this.density.dispose(); | ||
this.velocity.dispose(); | ||
this.model.dispose(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import { type Vector2 } from 'three'; | ||
import { TfjsService } from './TfjsService'; | ||
import ONNXService from './ONNXService'; | ||
|
||
export interface ModelService { | ||
startSimulation: () => void; | ||
pauseSimulation: () => void; | ||
bindOutput: (callback: (data: Float32Array) => void) => void; | ||
getInputTensor: () => Float32Array; | ||
updateForce: (pos: Vector2, forceDelta: Vector2) => void; | ||
loadDataArray: (array: number[][][][]) => void; | ||
} | ||
|
||
// a simple factory function to create a model service | ||
export async function createModelService( | ||
modelPath: string, | ||
gridSize: [number, number] = [64, 64], | ||
batchSize = 1, | ||
channelSize = 5, | ||
outputChannelSize = 3, | ||
fpsLimit = 15, | ||
): Promise<ModelService> { | ||
// detect the model type | ||
// TODO: read the model type from the model definition file | ||
const modelType = modelPath.split('.').pop(); | ||
switch (modelType) { | ||
case 'json': | ||
return TfjsService.createService( | ||
modelPath, | ||
gridSize, | ||
batchSize, | ||
channelSize, | ||
outputChannelSize, | ||
fpsLimit, | ||
); | ||
case 'onnx': | ||
return ONNXService.createService( | ||
modelPath, | ||
gridSize, | ||
batchSize, | ||
channelSize, | ||
outputChannelSize, | ||
fpsLimit, | ||
); | ||
default: | ||
throw new Error('Invalid model type'); | ||
} | ||
} |
Oops, something went wrong.