-
Notifications
You must be signed in to change notification settings - Fork 55
Gflownet optimize loss computation #451
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
josephdviviano
wants to merge
16
commits into
master
Choose a base branch
from
gflownet_optimize
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
b371585
debug threading through base class, gating of various warnings / asserts
josephdviviano b13b5b7
added loss information for special cases
josephdviviano d83fa5d
wandb removed by default, fixed imports for script / module runs
josephdviviano 5e50be7
switched seeding to use a local generator to prevent side-effects
josephdviviano 4621d71
tests for vectorized versions matching legacy
josephdviviano 4b8d30a
checkpoint before we re-try to vectorize the subtb loss calculation
josephdviviano c148a67
added benchmark
josephdviviano 3bbacb0
major speedup
josephdviviano d85d149
optimized code, good performance on all devices without pure vectoriz…
josephdviviano 953de5a
get_scores optimized for DetailedBalance
josephdviviano 3c554ba
added some benchmarking scripts (to be amalgamated)
josephdviviano a765178
black
josephdviviano 73bbaa5
very minor modified DB optimizations
josephdviviano c328e63
micro-optimizations for tb-style losses
josephdviviano 9eb52c8
added benchmark results for optimization
josephdviviano e0af06f
update
josephdviviano File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,3 @@ | ||
| import math | ||
| import warnings | ||
| from abc import ABC, abstractmethod | ||
| from typing import Any, Generic, Tuple, TypeVar | ||
|
|
@@ -48,6 +47,16 @@ class GFlowNet(ABC, nn.Module, Generic[TrainingSampleType]): | |
|
|
||
| log_reward_clip_min = float("-inf") # Default off. | ||
|
|
||
| def __init__(self, debug: bool = False) -> None: | ||
| """Initialize shared GFlowNet state. | ||
|
|
||
| Args: | ||
| debug: If True, keep runtime safety checks and warnings active. Set False | ||
| in compiled hot paths to avoid graph breaks; use True in tests/debugging. | ||
| """ | ||
| super().__init__() | ||
| self.debug = debug | ||
|
|
||
| @abstractmethod | ||
| def sample_trajectories( | ||
| self, | ||
|
|
@@ -148,13 +157,17 @@ def loss_from_trajectories( | |
|
|
||
| def assert_finite_gradients(self): | ||
| """Asserts that the gradients are finite.""" | ||
| if not self.debug: | ||
| return | ||
| for p in self.parameters(): | ||
| if p.grad is not None: | ||
| if not torch.isfinite(p.grad).all(): | ||
| raise RuntimeError("GFlowNet has non-finite gradients") | ||
|
|
||
| def assert_finite_parameters(self): | ||
| """Asserts that the parameters are finite.""" | ||
| if not self.debug: | ||
| return | ||
|
Comment on lines
+169
to
+170
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same |
||
| for p in self.parameters(): | ||
| if not torch.isfinite(p).all(): | ||
| raise RuntimeError("GFlowNet has non-finite parameters") | ||
|
|
@@ -177,6 +190,7 @@ def __init__( | |
| pb: Estimator | None, | ||
| constant_pb: bool = False, | ||
| log_reward_clip_min: float = float("-inf"), | ||
| debug: bool = False, | ||
| ) -> None: | ||
| """Initializes a PFBasedGFlowNet instance. | ||
|
|
||
|
|
@@ -189,9 +203,10 @@ def __init__( | |
| explicitly by user to ensure that pb is an Estimator except under this | ||
| special case. | ||
| log_reward_clip_min: If finite, clips log rewards to this value. | ||
| debug: If True, keep runtime safety checks active; disable in compiled runs. | ||
|
|
||
| """ | ||
| super().__init__() | ||
| super().__init__(debug=debug) | ||
| # Technical note: pb may be constant for a variety of edge cases, for example, | ||
| # if all terminal states can be reached with exactly the same number of | ||
| # trajectories, and we assume a uniform backward policy, then we can omit the pb | ||
|
|
@@ -365,23 +380,34 @@ def get_scores( | |
| ) | ||
|
|
||
| assert log_pf_trajectories is not None | ||
| total_log_pf_trajectories = log_pf_trajectories.sum(dim=0) | ||
| total_log_pb_trajectories = log_pb_trajectories.sum(dim=0) | ||
| total_log_pf_trajectories = log_pf_trajectories.sum(dim=0) # [N] | ||
| total_log_pb_trajectories = log_pb_trajectories.sum(dim=0) # [N] | ||
|
|
||
| log_rewards = trajectories.log_rewards | ||
| assert log_rewards is not None | ||
|
|
||
| if math.isfinite(self.log_reward_clip_min): | ||
| # Fast path: skip clamp when log_reward_clip_min is -inf to avoid extra work. | ||
| # TODO: Do we need log reward clamping at all? | ||
| if self.log_reward_clip_min != float("-inf"): | ||
| log_rewards = log_rewards.clamp_min(self.log_reward_clip_min) | ||
|
|
||
| if torch.any(torch.isinf(total_log_pf_trajectories)): | ||
| raise ValueError("Infinite pf logprobs found") | ||
| if torch.any(torch.isinf(total_log_pb_trajectories)): | ||
| raise ValueError("Infinite pb logprobs found") | ||
|
|
||
| assert total_log_pf_trajectories.shape == (trajectories.n_trajectories,) | ||
| assert total_log_pb_trajectories.shape == (trajectories.n_trajectories,) | ||
| return total_log_pf_trajectories - total_log_pb_trajectories - log_rewards | ||
| # Keep runtime safety checks under `debug` to avoid graph breaks in torch.compile. | ||
| if self.debug: | ||
| if torch.any(torch.isinf(total_log_pf_trajectories)): | ||
| raise ValueError("Infinite pf logprobs found") | ||
| if torch.any(torch.isinf(total_log_pb_trajectories)): | ||
| raise ValueError("Infinite pb logprobs found") | ||
| assert total_log_pf_trajectories.shape == (trajectories.n_trajectories,) | ||
| assert total_log_pb_trajectories.shape == (trajectories.n_trajectories,) | ||
|
|
||
| # Fused (pf - pb) then subtract rewards; keep it branch-free/out-of-place | ||
| # to stay friendly to torch.compile graphs. | ||
| scores = torch.sub( | ||
| total_log_pf_trajectories, total_log_pb_trajectories, alpha=1.0 | ||
| ) | ||
| # Subtract rewards in a separate op to avoid in-place mutations (graph-stable) | ||
| # while still keeping only one extra temporary. | ||
| scores = scores - log_rewards | ||
| return scores | ||
|
|
||
| def to_training_samples(self, trajectories: Trajectories) -> Trajectories: | ||
| """Returns the input trajectories as training samples. | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
it would be better to check self.debug at the caller level, not here