Skip to content

Bug-set-submodule-assigns-module-to-new-attribute #143441

@mariovas3

Description

@mariovas3

🐛 Describe the bug

Based on the docstring of nn.Module.set_submodule - https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.set_submodule

we have Set the submodule given by target if it exists, otherwise throw an error.

This is violated when passing non-dot-delimited strings.

This is because calling .split('.') on non-dot-delimited strings will result in a singleton list - '0'.split('.') -> ['0']. Currently you pop the last element of the resulting list, making it an empty list and the for loop that follows (where all the validation checks are done) gets skipped. So you directly jump to setting the attribute even though it might not exist. https://github.com/pytorch/pytorch/blob/main/torch/nn/modules/module.py#L773

E.g., see the example below:

from torch import nn


class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Linear(3, 4)


model = SimpleModel()
model.set_submodule('0', nn.Conv2d(2, 3, 3))
# this will work, despite there being no module named '0' in model
assert isinstance(getattr(model, '0'), nn.Conv2d)


try:
    model.set_submodule('foo.bar', nn.Conv2d(2, 3, 3))
except AttributeError as e:
    message = str(e)
    assert message == 'SimpleModel has no attribute `foo`'

I tested the above using the nightly release environment - created using the pytorch/tools/nightly.py script.

I am available to work on this, if you believe it is of value.

Versions

output of the collect_env.py script:

Collecting environment information...
PyTorch version: 2.6.0.dev20241216+cpu
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0
Clang version: Could not collect
CMake version: version 3.31.2
Libc version: glibc-2.31

Python version: 3.11.11 (main, Dec 11 2024, 16:28:39) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-125-generic-x86_64-with-glibc2.31
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                         x86_64
CPU op-mode(s):                       32-bit, 64-bit
Byte Order:                           Little Endian
Address sizes:                        39 bits physical, 48 bits virtual
CPU(s):                               8
On-line CPU(s) list:                  0-7
Thread(s) per core:                   2
Core(s) per socket:                   4
Socket(s):                            1
NUMA node(s):                         1
Vendor ID:                            GenuineIntel
CPU family:                           6
Model:                                142
Model name:                           Intel(R) Core(TM) i5-8265U CPU @ 1.60GHz
Stepping:                             12
CPU MHz:                              1800.000
CPU max MHz:                          3900.0000
CPU min MHz:                          400.0000
BogoMIPS:                             3600.00
Virtualisation:                       VT-x
L1d cache:                            128 KiB
L1i cache:                            128 KiB
L2 cache:                             1 MiB
L3 cache:                             6 MiB
NUMA node0 CPU(s):                    0-7
Vulnerability Gather data sampling:   Mitigation; Microcode
Vulnerability Itlb multihit:          KVM: Mitigation: VMX disabled
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow:   Not affected
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
Vulnerability Srbds:                  Mitigation; Microcode
Vulnerability Tsx async abort:        Not affected
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust sgx bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp md_clear flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] mypy==1.13.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==2.2.0
[conda] No relevant packages

cc @albanD @mruberry @jbschlosser @walterddr @mikaylagawarecki

Metadata

Metadata

Assignees

No one assigned

    Labels

    module: nnRelated to torch.nntriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions