Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .ci/scripts/test_model.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -164,6 +164,7 @@ test_model_with_qnn() {
export LD_LIBRARY_PATH=$QNN_SDK_ROOT/lib/x86_64-linux-clang/
export PYTHONPATH=$EXECUTORCH_ROOT/..

EXTRA_FLAGS=""
if [[ "${MODEL_NAME}" == "dl3" ]]; then
EXPORT_SCRIPT=deeplab_v3
elif [[ "${MODEL_NAME}" == "mv3" ]]; then
Expand All@@ -176,6 +177,12 @@ test_model_with_qnn() {
EXPORT_SCRIPT=inception_v3
elif [[ "${MODEL_NAME}" == "vit" ]]; then
EXPORT_SCRIPT=torchvision_vit
elif [[ "${MODEL_NAME}" == "mb" ]]; then
EXPORT_SCRIPT=mobilebert_fine_tune
EXTRA_FLAGS="--num_epochs 1"
pip install scikit-learn
elif [[ "${MODEL_NAME}" == "w2l" ]]; then
EXPORT_SCRIPT=wav2letter
elif [[ "${MODEL_NAME}" == "edsr" ]]; then
EXPORT_SCRIPT=edsr
# Additional deps for edsr
Expand All@@ -189,7 +196,7 @@ test_model_with_qnn() {
# TODO(guangyang): Make QNN chipset matches the target device
QNN_CHIPSET=SM8450

"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only
"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only $EXTRA_FLAGS
EXPORTED_MODEL=$(find "./${EXPORT_SCRIPT}" -type f -name "${MODEL_NAME}*.pte" -print -quit)
}

Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/trunk.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -311,7 +311,7 @@ jobs:
strategy:
matrix:
dtype: [fp32]
model: [dl3, mv3, mv2, ic4, ic3, vit]
model: [dl3, mv3, mv2, ic4, ic3, vit, mb, w2l]
fail-fast: false
with:
runner: linux.2xlarge
Expand Down
22 changes: 10 additions & 12 deletions backends/qualcomm/tests/test_qnn_delegate.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,7 @@
from executorch.examples.models.mobilenet_v3 import MV3Model
from executorch.examples.models.torchvision_vit.model import TorchVisionViTModel

# from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.exir import to_edge
from executorch.exir.backend.backend_api import disable_validation
from executorch.exir.passes import PassManager
Expand DownExpand Up@@ -907,8 +907,7 @@ def test_qnn_backend_example_models(self):
# Fail during lowering Reopen once resolved
# MobileBertModelExample(),
# TorchVisionViTModel(),
# Encountered undefined symbol in mainline. Reopen once resolved.
# Wav2LetterModel(),
Wav2LetterModel(),
]
expected_partitions = [
1,
Expand All@@ -917,8 +916,8 @@ def test_qnn_backend_example_models(self):
1,
1,
1,
1,
1,
# 1,
# 1,
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
Expand DownExpand Up@@ -1962,12 +1961,11 @@ def test_qnn_backend_example_models(self):
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
# Encountered undefined symbol in mainline. Reopen once resolved.
# {
# QCOM_MODULE: Wav2LetterModel(),
# QCOM_ANNOTATION: (),
# QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
# },
{
QCOM_MODULE: Wav2LetterModel(),
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
]
expected_partitions = [
1,
Expand All@@ -1979,7 +1977,7 @@ def test_qnn_backend_example_models(self):
# For MobileBertModelExample
# 1,
1,
# 1, For Wav2LetterModel
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
disable_validation()
Expand Down
5 changes: 4 additions & 1 deletion examples/qualcomm/oss_scripts/llama/llama.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -843,6 +843,7 @@ def post_process():
)

runner_cmd = ""
performance_output_path = "outputs/inference_speed.txt"
if args.enable_x86_64:
# x86 emulator is intended for CI and not performance. Check only the first few tokens.
seq_len = min(seq_len, 16)
Expand All@@ -862,6 +863,7 @@ def post_process():
f"--model_path {pte_path}",
f"--seq_len {seq_len}",
f"--output_path {args.artifact}/outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater ShiftPointer",
runner_args,
]
Expand All@@ -882,6 +884,7 @@ def post_process():
f"--model_path {pte_filename}.pte",
f"--seq_len {seq_len}",
"--output_path outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater {'SmartMask' if args.kv_updater == smart_mask_updater else 'ShiftPointer'}",
runner_args,
]
Expand All@@ -905,7 +908,7 @@ def post_process():
adb.pull(output_path=args.artifact, callback=post_process)
if args.ip and args.port != -1:
inference_speed = 0
with open(f"{args.artifact}/outputs/inference_speed.txt", "r") as f:
with open(f"{args.artifact}/{performance_output_path}", "r") as f:
inference_speed = float(f.read())

pte_size = os.path.getsize(pte_path)
Expand Down
5 changes: 5 additions & 0 deletions examples/qualcomm/oss_scripts/llama/qnn_llama_runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,10 @@ DEFINE_string(
output_path,
"outputs.txt",
"Executorch inference data output path.");
DEFINE_string(
performance_output_path,
"inference_speed.txt",
"Records inference speed. For CI purpose.");
DEFINE_string(tokenizer_path, "tokenizer.bin", "Tokenizer stuff.");
DEFINE_string(prompt, "The answer to the ultimate question is", "Prompt.");
DEFINE_string(
Expand DownExpand Up@@ -63,6 +67,7 @@ int main(int argc, char** argv) {
example::Runner runner(
{FLAGS_model_path},
FLAGS_tokenizer_path.c_str(),
FLAGS_performance_output_path.c_str(),
FLAGS_logits_scale,
FLAGS_logits_offset,
FLAGS_temperature,
Expand Down
15 changes: 11 additions & 4 deletions examples/qualcomm/oss_scripts/llama/runner/runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,13 +34,16 @@ namespace example {

namespace {
static constexpr auto kTopp = 0.9f;
void printReport(const Runner::Stats& stats);
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path);
std::string statsToJsonString(const Runner::Stats& stats);
} // namespace

Runner::Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand All@@ -49,6 +52,7 @@ Runner::Runner(
: n_bos_(1),
n_eos_(1),
tokenizer_path_(tokenizer_path),
performance_output_path_(performance_output_path),
logits_scale_(logits_scale),
logits_offset_(logits_offset),
temperature_(temperature),
Expand DownExpand Up@@ -437,7 +441,7 @@ Error Runner::generate(

stats_.num_prompt_tokens = num_prompt_tokens;
stats_.num_generated_tokens = pos - num_prompt_tokens;
printReport(stats_);
printReport(stats_, performance_output_path_);
if (stats_callback) {
stats_callback(stats_);
}
Expand All@@ -446,7 +450,9 @@ Error Runner::generate(
}

namespace {
void printReport(const Runner::Stats& stats) {
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path) {
printf("PyTorchObserver %s\n", statsToJsonString(stats).c_str());

ET_LOG(
Expand DownExpand Up@@ -507,7 +513,8 @@ void printReport(const Runner::Stats& stats) {

// For now, we just print the total inference time for CI, can save more info
// in future if needed.
std::ofstream outfile("outputs/inference_speed.txt");

std::ofstream outfile(performance_output_path.c_str());
if (outfile.is_open()) {
double num_tok = (stats.num_generated_tokens) /
(double)(stats.inference_end_ms - stats.inference_start_ms) *
Expand Down
2 changes: 2 additions & 0 deletions examples/qualcomm/oss_scripts/llama/runner/runner.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@ class Runner {
explicit Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path_,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand DownExpand Up@@ -101,6 +102,7 @@ class Runner {
const int32_t n_eos_;
std::vector<std::shared_ptr<executorch::extension::Module>> modules_;
std::string tokenizer_path_;
std::string performance_output_path_;
float logits_scale_;
int32_t logits_offset_;
float temperature_;
Expand Down
9 changes: 8 additions & 1 deletion examples/qualcomm/scripts/mobilebert_fine_tune.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -169,7 +169,7 @@ def get_fine_tuned_mobilebert(artifacts_dir, pretrained_weight, batch_size):
dataset_train = TensorDataset(input_ids_train, attention_masks_train, labels_train)
dataset_val = TensorDataset(input_ids_val, attention_masks_val, labels_val)

epochs = 5
epochs = args.num_epochs
dataloader_train = DataLoader(
dataset_train,
sampler=RandomSampler(dataset_train),
Expand DownExpand Up@@ -366,6 +366,13 @@ def calibrator(gm):
type=str,
)

parser.add_argument(
"--num_epochs",
help="If no pretrained weights are provided, set number of epochs to train the model",
default=5,
type=int,
)

parser.add_argument(
"-F",
"--use_fp16",
Expand Down
22 changes: 17 additions & 5 deletions examples/qualcomm/scripts/wav2letter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
# LICENSE file in the root directory of this source tree.

import json
import logging
import os
import sys
from multiprocessing.connection import Client
Expand DownExpand Up@@ -111,7 +112,12 @@ def main(args):
# target labels " abcdefghijklmnopqrstuvwxyz'*"
instance.vocab_size = 29
model = instance.get_eager_model().eval()
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
if args.pretrained_weight:
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
else:
logging.warning(
"It is strongly recommended to provide pretrained weights, otherwise accuracy will be bad. This option is here mainly for CI purpose to ensure compile is successful."
)

# convert conv1d to conv2d in nn.Module level will only introduce 2 permute
# nodes around input & output, which is more quantization friendly.
Expand All@@ -128,9 +134,15 @@ def main(args):

# retrieve dataset, will take some time to download
data_num = 100
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
if args.compile_only:
inputs = [(torch.rand(1, 1, 700, 1),)]
logging.warning(
"With compile_only, accuracy will be bad due to insufficient datasets for quantization."
)
else:
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
pte_filename = "w2l_qnn"
build_executorch_binary(
model,
Expand DownExpand Up@@ -212,7 +224,7 @@ def main(args):
),
default=None,
type=str,
required=True,
required=False,
)

args = parser.parse_args()
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .ci/scripts/test_model.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -164,6 +164,7 @@ test_model_with_qnn() {
export LD_LIBRARY_PATH=$QNN_SDK_ROOT/lib/x86_64-linux-clang/
export PYTHONPATH=$EXECUTORCH_ROOT/..

EXTRA_FLAGS=""
if [[ "${MODEL_NAME}" == "dl3" ]]; then
EXPORT_SCRIPT=deeplab_v3
elif [[ "${MODEL_NAME}" == "mv3" ]]; then
Expand All@@ -176,6 +177,12 @@ test_model_with_qnn() {
EXPORT_SCRIPT=inception_v3
elif [[ "${MODEL_NAME}" == "vit" ]]; then
EXPORT_SCRIPT=torchvision_vit
elif [[ "${MODEL_NAME}" == "mb" ]]; then
EXPORT_SCRIPT=mobilebert_fine_tune
EXTRA_FLAGS="--num_epochs 1"
pip install scikit-learn
elif [[ "${MODEL_NAME}" == "w2l" ]]; then
EXPORT_SCRIPT=wav2letter
elif [[ "${MODEL_NAME}" == "edsr" ]]; then
EXPORT_SCRIPT=edsr
# Additional deps for edsr
Expand All@@ -189,7 +196,7 @@ test_model_with_qnn() {
# TODO(guangyang): Make QNN chipset matches the target device
QNN_CHIPSET=SM8450

"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only
"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only $EXTRA_FLAGS
EXPORTED_MODEL=$(find "./${EXPORT_SCRIPT}" -type f -name "${MODEL_NAME}*.pte" -print -quit)
}

Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/trunk.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -311,7 +311,7 @@ jobs:
strategy:
matrix:
dtype: [fp32]
model: [dl3, mv3, mv2, ic4, ic3, vit]
model: [dl3, mv3, mv2, ic4, ic3, vit, mb, w2l]
fail-fast: false
with:
runner: linux.2xlarge
Expand Down
22 changes: 10 additions & 12 deletions backends/qualcomm/tests/test_qnn_delegate.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,7 @@
from executorch.examples.models.mobilenet_v3 import MV3Model
from executorch.examples.models.torchvision_vit.model import TorchVisionViTModel

# from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.exir import to_edge
from executorch.exir.backend.backend_api import disable_validation
from executorch.exir.passes import PassManager
Expand DownExpand Up@@ -907,8 +907,7 @@ def test_qnn_backend_example_models(self):
# Fail during lowering Reopen once resolved
# MobileBertModelExample(),
# TorchVisionViTModel(),
# Encountered undefined symbol in mainline. Reopen once resolved.
# Wav2LetterModel(),
Wav2LetterModel(),
]
expected_partitions = [
1,
Expand All@@ -917,8 +916,8 @@ def test_qnn_backend_example_models(self):
1,
1,
1,
1,
1,
# 1,
# 1,
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
Expand DownExpand Up@@ -1962,12 +1961,11 @@ def test_qnn_backend_example_models(self):
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
# Encountered undefined symbol in mainline. Reopen once resolved.
# {
# QCOM_MODULE: Wav2LetterModel(),
# QCOM_ANNOTATION: (),
# QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
# },
{
QCOM_MODULE: Wav2LetterModel(),
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
]
expected_partitions = [
1,
Expand All@@ -1979,7 +1977,7 @@ def test_qnn_backend_example_models(self):
# For MobileBertModelExample
# 1,
1,
# 1, For Wav2LetterModel
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
disable_validation()
Expand Down
5 changes: 4 additions & 1 deletion examples/qualcomm/oss_scripts/llama/llama.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -843,6 +843,7 @@ def post_process():
)

runner_cmd = ""
performance_output_path = "outputs/inference_speed.txt"
if args.enable_x86_64:
# x86 emulator is intended for CI and not performance. Check only the first few tokens.
seq_len = min(seq_len, 16)
Expand All@@ -862,6 +863,7 @@ def post_process():
f"--model_path {pte_path}",
f"--seq_len {seq_len}",
f"--output_path {args.artifact}/outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater ShiftPointer",
runner_args,
]
Expand All@@ -882,6 +884,7 @@ def post_process():
f"--model_path {pte_filename}.pte",
f"--seq_len {seq_len}",
"--output_path outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater {'SmartMask' if args.kv_updater == smart_mask_updater else 'ShiftPointer'}",
runner_args,
]
Expand All@@ -905,7 +908,7 @@ def post_process():
adb.pull(output_path=args.artifact, callback=post_process)
if args.ip and args.port != -1:
inference_speed = 0
with open(f"{args.artifact}/outputs/inference_speed.txt", "r") as f:
with open(f"{args.artifact}/{performance_output_path}", "r") as f:
inference_speed = float(f.read())

pte_size = os.path.getsize(pte_path)
Expand Down
5 changes: 5 additions & 0 deletions examples/qualcomm/oss_scripts/llama/qnn_llama_runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,10 @@ DEFINE_string(
output_path,
"outputs.txt",
"Executorch inference data output path.");
DEFINE_string(
performance_output_path,
"inference_speed.txt",
"Records inference speed. For CI purpose.");
DEFINE_string(tokenizer_path, "tokenizer.bin", "Tokenizer stuff.");
DEFINE_string(prompt, "The answer to the ultimate question is", "Prompt.");
DEFINE_string(
Expand DownExpand Up@@ -63,6 +67,7 @@ int main(int argc, char** argv) {
example::Runner runner(
{FLAGS_model_path},
FLAGS_tokenizer_path.c_str(),
FLAGS_performance_output_path.c_str(),
FLAGS_logits_scale,
FLAGS_logits_offset,
FLAGS_temperature,
Expand Down
15 changes: 11 additions & 4 deletions examples/qualcomm/oss_scripts/llama/runner/runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,13 +34,16 @@ namespace example {

namespace {
static constexpr auto kTopp = 0.9f;
void printReport(const Runner::Stats& stats);
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path);
std::string statsToJsonString(const Runner::Stats& stats);
} // namespace

Runner::Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand All@@ -49,6 +52,7 @@ Runner::Runner(
: n_bos_(1),
n_eos_(1),
tokenizer_path_(tokenizer_path),
performance_output_path_(performance_output_path),
logits_scale_(logits_scale),
logits_offset_(logits_offset),
temperature_(temperature),
Expand DownExpand Up@@ -437,7 +441,7 @@ Error Runner::generate(

stats_.num_prompt_tokens = num_prompt_tokens;
stats_.num_generated_tokens = pos - num_prompt_tokens;
printReport(stats_);
printReport(stats_, performance_output_path_);
if (stats_callback) {
stats_callback(stats_);
}
Expand All@@ -446,7 +450,9 @@ Error Runner::generate(
}

namespace {
void printReport(const Runner::Stats& stats) {
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path) {
printf("PyTorchObserver %s\n", statsToJsonString(stats).c_str());

ET_LOG(
Expand DownExpand Up@@ -507,7 +513,8 @@ void printReport(const Runner::Stats& stats) {

// For now, we just print the total inference time for CI, can save more info
// in future if needed.
std::ofstream outfile("outputs/inference_speed.txt");

std::ofstream outfile(performance_output_path.c_str());
if (outfile.is_open()) {
double num_tok = (stats.num_generated_tokens) /
(double)(stats.inference_end_ms - stats.inference_start_ms) *
Expand Down
2 changes: 2 additions & 0 deletions examples/qualcomm/oss_scripts/llama/runner/runner.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@ class Runner {
explicit Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path_,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand DownExpand Up@@ -101,6 +102,7 @@ class Runner {
const int32_t n_eos_;
std::vector<std::shared_ptr<executorch::extension::Module>> modules_;
std::string tokenizer_path_;
std::string performance_output_path_;
float logits_scale_;
int32_t logits_offset_;
float temperature_;
Expand Down
9 changes: 8 additions & 1 deletion examples/qualcomm/scripts/mobilebert_fine_tune.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -169,7 +169,7 @@ def get_fine_tuned_mobilebert(artifacts_dir, pretrained_weight, batch_size):
dataset_train = TensorDataset(input_ids_train, attention_masks_train, labels_train)
dataset_val = TensorDataset(input_ids_val, attention_masks_val, labels_val)

epochs = 5
epochs = args.num_epochs
dataloader_train = DataLoader(
dataset_train,
sampler=RandomSampler(dataset_train),
Expand DownExpand Up@@ -366,6 +366,13 @@ def calibrator(gm):
type=str,
)

parser.add_argument(
"--num_epochs",
help="If no pretrained weights are provided, set number of epochs to train the model",
default=5,
type=int,
)

parser.add_argument(
"-F",
"--use_fp16",
Expand Down
22 changes: 17 additions & 5 deletions examples/qualcomm/scripts/wav2letter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
# LICENSE file in the root directory of this source tree.

import json
import logging
import os
import sys
from multiprocessing.connection import Client
Expand DownExpand Up@@ -111,7 +112,12 @@ def main(args):
# target labels " abcdefghijklmnopqrstuvwxyz'*"
instance.vocab_size = 29
model = instance.get_eager_model().eval()
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
if args.pretrained_weight:
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
else:
logging.warning(
"It is strongly recommended to provide pretrained weights, otherwise accuracy will be bad. This option is here mainly for CI purpose to ensure compile is successful."
)

# convert conv1d to conv2d in nn.Module level will only introduce 2 permute
# nodes around input & output, which is more quantization friendly.
Expand All@@ -128,9 +134,15 @@ def main(args):

# retrieve dataset, will take some time to download
data_num = 100
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
if args.compile_only:
inputs = [(torch.rand(1, 1, 700, 1),)]
logging.warning(
"With compile_only, accuracy will be bad due to insufficient datasets for quantization."
)
else:
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
pte_filename = "w2l_qnn"
build_executorch_binary(
model,
Expand DownExpand Up@@ -212,7 +224,7 @@ def main(args):
),
default=None,
type=str,
required=True,
required=False,
)

args = parser.parse_args()
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .ci/scripts/test_model.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -164,6 +164,7 @@ test_model_with_qnn() {
export LD_LIBRARY_PATH=$QNN_SDK_ROOT/lib/x86_64-linux-clang/
export PYTHONPATH=$EXECUTORCH_ROOT/..

EXTRA_FLAGS=""
if [[ "${MODEL_NAME}" == "dl3" ]]; then
EXPORT_SCRIPT=deeplab_v3
elif [[ "${MODEL_NAME}" == "mv3" ]]; then
Expand All@@ -176,6 +177,12 @@ test_model_with_qnn() {
EXPORT_SCRIPT=inception_v3
elif [[ "${MODEL_NAME}" == "vit" ]]; then
EXPORT_SCRIPT=torchvision_vit
elif [[ "${MODEL_NAME}" == "mb" ]]; then
EXPORT_SCRIPT=mobilebert_fine_tune
EXTRA_FLAGS="--num_epochs 1"
pip install scikit-learn
elif [[ "${MODEL_NAME}" == "w2l" ]]; then
EXPORT_SCRIPT=wav2letter
elif [[ "${MODEL_NAME}" == "edsr" ]]; then
EXPORT_SCRIPT=edsr
# Additional deps for edsr
Expand All@@ -189,7 +196,7 @@ test_model_with_qnn() {
# TODO(guangyang): Make QNN chipset matches the target device
QNN_CHIPSET=SM8450

"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only
"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only $EXTRA_FLAGS
EXPORTED_MODEL=$(find "./${EXPORT_SCRIPT}" -type f -name "${MODEL_NAME}*.pte" -print -quit)
}

Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/trunk.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -311,7 +311,7 @@ jobs:
strategy:
matrix:
dtype: [fp32]
model: [dl3, mv3, mv2, ic4, ic3, vit]
model: [dl3, mv3, mv2, ic4, ic3, vit, mb, w2l]
fail-fast: false
with:
runner: linux.2xlarge
Expand Down
22 changes: 10 additions & 12 deletions backends/qualcomm/tests/test_qnn_delegate.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,7 @@
from executorch.examples.models.mobilenet_v3 import MV3Model
from executorch.examples.models.torchvision_vit.model import TorchVisionViTModel

# from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.exir import to_edge
from executorch.exir.backend.backend_api import disable_validation
from executorch.exir.passes import PassManager
Expand DownExpand Up@@ -907,8 +907,7 @@ def test_qnn_backend_example_models(self):
# Fail during lowering Reopen once resolved
# MobileBertModelExample(),
# TorchVisionViTModel(),
# Encountered undefined symbol in mainline. Reopen once resolved.
# Wav2LetterModel(),
Wav2LetterModel(),
]
expected_partitions = [
1,
Expand All@@ -917,8 +916,8 @@ def test_qnn_backend_example_models(self):
1,
1,
1,
1,
1,
# 1,
# 1,
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
Expand DownExpand Up@@ -1962,12 +1961,11 @@ def test_qnn_backend_example_models(self):
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
# Encountered undefined symbol in mainline. Reopen once resolved.
# {
# QCOM_MODULE: Wav2LetterModel(),
# QCOM_ANNOTATION: (),
# QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
# },
{
QCOM_MODULE: Wav2LetterModel(),
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
]
expected_partitions = [
1,
Expand All@@ -1979,7 +1977,7 @@ def test_qnn_backend_example_models(self):
# For MobileBertModelExample
# 1,
1,
# 1, For Wav2LetterModel
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
disable_validation()
Expand Down
5 changes: 4 additions & 1 deletion examples/qualcomm/oss_scripts/llama/llama.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -843,6 +843,7 @@ def post_process():
)

runner_cmd = ""
performance_output_path = "outputs/inference_speed.txt"
if args.enable_x86_64:
# x86 emulator is intended for CI and not performance. Check only the first few tokens.
seq_len = min(seq_len, 16)
Expand All@@ -862,6 +863,7 @@ def post_process():
f"--model_path {pte_path}",
f"--seq_len {seq_len}",
f"--output_path {args.artifact}/outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater ShiftPointer",
runner_args,
]
Expand All@@ -882,6 +884,7 @@ def post_process():
f"--model_path {pte_filename}.pte",
f"--seq_len {seq_len}",
"--output_path outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater {'SmartMask' if args.kv_updater == smart_mask_updater else 'ShiftPointer'}",
runner_args,
]
Expand All@@ -905,7 +908,7 @@ def post_process():
adb.pull(output_path=args.artifact, callback=post_process)
if args.ip and args.port != -1:
inference_speed = 0
with open(f"{args.artifact}/outputs/inference_speed.txt", "r") as f:
with open(f"{args.artifact}/{performance_output_path}", "r") as f:
inference_speed = float(f.read())

pte_size = os.path.getsize(pte_path)
Expand Down
5 changes: 5 additions & 0 deletions examples/qualcomm/oss_scripts/llama/qnn_llama_runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,10 @@ DEFINE_string(
output_path,
"outputs.txt",
"Executorch inference data output path.");
DEFINE_string(
performance_output_path,
"inference_speed.txt",
"Records inference speed. For CI purpose.");
DEFINE_string(tokenizer_path, "tokenizer.bin", "Tokenizer stuff.");
DEFINE_string(prompt, "The answer to the ultimate question is", "Prompt.");
DEFINE_string(
Expand DownExpand Up@@ -63,6 +67,7 @@ int main(int argc, char** argv) {
example::Runner runner(
{FLAGS_model_path},
FLAGS_tokenizer_path.c_str(),
FLAGS_performance_output_path.c_str(),
FLAGS_logits_scale,
FLAGS_logits_offset,
FLAGS_temperature,
Expand Down
15 changes: 11 additions & 4 deletions examples/qualcomm/oss_scripts/llama/runner/runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,13 +34,16 @@ namespace example {

namespace {
static constexpr auto kTopp = 0.9f;
void printReport(const Runner::Stats& stats);
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path);
std::string statsToJsonString(const Runner::Stats& stats);
} // namespace

Runner::Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand All@@ -49,6 +52,7 @@ Runner::Runner(
: n_bos_(1),
n_eos_(1),
tokenizer_path_(tokenizer_path),
performance_output_path_(performance_output_path),
logits_scale_(logits_scale),
logits_offset_(logits_offset),
temperature_(temperature),
Expand DownExpand Up@@ -437,7 +441,7 @@ Error Runner::generate(

stats_.num_prompt_tokens = num_prompt_tokens;
stats_.num_generated_tokens = pos - num_prompt_tokens;
printReport(stats_);
printReport(stats_, performance_output_path_);
if (stats_callback) {
stats_callback(stats_);
}
Expand All@@ -446,7 +450,9 @@ Error Runner::generate(
}

namespace {
void printReport(const Runner::Stats& stats) {
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path) {
printf("PyTorchObserver %s\n", statsToJsonString(stats).c_str());

ET_LOG(
Expand DownExpand Up@@ -507,7 +513,8 @@ void printReport(const Runner::Stats& stats) {

// For now, we just print the total inference time for CI, can save more info
// in future if needed.
std::ofstream outfile("outputs/inference_speed.txt");

std::ofstream outfile(performance_output_path.c_str());
if (outfile.is_open()) {
double num_tok = (stats.num_generated_tokens) /
(double)(stats.inference_end_ms - stats.inference_start_ms) *
Expand Down
2 changes: 2 additions & 0 deletions examples/qualcomm/oss_scripts/llama/runner/runner.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@ class Runner {
explicit Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path_,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand DownExpand Up@@ -101,6 +102,7 @@ class Runner {
const int32_t n_eos_;
std::vector<std::shared_ptr<executorch::extension::Module>> modules_;
std::string tokenizer_path_;
std::string performance_output_path_;
float logits_scale_;
int32_t logits_offset_;
float temperature_;
Expand Down
9 changes: 8 additions & 1 deletion examples/qualcomm/scripts/mobilebert_fine_tune.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -169,7 +169,7 @@ def get_fine_tuned_mobilebert(artifacts_dir, pretrained_weight, batch_size):
dataset_train = TensorDataset(input_ids_train, attention_masks_train, labels_train)
dataset_val = TensorDataset(input_ids_val, attention_masks_val, labels_val)

epochs = 5
epochs = args.num_epochs
dataloader_train = DataLoader(
dataset_train,
sampler=RandomSampler(dataset_train),
Expand DownExpand Up@@ -366,6 +366,13 @@ def calibrator(gm):
type=str,
)

parser.add_argument(
"--num_epochs",
help="If no pretrained weights are provided, set number of epochs to train the model",
default=5,
type=int,
)

parser.add_argument(
"-F",
"--use_fp16",
Expand Down
22 changes: 17 additions & 5 deletions examples/qualcomm/scripts/wav2letter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
# LICENSE file in the root directory of this source tree.

import json
import logging
import os
import sys
from multiprocessing.connection import Client
Expand DownExpand Up@@ -111,7 +112,12 @@ def main(args):
# target labels " abcdefghijklmnopqrstuvwxyz'*"
instance.vocab_size = 29
model = instance.get_eager_model().eval()
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
if args.pretrained_weight:
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
else:
logging.warning(
"It is strongly recommended to provide pretrained weights, otherwise accuracy will be bad. This option is here mainly for CI purpose to ensure compile is successful."
)

# convert conv1d to conv2d in nn.Module level will only introduce 2 permute
# nodes around input & output, which is more quantization friendly.
Expand All@@ -128,9 +134,15 @@ def main(args):

# retrieve dataset, will take some time to download
data_num = 100
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
if args.compile_only:
inputs = [(torch.rand(1, 1, 700, 1),)]
logging.warning(
"With compile_only, accuracy will be bad due to insufficient datasets for quantization."
)
else:
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
pte_filename = "w2l_qnn"
build_executorch_binary(
model,
Expand DownExpand Up@@ -212,7 +224,7 @@ def main(args):
),
default=None,
type=str,
required=True,
required=False,
)

args = parser.parse_args()
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .ci/scripts/test_model.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -164,6 +164,7 @@ test_model_with_qnn() {
export LD_LIBRARY_PATH=$QNN_SDK_ROOT/lib/x86_64-linux-clang/
export PYTHONPATH=$EXECUTORCH_ROOT/..

EXTRA_FLAGS=""
if [[ "${MODEL_NAME}" == "dl3" ]]; then
EXPORT_SCRIPT=deeplab_v3
elif [[ "${MODEL_NAME}" == "mv3" ]]; then
Expand All@@ -176,6 +177,12 @@ test_model_with_qnn() {
EXPORT_SCRIPT=inception_v3
elif [[ "${MODEL_NAME}" == "vit" ]]; then
EXPORT_SCRIPT=torchvision_vit
elif [[ "${MODEL_NAME}" == "mb" ]]; then
EXPORT_SCRIPT=mobilebert_fine_tune
EXTRA_FLAGS="--num_epochs 1"
pip install scikit-learn
elif [[ "${MODEL_NAME}" == "w2l" ]]; then
EXPORT_SCRIPT=wav2letter
elif [[ "${MODEL_NAME}" == "edsr" ]]; then
EXPORT_SCRIPT=edsr
# Additional deps for edsr
Expand All@@ -189,7 +196,7 @@ test_model_with_qnn() {
# TODO(guangyang): Make QNN chipset matches the target device
QNN_CHIPSET=SM8450

"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only
"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only $EXTRA_FLAGS
EXPORTED_MODEL=$(find "./${EXPORT_SCRIPT}" -type f -name "${MODEL_NAME}*.pte" -print -quit)
}

Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/trunk.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -311,7 +311,7 @@ jobs:
strategy:
matrix:
dtype: [fp32]
model: [dl3, mv3, mv2, ic4, ic3, vit]
model: [dl3, mv3, mv2, ic4, ic3, vit, mb, w2l]
fail-fast: false
with:
runner: linux.2xlarge
Expand Down
22 changes: 10 additions & 12 deletions backends/qualcomm/tests/test_qnn_delegate.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,7 @@
from executorch.examples.models.mobilenet_v3 import MV3Model
from executorch.examples.models.torchvision_vit.model import TorchVisionViTModel

# from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.exir import to_edge
from executorch.exir.backend.backend_api import disable_validation
from executorch.exir.passes import PassManager
Expand DownExpand Up@@ -907,8 +907,7 @@ def test_qnn_backend_example_models(self):
# Fail during lowering Reopen once resolved
# MobileBertModelExample(),
# TorchVisionViTModel(),
# Encountered undefined symbol in mainline. Reopen once resolved.
# Wav2LetterModel(),
Wav2LetterModel(),
]
expected_partitions = [
1,
Expand All@@ -917,8 +916,8 @@ def test_qnn_backend_example_models(self):
1,
1,
1,
1,
1,
# 1,
# 1,
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
Expand DownExpand Up@@ -1962,12 +1961,11 @@ def test_qnn_backend_example_models(self):
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
# Encountered undefined symbol in mainline. Reopen once resolved.
# {
# QCOM_MODULE: Wav2LetterModel(),
# QCOM_ANNOTATION: (),
# QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
# },
{
QCOM_MODULE: Wav2LetterModel(),
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
]
expected_partitions = [
1,
Expand All@@ -1979,7 +1977,7 @@ def test_qnn_backend_example_models(self):
# For MobileBertModelExample
# 1,
1,
# 1, For Wav2LetterModel
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
disable_validation()
Expand Down
5 changes: 4 additions & 1 deletion examples/qualcomm/oss_scripts/llama/llama.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -843,6 +843,7 @@ def post_process():
)

runner_cmd = ""
performance_output_path = "outputs/inference_speed.txt"
if args.enable_x86_64:
# x86 emulator is intended for CI and not performance. Check only the first few tokens.
seq_len = min(seq_len, 16)
Expand All@@ -862,6 +863,7 @@ def post_process():
f"--model_path {pte_path}",
f"--seq_len {seq_len}",
f"--output_path {args.artifact}/outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater ShiftPointer",
runner_args,
]
Expand All@@ -882,6 +884,7 @@ def post_process():
f"--model_path {pte_filename}.pte",
f"--seq_len {seq_len}",
"--output_path outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater {'SmartMask' if args.kv_updater == smart_mask_updater else 'ShiftPointer'}",
runner_args,
]
Expand All@@ -905,7 +908,7 @@ def post_process():
adb.pull(output_path=args.artifact, callback=post_process)
if args.ip and args.port != -1:
inference_speed = 0
with open(f"{args.artifact}/outputs/inference_speed.txt", "r") as f:
with open(f"{args.artifact}/{performance_output_path}", "r") as f:
inference_speed = float(f.read())

pte_size = os.path.getsize(pte_path)
Expand Down
5 changes: 5 additions & 0 deletions examples/qualcomm/oss_scripts/llama/qnn_llama_runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,10 @@ DEFINE_string(
output_path,
"outputs.txt",
"Executorch inference data output path.");
DEFINE_string(
performance_output_path,
"inference_speed.txt",
"Records inference speed. For CI purpose.");
DEFINE_string(tokenizer_path, "tokenizer.bin", "Tokenizer stuff.");
DEFINE_string(prompt, "The answer to the ultimate question is", "Prompt.");
DEFINE_string(
Expand DownExpand Up@@ -63,6 +67,7 @@ int main(int argc, char** argv) {
example::Runner runner(
{FLAGS_model_path},
FLAGS_tokenizer_path.c_str(),
FLAGS_performance_output_path.c_str(),
FLAGS_logits_scale,
FLAGS_logits_offset,
FLAGS_temperature,
Expand Down
15 changes: 11 additions & 4 deletions examples/qualcomm/oss_scripts/llama/runner/runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,13 +34,16 @@ namespace example {

namespace {
static constexpr auto kTopp = 0.9f;
void printReport(const Runner::Stats& stats);
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path);
std::string statsToJsonString(const Runner::Stats& stats);
} // namespace

Runner::Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand All@@ -49,6 +52,7 @@ Runner::Runner(
: n_bos_(1),
n_eos_(1),
tokenizer_path_(tokenizer_path),
performance_output_path_(performance_output_path),
logits_scale_(logits_scale),
logits_offset_(logits_offset),
temperature_(temperature),
Expand DownExpand Up@@ -437,7 +441,7 @@ Error Runner::generate(

stats_.num_prompt_tokens = num_prompt_tokens;
stats_.num_generated_tokens = pos - num_prompt_tokens;
printReport(stats_);
printReport(stats_, performance_output_path_);
if (stats_callback) {
stats_callback(stats_);
}
Expand All@@ -446,7 +450,9 @@ Error Runner::generate(
}

namespace {
void printReport(const Runner::Stats& stats) {
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path) {
printf("PyTorchObserver %s\n", statsToJsonString(stats).c_str());

ET_LOG(
Expand DownExpand Up@@ -507,7 +513,8 @@ void printReport(const Runner::Stats& stats) {

// For now, we just print the total inference time for CI, can save more info
// in future if needed.
std::ofstream outfile("outputs/inference_speed.txt");

std::ofstream outfile(performance_output_path.c_str());
if (outfile.is_open()) {
double num_tok = (stats.num_generated_tokens) /
(double)(stats.inference_end_ms - stats.inference_start_ms) *
Expand Down
2 changes: 2 additions & 0 deletions examples/qualcomm/oss_scripts/llama/runner/runner.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@ class Runner {
explicit Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path_,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand DownExpand Up@@ -101,6 +102,7 @@ class Runner {
const int32_t n_eos_;
std::vector<std::shared_ptr<executorch::extension::Module>> modules_;
std::string tokenizer_path_;
std::string performance_output_path_;
float logits_scale_;
int32_t logits_offset_;
float temperature_;
Expand Down
9 changes: 8 additions & 1 deletion examples/qualcomm/scripts/mobilebert_fine_tune.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -169,7 +169,7 @@ def get_fine_tuned_mobilebert(artifacts_dir, pretrained_weight, batch_size):
dataset_train = TensorDataset(input_ids_train, attention_masks_train, labels_train)
dataset_val = TensorDataset(input_ids_val, attention_masks_val, labels_val)

epochs = 5
epochs = args.num_epochs
dataloader_train = DataLoader(
dataset_train,
sampler=RandomSampler(dataset_train),
Expand DownExpand Up@@ -366,6 +366,13 @@ def calibrator(gm):
type=str,
)

parser.add_argument(
"--num_epochs",
help="If no pretrained weights are provided, set number of epochs to train the model",
default=5,
type=int,
)

parser.add_argument(
"-F",
"--use_fp16",
Expand Down
22 changes: 17 additions & 5 deletions examples/qualcomm/scripts/wav2letter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
# LICENSE file in the root directory of this source tree.

import json
import logging
import os
import sys
from multiprocessing.connection import Client
Expand DownExpand Up@@ -111,7 +112,12 @@ def main(args):
# target labels " abcdefghijklmnopqrstuvwxyz'*"
instance.vocab_size = 29
model = instance.get_eager_model().eval()
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
if args.pretrained_weight:
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
else:
logging.warning(
"It is strongly recommended to provide pretrained weights, otherwise accuracy will be bad. This option is here mainly for CI purpose to ensure compile is successful."
)

# convert conv1d to conv2d in nn.Module level will only introduce 2 permute
# nodes around input & output, which is more quantization friendly.
Expand All@@ -128,9 +134,15 @@ def main(args):

# retrieve dataset, will take some time to download
data_num = 100
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
if args.compile_only:
inputs = [(torch.rand(1, 1, 700, 1),)]
logging.warning(
"With compile_only, accuracy will be bad due to insufficient datasets for quantization."
)
else:
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
pte_filename = "w2l_qnn"
build_executorch_binary(
model,
Expand DownExpand Up@@ -212,7 +224,7 @@ def main(args):
),
default=None,
type=str,
required=True,
required=False,
)

args = parser.parse_args()
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .ci/scripts/test_model.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -164,6 +164,7 @@ test_model_with_qnn() {
export LD_LIBRARY_PATH=$QNN_SDK_ROOT/lib/x86_64-linux-clang/
export PYTHONPATH=$EXECUTORCH_ROOT/..

EXTRA_FLAGS=""
if [[ "${MODEL_NAME}" == "dl3" ]]; then
EXPORT_SCRIPT=deeplab_v3
elif [[ "${MODEL_NAME}" == "mv3" ]]; then
Expand All@@ -176,6 +177,12 @@ test_model_with_qnn() {
EXPORT_SCRIPT=inception_v3
elif [[ "${MODEL_NAME}" == "vit" ]]; then
EXPORT_SCRIPT=torchvision_vit
elif [[ "${MODEL_NAME}" == "mb" ]]; then
EXPORT_SCRIPT=mobilebert_fine_tune
EXTRA_FLAGS="--num_epochs 1"
pip install scikit-learn
elif [[ "${MODEL_NAME}" == "w2l" ]]; then
EXPORT_SCRIPT=wav2letter
elif [[ "${MODEL_NAME}" == "edsr" ]]; then
EXPORT_SCRIPT=edsr
# Additional deps for edsr
Expand All@@ -189,7 +196,7 @@ test_model_with_qnn() {
# TODO(guangyang): Make QNN chipset matches the target device
QNN_CHIPSET=SM8450

"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only
"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only $EXTRA_FLAGS
EXPORTED_MODEL=$(find "./${EXPORT_SCRIPT}" -type f -name "${MODEL_NAME}*.pte" -print -quit)
}

Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/trunk.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -311,7 +311,7 @@ jobs:
strategy:
matrix:
dtype: [fp32]
model: [dl3, mv3, mv2, ic4, ic3, vit]
model: [dl3, mv3, mv2, ic4, ic3, vit, mb, w2l]
fail-fast: false
with:
runner: linux.2xlarge
Expand Down
22 changes: 10 additions & 12 deletions backends/qualcomm/tests/test_qnn_delegate.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,7 @@
from executorch.examples.models.mobilenet_v3 import MV3Model
from executorch.examples.models.torchvision_vit.model import TorchVisionViTModel

# from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.exir import to_edge
from executorch.exir.backend.backend_api import disable_validation
from executorch.exir.passes import PassManager
Expand DownExpand Up@@ -907,8 +907,7 @@ def test_qnn_backend_example_models(self):
# Fail during lowering Reopen once resolved
# MobileBertModelExample(),
# TorchVisionViTModel(),
# Encountered undefined symbol in mainline. Reopen once resolved.
# Wav2LetterModel(),
Wav2LetterModel(),
]
expected_partitions = [
1,
Expand All@@ -917,8 +916,8 @@ def test_qnn_backend_example_models(self):
1,
1,
1,
1,
1,
# 1,
# 1,
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
Expand DownExpand Up@@ -1962,12 +1961,11 @@ def test_qnn_backend_example_models(self):
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
# Encountered undefined symbol in mainline. Reopen once resolved.
# {
# QCOM_MODULE: Wav2LetterModel(),
# QCOM_ANNOTATION: (),
# QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
# },
{
QCOM_MODULE: Wav2LetterModel(),
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
]
expected_partitions = [
1,
Expand All@@ -1979,7 +1977,7 @@ def test_qnn_backend_example_models(self):
# For MobileBertModelExample
# 1,
1,
# 1, For Wav2LetterModel
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
disable_validation()
Expand Down
5 changes: 4 additions & 1 deletion examples/qualcomm/oss_scripts/llama/llama.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -843,6 +843,7 @@ def post_process():
)

runner_cmd = ""
performance_output_path = "outputs/inference_speed.txt"
if args.enable_x86_64:
# x86 emulator is intended for CI and not performance. Check only the first few tokens.
seq_len = min(seq_len, 16)
Expand All@@ -862,6 +863,7 @@ def post_process():
f"--model_path {pte_path}",
f"--seq_len {seq_len}",
f"--output_path {args.artifact}/outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater ShiftPointer",
runner_args,
]
Expand All@@ -882,6 +884,7 @@ def post_process():
f"--model_path {pte_filename}.pte",
f"--seq_len {seq_len}",
"--output_path outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater {'SmartMask' if args.kv_updater == smart_mask_updater else 'ShiftPointer'}",
runner_args,
]
Expand All@@ -905,7 +908,7 @@ def post_process():
adb.pull(output_path=args.artifact, callback=post_process)
if args.ip and args.port != -1:
inference_speed = 0
with open(f"{args.artifact}/outputs/inference_speed.txt", "r") as f:
with open(f"{args.artifact}/{performance_output_path}", "r") as f:
inference_speed = float(f.read())

pte_size = os.path.getsize(pte_path)
Expand Down
5 changes: 5 additions & 0 deletions examples/qualcomm/oss_scripts/llama/qnn_llama_runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,10 @@ DEFINE_string(
output_path,
"outputs.txt",
"Executorch inference data output path.");
DEFINE_string(
performance_output_path,
"inference_speed.txt",
"Records inference speed. For CI purpose.");
DEFINE_string(tokenizer_path, "tokenizer.bin", "Tokenizer stuff.");
DEFINE_string(prompt, "The answer to the ultimate question is", "Prompt.");
DEFINE_string(
Expand DownExpand Up@@ -63,6 +67,7 @@ int main(int argc, char** argv) {
example::Runner runner(
{FLAGS_model_path},
FLAGS_tokenizer_path.c_str(),
FLAGS_performance_output_path.c_str(),
FLAGS_logits_scale,
FLAGS_logits_offset,
FLAGS_temperature,
Expand Down
15 changes: 11 additions & 4 deletions examples/qualcomm/oss_scripts/llama/runner/runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,13 +34,16 @@ namespace example {

namespace {
static constexpr auto kTopp = 0.9f;
void printReport(const Runner::Stats& stats);
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path);
std::string statsToJsonString(const Runner::Stats& stats);
} // namespace

Runner::Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand All@@ -49,6 +52,7 @@ Runner::Runner(
: n_bos_(1),
n_eos_(1),
tokenizer_path_(tokenizer_path),
performance_output_path_(performance_output_path),
logits_scale_(logits_scale),
logits_offset_(logits_offset),
temperature_(temperature),
Expand DownExpand Up@@ -437,7 +441,7 @@ Error Runner::generate(

stats_.num_prompt_tokens = num_prompt_tokens;
stats_.num_generated_tokens = pos - num_prompt_tokens;
printReport(stats_);
printReport(stats_, performance_output_path_);
if (stats_callback) {
stats_callback(stats_);
}
Expand All@@ -446,7 +450,9 @@ Error Runner::generate(
}

namespace {
void printReport(const Runner::Stats& stats) {
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path) {
printf("PyTorchObserver %s\n", statsToJsonString(stats).c_str());

ET_LOG(
Expand DownExpand Up@@ -507,7 +513,8 @@ void printReport(const Runner::Stats& stats) {

// For now, we just print the total inference time for CI, can save more info
// in future if needed.
std::ofstream outfile("outputs/inference_speed.txt");

std::ofstream outfile(performance_output_path.c_str());
if (outfile.is_open()) {
double num_tok = (stats.num_generated_tokens) /
(double)(stats.inference_end_ms - stats.inference_start_ms) *
Expand Down
2 changes: 2 additions & 0 deletions examples/qualcomm/oss_scripts/llama/runner/runner.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@ class Runner {
explicit Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path_,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand DownExpand Up@@ -101,6 +102,7 @@ class Runner {
const int32_t n_eos_;
std::vector<std::shared_ptr<executorch::extension::Module>> modules_;
std::string tokenizer_path_;
std::string performance_output_path_;
float logits_scale_;
int32_t logits_offset_;
float temperature_;
Expand Down
9 changes: 8 additions & 1 deletion examples/qualcomm/scripts/mobilebert_fine_tune.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -169,7 +169,7 @@ def get_fine_tuned_mobilebert(artifacts_dir, pretrained_weight, batch_size):
dataset_train = TensorDataset(input_ids_train, attention_masks_train, labels_train)
dataset_val = TensorDataset(input_ids_val, attention_masks_val, labels_val)

epochs = 5
epochs = args.num_epochs
dataloader_train = DataLoader(
dataset_train,
sampler=RandomSampler(dataset_train),
Expand DownExpand Up@@ -366,6 +366,13 @@ def calibrator(gm):
type=str,
)

parser.add_argument(
"--num_epochs",
help="If no pretrained weights are provided, set number of epochs to train the model",
default=5,
type=int,
)

parser.add_argument(
"-F",
"--use_fp16",
Expand Down
22 changes: 17 additions & 5 deletions examples/qualcomm/scripts/wav2letter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
# LICENSE file in the root directory of this source tree.

import json
import logging
import os
import sys
from multiprocessing.connection import Client
Expand DownExpand Up@@ -111,7 +112,12 @@ def main(args):
# target labels " abcdefghijklmnopqrstuvwxyz'*"
instance.vocab_size = 29
model = instance.get_eager_model().eval()
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
if args.pretrained_weight:
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
else:
logging.warning(
"It is strongly recommended to provide pretrained weights, otherwise accuracy will be bad. This option is here mainly for CI purpose to ensure compile is successful."
)

# convert conv1d to conv2d in nn.Module level will only introduce 2 permute
# nodes around input & output, which is more quantization friendly.
Expand All@@ -128,9 +134,15 @@ def main(args):

# retrieve dataset, will take some time to download
data_num = 100
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
if args.compile_only:
inputs = [(torch.rand(1, 1, 700, 1),)]
logging.warning(
"With compile_only, accuracy will be bad due to insufficient datasets for quantization."
)
else:
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
pte_filename = "w2l_qnn"
build_executorch_binary(
model,
Expand DownExpand Up@@ -212,7 +224,7 @@ def main(args):
),
default=None,
type=str,
required=True,
required=False,
)

args = parser.parse_args()
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .ci/scripts/test_model.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -164,6 +164,7 @@ test_model_with_qnn() {
export LD_LIBRARY_PATH=$QNN_SDK_ROOT/lib/x86_64-linux-clang/
export PYTHONPATH=$EXECUTORCH_ROOT/..

EXTRA_FLAGS=""
if [[ "${MODEL_NAME}" == "dl3" ]]; then
EXPORT_SCRIPT=deeplab_v3
elif [[ "${MODEL_NAME}" == "mv3" ]]; then
Expand All@@ -176,6 +177,12 @@ test_model_with_qnn() {
EXPORT_SCRIPT=inception_v3
elif [[ "${MODEL_NAME}" == "vit" ]]; then
EXPORT_SCRIPT=torchvision_vit
elif [[ "${MODEL_NAME}" == "mb" ]]; then
EXPORT_SCRIPT=mobilebert_fine_tune
EXTRA_FLAGS="--num_epochs 1"
pip install scikit-learn
elif [[ "${MODEL_NAME}" == "w2l" ]]; then
EXPORT_SCRIPT=wav2letter
elif [[ "${MODEL_NAME}" == "edsr" ]]; then
EXPORT_SCRIPT=edsr
# Additional deps for edsr
Expand All@@ -189,7 +196,7 @@ test_model_with_qnn() {
# TODO(guangyang): Make QNN chipset matches the target device
QNN_CHIPSET=SM8450

"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only
"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only $EXTRA_FLAGS
EXPORTED_MODEL=$(find "./${EXPORT_SCRIPT}" -type f -name "${MODEL_NAME}*.pte" -print -quit)
}

Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/trunk.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -311,7 +311,7 @@ jobs:
strategy:
matrix:
dtype: [fp32]
model: [dl3, mv3, mv2, ic4, ic3, vit]
model: [dl3, mv3, mv2, ic4, ic3, vit, mb, w2l]
fail-fast: false
with:
runner: linux.2xlarge
Expand Down
22 changes: 10 additions & 12 deletions backends/qualcomm/tests/test_qnn_delegate.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,7 @@
from executorch.examples.models.mobilenet_v3 import MV3Model
from executorch.examples.models.torchvision_vit.model import TorchVisionViTModel

# from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.exir import to_edge
from executorch.exir.backend.backend_api import disable_validation
from executorch.exir.passes import PassManager
Expand DownExpand Up@@ -907,8 +907,7 @@ def test_qnn_backend_example_models(self):
# Fail during lowering Reopen once resolved
# MobileBertModelExample(),
# TorchVisionViTModel(),
# Encountered undefined symbol in mainline. Reopen once resolved.
# Wav2LetterModel(),
Wav2LetterModel(),
]
expected_partitions = [
1,
Expand All@@ -917,8 +916,8 @@ def test_qnn_backend_example_models(self):
1,
1,
1,
1,
1,
# 1,
# 1,
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
Expand DownExpand Up@@ -1962,12 +1961,11 @@ def test_qnn_backend_example_models(self):
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
# Encountered undefined symbol in mainline. Reopen once resolved.
# {
# QCOM_MODULE: Wav2LetterModel(),
# QCOM_ANNOTATION: (),
# QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
# },
{
QCOM_MODULE: Wav2LetterModel(),
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
]
expected_partitions = [
1,
Expand All@@ -1979,7 +1977,7 @@ def test_qnn_backend_example_models(self):
# For MobileBertModelExample
# 1,
1,
# 1, For Wav2LetterModel
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
disable_validation()
Expand Down
5 changes: 4 additions & 1 deletion examples/qualcomm/oss_scripts/llama/llama.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -843,6 +843,7 @@ def post_process():
)

runner_cmd = ""
performance_output_path = "outputs/inference_speed.txt"
if args.enable_x86_64:
# x86 emulator is intended for CI and not performance. Check only the first few tokens.
seq_len = min(seq_len, 16)
Expand All@@ -862,6 +863,7 @@ def post_process():
f"--model_path {pte_path}",
f"--seq_len {seq_len}",
f"--output_path {args.artifact}/outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater ShiftPointer",
runner_args,
]
Expand All@@ -882,6 +884,7 @@ def post_process():
f"--model_path {pte_filename}.pte",
f"--seq_len {seq_len}",
"--output_path outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater {'SmartMask' if args.kv_updater == smart_mask_updater else 'ShiftPointer'}",
runner_args,
]
Expand All@@ -905,7 +908,7 @@ def post_process():
adb.pull(output_path=args.artifact, callback=post_process)
if args.ip and args.port != -1:
inference_speed = 0
with open(f"{args.artifact}/outputs/inference_speed.txt", "r") as f:
with open(f"{args.artifact}/{performance_output_path}", "r") as f:
inference_speed = float(f.read())

pte_size = os.path.getsize(pte_path)
Expand Down
5 changes: 5 additions & 0 deletions examples/qualcomm/oss_scripts/llama/qnn_llama_runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,10 @@ DEFINE_string(
output_path,
"outputs.txt",
"Executorch inference data output path.");
DEFINE_string(
performance_output_path,
"inference_speed.txt",
"Records inference speed. For CI purpose.");
DEFINE_string(tokenizer_path, "tokenizer.bin", "Tokenizer stuff.");
DEFINE_string(prompt, "The answer to the ultimate question is", "Prompt.");
DEFINE_string(
Expand DownExpand Up@@ -63,6 +67,7 @@ int main(int argc, char** argv) {
example::Runner runner(
{FLAGS_model_path},
FLAGS_tokenizer_path.c_str(),
FLAGS_performance_output_path.c_str(),
FLAGS_logits_scale,
FLAGS_logits_offset,
FLAGS_temperature,
Expand Down
15 changes: 11 additions & 4 deletions examples/qualcomm/oss_scripts/llama/runner/runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,13 +34,16 @@ namespace example {

namespace {
static constexpr auto kTopp = 0.9f;
void printReport(const Runner::Stats& stats);
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path);
std::string statsToJsonString(const Runner::Stats& stats);
} // namespace

Runner::Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand All@@ -49,6 +52,7 @@ Runner::Runner(
: n_bos_(1),
n_eos_(1),
tokenizer_path_(tokenizer_path),
performance_output_path_(performance_output_path),
logits_scale_(logits_scale),
logits_offset_(logits_offset),
temperature_(temperature),
Expand DownExpand Up@@ -437,7 +441,7 @@ Error Runner::generate(

stats_.num_prompt_tokens = num_prompt_tokens;
stats_.num_generated_tokens = pos - num_prompt_tokens;
printReport(stats_);
printReport(stats_, performance_output_path_);
if (stats_callback) {
stats_callback(stats_);
}
Expand All@@ -446,7 +450,9 @@ Error Runner::generate(
}

namespace {
void printReport(const Runner::Stats& stats) {
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path) {
printf("PyTorchObserver %s\n", statsToJsonString(stats).c_str());

ET_LOG(
Expand DownExpand Up@@ -507,7 +513,8 @@ void printReport(const Runner::Stats& stats) {

// For now, we just print the total inference time for CI, can save more info
// in future if needed.
std::ofstream outfile("outputs/inference_speed.txt");

std::ofstream outfile(performance_output_path.c_str());
if (outfile.is_open()) {
double num_tok = (stats.num_generated_tokens) /
(double)(stats.inference_end_ms - stats.inference_start_ms) *
Expand Down
2 changes: 2 additions & 0 deletions examples/qualcomm/oss_scripts/llama/runner/runner.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@ class Runner {
explicit Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path_,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand DownExpand Up@@ -101,6 +102,7 @@ class Runner {
const int32_t n_eos_;
std::vector<std::shared_ptr<executorch::extension::Module>> modules_;
std::string tokenizer_path_;
std::string performance_output_path_;
float logits_scale_;
int32_t logits_offset_;
float temperature_;
Expand Down
9 changes: 8 additions & 1 deletion examples/qualcomm/scripts/mobilebert_fine_tune.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -169,7 +169,7 @@ def get_fine_tuned_mobilebert(artifacts_dir, pretrained_weight, batch_size):
dataset_train = TensorDataset(input_ids_train, attention_masks_train, labels_train)
dataset_val = TensorDataset(input_ids_val, attention_masks_val, labels_val)

epochs = 5
epochs = args.num_epochs
dataloader_train = DataLoader(
dataset_train,
sampler=RandomSampler(dataset_train),
Expand DownExpand Up@@ -366,6 +366,13 @@ def calibrator(gm):
type=str,
)

parser.add_argument(
"--num_epochs",
help="If no pretrained weights are provided, set number of epochs to train the model",
default=5,
type=int,
)

parser.add_argument(
"-F",
"--use_fp16",
Expand Down
22 changes: 17 additions & 5 deletions examples/qualcomm/scripts/wav2letter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
# LICENSE file in the root directory of this source tree.

import json
import logging
import os
import sys
from multiprocessing.connection import Client
Expand DownExpand Up@@ -111,7 +112,12 @@ def main(args):
# target labels " abcdefghijklmnopqrstuvwxyz'*"
instance.vocab_size = 29
model = instance.get_eager_model().eval()
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
if args.pretrained_weight:
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
else:
logging.warning(
"It is strongly recommended to provide pretrained weights, otherwise accuracy will be bad. This option is here mainly for CI purpose to ensure compile is successful."
)

# convert conv1d to conv2d in nn.Module level will only introduce 2 permute
# nodes around input & output, which is more quantization friendly.
Expand All@@ -128,9 +134,15 @@ def main(args):

# retrieve dataset, will take some time to download
data_num = 100
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
if args.compile_only:
inputs = [(torch.rand(1, 1, 700, 1),)]
logging.warning(
"With compile_only, accuracy will be bad due to insufficient datasets for quantization."
)
else:
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
pte_filename = "w2l_qnn"
build_executorch_binary(
model,
Expand DownExpand Up@@ -212,7 +224,7 @@ def main(args):
),
default=None,
type=str,
required=True,
required=False,
)

args = parser.parse_args()
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .ci/scripts/test_model.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -164,6 +164,7 @@ test_model_with_qnn() {
export LD_LIBRARY_PATH=$QNN_SDK_ROOT/lib/x86_64-linux-clang/
export PYTHONPATH=$EXECUTORCH_ROOT/..

EXTRA_FLAGS=""
if [[ "${MODEL_NAME}" == "dl3" ]]; then
EXPORT_SCRIPT=deeplab_v3
elif [[ "${MODEL_NAME}" == "mv3" ]]; then
Expand All@@ -176,6 +177,12 @@ test_model_with_qnn() {
EXPORT_SCRIPT=inception_v3
elif [[ "${MODEL_NAME}" == "vit" ]]; then
EXPORT_SCRIPT=torchvision_vit
elif [[ "${MODEL_NAME}" == "mb" ]]; then
EXPORT_SCRIPT=mobilebert_fine_tune
EXTRA_FLAGS="--num_epochs 1"
pip install scikit-learn
elif [[ "${MODEL_NAME}" == "w2l" ]]; then
EXPORT_SCRIPT=wav2letter
elif [[ "${MODEL_NAME}" == "edsr" ]]; then
EXPORT_SCRIPT=edsr
# Additional deps for edsr
Expand All@@ -189,7 +196,7 @@ test_model_with_qnn() {
# TODO(guangyang): Make QNN chipset matches the target device
QNN_CHIPSET=SM8450

"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only
"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only $EXTRA_FLAGS
EXPORTED_MODEL=$(find "./${EXPORT_SCRIPT}" -type f -name "${MODEL_NAME}*.pte" -print -quit)
}

Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/trunk.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -311,7 +311,7 @@ jobs:
strategy:
matrix:
dtype: [fp32]
model: [dl3, mv3, mv2, ic4, ic3, vit]
model: [dl3, mv3, mv2, ic4, ic3, vit, mb, w2l]
fail-fast: false
with:
runner: linux.2xlarge
Expand Down
22 changes: 10 additions & 12 deletions backends/qualcomm/tests/test_qnn_delegate.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,7 @@
from executorch.examples.models.mobilenet_v3 import MV3Model
from executorch.examples.models.torchvision_vit.model import TorchVisionViTModel

# from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.exir import to_edge
from executorch.exir.backend.backend_api import disable_validation
from executorch.exir.passes import PassManager
Expand DownExpand Up@@ -907,8 +907,7 @@ def test_qnn_backend_example_models(self):
# Fail during lowering Reopen once resolved
# MobileBertModelExample(),
# TorchVisionViTModel(),
# Encountered undefined symbol in mainline. Reopen once resolved.
# Wav2LetterModel(),
Wav2LetterModel(),
]
expected_partitions = [
1,
Expand All@@ -917,8 +916,8 @@ def test_qnn_backend_example_models(self):
1,
1,
1,
1,
1,
# 1,
# 1,
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
Expand DownExpand Up@@ -1962,12 +1961,11 @@ def test_qnn_backend_example_models(self):
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
# Encountered undefined symbol in mainline. Reopen once resolved.
# {
# QCOM_MODULE: Wav2LetterModel(),
# QCOM_ANNOTATION: (),
# QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
# },
{
QCOM_MODULE: Wav2LetterModel(),
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
]
expected_partitions = [
1,
Expand All@@ -1979,7 +1977,7 @@ def test_qnn_backend_example_models(self):
# For MobileBertModelExample
# 1,
1,
# 1, For Wav2LetterModel
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
disable_validation()
Expand Down
5 changes: 4 additions & 1 deletion examples/qualcomm/oss_scripts/llama/llama.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -843,6 +843,7 @@ def post_process():
)

runner_cmd = ""
performance_output_path = "outputs/inference_speed.txt"
if args.enable_x86_64:
# x86 emulator is intended for CI and not performance. Check only the first few tokens.
seq_len = min(seq_len, 16)
Expand All@@ -862,6 +863,7 @@ def post_process():
f"--model_path {pte_path}",
f"--seq_len {seq_len}",
f"--output_path {args.artifact}/outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater ShiftPointer",
runner_args,
]
Expand All@@ -882,6 +884,7 @@ def post_process():
f"--model_path {pte_filename}.pte",
f"--seq_len {seq_len}",
"--output_path outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater {'SmartMask' if args.kv_updater == smart_mask_updater else 'ShiftPointer'}",
runner_args,
]
Expand All@@ -905,7 +908,7 @@ def post_process():
adb.pull(output_path=args.artifact, callback=post_process)
if args.ip and args.port != -1:
inference_speed = 0
with open(f"{args.artifact}/outputs/inference_speed.txt", "r") as f:
with open(f"{args.artifact}/{performance_output_path}", "r") as f:
inference_speed = float(f.read())

pte_size = os.path.getsize(pte_path)
Expand Down
5 changes: 5 additions & 0 deletions examples/qualcomm/oss_scripts/llama/qnn_llama_runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,10 @@ DEFINE_string(
output_path,
"outputs.txt",
"Executorch inference data output path.");
DEFINE_string(
performance_output_path,
"inference_speed.txt",
"Records inference speed. For CI purpose.");
DEFINE_string(tokenizer_path, "tokenizer.bin", "Tokenizer stuff.");
DEFINE_string(prompt, "The answer to the ultimate question is", "Prompt.");
DEFINE_string(
Expand DownExpand Up@@ -63,6 +67,7 @@ int main(int argc, char** argv) {
example::Runner runner(
{FLAGS_model_path},
FLAGS_tokenizer_path.c_str(),
FLAGS_performance_output_path.c_str(),
FLAGS_logits_scale,
FLAGS_logits_offset,
FLAGS_temperature,
Expand Down
15 changes: 11 additions & 4 deletions examples/qualcomm/oss_scripts/llama/runner/runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,13 +34,16 @@ namespace example {

namespace {
static constexpr auto kTopp = 0.9f;
void printReport(const Runner::Stats& stats);
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path);
std::string statsToJsonString(const Runner::Stats& stats);
} // namespace

Runner::Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand All@@ -49,6 +52,7 @@ Runner::Runner(
: n_bos_(1),
n_eos_(1),
tokenizer_path_(tokenizer_path),
performance_output_path_(performance_output_path),
logits_scale_(logits_scale),
logits_offset_(logits_offset),
temperature_(temperature),
Expand DownExpand Up@@ -437,7 +441,7 @@ Error Runner::generate(

stats_.num_prompt_tokens = num_prompt_tokens;
stats_.num_generated_tokens = pos - num_prompt_tokens;
printReport(stats_);
printReport(stats_, performance_output_path_);
if (stats_callback) {
stats_callback(stats_);
}
Expand All@@ -446,7 +450,9 @@ Error Runner::generate(
}

namespace {
void printReport(const Runner::Stats& stats) {
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path) {
printf("PyTorchObserver %s\n", statsToJsonString(stats).c_str());

ET_LOG(
Expand DownExpand Up@@ -507,7 +513,8 @@ void printReport(const Runner::Stats& stats) {

// For now, we just print the total inference time for CI, can save more info
// in future if needed.
std::ofstream outfile("outputs/inference_speed.txt");

std::ofstream outfile(performance_output_path.c_str());
if (outfile.is_open()) {
double num_tok = (stats.num_generated_tokens) /
(double)(stats.inference_end_ms - stats.inference_start_ms) *
Expand Down
2 changes: 2 additions & 0 deletions examples/qualcomm/oss_scripts/llama/runner/runner.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@ class Runner {
explicit Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path_,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand DownExpand Up@@ -101,6 +102,7 @@ class Runner {
const int32_t n_eos_;
std::vector<std::shared_ptr<executorch::extension::Module>> modules_;
std::string tokenizer_path_;
std::string performance_output_path_;
float logits_scale_;
int32_t logits_offset_;
float temperature_;
Expand Down
9 changes: 8 additions & 1 deletion examples/qualcomm/scripts/mobilebert_fine_tune.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -169,7 +169,7 @@ def get_fine_tuned_mobilebert(artifacts_dir, pretrained_weight, batch_size):
dataset_train = TensorDataset(input_ids_train, attention_masks_train, labels_train)
dataset_val = TensorDataset(input_ids_val, attention_masks_val, labels_val)

epochs = 5
epochs = args.num_epochs
dataloader_train = DataLoader(
dataset_train,
sampler=RandomSampler(dataset_train),
Expand DownExpand Up@@ -366,6 +366,13 @@ def calibrator(gm):
type=str,
)

parser.add_argument(
"--num_epochs",
help="If no pretrained weights are provided, set number of epochs to train the model",
default=5,
type=int,
)

parser.add_argument(
"-F",
"--use_fp16",
Expand Down
22 changes: 17 additions & 5 deletions examples/qualcomm/scripts/wav2letter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
# LICENSE file in the root directory of this source tree.

import json
import logging
import os
import sys
from multiprocessing.connection import Client
Expand DownExpand Up@@ -111,7 +112,12 @@ def main(args):
# target labels " abcdefghijklmnopqrstuvwxyz'*"
instance.vocab_size = 29
model = instance.get_eager_model().eval()
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
if args.pretrained_weight:
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
else:
logging.warning(
"It is strongly recommended to provide pretrained weights, otherwise accuracy will be bad. This option is here mainly for CI purpose to ensure compile is successful."
)

# convert conv1d to conv2d in nn.Module level will only introduce 2 permute
# nodes around input & output, which is more quantization friendly.
Expand All@@ -128,9 +134,15 @@ def main(args):

# retrieve dataset, will take some time to download
data_num = 100
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
if args.compile_only:
inputs = [(torch.rand(1, 1, 700, 1),)]
logging.warning(
"With compile_only, accuracy will be bad due to insufficient datasets for quantization."
)
else:
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
pte_filename = "w2l_qnn"
build_executorch_binary(
model,
Expand DownExpand Up@@ -212,7 +224,7 @@ def main(args):
),
default=None,
type=str,
required=True,
required=False,
)

args = parser.parse_args()
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .ci/scripts/test_model.sh
Original file line numberDiff line numberDiff line change
Expand Up@@ -164,6 +164,7 @@ test_model_with_qnn() {
export LD_LIBRARY_PATH=$QNN_SDK_ROOT/lib/x86_64-linux-clang/
export PYTHONPATH=$EXECUTORCH_ROOT/..

EXTRA_FLAGS=""
if [[ "${MODEL_NAME}" == "dl3" ]]; then
EXPORT_SCRIPT=deeplab_v3
elif [[ "${MODEL_NAME}" == "mv3" ]]; then
Expand All@@ -176,6 +177,12 @@ test_model_with_qnn() {
EXPORT_SCRIPT=inception_v3
elif [[ "${MODEL_NAME}" == "vit" ]]; then
EXPORT_SCRIPT=torchvision_vit
elif [[ "${MODEL_NAME}" == "mb" ]]; then
EXPORT_SCRIPT=mobilebert_fine_tune
EXTRA_FLAGS="--num_epochs 1"
pip install scikit-learn
elif [[ "${MODEL_NAME}" == "w2l" ]]; then
EXPORT_SCRIPT=wav2letter
elif [[ "${MODEL_NAME}" == "edsr" ]]; then
EXPORT_SCRIPT=edsr
# Additional deps for edsr
Expand All@@ -189,7 +196,7 @@ test_model_with_qnn() {
# TODO(guangyang): Make QNN chipset matches the target device
QNN_CHIPSET=SM8450

"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only
"${PYTHON_EXECUTABLE}" -m examples.qualcomm.scripts.${EXPORT_SCRIPT} -b ${CMAKE_OUTPUT_DIR} -m ${QNN_CHIPSET} --compile_only $EXTRA_FLAGS
EXPORTED_MODEL=$(find "./${EXPORT_SCRIPT}" -type f -name "${MODEL_NAME}*.pte" -print -quit)
}

Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/trunk.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -311,7 +311,7 @@ jobs:
strategy:
matrix:
dtype: [fp32]
model: [dl3, mv3, mv2, ic4, ic3, vit]
model: [dl3, mv3, mv2, ic4, ic3, vit, mb, w2l]
fail-fast: false
with:
runner: linux.2xlarge
Expand Down
22 changes: 10 additions & 12 deletions backends/qualcomm/tests/test_qnn_delegate.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,7 +73,7 @@
from executorch.examples.models.mobilenet_v3 import MV3Model
from executorch.examples.models.torchvision_vit.model import TorchVisionViTModel

# from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.examples.models.wav2letter import Wav2LetterModel
from executorch.exir import to_edge
from executorch.exir.backend.backend_api import disable_validation
from executorch.exir.passes import PassManager
Expand DownExpand Up@@ -907,8 +907,7 @@ def test_qnn_backend_example_models(self):
# Fail during lowering Reopen once resolved
# MobileBertModelExample(),
# TorchVisionViTModel(),
# Encountered undefined symbol in mainline. Reopen once resolved.
# Wav2LetterModel(),
Wav2LetterModel(),
]
expected_partitions = [
1,
Expand All@@ -917,8 +916,8 @@ def test_qnn_backend_example_models(self):
1,
1,
1,
1,
1,
# 1,
# 1,
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
Expand DownExpand Up@@ -1962,12 +1961,11 @@ def test_qnn_backend_example_models(self):
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
# Encountered undefined symbol in mainline. Reopen once resolved.
# {
# QCOM_MODULE: Wav2LetterModel(),
# QCOM_ANNOTATION: (),
# QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
# },
{
QCOM_MODULE: Wav2LetterModel(),
QCOM_ANNOTATION: (),
QCOM_QUANT_DTYPE: QuantDtype.use_8a8w,
},
]
expected_partitions = [
1,
Expand All@@ -1979,7 +1977,7 @@ def test_qnn_backend_example_models(self):
# For MobileBertModelExample
# 1,
1,
# 1, For Wav2LetterModel
1,
]
# TODO: Due to trigger maximum recursion depth exceeded, need to check it.
disable_validation()
Expand Down
5 changes: 4 additions & 1 deletion examples/qualcomm/oss_scripts/llama/llama.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -843,6 +843,7 @@ def post_process():
)

runner_cmd = ""
performance_output_path = "outputs/inference_speed.txt"
if args.enable_x86_64:
# x86 emulator is intended for CI and not performance. Check only the first few tokens.
seq_len = min(seq_len, 16)
Expand All@@ -862,6 +863,7 @@ def post_process():
f"--model_path {pte_path}",
f"--seq_len {seq_len}",
f"--output_path {args.artifact}/outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater ShiftPointer",
runner_args,
]
Expand All@@ -882,6 +884,7 @@ def post_process():
f"--model_path {pte_filename}.pte",
f"--seq_len {seq_len}",
"--output_path outputs/outputs.txt",
f"--performance_output_path {performance_output_path}",
f"--kv_updater {'SmartMask' if args.kv_updater == smart_mask_updater else 'ShiftPointer'}",
runner_args,
]
Expand All@@ -905,7 +908,7 @@ def post_process():
adb.pull(output_path=args.artifact, callback=post_process)
if args.ip and args.port != -1:
inference_speed = 0
with open(f"{args.artifact}/outputs/inference_speed.txt", "r") as f:
with open(f"{args.artifact}/{performance_output_path}", "r") as f:
inference_speed = float(f.read())

pte_size = os.path.getsize(pte_path)
Expand Down
5 changes: 5 additions & 0 deletions examples/qualcomm/oss_scripts/llama/qnn_llama_runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,6 +30,10 @@ DEFINE_string(
output_path,
"outputs.txt",
"Executorch inference data output path.");
DEFINE_string(
performance_output_path,
"inference_speed.txt",
"Records inference speed. For CI purpose.");
DEFINE_string(tokenizer_path, "tokenizer.bin", "Tokenizer stuff.");
DEFINE_string(prompt, "The answer to the ultimate question is", "Prompt.");
DEFINE_string(
Expand DownExpand Up@@ -63,6 +67,7 @@ int main(int argc, char** argv) {
example::Runner runner(
{FLAGS_model_path},
FLAGS_tokenizer_path.c_str(),
FLAGS_performance_output_path.c_str(),
FLAGS_logits_scale,
FLAGS_logits_offset,
FLAGS_temperature,
Expand Down
15 changes: 11 additions & 4 deletions examples/qualcomm/oss_scripts/llama/runner/runner.cpp
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,13 +34,16 @@ namespace example {

namespace {
static constexpr auto kTopp = 0.9f;
void printReport(const Runner::Stats& stats);
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path);
std::string statsToJsonString(const Runner::Stats& stats);
} // namespace

Runner::Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand All@@ -49,6 +52,7 @@ Runner::Runner(
: n_bos_(1),
n_eos_(1),
tokenizer_path_(tokenizer_path),
performance_output_path_(performance_output_path),
logits_scale_(logits_scale),
logits_offset_(logits_offset),
temperature_(temperature),
Expand DownExpand Up@@ -437,7 +441,7 @@ Error Runner::generate(

stats_.num_prompt_tokens = num_prompt_tokens;
stats_.num_generated_tokens = pos - num_prompt_tokens;
printReport(stats_);
printReport(stats_, performance_output_path_);
if (stats_callback) {
stats_callback(stats_);
}
Expand All@@ -446,7 +450,9 @@ Error Runner::generate(
}

namespace {
void printReport(const Runner::Stats& stats) {
void printReport(
const Runner::Stats& stats,
const std::string& performance_output_path) {
printf("PyTorchObserver %s\n", statsToJsonString(stats).c_str());

ET_LOG(
Expand DownExpand Up@@ -507,7 +513,8 @@ void printReport(const Runner::Stats& stats) {

// For now, we just print the total inference time for CI, can save more info
// in future if needed.
std::ofstream outfile("outputs/inference_speed.txt");

std::ofstream outfile(performance_output_path.c_str());
if (outfile.is_open()) {
double num_tok = (stats.num_generated_tokens) /
(double)(stats.inference_end_ms - stats.inference_start_ms) *
Expand Down
2 changes: 2 additions & 0 deletions examples/qualcomm/oss_scripts/llama/runner/runner.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,6 +29,7 @@ class Runner {
explicit Runner(
const std::vector<std::string>& models_path,
const std::string& tokenizer_path,
const std::string& performance_output_path_,
const float logits_scale,
const int32_t logits_offset,
const float temperature,
Expand DownExpand Up@@ -101,6 +102,7 @@ class Runner {
const int32_t n_eos_;
std::vector<std::shared_ptr<executorch::extension::Module>> modules_;
std::string tokenizer_path_;
std::string performance_output_path_;
float logits_scale_;
int32_t logits_offset_;
float temperature_;
Expand Down
9 changes: 8 additions & 1 deletion examples/qualcomm/scripts/mobilebert_fine_tune.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -169,7 +169,7 @@ def get_fine_tuned_mobilebert(artifacts_dir, pretrained_weight, batch_size):
dataset_train = TensorDataset(input_ids_train, attention_masks_train, labels_train)
dataset_val = TensorDataset(input_ids_val, attention_masks_val, labels_val)

epochs = 5
epochs = args.num_epochs
dataloader_train = DataLoader(
dataset_train,
sampler=RandomSampler(dataset_train),
Expand DownExpand Up@@ -366,6 +366,13 @@ def calibrator(gm):
type=str,
)

parser.add_argument(
"--num_epochs",
help="If no pretrained weights are provided, set number of epochs to train the model",
default=5,
type=int,
)

parser.add_argument(
"-F",
"--use_fp16",
Expand Down
22 changes: 17 additions & 5 deletions examples/qualcomm/scripts/wav2letter.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,6 +5,7 @@
# LICENSE file in the root directory of this source tree.

import json
import logging
import os
import sys
from multiprocessing.connection import Client
Expand DownExpand Up@@ -111,7 +112,12 @@ def main(args):
# target labels " abcdefghijklmnopqrstuvwxyz'*"
instance.vocab_size = 29
model = instance.get_eager_model().eval()
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
if args.pretrained_weight:
model.load_state_dict(torch.load(args.pretrained_weight, weights_only=True))
else:
logging.warning(
"It is strongly recommended to provide pretrained weights, otherwise accuracy will be bad. This option is here mainly for CI purpose to ensure compile is successful."
)

# convert conv1d to conv2d in nn.Module level will only introduce 2 permute
# nodes around input & output, which is more quantization friendly.
Expand All@@ -128,9 +134,15 @@ def main(args):

# retrieve dataset, will take some time to download
data_num = 100
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
if args.compile_only:
inputs = [(torch.rand(1, 1, 700, 1),)]
logging.warning(
"With compile_only, accuracy will be bad due to insufficient datasets for quantization."
)
else:
inputs, targets, input_list = get_dataset(
data_size=data_num, artifact_dir=args.artifact
)
pte_filename = "w2l_qnn"
build_executorch_binary(
model,
Expand DownExpand Up@@ -212,7 +224,7 @@ def main(args):
),
default=None,
type=str,
required=True,
required=False,
)

args = parser.parse_args()
Expand Down