ControlVector constructor

ControlVector(
  1. Map<int, Float32List> directions, {
  2. required int hiddenSize,
  3. ControlMode mode = ControlMode.add,
  4. double scale = 1.0,
  5. int firstLayer = 0,
  6. int? lastLayer,
})

Directions by zero-based layer, each of hiddenSize finite floats; layers without one are left alone. Only layers from firstLayer to lastLayer (inclusive; null: no upper bound) are steered. scale must be finite.

In ControlMode.project a direction of zero norm is an error: it has no unit direction to remove.

Implementation

ControlVector(
  Map<int, Float32List> directions, {
  required this.hiddenSize,
  this.mode = ControlMode.add,
  this.scale = 1.0,
  this.firstLayer = 0,
  this.lastLayer,
}) : directions = Map.unmodifiable({
       for (final e in directions.entries)
         e.key: Float32List.fromList(e.value),
     }) {
  if (hiddenSize <= 0) {
    throw ArgumentError.value(hiddenSize, 'hiddenSize', 'must be positive');
  }
  if (!scale.isFinite) {
    throw ArgumentError.value(scale, 'scale', 'must be finite');
  }
  if (firstLayer < 0 || (lastLayer != null && lastLayer! < firstLayer)) {
    throw ArgumentError(
      'invalid layer range $firstLayer..${lastLayer ?? ''}',
    );
  }
  for (final MapEntry(key: layer, value: d) in this.directions.entries) {
    if (layer < 0) {
      throw ArgumentError.value(layer, 'layer', 'must not be negative');
    }
    if (d.length != hiddenSize || d.any((v) => !v.isFinite)) {
      throw ArgumentError(
        'direction for layer $layer must contain $hiddenSize finite values',
      );
    }
    final Float32List applied;
    if (mode == ControlMode.add) {
      applied = Float32List(hiddenSize);
      for (var j = 0; j < hiddenSize; j++) {
        applied[j] = scale * d[j];
      }
      if (applied.any((v) => !v.isFinite)) {
        throw ArgumentError('scale $scale overflows layer $layer in float32');
      }
    } else {
      final norm = _norm(d);
      if (norm == 0 || !norm.isFinite) {
        throw ArgumentError(
          'direction for layer $layer has no unit direction to project out',
        );
      }
      applied = Float32List(hiddenSize);
      for (var j = 0; j < hiddenSize; j++) {
        applied[j] = d[j] / norm;
      }
    }
    _applied[layer] = applied;
  }
}