Repository: pytorch
Issue: Graph break due to unsupported builtin sys.audit
Labels: triaged,oncall: pt2,module: dynamo

### 🐛 Describe the bug

I'm using @torch.compile() for the initialization of a class. 
Hopefully it will speed it up.
sys.audit doesn't seem to be supported, but I don't explicitly call it in my code.
Maybe it's an operation of a function?

After I used these two lines of codes, the warning disappeared and a 2x speed boost was observed.
```
torch.compiler.allow_in_graph(sys.audit)
torch.compiler.allow_in_graph(os.fspath)
```
I searched all the issues according to the warning, and there was no identical discussion, so I brought up this issue.


### Error logs


/opt/conda/envs/monodle/lib/python3.11/site-packages/torch/_dynamo/variables/functions.py:663: UserWarning: Graph break due to unsupported builtin sys.audit. This function is either a Python builtin (e.g. _warnings.warn) or a third-party C/C++ Python extension (perhaps created with pybind). If it is a Python builtin, please file an issue on GitHub so the PyTorch team can add support for it and see the next case for a workaround. If it is a third-party C/C++ Python extension, please either wrap it into a PyTorch-understood custom operator (see https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html for more details) or, if it is traceable, use torch.compiler.allow_in_graph.
  torch._dynamo.utils.warn_once(msg)


### Minified repro

```
class OpenLane_dataset(Dataset):
    @torch.compile()
    def __init__(self, image_path, 
                   label_path,
                   point_range,
                   ):
        self.lane_type = {0: 'unkown',
                        1: 'white-dash',
                        2: 'white-solid',
                        3: 'double-white-dash',
                        4: 'double-white-solid',
                        5: 'white-ldash-rsolid',
                        6: 'white-lsolid-rdash',
                        7: 'yellow-dash',
                        8: 'yellow-solid',
                        9: 'double-yellow-dash',
                        10: 'double-yellow-solid',
                        11: 'yellow-ldash-rsolid',
                        12: 'yellow-lsolid-rdash',
                        20: 'left-curbside',
                        21: 'right-curbside'}
        torch.compiler.allow_in_graph(os.listdir)
        torch.compiler.allow_in_graph(sys.audit)
        torch.compiler.allow_in_graph(os.fspath)
        
        self.image_path = image_path #路径
        self.label_path = label_path #路径
        self.point_range = torch.tensor([point_range]).T # [3,1]
        self.anchors = build_anchor([10,20,40,60,80,100], [2,1,-1,-2]).T / self.point_range # [3,0]
        
        self.label_stash = list_subdirectories(label_path) # 提取所有子文件夹

        # 提取所有json绝对路径
        temp_l = []
        for file_path in self.label_stash:
            for json_file in os.listdir(file_path): # xxx.json
                temp_l.append(f'{file_path}/{json_file}')
        self.label_stash = temp_l

        # TODO:稀疏自动调整锚点
        lane_max_all = torch.empty((3,0))
        for i in tqdm(range(int(len(self.label_stash) * 0.2)),'find best anchor'):
            index = random.randint(0,len(self.label_stash)-1)
            label_file_path = self.label_stash[index]
            with open(label_file_path) as label:
                label = orjson.loads(label.read())
            lane_lines = label['lane_lines'] # many lanes
            if len(lane_lines) == 0: continue
            lane_xyz = torch.empty((3,0))
            for index,lane in enumerate(lane_lines):
                lane_attribute = lane['attribute']
                if lane_attribute == 0: continue
                lane_xyz = torch.cat((lane_xyz,torch.tensor(lane['xyz'])),dim=1)
                lane_xyz = torch.abs(lane_xyz)
            if lane_xyz.numel() == 0:continue
            lane_max = torch.amax(lane_xyz,dim=1).unsqueeze(1)
            lane_max_all = torch.cat((lane_max_all,lane_max),dim=1)
        
        lane_mean = torch.mean(lane_max_all,dim=1)
        lane_median = torch.median(lane_max_all,dim=1).values
        print(f'found mean {lane_mean} median {lane_median} in {lane_max_all.shape}')
            
    def __getitem__(self, index):
        start_time = time.time()
        label_file_path = self.label_stash[index]
        with open(label_file_path) as label:
            label = orjson.loads(label.read())

        intrinsic = label['intrinsic']
        extrinsic = label['extrinsic']
        lane_lines = label['lane_lines'] # many lanes
        file_path = label['file_path'].split('/',1)[1] #training/segment-xxx/xxx.jpg
        pose = label['pose']

        image = torchvision.io.read_image(f'{self.image_path}/{file_path}')
        transform = torchvision.transforms.Resize((384,1280))
        image = transform(image) 
        image = image / 255.0

        if len(lane_lines) == 0: 
            return image,{'distance':torch.zeros_like(self.anchors).float()},{'get_item_time':time.time()-start_time}
        
        lane_left_left =    torch.empty((3,0))
        lane_left =         torch.empty((3,0))
        lane_right_right =  torch.empty((3,0))
        lane_right =        torch.empty((3,0))
        # 提取车道线xyz
        for index,lane in enumerate(lane_lines):
            lane_category = lane['category']
            lane_visibility = lane['visibility']
            lane_uv =None
            lane_xyz = torch.tensor(lane['xyz'])
            lane_attribute = lane['attribute']
            lane_track_id = None
            if lane_attribute == 1:
                lane_left_left = torch.cat((lane_left_left,lane_xyz),dim=1)
            if lane_attribute == 2:
                lane_left = torch.cat((lane_left,lane_xyz),dim=1)
            if lane_attribute == 3:
                lane_right = torch.cat((lane_right,lane_xyz),dim=1)
            if lane_attribute == 4:
                lane_right_right = torch.cat((lane_right_right,lane_xyz),dim=1)

        if len(lane_left_left) == 0 and len(lane_left) == 0 and len(lane_right) == 0 and len(lane_right_right) == 0: 
            return image,{'distance':torch.zeros_like(self.anchors).float()},{'get_item_time':time.time()-start_time}

        #print(lane_left_left.shape,lane_left.shape,lane_right.shape,lane_right_right.shape)
        lane_left_left = range_flitter(lane_left_left,self.point_range)
        lane_left = range_flitter(lane_left,self.point_range)
        lane_right = range_flitter(lane_right,self.point_range)
        lane_right_right = range_flitter(lane_right_right,self.point_range)

        lane_left_left = lane_left_left / self.point_range # xyz归一化
        lane_left = lane_left / self.point_range
        lane_right_right = lane_right_right / self.point_range
        lane_right = lane_right / self.point_range
        
        
        # 依据锚点寻找最近点/最近点xyz偏置
        near_left_left = torch.empty((3,0))
        near_left = torch.empty((3,0))
        near_right_right = torch.empty((3,0))
        near_right = torch.empty((3,0))
        dis_left_left = torch.empty((3,0))
        dis_left = torch.empty((3,0))
        dis_right = torch.empty((3,0))
        dis_right_right = torch.empty((3,0))
        for index,anchor_point in enumerate(self.anchors.T):
            if index % 4 == 0:  # left_left
                new_find = find_nearest_point(anchor_point,lane_left_left.T).unsqueeze(1)
                near_left_left = torch.cat((near_left_left,new_find),dim=1)
                dis_left_left = torch.cat((dis_left_left,(self.anchors.T[index]-new_find.T[0]).unsqueeze(1)),dim=1)
            elif index % 4 == 1: # left
                new_find = find_nearest_point(anchor_point,lane_left.T).unsqueeze(1)
                near_left = torch.cat((near_left,new_find),dim=1)
                dis_left = torch.cat((dis_left,(self.anchors.T[index]-new_find.T[0]).unsqueeze(1)),dim=1)
            elif index % 4 == 2: # right
                new_find = find_nearest_point(anchor_point,lane_right_right.T).unsqueeze(1)
                near_right_right = torch.cat((near_right_right,new_find),dim=1)
                dis_right = torch.cat((dis_right,(self.anchors.T[index]-new_find.T[0]).unsqueeze(1)),dim=1)
            elif index % 4 == 3: # right_right
                new_find = find_nearest_point(anchor_point,lane_right.T).unsqueeze(1)
                near_right = torch.cat((near_right,new_find),dim=1)
                dis_right_right = torch.cat((dis_right_right,(self.anchors.T[index]-new_find.T[0]).unsqueeze(1)),dim=1)
        distance = torch.cat((dis_left_left,dis_left,dis_right,dis_right_right),dim=1)
        targets = {'distance':distance}
        info = {'get_item_time':time.time()-start_time}

        return image,targets,info

                

    def __len__(self):
        return len(self.label_stash)


def range_flitter(xyz,point_range):
    xyz = torch.abs(xyz)
    exceeds_threshold = (xyz < point_range).all(dim=0).nonzero().T[0]
    xyz = xyz[:,exceeds_threshold] 
    return xyz

def build_anchor(anchor_x,anchor_y,anchor_z=0):
    points = []
    for x in anchor_x:
        for y in anchor_y:
            points.append((x,y,anchor_z))
    
    points = torch.tensor(points)
    return points

def find_nearest_point(query_point, points):  
    """  
    在点集points中寻找与query_point最近的点。  
  
    :param query_point: torch.Tensor，形状为(3,)，表示一个三维空间中的点。  
    :param points: torch.Tensor，形状为(N, 3)，表示N个三维空间中的点。  
    :return: torch.Tensor，形状为(3,)，表示找到的最近点。  
    """  
    if points.numel() == 0: # 如果待查点集为0,则返回请求点自身
        return query_point

    # 计算query_point与points中每个点之间的欧几里得距离  
    distances = torch.norm(points - query_point, dim=1)  
  
    # 找到距离最小的索引  
    min_index = torch.argmin(distances)  
  
    # 返回对应的最近点  
    return points[min_index] 


def list_subdirectories(directory):  
    subdirs = []  
    for root, dirs, files in os.walk(directory):  
        for dir in dirs:  
            subdir = os.path.join(root, dir)  
            subdirs.append(subdir)  
    return subdirs

```

### Versions

```
Collecting environment information...
PyTorch version: 2.4.0
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: Could not collect
CMake version: version 3.30.2
Libc version: glibc-2.31

Python version: 3.11.9 | packaged by conda-forge | (main, Apr 19 2024, 18:36:13) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-5.15.0-1053-nvidia-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA A100-SXM4-80GB
GPU 1: NVIDIA A100-SXM4-80GB
GPU 2: NVIDIA A100-SXM4-80GB
GPU 3: NVIDIA A100-SXM4-80GB
GPU 4: NVIDIA A100-SXM4-80GB
GPU 5: NVIDIA A100-SXM4-80GB
GPU 6: NVIDIA A100-SXM4-80GB
GPU 7: NVIDIA A100-SXM4-80GB

Nvidia driver version: 535.161.08
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.6.0
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:                      43 bits physical, 48 bits virtual
CPU(s):                             256
On-line CPU(s) list:                0-255
Thread(s) per core:                 2
Core(s) per socket:                 64
Socket(s):                          2
NUMA node(s):                       8
Vendor ID:                          AuthenticAMD
CPU family:                         23
Model:                              49
Model name:                         AMD EPYC 7742 64-Core Processor
Stepping:                           0
Frequency boost:                    enabled
CPU MHz:                            3389.390
CPU max MHz:                        2250.0000
CPU min MHz:                        1500.0000
BogoMIPS:                           4491.47
Virtualization:                     AMD-V
L1d cache:                          4 MiB
L1i cache:                          4 MiB
L2 cache:                           64 MiB
L3 cache:                           512 MiB
NUMA node0 CPU(s):                  0-15,128-143
NUMA node1 CPU(s):                  16-31,144-159
NUMA node2 CPU(s):                  32-47,160-175
NUMA node3 CPU(s):                  48-63,176-191
NUMA node4 CPU(s):                  64-79,192-207
NUMA node5 CPU(s):                  80-95,208-223
NUMA node6 CPU(s):                  96-111,224-239
NUMA node7 CPU(s):                  112-127,240-255
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Not affected
Vulnerability Retbleed:             Mitigation; untrained return thunk; SMT enabled with STIBP protection
Vulnerability Spec rstack overflow: Mitigation; safe RET
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; Retpolines, IBPB conditional, STIBP always-on, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
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 mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr rdpru wbnoinvd arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl umip rdpid overflow_recov succor smca sme sev sev_es

Versions of relevant libraries:
[pip3] numpy==2.0.1
[pip3] optree==0.12.1
[pip3] torch==2.4.0
[pip3] torchaudio==2.4.0
[pip3] torchinfo==1.8.0
[pip3] torchopt==0.7.3
[pip3] torchvision==0.19.0
[pip3] triton==3.0.0
[conda] blas                      1.0                         mkl    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] libjpeg-turbo             2.0.0                h9bf148f_0    pytorch
[conda] mkl                       2023.1.0         h213fc3f_46344    defaults
[conda] mkl-service               2.4.0           py311h5eee18b_1    defaults
[conda] mkl_fft                   1.3.8           py311h5eee18b_0    defaults
[conda] mkl_random                1.2.4           py311hdb19cb5_0    defaults
[conda] numpy                     1.26.4          py311h08b1b3b_0    defaults
[conda] numpy-base                1.26.4          py311hf175353_0    defaults
[conda] pytorch                   2.4.0           py3.11_cuda12.1_cudnn9.1.0_0    pytorch
[conda] pytorch-cuda              12.1                 ha16c6d3_5    pytorch
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                2.4.0               py311_cu121    pytorch
[conda] torchinfo                 1.8.0                    pypi_0    pypi
[conda] torchtriton               3.0.0                     py311    pytorch
[conda] torchvision               0.19.0              py311_cu121    pytorch
```

cc @ezyang @chauhang @penguinwu @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @chenyang78 @kadeng @amjames