ngoctnq commited on
Commit
7f61496
·
verified ·
1 Parent(s): d70267d

Dataset card and loading code

Browse files
Files changed (2) hide show
  1. README.md +110 -0
  2. mntf.py +351 -0
README.md CHANGED
@@ -1,3 +1,113 @@
1
  ---
 
 
2
  license: cc-by-4.0
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ # For reference on dataset card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/datasetcard.md?plain=1
3
+ # Doc / guide: https://huggingface.co/docs/hub/datasets-cards
4
  license: cc-by-4.0
5
+ viewer: false
6
+ tags:
7
+ - security
8
+ - malware-detection
9
+ - android
10
+ - graph-machine-learning
11
+ - distribution-shift
12
+ - function-call-graph
13
  ---
14
+
15
+ # Dataset Card for MalNet-Tiny Distribution Shift Benchmarks
16
+
17
+ This dataset contains three datasets, **MalNet-Tiny**, **MalNet-Tiny-Common** and **MalNet-Tiny-Distinct**, designed to evaluate the robustness of graph-based Android malware classifiers under distribution shift. Derived from the [MalNet-Tiny](https://malnet.cs.gatech.edu/) dataset, these benchmarks introduce specific partitions to simulate realistic covariate shift (intra-family) and domain (cross-family) shifts by enriching Function Call Graphs (FCGs) with semantic function metadata and LLM-based code embeddings.
18
+
19
+ ## Dataset Details
20
+
21
+ ### Dataset Description
22
+
23
+ The dataset consists of Android Function Call Graphs (FCGs) where nodes represent functions and edges represent invocations. Unlike the original MalNet-Tiny, which relies on structure-only representations, this dataset enriches the graphs with:
24
+ 1. **Function Metadata:** Lightweight features such as function names, method signatures, and access flags.
25
+ 2. **LLM Embeddings:** Dense semantic representations of function bodies derived from Large Language Models (LLMs), extracted when source code is available.
26
+
27
+ The available datasets are defined as follows:
28
+ * **MalNet-Tiny:** The original MalNet-Tiny dataset with semantic features for nodes in the FCGs.
29
+ * **MalNet-Tiny-Common:** Evaluates generalization of the model under covariate shift.
30
+ * **MalNet-Tiny-Distinct:** Evaluates generalization of the model under domain shift.
31
+
32
+ ### Dataset Specification
33
+ - **License:** Creative Commons Attribution 4.0 International (CC-BY 4.0)
34
+
35
+ ## Uses
36
+
37
+ ### Direct Use
38
+
39
+ * **Robust Malware Detection:** Developing and benchmarking Graph Neural Networks (GNNs) that are resilient to evolving malware variants.
40
+ * **Distribution Shift Evaluation:** Testing model performance under covariate shift (Common) and domain shift (Distinct).
41
+ * **Graph Representation Learning:** Studying the integration of structural (graph) and semantic (LLM/Metadata) features in learning tasks.
42
+
43
+ ### Out-of-Scope Use
44
+
45
+ * This dataset is intended for research purposes (defense) and should not be used to generate or obfuscate malware.
46
+ * The semantic features rely on static analysis; dynamic execution traces are not included.
47
+
48
+ ## Dataset Structure
49
+
50
+ To improve usability, we have reworked the precomputed data structure such that there are no duplicate weights across the files, broken down large files into smaller ones for easy storage, and improved code to not unnecessarily allocate memory during the data loading process. Meanwhile, we retain the user's ability to download specific files needed for any requested split. The dataloading code is provided in `mntf.py` within this repository, with example usage:
51
+
52
+ ```python
53
+ from mntf import MNTF
54
+ from torch_geometric.loader import DataLoader
55
+ from torch_geometric.transforms import LocalDegreeProfile
56
+
57
+ dataset = MNTF(
58
+ collator="zero", ablation="all", variant="tiny", llm_name="cxe",
59
+ remove_isolated=True, transform=LocalDegreeProfile()
60
+ )
61
+ trainloader = DataLoader(
62
+ dataset[dataset.splits["train"]], batch_size=32, shuffle=True
63
+ )
64
+ ```
65
+
66
+ The code has been upgraded to work with the newer PyTorch Geometric 2.3+, whereas the original code extending from Exphormer used the now-defunct PyG 2.0.4. While we strongly recommend installing PyG 2.3+ for seamless installation (as it removes various hard component requirements such as `torch_scatter`) and set our minimum requirement as such, this code can be minimally adjusted to work with earlier versions. Another requirement is `safetensors` for loading graph features, replacing `.pt` checkpoints that requires `torch.load(weights_only=False)` in newer versions of PyTorch; and its default `mmap` backend eliminates the need to allocate each sub-tensor twice during concatenation.
67
+
68
+ Additionally, `huggingface_hub` is an optional dependency, which automatically downloads the required files to load the dataset. If not installed, these files need to be manually downloaded before dataset creation.
69
+
70
+ ## Dataset Creation
71
+
72
+ ### Curation Rationale
73
+
74
+ Existing graph-based classifiers achieve high accuracy on standard benchmarks (like MalNet-Tiny) but suffer noticeable performance drops on unseen families. These benchmarks were created to rigorously evaluate and improve the generalization capabilities of malware detectors in realistic, evolving threat environments.
75
+
76
+ ### Source Data
77
+
78
+ The data are processed from raw APK files from [AndroZoo](https://androzoo.uni.lu/), a repository of real-world Android packages.
79
+ Labels are derived from [MalNet](https://malnet.cs.gatech.edu/), a large-scale dataset containing Android Function Call Graphs and their malware classifications.
80
+
81
+ #### Data Collection and Processing
82
+
83
+ 1. **Base Data:** Samples and labels were selected from MalNet, then corresponding raw APK were downloaded from AndroZoo.
84
+ * *MalNet-Tiny:* The split from the original MalNet.
85
+ * *MalNet-Tiny-Common:* Samples from **same** malware *families* but different malware *types*.
86
+ * *MalNet-Tiny-Distinct:* Samples from **completely unseen** families of malwares.
87
+ 2. **Feature Extraction:**
88
+ * *Metadata Extraction:* Function names, signatures, and flags were extracted to provide lightweight semantic context.
89
+ * *LLM Embedding:* Source code (decompiled Smali/Java) of function bodies was processed using Large Language Models to generate dense code embeddings.
90
+
91
+ Accompanied code on dataset construction can be found at [this project page](https://ngoc.io/malnet-features).
92
+
93
+ ## Bias, Risks, and Limitations
94
+
95
+ * **Static Analysis Limitations:** The graphs are based on static analysis and may be vulnerable to obfuscation techniques that alter call graphs (e.g., reflection, dynamic loading) without changing behavior.
96
+ * **Feature Availability:** LLM embeddings depend on the successful decompilation and availability of function bodies.
97
+
98
+ ### Recommendations
99
+
100
+ Users should be made aware of the risks, biases, and limitations of the dataset. Models trained on this dataset should be evaluated in conjunction with dynamic analysis methods for deployment in critical security environments.
101
+
102
+ ## Citation
103
+ ```latex
104
+ @misc{tran2026evaluating,
105
+ title={Evaluating Out-of-Distribution Robustness in Graph-Based Android Malware Classification: A New Principled Benchmark},
106
+ author={Ngoc N. Tran and Anwar Said and Waseem Abbas and Tyler Derr and Xenofon D. Koutsoukos},
107
+ year={2026},
108
+ eprint={2508.06734},
109
+ archivePrefix={arXiv},
110
+ primaryClass={cs.CR},
111
+ url={https://arxiv.org/abs/2508.06734},
112
+ }
113
+ ```
mntf.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Callable, Dict, List, Optional
6
+
7
+ import safetensors.torch as st
8
+ import torch
9
+ from torch_geometric.data import Data, InMemoryDataset
10
+
11
+ shard_counts = {
12
+ 'tiny': {'cxe': 3, 'qwen': 1, 'rest': 1, 'trim': 1, 'unix': 1},
13
+ 'common': {'cxe': 4, 'qwen': 2, 'rest': 2, 'trim': 1, 'unix': 2},
14
+ 'distinct': {'cxe': 5, 'qwen': 2, 'rest': 2, 'trim': 1, 'unix': 2},
15
+ }
16
+
17
+ try:
18
+ import huggingface_hub as hf
19
+ except ImportError:
20
+ hf = None
21
+ repo_id = "ngoctnq/malnet-features"
22
+
23
+
24
+ def _llc_bytes(default=32 << 20):
25
+ """
26
+ Size of the last-level cache visible to cpu0 in bytes, capped at L3.
27
+ Defaults to 32Mb if the information is not available.
28
+ Used for determining the optimal chunk size for loading large feature
29
+ matrices in the MNTF dataset.
30
+ """
31
+ best = (0, default)
32
+ for d in glob.glob('/sys/devices/system/cpu/cpu0/cache/index*'):
33
+ try:
34
+ with open(os.path.join(d, 'level')) as f: level = int(f.read())
35
+ with open(os.path.join(d, 'type')) as f: kind = f.read().strip()
36
+ with open(os.path.join(d, 'size')) as f: s = f.read().strip()
37
+ except OSError:
38
+ continue
39
+ if kind not in ('Unified', 'Data') or level > 3:
40
+ continue # skip L1i, and memory-side L4
41
+ mult = {'K': 1 << 10, 'M': 1 << 20, 'G': 1 << 30}.get(s[-1:], 1)
42
+ nbytes = int(s[:-1] if mult > 1 else s) * mult
43
+ if level > best[0]:
44
+ best = (level, nbytes)
45
+ return best[1]
46
+
47
+
48
+ class MNTF(InMemoryDataset):
49
+ """
50
+ A custom dataset class for the MNTF dataset.
51
+ The splits are stored in a `splits` field, containing a dictionary
52
+ with keys "train", "valid", and "test", each mapping to a list of
53
+ indices for the corresponding split.
54
+
55
+ Example usage:
56
+ ```python
57
+ from torch_geometric.loader import DataLoader
58
+ from torch_geometric.transforms import LocalDegreeProfile
59
+
60
+ dataset = MNTF(
61
+ collator="zero", ablation="all", variant="tiny", llm_name="cxe",
62
+ remove_isolated=True, transform=LocalDegreeProfile()
63
+ )
64
+ trainloader = DataLoader(
65
+ dataset[dataset.splits["train"]], batch_size=32, shuffle=True
66
+ )
67
+ ```
68
+
69
+ Args:
70
+ collator (str): The collator type to use for processing the dataset.
71
+ Valid options are "trim", "prune", "zero", or "none".
72
+ ablation (str): The ablation type to use for processing the dataset.
73
+ Valid options are "base", "llm", or "all".
74
+ variant (str): The variant of the dataset to use.
75
+ Valid options are "tiny", "common", or "distinct".
76
+ llm_name (str, optional): The name of the LLM to use for processing the dataset.
77
+ Valid options are None, "unix", "qwen", or "cxe". Default is None.
78
+ root (str, optional): The root directory where the dataset is stored.
79
+ Default is './data/mntf' if `huggingface_hub` is not installed;
80
+ otherwise None uses the default HuggingFace cache directory.
81
+ remove_isolated (bool, optional): Whether to remove isolated nodes from the dataset.
82
+ Default is True.
83
+ transform (callable, optional): An optional transform function to apply to the dataset,
84
+ passed directly to the parent class' constructor. Default is None.
85
+ """
86
+ def __init__(
87
+ self,
88
+ collator: str,
89
+ ablation: str,
90
+ variant: str = "tiny",
91
+ llm_name: Optional[str] = None,
92
+ root: Optional[str] = None,
93
+ remove_isolated: bool = True,
94
+ transform: Optional[Callable] = None,
95
+ ):
96
+ self._validate_parameters(variant, collator, ablation, llm_name, remove_isolated)
97
+
98
+ # field assignment needs to come before super() to make processed_dir work
99
+ self.collator = collator
100
+ self.ablation = ablation
101
+ self.remove_isolated = remove_isolated
102
+ self.variant = variant
103
+ self.llm_name = llm_name
104
+
105
+ # for resolving real file directories when using hf_hub_download
106
+ self._resolved: Dict[str, str] = {}
107
+
108
+ if root is None and hf is None:
109
+ root = './data/mntf'
110
+
111
+ super().__init__(root, transform, pre_transform=None, pre_filter=None)
112
+ # override the default root set by super().__init__() to avoid creating a local '???' folder
113
+ if root is None:
114
+ self.root = None
115
+
116
+ base_data = st.load_file(self.processed_paths[0])
117
+ self._data = Data(**{k[len('data.'):]: v for k, v in base_data.items() if k.startswith('data.')})
118
+ # clone() to make sure future writes succeed, since the underlying storage is read-only
119
+ self.slices = {k[len('slices.'):]: v.clone() for k, v in base_data.items() if k.startswith('slices.')}
120
+ with open(self.processed_paths[-1]) as f:
121
+ self.splits = json.load(f)
122
+
123
+ node_mask = None
124
+ if remove_isolated:
125
+ node_mask = self.remove_isolated_nodes()
126
+ self.populate_features(connected_node_mask=node_mask)
127
+
128
+
129
+ @classmethod
130
+ def _validate_parameters(cls, variant, collator, ablation, llm_name, remove_isolated):
131
+ # validate inputs
132
+ assert variant in ('tiny', 'common', 'distinct'), f"Invalid variant: {variant}"
133
+ assert collator in ('trim', 'prune', 'zero', 'none'), f"Invalid collator: {collator}"
134
+ assert ablation in ('base', 'llm', 'all'), f"Invalid ablation: {ablation}"
135
+ assert llm_name is None or llm_name in ('cxe', 'qwen', 'unix'), f"Invalid llm_name: {llm_name}"
136
+ assert (ablation == 'base') ^ (llm_name is not None), f"Invalid combination: {ablation=} and {llm_name=}"
137
+ assert collator != 'trim' or ablation == 'base', "Cannot use trim with LLM features"
138
+ assert collator != 'prune' or not remove_isolated, "Cannot use prune with remove_isolated=True"
139
+
140
+
141
+ def populate_features(self, connected_node_mask: Optional[torch.Tensor] = None):
142
+ """ Note that all assignments have to be done in store! """
143
+ if connected_node_mask is not None:
144
+ assert connected_node_mask.shape[0] == self.x.shape[0], \
145
+ f"connected_node_mask shape {connected_node_mask.shape} does not match x shape {self.x.shape}"
146
+ # silence the linter
147
+ assert self._data is not None, "No base dataset loaded"
148
+
149
+ universal_node_mask = self.x.bool().squeeze()
150
+ # use mmap to avoid loading all features into memory at once (default safetensors)
151
+ # safetensors 0.8.0 introduced pread, which blows up AnonRSS -- if in
152
+ # the future the default changes, add an explicit backend='mmap' here.
153
+ # It's omitted now for backwards compatibility.
154
+ feature_tensors = [st.load_file(p)[Path(p).stem] for p in self.processed_paths[1:-1]]
155
+ feature_counts = [x.shape[1] for x in feature_tensors]
156
+ feature_count_cumsum = torch.cumsum(torch.tensor([0] + feature_counts), dim=0).tolist()
157
+
158
+ if self.collator == 'prune':
159
+ self.select_edges_from_node_mask(universal_node_mask)
160
+ assert connected_node_mask is None, "Cannot use prune with remove_isolated=True"
161
+ node_mask = universal_node_mask
162
+ else:
163
+ node_mask = connected_node_mask
164
+
165
+ num_nodes = self.x.shape[0]
166
+ new_num_nodes = num_nodes if node_mask is None else node_mask.sum().item()
167
+ assert isinstance(new_num_nodes, int) and new_num_nodes > 0, "No nodes in Storage, cannot assign features"
168
+
169
+ # create storage for x and populate with truncated features
170
+ self._data.stores[0].x = torch.zeros(
171
+ (new_num_nodes, feature_count_cumsum[-1]),
172
+ dtype=torch.float,
173
+ device=self.x.device,
174
+ )
175
+
176
+ for subfeature_idx, subfeature_matrix in enumerate(feature_tensors):
177
+ if subfeature_matrix.shape[1] == 0:
178
+ continue
179
+
180
+ # feature sets: trim, rest, llm
181
+ # node_mask: connected_node_mask [+ universal_node_mask], always on x_base
182
+ # universal_node_mask: which of x_base correspond to the current subfeature_matrix
183
+
184
+ # get a slice view of the destination subtensor
185
+ dest_tensor = self._data.stores[0].x[:, feature_count_cumsum[subfeature_idx]:feature_count_cumsum[subfeature_idx+1]]
186
+
187
+ # simple x_trim case
188
+ if subfeature_matrix.shape[0] == num_nodes:
189
+ if num_nodes == new_num_nodes:
190
+ # no nodes were removed, so we can just copy the entire subfeature_matrix
191
+ dest_tensor.copy_(subfeature_matrix)
192
+ else:
193
+ # if x_trim and mismatch dimension, connected_node_mask must have been provided
194
+ subfeature_idxs = torch.arange(num_nodes, device=self.x.device)[node_mask]
195
+ assert subfeature_idxs.numel() == new_num_nodes, \
196
+ f"subfeature_idxs count {subfeature_idxs.numel()} != {new_num_nodes} rows; index_select would resize the view"
197
+ # equivalent to: dst.copy_(src[mask])
198
+ torch.index_select(subfeature_matrix, 0, subfeature_idxs, out=dest_tensor)
199
+
200
+ # simple remove_isolated=False case, x_rest/x_llm only
201
+ elif connected_node_mask is None:
202
+ # prune + x_rest/x_llm
203
+ if dest_tensor.shape[0] == subfeature_matrix.shape[0]:
204
+ dest_tensor.copy_(subfeature_matrix)
205
+ # zero + x_rest/x_llm
206
+ else:
207
+ dest_tensor_idxs = torch.arange(num_nodes, device=self.x.device)[universal_node_mask]
208
+ # equivalent to: dst[mask].copy_(src)
209
+ dest_tensor.index_copy_(0, dest_tensor_idxs, subfeature_matrix)
210
+
211
+ # remove_isolated=True + x_rest/x_llm -> zero
212
+ else:
213
+ # remove_isolated=True implies not prune, thus node_mask = connected_node_mask
214
+ assert node_mask is not None, "sanity check: connected_node_mask is not None but node_mask is None"
215
+ subfeature_idxs = torch.arange(subfeature_matrix.shape[0], device=self.x.device)[node_mask[universal_node_mask]]
216
+ dest_tensor_idxs = torch.arange(new_num_nodes, device=self.x.device)[universal_node_mask[node_mask]]
217
+ # true by construction but doesn't hurt to check
218
+ assert subfeature_idxs.numel() == dest_tensor_idxs.numel(), \
219
+ f"subfeature_idxs count {subfeature_idxs.numel()} != dest_tensor_idxs count {dest_tensor_idxs.numel()}"
220
+ # quick check happy path shortcuts
221
+ if dest_tensor_idxs.numel() == new_num_nodes:
222
+ if new_num_nodes == subfeature_matrix.shape[0]:
223
+ # no nodes were removed, so we can just copy the entire subfeature_matrix
224
+ dest_tensor.copy_(subfeature_matrix)
225
+ else:
226
+ # equivalent to: dst.copy_(src[mask])
227
+ torch.index_select(subfeature_matrix, 0, subfeature_idxs, out=dest_tensor)
228
+ elif subfeature_idxs.numel() == subfeature_matrix.shape[0]:
229
+ # equivalent to: dst[mask].copy_(src)
230
+ dest_tensor.index_copy_(0, dest_tensor_idxs, subfeature_matrix)
231
+ else:
232
+ # chunking is faster than contiguous-block reads, since the overhead is dominated by PyTorch calls
233
+ chunk_size = max(1, _llc_bytes() // (subfeature_matrix.shape[1] * subfeature_matrix.element_size()))
234
+ for i in range(0, dest_tensor_idxs.numel(), chunk_size):
235
+ chunk_dest_idxs = dest_tensor_idxs[i : i + chunk_size]
236
+ chunk_subfeature_idxs = subfeature_idxs[i : i + chunk_size]
237
+ dest_tensor.index_copy_(0, chunk_dest_idxs, subfeature_matrix[chunk_subfeature_idxs])
238
+
239
+
240
+ def remove_isolated_nodes(self):
241
+ '''
242
+ Note: This function does not actually remove the isolated nodes from
243
+ the dataset, but _do_ remove the corresponding edges. Returns a boolean
244
+ mask indicating which nodes are _not_ isolated for later compaction.
245
+ '''
246
+ # silence the linter
247
+ assert self.slices is not None, "No dataset slices loaded"
248
+ assert self._data is not None, "No base dataset loaded"
249
+
250
+ # edge_index is local, lift to global to correctly identify non-isolated nodes
251
+ edge_counts = self.slices['edge_index'][1:] - self.slices['edge_index'][:-1]
252
+ per_edge_offset = torch.repeat_interleave(self.slices['x'][:-1], edge_counts)
253
+ global_ei = self._data.edge_index + per_edge_offset.unsqueeze(0)
254
+
255
+ mask = torch.zeros(self.x.shape[0], dtype=torch.bool, device=self.x.device)
256
+ not_self_loop = global_ei[0] != global_ei[1]
257
+ mask[global_ei[:, not_self_loop].view(-1)] = True
258
+ self.select_edges_from_node_mask(mask)
259
+
260
+ # return mask to defer tensor compaction
261
+ return mask
262
+
263
+
264
+ def select_edges_from_node_mask(self, node_mask: torch.Tensor):
265
+ # silence the linter
266
+ assert self.slices is not None, "No dataset slices loaded"
267
+ assert self._data is not None, "No base dataset loaded"
268
+
269
+ # edge_index is local, lift to global to correctly identify non-isolated nodes
270
+ edge_counts = self.slices['edge_index'][1:] - self.slices['edge_index'][:-1]
271
+ per_edge_offset = torch.repeat_interleave(self.slices['x'][:-1], edge_counts)
272
+ global_ei = self._data.edge_index + per_edge_offset.unsqueeze(0)
273
+
274
+ node_map = torch.full((self.x.shape[0],), -1, dtype=torch.long, device=node_mask.device)
275
+ node_map[node_mask] = torch.arange(node_mask.sum().item(), device=node_mask.device)
276
+ valid_edges = node_mask[global_ei[0]] & node_mask[global_ei[1]]
277
+ new_global_ei = node_map[global_ei[:, valid_edges]]
278
+
279
+ # defer to later to prevent unnecessary copies of x
280
+ # self._data.stores[0].x = self.x[node_mask]
281
+
282
+ # rebuild slices
283
+ x_slice_cumsum = torch.cumsum(node_mask, dim=0)
284
+ self.slices['x'][1:] = x_slice_cumsum[self.slices['x'][1:] - 1]
285
+
286
+ edge_slice_cumsum = torch.cumsum(valid_edges, dim=0)
287
+ self.slices['edge_index'][1:] = edge_slice_cumsum[self.slices['edge_index'][1:] - 1]
288
+
289
+ # convert back to local using updated slices
290
+ new_edge_counts = self.slices['edge_index'][1:] - self.slices['edge_index'][:-1]
291
+ new_per_edge_offset = torch.repeat_interleave(self.slices['x'][:-1], new_edge_counts)
292
+ self._data.stores[0].edge_index = new_global_ei - new_per_edge_offset.unsqueeze(0)
293
+
294
+
295
+ @property
296
+ def processed_file_names(self) -> List[str]:
297
+ components = ['base.safetensors']
298
+
299
+ def add_component(name: str):
300
+ # handle adding sharded components based on shard_counts
301
+ shard_count = shard_counts.get(self.variant, {}).get(name)
302
+ if shard_count is None or shard_count == 1:
303
+ components.append(f'x_{name}.safetensors')
304
+ else:
305
+ for i in range(shard_count):
306
+ components.append(f'x_{name}_{i}.safetensors')
307
+
308
+ if self.collator != 'none':
309
+ if self.ablation != 'llm':
310
+ add_component('trim')
311
+ if self.collator != 'trim':
312
+ add_component('rest')
313
+ if self.ablation != 'base':
314
+ assert self.llm_name is not None, "llm_name must be specified for LLM ablation"
315
+ add_component(self.llm_name)
316
+
317
+ return components + ["splits.json"]
318
+
319
+
320
+ @property
321
+ def processed_paths(self) -> List[str]:
322
+ files = self.processed_file_names
323
+ try:
324
+ return [self._resolve(f) for f in files]
325
+ except Exception:
326
+ print(
327
+ "[!] An error occurred while trying to load this dataset. "
328
+ f"Manually download the following files: {files} "
329
+ f"from https://huggingface.co/datasets/{repo_id}/{self.variant}"
330
+ + (f" into {self.root}/{self.variant}." if self.root is not None else ".")
331
+ )
332
+ raise
333
+
334
+
335
+ def _resolve(self, name: str) -> str:
336
+ if name in self._resolved:
337
+ return self._resolved[name]
338
+
339
+ if self.root is not None:
340
+ resolved_path = Path(self.root) / self.variant / name
341
+ if resolved_path.exists():
342
+ self._resolved[name] = str(resolved_path)
343
+ return self._resolved[name]
344
+
345
+ # Download the required files
346
+ if hf is None:
347
+ raise RuntimeError("Dataset not found and huggingface_hub is not installed.")
348
+ resolved = hf.hf_hub_download(repo_id, f'{self.variant}/{name}', repo_type="dataset", local_dir=self.root)
349
+ self._resolved[name] = resolved
350
+ return resolved
351
+