Hybridizing if elif and else statements in Gluon

Using hybridblock I am writing hybrid_forward as follows:-

def hybrid_forward(self, F, x):
    if F.mean(x) > 1.0:
        x = x - 1
    elif F.sum(x) < 0:
        x = F.abs(x)
    else:
        x = x + 1.0
    return x

Above code shows error that “bool” is only implemented for NDArray, not for Symbol.
I know how to use mx.symbol.where, but I want to implement that in gluon and then hybridize it.
Any suggestions would be great.

Unfortunately, you will have to rewrite your code, but you can you use contrib.cond function, so the code is not too bad.

Here is an example of rewriting your code making it hybridizable:

import mxnet as mx
from mxnet.gluon import HybridBlock
from mxnet.initializer import Xavier


class MyBlock(HybridBlock):
    def __init__(self):
        super().__init__()

    def hybrid_forward(self, F, x, **kwargs):
        result = F.contrib.cond(F.mean(x) > 1,
                                lambda: x - 1,
                                lambda: F.contrib.cond(F.sum(x) < 0,
                                                       lambda: F.abs(x),
                                                       lambda: x + 1))
        return result


block = MyBlock()
block.initialize(Xavier())
block.hybridize()

input = mx.nd.array([0, 1, 1])
output = block(input)
print(output)
2 Likes

Thanks for helping. But how long contrib is gonna stay in mxnet because at the documentation page of contrib I can see something like this:
“Warning
This package contains experimental APIs and may change in the near future.”

It is hard to say, of course, but I think regarding this particular functionality the worst thing that may happen is it will be included into the core of MXNet. That would lead to change of the package name - meaning you will have to replace the name of the package it in the code. Other than that, I believe that this functionality is not going to disappear.