Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 131 additions & 0 deletions python/tvm/relax/frontend/onnx/onnx_frontend.py
Original file line number Diff line number Diff line change
Expand Up @@ -5620,6 +5620,135 @@ def _impl_v1(cls, bb, inputs, attr, params):
return relax.Tuple([output, placeholder, placeholder])


class SimplifiedLayerNormalization(OnnxOpConverter):
"""Converts a microsoft contrib SimplifiedLayerNormalization node into a Relax expression."""

@classmethod
def _impl_v1(cls, bb, inputs, attr, params):
data = inputs[0]
scale = inputs[1]
bias = inputs[2] if len(inputs) > 2 and inputs[2] is not None else None
axis = attr.get("axis", -1)
epsilon = attr.get("epsilon", 1e-05)
stash_type = attr.get("stash_type", 1)

if stash_type != 1:
raise ValueError(
f"SimplifiedLayerNormalization currently only supports stash_type=1 (FLOAT), "
f"but got stash_type={stash_type}."
)

ndim = _get_known_tensor_rank(data)
if ndim is None:
raise ValueError("SimplifiedLayerNormalization requires a statically known input rank.")
axis = _normalize_constant_axes([axis], ndim, "SimplifiedLayerNormalization")[0]
axes = list(range(axis, ndim))

input_dtype = data.ty.dtype.dtype
scale_dtype = scale.ty.dtype.dtype

# Broadcast scale to the normalized shape if necessary
decompose_scale = True
if isinstance(data.ty.shape, relax.ShapeExpr) and isinstance(
scale.ty.shape, relax.ShapeExpr
):
normalized_shape = relax.ShapeExpr(data.ty.shape.values[axis:])
if tvm_ffi.structural_equal(scale.ty.shape, normalized_shape):
decompose_scale = False
elif len(scale.ty.shape) <= len(normalized_shape):
compute_broadcast_shape(scale.ty.shape.values, normalized_shape.values)
scale = relax.op.broadcast_to(scale, normalized_shape)
decompose_scale = False
else:
compute_broadcast_shape(scale.ty.shape.values, data.ty.shape.values)

# stash_type == 1 computes in float32
compute_dtype = "float32"

data_compute = (
data if input_dtype == compute_dtype else relax.op.astype(data, compute_dtype)
)
scale_compute = (
scale if scale_dtype == compute_dtype else relax.op.astype(scale, compute_dtype)
)

num_outputs = attr.get("tvm_custom", {}).get("num_outputs", 1)
full_reduce = len(axes) == ndim
use_decomposed = full_reduce or decompose_scale or num_outputs > 1

if use_decomposed:
mean_square = relax.op.mean(
relax.op.multiply(data_compute, data_compute), axis=axes, keepdims=True
)
inv_std = relax.op.rsqrt(
relax.op.add(mean_square, relax.const(epsilon, dtype=compute_dtype))
)
# Decompose to avoid the TOPI rms_norm 0-dim indexing bug
output = relax.op.multiply(relax.op.multiply(data_compute, inv_std), scale_compute)
else:
output = relax.op.nn.rms_norm(data_compute, scale_compute, axes, epsilon)

if bias is not None:
bias_compute = (
bias
if bias.ty.dtype.dtype == compute_dtype
else relax.op.astype(bias, compute_dtype)
)
output = relax.op.add(output, bias_compute)

if compute_dtype != scale_dtype:
output = relax.op.astype(output, scale_dtype)

if num_outputs == 1:
return output

return relax.Tuple([output, inv_std])


class SkipSimplifiedLayerNormalization(OnnxOpConverter):
"""Converts a microsoft contrib SkipSimplifiedLayerNormalization node into a Relax expression."""

@classmethod
def _impl_v1(cls, bb, inputs, attr, params):
data = inputs[0]
skip = inputs[1]
gamma = inputs[2]
bias = inputs[3] if len(inputs) > 3 and inputs[3] is not None else None

epsilon = attr.get("epsilon", 1e-12)
num_outputs = attr.get("tvm_custom", {}).get("num_outputs", 3)

input_dtype = data.ty.dtype.dtype
low_precision = input_dtype in ("float16", "bfloat16")
Comment thread
Netra-Srinivasan-McW marked this conversation as resolved.
Resolved
if low_precision:
data = relax.op.astype(data, "float32")
skip = relax.op.astype(skip, "float32")
gamma = relax.op.astype(gamma, "float32")
if bias is not None:
bias = relax.op.astype(bias, "float32")

data = relax.op.add(data, skip)
if bias is not None:
data = relax.op.add(data, bias)

output = relax.op.nn.rms_norm(data, gamma, axes=-1, epsilon=epsilon)

if low_precision:
output = relax.op.astype(output, input_dtype)
if num_outputs > 3:
data = relax.op.astype(data, input_dtype)

placeholder = relax.const(0, dtype="float32")
Comment thread
Netra-Srinivasan-McW marked this conversation as resolved.
Resolved

if num_outputs > 3:
# Output 4 - input_skip_bias_sum
return relax.Tuple([output, placeholder, placeholder, data])
if num_outputs == 1:
return output

return relax.Tuple([output, placeholder, placeholder])


class EmbedLayerNormalization(OnnxOpConverter):
"""Converts a microsoft contrib EmbedLayerNormalization node into a Relax expression."""

Expand Down Expand Up @@ -6898,8 +7027,10 @@ def _get_convert_map():
"BatchNormalization": BatchNormalization,
"LayerNormalization": LayerNormalization,
"RMSNormalization": RMSNormalization,
"SimplifiedLayerNormalization": SimplifiedLayerNormalization,
"GroupNormalization": GroupNormalization,
"SkipLayerNormalization": SkipLayerNormalization,
"SkipSimplifiedLayerNormalization": SkipSimplifiedLayerNormalization,
"EmbedLayerNormalization": EmbedLayerNormalization,
"InstanceNormalization": InstanceNormalization,
"MeanVarianceNormalization": MeanVarianceNormalization,
Expand Down
Loading