Skip to content

Commit 9593b1d

Browse files
Merge pull request #1102 from thc1006/bug/custom-sampler-seed-groups
BUG: give each CustomSampler its own stream instead of the model's seed Every CustomSampler on a model was reset with the model's own seed, so two samplers backed by default_rng started from the same state and drew the same underlying deviate. Each input now gets a stream keyed by its name, and samplers that share one generator declare a seed_group so the group is seeded once between them. Merged manually rather than through the button: the CHANGELOG conflicted with #1103, and the resolution keeps both entries. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2 parents 6224be7 + 6487992 commit 9593b1d

5 files changed

Lines changed: 469 additions & 18 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ Attention: The newest changes should be on top -->
4343

4444
### Fixed
4545

46+
- BUG: Give each `CustomSampler` input its own deterministic stream, and seed samplers sharing one generator once as a group. Existing fixed-seed `CustomSampler` baselines change, and samplers built on the legacy `RandomState` must move to `default_rng` because seeds now carry the full 128 bits. [#1102](https://github.com/RocketPy-Team/RocketPy/pull/1102)
4647
- BUG: Accept the callable parachute triggers `StochasticParachute` documents, and reject the ones it cannot mean. An invalid string, an empty list or a boolean now fails during validation instead of reaching `Parachute` or becoming a one-metre height trigger. [#1103](https://github.com/RocketPy-Team/RocketPy/pull/1103)
4748
- BUG: rocket with a late-starting thrust curve never leaves the rail [#1085](https://github.com/RocketPy-Team/RocketPy/pull/1085)
4849

‎docs/user/custom_sampler.rst‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -243,14 +243,16 @@ below implements an example of such a generator
243243
"""Reseeds the generator and discards the samples drawn before it
244244

245245
The cached samples came from the previous generator, so keeping them
246-
would let the first 1000 draws after a reseed ignore the new seed.
246+
would let the first draws after a reseed ignore the new seed. Nothing
247+
is generated here: ``top_up`` fills the shortfall when samples are
248+
first asked for, and a reseed happens once per simulation, so filling
249+
eagerly would build a thousand pairs to use one.
247250
"""
248251
self.rng = np.random.default_rng(seed)
249252
self.samples_list = []
250253
self.samples_generated = 0
251254
self.used_samples_x = 0
252255
self.used_samples_y = 0
253-
self.generate_samples(1000)
254256

255257
def top_up(self, used_samples, n_samples):
256258
"""Generates enough samples to cover the request, if it is short"""
@@ -300,6 +302,16 @@ sample list.
300302
def __init__(self, bivariate_gaussian_generator):
301303
self.generator = bivariate_gaussian_generator
302304

305+
@property
306+
def seed_group(self):
307+
"""The generator this shares with the other wrapper.
308+
309+
Both return the same object, so the pair is seeded once between
310+
them. Without this each would be seeded separately and one would
311+
silently overwrite the other.
312+
"""
313+
return self.generator
314+
303315
def sample(self, n_samples=1):
304316
samples_list = self.generator.get_samples(n_samples, "x")
305317
return samples_list
@@ -313,6 +325,16 @@ sample list.
313325
def __init__(self, bivariate_gaussian_generator):
314326
self.generator = bivariate_gaussian_generator
315327

328+
@property
329+
def seed_group(self):
330+
"""The generator this shares with the other wrapper.
331+
332+
Both return the same object, so the pair is seeded once between
333+
them. Without this each would be seeded separately and one would
334+
silently overwrite the other.
335+
"""
336+
return self.generator
337+
316338
def sample(self, n_samples=1):
317339
samples_list = self.generator.get_samples(n_samples, "y")
318340
return samples_list

‎rocketpy/stochastic/custom_sampler.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,32 @@
88
class CustomSampler(ABC):
99
"""Abstract subclass for user defined samplers"""
1010

11+
@property
12+
def seed_group(self):
13+
"""The generator state this sampler shares, if it shares one.
14+
15+
Samplers are independent by default and each is seeded on its own. Two
16+
wrappers over one generator, as the correlated wind pair in the
17+
documentation are, should both return that generator here, so the pair
18+
is seeded once as a unit rather than one of them silently overwriting
19+
the other's seed.
20+
21+
Return the same object on every call. Building the answer each time,
22+
which a property invites, gives each member a different identity and
23+
puts it back in a group of its own.
24+
25+
A group belongs to one model. Declaring the same generator on two
26+
models has them both seed it, and whichever is seeded last decides the
27+
stream, which is the overwrite this is here to avoid.
28+
29+
Returns
30+
-------
31+
object
32+
Identity is what counts, not equality. ``self`` by default, which
33+
makes every sampler its own group.
34+
"""
35+
return self
36+
1137
@abstractmethod
1238
def sample(self, n_samples=1):
1339
"""Generates samples from the custom distribution

‎rocketpy/stochastic/stochastic_model.py‎

Lines changed: 91 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,44 @@
1212

1313
from ..tools import get_distribution
1414

15+
16+
def _names_as_spawn_key(input_names):
17+
"""Encode names into spawn-key words that no other set of names produces.
18+
19+
A hash would be shorter, but a collision puts two samplers back on one
20+
stream, which is the bug this keying exists to prevent. The length prefix
21+
before each name is what makes it injective.
22+
"""
23+
payload = b""
24+
for name in input_names:
25+
encoded = name.encode("utf-8")
26+
payload += len(encoded).to_bytes(4, "little") + encoded
27+
payload += b"\0" * (-len(payload) % 4)
28+
return tuple(
29+
int.from_bytes(payload[at : at + 4], "little")
30+
for at in range(0, len(payload), 4)
31+
)
32+
33+
34+
def _sampler_seed(seed, input_names):
35+
"""Derive a seed for one sampler, or for one group that shares a generator.
36+
37+
Keyed by the names rather than by position, so declaring another parameter
38+
does not move the stream of the ones already there. A group is keyed by all
39+
of its members, so its stream does not depend on which of them happens to
40+
be reset last.
41+
"""
42+
if isinstance(input_names, str):
43+
input_names = (input_names,)
44+
# Sorted here rather than trusting the caller, so a future call site cannot
45+
# give one group two different seeds by listing its members another way.
46+
root = np.random.SeedSequence(
47+
entropy=seed, spawn_key=_names_as_spawn_key(tuple(sorted(input_names)))
48+
)
49+
words = root.generate_state(4, dtype=np.uint32)
50+
return sum(int(word) << (32 * position) for position, word in enumerate(words))
51+
52+
1553
# TODO: Stop using assert in production code. Use exceptions instead.
1654
# TODO: Each validation method should have a test case.
1755

@@ -82,16 +120,16 @@ def _set_stochastic(self, seed=None):
82120
self.__random_number_generator = np.random.default_rng(seed)
83121
self.last_rnd_dict = {}
84122

123+
self._reset_custom_samplers(seed)
124+
85125
# TODO: This code block is too complex. Refactor it.
86126
# TODO: Resetting a instance should not require re-validation.
87127
for input_name, input_value in self.__stochastic_dict.items():
88128
if input_name not in self.exception_list:
89129
attr_value = None
90130
if input_value is not None:
91131
if "factor" in input_name:
92-
attr_value = self._validate_factors(
93-
input_name, input_value, seed
94-
)
132+
attr_value = self._validate_factors(input_name, input_value)
95133
elif input_name not in self.exception_list:
96134
if isinstance(input_value, tuple):
97135
attr_value = self._validate_tuple(input_name, input_value)
@@ -101,7 +139,7 @@ def _set_stochastic(self, seed=None):
101139
attr_value = self._validate_scalar(input_name, input_value)
102140
elif isinstance(input_value, CustomSampler):
103141
attr_value = self._validate_custom_sampler(
104-
input_name, input_value, seed
142+
input_name, input_value
105143
)
106144
else:
107145
raise AssertionError(
@@ -288,7 +326,7 @@ def _validate_scalar(self, input_name, input_value, getattr=getattr): # pylint:
288326
get_distribution("normal", self.__random_number_generator),
289327
)
290328

291-
def _validate_factors(self, input_name, input_value, seed):
329+
def _validate_factors(self, input_name, input_value):
292330
"""
293331
Validate factor arguments.
294332
@@ -317,7 +355,7 @@ def _validate_factors(self, input_name, input_value, seed):
317355
elif isinstance(input_value, list):
318356
return self._validate_list_factor(input_name, input_value)
319357
elif isinstance(input_value, CustomSampler):
320-
return self._validate_custom_sampler(input_name, input_value, seed)
358+
return self._validate_custom_sampler(input_name, input_value)
321359
else:
322360
raise AssertionError(
323361
f"`{input_name}`: must be either a tuple or listor a custom sampler"
@@ -448,31 +486,68 @@ def _validate_positive_int_list(self, input_name, input_value):
448486
isinstance(member, int) and member >= 0 for member in input_value
449487
), f"`{input_name}` must be a list of positive integers"
450488

451-
def _validate_custom_sampler(self, input_name, sampler, seed=None):
489+
def _reset_custom_samplers(self, seed):
490+
"""Give each sampler its own stream, and each shared group one between
491+
them.
492+
493+
Samplers that share a generator, as the documented wind pair do, are
494+
seeded once as a unit. Resetting each member in turn would leave every
495+
seed but the last discarded and the group's stream decided by whichever
496+
member happened to go last.
497+
498+
Its own pass rather than the validation loop below, whose order sets
499+
``__dict__`` and so the order every other input is drawn in.
500+
"""
501+
groups = {}
502+
for input_name in sorted(self.__stochastic_dict):
503+
sampler = self.__stochastic_dict[input_name]
504+
if isinstance(sampler, CustomSampler):
505+
# Held in the value as well as keyed on, because `id` is
506+
# unique only among live objects. Defensive: a `seed_group`
507+
# that builds its answer did not merge in practice here.
508+
group = sampler.seed_group
509+
shared = groups.setdefault(id(group), ([], sampler, group))
510+
shared[0].append(input_name)
511+
512+
for names, sampler, group in groups.values():
513+
# The group itself when it can be reset, since it is the thing that
514+
# holds the shared state. Going through one member instead assumes
515+
# every member resets the same way and keeps nothing of its own.
516+
resetter = group if hasattr(group, "reset_seed") else sampler
517+
try:
518+
resetter.reset_seed(_sampler_seed(seed, names))
519+
except Exception as error:
520+
# Not just RuntimeError. The seed handed over is now 128 bits,
521+
# which the legacy RandomState refuses with a ValueError, and a
522+
# bare one of those does not say which sampler raised it.
523+
raise RuntimeError(
524+
f"An error occurred in the 'reset_seed' method of the "
525+
f"CustomSampler for {', '.join(names)}"
526+
) from error
527+
528+
def _validate_custom_sampler(self, input_name, sampler):
452529
"""
453530
Validate a custom sampler.
454531
532+
Seeding is not done here. It happens in ``_reset_custom_samplers``,
533+
which runs in a fixed order because two samplers can share one
534+
generator and whichever is reset last decides the stream.
535+
455536
Parameters
456537
----------
457538
input_name : str
458539
Name of the input argument.
459540
sampler : CustomSampler object
460541
Custom sampler provided by the user
461-
seed : int, optional
462-
Seed for the random number generator. The default is None
463542
464543
Raises
465544
------
466545
AssertionError
467546
If the input is not in a valid format.
468547
"""
469-
try:
470-
sampler.reset_seed(seed)
471-
except RuntimeError as e:
472-
raise RuntimeError(
473-
f"An error occurred in the 'reset_seed' method of {input_name} CustomSampler"
474-
) from e
475-
548+
assert isinstance(sampler, CustomSampler), (
549+
f"`{input_name}` must be a CustomSampler, not {type(sampler).__name__}"
550+
)
476551
return sampler
477552

478553
def _validate_airfoil(self, airfoil):

0 commit comments

Comments
 (0)