pytorch_geometric icon indicating copy to clipboard operation
pytorch_geometric copied to clipboard

Bug Report: Missing Keys in slice_dict for HeteroData Objects

Open baidingyuan opened this issue 7 months ago • 0 comments

🐛 Describe the bug

Description

I encountered an issue when using HeteroData objects with the PyTorch Geometric library. Specifically, while processing and saving HeteroData objects, keys such as subject and object were missing from the slice_dict during data loading. This causes a KeyError when trying to access these keys in the loaded data.

class Rail(InMemoryDataset):

    def __init__(
        self,
        root: str,
        transform: Optional[Callable] = None,
        pre_transform: Optional[Callable] = None,
        force_reload: bool = False,
    ) -> None:
        super().__init__(root, transform, pre_transform,
                         force_reload=force_reload)
        self.load(self.processed_paths[0], data_cls=HeteroData)

    @property
    def raw_file_names(self) -> str:
        return 'railway_hetero.csv'

    @property
    def processed_file_names(self) -> str:
        return 'data.pt'

    def download(self) -> None:
        pass


    def process(self) -> None:
        # 定义列名
        cols = ['graph_id', 'subject', 'object', 'relation', 'state']
        
        df = pd.read_csv('data/Rail/raw/railway_hetero.csv', sep=',', names=cols, encoding='utf-8')

        
        noun_keys = ['person', 'bicycle', 'car', 'train', 'small-animal', 'big-animal', 'rock', 'railroad', 'gravel', 'column', 'fence', 'tree']
        noun_map = {noun: i for i, noun in enumerate(noun_keys)}

        relation_dict = {'on': 0, 'beside': 1, 'over': 2, 'stand_on': 3, 'cross': 4, 'hold': 5, 'in-front-of': 6, 'away': 7, 'walking-on':8 }
        df['relation'] = df['relation'].map(relation_dict)
        
        df['subject'] = df['subject'].map(noun_map)
        df['object'] = df['object'].map(noun_map)
        
        grouped = df.groupby('graph_id')
        
        all_data = []
        
        for graph_id, group in grouped:
            data = HeteroData()

            num_entries = {}
            for name in ['subject','object']:
                value, group[name] = np.unique(group[[name]].values, return_inverse=True)
                num_entries[name] = value.shape[0]

            data['subject'].num_nodes = num_entries['subject']
            data['object'].num_nodes = num_entries['object']

            row = torch.from_numpy(group['subject'].values)
            col = torch.from_numpy(group['object'].values)
            data['subject', 'object'].edge_index = torch.stack([row, col], dim=0)
            relation = torch.from_numpy(group['relation'].values)
            data['subject', 'object'].relation = relation

            data['graph_state'] = torch.tensor([group['state'].iloc[0]])

            print(data)

            all_data.append(data)

        all_data = [data if self.pre_transform is None else self.pre_transform(data) for data in all_data]

        self.save(all_data, self.processed_paths[0])`

all the data that printed:

HeteroData(
  graph_state=[1],
  subject={ num_nodes=1 },
  object={ num_nodes=3 },
  (subject, to, object)={
    edge_index=[2, 3],
    relation=[3],
  }
)
HeteroData(
  graph_state=[1],
  subject={ num_nodes=2 },
  object={ num_nodes=2 },
  (subject, to, object)={
    edge_index=[2, 3],
    relation=[3],
  }
)
HeteroData(
  graph_state=[1],
  subject={ num_nodes=2 },
  object={ num_nodes=2 },
  (subject, to, object)={
    edge_index=[2, 5],
    relation=[5],
  }
)
HeteroData(
  graph_state=[1],
  subject={ num_nodes=2 },
  object={ num_nodes=2 },
  (subject, to, object)={
    edge_index=[2, 2],
    relation=[2],
  }
)
HeteroData(
  graph_state=[1],
  subject={ num_nodes=2 },
  object={ num_nodes=2 },
  (subject, to, object)={
    edge_index=[2, 3],
    relation=[3],
  }
)
HeteroData(
  graph_state=[1],
  subject={ num_nodes=1 },
  object={ num_nodes=3 },
  (subject, to, object)={
    edge_index=[2, 4],
    relation=[4],
  }
)
HeteroData(
  graph_state=[1],
  subject={ num_nodes=2 },
  object={ num_nodes=2 },
  (subject, to, object)={
    edge_index=[2, 3],
    relation=[3],
  }
)
HeteroData(
  graph_state=[1],
  subject={ num_nodes=2 },
  object={ num_nodes=2 },
  (subject, to, object)={
    edge_index=[2, 6],
    relation=[6],
  }
)
HeteroData(
  graph_state=[1],
  subject={ num_nodes=1 },
  object={ num_nodes=2 },
  (subject, to, object)={
    edge_index=[2, 3],
    relation=[3],
  }
)
HeteroData(
  graph_state=[1],
  subject={ num_nodes=1 },
  object={ num_nodes=3 },
  (subject, to, object)={
    edge_index=[2, 4],
    relation=[4],
  }
)

Error:

when

dataset = Rail(path) 
print(dataset[0])`

it gives :

`Traceback (most recent call last):
  File "/data/code/pytorch_geometric/examples/hetero/han_rail.py", line 30, in <module>
    print(dataset[0])
  File "/data/code/pytorch_geometric/torch_geometric/data/dataset.py", line 289, in __getitem__
    data = self.get(self.indices()[idx])
  File "/data/code/pytorch_geometric/torch_geometric/data/in_memory_dataset.py", line 111, in get
    data = separate(
  File "/data/code/pytorch_geometric/torch_geometric/data/separate.py", line 37, in separate
    attrs = slice_dict[key].keys()
KeyError: 'subject'`

I print slice_dict and got: {'graph_state': tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), ('subject', 'to', 'object'): {'edge_index': tensor([ 0, 3, 6, 11, 13, 16, 20, 23, 29, 32, 36]), 'relation': tensor([ 0, 3, 6, 11, 13, 16, 20, 23, 29, 32, 36])}} found the 'subject' and 'object' does not exist, which was weird cause they do exist when I create the Rail dataset

Versions

Collecting environment information...
PyTorch version: 2.3.1+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.8.19 (default, Mar 20 2024, 19:58:24)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.5.0-41-generic-x86_64-with-glibc2.17
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA GeForce RTX 4090
GPU 1: NVIDIA GeForce RTX 4090

Nvidia driver version: 535.183.01
cuDNN version: Probably one of the following:
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn.so.8.9.1
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8.9.1
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.9.1
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8.9.1
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8.9.1
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8.9.1
/usr/local/cuda-11.8/targets/x86_64-linux/lib/libcudnn_ops_train.so.8.9.1
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
架构:                              x86_64
CPU 运行模式:                      32-bit, 64-bit
Address sizes:                      52 bits physical, 57 bits virtual
字节序:                            Little Endian
CPU:                                32
在线 CPU 列表:                     0-31
厂商 ID:                           GenuineIntel
型号名称:                          Intel(R) Xeon(R) w5-3435X
CPU 系列:                          6
型号:                              143
每个核的线程数:                    2
每个座的核数:                      16
座:                                1
步进:                              8
CPU 最大 MHz:                      4700.0000
CPU 最小 MHz:                      800.0000
BogoMIPS:                          6192.00
标记:                              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 tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req vnmi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities
虚拟化:                            VT-x
L1d 缓存:                          768 KiB (16 instances)
L1i 缓存:                          512 KiB (16 instances)
L2 缓存:                           32 MiB (16 instances)
L3 缓存:                           45 MiB (1 instance)
NUMA 节点:                         1
NUMA 节点0 CPU:                    0-31
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:             Not affected
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl
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 BHI_DIS_S
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] numpy==1.24.1
[pip3] torch==2.3.1+cu118
[pip3] torch_cluster==1.6.3+pt23cu118
[pip3] torch-geometric==2.6.0
[pip3] torch_scatter==2.1.2+pt23cu118
[pip3] torch_sparse==0.6.18+pt23cu118
[pip3] torch_spline_conv==1.2.2+pt23cu118
[pip3] torchaudio==2.3.1+cu118
[pip3] torchvision==0.18.1+cu118
[pip3] triton==2.3.1
[conda] numpy                     1.24.1                   pypi_0    pypi
[conda] torch                     2.3.1+cu118              pypi_0    pypi
[conda] torch-cluster             1.6.3+pt23cu118          pypi_0    pypi
[conda] torch-geometric           2.6.0                    pypi_0    pypi
[conda] torch-scatter             2.1.2+pt23cu118          pypi_0    pypi
[conda] torch-sparse              0.6.18+pt23cu118          pypi_0    pypi
[conda] torch-spline-conv         1.2.2+pt23cu118          pypi_0    pypi
[conda] torchaudio                2.3.1+cu118              pypi_0    pypi
[conda] torchvision               0.18.1+cu118             pypi_0    pypi
[conda] triton                    2.3.1                    pypi_0    pypi

baidingyuan avatar Jul 24 '24 03:07 baidingyuan