33 """Control the smaller Dreamer-style implementation for vector observations.
35 :param world: Recurrent state-space model layout.
36 :param replay_capacity: Real transition capacity of the ring buffer.
37 :param batch_size: Number of measured sequence windows per model update.
38 :param sequence_length: Number of real transitions per window.
39 :param learning_starts: Minimum cumulative interaction count before learning.
40 :param train_every: Run one joint update per this many environment steps.
41 :param imagination_batch_size: Number of independent states and skills per imagined batch.
42 :param imagination_horizon: Number of model transitions per imagined trajectory.
43 :param critic_hidden_sizes: Widths of the reward and successor-feature value networks.
44 :param world_learning_rate: Adam rate of the recurrent model and its heads.
45 :param actor_learning_rate: Adam rate of the squashed Gaussian policy.
46 :param critic_learning_rate: Adam rate of the reward and successor-feature critics.
47 :param multiplier_learning_rate: Adam rate of the skill constraint multiplier.
48 :param gamma: Discount for imagined rewards and features.
49 :param return_lambda: Mixing parameter for imagined lambda returns.
50 :param tau: Polyak averaging rate of the value targets.
51 :param delta: Skill constraint radius in normalized coordinates.
52 :param huber_scale: Smoothing scale of the actor's skill penalty.
53 :param lambda_scale: Multiplier of the smoothed skill distance.
54 :param entropy_scale: Fixed weight of the normalized action entropy.
55 :param free_nats: Floor below which the latent KL receives no gradient.
56 :param gradient_clip: Maximum optimizer gradient norm.
60 replay_capacity: int = 100_000
62 sequence_length: int = 16
63 learning_starts: int = 256
65 imagination_batch_size: int = 32
66 imagination_horizon: int = 12
67 critic_hidden_sizes: tuple[int, ...] = (128, 128)
68 world_learning_rate: float = 3e-4
69 actor_learning_rate: float = 3e-4
70 critic_learning_rate: float = 3e-4
71 multiplier_learning_rate: float = 3e-4
73 return_lambda: float = .95
76 huber_scale: float = .001
77 lambda_scale: float = 1.
78 entropy_scale: float = .003
80 gradient_clip: float = 100.
82 def __post_init__(self):
83 if not isinstance(self.
world, QDACMBWorldConfig):
84 raise TypeError(
"world must be a QDACMBWorldConfig.")
85 for name
in (
"replay_capacity",
"batch_size",
"sequence_length",
"train_every",
86 "imagination_batch_size",
"imagination_horizon"):
87 object.__setattr__(self, name, _integer(getattr(self, name), name))
88 object.__setattr__(self,
"learning_starts", _integer(self.
learning_starts,
"learning_starts", 0))
91 raise ValueError(
"sequence_length cannot exceed replay_capacity.")
93 raise ValueError(
"Use gamma in [0, 1), return_lambda in [0, 1], and tau in (0, 1].")
94 limits = np.finfo(np.float32)
95 for name
in (
"world_learning_rate",
"actor_learning_rate",
"critic_learning_rate",
"multiplier_learning_rate",
96 "delta",
"huber_scale",
"lambda_scale",
"gradient_clip"):
97 if not limits.tiny <= getattr(self, name) <= limits.max:
98 raise ValueError(f
"{name} must be positive and representable as a normal float32.")
99 for name
in (
"free_nats",
"entropy_scale"):
100 if not 0 <= getattr(self, name) <= limits.max:
101 raise ValueError(f
"{name} must be nonnegative and representable in float32.")
153 """Hold the policy weights, physical skill bounds, and observation and action layouts.
155 The actor uses a recurrent session because the current latent state
156 depends on previous actions. Its saved representation contains the
157 latent model and squashed Gaussian actor weights.
159 :param observation_space: Gymnasium Box containing the raw numeric observation.
160 :param action_space: Finite floating-point Gymnasium Box.
161 :param skill_bounds: Physical bounds for the desired behaviour coordinates.
162 :param policy: Optional PolicyConfig for the latent-space actor.
163 :param world: Optional QDACMBWorldConfig for recurrent inference.
164 :param seed: Initialization seed and default seed for new sessions.
165 :param device: Torch CPU or CUDA device.
168 _kind =
"qdac-mb-recurrent"
170 def __init__(self, observation_space, action_space, skill_bounds, *, policy=None, world=None,
171 seed=0, device="cpu"):
173 if not isinstance(world, QDACMBWorldConfig):
174 raise TypeError(
"world must be a QDACMBWorldConfig.")
175 self.
_initialize(_observation_shape(observation_space), _BoxLayout.from_space(action_space),
177 world, _integer(seed,
"seed", 0), device)
179 def _initialize(self, shape, actions, domain, policy, world, seed, device):
182 rssm_rng, actor_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
183 self.
_actor = SACPolicy._from_layout((world.state_size + len(domain.bounds),), actions, policy,
184 _seed(actor_rng), device, stochastic=
False)
185 self.
_rssm =
_RSSM(prod(shape), prod(actions.shape), world, _seed(rssm_rng), self.
device)
189 """Return immutable physical skill intervals."""
194 """Return the policy's Torch device."""
197 def _observation(self, observation):
198 return _flatten_observation(observation, self.
_obs_shape)
200 def _parameters(self):
201 return (*self.
_rssm.parameters(), *self.
_actor._trainable_parameters())
207 """Return an inference session for a freshly reset environment."""
208 seed = self.
_episode_seed if seed
is None else _integer(seed,
"seed", 0)
209 generator = torch.Generator(device=self.
device).manual_seed(seed)
214 """Export the policy independently of the trainer and simulator."""
217 weights = nn.utils.parameters_to_vector(self.
_parameters()).detach().cpu().numpy()
218 _save_actor(path, metadata, weights)
222 def load(cls, path, *, device="cpu", seed=0):
223 """Restore the actor and latent dynamics with a default seed for new sessions."""
224 metadata, weights, shape, actions, config = _load_actor_layout(path, cls.
_kind)
225 policy = cls.__new__(cls)
226 policy._initialize(shape, actions,
_DescriptorDomain(metadata[
"skill_bounds"]), config,
228 parameters = policy._parameters()
229 values = np.array(weights, dtype=np.float32, copy=
True)
230 if values.shape != (sum(parameter.numel()
for parameter
in parameters),)
or not np.isfinite(values).all():
231 raise ValueError(
"The recurrent policy contains invalid parameters.")
232 with torch.no_grad():
233 nn.utils.vector_to_parameters(policy._actor._tensor(values), parameters)
250 """Fit real dynamics, then optimize skills on trajectories through the frozen model."""
252 def __init__(self, policy, config, seed, counts, sample_skill):
254 self.
_world_rng, self.
_prior_rng, init = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
255 self.
_torch_rng = torch.Generator(device=policy.device).manual_seed(_seed(init))
256 obs_size, action_size = prod(policy._obs_shape), prod(policy._actions.shape)
257 goal_size = len(policy.skill_bounds)
259 self.
world =
_WorldModel(policy._rssm, obs_size, action_size, goal_size, _seed(init), policy.device)
260 inputs = config.world.state_size + goal_size
262 self.
reward = _scalar_head(inputs, widths, init, policy.device)
263 self.
successor = _mlp(inputs, goal_size, widths, _seed(init), policy.device, nn.SiLU)
264 self.
multiplier = _mlp(inputs, 1, widths, _seed(init), policy.device, nn.SiLU)
267 self.
_world_opt = torch.optim.Adam(self.
world.parameters(), lr=config.world_learning_rate)
268 self.
_actor_opt = torch.optim.Adam(policy._actor._trainable_parameters(), lr=config.actor_learning_rate)
269 self.
_value_opt = torch.optim.Adam(self.
reward.parameters(), lr=config.critic_learning_rate)
273 def ready(self, steps):
275 return steps >= config.learning_starts
and steps % config.train_every == 0
and (
276 self.
replay.size >= config.sequence_length)
278 def record(self, observation, action, reward, successor, terminated, feature, first):
279 self.
replay.add(observation, self.
policy._actor._encode(action), reward, successor, terminated,
280 feature=feature, start=first)
282 def _step(self, name, optimizer, loss):
283 if not torch.isfinite(loss):
284 raise ValueError(f
"QDAC-MB produced nonfinite {name} loss.")
285 optimizer.zero_grad(set_to_none=
True)
287 parameters = [parameter
for group
in optimizer.param_groups
for parameter
in group[
"params"]]
288 nn.utils.clip_grad_norm_(parameters, self.
config.gradient_clip, error_if_nonfinite=
True)
290 self.
counts[name +
"_updates"] += 1
291 self.
counts[
"optimizer_steps"] += 1
293 def _imagine(self, recurrent, latent, skill):
295 states, actions, densities = [], [], []
296 for _
in range(config.imagination_horizon):
297 state = rssm.flatten(recurrent, latent)
298 action, log_prob = actor._sample_actions(torch.cat((state, skill), -1), self.
_torch_rng)
300 actions.append(action)
301 densities.append(log_prob)
302 recurrent = rssm.transition(recurrent, latent, action)
303 latent = rssm.draw(rssm.prior_probs(recurrent), self.
_torch_rng)
304 trajectory = torch.stack(states)
305 successor = torch.cat((trajectory[1:], rssm.flatten(recurrent, latent).unsqueeze(0)))
306 goals = skill.expand(len(trajectory), -1, -1)
307 current = torch.cat((trajectory, goals), -1)
308 following = torch.cat((successor, goals), -1)
309 self.
counts[
"imagined_steps"] += len(trajectory) * len(skill)
310 reward_logits, features, cont_logits = self.
world.predict(trajectory, torch.stack(actions))
311 discounts = config.gamma * cont_logits.sigmoid()
312 rewards = _lambda_returns(_symlog_mean(reward_logits), discounts, _symlog_mean(self.
reward_target(following)),
313 config.return_lambda)
314 successors = _lambda_returns(features, discounts, self.
successor_target(following), config.return_lambda)
315 weights = torch.cat((torch.ones_like(discounts[:1]), discounts[:-1].detach().cumprod(0)))
316 return current, rewards, successors, goals, weights, torch.stack(densities)
318 def _actor_step(self, recurrent, latent, skill):
320 self.
world.requires_grad_(
False)
322 current, rewards, successors, goals, weights, log_prob = self.
_imagine(recurrent, latent, skill)
323 with torch.no_grad():
324 multiplier = self.
multiplier(current).squeeze(-1).sigmoid()
325 error = (1 - config.gamma) * successors - goals
326 loss = (config.entropy_scale * log_prob - (1 - multiplier) * rewards
327 + config.lambda_scale * multiplier * _pseudo_huber(error, config.huber_scale))
328 self.
_step(
"actor", self.
_actor_opt, (loss * weights).sum() / weights.sum())
330 self.
world.requires_grad_(
True)
331 return current.detach(), rewards.detach(), successors.detach(), error.detach(), weights
335 batch = self.
replay.windows(config.batch_size, config.sequence_length, self.
_world_rng, self.
policy.device)
336 self.
counts[
"replay_transitions"] += config.batch_size * config.sequence_length
337 model_loss, h, z = self.
world.loss(batch, self.
_torch_rng, config.free_nats)
339 rows = torch.as_tensor(self.
_prior_rng.integers(len(h), size=config.imagination_batch_size), device=h.device)
341 skill = self.
policy._actor._tensor(skills)
342 current, rewards, successors, error, weights = self.
_actor_step(h[rows], z[rows], skill)
345 violated = (torch.linalg.vector_norm(error, dim=-1) >= config.delta).to(logit.dtype)
346 multiplier_loss = F.binary_cross_entropy_with_logits(logit, violated, reduction=
"none")
347 value_loss = _symlog_loss(self.
reward(current), rewards)
348 sf_loss = (self.
successor(current) - successors).square().mean(-1)
349 for name, optimizer, loss
in ((
"critic", self.
_value_opt, value_loss),
352 self.
_step(name, optimizer, (loss * weights).sum() / weights.sum())
359 """Implement QDAC-MB for numeric Box observations and continuous Box actions.
361 Use the same physical skill bounds and pre-action feature callback
362 as model-free QDAC. This vector-state adaptation uses a categorical
363 GRU world model, prediction of reward, features and continuation,
364 and pathwise actor updates through imagined lambda returns. It uses
365 the standard QDpy continuous-action layout and an episode session.
367 :param env_factory: Callable returning a fresh Gymnasium environment.
368 :param feature: Callable returning a feature vector from observation, action and info.
369 :param skill_bounds: Ordered physical bounds for each feature coordinate.
370 :param skill_sampler: Optional function of a NumPy Generator returning a desired skill.
371 :param policy: Optional PolicyConfig with the latent actor's widths.
372 :param config: Optional QDACMBConfig controlling real and imagined work.
373 :param max_episode_steps: External time limit for environment interactions.
374 :param seed: Nonnegative seed for initialization, replay, goals and actions.
375 :param device: Torch CPU or CUDA device.
378 _config_type = QDACMBConfig
379 _stats_type = QDACMBStats
381 def _make_policy(self, env, policy, seed, device):
383 policy=policy, world=self.
config.world, seed=seed, device=device)
385 def _make_learner(self, seed):
390 """Return real training steps, sampled replay rows, imagined steps, and updates."""
393 def _start_episode(self):
396 def _action(self, observation, context):
397 goal, session = context
398 return session._act(observation, goal,
False)
400 def _record(self, observation, action, reward, successor, terminated, truncated, feature, context):
402 self.
_learner.record(observation, action, reward, successor, terminated, feature, session.steps == 1)