diff --git a/.gitattributes b/.gitattributes index 48e1fe032537c7401a1b7f2740bf08603da43745..a6344aac8c09253b3b630fb776ae94478aa0275b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,4 +33,3 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text -training_time.png filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore index f99b49e07aea8444d8bc57f2e00889b42a756a91..3f992ad4c0a1f5004e4c6b529902b67a7fc3c2c3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,3 @@ __pycache__/ trainings/ scores/ -slurm/ -.onnx -.png diff --git a/README.md b/README.md index e5e004a4ae410d57a4be172387fa1036ff0f142b..7be5fc7f47d5db027d120b8024982df93db95b74 100644 --- a/README.md +++ b/README.md @@ -1,358 +1,3 @@ --- license: mit -tags: -- arXiv:2412.10665 --- - -This is a demo is of the approach described in the paper, ["Pretrained Event Classification Model for High Energy Physics Analysis"](https://arxiv.org/abs/2412.10665) -``` -@misc{ho2024pretrained, - title={Pretrained Event Classification Model for High Energy Physics Analysis}, - author={Joshua Ho, Benjamin Ryan Roberts, Shuo Han, Haichen Wang}, - year={2024}, - eprint={2412.10665}, - archivePrefix={arXiv} -} -``` - -## Abstract - -We introduce a foundation model for event classification in high-energy physics, built on a **Graph Neural Network** architecture and trained on **120 million simulated proton-proton collision events** spanning 12 distinct physics processes. The model is *pretrained* to learn a general and robust representation of collision data using challenging multiclass and multilabel classification tasks. - -Its performance is evaluated across five event classification tasks, which include both physics processes used during pretraining and new processes not encountered during pretraining. Fine-tuning the pretrained model significantly improves classification performance, particularly in scenarios with limited training data, demonstrating gains in both accuracy and computational efficiency. - -To investigate the underlying mechanisms behind these performance improvements, we employ a representational similarity evaluation framework based on *Centered Kernel Alignment*. This analysis reveals notable differences in the learned representations of fine-tuned pretrained models compared to baseline models trained from scratch. - -## Introduction - -Machine learning has become a ubiquitous tool in particle physics, employed in a variety of tasks including triggering, simulation, reconstruction, and offline analysis. While its utility spans classification, regression, and generative tasks, the current paradigm of developing machine learning models from scratch for each specific application presents several challenges. This approach not only demands specialized expertise and substantial computing resources but can also result in suboptimal performance due to limited training data. The from-scratch development of models necessitates individual validation studies to ensure that neural networks utilize well-modeled information from training samples, whether derived from Monte Carlo simulations or control samples from experimental data. - -Foundation models offer a promising direction to address these limitations. These models, pre-trained on large, diverse datasets across various tasks, provide robust and general representations of underlying data structures. Notable examples in other fields include GPT-4 [OpenAI et al., 2024](#ref-openai-2024-gpt4) and BERT [Devlin et al., 2018](#ref-devlin-2018-bert) in natural language processing, Stable Diffusion [Rombach et al., 2021](#ref-rombach-2021-latentdiffusion) in image processing, and AlphaFold [Jumper et al., 2021](#ref-jumper-2021-alphafold) in structural biology. The foundation model approach offers several advantages for particle physics applications: reduced computing resources for fine-tuning [Yosinski et al., 2014](#ref-yosinski-2014-transfer) compared to training from scratch, superior performance on specific tasks (particularly with limited training data), and potentially simplified validation procedures as downstream tasks inherit verified representations from the pre-trained model. - -Current literature on pretrained models for particle physics can be categorized based on the data representation they handle. Models operating on particle- or event-level numerical data use features like particle four momenta or jets, leveraging self-supervised or generative methods to learn versatile representations. Detector-focused models operate on high-dimensional responses such as calorimeter deposits or pixel hits, employing geometry-aware techniques for accurate simulation and analysis. Finally, models using textual or code representations apply large language model architectures to integrate domain knowledge, enabling tasks like question answering and code generation. - -Recent studies have begun exploring foundation models tailored to particle physics data, which has a variety of distinct structures and properties across many experiments and data processing stages, including: - -- particle-level & event-level numeric data [Wildridge et al., 2024](#ref-wildridge-2024-bumblebee), [Katel et al., 2024](#ref-katel-2024-jet), [Golling et al., 2024](#ref-golling-2024-maskedset), [Mikuni & Nachman, 2024](#ref-mikuni-2024-omnilearn), [Harris et al., 2024](#ref-harris-2024-resimulation), [Birk et al., 2024](#ref-birk-2024-omnijet), [Vigl et al., 2024](#ref-vigl-2024-finetune), -- detector-level & geometry-aware data [Araz et al., 2024](#ref-araz-2024-pointcloud), [Liu et al., 2023](#ref-liu-2023-gaam), [Hashemi et al., 2024](#ref-hashemi-2024-gen), [Huang et al., 2024](#ref-huang-2024-lmtracking), -- textual or code data [Zhang et al., 2024](#ref-zhang-2024-xiwu). - -This paper presents a foundation model designed specifically for collider event-level data. In modern collider experiments, final-stage analysis processes information from reconstructed objects that either directly correspond to particles in collision final states (such as leptons and photons) or serve as proxies (such as jets and missing transverse energy). While traditional approaches often relied on "high-level" variables calculated from object features, recent trends favor direct input of event objects and their features into neural networks for analysis tasks. A notable example is [ATLAS Collaboration, 2023](#ref-atlas-2023-4top), which established the observation of simultaneous production of four top quarks with the ATLAS experiment by employing a graph neural network (GNN) architecture to process event-level object information. - -We present foundation models that adopt an architecture similar to that used for [ATLAS Collaboration, 2023](#ref-atlas-2023-4top). Our models are pre-trained using either multiclass classification or multi-label learning tasks across 12 distinct physics processes. We evaluate these models through fine-tuning and testing on five classification tasks, including both familiar and novel processes not seen during pre-training. Our analysis benchmarks the models' performance improvements, their scaling behavior with training sample size, and computational efficiency, representing the first prototype of a foundation model operating on collider final-state object data. - -## Data Samples - -To provide a diverse set of physics processes for the pretraining, we use Madgraph@NLO 2.7.3 [Alwall et al., 2014](#ref-alwall-2014hca) to generate proton-proton collision events at next-to-leading order (NLO) in Quantum Chromodynamics (QCD). We generate 12 distinct Standard Model (SM) physics processes, including six major Higgs boson production mechanisms: gluon fusion production \\(ggF\\), vector boson fusion \\(VBF\\), associated production of the Higgs boson with a W boson \\(WH\\) or a Z boson \\(ZH\\), associated production of the Higgs boson with a top-quark pair \\(t\bar{t}H\\), and associated production of the Higgs boson with a single top quark and a forward quark \\(tHq\\). Additionally, we simulate six top quark production processes: single top production, top-quark pair production \\(t\bar{t}\\), top quark pair production in association with a pair of photons \\(t\bar{t}\gamma\gamma\\), associated production of a top-quark pair with a W boson \\(t\bar{t}W\\), simultaneous production of three top quarks \\(t\bar{t}t\\), and simultaneous production of four top quarks \\(t\bar{t}t\bar{t}\\). In these samples, the Higgs boson and top quarks decay inclusively. These 12 Higgs and top quark production processes constitute the pretraining dataset. - -To test the pretrained model, we further generated four processes including three beyond Standard Model (SM) processes: a SM \\(t\bar{t}H\\) production where the Higgs boson decays exclusively to a pair of photons, a \\(t\bar{t}H\\) production with the Higgs boson decaying to a pair of photons, where the top-Yukawa coupling is CP-odd, implemented using the Higgs Characterization model [Artoisenet et al., 2013](#ref-artoisinet-2013puc), the production of a pair of superpartners of the top quark (s-top) using the Minimal Supersymmetric Standard Model (MSSM) [Rosiek, 1990](#ref-rosiek-1990), [Allanach et al., 2009](#ref-allanach-2009), and flavor changing neutral current (FCNC) processes [Degrande et al., 2015](#ref-degrande-2015), [Durieux et al., 2015](#ref-durieux-2015). For the s-top process, we simulate the production of heavier s-top pairs \\(t_2\bar{t_2}\\), where each heavier s-top (mass 582 GeV) decays into a lighter s-top \\(t_1\\) or \\(\bar{t_1}\\), mass 400 GeV) and a Higgs boson. The FCNC process involves \\(t\bar{t}\\) production where one top quark decays to a Higgs boson and a light quark. We generate 10 million events for each process, except for \\(tHq\\) and \\(t\bar{t}t\bar{t}\\), where 5 million events were produced. - -In all simulation samples, the center of mass energy of the proton-proton collision is set to 13 TeV. The Higgs boson, top quarks, and vector bosons are set to decay inclusively (except the \\(t\bar{t}H \rightarrow \gamma\gamma\\) samples), with MadSpin [Artoisenet et al., 2012](#ref-artoisinet-2012st) handling the decays of top quarks and W bosons. The generated events are processed through Pythia 8.235 [Sjostrand et al., 2015](#ref-sjostrand-2015) for parton showering and heavy particle decays, followed by Delphes 3.4.2 [de Favereau et al., 2014](#ref-defavereau-2014) configured to emulate the ATLAS detector [ATLAS Collaboration, 2008](#ref-atlas-2008) for fast detector simulation. - -The detector-level object selection criteria are defined to align with typical experimental conditions. Photons are required to have transverse momentum \\(p_T \geq 20~\mathrm{GeV}\\) and pseudorapidity \\(|\eta| \leq 2.37\\), excluding the electromagnetic calorimeter crack region \\(1.37 < |\eta| < 1.52\\). Electrons must have \\(p_T \geq 10~\mathrm{GeV}\\) and \\(|\eta| \leq 2.47\\) (excluding the same crack region), while muons are selected with \\(p_T \geq 10~\mathrm{GeV}\\) and \\(|\eta| \leq 2.7\\). Jets are reconstructed using the anti-\\(k_t\\) algorithm [Cacciari et al., 2008](#ref-cacciari-2008gp) with radius parameter \\(\Delta R=0.4\\), where \\(\Delta R\\) is defined as \\(\sqrt{\Delta\eta ^2 + \Delta\phi^2}\\), with \\(\Delta\eta\\) being the difference in pseudorapidity and \\(\Delta\phi\\) the difference in azimuthal angle. Jets must satisfy \\(p_T \geq 25~\mathrm{GeV}\\) and \\(|\eta| \leq 2.5\\). To avoid double-counting, jets are removed if they are within \\(\Delta R < 0.4\\) of a photon or lepton. The identification of jets originating from b-quark decays (b-tagging) is performed by matching jets within \\(\Delta R = 0.4\\) of a b-quark, with efficiency corrections applied to match the performance of the ATLAS experiment's b-tagging algorithm [ATLAS Collaboration, 2019](#ref-atlas-2019bwq). - -## Methods - -### Overview - -We present a methodology for developing and evaluating a foundation model for particle collision event analysis. The approach centers on pretraining a Graph Neural Network (GNN) architecture using a comprehensive dataset that spans multiple physics tasks, enabling the model to learn robust and transferable features. For task-specific applications, we employ a fine-tuning strategy that combines output layer adaptation with carefully calibrated learning rates for updating the pretrained parameters. - -Given the prevalence of classification problems in particle physics data analysis, we evaluate the model's efficacy through a systematic assessment across five binary classification tasks: - -- \\(t\bar{t}H(\rightarrow \gamma\gamma)\\) with CP-even versus CP-odd t-H interaction -- \\(t\bar{t}\\) with FCNC top quark decays versus $tHq$ processes -- \\(t\bar{t}W\\) versus $ttt$ processes -- Stop pair production with Higgs bosons in the decay chain versus \\(t\bar{t}H\\) processes -- \\(WH\\) versus \\(ZH\\) production modes - -Our evaluation metrics encompass classification performance, computational efficiency, and model interpretability. The investigation extends to analyzing the model's scaling behavior with respect to training dataset size, benchmarked against models trained without pretraining. Although we explored transfer learning through parameter freezing of pretrained layers, this approach did not yield performance improvements, leading us to focus our detailed analysis on fine-tuning strategies. - -This methodological framework demonstrates the potential of foundation models to enhance the efficiency of particle physics analyses while improving task-specific performance, offering a promising direction for future high-energy physics research. - ---- - -### GNN Architecture - -We implement a Graph Neural Network (GNN) architecture that naturally accommodates the point-cloud structure of particle physics data, employing the DGL framework with a PyTorch backend [Wang et al., 2019][ref-dgl-2019], [Paszke et al., 2019][ref-pytorch-2019]. A fully connected graph is constructed for each event, with nodes corresponding to reconstructed jets, electrons, muons, photons, and \\(\vec{E}_T^{\text{miss}}\\). The features of each node include the four-momentum \\((p_T, \eta, \phi, E)\\) of the object with a massless assumption (\\(E = p_T \cosh \eta\\)), the b-tagging label (for jets), the charge (for leptons), and an integer labeling the type of object represented by the node. We use a placeholder value of 0 for features which are not defined for every node type such as the b-jet tag, lepton charge, or the pseudorapidity of \\(\vec{E}_T^{\text{miss}}\\). We assign the angular distances (\\(\Delta \eta, \Delta \phi, \Delta R\\)) as edge features and the number of nodes $N$ in the graph as a global feature. We denote the node features \\(\{\vec x_i\}\\), edge features \\(\{\vec y_{ij}\}\\), and global features \\(\{\vec z\}\\). - -The GNN model is based on the graph network architecture described in [Battaglia et al., 2018][ref-graphnets-2018] using simple multilayer perceptron (MLP) feature functions and summation aggregation. The model is comprised of three primary components: an encoder, the graph network, and a decoder. In the encoder, three MLPs embed the nodes, edges, and global features into a latent space of dimension 64. The graph network block, which is designed to facilitate message passing between different domains of the graph, performs an edge update $f_e$, followed by a node update $f_n$, and finally a global update $f_g$, all defined below. The inputs to each update MLP are concatenated. - -$$ -\vec {y'}_{ij} = f_e\left(\{\vec x_k\},\vec y_{ij},\vec z\right) = \mathrm{MLP}\left(\vec x_i,\vec x_j,\vec y_{ij},\vec z\right) -$$ - -$$ -\vec{x'}_{i} = f_n\left(\vec x_i,\{\vec{y'}_{jk}\},\vec z\right) = \mathrm{MLP}\left(\vec x_i,\sum_j\vec{y'}_{ij},\vec z\right) -$$ - -$$ -\vec{z'} = f_g\left(\{\vec{x'}_i\},\{\vec{y'}_{ij}\},\vec z\right) = \mathrm{MLP}\left(\sum_i\vec{x'}_i,\sum_{i,j}\vec{y'}_{ij},\vec z\right) -$$ - -This graph block is iterated four times with the same update MLPs. Finally, the global features are passed through a decoder MLP and a final layer linear to produce the desired model outputs. Each MLP consists of 4 linear layers, each with an output width of 64, with the `ReLU` activation function. The output of the MLP is then passed through a `LayerNorm` layer [Ba et al., 2016][ref-layernorm-2016]. The total number of trainable parameters in this model is about 400,000. - -As a performance benchmark, a baseline GNN model is trained from scratch for each classification task. The initial learning rate is set to \\(10^{-4}\\) with an exponential decay following \\(LR(x) = LR_{\text{initial}}\cdot(0.99)^x\\), where \\(x\\) represents the epoch number. - ---- - -### Pretraining Strategy - -We explore two complementary pretraining approaches to develop robust representations of collision events: (1) multi-class classification, which trains the model to distinguish between different physics processes, and (2) multi-label classification, which predicts the existence and kinematics of heavy particles with prompt decays. The pretraining dataset consists of approximately 120 million events, evenly distributed across 12 distinct physics processes, including all major Higgs boson production mechanisms and top quark processes as described in [Data Samples](#sec-data). This large-scale pretraining effort was conducted on the Perlmutter supercomputer at NERSC. - -#### Multi-class Classification - -For Monte Carlo simulated events, the underlying physics process that generated each event is known precisely, providing natural labels for supervised learning. However, the challenge lies in the complexity of collision events: different physics processes can produce similar kinematics and event topologies, particularly in certain regions of phase space. No single observable can unambiguously identify the underlying process. By training the model to distinguish between 12 different processes simultaneously, we challenge it to learn subtle differences in kinematics and topology that collectively characterize each process. The model is trained using categorical cross entropy as the loss function. The output layer of the multiclass classification model has 832 trainable parameters. - -#### Multi-label Classification - -This approach combines both classification and regression tasks to characterize collision events. For discrete properties like particle presence in specific kinematic regions, we employ classification labels with binary cross-entropy loss. For continuous quantities like particle multiplicities, we use regression labels with mean-squared error loss. This hybrid approach enables the model to learn both categorical and continuous aspects of the physics processes simultaneously. - -We develop a comprehensive set of 41 labels that capture both particle multiplicities and kinematic properties. This approach increases prediction granularity and enhances model interpretability. By training the model to predict event kinematics rather than event identification, we create a task-independent framework that can potentially generalize better to novel scenarios not seen during pretraining. - -The particle multiplicity labels count the number of Higgs bosons (\\(n_{\text{higgs}}\\)), top quarks (\\(n_{\text{tops}}\\)), vector bosons (\\(n_V\\)), \\(W\\) bosons (\\(n_W\\)), and \\(Z\\) bosons (\\(n_Z\\)). The kinematic labels characterize the transverse momentum (\\(p_T\\)), pseudorapidity (\\(\eta\\)), and azimuthal angle (\\(\phi\\)) of Higgs bosons and top quarks through binned classifications. - -For Higgs bosons, $p_T$ is categorized into three ranges: (0, 30) GeV, (30, 200) GeV, and (200, \\(\infty\\)) GeV, with the upper range particularly sensitive to potential BSM effects. Similarly, both leading and subleading top quarks have $p_T$ classifications spanning (0, 30) GeV, (30, 300) GeV, and (300, \\(\infty\\)) GeV. When no particle exists within a specific \\(p_T\\) range, the corresponding label is set to \\([0, 0, 0]\\). For all particles, \\(\eta\\) measurements are divided into 4 bins with boundaries at \\([-1.5, 0, 1.5]\\), while \\(\phi\\) measurements use 4 bins with boundaries at \\([-\frac{\pi}{2}, 0, \frac{\pi}{2}]\\). As with \\(p_T\\), both \\(\eta\\) and \\(\phi\\) labels default to \\([0, 0, 0, 0]\\) in the absence of a particle. This comprehensive labeling schema enables fine-grained learning of kinematic distributions and particle multiplicities, essential for characterizing complex collision events. - -The loss function combines individual losses from all 41 labels through weighted averaging. Binary cross-entropy is applied to classification labels, while mean-squared error is used for regression labels. The model generates predictions for all labels simultaneously, with individual losses calculated according to their respective types. The final loss is computed as an equally-weighted average across all labels, with weights set to 1 to ensure uniform contribution to the optimization process. The output layer of the multilabel model has 2,688 trainable parameters. - -#### Pretraining - -During pre-training, the initial learning rate is \\(10^{-4}\\), and the learning rate decays by 1% each epoch following the power law function \\(LR(x) = 10^{-4}\cdot(0.99)^x\\), where \\(x\\) is the number of epochs. Both pre-trained models reach a plateau in loss by epoch 50, at which point the training is stopped. - ---- -### Fine-tuning Methodology - -For downstream tasks, we adjust the model architecture for fine-tuning by replacing the original output layer (final linear layer) with a newly initialized linear layer while retaining the pre-trained weights for all other layers. This modification allows the model to specialize in the specific downstream task while leveraging the general features learned during pretraining. - -The fine-tuning process begins with distinct learning rate setups for different parts of the model. The newly initialized linear layer is trained with an initial learning rate of \\(10^{-4}\\), matching the rate used for models trained from scratch. Meanwhile, the pre-trained layers are fine-tuned more cautiously with a lower initial learning rate of \\(10^{-5}\\). This approach ensures that the pre-trained layers adapt gradually without losing their general features, while the new layer learns effectively from scratch. Both learning rates decay over time following the same power law function, \\(LR(x) = LR_{initial} \cdot (0.99)^x\\), to promote stable convergence as training progresses. - -We also evaluated a transfer learning setup in which either the decoder MLP or the final linear layer was replaced with a newly initialized component. During this process, all other model parameters remained frozen, leveraging the pre-trained features without further updating them. However, we did not observe performance improvements using the transfer learning setup. Consequently, we focus on reporting results obtained with the fine-tuning approach. - ---- - -### Performance Evaluation - -We assess model performance using two figures of merit: the classification accuracy and the Area Under the Curve (AUC) of the Receiver Operating Characteristic (ROC) curve. The accuracy is defined as the fraction of correctly classified events when applying a threshold of 0.5 to the neural network output score. Both metrics demonstrate consistent trends in our analysis. - -To obtain reliable performance estimates and uncertainties, we employ an ensemble training approach where 5 independent models are trained for each configuration with random weight initialization and random subsets of the training dataset. This enables us to evaluate both the models' sensitivity to initial parameters and to quantify uncertainties in their performance. - -To investigate how model performance scales with training data, we conducted training runs using sample sizes ranging from \\(10^3\\) to \\(10^7\\) events per class (\\(10^3\\), \\(10^4\\), \\(10^5\\), \\(10^6\\), and \\(10^7\\)) for each model setup: the from-scratch baseline and models fine-tuned from multi-class or multi-label pretrained models. For the \\(10^7\\) case, only the initialization was randomized due to dataset size limitations. All models were evaluated on the same testing dataset, consisting of 2 million events per class, which remained separate from the training process. - -| **Name of Task** | **Pretraining Task** | \\(10^3\\) | \\(10^4\\) | \\(10^5\\) | \\(10^6\\) | \\(10^7\\) | -|----------------------|----------------------|--------------------|--------------------|--------------------|--------------------|--------------------| -| **ttH CP Even vs Odd** | Baseline Accuracy | 56.5 ± 1.1 | 62.2 ± 0.1 | 64.3 ± 0.0 | 65.7 ± 0.0 | 66.2 ± 0.0 | -| | Multiclass (%) | +4.8 ± 1.1 | +3.4 ± 0.1 | +1.3 ± 0.0 | +0.2 ± 0.0 | −0.0 ± 0.0 | -| | Multilabel (%) | +2.1 ± 1.2 | +1.9 ± 0.1 | +0.8 ± 0.1 | +0.0 ± 0.0 | −0.1 ± 0.0 | -| **FCNC vs tHq** | Baseline Accuracy | 63.6 ± 0.7 | 67.8 ± 0.4 | 68.4 ± 0.3 | 69.3 ± 0.3 | 67.9 ± 0.0 | -| | Multiclass (%) | +5.8 ± 0.8 | +1.2 ± 0.4 | +1.4 ± 0.3 | +0.5 ± 0.3 | −0.0 ± 0.0 | -| | Multilabel (%) | −5.3 ± 0.8 | −1.3 ± 0.4 | +0.9 ± 0.4 | +0.3 ± 0.3 | +0.4 ± 0.1 | -| **ttW vs ttt** | Baseline Accuracy | 75.8 ± 0.1 | 77.6 ± 0.1 | 78.9 ± 0.0 | 79.8 ± 0.0 | 80.3 ± 0.0 | -| | Multiclass (%) | +3.7 ± 0.1 | +2.7 ± 0.1 | +1.3 ± 0.0 | +0.4 ± 0.0 | +0.0 ± 0.0 | -| | Multilabel (%) | +2.2 ± 0.1 | +1.1 ± 0.1 | +0.5 ± 0.0 | +0.0 ± 0.0 | −0.1 ± 0.0 | -| **stop vs ttH** | Baseline Accuracy | 83.0 ± 0.2 | 86.3 ± 0.1 | 87.6 ± 0.0 | 88.5 ± 0.0 | 88.8 ± 0.0 | -| | Multiclass (%) | +0.4 ± 0.2 | +1.9 ± 0.1 | +1.0 ± 0.0 | +0.3 ± 0.0 | +0.0 ± 0.0 | -| | Multilabel (%) | +2.8 ± 0.2 | +1.0 ± 0.1 | +0.5 ± 0.0 | +0.0 ± 0.0 | −0.0 ± 0.0 | -| **WH vs ZH** | Baseline Accuracy | 51.4 ± 0.1 | 53.9 ± 0.1 | 55.8 ± 0.0 | 57.5 ± 0.0 | 58.0 ± 0.0 | -| | Multiclass (%) | +5.2 ± 0.1 | +5.3 ± 0.1 | +3.1 ± 0.0 | +0.6 ± 0.0 | +0.1 ± 0.0 | -| | Multilabel (%) | −1.1 ± 0.1 | −0.9 ± 0.2 | +0.5 ± 0.1 | +0.1 ± 0.0 | −0.1 ± 0.0 | - -> **Table 1**: Accuracy of the traditional model versus the accuracy increase due to fine-tuning from various pretraining tasks. -> The accuracies are averaged over 5 independently trained models with randomly initialized weights and trained on a random subset of the data. One exception is the \\(10^7\\) training where all models use the same dataset due to limitations on our dataset size. The random subsets are allowed to overlap, but this overlap should be very minimal because all models take an independent random subset of \\(10^7\\) events. The testing accuracy is calculated from the same testing set of 2 million events per class across all models for a specific training task. The errors are the propagated errors (root sum of squares) of the standard deviation of accuracies for each model. - -## Results - -### Classification Performance - -Since the observations of AUC and accuracy show similar trends, we focus the presentation of the results using accuracy here for conciseness in Table 1. - -In general, the fine-tuned pretrained model achieves at least the same level of classification performance as the baseline model. Notably, there are significant improvements, particularly when the sample size is small, ranging from \\(10^3\\) to \\(10^4\\) events. In some cases, the accuracy improvements exceed five percentage points, demonstrating that pretrained models provide a strong initial representation that compensates for limited data. The numerical values of the improvements in accuracy may not fully capture the impact on the sensitivity of the measurements for which the neural network classifier is used, and the final sensitivity improvement is likely to be greater. - -As the training sample size grows to \\(10^5\\), \\(10^6\\), and eventually \\(10^7\\) events, the added benefit of pretraining diminishes. With abundant data, models trained from scratch approach or even match the accuracy of fine-tuned pretrained models. This suggests that large datasets enable effective learning from scratch, rendering the advantage of pretraining negligible in such scenarios. - -Although both pretraining approaches offer benefits, multiclass pretraining tends to provide more consistent improvements across tasks, especially in the low-data regime. In contrast, multilabel pretraining can sometimes lead to neutral or even slightly negative effects for certain tasks and data sizes. This highlights the importance of the pretraining task design, as the similarity between pretraining and fine-tuning tasks in the multiclass approach appears to yield better-aligned representations. - -Finally, the spread of accuracy across the five tasks for the baseline model is quite large, offering a robust test of fine-tuning across tasks of varying difficulty. The consistent observation of these trends across tasks confirms the reliability and robustness of the findings. - ---- - -### Model Interpretability - -We aim to understand whether pretrained and baseline models learn the same underlying representations. If the two models exhibit high similarity, a plausible interpretation is that pretraining provides the pretrained model with an advantageous initialization, allowing it to converge to a similar state as the baseline model more efficiently. Conversely, significant differences between the models would indicate that pretraining facilitates the development of a more general and robust latent space, which serves as a foundation for fine-tuning to effectively adapt to the downstream task. To investigate this, we analyzed the representational similarity between a pretrained model fine-tuned for the downstream task and a baseline model trained directly on the downstream task without pretraining. - -We use Centered Kernel Alignment (CKA) [Kornblith et al., 2019][ref-kornblith-2019-cka] to analyze model similarity and interpretability. CKA is a robust metric that quantifies the similarity between the internal representations of neural networks by comparing their feature matrices in a manner that is invariant to scaling, rotation, and alignment. This invariance makes CKA particularly effective for studying relationships between network layers, even across networks of different sizes or those trained from varying initializations. - -The similarity is evaluated using a 64-dimensional latent representation after the decoder stage of the GNN model. This choice allows us to compare the internal states of the models at a fine-grained level and understand how training strategies impact the representations directly used for the output task. - -To provide an intuitive understanding of CKA values, we construct a table of the CKA scores for various transformations performed on a set of dummy data. - -- **A:** randomly initialized matrix with shape (1000, 64), following a normal distribution (\\(\sigma = 1, \mu = 0\\)) -- **B:** matrix with shape (1000, 64) constructed via various transformations performed on \\(A\\) -- **Noise:** randomly initialized noise matrix with shape (1000, 64), following a normal distribution (\\(\sigma = 1, \mu = 0\\)) - -| Dataset | CKA Score | -|---------|-----------| -| \\(A, B = A\\) | 1.00 | -| \\(A, B =\\) permutation on columns of \\(A\\) | 1.00 | -| \\(A, B = A + \mathrm{Noise}(0.1)\\) | 0.99 | -| \\(A, B = A + \mathrm{Noise}(0.5)\\) | 0.80 | -| \\(A, B = A + \mathrm{Noise}(0.75)\\) | 0.77 | -| \\(A, B = A \cdot \mathrm{Noise}(1)\\) (Linear Transformation) | 0.76 | -| \\(A, B = A + \mathrm{Noise}(1)\\) | 0.69 | -| \\(A, B = A + \mathrm{Noise}(2)\\) | 0.51 | -| \\(A, B = A + \mathrm{Noise}(5)\\) | 0.39 | - -**Table 2:** CKA scores for a dummy dataset \\(A\\) and \\(B\\), where \\(B\\) is created via various transformations performed on \\(A\\). - -As seen in Table 2 and in the definition of the CKA, the CKA score is permutation-invariant. We will use the CKA score to evaluate the similarity between various models and gain insight into the learned representation of detector events in each model (i.e., the information that each model learns). - -We train ensembles of models for each training task to observe how the CKA score changes due to the random initialization of our models. The CKA score between two models is then defined to be: - -\\[ -CKA(A, B) = \frac{1}{n^2} \sum_i^n \sum_j^n CKA(A_i, B_j) -\\] - -where \\(A_i\\) is the representation learned by the \\(i^{\text{th}}\\) model in an ensemble with \\(n\\) total models. The error in CKA is the standard deviation of \\(CKA(A_i, B_j)\\). - -Here we present results for the CKA similarity between the final model in each setup with the final model in the baseline, shown in Table 3. - -| Training Task | Baseline | Multiclass | Multilabel | -|-----------------------|------------------|-----------------|-----------------| -| ttH CP Even vs Odd | 0.94 ± 0.05 | 0.82 ± 0.01 | 0.77 ± 0.06 | -| FCNC vs tHq | 0.96 ± 0.03 | 0.76 ± 0.01 | 0.81 ± 0.01 | -| ttW vs ttt | 0.91 ± 0.08 | 0.75 ± 0.10 | 0.72 ± 0.05 | -| stop vs ttH | 0.87 ± 0.11 | 0.79 ± 0.12 | 0.71 ± 0.08 | -| WH vs ZH | 0.90 ± 0.07 | 0.53 ± 0.03 | 0.44 ± 0.06 | - -**Table 3:** CKA Similarity of the latent representation before the decoder with the baseline model, averaged over 3 models per training setup, and all models trained with the full dataset (\\(10^7\\)). The baseline column is not guaranteed to be 1.0 because of the random initialization of the model. Each baseline model converges to a slightly different representation as seen in the CKA values in that column. - -The baseline models with different initializations exhibit high similarity values, ranging from approximately 0.87 to 0.96, which indicates that independently trained baseline models tend to converge on similar internal representations despite random initialization. Across the considered tasks, models trained as multi-class or multi-label classifiers exhibit noticeably lower CKA similarity scores when compared to the baseline model. For example, in the WH vs ZH task, the baseline model and another baseline trained model have a high similarity of 0.90, whereas the multi-class and multi-label models show significantly reduced similarities (0.53 and 0.44, respectively). This pattern suggests that the representational spaces developed by multi-class or multi-label models differ substantially from those learned by the baseline model that was trained directly on the downstream classification task. - -### Computational Efficiency - -To estimate the computational resources required for each approach, we measured the wall time needed for a model to reach its final performance. For baseline models, this is defined as the wall time from the start of training until the loss of the model plateaus. For the foundation model approach, the estimate includes both the pretraining time and the fine-tuning time, each measured from the start of training until the loss plateaus. This approach ensures a consistent and comprehensive evaluation of the computational demands. - -![The ratio of the fine-tuning time required to achieve 99% of the baseline model's final classification accuracy to the total time spent training the baseline model.](training_time.png) -*Fig. 1: The ratio of the fine-tuning time required to achieve 99% of the baseline model's final classification accuracy to the total time spent training the baseline model.* - -Figure 1 shows the fine-tuning time for the model pretrained with multiclass classification, relative to the time required for the baseline model, as a function of training sample size. In general, the fine-tuning time is significantly shorter than the training time required by the baseline model approach. For smaller training sets, on the order of \\(10^5\\) events, tasks such as FCNC vs. tHq and ttW vs. ttt benefit substantially from the pretrained model’s “head start,” achieving their final performance in only about 1% of the baseline time. For large training datasets, the fine-tuning time relative to the baseline training time becomes larger; however, given that the large training sample typically requires longer training time, fine-tuning still yields much faster training convergence. The ttH CP-even vs. ttH CP-odd task, with a training sample size of \\(10^7\\) events, is an exception where the fine-tuning time exceeds the training time required for the baseline model. This is likely because the processes involved in this task include photon objects in the final states, which are absent from the events used during pretraining. - -To accurately evaluate the total time consumption, it is necessary to include the pretraining time required for the foundation model approach. The pretraining times are as follows: - -- **Multi-class pretraining:** 45.5 GPU hours -- **Multi-label pretraining:** 60.0 GPU hours - -The GPU hours recorded for the multi-label model represent the total time required when training the model in parallel on 16 GPUs. This includes a model synchronization step, which results in higher GPU hours compared to the multi-class pretraining model. - -The foundation model approach becomes increasingly efficient when a large number of tasks are fine-tuned using the same pretrained model, compared to training each task independently from scratch. To illustrate this, we evaluate the computational time required for a scenario where the training sample contains \\(10^7\\) events. For the five tasks tested in this study, the baseline training time (training from scratch) ranges from 1.68 GPU hours (WH vs. ZH) to 5.30 GPU hours (ttW vs. ttt), with an average baseline training time of 2.94 GPU hours. In contrast, the average fine-tuning time for the foundation model approach, relative to the baseline, is 38% of the baseline training time for \\(10^7\\) events. Based on these averages, we estimate that the foundation model approach becomes more computationally efficient than the baseline approach when fine-tuning is performed for more than 41 tasks. - -As a practical example, the ATLAS measurement of Higgs boson couplings using the \\(H \rightarrow \gamma\gamma\\) decay channel [ATLAS Collaboration, 2023][ref-atlas-2023-higg] involved training 42 classifiers for event categorization. This coincides with our estimate, suggesting that the foundation model approach can reduce computational costs even for a single high-energy physics measurement. - -## Conclusions - -We presented an in-depth study of a particle physics foundation model designed to operate on the four-momentum and identification properties of event final-state objects. This model is built on a Graph Neural Network (GNN) architecture and trained on a dataset comprising 120 million simulated proton-proton collision events across 12 distinct physics processes. The pretraining phase explored both multiclass and multilabel classification tasks, providing a robust foundation for downstream applications. Notably, the pretrained models demonstrated significant improvements in event classification performance when fine-tuned, particularly for tasks with limited training samples. - -The foundation model approach also offers substantial computational advantages. By leveraging fine-tuning, this methodology reduces the computational resources required for large-scale applications across multiple tasks. Our estimates indicate that significant resource savings can be achieved even for single particle physics measurements, making this approach both scalable and efficient. - -To better understand the learned representations of the pretrained model and guide future optimization efforts, we employed a representational similarity evaluation framework using Centered Kernel Alignment (CKA). This metric allowed us to investigate the source of the performance gains observed in the foundation model. Our analysis revealed notable differences in the learned representations between the fine-tuned pretrained model and a baseline model trained from scratch. In deep learning, it is well-established that multiple equally valid solutions can exist. Future studies are necessary to determine whether the low similarity in latent representations reflects complementary information uniquely captured by the foundation and baseline models, or if it can simply be attributed to connected local minima in the loss landscape. - -## Acknowledgments - -This work is supported by the U.S. National Science Foundation under the Award No. 2046280, and by U.S. Department of Energy, Office of Science under contract DE-AC02-05CH11231. - -## References - -- **OpenAI et al.** GPT-4 Technical Report. arXiv:2303.08774 (2024). [https://arxiv.org/abs/2303.08774](https://arxiv.org/abs/2303.08774) - -- **Jason Yosinski, Jeff Clune, Yoshua Bengio, Hod Lipson.** How transferable are features in deep neural networks? CoRR abs/1411.1792 (2014). [http://arxiv.org/abs/1411.1792](http://arxiv.org/abs/1411.1792) - -- **Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, Björn Ommer.** High-Resolution Image Synthesis with Latent Diffusion Models. CoRR abs/2112.10752 (2021). [https://arxiv.org/abs/2112.10752](https://arxiv.org/abs/2112.10752) - -- **Dustin Podell, Zion English, Kyle Lacey et al.** SDXL: Improving Latent Diffusion Models for High-Resolution Image Synthesis. arXiv:2307.01952 (2023). [https://arxiv.org/abs/2307.01952](https://arxiv.org/abs/2307.01952) - -- **John Jumper, Richard Evans, Alexander Pritzel et al.** Highly accurate protein structure prediction with AlphaFold. Nature 596, 583-589 (2021). [https://doi.org/10.1038/s41586-021-03819-2](https://doi.org/10.1038/s41586-021-03819-2) - -- **Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova.** BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. CoRR abs/1810.04805 (2018). [http://arxiv.org/abs/1810.04805](http://arxiv.org/abs/1810.04805) - -- **ATLAS Collaboration.** Measurement of the properties of Higgs boson production at \\(\sqrt{s} = 13\,\text{TeV}\\) in the \\(H \to \gamma\gamma\\) channel using \\(139\,\text{fb}^{-1}\\) of \\(pp\\) collision data with the ATLAS experiment. JHEP 07 (2023) 088. [arXiv:2207.00348](https://arxiv.org/abs/2207.00348), [https://doi.org/10.1007/JHEP07(2023)088](https://doi.org/10.1007/JHEP07(2023)088) - -- **ATLAS Collaboration.** Observation of four-top-quark production in the multilepton final state with the ATLAS detector. Eur. Phys. J. C 83 (2023) 496. [arXiv:2303.15061](https://arxiv.org/abs/2303.15061), [https://doi.org/10.1140/epjc/s10052-023-11573-0](https://doi.org/10.1140/epjc/s10052-023-11573-0) - -- **Simon Kornblith, Mohammad Norouzi, Honglak Lee, Geoffrey Hinton.** Similarity of Neural Network Representations Revisited. CoRR abs/1905.00414 (2019). [http://arxiv.org/abs/1905.00414](http://arxiv.org/abs/1905.00414) - ---- - - - -- **N. D. Birell, P. C. W. Davies.** Quantum Fields in Curved Space. Cambridge Univ. Press (1982). - -- **R. P. Feynman.** Phys. Rev. 94, 262 (1954). - -- **A. Einstein, Yu. Podolsky, N. Rosen.** Phys. Rev. 47, 777 (1935). - -- **G. P. Berman, Jr., F. M. Izrailev, Jr.** Stability of nonlinear modes. Physica D 88, 445 (1983). - -- **E. B. Davies, L. Parns.** Trapped modes in acoustic waveguides. Q. J. Mech. Appl. Math. 51, 477–492 (1988). - -- **Edward Witten.** hep-th/0106109 (2001). [https://arxiv.org/abs/hep-th/0106109](https://arxiv.org/abs/hep-th/0106109) - ---- - - - -- **E. Beutler.** Williams Hematology, 5th Edition, Chapter 7, pp. 654–662. McGraw-Hill, New York (1994). - -- **Donald E. Knuth.** The Art of Computer Programming vol. 1: Fundamental Algorithms, 2nd Ed., Addison-Wesley (1973). - -- **J. S. Smith, G. W. Johnson.** Philos. Trans. R. Soc. London, Ser. B 777, 1395 (2005). - -- **W. J. Smith, T. J. Johnson, B. G. Miller.** Surface chemistry and preferential crystal orientation on a silicon surface. J. Appl. Phys. (unpublished, 2010). - -- **V. K. Smith, K. Johnson, M. O. Klein.** Surface chemistry and preferential crystal orientation on a silicon surface. J. Appl. Phys. (submitted, 2010). - -- **Ulrich Underwood, Ned Net, Paul Pot.** Lower Bounds for Wishful Research Results. Talk at Fanstord University (1988). - -- **M. P. Johnson, K. L. Miller, K. Smith.** Personal communication (Jan-May 2007). - ---- - - - -- **Adam Paszke et al.** PyTorch: An Imperative Style, High-Performance Deep Learning Library. arXiv:1912.01703 (2019). [http://arxiv.org/abs/1912.01703](http://arxiv.org/abs/1912.01703) - -- **Minjie Wang et al.** Deep Graph Library: Towards Efficient and Scalable Deep Learning on Graphs. arXiv:1909.01315 (2019). [http://arxiv.org/abs/1909.01315](http://arxiv.org/abs/1909.01315) - -- **Peter W. Battaglia et al.** Relational inductive biases, deep learning, and graph networks. arXiv:1806.01261 (2018). [http://arxiv.org/abs/1806.01261](http://arxiv.org/abs/1806.01261) - -- **Jimmy Lei Ba, Jamie Ryan Kiros, Geoffrey E. Hinton.** Layer Normalization. arXiv:1607.06450 (2016). [https://arxiv.org/abs/1607.06450](https://arxiv.org/abs/1607.06450) - ---- - - - -- **Andrew J. Wildridge et al.** Bumblebee: Foundation Model for Particle Physics Discovery. arXiv:2412.07867 (2024). [https://arxiv.org/abs/2412.07867](https://arxiv.org/abs/2412.07867) - -- **Subash Katel et al.** Learning Symmetry-Independent Jet Representations via Jet-Based Joint Embedding Predictive Architecture. arXiv:2412.05333 (2024). [https://arxiv.org/abs/2412.05333](https://arxiv.org/abs/2412.05333) - -- **Jack Y. Araz et al.** Point cloud-based diffusion models for the Electron-Ion Collider. arXiv:2410.22421 (2024). [https://arxiv.org/abs/2410.22421](https://arxiv.org/abs/2410.22421) - -- **Matthew Leigh et al.** Is Tokenization Needed for Masked Particle Modelling? arXiv:2409.12589 (2024). [https://arxiv.org/abs/2409.12589](https://arxiv.org/abs/2409.12589) - -- **Vinicius Mikuni, Benjamin Nachman.** OmniLearn: A Method to Simultaneously Facilitate All Jet Physics Tasks. arXiv:2404.16091 (2024). [https://arxiv.org/abs/2404.16091](https://arxiv.org/abs/2404.16091) - -- **Zhengde Zhang et al.** Xiwu: A Basis Flexible and Learnable LLM for High Energy Physics. arXiv:2404.08001 (2024). [https://arxiv.org/abs/2404.08001](https://arxiv.org/abs/2404.08001) - -- **Philip Harris et al.** Re-Simulation-based Self-Supervised Learning for Pre-Training Foundation Models. arXiv:2403.07066 (2024). [https://arxiv.org/abs/2403.07066](https://arxiv.org/abs/2403.07066) - -- **Joschka Birk, Anna Hallin, Gregor Kasieczka.** OmniJet-$\alpha$: the first cross-task foundation model for particle physics. Machine Learning: Science and Technology. 5(3), 035031 (Aug 2024). [https://doi.org/10.1088/2632-2153/ad66ad](https://doi.org/10.1088/2632-2153/ad66ad) - -- **Andris Huang et al.** A Language Model for Particle Tracking. arXiv:2402.10239 (2024). [https://arxiv.org/abs/2402.10239](https://arxiv.org/abs/2402.10239) - -- **Tobias Golling et al.** Masked Particle Modeling on Sets: Towards Self-Supervised High Energy Physics Foundation Models. arXiv:2401.13537 (2024). [https://arxiv.org/abs/2401.13537](https://arxiv.org/abs/2401.13537) - -- **Junze Liu et al.** Generalizing to new geometries with Geometry-Aware Autoregressive Models (GAAMs) for fast calorimeter simulation. Journal of Instrumentation 18(11), P11003 (Nov 2023). [https://doi.org/10.1088/1748-0221/18/11/p11003](https://doi.org/10.1088/1748-0221/18/11/p11003) - -- **Baran Hashemi et al.** Ultra-high-granularity detector simulation with intra-event aware generative adversarial network and self-supervised relational reasoning. Nature Communications 15(1) (June 2024). [https://doi.org/10.1038/s41467-024-49104-4](https://doi.org/10.1038/s41467-024-49104-4) - -- **Matthias Vigl et al.** Finetuning Foundation Models for Joint Analysis Optimization. arXiv:2401.13536 (2024). [https://arxiv.org/abs/2401.13536](https://arxiv.org/abs/2401.13536) - -- **Chen Li, Hao Cai, Xianyang Jiang.** Refine neutrino events reconstruction with BEiT-3. Journal of Instrumentation 19(6), T06003 (Jun 2024). [https://doi.org/10.1088/1748-0221/19/06/t06003](https://doi.org/10.1088/1748-0221/19/06/t06003) \ No newline at end of file diff --git a/physicsnemo/configs/config.yaml b/physicsnemo/configs/config.yaml deleted file mode 100644 index f4ba528f692c8cde29bfb3cad5560510b408f134..0000000000000000000000000000000000000000 --- a/physicsnemo/configs/config.yaml +++ /dev/null @@ -1,64 +0,0 @@ -# ignore_header_test -# Copyright 2023 Stanford University -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -random_seed: 2 - -scheduler: - lr: 1.E-3 - lr_decay: 1.E-3 - -training: - epochs: 100 - -checkpoints: - ckpt_path: "checkpoints" - ckpt_name: "config" - -performance: - amp: False - jit: False - -architecture: - processor_size: 8 - hidden_dim_node_encoder: 128 - hidden_dim_edge_encoder: 128 - hidden_dim_processor: 128 - hidden_dim_node_decoder: 128 - out_dim: 1 - -paths: - data_dir: /global/cfs/projectdirs/atlas/joshua/hackathon_data/stats_100K - save_dir: /pscratch/sd/j/joshuaho/physicsnemo/graphs/stats_100K - training_dir: ./training_stats_100K/ - -datasets: - - name: ttH_cp_even - load_path: ${paths.data_dir}/ttH_NLO.root - label: 0 - - name: ttH_cp_odd - load_path: ${paths.data_dir}/ttH_CPodd.root - label: 1 - -root_dataset: - ttree: output - type: torch.bfloat16 - particles: ["jet", "ele", "mu", "ph", "MET"] - features: ["pt", "eta", "phi", "energy", "btag", "charge", "node_type"] - globals: [] - weights: "" - tracking: [] - step_size: 8192 - batch_size: 8192 - train_val_test_split: [0.75, 0.24, 0.01] \ No newline at end of file diff --git a/physicsnemo/configs/config_stats_all.yaml b/physicsnemo/configs/config_stats_all.yaml deleted file mode 100644 index bf7ac89fb86304cf48071dc7856db3da1e4bc057..0000000000000000000000000000000000000000 --- a/physicsnemo/configs/config_stats_all.yaml +++ /dev/null @@ -1,65 +0,0 @@ -# ignore_header_test -# Copyright 2023 Stanford University -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -random_seed: 2 - -scheduler: - lr: 1.E-4 - lr_decay: 1.E-3 - -training: - epochs: 100 - -checkpoints: - ckpt_path: "checkpoints" - ckpt_name: "config_stats_all" - -performance: - amp: False - jit: False - -architecture: - processor_size: 5 - hidden_dim_node_encoder: 64 - hidden_dim_edge_encoder: 64 - hidden_dim_processor: 64 - hidden_dim_node_decoder: 64 - out_dim: 1 - -paths: - data_dir: /global/cfs/projectdirs/atlas/joshua/hackathon_data/stats_all - save_dir: /pscratch/sd/j/joshuaho/physicsnemo/graphs/stats_all - training_dir: ./training_stats_all/ - -datasets: - - name: ttH_cp_even - load_path: ${paths.data_dir}/ttH_NLO.root - label: 0 - - name: ttH_cp_odd - load_path: ${paths.data_dir}/ttH_CPodd.root - label: 1 - -root_dataset: - ttree: output - type: torch.bfloat16 - particles: ["jet", "ele", "mu", "ph", "MET"] - features: ["pt", "eta", "phi", "energy", "btag", "charge", "node_type"] - globals: [] - weights: "" - tracking: [] - step_size: 81920 - batch_size: 8192 - train_val_test_split: [0.75, 0.24, 0.01] - prebatch: True \ No newline at end of file diff --git a/physicsnemo/configs/tHjb_CP_0_vs_45.yaml b/physicsnemo/configs/tHjb_CP_0_vs_45.yaml deleted file mode 100644 index 2bc0cfd298a5da976ae5c93b80f99e091b7f0a6c..0000000000000000000000000000000000000000 --- a/physicsnemo/configs/tHjb_CP_0_vs_45.yaml +++ /dev/null @@ -1,79 +0,0 @@ -# ignore_header_test -# Copyright 2023 Stanford University -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -random_seed: 2 - -scheduler: - lr: 1.E-3 - lr_decay: 1.E-3 - -training: - epochs: 100 - -checkpoints: - ckpt_path: "checkpoints" - ckpt_name: "config" - -performance: - amp: False - jit: False - -architecture: - processor_size: 8 - hidden_dim_node_encoder: 128 - hidden_dim_edge_encoder: 128 - hidden_dim_processor: 128 - hidden_dim_node_decoder: 128 - global_emb_dim: 128 - out_dim: 1 - -paths: - data_dir: /global/cfs/projectdirs/atlas/joshua/ttHCP/ntuples/v02/preselection/merged_fixed/train/ - save_dir: /pscratch/sd/j/joshuaho/physicsnemo/ttHCP/graphs/tHjb_CP_0_vs_45/ - training_dir: ./training_tHjb_CP_0_vs_45/ - -datasets: - - name: tHjb_cp_0_had - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_0_AF3_had_scaled.root - label: 0 - - name: tHjb_cp_0_lep - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_0_AF3_lep_scaled.root - label: 0 - - name: tHjb_cp_45_had - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_45_AF3_had_scaled.root - label: 1 - - name: tHjb_cp_45_lep - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_45_AF3_lep_scaled.root - label: 1 - -root_dataset: - ttree: output - dtype: torch.bfloat16 - features: - # pt, eta, phi, energy, btag, charge, node_type - jet: [m_jet_pt, m_jet_eta, m_jet_phi, CALC_E, m_jet_PCbtag, 0, 0] - electron: [m_el_pt, m_el_eta, m_el_phi, CALC_E, 0, m_el_charge, 1] - muon: [m_mu_pt, m_mu_eta, m_mu_phi, CALC_E, 0, m_mu_charge, 2] - photon: [ph_pt_myy, ph_eta, ph_phi, CALC_E, 0, 0, 3] - met: [m_met, 0, m_met_phi, CALC_E, 0, 0, 4] - globals: [NUM_NODES] - weights: m_weightXlumi - tracking: [] - step_size: 16384 - batch_size: 16384 - train_val_test_split: [0.5, 0.25, 0.25] - prebatch: - enabled: True - chunk_size: 512 \ No newline at end of file diff --git a/physicsnemo/configs/tHjb_CP_0_vs_90.yaml b/physicsnemo/configs/tHjb_CP_0_vs_90.yaml deleted file mode 100644 index 55737ff7b99cbd5b8fcceb41cc94e2e115e63333..0000000000000000000000000000000000000000 --- a/physicsnemo/configs/tHjb_CP_0_vs_90.yaml +++ /dev/null @@ -1,87 +0,0 @@ -# ignore_header_test -# Copyright 2023 Stanford University -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -random_seed: 2 - -scheduler: - lr: 1.E-3 - lr_decay: 1.E-3 - -training: - epochs: 100 - -checkpoints: - ckpt_path: "checkpoints" - ckpt_name: "tHjb_CP_0_vs_90" - -performance: - amp: False - jit: False - -architecture: - module: models.MeshGraphNet - class: MeshGraphNet - args: - base_gnn: - input_dim_nodes: 7 - input_dim_edges: 3 - output_dim: 128 - processor_size: 8 - hidden_dim_node_encoder: 128 - hidden_dim_edge_encoder: 128 - hidden_dim_processor: 128 - hidden_dim_node_decoder: 128 - global_emb_dim: 128 - global_feat_dim: 1 - out_dim: 1 - -paths: - data_dir: /global/cfs/projectdirs/atlas/joshua/ttHCP/ntuples/v02/preselection/merged_fixed/train/ - save_dir: /pscratch/sd/j/joshuaho/physicsnemo/ttHCP/graphs/tHjb_CP_0_vs_90/ - training_dir: ./tHjb_CP_0_vs_90/ - -datasets: - - name: tHjb_cp_0_had - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_0_AF3_had_scaled.root - label: 0 - - name: tHjb_cp_0_lep - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_0_AF3_lep_scaled.root - label: 0 - - name: tHjb_cp_90_had - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_90_AF3_had_scaled.root - label: 1 - - name: tHjb_cp_90_lep - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_90_AF3_lep_scaled.root - label: 1 - -root_dataset: - ttree: output - dtype: torch.bfloat16 - features: - # pt, eta, phi, energy, btag, charge, node_type - jet: [m_jet_pt, m_jet_eta, m_jet_phi, CALC_E, m_jet_PCbtag, 0, 0] - electron: [m_el_pt, m_el_eta, m_el_phi, CALC_E, 0, m_el_charge, 1] - muon: [m_mu_pt, m_mu_eta, m_mu_phi, CALC_E, 0, m_mu_charge, 2] - photon: [ph_pt_myy, ph_eta, ph_phi, CALC_E, 0, 0, 3] - met: [m_met, 0, m_met_phi, CALC_E, 0, 0, 4] - globals: [NUM_NODES] - weights: 1 - tracking: [] - step_size: 16384 - batch_size: 16384 - train_val_test_split: [0.5, 0.25, 0.25] - prebatch: - enabled: True - chunk_size: 512 \ No newline at end of file diff --git a/physicsnemo/configs/tHjb_CP_0_vs_90_edge_network.yaml b/physicsnemo/configs/tHjb_CP_0_vs_90_edge_network.yaml deleted file mode 100644 index 1fd6cfa0078254c3f817aad2736b0cd864fb672a..0000000000000000000000000000000000000000 --- a/physicsnemo/configs/tHjb_CP_0_vs_90_edge_network.yaml +++ /dev/null @@ -1,82 +0,0 @@ -# ignore_header_test -# Copyright 2023 Stanford University -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -random_seed: 2 - -scheduler: - lr: 1.E-3 - lr_decay: 1.E-3 - -training: - epochs: 100 - -checkpoints: - ckpt_path: "checkpoints" - ckpt_name: "tHjb_CP_0_vs_90_edge_network" - -performance: - amp: False - jit: False - -architecture: - module: models.Edge_Network - class: Edge_Network - args: - input_dim_nodes: 7 - input_dim_edges: 3 - input_dim_globals: 1 - hid_size: 64 - n_layers: 4 - n_proc_steps: 4 - out_dim: 1 - -paths: - data_dir: /global/cfs/projectdirs/atlas/joshua/ttHCP/ntuples/v02/preselection/merged_fixed/train/ - save_dir: /pscratch/sd/j/joshuaho/physicsnemo/ttHCP/graphs/tHjb_CP_0_vs_90/ - training_dir: ./tHjb_CP_0_vs_90_edge_network/ - -datasets: - - name: tHjb_cp_0_had - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_0_AF3_had_scaled.root - label: 0 - - name: tHjb_cp_0_lep - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_0_AF3_lep_scaled.root - label: 0 - - name: tHjb_cp_90_had - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_90_AF3_had_scaled.root - label: 1 - - name: tHjb_cp_90_lep - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_90_AF3_lep_scaled.root - label: 1 - -root_dataset: - ttree: output - dtype: torch.bfloat16 - features: - # pt, eta, phi, energy, btag, charge, node_type - jet: [m_jet_pt, m_jet_eta, m_jet_phi, CALC_E, m_jet_PCbtag, 0, 0] - electron: [m_el_pt, m_el_eta, m_el_phi, CALC_E, 0, m_el_charge, 1] - muon: [m_mu_pt, m_mu_eta, m_mu_phi, CALC_E, 0, m_mu_charge, 2] - photon: [ph_pt_myy, ph_eta, ph_phi, CALC_E, 0, 0, 3] - met: [m_met, 0, m_met_phi, CALC_E, 0, 0, 4] - globals: [NUM_NODES] - weights: 1 - tracking: [] - step_size: 16384 - batch_size: 16384 - train_val_test_split: [0.5, 0.25, 0.25] - prebatch: - enabled: True - chunk_size: 512 \ No newline at end of file diff --git a/physicsnemo/configs/tHjb_CP_0_vs_90_globals.yaml b/physicsnemo/configs/tHjb_CP_0_vs_90_globals.yaml deleted file mode 100644 index 546a69e7209db96d5b783eb60d09a0612b13b483..0000000000000000000000000000000000000000 --- a/physicsnemo/configs/tHjb_CP_0_vs_90_globals.yaml +++ /dev/null @@ -1,84 +0,0 @@ -# ignore_header_test -# Copyright 2023 Stanford University -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -random_seed: 2 - -scheduler: - lr: 1.E-3 - lr_decay: 1.E-3 - -training: - epochs: 100 - -checkpoints: - ckpt_path: "checkpoints" - ckpt_name: "tHjb_CP_0_vs_90_globals" - -performance: - amp: False - jit: False - -architecture: - base_gnn: - input_dim_nodes: 7 - input_dim_edges: 3 - output_dim: 128 - processor_size: 8 - hidden_dim_node_encoder: 128 - hidden_dim_edge_encoder: 128 - hidden_dim_processor: 128 - hidden_dim_node_decoder: 128 - global_emb_dim: 128 - global_feat_dim: 5 - out_dim: 1 - -paths: - data_dir: /global/cfs/projectdirs/atlas/joshua/ttHCP/ntuples/v02/preselection/merged_fixed/train/ - save_dir: /pscratch/sd/j/joshuaho/physicsnemo/ttHCP/graphs/tHjb_CP_0_vs_90_globals/ - training_dir: ./tHjb_CP_0_vs_90_globals/ - -datasets: - - name: tHjb_cp_0_had - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_0_AF3_had_scaled.root - label: 0 - - name: tHjb_cp_0_lep - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_0_AF3_lep_scaled.root - label: 0 - - name: tHjb_cp_90_had - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_90_AF3_had_scaled.root - label: 1 - - name: tHjb_cp_90_lep - load_path: ${paths.data_dir}/merged_aMCPy8_tHjb125_CP_90_AF3_lep_scaled.root - label: 1 - -root_dataset: - ttree: output - dtype: torch.bfloat16 - features: - # pt, eta, phi, energy, btag, charge, node_type - jet: [m_jet_pt, m_jet_eta, m_jet_phi, CALC_E, m_jet_PCbtag, 0, 0] - electron: [m_el_pt, m_el_eta, m_el_phi, CALC_E, 0, m_el_charge, 1] - muon: [m_mu_pt, m_mu_eta, m_mu_phi, CALC_E, 0, m_mu_charge, 2] - photon: [ph_pt_myy, ph_eta, ph_phi, CALC_E, 0, 0, 3] - met: [m_met, 0, m_met_phi, CALC_E, 0, 0, 4] - globals: [NUM_NODES, eta_H, pt_H, eta_recotop1, pT_recotop1] - weights: 1 - tracking: [] - step_size: 16384 - batch_size: 16384 - train_val_test_split: [0.5, 0.25, 0.25] - prebatch: - enabled: True - chunk_size: 512 \ No newline at end of file diff --git a/physicsnemo/dataset/Dataset.py b/physicsnemo/dataset/Dataset.py deleted file mode 100644 index 107f83e80091a2133ef32f8f8c0b20af1096cd94..0000000000000000000000000000000000000000 --- a/physicsnemo/dataset/Dataset.py +++ /dev/null @@ -1,243 +0,0 @@ -import os -import uproot -import dgl -import torch -import numpy as np -from omegaconf import DictConfig -from typing import List -from concurrent.futures import ProcessPoolExecutor, as_completed -from tqdm import tqdm - -from dataset import GraphBuilder -from dataset import Graphs -from dataset import Normalization - -from dgl.dataloading import GraphDataLoader - -class Dataset: - def __init__( - self, - name: str, - label: int, - load_path: str, - save_path: str, - dtype: torch.dtype, - device: str, - cfg: DictConfig - ): - self.name = name - self.label = label - self.load_path = load_path - self.save_path = save_path - self.dtype = dtype - self.data = None - self.device = device - - self.ttree = cfg.ttree - self.features = cfg.features - self.weights = cfg.weights - self.globals = cfg.globals - self.tracking = cfg.tracking - self.step_size = cfg.step_size - self.batch_size = cfg.batch_size - - self.prebatch = cfg.get('prebatch', {'enabled': False}) - - self.train_val_test_split = cfg.train_val_test_split - assert np.sum(self.train_val_test_split) == 1, "train_val_test_split must sum to 1" - - print(f"initializing dataset {name} with dtype {self.dtype}") - - def get_branches(self) -> List[str]: - node_branches = [ - branches - for particle in self.features.values() - for branches in particle - if isinstance(branches, str) and (branches != "CALC_E" or branches != "NUM_NODES") - ] - global_branches = [x for x in self.globals if isinstance(x, str)] - weight_branch = [self.weights] if isinstance(self.weights, str) else [] - tracking_branches = [x for x in self.tracking if isinstance(x, str)] - label_branch = [self.label] if isinstance(self.label, str) else [] - - return node_branches + global_branches + weight_branch + tracking_branches + label_branch - - def process(self): - branches = self.get_branches() - with uproot.open(f"{self.load_path}:{self.ttree}") as tree: - available_branches = set(tree.keys()) - num_entries = tree.num_entries - - print(f"getting branches: {branches}") - - num_cpus = os.cpu_count() - total_chunks = np.ceil(num_entries / self.step_size) - - with ProcessPoolExecutor(max_workers=num_cpus) as executor: - futures = [] - - with tqdm( - uproot.iterate( - f"{self.load_path}:{self.ttree}", - expressions=[b for b in branches if b in available_branches], - step_size=self.step_size, - library="ak" - ), - desc="loading root file", - total=total_chunks, - position=0, - leave=True - ) as pbar: - - for chunk_id, arrays in enumerate(pbar): - - cfg = GraphBuilder.ChunkConfig( - name=self.name, - label=self.label, - chunk_id=chunk_id, - batch_size=self.batch_size, - arrays=arrays, - features=self.features, - globals=self.globals, - tracking=self.tracking, - weights=self.weights, - branches=branches, - dtype=self.dtype, - save_path=self.save_path, - prebatch = self.prebatch, - ) - - futures.append(executor.submit(GraphBuilder.process_chunk, cfg)) - - for idx, future in enumerate(as_completed(futures)): - try: - future.result() - except Exception as e: - import traceback - print(f"exception in chunk: {idx}") - traceback.print_exception(type(e), e, e.__traceback__) - return - - def load(self): - with uproot.open(f"{self.load_path}:{self.ttree}") as tree: - num_entries = tree.num_entries - total_chunks = int(np.ceil(num_entries / self.step_size)) - - chunk_files = [f"{self.save_path}/{self.name}_{chunk_id:04d}.bin" for chunk_id in range(total_chunks)] - if not all(os.path.exists(f) for f in chunk_files): - print("graphs not found. processing root file...") - self.process() - - graph_tuple_list = [] - - for chunk_id, f in enumerate(chunk_files): - if chunk_id < total_chunks - 1: - if (self.prebatch.enabled): - n_graphs = self.step_size // self.prebatch.chunk_size - else: - n_graphs = self.step_size - else: - if (self.prebatch.enabled): - n_graphs = (num_entries - self.step_size * (total_chunks - 1)) // self.prebatch.chunk_size + 1 - else: - n_graphs = num_entries - self.step_size * (total_chunks - 1) - graph_tuple_list.extend((f, idx) for idx in range(n_graphs)) - - split = self.train_val_test_split - n_total = len(graph_tuple_list) - n_train = int(split[0] * n_total) - n_val = int(split[1] * n_total) - - train_tuples = graph_tuple_list[:n_train] - val_tuples = graph_tuple_list[n_train:n_train + n_val] - test_tuples = graph_tuple_list[n_train + n_val:] - return train_tuples, val_tuples, test_tuples - -class GraphTupleDataset: - def __init__(self, tuple_list, stats): - self.tuple_list = tuple_list - self.stats = stats - self.cache = {} - - def __len__(self): - return len(self.tuple_list) - - def __getitem__(self, idx): - f, graph_idx = self.tuple_list[idx] - if f in self.cache: - g = self.cache[f] - else: - g = Graphs.load_graphs(f) - g.normalize(self.stats) - self.cache[f] = g - return g[graph_idx] - - @staticmethod - def collate_fn(samples): - all_graphs = [] - all_metadata = {} - - # Initialize keys in all_metadata from the first sample - for k in samples[0][1]: - all_metadata[k] = [] - - for graph, metadata in samples: - all_graphs.append(graph) - for k, v in metadata.items(): - all_metadata[k].append(v) - - # Stack or concatenate metadata for each key - for k in all_metadata: - # If v is a tensor, stack or cat as appropriate - # Use torch.cat if v is already [N, ...] (e.g. labels, features) - # Use torch.stack if v is scalar or needs new dimension - try: - all_metadata[k] = torch.cat(all_metadata[k], dim=0) - except Exception: - all_metadata[k] = torch.stack(all_metadata[k], dim=0) - - batched_graph = dgl.batch(all_graphs) - return batched_graph, all_metadata - -def get_dataset(cfg: DictConfig, device): - - all_train = [] - all_val = [] - all_test = [] - - dtype_str = getattr(cfg.root_dataset, "dtype", "torch.float32") - if isinstance(dtype_str, str) and dtype_str.startswith("torch."): - dtype = getattr(torch, dtype_str.split(".")[-1], torch.float32) - else: - dtype = torch.float32 - - for ds in cfg.datasets: - name = ds['name'] - load_path = ds.get('load_path', f"{cfg.paths.data_dir}/{name}.root") - save_path = ds.get('save_path', f"{cfg.paths.save_dir}/") - datastet = Dataset(name, ds.get('label'), load_path, save_path, dtype, device, cfg.root_dataset) - train, val, test = datastet.load() - all_train.extend(train) - all_val.extend(val) - all_test.extend(test) - - stats = Normalization.global_stats(f"{cfg.paths.save_dir}/stats/", dtype=dtype) - - train_dataset = GraphTupleDataset(all_train, stats) - val_dataset = GraphTupleDataset(all_val, stats) - test_dataset = GraphTupleDataset(all_test, stats) - - if (cfg.root_dataset.get('prebatch', False)): - batch_size = cfg.root_dataset.batch_size // cfg.root_dataset.prebatch.chunk_size - collate_fn = GraphTupleDataset.collate_fn - else: - batch_size = cfg.root_dataset.batch_size - collate_fn = None - - train_loader = GraphDataLoader(train_dataset, batch_size=batch_size, shuffle=True, pin_memory=True, num_workers=5, drop_last=False, collate_fn=collate_fn) - val_loader = GraphDataLoader(val_dataset, batch_size=batch_size, shuffle=False, pin_memory=True, num_workers=5, drop_last=False, collate_fn=collate_fn) - test_loader = GraphDataLoader(test_dataset, batch_size=batch_size, shuffle=False, pin_memory=True, num_workers=0, drop_last=False, collate_fn=collate_fn) - - print("all data loaded successfully") - print(f"train: {len(train_dataset)}, val: {len(val_dataset)}, test: {len(test_dataset)}") - return train_loader, val_loader, test_loader \ No newline at end of file diff --git a/physicsnemo/dataset/GraphBuilder.py b/physicsnemo/dataset/GraphBuilder.py deleted file mode 100644 index 2a21f04e58203177d680a9259af19086f28c9489..0000000000000000000000000000000000000000 --- a/physicsnemo/dataset/GraphBuilder.py +++ /dev/null @@ -1,162 +0,0 @@ -import dgl -import torch -import numpy as np -import awkward as ak -from dataclasses import dataclass -from typing import List, Any, Union - -from dataset.Graphs import Graphs, save_graphs -from dataset import Normalization - -@dataclass -class ChunkConfig: - name: str - label: Union[str, int] - chunk_id: int - batch_size: int - arrays: List[Any] - features: List[Any] - globals: List[Any] - weights: Union[str, float] - tracking: List[Any] - branches: List[Any] - dtype: torch.dtype - save_path: str - prebatch: dict - -def process_chunk(cfg: ChunkConfig): - # Collect everything as lists first - graph_list = [] - meta_dict = { - 'globals': [], - 'label': [], - 'weight': [], - 'tracking': [], - 'batch_num_nodes': [], - 'batch_num_edges': [], - } - - for i in range(len(cfg.arrays)): - g, meta = process_single_entry(cfg, i) - graph_list.append(g) - for k in meta_dict: - meta_dict[k].append(meta[k]) - - # Stack all metadata fields into tensors - for k in meta_dict: - meta_dict[k] = torch.stack(meta_dict[k]) - - graphs = Graphs(graphs=graph_list, metadata=meta_dict) - Normalization.save_stats(graphs, f"{cfg.save_path}/stats/{cfg.name}_{cfg.chunk_id:04d}.json") - - if getattr(cfg.prebatch, "enabled", False): - graphs.shuffle() - graphs.batch(cfg.prebatch["chunk_size"]) - - save_graphs(graphs, f"{cfg.save_path}/{cfg.name}_{cfg.chunk_id:04d}.bin") - -def process_single_entry(cfg, i): - # 1) node features - node_features: List[torch.Tensor] = [] - - for particle, branch_list in cfg.features.items(): - feature_tensors: List[torch.Tensor] = [] - for branch in branch_list: - if branch == "CALC_E": - pT = feature_tensors[0] - eta = feature_tensors[1] - val = pT * torch.cosh(eta) - elif isinstance(branch, str): - arr = cfg.arrays[branch][i] - val = torch.from_numpy(ak.to_numpy(arr)).to(cfg.dtype) - else: - length = feature_tensors[0].shape[0] - val = torch.full((length,), float(branch), dtype=cfg.dtype) - feature_tensors.append(val) - - if feature_tensors and feature_tensors[0].numel() > 0: - block = torch.stack(feature_tensors, dim=1) - node_features.append(block) - - node_features = torch.cat(node_features, dim=0) if node_features else torch.empty((0, len(cfg.features)), dtype=cfg.dtype) - - # 2) global features - global_feat_list: List[torch.Tensor] = [] - for b in cfg.globals: - if b == "NUM_NODES": - global_feat_list.append(torch.tensor([len(node_features)], dtype=cfg.dtype)) - else: - arr = cfg.arrays[b][i] - global_feat_list.append(torch.from_numpy(ak.to_numpy(arr)).to(cfg.dtype)) - global_feat = torch.cat(global_feat_list, dim=0) if global_feat_list else torch.zeros((1,), dtype=cfg.dtype) - - # 3) tracking - tracking_list: List[torch.Tensor] = [] - for b in cfg.tracking: - arr = cfg.arrays[b][i] - tracking_list.append(torch.from_numpy(ak.to_numpy(arr)).to(cfg.dtype)) - tracking = torch.cat(tracking_list, dim=0) if tracking_list else torch.zeros((1,), dtype=cfg.dtype) - - # 4) weight - weight = float(cfg.arrays[cfg.weights][i]) if isinstance(cfg.weights, str) else cfg.weights - weight = torch.tensor(weight, dtype=cfg.dtype) - - # 5) label - label = float(cfg.arrays[cfg.label][i]) if isinstance(cfg.label, str) else cfg.label - label = torch.tensor(label, dtype=cfg.dtype) - - # 6) make the DGLGraph - g = make_graph(node_features, dtype=cfg.dtype) - - # 7) batch_num_nodes and batch_num_edges - batch_num_nodes = g.batch_num_nodes() - batch_num_edges = g.batch_num_edges() - - meta = { - 'globals': global_feat, - 'label': label, - 'weight': weight, - 'tracking': tracking, - 'batch_num_nodes': batch_num_nodes, - 'batch_num_edges': batch_num_edges, - } - return g, meta - -src_dst_cache = {} -def get_src_dst(num_nodes): - if num_nodes not in src_dst_cache: - src, dst = torch.meshgrid(torch.arange(num_nodes), torch.arange(num_nodes), indexing='ij') - src_dst_cache[num_nodes] = (src.flatten(), dst.flatten()) - return src_dst_cache[num_nodes] - -@torch.jit.script -def compute_edge_features(eta, phi, src, dst): - deta = eta[src] - eta[dst] - dphi = phi[src] - phi[dst] - dphi = torch.remainder(dphi + np.pi, 2 * np.pi) - np.pi - dR = torch.sqrt(deta ** 2 + dphi ** 2) - edge_features = torch.stack([dR, deta, dphi], dim=1) - return edge_features - -def make_graph(node_features: torch.tensor, dtype=torch.float32): - - num_nodes = node_features.shape[0] - if num_nodes == 0: - g = dgl.graph(([], [])) - g.ndata['features'] = node_features - g.edata['features'] = torch.empty((0, 3), dtype=dtype) - g.globals = torch.tensor([0], dtype=dtype) - return g - - src, dst = get_src_dst(num_nodes) - src = src.flatten() - dst = dst.flatten() - g = dgl.graph((src, dst)) - g.ndata['features'] = node_features - - eta = node_features[:, 1] - phi = node_features[:, 2] - edge_features = compute_edge_features(eta, phi, src, dst) - g.edata['features'] = edge_features - - return g \ No newline at end of file diff --git a/physicsnemo/dataset/Graphs.py b/physicsnemo/dataset/Graphs.py deleted file mode 100644 index bcbd359e240e2a7778581cf7e3c9af3f5b70ab4d..0000000000000000000000000000000000000000 --- a/physicsnemo/dataset/Graphs.py +++ /dev/null @@ -1,88 +0,0 @@ -import dgl -import torch -from dataclasses import dataclass, field -from typing import List, Dict - -@dataclass -class Graphs: - graphs: List[dgl.DGLGraph] - metadata: Dict[str, torch.Tensor] - - def __len__(self): - return len(self.graphs) - - def __getitem__(self, idx): - meta = {k: v[idx] for k, v in self.metadata.items()} - return self.graphs[idx], meta - - def shuffle(self): - idx = torch.randperm(len(self.graphs)) - self.graphs = [self.graphs[i] for i in idx] - for k in self.metadata: - self.metadata[k] = self.metadata[k][idx] - - def batch(self, batch_size, node_feature_dim=None, dtype=None): - """ - In-place batching: after this, self.graphs is a list of batched DGLGraphs, - and self.metadata[k] is a tensor of shape [num_batches, batch_size, ...]. - """ - batched_graphs = [] - batched_meta = {k: [] for k in self.metadata} - N = len(self.graphs) - - # Infer node_feature_dim and dtype if not specified - if node_feature_dim is None and N > 0: - feats = self.graphs[0].ndata['features'] - node_feature_dim = feats.shape[1] if feats.ndim > 1 else 1 - if dtype is None and N > 0: - dtype = self.graphs[0].ndata['features'].dtype - - for start in range(0, N, batch_size): - end = start + batch_size - batch_graphs = self.graphs[start:end] - batch_meta = {k: v[start:end] for k, v in self.metadata.items()} - - # Padding if needed - pad_count = batch_size - len(batch_graphs) - if pad_count > 0: - dummy_graph = dgl.graph(([], [])) - dummy_graph.ndata['features'] = torch.empty((0, node_feature_dim), dtype=dtype) - dummy_graph.edata['features'] = torch.empty((0, 3), dtype=dtype) # assuming 3 edge features - batch_graphs += [dummy_graph] * pad_count - - # Pad metadata with zeros - for k, v in batch_meta.items(): - shape = list(v[0].shape) if len(v) > 0 else [] - pad_tensor = torch.zeros([pad_count] + shape, dtype=v.dtype, device=v.device) - batch_meta[k] = torch.cat([v, pad_tensor], dim=0) - else: - for k, v in batch_meta.items(): - batch_meta[k] = torch.stack(v, dim=0) if isinstance(v, list) else v - - batched_graphs.append(dgl.batch(batch_graphs)) - for k in batched_meta: - batched_meta[k].append(batch_meta[k]) - - # Now stack along a new axis: [num_batches, batch_size, ...] - for k in batched_meta: - self.metadata[k] = torch.stack(batched_meta[k], dim=0) - - self.graphs = batched_graphs - - def normalize(self, stats): - node_mean, node_std, _ = stats['node'] - edge_mean, edge_std, _ = stats['edge'] - for g in self.graphs: - g.ndata['features'] = (g.ndata['features'] - node_mean) / node_std - g.edata['features'] = (g.edata['features'] - edge_mean) / edge_std - -def save_graphs(graphs: Graphs, f: str): - meta_to_save = {k: v for k, v in graphs.metadata.items()} - dgl.save_graphs(f, graphs.graphs, meta_to_save) - -def load_graphs(f: str) -> Graphs: - g, meta = dgl.load_graphs(f) - for k in meta: - if not isinstance(meta[k], torch.Tensor): - meta[k] = torch.stack(meta[k]) - return Graphs(graphs=g, metadata=meta) \ No newline at end of file diff --git a/physicsnemo/dataset/Normalization.py b/physicsnemo/dataset/Normalization.py deleted file mode 100644 index ac168f5f41242af21c1018fc71051cd43f7ba643..0000000000000000000000000000000000000000 --- a/physicsnemo/dataset/Normalization.py +++ /dev/null @@ -1,144 +0,0 @@ -import torch -import json -import os -from dataset.Graphs import Graphs -from typing import List, Dict, Tuple - -def combine_feature_stats(chunks: List[Dict]) -> Tuple[torch.Tensor, torch.Tensor, int]: - """ - Combine mean/std/count from multiple chunks using Welford's algorithm. - Returns combined mean, std, and total count. - """ - n_total = 0 - mean_total = None - M2_total = None - - for chunk in chunks: - n_k = chunk['count'] - if n_k == 0: - continue - - mean_k = torch.tensor(chunk['mean']) - std_k = torch.tensor(chunk['std']) - M2_k = (std_k ** 2) * n_k - - if n_total == 0: - mean_total = mean_k - M2_total = M2_k - n_total = n_k - else: - delta = mean_k - mean_total - N = n_total + n_k - mean_total += delta * (n_k / N) - M2_total += M2_k + (delta ** 2) * (n_total * n_k / N) - n_total = N - - if n_total == 0: - return torch.tensor([]), torch.tensor([]), 0 - - std_total = torch.sqrt(M2_total / n_total) - return mean_total, std_total, n_total - -def global_stats(dirpath: str, dtype: torch.dtype) -> Dict[str, Tuple[torch.Tensor, torch.Tensor, int]]: - """ - Load all JSON stats files in a directory, combine node, edge, and global stats, - and optionally save the combined stats as JSON to `save_path`. - """ - - combined_stats_path = os.path.join(dirpath, "global_stats.json") - - if not os.path.exists(combined_stats_path): - stats_list = [] - for fname in os.listdir(dirpath): - if fname.endswith('.json'): - with open(os.path.join(dirpath, fname), 'r') as f: - stats_list.append(json.load(f)) - - node_stats = [s['node'] for s in stats_list] - edge_stats = [s['edge'] for s in stats_list] - - combined = { - 'node': combine_feature_stats(node_stats), - 'edge': combine_feature_stats(edge_stats), - } - - combined_json = {} - for key, (mean, std, count) in combined.items(): - combined_json[key] = { - 'mean': mean.tolist() if mean.numel() > 0 else [], - 'std': std.tolist() if std.numel() > 0 else [], - 'count': count, - } - - with open(combined_stats_path, 'w') as f: - json.dump(combined_json, f, indent=4) - - with open(combined_stats_path, 'r') as f: - combined_json = json.load(f) - - def to_tensor(d): - mean = torch.tensor(d['mean'], dtype=dtype) if d['mean'] else torch.tensor([], dtype=dtype) - std = torch.tensor(d['std'], dtype=dtype) if d['std'] else torch.tensor([], dtype=dtype) - count = d['count'] - return mean, std, count - - return { - 'node': to_tensor(combined_json['node']), - 'edge': to_tensor(combined_json['edge']), - } - -def compute_stats(feats, eps=1e-6): - mean = feats.mean(dim=0) - if feats.size(0) > 1: - var = ((feats - mean) ** 2).mean(dim=0) - else: - var = torch.zeros_like(mean) - std = torch.sqrt(var) - std = torch.where(std < eps, torch.full_like(std, eps), std) - - return mean, std - -def save_stats(graphs: 'Graphs', filepath: str, categorical_unique_threshold=50): - """ - Compute and save normalization stats (mean, std, counts) for node and edge features. - Categorical features (few unique values) have normalization disabled (mean=0, std=1). - """ - if len(graphs) == 0: - raise ValueError("No graphs to compute stats from.") - - # Node and edge features - all_node_feats = torch.cat([g.ndata['features'] for g, _ in graphs], dim=0) - all_edge_feats = torch.cat([g.edata['features'] for g, _ in graphs], dim=0) - - counts = { - 'node': all_node_feats.size(0), - 'edge': all_edge_feats.size(0), - } - - node_mean, node_std = compute_stats(all_node_feats) - edge_mean, edge_std = compute_stats(all_edge_feats) - - categorical_mask = torch.tensor([ - torch.unique(all_node_feats[:, i]).numel() < categorical_unique_threshold - for i in range(node_mean.size(0)) - ], dtype=torch.bool) - node_mean[categorical_mask] = 0.0 - node_std[categorical_mask] = 1.0 - - stats = { - 'node': { - 'mean': node_mean.tolist(), - 'std': node_std.tolist(), - 'count': counts['node'], - }, - 'edge': { - 'mean': edge_mean.tolist(), - 'std': edge_std.tolist(), - 'count': counts['edge'], - }, - } - - os.makedirs(os.path.dirname(filepath), exist_ok=True) - - with open(filepath, 'w') as f: - json.dump(stats, f, indent=4) \ No newline at end of file diff --git a/physicsnemo/metrics.py b/physicsnemo/metrics.py deleted file mode 100644 index 5393c7a78e4ac9b90580901d2b1ba4a46924277f..0000000000000000000000000000000000000000 --- a/physicsnemo/metrics.py +++ /dev/null @@ -1,110 +0,0 @@ -import torch -import numpy as np -import torch.nn.functional as F - -def bce(input, target, weights=None): - - if input.shape != target.shape: - if input.shape[-1] == 1 and input.shape[:-1] == target.shape: - input = input.squeeze(-1) - elif target.shape[-1] == 1 and target.shape[:-1] == input.shape: - target = target.squeeze(-1) - - loss = F.binary_cross_entropy_with_logits(input, target, reduction='none') - return torch.mean(loss) - -def weighted_bce(input, target, weights=None): - """ - Compute a weighted and label-normalized binary cross entropy (BCE) loss. - - For each unique label in the target tensor, the BCE loss is computed and weighted, - then normalized by the sum of weights for that label. The final loss is the mean - of these per-label normalized losses. - - Args: - input (Tensor): Predicted logits of shape (N, ...). - target (Tensor): Ground truth labels of shape (N, ...), with discrete label values. - weights (Tensor or None): Optional tensor of per-sample weights, same shape as input/target. - - Returns: - Tensor: Scalar tensor representing the normalized weighted BCE loss. - """ - - if input.shape != target.shape: - if input.shape[-1] == 1 and input.shape[:-1] == target.shape: - input = input.squeeze(-1) - elif target.shape[-1] == 1 and target.shape[:-1] == input.shape: - target = target.squeeze(-1) - - # Compute per-element BCE loss (no reduction) - loss = F.binary_cross_entropy_with_logits(input, target, reduction='none') - - # If weights not provided, use ones - if weights is None: - weights = torch.ones_like(loss) - - unique_labels = torch.unique(target) - normalized_losses = [] - for label in unique_labels: - label_mask = (target == label) # This will be a bool tensor - # Defensive: make sure mask is bool - if label_mask.dtype != torch.bool: - label_mask = label_mask.bool() - label_weights = weights[label_mask] - label_losses = loss[label_mask] - weight_sum = label_weights.sum() - if weight_sum > 0: - label_loss = (label_weights * label_losses).sum() / weight_sum - normalized_losses.append(label_loss) - - if normalized_losses: - return torch.stack(normalized_losses).mean() - else: - return torch.tensor(0.0, device=input.device) - - -def roc_auc_score(classes : np.ndarray, - predictions : np.ndarray, - weights : np.ndarray = None) -> float: - """ - Calculating ROC AUC score as the probability of correct ordering - """ - - if weights is None: - weights = np.ones_like(predictions) - - assert len(classes) == len(predictions) == len(weights) - assert classes.ndim == predictions.ndim == weights.ndim == 1 - class0, class1 = sorted(np.unique(classes)) - - data = np.empty( - shape=len(classes), - dtype=[('c', classes.dtype), - ('p', predictions.dtype), - ('w', weights.dtype)] - ) - data['c'], data['p'], data['w'] = classes, predictions, weights - - data = data[np.argsort(data['c'])] - data = data[np.argsort(data['p'], kind='mergesort')] # here we're relying on stability as we need class orders preserved - - correction = 0. - # mask1 - bool mask to highlight collision areas - # mask2 - bool mask with collision areas' start points - mask1 = np.empty(len(data), dtype=bool) - mask2 = np.empty(len(data), dtype=bool) - mask1[0] = mask2[-1] = False - mask1[1:] = data['p'][1:] == data['p'][:-1] - if mask1.any(): - mask2[:-1] = ~mask1[:-1] & mask1[1:] - mask1[:-1] |= mask1[1:] - ids, = mask2.nonzero() - correction = sum([((dsplit['c'] == class0) * dsplit['w'] * msplit).sum() * - ((dsplit['c'] == class1) * dsplit['w'] * msplit).sum() - for dsplit, msplit in zip(np.split(data, ids), np.split(mask1, ids))]) * 0.5 - - weights_0 = data['w'] * (data['c'] == class0) - weights_1 = data['w'] * (data['c'] == class1) - cumsum_0 = weights_0.cumsum() - - return ((cumsum_0 * weights_1).sum() - correction) / (weights_1.sum() * cumsum_0[-1]) diff --git a/physicsnemo/models/Edge_Network.py b/physicsnemo/models/Edge_Network.py deleted file mode 100644 index e7cf7591fa03375552f31a3978c2fa91cf1780e7..0000000000000000000000000000000000000000 --- a/physicsnemo/models/Edge_Network.py +++ /dev/null @@ -1,72 +0,0 @@ -import torch -import torch.nn as nn -import dgl - -from models import utils - -class Edge_Network(nn.Module): - def __init__(self, cfg): - super().__init__() - hid_size = cfg.hid_size - n_layers = cfg.n_layers - self.n_proc_steps = cfg.n_proc_steps - - #encoder - self.node_encoder = utils.Make_MLP(cfg.input_dim_nodes, hid_size, hid_size, n_layers) - self.edge_encoder = utils.Make_MLP(cfg.input_dim_edges, hid_size, hid_size, n_layers) - self.global_encoder = utils.Make_MLP(cfg.input_dim_globals, hid_size, hid_size, n_layers) - - #GNN - self.node_update = utils.Make_MLP(3*hid_size, hid_size, hid_size, n_layers) - self.edge_update = utils.Make_MLP(4*hid_size, hid_size, hid_size, n_layers) - self.global_update = utils.Make_MLP(3*hid_size, hid_size, hid_size, n_layers) - - #decoder - self.global_decoder = utils.Make_MLP(hid_size, hid_size, hid_size, n_layers) - self.classify = nn.Linear(hid_size, cfg.out_dim) - - def forward(self, node_feats, edge_feats, global_feats, batched_graph, metadata={}): - # encoders - batched_graph.ndata['h'] = self.node_encoder(node_feats) - batched_graph.edata['e'] = self.edge_encoder(edge_feats) - - if global_feats.ndim == 3: - global_feats = global_feats.view(-1, global_feats.shape[-1]) - h_global = self.global_encoder(global_feats) - - # message passing - for _ in range(self.n_proc_steps): - batched_graph.apply_edges(dgl.function.copy_u('h', 'm_u')) - batched_graph.apply_edges(utils.copy_v) - - # edge update - edge_inputs = torch.cat([ - batched_graph.edata['e'], - batched_graph.edata['m_u'], - batched_graph.edata['m_v'], - utils.broadcast_global_to_edges(h_global, edge_split=metadata.get("batch_num_edges", None)) - ], dim=1) - batched_graph.edata['e'] = self.edge_update(edge_inputs) - - # node update - batched_graph.update_all(dgl.function.copy_e('e', 'm'), dgl.function.sum('m', 'h_e')) - node_inputs = torch.cat([ - batched_graph.ndata['h'], - batched_graph.ndata['h_e'], - utils.broadcast_global_to_nodes(h_global, node_split=metadata.get("batch_num_nodes", None)) - ], dim=1) - batched_graph.ndata['h'] = self.node_update(node_inputs) - - # global update - graph_node_feat = utils.mean_nodes( - batched_graph, 'h', node_split=metadata.get("batch_num_nodes", None) - ) - graph_edge_feat = utils.mean_edges( - batched_graph, 'e', edge_split=metadata.get("batch_num_edges", None) - ) - h_global = self.global_update(torch.cat([h_global, graph_node_feat, graph_edge_feat], dim=1)) - - h_global = self.global_decoder(h_global) - out = self.classify(h_global) - return out - diff --git a/physicsnemo/models/MeshGraphNet.py b/physicsnemo/models/MeshGraphNet.py deleted file mode 100644 index c20cd3813f1373900f4fdaab25e6b0964a678daf..0000000000000000000000000000000000000000 --- a/physicsnemo/models/MeshGraphNet.py +++ /dev/null @@ -1,51 +0,0 @@ -import torch -import torch.nn as nn -import dgl - -from models import utils - -# Import the PhysicsNemo MeshGraphNet model -from physicsnemo.models.meshgraphnet import MeshGraphNet as PhysicsNemoMeshGraphNet - -class MeshGraphNet(nn.Module): - def __init__(self, cfg): - super().__init__() - base_gnn_cfg = cfg.base_gnn - self.base_gnn = PhysicsNemoMeshGraphNet(**base_gnn_cfg) - - self.global_mlp = nn.Sequential( - nn.Linear(cfg.global_feat_dim, cfg.global_emb_dim), - nn.ReLU(), - ) - - self.mlp = nn.Linear( - base_gnn_cfg['output_dim'] + base_gnn_cfg['input_dim_edges'] + cfg.global_emb_dim, - cfg.out_dim - ) - - def forward(self, node_feats, edge_feats, global_feats, batched_graph, metadata={}): - """ - node_feats: [total_num_nodes, node_feat_dim] - edge_feats: [total_num_edges, edge_feat_dim] - global_feats: [num_graphs, global_feat_dim] - batched_graph: DGLGraph, representing the collection of graphs in a batch - metadata: dict, may contain 'batch_num_nodes', 'batch_num_edges', etc. - Returns: - graph_pred: [num_graphs, out_dim] - """ - node_pred = self.base_gnn(node_feats, edge_feats, batched_graph) - batched_graph.ndata['h'] = node_pred - batched_graph.edata['e'] = edge_feats - - graph_node_feat = utils.mean_nodes(batched_graph, 'h', node_split=metadata.get("batch_num_nodes", None)) - graph_edge_feat = utils.mean_edges(batched_graph, 'e', edge_split=metadata.get("batch_num_edges", None)) - - # Flatten global_feats if needed - if global_feats.ndim == 3: - global_feats = global_feats.view(-1, global_feats.shape[-1]) - global_emb = self.global_mlp(global_feats) # [num_graphs, global_emb_dim] - - combined_feat = torch.cat([graph_node_feat, graph_edge_feat, global_emb], dim=-1) - graph_pred = self.mlp(combined_feat) - return graph_pred - diff --git a/physicsnemo/models/utils.py b/physicsnemo/models/utils.py deleted file mode 100644 index 2823e5397f5a518836351106cbbc9fa884338d4e..0000000000000000000000000000000000000000 --- a/physicsnemo/models/utils.py +++ /dev/null @@ -1,135 +0,0 @@ -import torch -import torch.nn as nn -import dgl - -def mean_nodes(batched_graph, feat_key='h', op='mean', node_split=None): - """ - Aggregates node features per disjoint graph in a batched DGLGraph. - - Args: - batched_graph: DGLGraph - feat_key: str, node feature key - op: 'mean', 'sum', or 'max' - node_split: 1D tensor or list of ints (num nodes per graph) - - Returns: - Tensor of shape [num_graphs, node_feat_dim] - """ - h = batched_graph.ndata[feat_key] - if node_split is None or len(node_split) == 0: - if op == 'mean': - return dgl.mean_nodes(batched_graph, feat_key) - elif op == 'sum': - return dgl.sum_nodes(batched_graph, feat_key) - elif op == 'max': - return dgl.max_nodes(batched_graph, feat_key) - else: - raise ValueError(f"Unknown op: {op}") - else: - # Ensure node_split is a flat list of ints - if isinstance(node_split, torch.Tensor): - splits = node_split.view(-1).tolist() - else: - splits = [int(x) for x in node_split] - chunks = torch.split(h, splits, dim=0) - if op == 'mean': - out = torch.stack([chunk.mean(0) if chunk.shape[0] > 0 else torch.zeros_like(h[0]) for chunk in chunks]) - elif op == 'sum': - out = torch.stack([chunk.sum(0) if chunk.shape[0] > 0 else torch.zeros_like(h[0]) for chunk in chunks]) - elif op == 'max': - out = torch.stack([chunk.max(0).values if chunk.shape[0] > 0 else torch.zeros_like(h[0]) for chunk in chunks]) - else: - raise ValueError(f"Unknown op: {op}") - return out - -def mean_edges(batched_graph, feat_key='e', op='mean', edge_split=None): - """ - Aggregates edge features per disjoint graph in a batched DGLGraph. - - Args: - batched_graph: DGLGraph - feat_key: str, edge feature key - op: 'mean', 'sum', or 'max' - edge_split: 1D tensor or list of ints (num edges per graph) - - Returns: - Tensor of shape [num_graphs, edge_feat_dim] - """ - e = batched_graph.edata[feat_key] - if edge_split is None or len(edge_split) == 0: - if op == 'mean': - return dgl.mean_edges(batched_graph, feat_key) - elif op == 'sum': - return dgl.sum_edges(batched_graph, feat_key) - elif op == 'max': - return dgl.max_edges(batched_graph, feat_key) - else: - raise ValueError(f"Unknown op: {op}") - else: - # Ensure edge_split is a flat list of ints - if isinstance(edge_split, torch.Tensor): - splits = edge_split.view(-1).tolist() - else: - splits = [int(x) for x in edge_split] - chunks = torch.split(e, splits, dim=0) - if op == 'mean': - out = torch.stack([chunk.mean(0) if chunk.shape[0] > 0 else torch.zeros_like(e[0]) for chunk in chunks]) - elif op == 'sum': - out = torch.stack([chunk.sum(0) if chunk.shape[0] > 0 else torch.zeros_like(e[0]) for chunk in chunks]) - elif op == 'max': - out = torch.stack([chunk.max(0).values if chunk.shape[0] > 0 else torch.zeros_like(e[0]) for chunk in chunks]) - else: - raise ValueError(f"Unknown op: {op}") - return out - -def Make_SLP(in_size, out_size, activation = nn.ReLU, dropout = 0): - layers = [] - layers.append(nn.Linear(in_size, out_size)) - layers.append(activation()) - layers.append(nn.Dropout(dropout)) - return layers - -def Make_MLP(in_size, hid_size, out_size, n_layers, activation = nn.ReLU, dropout = 0): - layers = [] - if n_layers > 1: - layers += Make_SLP(in_size, hid_size, activation, dropout) - for i in range(n_layers-2): - layers += Make_SLP(hid_size, hid_size, activation, dropout) - layers += Make_SLP(hid_size, out_size, activation, dropout) - else: - layers += Make_SLP(in_size, out_size, activation, dropout) - layers.append(torch.nn.LayerNorm(out_size)) - return nn.Sequential(*layers) - -def broadcast_global_to_nodes(globals, node_split): - """ - globals: [num_graphs, global_dim] - node_split: list/1D tensor of length num_graphs, number of nodes per graph - Returns: [total_num_nodes, global_dim] - """ - if node_split is None: - raise ValueError("node_split must be provided") - if not torch.is_tensor(node_split): - node_split = torch.tensor(node_split, dtype=torch.long, device=globals.device) - else: - node_split = node_split.to(device=globals.device, dtype=torch.long) - node_split = node_split.flatten() - return torch.repeat_interleave(globals, node_split, dim=0) - -def broadcast_global_to_edges(globals, edge_split): - """ - globals: [num_graphs, global_dim] (on CUDA or CPU) - edge_split: list/1D tensor of length num_graphs, number of edges per graph (CPU or CUDA) - Returns: [total_num_edges, global_dim] - """ - if edge_split is None: - raise ValueError("edge_split must be provided") - if not torch.is_tensor(edge_split): - edge_split = torch.tensor(edge_split, dtype=torch.long, device=globals.device) - else: - edge_split = edge_split.to(device=globals.device, dtype=torch.long) - edge_split = edge_split.flatten() - return torch.repeat_interleave(globals, edge_split, dim=0) - -def copy_v(edges): - return {'m_v': edges.dst['h']} \ No newline at end of file diff --git a/physicsnemo/setup/Dockerfile b/physicsnemo/setup/Dockerfile deleted file mode 100755 index 89cf6d2f530e3a8c186e82c43f22e3f428f4a65f..0000000000000000000000000000000000000000 --- a/physicsnemo/setup/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -FROM nvcr.io/nvidia/physicsnemo/physicsnemo:25.06 - -WORKDIR /global/cfs/projectdirs/atlas/joshua/GNN4Colliders - -LABEL maintainer.name="Joshua Ho" -LABEL maintainer.email="ho22joshua@berkeley.edu" - -ENV LANG=C.UTF-8 - -# Install system dependencies: vim, OpenMPI, and build tools -RUN apt-get update -qq \ - && apt-get install -y --no-install-recommends \ - wget lsb-release gnupg software-properties-common \ - vim \ - g++-11 gcc-11 libstdc++-11-dev \ - openmpi-bin openmpi-common libopenmpi-dev \ - && rm -rf /var/lib/apt/lists/* - -# Install Python packages: mpi4py and jupyter -RUN pip install --no-cache-dir mpi4py jupyter uproot - -# (Optional) Expose Jupyter port -EXPOSE 8888 diff --git a/physicsnemo/setup/build_image.sh b/physicsnemo/setup/build_image.sh deleted file mode 100755 index f9d1ecbb9bda5da752e97ed025f51d454ea6566b..0000000000000000000000000000000000000000 --- a/physicsnemo/setup/build_image.sh +++ /dev/null @@ -1,4 +0,0 @@ -tag=$1 -echo $tag -podman-hpc build -t joshuaho/nemo:$tag --platform linux/amd64 . -podman-hpc migrate joshuaho/nemo:$tag diff --git a/physicsnemo/train.py b/physicsnemo/train.py deleted file mode 100644 index 0801dd4bff1b49aa0fa2561ea9187f8d096495bd..0000000000000000000000000000000000000000 --- a/physicsnemo/train.py +++ /dev/null @@ -1,246 +0,0 @@ -import time, os - -start = time.time() -import torch -from torch.nn.parallel import DistributedDataParallel -from dgl.dataloading import GraphDataLoader -from torch.amp import GradScaler -import numpy as np -import hydra -from omegaconf import DictConfig -from physicsnemo.launch.logging import ( - PythonLogger, - RankZeroLoggingWrapper, -) -from physicsnemo.launch.utils import load_checkpoint, save_checkpoint -from physicsnemo.distributed.manager import DistributedManager - -import json -from tqdm import tqdm -import random - -import models.MeshGraphNet as MeshGraphNet -from dataset.Dataset import get_dataset -import metrics - -import utils - -class MGNTrainer: - def __init__(self, logger, cfg, dist): - # set device - self.device = dist.device - logger.info(f"Using {self.device} device") - - start = time.time() - self.trainloader, self.valloader, self.testloader = get_dataset(cfg, self.device) - print(f"total time loading dataset: {time.time() - start:.2f} seconds") - - dtype_str = getattr(cfg.root_dataset, "dtype", "torch.float32") - if isinstance(dtype_str, str) and dtype_str.startswith("torch."): - self.dtype = getattr(torch, dtype_str.split(".")[-1], torch.float32) - else: - self.dtype = torch.float32 - - self.model = utils.build_from_module(cfg.architecture) - self.model = self.model.to(dtype=self.dtype, device=self.device) - # num_params = sum(p.numel() for p in self.model.parameters() if p.requires_grad) - # print(f"Number of trainable parameters: {num_params}") - - if cfg.performance.jit: - self.model = torch.jit.script(self.model).to(self.device) - else: - self.model = self.model.to(self.device) - - # instantiate loss, optimizer, and scheduler - self.optimizer = torch.optim.Adam(self.model.parameters(), lr=cfg.scheduler.lr) - self.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( - self.optimizer, - T_max=cfg.training.epochs, - eta_min=cfg.scheduler.lr * cfg.scheduler.lr_decay, - ) - self.scaler = GradScaler('cuda') - - # load checkpoint - self.epoch_init = load_checkpoint( - os.path.join(cfg.checkpoints.ckpt_path, cfg.checkpoints.ckpt_name), - models=self.model, - optimizer=self.optimizer, - scheduler=self.scheduler, - scaler=self.scaler, - device=self.device, - ) - - self.cfg = cfg - - def backward(self, loss): - """ - Perform backward pass. - - Arguments: - loss: loss value. - - """ - # backward pass - if self.cfg.performance.amp: - self.scaler.scale(loss).backward() - self.scaler.step(self.optimizer) - self.scaler.update() - else: - loss.backward() - self.optimizer.step() - - def train(self, graph, metadata): - """ - Perform one training iteration over one graph. The training is performed - over multiple timesteps, where the number of timesteps is specified in - the 'stride' parameter. - - Arguments: - graph: the desired graph. - - Returns: - loss: loss value. - - """ - graph = graph.to(self.device, non_blocking=True) - globals = metadata['globals'].to(self.device, non_blocking=True) - label = metadata['label'].to(self.device, non_blocking=True) - weight = metadata['weight'].to(self.device, non_blocking=True) - - self.optimizer.zero_grad() - pred = self.model(graph.ndata["features"], graph.edata["features"], globals, graph, metadata) - loss = metrics.weighted_bce(pred, label, weights=weight) - self.backward(loss) - return loss.detach() - - @torch.no_grad() - def eval(self): - """ - Evaluate the model on one batch. - - Args: - graph (DGLGraph): The input graph. - label (Tensor): The target labels. - - Returns: - loss (Tensor): The computed loss value (scalar). - """ - predictions = [] - labels = [] - weights = [] - - for graph, metadata in self.valloader: - - graph = graph.to(self.device, non_blocking=True) - globals = metadata['globals'].to(self.device, non_blocking=True) - label = metadata['label'].to(self.device, non_blocking=True) - weight = metadata['weight'].to(self.device, non_blocking=True) - - pred = self.model(graph.ndata["features"], graph.edata["features"], globals, graph, metadata) - predictions.append(pred) - labels.append(label) - weights.append(weight) - - predictions = torch.cat(predictions, dim=0) - labels = torch.cat(labels, dim=0) - weights = torch.cat(weights, dim=0) - - loss = metrics.weighted_bce(predictions, labels, weights=weights) - - # Convert logits to probabilities - prob = torch.sigmoid(predictions) - - # Flatten to 1D arrays - prob_flat = prob.detach().to(torch.float32).cpu().numpy().flatten() - labels_flat = labels.detach().to(torch.float32).cpu().numpy().flatten() - - # Calculate AUC - try: - auc = metrics.roc_auc_score(labels_flat, prob_flat) - except ValueError: - auc = float('nan') # Not enough classes present for AUC - - return loss, auc - -@hydra.main(version_base=None, config_path="./configs/", config_name="tHjb_CP_0_vs_45") -def do_training(cfg: DictConfig): - """ - Perform training over all graphs in the dataset. - - Arguments: - cfg: Dictionary of parameters. - - """ - random.seed(cfg.random_seed) - np.random.seed(cfg.random_seed) - torch.manual_seed(cfg.random_seed) - - # initialize distributed manager - DistributedManager.initialize() - dist = DistributedManager() - - # initialize loggers - os.makedirs(cfg.checkpoints.ckpt_path, exist_ok=True) - logger = PythonLogger("main") - logger.file_logging(os.path.join(cfg.checkpoints.ckpt_path, "train.log")) - - # initialize trainer - trainer = MGNTrainer(logger, cfg, dist) - - if dist.distributed: - ddps = torch.cuda.Stream() - with torch.cuda.stream(ddps): - trainer.model = DistributedDataParallel( - trainer.model, - device_ids=[dist.local_rank], # Set the device_id to be - # the local rank of this process on - # this node - output_device=dist.device, - broadcast_buffers=dist.broadcast_buffers, - find_unused_parameters=dist.find_unused_parameters, - ) - torch.cuda.current_stream().wait_stream(ddps) - - # training loop - start = time.time() - logger.info("Training started...") - for epoch in range(trainer.epoch_init, cfg.training.epochs): - - # Training - train_loss = [] - for graph, metadata in tqdm(trainer.trainloader, desc=f"epoch {epoch} trianing"): - trainer.model.train() - loss = trainer.train(graph, metadata) - train_loss.append(loss.item()) - - val_loss, val_auc = trainer.eval() - - train_loss = torch.tensor(train_loss).mean() - - logger.info( - f"epoch: {epoch}, loss: {train_loss:10.3e}, val_loss: {val_loss:10.3e}, val_auc = {val_auc:10.3e}, time per epoch: {(time.time()-start):10.3e}" - ) - - # save checkpoint - save_checkpoint( - os.path.join(cfg.checkpoints.ckpt_path, cfg.checkpoints.ckpt_name), - models=trainer.model, - optimizer=trainer.optimizer, - scheduler=trainer.scheduler, - scaler=trainer.scaler, - epoch=epoch, - ) - start = time.time() - trainer.scheduler.step() - logger.info("Training completed!") - - -""" - Perform training over all graphs in the dataset. - - Arguments: - cfg: Dictionary of parameters. - - """ -if __name__ == "__main__": - do_training() \ No newline at end of file diff --git a/physicsnemo/utils.py b/physicsnemo/utils.py deleted file mode 100644 index bbbdb423dd993b19ca69a3f5c648ad2bd49b46c9..0000000000000000000000000000000000000000 --- a/physicsnemo/utils.py +++ /dev/null @@ -1,11 +0,0 @@ -import importlib -from types import SimpleNamespace - -def build_from_module(cfg): - modname = cfg['module'] - classname = cfg['class'] - args = cfg['args'] - module = importlib.import_module(modname) - model_cls = getattr(module, classname) - cfg_obj = SimpleNamespace(**args) - return model_cls(cfg_obj) \ No newline at end of file diff --git a/root_gnn_dgl/.codex/skills/root-gnn-dgl-data-preparation/SKILL.md b/root_gnn_dgl/.codex/skills/root-gnn-dgl-data-preparation/SKILL.md deleted file mode 100644 index 6e959b2d9e859d3217105766c26904c93b07359d..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/.codex/skills/root-gnn-dgl-data-preparation/SKILL.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -name: root-gnn-dgl-data-preparation -description: Use when the user asks to build graphs or prebatched .bin files, rerun failed data prep, verify missing graph chunks, or use scripts/prep_data.py, scripts/check_dataset_files.py, or jobs/prep_data/prep_data.sh before training in root_gnn_dgl. ---- - -# root-gnn-dgl-data-preparation - -Use this skill for graph creation and graph-readiness checks before training. - -## Primary entry point - -Run from the repo root: - -```bash -python scripts/prep_data.py --config --dataset --chunk -``` - -Use `--shuffle_mode` when you want preshuffled, prebatched graph files for training: - -```bash -python scripts/prep_data.py --config --dataset --shuffle_mode --chunk -``` - -## Recommended run pattern - -- Read dataset names from `config["Datasets"]`. -- Read the chunk count from each dataset's `args.chunks`. -- When matching the repo's own wrappers, run chunk `0` once before the full loop. Both `run_demo.sh` and `jobs/prep_data/prep_data.sh` do this. - -Example pattern: - -```bash -python scripts/prep_data.py --config configs/stats_100K/pretraining_multiclass.yaml --dataset ttH --shuffle_mode --chunk 0 -for i in 0 1 2; do - python scripts/prep_data.py --config configs/stats_100K/pretraining_multiclass.yaml --dataset ttH --shuffle_mode --chunk "$i" -done -``` - -Use the repo wrapper when you want the standard loop: - -```bash -bash jobs/prep_data/prep_data.sh [extra_args] -``` - -## Important flags and caveats - -- `--shuffle_mode` creates the prebatched artifacts consumed by `scripts/training_script.py --preshuffle`. -- `--drop_last` is inverted by the CLI definition: passing the flag sets `drop_last=False`. -- Dataset configs can override training batch size during prebatching with a dataset-level `batch_size`. -- The README says a `list index out of range` after graph saving is currently expected in some prep runs. Treat it as non-fatal if the output `.bin` files were written successfully. - -## Dataset selections - -Datasets may define event selections at the dataset level: - -```yaml -Datasets: - signal: - args: - ... - selections: - - [n_jets, 4, ">="] - - "met_met_NOSYS > 30000" -``` - -Selection behavior: - -- Selections are applied during data prep before graph chunking. -- `scripts/prep_data.py` prints a cutflow for each dataset before processing. -- Tuple/list selections use `[branch, cut, op]`, where `op` can be `>`, `>=`, `<`, `<=`, `==`, or `!=`. -- String selections are evaluated against loaded ROOT branches, so referenced branch names must exist. -- Selection branches are added automatically to the branch list through `selection_branches()`. -- Empty or omitted `selections` means all events pass. -- If a selection references vector branches, verify the result is one boolean per event; jagged per-object masks will not index event arrays correctly. - -## Audit the outputs - -Run from the repo root: - -```bash -python scripts/check_dataset_files.py --configs stats_100K/pretraining_multiclass.yaml -``` - -The `--configs` argument must be a comma-separated list of paths relative to `configs/`. - -This checker validates: - -- chunk files named `${dataset}_${chunk}.bin` -- prebatched fold files named `${dataset}_prebatched_padded_${i}_n_${n_folds}_f_${foldlist}.bin` - -Use rerun mode to repair missing artifacts: - -```bash -python scripts/check_dataset_files.py --configs stats_100K/pretraining_multiclass.yaml --rerun -``` - -For bulk prep over every dataset in one or more configs, use: - -```bash -python jobs/prep_data/run_processing.py configs/run_3_ttH/scratch.yaml configs/run_3_ttH/finetuning.yaml -``` - -This calls `jobs/prep_data/prep_data.sh` for each dataset using the dataset-level `shuffle_chunks` value. - -Treat data prep as ready only if: - -- every required chunk file exists -- every required prebatched fold file exists when training will use `--preshuffle` -- save paths match the config -- any post-save `IndexError` did not prevent the files from being written diff --git a/root_gnn_dgl/.codex/skills/root-gnn-dgl-env-setup/SKILL.md b/root_gnn_dgl/.codex/skills/root-gnn-dgl-env-setup/SKILL.md deleted file mode 100644 index 019d6834098b8dd05141b02591c50dac6f017d84..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/.codex/skills/root-gnn-dgl-env-setup/SKILL.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -name: root-gnn-dgl-env-setup -description: Use when the user asks to set up or validate the root_gnn_dgl runtime, such as running conda setup from setup/environment.yml, setup/test_setup.py, import ROOT checks, podman-hpc image setup, or the interactive allocation scripts in jobs/ before data prep, training, or inference. ---- - -# root-gnn-dgl-env-setup - -Use this skill from the repo root before any stage run. - -## Choose the runtime - -- Use the conda environment in `setup/environment.yml` for `scripts/inference.py`. The repo README says inference needs PyROOT, and the podman image does not include ROOT. -- Use the `podman-hpc` image `joshuaho/pytorch:1.0` for training on Perlmutter when you want the containerized path. -- For parallel inference, make sure `mpi4py` is available. The README notes it is not listed in the conda environment requirements; `setup/Dockerfile` installs it in the container image. - -## Conda path - -```bash -cd setup -conda env create -f environment.yml -conda activate pytorch -cd .. -python setup/test_setup.py -python -c "import ROOT" -``` - -Run `setup/test_setup.py` from the repo root. It appends the current working directory to `sys.path` and checks imports in `scripts`, `root_gnn_base`, and `models`. - -## Podman path - -```bash -podman-hpc pull docker.io/joshuaho/pytorch:1.0 -``` - -Or build locally: - -```bash -cd setup -source build_image.sh -``` - -The helper `setup/launch_image.sh` mounts `/pscratch/sd/j/joshuaho/` and `/global/cfs/projectdirs/atlas/joshua/` into the container and then runs the given entrypoint. - -## Interactive allocations - -- `source jobs/interactive.sh` for one shared interactive GPU node. -- `source jobs/cpu.sh` for a CPU allocation that suits large prep loops. -- `source jobs/salloc.sh` for a multi-node GPU allocation. - -## Runtime audit - -- Use `nvidia-smi` before training on login or interactive nodes to confirm memory availability. -- Validate the basic repo imports with `python setup/test_setup.py`. -- Validate PyROOT explicitly with `python -c "import ROOT"`. -- For parallel inference, also validate `python -c "from mpi4py import MPI"`. -- Some repo scripts hard-code NERSC-style paths under `/global/cfs/projectdirs/atlas/joshua/...`. If running elsewhere, fix those paths before assuming the environment is valid. - -Treat environment setup as passing only if: - -- imports succeed -- the chosen runtime matches the stage you plan to run -- required site-specific paths exist -- GPU or CPU resources are actually available for the intended stage diff --git a/root_gnn_dgl/.codex/skills/root-gnn-dgl-inference/SKILL.md b/root_gnn_dgl/.codex/skills/root-gnn-dgl-inference/SKILL.md deleted file mode 100644 index 42705440485124252f0ad018356abd9399c546db..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/.codex/skills/root-gnn-dgl-inference/SKILL.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -name: root-gnn-dgl-inference -description: Use when the user asks to score ROOT files, add GNN score branches, launch MPI inference, or verify inference outputs in root_gnn_dgl, including scripts/inference.py, jobs/inference/run_inference.py, ROOT branch checks, and NPZ or ROOT output audits. ---- - -# root-gnn-dgl-inference - -Use this skill to score ntuples with trained models and verify the outputs. - -## Environment - -- Run inference in an environment with PyROOT available. -- The repo README says the conda environment is required for inference because the podman training image does not include ROOT. - -## Entry point - -Run from the repo root: - -```bash -python scripts/inference.py \ - --target \ - --destination \ - --config \ - --branch_name \ - --chunks 1 \ - --chunkno 0 \ - --write -``` - -## Multi-model inference - -The script accepts multiple configs and multiple branch names in one run: - -```bash -python scripts/inference.py \ - --target \ - --destination \ - --config config_a.yaml config_b.yaml \ - --branch_name score_a score_b \ - --chunks 1 \ - --chunkno 0 \ - --write -``` - -The number of configs and branch names must match. - -## Checkpoint selection - -- With the default `--ckpt -1`, the script selects the best epoch from `training.log` using `--var` and `--mode`. -- Use `--ckpt ` to force a specific checkpoint. -- If `--destination` is omitted, the script writes under `/inference/`. - -## Output modes - -- `--write` creates a new ROOT file and adds score branches. -- Without `--write`, the script saves an `.npz` bundle containing scores, labels, and tracking info. -- Use `--clobber` when reusing an existing destination path. - -## Parallel inference - -Use the generic MPI/local wrapper for many files or many models: - -```bash -mpirun -np python jobs/inference/run_inference.py \ - --sample-config \ - --config-dir \ - --output-dir \ - --write -``` - -Useful variants: - -```bash -python jobs/inference/run_inference.py --target '' --config model.yaml --output-dir scores --write -python jobs/inference/run_inference.py --sample-config samples.yaml --config model_a.yaml model_b.yaml --branch-name score_a score_b --output-dir scores --write -python jobs/inference/run_inference.py --sample-config samples.yaml --config-dir configs/run_3_ttH --output-dir scores --write --test -``` - -Wrapper behavior: - -- `--sample-config` discovers target ROOT files from every dataset's `args.raw_dir` and `args.file_names`. -- `--target` accepts explicit files or glob patterns. -- `--config-dir` discovers model configs from `*.yaml`; `--config` accepts explicit config files. -- Branch names default to each model config's `Training_Name` plus `_score`. -- `--branch-name` may override branch names, but the count must match the config count. -- `--test` prints the planned `scripts/inference.py` commands without running them. -- With MPI, tasks are split by target file across ranks; without MPI it runs serially. -- GPU assignment is local rank modulo 4 through `CUDA_VISIBLE_DEVICES`. - -## Repo-specific behavior - -- The first config's first dataset is used as the template dataset. The script rewrites `raw_dir`, `file_names`, `save_dir`, `chunks`, `process_chunks`, and optionally `tree_name` at runtime. -- Pass `--tree ` if the ROOT tree name differs from the config default. -- Chunked inference writes per-chunk outputs; merging those outputs is a separate step. -- Job wrappers should derive the repo root from their own path; avoid adding hard-coded checkout paths. - -## Audit the outputs - -Start with basic runtime evidence if you have a log: - -- `Writing to file` -- `Input entries:` -- `Output entries:` -- `Wrote scores to` -- absence of `Traceback` - -For ROOT outputs, prefer `uproot`: - -```bash -python - <<'PY' -import numpy as np -import uproot -path = "" -branches = [""] -tree = uproot.open(path)["output"] -print("entries", tree.num_entries) -for branch in branches: - arr = tree[branch].array(library="np") - print(branch, len(arr), np.isnan(arr).sum(), float(np.nanmin(arr)), float(np.nanmax(arr)), float(np.nanmean(arr))) -PY -``` - -Treat inference as valid only if: - -- the destination file exists -- every requested score branch exists -- output entry count matches the input tree -- score arrays contain no NaNs -- score arrays are not constant - -For multi-model inference, every branch must exist and branch statistics should usually differ unless the models are intentionally identical. - -Without `--write`, inspect the `.npz` keys `scores`, `labels`, and `tracking_info` and verify array lengths and NaN counts. diff --git a/root_gnn_dgl/.codex/skills/root-gnn-dgl-plotting/SKILL.md b/root_gnn_dgl/.codex/skills/root-gnn-dgl-plotting/SKILL.md deleted file mode 100644 index de2c79e2e5a0b919d0f4df2f6bb12d53a9183a43..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/.codex/skills/root-gnn-dgl-plotting/SKILL.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -name: root-gnn-dgl-plotting -description: Use when the user asks to plot training curves, regenerate training.png, build the sweep PDF from plotting/training_performance.py, compare training runs, or extract Loss, Accuracy, Test_Loss, Test_AUC, and timing information from training.log files in root_gnn_dgl. ---- - -# root-gnn-dgl-plotting - -Use this skill when the task is about plots or metrics derived from `training.log`. - -## Single-run plot regeneration - -The training script can regenerate the per-run PNG directly: - -```bash -python scripts/training_script.py --config --plot -``` - -That uses `root_gnn_base.utils.read_log()` and `root_gnn_base.utils.plot_log()` to rebuild `training.png` from `Training_Directory/training.log`. - -`plot_log()` produces a 2x2 figure with: - -- cumulative time in seconds -- train and test loss -- accuracy -- test AUC - -Be aware that `plot_log()` fixes the accuracy axis to `(0.44, 0.56)`, which may be too narrow for some runs. - -## Sweep-level plotting - -Use the dedicated plotting script when the user wants a PDF comparing shipped sweeps: - -```bash -python plotting/training_performance.py -python plotting/training_performance.py --output -``` - -The script currently plots two config groups: - -- `pretraining` -- `higgs_production` - -It writes one PDF page per group and resolves each run's `Training_Directory` from its config. - -## What the plotting script reads from training.log - -`plotting/training_performance.py` parses rows that start with `Epoch` and extracts: - -- `Epoch` -- `Loss` -- `Accuracy` -- `Test_Loss` -- `Test_AUC` -- `Time` - -It also computes cumulative time in hours. - -Baseline runs are drawn as lines. Non-baseline sweep variants are drawn as point clouds and labeled by the parameter change relative to the baseline. - -## Audit the log before plotting - -Treat plotting input as valid only if: - -- `training.log` exists -- it contains at least one valid `Epoch ...` row -- parsed metric arrays are finite -- the referenced `Training_Directory` actually exists - -If the plotting script fails, inspect the log directly: - -```bash -sed -n '1,40p' /training.log -tail -n 25 /training.log -``` - -## When to use which plot path - -- Use `--plot` on `scripts/training_script.py` when the user wants the repo's standard per-run `training.png`. -- Use `plotting/training_performance.py` when the user wants a cross-run PDF for the built-in sweep groups. -- If the user wants custom comparisons outside the built-in groups, start from the parsing logic in `plotting/training_performance.py` and the metric schema in `training.log`. diff --git a/root_gnn_dgl/.codex/skills/root-gnn-dgl-training/SKILL.md b/root_gnn_dgl/.codex/skills/root-gnn-dgl-training/SKILL.md deleted file mode 100644 index 167ef8626ae125136731463b028554c2f73812e7..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/.codex/skills/root-gnn-dgl-training/SKILL.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -name: root-gnn-dgl-training -description: Use when the user asks to train, finetune, resume, submit, queue-check, log-check, or validate training runs in root_gnn_dgl, including scripts/training_script.py, sqs, jobs/slurm/.out, training.log, checkpoints, and scripts/generate_multiclass_finetuning_configs.py. ---- - -# root-gnn-dgl-training - -Use this skill for any training stage in the repo, from launch through monitoring and artifact review. - -## Run locally - -Run from the repo root: - -```bash -python scripts/training_script.py --config --preshuffle --nocompile --lazy -``` - -This matches the README, `run_demo.sh`, and the podman job wrappers. - -## Why these defaults - -- `--preshuffle` uses the saved prebatched graph files created during data prep. -- `--nocompile` is recommended by the README because compiled mode requires padded graphs at prep time. -- `--lazy` matches the common dataset classes used by the shipped configs. - -## Common runtime modes - -- `--restart` starts from scratch instead of resuming from the last checkpoint. -- Without `--restart`, the script resumes from the last `model_epoch_.pt` it finds in `Training_Directory`. -- `--evaluate ` skips training and evaluates a specific checkpoint. -- `--plot` regenerates `training.png` from `training.log`. -- `--directory ` appends a suffix to `Training_Directory`. -- `--cpu`, `--multigpu`, `--multinode`, `--statistics`, `--seed`, and `--abs` are available when needed. - -## Run multiple local trainings - -Use the single-node launcher when queueing many config files on the current node: - -```bash -python jobs/training/run_parallel_trainings.py --split -``` - -Useful examples: - -```bash -python jobs/training/run_parallel_trainings.py configs/run_3_ttH --split 2/2 -python jobs/training/run_parallel_trainings.py configs/run_3_ttH --split 2/2 --test -``` - -Launcher behavior: - -- Discovers `.yaml` files from each target directory, or accepts explicit config files. -- Uses fixed local GPU slots `0,1,2,3` via `CUDA_VISIBLE_DEVICES`. -- Runs `scripts/training_script.py --config --preshuffle --nocompile --lazy`. -- Forwards unknown args to `training_script.py`, such as `--restart` or `--seed 7`. -- Rejects configs with duplicate `Training_Directory` values. -- `--split K/N` selects configs by deterministic index modulo `N`; use `--split 1/2` and `--split 2/2` for two complementary halves. -- `--test` prints the launch plan without starting training. -- Logs go under `jobs/slurm/parallel_training_logs//`. - -## Submit on Perlmutter - -Prefer the podman path: - -```bash -sbatch jobs/training/podman/run_job.sh -``` - -The job wrappers derive the repo root from their own location. `jobs/training/podman/submit.sh` and `jobs/training/conda/submit.sh` accept config paths as arguments; without arguments they run their built-in default sweeps. Set `SLURM_ACCOUNT` when the cluster requires an account: - -```bash -SLURM_ACCOUNT=atlas sbatch jobs/training/podman/run_job.sh configs/run_3_ttH/scratch.yaml -bash jobs/training/podman/submit.sh configs/run_3_ttH/scratch.yaml configs/run_3_ttH/finetuning.yaml -``` - -For the conda wrapper, set `ROOT_GNN_CONDA_ENV` if the environment is not named `dgl`. - -For distributed training, pass `--multinode` and launch under an environment that sets `RANK`, `LOCAL_RANK`, and `WORLD_SIZE`. - -## Preconditions - -- If you use `--preshuffle`, run data preparation first and confirm the graph artifacts exist. -- For finetuning configs, verify that `Model.args.pretraining_path` points to an existing checkpoint before launching training. -- For multinode runs, pass `--multinode` and launch under the relevant distributed job environment. - -## Monitor queue and logs - -Check queue state: - -```bash -sqs -u "$USER" -sqs -u "$USER" | rg "" -``` - -Useful interpretations: - -- `PD` means pending -- `R` means running -- `START_TIME N/A` with reason `Priority` means queued normally, not broken - -Once a job has a `JOBID`, inspect: - -```bash -sed -n '1,80p' jobs/slurm/.out -tail -n 80 jobs/slurm/.out -rg -n "Traceback|Error|Exception|Epoch|Epoch Done|Early Termination|Done" jobs/slurm/.out -``` - -Healthy training logs usually show: - -- the `Executing: python -u ... scripts/training_script.py ...` line -- dataset cache loads -- repeated `Epoch ... | LR ... | Loss ... | Accuracy ... | Test_Loss ... | Test_AUC ... | Time ... s` -- `Epoch Done.` -- `Num batches trained = ...` -- valid completion via `Done`, sometimes after `Early Termination at Epoch ...` - -Early stopping is a normal completion mode in this repo. - -## Audit training artifacts - -Training writes into `Training_Directory`: - -- `config.yaml` -- `model_epoch_.pt` -- `model_epoch_.npz` -- `training.log` -- `training.png` - -Primary checks: - -```bash -sed -n '1,40p' /training.log -tail -n 25 /training.log -``` - -Treat the run as healthy only if: - -- epoch numbers increase monotonically -- `Loss`, `Test_Loss`, and `Test_AUC` stay finite -- the latest logged epoch has a matching `model_epoch_.pt` -- the run produced real epoch rows rather than stopping before training started - -If `training.log` grows but checkpoints stop appearing, suspect a save-path or filesystem issue. - -Use `python plotting/training_performance.py` or the `root-gnn-dgl-plotting` skill when you want consolidated sweep-level PDFs instead of a single-run `training.png`. - -## Generate finetuning configs - -Use this when you want to derive `configs/higgs_production/multiclass_finetuning/*.yaml` from completed multiclass pretraining runs: - -```bash -python scripts/generate_multiclass_finetuning_configs.py -``` - -Before using the generated configs, verify that the chosen best-epoch checkpoint paths still exist. diff --git a/root_gnn_dgl/.codex/skills/root-gnn-dgl-workflow/SKILL.md b/root_gnn_dgl/.codex/skills/root-gnn-dgl-workflow/SKILL.md deleted file mode 100644 index 26d40bebf5c1751025c8ad421883e70a6a892b16..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/.codex/skills/root-gnn-dgl-workflow/SKILL.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -name: root-gnn-dgl-workflow -description: Use when the user asks to run or review the full root_gnn_dgl workflow, such as run_demo.sh, a full pretraining-to-finetuning-to-inference campaign, or a stage-by-stage pass, warning, fail audit across environment setup, data preparation, training, inference, and outputs. ---- - -# root-gnn-dgl-workflow - -Use this skill when the user wants an end-to-end workflow rather than a single isolated stage. - -## Shipped demo - -Run from the repo root: - -```bash -source run_demo.sh -``` - -The demo does: - -1. graph prep for multiclass pretraining -2. multiclass pretraining -3. graph prep for binary classification -4. from-scratch binary training -5. finetuned binary training -6. inference with two output score branches - -## Before running the workflow - -- Check GPU availability with `nvidia-smi` or request an interactive node with `jobs/interactive.sh`. -- Confirm the target data and output directories in `run_demo.sh` exist and are writable. -- Confirm `configs/stats_100K/finetuning_ttH_CP_even_vs_odd.yaml` points at the checkpoint you actually want to finetune from. - -## Workflow audit order - -When reviewing a campaign, check stages in this order: - -1. environment readiness -2. data-prep outputs -3. training submission and queue state -4. training logs and checkpoints -5. inference outputs - -Use the retained stage skills for each check: - -- `root-gnn-dgl-env-setup` -- `root-gnn-dgl-data-preparation` -- `root-gnn-dgl-training` -- `root-gnn-dgl-inference` - -## Output style - -Return a short status for each stage: - -- `pass`: evidence is consistent with a healthy stage -- `warning`: stage likely worked but still needs a follow-up check -- `fail`: concrete blocker or corrupted or missing artifact found - -Repo-specific workflow blockers: - -- pending jobs in `sqs` with `Priority` are waiting, not failed -- missing prebatched `.bin` files block `--preshuffle` training -- missing `pretraining_path` blocks finetuning -- ROOT outputs without the requested score branches are inference failures even if the file exists - -## When to adapt instead of sourcing the demo - -- If you only want one stage, call the underlying prep, training, or inference script directly. -- If dataset paths, branch names, or chunk counts differ, copy the command pattern from `run_demo.sh` and adjust the values instead of editing the demo in place. diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/config.yaml b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/config.yaml deleted file mode 100755 index 1370d23875c785ac41bafb8011bb4324f761cca7..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/config.yaml +++ /dev/null @@ -1,319 +0,0 @@ -Datasets: - SingleT_schan: - args: - buffer_size: 11 - chunks: 100 - file_names: SingleT_schan.root - fold_var: Number - label: 8 - name: SingleT_schan - node_branch_names: &id001 - - - jet_pt - - ele_pt - - mu_pt - - ph_pt - - MET_met - - - jet_eta - - ele_eta - - mu_eta - - ph_eta - - 0 - - - jet_phi - - ele_phi - - mu_phi - - ph_phi - - MET_phi - - CALC_E - - - jet_btag - - 0 - - 0 - - 0 - - 0 - - - 0 - - ele_charge - - mu_charge - - 0 - - 0 - - NODE_TYPE - node_branch_types: &id002 - - vector - - vector - - vector - - vector - - single - node_feature_scales: &id003 - - 1e-1 - - 1 - - 1 - - 1e-1 - - 1 - - 1 - - 1 - raw_dir: /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/data/ntuples/Hyy_pretraining/ - save_dir: /pscratch/sd/j/joshuaho/root_gnn/root_gnn_dgl/data/processed_pretraining_multiclass_12_process/ - tree_name: output - weight_var: weight - class: LazyDataset - folding: &id004 - n_folds: 10 - test: - - 0 - - 1 - train: - - 2 - - 3 - - 4 - - 5 - - 6 - - 7 - - 8 - - 9 - module: root_gnn_base.dataset - padding_mode: NONE - shuffle_chunks: 10 - VBF: - args: - buffer_size: 11 - chunks: 100 - file_names: VBF_NLO_inc.root - fold_var: Number - label: 3 - name: VBF - node_branch_names: *id001 - node_branch_types: *id002 - node_feature_scales: *id003 - raw_dir: /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/data/ntuples/Hyy_pretraining/ - save_dir: /pscratch/sd/j/joshuaho/root_gnn/root_gnn_dgl/data/processed_pretraining_multiclass_12_process/ - tree_name: output - weight_var: weight - class: LazyDataset - folding: *id004 - module: root_gnn_base.dataset - padding_mode: NONE - shuffle_chunks: 10 - WH: - args: - buffer_size: 11 - chunks: 100 - file_names: WH_NLO_inc.root - fold_var: Number - label: 4 - name: WH - node_branch_names: *id001 - node_branch_types: *id002 - node_feature_scales: *id003 - raw_dir: /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/data/ntuples/Hyy_pretraining/ - save_dir: /pscratch/sd/j/joshuaho/root_gnn/root_gnn_dgl/data/processed_pretraining_multiclass_12_process/ - tree_name: output - weight_var: weight - class: LazyDataset - folding: *id004 - module: root_gnn_base.dataset - padding_mode: NONE - shuffle_chunks: 10 - ZH: - args: - buffer_size: 11 - chunks: 100 - file_names: ZH_NLO_inc.root - fold_var: Number - label: 5 - name: ZH - node_branch_names: *id001 - node_branch_types: *id002 - node_feature_scales: *id003 - raw_dir: /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/data/ntuples/Hyy_pretraining/ - save_dir: /pscratch/sd/j/joshuaho/root_gnn/root_gnn_dgl/data/processed_pretraining_multiclass_12_process/ - tree_name: output - weight_var: weight - class: LazyDataset - folding: *id004 - module: root_gnn_base.dataset - padding_mode: NONE - shuffle_chunks: 10 - ggF: - args: - buffer_size: 11 - chunks: 100 - file_names: ggF_NLO_inc.root - fold_var: Number - label: 2 - name: ggF - node_branch_names: *id001 - node_branch_types: *id002 - node_feature_scales: *id003 - raw_dir: /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/data/ntuples/Hyy_pretraining/ - save_dir: /pscratch/sd/j/joshuaho/root_gnn/root_gnn_dgl/data/processed_pretraining_multiclass_12_process/ - tree_name: output - weight_var: weight - class: LazyDataset - folding: *id004 - module: root_gnn_base.dataset - padding_mode: NONE - shuffle_chunks: 10 - tHjb: - args: - buffer_size: 11 - chunks: 100 - file_names: tHjb_NLO_inc.root - fold_var: Number - label: 1 - name: tHjb - node_branch_names: *id001 - node_branch_types: *id002 - node_feature_scales: *id003 - raw_dir: /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/data/ntuples/Hyy_pretraining/ - save_dir: /pscratch/sd/j/joshuaho/root_gnn/root_gnn_dgl/data/processed_pretraining_multiclass_12_process/ - tree_name: output - weight_var: weight - class: LazyDataset - folding: *id004 - module: root_gnn_base.dataset - padding_mode: NONE - shuffle_chunks: 10 - ttH: - args: - buffer_size: 11 - chunks: 100 - file_names: ttH_NLO_inc.root - fold_var: Number - label: 0 - name: ttH - node_branch_names: *id001 - node_branch_types: *id002 - node_feature_scales: *id003 - raw_dir: /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/data/ntuples/Hyy_pretraining/ - save_dir: /pscratch/sd/j/joshuaho/root_gnn/root_gnn_dgl/data/processed_pretraining_multiclass_12_process/ - tree_name: output - weight_var: weight - class: LazyDataset - folding: *id004 - module: root_gnn_base.dataset - padding_mode: NONE - shuffle_chunks: 10 - ttW: - args: - buffer_size: 11 - chunks: 100 - file_names: ttW.root - fold_var: Number - label: 10 - name: ttW - node_branch_names: *id001 - node_branch_types: *id002 - node_feature_scales: *id003 - raw_dir: /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/data/ntuples/Hyy_pretraining/ - save_dir: /pscratch/sd/j/joshuaho/root_gnn/root_gnn_dgl/data/processed_pretraining_multiclass_12_process/ - tree_name: output - weight_var: weight - class: LazyDataset - folding: *id004 - module: root_gnn_base.dataset - padding_mode: NONE - shuffle_chunks: 10 - ttbar: - args: - buffer_size: 11 - chunks: 100 - file_names: ttbar.root - fold_var: Number - label: 9 - name: ttbar - node_branch_names: *id001 - node_branch_types: *id002 - node_feature_scales: *id003 - raw_dir: /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/data/ntuples/Hyy_pretraining/ - save_dir: /pscratch/sd/j/joshuaho/root_gnn/root_gnn_dgl/data/processed_pretraining_multiclass_12_process/ - tree_name: output - weight_var: weight - class: LazyDataset - folding: *id004 - module: root_gnn_base.dataset - padding_mode: NONE - shuffle_chunks: 10 - ttt: - args: - buffer_size: 11 - chunks: 100 - file_names: ttt.root - fold_var: Number - label: 11 - name: ttt - node_branch_names: *id001 - node_branch_types: *id002 - node_feature_scales: *id003 - raw_dir: /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/data/ntuples/Hyy_pretraining/ - save_dir: /pscratch/sd/j/joshuaho/root_gnn/root_gnn_dgl/data/processed_pretraining_multiclass_12_process/ - tree_name: output - weight_var: weight - class: LazyDataset - folding: *id004 - module: root_gnn_base.dataset - padding_mode: NONE - shuffle_chunks: 10 - tttt: - args: - buffer_size: 11 - chunks: 100 - file_names: tttt.root - fold_var: Number - label: 7 - name: tttt - node_branch_names: *id001 - node_branch_types: *id002 - node_feature_scales: *id003 - raw_dir: /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/data/ntuples/Hyy_pretraining/ - save_dir: /pscratch/sd/j/joshuaho/root_gnn/root_gnn_dgl/data/processed_pretraining_multiclass_12_process/ - tree_name: output - weight_var: weight - class: LazyDataset - folding: *id004 - module: root_gnn_base.dataset - padding_mode: NONE - shuffle_chunks: 10 - ttyy: - args: - buffer_size: 11 - chunks: 100 - file_names: ttyy.root - fold_var: Number - label: 6 - name: ttyy_ch - node_branch_names: *id001 - node_branch_types: *id002 - node_feature_scales: *id003 - raw_dir: /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/data/ntuples/Hyy_pretraining/ - save_dir: /pscratch/sd/j/joshuaho/root_gnn/root_gnn_dgl/data/processed_pretraining_multiclass_12_process/ - tree_name: output - weight_var: weight - class: LazyDataset - folding: *id004 - module: root_gnn_base.dataset - padding_mode: NONE - shuffle_chunks: 10 -Loss: - args: {} - class: CrossEntropyLoss - finish: - args: - dim: 1 - class: Softmax - module: torch.nn - module: torch.nn -Model: - args: - dropout: 0 - hid_size: 64 - in_size: 7 - n_layers: 4 - n_proc_steps: 4 - out_size: 12 - class: Edge_Network - module: models.GCN -Training: - batch_size: 1024 - epochs: 100 - gamma: 0.99 - learning_rate: 0.0001 -Training_Directory: trainings/pretraining_multiclass/multiclass_12_process/ -Training_Name: multiclass_12_process diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_0.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_0.pt deleted file mode 100755 index 1cccd0def27edb421627fa33e0311c070fa159b7..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_0.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f13357759bae5ee14a4dd682fe867c09381aed0842ed712b0c12770aa621dd44 -size 1707210 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_1.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_1.pt deleted file mode 100755 index 5befaa60c0dd42423084cb15dadaeca4bea39806..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_1.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9617167a01ee1d11ba2ec03f71440bd4fa25f4fa5f32e72bd9d71f5d10cd11b2 -size 1707210 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_10.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_10.pt deleted file mode 100755 index d0915d92261895dd0d872199028d63b81828fad5..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_10.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5224b15282d60c8f09724904e5a665f27426d81ff577b234d901260050cb97e7 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_11.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_11.pt deleted file mode 100755 index 02fa7cc4dca6658e91b43121c5c635f2af496c1c..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_11.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a2fd4704348456e2a6c9655ee3aa2a9143df3f8394ba0d745207d46af139b558 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_12.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_12.pt deleted file mode 100755 index 4412f37037acc10ce2677203010ea18146926d77..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_12.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6960240dabb5128be0a501077ff952a985295885fbcece663282df40bb8d4584 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_13.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_13.pt deleted file mode 100755 index c20dbd992938bb377fbbe8210b0a76e4ff7d7395..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_13.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c11d6492d985d8f46b3476ed13671a3f9295269c0108dc55f491d7ef8270b901 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_14.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_14.pt deleted file mode 100755 index c654dbaf948b3ce058e44fde00cbaaa5a8ce9aeb..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_14.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:15bfd6edcb5cb2d9176683d13c546cdd2115eda320ddbc9a04b23dba8936d989 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_15.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_15.pt deleted file mode 100755 index 91c377c6afa675b4943a102c1c78ff9172600118..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_15.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5697fbccabb743b9c900a9e7f1e432077879fa4f83db42385e8ad1f597844195 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_16.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_16.pt deleted file mode 100755 index 3a90f37534199dcf5163ebaec6b5abcfea5eae2a..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_16.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dc1818c04ee5d17f5cf05e985e69dbabf55e0c1c4c4b7c2cd29939b766350b39 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_17.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_17.pt deleted file mode 100755 index 4e2c83c6b0607758f3281f156cb5fffb172a5082..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_17.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:945575404de1372332c67423b1ea681edd4445e5445a21774d517dec45341c34 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_18.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_18.pt deleted file mode 100755 index 0079811bb18009af693cfd0b3887620cd3e5b2f3..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_18.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7f8e9f611bba22ad5682c44d158de95f76c3dfc2223654a64540f91972c12ed7 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_19.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_19.pt deleted file mode 100755 index b346ae37a0e99786a31bf92e1d057f71cddffe37..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_19.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b1957ba99bf8b1aeb6b5a19a6867433aa86e5658c3abfdb737bc16489ce3d83b -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_2.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_2.pt deleted file mode 100755 index 847b939168c63092237162cab6be265611909ef9..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_2.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:67b72a00c515215745d693f7f62d3a02274c8b702f53d7e68c1b162b0eee44ec -size 1707210 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_20.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_20.pt deleted file mode 100755 index 8a1b493b3d8c0f5058c931fe1935df05d00d5fba..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_20.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:38bd863cfeeb558c586b3c90686de8faf33f08b2675ca93edd4bf8ce63ba62ee -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_21.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_21.pt deleted file mode 100755 index 8d28bfeed081ab54902a1963d5d434d2a00e5511..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_21.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7e90498dffe402581e1e554870b10369c05b45aba7b98a3480422512fbd9832e -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_22.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_22.pt deleted file mode 100755 index c3ee0db50eb8739fc7ea9859c6eaa2ae52d40245..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_22.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a0ea74fb7cfbfa3ebf6908f75fd6d5e018ee307801f608ecdde228d29e666f81 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_23.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_23.pt deleted file mode 100755 index 813ba04d7ff30e13dd9d3bd2a679d697dfd1864f..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_23.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:01d1edadaa1b2ee1a7e7dea46f34c47992c625dac5aa592ce607a75a4aa89170 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_24.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_24.pt deleted file mode 100755 index 42804a503aae74bad3ac797811892b277af5fd0b..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_24.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d8ba9057ffc46f012d10ab5c09c16a441ec4681bff005e61bef33ac928298a0e -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_25.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_25.pt deleted file mode 100755 index 6a4cf8f09e5be383e9be3e61f31495e105a25410..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_25.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1c0b6074ff2fd237eb73612f94b0e9fe4e6ed74522b409cfc326a262edb81739 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_26.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_26.pt deleted file mode 100755 index 57edc95af62a66dc9dc01b6564a819df3090efa9..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_26.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:08c7620306f80b16df74051430adaa6fc4757e15a314eac46a71cf7c8b9f393e -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_27.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_27.pt deleted file mode 100755 index 9e874482a07f16e3ca295e66c5ca7e69b7620d78..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_27.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bd00777e30f340d99367804c520a0a432792cc149fb21299e86c9b9900e4e4de -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_28.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_28.pt deleted file mode 100755 index c5d30bc62a5b16700d34891e63a943cc663ef43b..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_28.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4179f61fcb98c60fd2712cb2e6a1467fc83ddc70331b19b9c720ba81b790dbde -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_29.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_29.pt deleted file mode 100755 index 7a6fcd4c11cb8805aa2f588b4da58c11db637b1f..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_29.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a82de1d53ad4dcde09215da9d94a278d484f58e9ae179c3c12379992ecfc5d86 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_3.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_3.pt deleted file mode 100755 index 4499bf2518ec45be8851885fd1db0d72d653cd40..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_3.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:824dda23baf611b3de75eabf3e85cc09f324957bbc8e5399c8a2f309730557c3 -size 1707210 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_30.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_30.pt deleted file mode 100755 index 52d7a1692695c00be40f2a92a82512d8d51333c2..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_30.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dd872b572b793a5e21c59206c25d655db4784eca3343130f39a6aae729272f3e -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_31.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_31.pt deleted file mode 100755 index 0cfd9fce09e74dd448c160c7160b45adf6896401..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_31.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3b8c20ece0701e7e3a90bb32ab2af634143444662298fdfcc0d3bff5e416320e -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_32.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_32.pt deleted file mode 100755 index cd0d114eab4723e4cff351f7e1a128e710ac4f76..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_32.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2f455a58bfb5a2e4ee9ffeff26b82d88f90ff17d96ee477bbd0870a991cd94a4 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_33.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_33.pt deleted file mode 100755 index fc3050bbeefee6f5fe655c3c5b544e2a6015597a..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_33.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d60d6d9d14dac0b18cb5e360d392e5275eb2ae62879aa153b988372548a739f7 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_34.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_34.pt deleted file mode 100755 index fe6a92f0f81e83ca2ab0202fc0864d0db819654b..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_34.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:180c776909a07ea261e5ee287bb0397a73f3b706622f24b3fc2d7799d118b2d9 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_35.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_35.pt deleted file mode 100755 index 3492a170b324282a80bc7b770effa90f420954c0..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_35.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0526e9b114d77695d87c998cdb296b9ba092562bda1203937b9797c0bfd3f4a0 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_36.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_36.pt deleted file mode 100755 index ef277c920b22722e6142646540a5de83ab16e829..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_36.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2a048e5467642275af1d31472202dafa0fb1d76b9d31dbabf3350594ea6638c5 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_37.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_37.pt deleted file mode 100755 index 82984fc806765a50bd2d69d26b45ce9804bc9c1a..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_37.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:64753f005246efaa7703a3c42dd41af20360290c6964287a804b48263060fb68 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_38.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_38.pt deleted file mode 100755 index 2d309dd0bdc07a3dca23fd2379424779593f06b7..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_38.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:51a5e7081a9794ca9a30d31a3e4d115790f3c002c76d4ec9b6c9151ee30e1959 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_39.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_39.pt deleted file mode 100755 index f7059b32b05acce91f28266e792a3fafebe21325..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_39.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0de00211875e257b7d5fc84eb05bc7d7811fa342127769d8b7b39262cca0efbc -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_4.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_4.pt deleted file mode 100755 index 6d8f3db11967fe0f93539265258666f414d03b38..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_4.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f800d37e79e3d9bd22ae47efb5f3089c55fc82f84e2503e5fccd163fd072d2f0 -size 1707210 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_40.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_40.pt deleted file mode 100755 index 1f7b8d2ff2d6d95382fda9365912c63c1782bb60..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_40.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:51be6db1707e8d49ea6df923b5ac7f6ffbaa4e2a228f2fc3c54624f2eb74136a -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_41.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_41.pt deleted file mode 100755 index 18b25e2b154b75173ca89c546c27a72bc4f94a61..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_41.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3d21965ac3908046a8af6f5032c20ffd8e33b22442ae05f6ce1e9d592fdb035e -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_42.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_42.pt deleted file mode 100755 index 28c8bcede6442031b2da105d0cd1472161255e4f..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_42.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:964eb93aaa7a05490d1f31a7e70d8514091a555822cee24bd1657ff4f52fc796 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_43.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_43.pt deleted file mode 100755 index 405d6d3a82d801c49885e6a9befe9b1aab397fa9..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_43.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3c4a379e4f5b55c3b1bbeda41c006cce7da055dab4b48d1f97faf835cd495370 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_44.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_44.pt deleted file mode 100755 index ed1a55f2b16b47b586827272669c9966de5ff99d..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_44.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:81b685db8579014076f38a3dbb0ec89c042c697fcd3b3d008994e4fcb13b4528 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_45.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_45.pt deleted file mode 100755 index 8e18f365ad825661fd694c4000ac21537f979302..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_45.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8a5e945caca75699fae347e22164537bf1af73c668f44b9d5001be9a45434d30 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_46.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_46.pt deleted file mode 100755 index de292f4bf482ac352cd034af80e975f6212f8881..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_46.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ddbe65014209fa0a71b55f28bae90da42d36ecf3145ca074daa3f5b30443441e -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_47.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_47.pt deleted file mode 100755 index 55e29d4f873b5b48ae65ae79bbf72646a55a9528..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_47.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:89deaa3de5cc05b87eac0fbfb94a6f34765e56c282ab6ba6e9b635e057cf1afe -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_48.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_48.pt deleted file mode 100755 index bf20f68a3dd537c331e79ee192959a3c30eb6f0d..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_48.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6f6f776731bd62504a2da894a6e628552b714c8d6433e9714868782167327a8c -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_49.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_49.pt deleted file mode 100755 index 49775f1a19b6ebffd01471edb9f17907f7cd03c1..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_49.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d39185a4ae0527343f7a7c41655b8dfebf2cfd5fb05c3fede3513baf3ba656c4 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_5.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_5.pt deleted file mode 100755 index 4c37752abb81fffd02663e790e6801ef7302df74..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_5.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:feff3fb319b0c403dc9fc49d7a58ba3a2fd02441cfd9fe5576925f558389fa00 -size 1707210 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_50.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_50.pt deleted file mode 100755 index b102f7b9707340bcdf93dfd165816310d2e67b25..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_50.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8414856c68ff2505a132993c4a6821893a371b240500eef03a4ae5e96738d4e4 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_51.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_51.pt deleted file mode 100755 index ac888bbf9a4979373ff257a60213842560e67c37..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_51.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:298ee4c7ad2f2c3551d575311ed2843adbc319a5d42662f8a52d7980005c08f2 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_52.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_52.pt deleted file mode 100755 index ad5b2177811130bf6378bb6dc5fd2b3bb57da913..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_52.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b0c6171f4ccd9130879bdd9c0029aa6ad57f160ed4fc79900cfae7853a1cf487 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_53.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_53.pt deleted file mode 100755 index 7c22531fa1d729739b1ea63150fcc88e7dc510b8..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_53.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1ad6ddfbedcf332a87ac87b1def7d37b3de0247e0863d61c615615e2b227a75e -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_54.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_54.pt deleted file mode 100755 index 024baddaa388f1e8a4df4626001036ac5ad1dd23..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_54.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ae3b5fe0a6a0a5c289c0a122f5a68c79862535b8f1ca366c1116436c7915db5c -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_55.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_55.pt deleted file mode 100755 index 294aaba4ee9ee1593827f07a93ee186aed8ff3c4..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_55.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:20688eb442db6737cc37318c76a7128ae4fd79505a470ba36c09bdaffe573c83 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_56.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_56.pt deleted file mode 100755 index eeb79093c131eaa46dc1fbe70839955b0191f54a..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_56.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9e3889c446789d532bcc9936232026c5f7c8a3f624ceea4cdda3132389bdc5d2 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_57.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_57.pt deleted file mode 100755 index 8691fe8d9c276b2d825b9cf96dbd92e6ac753c39..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_57.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:89cd230b025bea3c77fa984cea8df8aed91e72ce974bf2e85e8a097cb76c07f0 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_58.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_58.pt deleted file mode 100755 index b270bb3e633eecdb684d24a0209a38c530a276a0..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_58.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:46b69748fbce6aed56e13e9142c3d30f632a4572da19f33b89a7f16d43105e5b -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_59.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_59.pt deleted file mode 100755 index 761410e34ebede1d1b3c8b5cb81f188dcba213b6..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_59.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dd0d983094ffdd377339c1786d042e4f79449f0124ba95c6f1041265bd40d54f -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_6.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_6.pt deleted file mode 100755 index 1fe5e30bca258703dc092187480eedd402128efb..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_6.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4877113b9a0dda418705feb99e0668c488da9118b6d2cad2ddbe212c5c1d0797 -size 1707210 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_60.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_60.pt deleted file mode 100755 index 8ea7bbcc2f856d528d57a4c9cd9d57011205623b..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_60.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:13464c40181b7daf5251a84e38a14474c03135558561ffe677092dfbe7ec8387 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_61.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_61.pt deleted file mode 100755 index 7e088d2e031604043370836bab4f792d24b48383..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_61.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c49038389ce16f886aeec01296aca1a62e1c08fbf7b1e88d2063e08b3d62237b -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_62.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_62.pt deleted file mode 100755 index 594f0efcb4b76ba7504cd6dfd597200f2c758b0d..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_62.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:222ffeb7f9466325f330492bc768e6a3202e26c0f3aa04738600e93d3b4a0392 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_63.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_63.pt deleted file mode 100755 index 888827971352b376ff3c3add47928e3a303c6361..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_63.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9f13a872904cf664c5ad81ab4fadad26c5c51b716385c9742a1c52268c8ae118 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_64.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_64.pt deleted file mode 100755 index 26267f88ac8e3ba1d5b628beaea78d1c42442d8b..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_64.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5d213c0b475bd54aa8e3714ef6a15a8d2768239bb8531824c95939bf8825b18a -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_65.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_65.pt deleted file mode 100755 index 7bf2363326cda4e1bdef4ca8a542f49b3433c3f0..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_65.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:172f4ce8a4f794ed2c4e6b80ea69d32436f7b263cc0ab090bb1dfdebe1b22b18 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_66.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_66.pt deleted file mode 100755 index 547bb0c251e49633f87d2b8891bbc156b4628d6c..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_66.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:50a3f94d433cef8ad9624e0af89b6bb8869ddf7af61e86b00231065c49d19322 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_67.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_67.pt deleted file mode 100755 index 1c9b25c8a07fb32a4462625af5999d87a1221ec4..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_67.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1e01c366ea60ff5b91e24ba82f1fb91f04f2b6741468a78eabb1b08fa30e1b74 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_68.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_68.pt deleted file mode 100755 index c0e3054373b76e9b283e846680bef385d3e4b014..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_68.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8955dbd9032aa10679c2182892bc6377ea52bfef5951ab569e67d57b2226c126 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_69.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_69.pt deleted file mode 100755 index 149615e138ad25b50cc20a782e058458047167b2..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_69.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7cd88340b42715aa31ec38774e0d1a8c96c68a8854b11e093dac619ea7423db7 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_7.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_7.pt deleted file mode 100755 index 592ff0544d7d1e2d50bf198989bec2958287177a..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_7.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:811001ddeb217631289f7093d87a8600066a01d9b5cc9bfdf004d978a9a17fd7 -size 1707210 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_70.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_70.pt deleted file mode 100755 index dd40b8c5c2c3f7cc3a706f98bf6f2353c3bfea75..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_70.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6c24753f14abefaf1062084242a0ae6dc74a2541dd4bca8ad6acd7f018536dfa -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_71.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_71.pt deleted file mode 100755 index 4c2025ee7cbd748ae0080a2b5648c4b1e17c9f3d..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_71.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f382f9f8b2d8c09b896657d397985f9149f018fcf3aa6d6f56ce3e51cf8a6351 -size 1707502 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_8.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_8.pt deleted file mode 100755 index 1c99e3aa04602616da6dea5f2f924aa647f2b6ac..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_8.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7f96ccbbe7194fc54dbadda7a1cb6a7c7a1389678142c0b5c915270549b955c8 -size 1707210 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_9.pt b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_9.pt deleted file mode 100755 index 47da8b5df4f3b2dcac3115cc3dcdad203f96f1e1..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_9.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9d21ef077a1cd3e46fc94e0c80105bcf2246c70d9811027a666c28ff21cb4c7f -size 1707210 diff --git a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/training.log b/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/training.log deleted file mode 100755 index 9412d7e31a69685e670faaa0eb986a936784b103..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/Pretrained_GNN/multiclass_pretrained_model_12/training.log +++ /dev/null @@ -1,74 +0,0 @@ -Training multiclass_12_process 2024-09-06 23:50:52.835697 -Epoch 00000 | LR 1.0000e-04 | Loss 1.6853 | Accuracy 0.3672 | Test_Loss 1.6844 | Test_AUC 0.8323 | Time 2406.1502 s -Epoch 00001 | LR 9.9000e-05 | Loss 1.6216 | Accuracy 0.3743 | Test_Loss 1.6660 | Test_AUC 0.8344 | Time 2406.9453 s -Epoch 00002 | LR 9.8010e-05 | Loss 1.6066 | Accuracy 0.3769 | Test_Loss 1.6656 | Test_AUC 0.8389 | Time 2355.3162 s -Epoch 00003 | LR 9.7030e-05 | Loss 1.5989 | Accuracy 0.3752 | Test_Loss 1.6700 | Test_AUC 0.8379 | Time 2351.9926 s -Epoch 00004 | LR 9.6060e-05 | Loss 1.5936 | Accuracy 0.3809 | Test_Loss 1.6568 | Test_AUC 0.8435 | Time 2323.1655 s -Epoch 00005 | LR 9.5099e-05 | Loss 1.5898 | Accuracy 0.3784 | Test_Loss 1.6613 | Test_AUC 0.8405 | Time 2293.3972 s -Epoch 00006 | LR 9.4148e-05 | Loss 1.5869 | Accuracy 0.3832 | Test_Loss 1.6416 | Test_AUC 0.8416 | Time 2297.7492 s -Epoch 00007 | LR 9.3207e-05 | Loss 1.5844 | Accuracy 0.3917 | Test_Loss 1.6090 | Test_AUC 0.8455 | Time 2296.5126 s -Epoch 00008 | LR 9.2274e-05 | Loss 1.5822 | Accuracy 0.3895 | Test_Loss 1.6174 | Test_AUC 0.8429 | Time 2372.6853 s -Epoch 00009 | LR 9.1352e-05 | Loss 1.5810 | Accuracy 0.3965 | Test_Loss 1.6079 | Test_AUC 0.8453 | Time 2455.0305 s -Epoch 00010 | LR 9.0438e-05 | Loss 1.5795 | Accuracy 0.3966 | Test_Loss 1.6067 | Test_AUC 0.8468 | Time 2459.9180 s -Epoch 00011 | LR 8.9534e-05 | Loss 1.5782 | Accuracy 0.3943 | Test_Loss 1.6117 | Test_AUC 0.8465 | Time 2444.6930 s -Epoch 00012 | LR 8.8638e-05 | Loss 1.5770 | Accuracy 0.3973 | Test_Loss 1.6081 | Test_AUC 0.8471 | Time 2475.8966 s -Epoch 00013 | LR 8.7752e-05 | Loss 1.5759 | Accuracy 0.3973 | Test_Loss 1.6037 | Test_AUC 0.8486 | Time 2330.9825 s -Epoch 00014 | LR 8.6875e-05 | Loss 1.5749 | Accuracy 0.3974 | Test_Loss 1.6066 | Test_AUC 0.8491 | Time 2276.6652 s -Epoch 00015 | LR 8.6006e-05 | Loss 1.5741 | Accuracy 0.3981 | Test_Loss 1.6070 | Test_AUC 0.8475 | Time 2278.0207 s -Epoch 00016 | LR 8.5146e-05 | Loss 1.5733 | Accuracy 0.3958 | Test_Loss 1.6089 | Test_AUC 0.8471 | Time 2296.7680 s -Epoch 00017 | LR 8.4294e-05 | Loss 1.5726 | Accuracy 0.3978 | Test_Loss 1.6004 | Test_AUC 0.8491 | Time 2273.7842 s -Epoch 00018 | LR 8.3451e-05 | Loss 1.5718 | Accuracy 0.3847 | Test_Loss 1.6652 | Test_AUC 0.8448 | Time 2265.8179 s -Epoch 00019 | LR 8.2617e-05 | Loss 1.5713 | Accuracy 0.3858 | Test_Loss 1.6495 | Test_AUC 0.8434 | Time 2271.3266 s -Epoch 00020 | LR 8.1791e-05 | Loss 1.5708 | Accuracy 0.3842 | Test_Loss 1.6602 | Test_AUC 0.8431 | Time 2263.7548 s -Epoch 00021 | LR 8.0973e-05 | Loss 1.5703 | Accuracy 0.3829 | Test_Loss 1.6628 | Test_AUC 0.8439 | Time 2277.5963 s -Epoch 00022 | LR 8.0163e-05 | Loss 1.5699 | Accuracy 0.3873 | Test_Loss 1.6452 | Test_AUC 0.8436 | Time 2381.2508 s -Epoch 00023 | LR 7.9361e-05 | Loss 1.5694 | Accuracy 0.3841 | Test_Loss 1.6477 | Test_AUC 0.8446 | Time 2371.5616 s -Epoch 00024 | LR 7.8568e-05 | Loss 1.5690 | Accuracy 0.3917 | Test_Loss 1.6253 | Test_AUC 0.8448 | Time 2412.1963 s -Epoch 00025 | LR 7.7782e-05 | Loss 1.5685 | Accuracy 0.3997 | Test_Loss 1.5952 | Test_AUC 0.8483 | Time 2361.6398 s -Epoch 00026 | LR 7.7004e-05 | Loss 1.5680 | Accuracy 0.3975 | Test_Loss 1.6004 | Test_AUC 0.8491 | Time 2370.2956 s -Epoch 00027 | LR 7.6234e-05 | Loss 1.5679 | Accuracy 0.4008 | Test_Loss 1.6004 | Test_AUC 0.8496 | Time 2401.6121 s -Epoch 00028 | LR 7.5472e-05 | Loss 1.5678 | Accuracy 0.3993 | Test_Loss 1.6004 | Test_AUC 0.8492 | Time 2403.7899 s -Epoch 00029 | LR 7.4717e-05 | Loss 1.5676 | Accuracy 0.3993 | Test_Loss 1.5997 | Test_AUC 0.8497 | Time 2407.6645 s -Epoch 00030 | LR 7.3970e-05 | Loss 1.5672 | Accuracy 0.4022 | Test_Loss 1.5928 | Test_AUC 0.8498 | Time 2401.9651 s -Epoch 00031 | LR 7.3230e-05 | Loss 1.5669 | Accuracy 0.3991 | Test_Loss 1.6006 | Test_AUC 0.8475 | Time 2397.6024 s -Epoch 00032 | LR 7.2498e-05 | Loss 1.5667 | Accuracy 0.4011 | Test_Loss 1.5956 | Test_AUC 0.8483 | Time 2404.3273 s -Epoch 00033 | LR 7.1773e-05 | Loss 1.5664 | Accuracy 0.3999 | Test_Loss 1.5982 | Test_AUC 0.8468 | Time 2397.5160 s -Epoch 00034 | LR 7.1055e-05 | Loss 1.5662 | Accuracy 0.4012 | Test_Loss 1.5956 | Test_AUC 0.8491 | Time 2396.6267 s -Epoch 00035 | LR 7.0345e-05 | Loss 1.5659 | Accuracy 0.4003 | Test_Loss 1.5962 | Test_AUC 0.8473 | Time 2393.2753 s -Training multiclass_12_process 2024-09-08 07:29:43.909566 -Epoch 00036 | LR 7.0345e-05 | Loss 1.5654 | Accuracy 0.3859 | Test_Loss 1.6487 | Test_AUC 0.8440 | Time 2350.2070 s -Epoch 00037 | LR 6.9641e-05 | Loss 1.5654 | Accuracy 0.3855 | Test_Loss 1.6569 | Test_AUC 0.8450 | Time 2376.8111 s -Epoch 00038 | LR 6.8945e-05 | Loss 1.5652 | Accuracy 0.3876 | Test_Loss 1.6477 | Test_AUC 0.8444 | Time 2388.1118 s -Epoch 00039 | LR 6.8255e-05 | Loss 1.5650 | Accuracy 0.3856 | Test_Loss 1.6473 | Test_AUC 0.8441 | Time 2367.7247 s -Epoch 00040 | LR 6.7573e-05 | Loss 1.5648 | Accuracy 0.3893 | Test_Loss 1.6384 | Test_AUC 0.8448 | Time 2354.1136 s -Epoch 00041 | LR 6.6897e-05 | Loss 1.5646 | Accuracy 0.3861 | Test_Loss 1.6461 | Test_AUC 0.8458 | Time 2340.8834 s -Epoch 00042 | LR 6.6228e-05 | Loss 1.5644 | Accuracy 0.3932 | Test_Loss 1.6217 | Test_AUC 0.8482 | Time 2349.6574 s -Epoch 00043 | LR 6.5566e-05 | Loss 1.5641 | Accuracy 0.4010 | Test_Loss 1.5895 | Test_AUC 0.8484 | Time 2360.5786 s -Epoch 00044 | LR 6.4910e-05 | Loss 1.5638 | Accuracy 0.4019 | Test_Loss 1.5900 | Test_AUC 0.8483 | Time 2468.9202 s -Epoch 00045 | LR 6.4261e-05 | Loss 1.5640 | Accuracy 0.4008 | Test_Loss 1.5990 | Test_AUC 0.8481 | Time 2473.0072 s -Epoch 00046 | LR 6.3619e-05 | Loss 1.5639 | Accuracy 0.4011 | Test_Loss 1.5962 | Test_AUC 0.8498 | Time 2448.4408 s -Epoch 00047 | LR 6.2982e-05 | Loss 1.5638 | Accuracy 0.4017 | Test_Loss 1.5946 | Test_AUC 0.8485 | Time 2381.1478 s -Epoch 00048 | LR 6.2353e-05 | Loss 1.5636 | Accuracy 0.4011 | Test_Loss 1.5942 | Test_AUC 0.8480 | Time 2393.2382 s -Epoch 00049 | LR 6.1729e-05 | Loss 1.5635 | Accuracy 0.4022 | Test_Loss 1.5950 | Test_AUC 0.8482 | Time 2350.8688 s -Epoch 00050 | LR 6.1112e-05 | Loss 1.5634 | Accuracy 0.4007 | Test_Loss 1.5968 | Test_AUC 0.8500 | Time 2334.9762 s -Epoch 00051 | LR 6.0501e-05 | Loss 1.5632 | Accuracy 0.4026 | Test_Loss 1.5919 | Test_AUC 0.8487 | Time 2269.9354 s -Epoch 00052 | LR 5.9896e-05 | Loss 1.5631 | Accuracy 0.4018 | Test_Loss 1.5961 | Test_AUC 0.8493 | Time 2303.6344 s -Epoch 00053 | LR 5.9297e-05 | Loss 1.5630 | Accuracy 0.4022 | Test_Loss 1.5928 | Test_AUC 0.8501 | Time 2275.7180 s -Epoch 00054 | LR 5.8704e-05 | Loss 1.5626 | Accuracy 0.3868 | Test_Loss 1.6539 | Test_AUC 0.8439 | Time 2282.3519 s -Epoch 00055 | LR 5.8117e-05 | Loss 1.5626 | Accuracy 0.3848 | Test_Loss 1.6525 | Test_AUC 0.8449 | Time 2338.0367 s -Epoch 00056 | LR 5.7535e-05 | Loss 1.5625 | Accuracy 0.3861 | Test_Loss 1.6500 | Test_AUC 0.8444 | Time 2349.1735 s -Epoch 00057 | LR 5.6960e-05 | Loss 1.5624 | Accuracy 0.3883 | Test_Loss 1.6474 | Test_AUC 0.8438 | Time 2352.2581 s -Epoch 00058 | LR 5.6391e-05 | Loss 1.5623 | Accuracy 0.3869 | Test_Loss 1.6484 | Test_AUC 0.8453 | Time 2300.8949 s -Epoch 00059 | LR 5.5827e-05 | Loss 1.5621 | Accuracy 0.3885 | Test_Loss 1.6456 | Test_AUC 0.8452 | Time 2296.1956 s -Epoch 00060 | LR 5.5268e-05 | Loss 1.5620 | Accuracy 0.3891 | Test_Loss 1.6347 | Test_AUC 0.8457 | Time 2311.4265 s -Epoch 00061 | LR 5.4716e-05 | Loss 1.5618 | Accuracy 0.4018 | Test_Loss 1.5879 | Test_AUC 0.8495 | Time 2307.2661 s -Epoch 00062 | LR 5.4169e-05 | Loss 1.5615 | Accuracy 0.4029 | Test_Loss 1.5857 | Test_AUC 0.8507 | Time 2356.9390 s -Epoch 00063 | LR 5.3627e-05 | Loss 1.5617 | Accuracy 0.4008 | Test_Loss 1.5969 | Test_AUC 0.8497 | Time 2315.4540 s -Epoch 00064 | LR 5.3091e-05 | Loss 1.5618 | Accuracy 0.4014 | Test_Loss 1.5944 | Test_AUC 0.8490 | Time 2322.3426 s -Epoch 00065 | LR 5.2560e-05 | Loss 1.5618 | Accuracy 0.4013 | Test_Loss 1.5960 | Test_AUC 0.8498 | Time 2337.3654 s -Epoch 00066 | LR 5.2034e-05 | Loss 1.5616 | Accuracy 0.4038 | Test_Loss 1.5905 | Test_AUC 0.8505 | Time 2354.6974 s -Epoch 00067 | LR 5.1514e-05 | Loss 1.5615 | Accuracy 0.4028 | Test_Loss 1.5932 | Test_AUC 0.8491 | Time 2346.2346 s -Epoch 00068 | LR 5.0999e-05 | Loss 1.5615 | Accuracy 0.4026 | Test_Loss 1.5919 | Test_AUC 0.8492 | Time 2364.3581 s -Epoch 00069 | LR 5.0489e-05 | Loss 1.5614 | Accuracy 0.4014 | Test_Loss 1.5947 | Test_AUC 0.8485 | Time 2321.0254 s -Epoch 00070 | LR 4.9984e-05 | Loss 1.5613 | Accuracy 0.4018 | Test_Loss 1.5942 | Test_AUC 0.8504 | Time 2360.4706 s -Epoch 00071 | LR 4.9484e-05 | Loss 1.5612 | Accuracy 0.4016 | Test_Loss 1.5946 | Test_AUC 0.8487 | Time 2348.2632 s diff --git a/root_gnn_dgl/README.md b/root_gnn_dgl/README.md index 25c82ab0cf6bd50c79e770d66ac2962613990ea2..7337e9ed4e171ccfae13100f48c23a4afbe3ac89 100644 --- a/root_gnn_dgl/README.md +++ b/root_gnn_dgl/README.md @@ -1,68 +1,53 @@ - # root_gnn_dgl -Pretrained DGL-based ROOT graph neural network. +## Data Directory (for Hackathon) +`/global/cfs/projectdirs/trn007/lbl_atlas/data/` + +* `stats_all`: full statistics sample, ~10M events per process +* `stats_100K`: reduced statistics sample, 100K events per process +* `processed_graphs`: graphs that have already been processed +* `scores`: a copy of the samples along with the GNN scores for each event -Pretrained model location: `/global/cfs/projectdirs/atlas/joshua/Pretrained_GNN/multiclass_pretrained_model_12/` -To use the pretrained model, take a look at a finetuning config in `configs`. -Replace `pretraining_path:` with `/global/cfs/projectdirs/atlas/joshua/Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_71.pt`. +## Environment Setup -## Overview -- Stable release with pretrained model weights. +The environment dependencies for this project are listed in `setup/environment.yml`. Follow the steps below to set up the environment: -## Conda setup +### Step 1: Install Conda +If you don’t already have Conda installed, install either Miniconda (lightweight) or Anaconda (full version): -The conda environment is required for the inference step: applying the GNN onto root files and saving GNN scores as an additional branch. This is because the infereces script uses pyROOT. +- **Miniconda**: Download and install from [https://docs.conda.io/en/latest/miniconda.html](https://docs.conda.io/en/latest/miniconda.html). +- **Anaconda**: Download and install from [https://www.anaconda.com/products/distribution](https://www.anaconda.com/products/distribution). +### Step 2: Clone the Repository +Clone this repository to your local machine: ```bash -cd setup -conda env create -f environment.yml -conda activate pytorch -cd .. -python setup/test_setup.py +git init +git lfs install +git clone https://huggingface.co/HWresearch/GNN4Colliders ``` - -## Container Setup (Podman-HPC) - -- NERSC Perlmutter environment with `podman-hpc` available. -- Access to `joshuaho/pytorch:1.0` on Docker Hub [https://hub.docker.com/r/joshuaho/pytorch](https://hub.docker.com/r/joshuaho/pytorch) - -The inference step requires the conda environment, since the container does not contain ROOT. - -### Pull the Prebuilt Image - +If you want to clone without large files - just their pointers ```bash -podman-hpc pull docker.io/joshuaho/pytorch:1.0 +GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/HWresearch/GNN4Colliders ``` -Or, you can build your own container here: - +### Step 3: Create the Conda Environment +Use the `environment.yml` file to create the Conda environment: ```bash -cd setup -source build_image.sh +conda env create -f setup/environment.yml -n ``` -Run the image and mount the paths you need, replaceing `` with source directory path and `` with the path for when you are inside the container. +### Step 4: Activate the Environment +Activate the newly created environment: ```bash +conda activate +``` +Replace with the name of the environment specified in Step 4. -podman-hpc run \ - -it \ - --mount type=bind,source=,target= \ - --rm \ - --network host \ - --gpu \ - --userns keep-id \ - --shm-size=32g \ - joshuaho/pytorch:1.0 - ``` - -### Test the Environment +### Step 5: Test the Environment Run the `setup/test_setup.py` script to confirm that all packages needed for training are properly set up. ```bash python setup/test_setup.py ``` - - ## Running the Demo The demo training is an example of our ML workflow, consisting of training a pretrained model, then finetuning it for an analysis task, while also training a model for the analysis task from scratch. The config files for the demo are located in the directory `configs/stats_100K/`. The demo can be run on a login node on Perlmutter (if enough GPU memory is availble). @@ -104,44 +89,6 @@ dgl.save_graphs(str(graph_path).replace('.bin', f'_{self.process_chunks[i]}.bin' IndexError: list index out of range ``` -To make sure you have all the necessary graphs to train, you can use the `scripts/check_dataset_files.py` script to ensure all graphs are properly processed. Using the `--rerun` runtime arguement will tell the script to automically re-processes any missing files. - -### Selections -Dataset-level event selections are defined in the config file at the same level as `args:` and `folding:`. They are applied during data preparation before graphs are built, and they are also reported as a cutflow after processing. - -Example: -```yaml -Datasets: - ttH_CP_even: - module: root_gnn_base.dataset - class: LazyDataset - args: - name: ttH_CP_even - # ... - selections: - - "N_jet >= 5" - - "(123 < higgs_m) & (higgs_m < 127)" - folding: - n_folds: 4 - test: [0] - train: [1, 2, 3] -``` - -Supported selection syntax: -- Simple comparisons like `"N_jet >= 5"`, `"higgs_m < 200"`, or `"MET_met == 0"` -- Multiple conditions combined with `&` and parentheses, for example `"(123 < higgs_m) & (higgs_m < 127)"` - -To quickly test that the selections in a config are valid and to print a fast cutflow for every dataset, run: -```bash -python scripts/selections.py --config configs/stats_100K/ttH_CP_even_vs_odd.yaml -``` - -This script reads only the branches needed for the selections and prints: -- the status of each selection expression -- the yield after each cut -- the individual efficiency of each cut -- the total efficiency relative to the uncut sample - ## Training Training is run by `scripts/training_script`. `--preshuffle` tells it to use the preshuffled and batched graphs rather than shuffling and batching on the fly, and `--restart` can be used to force the training to start from the beginning rather than from the last available checkpoint. @@ -158,65 +105,16 @@ Inference is done by `scripts/inference.py`. This script applies the model defin ```bash python scripts/inference.py \ - --target "/global/cfs/projectdirs/atlas/joshua/gnn_data/stats_100K/ttH_NLO.root" \ - --destination "/global/cfs/projectdirs/atlas/joshua/gnn_data/scores/stats_100K/ttH_NLO.root" \ + --target "/global/cfs/projectdirs/trn007/lbl_atlas/data/stats_100K/ttH_NLO.root" \ + --destination "/global/cfs/projectdirs/trn007/lbl_atlas/data/scores/stats_100K/ttH_NLO.root" \ --config "configs/stats_100K/finetuning_ttH_CP_even_vs_odd.yaml" \ - --branch_name "GNN_Score" \ --chunks 1 \ --chunkno 0 \ - --write -``` - -You can also input a list as the `--config` and the `--branch_name` to simultaneously apply multiple models onto the same set of samples. An example on how to do this in shell script is in the `run_demo.sh` file. - -## ONNX Export -The `scripts/onnx_export.py` script exports a trained model to ONNX and validates the exported model against PyTorch on a real batch from the processed dataset. - -Example: -```bash -python scripts/onnx_export.py --config configs/stats_100K/ttH_CP_even_vs_odd.yaml --name ttH.onnx -``` - -To export a specific checkpoint instead of the best `Test_AUC` epoch, pass `--epoch`: -```bash -python scripts/onnx_export.py --config configs/stats_100K/ttH_CP_even_vs_odd.yaml --name ttH_epoch68.onnx --epoch 68 + --write \ + --branch 'GNN_Score' ``` -What it does: -- Reads the model definition from the provided config -- Automatically chooses the matching model class from the config, including the finetuning or from-scratch path -- Loads the first prebatched chunk from the dataset save directory -- Uses the graph node count per event as `global_features` -- Exports an ONNX model with inputs in this order: - 1. `node_features` - 2. `edge_features` - 3. `global_features` - 4. `edge_index` - 5. `node_batch` -- Checks the ONNX graph with `onnx.checker` -- Runs ONNX Runtime and compares the output to PyTorch - -If `--epoch` is omitted, the script loads the checkpoint from the best `Test_AUC` entry in `training.log`, which matches the previous behavior. - -The validation is a three-way comparison: -1. The original DGL model from training -2. The tensor-based PyTorch translation of the same GNN -3. The exported ONNX model - -The script compares both logits and final sigmoid scores across all three models. It also produces a diagnostic plot showing: -- score distributions for the DGL, tensor, and ONNX models -- residual distributions for tensor - DGL and ONNX - DGL - -The plot is saved automatically next to the ONNX file using the same stem, with `_onnx.png` appended. - -Input shapes follow the notebook convention: -- `node_features`: `[num_nodes, node_feature_dim]` -- `edge_features`: `[num_edges, edge_feature_dim]` -- `global_features`: `[batch_size, 1]` -- `edge_index`: `[2, num_edges]` -- `node_batch`: `[num_nodes]` - -The validation prints the max and mean absolute differences for both logits and sigmoid probabilities. For a healthy export, those differences should be very small, typically around `1e-5` or better for logits. +You can also input a list as the `--config` and the `--branch` to simultaneously apply multiple models onto the same set of samples. An example on how to do this in shell script is in the `run_demo.sh` file. ## Running Jobs + Parallelization diff --git a/root_gnn_dgl/configs/attention/ttH_CP_even_vs_odd.yaml b/root_gnn_dgl/configs/attention/ttH_CP_even_vs_odd.yaml new file mode 100755 index 0000000000000000000000000000000000000000..dc124be431b366eed524c31ac6fc11c2325f4f42 --- /dev/null +++ b/root_gnn_dgl/configs/attention/ttH_CP_even_vs_odd.yaml @@ -0,0 +1,58 @@ +Training_Name: ttH_CP_even_vs_odd +Training_Directory: trainings/attention/ttH_CP_even_vs_odd +Model: + module: models.GCN + class: Attention_Edge_Network + args: + hid_size: 64 + in_size: 7 + out_size: 1 + n_layers: 4 + n_proc_steps: 4 + dropout: 0 + num_heads: 2 +Training: + epochs: 500 + batch_size: 1024 + learning_rate: 0.0001 + gamma: 0.99 +Datasets: + ttH_CP_even: &dataset_defn + module: root_gnn_base.dataset + class: LazyDataset + shuffle_chunks: 3 + batch_size: 1024 + padding_mode: NODE + args: &dataset_args + name: ttH_CP_even + label: 0 + # weight_var: weight + chunks: 3 + buffer_size: 2 + file_names: ttH_NLO.root + tree_name: output + fold_var: Number + raw_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/stats_100K/ + save_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/processed_graphs/attention/ttH_CP_even_vs_odd/ + node_branch_names: + - [jet_pt, ele_pt, mu_pt, ph_pt, MET_met] + - [jet_eta, ele_eta, mu_eta, ph_eta, 0] + - [jet_phi, ele_phi, mu_phi, ph_phi, MET_phi] + - CALC_E + - [jet_btag, 0, 0, 0, 0] + - [0, ele_charge, mu_charge, 0, 0] + - NODE_TYPE + node_branch_types: [vector, vector, vector, vector, single] + node_feature_scales: [1e-1, 1, 1, 1e-1, 1, 1, 1] + folding: + n_folds: 4 + test: [0] + # validation: 1 + train: [1, 2, 3] + ttH_CP_odd: + <<: *dataset_defn + args: + <<: *dataset_args + name: ttH_CP_odd + label: 1 + file_names: ttH_CPodd.root diff --git a/root_gnn_dgl/configs/stats_100K/finetuning_ttH_CP_even_vs_odd.yaml b/root_gnn_dgl/configs/stats_100K/finetuning_ttH_CP_even_vs_odd.yaml index 33c62c3d4cab69684e191d46b7c5e325c0f032cd..ae56b014189afbba4886f421dda9aad12f6d467c 100755 --- a/root_gnn_dgl/configs/stats_100K/finetuning_ttH_CP_even_vs_odd.yaml +++ b/root_gnn_dgl/configs/stats_100K/finetuning_ttH_CP_even_vs_odd.yaml @@ -4,7 +4,7 @@ Model: module: models.GCN class: Transferred_Learning_Finetuning args: - pretraining_path: Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_71.pt + pretraining_path: trainings/stats_100K/pretraining_multiclass/model_epoch_100.pt # update to the last epoch of the pretraining pretraining_model: module: models.GCN class: Edge_Network @@ -23,7 +23,7 @@ Model: Training: epochs: 500 batch_size: 1024 - learning_rate: 0.00001 + learning_rate: 0.0001 gamma: 0.99 Datasets: ttH_CP_even: &dataset_defn @@ -41,8 +41,8 @@ Datasets: file_names: ttH_NLO.root tree_name: output fold_var: Number - raw_dir: /global/cfs/projectdirs/atlas/joshua/gnn_data/stats_100K/ - save_dir: /pscratch/sd/j/joshuaho/gnn/stats_100K/ttH_CP_even_vs_odd/ + raw_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/stats_100K/ + save_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/processed_graphs/stats_100K/ttH_CP_even_vs_odd/ node_branch_names: - [jet_pt, ele_pt, mu_pt, ph_pt, MET_met] - [jet_eta, ele_eta, mu_eta, ph_eta, 0] @@ -53,9 +53,6 @@ Datasets: - NODE_TYPE node_branch_types: [vector, vector, vector, vector, single] node_feature_scales: [1e-1, 1, 1, 1e-1, 1, 1, 1] - selections: - - "N_jet >= 5" - - "(123 < higgs_m) & (higgs_m < 127)" folding: n_folds: 4 test: [0] diff --git a/root_gnn_dgl/configs/stats_100K/pretraining_multiclass.yaml b/root_gnn_dgl/configs/stats_100K/pretraining_multiclass.yaml index d3c1cdbd9015bbf2d85aa0c571f156ba69953cf4..c182c8588431ebd1016178fc7f8b9c1dda543a0b 100644 --- a/root_gnn_dgl/configs/stats_100K/pretraining_multiclass.yaml +++ b/root_gnn_dgl/configs/stats_100K/pretraining_multiclass.yaml @@ -38,8 +38,8 @@ Datasets: file_names: ttH_NLO_inc.root tree_name: output fold_var: Number - raw_dir: /global/cfs/projectdirs/atlas/joshua/gnn_data/stats_100K/ - save_dir: /pscratch/sd/j/joshuaho/gnn/stats_100K/pretraining_multiclass/ + raw_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/stats_100K/ + save_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/processed_graphs/stats_100K/pretraining_multiclass/ node_branch_names: - [jet_pt, ele_pt, mu_pt, ph_pt, MET_met] - [jet_eta, ele_eta, mu_eta, ph_eta, 0] @@ -94,7 +94,7 @@ Datasets: <<: *dataset_defn args: <<: *dataset_args - name: ttyy + name: ttyy_ch label: 6 file_names: 'ttyy.root' tttt: diff --git a/root_gnn_dgl/configs/stats_100K/ttH_CP_even_vs_odd.yaml b/root_gnn_dgl/configs/stats_100K/ttH_CP_even_vs_odd.yaml index 44999846ead6ff5066b53287c012ce7fde0ce182..5fcb903b08a68a8640bf65ee4aab0c81a9d91d66 100755 --- a/root_gnn_dgl/configs/stats_100K/ttH_CP_even_vs_odd.yaml +++ b/root_gnn_dgl/configs/stats_100K/ttH_CP_even_vs_odd.yaml @@ -31,8 +31,8 @@ Datasets: file_names: ttH_NLO.root tree_name: output fold_var: Number - raw_dir: /global/cfs/projectdirs/atlas/joshua/gnn_data/stats_100K/ - save_dir: /pscratch/sd/j/joshuaho/gnn/stats_100K/ttH_CP_even_vs_odd/ + raw_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/stats_100K/ + save_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/processed_graphs/stats_100K/ttH_CP_even_vs_odd/ node_branch_names: - [jet_pt, ele_pt, mu_pt, ph_pt, MET_met] - [jet_eta, ele_eta, mu_eta, ph_eta, 0] @@ -43,9 +43,6 @@ Datasets: - NODE_TYPE node_branch_types: [vector, vector, vector, vector, single] node_feature_scales: [1e-1, 1, 1, 1e-1, 1, 1, 1] - selections: - - "N_jet >= 5" - - "(123 < higgs_m) & (higgs_m < 127)" folding: n_folds: 4 test: [0] diff --git a/root_gnn_dgl/configs/stats_all/finetuning_ttH_CP_even_vs_odd.yaml b/root_gnn_dgl/configs/stats_all/finetuning_ttH_CP_even_vs_odd.yaml index eefb5d82e72a6b4cb93ff859c37892867897ed9b..4ea8a0f4e8f4c1fb2467574a7f3730a7cf0768e9 100755 --- a/root_gnn_dgl/configs/stats_all/finetuning_ttH_CP_even_vs_odd.yaml +++ b/root_gnn_dgl/configs/stats_all/finetuning_ttH_CP_even_vs_odd.yaml @@ -4,7 +4,7 @@ Model: module: models.GCN class: Transferred_Learning_Finetuning args: - pretraining_path: Pretrained_GNN/multiclass_pretrained_model_12/model_epoch_71.pt + pretraining_path: trainings/stats_100K/pretraining_multiclass/model_epoch_100.pt # update to the last epoch of the pretraining pretraining_model: module: models.GCN class: Edge_Network @@ -20,11 +20,6 @@ Model: n_layers: 4 n_proc_steps: 4 dropout: 0 -Training: - epochs: 500 - batch_size: 1024 - learning_rate: 0.00001 - gamma: 0.99 Datasets: ttH_CP_even: &dataset_defn module: root_gnn_base.dataset @@ -41,8 +36,8 @@ Datasets: file_names: ttH_NLO.root tree_name: output fold_var: Number - raw_dir: /global/cfs/projectdirs/atlas/joshua/gnn_data/stats_all/ - save_dir: /pscratch/sd/j/joshuaho/gnn/stats_all/ttH_CP_even_vs_odd/ + raw_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/stats_all/ + save_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/processed_graphs/stats_all/ttH_CP_even_vs_odd/ node_branch_names: - [jet_pt, ele_pt, mu_pt, ph_pt, MET_met] - [jet_eta, ele_eta, mu_eta, ph_eta, 0] diff --git a/root_gnn_dgl/configs/stats_all/pretraining_multiclass.yaml b/root_gnn_dgl/configs/stats_all/pretraining_multiclass.yaml index de99ab56f6f824b98cf1aace37488e67b880c04d..8cc480f9f3956ee05dcc033f89ed05d217658de2 100644 --- a/root_gnn_dgl/configs/stats_all/pretraining_multiclass.yaml +++ b/root_gnn_dgl/configs/stats_all/pretraining_multiclass.yaml @@ -38,8 +38,8 @@ Datasets: file_names: ttH_NLO_inc.root tree_name: output fold_var: Number - raw_dir: /global/cfs/projectdirs/atlas/joshua/gnn_data/stats_all/ - save_dir: /pscratch/sd/j/joshuaho/gnn/stats_all/pretraining_multiclass/ + raw_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/stats_all/ + save_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/processed_graphs/stats_all/pretraining_multiclass/ node_branch_names: - [jet_pt, ele_pt, mu_pt, ph_pt, MET_met] - [jet_eta, ele_eta, mu_eta, ph_eta, 0] diff --git a/root_gnn_dgl/configs/stats_all/ttH_CP_even_vs_odd.yaml b/root_gnn_dgl/configs/stats_all/ttH_CP_even_vs_odd.yaml index 6aaa14e9bc08a6989a247e82456413467c9e99bd..0d074acab903084ce8895a47ba231f28732f9094 100755 --- a/root_gnn_dgl/configs/stats_all/ttH_CP_even_vs_odd.yaml +++ b/root_gnn_dgl/configs/stats_all/ttH_CP_even_vs_odd.yaml @@ -31,8 +31,8 @@ Datasets: file_names: ttH_NLO.root tree_name: output fold_var: Number - raw_dir: /global/cfs/projectdirs/atlas/joshua/gnn_data/stats_all/ - save_dir: /pscratch/sd/j/joshuaho/gnn/stats_all/ttH_CP_even_vs_odd/ + raw_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/stats_all/ + save_dir: /global/cfs/projectdirs/trn007/lbl_atlas/data/processed_graphs/stats_all/ttH_CP_even_vs_odd/ node_branch_names: - [jet_pt, ele_pt, mu_pt, ph_pt, MET_met] - [jet_eta, ele_eta, mu_eta, ph_eta, 0] diff --git a/root_gnn_dgl/jobs/cpu.sh b/root_gnn_dgl/jobs/cpu.sh index b9dabeb9f8cc1cf2f887bde1bf81bde74af204f4..ae17a41d66445d21ba5ccfb636ccda113b921eb6 100644 --- a/root_gnn_dgl/jobs/cpu.sh +++ b/root_gnn_dgl/jobs/cpu.sh @@ -1,5 +1 @@ -#!/bin/bash - -ACCOUNT="${SLURM_ACCOUNT:-atlas}" - -salloc --nodes=1 --ntasks=64 --cpus-per-task=1 --qos=interactive --time=04:00:00 --constraint=cpu --account="$ACCOUNT" +salloc --nodes=1 --ntasks=64 --cpus-per-task=1 --qos=interactive --time=04:00:00 --constraint=cpu --account=trn007 diff --git a/root_gnn_dgl/jobs/inference/run_inference.py b/root_gnn_dgl/jobs/inference/run_inference.py index 014a5bb1079a1bfe4567ef653c5034f64e83c153..b393af6d25073ad269af1d82d0e912d93587ad7d 100644 --- a/root_gnn_dgl/jobs/inference/run_inference.py +++ b/root_gnn_dgl/jobs/inference/run_inference.py @@ -1,277 +1,214 @@ -#!/usr/bin/env python3 - -from __future__ import annotations - -import argparse -import glob import os -import re import subprocess -import sys -from dataclasses import dataclass -from pathlib import Path - -import yaml - -try: - from mpi4py import MPI -except ImportError: - MPI = None +from mpi4py import MPI - -REPO_ROOT = Path(__file__).resolve().parents[2] +# Define the number of GPUs per node GPUS_PER_NODE = 4 - -@dataclass(frozen=True) -class InferenceTask: - target: Path - destination: Path - - -def load_config(path: Path) -> dict: - with path.open("r", encoding="utf-8") as handle: - return yaml.safe_load(handle) - - -def repo_relative(path: Path) -> str: - try: - return str(path.resolve().relative_to(REPO_ROOT)) - except ValueError: - return str(path) - - -def resolve_path(raw_path: str) -> Path: - path = Path(raw_path).expanduser() - if path.is_absolute(): - return path.resolve() - - repo_path = (REPO_ROOT / path).resolve() - if repo_path.exists() or str(raw_path).startswith(("configs/", "jobs/", "scripts/")): - return repo_path - - return (Path.cwd() / path).resolve() - - -def sanitize_branch_name(name: str) -> str: - cleaned = re.sub(r"\W+", "_", name).strip("_") - if not cleaned: - cleaned = "gnn" - if cleaned[0].isdigit(): - cleaned = f"gnn_{cleaned}" - return f"{cleaned}_score" - - -def discover_model_configs(raw_configs: list[str], raw_config_dirs: list[str]) -> list[Path]: - configs = [] - for raw_config in raw_configs: - config = resolve_path(raw_config) - if not config.is_file(): - raise FileNotFoundError(f"Config file does not exist: {config}") - configs.append(config) - - for raw_dir in raw_config_dirs: - config_dir = resolve_path(raw_dir) - if not config_dir.is_dir(): - raise NotADirectoryError(f"Config directory does not exist: {config_dir}") - configs.extend(sorted(path.resolve() for path in config_dir.glob("*.yaml"))) - - unique_configs = [] - seen = set() - for config in configs: - if config not in seen: - unique_configs.append(config) - seen.add(config) - if not unique_configs: - raise ValueError("No model configs were provided.") - return unique_configs - - -def default_branch_names(config_paths: list[Path]) -> list[str]: - branch_names = [] - for config_path in config_paths: - config = load_config(config_path) - training_name = config.get("Training_Name") or config_path.stem - branch_names.append(sanitize_branch_name(str(training_name))) - return branch_names - - -def discover_targets_from_config(sample_config_path: Path) -> list[Path]: - config = load_config(sample_config_path) - targets = [] - - for dataset_name, dataset_config in config.get("Datasets", {}).items(): - args = dataset_config.get("args", {}) - raw_dir = args.get("raw_dir") - file_names = args.get("file_names") - if not raw_dir or not file_names: - raise ValueError(f"Dataset {dataset_name} is missing raw_dir or file_names.") - - patterns = file_names if isinstance(file_names, list) else [file_names] - for pattern in patterns: - matches = sorted(Path(path).resolve() for path in glob.glob(os.path.join(raw_dir, pattern))) - if not matches: - raise FileNotFoundError(f"No files matched {os.path.join(raw_dir, pattern)}") - targets.extend(matches) - - unique_targets = [] - seen = set() - for target in targets: - if target not in seen: - unique_targets.append(target) - seen.add(target) - return unique_targets - - -def discover_targets(raw_targets: list[str], sample_config: str | None) -> list[Path]: - targets = [] - if sample_config: - targets.extend(discover_targets_from_config(resolve_path(sample_config))) - - for raw_target in raw_targets: - matches = sorted(Path(path).resolve() for path in glob.glob(str(resolve_path(raw_target)))) - if matches: - targets.extend(matches) +# Define your files, configs, and branch namesfiles = [ +files = [ + "merged_aMCPy8_tHjb125_CP_0_AF3_had_scaled.root", + "merged_aMCPy8_tHjb125_CP_0_AF3_lep_scaled.root", + "merged_aMCPy8_tHjb125_CP_0_FullSim_had_scaled.root", + "merged_aMCPy8_tHjb125_CP_0_FullSim_lep_scaled.root", + "merged_aMCPy8_tHjb125_CP_15_AF3_had_scaled.root", + "merged_aMCPy8_tHjb125_CP_15_AF3_lep_scaled.root", + "merged_aMCPy8_tHjb125_CP_30_AF3_had_scaled.root", + "merged_aMCPy8_tHjb125_CP_30_AF3_lep_scaled.root", + "merged_aMCPy8_tHjb125_CP_45_AF3_had_scaled.root", + "merged_aMCPy8_tHjb125_CP_45_AF3_lep_scaled.root", + "merged_aMCPy8_tHjb125_CP_45_FullSim_had_scaled.root", + "merged_aMCPy8_tHjb125_CP_45_FullSim_lep_scaled.root", + "merged_aMCPy8_tHjb125_CP_60_AF3_had_scaled.root", + "merged_aMCPy8_tHjb125_CP_60_AF3_lep_scaled.root", + "merged_aMCPy8_tHjb125_CP_75_AF3_had_scaled.root", + "merged_aMCPy8_tHjb125_CP_75_AF3_lep_scaled.root", + "merged_aMCPy8_tHjb125_CP_90_AF3_had_scaled.root", + "merged_aMCPy8_tHjb125_CP_90_AF3_lep_scaled.root", + "merged_aMCPy8_ttH125_CP_0_AF3_had_scaled.root", + "merged_aMCPy8_ttH125_CP_0_AF3_lep_scaled.root", + "merged_aMCPy8_ttH125_CP_0_FullSim_had_scaled.root", + "merged_aMCPy8_ttH125_CP_0_FullSim_lep_scaled.root", + "merged_aMCPy8_ttH125_CP_15_AF3_had_scaled.root", + "merged_aMCPy8_ttH125_CP_15_AF3_lep_scaled.root", + "merged_aMCPy8_ttH125_CP_30_AF3_had_scaled.root", + "merged_aMCPy8_ttH125_CP_30_AF3_lep_scaled.root", + "merged_aMCPy8_ttH125_CP_45_AF3_had_scaled.root", + "merged_aMCPy8_ttH125_CP_45_AF3_lep_scaled.root", + "merged_aMCPy8_ttH125_CP_45_FullSim_had_scaled.root", + "merged_aMCPy8_ttH125_CP_45_FullSim_lep_scaled.root", + "merged_aMCPy8_ttH125_CP_60_AF3_had_scaled.root", + "merged_aMCPy8_ttH125_CP_60_AF3_lep_scaled.root", + "merged_aMCPy8_ttH125_CP_75_AF3_had_scaled.root", + "merged_aMCPy8_ttH125_CP_75_AF3_lep_scaled.root", + "merged_aMCPy8_ttH125_CP_90_AF3_had_scaled.root", + "merged_aMCPy8_ttH125_CP_90_AF3_lep_scaled.root", + "merged_aMCPy8_tWH125_CP_0_AF3_had_scaled.root", + "merged_aMCPy8_tWH125_CP_0_AF3_lep_scaled.root", + "merged_aMCPy8_tWH125_CP_0_FullSim_had_scaled.root", + "merged_aMCPy8_tWH125_CP_0_FullSim_lep_scaled.root", + "merged_aMCPy8_tWH125_CP_15_AF3_had_scaled.root", + "merged_aMCPy8_tWH125_CP_15_AF3_lep_scaled.root", + "merged_aMCPy8_tWH125_CP_30_AF3_had_scaled.root", + "merged_aMCPy8_tWH125_CP_30_AF3_lep_scaled.root", + "merged_aMCPy8_tWH125_CP_45_AF3_had_scaled.root", + "merged_aMCPy8_tWH125_CP_45_AF3_lep_scaled.root", + "merged_aMCPy8_tWH125_CP_45_FullSim_had_scaled.root", + "merged_aMCPy8_tWH125_CP_45_FullSim_lep_scaled.root", + "merged_aMCPy8_tWH125_CP_60_AF3_had_scaled.root", + "merged_aMCPy8_tWH125_CP_60_AF3_lep_scaled.root", + "merged_aMCPy8_tWH125_CP_75_AF3_had_scaled.root", + "merged_aMCPy8_tWH125_CP_75_AF3_lep_scaled.root", + "merged_aMCPy8_tWH125_CP_90_AF3_had_scaled.root", + "merged_aMCPy8_tWH125_CP_90_AF3_lep_scaled.root", + "merged_hadnti_data.root", + "merged_hadti_data.root", + "merged_lepnti_data.root", + "merged_lepti_data.root", + "merged_MGPy8_ttyy_combined_FullSim_had_scaled.root", + "merged_MGPy8_ttyy_combined_FullSim_lep_scaled.root", + "merged_PhPy8_4FS_A14NNPDF_bbH125_FullSim_had_scaled.root", + "merged_PhPy8_4FS_A14NNPDF_bbH125_FullSim_lep_scaled.root", + "merged_PhPy8_ggH125_NNLOPS_FullSim_had_scaled.root", + "merged_PhPy8_ggH125_NNLOPS_FullSim_lep_scaled.root", + "merged_PhPy8_ggZH125_FullSim_had_scaled.root", + "merged_PhPy8_ggZH125_FullSim_lep_scaled.root", + "merged_PhPy8_VBFH125_FullSim_had_scaled.root", + "merged_PhPy8_VBFH125_FullSim_lep_scaled.root", + "merged_PhPy8_WmH125J_MINLO_FullSim_had_scaled.root", + "merged_PhPy8_WmH125J_MINLO_FullSim_lep_scaled.root", + "merged_PhPy8_WpH125J_MINLO_FullSim_had_scaled.root", + "merged_PhPy8_WpH125J_MINLO_FullSim_lep_scaled.root", + "merged_PhPy8_ZH125J_MINLO_FullSim_had_scaled.root", + "merged_PhPy8_ZH125J_MINLO_FullSim_lep_scaled.root", +] +# Configurations for each type of file +config = [ + "configs/model_configs/run_3_ttH/v06/sb_yukawa_no_weights.yaml", + "configs/model_configs/run_3_ttH/v06/sb_yukawa_weights.yaml", + "configs/model_configs/run_3_ttH/v06/tHjb_CP_no_weights.yaml", + "configs/model_configs/run_3_ttH/v06/tHjb_CP_weights.yaml", + "configs/model_configs/run_3_ttH/v06/ttH_CP_no_weights.yaml", + "configs/model_configs/run_3_ttH/v06/ttH_CP_weights.yaml", + "configs/model_configs/run_3_ttH/v06/ttH_tHjb_tWH_CP_no_weights.yaml", + "configs/model_configs/run_3_ttH/v06/ttH_tHjb_tWH_CP_weights.yaml", + "configs/model_configs/run_3_ttH/v06/tWH_CP_no_weights.yaml", + "configs/model_configs/run_3_ttH/v06/tWH_CP_weights.yaml", + +] + +# Branch names for each type of file +branch_name = [ + "sb_yukawa_no_weights_score", + "sb_yukawa_weights_score", + "tHjb_CP_no_weights_score", + "tHjb_CP_weights_score", + "ttH_CP_no_weights_score", + "ttH_CP_weights_score", + "ttH_tHjb_tWH_CP_no_weights_score", + "ttH_tHjb_tWH_CP_weights_score", + "tWH_CP_no_weights_score", + "tWH_CP_weights_score", +] + +# MPI Initialization +comm = MPI.COMM_WORLD +rank = comm.Get_rank() # Process rank (unique ID for each process) +size = comm.Get_size() # Total number of processes across all nodes + +# Master process manages the task queue +def master(): + num_workers = size - 1 # Exclude the master process + task_queue = files[:] # Copy the list of files + workers_busy = [False] * num_workers # Track if workers are busy + + print(f"Master process starting with {num_workers} workers.") + + # Distribute initial tasks to workers + for worker_rank in range(1, size): + if task_queue: + # Send a file to the worker + file = task_queue.pop(0) + comm.send(file, dest=worker_rank, tag=0) + workers_busy[worker_rank - 1] = True else: - target = resolve_path(raw_target) - if not target.exists(): - raise FileNotFoundError(f"Target does not exist: {target}") - targets.append(target) - - unique_targets = [] - seen = set() - for target in targets: - if target not in seen: - unique_targets.append(target) - seen.add(target) - if not unique_targets: - raise ValueError("No inference targets were provided.") - return unique_targets - - -def build_tasks(targets: list[Path], output_dir: Path) -> list[InferenceTask]: - output_dir.mkdir(parents=True, exist_ok=True) - return [InferenceTask(target=target, destination=(output_dir / target.name).resolve()) for target in targets] - - -def build_command( - task: InferenceTask, - config_paths: list[Path], - branch_names: list[str], - args: argparse.Namespace, -) -> list[str]: - command = [ - sys.executable, - "scripts/inference.py", - "--target", - str(task.target), - "--destination", - str(task.destination), - "--config", - *[str(path) for path in config_paths], - "--branch_name", - *branch_names, - "--chunks", - str(args.chunks), - "--chunkno", - str(args.chunkno), - ] - - if args.write: - command.append("--write") - if args.clobber: - command.append("--clobber") - if args.ckpt is not None: - command.extend(["--ckpt", str(args.ckpt)]) - if args.var: - command.extend(["--var", args.var]) - if args.mode: - command.extend(["--mode", args.mode]) - if args.tree: - command.extend(["--tree", args.tree]) - return command - - -def run_task( - task: InferenceTask, - config_paths: list[Path], - branch_names: list[str], - args: argparse.Namespace, - rank: int, -) -> int: - gpu_id = rank % GPUS_PER_NODE - env = os.environ.copy() - env["CUDA_VISIBLE_DEVICES"] = str(gpu_id) - command = build_command(task, config_paths, branch_names, args) - - print( - f"[rank {rank}] target={task.target} destination={task.destination} gpu={gpu_id}", - flush=True, - ) - print(f"[rank {rank}] command={' '.join(command)}", flush=True) - if args.test: - return 0 - return subprocess.run(command, cwd=REPO_ROOT, env=env).returncode - - -def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser( - description="Run scripts/inference.py over many ROOT files with many model configs." - ) - parser.add_argument("--sample-config", help="Config whose dataset file_names define inference targets.") - parser.add_argument("--target", nargs="*", default=[], help="Target ROOT files or glob patterns.") - parser.add_argument("--config", nargs="*", default=[], help="Model config files to score.") - parser.add_argument("--config-dir", nargs="*", default=[], help="Directories containing model YAML configs.") - parser.add_argument("--branch-name", nargs="*", default=[], help="Score branch names. Defaults to Training_Name_score.") - parser.add_argument("--output-dir", required=True, help="Directory for output ROOT/NPZ files.") - parser.add_argument("--chunks", type=int, default=1) - parser.add_argument("--chunkno", type=int, default=0) - parser.add_argument("--write", action="store_true", help="Write ROOT files with score branches.") - parser.add_argument("--clobber", action="store_true") - parser.add_argument("--ckpt", type=int, default=None, help="Checkpoint epoch. Omit to let scripts/inference.py choose best epoch.") - parser.add_argument("--var", default="Test_AUC") - parser.add_argument("--mode", default="max") - parser.add_argument("--tree", default="") - parser.add_argument("--test", action="store_true", help="Print planned commands without running inference.") - return parser.parse_args() - - -def main() -> int: - args = parse_args() - config_paths = discover_model_configs(args.config, args.config_dir) - branch_names = args.branch_name or default_branch_names(config_paths) - if len(branch_names) != len(config_paths): - raise ValueError("--branch-name count must match the number of model configs.") - - targets = discover_targets(args.target, args.sample_config) - tasks = build_tasks(targets, resolve_path(args.output_dir)) - - print(f"Repo root: {REPO_ROOT}", flush=True) - print(f"Targets: {len(tasks)}", flush=True) - print(f"Model configs: {len(config_paths)}", flush=True) - print("Branches:", " ".join(branch_names), flush=True) - - if MPI is None: - failures = 0 - for task in tasks: - failures += int(run_task(task, config_paths, branch_names, args, rank=0) != 0) - return 1 if failures else 0 - - comm = MPI.COMM_WORLD - rank = comm.Get_rank() - size = comm.Get_size() - - failures = 0 - for index, task in enumerate(tasks): - if index % size != rank: - continue - failures += int(run_task(task, config_paths, branch_names, args, rank=rank) != 0) - - total_failures = comm.allreduce(failures, op=MPI.SUM) - if rank == 0: - print(f"Completed {len(tasks) - total_failures} task(s); failed {total_failures}.", flush=True) - return 1 if total_failures else 0 - - + # No tasks left, send termination signal + comm.send(None, dest=worker_rank, tag=1) + + # Process results and assign new tasks dynamically + while any(workers_busy): + # Receive results from workers + status = MPI.Status() + result = comm.recv(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG, status=status) + worker_rank = status.Get_source() + workers_busy[worker_rank - 1] = False # Worker is now free + + # Assign a new task if available + if task_queue: + file = task_queue.pop(0) + comm.send(file, dest=worker_rank, tag=0) + workers_busy[worker_rank - 1] = True + else: + # No tasks left, send termination signal + comm.send(None, dest=worker_rank, tag=1) + + print("Master process: All tasks completed.") + +# Worker processes handle tasks dynamically +def worker(): + gpu_id = (rank - 1) % GPUS_PER_NODE # Assign GPU ID based on rank + print(f"Worker {rank} starting, GPU ID: {gpu_id}", flush=True) + + while True: + # Receive a task from the master + file = comm.recv(source=0, tag=MPI.ANY_TAG) + if file is None: + # Termination signal received + print(f"Worker {rank}: Termination signal received.") + break + + # Initialize config and branch_name for each file + local_config = config[:] # Create a copy of the global config + local_branch_name = branch_name[:] # Create a copy of the global branch_name + + # Determine file type and append appropriate configurations + if "had" in file: + local_config += had_config # Append had-specific configurations + local_branch_name += had_branch_name # Append had-specific branch names + elif "lep" in file: + local_config += lep_config # Append lep-specific configurations + local_branch_name += lep_branch_name # Append lep-specific branch names + + # Process the file + print(f"Worker {rank}: Processing file {file} on GPU {gpu_id}", flush=True) + print(f"branches = {local_branch_name}") + target = f"/global/cfs/projectdirs/atlas/joshua/ttHCP/ntuples/v02/preselection/merged/{file}" + destination = f"/global/cfs/projectdirs/atlas/joshua/ttHCP/ntuples/scores/gnn_v06/{file}" + + # Set the GPU for this process + os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id) + + # Build the command + command = [ + "python", "scripts/inference.py", + "--target", target, + "--destination", destination, + "--config", *local_config, + "--branch_name", *local_branch_name, + "--chunks", "1", + "--chunkno", "0", + "--write" + ] + + # Execute the command + subprocess.run(command) + + # Notify the master that the task is complete + comm.send(f"Worker {rank}: Finished {file}", dest=0, tag=0) + +# Main function if __name__ == "__main__": - sys.exit(main()) + if rank == 0: + master() + else: + worker() \ No newline at end of file diff --git a/root_gnn_dgl/jobs/interactive.sh b/root_gnn_dgl/jobs/interactive.sh index 0920e5c02f41e85c7588d6fd8d8908c88887507b..8197dd547c8fd7292172146af10d734a68ddaadb 100644 --- a/root_gnn_dgl/jobs/interactive.sh +++ b/root_gnn_dgl/jobs/interactive.sh @@ -1,5 +1 @@ -#!/bin/bash - -ACCOUNT="${SLURM_ACCOUNT:-atlas}" - -salloc --nodes 1 --qos shared_interactive --time 04:00:00 --constraint gpu --account="$ACCOUNT" --gres=gpu:1 +salloc --nodes 1 --qos shared_interactive --time 04:00:00 --constraint gpu --account=trn007 --gres=gpu:1 diff --git a/root_gnn_dgl/jobs/prep_data/run_processing.py b/root_gnn_dgl/jobs/prep_data/run_processing.py index 7ae76366d7bae354fb731cc9608c13f6aa6e8039..3cf70ffaf38af5bc5484dae3a537ea70be771d67 100644 --- a/root_gnn_dgl/jobs/prep_data/run_processing.py +++ b/root_gnn_dgl/jobs/prep_data/run_processing.py @@ -1,9 +1,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed -import argparse import yaml import os import subprocess -from pathlib import Path def extract_dataset_keys_and_chunks(yaml_file): """ @@ -36,27 +34,21 @@ def call_bash_script(config, dataset_key, shuffle_chunks, bash_script): """ try: # Construct the command to call the bash script - command = [bash_script, config, dataset_key, str(shuffle_chunks)] + command = f"{bash_script} {config} {dataset_key} {shuffle_chunks}" - print(f"Executing command: {' '.join(command)}") + print(f"Executing command: {command}") # Debugging: Print the command being executed - result = subprocess.run(command, check=True, capture_output=True, text=True) - if result.stdout: - print(result.stdout, end="") - if result.stderr: - print(result.stderr, end="") + # Run the command + result = subprocess.run(command, shell=True, check=True) return f"Success: {dataset_key}" except subprocess.CalledProcessError as e: - stderr = e.stderr if isinstance(e.stderr, str) else (e.stderr.decode() if e.stderr else "") - stdout = e.stdout if isinstance(e.stdout, str) else (e.stdout.decode() if e.stdout else "") - message = f"Error executing bash script for dataset {dataset_key}: {stderr or stdout or str(e)}" - return message + return f"Error executing bash script for dataset {dataset_key}: {e.stderr.decode()}" def process_yaml_file(config, base_directory, bash_script): """ Process a single YAML file by extracting datasets and calling the bash script in parallel. """ - yaml_file = os.path.join(base_directory, config) + yaml_file = os.path.join(base_directory, config) # Construct full path if os.path.exists(yaml_file): print(f"Processing file: {config}") datasets = extract_dataset_keys_and_chunks(yaml_file) @@ -78,19 +70,20 @@ def process_yaml_file(config, base_directory, bash_script): return [f"File not found: {yaml_file}"] def main(): - parser = argparse.ArgumentParser(description="Run prep_data.sh for every dataset in one or more configs.") - parser.add_argument("configs", nargs="+", help="YAML config files, relative to the repo root or absolute.") - parser.add_argument( - "--bash-script", - default=None, - help="Path to prep_data.sh. Defaults to jobs/prep_data/prep_data.sh under the repo root.", - ) - args = parser.parse_args() + # Base directory containing the YAML files + base_directory = os.getcwd() + "/" - repo_root = Path(__file__).resolve().parents[2] - base_directory = str(repo_root) + "/" - configs = [str(Path(config).resolve()) if Path(config).is_absolute() else config for config in args.configs] - bash_script = args.bash_script or str(repo_root / "jobs/prep_data/prep_data.sh") + # List of YAML configuration files (relative to the base directory) + configs = [ + # "configs/stats_100K/pretraining_multiclass.yaml", + # "configs/stats_100K/ttH_CP_even_vs_odd.yaml", + # "configs/stats_all/pretraining_multiclass.yaml", + # "configs/stats_all/ttH_CP_even_vs_odd.yaml", + "configs/attention/ttH_CP_even_vs_odd.yaml", + ] + + # Path to the bash script to be called + bash_script = base_directory + "jobs/prep_data/prep_data.sh" # Use ThreadPoolExecutor to process YAML files concurrently max_workers = os.cpu_count() # Use all available CPU cores @@ -107,4 +100,4 @@ def main(): print(result) if __name__ == "__main__": - main() + main() \ No newline at end of file diff --git a/root_gnn_dgl/jobs/salloc.sh b/root_gnn_dgl/jobs/salloc.sh index 132cfc83c1b0477af0050a94115ee7c8c55e2355..5c7f378bda998338b844af9fe35493993432518d 100644 --- a/root_gnn_dgl/jobs/salloc.sh +++ b/root_gnn_dgl/jobs/salloc.sh @@ -1,5 +1 @@ -#!/bin/bash - -ACCOUNT="${SLURM_ACCOUNT:-atlas}" - -salloc --nodes 4 --qos interactive --time 04:00:00 --constraint gpu --account="$ACCOUNT" --gres=gpu:4 +salloc --nodes 4 --qos interactive --time 04:00:00 --constraint gpu --account=trn007 --gres=gpu:4 diff --git a/root_gnn_dgl/jobs/training/conda/run_job.sh b/root_gnn_dgl/jobs/training/conda/run_job.sh deleted file mode 100755 index 7315469900a963352a719e739172a9daa9a42c8a..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/jobs/training/conda/run_job.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/bash -#SBATCH -N 1 -#SBATCH -C gpu -#SBATCH -q shared -#SBATCH -t 15:00:00 -#SBATCH -o jobs/slurm/%j.out # STDOUT - -CONFIG=$1 -shift -ARGUMENTS=("$@") - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" - -cd "$REPO_ROOT" -mkdir -p jobs/slurm - -eval "$(conda shell.bash hook)" -conda activate "${ROOT_GNN_CONDA_ENV:-dgl}" - -COMMAND=( - "$REPO_ROOT/scripts/training_script.py" - "${ARGUMENTS[@]}" - "--preshuffle" - "--nocompile" - "--lazy" - "--config" - "$CONFIG" -) - -echo "Running my script now" -echo "Executing: python -u ${COMMAND[*]}" -python -u "${COMMAND[@]}" -echo "Done" diff --git a/root_gnn_dgl/jobs/training/conda/submit.sh b/root_gnn_dgl/jobs/training/conda/submit.sh deleted file mode 100644 index a0b85c7cc2c807f8ab40388e9d0990e74f414147..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/jobs/training/conda/submit.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash - -date - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" -RUN_JOB="$REPO_ROOT/jobs/training/conda/run_job.sh" -SBATCH_ACCOUNT_ARGS=() -if [ -n "${SLURM_ACCOUNT:-}" ]; then - SBATCH_ACCOUNT_ARGS=(--account "$SLURM_ACCOUNT") -fi - -default_configs=( - "configs/stats_all/ttH_CP_even_vs_odd.yaml" - "configs/stats_all/ttH_CP_even_vs_odd_batch_size_2048.yaml" - "configs/stats_all/ttH_CP_even_vs_odd_batch_size_4096.yaml" - "configs/stats_all/ttH_CP_even_vs_odd_batch_size_8192.yaml" -) - -if [ "$#" -gt 0 ]; then - configs=("$@") -else - configs=("${default_configs[@]}") -fi - -counter=0 - -hours=12 -time="${hours}:00:00" - -for job in "${configs[@]}" -do - sbatch "${SBATCH_ACCOUNT_ARGS[@]}" --job-name="$job" --time="$time" "$RUN_JOB" "$job" - ((counter++)) -done - -echo "Total jobs submitted: $counter" diff --git a/root_gnn_dgl/jobs/training/multinode/run_multinode_1.sh b/root_gnn_dgl/jobs/training/multinode/run_multinode_1.sh new file mode 100755 index 0000000000000000000000000000000000000000..f15bbf9051b700e77344bffaad4670c856538092 --- /dev/null +++ b/root_gnn_dgl/jobs/training/multinode/run_multinode_1.sh @@ -0,0 +1,51 @@ +#!/bin/bash +#SBATCH -C gpu +#SBATCH -N 4 +#SBATCH --gres=gpu:4 +#SBATCH -q regular +#SBATCH --mail-user=ho22joshua@berkeley.edu +#SBATCH --mail-type=ALL +#SBATCH -t 05:00:00 +#SBATCH -A atlas +#SBATCH -o /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/jobs/slurm/%j.out # STDOUT + + +CONFIG="$*" + +echo "Executing command: $CONFIG" + +cd /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/ + +eval "$(conda shell.bash hook)" +conda init bash +conda activate /global/homes/j/joshuaho/.conda/envs/dgl + +# Run the Python script and capture the output +MASTER_PORT=$(python /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/scripts/find_free_port.py) + +# export MASTER_ADDR=$(hostname) +export MASTER_PORT=$MASTER_PORT + +# Dynamically get the hostname of the first node in the allocation to use as MASTER_ADDR +export MASTER_ADDR=$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n 1) + +# Debugging: Print the master address and port +echo "Master Address: $MASTER_ADDR" +echo "Master Port: $MASTER_PORT" + +TORCHRUN_ARGUMENTS="--nnodes=$SLURM_NNODES \ + --nproc-per-node=$SLURM_GPUS_ON_NODE \ + --rdzv-id=$SLURM_JOB_ID \ + --rdzv-backend=c10d \ + --rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT" + +GPUS=$(( $SLURM_NNODES * 4 )) + +echo GPUS: $GPUS + +srun --gpus=$GPUS \ + --ntasks-per-node=1 \ + /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/launch_image.sh \ + "--entrypoint /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/jobs/run_multinode_2.sh" \ + $TORCHRUN_ARGUMENTS \ + $CONFIG \ No newline at end of file diff --git a/root_gnn_dgl/jobs/training/multinode/run_multinode_2.sh b/root_gnn_dgl/jobs/training/multinode/run_multinode_2.sh new file mode 100755 index 0000000000000000000000000000000000000000..2b890388629f5c2b7d2b7a4498cddca827986bfd --- /dev/null +++ b/root_gnn_dgl/jobs/training/multinode/run_multinode_2.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +TORCHRUN_ARGUMENTS="$1 $2 $3 $4 $5" +shift 5 +TRAIN_ARGUMENTS="$@" + +# Print the entire argument string +echo "TORCHRUN_ARGUMENTS: $TORCHRUN_ARGUMENTS" +echo "TRAIN_ARGUMENTS: $TRAIN_ARGUMENTS" + +cd /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/ + +DIRECTORY="/global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/configs/model_configs/" +COMMAND="/global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/scripts/training_script.py --preshuffle --nocompile --lazy --config $DIRECTORY$TRAIN_ARGUMENTS" + +eval "$(conda shell.bash hook)" +conda init bash +conda activate /opt/conda/envs/dgl + +echo $COMMAND + +torchrun \ + $TORCHRUN_ARGUMENTS \ + $COMMAND \ No newline at end of file diff --git a/root_gnn_dgl/jobs/training/multinode/run_multinode_3.sh b/root_gnn_dgl/jobs/training/multinode/run_multinode_3.sh new file mode 100755 index 0000000000000000000000000000000000000000..1c9c31abb71f95201b8e9c3c9c16d44269968f1e --- /dev/null +++ b/root_gnn_dgl/jobs/training/multinode/run_multinode_3.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +CONFIG=$1 +shift +ARGUEMENTS="$*" + + +DIRECTORY="/global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/configs/model_configs/" +BASE_COMMAND="/global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/scripts/training_script.py $ARGUEMENTS --preshuffle --nocompile --lazy --config $DIRECTORY" + +echo "launched image" +cd /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/ + +COMMAND="$BASE_COMMAND$CONFIG" + +eval "$(conda shell.bash hook)" +conda init bash +conda activate /opt/conda/envs/dgl + +echo "Running my script now" +python $COMMAND + + +echo "Done" \ No newline at end of file diff --git a/root_gnn_dgl/jobs/training/multinode/submit.sh b/root_gnn_dgl/jobs/training/multinode/submit.sh new file mode 100644 index 0000000000000000000000000000000000000000..e0a24828805c5e7585e5f90b0c7a1b0e979ca6cf --- /dev/null +++ b/root_gnn_dgl/jobs/training/multinode/submit.sh @@ -0,0 +1,21 @@ +date + +DIRECTORY="/global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/configs/model_configs/" + +configs=( + 'pretraining_multilabel/multilabel_5_particle_counting.yaml --restart --multinode' + 'pretraining_multilabel/multilabel_17_higgs_kinematics.yaml --restart --multinode' + 'pretraining_multilabel/multilabel_29_top_kinematics.yaml --restart --multinode' + 'pretraining_multilabel/multilabel_41_higgs_tops_all_kinematics.yaml --restart --multinode' +) + +counter=0 + +for job in "${configs[@]}" +do + sbatch --job-name="$job" \ + /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/jobs/run_multinode_1.sh "$job" + ((counter++)) +done + +echo "Total jobs submitted: $counter" \ No newline at end of file diff --git a/root_gnn_dgl/jobs/training/podman/run_job.sh b/root_gnn_dgl/jobs/training/podman/run_job.sh deleted file mode 100755 index a6219c9f5031ed644c061ba8cf8f48905d9bcc6e..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/jobs/training/podman/run_job.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash -#SBATCH -N 1 -#SBATCH -C "gpu&hbm80g" -#SBATCH -q shared -#SBATCH -t 24:00:00 -#SBATCH -o jobs/slurm/%j.out # STDOUT - -ARGUMENTS=("$@") - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" - -cd "$REPO_ROOT" -mkdir -p jobs/slurm - -echo "Arguments: ${ARGUMENTS[*]}" - -source "$REPO_ROOT/setup/launch_image.sh" "$REPO_ROOT/jobs/training/podman/run_job_image.sh" "${ARGUMENTS[@]}" diff --git a/root_gnn_dgl/jobs/training/podman/run_job_image.sh b/root_gnn_dgl/jobs/training/podman/run_job_image.sh deleted file mode 100755 index 46c22e4265047f441e763c256b1acba9cf5773a1..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/jobs/training/podman/run_job_image.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/bash - -CONFIG=$1 -shift -# Store any other potential arguments safely -OTHER_ARGUEMENTS=("$@") - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" - -cd "$REPO_ROOT" - -# Use a bash array to build the command and its arguments -# Each element in the () is a separate argument. -COMMAND_ARGS=( - "$REPO_ROOT/scripts/training_script.py" - "${OTHER_ARGUEMENTS[@]}" - "--preshuffle" - "--nocompile" - "--lazy" - "--config" - "$CONFIG" -) - -echo "Running my script now" -# Using "@" in quotes expands the array correctly -echo "Executing: python -u ${COMMAND_ARGS[@]}" - -# The "${COMMAND_ARGS[@]}" syntax ensures each element is passed as a distinct argument -python -u "${COMMAND_ARGS[@]}" - -echo "Done" diff --git a/root_gnn_dgl/jobs/training/podman/submit.sh b/root_gnn_dgl/jobs/training/podman/submit.sh deleted file mode 100644 index ee19d1b9464c82f5b01003b6db5eafccbbf3dd9a..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/jobs/training/podman/submit.sh +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/bash - -date - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" -RUN_JOB="$REPO_ROOT/jobs/training/podman/run_job.sh" -SBATCH_ACCOUNT_ARGS=() -if [ -n "${SLURM_ACCOUNT:-}" ]; then - SBATCH_ACCOUNT_ARGS=(--account "$SLURM_ACCOUNT") -fi - -default_configs=( - # "configs/multiclass_pretraining/baseline.yaml" - # "configs/multiclass_pretraining/pretraining_batch_size/multiclass_bs_4096.yaml" - # "configs/multiclass_pretraining/pretraining_hid_size/multiclass_hid_256.yaml" - # "configs/multiclass_pretraining/pretraining_lr/multiclass_lr_1e2.yaml" - # "configs/multiclass_pretraining/pretraining_n_layers/multiclass_layers_6.yaml" - - # "configs/multiclass_pretraining/pretraining_batch_size/multiclass_bs_2048.yaml" - # "configs/multiclass_pretraining/pretraining_hid_size/multiclass_hid_128.yaml" - # "configs/multiclass_pretraining/pretraining_lr/multiclass_lr_1e3.yaml" - # "configs/multiclass_pretraining/pretraining_n_layers/multiclass_layers_5.yaml" - - # "configs/higgs_production/baseline.yaml" - # "configs/higgs_production/higgs_production_batch_size/higgs_production_bs_4096.yaml" - # "configs/higgs_production/higgs_production_hid_size/higgs_production_hid_256.yaml" - # "configs/higgs_production/higgs_production_lr/higgs_production_lr_1e2.yaml" - # "configs/higgs_production/higgs_production_n_layers/higgs_production_layers_6.yaml" - - # "configs/higgs_production/higgs_production_batch_size/higgs_production_bs_2048.yaml" - # "configs/higgs_production/higgs_production_hid_size/higgs_production_hid_128.yaml" - # "configs/higgs_production/higgs_production_lr/higgs_production_lr_1e3.yaml" - # "configs/higgs_production/higgs_production_n_layers/higgs_production_layers_5.yaml" - # "configs/higgs_production/baseline2.yaml" - # "configs/higgs_production/baseline3.yaml" - # "configs/higgs_production/baseline4.yaml" - # "configs/higgs_production/baseline5.yaml" - "configs/higgs_production/multiclass_finetuning/baseline.yaml" - "configs/higgs_production/multiclass_finetuning/baseline_lr_1e4.yaml" - "configs/higgs_production/multiclass_finetuning/baseline_lr_1e6.yaml" - "configs/higgs_production/multiclass_finetuning/multiclass_hid_128.yaml" - "configs/higgs_production/multiclass_finetuning/multiclass_hid_128_lr_1e4.yaml" - "configs/higgs_production/multiclass_finetuning/multiclass_hid_128_lr_1e6.yaml" - "configs/higgs_production/multiclass_finetuning/multiclass_hid_256.yaml" - "configs/higgs_production/multiclass_finetuning/multiclass_hid_256_lr_1e4.yaml" - "configs/higgs_production/multiclass_finetuning/multiclass_hid_256_lr_1e6.yaml" - "configs/higgs_production/multiclass_finetuning/multiclass_layers_6.yaml" - "configs/higgs_production/multiclass_finetuning/multiclass_layers_6_lr_1e4.yaml" - "configs/higgs_production/multiclass_finetuning/multiclass_layers_6_lr_1e6.yaml" - "configs/higgs_production/multiclass_finetuning/multiclass_lr_1e3.yaml" - "configs/higgs_production/multiclass_finetuning/multiclass_lr_1e3_lr_1e4.yaml" - "configs/higgs_production/multiclass_finetuning/multiclass_lr_1e3_lr_1e6.yaml" - - -) - -if [ "$#" -gt 0 ]; then - configs=("$@") -else - configs=("${default_configs[@]}") -fi - -counter=0 - -hours=24 -time="${hours}:00:00" - -for job in "${configs[@]}" -do - sbatch "${SBATCH_ACCOUNT_ARGS[@]}" --job-name="$job" --time="$time" "$RUN_JOB" "$job" - ((counter++)) -done - -echo "Total jobs submitted: $counter" diff --git a/root_gnn_dgl/jobs/training/run_parallel_trainings.py b/root_gnn_dgl/jobs/training/run_parallel_trainings.py deleted file mode 100644 index 15c663f79e3ab21dd6fb44fb61007e9a2510c265..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/jobs/training/run_parallel_trainings.py +++ /dev/null @@ -1,509 +0,0 @@ -#!/usr/bin/env python3 - -from __future__ import annotations - -import argparse -import os -import re -import shlex -import subprocess -import sys -import time -from collections import deque -from dataclasses import dataclass -from pathlib import Path -import socket - -import yaml - - -REPO_ROOT = Path(__file__).resolve().parents[2] -DEFAULT_TARGETS = ( - REPO_ROOT / "configs/higgs_production_updated_leptons", - REPO_ROOT / "configs/triboson", -) -FIXED_GPU_TOKENS = ("0", "1", "2", "3") -DEFAULT_TRAINING_ARGS = ("--preshuffle", "--nocompile", "--lazy") -FORBIDDEN_TRAINING_ARGS = {"--config", "--multigpu", "--multinode"} - - -@dataclass(frozen=True) -class ExecutionSlot: - gpu_token: str - - -@dataclass -class TrainingJob: - config_path: Path - training_directory: str - pretraining_path: Path | None - - -@dataclass -class ActiveProcess: - job: TrainingJob - slot: ExecutionSlot - log_path: Path - log_handle: object - process: subprocess.Popen - - -def parse_args() -> tuple[argparse.Namespace, list[str]]: - parser = argparse.ArgumentParser( - description=( - "Queue local single-GPU trainings on the current node only. This launcher " - "is intentionally hard-coded to use GPUs 0,1,2,3 with no srun or multi-node logic." - ), - epilog=( - "Unknown arguments are forwarded to scripts/training_script.py. " - "Example: python jobs/training/run_parallel_trainings.py --split 1/2 --restart --seed 7" - ), - ) - parser.add_argument( - "targets", - nargs="*", - help=( - "Config files or directories. Defaults to " - "configs/higgs_production_updated_leptons and configs/triboson." - ), - ) - parser.add_argument( - "--split", - type=str, - help=( - "Run only one deterministic slice of the config queue, formatted as K/N. " - "Example: --split 1/2 for the first half and --split 2/2 for the second." - ), - ) - parser.add_argument( - "--logs-root", - type=str, - default="jobs/slurm/parallel_training_logs", - help="Directory where launcher stdout/stderr logs should be written.", - ) - parser.add_argument( - "--stop-on-failure", - action="store_true", - help="Stop launching new trainings after the first failure.", - ) - parser.add_argument( - "--ignore-missing-pretraining", - action="store_true", - help="Launch even if a finetuning config points to a missing pretraining checkpoint.", - ) - parser.add_argument( - "--test", - action="store_true", - help="Run preflight checks and print the launch plan without starting trainings.", - ) - parser.add_argument( - "--poll-seconds", - type=float, - default=10.0, - help="Seconds between checks for finished trainings.", - ) - - # Accepted only so older commands do not fail; these are ignored in the - # single-node hard-coded launcher. - parser.add_argument("--gpus", type=str, help=argparse.SUPPRESS) - parser.add_argument("--nodelist", type=str, help=argparse.SUPPRESS) - parser.add_argument("--local-only", action="store_true", help=argparse.SUPPRESS) - parser.add_argument("--srun-binary", type=str, help=argparse.SUPPRESS) - parser.add_argument("--scontrol-binary", type=str, help=argparse.SUPPRESS) - parser.add_argument("--max-parallel", type=int, help=argparse.SUPPRESS) - parser.add_argument("--dry-run", action="store_true", help=argparse.SUPPRESS) - - args, forwarded_args = parser.parse_known_args() - return args, forwarded_args - - -def repo_relative(path: Path) -> str: - try: - return str(path.resolve().relative_to(REPO_ROOT)) - except ValueError: - return str(path.resolve()) - - -def resolve_target(raw_target: str) -> Path: - raw_path = Path(raw_target).expanduser() - if raw_path.is_absolute(): - return raw_path.resolve() - - repo_candidate = (REPO_ROOT / raw_path).resolve() - if repo_candidate.exists(): - return repo_candidate - - return (Path.cwd() / raw_path).resolve() - - -def discover_configs(raw_targets: list[str]) -> list[Path]: - targets = [resolve_target(raw_target) for raw_target in raw_targets] if raw_targets else list(DEFAULT_TARGETS) - configs: list[Path] = [] - - for target in targets: - if target.is_file(): - if target.suffix != ".yaml": - raise FileNotFoundError(f"Expected a .yaml config file, got {target}") - configs.append(target) - continue - - if not target.is_dir(): - raise FileNotFoundError(f"Config target does not exist: {target}") - - configs.extend(sorted(path.resolve() for path in target.glob("*.yaml"))) - - unique_configs = [] - seen = set() - for config in configs: - if config not in seen: - unique_configs.append(config) - seen.add(config) - return unique_configs - - -def resolve_checkpoint_path(raw_path: str) -> Path: - candidate = Path(raw_path).expanduser() - if candidate.is_absolute(): - return candidate.resolve() - return (REPO_ROOT / candidate).resolve() - - -def load_job(config_path: Path) -> TrainingJob: - with config_path.open("r", encoding="utf-8") as handle: - config = yaml.safe_load(handle) - - if not isinstance(config, dict): - raise ValueError(f"Config is not a YAML mapping: {config_path}") - - training_directory = config.get("Training_Directory") - if not training_directory: - raise ValueError(f"Config is missing Training_Directory: {config_path}") - - pretraining_path = None - model_args = config.get("Model", {}).get("args", {}) - if isinstance(model_args, dict) and model_args.get("pretraining_path"): - pretraining_path = resolve_checkpoint_path(model_args["pretraining_path"]) - - return TrainingJob( - config_path=config_path.resolve(), - training_directory=str(training_directory), - pretraining_path=pretraining_path, - ) - - -def parse_split_spec(raw_split: str | None) -> tuple[int, int] | None: - if raw_split is None: - return None - - match = re.fullmatch(r"\s*(\d+)\s*/\s*(\d+)\s*", raw_split) - if not match: - raise ValueError( - f"Invalid --split value {raw_split!r}. Use the format K/N, for example 1/2." - ) - - split_index = int(match.group(1)) - split_count = int(match.group(2)) - - if split_count <= 0: - raise ValueError("--split requires N > 0.") - if split_index <= 0: - raise ValueError("--split requires K >= 1.") - if split_index > split_count: - raise ValueError("--split requires K <= N.") - - return split_index, split_count - - -def select_jobs_for_split( - jobs: list[TrainingJob], - split_spec: tuple[int, int] | None, -) -> tuple[list[TrainingJob], str | None]: - if split_spec is None: - return jobs, None - - split_index, split_count = split_spec - selected_jobs = [ - job for index, job in enumerate(jobs) - if index % split_count == (split_index - 1) - ] - return selected_jobs, f"{split_index}/{split_count}" - - -def validate_forwarded_args(forwarded_args: list[str]) -> None: - normalized_args = [arg.split("=", 1)[0] for arg in forwarded_args] - forbidden = sorted(arg for arg in normalized_args if arg in FORBIDDEN_TRAINING_ARGS) - if forbidden: - joined = ", ".join(forbidden) - raise ValueError( - f"These training arguments are controlled by the launcher and cannot be forwarded: {joined}" - ) - - -def warn_about_ignored_args(args: argparse.Namespace) -> None: - ignored = [] - - if args.gpus: - ignored.append("--gpus") - if args.nodelist: - ignored.append("--nodelist") - if args.local_only: - ignored.append("--local-only") - if args.srun_binary: - ignored.append("--srun-binary") - if args.scontrol_binary: - ignored.append("--scontrol-binary") - if args.max_parallel is not None: - ignored.append("--max-parallel") - if args.dry_run: - ignored.append("--dry-run") - - if ignored: - print( - "Ignoring launcher options not used by the single-node version: " - + ", ".join(ignored), - flush=True, - ) - - -def format_slot(slot: ExecutionSlot, hostname: str) -> str: - return f"{hostname}:gpu{slot.gpu_token}" - - -def sanitize_log_name(config_path: Path) -> str: - try: - relative = config_path.resolve().relative_to(REPO_ROOT) - name = "__".join(relative.parts) - except ValueError: - name = config_path.name - return f"{name}.log" - - -def terminate_active_processes(active_processes: list[ActiveProcess]) -> None: - for active in active_processes: - if active.process.poll() is None: - active.process.terminate() - - deadline = time.time() + 10 - while time.time() < deadline: - if all(active.process.poll() is not None for active in active_processes): - break - time.sleep(0.5) - - for active in active_processes: - if active.process.poll() is None: - active.process.kill() - - for active in active_processes: - if not active.log_handle.closed: - active.log_handle.close() - - -def build_training_command(job: TrainingJob, forwarded_args: list[str]) -> list[str]: - return [ - sys.executable, - "scripts/training_script.py", - "--config", - str(job.config_path), - *DEFAULT_TRAINING_ARGS, - *forwarded_args, - ] - - -def launch_job( - job: TrainingJob, - slot: ExecutionSlot, - forwarded_args: list[str], - log_dir: Path, - hostname: str, -) -> ActiveProcess: - log_path = log_dir / sanitize_log_name(job.config_path) - log_path.parent.mkdir(parents=True, exist_ok=True) - log_handle = log_path.open("w", encoding="utf-8") - - command = build_training_command(job, forwarded_args) - - env = os.environ.copy() - env["CUDA_VISIBLE_DEVICES"] = slot.gpu_token - - process = subprocess.Popen( - command, - cwd=REPO_ROOT, - env=env, - stdout=log_handle, - stderr=subprocess.STDOUT, - ) - - print( - f"[launch] slot={format_slot(slot, hostname)} config={repo_relative(job.config_path)} " - f"log={repo_relative(log_path)}", - flush=True, - ) - - return ActiveProcess( - job=job, - slot=slot, - log_path=log_path, - log_handle=log_handle, - process=process, - ) - - -def main() -> int: - args, forwarded_args = parse_args() - validate_forwarded_args(forwarded_args) - warn_about_ignored_args(args) - split_spec = parse_split_spec(args.split) - - config_paths = discover_configs(args.targets) - if not config_paths: - raise RuntimeError("No YAML configs were found for the requested targets.") - - all_jobs = [load_job(config_path) for config_path in config_paths] - jobs, split_label = select_jobs_for_split(all_jobs, split_spec) - if not jobs: - raise RuntimeError("No configs were selected for this split.") - - duplicated_training_dirs: dict[str, Path] = {} - duplicate_messages = [] - missing_pretraining = [] - for job in jobs: - if job.training_directory in duplicated_training_dirs: - duplicate_messages.append( - f"{repo_relative(job.config_path)} conflicts with " - f"{repo_relative(duplicated_training_dirs[job.training_directory])} " - f"on Training_Directory={job.training_directory}" - ) - else: - duplicated_training_dirs[job.training_directory] = job.config_path - - if job.pretraining_path is not None and not job.pretraining_path.exists(): - missing_pretraining.append( - f"{repo_relative(job.config_path)} -> missing {job.pretraining_path}" - ) - - if duplicate_messages: - raise RuntimeError( - "Refusing to launch configs with overlapping Training_Directory values:\n" - + "\n".join(duplicate_messages) - ) - - if missing_pretraining and not args.ignore_missing_pretraining: - raise RuntimeError( - "Missing pretraining checkpoints were found:\n" - + "\n".join(missing_pretraining) - + "\nRe-run with --ignore-missing-pretraining to launch anyway." - ) - - if missing_pretraining: - print("Pretraining checkpoint warnings:", flush=True) - for message in missing_pretraining: - print(f" {message}", flush=True) - - hostname = socket.gethostname().split(".", 1)[0] - execution_slots = [ExecutionSlot(gpu_token=gpu_token) for gpu_token in FIXED_GPU_TOKENS] - max_parallel = len(execution_slots) - - timestamp = time.strftime("%Y%m%d_%H%M%S") - log_dir = (REPO_ROOT / args.logs_root / timestamp).resolve() - - print(f"Repo root: {REPO_ROOT}", flush=True) - print(f"Configs discovered: {len(all_jobs)}", flush=True) - if split_label: - print(f"Configs selected for split {split_label}: {len(jobs)}", flush=True) - else: - print(f"Configs selected: {len(jobs)}", flush=True) - print(f"Node selected: {hostname}", flush=True) - print(f"GPUs selected: {', '.join(FIXED_GPU_TOKENS)}", flush=True) - print(f"Max parallel trainings: {max_parallel}", flush=True) - print(f"Training args: {' '.join(DEFAULT_TRAINING_ARGS + tuple(forwarded_args))}", flush=True) - print(f"Launcher logs: {repo_relative(log_dir)}", flush=True) - print("Launch mode: local queued trainings only", flush=True) - - if args.test or args.dry_run: - print("Running launcher self-test; no trainings will be started.", flush=True) - for index, job in enumerate(jobs, start=1): - slot = execution_slots[(index - 1) % len(execution_slots)] - command = build_training_command(job, forwarded_args) - print( - f"[dry-run {index:02d}] slot={format_slot(slot, hostname)} " - f"dir={job.training_directory} cmd={shlex.join(command)}", - flush=True, - ) - return 0 - - log_dir.mkdir(parents=True, exist_ok=True) - - pending_jobs = deque(jobs) - free_slots = deque(execution_slots) - active_processes: list[ActiveProcess] = [] - failed_jobs: list[tuple[TrainingJob, int, Path]] = [] - completed_jobs = 0 - - try: - while pending_jobs or active_processes: - while pending_jobs and free_slots: - job = pending_jobs.popleft() - slot = free_slots.popleft() - active_processes.append(launch_job(job, slot, forwarded_args, log_dir, hostname)) - - if not active_processes: - break - - time.sleep(args.poll_seconds) - - still_active: list[ActiveProcess] = [] - for active in active_processes: - return_code = active.process.poll() - if return_code is None: - still_active.append(active) - continue - - active.log_handle.close() - free_slots.append(active.slot) - - if return_code == 0: - completed_jobs += 1 - print( - f"[done] slot={format_slot(active.slot, hostname)} " - f"config={repo_relative(active.job.config_path)} " - f"completed={completed_jobs}/{len(jobs)}", - flush=True, - ) - else: - failed_jobs.append((active.job, return_code, active.log_path)) - print( - f"[fail] slot={format_slot(active.slot, hostname)} " - f"config={repo_relative(active.job.config_path)} " - f"exit={return_code} log={repo_relative(active.log_path)}", - flush=True, - ) - if args.stop_on_failure: - pending_jobs.clear() - - active_processes = still_active - - if failed_jobs and args.stop_on_failure: - terminate_active_processes(active_processes) - active_processes = [] - break - - except KeyboardInterrupt: - print("\nInterrupted. Terminating active trainings...", flush=True) - terminate_active_processes(active_processes) - return 130 - - print(f"Completed {completed_jobs} training(s); failed {len(failed_jobs)}.", flush=True) - if failed_jobs: - for job, return_code, log_path in failed_jobs: - print( - f" {repo_relative(job.config_path)} exit={return_code} " - f"log={repo_relative(log_path)}", - flush=True, - ) - return 1 - - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/root_gnn_dgl/jobs/training/singlegpu/run_job.sh b/root_gnn_dgl/jobs/training/singlegpu/run_job.sh new file mode 100755 index 0000000000000000000000000000000000000000..cf4317b17682f4e6f16b4f406eeb4d19dcc2d541 --- /dev/null +++ b/root_gnn_dgl/jobs/training/singlegpu/run_job.sh @@ -0,0 +1,15 @@ +#!/bin/bash +#SBATCH -N 1 +#SBATCH -C gpu +#SBATCH -q shared +#SBATCH --mail-user=ho22joshua@berkeley.edu +#SBATCH --mail-type=ALL +#SBATCH -t 15:00:00 +#SBATCH -A atlas +#SBATCH -o /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/jobs/slurm/%j.out # STDOUT + +ARGUEMENTS="$*" + +echo "Arguements: $ARGUEMENTS" +echo "launching image" +source launch_image.sh "--entrypoint /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/jobs/run_job_image.sh" $ARGUEMENTS \ No newline at end of file diff --git a/root_gnn_dgl/jobs/training/singlegpu/run_job_image.sh b/root_gnn_dgl/jobs/training/singlegpu/run_job_image.sh new file mode 100755 index 0000000000000000000000000000000000000000..5f213b5e478703af57bcd897815abc45bde63793 --- /dev/null +++ b/root_gnn_dgl/jobs/training/singlegpu/run_job_image.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +CONFIG=$1 +shift +ARGUEMENTS="$*" + +DIRECTORY="/global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/configs/model_configs/" +BASE_COMMAND="/global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/scripts/training_script.py $ARGUEMENTS --preshuffle --nocompile --lazy --config $DIRECTORY" + +echo "launched image" +cd /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/ + +COMMAND="$BASE_COMMAND$CONFIG" + +eval "$(conda shell.bash hook)" +conda init bash +conda activate /opt/conda/envs/dgl + +echo "Running my script now" +echo $COMMAND +python -u $COMMAND +echo "Done" \ No newline at end of file diff --git a/root_gnn_dgl/jobs/training/singlegpu/submit.sh b/root_gnn_dgl/jobs/training/singlegpu/submit.sh new file mode 100644 index 0000000000000000000000000000000000000000..474bcd0b91cb0a56e0fa9f14c4ab4c8557334343 --- /dev/null +++ b/root_gnn_dgl/jobs/training/singlegpu/submit.sh @@ -0,0 +1,20 @@ +date + +DIRECTORY="/global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/configs/model_configs/" + +configs=( + "run_3_ttH/v05/sb_yukawa_cp_abs_weights.yaml --abs" +) + +counter=0 + +hours=12 +time="${hours}:00:00" + +for job in "${configs[@]}" +do + sbatch --job-name="$job" --time="$time" /global/cfs/projectdirs/atlas/joshua/root_gnn/root_gnn_dgl/jobs/run_job.sh "$job" + ((counter++)) +done + +echo "Total jobs submitted: $counter" \ No newline at end of file diff --git a/root_gnn_dgl/models/GCN.py b/root_gnn_dgl/models/GCN.py index 35b09bf1259a80b03db873ffc824f982ce435ded..b4fd1b47bc0d0115c9a41dd52cece8e85dc40fc9 100755 --- a/root_gnn_dgl/models/GCN.py +++ b/root_gnn_dgl/models/GCN.py @@ -1154,7 +1154,6 @@ class Attention(nn.Module): self.n_proc_steps = n_proc_steps self.layers = nn.ModuleList() self.has_global = sample_global.shape[1] != 0 - self.hid_size = hid_size gl_size = sample_global.shape[1] if self.has_global else 1 #encoder @@ -1197,7 +1196,7 @@ class Attention(nn.Module): batch_num_nodes.append(non_padded_count) start_idx = end_idx batch_num_nodes = torch.tensor(batch_num_nodes, device = g.ndata['features'].device) - sum_weights = batch_num_nodes[:, None].repeat(1, self.hid_size) + sum_weights = batch_num_nodes[:, None].repeat(1, 64) global_feats = batch_num_nodes[:, None].to(torch.float) h_global = self.global_encoder(global_feats) @@ -1365,7 +1364,6 @@ class Transferred_Learning_Attention(nn.Module): self.n_proc_steps = n_proc_steps self.layers = nn.ModuleList() self.has_global = sample_global.shape[1] != 0 - self.hid_size = hid_size gl_size = sample_global.shape[1] if self.has_global else 1 self.learning_rate = learning_rate @@ -1442,7 +1440,7 @@ class Transferred_Learning_Attention(nn.Module): batch_num_nodes.append(non_padded_count) start_idx = end_idx batch_num_nodes = torch.tensor(batch_num_nodes, device = g.ndata['features'].device) - sum_weights = batch_num_nodes[:, None].repeat(1, self.hid_size) + sum_weights = batch_num_nodes[:, None].repeat(1, 64) global_feats = batch_num_nodes[:, None].to(torch.float) h_global = self.TL_global_encoder(global_feats) @@ -1858,7 +1856,6 @@ class Clustering(nn.Module): self.n_layers = n_layers self.n_proc_steps = n_proc_steps self.layers = nn.ModuleList() - self.hid_size = hid_size if (len(sample_global) == 0): self.has_global = False else: @@ -1902,7 +1899,7 @@ class Clustering(nn.Module): batch_num_nodes.append(non_padded_count) start_idx = end_idx batch_num_nodes = torch.tensor(batch_num_nodes, device = g.ndata[features].device) - sum_weights = batch_num_nodes[:, None].repeat(1, self.hid_size) + sum_weights = batch_num_nodes[:, None].repeat(1, 64) global_feats = batch_num_nodes[:, None].to(torch.float) h_global = self.global_encoder(global_feats) diff --git a/root_gnn_dgl/profile.sh b/root_gnn_dgl/profile.sh deleted file mode 100644 index 9d3b20f528c749c34c3de3fa4389e95a16300967..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/profile.sh +++ /dev/null @@ -1,35 +0,0 @@ -nsys profile \ - -o /pscratch/sd/j/joshuaho/full_stats_profile_1_gpu_batch_size_1028 \ - --capture-range=cudaProfilerApi \ - --duration=100 \ - --force-overwrite true \ - --trace=nvtx \ - --cudabacktrace=all \ - python scripts/training_script.py --config configs/stats_all/ttH_CP_even_vs_odd.yaml --preshuffle --nocompile --lazy --restart --profile - -nsys profile \ - -o /pscratch/sd/j/joshuaho/full_stats_profile_1_gpu_batch_size_2048 \ - --capture-range=cudaProfilerApi \ - --duration=100 \ - --force-overwrite true \ - --trace=nvtx \ - --cudabacktrace=all \ - python scripts/training_script.py --config configs/stats_all/ttH_CP_even_vs_odd_batch_size_2048.yaml --preshuffle --nocompile --lazy --restart --profile - -nsys profile \ - -o /pscratch/sd/j/joshuaho/full_stats_profile_1_gpu_batch_size_4096 \ - --capture-range=cudaProfilerApi \ - --duration=100 \ - --force-overwrite=true \ - --trace=nvtx \ - --cudabacktrace=all \ - python scripts/training_script.py --config configs/stats_all/ttH_CP_even_vs_odd_batch_size_4096.yaml --preshuffle --nocompile --lazy --restart --profile - -nsys profile \ - -o /pscratch/sd/j/joshuaho/full_stats_profile_1_gpu_batch_size_8192 \ - --capture-range=cudaProfilerApi \ - --duration=100 \ - --force-overwrite true \ - --trace=nvtx \ - --cudabacktrace=all \ - python scripts/training_script.py --config configs/stats_all/ttH_CP_even_vs_odd_batch_size_8192.yaml --preshuffle --nocompile --lazy --restart --profile diff --git a/root_gnn_dgl/root_gnn_base/batched_dataset.py b/root_gnn_dgl/root_gnn_base/batched_dataset.py index 94bcc3109d7de02e3282d42d06d8fe21fdde8124..101ada4a0a7ae4c2fba01068579d190332fbe444 100644 --- a/root_gnn_dgl/root_gnn_base/batched_dataset.py +++ b/root_gnn_dgl/root_gnn_base/batched_dataset.py @@ -14,25 +14,9 @@ def GetBatchedLoader(dataset, batch_size, mask_fn = None, drop_last=True, **kwar dloader = GraphDataLoader(dataset, sampler=SubsetRandomSampler(torch.arange(len(dataset))[mask_fn(dataset)]), batch_size=batch_size, drop_last=drop_last, num_workers = 0) return dloader -class FixedOrderSampler: - def __init__(self, indices): - self.indices = indices - - def __iter__(self): - return iter(self.indices.tolist()) - - def __len__(self): - return len(self.indices) - -def hash_partition(indices, chunks, seed): - if chunks <= 1: - return torch.zeros(len(indices), dtype=torch.long) - hashed = (indices * 1103515245 + int(seed)) % 2147483647 - return hashed % chunks - #Dataset which contains prebatched shuffled graphs. Cannot be saved to disk, else batching info is lost. class PreBatchedDataset(DGLDataset): - def __init__(self, start_dataset, batch_size, mask_fn = None, drop_last=True, save_to_disk = True, suffix = '', chunks = 1, chunkno = -1, shuffle = True, padding_mode = 'NONE', hidden_size=64, shuffle_seed=12345, **kwargs): + def __init__(self, start_dataset, batch_size, mask_fn = None, drop_last=True, save_to_disk = True, suffix = '', chunks = 1, chunkno = -1, shuffle = True, padding_mode = 'NONE', **kwargs): print(f'Unused kwargs: {kwargs}') self.start_dataset = start_dataset self.start_dataset.load() @@ -41,32 +25,28 @@ class PreBatchedDataset(DGLDataset): self.chunks = chunks self.chunkno = chunkno self.mask_fn = mask_fn - if self.mask_fn == None: - self.mask_fn = lambda x: torch.ones(len(x), dtype=torch.bool) self.drop_last = drop_last self.graphs = [] self.label = [] self.padding_mode = padding_mode self.save_to_disk = save_to_disk self.shuffle = shuffle - self.shuffle_seed = shuffle_seed self.suffix = suffix self.current_chunk = None self.current_chunk_idx = -1 - self.hid_size = hidden_size super().__init__(name = start_dataset.name + '_prebatched_padded', save_dir=start_dataset.save_dir) def process(self): - dataset_indices = torch.arange(len(self.start_dataset)) - fold_indices = dataset_indices[self.mask_fn(self.start_dataset)] + first = 0 + last = len(self.start_dataset) + if self.chunks > 1 and self.chunkno >= 0: + first = int(self.chunkno / self.chunks * len(self.start_dataset)) + last = int((self.chunkno + 1) / self.chunks * len(self.start_dataset)) + print(f'Processing chunk {self.chunkno} of {self.chunks} from {first} to {last} of {len(self.start_dataset)}') + mask = torch.logical_and(torch.logical_and(self.mask_fn(self.start_dataset), torch.arange(len(self.start_dataset)) >= first), torch.arange(len(self.start_dataset)) < last) if self.shuffle: - if self.chunks > 1 and self.chunkno >= 0: - partitions = hash_partition(fold_indices, self.chunks, self.shuffle_seed) - fold_indices = fold_indices[partitions == self.chunkno] - print(f'Processing shuffled chunk {self.chunkno} of {self.chunks} with {len(fold_indices)} events from {len(self.start_dataset)} total') - dloader = GraphDataLoader(self.start_dataset, sampler=FixedOrderSampler(fold_indices), batch_size=self.batch_size, drop_last=self.drop_last) + dloader = GraphDataLoader(self.start_dataset, sampler=SubsetRandomSampler(torch.arange(len(self.start_dataset))[mask]), batch_size=self.batch_size, drop_last=self.drop_last) else: #Only don't shuffle if we're doing inference. Then we want all of the events anyways? - print(f'Processing sequential dataset with {len(self.start_dataset)} events') dloader = GraphDataLoader(self.start_dataset, sampler=SequentialSampler(self.start_dataset), batch_size=self.batch_size, drop_last=self.drop_last) self.graphs = [] self.labels = [] @@ -88,15 +68,6 @@ class PreBatchedDataset(DGLDataset): self.globals.append(global_feat) load_batch_end = time.time() print(f'Loaded {len(self.graphs)} batches in {load_batch_end - load_batch_start} seconds') - if self.shuffle and len(self.graphs) > 1: - generator = torch.Generator() - generator.manual_seed(self.shuffle_seed + 7919 * max(self.chunkno, 0)) - batch_order = torch.randperm(len(self.graphs), generator=generator).tolist() - self.graphs = [self.graphs[i] for i in batch_order] - self.labels = [self.labels[i] for i in batch_order] - self.tracking = [self.tracking[i] for i in batch_order] - self.globals = [self.globals[i] for i in batch_order] - print(f'Shuffled {len(self.graphs)} prebatched batches before padding') if self.padding_mode == 'STEPS': pad_node, pad_edge = utils.pad_size(self.batch_size, max_edges, max_nodes) elif self.padding_mode == 'FIXED': @@ -115,7 +86,7 @@ class PreBatchedDataset(DGLDataset): for i in range(len(self.graphs)): unbatched_g = dgl.unbatch(self.graphs[i]) max_num_nodes = max(g.number_of_nodes() for g in unbatched_g) - self.graphs[i] = utils.pad_batch_num_nodes(self.graphs[i], max_num_nodes, hid_size=self.hid_size) + self.graphs[i] = utils.pad_batch_num_nodes(self.graphs[i], max_num_nodes) self.batch_num_nodes.append(self.graphs[i].batch_num_nodes()) self.batch_num_edges.append(self.graphs[i].batch_num_edges()) else: diff --git a/root_gnn_dgl/root_gnn_base/dataset.py b/root_gnn_dgl/root_gnn_base/dataset.py index 8bf4c4a85c205c7c00f8880a55ce6b9ccd2baa05..dd34b01e3e1267e52ad909ddfefa076df5faf112 100644 --- a/root_gnn_dgl/root_gnn_base/dataset.py +++ b/root_gnn_dgl/root_gnn_base/dataset.py @@ -1,24 +1,20 @@ from dgl.data import DGLDataset import dgl -import uproot -import awkward as ak +import ROOT import torch import os import glob import time import numpy as np -import re from root_gnn_base import utils -FEATURE_DTYPE = torch.float32 - def node_features_from_tree(ch, node_branch_names, node_branch_types, node_feature_scales): lengths = [] for branch, node_type in zip(node_branch_names[0], node_branch_types): if node_type == 'single': lengths.append(1) elif node_type == 'vector': - lengths.append(len(ch[branch])) + lengths.append(len(getattr(ch, branch))) else: print('Unknown node branch type: {}'.format(node_type)) features = [] @@ -30,7 +26,7 @@ def node_features_from_tree(ch, node_branch_names, node_branch_types, node_featu feat = [] for i, length in enumerate(lengths): feat.extend([i,]*length) - features.append(torch.tensor(feat, dtype=FEATURE_DTYPE)) + features.append(torch.tensor(feat)) continue feat = [] itype = 0 @@ -42,14 +38,16 @@ def node_features_from_tree(ch, node_branch_names, node_branch_types, node_featu this_type_ends_at = sum(lengths[:itype+1]) feat.extend(features[0][this_type_starts_at:this_type_ends_at]*torch.cosh(features[1][this_type_starts_at:this_type_ends_at])) elif node_type == 'single': - feat.append(ch[branch]) + feat.append(getattr(ch, branch)) elif node_type == 'vector': - feat.extend(ch[branch]) + feat.extend(getattr(ch, branch)) itype += 1 - features.append(torch.as_tensor(np.asarray(feat, dtype=np.float32), dtype=FEATURE_DTYPE)) + features.append(torch.tensor(feat)) return torch.stack(features, dim=1) * node_feature_scales, lengths def full_connected_graph(n_nodes, self_loops=True): + senders = [] + receivers = [] senders = np.arange(n_nodes*n_nodes) // n_nodes receivers = np.arange(n_nodes*n_nodes) % n_nodes if not self_loops and n_nodes > 1: @@ -58,112 +56,26 @@ def full_connected_graph(n_nodes, self_loops=True): receivers = receivers[mask] return dgl.graph((senders, receivers)) -def _selection_context(ch): - if isinstance(ch, dict): - return ch - if hasattr(ch, 'GetListOfBranches'): - context = {} - for branch in ch.GetListOfBranches(): - branch_name = branch.GetName() - try: - context[branch_name] = getattr(ch, branch_name) - except Exception: - continue - return context - return vars(ch) - def check_selection(ch, selection): - if isinstance(selection, str): - return bool(eval(selection, {"__builtins__": {}}, _selection_context(ch))) var, cut, op = selection if op == '>': - return ch[var] > cut - elif op == '>=': - return ch[var] >= cut + return getattr(ch, var) > cut elif op == '<': - return ch[var] < cut - elif op == '<=': - return ch[var] <= cut + return getattr(ch, var) < cut elif op == '==': - return ch[var] == cut - elif op == '!=': - return ch[var] != cut - raise ValueError(f'Unknown selection operator: {op}') - + return getattr(ch, var) == cut + def check_selections(ch, selections): for selection in selections: if not check_selection(ch, selection): return False return True -def selection_branches(selection): - if isinstance(selection, str): - tokens = re.findall(r"\b[A-Za-z_][A-Za-z0-9_]*\b", selection) - keywords = {"and", "or", "not", "True", "False"} - return [tok for tok in tokens if tok not in keywords] - if isinstance(selection, (list, tuple)) and len(selection) > 0: - return [selection[0]] - return [] - -def init_cutflow(selections): - return {"selections": list(selections), "counts": [0] * len(selections), "total": 0} - -def update_cutflow(cutflow, ch): - cutflow["total"] += 1 - passed = True - for i, selection in enumerate(cutflow["selections"]): - if passed and check_selection(ch, selection): - cutflow["counts"][i] += 1 - else: - passed = False - -def print_cutflow(cutflow, title="Cutflow"): - total = cutflow["total"] - print(f"\n{title}") - print(f"{'Step':<6} {'Label':<30} {'Yield':>12} {'Ind. Eff.':>12} {'Tot. Eff.':>12}") - prev = total - current = total - print(f"{0:<6} {'all events':<30} {total:>12} {1.0:>12.4f} {1.0:>12.4f}") - for i, (selection, count) in enumerate(zip(cutflow["selections"], cutflow["counts"]), start=1): - current = count - ind_eff = current / prev if prev else 0.0 - tot_eff = current / total if total else 0.0 - print(f"{i:<6} {str(selection):<30} {current:>12} {ind_eff:>12.4f} {tot_eff:>12.4f}") - prev = current - -def selection_mask(data, selections): - if len(selections) == 0: - first_field = data.fields[0] if len(data.fields) > 0 else None - return np.ones(len(data[first_field]), dtype=bool) if first_field is not None else None - mask = None - for selection in selections: - current_mask = eval(selection, {"__builtins__": {}}, data) if isinstance(selection, str) else check_selection(data, selection) - if mask is None: - mask = current_mask - else: - mask = mask & current_mask - return mask - -def compute_cutflow(data, selections): - cutflow = init_cutflow(selections) - first_field = data.fields[0] if len(data.fields) > 0 else None - cutflow["total"] = len(data[first_field]) if first_field is not None else 0 - if first_field is None: - return cutflow - running_mask = np.ones(cutflow["total"], dtype=bool) - for i, selection in enumerate(selections): - current_mask = eval(selection, {"__builtins__": {}}, data) if isinstance(selection, str) else check_selection(data, selection) - running_mask = running_mask & current_mask - cutflow["counts"][i] = int(ak.sum(running_mask)) - return cutflow - +#Base dataset class for making graphs from ROOT ntuples. class RootDataset(DGLDataset): def __init__(self, name=None, raw_dir=None, save_dir=None, label=1, file_names = '*.root', node_branch_names=None, node_branch_types=None, node_feature_scales=None, selections=[], save=True, tree_name = 'nominal_Loose', fold_var = 'eventNumber', weight_var = None, chunks = 1, process_chunks = None, global_features = [], tracking_info = [], **kwargs): - ignored_keys = {'shuffle_chunks', 'shuffle_seed', 'batch_size', 'padding_mode', 'folding'} - unused_kwargs = {k: v for k, v in kwargs.items() if k not in ignored_keys} - if len(unused_kwargs) > 0: - print(f'Unused args while creating RootDataset: {unused_kwargs}') + print(f'Unused args while creating RootDataset: {kwargs}') self.label = label self.counts = [] self.selections = selections @@ -171,12 +83,12 @@ class RootDataset(DGLDataset): self.file_names = file_names self.node_branch_names = node_branch_names self.node_branch_types = node_branch_types - self.node_feature_scales = torch.tensor([float(sf) for sf in node_feature_scales], dtype=FEATURE_DTYPE) + self.node_feature_scales = torch.tensor([float(sf) for sf in node_feature_scales]) self.tree_name = tree_name self.fold_var = fold_var self.tracking_info = tracking_info self.tracking_info.insert(0, fold_var) - if weight_var is None: + if weight_var == None: weight_var = 1 self.tracking_info.insert(1, weight_var) self.global_features = global_features @@ -203,8 +115,8 @@ class RootDataset(DGLDataset): if isinstance(feat, str): branches.append(feat) for selection in self.selections: - branches.extend(selection_branches(selection)) - return list(set(branches)) # Remove duplicates + branches.append(selection[0]) + return branches def make_graph(self, ch): t1 = time.time() @@ -217,7 +129,7 @@ class RootDataset(DGLDataset): self.times[0] += t2 - t1 self.times[1] += t3 - t2 return g - + def process(self): times = [0, 0, 0] oldtime = time.time() @@ -227,35 +139,29 @@ class RootDataset(DGLDataset): self.files = [] for file_name in self.file_names: self.files.extend(glob.glob(os.path.join(self.raw_dir, file_name))) - branches = self.get_list_of_branches() + self.chain = ROOT.TChain(self.tree_name) - # Read all files and concatenate arrays - arrays = [] - for file in self.files: - with uproot.open(file) as f: - arrays.append(f[self.tree_name].arrays(branches, library="ak")) - if len(arrays) == 0: + if len(self.files) == 0: print('No files found in {}'.format(os.path.join(self.raw_dir, self.file_names))) - return - data = ak.concatenate(arrays, axis=0) - sel_mask = selection_mask(data, self.selections) - selected_indices = np.arange(len(data[branches[0]])) - if sel_mask is not None: - selected_indices = selected_indices[ak.to_numpy(sel_mask)] - n_entries = len(selected_indices) + for file in self.files: + utils.set_timeout(60*2) + self.chain.Add(file) + utils.unset_timeout() + branches = self.get_list_of_branches() + self.chain.SetBranchStatus('*', 0) + for branch in branches: + self.chain.SetBranchStatus(branch, 1) newtime = time.time() times[0] += newtime - oldtime - chunks = np.array_split(selected_indices, self.chunks) + chunks = np.array_split(np.arange(self.chain.GetEntries()), self.chunks) chunks = [chunk for i, chunk in enumerate(chunks) if i in self.process_chunks] self.graph_chunks = [] self.label_chunks = [] self.tracking_chunks = [] self.global_chunks = [] - cutflow = init_cutflow(self.selections) chunk_id = -1 for chunk in chunks: - print('Processing chunk {}/{}'.format(chunk_id + 1, len(chunks)), flush=True) chunk_id += 1 graphs = [] labels = [] @@ -263,30 +169,28 @@ class RootDataset(DGLDataset): globals = [] for ientry in chunk: if (ientry % 10000 == 0): - print('Processing event {}/{}'.format(ientry, n_entries), flush=True) - ch = {b: data[b][ientry] for b in branches} + print('Processing event {}/{}'.format(ientry, self.chain.GetEntries()), flush=True) + self.chain.GetEntry(ientry) passed = True for selection in self.selections: - if not check_selection(ch, selection): + if not check_selection(self.chain, selection): passed = False continue oldtime = newtime newtime = time.time() times[1] += newtime - oldtime if passed: - graphs.append(self.make_graph(ch)) - labels.append(self.label) - tracking.append(torch.zeros(len(self.tracking_info), dtype=FEATURE_DTYPE)) - globals.append(torch.zeros(len(self.global_features), dtype=FEATURE_DTYPE)) + graphs.append(self.make_graph(self.chain)) + labels.append( self.label ) + tracking.append(torch.zeros(len(self.tracking_info), dtype=torch.double)) + globals.append(torch.zeros(len(self.global_features))) for i_ti, tr_branch in enumerate(self.tracking_info): if isinstance(tr_branch, str): - dtype = tracking[-1].dtype - tracking[-1][i_ti] = torch.as_tensor(ch[tr_branch], dtype=dtype) - # tracking[-1][i_ti] = ch[tr_branch] + tracking[-1][i_ti] = getattr(self.chain, tr_branch) else: tracking[-1][i_ti] = tr_branch for i_gl, gl_branch in enumerate(self.global_features): - globals[-1][i_gl] = ch[gl_branch] + globals[-1][i_gl] = getattr(self.chain, gl_branch) oldtime = newtime newtime = time.time() times[2] += newtime - oldtime @@ -294,12 +198,6 @@ class RootDataset(DGLDataset): labels = torch.tensor(labels) tracking = torch.stack(tracking) globals = torch.stack(globals) - - # self.graph_chunks.append(graphs) - # self.label_chunks.append(labels) - # self.tracking_chunks.append(tracking) - # self.global_chunks.append(globals) - # self.counts.append(len(graphs)) if (self.chunks > 1): self.save_chunk(chunk_id, graphs, labels, tracking, globals) @@ -310,33 +208,40 @@ class RootDataset(DGLDataset): self.graphs = graphs self.save() return - + self.graphs = self.graph_chunks[0] + for chunk in self.graph_chunks[1:]: + self.graphs += chunk + self.labels = torch.cat(self.label_chunks) + self.tracking = torch.cat(self.tracking_chunks) + self.global_features = torch.cat(self.global_chunks) + print('Time spent: Creating TChain: {}s, Getting Entries and Selection: {}s, Graph Creation: {}s'.format(*times)) + print('Time spent in node_features_from_tree: {}s, full_connected_graph: {}s'.format(*self.times)) + def save(self): + """save the graph list and the labels""" if not self.save_to_disk: return - if self.chunks > 1 and (not hasattr(self, "graph_chunks") or len(self.graph_chunks) == 0): - print(f"Skipping save for {self.name}: no graphs were created.") - return graph_path = os.path.join(self.save_dir, self.name + '.bin') if self.chunks == 1: + # print(len(self.graphs)) + # print(len(self.labels)) + # print(len(self.tracking)) + # print(len(self.globals)) print(f'Saving dataset to {os.path.join(self.save_dir, self.name + ".bin")}') dgl.save_graphs(str(graph_path), self.graphs, {'labels': torch.tensor(self.labels), 'tracking': torch.tensor(self.tracking), 'global': torch.tensor(self.global_features)}) else: + print(len(self.graph_chunks)) for i in range(len(self.process_chunks)): print(f'Saving dataset to {os.path.join(self.save_dir, self.name + f"_{self.process_chunks[i]}.bin")}') - dgl.save_graphs(str(graph_path).replace('.bin', f'_{self.process_chunks[i]}.bin'), self.graph_chunks[i], {'labels': self.label_chunks[i], 'tracking': self.tracking_chunks[i], 'global': self.global_chunks[i]}) def save_chunk(self, chunk_id, graphs, labels, tracking, globals): if not self.save_to_disk: return - if len(graphs) == 0: - print(f"Skipping save for chunk {chunk_id}: no graphs passed selections.") - return graph_path = os.path.join(self.save_dir, self.name + '.bin') print(f'Saving dataset to {os.path.join(self.save_dir, self.name + f"_{self.process_chunks[chunk_id]}.bin")}') dgl.save_graphs(str(graph_path).replace('.bin', f'_{self.process_chunks[chunk_id]}.bin'), graphs, {'labels': labels, 'tracking': tracking, 'global': globals}) - + def has_cache(self): print(f'Checking for cache of {self.name}') if not self.save_to_disk: @@ -385,7 +290,7 @@ class RootDataset(DGLDataset): def __len__(self): return len(self.graphs) - + #Dataset with edge features added (deta, dphi, dR) class EdgeDataset(RootDataset): def make_graph(self, ch): @@ -542,17 +447,7 @@ class MultiLabelDataset(EdgeDataset): self.chain.SetBranchStatus(branch, 1) newtime = time.time() times[0] += newtime - oldtime - all_indices = np.arange(self.chain.GetEntries()) - branches = self.get_list_of_branches() - data = {branch: [] for branch in branches} - for ientry in all_indices: - self.chain.GetEntry(ientry) - for branch in branches: - data[branch].append(getattr(self.chain, branch)) - data = {branch: ak.Array(values) for branch, values in data.items()} - sel_mask = selection_mask(data, self.selections) - selected_indices = all_indices[ak.to_numpy(sel_mask)] if sel_mask is not None else all_indices - chunks = np.array_split(selected_indices, self.chunks) + chunks = np.array_split(np.arange(self.chain.GetEntries()), self.chunks) chunks = [chunk for i, chunk in enumerate(chunks) if i in self.process_chunks] self.graph_chunks = [] self.label_chunks = [] @@ -569,7 +464,6 @@ class MultiLabelDataset(EdgeDataset): if (ientry % 10000 == 0): print('Processing event {}/{}'.format(ientry, self.chain.GetEntries()), flush=True) self.chain.GetEntry(ientry) - ch = {b: getattr(self.chain, b) for b in branches} passed = True for selection in self.selections: if not check_selection(self.chain, selection): @@ -581,8 +475,8 @@ class MultiLabelDataset(EdgeDataset): if passed: graphs.append(self.make_graph(self.chain)) labels.append(self.get_label(self.chain)) - tracking.append(torch.zeros(len(self.tracking_info), dtype=FEATURE_DTYPE)) - globals.append(torch.zeros(len(self.global_features), dtype=FEATURE_DTYPE)) + tracking.append(torch.zeros(len(self.tracking_info), dtype=torch.double)) + globals.append(torch.zeros(len(self.global_features))) for i_ti, tr_branch in enumerate(self.tracking_info): if isinstance(tr_branch, str): tracking[-1][i_ti] = getattr(self.chain, tr_branch) @@ -789,4 +683,4 @@ class AugmentedDataset(RootDataset): dR = torch.sqrt(deta**2 + dphi**2) g.edata['augmented_features'] = torch.stack([deta, dphi, dR], dim=1) - return g + return g \ No newline at end of file diff --git a/root_gnn_dgl/root_gnn_base/utils.py b/root_gnn_dgl/root_gnn_base/utils.py index 08c5a1a56ac6b11f11fc84ca344bb2ac2b70fdeb..8f4ff676c074a05c90499318c5fe65f3b2311eb8 100644 --- a/root_gnn_dgl/root_gnn_base/utils.py +++ b/root_gnn_dgl/root_gnn_base/utils.py @@ -8,18 +8,10 @@ import dgl import signal def buildFromConfig(conf, run_time_args = {}): - device = run_time_args.get('device', 'cpu') if 'module' in conf: module = importlib.import_module(conf['module']) cls = getattr(module, conf['class']) - args = conf['args'].copy() - extra_args = {k: v for k, v in conf.items() if k not in ['module', 'class', 'args']} - args.update(extra_args) - if 'weight' in args and isinstance(args['weight'], list): - args['weight'] = torch.tensor(args['weight'], dtype=torch.float, device=device) - # Remove device from run_time_args to not pass it to the class - run_time_args = {k: v for k, v in run_time_args.items() if k != 'device'} - return cls(**args, **run_time_args) + return cls(**conf['args'], **run_time_args) else: print('No module specified in config. Returning None.') @@ -94,7 +86,7 @@ def pad_batch(batch, edges = 104000, nodes = 16000): return make_padding_graph(batch, pad_nodes, pad_edges) def pad_batch_num_nodes(batch, max_num_nodes, hid_size = 64): - print(f"Padding each graph to have {max_num_nodes} nodes. Using hidden size {hid_size}.") + print(f"Padding each graph to have {max_num_nodes} nodes") unbatched = dgl.unbatch(batch) for g in unbatched: @@ -185,101 +177,21 @@ def get_specific_epoch(config, target_epoch, device = None, from_ryan = False): checkpoint = torch.load(os.path.join(config['Training_Directory'], f'model_epoch_{last_epoch}.pt'), map_location=device) return last_epoch, checkpoint -#Return the index and checkpoint of the nest epoch. -def get_best_epoch(config, var='Test_AUC', mode='max', device=None, from_ryan=False): - # Read the training log - log = read_log(config) - - # Ensure the specified variable exists in the log - if var not in log: - raise ValueError(f"Variable '{var}' not found in the training log.") - - # Determine the target epoch based on the mode ('max' or 'min') - if mode == 'max': - target_epoch = int(np.argmax(log[var])) - print(f"Best epoch based on '{var}' (max): {target_epoch} with value: {log[var][target_epoch]}") - elif mode == 'min': - target_epoch = int(np.argmin(log[var])) - print(f"Best epoch based on '{var}' (min): {target_epoch} with value: {log[var][target_epoch]}") - else: - raise ValueError(f"Invalid mode '{mode}'. Expected 'max' or 'min'.") - - # Initialize checkpoint retrieval variables - last_epoch = -1 - checkpoint = None - - # Iterate through epochs up to the target epoch to find the corresponding checkpoint - for ep in range(target_epoch + 1): - if from_ryan: - checkpoint_path = os.path.join( - '/global/cfs/cdirs/atlas/berobert/root_gnn_dgl/', - config['Training_Directory'], - f'model_epoch_{ep}.pt' - ) - else: - checkpoint_path = os.path.join( - config['Training_Directory'], - f'model_epoch_{ep}.pt' - ) - - if os.path.exists(checkpoint_path): - last_epoch = ep - else: - print(f'Epoch {ep} not found. Stopping at epoch {last_epoch}') - print('File not found: ', checkpoint_path) - break - - # Load the checkpoint for the last valid epoch - if last_epoch >= 0: - if from_ryan: - checkpoint_path = os.path.join( - '/global/cfs/cdirs/atlas/berobert/root_gnn_dgl/', - config['Training_Directory'], - f'model_epoch_{last_epoch}.pt' - ) - else: - checkpoint_path = os.path.join( - config['Training_Directory'], - f'model_epoch_{last_epoch}.pt' - ) - - checkpoint = torch.load(checkpoint_path, map_location=device) - - return last_epoch, checkpoint - +#Convert training logs into dict for plotting. def read_log(config): lines = [] with open(config['Training_Directory'] + '/training.log', 'r') as f: lines = f.readlines() - lines = [l for l in lines if 'Epoch' in l] - + lines = [ l for l in lines if 'Epoch' in l ] + nlines = len(lines) labels = [] for field in lines[0].split('|'): labels.append(field.split()[0]) - - # Initialize log as a dictionary with empty lists - log = {label: [] for label in labels} - - for line in lines: - valid_row = True # Flag to check if the row is valid - temp_row = {} # Temporary row to store values before adding to log - + log = {label : np.zeros(nlines) for label in labels} + for i, line in enumerate(lines): for field in line.split('|'): spl = field.split() - try: - temp_row[spl[0]] = float(spl[1]) - except (ValueError, IndexError): - valid_row = False # Mark row as invalid if conversion fails - break - - if valid_row: # Only add the row if all fields are valid - for label in labels: - log[label].append(temp_row.get(label, np.nan)) # Handle missing labels gracefully - - # Convert lists to numpy arrays for consistency - for label in labels: - log[label] = np.array(log[label]) - + log[spl[0]][i] = float(spl[1]) return log #Plot training logs. @@ -392,4 +304,4 @@ class EarlyStop(): def graph_augmentation(graph): print("Augmenting Graph") - return + return \ No newline at end of file diff --git a/root_gnn_dgl/run_demo.sh b/root_gnn_dgl/run_demo.sh index 71fc5f9514e5f8f53464d16a38f8e4a95ae832ef..c17c36add96523aaef1682922de611e9504542ec 100644 --- a/root_gnn_dgl/run_demo.sh +++ b/root_gnn_dgl/run_demo.sh @@ -13,7 +13,7 @@ done python scripts/training_script.py --config configs/stats_100K/pretraining_multiclass.yaml --preshuffle --nocompile --lazy -# From Scratch Training +# Finetuning datasets=("ttH_CP_even" "ttH_CP_odd") chunks=3 @@ -27,11 +27,9 @@ done python scripts/training_script.py --config configs/stats_100K/ttH_CP_even_vs_odd.yaml --preshuffle --nocompile --lazy -# Finetuning Training - python scripts/training_script.py --config configs/stats_100K/finetuning_ttH_CP_even_vs_odd.yaml --preshuffle --nocompile --lazy -# Inference: Writing GNN Scores for from-scratch training and finetuned training to root files +# Inference files=( "ttH_NLO.root" "ttH_CPodd.root" @@ -50,8 +48,8 @@ branch_name=( for ((j=0; j<${#files[@]}; j++)) do python scripts/inference.py \ - --target "/global/cfs/projectdirs/atlas/joshua/gnn_data/stats_100K/${files[j]}" \ - --destination "/global/cfs/projectdirs/atlas/joshua/gnn_data/scores/stats_100K/${files[j]}" \ + --target "/global/cfs/projectdirs/trn007/lbl_atlas/data/stats_100K/${files[j]}" \ + --destination "/global/cfs/projectdirs/trn007/lbl_atlas/data/scores/stats_100K/${files[j]}" \ --config "${config[@]}" \ --branch_name "${branch_name[@]}" \ --chunks 1 \ diff --git a/root_gnn_dgl/scripts/check_dataset_files.py b/root_gnn_dgl/scripts/check_dataset_files.py deleted file mode 100644 index 0ea3a2810e556d91064c307db845e1286e225995..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/scripts/check_dataset_files.py +++ /dev/null @@ -1,128 +0,0 @@ -import yaml -import os -import subprocess -import argparse -from pathlib import Path - -REPO_ROOT = Path(__file__).resolve().parents[1] - -def check_dataset_files(yaml_file, rerun=False): - """ - Check if all required .bin files exist for each dataset in the YAML file. - """ - try: - # Open and parse the YAML file - with open(yaml_file, 'r') as file: - config = yaml.safe_load(file) - - # Check if 'Datasets' exists in the YAML file - if 'Datasets' not in config: - print(f"No 'Datasets' section found in {yaml_file}.") - return - - datasets = config['Datasets'] - all_files_exist = True - - for dataset_name, dataset_config in datasets.items(): - # Extract required information - save_dir = dataset_config['args']['save_dir'] - chunks = dataset_config['args']['chunks'] - folding = dataset_config.get('folding', {}) - n_folds = folding.get('n_folds', 0) - test_folds = folding.get('test', []) - train_folds = folding.get('train', []) - - print(f"\n== Checking dataset: {dataset_name} ==") - print(f" save_dir: {save_dir}") - print(f" chunks: {chunks}") - print(f" n_folds: {n_folds}") - print(f" test_folds: {test_folds}") - print(f" train_folds: {train_folds}") - - missing_files = [] - - # 1. Check for chunk files - for chunk in range(chunks): - chunk_file = os.path.join(save_dir, f"{dataset_name}_{chunk}.bin") - if not os.path.exists(chunk_file): - missing_files.append(chunk_file) - - # 2. Check for prebatched fold files (test and train) - # Naming: dataset_name_prebatched_padded_{fold}_n_{n_folds}_f_{foldlist}.bin - fold_types = [('test', test_folds), ('train', train_folds)] - for fold_type, folds in fold_types: - if not folds: - continue - foldlist_str = '_'.join(map(str, folds)) - for i in range(chunks): - prebatched_file = os.path.join( - save_dir, - f"{dataset_name}_prebatched_padded_{i}_n_{n_folds}_f_{foldlist_str}.bin" - ) - if not os.path.exists(prebatched_file): - missing_files.append(prebatched_file) - - # Print results for the current dataset - if missing_files: - all_files_exist = False - print(f" Missing files for dataset '{dataset_name}':") - for missing_file in missing_files: - print(f" - {missing_file}") - - # Optionally rerun data prep - if rerun: - print(f" Reprocessing dataset '{dataset_name}' ...") - prep_command = [str(REPO_ROOT / "jobs/prep_data/prep_data.sh"), yaml_file, dataset_name, str(chunks)] - try: - subprocess.run(prep_command, check=True) - except subprocess.CalledProcessError as e: - print(f" Could NOT reprocess '{dataset_name}': {e}") - else: - print(f" All files exist for dataset '{dataset_name}'.") - - # Final summary - if all_files_exist: - print("\nAll required files exist for all datasets.") - else: - print("\nSome files are missing.") - - except Exception as e: - print(f"Error processing {yaml_file}: {e}") - -def main(pargs): - base_directory = REPO_ROOT / "configs" - - if pargs.configs: - configs = [p.strip() for p in pargs.configs.split(',')] - else: - configs = [ - "higgs_production/baseline.yaml", - "higgs_production/higgs_production_batch_size/higgs_production_bs_2048.yaml", - "higgs_production/higgs_production_batch_size/higgs_production_bs_4096.yaml", - "higgs_production/higgs_production_batch_size/higgs_production_bs_8192.yaml", - ] - - for config in configs: - config_path = Path(config).expanduser() - yaml_file = config_path if config_path.is_absolute() else base_directory / config_path - if yaml_file.exists(): - print(f"\nProcessing file: {config}") - check_dataset_files(str(yaml_file), pargs.rerun) - else: - print(f"File not found: {yaml_file}") - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Check YAML config files") - parser.add_argument( - "--configs", "-c", - type=str, - required=False, - help="Comma-separated list of YAML config paths relative to configs/ or absolute paths" - ) - parser.add_argument( - "--rerun", "-r", - action='store_true', # Correct way for a boolean flag - help="Automatically re-run data processing to fix missing files" - ) - args = parser.parse_args() - main(args) diff --git a/root_gnn_dgl/scripts/export_onnx.py b/root_gnn_dgl/scripts/export_onnx.py deleted file mode 100644 index b8b6e8172c1c8dffdebea1d953f35adee0d0893e..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/scripts/export_onnx.py +++ /dev/null @@ -1,1036 +0,0 @@ -#!/usr/bin/env python3 -"""Export a trained DGL GNN checkpoint to ONNX and validate one graph/event at a time. - -Usage: - python scripts/export_onnx.py --config configs/stats_100K/ttH_CP_even_vs_odd.yaml --name ttH.onnx - -Defaults: - - infer best epoch from training log via root_gnn_base.utils.get_best_epoch - - export ONNX using one real graph/event - - validate with real data, one graph/event at a time - - compare DGL -> tensor and tensor -> ONNX - - save diagnostic plot next to ONNX file -""" - -from __future__ import annotations - -import argparse -import inspect -import importlib -import os -import sys -from pathlib import Path -from types import MethodType, SimpleNamespace -from typing import Any, Dict, Iterator, Optional, Tuple - -REPO_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(REPO_ROOT)) - -import dgl -import matplotlib.pyplot as plt -import numpy as np -import onnxruntime as ort -import torch -import torch.nn as nn -import yaml -from dgl.dataloading import GraphDataLoader -from torch_scatter import scatter_mean, scatter_sum - -try: - from root_gnn_base import utils -except Exception as exc: - utils = None - _UTILS_IMPORT_ERROR = exc -else: - _UTILS_IMPORT_ERROR = None - - -# ------------------------- -# Config / checkpoint utils -# ------------------------- - - -def load_config(config_file: str | os.PathLike[str]) -> Dict[str, Any]: - config_path = Path(config_file) - with config_path.open() as f: - conf = yaml.load(f, Loader=yaml.FullLoader) - - if conf is None: - raise ValueError(f"Empty config: {config_file}") - - include_config(conf, config_path.parent) - return conf - - -def include_config(conf: Dict[str, Any], base_dir: Path) -> None: - includes = conf.pop("include", None) - if not includes: - return - - if isinstance(includes, (str, os.PathLike)): - includes = [includes] - - for inc in includes: - inc_path = Path(inc) - if not inc_path.is_absolute(): - inc_path = base_dir / inc_path - - with inc_path.open() as f: - included = yaml.load(f, Loader=yaml.FullLoader) or {} - - include_config(included, inc_path.parent) - conf.update(included) - - -def find_model_class(model_cfg: Dict[str, Any]) -> str: - return str(model_cfg.get("class", "")).split(".")[-1] - - -def infer_global_size(model_args: Dict[str, Any]) -> int: - for key in ("global_size", "global_in_size", "global_dim", "n_global", "sample_global"): - if key in model_args: - return int(model_args[key]) - return 1 - - -def load_best_checkpoint(conf: Dict[str, Any]) -> Tuple[int, Dict[str, Any]]: - if utils is None: - raise RuntimeError( - "Could not import root_gnn_base.utils, which is needed for utils.get_best_epoch. " - f"Original import error: {_UTILS_IMPORT_ERROR}" - ) - - try: - return utils.get_best_epoch(conf, mode="max") - except TypeError: - return utils.get_best_epoch(conf) - - -def load_checkpoint(conf: Dict[str, Any], epoch: Optional[int]) -> Tuple[int, Dict[str, Any]]: - if epoch is None: - return load_best_checkpoint(conf) - - training_dir = Path(conf["Training_Directory"]) - checkpoint_path = training_dir / f"model_epoch_{epoch}.pt" - - if not checkpoint_path.exists(): - raise FileNotFoundError(f"Could not find checkpoint: {checkpoint_path}") - - checkpoint = torch.load(checkpoint_path, map_location="cpu") - return epoch, checkpoint - - -# ------------------------- -# MLP helpers -# ------------------------- - - -def make_slp(in_size: int, out_size: int, activation=nn.ReLU, dropout: float = 0) -> list[nn.Module]: - return [nn.Linear(in_size, out_size), activation(), nn.Dropout(dropout)] - - -def make_mlp( - in_size: int, - hid_size: int, - out_size: int, - n_layers: int, - activation=nn.ReLU, - dropout: float = 0, -) -> nn.Sequential: - layers: list[nn.Module] = [] - - if n_layers > 1: - layers += make_slp(in_size, hid_size, activation, dropout) - for _ in range(n_layers - 2): - layers += make_slp(hid_size, hid_size, activation, dropout) - layers += make_slp(hid_size, out_size, activation, dropout) - else: - layers += make_slp(in_size, out_size, activation, dropout) - - layers.append(nn.LayerNorm(out_size)) - return nn.Sequential(*layers) - - -def broadcast_global_to_nodes(h_global: torch.Tensor, node_batch: torch.Tensor) -> torch.Tensor: - if h_global.dim() == 1: - h_global = h_global.unsqueeze(0) - return h_global[node_batch.to(torch.long)] - - -def broadcast_global_to_edges(h_global: torch.Tensor, edge_batch: torch.Tensor) -> torch.Tensor: - if h_global.dim() == 1: - h_global = h_global.unsqueeze(0) - return h_global[edge_batch.to(torch.long)] - - -def copy_v_udf(edges): - return {"m_v": edges.dst["h"]} - - -def make_node_batch_ids(batch_num_nodes: torch.Tensor) -> torch.Tensor: - return torch.repeat_interleave( - torch.arange(len(batch_num_nodes), device=batch_num_nodes.device, dtype=torch.long), - batch_num_nodes.to(torch.long), - ) - - -def make_edge_batch_ids(batch_num_edges: torch.Tensor) -> torch.Tensor: - return torch.repeat_interleave( - torch.arange(len(batch_num_edges), device=batch_num_edges.device, dtype=torch.long), - batch_num_edges.to(torch.long), - ) - - -# ------------------------- -# Tensor / ONNX model copies -# ------------------------- - - -class EdgeNetworkONNX(nn.Module): - """ONNX-friendly tensor implementation of the DGL Edge_Network.""" - - def __init__( - self, - sample_graph: Any, - sample_global: int, - hid_size: int, - out_size: int, - n_layers: int, - n_proc_steps: int, - dropout: float = 0, - **kwargs: Any, - ) -> None: - super().__init__() - - if kwargs: - print(f"Unused args while creating EdgeNetworkONNX: {kwargs}") - - self.n_proc_steps = n_proc_steps - - node_in = int(sample_graph.ndata["features"].shape[1]) - edge_in = int(sample_graph.edata["features"].shape[1]) - gl_size = int(sample_global) - - self.layers = nn.ModuleList() - self.node_encoder = make_mlp(node_in, hid_size, hid_size, n_layers, dropout=dropout) - self.edge_encoder = make_mlp(edge_in, hid_size, hid_size, n_layers, dropout=dropout) - self.global_encoder = make_mlp(gl_size, hid_size, hid_size, n_layers, dropout=dropout) - - self.node_update = make_mlp(3 * hid_size, hid_size, hid_size, n_layers, dropout=dropout) - self.edge_update = make_mlp(4 * hid_size, hid_size, hid_size, n_layers, dropout=dropout) - self.global_update = make_mlp(3 * hid_size, hid_size, hid_size, n_layers, dropout=dropout) - - self.global_decoder = make_mlp(hid_size, hid_size, hid_size, n_layers, dropout=dropout) - self.classify = nn.Linear(hid_size, out_size) - - def forward( - self, - node_features: torch.Tensor, - edge_features: torch.Tensor, - global_feats: torch.Tensor, - edge_index: torch.Tensor, - node_batch: torch.Tensor, - ) -> torch.Tensor: - src = edge_index[0].to(torch.long) - dst = edge_index[1].to(torch.long) - node_batch = node_batch.to(torch.long) - - h = self.node_encoder(node_features) - e = self.edge_encoder(edge_features) - h_global = self.global_encoder(global_feats) - - num_graphs = global_feats.size(0) - - for _ in range(self.n_proc_steps): - edge_batch = node_batch[dst] - - e = self.edge_update( - torch.cat( - [ - e, - h[src], - h[dst], - broadcast_global_to_edges(h_global, edge_batch), - ], - dim=1, - ) - ) - - h_e = scatter_sum(e, dst, dim=0, dim_size=h.size(0)) - - h = self.node_update( - torch.cat( - [ - h, - h_e, - broadcast_global_to_nodes(h_global, node_batch), - ], - dim=1, - ) - ) - - mean_n = scatter_mean(h, node_batch, dim=0, dim_size=num_graphs) - mean_e = scatter_mean(e, edge_batch, dim=0, dim_size=num_graphs) - - h_global = self.global_update(torch.cat([h_global, mean_n, mean_e], dim=1)) - - return self.classify(self.global_decoder(h_global)) - - -class TransferredLearningFinetuningONNX(nn.Module): - """ONNX-friendly tensor implementation of Transferred_Learning_Finetuning.""" - - def __init__( - self, - pretraining_path: str, - pretraining_model_args: Dict[str, Any], - sample_graph: Any, - sample_global: int, - hid_size: int, - out_size: int, - n_layers: int, - n_proc_steps: int, - dropout: float = 0, - frozen_pretraining: bool = False, - **kwargs: Any, - ) -> None: - super().__init__() - - if kwargs: - print(f"Unused args while creating TransferredLearningFinetuningONNX: {kwargs}") - - self.n_proc_steps = n_proc_steps - - pre_args = dict(pretraining_model_args) - pre_args.setdefault("dropout", dropout) - - self.pretrained_model = EdgeNetworkONNX( - sample_graph=sample_graph, - sample_global=sample_global, - **pre_args, - ) - - checkpoint = torch.load(pretraining_path, map_location="cpu") - self.pretrained_model.load_state_dict(checkpoint["model_state_dict"]) - - self.pretrained_model = nn.Sequential(*list(self.pretrained_model.children())[:-1]) - - print(f"Freeze Pretraining = {frozen_pretraining}") - - if frozen_pretraining: - for param in self.pretrained_model.parameters(): - param.requires_grad = False - for param in self.pretrained_model[7].parameters(): - param.requires_grad = True - - torch.manual_seed(2) - self.classify = nn.Linear(hid_size, out_size) - - def _backbone_forward( - self, - node_features: torch.Tensor, - edge_features: torch.Tensor, - global_feats: torch.Tensor, - edge_index: torch.Tensor, - node_batch: torch.Tensor, - ) -> torch.Tensor: - src = edge_index[0].to(torch.long) - dst = edge_index[1].to(torch.long) - node_batch = node_batch.to(torch.long) - - node_enc = self.pretrained_model[1] - edge_enc = self.pretrained_model[2] - glob_enc = self.pretrained_model[3] - node_upd = self.pretrained_model[4] - edge_upd = self.pretrained_model[5] - glob_upd = self.pretrained_model[6] - glob_dec = self.pretrained_model[7] - - h = node_enc(node_features) - e = edge_enc(edge_features) - h_global = glob_enc(global_feats) - - num_graphs = global_feats.size(0) - - for _ in range(self.n_proc_steps): - edge_batch = node_batch[dst] - - e = edge_upd( - torch.cat( - [ - e, - h[src], - h[dst], - broadcast_global_to_edges(h_global, edge_batch), - ], - dim=1, - ) - ) - - h_e = scatter_sum(e, dst, dim=0, dim_size=h.size(0)) - - h = node_upd( - torch.cat( - [ - h, - h_e, - broadcast_global_to_nodes(h_global, node_batch), - ], - dim=1, - ) - ) - - mean_n = scatter_mean(h, node_batch, dim=0, dim_size=num_graphs) - mean_e = scatter_mean(e, edge_batch, dim=0, dim_size=num_graphs) - - h_global = glob_upd(torch.cat([h_global, mean_n, mean_e], dim=1)) - - return glob_dec(h_global) - - def forward( - self, - node_features: torch.Tensor, - edge_features: torch.Tensor, - global_feats: torch.Tensor, - edge_index: torch.Tensor, - node_batch: torch.Tensor, - ) -> torch.Tensor: - return self.classify( - self._backbone_forward( - node_features, - edge_features, - global_feats, - edge_index, - node_batch, - ) - ) - - -# ------------------------- -# Model construction -# ------------------------- - - -def make_sample_graph(node_features: int, edge_features: int) -> Any: - return SimpleNamespace( - ndata={"features": torch.zeros(2, node_features, dtype=torch.float32)}, - edata={"features": torch.zeros(2, edge_features, dtype=torch.float32)}, - ) - - -def build_tensor_model(conf: Dict[str, Any]) -> nn.Module: - model_cfg = conf["Model"] - model_args = dict(model_cfg.get("args", {})) - class_name = find_model_class(model_cfg) - - node_in = int(model_args.get("in_size", 7)) - edge_in = int(model_args.get("edge_in_size", 3)) - global_in = infer_global_size(model_args) - - sample_graph = make_sample_graph(node_in, edge_in) - - common = { - "sample_graph": sample_graph, - "sample_global": global_in, - "hid_size": int(model_args["hid_size"]), - "out_size": int(model_args["out_size"]), - "n_layers": int(model_args["n_layers"]), - "n_proc_steps": int(model_args["n_proc_steps"]), - "dropout": float(model_args.get("dropout", 0)), - } - - if class_name == "Edge_Network": - return EdgeNetworkONNX(**common) - - if class_name == "Transferred_Learning_Finetuning": - pretraining_model = model_args.get("pretraining_model", {}) - pre_args = dict(pretraining_model.get("args", {})) - - pre_args.pop("in_size", None) - pre_args.pop("edge_in_size", None) - - return TransferredLearningFinetuningONNX( - pretraining_path=model_args["pretraining_path"], - pretraining_model_args=pre_args, - frozen_pretraining=bool(model_args.get("frozen_pretraining", False)), - **common, - ) - - raise ValueError( - f"Unsupported Model.class={class_name!r}. " - "Expected Edge_Network or Transferred_Learning_Finetuning." - ) - - -def build_dgl_model(conf: Dict[str, Any], sample_graph: dgl.DGLGraph, sample_global: torch.Tensor) -> nn.Module: - if utils is None: - raise RuntimeError( - "Could not import root_gnn_base.utils, which is needed to build the DGL model. " - f"Original import error: {_UTILS_IMPORT_ERROR}" - ) - - return utils.buildFromConfig( - conf["Model"], - { - "sample_graph": sample_graph, - "sample_global": sample_global, - }, - ) - - -def patch_finetuning_pretrained_output(model: nn.Module) -> nn.Module: - """Patch older finetuning models so Pretrained_Output can accept explicit globals. - - The repo has moved through a few signatures for the finetuning DGL model. - Some checkpoints still load a class whose forward() calls Pretrained_Output(g.clone()) - while the body expects a global_feats tensor. This adapter preserves the original - module weights but makes the instance callable from the exporter in either style. - """ - - if not hasattr(model, "TL_node_encoder") or not hasattr(model, "TL_global_encoder"): - return model - - original = getattr(model, "Pretrained_Output", None) - if original is None: - return model - - try: - signature = inspect.signature(original) - # Bound methods exclude "self". - if len(signature.parameters) > 1: - return model - except (TypeError, ValueError): - pass - - def _patched_pretrained_output(self, g, global_feats=None): - h = self.TL_node_encoder(g.ndata["features"]) - e = self.TL_edge_encoder(g.edata["features"]) - g.ndata["h"] = h - g.edata["e"] = e - - if global_feats is None: - global_feats = g.batch_num_nodes()[:, None].to(torch.float) - - h_global = self.TL_global_encoder(global_feats) - node_batch = make_node_batch_ids(g.batch_num_nodes()) - edge_batch = make_edge_batch_ids(g.batch_num_edges()) - - for _ in range(self.n_proc_steps): - g.apply_edges(dgl.function.copy_u("h", "m_u")) - g.apply_edges(copy_v_udf) - g.edata["e"] = self.TL_edge_update( - torch.cat( - ( - g.edata["e"], - g.edata["m_u"], - g.edata["m_v"], - broadcast_global_to_edges(h_global, edge_batch), - ), - dim=1, - ) - ) - g.update_all(dgl.function.copy_e("e", "m"), dgl.function.sum("m", "h_e")) - g.ndata["h"] = self.TL_node_update( - torch.cat((g.ndata["h"], g.ndata["h_e"], broadcast_global_to_nodes(h_global, node_batch)), dim=1) - ) - h_global = self.TL_global_update( - torch.cat((h_global, dgl.mean_nodes(g, "h"), dgl.mean_edges(g, "e")), dim=1) - ) - - return self.TL_global_decoder(h_global) - - model.Pretrained_Output = MethodType(_patched_pretrained_output, model) - return model - - -# ------------------------- -# Dataset / graph utilities -# ------------------------- - - -def build_dataset_from_config(conf: Dict[str, Any]): - if utils is None: - raise RuntimeError( - "Could not import root_gnn_base.utils, which is needed to build the dataset. " - f"Original import error: {_UTILS_IMPORT_ERROR}" - ) - - dset_name = list(conf["Datasets"].keys())[0] - dset_conf = dict(conf["Datasets"][dset_name]) - dataset = utils.buildFromConfig(dset_conf) - return dset_name, dataset - - -def single_graph_loader(conf: Dict[str, Any]) -> Tuple[str, GraphDataLoader]: - dset_name, dataset = build_dataset_from_config(conf) - - loader = GraphDataLoader( - dataset, - batch_size=1, - shuffle=False, - drop_last=False, - num_workers=0, - ) - - return dset_name, loader - - -def get_global_features(batch: dgl.DGLGraph) -> torch.Tensor: - candidates = [] - - for attr in ("global_features", "global_feats", "globals"): - if hasattr(batch, attr): - candidates.append(getattr(batch, attr)) - - for key in ("global_features", "global_feats", "globals", "features"): - try: - if key in batch.ndata and False: - pass - except Exception: - pass - - for candidate in candidates: - if isinstance(candidate, torch.Tensor) and candidate.numel() > 0: - if candidate.dim() == 1: - candidate = candidate.unsqueeze(0) - return candidate.to(torch.float32) - - return batch.batch_num_nodes().to(torch.float32).unsqueeze(1) - - -def tensorize_single_graph(batch: dgl.DGLGraph) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: - if len(batch.batch_num_nodes()) != 1: - raise ValueError( - f"Expected a single graph/event, but got batched graph with {len(batch.batch_num_nodes())} graphs" - ) - - node_features = batch.ndata["features"].detach().cpu().to(torch.float32) - edge_features = batch.edata["features"].detach().cpu().to(torch.float32) - - src, dst = batch.edges() - edge_index = torch.stack([src.detach().cpu(), dst.detach().cpu()], dim=0).to(torch.long) - - node_batch = torch.zeros(node_features.shape[0], dtype=torch.long) - global_feats = get_global_features(batch).detach().cpu().to(torch.float32) - - if global_feats.dim() == 1: - global_feats = global_feats.unsqueeze(0) - - if global_feats.shape[0] != 1: - global_feats = global_feats.reshape(1, -1) - - return node_features, edge_features, global_feats, edge_index, node_batch - - -def first_real_event_inputs(conf: Dict[str, Any]) -> Tuple[str, dgl.DGLGraph, Tuple[torch.Tensor, ...]]: - dset_name, loader = single_graph_loader(conf) - - batch, labels, tracking, extra = next(iter(loader)) - _ = labels, tracking, extra - - inputs = tensorize_single_graph(batch) - return dset_name, batch, inputs - - -# ------------------------- -# ONNX export / runtime -# ------------------------- - - -def export_onnx(model: nn.Module, inputs: Tuple[torch.Tensor, ...], out_path: str) -> None: - output = Path(out_path) - - if output.parent and str(output.parent) != ".": - output.parent.mkdir(parents=True, exist_ok=True) - - torch.onnx.export( - model, - inputs, - str(output), - input_names=[ - "node_features", - "edge_features", - "global_features", - "edge_index", - "node_batch", - ], - output_names=["logits"], - dynamic_axes={ - "node_features": {0: "num_nodes"}, - "edge_features": {0: "num_edges"}, - "edge_index": {1: "num_edges"}, - "node_batch": {0: "num_nodes"}, - }, - opset_version=16, - ) - - -def make_onnx_session(onnx_path: str) -> ort.InferenceSession: - sess_options = ort.SessionOptions() - - # Avoid Perlmutter / CPU affinity warnings from ONNX Runtime. - sess_options.intra_op_num_threads = 1 - sess_options.inter_op_num_threads = 1 - - return ort.InferenceSession( - onnx_path, - sess_options=sess_options, - providers=["CPUExecutionProvider"], - ) - - -def run_onnx(sess: ort.InferenceSession, inputs: Tuple[torch.Tensor, ...]) -> np.ndarray: - node_features, edge_features, global_feats, edge_index, node_batch = inputs - - ort_inputs = { - "node_features": node_features.numpy().astype(np.float32), - "edge_features": edge_features.numpy().astype(np.float32), - "global_features": global_feats.numpy().astype(np.float32), - "edge_index": edge_index.numpy().astype(np.int64), - "node_batch": node_batch.numpy().astype(np.int64), - } - - ort_input_names = {inp.name for inp in sess.get_inputs()} - ort_inputs = {k: v for k, v in ort_inputs.items() if k in ort_input_names} - - return sess.run(None, ort_inputs)[0] - - -# ------------------------- -# Real-data validation loop -# ------------------------- - - -def sigmoid_np(x: np.ndarray) -> np.ndarray: - return 1.0 / (1.0 + np.exp(-x)) - - -def run_real_data_test( - conf: Dict[str, Any], - tensor_model: nn.Module, - onnx_path: str, - epoch: int, - checkpoint: Dict[str, Any], - max_events: int, - tol_dgl_tensor: float, - tol_tensor_onnx: float, -) -> None: - dset_name, loader = single_graph_loader(conf) - - first_batch, labels, tracking, extra = next(iter(loader)) - _ = labels, tracking, extra - - first_inputs = tensorize_single_graph(first_batch) - first_global = first_inputs[2] - - dgl_model = build_dgl_model(conf, first_batch, first_global) - dgl_model.load_state_dict(checkpoint["model_state_dict"]) - dgl_model = patch_finetuning_pretrained_output(dgl_model) - dgl_model.eval().cpu() - - tensor_model.eval().cpu() - - sess = make_onnx_session(onnx_path) - - all_dgl_logits = [] - all_tensor_logits = [] - all_onnx_logits = [] - - all_dgl_prob = [] - all_tensor_prob = [] - all_onnx_prob = [] - - dgl_tensor_max_diffs = [] - tensor_onnx_max_diffs = [] - - n_tested = 0 - - # Recreate loader so event 0 is included. - _, loader = single_graph_loader(conf) - - for item in loader: - batch, labels, tracking, extra = item - _ = labels, tracking, extra - - inputs = tensorize_single_graph(batch) - node_features, edge_features, global_feats, edge_index, node_batch = inputs - - with torch.no_grad(): - dgl_logits = dgl_model(batch, global_feats).detach().cpu().numpy() - tensor_logits = tensor_model(*inputs).detach().cpu().numpy() - - onnx_logits = run_onnx(sess, inputs) - - dgl_prob = sigmoid_np(dgl_logits) - tensor_prob = sigmoid_np(tensor_logits) - onnx_prob = sigmoid_np(onnx_logits) - - all_dgl_logits.append(dgl_logits.reshape(-1)) - all_tensor_logits.append(tensor_logits.reshape(-1)) - all_onnx_logits.append(onnx_logits.reshape(-1)) - - all_dgl_prob.append(dgl_prob.reshape(-1)) - all_tensor_prob.append(tensor_prob.reshape(-1)) - all_onnx_prob.append(onnx_prob.reshape(-1)) - - dgl_tensor_max_diffs.append(float(np.max(np.abs(dgl_logits - tensor_logits)))) - tensor_onnx_max_diffs.append(float(np.max(np.abs(tensor_logits - onnx_logits)))) - - n_tested += 1 - - if n_tested % 100 == 0: - print(f"Validated {n_tested} single-event graphs...") - - if max_events > 0 and n_tested >= max_events: - break - - if n_tested == 0: - raise RuntimeError("No events were available for validation.") - - dgl_logits_all = np.concatenate(all_dgl_logits) - tensor_logits_all = np.concatenate(all_tensor_logits) - onnx_logits_all = np.concatenate(all_onnx_logits) - - dgl_prob_all = np.concatenate(all_dgl_prob) - tensor_prob_all = np.concatenate(all_tensor_prob) - onnx_prob_all = np.concatenate(all_onnx_prob) - - dgl_vs_tensor = np.abs(dgl_logits_all - tensor_logits_all) - tensor_vs_onnx = np.abs(tensor_logits_all - onnx_logits_all) - - dgl_vs_tensor_prob = np.abs(dgl_prob_all - tensor_prob_all) - tensor_vs_onnx_prob = np.abs(tensor_prob_all - onnx_prob_all) - - print(f"\n== Real Data Test: {dset_name} ==") - print(f"Epoch : {epoch}") - print(f"Single-event graphs tested : {n_tested}") - print(f"DGL output shape : {dgl_logits_all.shape}") - print(f"Tensor output shape : {tensor_logits_all.shape}") - print(f"ONNX output shape : {onnx_logits_all.shape}") - - print("\nLogit comparisons") - print(f"max abs diff DGL->Tensor : {dgl_vs_tensor.max():.8g}") - print(f"mean abs diff DGL->Tensor : {dgl_vs_tensor.mean():.8g}") - print(f"max abs diff Tensor->ONNX : {tensor_vs_onnx.max():.8g}") - print(f"mean abs diff Tensor->ONNX : {tensor_vs_onnx.mean():.8g}") - - print("\nScore comparisons") - print(f"max abs diff DGL->Tensor : {dgl_vs_tensor_prob.max():.8g}") - print(f"mean abs diff DGL->Tensor : {dgl_vs_tensor_prob.mean():.8g}") - print(f"max abs diff Tensor->ONNX : {tensor_vs_onnx_prob.max():.8g}") - print(f"mean abs diff Tensor->ONNX : {tensor_vs_onnx_prob.mean():.8g}") - - print("\nPer-event max logit-diff summaries") - print(f"DGL->Tensor max over events : {np.max(dgl_tensor_max_diffs):.8g}") - print(f"DGL->Tensor mean over events : {np.mean(dgl_tensor_max_diffs):.8g}") - print(f"Tensor->ONNX max over events : {np.max(tensor_onnx_max_diffs):.8g}") - print(f"Tensor->ONNX mean over events : {np.mean(tensor_onnx_max_diffs):.8g}") - - save_comparison_plot( - onnx_path=onnx_path, - sample_name=dset_name, - dgl_prob=dgl_prob_all, - tensor_prob=tensor_prob_all, - onnx_prob=onnx_prob_all, - ) - - failed = False - - if dgl_vs_tensor.max() > tol_dgl_tensor: - failed = True - print( - f"\nFAIL: DGL->Tensor max diff {dgl_vs_tensor.max():.8g} " - f"> tolerance {tol_dgl_tensor:.8g}" - ) - - if tensor_vs_onnx.max() > tol_tensor_onnx: - failed = True - print( - f"\nFAIL: Tensor->ONNX max diff {tensor_vs_onnx.max():.8g} " - f"> tolerance {tol_tensor_onnx:.8g}" - ) - - if failed: - raise RuntimeError("Real-data validation failed.") - - print("\nReal-data validation passed") - - -def save_comparison_plot( - onnx_path: str, - sample_name: str, - dgl_prob: np.ndarray, - tensor_prob: np.ndarray, - onnx_prob: np.ndarray, -) -> None: - score_bins = np.linspace(0.0, 1.0, 41) - - residuals_onnx = onnx_prob.reshape(-1) - dgl_prob.reshape(-1) - residuals_tensor = tensor_prob.reshape(-1) - dgl_prob.reshape(-1) - - combined_residuals = np.concatenate([residuals_onnx, residuals_tensor]) - - if np.all(combined_residuals == combined_residuals[0]): - diff_bins = np.linspace(combined_residuals[0] - 1e-8, combined_residuals[0] + 1e-8, 80) - else: - diff_bins = np.histogram_bin_edges(combined_residuals, bins=80) - - fig, (ax_left, ax_right) = plt.subplots(1, 2, figsize=(12, 4)) - - ax_left.hist( - dgl_prob.reshape(-1), - bins=score_bins, - histtype="step", - linewidth=2.0, - label="DGL", - ) - ax_left.hist( - tensor_prob.reshape(-1), - bins=score_bins, - histtype="step", - linewidth=2.0, - label="Tensor", - ) - ax_left.hist( - onnx_prob.reshape(-1), - bins=score_bins, - histtype="step", - linewidth=2.0, - label="ONNX", - ) - ax_left.set_title(f"Score Distributions: {sample_name}") - ax_left.set_xlabel("Score") - ax_left.set_ylabel("Events / bin") - ax_left.legend() - - ax_right.hist( - residuals_onnx, - bins=diff_bins, - histtype="step", - linewidth=1.8, - label="ONNX - DGL", - ) - ax_right.hist( - residuals_tensor, - bins=diff_bins, - histtype="step", - linewidth=1.8, - label="Tensor - DGL", - ) - ax_right.set_title(f"Differences vs DGL: {sample_name}") - ax_right.set_xlabel("Score difference") - ax_right.set_ylabel("Events / bin") - ax_right.set_yscale("log") - ax_right.legend() - - plt.tight_layout() - - plot_path = os.path.splitext(onnx_path)[0] + "_onnx.png" - plt.savefig(plot_path, dpi=200, bbox_inches="tight") - plt.close(fig) - - print(f"Saved comparison plot to {plot_path}") - - -# ------------------------- -# CLI -# ------------------------- - - -def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser(description="Export root_gnn_base GCN models to ONNX.") - - parser.add_argument("--config", required=True, help="YAML training config.") - parser.add_argument("--name", required=True, help='Output ONNX filename, e.g. "ttH.onnx".') - - parser.add_argument( - "--epoch", - type=int, - default=None, - help="Checkpoint epoch to export. Default: best Test_AUC epoch.", - ) - parser.add_argument( - "--no-test", - action="store_true", - help="Skip real-data validation and plotting.", - ) - parser.add_argument( - "--max-test-events", - type=int, - default=1000, - help="Number of single-event graphs to validate. Use 0 for all events. Default: 1000.", - ) - parser.add_argument( - "--tol-dgl-tensor", - type=float, - default=1e-8, - help="Max allowed logit difference for DGL vs tensor model.", - ) - parser.add_argument( - "--tol-tensor-onnx", - type=float, - default=5e-5, - help="Max allowed logit difference for tensor model vs ONNX.", - ) - - return parser.parse_args() - - -def main() -> None: - args = parse_args() - conf = load_config(args.config) - - tensor_model = build_tensor_model(conf) - epoch, checkpoint = load_checkpoint(conf, args.epoch) - - tensor_model.load_state_dict(checkpoint["model_state_dict"]) - tensor_model.eval().cpu() - - if args.no_test: - model_args = conf["Model"].get("args", {}) - - node_in = int(model_args.get("in_size", 7)) - edge_in = int(model_args.get("edge_in_size", 3)) - global_in = infer_global_size(model_args) - - node_features = torch.randn(4, node_in, dtype=torch.float32) - src = torch.tensor([0, 0, 1, 1, 2, 2, 3, 3], dtype=torch.long) - dst = torch.tensor([1, 2, 0, 3, 0, 3, 1, 2], dtype=torch.long) - edge_index = torch.stack([src, dst], dim=0) - edge_features = torch.randn(edge_index.shape[1], edge_in, dtype=torch.float32) - global_features = torch.ones(1, global_in, dtype=torch.float32) - node_batch = torch.zeros(node_features.shape[0], dtype=torch.long) - - export_inputs = ( - node_features, - edge_features, - global_features, - edge_index, - node_batch, - ) - else: - dset_name, first_batch, export_inputs = first_real_event_inputs(conf) - print(f"Using one real event from {dset_name} as the ONNX export example input.") - - with torch.no_grad(): - _ = tensor_model(*export_inputs) - - export_onnx(tensor_model, export_inputs, args.name) - - print(f"Exported epoch {epoch} to {args.name}") - - if not args.no_test: - run_real_data_test( - conf=conf, - tensor_model=tensor_model, - onnx_path=args.name, - epoch=epoch, - checkpoint=checkpoint, - max_events=args.max_test_events, - tol_dgl_tensor=args.tol_dgl_tensor, - tol_tensor_onnx=args.tol_tensor_onnx, - ) - - -if __name__ == "__main__": - main() diff --git a/root_gnn_dgl/scripts/inference.py b/root_gnn_dgl/scripts/inference.py index 0508835ca0265cf66c1c38e288c8f60bc2aed10b..3100a08a099dcfbf3c360f51249984dc2db69e11 100644 --- a/root_gnn_dgl/scripts/inference.py +++ b/root_gnn_dgl/scripts/inference.py @@ -1,15 +1,11 @@ import sys import os +file_path = os.getcwd() +sys.path.append(file_path) +import os import argparse import yaml import gc -from array import array -import fnmatch -import re -from pathlib import Path - -REPO_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(REPO_ROOT)) import torch import dgl @@ -88,78 +84,6 @@ def load_config(config_file): include_config(conf) return conf -def _branch_names(tree): - return {branch.GetName() for branch in tree.GetListOfBranches()} - -def _compare(value, cut, op): - if op == '>': - return value > cut - if op == '>=': - return value >= cut - if op == '<': - return value < cut - if op == '<=': - return value <= cut - if op == '==': - return value == cut - if op == '!=': - return value != cut - raise ValueError(f'Unknown selection operator: {op}') - -def compute_selection_pass(tree, selections): - if not selections: - return 1 - - names = _branch_names(tree) - - for selection in selections: - if isinstance(selection, str): - tokens = set(re.findall(r'\b[A-Za-z_]\w*\b', selection)) - needed = tokens & names - - context = {} - for name in needed: - context[name] = getattr(tree, name) - - try: - passed = bool(eval(selection, {"__builtins__": {}}, context)) - except NameError as exc: - raise NameError( - f"Selection expression references an unknown name: {selection}" - ) from exc - - if not passed: - return 0 - else: - if not isinstance(selection, (tuple, list)) or len(selection) != 3: - raise ValueError( - f"Selection must be a string or a 3-item sequence " - f"(var, cut, op), got: {selection}" - ) - - var, cut, op = selection - - if var not in names: - raise KeyError(f"Selection references missing branch: {var}") - - value = getattr(tree, var) - - if not _compare(value, cut, op): - return 0 - - return 1 - -def select_dataset_config(configs, target_path): - target_name = os.path.basename(target_path) - for config in configs: - dset_config = config['Datasets'][list(config['Datasets'].keys())[0]] - file_names = dset_config['args'].get('file_names', '') - patterns = file_names if isinstance(file_names, list) else [file_names] - for pattern in patterns: - if fnmatch.fnmatch(target_name, os.path.basename(pattern)): - return dset_config - return configs[0]['Datasets'][list(configs[0]['Datasets'].keys())[0]] - def main(): parser = argparse.ArgumentParser() @@ -221,7 +145,7 @@ def main(): print('Imports finished in {:.2f} seconds'.format(end - start)) start = time.time() - dset_config = select_dataset_config([load_config(c) for c in args.config], args.target) + dset_config = config['Datasets'][list(config['Datasets'].keys())[0]] if dset_config['class'] == 'LazyDataset': dset_config['class'] = 'EdgeDataset' elif dset_config['class'] == 'LazyMultiLabelDataset': @@ -263,7 +187,6 @@ def main(): lend = time.time() print('Loader finished in {:.2f} seconds'.format(lend - lstart)) sample_graph, _, _, global_sample = loader[0] - global_sample = [] print('dset length =', len(dset)) print('loader length =', len(loader)) @@ -275,7 +198,6 @@ def main(): for config_file, branch in zip(args.config, args.branch_name): config = load_config(config_file) model = utils.buildFromConfig(config['Model'], {'sample_graph' : sample_graph, 'sample_global': global_sample}).to(device) - if args.ckpt < 0: ep, checkpoint = utils.get_best_epoch(config, var=args.var, mode='max', device=device) else: @@ -327,11 +249,9 @@ def main(): if args.write: from ROOT import std - write_config = select_dataset_config([load_config(c) for c in args.config], args.target) # Open the original ROOT file infile = ROOT.TFile.Open(args.target) - tree = infile.Get(write_config['args']['tree_name']) - selections = write_config.get('selections', []) + tree = infile.Get(dset_config['args']['tree_name']) # Create the destination directory if it doesn't exist os.makedirs(os.path.split(args.destination)[0], exist_ok=True) @@ -354,13 +274,9 @@ def main(): branch_vectors[branch] = array('f', [0]) outtree.Branch(branch, branch_vectors[branch], f'{branch}/F') - selection_pass = array('i', [1]) - outtree.Branch('selection_pass', selection_pass, 'selection_pass/I') - # Fill the tree for i in range(tree.GetEntries()): tree.GetEntry(i) - selection_pass[0] = compute_selection_pass(tree, selections) for branch, scores in all_scores.items(): branch_data = branch_vectors[branch] @@ -376,7 +292,7 @@ def main(): # Write the modified tree to the new file print(f'Writing to file {args.destination}') print(f'Input entries: {tree.GetEntries()}, Output entries: {outtree.GetEntries()}') - print(f'Wrote scores to {args.branch_name} and selection_pass') + print(f'Wrote scores to {args.branch_name}') outtree.Write() outfile.Close() infile.Close() @@ -385,4 +301,4 @@ def main(): np.savez(args.destination, scores=all_scores, labels=all_labels, tracking_info=all_tracking) if __name__ == '__main__': - main() + main() \ No newline at end of file diff --git a/root_gnn_dgl/scripts/plot_config_distributions.py b/root_gnn_dgl/scripts/plot_config_distributions.py deleted file mode 100644 index 72cec8039651a0f35004f3786f324816ba146181..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/scripts/plot_config_distributions.py +++ /dev/null @@ -1,304 +0,0 @@ -#!/usr/bin/env python3 - -import argparse -import glob -import math -import os -import re -from pathlib import Path - -import awkward as ak -import matplotlib -matplotlib.use("Agg") -import matplotlib.pyplot as plt -from matplotlib.backends.backend_pdf import PdfPages -import numpy as np -import uproot -import yaml - - -OPERATORS = { - ">": lambda values, cut: values > cut, - ">=": lambda values, cut: values >= cut, - "<": lambda values, cut: values < cut, - "<=": lambda values, cut: values <= cut, - "==": lambda values, cut: values == cut, - "!=": lambda values, cut: values != cut, -} - - -def load_config(path): - with open(path, "r", encoding="utf-8") as handle: - return yaml.safe_load(handle) - - -def selection_branches(selection): - if isinstance(selection, str): - tokens = re.findall(r"\b[A-Za-z_][A-Za-z0-9_]*\b", selection) - keywords = {"and", "or", "not", "True", "False"} - return [token for token in tokens if token not in keywords] - if isinstance(selection, (list, tuple)) and len(selection) > 0: - return [selection[0]] - return [] - - -def feature_branches(node_branch_names): - branches = [] - for feature in node_branch_names: - if not isinstance(feature, list): - continue - for branch in feature: - if isinstance(branch, str) and branch != "CALC_E": - branches.append(branch) - return branches - - -def branches_for_dataset(dataset_config): - args = dataset_config["args"] - branches = feature_branches(args.get("node_branch_names", [])) - for selection in dataset_config.get("selections", []): - branches.extend(selection_branches(selection)) - return sorted(set(branches)) - - -def resolve_files(args): - raw_dir = args["raw_dir"] - file_names = args["file_names"] - files = [] - if isinstance(file_names, str): - files.extend(glob.glob(os.path.join(raw_dir, file_names))) - else: - for file_name in file_names: - files.extend(glob.glob(os.path.join(raw_dir, file_name))) - return sorted(files) - - -def load_arrays(dataset_config, max_events=None): - args = dataset_config["args"] - tree_name = args.get("tree_name", "nominal_Loose") - branches = branches_for_dataset(dataset_config) - arrays = [] - events_read = 0 - - for file_name in resolve_files(args): - with uproot.open(file_name) as root_file: - tree = root_file[tree_name] - entry_stop = None - if max_events is not None: - remaining = max_events - events_read - if remaining <= 0: - break - entry_stop = remaining - array = tree.arrays(branches, library="ak", entry_stop=entry_stop) - arrays.append(array) - if branches: - events_read += len(array[branches[0]]) - if max_events is not None and events_read >= max_events: - break - - if not arrays: - pattern = os.path.join(args["raw_dir"], str(args["file_names"])) - raise FileNotFoundError(f"No files found for pattern {pattern}") - return ak.concatenate(arrays, axis=0) - - -def selection_mask(data, selections): - first_field = data.fields[0] if len(data.fields) > 0 else None - if first_field is None: - return None - - mask = np.ones(len(data[first_field]), dtype=bool) - for selection in selections: - if isinstance(selection, str): - current_mask = eval(selection, {"__builtins__": {}}, data) - else: - branch, cut, op = selection - if op not in OPERATORS: - raise ValueError(f"Unknown selection operator: {op}") - current_mask = OPERATORS[op](data[branch], cut) - mask = mask & ak.to_numpy(current_mask) - return mask - - -def ensure_node_array(value, reference): - if isinstance(value, (int, float, complex)): - return ak.full_like(reference, value) - return value - - -def branch_array(data, branch, node_type, reference): - value = ensure_node_array(branch, reference) - if not isinstance(branch, str): - return value - value = data[branch] - if node_type == "single": - return ak.singletons(value) - return value - - -def clean_label(value): - return str(value).replace("/", "_") - - -def per_type_feature_label(feature_spec, type_index): - return clean_label(feature_spec[type_index]) - - -def flatten_values(values): - flat_values = np.asarray(ak.to_numpy(ak.ravel(values)), dtype=float) - return flat_values[np.isfinite(flat_values)] - - -def build_feature_values(data, dataset_config): - args = dataset_config["args"] - node_branch_names = args["node_branch_names"] - node_branch_types = args["node_branch_types"] - node_feature_scales = [float(scale) for scale in args["node_feature_scales"]] - n_types = len(node_branch_names[0]) - - references = [] - for type_index in range(n_types): - branch = node_branch_names[0][type_index] - node_type = node_branch_types[type_index] - if isinstance(branch, str): - reference = data[branch] - if node_type == "single": - reference = ak.singletons(reference) - else: - raise ValueError("The first node feature must use real branches to define node counts.") - references.append(reference) - - features = {} - pt_parts = [] - eta_parts = [] - - for type_index in range(n_types): - pt_parts.append(branch_array(data, node_branch_names[0][type_index], node_branch_types[type_index], references[type_index])) - eta_parts.append(branch_array(data, node_branch_names[1][type_index], node_branch_types[type_index], references[type_index])) - - for feature_index, feature_spec in enumerate(node_branch_names): - if not isinstance(feature_spec, list): - continue - - per_type_parts = [] - for type_index in range(n_types): - branch = feature_spec[type_index] - if not isinstance(branch, str) or branch == "CALC_E": - per_type_parts.append(None) - continue - - reference = references[type_index] - node_type = node_branch_types[type_index] - per_type_parts.append(branch_array(data, branch, node_type, reference)) - - for type_index, part in enumerate(per_type_parts): - if part is None: - continue - scaled_part = part * node_feature_scales[feature_index] - scaled_pt = pt_parts[type_index] * node_feature_scales[0] - scaled_part = scaled_part[scaled_pt != 0] - features[per_type_feature_label(feature_spec, type_index)] = flatten_values(scaled_part) - - return features - - -def common_bins(datasets, feature_name, bins): - values = np.concatenate([features[feature_name] for features in datasets.values() if len(features[feature_name]) > 0]) - if len(values) == 0: - return np.linspace(0, 1, bins + 1) - - unique_values = np.unique(values) - if len(unique_values) <= 20 and np.allclose(unique_values, np.round(unique_values)): - low = math.floor(values.min()) - high = math.ceil(values.max()) - return np.arange(low - 0.5, high + 1.5, 1) - - low, high = np.percentile(values, [0.5, 99.5]) - if not np.isfinite(low) or not np.isfinite(high) or low == high: - low, high = values.min(), values.max() - if low == high: - low -= 0.5 - high += 0.5 - return np.linspace(low, high, bins + 1) - - -def plot_feature(feature_name, datasets, bins): - fig, ax = plt.subplots(figsize=(8, 6)) - hist_bins = common_bins(datasets, feature_name, bins) - - for dataset_name, features in datasets.items(): - values = features[feature_name] - if len(values) == 0: - continue - ax.hist( - values, - bins=hist_bins, - histtype="step", - density=True, - linewidth=1.8, - label=f"{dataset_name} (n={len(values)})", - ) - - ax.set_xlabel(feature_name) - ax.set_ylabel("Normalized entries") - ax.legend(frameon=False) - ax.grid(alpha=0.25) - fig.tight_layout() - return fig - - -def safe_filename(name): - return re.sub(r"[^A-Za-z0-9_.-]+", "_", name).strip("_") - - -def main(): - parser = argparse.ArgumentParser( - description="Plot model-input node feature distributions for every dataset in a config." - ) - parser.add_argument("--config", required=True, help="YAML config containing Datasets.") - parser.add_argument( - "--output-dir", - default=None, - help="Directory for optional PNG outputs. Defaults to plots/_distributions.", - ) - parser.add_argument( - "--output-pdf", - default=None, - help="Path for the multi-page PDF. Defaults to plots/_distributions.pdf.", - ) - parser.add_argument("--write-pngs", action="store_true", help="Also write one PNG per plot.") - parser.add_argument("--bins", type=int, default=80, help="Number of bins for continuous features.") - parser.add_argument("--max-events", type=int, default=None, help="Optional maximum events per dataset.") - args = parser.parse_args() - - config = load_config(args.config) - output_dir = Path(args.output_dir) if args.output_dir else Path("plots") / f"{Path(args.config).stem}_distributions" - output_pdf = Path(args.output_pdf) if args.output_pdf else Path("plots") / f"{Path(args.config).stem}_distributions.pdf" - output_pdf.parent.mkdir(parents=True, exist_ok=True) - if args.write_pngs: - output_dir.mkdir(parents=True, exist_ok=True) - - dataset_features = {} - for dataset_name, dataset_config in config["Datasets"].items(): - print(f"Loading {dataset_name}", flush=True) - data = load_arrays(dataset_config, max_events=args.max_events) - mask = selection_mask(data, dataset_config.get("selections", [])) - if mask is not None: - data = data[mask] - dataset_features[dataset_name] = build_feature_values(data, dataset_config) - - feature_names = list(next(iter(dataset_features.values())).keys()) - with PdfPages(output_pdf) as pdf: - for feature_name in feature_names: - fig = plot_feature(feature_name, dataset_features, args.bins) - pdf.savefig(fig) - if args.write_pngs: - output_path = output_dir / f"{safe_filename(feature_name)}.png" - fig.savefig(output_path, dpi=160) - print(f"Wrote {output_path}", flush=True) - plt.close(fig) - print(f"Wrote {output_pdf}", flush=True) - - -if __name__ == "__main__": - main() diff --git a/root_gnn_dgl/scripts/prep_data.py b/root_gnn_dgl/scripts/prep_data.py index fc0eec79b4f5e1fe8d04248a334674b3f13b649a..87306c834cc1e84e115a85b52e609c2deb956ec7 100644 --- a/root_gnn_dgl/scripts/prep_data.py +++ b/root_gnn_dgl/scripts/prep_data.py @@ -1,63 +1,13 @@ import sys import os -import glob -from pathlib import Path - -REPO_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(REPO_ROOT)) +file_path = os.getcwd() +sys.path.append(file_path) import root_gnn_base.utils as utils -from root_gnn_base.dataset import compute_cutflow, print_cutflow -import uproot -import awkward as ak import argparse from root_gnn_base.batched_dataset import PreBatchedDataset from root_gnn_base.batched_dataset import LazyPreBatchedDataset - -def print_dataset_cutflow(dset_config, dataset_name): - args = dset_config["args"] - raw_dir = args["raw_dir"] - file_names = args["file_names"] - tree_name = args.get("tree_name", "nominal_Loose") - selections = dset_config.get("selections", []) - - files = [] - if isinstance(file_names, str): - files = glob.glob(os.path.join(raw_dir, file_names)) - else: - for file_name in file_names: - files.extend(glob.glob(os.path.join(raw_dir, file_name))) - - branches = [] - for feat in args.get("node_branch_names", []): - if isinstance(feat, list): - for branch in feat: - if isinstance(branch, str) and branch != "CALC_E": - branches.append(branch) - for feat in args.get("global_features", []): - if isinstance(feat, str): - branches.append(feat) - for feat in args.get("tracking_info", []): - if isinstance(feat, str): - branches.append(feat) - from root_gnn_base.dataset import selection_branches - for selection in selections: - branches.extend(selection_branches(selection)) - branches = sorted(set(branches)) - - arrays = [] - for file in files: - with uproot.open(file) as f: - arrays.append(f[tree_name].arrays(branches, library="ak")) - if not arrays: - print(f"No files found for dataset {dataset_name} in {os.path.join(raw_dir, str(file_names))}") - return - - data = ak.concatenate(arrays, axis=0) - cutflow = compute_cutflow(data, selections) - print_cutflow(cutflow, title=f"Cutflow for {dataset_name}") - def main(): parser = argparse.ArgumentParser() add_arg = parser.add_argument @@ -70,7 +20,6 @@ def main(): config = utils.load_config(args.config) dset_config = config['Datasets'][args.dataset] - print_dataset_cutflow(dset_config, args.dataset) batch_size = config['Training']['batch_size'] if not args.shuffle_mode: dset = utils.buildFromConfig(dset_config, {'process_chunks': [args.chunk,]}) @@ -80,17 +29,16 @@ def main(): batch_size = dset_config['batch_size'] shuffle_chunks = dset_config.get('shuffle_chunks', 10) - shuffle_seed = dset_config.get('shuffle_seed', 12345) padding_mode = dset_config.get('padding_mode', 'STEPS') fold_conf = dset_config["folding"] - print(f"shuffle_chunks = {shuffle_chunks}, args.chunk = {args.chunk}, padding_mode = {padding_mode}, shuffle_seed = {shuffle_seed}") + print(f"shuffle_chunks = {shuffle_chunks}, args.chunk = {args.chunk}, padding_mode = {padding_mode}") if dset_config["class"] == "LazyMultiLabelDataset": - LazyPreBatchedDataset(start_dataset = dset, batch_size = batch_size, mask_fn = utils.fold_selection(fold_conf, "train"), suffix = utils.fold_selection_name(fold_conf, "train"), chunks = shuffle_chunks, chunkno = args.chunk, padding_mode = padding_mode, drop_last=args.drop_last, hidden_size=config['Model']['args']['hid_size'], shuffle_seed=shuffle_seed ) - LazyPreBatchedDataset(start_dataset = dset, batch_size = batch_size, mask_fn = utils.fold_selection(fold_conf, "test"), suffix = utils.fold_selection_name(fold_conf, 'test'), chunks = shuffle_chunks, chunkno = args.chunk, padding_mode = padding_mode, drop_last=args.drop_last, hidden_size=config['Model']['args']['hid_size'], shuffle_seed=shuffle_seed) + LazyPreBatchedDataset(start_dataset = dset, batch_size = batch_size, mask_fn = utils.fold_selection(fold_conf, "train"), suffix = utils.fold_selection_name(fold_conf, "train"), chunks = shuffle_chunks, chunkno = args.chunk, padding_mode = padding_mode, drop_last=args.drop_last) + LazyPreBatchedDataset(start_dataset = dset, batch_size = batch_size, mask_fn = utils.fold_selection(fold_conf, "test"), suffix = utils.fold_selection_name(fold_conf, 'test'), chunks = shuffle_chunks, chunkno = args.chunk, padding_mode = padding_mode, drop_last=args.drop_last) else: - PreBatchedDataset(dset, batch_size, utils.fold_selection(fold_conf, "train"), suffix = utils.fold_selection_name(fold_conf, "train"), chunks = shuffle_chunks, chunkno = args.chunk, padding_mode = padding_mode, drop_last=args.drop_last,hidden_size=config['Model']['args']['hid_size'], shuffle_seed=shuffle_seed) - PreBatchedDataset(dset, batch_size, utils.fold_selection(fold_conf, "test"), suffix = utils.fold_selection_name(fold_conf, 'test'), chunks = shuffle_chunks, chunkno = args.chunk, padding_mode = padding_mode, drop_last=args.drop_last,hidden_size=config['Model']['args']['hid_size'], shuffle_seed=shuffle_seed ) + PreBatchedDataset(dset, batch_size, utils.fold_selection(fold_conf, "train"), suffix = utils.fold_selection_name(fold_conf, "train"), chunks = shuffle_chunks, chunkno = args.chunk, padding_mode = padding_mode, drop_last=args.drop_last) + PreBatchedDataset(dset, batch_size, utils.fold_selection(fold_conf, "test"), suffix = utils.fold_selection_name(fold_conf, 'test'), chunks = shuffle_chunks, chunkno = args.chunk, padding_mode = padding_mode, drop_last=args.drop_last) if __name__ == "__main__": - main() + main() \ No newline at end of file diff --git a/root_gnn_dgl/scripts/selections.py b/root_gnn_dgl/scripts/selections.py deleted file mode 100644 index 5cf19ca46a8662cf476ebcdeeebd3d8f3c697696..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/scripts/selections.py +++ /dev/null @@ -1,104 +0,0 @@ -import argparse -import glob -import os -import sys -from pathlib import Path - -import awkward as ak -import uproot - -REPO_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(REPO_ROOT)) - -from root_gnn_base import utils -from root_gnn_base.dataset import selection_branches, check_selection, print_cutflow, init_cutflow - - -def get_branches(dataset_config): - args = dataset_config["args"] - branches = [] - for feat in args.get("node_branch_names", []): - if isinstance(feat, list): - for branch in feat: - if isinstance(branch, str) and branch != "CALC_E": - branches.append(branch) - for feat in args.get("global_features", []): - if isinstance(feat, str): - branches.append(feat) - for feat in args.get("tracking_info", []): - if isinstance(feat, str): - branches.append(feat) - for selection in dataset_config.get("selections", []): - branches.extend(selection_branches(selection)) - return sorted(set(branches)) - - -def load_arrays(dataset_config): - args = dataset_config["args"] - raw_dir = args["raw_dir"] - file_names = args["file_names"] - tree_name = args.get("tree_name", "nominal_Loose") - - files = [] - if isinstance(file_names, str): - files = glob.glob(os.path.join(raw_dir, file_names)) - else: - for file_name in file_names: - files.extend(glob.glob(os.path.join(raw_dir, file_name))) - - branches = get_branches(dataset_config) - arrays = [] - for file in files: - with uproot.open(file) as f: - arrays.append(f[tree_name].arrays(branches, library="ak")) - if not arrays: - raise FileNotFoundError(f"No files found in {os.path.join(raw_dir, str(file_names))}") - return ak.concatenate(arrays, axis=0), branches - - -def vectorized_cutflow(data, selections): - cutflow = init_cutflow(selections) - first_field = data.fields[0] if len(data.fields) > 0 else None - cutflow["total"] = len(data[first_field]) if first_field is not None else 0 - mask = ak.ones_like(data[first_field], dtype=bool) if first_field is not None else None - - for i, selection in enumerate(selections): - if isinstance(selection, str): - current_mask = eval(selection, {"__builtins__": {}}, data) - else: - current_mask = check_selection(data, selection) - current_mask = ak.to_numpy(current_mask) - if mask is None: - mask = current_mask - else: - mask = mask & current_mask - cutflow["counts"][i] = int(ak.sum(mask)) - return cutflow - - -def main(): - parser = argparse.ArgumentParser(description="Fast selection tester and cutflow printer") - parser.add_argument("--config", required=True, help="Path to YAML config file") - args = parser.parse_args() - - config = utils.load_config(args.config) - for dataset_name, dataset_config in config["Datasets"].items(): - selections = dataset_config.get("selections", []) - print(f"\n== Dataset: {dataset_name} ==") - - data, branches = load_arrays(dataset_config) - - for selection in selections: - try: - _ = eval(selection, {"__builtins__": {}}, data) if isinstance(selection, str) else check_selection({b: data[b] for b in branches}, selection) - print(f"OK: {selection}") - except Exception: - print(f"FAILED: {selection}") - raise - - cutflow = vectorized_cutflow(data, selections) - print_cutflow(cutflow, title=f"Cutflow for {dataset_name}") - - -if __name__ == "__main__": - main() diff --git a/root_gnn_dgl/scripts/training_script.py b/root_gnn_dgl/scripts/training_script.py index a73ffde84c18f5bf1cab81a37753f65beecb4767..ae733e860ba0459c470890b6be006bfe7829fe46 100644 --- a/root_gnn_dgl/scripts/training_script.py +++ b/root_gnn_dgl/scripts/training_script.py @@ -3,7 +3,6 @@ import time import datetime import yaml import os -from pathlib import Path start_time = time.time() @@ -12,8 +11,8 @@ import torch import torch.nn as nn import sys -REPO_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(REPO_ROOT)) +file_path = os.getcwd() +sys.path.append(file_path) import root_gnn_base.batched_dataset as datasets from root_gnn_base import utils import root_gnn_base.custom_scheduler as lr_utils @@ -46,10 +45,10 @@ def gpu_mem(): # except: # pass print(f'Current GPU memory usage: {torch.cuda.memory_allocated() / 1024 / 1024 / 1024} GB') - # print(f'Current GPU cache usage: {torch.cuda.memory_cached() / 1024 / 1024 / 1024} GB') - # print(f'Current GPU max memory usage: {torch.cuda.max_memory_allocated() / 1024 / 1024 / 1024} GB') - # print(f'Current GPU max cache usage: {torch.cuda.max_memory_cached() / 1024 / 1024 / 1024} GB') - # print(f'Numel in current tensors: {sum}') + print(f'Current GPU cache usage: {torch.cuda.memory_cached() / 1024 / 1024 / 1024} GB') + print(f'Current GPU max memory usage: {torch.cuda.max_memory_allocated() / 1024 / 1024 / 1024} GB') + print(f'Current GPU max cache usage: {torch.cuda.max_memory_cached() / 1024 / 1024 / 1024} GB') + print(f'Numel in current tensors: {sum}') mem() @@ -264,16 +263,11 @@ def train(train_loaders, test_loaders, model, device, config, args, rank): for epoch in range(starting_epoch, config['Training']['epochs']): start = time.time() run = start - if (args.profile): - if (epoch == 0): - torch.cuda.cudart().cudaProfilerStart() - torch.cuda.nvtx.range_push("Epoch Start") - if (args.multigpu or args.multinode): dist.barrier() - - if (epoch == 5): - exit + if (epoch == 2): + # torch.cuda.cudart().cudaProfilerStart() + pass # training model.train() @@ -298,8 +292,6 @@ def train(train_loaders, test_loaders, model, device, config, args, rank): if is_padded: #Padding the globals to match padded graphs. global_feats = torch.concatenate((global_feats, torch.zeros(1, len(global_feats[0])).to(device))) load = time.time() - if (args.profile): - torch.cuda.nvtx.range_push("Model Forward") if (len(logits) == 0): logits = model(graph, global_feats) tlabels = label @@ -310,9 +302,6 @@ def train(train_loaders, test_loaders, model, device, config, args, rank): weights = torch.concatenate((weights, track[:,1]), dim=0) batch_lengths.append(logits.shape[0] - 1) - if (args.profile): - torch.cuda.nvtx.range_pop() # popping model forward - if is_padded: keepmask = torch.full_like(logits[:,0], True, dtype=torch.bool) keepmask[batch_lengths] = False @@ -351,15 +340,11 @@ def train(train_loaders, test_loaders, model, device, config, args, rank): normalized_loss += label_loss loss = normalized_loss / len(unique_labels) - if (args.profile): - torch.cuda.nvtx.range_push("Model Backward") + optimizer.zero_grad() loss.backward() optimizer.step() total_loss += loss.detach().cpu().item() - - if (args.profile): - torch.cuda.nvtx.range_pop() # pop model backward ibatch += 1 cumulative_times[0] += batch_start - run cumulative_times[1] += load - batch_start @@ -381,10 +366,6 @@ def train(train_loaders, test_loaders, model, device, config, args, rank): labels = [] weights = [] model.eval() - - if (args.profile): - torch.cuda.nvtx.range_push("Model Evaluation") - with torch.no_grad(): for loader in test_loaders: for batch, label, track, global_feats in loader: @@ -405,9 +386,6 @@ def train(train_loaders, test_loaders, model, device, config, args, rank): eval_end = time.time() cumulative_times[3] += eval_end - run - if (args.profile): - torch.cuda.nvtx.range_pop() # pop evaluation - if scores == []: #If validation set is empty. continue logits = torch.concatenate(scores).to(device) @@ -497,8 +475,6 @@ def train(train_loaders, test_loaders, model, device, config, args, rank): try: #test_auc = roc_auc_score(labels[wgt_mask].to("cpu") == 1, scores[wgt_mask].to("cpu"), multi_class='ovr', sample_weight=weights[wgt_mask].to("cpu")) - if (len(scores[0]) != config["Model"]["args"]["out_size"]): - print("ERROR: The out_size and the number of class labels don't match! Please check config.") test_auc = roc_auc_score(labels_onehot[wgt_mask], scores[wgt_mask].to("cpu"), multi_class='ovr', sample_weight=weights[wgt_mask].to("cpu")) except ValueError: test_auc = np.nan @@ -603,9 +579,6 @@ def train(train_loaders, test_loaders, model, device, config, args, rank): custom_scheduler.step(model, {'test_auc':test_auc}) scheduler.step() - if (args.profile): - torch.cuda.nvtx.range_pop() # pop epoch - print(f"Load: {cumulative_times[0]:.4f} s") print(f"Batch: {cumulative_times[1]:.4f} s") print(f"Train: {cumulative_times[2]:.4f} s") @@ -705,7 +678,7 @@ def main(rank=0, args=None, world_size=1, port=24500, seed=12345): mask_fn = utils.fold_selection(fold_conf, "train") if args.preshuffle: # ldr = ldr_type(start_dataset=dset, batch_size=batch_size, mask_fn=mask_fn, suffix = utils.fold_selection_name(fold_conf, 'train'), chunks = shuffle_chunks, padding_mode = padding_mode, use_ddp = args.multigpu, rank=rank, world_size=world_size) - ldr = ldr_type(start_dataset=dset, batch_size=batch_size, mask_fn=mask_fn, suffix = utils.fold_selection_name(fold_conf, 'train'), chunks = shuffle_chunks, padding_mode = padding_mode, hidden_size = config["Model"]["args"]["hid_size"]) + ldr = ldr_type(start_dataset=dset, batch_size=batch_size, mask_fn=mask_fn, suffix = utils.fold_selection_name(fold_conf, 'train'), chunks = shuffle_chunks, padding_mode = padding_mode) gsamp, _, _, global_samp = ldr[0] sampler = None @@ -722,7 +695,7 @@ def main(rank=0, args=None, world_size=1, port=24500, seed=12345): sampler = DistributedSampler(ldr, num_replicas=world_size, rank=pargs.global_rank, shuffle=False, drop_last=True) train_loaders.append(torch.utils.data.DataLoader(ldr, batch_size = None, num_workers = 0, sampler = sampler)) sampler = None - ldr = ldr_type(start_dataset=dset, batch_size=batch_size, mask_fn=mask_fn, suffix = utils.fold_selection_name(fold_conf, 'test'), chunks = shuffle_chunks, padding_mode = padding_mode, hidden_size= config['Model']['args']['hid_size']) + ldr = ldr_type(start_dataset=dset, batch_size=batch_size, mask_fn=mask_fn, suffix = utils.fold_selection_name(fold_conf, 'test'), chunks = shuffle_chunks, padding_mode = padding_mode) if (args.multigpu): sampler = DistributedSampler(ldr, num_replicas=world_size, rank=rank, shuffle=False, drop_last=True) # num_batches = len(ldr) @@ -734,10 +707,10 @@ def main(rank=0, args=None, world_size=1, port=24500, seed=12345): test_loaders.append(torch.utils.data.DataLoader(ldr, batch_size = None, num_workers = 0, sampler=sampler)) - # if "validation" in fold_conf: - # val_loaders.append(torch.utils.data.DataLoader((ldr_type(start_dataset=dset, batch_size=batch_size, mask_fn=utils.fold_selection(fold_conf, "validation"), suffix = utils.fold_selection_name(fold_conf, 'validation'), chunks = shuffle_chunks, hidden_size=config['Model']['args']['hid_size'], padding_mode = padding_mode, rank=rank, world_size=1)), batch_size = None, num_workers = 0, sampler = sampler)) - # else: - # print("No validation set for dataset ", dset_conf) + if "validation" in fold_conf: + val_loaders.append(torch.utils.data.DataLoader((ldr_type(start_dataset=dset, batch_size=batch_size, mask_fn=utils.fold_selection(fold_conf, "validation"), suffix = utils.fold_selection_name(fold_conf, 'validation'), chunks = shuffle_chunks, padding_mode = padding_mode, rank=rank, world_size=1)), batch_size = None, num_workers = 0, sampler = sampler)) + else: + print("No validation set for dataset ", dset_conf) else: train_loaders.append(datasets.GetBatchedLoader(dset, batch_size, utils.fold_selection(fold_conf, "train"))) gsamp, _, _, global_samp = dset[0] @@ -751,8 +724,6 @@ def main(rank=0, args=None, world_size=1, port=24500, seed=12345): print("Load time: {:.4f} s".format(load_end - load_start)) model = utils.buildFromConfig(config["Model"], {'sample_graph': gsamp, 'sample_global': global_samp, 'seed': seed}).to(device) - pytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad) - print(f"Number of trainable parameters = {pytorch_total_params}") if not args.nocompile: model = torch.compile(model) if args.multigpu: @@ -817,7 +788,6 @@ if __name__ == "__main__": add_arg("--directory", type=str, help="Append to Training Directory") add_arg("--seed", type=int, default=2, help="Sets random seed") add_arg("--abs", action="store_true", help="Use abs value of per-event weight") - add_arg("--profile", action="store_true", help="use nsight systems profiler") pargs = parser.parse_args() diff --git a/root_gnn_dgl/setup/Dockerfile b/root_gnn_dgl/setup/Dockerfile deleted file mode 100755 index 854db7c1043c98701a35b99f4fcd5cbfaa04c102..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/setup/Dockerfile +++ /dev/null @@ -1,22 +0,0 @@ -FROM nvcr.io/nvidia/dgl:25.05-py3 - -WORKDIR /workspace - -LABEL maintainer.name="Joshua Ho" -LABEL maintainer.email="ho22joshua@berkeley.edu" - -ENV LANG=C.UTF-8 - -# System deps (with CA certs for HTTPS downloads) -RUN apt-get update -qq \ - && apt-get install -y --no-install-recommends \ - wget curl ca-certificates lsb-release gnupg software-properties-common \ - vim \ - g++-11 gcc-11 libstdc++-11-dev \ - openmpi-bin openmpi-common libopenmpi-dev \ - && rm -rf /var/lib/apt/lists/* - -# Python packages -RUN pip install --no-cache-dir mpi4py jupyter uproot - -EXPOSE 8888 \ No newline at end of file diff --git a/root_gnn_dgl/setup/build_image.sh b/root_gnn_dgl/setup/build_image.sh deleted file mode 100755 index aae10c14f375fb9427b6bc6564375383b3b571d1..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/setup/build_image.sh +++ /dev/null @@ -1,2 +0,0 @@ -podman-hpc build -t joshuaho/pytorch:1.0 --platform linux/amd64 . -podman-hpc migrate joshuaho/pytorch:1.0 diff --git a/root_gnn_dgl/setup/environment.yml b/root_gnn_dgl/setup/environment.yml index acf2a34ea3b5e72f1e4a4f32ea3b32856362ff75..d55c25d7b4d0f7b0b2f625c5dc47b4ed1bd47f12 100644 --- a/root_gnn_dgl/setup/environment.yml +++ b/root_gnn_dgl/setup/environment.yml @@ -1,4 +1,4 @@ -name: pytorch +name: dgl channels: - pytorch - dglteam/label/cu118 @@ -387,4 +387,5 @@ dependencies: - triton==2.3.0 - typing-extensions==4.11.0 - tzdata==2024.1 - - uproot==5.3.7 \ No newline at end of file + - uproot==5.3.7 +prefix: /global/homes/j/joshuaho/.conda/envs/dgl diff --git a/root_gnn_dgl/setup/launch_image.sh b/root_gnn_dgl/setup/launch_image.sh deleted file mode 100644 index 6f0b08dfc55d6577b883839ff18080028dbe0a06..0000000000000000000000000000000000000000 --- a/root_gnn_dgl/setup/launch_image.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash - -ENTRYPOINT=$1 -shift -ARGUEMENTS="$*" - -echo "launched image" -echo "Entrypoint = $ENTRYPOINT" -echo "Arguements = $ARGUEMENTS" - -podman-hpc run \ - -it \ - --mount type=bind,source=/pscratch/sd/j/joshuaho/,target=/pscratch/sd/j/joshuaho/ \ - --mount type=bind,source=/global/cfs/projectdirs/atlas/joshua/,target=/global/cfs/projectdirs/atlas/joshua/ \ - --rm \ - --network host \ - --gpu \ - --shm-size=32g \ - joshuaho/pytorch:1.0 \ - $ENTRYPOINT \ - $ARGUEMENTS \ No newline at end of file diff --git a/training_time.png b/training_time.png deleted file mode 100644 index 5cb363d853a012b511c5944ae7ea3c6fa761297a..0000000000000000000000000000000000000000 --- a/training_time.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:eccc855e8c797c433903e13422bd3e6024270e9db25decd8cba1d2233fd4166a -size 292604