|
| 1 | +// Copyright 2025 Tencent |
| 2 | +// SPDX-License-Identifier: BSD-3-Clause |
| 3 | + |
| 4 | +#include "fuse_convert_rotaryembed.h" |
| 5 | + |
| 6 | +#include "pass_level2.h" |
| 7 | + |
| 8 | +namespace pnnx { |
| 9 | + |
| 10 | +namespace ncnn { |
| 11 | + |
| 12 | +class fuse_rotaryembed_pass_interleaved : public GraphRewriterPass |
| 13 | +{ |
| 14 | +public: |
| 15 | + const char* match_pattern_graph() const |
| 16 | + { |
| 17 | + return R"PNNXIR(7767517 |
| 18 | +11 11 |
| 19 | +pnnx.Input input_0 0 1 input |
| 20 | +pnnx.Input input_1 0 1 cos_cache |
| 21 | +pnnx.Input input_2 0 1 sin_cache |
| 22 | +Tensor.reshape op_0 1 1 input 22 shape=(%batch,%num_heads,%seqlen,%embed_dim_half,2) |
| 23 | +torch.transpose op_1 1 1 22 23 dim0=%interleave_dim0 dim1=%interleave_dim1 |
| 24 | +Tensor.reshape op_2 1 1 23 24 shape=(%batch,%num_heads,%seqlen,%embed_dim) |
| 25 | +torch.tensor_split op_3 1 2 24 28 29 dim=%split_dim indices=(%embed_dim_half) |
| 26 | +pnnx.Expression op_4 1 1 29 30 expr=neg(@0) |
| 27 | +torch.cat op_5 2 1 30 28 31 dim=%cat_dim |
| 28 | +pnnx.Expression op_6 4 1 24 cos_cache 31 sin_cache out expr=add(mul(@0,@1),mul(@2,@3)) |
| 29 | +pnnx.Output output 1 0 out |
| 30 | +)PNNXIR"; |
| 31 | + } |
| 32 | + |
| 33 | + const char* type_str() const |
| 34 | + { |
| 35 | + return "RotaryEmbed"; |
| 36 | + } |
| 37 | + |
| 38 | + const char* name_str() const |
| 39 | + { |
| 40 | + return "rope"; |
| 41 | + } |
| 42 | + |
| 43 | + bool match(const std::map<std::string, Parameter>& captured_params) const |
| 44 | + { |
| 45 | + const int embed_dim_half = captured_params.at("embed_dim_half").i; |
| 46 | + const int embed_dim = captured_params.at("embed_dim").i; |
| 47 | + if (embed_dim != embed_dim_half * 2) |
| 48 | + return false; |
| 49 | + |
| 50 | + const int interleave_dim0 = captured_params.at("interleave_dim0").i; |
| 51 | + const int interleave_dim1 = captured_params.at("interleave_dim1").i; |
| 52 | + if (!((interleave_dim0 == 4 && interleave_dim1 == 3) || (interleave_dim0 == 3 && interleave_dim1 == 4))) |
| 53 | + return false; |
| 54 | + |
| 55 | + const int split_dim = captured_params.at("split_dim").i; |
| 56 | + if (split_dim != 3 && split_dim != -1) |
| 57 | + return false; |
| 58 | + |
| 59 | + const int cat_dim = captured_params.at("cat_dim").i; |
| 60 | + if (cat_dim != 3 && cat_dim != -1) |
| 61 | + return false; |
| 62 | + |
| 63 | + return true; |
| 64 | + } |
| 65 | + |
| 66 | + void write(Operator* op, const std::map<std::string, Parameter>& /*captured_params*/) const |
| 67 | + { |
| 68 | + op->params["0"] = 1; // interleaved |
| 69 | + } |
| 70 | +}; |
| 71 | + |
| 72 | +void fuse_convert_rotaryembed(Graph& graph) |
| 73 | +{ |
| 74 | + fuse_rotaryembed_pass_interleaved a; |
| 75 | + int opindex = 0; |
| 76 | + |
| 77 | + pnnx_graph_rewrite(graph, &a, opindex); |
| 78 | +} |
| 79 | + |
| 80 | +} // namespace ncnn |
| 81 | + |
| 82 | +} // namespace pnnx |
0 commit comments