Demo

jaxguidesdocs_nnxflax

NNX Demo

[1]

[1] NNX is Pythonic

[7]
model = MLP(
  blocks=[Block(
      linear=Linear(
            in_features=4,
            out_features=4,
            use_bias=True,
            dtype=None,
            param_dtype=<class 'jax.numpy.float32'>,
            precision=None,
            kernel_init=<function variance_scaling.<locals>.init at 0x28ae86dc0>,
            bias_init=<function zeros at 0x122d39f70>,
            dot_general=<function dot_general at 0x1218459d0>
          ),
      bn=BatchNorm(
            num_features=4,
  
...

Because NNX Modules contain their own state, they are very easily to inspect:

[9]
model.count = Count(
  raw_value=1
)
model.blocks[0].linear.kernel = Param(
  raw_value=Array([[-0.80345297, -0.34071913, -0.9408296 ,  0.01005968],
         [ 0.26146442,  1.1247735 ,  0.54563737, -0.374164  ],
         [ 1.0281805 , -0.6798804 , -0.1488401 ,  0.05694951],
         [-0.44308168, -0.60587114,  0.434087  , -0.40541083]],      dtype=float32)
)

[2] Model Surgery is Intuitive

[10]
y.shape = (2, 4)

[3] Interacting with JAX is easy

[11]
state = State({
  'blocks': {
    '0': {
      'linear': {
        'kernel': Param(
          raw_value=Array([[-0.33095378,  0.67149884,  0.33700302,  0.30972847],
                 [ 0.8662822 , -0.11225506, -1.0820619 , -0.9906892 ],
                 [ 0.88298297, -0.2143851 ,  0.48143268,  0.6474548 ],
                 [-0.7710582 ,  0.3372276 ,  0.15487202,  0.6219269 ]],      dtype=float32)
        ),
        'bias': Param(
          raw_value=Array([0., 0., 0., 0.], dtype=float32)
        
...

graphdef = GraphDef(
  type=MLP,
  index=0,
  attributes=('blocks', 'count'),
  subgraphs={
    'blocks': GraphDef(
      type=list,
      index=1,
      attributes=('0', '1', '2', '3', '4'),
      subgraphs={
        '0': GraphDef(
          type=Block,
          index=2,
          attributes=('line
...
[12]
y.shape = (2, 4)
model.count.value = Array(3, dtype=int32, weak_type=True)
[7]
y.shape = (2, 4)
model.count = Array(4, dtype=int32, weak_type=True)
[14]
y.shape = (2, 4)
parent.model.count.value = Array(4, dtype=int32, weak_type=True)
[ ]