Skip to content

Commit e79adcb

Browse files
neuropilot-captainneuropilot-captain
authored andcommitted
Apply lintrunner
1 parent 7948376 commit e79adcb

File tree

13 files changed

+107
-90
lines changed

13 files changed

+107
-90
lines changed

examples/mediatek/README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,4 +147,3 @@ python3 eval_utils/eval_oss_result.py --eval_type piq --target_f edsr --output_f
147147
- `eval_type`: topk/piq/segmentation
148148
- `target_f`: folder contain golden data files. file name is `golden_<data_idx>_0.bin`
149149
- `output_f`: folder contain model output data files. file name is `output_<data_idx>_0.bin`
150-

examples/mediatek/aot_utils/oss_utils/utils.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,16 @@
66

77
import os
88
from typing import Optional
9+
910
import numpy as np
1011

1112
import torch
1213
from executorch import exir
13-
from executorch.backends.mediatek import NeuropilotPartitioner, NeuropilotQuantizer, Precision
14+
from executorch.backends.mediatek import (
15+
NeuropilotPartitioner,
16+
NeuropilotQuantizer,
17+
Precision,
18+
)
1419
from torch.ao.quantization.quantize_pt2e import convert_pt2e, prepare_pt2e
1520

1621

@@ -42,11 +47,17 @@ def build_executorch_binary(
4247

4348
edge_compile_config = exir.EdgeCompileConfig(_check_ir_validity=False)
4449
# skipped op names are used for deeplabV3 model
45-
neuro_partitioner = NeuropilotPartitioner([], op_names_to_skip={'aten_convolution_default_106', 'aten_convolution_default_107'})
50+
neuro_partitioner = NeuropilotPartitioner(
51+
[],
52+
op_names_to_skip={
53+
"aten_convolution_default_106",
54+
"aten_convolution_default_107",
55+
},
56+
)
4657
edge_prog = to_edge_transform_and_lower(
47-
aten_dialect,
48-
compile_config=edge_compile_config,
49-
partitioner=[neuro_partitioner],
58+
aten_dialect,
59+
compile_config=edge_compile_config,
60+
partitioner=[neuro_partitioner],
5061
)
5162

5263
exec_prog = edge_prog.to_executorch(
@@ -62,5 +73,3 @@ def make_output_dir(path: str):
6273
os.remove(os.path.join(path, f))
6374
os.removedirs(path)
6475
os.makedirs(path)
65-
66-

examples/mediatek/eval_utils/eval_oss_result.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,23 @@
44
# This source code is licensed under the BSD-style license found in the
55
# LICENSE file in the root directory of this source tree.
66

7-
import sys
7+
import argparse
8+
import json
89
import os
9-
import piq
10+
import sys
11+
1012
import numpy as np
11-
import argparse
13+
import piq
1214
import torch
13-
import json
1415

1516

1617
def check_data(target_f, predict_f):
1718
target_files = os.listdir(target_f)
1819
predict_files = os.listdir(predict_f)
1920
if len(target_files) != len(predict_files):
20-
raise RuntimeError("Data number in target folder and prediction folder must be same")
21+
raise RuntimeError(
22+
"Data number in target folder and prediction folder must be same"
23+
)
2124

2225
predict_set = set(predict_files)
2326
for f in target_files:
@@ -38,7 +41,7 @@ def eval_topk(target_f, predict_f):
3841
def solve(prob, target, k):
3942
_, indices = torch.topk(prob, k=k, sorted=True)
4043
golden = torch.reshape(target, [-1, 1])
41-
correct = (golden == indices)
44+
correct = golden == indices
4245
if torch.any(correct):
4346
return 1
4447
else:
@@ -62,18 +65,18 @@ def solve(prob, target, k):
6265

6366
def eval_piq(target_f, predict_f):
6467
target_files = os.listdir(target_f)
65-
68+
6669
psnr_list = []
6770
ssim_list = []
6871
for target_name in target_files:
6972
pred_name = target_name.replace("golden", "output")
7073
hr = np.fromfile(os.path.join(target_f, target_name), dtype=np.float32)
71-
hr = hr.reshape((1,448,448,3))
74+
hr = hr.reshape((1, 448, 448, 3))
7275
hr = np.moveaxis(hr, 3, 1)
7376
hr = torch.from_numpy(hr)
7477

7578
sr = np.fromfile(os.path.join(predict_f, pred_name), dtype=np.float32)
76-
sr = sr.reshape((1,448,448,3))
79+
sr = sr.reshape((1, 448, 448, 3))
7780
sr = np.moveaxis(sr, 3, 1)
7881
sr = torch.from_numpy(sr).clamp(0, 1)
7982

@@ -188,11 +191,9 @@ def histogram(golden, predict):
188191

189192
check_data(args.target_f, args.out_f)
190193

191-
if args.eval_type == 'topk':
194+
if args.eval_type == "topk":
192195
eval_topk(args.target_f, args.out_f)
193-
elif args.eval_type == 'piq':
196+
elif args.eval_type == "piq":
194197
eval_piq(args.target_f, args.out_f)
195-
elif args.eval_type == 'segmentation':
198+
elif args.eval_type == "segmentation":
196199
eval_segmentation(args.target_f, args.out_f)
197-
198-

examples/mediatek/executor_runner/mtk_oss_executor_runner.cpp

Lines changed: 32 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,12 @@
1818
* all fp32 tensors.
1919
*/
2020

21+
#include <cstdlib>
2122
#include <ctime>
22-
#include <iostream>
23+
#include <filesystem>
2324
#include <fstream>
25+
#include <iostream>
2426
#include <memory>
25-
#include <cstdlib>
26-
#include <filesystem>
2727

2828
#include <gflags/gflags.h>
2929

@@ -38,14 +38,23 @@
3838
static uint8_t method_allocator_pool[8 * 1024U * 1024U]; // 8 MB
3939

4040
// Model Path
41-
DEFINE_string(model_path, "model.pte", "Model serialized in flatbuffer format. Default to 'model.pte'");
42-
DEFINE_string(input_list, "input_list.txt", "Model input list. Default to 'input_list.txt'");
43-
DEFINE_string(output_folder, "outputs", "Model output folder. Default to 'outputs'");
41+
DEFINE_string(
42+
model_path,
43+
"model.pte",
44+
"Model serialized in flatbuffer format. Default to 'model.pte'");
45+
DEFINE_string(
46+
input_list,
47+
"input_list.txt",
48+
"Model input list. Default to 'input_list.txt'");
49+
DEFINE_string(
50+
output_folder,
51+
"outputs",
52+
"Model output folder. Default to 'outputs'");
4453

4554
using namespace torch::executor;
4655
using torch::executor::MemoryAllocator;
47-
using torch::executor::util::FileDataLoader;
4856
using torch::executor::util::BufferCleanup;
57+
using torch::executor::util::FileDataLoader;
4958
using namespace std::filesystem;
5059

5160
int main(int argc, char** argv) {
@@ -132,11 +141,12 @@ int main(int argc, char** argv) {
132141
// fast/small SRAM, or for memory associated with particular cores.
133142
std::vector<std::unique_ptr<uint8_t[]>> planned_buffers; // Owns the memory
134143
std::vector<Span<uint8_t>> planned_spans; // Passed to the allocator
135-
size_t num_memory_planned_buffers = method_meta_result->num_memory_planned_buffers();
144+
size_t num_memory_planned_buffers =
145+
method_meta_result->num_memory_planned_buffers();
136146
for (size_t id = 0; id < num_memory_planned_buffers; ++id) {
137147
// .get() will always succeed because id < num_memory_planned_buffers.
138-
size_t buffer_size =
139-
static_cast<size_t>(method_meta_result->memory_planned_buffer_size(id).get());
148+
size_t buffer_size = static_cast<size_t>(
149+
method_meta_result->memory_planned_buffer_size(id).get());
140150
ET_LOG(Info, "Setting up planned buffer %zu, size %zu.", id, buffer_size);
141151
planned_buffers.push_back(std::make_unique<uint8_t[]>(buffer_size));
142152
planned_spans.push_back({planned_buffers.back().get(), buffer_size});
@@ -164,8 +174,8 @@ int main(int argc, char** argv) {
164174
std::ifstream input_list(FLAGS_input_list);
165175
ET_CHECK_MSG(
166176
input_list.is_open(),
167-
"Error: cannot open input file %s",
168-
FLAGS_input_list.c_str());
177+
"Error: cannot open input file %s",
178+
FLAGS_input_list.c_str());
169179

170180
auto split = [](std::string s, std::string delimiter) {
171181
size_t pos_start = 0, pos_end, delim_len = delimiter.length();
@@ -225,7 +235,7 @@ int main(int argc, char** argv) {
225235
nbytes);
226236

227237
fin.seekg(0, fin.beg);
228-
fin.read(static_cast<char*> (data_ptr), file_size);
238+
fin.read(static_cast<char*>(data_ptr), file_size);
229239
fin.close();
230240
inputs[num_allocated++] = data_ptr;
231241

@@ -243,8 +253,7 @@ int main(int argc, char** argv) {
243253
Tensor tensor(&impl);
244254
Error ret = method->set_input(tensor, i);
245255
if (ret != Error::Ok) {
246-
ET_LOG(
247-
Error, "Failed to set input %zu: 0x%" PRIx32, i, (uint32_t)ret);
256+
ET_LOG(Error, "Failed to set input %zu: 0x%" PRIx32, i, (uint32_t)ret);
248257
// The BufferCleanup will free the inputs when it goes out of scope.
249258
BufferCleanup cleanup({inputs, num_allocated});
250259
return 1;
@@ -258,14 +267,12 @@ int main(int argc, char** argv) {
258267
Error status = Error::Ok;
259268
status = method->execute();
260269
auto after_exec = std::chrono::high_resolution_clock::now();
261-
double elapsed_time =
262-
std::chrono::duration_cast<std::chrono::microseconds>(
263-
after_exec - before_exec).count() / 1000.0;
264-
265-
ET_LOG(
266-
Info,
267-
"Inference took %f ms",
268-
elapsed_time);
270+
double elapsed_time = std::chrono::duration_cast<std::chrono::microseconds>(
271+
after_exec - before_exec)
272+
.count() /
273+
1000.0;
274+
275+
ET_LOG(Info, "Inference took %f ms", elapsed_time);
269276
ET_CHECK_MSG(
270277
status == Error::Ok,
271278
"Execution of method %s failed with status 0x%" PRIx32,
@@ -282,11 +289,9 @@ int main(int argc, char** argv) {
282289
for (size_t i = 0; i < output_size; i++) {
283290
auto output_tensor = outputs[i].toTensor();
284291
auto output_file_name = FLAGS_output_folder + "/output_" +
285-
std::to_string(inference_index) + "_" +
286-
std::to_string(i) + ".bin";
292+
std::to_string(inference_index) + "_" + std::to_string(i) + ".bin";
287293
std::ofstream fout(output_file_name.c_str(), std::ios::binary);
288-
fout.write(
289-
output_tensor.const_data_ptr<char>(), output_tensor.nbytes());
294+
fout.write(output_tensor.const_data_ptr<char>(), output_tensor.nbytes());
290295
fout.close();
291296
}
292297

examples/mediatek/model_export_scripts/deeplab_v3.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,22 @@
44
# This source code is licensed under the BSD-style license found in the
55
# LICENSE file in the root directory of this source tree.
66

7+
import argparse
78
import json
89
import os
910
import random
1011
import re
1112
import sys
13+
1214
import numpy as np
13-
import argparse
1415

1516
import torch
1617
from executorch.backends.mediatek import Precision
17-
from executorch.examples.models.deeplab_v3 import DeepLabV3ResNet101Model
1818
from executorch.examples.mediatek.aot_utils.oss_utils.utils import (
1919
build_executorch_binary,
2020
make_output_dir,
2121
)
22+
from executorch.examples.models.deeplab_v3 import DeepLabV3ResNet101Model
2223

2324

2425
class NhwcWrappedModel(torch.nn.Module):
@@ -112,7 +113,7 @@ def get_dataset(data_size, dataset_dir, download):
112113
for idx, data in enumerate(targets):
113114
file_name = f"{args.artifact}/golden_{idx}_0.bin"
114115
data.tofile(file_name)
115-
if idx==0:
116+
if idx == 0:
116117
print("golden shape: ", data.shape)
117118
print("golden type: ", data.dtype)
118119

@@ -126,4 +127,3 @@ def get_dataset(data_size, dataset_dir, download):
126127
inputs,
127128
quant_dtype=Precision.A8W8,
128129
)
129-

examples/mediatek/model_export_scripts/edsr.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,19 @@
44
# This source code is licensed under the BSD-style license found in the
55
# LICENSE file in the root directory of this source tree.
66

7+
import argparse
78
import json
89
import os
10+
911
import numpy as np
10-
import argparse
1112

1213
import torch
1314
from executorch.backends.mediatek import Precision
14-
from executorch.examples.models.edsr import EdsrModel
1515
from executorch.examples.mediatek.aot_utils.oss_utils.utils import (
1616
build_executorch_binary,
1717
make_output_dir,
1818
)
19+
from executorch.examples.models.edsr import EdsrModel
1920

2021
from PIL import Image
2122
from torch.utils.data import Dataset
@@ -33,6 +34,7 @@ def forward(self, input1):
3334
nchw_output = self.edsr(nchw_input1)
3435
return nchw_output.permute(0, 2, 3, 1)
3536

37+
3638
class SrDataset(Dataset):
3739
def __init__(self, hr_dir: str, lr_dir: str):
3840
self.input_size = np.asanyarray([224, 224])
@@ -59,7 +61,11 @@ def __len__(self):
5961

6062
def _resize_img(self, file: str, scale: int):
6163
with Image.open(file) as img:
62-
return to_tensor(img.resize(tuple(self.input_size * scale))).unsqueeze(0).permute(0, 2, 3, 1)
64+
return (
65+
to_tensor(img.resize(tuple(self.input_size * scale)))
66+
.unsqueeze(0)
67+
.permute(0, 2, 3, 1)
68+
)
6369

6470
def get_input_list(self):
6571
input_list = ""
@@ -164,5 +170,3 @@ def get_dataset(hr_dir: str, lr_dir: str, default_dataset: str, dataset_dir: str
164170
[(input,) for input in inputs],
165171
quant_dtype=Precision.A8W8,
166172
)
167-
168-

examples/mediatek/model_export_scripts/inception_v3.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,19 @@
44
# This source code is licensed under the BSD-style license found in the
55
# LICENSE file in the root directory of this source tree.
66

7+
import argparse
78
import json
89
import os
10+
911
import numpy as np
10-
import argparse
1112

1213
import torch
1314
from executorch.backends.mediatek import Precision
14-
from executorch.examples.models.inception_v3 import InceptionV3Model
1515
from executorch.examples.mediatek.aot_utils.oss_utils.utils import (
1616
build_executorch_binary,
1717
make_output_dir,
1818
)
19+
from executorch.examples.models.inception_v3 import InceptionV3Model
1920

2021

2122
class NhwcWrappedModel(torch.nn.Module):
@@ -28,6 +29,7 @@ def forward(self, input1):
2829
output = self.inception(nchw_input1)
2930
return output
3031

32+
3133
def get_dataset(dataset_path, data_size):
3234
from torchvision import datasets, transforms
3335

@@ -55,7 +57,7 @@ def get_data_loader():
5557
if index >= data_size:
5658
break
5759
feature, target = data
58-
feature = feature.permute(0, 2, 3, 1) # NHWC
60+
feature = feature.permute(0, 2, 3, 1) # NHWC
5961
inputs.append((feature,))
6062
targets.append(target)
6163
input_list += f"input_{index}_0.bin\n"
@@ -120,5 +122,3 @@ def get_data_loader():
120122
inputs,
121123
quant_dtype=Precision.A8W8,
122124
)
123-
124-

0 commit comments

Comments
 (0)