Skip to content

Commit 728a75a

Browse files
srkreddy1238gemini-code-assist[bot]
authored andcommitted
Analysis (apache#166)
Co-authored-by: Siva <quic_sivb@quicinc.com> Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
1 parent d72fa88 commit 728a75a

32 files changed

Lines changed: 328 additions & 584 deletions

include/tvm/relax/exec_builder.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,15 @@ class ExecBuilderNode : public Object {
122122
rv = value;
123123
return ConvertConstant_(rv);
124124
}
125+
/*!
126+
* \brief update memory scopes.
127+
*
128+
* This function builds the memory scopes for constants.
129+
*
130+
* \param idx Index of the constant
131+
* \param scope The memory scope.
132+
*/
133+
void SaveMemoryScope(vm::Instruction::Arg idx, ffi::String scope);
125134
/*!
126135
* \brief Raw access to underlying executable build in progress.
127136
*/

include/tvm/runtime/tensor.h

Lines changed: 6 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@
3636

3737
#include <atomic>
3838
#include <functional>
39-
#include <string>
4039
#include <utility>
4140
#include <vector>
4241

@@ -189,25 +188,14 @@ class Tensor : public tvm::ffi::Tensor {
189188
*/
190189
TVM_DLL static void CopyFromBytes(const DLTensor* to, void* from, size_t nbytes,
191190
TVMStreamHandle stream = nullptr);
192-
193-
TVM_DLL void SetScope(ffi::String scope);
194-
TVM_DLL ffi::String GetScope() const;
195-
196-
protected:
197-
/*!
198-
* \brief The memory scope
199-
* represents the underlaying scope information of device
200-
*/
201-
ffi::String scope = "global";
202191
};
203192

204193
/*!
205194
* \brief Save a DLTensor to stream
206195
* \param strm The output stream
207196
* \param tensor The tensor to be saved.
208-
* \param scope The tensor storage scope.
209197
*/
210-
inline bool SaveDLTensor(dmlc::Stream* strm, const DLTensor* tensor, ffi::String scope = "global");
198+
inline bool SaveDLTensor(dmlc::Stream* strm, const DLTensor* tensor);
211199

212200
inline void Tensor::CopyFrom(const DLTensor* other) {
213201
ICHECK(data_ != nullptr);
@@ -232,11 +220,10 @@ inline void Tensor::CopyTo(const Tensor& other) const {
232220
}
233221

234222
/*! \brief Magic number for Tensor file */
235-
constexpr uint64_t kTVMNDArrayMagic = 0xDD5E40F096B4A13F;
236-
constexpr uint64_t kTVMNDArrayScopedMagic = 0xDD5E40F096B4A13E;
223+
constexpr uint64_t kTVMTensorMagic = 0xDD5E40F096B4A13F;
237224

238-
inline bool SaveDLTensor(dmlc::Stream* strm, const DLTensor* tensor, ffi::String scope) {
239-
uint64_t header = kTVMNDArrayScopedMagic, reserved = 0;
225+
inline bool SaveDLTensor(dmlc::Stream* strm, const DLTensor* tensor) {
226+
uint64_t header = kTVMTensorMagic, reserved = 0;
240227
strm->Write(header);
241228
strm->Write(reserved);
242229
// Always save data as CPU context
@@ -256,7 +243,6 @@ inline bool SaveDLTensor(dmlc::Stream* strm, const DLTensor* tensor, ffi::String
256243
strm->Write(tensor->dtype);
257244
int ndim = tensor->ndim;
258245
strm->WriteArray(tensor->shape, ndim);
259-
strm->Write(std::string(scope));
260246
int type_bytes = (tensor->dtype.bits + 7) / 8;
261247
int64_t num_elems = 1;
262248
for (int i = 0; i < ndim; ++i) {
@@ -280,14 +266,13 @@ inline bool SaveDLTensor(dmlc::Stream* strm, const DLTensor* tensor, ffi::String
280266
return true;
281267
}
282268

283-
inline void Tensor::Save(dmlc::Stream* strm) const { SaveDLTensor(strm, operator->(), GetScope()); }
269+
inline void Tensor::Save(dmlc::Stream* strm) const { SaveDLTensor(strm, operator->()); }
284270

285271
inline bool Tensor::Load(dmlc::Stream* strm) {
286272
uint64_t header, reserved;
287273
ICHECK(strm->Read(&header)) << "Invalid DLTensor file format";
288274
ICHECK(strm->Read(&reserved)) << "Invalid DLTensor file format";
289-
ICHECK((header == kTVMNDArrayMagic) || (header == kTVMNDArrayScopedMagic))
290-
<< "Invalid DLTensor file format";
275+
ICHECK(header == kTVMTensorMagic) << "Invalid DLTensor file format";
291276
Device dev;
292277
int ndim;
293278
DLDataType dtype;
@@ -305,11 +290,6 @@ inline bool Tensor::Load(dmlc::Stream* strm) {
305290
for (int i = 0; i < ret->ndim; ++i) {
306291
num_elems *= ret->shape[i];
307292
}
308-
if (header == kTVMNDArrayScopedMagic) {
309-
std::string scope;
310-
strm->Read(&scope);
311-
ret.SetScope(scope);
312-
}
313293
int64_t data_byte_size;
314294
ICHECK(strm->Read(&data_byte_size)) << "Invalid DLTensor file format";
315295
ICHECK(data_byte_size == num_elems * elem_bytes) << "Invalid DLTensor file format";

include/tvm/runtime/vm/executable.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,8 @@ class VMExecutable : public ffi::ModuleObj {
155155
std::unordered_map<std::string, Index> func_map;
156156
/*! \brief The global constant pool. */
157157
std::vector<ffi::Any> constants;
158+
/*! \brief The VDevice memory scopes */
159+
std::unordered_map<Index, std::string> memory_scopes;
158160
/*! \brief The offset of instruction. */
159161
std::vector<Index> instr_offset;
160162
/*! \brief The byte data of instruction. */
@@ -177,6 +179,11 @@ class VMExecutable : public ffi::ModuleObj {
177179
* \param strm The input stream.
178180
*/
179181
void SaveGlobalSection(dmlc::Stream* strm) const;
182+
/*!
183+
* \brief Save the memory scopes.
184+
* \param strm The output stream.
185+
*/
186+
void SaveMemoryScopeSection(dmlc::Stream* strm) const;
180187
/*!
181188
* \brief Save the constant pool.
182189
* \param strm The input stream.
@@ -197,6 +204,11 @@ class VMExecutable : public ffi::ModuleObj {
197204
* \param strm The input stream.
198205
*/
199206
void LoadGlobalSection(dmlc::Stream* strm);
207+
/*!
208+
* \brief Load the memory scopes.
209+
* \param strm The input stream.
210+
*/
211+
void LoadMemoryScopeSection(dmlc::Stream* strm);
200212
/*!
201213
* \brief Load the constant pool.
202214
* \param strm The input stream.

include/tvm/tir/transform.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -774,7 +774,7 @@ TVM_DLL Pass DefaultGPUSchedule();
774774
TVM_DLL Pass UseAssumeToReduceBranches();
775775

776776
/*!
777-
* \brief Inject Texture Allocation intrensic.
777+
* \brief Inject Texture Allocation intrinsic.
778778
* \return The pass.
779779
*/
780780
TVM_DLL Pass InjectTextureAlloc();

python/tvm/dlight/adreno/__init__.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,3 @@
2121
from .layout_transform import LayoutTransform
2222
from .fallback import Fallback
2323
from .pool import Pool2D
24-
25-
# from .fallback import Fallback

python/tvm/dlight/adreno/convolution.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
from tvm import tir
2222
from tvm.target import Target
2323

24-
from .utils import schedule_inline_blocks, schedule_storage_annotate, schedule_default
25-
from ..base import analysis
24+
from .utils import schedule_inline_blocks, schedule_default
25+
from .. import analysis
2626
from .base import AdrenoScheduleRule
2727

2828

@@ -68,7 +68,7 @@ def schedule_conv2d(sch: tir.Schedule, blk: tir.schedule.BlockRV):
6868

6969
def apply( # pylint: disable=too-many-locals,missing-docstring
7070
self,
71-
func: Union[tir.PrimFunc],
71+
func: Union[tir.PrimFunc, tir.Schedule],
7272
target: Target,
7373
_: bool,
7474
) -> Optional[tir.Schedule]:
@@ -102,6 +102,5 @@ def is_convolution(blk):
102102
Conv2d.schedule_conv2d(sch, conv_blk)
103103
remaining_blocks = schedule_inline_blocks(sch, remaining_blocks)
104104
schedule_default(sch, remaining_blocks)
105-
schedule_storage_annotate(sch, remaining_blocks)
106105

107106
return sch

python/tvm/dlight/adreno/fallback.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,24 @@
2121

2222
from tvm import tir
2323
from tvm.target import Target
24-
from ..base import analysis
24+
from .. import analysis
2525
from .base import AdrenoScheduleRule
26-
from .utils import get_texture_storage
26+
27+
28+
def _assert_gpu_target(target: Target):
29+
if "gpu" not in target.keys:
30+
raise ValueError(f"Expect a GPU target, but got {target}")
31+
32+
33+
def get_max_threads_per_block(target: Target) -> int:
34+
_assert_gpu_target(target)
35+
max_threads_per_block = None
36+
for name in ["max_threads_per_block", "max_num_threads"]:
37+
if max_threads_per_block is None:
38+
max_threads_per_block = target.attrs.get(name, None)
39+
if max_threads_per_block is None:
40+
max_threads_per_block = 64
41+
return int(max_threads_per_block)
2742

2843

2944
# pylint: disable=invalid-name,missing-function-docstring,unused-variable,unused-import
@@ -45,13 +60,13 @@ def schedule_inline_blocks(
4560
remaining_blocks = []
4661
for blk in blocks:
4762
block_info = analysis.get_block_info(sch, blk)
48-
if block_info.is_injective() and not block_info.is_data_pad():
49-
if len(block_info.consumers) == 1:
63+
if block_info.is_injective() and not block_info.is_data_pad(sch):
64+
if len(sch.get_consumers(blk)) == 1:
5065
try:
5166
sch.compute_inline(blk)
5267
except Exception: # pylint: disable=broad-exception-caught
5368
remaining_blocks.append(blk)
54-
elif len(block_info.producers) == 1:
69+
elif len(sch.get_producers(blk)) == 1:
5570
inlined_once = False
5671
try:
5772
# Would cause an issue inlining to producer with multiple consumers
@@ -71,34 +86,20 @@ def schedule_inline_blocks(
7186
remaining_blocks.append(blk)
7287
return remaining_blocks
7388

74-
@staticmethod
75-
def schedule_annotate_storage(sch: tir.Schedule, func=get_texture_storage):
76-
"""Annotates intermediate buffers to textures whenever it's possible to do so"""
77-
return
78-
# pylint: disable=unreachable
79-
root_blk = analysis.get_root_block(sch)
80-
blocks = sch.get_child_blocks(root_blk)
81-
82-
for blk in blocks:
83-
block_info = analysis.get_block_info(sch, blk)
84-
scope = func(block_info)
85-
if scope is not None and len(sch.get_consumers(blk)) > 0:
86-
sch.set_scope(blk, 0, scope)
87-
8889
@staticmethod
8990
def schedule_default(sch: tir.Schedule, blk: tir.schedule.BlockRV):
9091
block_info = analysis.get_block_info(sch, blk)
9192

9293
s_loops, r_loops, o_loops = [], [], []
93-
v_loop = block_info.write_bufs[0].assoc_lps[-1]
94+
v_loop = block_info.write_bufs(sch)[0].assoc_lps[-1]
9495

9596
for iter_info in block_info.iters:
9697
if sch.get(iter_info.loop_rv) == sch.get(v_loop):
9798
continue
9899
{"S": s_loops, "R": r_loops, "O": o_loops}.get(iter_info.kind).append(iter_info.loop_rv)
99100

100101
iter_vars = analysis.collect_block_iter_vars_used_in_access_region(
101-
block_info.block_stmt, block_info.write_bufs[0].buf_region.region
102+
sch.get(blk), block_info.write_bufs(sch)[0].buf_region.region
102103
)
103104
o_outer = [lp for lp in o_loops if sch.get(lp).var in iter_vars]
104105
o_inner = [lp for lp in o_loops if sch.get(lp).var not in iter_vars]
@@ -114,7 +115,7 @@ def schedule_default(sch: tir.Schedule, blk: tir.schedule.BlockRV):
114115
tgt = Target.current(allow_none=True)
115116

116117
b = sch.fuse(*s_loops)
117-
tx_extent = analysis.get_max_threads_per_block(tgt) if tgt is not None else 256
118+
tx_extent = get_max_threads_per_block(tgt) if tgt is not None else 256
118119
bx, tx = sch.split(b, [None, tx_extent])
119120
sch.bind(bx, "blockIdx.x")
120121
sch.bind(tx, "threadIdx.x")
@@ -139,7 +140,7 @@ def schedule_fallback(sch):
139140
blk
140141
for blk in blocks
141142
if analysis.get_block_info(sch, blk).is_reduction()
142-
or analysis.get_block_info(sch, blk).is_data_pad()
143+
or analysis.get_block_info(sch, blk).is_data_pad(sch)
143144
]
144145
remaining_blocks = [blk for blk in blocks if blk not in schedule_blocks]
145146

@@ -149,7 +150,6 @@ def schedule_fallback(sch):
149150
# TODO: Analyze unscheduled blocks to schedule instead of relying on remaining
150151
for blk in remaining_blocks:
151152
Fallback.schedule_default(sch, blk)
152-
Fallback.schedule_annotate_storage(sch, schedule_blocks + remaining_blocks)
153153

154154
def apply( # pylint: disable=too-many-locals
155155
self,
@@ -170,7 +170,7 @@ def apply( # pylint: disable=too-many-locals
170170
return None
171171

172172
block_infos = [analysis.get_block_info(sch, block) for block in blocks]
173-
if not any("texture" in block.write_bufs[0].get_scope() for block in block_infos):
173+
if not any("texture" in block.write_bufs(sch)[0].get_scope() for block in block_infos):
174174
return None
175175

176176
Fallback.schedule_fallback(sch)

python/tvm/dlight/adreno/layout_transform.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
from tvm import tir
2424
from tvm.target import Target
25-
from ..base import analysis
25+
from .. import analysis
2626

2727
from .base import AdrenoScheduleRule
2828

@@ -61,11 +61,11 @@ def apply( # pylint: disable=too-many-locals
6161
block_info = analysis.get_block_info(sch, blk)
6262
if not (
6363
(self.use_op_name and block_info.name == "te_layout_transform")
64-
or (not self.use_op_name and block_info.is_layout_transform())
64+
or (not self.use_op_name and block_info.is_layout_transform(sch))
6565
):
6666
return None
6767

68-
read_buf, write_buf = (block_info.read_bufs[0], block_info.write_bufs[0])
68+
read_buf, write_buf = (block_info.read_bufs(sch)[0], block_info.write_bufs(sch)[0])
6969
lps = block_info.get_loops()
7070
lpv_read, lpv_write = (
7171
read_buf.assoc_lps[-1],
@@ -124,9 +124,6 @@ def apply( # pylint: disable=too-many-locals
124124
b = sch.fuse(*block_loops)
125125
tx_extent = min(sch.get(b).extent, 256)
126126
candidates = [1, 2, 4, 8, 16, 32]
127-
ux = sch.sample_categorical(
128-
candidates, [1 / len(candidates) for _ in range(len(candidates))]
129-
)
130127
bx, tx = sch.split(b, [None, 256], preserve_unit_iters=True)
131128
sch.bind(bx, "blockIdx.x")
132129
sch.bind(tx, "threadIdx.x")

python/tvm/dlight/adreno/pool.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from tvm.target import Target
2222

2323
from .base import AdrenoScheduleRule
24-
from ..base import analysis
24+
from .. import analysis
2525

2626

2727
# pylint: disable=invalid-name, unused-variable
@@ -87,6 +87,6 @@ def schedule_max_pool(blk: tir.schedule.BlockRV):
8787
sch.reverse_compute_inline(blk)
8888
else:
8989
sch.compute_inline(blk)
90-
except: # pylint: disable=bare-except
90+
except Exception: # pylint: disable=broad-exception-caught
9191
pass
9292
return sch

python/tvm/dlight/adreno/utils.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from tvm.target import Target
2323
from tvm import tir
2424

25-
from ..base.analysis import BlockInfo
25+
from ..analysis import BlockInfo
2626

2727

2828
def get_texture_storage(block_info: BlockInfo):
@@ -83,13 +83,6 @@ def schedule_default(sch, blocks: List[tir.schedule.BlockRV] = None):
8383
return ret
8484

8585

86-
def schedule_storage_annotate(sch: tir.Schedule, func=get_texture_storage):
87-
# Check the Write Buffer isn't one of input Params and is Texturizable...
88-
from .fallback import Fallback
89-
90-
return Fallback.schedule_annotate_storage(sch)
91-
92-
9386
def schedule_fallback(sch, blk):
9487
from .fallback import Fallback
9588

0 commit comments

Comments
 (0)