random static method

Tensor random(
  1. List<int> shape, {
  2. double scale = 0.005,
})

Implementation

static Tensor random(List<int> shape, {double scale = 0.005}) {
  final int rows = shape[0];
  final int cols = shape.length > 1 ? shape[1] : 1;
  final int size = rows * cols;

  final int nIn = shape[0];
  final int nOut = shape[shape.length - 1];
  final double limit = math.sqrt(6.0 / (nIn + nOut));

  final math.Random rng = math.Random();

  // 1. Allocate native memory (Pointer<Float>)
  final ffi.Pointer<ffi.Float> nativeBuffer = calloc<ffi.Float>(size);

  // 2. Fill the native buffer with random values
  for (int i = 0; i < size; i++) {
    // Approximating a small normal distribution
    // nativeBuffer[i] = (rng.nextDouble() * 2 - 1) * scale;

    nativeBuffer[i] = (rng.nextDouble() * 2 - 1) * limit;
  }

  // 3. Pass the pointer to C++
  // createTensor should be: Pointer<Void> Function(Int32, Int32, Pointer<Float>)
  final handle = engine.createTensor(rows, cols, nativeBuffer);

  // 4. IMPORTANT: Free the native memory after the GPU has copied it
  calloc.free(nativeBuffer);

  return Tensor._raw(handle, shape);
}