Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

my own dataset using LinkNeighborLoader #9914

Open
ZJL0111 opened this issue Jan 3, 2025 · 0 comments
Open

my own dataset using LinkNeighborLoader #9914

ZJL0111 opened this issue Jan 3, 2025 · 0 comments
Labels

Comments

@ZJL0111
Copy link

ZJL0111 commented Jan 3, 2025

🐛 Describe the bug

i want to train a HGT model on my own biomedical KG dataset, i load my data from csv

from torch_geometric.data import HeteroData
from torch_geometric.transforms import RandomLinkSplit
from torch_geometric.loader import NeighborLoader
import pandas as pd
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch_geometric.loader import LinkNeighborLoader

# todo: 加载数据
# 读取TSV文件
edges_df = pd.read_csv('../train_data/TarKG_edges_filter.csv', sep=',', header=None,
                       names=['index', 'node1', 'node1_type', 'relation', 'node2', 'node2_type'])
edges_df = edges_df[1:50000]
# edges_df = edges_df[1:]

print(edges_df)
# 创建HeteroData对象
data = HeteroData()
# 获取所有节点类型
node_types = set(edges_df['node1_type']).union(set(edges_df['node2_type']))
# 为每种节点类型添加节点
# 创建节点ID到索引的映射
node_id_to_index = {}
index_counter = 0
# todo:获取所有节点ID
all_node_ids = pd.concat([edges_df['node1'], edges_df['node2']]).unique()
# 创建节点ID到索引的映射
for node_id in all_node_ids:
    if node_id not in node_id_to_index:
        node_id_to_index[node_id] = index_counter
        index_counter += 1
# print("node_id_to_index", node_id_to_index)
# node_id_to_index {'DOID:0001816': 0, 'DOID:0080189': 1, 'DOID:3316': 2,

# todo:为每种节点类型添加节点
for node_type in node_types:
    node1_ids = pd.Series(edges_df[edges_df['node1_type'] == node_type]['node1'].unique())
    node2_ids = pd.Series(edges_df[edges_df['node2_type'] == node_type]['node2'].unique())
    node_ids = pd.concat([node1_ids, node2_ids]).unique()
    data[node_type].node_id = torch.tensor([node_id_to_index[node_id] for node_id in node_ids])
    # print("check:", len([node_id_to_index[node_id] for node_id in node_ids]), [node_id_to_index[node_id] for node_id in node_ids])
    data[node_type].x = torch.randn(len(node_ids), 200)
    data[node_type].num_nodes = len(node_ids)
# print("data", data)

# 添加边
for relation in edges_df['relation'].unique():
    sub_df = edges_df[edges_df['relation'] == relation]
    edge_index = torch.tensor([
        [node_id_to_index[node_id] for node_id in sub_df['node1']],
        [node_id_to_index[node_id] for node_id in sub_df['node2']]
    ])
    data[sub_df['node1_type'].iloc[0], relation, sub_df['node2_type'].iloc[0]].edge_index = edge_index

# print("data", data)
print("data.edge_types", data.edge_types)
data.edge_types [('Disease', 'is a', 'Disease'), ('Disease', 'resembles', 'Disease'), ('Compound', 'treats', 'Disease'), ('Compound', 'side effect', 'Disease'), ('Compound', 'associated with', 'Disease'), ('Gene', 'biomarkers', 'Disease'), ('Compound', 'indication', 'Disease'), ('Gene', 'role in pathogenesis, or promotes progression', 'Disease'), ('Gene', 'mutations affect, or polymorphisms alter risk', 'Disease'), ('Gene', 'improper regulation linked to disease', 'Disease'), ('Gene', 'causal mutations', 'Disease'), ('Compound', 'role in pathogenesis', 'Disease'), ('Compound', 'inhibits cell growth', 'Disease'), ('Compound', 'alleviates', 'Disease'), ('Disease', 'ancestors', 'Disease'), ('Gene', 'drug targets', 'Disease'), ('Gene', 'polymorphisms alter risk', 'Disease'), ('Gene', 'promotes progression', 'Disease'), ('Gene', 'overexpression', 'Disease'), ('Disease', 'stimulates', 'Gene'), ('Disease', 'inhibits', 'Gene'), ('Gene', 'catalysis', 'Gene'), ('Gene', 'ubiquitination', 'Gene'), ('Gene', 'negative correlate', 'Gene'), ('Gene', 'other', 'Gene'), ('Gene', 'positive correlate', 'Gene'), ('Gene', 'regulates', 'Gene'), ('Gene', 'ppi', 'Gene'), ('Gene', 'activates', 'Gene'), ('Gene', 'binds', 'Gene'), ('Gene', 'production by cell population', 'Gene'), ('Gene', 'relationships involving regulation and pathways', 'Gene'), ('Disease', 'upregulates', 'Gene'), ('Gene', 'physical association', 'Gene'), ('Compound', 'downregulates', 'Gene'), ('Compound', 'target', 'Gene'), ('Compound', 'interacts with', 'Gene'), ('Compound', 'transcriptome', 'Gene'), ('Compound', 'metabolism', 'Gene'), ('Compound', 'adme', 'Gene'), ('Compound', 'affects expression', 'Gene'), ('Gene', 'same protein or complex', 'Gene'), ('Gene', 'colocalization', 'Gene'), ('Gene', 'phosphorylation reaction', 'Gene'), ('Gene', 'reaction', 'Gene')]

pre_edge_types = []
for t in data.edge_types:
    if t[0] in ['Disease', 'Gene'] and t[2] in ['Disease', 'Gene'] and t[0]!=t[2]:
        pre_edge_types.append(t)
print("pre_edge_types", pre_edge_types) 
# 需要预测的链接类型
pre_edge_types [('Gene', 'biomarkers', 'Disease'), ('Gene', 'role in pathogenesis, or promotes progression', 'Disease'), ('Gene', 'mutations affect, or polymorphisms alter risk', 'Disease'), ('Gene', 'improper regulation linked to disease', 'Disease'), ('Gene', 'causal mutations', 'Disease'), ('Gene', 'drug targets', 'Disease'), ('Gene', 'polymorphisms alter risk', 'Disease'), ('Gene', 'promotes progression', 'Disease'), ('Gene', 'overexpression', 'Disease'), ('Disease', 'stimulates', 'Gene'), ('Disease', 'inhibits', 'Gene'), ('Disease', 'upregulates', 'Gene')] 

my dataset looks like

HeteroData(
  Disease={
    node_id=[494],
    x=[494, 200],
    num_nodes=494,
  },
  Gene={
    node_id=[734],
    x=[734, 200],
    num_nodes=734,
  },
  Compound={
    node_id=[2110],
    x=[2110, 200],
    num_nodes=2110,
  },
 ......
  (Gene, mutations affect, or polymorphisms alter risk, Disease)={
    edge_index=[2, 40],
    edge_label=[16],
    edge_label_index=[2, 16],
  },
  (Gene, improper regulation linked to disease, Disease)={
    edge_index=[2, 51],
    edge_label=[21],
    edge_label_index=[2, 21],
  },
  (Gene, causal mutations, Disease)={
    edge_index=[2, 4],
    edge_label=[1],
    edge_label_index=[2, 1],
  })

then i split my data using

transform = RandomLinkSplit(num_val=0.05, num_test=0.05,
                            disjoint_train_ratio=0.3, 
                            neg_sampling_ratio=0,
                            is_undirected=False,
                            add_negative_train_samples=False,
                            edge_types=list(data.edge_types)  # 多任务学习可以通过共享参数和信息,提升模型的整体性能
                            )
train_data, val_data, test_data = transform(data)

as my aim is to predict all relation type between 'Gene' and 'Disease' so i prepare my edge_label_index and edge_label by

for e in train_data.edge_types:
   train_neighbors[e] = [10,10]
   # if e[0] in ['Disease', 'Gene'] and e[2] in ['Disease', 'Gene'] and e[0]!=e[2]:
   #     neighbors[e] = [20,20]
   # else:
   #     neighbors[e] = [10,10]
print("neighbors", train_neighbors)


# 如果你要同时预测多种边类型,需要拼接
edge_label_index_list = []
edge_label_list = []
for edge_type in pre_edge_types:
   print("test edge_type", edge_type)
   # 确保数据存在且格式正确
   curr_label_index = train_data[edge_type].edge_label_index
   curr_label = train_data[edge_type].edge_label
   print("edge_type", edge_type)
   print("curr_label_index", curr_label_index.shape, curr_label_index)
   print("curr_label", curr_label.shape, curr_label)
   edge_label_index_list.append(curr_label_index)
   edge_label_list.append(curr_label)

#  安全地拼接张量
if edge_label_index_list and edge_label_list:
   edge_label_index = torch.cat(edge_label_index_list, dim=1)
   edge_label = torch.cat(edge_label_list, dim=0)
else:
   raise ValueError("No valid edge labels found for prediction")
# edge_label_index torch.Size([2, 128]) 
#  edge_label torch.Size([128]) 

then i load my data using

train_loader = LinkNeighborLoader(train_data,
                                  num_neighbors=train_neighbors,
                                  batch_size=8,
                                  edge_label_index= (pre_edge_types, edge_label_index),
                                  edge_label=edge_label,
                                  shuffle=True)

i get warning of the parameter edge_label_index, here my pre_edge_types ia a list, while looks into this function find it requires
(Tensor or EdgeType or Tuple[EdgeType, Tensor]), so i modify my pre_edge_types=[pre_edge_types[1]], to retest my code, i get error

python3: malloc.c:2617: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)

I've been stuck on this for a while. i need help. And for hetero KG data, '''LinkNeighborLoader'''' seem s like does not support multiple edge types

Versions

PyTorch version: 2.4.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

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

Python version: 3.12.7 | packaged by Anaconda, Inc. | (main, Oct  4 2024, 13:27:36) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.5.0-28-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA A800 80GB PCIe
GPU 1: NVIDIA A800 80GB PCIe
GPU 2: NVIDIA A800 80GB PCIe
GPU 3: NVIDIA A800 80GB PCIe
GPU 4: NVIDIA A800 80GB PCIe
GPU 5: NVIDIA A800 80GB PCIe
GPU 6: NVIDIA A800 80GB PCIe
GPU 7: NVIDIA A800 80GB PCIe

Nvidia driver version: 550.54.15
cuDNN version: Could not collect
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
Address sizes:                      52 bits physical, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             384
On-line CPU(s) list:                0-383
Vendor ID:                          AuthenticAMD
Model name:                         AMD EPYC 9654 96-Core Processor
CPU family:                         25
Model:                              17
Thread(s) per core:                 2
Core(s) per socket:                 96
Socket(s):                          2
Stepping:                           1
Frequency boost:                    enabled
CPU max MHz:                        3707.8120
CPU min MHz:                        1500.0000
BogoMIPS:                           4792.47
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 amd_lbr_v2 nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid 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 invpcid_single hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif x2avic v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d
Virtualization:                     AMD-V
L1d cache:                          6 MiB (192 instances)
L1i cache:                          6 MiB (192 instances)
L2 cache:                           192 MiB (192 instances)
L3 cache:                           768 MiB (24 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0-95,192-287
NUMA node1 CPU(s):                  96-191,288-383
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: Mitigation; Safe RET
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, STIBP always-on, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:

[pip3] numpy==1.26.4
[pip3] nvidia-cublas-cu12==12.1.3.1
[pip3] nvidia-cuda-cupti-cu12==12.1.105
[pip3] nvidia-cuda-nvrtc-cu12==12.1.105
[pip3] nvidia-cuda-runtime-cu12==12.1.105
[pip3] nvidia-cudnn-cu12==9.1.0.70
[pip3] nvidia-cufft-cu12==11.0.2.54
[pip3] nvidia-curand-cu12==10.3.2.106
[pip3] nvidia-cusolver-cu12==11.4.5.107
[pip3] nvidia-cusparse-cu12==12.1.0.106
[pip3] nvidia-nccl-cu12==2.20.5
[pip3] nvidia-nvjitlink-cu12==12.4.127
[pip3] nvidia-nvtx-cu12==12.1.105
[pip3] torch==2.4.0
[pip3] torch_cluster==1.6.3+pt24cu124
[pip3] torch-geometric==2.6.1
[pip3] torch_scatter==2.1.2+pt24cu124
[pip3] torch_sparse==0.6.18+pt24cu124
[pip3] torchdata==0.9.0
[pip3] triton==3.0.0
[conda] numpy                     1.26.4                   pypi_0    pypi
[conda] nvidia-cublas-cu12        12.1.3.1                 pypi_0    pypi
[conda] nvidia-cuda-cupti-cu12    12.1.105                 pypi_0    pypi
[conda] nvidia-cuda-nvrtc-cu12    12.1.105                 pypi_0    pypi
[conda] nvidia-cuda-runtime-cu12  12.1.105                 pypi_0    pypi
[conda] nvidia-cudnn-cu12         9.1.0.70                 pypi_0    pypi
[conda] nvidia-cufft-cu12         11.0.2.54                pypi_0    pypi
[conda] nvidia-curand-cu12        10.3.2.106               pypi_0    pypi
[conda] nvidia-cusolver-cu12      11.4.5.107               pypi_0    pypi
[conda] nvidia-cusparse-cu12      12.1.0.106               pypi_0    pypi
[conda] nvidia-nccl-cu12          2.20.5                   pypi_0    pypi
[conda] nvidia-nvjitlink-cu12     12.4.127                 pypi_0    pypi
[conda] nvidia-nvtx-cu12          12.1.105                 pypi_0    pypi
[conda] torch                     2.4.0                    pypi_0    pypi
[conda] torch-cluster             1.6.3+pt24cu124          pypi_0    pypi
[conda] torch-geometric           2.6.1                    pypi_0    pypi
[conda] torch-scatter             2.1.2+pt24cu124          pypi_0    pypi
[conda] torch-sparse              0.6.18+pt24cu124          pypi_0    pypi
[conda] torchdata                 0.9.0                    pypi_0    pypi
[conda] triton                    3.0.0                    pypi_0    pypi
@ZJL0111 ZJL0111 added the bug label Jan 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant