Skip to content

Instantly share code, notes, and snippets.

@piscisaureus
Last active March 18, 2018 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piscisaureus/e4fbd49b87080eea50e90382a8f1953c to your computer and use it in GitHub Desktop.
Save piscisaureus/e4fbd49b87080eea50e90382a8f1953c to your computer and use it in GitHub Desktop.
let implementMe: any, math: any;
const compute = Symbol("compute");
const source = Symbol("source");
interface Computable {
[compute](): Promise<TensorBuffer>;
}
class TensorBuffer implements Computable {
asArrayBuffer(): ArrayBuffer { return implementMe; }
async [compute]() { return this; }
}
class AddOp implements Computable {
inputs: Tensor[];
constructor(...inputs: Tensor[]) {
this.inputs = inputs;
}
async [compute]() {
const tbufs: TensorBuffer[] = await Promise.all(
this.inputs.map(t => t[compute]()));
return math.add(...tbufs);
}
}
class MatMulOp implements Computable {
constructor(private input1: Tensor, private input2: Tensor) {}
async [compute]() {
const [tb1, tb2]: TensorBuffer[] = await Promise.all([
this.input1[compute](),
this.input2[compute]()
]);
return math.matmul(tb1, tb2);
}
}
class Tensor {
[source]: Computable;
constructor(value: Computable) {
this[source] = value;
}
add(...addend: Tensor[]): Tensor {
return new Tensor(new AddOp(this, ...addend));
}
matmul(that: Tensor): Tensor {
return new Tensor(new MatMulOp(this, that));
}
async data(): Promise<ArrayBuffer> {
return (await this[compute]()).asArrayBuffer();
}
async [compute](): Promise<TensorBuffer> {
if (!(this[source] instanceof TensorBuffer)) {
this[source] = await this[source][compute]();
}
return this[source] as TensorBuffer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment