funcflows 0.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- FuncFlows/__init__.py +0 -0
- FuncFlows/base_measures/__init__.py +3 -0
- FuncFlows/base_measures/abstract_reference_measure.py +28 -0
- FuncFlows/base_measures/bases.py +112 -0
- FuncFlows/base_measures/gaussian_reference_measure.py +37 -0
- FuncFlows/diagnostics/__init__.py +2 -0
- FuncFlows/diagnostics/coverage.py +46 -0
- FuncFlows/diagnostics/importance.py +60 -0
- FuncFlows/objectives/__init__.py +5 -0
- FuncFlows/objectives/alpha_divergence.py +67 -0
- FuncFlows/objectives/flow_matching.py +132 -0
- FuncFlows/objectives/negative_logl.py +15 -0
- FuncFlows/objectives/reverse_kl.py +48 -0
- FuncFlows/samplers/__init__.py +1 -0
- FuncFlows/samplers/latent_pcn.py +53 -0
- FuncFlows/transports/__init__.py +3 -0
- FuncFlows/transports/abstract_transformation.py +32 -0
- FuncFlows/transports/continuous/__init__.py +6 -0
- FuncFlows/transports/continuous/base_continuous.py +63 -0
- FuncFlows/transports/continuous/conditioners.py +83 -0
- FuncFlows/transports/continuous/grid_fields.py +403 -0
- FuncFlows/transports/continuous/vector_fields.py +306 -0
- FuncFlows/transports/layers/__init__.py +2 -0
- FuncFlows/transports/layers/base_discrete.py +29 -0
- FuncFlows/transports/layers/layer_classes.py +81 -0
- FuncFlows/utils/__init__.py +0 -0
- FuncFlows/utils/gaussian_misfit.py +16 -0
- FuncFlows/utils/train.py +31 -0
- funcflows-0.1.2.dist-info/METADATA +43 -0
- funcflows-0.1.2.dist-info/RECORD +33 -0
- funcflows-0.1.2.dist-info/WHEEL +5 -0
- funcflows-0.1.2.dist-info/licenses/LICENSE +21 -0
- funcflows-0.1.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def combine_context(stack, context, weights):
|
|
7
|
+
"""sum_t w_t (stack_t @ context) without forming the [batch, out, context] tensor. """
|
|
8
|
+
|
|
9
|
+
partial = torch.einsum("toc,bc->bto", stack, context)
|
|
10
|
+
|
|
11
|
+
return (weights.reshape(-1, stack.shape[0], 1) * partial).sum(1)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
################################################################################################################
|
|
15
|
+
################################################################################################################
|
|
16
|
+
################################################################################################################
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class VectorField(torch.nn.Module):
|
|
20
|
+
"""dv/dt = velocity(coeffs, time). Must also expose the trace of its Jacobian.
|
|
21
|
+
|
|
22
|
+
'v' is used to refer to the function space coefficient vectors
|
|
23
|
+
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
supports_batched_time = False # can `time_value` carry one entry per sample?
|
|
27
|
+
trace_samples = 1 # Hutchinson probes, where the trace is estimated
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def velocity(self, coeffs, time_value, context=None):
|
|
31
|
+
raise NotImplementedError
|
|
32
|
+
|
|
33
|
+
def trace(self, coeffs, time_value, context=None):
|
|
34
|
+
return self.estimated_trace(coeffs, time_value, context)
|
|
35
|
+
|
|
36
|
+
def estimated_trace(self, coeffs, time_value, context=None):
|
|
37
|
+
return self.estimated_velocity_and_trace(coeffs, time_value, context)[1]
|
|
38
|
+
|
|
39
|
+
def estimated_velocity_and_trace(self, coeffs, time_value, context=None):
|
|
40
|
+
"""Hutchinson (FFJORD): Tr J = E[probe . J probe] for any probe with unit covariance."""
|
|
41
|
+
needs_graph = torch.is_grad_enabled()
|
|
42
|
+
|
|
43
|
+
with torch.enable_grad():
|
|
44
|
+
state = coeffs if coeffs.requires_grad else coeffs.detach().requires_grad_(True)
|
|
45
|
+
velocity = self.velocity(state, time_value, context)
|
|
46
|
+
total = torch.zeros_like(coeffs[..., 0])
|
|
47
|
+
|
|
48
|
+
for index in range(self.trace_samples):
|
|
49
|
+
|
|
50
|
+
probe = 2.0 * torch.randint(0, 2, coeffs.shape, device=coeffs.device).to(coeffs) - 1.0
|
|
51
|
+
slope, = torch.autograd.grad(velocity, state, grad_outputs=probe,
|
|
52
|
+
create_graph=needs_graph,
|
|
53
|
+
retain_graph=index + 1 < self.trace_samples or needs_graph)
|
|
54
|
+
total = total + (probe * slope).sum(-1)
|
|
55
|
+
total = total / self.trace_samples
|
|
56
|
+
|
|
57
|
+
return (velocity, total) if needs_graph else (velocity.detach(), total.detach())
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def velocity_and_trace(self, coeffs, time_value, context=None):
|
|
61
|
+
"""Both at once. Subclasses that share work between them should override this."""
|
|
62
|
+
|
|
63
|
+
return self.velocity(coeffs, time_value, context), self.trace(coeffs, time_value, context)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
################################################################################################################
|
|
71
|
+
################################################################################################################
|
|
72
|
+
################################################################################################################
|
|
73
|
+
|
|
74
|
+
class TimeCosines(torch.nn.Module):
|
|
75
|
+
"""cosine_time_weights with the order vector held as a buffer instead of rebuilt per call. """
|
|
76
|
+
|
|
77
|
+
def __init__(self, num_time_modes, total_time, dtype, time_pair=False):
|
|
78
|
+
super().__init__()
|
|
79
|
+
self.total_time, self.time_pair = total_time, time_pair
|
|
80
|
+
self.register_buffer("orders", torch.arange(num_time_modes, dtype=dtype), persistent=False)
|
|
81
|
+
|
|
82
|
+
per_axis = int(num_time_modes ** 0.5 - 1e-9) + 1 # ceil, so per_axis^2 >= n
|
|
83
|
+
pairs = torch.cartesian_prod(torch.arange(per_axis, dtype=dtype),
|
|
84
|
+
torch.arange(per_axis, dtype=dtype))
|
|
85
|
+
|
|
86
|
+
chosen = pairs[torch.argsort(pairs.sum(1), stable=True)[:num_time_modes]]
|
|
87
|
+
|
|
88
|
+
self.register_buffer("end_orders", chosen[:, 0].contiguous(), persistent=False)
|
|
89
|
+
self.register_buffer("span_orders", chosen[:, 1].contiguous(), persistent=False)
|
|
90
|
+
|
|
91
|
+
self.cached = {}
|
|
92
|
+
|
|
93
|
+
def as_times(self, time_value):
|
|
94
|
+
"""-> a tensor, or a (start, end) tuple of tensors, on this module's device and dtype."""
|
|
95
|
+
|
|
96
|
+
def cast(value):
|
|
97
|
+
return torch.as_tensor(value, dtype=self.orders.dtype, device=self.orders.device)
|
|
98
|
+
|
|
99
|
+
if isinstance(time_value, tuple):
|
|
100
|
+
return cast(time_value[0]), cast(time_value[1])
|
|
101
|
+
|
|
102
|
+
return (cast(time_value), cast(time_value)) if self.time_pair else cast(time_value)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def weights(self, times):
|
|
106
|
+
if not self.time_pair:
|
|
107
|
+
return torch.cos(torch.pi * self.orders * (times.unsqueeze(-1) / self.total_time))
|
|
108
|
+
start_time, end_time = times
|
|
109
|
+
span = (end_time - start_time).unsqueeze(-1) / self.total_time
|
|
110
|
+
return (torch.cos(torch.pi * self.end_orders * (end_time.unsqueeze(-1) / self.total_time))
|
|
111
|
+
* torch.cos(torch.pi * self.span_orders * span))
|
|
112
|
+
|
|
113
|
+
def forward(self, time_value):
|
|
114
|
+
compiling = getattr(torch.compiler, "is_compiling", lambda: False)()
|
|
115
|
+
tensor_time = (torch.is_tensor(time_value)
|
|
116
|
+
or (isinstance(time_value, tuple) and torch.is_tensor(time_value[0])))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
if tensor_time or compiling:
|
|
120
|
+
return self.weights(self.as_times(time_value))
|
|
121
|
+
|
|
122
|
+
label = (time_value if isinstance(time_value, tuple) else (time_value,),
|
|
123
|
+
self.orders.device.type, self.orders.dtype)
|
|
124
|
+
|
|
125
|
+
if label not in self.cached:
|
|
126
|
+
if len(self.cached) > 512:
|
|
127
|
+
self.cached.clear()
|
|
128
|
+
self.cached[label] = self.weights(self.as_times(time_value))
|
|
129
|
+
|
|
130
|
+
return self.cached[label]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
################################################################################################################
|
|
136
|
+
################################################################################################################
|
|
137
|
+
################################################################################################################
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class LinearField(VectorField):
|
|
141
|
+
"""h(v,t,c) = gain_k(t) \odot v + s \odot W(t) c """
|
|
142
|
+
|
|
143
|
+
def __init__(self, num_functions, context_dim=None, num_time_modes=4, total_time=1.0, init_scale=0.0,
|
|
144
|
+
time_pair=False, dtype=torch.float64, mode_scale=None, rank=None, ):
|
|
145
|
+
super().__init__()
|
|
146
|
+
|
|
147
|
+
self.num_time_modes, self.total_time, self.dtype = num_time_modes, total_time, dtype
|
|
148
|
+
|
|
149
|
+
self.gain_stack = torch.nn.Parameter(
|
|
150
|
+
init_scale * torch.randn(num_time_modes, num_functions, dtype=dtype)
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
self.cosines = TimeCosines(num_time_modes, total_time, dtype, time_pair)
|
|
154
|
+
|
|
155
|
+
self.mode_scale, self.rank = mode_scale, rank
|
|
156
|
+
|
|
157
|
+
self.has_drift = bool(context_dim)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
if self.has_drift:
|
|
161
|
+
if rank:
|
|
162
|
+
self.left = torch.nn.Parameter(
|
|
163
|
+
init_scale / rank ** 0.5 * torch.randn(num_functions, rank, dtype=dtype))
|
|
164
|
+
self.right = torch.nn.Parameter(
|
|
165
|
+
init_scale / (context_dim * num_time_modes) ** 0.5
|
|
166
|
+
* torch.randn(num_time_modes, rank, context_dim, dtype=dtype))
|
|
167
|
+
else:
|
|
168
|
+
self.drift_stack = torch.nn.Parameter(
|
|
169
|
+
init_scale / (context_dim * num_time_modes) ** 0.5
|
|
170
|
+
* torch.randn(num_time_modes, num_functions, context_dim, dtype=dtype))
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _gains(self, time_value):
|
|
174
|
+
return self.cosines(time_value) @ self.gain_stack
|
|
175
|
+
|
|
176
|
+
def velocity(self, coeffs, time_value, context=None):
|
|
177
|
+
|
|
178
|
+
if self.has_drift:
|
|
179
|
+
if context is None:
|
|
180
|
+
return self._gains(time_value) * coeffs
|
|
181
|
+
|
|
182
|
+
weights = self.cosines(time_value)
|
|
183
|
+
|
|
184
|
+
if self.rank:
|
|
185
|
+
update = combine_context(self.right, context, weights) @ self.left.T
|
|
186
|
+
else:
|
|
187
|
+
update = combine_context(self.drift_stack, context, weights)
|
|
188
|
+
drift_update = update if self.mode_scale is None else update * self.mode_scale
|
|
189
|
+
|
|
190
|
+
return self._gains(time_value) * coeffs + drift_update
|
|
191
|
+
|
|
192
|
+
else:
|
|
193
|
+
|
|
194
|
+
return self._gains(time_value) * coeffs
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def trace(self, coeffs, time_value, context=None):
|
|
198
|
+
return self._gains(time_value).sum(-1).expand(coeffs.shape[:-1])
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def velocity_and_trace(self, coeffs, time_value, context=None):
|
|
202
|
+
|
|
203
|
+
gains = self._gains(time_value)
|
|
204
|
+
|
|
205
|
+
return self.velocity(coeffs, time_value, context=context), gains.sum(-1).expand(coeffs.shape[:-1])
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
################################################################################################################
|
|
213
|
+
################################################################################################################
|
|
214
|
+
################################################################################################################
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class MatrixField(VectorField):
|
|
218
|
+
"""Based off of arXiv:1803.05649 Sylvester flows
|
|
219
|
+
|
|
220
|
+
"""
|
|
221
|
+
|
|
222
|
+
supports_batched_time = False
|
|
223
|
+
|
|
224
|
+
def __init__(self, conditioner, activation="tanh", mode_scale=None, num_active=None):
|
|
225
|
+
super().__init__()
|
|
226
|
+
self.conditioner = conditioner
|
|
227
|
+
self.activation = activation
|
|
228
|
+
self.mode_scale = mode_scale
|
|
229
|
+
self.num_active = num_active or conditioner.num_functions
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _parts(self, coeffs, time_value, context=None):
|
|
234
|
+
|
|
235
|
+
output_matrix, input_matrix, biases = self.conditioner(time_value, context)
|
|
236
|
+
active = coeffs[..., :self.num_active]
|
|
237
|
+
|
|
238
|
+
if self.mode_scale is not None:
|
|
239
|
+
active = active / self.mode_scale[:self.num_active]
|
|
240
|
+
pre_activation = active @ input_matrix.T + biases
|
|
241
|
+
|
|
242
|
+
if self.activation == "identity":
|
|
243
|
+
return output_matrix, input_matrix, pre_activation, torch.ones_like(pre_activation)
|
|
244
|
+
hidden = torch.tanh(pre_activation)
|
|
245
|
+
|
|
246
|
+
return output_matrix, input_matrix, hidden, 1 - hidden ** 2
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _update(self, coeffs, output_matrix, hidden):
|
|
251
|
+
update = hidden @ output_matrix.T
|
|
252
|
+
if self.mode_scale is not None:
|
|
253
|
+
update = update * self.mode_scale[:self.num_active]
|
|
254
|
+
|
|
255
|
+
return torch.nn.functional.pad(update, (0, coeffs.shape[-1] - self.num_active))
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def velocity(self, coeffs, time_value, context=None):
|
|
259
|
+
output_matrix, _, hidden, _ = self._parts(coeffs, time_value, context)
|
|
260
|
+
|
|
261
|
+
return self._update(coeffs, output_matrix, hidden)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def trace(self, coeffs, time_value, context=None):
|
|
265
|
+
output_matrix, input_matrix, _, derivative = self._parts(coeffs, time_value, context)
|
|
266
|
+
|
|
267
|
+
return (derivative * (input_matrix * output_matrix.T).sum(1)).sum(-1)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def velocity_and_trace(self, coeffs, time_value, context=None):
|
|
271
|
+
output_matrix, input_matrix, hidden, derivative = self._parts(coeffs, time_value, context)
|
|
272
|
+
|
|
273
|
+
return (self._update(coeffs, output_matrix, hidden),
|
|
274
|
+
(derivative * (input_matrix * output_matrix.T).sum(1)).sum(-1))
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
################################################################################################################
|
|
282
|
+
################################################################################################################
|
|
283
|
+
################################################################################################################
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class SumField(VectorField):
|
|
287
|
+
"""h = sum of the given fields. Velocities add; traces add."""
|
|
288
|
+
|
|
289
|
+
def __init__(self, *fields):
|
|
290
|
+
super().__init__()
|
|
291
|
+
self.fields = torch.nn.ModuleList(fields)
|
|
292
|
+
|
|
293
|
+
@property
|
|
294
|
+
def supports_batched_time(self):
|
|
295
|
+
return all(field.supports_batched_time for field in self.fields)
|
|
296
|
+
|
|
297
|
+
def velocity(self, coeffs, time_value, context=None):
|
|
298
|
+
return sum(field.velocity(coeffs, time_value, context) for field in self.fields)
|
|
299
|
+
|
|
300
|
+
def trace(self, coeffs, time_value, context=None):
|
|
301
|
+
return sum(field.trace(coeffs, time_value, context) for field in self.fields)
|
|
302
|
+
|
|
303
|
+
def velocity_and_trace(self, coeffs, time_value, context=None):
|
|
304
|
+
parts = [field.velocity_and_trace(coeffs, time_value, context) for field in self.fields]
|
|
305
|
+
return sum(part[0] for part in parts), sum(part[1] for part in parts)
|
|
306
|
+
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
|
|
3
|
+
from ..abstract_transformation import Transformation
|
|
4
|
+
from .layer_classes import DiscreteLayer
|
|
5
|
+
from FuncFlows.base_measures import ReferenceMeasure
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class DiscreteTransformation(Transformation):
|
|
9
|
+
"""A stack of DiscreteLayers. Pass either a list of layers, or a layer class + count + its kwargs."""
|
|
10
|
+
|
|
11
|
+
def __init__(self, base_measure: ReferenceMeasure,
|
|
12
|
+
layers=None, layer_class: type[DiscreteLayer] = None,
|
|
13
|
+
num_layers: int = 1, **layer_kwargs):
|
|
14
|
+
super().__init__(base_measure)
|
|
15
|
+
if layers is None:
|
|
16
|
+
layers = [layer_class(base_measure, **layer_kwargs) for _ in range(num_layers)]
|
|
17
|
+
self.layers = torch.nn.ModuleList(layers)
|
|
18
|
+
|
|
19
|
+
def _map(self, coeffs, context=None):
|
|
20
|
+
log_det_term = torch.zeros_like(coeffs[..., 0]) # inherits device and dtype
|
|
21
|
+
for layer in self.layers:
|
|
22
|
+
coeffs, layer_log_det = layer._map(coeffs, context)
|
|
23
|
+
log_det_term = log_det_term + layer_log_det
|
|
24
|
+
return coeffs, log_det_term
|
|
25
|
+
|
|
26
|
+
def pull_back(self, coeffs_out, context=None):
|
|
27
|
+
for layer in reversed(self.layers):
|
|
28
|
+
coeffs_out = layer.pull_back(coeffs_out, context)
|
|
29
|
+
return coeffs_out
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import math
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
|
|
5
|
+
from ..abstract_transformation import Transformation
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class DiscreteLayer(Transformation):
|
|
9
|
+
"""One invertible layer acting on the leading num_modes coefficients; the tail passes through."""
|
|
10
|
+
|
|
11
|
+
def __init__(self, base_measure, num_modes):
|
|
12
|
+
super().__init__(base_measure)
|
|
13
|
+
if num_modes > base_measure.num_functions:
|
|
14
|
+
raise ValueError(f"num_modes {num_modes} exceeds the measure's {base_measure.num_functions}")
|
|
15
|
+
self.num_modes = num_modes
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class HouseholderLayer(DiscreteLayer):
|
|
19
|
+
"""f(u) = u - 0.5 v (v.u + b), unit v. P1 §2.3.1; Jacobian I - 0.5 v v^T has det 0.5 exactly."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, base_measure, num_modes):
|
|
22
|
+
super().__init__(base_measure, num_modes)
|
|
23
|
+
self.direction_raw = torch.nn.Parameter(0.1 * torch.randn(num_modes, dtype=base_measure.dtype))
|
|
24
|
+
self.bias = torch.nn.Parameter(torch.zeros(1, dtype=base_measure.dtype))
|
|
25
|
+
|
|
26
|
+
def _map(self, coeffs, context=None):
|
|
27
|
+
direction = self.direction_raw / self.direction_raw.norm() # P1 Thm 2.4 normalisation
|
|
28
|
+
head = coeffs[..., :self.num_modes]
|
|
29
|
+
head = head - 0.5 * direction * (head @ direction + self.bias)[..., None]
|
|
30
|
+
coeffs_out = torch.cat([head, coeffs[..., self.num_modes:]], dim=-1)
|
|
31
|
+
log_det = torch.full_like(coeffs[..., 0], math.log(0.5)) # inherits device
|
|
32
|
+
return coeffs_out, log_det
|
|
33
|
+
|
|
34
|
+
def pull_back(self, coeffs_out, context=None):
|
|
35
|
+
direction = self.direction_raw / self.direction_raw.norm()
|
|
36
|
+
head = coeffs_out[..., :self.num_modes]
|
|
37
|
+
head = head + direction * (head @ direction + self.bias)[..., None]
|
|
38
|
+
return torch.cat([head, coeffs_out[..., self.num_modes:]], dim=-1)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SylvesterLayer(DiscreteLayer):
|
|
42
|
+
"""f(u) = u + A tanh(B u + b) with A, B upper-triangular (P1 §2.3.2, van den Berg et al. 2018).
|
|
43
|
+
|
|
44
|
+
diag(B) = 1 and diag(A) = tanh(.) in (-1, 1), so by Sylvester's identity
|
|
45
|
+
log|det Df| = sum_j log(1 + (1 - h_j^2) diag(A)_j) is exact and O(num_modes).
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, base_measure, num_modes, init_scale=0.1):
|
|
49
|
+
super().__init__(base_measure, num_modes)
|
|
50
|
+
dtype = base_measure.dtype
|
|
51
|
+
self.upper_before = torch.nn.Parameter(init_scale * torch.randn(num_modes, num_modes, dtype=dtype)) # R_B
|
|
52
|
+
self.upper_after = torch.nn.Parameter(init_scale * torch.randn(num_modes, num_modes, dtype=dtype)) # R_A
|
|
53
|
+
self.diag_after_raw = torch.nn.Parameter(init_scale * torch.randn(num_modes, dtype=dtype))
|
|
54
|
+
self.bias = torch.nn.Parameter(torch.zeros(num_modes, dtype=dtype))
|
|
55
|
+
self.register_buffer("identity", torch.eye(num_modes, dtype=dtype)) # a buffer, so .to() moves it
|
|
56
|
+
|
|
57
|
+
def matrices(self):
|
|
58
|
+
before = torch.triu(self.upper_before, diagonal=1) + self.identity # unit diagonal
|
|
59
|
+
diag_after = torch.tanh(self.diag_after_raw)
|
|
60
|
+
after = torch.triu(self.upper_after, diagonal=1) + torch.diag(diag_after)
|
|
61
|
+
return before, after, diag_after
|
|
62
|
+
|
|
63
|
+
def _map(self, coeffs, context=None):
|
|
64
|
+
before, after, diag_after = self.matrices()
|
|
65
|
+
head, tail = coeffs[..., :self.num_modes], coeffs[..., self.num_modes:]
|
|
66
|
+
hidden = torch.tanh(head @ before.T + self.bias)
|
|
67
|
+
head = head + hidden @ after.T
|
|
68
|
+
log_det = torch.log1p((1 - hidden ** 2) * diag_after).sum(-1)
|
|
69
|
+
return torch.cat([head, tail], dim=-1), log_det
|
|
70
|
+
|
|
71
|
+
def pull_back(self, coeffs_out, context=None, num_iterations=30):
|
|
72
|
+
"""Fixed-point inverse. Converges when the layer is a contraction, which the small
|
|
73
|
+
init_scale and |diag(A)| < 1 encourage but do not guarantee. No residual check inside
|
|
74
|
+
the loop: on a GPU that would be a sync per iteration. Check once outside if in doubt:
|
|
75
|
+
(layer._map(layer.pull_back(x))[0] - x).abs().max()."""
|
|
76
|
+
before, after, _ = self.matrices()
|
|
77
|
+
head_out, tail = coeffs_out[..., :self.num_modes], coeffs_out[..., self.num_modes:]
|
|
78
|
+
head = head_out
|
|
79
|
+
for _ in range(num_iterations):
|
|
80
|
+
head = head_out - torch.tanh(head @ before.T + self.bias) @ after.T
|
|
81
|
+
return torch.cat([head, tail], dim=-1)
|
|
File without changes
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
|
|
2
|
+
# This is here just as an example
|
|
3
|
+
# it's just a gaussian likelihood but the coefficients are part of the call
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class GaussianMisfit:
|
|
7
|
+
"""Phi(coeffs) = ½ ||data - forward_map(coeffs)||² / noise_std².
|
|
8
|
+
|
|
9
|
+
forward_map: coeffs [..., r] -> [..., num_data].
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
def __init__(self, forward_map, data, noise_std):
|
|
13
|
+
self.forward_map, self.data, self.noise_std = forward_map, data, noise_std
|
|
14
|
+
|
|
15
|
+
def __call__(self, coeffs, extra_variance=0.0):
|
|
16
|
+
return 0.5 * ((self.data - self.forward_map(coeffs)) ** 2).sum(-1) / (self.noise_std ** 2 + extra_variance)
|
FuncFlows/utils/train.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from tqdm import trange
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def train(objective, parameters, num_steps=5000, learning_rate=0.01, decay=0.8, decay_every=500,
|
|
6
|
+
sync_every=50):
|
|
7
|
+
"""The standard loop: objective() returns the loss, parameters are whatever it should move.
|
|
8
|
+
|
|
9
|
+
parameters is materialised with list() because model.parameters() is a generator: reusing
|
|
10
|
+
one across two train() calls used to hand Adam an empty list on the second call.
|
|
11
|
+
Losses are read back every sync_every steps in one transfer; loss.item() on every step
|
|
12
|
+
is a device sync per step, which on a GPU/MPS stalls the whole pipeline.
|
|
13
|
+
"""
|
|
14
|
+
parameters = list(parameters)
|
|
15
|
+
optimiser = torch.optim.Adam(parameters, lr=learning_rate)
|
|
16
|
+
scheduler = torch.optim.lr_scheduler.StepLR(optimiser, decay_every, decay)
|
|
17
|
+
|
|
18
|
+
losses, pending = [], []
|
|
19
|
+
for _ in trange(num_steps, desc="Training"):
|
|
20
|
+
optimiser.zero_grad()
|
|
21
|
+
loss = objective()
|
|
22
|
+
loss.backward()
|
|
23
|
+
optimiser.step()
|
|
24
|
+
scheduler.step()
|
|
25
|
+
pending.append(loss.detach())
|
|
26
|
+
if len(pending) == sync_every:
|
|
27
|
+
losses += torch.stack(pending).tolist()
|
|
28
|
+
pending = []
|
|
29
|
+
if pending:
|
|
30
|
+
losses += torch.stack(pending).tolist()
|
|
31
|
+
return losses
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: funcflows
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: Normalizing flows and flow matching on function spaces, with exact-trace vector fields
|
|
5
|
+
Author: Liam Pinchbeck
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/YOUR_USER/FuncFlows
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: torch
|
|
17
|
+
Requires-Dist: torchvision
|
|
18
|
+
Requires-Dist: tqdm
|
|
19
|
+
Requires-Dist: scipy
|
|
20
|
+
Requires-Dist: matplotlib
|
|
21
|
+
Provides-Extra: ot
|
|
22
|
+
Requires-Dist: scipy; extra == "ot"
|
|
23
|
+
Provides-Extra: test
|
|
24
|
+
Requires-Dist: pytest; extra == "test"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# FuncFlows
|
|
28
|
+
|
|
29
|
+
Normalizing flows and flow matching on function spaces. Functions are represented by
|
|
30
|
+
coefficients on a Laplacian eigenbasis (cosine or Fourier), the reference measure is a Gaussian
|
|
31
|
+
on those coefficients, and transports are neural ODEs whose vector fields (`LinearField`,
|
|
32
|
+
`MatrixField`, `PointwiseField`) all have closed-form divergences, so densities relative to the
|
|
33
|
+
reference measure are exact.
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install funcflows
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Objectives: flow matching (conditional / amortised), reverse KL, alpha-divergences, negative
|
|
40
|
+
log-likelihood. Samplers and diagnostics: latent-space pCN, importance correction, TARP coverage.
|
|
41
|
+
|
|
42
|
+
`torch` is a hard dependency and is large; install it first from pytorch.org if you need a
|
|
43
|
+
specific CUDA/MPS build.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
FuncFlows/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
FuncFlows/base_measures/__init__.py,sha256=MNpfvHZo9zM1UB4PKWseAHo9Dd_VokwxNxgY1glgyfQ,173
|
|
3
|
+
FuncFlows/base_measures/abstract_reference_measure.py,sha256=6CZnVtzA9W6y4YHKIXIKHzYG8WIHv7JAEmQIzU7RkfU,1033
|
|
4
|
+
FuncFlows/base_measures/bases.py,sha256=mRUeWnaa6teIRhgEnzwKj_txsQo3hCRxhDzvjxmEF0w,6302
|
|
5
|
+
FuncFlows/base_measures/gaussian_reference_measure.py,sha256=OLv908JPr38etrQ6VhvKhgOnL-DOEzgJ5a9x09Jpwq0,1792
|
|
6
|
+
FuncFlows/diagnostics/__init__.py,sha256=E7vdcr_nUgyHvV3eifOhW7-w9by4Bcw_P7_BIOutR8Y,98
|
|
7
|
+
FuncFlows/diagnostics/coverage.py,sha256=Llx46y0BglCP_dOfuOH_eNHVp37KtBYvBaRRKc_pfig,2541
|
|
8
|
+
FuncFlows/diagnostics/importance.py,sha256=X0AlezvmopR5JEJi_6x6W9lSyda1AcjSuq22eBoM5E4,2708
|
|
9
|
+
FuncFlows/objectives/__init__.py,sha256=UpYH2M7HUFcpbtaEJfVrb76svRousxl4hB9eqwlMxQo,286
|
|
10
|
+
FuncFlows/objectives/alpha_divergence.py,sha256=_iwwPUoyovy3d4dl5Bcndu70TDR7lJTuFG3kC01MkY0,3822
|
|
11
|
+
FuncFlows/objectives/flow_matching.py,sha256=DuTNDdjZ13o156H9aQORV-1qjrCpgrcrWWs0R8Qu3zM,7313
|
|
12
|
+
FuncFlows/objectives/negative_logl.py,sha256=QWHIOMp1uBZxFgBn-Wh8SRUD6tlY5Wh1H15rR470Qpg,758
|
|
13
|
+
FuncFlows/objectives/reverse_kl.py,sha256=ZXlVxWgwh5uJ7xjuLv1iYu1oSQXppiwFsD7O3Wl4ONw,2690
|
|
14
|
+
FuncFlows/samplers/__init__.py,sha256=D9V3yCl_qqmsYjhVeEUpk6SJZMK3uMUx13sJ8Fo6uHI,35
|
|
15
|
+
FuncFlows/samplers/latent_pcn.py,sha256=os6PcqMeC64yMb86PDTpSi8Tec4jDBAgzYuT2dR4Jgc,2907
|
|
16
|
+
FuncFlows/transports/__init__.py,sha256=R6In-pSfeB6IVV-e_RbdqLrQ_6Ex8dJCsZKc2d-2JN4,144
|
|
17
|
+
FuncFlows/transports/abstract_transformation.py,sha256=56b7NDhulD7xC4f0HKHnUq6anHAMtK6N7bKDiyF_ohY,1331
|
|
18
|
+
FuncFlows/transports/continuous/__init__.py,sha256=gcCzACXLajQrcV8wdZ766jm-2nw84Bzlv-r-66SUzAc,349
|
|
19
|
+
FuncFlows/transports/continuous/base_continuous.py,sha256=CFTkVdvDmayzCcqLreaMRLpMDDu6AYGYJr2STNWotwk,3339
|
|
20
|
+
FuncFlows/transports/continuous/conditioners.py,sha256=VXj2ZigjV3TzjfzlcNH08Yoken1JrwVCfG2Mq_jf67Y,3449
|
|
21
|
+
FuncFlows/transports/continuous/grid_fields.py,sha256=4pVDMgK79NKtrLQbOZzAHaUbmDT7fLu7JzdR82OtaTA,18876
|
|
22
|
+
FuncFlows/transports/continuous/vector_fields.py,sha256=i4WwubIOFX84Jp2epmS5FIjUgZI0eFFIJ6xGwSKxkxc,12180
|
|
23
|
+
FuncFlows/transports/layers/__init__.py,sha256=PMgHayKpTCIgG_1uOYPW5wqGnREiPShBYBNE0vbXTw0,125
|
|
24
|
+
FuncFlows/transports/layers/base_discrete.py,sha256=RqDSup0lnOm01qSzUQlkP9-z348J04X1irvtN-kzIYM,1216
|
|
25
|
+
FuncFlows/transports/layers/layer_classes.py,sha256=qoed6aVZh1AUN_kZz0p9t8TsH02UpfF_HwVF-ykaYI8,4144
|
|
26
|
+
FuncFlows/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
27
|
+
FuncFlows/utils/gaussian_misfit.py,sha256=Q4znj86c62DmxQcmZP1pNp1Pm7xcb-Nd1-Xg3E3meSc,579
|
|
28
|
+
FuncFlows/utils/train.py,sha256=HfoxFW-Sjs8ppc0oO8xg8gX7gnHbX1VVo0k7hwaAz_4,1236
|
|
29
|
+
funcflows-0.1.2.dist-info/licenses/LICENSE,sha256=0SJU1dVe5uk0rKC9g3BKPevyAWTYQxcqVtDVW9ORk5Y,1065
|
|
30
|
+
funcflows-0.1.2.dist-info/METADATA,sha256=f1U_LTAnuouWSjGU-jNfhhUbWW_1HMpN5WU-hQJq-uE,1577
|
|
31
|
+
funcflows-0.1.2.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
32
|
+
funcflows-0.1.2.dist-info/top_level.txt,sha256=3aOZIxxmKc6v_UD7mIKrW-60jGIFU4s9Ro7XWmgfaik,10
|
|
33
|
+
funcflows-0.1.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Your Name
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
FuncFlows
|