Skip to content

Commit d9f2c46

Browse files
committed
Arm backend: Fixes and ignores for bandit
Added fixes or ignores for bandit, most are for tests that can just be safely ignored and some are actual good finds like pinning versions and safe practices. Signed-off-by: per.held@arm.com Change-Id: I783676e285f7cb3ad7c8615e8774092dcf4ef559
1 parent 8438bde commit d9f2c46

File tree

11 files changed

+38
-25
lines changed

11 files changed

+38
-25
lines changed

backends/arm/_passes/fuse_equal_placeholders_pass.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def call(self, graph_module: torch.fx.GraphModule) -> PassResult:
6060
is_int48,
6161
str(t_cpu.dtype),
6262
tuple(t_cpu.shape),
63-
hashlib.sha1(data_bytes).hexdigest(),
63+
hashlib.sha1(data_bytes, usedforsecurity=False).hexdigest(),
6464
)
6565
hash_buckets[key].append((node, t_cpu))
6666

backends/arm/test/conftest.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def pytest_addoption(parser):
4040
def try_addoption(*args, **kwargs):
4141
try:
4242
parser.addoption(*args, **kwargs)
43-
except Exception:
43+
except Exception: # nosec B110 - pytest redefines options, safe to ignore
4444
pass
4545

4646
try_addoption("--arm_quantize_io", action="store_true", help="Deprecated.")
@@ -85,7 +85,7 @@ def set_random_seed():
8585

8686
if os.environ.get("ARM_TEST_SEED", "RANDOM") == "RANDOM":
8787
random.seed() # reset seed, in case any other test has fiddled with it
88-
seed = random.randint(0, 2**32 - 1)
88+
seed = random.randint(0, 2**32 - 1) # nosec B311 - non-crypto seed for tests
8989
torch.manual_seed(seed)
9090
else:
9191
seed_str = os.environ.get("ARM_TEST_SEED", "0")

backends/arm/test/misc/test_debug_hook.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def _get_action_str() -> str:
3131
name="convolution",
3232
target="aten.convolution.default",
3333
graph_id=6052414368,
34-
pass_name="ExportedProgram.module()",
34+
pass_name="ExportedProgram.module()", # nosec B106 - static test string, not a secret
3535
action="create",
3636
from_node=[],
3737
_get_action_string=_get_action_str,
@@ -41,7 +41,7 @@ def _get_action_str() -> str:
4141
name="convolution",
4242
target="aten.convolution.default",
4343
graph_id=5705954832,
44-
pass_name="Interpreter_PropagateUnbackedSymInts",
44+
pass_name="Interpreter_PropagateUnbackedSymInts", # nosec B106 - static test string, not a secret
4545
action="create",
4646
from_node=[from_node_2],
4747
_get_action_string=_get_action_str,
@@ -69,7 +69,7 @@ def _get_action_str() -> str:
6969
name="convolution",
7070
target="aten.convolution.default",
7171
graph_id=5705954832,
72-
pass_name="Interpreter_PropagateUnbackedSymInts",
72+
pass_name="Interpreter_PropagateUnbackedSymInts", # nosec B106 - static test string, not a secret
7373
action="create",
7474
from_node=[],
7575
_get_action_string=_get_action_str,

backends/arm/test/misc/test_save_exported_model.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ def test_save_load_exported_int_model():
4848
torch.export.save(quantized_exported_module, file_path)
4949

5050
# Verify that we can load the model back
51-
loaded_model = torch.export.load(file_path)
51+
loaded_model = torch.export.load(
52+
file_path
53+
) # nosec B614 - loads trusted test artifact
5254
for original_node, loaded_node in zip(
5355
quantized_exported_module.graph.nodes, loaded_model.graph.nodes
5456
):

backends/arm/test/models/test_nss.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ def nss() -> AutoEncoderV1:
3636
"""Get an instance of NSS with weights loaded."""
3737

3838
weights = hf_hub_download(
39-
repo_id="Arm/neural-super-sampling", filename="nss_v0.1.0_fp32.pt"
39+
repo_id="Arm/neural-super-sampling",
40+
filename="nss_v0.1.0_fp32.pt",
41+
revision="2e9b606acd9fa25071825a12f0764f1c3bef9480",
4042
)
4143

4244
nss_model = NSS()

backends/arm/test/runner_utils.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import os
99
import re
1010
import shutil
11-
import subprocess
11+
import subprocess # nosec B404 - invoked only for trusted toolchain binaries
1212
import tempfile
1313

1414
from pathlib import Path
@@ -572,7 +572,9 @@ def _run_cmd(cmd: List[str], check=True) -> subprocess.CompletedProcess[bytes]:
572572
cmd (List[str]): The command to run as a list.
573573
"""
574574
try:
575-
result = subprocess.run(cmd, check=check, capture_output=True)
575+
result = subprocess.run( # nosec B603 - cmd constructed from trusted inputs
576+
cmd, check=check, capture_output=True
577+
)
576578
return result
577579
except subprocess.CalledProcessError as e:
578580
arg_string = " ".join(cmd)
@@ -637,8 +639,7 @@ def dbg_tosa_fb_to_json(tosa_fb: bytes) -> Dict:
637639
data = np.frombuffer(data, dtype=np.float32)
638640
data = data.reshape(tensor["shape"])
639641
tensor["data"] = data
640-
except Exception:
641-
# This is just nice-to-have if it works, don't care if it fails.
642+
except Exception: # nosec B110 - best-effort casting for debug output only
642643
pass
643644

644645
return json_out

backends/arm/test/test_model.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import argparse
77
import os
8-
import subprocess
8+
import subprocess # nosec B404 - launches trusted build/test scripts
99
import sys
1010
import time
1111
from typing import Sequence
@@ -106,7 +106,9 @@ def get_args():
106106
def run_external_cmd(cmd: Sequence[str]) -> None:
107107
print("CALL:", *cmd, sep=" ")
108108
try:
109-
subprocess.check_call(cmd)
109+
subprocess.check_call(
110+
cmd
111+
) # nosec B603 - cmd assembled from vetted scripts/flags
110112
except subprocess.CalledProcessError as err:
111113
print("ERROR called: ", *cmd, sep=" ")
112114
print(f"Failed with: {err.returncode}")

backends/arm/util/arm_model_evaluator.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,9 @@ def _build_calibration_loader(
6565
seed = default_seed
6666
else:
6767
seed = default_seed
68-
rng = random.Random(seed)
68+
rng = random.Random(
69+
seed
70+
) # nosec B311 - deterministic shuffling for evaluation only
6971
indices = list(range(len(dataset)))
7072
rng.shuffle(indices)
7173
selected = sorted(indices[:k])

backends/arm/vgf/backend.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
"""Ahead-of-time Arm VGF backend built on the shared TOSA pipeline."""
1414

1515
import logging
16-
import os
17-
import subprocess
16+
import os # nosec B404 - used alongside subprocess for tool invocation
17+
import subprocess # nosec B404 - required to drive external converter CLI
1818
import tempfile
1919
from typing import final, List
2020

@@ -150,7 +150,7 @@ def vgf_compile(
150150
f"{converter_binary} {additional_flags} -i {tosa_path} -o {vgf_path}"
151151
)
152152
try:
153-
subprocess.run(
153+
subprocess.run( # nosec B602 - shell invocation constrained to trusted converter binary
154154
[conversion_command], shell=True, check=True, capture_output=True
155155
)
156156
except subprocess.CalledProcessError as process_error:
@@ -164,7 +164,9 @@ def vgf_compile(
164164
logger.info(f"Emitting debug output to: {vgf_path=}")
165165
os.makedirs(artifact_path, exist_ok=True)
166166
cp = f"cp {vgf_path} {artifact_path}"
167-
subprocess.run(cp, shell=True, check=True, capture_output=False)
167+
subprocess.run( # nosec B602 - shell copy of trusted artifact for debugging
168+
cp, shell=True, check=True, capture_output=False
169+
)
168170

169171
vgf_bytes = open(vgf_path, "rb").read()
170172
return vgf_bytes

examples/arm/aot_arm_compiler.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -74,15 +74,17 @@
7474
logging.basicConfig(level=logging.WARNING, format=FORMAT)
7575

7676

77-
def _load_example_inputs(model_input: str | None) -> Any:
77+
def _load_example_inputs(model_input: str | None) -> Any: # nosec B614
7878
"""Load example inputs from a `.pt` file when a path is provided."""
7979
if model_input is None:
8080
return None
8181

8282
logging.info(f"Load model input from {model_input}")
8383

8484
if model_input.endswith(".pt"):
85-
return torch.load(model_input, weights_only=False)
85+
return torch.load(
86+
model_input, weights_only=False
87+
) # nosec B614 trusted artifacts
8688

8789
raise RuntimeError(
8890
f"Model input data '{model_input}' is not a valid name. Use --model_input "
@@ -167,14 +169,14 @@ def _load_python_module_model(
167169

168170
def _load_serialized_model(
169171
model_name: str, example_inputs: Any
170-
) -> Optional[Tuple[torch.nn.Module, Any]]:
172+
) -> Optional[Tuple[torch.nn.Module, Any]]: # nosec B614
171173
"""Load a serialized Torch model saved via `torch.save`."""
172174
if not model_name.endswith((".pth", ".pt")):
173175
return None
174176

175177
logging.info(f"Load model file {model_name}")
176178

177-
model = torch.load(model_name, weights_only=False)
179+
model = torch.load(model_name, weights_only=False) # nosec B614 trusted inputs
178180
if example_inputs is None:
179181
raise RuntimeError(
180182
f"Model '{model_name}' requires input data specify --model_input <FILE>.pt"

0 commit comments

Comments
 (0)