You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by GitBox <gi...@apache.org> on 2020/12/03 02:18:06 UTC
[GitHub] [tvm] merrymercy opened a new pull request #7019: [AutoScheduler] Add tutorial on auto-scheduling a network for CPU
merrymercy opened a new pull request #7019:
URL: https://github.com/apache/tvm/pull/7019
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] merrymercy commented on a change in pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for x86 CPU
Posted by GitBox <gi...@apache.org>.
merrymercy commented on a change in pull request #7019:
URL: https://github.com/apache/tvm/pull/7019#discussion_r534702348
##########
File path: tutorials/auto_scheduler/tune_network_x86.py
##########
@@ -0,0 +1,307 @@
+# 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.
+"""
+Auto-scheduling a Neural Network for x86 CPU
+============================================
+**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_
+
+Auto-tuning for specific devices and workloads is critical for getting the
+best performance. This is a tutorial on how to tune a whole neural
+network for x86 CPU with the auto-scheduler.
+
+To auto-tune a neural network, we partition the network into small subgraphs and
+tune them independently. Each subgraph is treated as one search task.
+A task scheduler slices the time and dynamically allocates time resources to
+these tasks. The task scheduler predicts the impact of each task on the end-to-end
+execution time and prioritizes the one that can reduce the execution time the most.
+
+For each subgraph, we use the compute declaration in :code:`tvm/python/topi` to
+get the computational DAG in the tensor expression form.
+We then use the auto-scheduler to construct a search space of this DAG and search
+for good schedules (low-level optimizations).
+
+Different from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on
+manual templates to define the search space, the auto-scheduler does not require any
+schedule templates. In other words, the auto-scheduler only uses the compute declarations
+in :code:`tvm/python/topi` while does not use existing schedule templates.
+
+Note that this tutorial will not run on Windows or recent versions of macOS. To
+get it to run, you will need to wrap the body of this tutorial in a :code:`if
+__name__ == "__main__":` block.
+"""
+
+import numpy as np
+
+import tvm
+from tvm import relay, auto_scheduler
+import tvm.relay.testing
+from tvm.contrib import graph_runtime
+
+#################################################################
+# Define a Network
+# ----------------
+# First, we need to define the network with relay frontend API.
+# We can load some pre-defined network from :code:`tvm.relay.testing`.
+# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow
+# (see :ref:`front end tutorials<tutorial-frontend>`).
+#
+# For convolutional neural networks, although auto-scheduler can work
+# correctly with any layout, we found the best performance is typically
+# achieved with NHWC layout. We also implemented more optimizations for
+# NHWC layouts with the auto-scheduler.
+# So it is recommended to convert your models to NHWC layout to use
+# the auto-scheduler.
+
+
+def get_network(name, batch_size, layout="NHWC", dtype="float32"):
Review comment:
Yeah. I will add a link to the [convert layout pass](https://tvm.apache.org/docs/dev/convert_layout.html)
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] merrymercy commented on pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for CPU
Posted by GitBox <gi...@apache.org>.
merrymercy commented on pull request #7019:
URL: https://github.com/apache/tvm/pull/7019#issuecomment-737623657
cc @tqchen @junrushao1994 @jcf94 @minminsun
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] merrymercy commented on a change in pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for x86 CPU
Posted by GitBox <gi...@apache.org>.
merrymercy commented on a change in pull request #7019:
URL: https://github.com/apache/tvm/pull/7019#discussion_r534699235
##########
File path: tutorials/auto_scheduler/tune_network_x86.py
##########
@@ -0,0 +1,307 @@
+# 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.
+"""
+Auto-scheduling a Neural Network for x86 CPU
+============================================
+**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_
+
+Auto-tuning for specific devices and workloads is critical for getting the
+best performance. This is a tutorial on how to tune a whole neural
+network for x86 CPU with the auto-scheduler.
+
+To auto-tune a neural network, we partition the network into small subgraphs and
+tune them independently. Each subgraph is treated as one search task.
+A task scheduler slices the time and dynamically allocates time resources to
+these tasks. The task scheduler predicts the impact of each task on the end-to-end
+execution time and prioritizes the one that can reduce the execution time the most.
+
+For each subgraph, we use the compute declaration in :code:`tvm/python/topi` to
+get the computational DAG in the tensor expression form.
+We then use the auto-scheduler to construct a search space of this DAG and search
+for good schedules (low-level optimizations).
+
+Different from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on
+manual templates to define the search space, the auto-scheduler does not require any
+schedule templates. In other words, the auto-scheduler only uses the compute declarations
+in :code:`tvm/python/topi` while does not use existing schedule templates.
+
+Note that this tutorial will not run on Windows or recent versions of macOS. To
+get it to run, you will need to wrap the body of this tutorial in a :code:`if
+__name__ == "__main__":` block.
+"""
+
+import numpy as np
+
+import tvm
+from tvm import relay, auto_scheduler
+import tvm.relay.testing
+from tvm.contrib import graph_runtime
+
+#################################################################
+# Define a Network
+# ----------------
+# First, we need to define the network with relay frontend API.
+# We can load some pre-defined network from :code:`tvm.relay.testing`.
+# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow
+# (see :ref:`front end tutorials<tutorial-frontend>`).
+#
+# For convolutional neural networks, although auto-scheduler can work
+# correctly with any layout, we found the best performance is typically
+# achieved with NHWC layout. We also implemented more optimizations for
+# NHWC layouts with the auto-scheduler.
+# So it is recommended to convert your models to NHWC layout to use
Review comment:
It is recommended. Auto-scheduler can work correctly with any layout. But the performance for NCHW is just not guaranteed.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] FrozenGene commented on a change in pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for x86 CPU
Posted by GitBox <gi...@apache.org>.
FrozenGene commented on a change in pull request #7019:
URL: https://github.com/apache/tvm/pull/7019#discussion_r534724071
##########
File path: tutorials/auto_scheduler/tune_network_x86.py
##########
@@ -0,0 +1,307 @@
+# 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.
+"""
+Auto-scheduling a Neural Network for x86 CPU
+============================================
+**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_
+
+Auto-tuning for specific devices and workloads is critical for getting the
+best performance. This is a tutorial on how to tune a whole neural
+network for x86 CPU with the auto-scheduler.
+
+To auto-tune a neural network, we partition the network into small subgraphs and
+tune them independently. Each subgraph is treated as one search task.
+A task scheduler slices the time and dynamically allocates time resources to
+these tasks. The task scheduler predicts the impact of each task on the end-to-end
+execution time and prioritizes the one that can reduce the execution time the most.
+
+For each subgraph, we use the compute declaration in :code:`tvm/python/topi` to
+get the computational DAG in the tensor expression form.
+We then use the auto-scheduler to construct a search space of this DAG and search
+for good schedules (low-level optimizations).
+
+Different from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on
+manual templates to define the search space, the auto-scheduler does not require any
+schedule templates. In other words, the auto-scheduler only uses the compute declarations
+in :code:`tvm/python/topi` and does not use existing schedule templates.
+
+Note that this tutorial will not run on Windows or recent versions of macOS. To
+get it to run, you will need to wrap the body of this tutorial in a :code:`if
+__name__ == "__main__":` block.
+"""
+
+import numpy as np
+
+import tvm
+from tvm import relay, auto_scheduler
+import tvm.relay.testing
+from tvm.contrib import graph_runtime
+
+#################################################################
+# Define a Network
+# ----------------
+# First, we need to define the network with relay frontend API.
+# We can load some pre-defined network from :code:`tvm.relay.testing`.
+# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow
+# (see :ref:`front end tutorials<tutorial-frontend>`).
+#
+# For convolutional neural networks, although auto-scheduler can work
+# correctly with any layout, we found the best performance is typically
+# achieved with NHWC layout. We also implemented more optimizations for
+# NHWC layouts with the auto-scheduler.
+# So it is recommended to convert your models to NHWC layout to use
+# the auto-scheduler.
+
+
+def get_network(name, batch_size, layout="NHWC", dtype="float32"):
+ """Get the symbol definition and random weight of a network"""
+
+ # auto-scheduler prefers NHWC layout
+ if layout == "NHWC":
+ image_shape = (224, 224, 3)
+ elif layout == "NCHW":
+ image_shape = (3, 224, 224)
+ else:
+ raise ValueError("Invalid layout: " + layout)
+
+ input_shape = (batch_size,) + image_shape
+ output_shape = (batch_size, 1000)
+
+ if name.startswith("resnet-"):
+ n_layer = int(name.split("-")[1])
+ mod, params = relay.testing.resnet.get_workload(
+ num_layers=n_layer,
+ batch_size=batch_size,
+ layout=layout,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name.startswith("resnet3d-"):
+ n_layer = int(name.split("-")[1])
+ mod, params = relay.testing.resnet.get_workload(
+ num_layers=n_layer,
+ batch_size=batch_size,
+ layout=layout,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name == "mobilenet":
+ mod, params = relay.testing.mobilenet.get_workload(
+ batch_size=batch_size, layout=layout, dtype=dtype, image_shape=image_shape
+ )
+ elif name == "squeezenet_v1.1":
+ assert layout == "NCHW", "squeezenet_v1.1 only supports NCHW layout"
+ mod, params = relay.testing.squeezenet.get_workload(
+ version="1.1",
+ batch_size=batch_size,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name == "inception_v3":
+ input_shape = (batch_size, 3, 299, 299) if layout == "NCHW" else (batch_size, 299, 299, 3)
+ mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)
+ elif name == "mxnet":
+ # an example for mxnet model
+ from mxnet.gluon.model_zoo.vision import get_model
+
+ assert layout == "NCHW"
+
+ block = get_model("resnet50_v1", pretrained=True)
+ mod, params = relay.frontend.from_mxnet(block, shape={"data": input_shape}, dtype=dtype)
+ net = mod["main"]
+ net = relay.Function(
+ net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs
+ )
+ mod = tvm.IRModule.from_expr(net)
+
+ return mod, params, input_shape, output_shape
+
+
+# Define the neural network and compilation target.
+# If the target machine supports avx512 instructions, replace the
+# "llvm -mcpu=core-avx2" with "llvm -mcpu=skylake-avx512"
+network = "resnet-50"
+batch_size = 1
+layout = "NHWC"
+target = tvm.target.Target("llvm -mcpu=skylake-avx512")
+dtype = "float32"
+log_file = "%s-%s-B%d-%s.json" % (network, layout, batch_size, target.kind.name)
+
+#################################################################
+# Extract Search Tasks
+# --------------------
+# Next, we extract the search tasks and their weights from a network.
+# The weight of a task is the number of appearances of the task's subgraph
+# in the whole network.
+# By using the weight, we can approximate the end-to-end latency of the network
+# as :code:`sum(latency[t] * weight[t])`, where :code:`latency[t]` is the
+# latency of a task and :code:`weight[t]` is the weight of the task.
+# The task scheduler will just optimize this objective.
+
+# Extract tasks from the network
+print("Extract tasks...")
+mod, params, input_shape, output_shape = get_network(network, batch_size, layout, dtype=dtype)
+tasks, task_weights = auto_scheduler.extract_tasks(mod["main"], params, target)
+
+for idx, task in enumerate(tasks):
+ print("========== Task %d (workload key: %s) ==========" % (idx, task.workload_key))
+ print(task.compute_dag)
+
+#################################################################
+# Begin Tuning
+# ------------
+# Now, we set some options for tuning and launch the search tasks
+#
+# * :code:`num_measure_trials` is the number of measurement trials we can use during the tuning.
+# You can set it to a small number (e.g., 200) for a fast demonstrative run.
+# In practice, we recommend setting it around :code:`800 * len(tasks)`,
Review comment:
Here is 800 now. GPU is 900. I think it is a bit confused. If there is no special reason, unified them into 1000?
##########
File path: tutorials/auto_scheduler/tune_network_cuda.py
##########
@@ -170,11 +172,11 @@ def get_network(name, batch_size, layout="NHWC", dtype="float32"):
# Typically, we recommend a value >= 300 ms.
# * :code:`num_measure_trials` is the number of measurement trials we can use during the tuning.
# You can set it to a small number (e.g., 200) for a fast demonstrative run.
-# In practice, we recommend setting it around :code:`1000 * len(tasks)`,
+# In practice, we recommend setting it around :code:`900 * len(tasks)`,
Review comment:
What is the reason changing `1000` to `900`? Any experiment or principle?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] tmoreau89 commented on a change in pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for x86 CPU
Posted by GitBox <gi...@apache.org>.
tmoreau89 commented on a change in pull request #7019:
URL: https://github.com/apache/tvm/pull/7019#discussion_r534651701
##########
File path: tutorials/auto_scheduler/tune_network_x86.py
##########
@@ -0,0 +1,307 @@
+# 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.
+"""
+Auto-scheduling a Neural Network for x86 CPU
+============================================
+**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_
+
+Auto-tuning for specific devices and workloads is critical for getting the
+best performance. This is a tutorial on how to tune a whole neural
+network for x86 CPU with the auto-scheduler.
+
+To auto-tune a neural network, we partition the network into small subgraphs and
+tune them independently. Each subgraph is treated as one search task.
+A task scheduler slices the time and dynamically allocates time resources to
+these tasks. The task scheduler predicts the impact of each task on the end-to-end
+execution time and prioritizes the one that can reduce the execution time the most.
+
+For each subgraph, we use the compute declaration in :code:`tvm/python/topi` to
+get the computational DAG in the tensor expression form.
+We then use the auto-scheduler to construct a search space of this DAG and search
+for good schedules (low-level optimizations).
+
+Different from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on
Review comment:
Sentence a little difficult to read; perhaps go with : "The autoscheduler does not require any schedule templates. Therefore it greatly improves upon the template-based autoTVM..."
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] tmoreau89 commented on a change in pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for x86 CPU
Posted by GitBox <gi...@apache.org>.
tmoreau89 commented on a change in pull request #7019:
URL: https://github.com/apache/tvm/pull/7019#discussion_r534654075
##########
File path: tutorials/auto_scheduler/tune_network_x86.py
##########
@@ -0,0 +1,307 @@
+# 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.
+"""
+Auto-scheduling a Neural Network for x86 CPU
+============================================
+**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_
+
+Auto-tuning for specific devices and workloads is critical for getting the
+best performance. This is a tutorial on how to tune a whole neural
+network for x86 CPU with the auto-scheduler.
+
+To auto-tune a neural network, we partition the network into small subgraphs and
+tune them independently. Each subgraph is treated as one search task.
+A task scheduler slices the time and dynamically allocates time resources to
+these tasks. The task scheduler predicts the impact of each task on the end-to-end
+execution time and prioritizes the one that can reduce the execution time the most.
+
+For each subgraph, we use the compute declaration in :code:`tvm/python/topi` to
+get the computational DAG in the tensor expression form.
+We then use the auto-scheduler to construct a search space of this DAG and search
+for good schedules (low-level optimizations).
+
+Different from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on
+manual templates to define the search space, the auto-scheduler does not require any
+schedule templates. In other words, the auto-scheduler only uses the compute declarations
+in :code:`tvm/python/topi` while does not use existing schedule templates.
+
+Note that this tutorial will not run on Windows or recent versions of macOS. To
+get it to run, you will need to wrap the body of this tutorial in a :code:`if
+__name__ == "__main__":` block.
+"""
+
+import numpy as np
+
+import tvm
+from tvm import relay, auto_scheduler
+import tvm.relay.testing
+from tvm.contrib import graph_runtime
+
+#################################################################
+# Define a Network
+# ----------------
+# First, we need to define the network with relay frontend API.
+# We can load some pre-defined network from :code:`tvm.relay.testing`.
+# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow
+# (see :ref:`front end tutorials<tutorial-frontend>`).
+#
+# For convolutional neural networks, although auto-scheduler can work
+# correctly with any layout, we found the best performance is typically
+# achieved with NHWC layout. We also implemented more optimizations for
+# NHWC layouts with the auto-scheduler.
+# So it is recommended to convert your models to NHWC layout to use
+# the auto-scheduler.
+
+
+def get_network(name, batch_size, layout="NHWC", dtype="float32"):
+ """Get the symbol definition and random weight of a network"""
+
+ # auto-scheduler prefers NHWC layout
+ if layout == "NHWC":
+ image_shape = (224, 224, 3)
+ elif layout == "NCHW":
+ image_shape = (3, 224, 224)
+ else:
+ raise ValueError("Invalid layout: " + layout)
+
+ input_shape = (batch_size,) + image_shape
+ output_shape = (batch_size, 1000)
+
+ if name.startswith("resnet-"):
+ n_layer = int(name.split("-")[1])
+ mod, params = relay.testing.resnet.get_workload(
+ num_layers=n_layer,
+ batch_size=batch_size,
+ layout=layout,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name.startswith("resnet3d-"):
+ n_layer = int(name.split("-")[1])
+ mod, params = relay.testing.resnet.get_workload(
+ num_layers=n_layer,
+ batch_size=batch_size,
+ layout=layout,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name == "mobilenet":
+ mod, params = relay.testing.mobilenet.get_workload(
+ batch_size=batch_size, layout=layout, dtype=dtype, image_shape=image_shape
+ )
+ elif name == "squeezenet_v1.1":
+ assert layout == "NCHW", "squeezenet_v1.1 only supports NCHW layout"
+ mod, params = relay.testing.squeezenet.get_workload(
+ version="1.1",
+ batch_size=batch_size,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name == "inception_v3":
+ input_shape = (batch_size, 3, 299, 299) if layout == "NCHW" else (batch_size, 299, 299, 3)
+ mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)
+ elif name == "mxnet":
+ # an example for mxnet model
+ from mxnet.gluon.model_zoo.vision import get_model
+
+ assert layout == "NCHW"
+
+ block = get_model("resnet50_v1", pretrained=True)
+ mod, params = relay.frontend.from_mxnet(block, shape={"data": input_shape}, dtype=dtype)
+ net = mod["main"]
+ net = relay.Function(
+ net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs
+ )
+ mod = tvm.IRModule.from_expr(net)
+
+ return mod, params, input_shape, output_shape
+
+
+# Define the neural network and compilation target.
+# If the target machine supports avx512 instructions, replace the
+# "llvm -mcpu=core-avx2" with "llvm -mcpu=skylake-avx512"
+network = "resnet-50"
+batch_size = 1
+layout = "NCHW"
+target = tvm.target.Target("llvm -mcpu=skylake-avx512")
+dtype = "float32"
+log_file = "%s-%s-B%d-%s.json" % (network, layout, batch_size, target.kind.name)
+
+#################################################################
+# Extract Search Tasks
+# --------------------
+# Next, we extract the search tasks and their weights from a network.
+# The weight of a task is the number of appearances of the task's subgraph
+# in the whole network.
+# By using the weight, we can approximate the end-to-end latency of the network
+# as :code:`sum(latency[t] * weight[t])`, where :code:`latency[t]` is the
+# latency of a task and :code:`weight[t]` is the weight of the task.
+# The task scheduler will just optimize this objective.
+
+# Extract tasks from the network
+print("Extract tasks...")
+mod, params, input_shape, output_shape = get_network(network, batch_size, layout, dtype=dtype)
+tasks, task_weights = auto_scheduler.extract_tasks(mod["main"], params, target)
+
+for idx, task in enumerate(tasks):
+ print("========== Task %d (workload key: %s) ==========" % (idx, task.workload_key))
+ print(task.compute_dag)
+
+#################################################################
+# Begin Tuning
+# ------------
+# Now, we set some options for tuning and launch the search tasks
+#
+# * :code:`num_measure_trials` is the number of measurement trials we can use during the tuning.
+# You can set it to a small number (e.g., 200) for a fast demonstrative run.
+# In practice, we recommend setting it around :code:`800 * len(tasks)`,
+# which is typically enough for the search to converge.
+# For example, there are 29 tasks in resnet-50, so we can set it as 20000.
+# You can adjust this parameter according to your time budget.
+# * In addition, we use :code:`RecordToFile` to dump measurement records into a log file,
+# The measurement records can be used to query the history best, resume the search,
+# and do more analyses later.
+# * see :any:`auto_scheduler.TuningOptions`,
+# :any:`auto_scheduler.LocalRunner` for more parameters.
+#
+
+
+def run_tuning():
+ print("Begin tuning...")
+ tuner = auto_scheduler.TaskScheduler(tasks, task_weights)
+ tune_option = auto_scheduler.TuningOptions(
+ num_measure_trials=20000, # change this to 20000 to achieve the best performance
+ runner=auto_scheduler.LocalRunner(repeat=10, enable_cpu_cache_flush=True),
+ measure_callbacks=[auto_scheduler.RecordToFile(log_file)],
+ )
+
+ tuner.tune(tune_option)
+
+
+# We do not run the tuning in our webpage server since it takes too long.
+# Uncomment the following line to run it by yourself.
+
+run_tuning()
Review comment:
Should this be commented out?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] tmoreau89 commented on a change in pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for x86 CPU
Posted by GitBox <gi...@apache.org>.
tmoreau89 commented on a change in pull request #7019:
URL: https://github.com/apache/tvm/pull/7019#discussion_r534652254
##########
File path: tutorials/auto_scheduler/tune_network_x86.py
##########
@@ -0,0 +1,307 @@
+# 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.
+"""
+Auto-scheduling a Neural Network for x86 CPU
+============================================
+**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_
+
+Auto-tuning for specific devices and workloads is critical for getting the
+best performance. This is a tutorial on how to tune a whole neural
+network for x86 CPU with the auto-scheduler.
+
+To auto-tune a neural network, we partition the network into small subgraphs and
+tune them independently. Each subgraph is treated as one search task.
+A task scheduler slices the time and dynamically allocates time resources to
+these tasks. The task scheduler predicts the impact of each task on the end-to-end
+execution time and prioritizes the one that can reduce the execution time the most.
+
+For each subgraph, we use the compute declaration in :code:`tvm/python/topi` to
+get the computational DAG in the tensor expression form.
+We then use the auto-scheduler to construct a search space of this DAG and search
+for good schedules (low-level optimizations).
+
+Different from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on
+manual templates to define the search space, the auto-scheduler does not require any
+schedule templates. In other words, the auto-scheduler only uses the compute declarations
+in :code:`tvm/python/topi` while does not use existing schedule templates.
+
+Note that this tutorial will not run on Windows or recent versions of macOS. To
+get it to run, you will need to wrap the body of this tutorial in a :code:`if
+__name__ == "__main__":` block.
+"""
+
+import numpy as np
+
+import tvm
+from tvm import relay, auto_scheduler
+import tvm.relay.testing
+from tvm.contrib import graph_runtime
+
+#################################################################
+# Define a Network
+# ----------------
+# First, we need to define the network with relay frontend API.
+# We can load some pre-defined network from :code:`tvm.relay.testing`.
+# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow
+# (see :ref:`front end tutorials<tutorial-frontend>`).
+#
+# For convolutional neural networks, although auto-scheduler can work
+# correctly with any layout, we found the best performance is typically
+# achieved with NHWC layout. We also implemented more optimizations for
+# NHWC layouts with the auto-scheduler.
+# So it is recommended to convert your models to NHWC layout to use
Review comment:
Note: is it recommended or mandatory?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] tmoreau89 commented on a change in pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for x86 CPU
Posted by GitBox <gi...@apache.org>.
tmoreau89 commented on a change in pull request #7019:
URL: https://github.com/apache/tvm/pull/7019#discussion_r534653594
##########
File path: tutorials/auto_scheduler/tune_network_x86.py
##########
@@ -0,0 +1,307 @@
+# 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.
+"""
+Auto-scheduling a Neural Network for x86 CPU
+============================================
+**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_
+
+Auto-tuning for specific devices and workloads is critical for getting the
+best performance. This is a tutorial on how to tune a whole neural
+network for x86 CPU with the auto-scheduler.
+
+To auto-tune a neural network, we partition the network into small subgraphs and
+tune them independently. Each subgraph is treated as one search task.
+A task scheduler slices the time and dynamically allocates time resources to
+these tasks. The task scheduler predicts the impact of each task on the end-to-end
+execution time and prioritizes the one that can reduce the execution time the most.
+
+For each subgraph, we use the compute declaration in :code:`tvm/python/topi` to
+get the computational DAG in the tensor expression form.
+We then use the auto-scheduler to construct a search space of this DAG and search
+for good schedules (low-level optimizations).
+
+Different from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on
+manual templates to define the search space, the auto-scheduler does not require any
+schedule templates. In other words, the auto-scheduler only uses the compute declarations
+in :code:`tvm/python/topi` while does not use existing schedule templates.
+
+Note that this tutorial will not run on Windows or recent versions of macOS. To
+get it to run, you will need to wrap the body of this tutorial in a :code:`if
+__name__ == "__main__":` block.
+"""
+
+import numpy as np
+
+import tvm
+from tvm import relay, auto_scheduler
+import tvm.relay.testing
+from tvm.contrib import graph_runtime
+
+#################################################################
+# Define a Network
+# ----------------
+# First, we need to define the network with relay frontend API.
+# We can load some pre-defined network from :code:`tvm.relay.testing`.
+# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow
+# (see :ref:`front end tutorials<tutorial-frontend>`).
+#
+# For convolutional neural networks, although auto-scheduler can work
+# correctly with any layout, we found the best performance is typically
+# achieved with NHWC layout. We also implemented more optimizations for
+# NHWC layouts with the auto-scheduler.
+# So it is recommended to convert your models to NHWC layout to use
+# the auto-scheduler.
+
+
+def get_network(name, batch_size, layout="NHWC", dtype="float32"):
+ """Get the symbol definition and random weight of a network"""
+
+ # auto-scheduler prefers NHWC layout
+ if layout == "NHWC":
+ image_shape = (224, 224, 3)
+ elif layout == "NCHW":
+ image_shape = (3, 224, 224)
+ else:
+ raise ValueError("Invalid layout: " + layout)
+
+ input_shape = (batch_size,) + image_shape
+ output_shape = (batch_size, 1000)
+
+ if name.startswith("resnet-"):
+ n_layer = int(name.split("-")[1])
+ mod, params = relay.testing.resnet.get_workload(
+ num_layers=n_layer,
+ batch_size=batch_size,
+ layout=layout,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name.startswith("resnet3d-"):
+ n_layer = int(name.split("-")[1])
+ mod, params = relay.testing.resnet.get_workload(
+ num_layers=n_layer,
+ batch_size=batch_size,
+ layout=layout,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name == "mobilenet":
+ mod, params = relay.testing.mobilenet.get_workload(
+ batch_size=batch_size, layout=layout, dtype=dtype, image_shape=image_shape
+ )
+ elif name == "squeezenet_v1.1":
+ assert layout == "NCHW", "squeezenet_v1.1 only supports NCHW layout"
+ mod, params = relay.testing.squeezenet.get_workload(
+ version="1.1",
+ batch_size=batch_size,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name == "inception_v3":
+ input_shape = (batch_size, 3, 299, 299) if layout == "NCHW" else (batch_size, 299, 299, 3)
+ mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)
+ elif name == "mxnet":
+ # an example for mxnet model
+ from mxnet.gluon.model_zoo.vision import get_model
+
+ assert layout == "NCHW"
+
+ block = get_model("resnet50_v1", pretrained=True)
+ mod, params = relay.frontend.from_mxnet(block, shape={"data": input_shape}, dtype=dtype)
+ net = mod["main"]
+ net = relay.Function(
+ net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs
+ )
+ mod = tvm.IRModule.from_expr(net)
+
+ return mod, params, input_shape, output_shape
+
+
+# Define the neural network and compilation target.
+# If the target machine supports avx512 instructions, replace the
+# "llvm -mcpu=core-avx2" with "llvm -mcpu=skylake-avx512"
+network = "resnet-50"
+batch_size = 1
+layout = "NCHW"
+target = tvm.target.Target("llvm -mcpu=skylake-avx512")
+dtype = "float32"
+log_file = "%s-%s-B%d-%s.json" % (network, layout, batch_size, target.kind.name)
+
+#################################################################
+# Extract Search Tasks
+# --------------------
+# Next, we extract the search tasks and their weights from a network.
+# The weight of a task is the number of appearances of the task's subgraph
+# in the whole network.
+# By using the weight, we can approximate the end-to-end latency of the network
+# as :code:`sum(latency[t] * weight[t])`, where :code:`latency[t]` is the
+# latency of a task and :code:`weight[t]` is the weight of the task.
+# The task scheduler will just optimize this objective.
+
+# Extract tasks from the network
+print("Extract tasks...")
+mod, params, input_shape, output_shape = get_network(network, batch_size, layout, dtype=dtype)
+tasks, task_weights = auto_scheduler.extract_tasks(mod["main"], params, target)
Review comment:
Another quality of life improvement here would be to error out if the tasks are for NCHW layout in which case no tasks would get extracted.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] tmoreau89 commented on a change in pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for x86 CPU
Posted by GitBox <gi...@apache.org>.
tmoreau89 commented on a change in pull request #7019:
URL: https://github.com/apache/tvm/pull/7019#discussion_r534652925
##########
File path: tutorials/auto_scheduler/tune_network_x86.py
##########
@@ -0,0 +1,307 @@
+# 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.
+"""
+Auto-scheduling a Neural Network for x86 CPU
+============================================
+**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_
+
+Auto-tuning for specific devices and workloads is critical for getting the
+best performance. This is a tutorial on how to tune a whole neural
+network for x86 CPU with the auto-scheduler.
+
+To auto-tune a neural network, we partition the network into small subgraphs and
+tune them independently. Each subgraph is treated as one search task.
+A task scheduler slices the time and dynamically allocates time resources to
+these tasks. The task scheduler predicts the impact of each task on the end-to-end
+execution time and prioritizes the one that can reduce the execution time the most.
+
+For each subgraph, we use the compute declaration in :code:`tvm/python/topi` to
+get the computational DAG in the tensor expression form.
+We then use the auto-scheduler to construct a search space of this DAG and search
+for good schedules (low-level optimizations).
+
+Different from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on
+manual templates to define the search space, the auto-scheduler does not require any
+schedule templates. In other words, the auto-scheduler only uses the compute declarations
+in :code:`tvm/python/topi` while does not use existing schedule templates.
+
+Note that this tutorial will not run on Windows or recent versions of macOS. To
+get it to run, you will need to wrap the body of this tutorial in a :code:`if
+__name__ == "__main__":` block.
+"""
+
+import numpy as np
+
+import tvm
+from tvm import relay, auto_scheduler
+import tvm.relay.testing
+from tvm.contrib import graph_runtime
+
+#################################################################
+# Define a Network
+# ----------------
+# First, we need to define the network with relay frontend API.
+# We can load some pre-defined network from :code:`tvm.relay.testing`.
+# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow
+# (see :ref:`front end tutorials<tutorial-frontend>`).
+#
+# For convolutional neural networks, although auto-scheduler can work
+# correctly with any layout, we found the best performance is typically
+# achieved with NHWC layout. We also implemented more optimizations for
+# NHWC layouts with the auto-scheduler.
+# So it is recommended to convert your models to NHWC layout to use
+# the auto-scheduler.
+
+
+def get_network(name, batch_size, layout="NHWC", dtype="float32"):
Review comment:
Note on the restriction: while relay.testing library is really convenient, not all models offer the choice to change the layout (VGG). In addition, many importers are fixed layout. It would greatly benefit this tutorial if we showed how to transform the layout of a whole graph that is NCHW since many folks will hit this limitation coming from MxNet, Pytorch, ONNX etc.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] tmoreau89 commented on a change in pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for x86 CPU
Posted by GitBox <gi...@apache.org>.
tmoreau89 commented on a change in pull request #7019:
URL: https://github.com/apache/tvm/pull/7019#discussion_r534651971
##########
File path: tutorials/auto_scheduler/tune_network_x86.py
##########
@@ -0,0 +1,307 @@
+# 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.
+"""
+Auto-scheduling a Neural Network for x86 CPU
+============================================
+**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_
+
+Auto-tuning for specific devices and workloads is critical for getting the
+best performance. This is a tutorial on how to tune a whole neural
+network for x86 CPU with the auto-scheduler.
+
+To auto-tune a neural network, we partition the network into small subgraphs and
+tune them independently. Each subgraph is treated as one search task.
+A task scheduler slices the time and dynamically allocates time resources to
+these tasks. The task scheduler predicts the impact of each task on the end-to-end
+execution time and prioritizes the one that can reduce the execution time the most.
+
+For each subgraph, we use the compute declaration in :code:`tvm/python/topi` to
+get the computational DAG in the tensor expression form.
+We then use the auto-scheduler to construct a search space of this DAG and search
+for good schedules (low-level optimizations).
+
+Different from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on
+manual templates to define the search space, the auto-scheduler does not require any
+schedule templates. In other words, the auto-scheduler only uses the compute declarations
+in :code:`tvm/python/topi` while does not use existing schedule templates.
Review comment:
while does not ... templates -> and does not rely on schedule templates
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] merrymercy commented on a change in pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for x86 CPU
Posted by GitBox <gi...@apache.org>.
merrymercy commented on a change in pull request #7019:
URL: https://github.com/apache/tvm/pull/7019#discussion_r534700837
##########
File path: tutorials/auto_scheduler/tune_network_x86.py
##########
@@ -0,0 +1,307 @@
+# 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.
+"""
+Auto-scheduling a Neural Network for x86 CPU
+============================================
+**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_
+
+Auto-tuning for specific devices and workloads is critical for getting the
+best performance. This is a tutorial on how to tune a whole neural
+network for x86 CPU with the auto-scheduler.
+
+To auto-tune a neural network, we partition the network into small subgraphs and
+tune them independently. Each subgraph is treated as one search task.
+A task scheduler slices the time and dynamically allocates time resources to
+these tasks. The task scheduler predicts the impact of each task on the end-to-end
+execution time and prioritizes the one that can reduce the execution time the most.
+
+For each subgraph, we use the compute declaration in :code:`tvm/python/topi` to
+get the computational DAG in the tensor expression form.
+We then use the auto-scheduler to construct a search space of this DAG and search
+for good schedules (low-level optimizations).
+
+Different from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on
+manual templates to define the search space, the auto-scheduler does not require any
+schedule templates. In other words, the auto-scheduler only uses the compute declarations
+in :code:`tvm/python/topi` while does not use existing schedule templates.
+
+Note that this tutorial will not run on Windows or recent versions of macOS. To
+get it to run, you will need to wrap the body of this tutorial in a :code:`if
+__name__ == "__main__":` block.
+"""
+
+import numpy as np
+
+import tvm
+from tvm import relay, auto_scheduler
+import tvm.relay.testing
+from tvm.contrib import graph_runtime
+
+#################################################################
+# Define a Network
+# ----------------
+# First, we need to define the network with relay frontend API.
+# We can load some pre-defined network from :code:`tvm.relay.testing`.
+# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow
+# (see :ref:`front end tutorials<tutorial-frontend>`).
+#
+# For convolutional neural networks, although auto-scheduler can work
+# correctly with any layout, we found the best performance is typically
+# achieved with NHWC layout. We also implemented more optimizations for
+# NHWC layouts with the auto-scheduler.
+# So it is recommended to convert your models to NHWC layout to use
+# the auto-scheduler.
+
+
+def get_network(name, batch_size, layout="NHWC", dtype="float32"):
+ """Get the symbol definition and random weight of a network"""
+
+ # auto-scheduler prefers NHWC layout
+ if layout == "NHWC":
+ image_shape = (224, 224, 3)
+ elif layout == "NCHW":
+ image_shape = (3, 224, 224)
+ else:
+ raise ValueError("Invalid layout: " + layout)
+
+ input_shape = (batch_size,) + image_shape
+ output_shape = (batch_size, 1000)
+
+ if name.startswith("resnet-"):
+ n_layer = int(name.split("-")[1])
+ mod, params = relay.testing.resnet.get_workload(
+ num_layers=n_layer,
+ batch_size=batch_size,
+ layout=layout,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name.startswith("resnet3d-"):
+ n_layer = int(name.split("-")[1])
+ mod, params = relay.testing.resnet.get_workload(
+ num_layers=n_layer,
+ batch_size=batch_size,
+ layout=layout,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name == "mobilenet":
+ mod, params = relay.testing.mobilenet.get_workload(
+ batch_size=batch_size, layout=layout, dtype=dtype, image_shape=image_shape
+ )
+ elif name == "squeezenet_v1.1":
+ assert layout == "NCHW", "squeezenet_v1.1 only supports NCHW layout"
+ mod, params = relay.testing.squeezenet.get_workload(
+ version="1.1",
+ batch_size=batch_size,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name == "inception_v3":
+ input_shape = (batch_size, 3, 299, 299) if layout == "NCHW" else (batch_size, 299, 299, 3)
+ mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)
+ elif name == "mxnet":
+ # an example for mxnet model
+ from mxnet.gluon.model_zoo.vision import get_model
+
+ assert layout == "NCHW"
+
+ block = get_model("resnet50_v1", pretrained=True)
+ mod, params = relay.frontend.from_mxnet(block, shape={"data": input_shape}, dtype=dtype)
+ net = mod["main"]
+ net = relay.Function(
+ net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs
+ )
+ mod = tvm.IRModule.from_expr(net)
+
+ return mod, params, input_shape, output_shape
+
+
+# Define the neural network and compilation target.
+# If the target machine supports avx512 instructions, replace the
+# "llvm -mcpu=core-avx2" with "llvm -mcpu=skylake-avx512"
+network = "resnet-50"
+batch_size = 1
+layout = "NCHW"
+target = tvm.target.Target("llvm -mcpu=skylake-avx512")
+dtype = "float32"
+log_file = "%s-%s-B%d-%s.json" % (network, layout, batch_size, target.kind.name)
+
+#################################################################
+# Extract Search Tasks
+# --------------------
+# Next, we extract the search tasks and their weights from a network.
+# The weight of a task is the number of appearances of the task's subgraph
+# in the whole network.
+# By using the weight, we can approximate the end-to-end latency of the network
+# as :code:`sum(latency[t] * weight[t])`, where :code:`latency[t]` is the
+# latency of a task and :code:`weight[t]` is the weight of the task.
+# The task scheduler will just optimize this objective.
+
+# Extract tasks from the network
+print("Extract tasks...")
+mod, params, input_shape, output_shape = get_network(network, batch_size, layout, dtype=dtype)
+tasks, task_weights = auto_scheduler.extract_tasks(mod["main"], params, target)
Review comment:
Auto-scheduler can work with any layout. For NCHW, it can correctly extract tasks and tune them.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] merrymercy merged pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for x86 CPU
Posted by GitBox <gi...@apache.org>.
merrymercy merged pull request #7019:
URL: https://github.com/apache/tvm/pull/7019
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] comaniac commented on a change in pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for CPU
Posted by GitBox <gi...@apache.org>.
comaniac commented on a change in pull request #7019:
URL: https://github.com/apache/tvm/pull/7019#discussion_r534622889
##########
File path: tutorials/auto_scheduler/tune_network_x86.py
##########
@@ -0,0 +1,305 @@
+# 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.
+"""
+Auto-scheduling a Neural Network for x86 CPU
+===============================================
+**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_
+
+Auto-tuning for specific devices and workloads is critical for getting the
+best performance. This is a tutorial on how to tune a whole neural
+network for x86 CPU with the auto-scheduler.
+
+To auto-tune a neural network, we partition the network into small subgraphs and
+tune them independently. Each subgraph is treated as one search task.
+A task scheduler slices the time and dynamically allocates time resources to
+these tasks. The task scheduler predicts the impact of each task on the end-to-end
+execution time and prioritizes the one that can reduce the execution time the most.
+
+For each subgraph, we use the compute declaration in :code:`tvm/python/topi` to
+get the computational DAG in the tensor expression form.
+We then use the auto-scheduler to construct a search space of this DAG and search
+for good schedules (low-level optimizations).
+
+Different from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on
+manual templates to define the search space, the auto-scheduler does not require any
+schedule templates. In other words, the auto-scheduler only uses the compute declarations
+in :code:`tvm/python/topi` while does not use existing schedule templates.
+
+Note that this tutorial will not run on Windows or recent versions of macOS. To
+get it to run, you will need to wrap the body of this tutorial in a :code:`if
+__name__ == "__main__":` block.
+"""
+
+import numpy as np
+
+import tvm
+from tvm import relay, auto_scheduler
+import tvm.relay.testing
+from tvm.contrib import graph_runtime
+
+#################################################################
+# Define a Network
+# ----------------
+# First, we need to define the network with relay frontend API.
+# We can load some pre-defined network from :code:`tvm.relay.testing`.
+# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow
+# (see :ref:`front end tutorials<tutorial-frontend>`).
+#
+# Note that although auto-scheduler can work with any layouts,
+# we found that the best performance is typically archived with NHWC layout
+# for convolutional neural networks, so we use NHWC layout in this tutorial.
+#
+
+
+def get_network(name, batch_size, layout="NHWC", dtype="float32"):
+ """Get the symbol definition and random weight of a network"""
+
+ # auto-scheduler prefers NHWC layout
+ if layout == "NHWC":
+ image_shape = (224, 224, 3)
+ elif layout == "NCHW":
+ image_shape = (3, 224, 224)
+ else:
+ raise ValueError("Invalid layout: " + layout)
+
+ input_shape = (batch_size,) + image_shape
+ output_shape = (batch_size, 1000)
+
+ if name.startswith("resnet-"):
+ n_layer = int(name.split("-")[1])
+ mod, params = relay.testing.resnet.get_workload(
+ num_layers=n_layer,
+ batch_size=batch_size,
+ layout=layout,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name.startswith("resnet3d-"):
+ n_layer = int(name.split("-")[1])
+ mod, params = relay.testing.resnet.get_workload(
+ num_layers=n_layer,
+ batch_size=batch_size,
+ layout=layout,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name == "mobilenet":
+ mod, params = relay.testing.mobilenet.get_workload(
+ batch_size=batch_size, layout=layout, dtype=dtype, image_shape=image_shape
+ )
+ elif name == "squeezenet_v1.1":
+ assert layout == "NCHW", "squeezenet_v1.1 only supports NCHW layout"
+ mod, params = relay.testing.squeezenet.get_workload(
+ version="1.1",
+ batch_size=batch_size,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name == "inception_v3":
+ input_shape = (batch_size, 3, 299, 299) if layout == "NCHW" else (batch_size, 299, 299, 3)
+ mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)
+ elif name == "mxnet":
+ # an example for mxnet model
+ from mxnet.gluon.model_zoo.vision import get_model
+
+ assert layout == "NCHW"
+
+ block = get_model("resnet50_v1", pretrained=True)
+ mod, params = relay.frontend.from_mxnet(block, shape={"data": input_shape}, dtype=dtype)
+ net = mod["main"]
+ net = relay.Function(
+ net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs
+ )
+ mod = tvm.IRModule.from_expr(net)
+
+ return mod, params, input_shape, output_shape
+
+
+# Define the neural network and compilation target.
+# If the target machine supports avx512 instructions, replace the
+# "llvm -mcpu=core-avx2" with "llvm -mcpu=skylake-avx512"
+network = "resnet-50"
+batch_size = 1
+layout = "NHWC"
+target = tvm.target.Target("llvm -mcpu=core-avx2")
+dtype = "float32"
+log_file = "%s-%s-B%d-%s.json" % (network, layout, batch_size, target.kind.name)
+
+#################################################################
+# Extract Search Tasks
+# --------------------
+# Next, we extract the search tasks and their weights from a network.
+# The weight of a task is the number of appearances of the task's subgraph
+# in the whole network.
+# By using the weight, we can approximate the end-to-end latency of the network
+# as :code:`sum(latency[t] * weight[t])`, where :code:`latency[t]` is the
+# latency of a task and :code:`weight[t]` is the weight of the task.
+# The task scheduler will just optimize this objective.
+
+# Extract tasks from the network
+print("Extract tasks...")
+mod, params, input_shape, output_shape = get_network(network, batch_size, layout, dtype=dtype)
+tasks, task_weights = auto_scheduler.extract_tasks(mod["main"], params, target)
+
+for idx, task in enumerate(tasks):
+ print("========== Task %d (workload key: %s) ==========" % (idx, task.workload_key))
+ print(task.compute_dag)
+
+#################################################################
+# Begin Tuning
+# ------------
+# Now, we set some options for tuning and launch the search tasks
+#
+# * :code:`num_measure_trials` is the number of measurement trials we can use during the tuning.
+# You can set it to a small number (e.g., 200) for a fast demonstrative run.
+# In practice, we recommend setting it around :code:`800 * len(tasks)`,
+# which is typically enough for the search to converge.
+# For example, there are 29 tasks in resnet-50, so we can set it as 20000.
+# You can adjust this parameter according to your time budget.
+# * In addition, we use :code:`RecordToFile` to dump measurement records into a log file,
+# The measurement records can be used to query the history best, resume the search,
+# and do more analyses later.
+# * see :any:`auto_scheduler.TuningOptions`,
+# :any:`auto_scheduler.LocalRunner` for more parameters.
+#
+
+
+def run_tuning():
+ print("Begin tuning...")
+ tuner = auto_scheduler.TaskScheduler(tasks, task_weights)
+ tune_option = auto_scheduler.TuningOptions(
+ num_measure_trials=200, # change this to 20000 to achieve the best performance
+ runner=auto_scheduler.LocalRunner(repeat=10, enable_cpu_cache_flush=True),
+ measure_callbacks=[auto_scheduler.RecordToFile(log_file)],
+ )
+
+ tuner.tune(tune_option)
+
+
+# We do not run the tuning in our webpage server since it takes too long.
+# Uncomment the following line to run it by yourself.
+
+# run_tuning()
+
+
+######################################################################
+# .. note:: Explain the printed information during tuning
+#
+# During the tuning, a lot of information will be printed on the console.
+# They are used for debugging purposes. The most important info is the output
+# of the task scheduler. The following table is a sample output.
+#
+# .. code-block:: c
+#
+# ----------------------------------------------------------------------
+# ------------------------------ [ Task Scheduler ]
+# ----------------------------------------------------------------------
+# | ID | Latency (ms) | Speed (GFLOPS) | Trials |
+# -------------------------------------------------
+# | 0 | 0.010 | 0.40 | 64 |
+# | 1 | 0.087 | 47.19 | 64 |
+# | 2 | 0.008 | -0.00 | 64 |
Review comment:
As @masahi pointed out in the forum, it would be better to explain why we got `-0.00` for this task.
##########
File path: tutorials/auto_scheduler/tune_network_x86.py
##########
@@ -0,0 +1,305 @@
+# 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.
+"""
+Auto-scheduling a Neural Network for x86 GPU
+===============================================
Review comment:
```suggestion
============================================
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [tvm] merrymercy commented on a change in pull request #7019: [AutoScheduler] Add a tutorial on auto-scheduling a network for x86 CPU
Posted by GitBox <gi...@apache.org>.
merrymercy commented on a change in pull request #7019:
URL: https://github.com/apache/tvm/pull/7019#discussion_r534755166
##########
File path: tutorials/auto_scheduler/tune_network_x86.py
##########
@@ -0,0 +1,307 @@
+# 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.
+"""
+Auto-scheduling a Neural Network for x86 CPU
+============================================
+**Author**: `Lianmin Zheng <https://github.com/merrymercy>`_
+
+Auto-tuning for specific devices and workloads is critical for getting the
+best performance. This is a tutorial on how to tune a whole neural
+network for x86 CPU with the auto-scheduler.
+
+To auto-tune a neural network, we partition the network into small subgraphs and
+tune them independently. Each subgraph is treated as one search task.
+A task scheduler slices the time and dynamically allocates time resources to
+these tasks. The task scheduler predicts the impact of each task on the end-to-end
+execution time and prioritizes the one that can reduce the execution time the most.
+
+For each subgraph, we use the compute declaration in :code:`tvm/python/topi` to
+get the computational DAG in the tensor expression form.
+We then use the auto-scheduler to construct a search space of this DAG and search
+for good schedules (low-level optimizations).
+
+Different from the template-based :ref:`autotvm <tutorials-autotvm-sec>` which relies on
+manual templates to define the search space, the auto-scheduler does not require any
+schedule templates. In other words, the auto-scheduler only uses the compute declarations
+in :code:`tvm/python/topi` and does not use existing schedule templates.
+
+Note that this tutorial will not run on Windows or recent versions of macOS. To
+get it to run, you will need to wrap the body of this tutorial in a :code:`if
+__name__ == "__main__":` block.
+"""
+
+import numpy as np
+
+import tvm
+from tvm import relay, auto_scheduler
+import tvm.relay.testing
+from tvm.contrib import graph_runtime
+
+#################################################################
+# Define a Network
+# ----------------
+# First, we need to define the network with relay frontend API.
+# We can load some pre-defined network from :code:`tvm.relay.testing`.
+# We can also load models from MXNet, ONNX, PyTorch, and TensorFlow
+# (see :ref:`front end tutorials<tutorial-frontend>`).
+#
+# For convolutional neural networks, although auto-scheduler can work
+# correctly with any layout, we found the best performance is typically
+# achieved with NHWC layout. We also implemented more optimizations for
+# NHWC layouts with the auto-scheduler.
+# So it is recommended to convert your models to NHWC layout to use
+# the auto-scheduler.
+
+
+def get_network(name, batch_size, layout="NHWC", dtype="float32"):
+ """Get the symbol definition and random weight of a network"""
+
+ # auto-scheduler prefers NHWC layout
+ if layout == "NHWC":
+ image_shape = (224, 224, 3)
+ elif layout == "NCHW":
+ image_shape = (3, 224, 224)
+ else:
+ raise ValueError("Invalid layout: " + layout)
+
+ input_shape = (batch_size,) + image_shape
+ output_shape = (batch_size, 1000)
+
+ if name.startswith("resnet-"):
+ n_layer = int(name.split("-")[1])
+ mod, params = relay.testing.resnet.get_workload(
+ num_layers=n_layer,
+ batch_size=batch_size,
+ layout=layout,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name.startswith("resnet3d-"):
+ n_layer = int(name.split("-")[1])
+ mod, params = relay.testing.resnet.get_workload(
+ num_layers=n_layer,
+ batch_size=batch_size,
+ layout=layout,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name == "mobilenet":
+ mod, params = relay.testing.mobilenet.get_workload(
+ batch_size=batch_size, layout=layout, dtype=dtype, image_shape=image_shape
+ )
+ elif name == "squeezenet_v1.1":
+ assert layout == "NCHW", "squeezenet_v1.1 only supports NCHW layout"
+ mod, params = relay.testing.squeezenet.get_workload(
+ version="1.1",
+ batch_size=batch_size,
+ dtype=dtype,
+ image_shape=image_shape,
+ )
+ elif name == "inception_v3":
+ input_shape = (batch_size, 3, 299, 299) if layout == "NCHW" else (batch_size, 299, 299, 3)
+ mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)
+ elif name == "mxnet":
+ # an example for mxnet model
+ from mxnet.gluon.model_zoo.vision import get_model
+
+ assert layout == "NCHW"
+
+ block = get_model("resnet50_v1", pretrained=True)
+ mod, params = relay.frontend.from_mxnet(block, shape={"data": input_shape}, dtype=dtype)
+ net = mod["main"]
+ net = relay.Function(
+ net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs
+ )
+ mod = tvm.IRModule.from_expr(net)
+
+ return mod, params, input_shape, output_shape
+
+
+# Define the neural network and compilation target.
+# If the target machine supports avx512 instructions, replace the
+# "llvm -mcpu=core-avx2" with "llvm -mcpu=skylake-avx512"
+network = "resnet-50"
+batch_size = 1
+layout = "NHWC"
+target = tvm.target.Target("llvm -mcpu=skylake-avx512")
+dtype = "float32"
+log_file = "%s-%s-B%d-%s.json" % (network, layout, batch_size, target.kind.name)
+
+#################################################################
+# Extract Search Tasks
+# --------------------
+# Next, we extract the search tasks and their weights from a network.
+# The weight of a task is the number of appearances of the task's subgraph
+# in the whole network.
+# By using the weight, we can approximate the end-to-end latency of the network
+# as :code:`sum(latency[t] * weight[t])`, where :code:`latency[t]` is the
+# latency of a task and :code:`weight[t]` is the weight of the task.
+# The task scheduler will just optimize this objective.
+
+# Extract tasks from the network
+print("Extract tasks...")
+mod, params, input_shape, output_shape = get_network(network, batch_size, layout, dtype=dtype)
+tasks, task_weights = auto_scheduler.extract_tasks(mod["main"], params, target)
+
+for idx, task in enumerate(tasks):
+ print("========== Task %d (workload key: %s) ==========" % (idx, task.workload_key))
+ print(task.compute_dag)
+
+#################################################################
+# Begin Tuning
+# ------------
+# Now, we set some options for tuning and launch the search tasks
+#
+# * :code:`num_measure_trials` is the number of measurement trials we can use during the tuning.
+# You can set it to a small number (e.g., 200) for a fast demonstrative run.
+# In practice, we recommend setting it around :code:`800 * len(tasks)`,
Review comment:
GPU has a larger search space so it should use a larger value.
1000 is typically too much.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org