eleanor.jax.weight_quantization

eleanor.jax.weight_quantization#

class eleanor.jax.weight_quantization.QuantizedLinear(in_features, out_features, use_bias=True, dtype=None, quant_bits=8, stochastic=True, *, key)[source]#

Bases: Linear

Adapted from nn.Linear. Performs a linear transformation, and produces quantized weights when called.

Parameters:
  • in_features (int | Literal['scalar'])

  • out_features (int | Literal['scalar'])

  • use_bias (bool)

  • quant_bits (int)

  • stochastic (bool)

  • key (Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'])

__call__(x, *, key=None)[source]#
Parameters:
  • x (Array) – The input. Should be a JAX array of shape (in_features,). (Or shape () if in_features=”scalar”.)

  • key (PRNGKey) – Ignored; provided for compatibility with the rest of the Equinox API. (Keyword only argument.)

Return type:

Array

Notes

If you want to use higher order tensors as inputs (for example featuring ” “batch dimensions) then use jax.vmap. For example, for an input x of ” “shape (batch, in_features), using `python linear = eleanor.weight_quantization.QuantizedLinear(...) jax.vmap(linear)(x) ` will produce the appropriate output of shape (batch, out_features).

Returns:

  • A JAX array of shape (out_features,). (Or shape () if

  • out_features=”scalar”.)

Parameters:
  • x (Array)

  • key (Key[Array, ''] | UInt32[Array, '2'] | UInt32[Array, '4'] | None)

Return type:

Array

eleanor.jax.weight_quantization.quantize_weights(weights, num_bits=8, preserve_zero=True, preserve_max_val=False, stochastic=True, key=None)[source]#

Quantize weights to a specified bit precision. It can apply stochastic rounding using the weight value as the probability for rounding.

Parameters:
  • weights (Array) – The weights to quantize.

  • num_bits (int) – Number of bits for quantization (e.g., 8 for int8).

  • preserve_zero (bool) – Preserve zero value in the quantization.

  • preserve_max_val (bool) – preserve maximum weight value in the quantization.

  • stochastic (bool) – Apply stochastic rounding based on the weight value.

  • key (PRNGKey) – A random key is used to implement stochastic rounding. Optional in case not using stochastic rounding.

Return type:

Quantized weights.