apply method

void apply(
  1. Float32List rows,
  2. int rowCount,
  3. int layer
)

Steers rowCount rows of hiddenSize at the start of rows, the residual stream leaving layer, in place. Does nothing for a layer it does not steers. Each row is computed on its own, in a fixed order, so the result does not depend on how tokens are chunked.

Implementation

void apply(Float32List rows, int rowCount, int layer) {
  if (!steers(layer)) return;
  final v = _applied[layer]!;
  final h = hiddenSize;
  if (rowCount < 0 || rowCount * h > rows.length) {
    throw RangeError('$rowCount rows of $h exceed ${rows.length} values');
  }
  if (mode == ControlMode.add) {
    for (var t = 0; t < rowCount; t++) {
      final o = t * h;
      for (var j = 0; j < h; j++) {
        rows[o + j] = rows[o + j] + v[j];
      }
    }
    return;
  }
  for (var t = 0; t < rowCount; t++) {
    final o = t * h;
    var dot = 0.0;
    for (var j = 0; j < h; j++) {
      dot += rows[o + j] * v[j];
    }
    final c = scale * dot;
    for (var j = 0; j < h; j++) {
      rows[o + j] = rows[o + j] - c * v[j];
    }
  }
}