Skip to content

Commit 4ee9109

Browse files
authored
Merge pull request #534 from gongchensu/feature/add_silu_python_api
Add silu operator python interface and tests.
2 parents 6cef1a9 + 229ed8a commit 4ee9109

9 files changed

Lines changed: 250 additions & 0 deletions

File tree

include/infinicore/ops.hpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,5 @@
66
#include "ops/ones.hpp"
77
#include "ops/rearrange.hpp"
88
#include "ops/rms_norm.hpp"
9+
#include "ops/silu.hpp"
910
#include "ops/swiglu.hpp"

include/infinicore/ops/silu.hpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#pragma once
2+
3+
#include "../device.hpp"
4+
#include "common/op.hpp"
5+
6+
namespace infinicore::op {
7+
class Silu {
8+
public:
9+
using schema = void (*)(Tensor, Tensor);
10+
static void execute(Tensor output, Tensor input);
11+
static common::OpDispatcher<schema> &dispatcher();
12+
};
13+
14+
Tensor silu(Tensor input);
15+
void silu_(Tensor output, Tensor input);
16+
} // namespace infinicore::op

python/infinicore/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from infinicore.ops.matmul import matmul
3131
from infinicore.ops.rearrange import rearrange
3232
from infinicore.ops.rms_norm import rms_norm
33+
from infinicore.ops.silu import silu
3334
from infinicore.ops.swiglu import swiglu
3435
from infinicore.tensor import (
3536
empty,
@@ -75,6 +76,7 @@
7576
"matmul",
7677
"rearrange",
7778
"rms_norm",
79+
"silu",
7880
"swiglu",
7981
"empty",
8082
"from_blob",

python/infinicore/ops/silu.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from infinicore.lib import _infinicore
2+
from infinicore.tensor import Tensor
3+
4+
5+
def silu(input, *, out=None):
6+
if out is None:
7+
return Tensor(_infinicore.silu(input._underlying))
8+
9+
_infinicore.silu_(out._underlying, input._underlying)

src/infinicore/ops/silu/silu.cc

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#include "infinicore/ops/silu.hpp"
2+
#include <stdexcept>
3+
4+
namespace infinicore::op {
5+
6+
common::OpDispatcher<Silu::schema> &Silu::dispatcher() {
7+
static common::OpDispatcher<Silu::schema> dispatcher_;
8+
return dispatcher_;
9+
};
10+
11+
void Silu::execute(Tensor output, Tensor input) {
12+
auto device_type = context::getDevice().getType();
13+
auto func = dispatcher().lookup(device_type);
14+
15+
if (func == nullptr) {
16+
throw std::runtime_error("No Silu implementation found for device type: " + std::to_string(static_cast<int>(device_type)));
17+
}
18+
19+
func(output, input);
20+
}
21+
22+
Tensor silu(Tensor input) {
23+
Shape shape = input->shape();
24+
auto output = Tensor::empty(shape, input->dtype(), input->device());
25+
silu_(output, input);
26+
return output;
27+
}
28+
29+
void silu_(Tensor output, Tensor input) {
30+
Silu::execute(output, input);
31+
}
32+
} // namespace infinicore::op
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include "../../utils.hpp"
2+
#include "infinicore/common/hash.hpp"
3+
#include "infinicore/ops/common/cache.hpp"
4+
#include "infinicore/ops/silu.hpp"
5+
#include <infiniop.h>
6+
7+
namespace infinicore::op::silu_impl::infiniop {
8+
9+
thread_local common::OpCache<size_t, infiniopSiluDescriptor_t> caches(
10+
100, // capacity
11+
[](infiniopSiluDescriptor_t &desc) {
12+
if (desc != nullptr) {
13+
INFINICORE_CHECK_ERROR(infiniopDestroySiluDescriptor(desc));
14+
desc = nullptr;
15+
}
16+
});
17+
18+
void calculate(Tensor output, Tensor input) {
19+
size_t seed = hash_combine(output, input);
20+
21+
auto device_type = context::getDevice().getType();
22+
auto device_index = context::getDevice().getIndex();
23+
24+
auto &cache = caches.getCache(device_type, device_index);
25+
26+
auto desc_opt = cache.get(seed);
27+
infiniopSiluDescriptor_t desc = nullptr;
28+
29+
if (!desc_opt) {
30+
INFINICORE_CHECK_ERROR(infiniopCreateSiluDescriptor(
31+
context::getInfiniopHandle(), &desc,
32+
output->desc(), input->desc()));
33+
cache.put(seed, desc);
34+
} else {
35+
desc = *desc_opt;
36+
}
37+
38+
size_t workspace_size = 0;
39+
INFINICORE_CHECK_ERROR(infiniopGetSiluWorkspaceSize(desc, &workspace_size));
40+
std::shared_ptr<Memory> workspace = context::allocateMemory(workspace_size);
41+
42+
INFINICORE_CHECK_ERROR(infiniopSilu(
43+
desc, workspace->data(), workspace_size,
44+
output->data(), input->data(), context::getStream()));
45+
}
46+
47+
static bool registered = []() {
48+
Silu::dispatcher().registerAll(&calculate, false);
49+
return true;
50+
}();
51+
52+
} // namespace infinicore::op::silu_impl::infiniop

src/infinicore/pybind11/ops.hpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#include "ops/matmul.hpp"
88
#include "ops/rearrange.hpp"
99
#include "ops/rms_norm.hpp"
10+
#include "ops/silu.hpp"
1011
#include "ops/swiglu.hpp"
1112

1213
namespace py = pybind11;
@@ -19,6 +20,7 @@ inline void bind(py::module &m) {
1920
bind_matmul(m);
2021
bind_rearrange(m);
2122
bind_rms_norm(m);
23+
bind_silu(m);
2224
bind_swiglu(m);
2325
}
2426

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#pragma once
2+
3+
#include <pybind11/pybind11.h>
4+
5+
#include "infinicore/ops/silu.hpp"
6+
7+
namespace py = pybind11;
8+
9+
namespace infinicore::ops {
10+
11+
inline void bind_silu(py::module &m) {
12+
m.def("silu",
13+
&op::silu,
14+
py::arg("input"),
15+
R"doc(SiLU (Swish) activation function.)doc");
16+
17+
m.def("silu_",
18+
&op::silu_,
19+
py::arg("output"),
20+
py::arg("input"),
21+
R"doc(In-place SiLU (Swish) activation function.)doc");
22+
}
23+
24+
} // namespace infinicore::ops

test/infinicore/ops/silu.py

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import sys
2+
import os
3+
4+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
5+
6+
import torch
7+
import infinicore
8+
from framework.base import BaseOperatorTest, TensorSpec, TestCase
9+
from framework.runner import GenericTestRunner
10+
11+
# ==============================================================================
12+
# Operator-specific configuration
13+
# ==============================================================================
14+
15+
# Test cases format: (operation_mode, shape, input_strides, output_strides)
16+
# SiLU is a single-input activation function: output = input * sigmoid(input)
17+
_TEST_CASES_DATA = [
18+
# Basic 2D SiLU
19+
(TestCase.BOTH, (2, 4), None, None),
20+
(TestCase.BOTH, (128, 64), None, None),
21+
# 3D SiLU
22+
(TestCase.BOTH, (2, 4, 8), None, None),
23+
(TestCase.BOTH, (4, 48, 6), None, None),
24+
# Strided tensors
25+
(TestCase.BOTH, (1, 2048), (4096, 1), (4096, 1)),
26+
(TestCase.BOTH, (6, 2560), (2048, 1), (2560, 1)),
27+
# Mixed cases
28+
(TestCase.BOTH, (8, 16, 32), None, None),
29+
# Large tensors
30+
(TestCase.BOTH, (16, 5632), None, None),
31+
(TestCase.BOTH, (4, 4, 5632), None, None),
32+
]
33+
34+
35+
def parse_test_cases(data):
36+
"""
37+
Parse silu test case data according to format:
38+
(operation_mode, shape, input_strides, output_strides)
39+
"""
40+
operation_mode = data[0]
41+
shape = data[1]
42+
input_strides = data[2] if len(data) > 2 else None
43+
output_strides = data[3] if len(data) > 3 else None
44+
45+
# Create input specifications
46+
inputs = []
47+
48+
# Tensor input
49+
if input_strides is not None:
50+
inputs.append(TensorSpec.from_strided_tensor(shape, input_strides))
51+
else:
52+
inputs.append(TensorSpec.from_tensor(shape))
53+
54+
# Output tensor
55+
if output_strides is not None:
56+
output = TensorSpec.from_strided_tensor(shape, output_strides)
57+
else:
58+
output = TensorSpec.from_tensor(shape)
59+
60+
return TestCase(operation_mode, inputs, output)
61+
62+
63+
# Parse test cases
64+
_TEST_CASES = [parse_test_cases(data) for data in _TEST_CASES_DATA]
65+
66+
# Data types
67+
_TENSOR_DTYPES = [infinicore.float16, infinicore.bfloat16, infinicore.float32]
68+
69+
# Tolerance
70+
_TOLERANCE_MAP = {
71+
infinicore.float16: {"atol": 1e-3, "rtol": 1e-3},
72+
infinicore.float32: {"atol": 1e-5, "rtol": 1e-5},
73+
infinicore.bfloat16: {"atol": 5e-3, "rtol": 1e-2},
74+
}
75+
76+
77+
class OpTest(BaseOperatorTest):
78+
"""SiLU test with simplified test case parsing"""
79+
80+
def __init__(self):
81+
super().__init__("SiLU")
82+
83+
def get_test_cases(self):
84+
return _TEST_CASES
85+
86+
def get_tensor_dtypes(self):
87+
return _TENSOR_DTYPES
88+
89+
def get_tolerance_map(self):
90+
return _TOLERANCE_MAP
91+
92+
def torch_operator(self, input, out=None, **kwargs):
93+
# SiLU implementation: input * sigmoid(input)
94+
sigmoid_input = torch.sigmoid(input)
95+
result = input * sigmoid_input
96+
if out is not None:
97+
out.copy_(result)
98+
return out
99+
return result
100+
101+
def infinicore_operator(self, input, out=None, **kwargs):
102+
return infinicore.silu(input, out=out)
103+
104+
105+
def main():
106+
"""Main entry point"""
107+
runner = GenericTestRunner(OpTest)
108+
runner.run_and_exit()
109+
110+
111+
if __name__ == "__main__":
112+
main()

0 commit comments

Comments
 (0)