-
Notifications
You must be signed in to change notification settings - Fork 607
Qualcomm AI Engine Direct - Model sharding for LLM #4923
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
Merged
cccclai
merged 1 commit into
pytorch:main
from
CodeLinaro:dev1/hutton/model_sharding_with_custom_op
Aug 28, 2024
Merged
Changes from all commits
Commits
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 hidden or 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 hidden or 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 hidden or 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 hidden or 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,104 @@ | ||
# Copyright (c) Qualcomm Innovation Center, Inc. | ||
# All rights reserved | ||
# | ||
# This source code is licensed under the BSD-style license found in the | ||
# LICENSE file in the root directory of this source tree. | ||
import re | ||
from typing import List | ||
|
||
import torch | ||
|
||
from executorch.backends.qualcomm.utils.constants import QCOM_QUANT_ATTRS | ||
from executorch.exir.dialects._ops import ops as exir_ops | ||
from executorch.exir.pass_base import ExportPass, PassResult | ||
from torch.export.exported_program import ExportedProgram | ||
from torch.library import impl, Library | ||
|
||
|
||
fallback_op_lib = Library("llama", "DEF") | ||
# registering an operator. | ||
fallback_op_lib.define("fallback(Tensor input) -> Tensor") | ||
|
||
|
||
@impl(fallback_op_lib, "fallback") | ||
def fallback_impl(a: torch.Tensor) -> torch.Tensor: | ||
return a | ||
|
||
|
||
# registering the out variant. | ||
fallback_op_lib.define("fallback.out(Tensor input, *, Tensor(a!) output) -> Tensor(a!)") | ||
|
||
|
||
@impl(fallback_op_lib, "fallback.out") | ||
def fallback_out_impl(a: torch.Tensor, *, out: torch.Tensor) -> torch.Tensor: | ||
out.copy_(a) | ||
return out | ||
|
||
|
||
class SplitGraph(ExportPass): | ||
""" | ||
Class to split the model to multiple partitions. | ||
Because there is limited memory on the device, it could | ||
not load all llama model in one pte. | ||
""" | ||
|
||
def __init__(self, shard_layers: List[int]): | ||
super().__init__() | ||
self.shard_layers = shard_layers | ||
|
||
def _insert_fallback_op( | ||
self, graph_module: torch.fx.GraphModule | ||
) -> torch.fx.GraphModule: | ||
""" | ||
Insert fallback op before layer that needs to be shard. | ||
Example: | ||
There is 12 layers llama model and num_sharding is 3. | ||
The first partition will contain layers [0, 4) and embedding. | ||
The second partition will contain layers [4, 8). | ||
The third partition will contain layers [8, 12) and output. | ||
""" | ||
pattern = r"layers.(\d+)" | ||
prev_node = None | ||
prev_layer = None | ||
for node in graph_module.graph.nodes: | ||
if node.op != "call_function" or "nn_module_stack" not in node.meta: | ||
continue | ||
|
||
module_values_list = list(node.meta["nn_module_stack"].values()) | ||
full_qualified_name = module_values_list[-1][0] | ||
# Search which layer this node belongs to | ||
match = re.search(pattern, full_qualified_name) | ||
if match is None: | ||
continue | ||
|
||
cur_layer = int(match.group(1)) | ||
# Check the current node which is the last node of the layer | ||
if cur_layer in self.shard_layers and prev_layer == cur_layer - 1: | ||
with graph_module.graph.inserting_after(prev_node): | ||
users = list(prev_node.users.keys()) | ||
inserted_node = graph_module.graph.create_node( | ||
"call_function", | ||
exir_ops.edge.llama.fallback.default, | ||
(prev_node,), | ||
) | ||
inserted_node.meta["val"] = prev_node.meta["val"] | ||
if prev_node.meta.get(QCOM_QUANT_ATTRS, None): | ||
inserted_node.meta[QCOM_QUANT_ATTRS] = prev_node.meta[ | ||
QCOM_QUANT_ATTRS | ||
] | ||
for user in users: | ||
user.replace_input_with(prev_node, inserted_node) | ||
|
||
prev_layer = cur_layer | ||
prev_node = node | ||
|
||
def call(self, graph_module: torch.fx.GraphModule): | ||
self._insert_fallback_op(graph_module) | ||
graph_module.recompile() | ||
return PassResult(graph_module, True) | ||
|
||
|
||
def split_graph(edge_program: ExportedProgram, num_layers: int, shares: int): | ||
graph_module = edge_program.graph_module | ||
shard_layers = list(range(0, num_layers, int(num_layers / shares))) | ||
return SplitGraph(shard_layers)(graph_module) |
This file contains hidden or 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,48 @@ | ||
/* | ||
* Copyright (c) Qualcomm Innovation Center, Inc. | ||
* All rights reserved. | ||
* | ||
* This source code is licensed under the BSD-style license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
#include <executorch/extension/kernel_util/make_boxed_from_unboxed_functor.h> | ||
#include <executorch/extension/llm/custom_ops/op_fallback.h> | ||
#include <cstring> | ||
|
||
namespace torch { | ||
namespace executor { | ||
|
||
namespace native { | ||
|
||
// Copy from op_clone.cpp | ||
Tensor& fallback_out(RuntimeContext& ctx, const Tensor& in, Tensor& out) { | ||
(void)ctx; | ||
|
||
ET_KERNEL_CHECK( | ||
ctx, | ||
resize_tensor(out, in.sizes()) == torch::executor::Error::Ok, | ||
InvalidArgument, | ||
out); | ||
|
||
// The input and out shall share same dtype and size | ||
ET_KERNEL_CHECK( | ||
ctx, tensors_have_same_shape_and_dtype(in, out), InvalidArgument, out); | ||
|
||
if (in.nbytes() > 0) { | ||
// Note that this check is important. It's valid for a tensor with numel 0 | ||
// to have a null data pointer, but in some environments it's invalid to | ||
// pass a null pointer to memcpy() even when the size is zero. | ||
memcpy(out.mutable_data_ptr(), in.const_data_ptr(), in.nbytes()); | ||
} | ||
|
||
return out; | ||
} | ||
|
||
} // namespace native | ||
} // namespace executor | ||
} // namespace torch | ||
|
||
EXECUTORCH_LIBRARY( | ||
llama, | ||
"fallback.out", | ||
torch::executor::native::fallback_out); |
This file contains hidden or 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,20 @@ | ||
/* | ||
* Copyright (c) Qualcomm Innovation Center, Inc. | ||
* All rights reserved. | ||
* | ||
* This source code is licensed under the BSD-style license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
|
||
#pragma once | ||
|
||
#include <executorch/runtime/kernel/kernel_includes.h> | ||
|
||
namespace torch { | ||
namespace executor { | ||
|
||
namespace native { | ||
Tensor& fallback_out(RuntimeContext& ctx, const Tensor& in, Tensor& out); | ||
} // namespace native | ||
} // namespace executor | ||
} // namespace torch |
This file contains hidden or 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 hidden or 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 hidden or 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
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.
Uh oh!
There was an error while loading. Please reload this page.