Download tasks/task9.md from HWresearch/GNN4Colliders: direct link, hf CLI and curl.
- Browser
- Download file 19.1 kB
-
https://huggingface.co/HWresearch/GNN4Colliders/resolve/refs%2Fpr%2F13/tasks/task9.md
- Command line
-
hf download hf://HWresearch/GNN4Colliders@refs/pr/13/tasks/task9.md
-
curl -L -o task9.md https://huggingface.co/HWresearch/GNN4Colliders/resolve/refs%2Fpr%2F13/tasks/task9.md
Task 9: Implement Classification Tasks, Weighted Losses, Metrics, and Output Handling
Implement the task-level logic that converts model logits and batch metadata into losses, predictions, and evaluation metrics.
This task builds on:
Task 4: shared physics feature construction
Task 5: ROOT-GNN graph construction
Task 6: ROOT/Awkward ingestion and EventSample
Task 7: metadata-aware caching, splits, batching, and GraphBatch
Task 8: ROOT-GNN model and transfer/fine-tuning
Before making changes, read:
AGENTS.md
docs/architecture.md
docs/migration.md
Then inspect:
src/gnn4colliders/models/
src/gnn4colliders/training/
tests/unit/
tests/parity/
tests/integration/
legacy/root_gnn_dgl/models/loss.py
legacy/root_gnn_dgl/scripts/training_script.py
Focus on the active classification behavior used by standard ROOT-GNN training and evaluation.
Do not implement the epoch/training lifecycle, optimizer setup, scheduler, checkpoint orchestration, or DDP in this task.
Goal
Implement explicit task semantics around:
GraphBatch
->
Model
->
logits
->
classification task
├── loss
├── predictions
└── metrics
The model should remain responsible only for producing logits.
The task layer should be responsible for interpreting those logits for a particular learning problem.
Support the active:
binary classification
multiclass classification
workflows, including the transfer/fine-tuning use case.
1. Introduce a task layer
Add a small task abstraction.
Prefer a structure such as:
src/gnn4colliders/tasks/
__init__.py
binary_classification.py
multiclass_classification.py
or a similarly small organization.
Do not bury classification semantics inside the future trainer.
The trainer should eventually be able to do something conceptually like:
logits = model(batch)
loss = task.loss(logits, batch)
metrics = task.metrics(logits, batch)
The exact API may differ.
Keep it simple.
2. Keep training mechanics separate from task semantics
The task layer should own things like:
how logits are interpreted
how targets are shaped
how event weights are applied
how predictions are produced
which metrics are computed
The future trainer should own things like:
forward pass
backward pass
optimizer step
epochs
logging
checkpointing
Do not mix those responsibilities.
3. Binary classification task
Implement the active binary-classification behavior.
Expected model output:
[batch_size, 1]
The model returns raw logits.
The task should handle any reshaping needed for loss/metrics in an explicit way.
Do not apply sigmoid before BCEWithLogitsLoss.
For prediction/metrics, apply sigmoid where appropriate.
4. Binary targets
Characterize the active binary target representation from the legacy workflow.
Verify:
- dtype
- shape
- expected values
- whether labels arrive as
[B]or[B, 1]
Do not silently rely on PyTorch broadcasting.
Normalize target shape explicitly inside the task layer where appropriate.
Add tests for target-shape handling.
5. Legacy binary weighted loss
Reproduce the active legacy binary-loss behavior.
The architecture analysis indicates that the legacy code approximately does:
elementwise BCEWithLogitsLoss
->
multiply by event weights
->
average separately per unique label
->
average across labels
Verify the exact implementation against:
legacy/root_gnn_dgl/scripts/training_script.py
legacy/root_gnn_dgl/models/loss.py
Do not assume ordinary weighted BCE is equivalent.
Implement the actual active semantics.
6. Event weights use named metadata
The new implementation must obtain event weights through named metadata.
For example:
batch.metadata.weight
or the equivalent Task 7 API.
Do not reintroduce positional legacy access such as:
tracking[:, 1]
Add parity tests proving:
legacy tracking weight
==
new EventMetadata.weight
at the loss boundary.
7. Negative weights
Characterize the active legacy behavior for negative weights.
The legacy CLI historically has an --abs path that makes weights positive.
Do not make weights absolute by default unless that is the active task configuration.
The task/loss API should make this choice explicit.
For example, conceptually:
BinaryClassificationTask(
use_absolute_weights=False,
)
or an equivalent option.
Avoid hiding this behavior in dataset processing.
Add tests covering:
positive weights
negative weights
absolute-weight option
if the legacy active path supports them.
8. Per-class balancing semantics
If the legacy loss averages weighted loss separately for each unique label and then averages across labels, implement that explicitly.
For binary classification, this likely means something conceptually like:
loss(label == 0)
loss(label == 1)
mean of class losses
Verify the precise denominator/weight handling.
Do not replace it with:
torch.mean(weight * bce)
unless parity proves they are equivalent for the active implementation.
9. Multiclass classification task
Implement the active multiclass behavior.
The active pretraining model uses a multiclass output, historically with 12 outputs in the standard configuration.
Do not hardcode 12 into generic task logic.
Use:
num_classes
or infer from logits/configuration where appropriate.
Expected logits:
[batch_size, num_classes]
10. Multiclass target representation
Characterize the active legacy multiclass target representation carefully.
Determine whether the active path uses:
class indices
one-hot / multilabel-like target tensors
and which loss is actually used.
Do not assume CrossEntropyLoss merely because the task is multiclass.
The architecture analysis indicates the legacy default objective uses BCEWithLogitsLoss, including for the multiclass path.
Verify this directly.
Reproduce active behavior rather than replacing it with a more conventional formulation in this task.
If the current active multiclass labels are one-hot and use BCE-with-logits, preserve that for parity.
Document it as a compatibility behavior if it is unusual.
11. Multiclass weighted loss
Implement the active multiclass weighting/reduction behavior.
Verify:
- elementwise loss shape
- event-weight broadcast behavior
- per-label or per-class reduction
- final reduction
Use explicit operations rather than relying on ambiguous broadcasting.
Add small hand-computable tests.
12. Hand-computable loss tests
For both binary and multiclass behavior, add tests with tiny fixed tensors where expected loss can be calculated explicitly.
For example:
logits = ...
targets = ...
weights = ...
and compare against a manually constructed expected result.
These tests should not merely call the same helper function twice.
The purpose is to lock down reduction semantics.
13. Binary prediction semantics
Implement binary predictions according to the active legacy behavior.
The architecture analysis indicates:
sigmoid(logit) >= 0.5
or equivalent threshold behavior.
Verify exact comparison semantics:
>
>=
if it matters.
Expose prediction utilities clearly.
For example:
probabilities = task.probabilities(logits)
predictions = task.predict(logits)
The exact API may differ.
14. Binary probabilities
Provide access to sigmoid probabilities separately from hard predictions.
Do not mutate logits.
Keep:
logits
probabilities
predictions
conceptually distinct.
This will be useful later for inference and ROC calculations.
15. Multiclass prediction semantics
Implement active multiclass prediction behavior.
The architecture indicates predictions use:
argmax
Verify the exact dimension.
If probability-like outputs are needed, determine whether legacy evaluation uses:
sigmoid per output
softmax
raw logits
for ROC AUC.
Do not assume.
Characterize the actual active implementation.
16. Accuracy
Implement active accuracy metrics.
For binary classification:
- use the characterized threshold
- preserve weighting semantics if legacy accuracy is weighted
For multiclass classification:
- use argmax
- preserve weighting semantics if legacy accuracy is weighted
Verify whether the legacy metric is:
ordinary accuracy
weighted accuracy
and reproduce the active path.
17. ROC AUC
Implement active ROC AUC behavior using scikit-learn or an equivalent already-approved dependency.
For binary classification, verify:
- probability/score input
- sample weights
- handling of one-class batches/datasets
For multiclass classification, verify:
- one-vs-rest behavior
- score representation
- sample weights
- averaging mode
The architecture analysis indicates weighted ROC AUC and one-vs-rest multiclass behavior, but verify the exact implementation.
18. Metrics are evaluation-level, not necessarily batch-safe
Some metrics such as ROC AUC are not meaningful or robust on every individual mini-batch.
Design metric APIs so they can work on accumulated epoch-level predictions/targets/weights later.
Do not force the future trainer to compute ROC AUC independently on every batch.
Prefer metric functions that operate on:
all logits/scores for a split
all targets
all weights
This will integrate cleanly with Task 10.
19. Metric inputs
Prefer explicit metric input structures.
A lightweight structure is acceptable, for example:
@dataclass(frozen=True)
class ClassificationOutputs:
logits: torch.Tensor
targets: torch.Tensor
weights: torch.Tensor
Do not create abstractions unless they improve clarity.
Avoid coupling metrics directly to DGL graphs.
20. CPU conversion for sklearn metrics
If scikit-learn is used, isolate conversion from PyTorch tensors.
For example:
tensor.detach()
->
cpu()
->
numpy()
Do not accidentally keep autograd graphs alive during metric computation.
Keep conversion logic in one clear place.
21. Finish/postprocessing functions
Inspect active finish functions in:
legacy/root_gnn_dgl/models/loss.py
Determine which ones are actually used by the active standard configurations.
Only implement the output transformations required by active:
binary
multiclass
fine-tuning
workflows.
Do not migrate every historical finish function.
If output transformation is just:
sigmoid
argmax
prefer clear task methods over carrying forward arbitrary legacy "finish function" terminology.
22. Task API
Prefer a small interface.
Conceptually:
class BinaryClassificationTask:
def loss(self, logits, targets, weights): ...
def probabilities(self, logits): ...
def predict(self, logits): ...
def metrics(self, logits, targets, weights): ...
and:
class MulticlassClassificationTask:
...
The exact API can use functions or dataclasses instead of classes if simpler.
Do not introduce a deep abstract base-class hierarchy.
Only add a shared protocol/base abstraction if it reduces real duplication.
23. Batch-facing convenience API
It is acceptable to provide convenience methods that consume GraphBatch:
loss = task.loss_from_batch(logits, batch)
if this keeps the future trainer clean.
However, keep core loss functions testable using plain tensors.
Do not make the mathematical implementation depend on DGL.
24. Weight dtype/device
Ensure event weights are compatible with logits.
Handle:
- device
- dtype
- shape
explicitly.
Do not silently move the entire batch between CPU/GPU inside loss functions.
Small metadata tensors may be moved/cast as needed in a controlled way, but the behavior should be clear and tested.
25. Empty classes / missing labels
Characterize behavior when a loss-reduction batch contains no examples for one class.
This matters if the legacy implementation loops over unique labels.
Do not invent a divide-by-zero behavior.
Implement the observed semantics and add a test if this can occur.
26. Degenerate ROC AUC inputs
Handle cases where ROC AUC cannot be computed because only one class is present.
Choose behavior consistent with the active legacy workflow where possible.
Prefer an explicit:
NaN
None
clear exception
over a misleading numeric value.
Document the chosen behavior.
Do not hide metric failures silently.
27. No model changes unless required for interface cleanup
Do not change Task 8 model mathematics.
Model output remains raw logits.
Only make minimal interface changes if necessary to integrate with the task layer.
Any model change must preserve Task 8 parity.
28. No training lifecycle
Do not implement:
optimizer
backward
zero_grad
optimizer.step
epochs
schedulers
gradient clipping
early stopping
training loops
Those belong to Task 10.
29. No checkpointing
Do not implement:
checkpoint save
checkpoint resume
best epoch
last epoch
optimizer-state restoration
Those belong to Task 11.
30. No Hydra wiring yet
Do not implement full Hydra task configuration yet.
Use explicit Python task constructors/options.
Hydra/YAML composition will be wired in a later task.
31. No distributed metrics yet
Do not implement distributed all-gather/reduction.
Task 10/14 will address distributed execution.
Metric APIs should be designed so accumulated outputs can later be gathered across ranks.
32. Unit tests
Add focused tests under:
tests/unit/tasks/
Suggested files:
test_binary_classification.py
test_multiclass_classification.py
test_metrics.py
or a smaller clear organization.
Cover:
binary loss
binary weighting
negative weights
absolute-weight option
binary thresholding
binary probabilities
multiclass loss
multiclass predictions
accuracy
ROC AUC
shape validation
dtype/device handling
33. Legacy parity tests
Add parity tests comparing new task logic to the active legacy implementations.
Use deterministic fixed:
logits
targets
weights
rather than running a full training loop.
Compare:
- loss
- probabilities/scores
- predictions
- accuracy
- ROC AUC
where deterministic and practical.
34. Fine-tuning task parity
Explicitly cover the active binary fine-tuning case produced by:
FineTunedEdgeNetwork
Use deterministic logits or a deterministic model fixture.
Verify:
FineTunedEdgeNetwork
->
raw binary logits
->
BinaryClassificationTask
->
weighted loss / metrics
No optimizer or backward pass is needed.
35. Multiclass pretraining task parity
Explicitly cover the active pretraining output.
Verify:
EdgeNetwork(out_size=active_num_classes)
->
raw logits
->
MulticlassClassificationTask
matches legacy loss/prediction/metric semantics.
36. Integration test
Add an integration test covering:
tiny ROOT fixture
->
GraphBatch
->
EdgeNetwork or FineTunedEdgeNetwork
->
logits
->
task loss
->
task predictions
Verify:
- finite loss
- expected shape
- metadata weight use
- no positional tracking dependency
Do not perform backward/optimizer steps yet.
37. Documentation
Update:
docs/architecture.md
to make the new boundary explicit:
model
raw logits only
task
target semantics
weighting
loss
probabilities
predictions
metrics
trainer
future execution lifecycle
Document that event weights come from:
EventMetadata.weight / BatchMetadata.weight
rather than legacy tracking columns.
If the active multiclass implementation intentionally retains unusual BCE-with-logits semantics, document that as a compatibility behavior.
Update:
docs/migration.md
when Task 9 parity is established.
38. Public exports
Expose the intended task APIs.
For example:
from gnn4colliders.tasks import (
BinaryClassificationTask,
MulticlassClassificationTask,
)
Do not expose internal helper functions unnecessarily.
Validation
Run focused tests:
uv run pytest tests/unit/tasks -v
Run relevant model/integration tests:
uv run pytest tests/unit/models/root_gnn -v
uv run pytest tests/integration -v
Run parity tests:
uv run pytest tests/parity -v
Run the full suite:
uv run pytest
Run lint/format checks:
uv run ruff check src tests
uv run ruff format --check src tests
Inspect:
git status
git diff
Verify:
- legacy code is unchanged
- weights are accessed through named metadata
- no positional tracking API has returned
- model outputs remain raw logits
- no optimizer/training loop was added
- no checkpoint system was added
- no unrelated changes are included
Completion criteria
Task 9 is complete when:
- A clear task layer exists.
- Binary classification behavior is implemented.
- Multiclass classification behavior is implemented.
- Active legacy loss semantics are reproduced.
- Event weights use named metadata.
- Negative/absolute-weight semantics are explicit.
- Binary probability and threshold behavior match legacy.
- Multiclass prediction behavior matches legacy.
- Accuracy matches active legacy semantics.
- Binary weighted ROC AUC matches legacy.
- Multiclass one-vs-rest ROC AUC matches legacy.
- Task APIs can operate on plain tensors independently of DGL.
- Fine-tuning task parity passes.
- Multiclass pretraining task parity passes.
- Unit tests pass.
- Integration tests pass.
- Parity tests pass.
- Full tests pass.
- No training lifecycle or checkpoint implementation has been added.
- Legacy code remains untouched.
Completion report
Report:
- files created
- files modified
- task API design
- binary target semantics
- binary weighted-loss formula
- negative-weight handling
- multiclass target semantics
- multiclass loss formula
- prediction/probability behavior
- accuracy behavior
- ROC AUC behavior
- degenerate metric handling
- legacy finish-function behavior retained or replaced
- event-weight metadata integration
- unit test results
- integration test results
- parity results
- intentional deviations from legacy internals
- numerical tolerances used
- unresolved ambiguities
- validation commands and results
After validation succeeds, create one Git commit containing only Task 9 changes.
Use:
feat: implement classification losses and metrics
Before committing, inspect the final diff and ensure no unrelated files are included.