cuda.js
Version:
CUDA bindings for Node.js
90 lines • 3.21 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GpuArray = void 0;
const memory_1 = require("./memory");
function dtypeByteSize(dtype) {
switch (dtype) {
case 'float32': return 4;
case 'float64': return 8;
case 'int32': return 4;
case 'uint8': return 1;
default: throw new Error(`Unsupported dtype: ${dtype}`);
}
}
function makeArray(dtype, ab) {
switch (dtype) {
case 'float32': return new Float32Array(ab);
case 'float64': return new Float64Array(ab);
case 'int32': return new Int32Array(ab);
case 'uint8': return new Uint8Array(ab);
default: throw new Error(`Unsupported dtype: ${dtype}`);
}
}
class GpuArray {
constructor(shapeOrData, dtype = 'float32') {
if (Array.isArray(shapeOrData)) {
this.shape = shapeOrData.slice();
this.dtype = dtype;
this.size = this.shape.reduce((a, b) => a * b, 1);
this.buffer = new memory_1.GpuBuffer(this.size * dtypeByteSize(this.dtype));
}
else {
const data = shapeOrData;
this.shape = [data.length];
// Infer dtype from typed array
if (data instanceof Float32Array)
this.dtype = 'float32';
else if (data instanceof Float64Array)
this.dtype = 'float64';
else if (data instanceof Int32Array)
this.dtype = 'int32';
else if (data instanceof Uint8Array)
this.dtype = 'uint8';
else
this.dtype = dtype;
this.size = data.length;
this.buffer = new memory_1.GpuBuffer(this.size * dtypeByteSize(this.dtype));
this.upload(data);
}
}
upload(data) {
if (data.byteLength !== this.buffer.size) {
if (data.byteLength > this.buffer.size)
throw new Error('Data larger than buffer');
}
this.buffer.upload(data);
}
download() {
const raw = this.buffer.download(); // Uint8Array
return makeArray(this.dtype, raw.buffer);
}
fill(value) {
if (this.dtype === 'uint8') {
this.buffer.memset(value & 0xFF, this.buffer.size);
}
else {
// Simple kernel fill could be added; MVP uses upload from filled host array
const bytes = dtypeByteSize(this.dtype);
const ab = new ArrayBuffer(this.size * bytes);
const arr = makeArray(this.dtype, ab);
for (let i = 0; i < this.size; ++i)
arr[i] = value;
this.upload(arr);
}
}
copy() {
const out = new GpuArray(this.shape, this.dtype);
out.buffer.copy(this.buffer, this.buffer.size);
return out;
}
add(other) {
throw new Error('Not implemented in MVP; use custom Kernel for math ops.');
}
multiply(other) {
throw new Error('Not implemented in MVP; use custom Kernel for math ops.');
}
get length() { return this.size; }
get byteLength() { return this.buffer.size; }
}
exports.GpuArray = GpuArray;
//# sourceMappingURL=gpuarray.js.map