-
Notifications
You must be signed in to change notification settings - Fork 3.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[TE] Optimized version of concatenation layer #11341
Merged
masahi
merged 21 commits into
apache:main
from
Deelvin:sshtin/concat_optimization_for_DLRM
Jun 1, 2022
Merged
Changes from 19 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
f2d18e4
[TE] Optimized version of concatenation layer
cd1fbd8
*test fix
7c37a4b
test_any.py fix.
fefb4af
test_forward.py from tensorflow fix.
ae64002
lint fix.
cab5fbb
Fixes after code review.
1a01771
New comment added.
e000d27
Lint fix.
a350af1
Another lint fix.
b0d742d
Comments added.
bfbcb86
rebase issue fix.
14e8b70
Restored previous state.
3ec0d76
Update after code review.
835e8a1
After code review changes.
2199e43
lint review.
d474d16
Change strategy for cuda to fix tests.
37250d3
Rebase to main
a2c9682
Comments changes after review.
dd8d1db
Some more comments fixes.
213c3c6
One more error fix in comments.
ef94d6f
restart build
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -43,3 +43,4 @@ | |
from .scatter import * | ||
from .group_conv2d import * | ||
from .math_alter_op import * | ||
from .concat import * |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
# Licensed to the Apache Software Foundation (ASF) under one | ||
# or more contributor license agreements. See the NOTICE file | ||
# distributed with this work for additional information | ||
# regarding copyright ownership. The ASF licenses this file | ||
# to you under the Apache License, Version 2.0 (the | ||
# "License"); you may not use this file except in compliance | ||
# with the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, | ||
# software distributed under the License is distributed on an | ||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
# KIND, either express or implied. See the License for the | ||
# specific language governing permissions and limitations | ||
# under the License. | ||
"concatenate related operators" | ||
from typing import Optional | ||
import tvm | ||
from tvm import te | ||
import numpy as np | ||
from ..utils import get_const_int, const_vector | ||
|
||
|
||
def concatenate(data: tvm.te.Tensor, axis: Optional[int] = 0): | ||
"""Join a sequence of arrays along an existing axis. Optimized for CPU exeution. | ||
|
||
Parameters | ||
---------- | ||
data : tuple of tvm.te.Tensor | ||
The arrays to concatenate | ||
|
||
axis : int, optional | ||
The axis along which the arrays will be joined. Default is 0. | ||
|
||
Returns | ||
------- | ||
ret : tvm.te.Tensor | ||
""" | ||
|
||
def gen_ir_1d(data_bufs, in_outers_tensor, in_cumsum_tensor, out_buf): | ||
"""Custom conactenation execution.""" | ||
i_b = tvm.tir.ir_builder.create() | ||
data_bufs1 = [i_b.buffer_ptr(data_buf) for data_buf in data_bufs] | ||
out_buf = i_b.buffer_ptr(out_buf) | ||
outers = i_b.buffer_ptr(in_outers_tensor) | ||
cumsum = i_b.buffer_ptr(in_cumsum_tensor) | ||
for i in range(len(data)): | ||
with i_b.for_range(0, outers[i], name="j") as j: | ||
out_buf[cumsum[i] + j] = data_bufs1[i][j] | ||
return i_b.get() | ||
|
||
def gen_ir(data_bufs, in_outers_tensor, in_cumsum_tensor, out_buf, inner, outer): | ||
"""Common case of conactenation execution.""" | ||
i_b = tvm.tir.ir_builder.create() | ||
data_bufs1 = [i_b.buffer_ptr(data_buf) for data_buf in data_bufs] | ||
out_buf = i_b.buffer_ptr(out_buf) | ||
outers = i_b.buffer_ptr(in_outers_tensor) | ||
cumsum = i_b.buffer_ptr(in_cumsum_tensor) | ||
if inner > 1: | ||
with i_b.for_range(0, inner, name="inn", kind="parallel") as inn: | ||
pos = inn * outer | ||
for i in range(len(data)): | ||
offset = inn * outers[i] | ||
with i_b.for_range(0, outers[i], name="j") as j: | ||
out_buf[pos + cumsum[i] + j] = data_bufs1[i][offset + j] | ||
else: | ||
for i in range(len(data)): | ||
with i_b.for_range(0, outers[i], name="j", kind="parallel") as j: | ||
out_buf[cumsum[i] + j] = data_bufs1[i][j] | ||
return i_b.get() | ||
|
||
if axis < 0: | ||
axis += len(data[0].shape) | ||
concat_axis_sizes = [int(t.shape[axis]) for t in data] | ||
join_size = int(np.sum(concat_axis_sizes)) | ||
in_outers = [int(np.prod(i.shape[axis:])) for i in data] | ||
in_outers_cumsum = [0, *np.cumsum(in_outers, dtype="int64")[0:-1]] | ||
dtype = data[0].dtype | ||
out_shape = data[0].shape[:axis] + [join_size] + data[0].shape[axis + 1 :] | ||
in_outers_tensor = const_vector(in_outers) | ||
in_cumsum_tensor = const_vector(in_outers_cumsum, name="cumsum") | ||
right_val = np.prod(out_shape[axis:]) | ||
left_val = np.prod(out_shape[:axis]) | ||
|
||
if ( | ||
len(data[0].shape) == 1 | ||
or right_val == 1 | ||
or (left_val == 1 and axis == len(data[0].shape) - 1) | ||
or (left_val == 1 and right_val == 1) | ||
): | ||
# badly parallelized case | ||
return te.extern( | ||
[out_shape], | ||
list(data) + [in_outers_tensor, in_cumsum_tensor], | ||
lambda ins, outs: gen_ir_1d(ins, ins[-2], ins[-1], outs[0]), | ||
dtype=dtype, | ||
name="concatenate_ext", | ||
) | ||
|
||
inner = get_const_int(int(left_val)) | ||
outer = get_const_int(int(right_val)) | ||
return te.extern( | ||
[out_shape], | ||
list(data) + [in_outers_tensor, in_cumsum_tensor], | ||
lambda ins, outs: gen_ir(ins, ins[-2], ins[-1], outs[0], inner, outer), | ||
dtype=dtype, | ||
name="concatenate_ext", | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -511,6 +511,29 @@ void InjectInline(ScheduleNode* sch, bool feature_extraction_mode) { | |
std::vector<bool> changed(sch->stages.size(), false); | ||
std::vector<Stmt> new_hybrid_body(sch->stages.size()); | ||
std::vector<bool> hybrid_changed(sch->stages.size(), false); | ||
// (sshtin): this workaround allows to inline extern ops into their consumer. | ||
// All inputs for extern op should not be inlined because inlining may happen | ||
// before TE generation for particular extern op. That may lead to | ||
// crash during lowering or building stages. | ||
// The problem description: | ||
// In case of operations fusing, arguments inlining | ||
// prevents creation of ProducerNode for extern operation. | ||
// Instead of the creation it is supposed to use operation argument as inlined buffer | ||
// but extern_op TIR generation can be peformed after inlining procedure so | ||
// newly generated TIR does not have reference to input data at all. | ||
std::unordered_map<Operation, Operation> ext_ops; | ||
shtinsa marked this conversation as resolved.
Show resolved
Hide resolved
|
||
for (size_t i = 0; i < sch->stages.size(); i++) { | ||
Stage stage = sch->stages[i]; | ||
auto ext_op = stage->op.as<ExternOpNode>(); | ||
if (ext_op) { | ||
auto inps = ext_op->InputTensors(); | ||
for (size_t ii = 0; ii < inps.size(); ++ii) { | ||
if (ext_ops.find(inps[ii]->op) == ext_ops.end()) { | ||
ext_ops[inps[ii]->op] = stage->op; | ||
} | ||
} | ||
} | ||
} | ||
// inline all the ops | ||
for (size_t i = sch->stages.size(); i != 0; --i) { | ||
Stage stage = sch->stages[i - 1]; | ||
|
@@ -525,8 +548,13 @@ void InjectInline(ScheduleNode* sch, bool feature_extraction_mode) { | |
for (auto iv : compute->axis) { | ||
args.push_back(iv->var); | ||
} | ||
if (ext_ops.find(stage->op) != ext_ops.end()) { | ||
// sshtin: The extern op can try to get access to the input tensors as a row data, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. sorry one more comment: Do you mean "raw data" here, or what is "row data" otherwise? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oh yes :) it is looks like a CV phantom, Fixed |
||
// that can lead to error in IR builder. | ||
stage->attach_type = kGroupRoot; | ||
continue; | ||
} | ||
masahi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
ICHECK_EQ(compute->body.size(), 1U) << "can only inline compute op with 1 output"; | ||
|
||
if (feature_extraction_mode && compute->attrs.count("const_matrix")) { | ||
// Use constant value to replace access of const matrices. | ||
// This produces wrong IR but is good enough for feature extraction purposes. | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi shtinsa, why make
in_outers_tensor
andin_cumsum_tensor
aste.tensor.Tensor
here? Functionconst_vector
bringsselect
in lowered tir. In my test, I kept them as lists ofint
and passed them to thecallback
function, theselect
was gone and it was faster thante.tensor.Tensor
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hello @DzAvril I analyzed compiled so files and disasm code, and code block for one concatenation looks like this:
So formally I would add some unrolling to copy loop and remove tiles evaluation for data-blocks proportional to SIMD line. But it is a very small improvement which should be implemented on codegen side. Anyway I'm going to check the performance of your's proposals.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I can confirm this. We are currently working on a PR to change the behavior here.
Just as a reference the comparison of the resulting C code with plain list of ints
and with
te.tensor.Tensor
:@UlrikHjort-Bosch @vdkhoi @MichaelJKlaiber
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see, That c code looks better but I tested "llvm" target, so that may be a difference in output.
The same time I should notice that
select
operator is used for filling up the indices table and this code can be excluded from the execution pipeline in case of static shaping. I.e. these tensors can be implemented as const buffers pre-allocated within the data section, but for dynamic shaping this improvement may have effect especially for the small data blocks.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How about I implement the other version and we discuss what is best for all purposes then?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I added comment to #11800 (comment)