Jhnony/Mobilekernelbench huggingface dataset:
# Reduction / ReduceL1_negative_axes_keepdims
import torch
import torch.nn as nn
from typing import List, Optional


class Model(nn.Module):
    """
    A model that computes L1 norm (sum of absolute values) reduction.
    
    Number of inputs: 1
    Implementation type: direct
    
    Semantics:
        Computes the L1 norm of the input tensor along specified axes.
        L1 norm is the sum of absolute values: ||x||₁ = Σ|xᵢ|
        
        Supports:
        - Negative axis indices (e.g., -1 for last dimension)
        - keepdims option to preserve reduced dimensions
    
    Args:
        axes: Axes to reduce over (can be negative), default -1
        keepdims: Whether to keep reduced dimensions (1/True or 0/False)
    """
    
    def __init__(self, axes: int = -1, keepdims: int = 1):
        """
        Initialize the ReduceL1 model.
        
        Args:
            axes: Axis to reduce over (default: -1, last dimension)
            keepdims: Keep reduced dimensions if 1/True (default: 1)
        """
        super(Model, self).__init__()
        self.axes = axes
        self.keepdims = bool(keepdims)
    
    def forward(self, data: torch.Tensor) -> torch.Tensor:
        """
        Forward pass
        
        Args:
            data: Input tensor
        
        Returns:
            Tensor with L1 norm computed along specified axes
        """
        # Compute L1 norm (sum of absolute values)
        return torch.norm(data, p=1, dim=self.axes, keepdim=self.keepdims)


# ======== Example input configuration ========

dim1 = 8
dim2 = 64
dim3 = 64
default_axes = -1
default_keepdims = 1

def get_inputs():
    torch.manual_seed(42)
    data = torch.randn(dim1, dim2, dim3)
    return [data]

def get_init_inputs():
    return [default_axes, default_keepdims]
# Reduction / ReduceL2
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ReduceL2 算子 - PyTorch 实现

ONNX Opset Version: 18
Domain: ai.onnx
Category: reduction
Implementation Strategy: api_with_dim_handling

语义分析:
    标准算子实现
    
自动生成时间: 2026-01-21 23:31:59
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from typing import Optional, List, Tuple, Any

class Model(nn.Module):
    """
    ReduceL2 算子实现
    
    Computes the L2 norm of the input tensor's elements along the provided axes. The resulting
    
    Inputs:
        data: T (Single)
        axes: tensor(int64) (Optional)
    
    Outputs:
        reduced: T (Single)
    
    Attributes:
        noop_with_empty_axes: int (可选, default=0)
        keepdims: int (可选, default=1)
    
    Semantics:
        标准算子实现
    """
    
    def __init__(self, noop_with_empty_axes: int = 0, keepdims: int = 1):
        super(Model, self).__init__()
        self.noop_with_empty_axes = noop_with_empty_axes
        self.keepdims = keepdims
    
    def forward(self, data: torch.Tensor, axes: Optional[torch.Tensor] = None) -> torch.Tensor:
        """
        ReduceL2 的 forward 实现
        """
        # 处理维度参数
        axes = self.axes if hasattr(self, 'axes') and self.axes is not None else None
        keepdims = self.keepdims if hasattr(self, 'keepdims') else False
        
        if axes is not None:
            # 转换为 tuple 或 int
            dim = tuple(axes) if isinstance(axes, list) else axes
            return torch.norm(data, dim=dim, keepdim=keepdims)
        else:
            # 全局归约，不传 keepdim
            return torch.norm(data)

def get_inputs():
    """
    生成测试输入
    
    根据算子约束生成合法范围内的输入张量
    """
    data = torch.randn(2, 3, 4)
    return [data]

def get_init_inputs():
    """
    获取初始化参数
    
    返回用于初始化 Model 类的属性值列表
    """
    return [0, 1]

if __name__ == "__main__":
    model = Model(*get_init_inputs())
    inputs = get_inputs()
    
    print("=" * 60)
    print(f"ReduceL2 算子测试")
    print("=" * 60)
    
    try:
        with torch.no_grad():
            outputs = model(*inputs)
        
        print(f"\n输入数量: {len(inputs)}")
        for i, inp in enumerate(inputs):
            print(f"  Input {i}: shape={inp.shape}, dtype={inp.dtype}")
        
        if isinstance(outputs, (list, tuple)):
            print(f"\n输出数量: {len(outputs)}")
            for i, out in enumerate(outputs):
                print(f"  Output {i}: shape={out.shape}, dtype={out.dtype}")
        else:
            print(f"\n输出: shape={outputs.shape}, dtype={outputs.dtype}")
        
        print("\n✅ 测试通过！")
    except NotImplementedError as e:
        print(f"\n⚠️  算子尚未实现: {e}")
    except Exception as e:
        print(f"\n❌ 测试失败: {e}")
# Reduction / ReduceL2_2d_input
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    ReduceL2 on 2D input
    """
    def __init__(self, axes: int, keepdims: int = 0):
        super(Model, self).__init__()
        self.axes = axes
        self.keepdims = keepdims
    
    def forward(self, data: torch.Tensor) -> torch.Tensor:
        """
        L2 norm over 2D tensor
        
        Args:
            data: 2D input tensor
            
        Returns:
            Tensor with specified dimension reduced
        """
        return torch.norm(data, dim=self.axes, keepdim=bool(self.keepdims))

rows = 64
cols = 128
axes = 1
keepdims = 0

def get_inputs():
    data = torch.randn(rows, cols)
    return [data]

def get_init_inputs():
    return [axes, keepdims]
# Reduction / ReduceL2_keepdims
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    ReduceL2 with keeping dimensions
    """
    def __init__(self, axes: int, keepdims: int = 1):
        super(Model, self).__init__()
        self.axes = axes
        self.keepdims = True
    
    def forward(self, data: torch.Tensor) -> torch.Tensor:
        """
        L2 norm over specified dimension while keeping it as size 1
        
        Args:
            data: Input tensor
            
        Returns:
            Tensor with specified dimension kept as 1 after L2 norm
        """
        return torch.norm(data, dim=self.axes, keepdim=self.keepdims)

axes = 1

def get_inputs():
    data = torch.randn(2, 3, 4)
    return [data]

def get_init_inputs():
    return [axes]
# Reduction / ReduceL2_multiple_axes
import torch
import torch.nn as nn
from typing import Tuple

class Model(nn.Module):
    """
    ReduceL2 over multiple axes
    """
    def __init__(self, axes: Tuple[int, ...], keepdims: int = 0):
        super(Model, self).__init__()
        self.axes = axes
        self.keepdims = keepdims
    
    def forward(self, data: torch.Tensor) -> torch.Tensor:
        """
        L2 norm over multiple specified dimensions
        
        Args:
            data: Input tensor
            
        Returns:
            Tensor with L2 norm over multiple dimensions
        """
        return torch.norm(data, dim=self.axes, keepdim=bool(self.keepdims))

axes = (0, 2)
keepdims = 0

def get_inputs():
    data = torch.randn(2, 3, 4)
    return [data]

def get_init_inputs():
    return [axes, keepdims]
# Reduction / ReduceLogSumExp
import torch
import torch.nn as nn
from typing import List, Optional


class Model(nn.Module):
    """
    A model that computes the log sum of exponentials along specified axes.
    
    Number of inputs: 1
    Implementation type: direct
    
    Semantics:
        Computes log(sum(exp(x))) along the provided axes.
        This is numerically stable implementation of the operation.
        axes: Fixed reduction dimensions specified at initialization.
        keepdims: Whether to keep reduced dimensions (1) or not (0).
    """
    
    def __init__(self, axes: Optional[List[int]] = None, keepdims: int = 1):
        """
        Initialize the ReduceLogSumExp model.
        
        Args:
            axes: List of axes to reduce along (None means reduce all)
            keepdims: Whether to keep reduced dimensions (0 or 1)
        """
        super(Model, self).__init__()
        self.axes = axes
        self.keepdims = bool(keepdims)
    
    def forward(self, data: torch.Tensor) -> torch.Tensor:
        """
        Forward pass
        
        Args:
            data: Input tensor to reduce
        
        Returns:
            Reduced tensor with log-sum-exp applied
        """
        if self.axes is not None:
            # Reduce along specified axes
            dim = tuple(self.axes)
            return torch.logsumexp(data, dim=dim, keepdim=self.keepdims)
        else:
            # Reduce over all dimensions
            result = torch.logsumexp(data.flatten(), dim=0)
            if self.keepdims:
                # Reshape to maintain original rank with all dims = 1
                return result.view([1] * data.ndim)
            else:
                return result


# ======== Example input configuration ========

dim1 = 2
dim2 = 3
dim3 = 4
reduce_axes = [0, 2]  # Axes to reduce along
keepdims = 1

def get_inputs():
    data = torch.randn(dim1, dim2, dim3)
    return [data]

def get_init_inputs():
    return [reduce_axes, keepdims]
# Reduction / ReduceLogSumExp_2d_input
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    ReduceLogSumExp on 2D input
    """
    def __init__(self, axes: int, keepdims: int = 0):
        super(Model, self).__init__()
        self.axes = axes
        self.keepdims = keepdims
    
    def forward(self, data: torch.Tensor) -> torch.Tensor:
        """
        LogSumExp over 2D tensor
        
        Args:
            data: 2D input tensor
            
        Returns:
            Tensor with specified dimension reduced
        """
        return torch.logsumexp(data, dim=self.axes, keepdim=bool(self.keepdims))

rows = 64
cols = 128
axes = 1
keepdims = 0

def get_inputs():
    data = torch.randn(rows, cols)
    return [data]

def get_init_inputs():
    return [axes, keepdims]
# Reduction / ReduceLogSumExp_keepdims
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    ReduceLogSumExp with keeping dimensions
    """
    def __init__(self, axes: int, keepdims: int = 1):
        super(Model, self).__init__()
        self.axes = axes
        self.keepdims = True
    
    def forward(self, data: torch.Tensor) -> torch.Tensor:
        """
        LogSumExp over specified dimension while keeping it as size 1
        
        Args:
            data: Input tensor
            
        Returns:
            Tensor with specified dimension kept as 1 after LogSumExp
        """
        return torch.logsumexp(data, dim=self.axes, keepdim=self.keepdims)

axes = 1

def get_inputs():
    data = torch.randn(2, 3, 4)
    return [data]

def get_init_inputs():
    return [axes]
# Reduction / ReduceLogSumExp_multiple_axes
import torch
import torch.nn as nn
from typing import Tuple

class Model(nn.Module):
    """
    ReduceLogSumExp over multiple axes
    """
    def __init__(self, axes: Tuple[int, ...], keepdims: int = 0):
        super(Model, self).__init__()
        self.axes = axes
        self.keepdims = keepdims
    
    def forward(self, data: torch.Tensor) -> torch.Tensor:
        """
        LogSumExp over multiple specified dimensions
        
        Args:
            data: Input tensor
            
        Returns:
            Tensor with LogSumExp over multiple dimensions
        """
        return torch.logsumexp(data, dim=self.axes, keepdim=bool(self.keepdims))

axes = (0, 2)
keepdims = 0

def get_inputs():
    data = torch.randn(2, 3, 4)
    return [data]

def get_init_inputs():
    return [axes, keepdims]
# Reduction / ReduceMax
import torch
import torch.nn as nn

class Model(nn.Module):
    def __init__(self, dim: int, keepdim: bool = False):
        super(Model, self).__init__()
        self.dim = dim
        self.keepdim = keepdim

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return torch.max(x, dim=self.dim, keepdim=self.keepdim).values

batch_size = 16
input_shape = (128, 128, 64)
dim = 1
keepdim = False

# ======== Example input configuration ========
def get_inputs() -> list:
    return [torch.rand(batch_size, *input_shape)]

def get_init_inputs():
    return [dim, keepdim]
# Reduction / ReduceMax_empty_axes
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    ReduceMax over all axes (returns scalar)
    """
    def __init__(self):
        super(Model, self).__init__()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Maximum of all elements in the tensor
        
        Args:
            x: Input tensor
            
        Returns:
            Scalar tensor with maximum of all elements
        """
        return torch.max(x)

batch_size = 16
input_shape = (128, 128, 64)

def get_inputs() -> list:
    return [torch.rand(batch_size, *input_shape)]

def get_init_inputs():
    return []
# Reduction / ReduceMax_with_negative_values
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    ReduceMax with negative values in input
    """
    def __init__(self, dim: int, keepdim: bool = False):
        super(Model, self).__init__()
        self.dim = dim
        self.keepdim = keepdim

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Maximum over specified dimension with negative values
        
        Args:
            x: Input tensor (may contain negative values)
            
        Returns:
            Tensor with maximum values
        """
        return torch.max(x, dim=self.dim, keepdim=self.keepdim).values

batch_size = 16
input_shape = (128, 128, 64)
dim = 1
keepdim = False

def get_inputs() -> list:
    # Generate values in range [-1, 1]
    return [torch.randn(batch_size, *input_shape)]

def get_init_inputs():
    return [dim, keepdim]
# Reduction / ReduceMean
import torch
import torch.nn as nn

class Model(nn.Module):
    def __init__(self, dim: int, keepdim: bool = False):
        super(Model, self).__init__()
        self.dim = dim
        self.keepdim = keepdim

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return torch.mean(x, dim=self.dim, keepdim=self.keepdim)

batch_size = 16
input_shape = (128, 128, 64)
dim = 1
keepdim = False

# ======== Example input configuration ========
def get_inputs() -> list:
    return [torch.rand(batch_size, *input_shape)]

def get_init_inputs():
    return [dim, keepdim]
# Reduction / ReduceMean_keepdims
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    ReduceMean with keeping dimensions
    """
    def __init__(self, dim: int, keepdim: bool = True):
        super(Model, self).__init__()
        self.dim = dim
        self.keepdim = True

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Mean over specified dimension while keeping it as size 1
        
        Args:
            x: Input tensor
            
        Returns:
            Tensor with specified dimension kept as 1 after averaging
        """
        return torch.mean(x, dim=self.dim, keepdim=self.keepdim)

batch_size = 8
input_shape = (64, 256, 256)
dim = 1

def get_inputs() -> list:
    return [torch.rand(batch_size, *input_shape)]

def get_init_inputs():
    return [dim]
# Reduction / ReduceMean_multiple_axes
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    ReduceMean over spatial dimensions (Global Average Pooling)
    """
    def __init__(self, dims: tuple = (2, 3), keepdim: bool = False):
        super(Model, self).__init__()
        self.dims = dims
        self.keepdim = keepdim

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Mean over spatial dimensions (height and width)
        
        Args:
            x: Input tensor of shape (batch, channels, height, width)
            
        Returns:
            Tensor with spatial dimensions reduced
        """
        return torch.mean(x, dim=self.dims, keepdim=self.keepdim)

batch_size = 8
input_shape = (128, 64, 64)
dims = (2, 3)
keepdim = False

def get_inputs() -> list:
    return [torch.rand(batch_size, *input_shape)]

def get_init_inputs():
    return [dims, keepdim]
# Reduction / ReduceMin
import torch
import torch.nn as nn

class Model(nn.Module):
    def __init__(self, dim: int, keepdim: bool = False):
        super(Model, self).__init__()
        self.dim = dim
        self.keepdim = keepdim

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return torch.min(x, dim=self.dim, keepdim=self.keepdim).values

batch_size = 8
input_shape = (64, 64, 64)    
dim = 1
keepdim = False

# ======== Example input configuration ========
def get_inputs() -> list:
    return [torch.rand(batch_size, *input_shape)]

def get_init_inputs():
    return [dim, keepdim]
# Reduction / ReduceMin_empty_axes
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    ReduceMin over all axes (returns scalar)
    """
    def __init__(self):
        super(Model, self).__init__()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Minimum of all elements in the tensor
        
        Args:
            x: Input tensor
            
        Returns:
            Scalar tensor with minimum of all elements
        """
        return torch.min(x)

batch_size = 8
input_shape = (64, 32, 32)

def get_inputs() -> list:
    return [torch.rand(batch_size, *input_shape)]

def get_init_inputs():
    return []
# Reduction / ReduceMin_with_negative_values
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    ReduceMin with negative values in input
    """
    def __init__(self, dim: int, keepdim: bool = False):
        super(Model, self).__init__()
        self.dim = dim
        self.keepdim = keepdim

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Minimum over specified dimension with negative values
        
        Args:
            x: Input tensor (may contain negative values)
            
        Returns:
            Tensor with minimum values (likely negative)
        """
        return torch.min(x, dim=self.dim, keepdim=self.keepdim).values

batch_size = 16
input_shape = (128, 128, 64)
dim = 1
keepdim = False

def get_inputs() -> list:
    # Generate values in range [-1, 1]
    return [torch.rand(batch_size, *input_shape) * 2 - 1]

def get_init_inputs():
    return [dim, keepdim]
# Reduction / ReduceProd
import torch
import torch.nn as nn

class Model(nn.Module):
    def __init__(self, dim: int, keepdim: bool = False):
        super(Model, self).__init__()
        self.dim = dim
        self.keepdim = keepdim

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return torch.prod(x, dim=self.dim, keepdim=self.keepdim)

batch_size = 8
input_shape = (64, 32, 32)    
dim = 1
keepdim = False

# ======== Example input configuration ========
def get_inputs() -> list:
    return [torch.rand(batch_size, *input_shape)]

def get_init_inputs():
    return [dim, keepdim]
# Reduction / ReduceProd_1d
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    ReduceProd on 1D tensor
    """
    def __init__(self, dim: int = 0, keepdim: bool = False):
        super(Model, self).__init__()
        self.dim = dim
        self.keepdim = keepdim

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Product over 1D tensor
        
        Args:
            x: 1D input tensor
            
        Returns:
            Scalar or 1D tensor with single element
        """
        return torch.prod(x, dim=self.dim, keepdim=self.keepdim)

vector_size = 4096
dim = 0
keepdim = False

def get_inputs() -> list:
    return [torch.rand(vector_size) * 0.5 + 0.5]

def get_init_inputs():
    return [dim, keepdim]
# Reduction / ReduceProd_keepdims
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    ReduceProd with keeping dimensions
    """
    def __init__(self, dim: int, keepdim: bool = True):
        super(Model, self).__init__()
        self.dim = dim
        self.keepdim = True

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Product over specified dimension while keeping it as size 1
        
        Args:
            x: Input tensor
            
        Returns:
            Tensor with specified dimension kept as 1 after product
        """
        return torch.prod(x, dim=self.dim, keepdim=self.keepdim)

batch_size = 16
input_shape = (64, 64, 32)
dim = 1

def get_inputs() -> list:
    return [torch.rand(batch_size, *input_shape) * 0.1 + 0.9]

def get_init_inputs():
    return [dim]
# Reduction / ReduceSum
import torch
import torch.nn as nn

class Model(nn.Module):
    def __init__(self, dim: int, keepdim: bool = False):
        super(Model, self).__init__()
        self.dim = dim
        self.keepdim = keepdim

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return torch.sum(x, dim=self.dim, keepdim=self.keepdim)

batch_size = 8
input_shape = (128, 64, 32)    
dim = 1
keepdim = False

# ======== Example input configuration ========
def get_inputs() -> list:
    return [torch.rand(batch_size, *input_shape)]

def get_init_inputs():
    return [dim, keepdim]
# Reduction / ReduceSum_empty_axes
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    ReduceSum over all axes (returns scalar)
    """
    def __init__(self):
        super(Model, self).__init__()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Sum all elements in the tensor
        
        Args:
            x: Input tensor
            
        Returns:
            Scalar tensor with sum of all elements
        """
        return torch.sum(x)

batch_size = 8
input_shape = (256, 64, 64)

def get_inputs() -> list:
    return [torch.rand(batch_size, *input_shape)]

def get_init_inputs():
    return []
# Reduction / ReduceSum_multiple_axes
import torch
import torch.nn as nn
from typing import List, Tuple, Union

class Model(nn.Module):
    """
    ReduceSum over multiple axes
    """
    def __init__(self, dims: Union[List[int], Tuple[int, ...]], keepdim: bool = False):
        super(Model, self).__init__()
        self.dims = dims
        self.keepdim = keepdim

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Sum over multiple specified dimensions
        
        Args:
            x: Input tensor
            
        Returns:
            Tensor with summation over multiple dimensions
        """
        return torch.sum(x, dim=self.dims, keepdim=self.keepdim)

batch_size = 16
input_shape = (128, 64, 64)
dims = (1, 2)  # Sum over both spatial dimensions
keepdim = False

def get_inputs() -> list:
    return [torch.rand(batch_size, *input_shape)]

def get_init_inputs():
    return [dims, keepdim]
# Tensor / Cast
import torch
import torch.nn as nn

_DTYPE_MAP = {
    "float32": torch.float32,
    "float16": torch.float16,
    "float64": torch.float64,
    "int32": torch.int32,
    "int64": torch.int64,
    "bool": torch.bool,
}

class Model(nn.Module):
    """
    Cast: cast the input tensor to a target dtype.

    Semantics (ONNX Cast-like):
        y = Cast(x, to=target_dtype)

    Parameters:
        to_dtype (str): one of {"float32","float16","float64","int32","int64","bool"}
    """

    def __init__(self, to_dtype: str = "int32"):
        super(Model, self).__init__()
        assert to_dtype in _DTYPE_MAP, f"Unsupported dtype: {to_dtype}"
        self.to_dtype_name = to_dtype
        self.to_dtype = _DTYPE_MAP[to_dtype]

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return x.to(self.to_dtype)


# ======== Example input configuration ========

batch_size = 8
input_shape = (512, 256)

def get_inputs():
    x = torch.randn(batch_size, *input_shape, dtype=torch.float32)
    return [x]

def get_init_inputs():
    return ["int32"]
# Tensor / Clip
import torch
import torch.nn as nn

class Model(nn.Module):
    def __init__(self, min_val: float = 0.0, max_val: float = 1.0):
        super().__init__()
        self.min_val = min_val
        self.max_val = max_val

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return torch.clamp(x, min=self.min_val, max=self.max_val)

batch_size = 16
input_shape = (32, 128, 256)
min_val = -0.5
max_val = 0.5

def get_inputs() -> list:
    return [torch.randn(batch_size, *input_shape)]

def get_init_inputs():
    return [min_val, max_val]