Skip to content

Avoid using NumPy inside PyTorch modules

Description

Using NumPy functions inside PyTorch modules can lead to efficiency issues and problems with ONNX loading. It is recommended to avoid mixing these libraries.

Examples

Insecure Code

python
class MyModule(torch.nn.Module):
    def __init__(self):
        self.x = numpy.array([1, 2, 3])

Secure Code

python
class MyModule(torch.nn.Module):
    def __init__(self):
        self.x = torch.tensor([1, 2, 3])

Remediation

Refactor the code to use PyTorch functions instead of NumPy functions inside PyTorch modules.

Rule Details

FieldValue
IDCODE-0758
CategoryPerformance
SeverityMEDIUM
CWE
ConfidenceMEDIUM
ImpactMEDIUM
LikelihoodMEDIUM
ExploitabilityCOMPLEX
Tagsperformance, audit
OWASPN/A

References