QDpy
Loading...
Searching...
No Matches
qdos.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Advantage-weighted trajectory skills and offline-to-online latent control."""
7
8from collections import Counter
9from copy import deepcopy
10from dataclasses import dataclass
11from math import prod
12
13import numpy as np
14import torch
15from torch.nn import functional as F
16
17from .policy import (PolicyConfig, _BoxLayout, _flatten_observation, _integer, _mlp,
18 _observation_shape, _save_actor, _squashed_log_prob)
19from .rollout import Episode, _Cursor, _StepBudget, _open_environment, _seed
20from .sac import SACConfig, SACPolicy, SACStats, _SACLearner, _actor_metadata, _load_actor_layout, _twin_loss
21from .td3 import _Replay, _checked_step, _critic, _polyak, _twin_critics
22
23__all__ = ["QDOS", "QDOSConfig", "QDOSPolicy", "QDOSStats"]
24
25_FLOAT_MAX = np.finfo(np.float32).max
26
27
28
29@dataclass(frozen=True)
31 """Set the skill representation and its use in offline and online learning.
32
33 :param skill_horizon: Maximum environment steps per latent action.
34 :param latent_size: Number of coordinates of a bounded continuous skill.
35 :param batch_size: Offline representation minibatch size.
36 :param expectile: Upper expectile for implicit Q-learning.
37 :param advantage_temperature: Temperature of normalized advantage weights.
38 :param advantage_weighted: Use IQL advantages to weight representation learning.
39 :param kl_weight: Weight on Gaussian posterior-to-prior divergence.
40 :param information_weight: Weight of latent recovery on decoded logged states.
41 :param optimism: Random network distillation bonus for offline replay rewards.
42 :param offline_fraction: Fraction of offline samples in high-level SAC updates.
43 :param updates_per_skill: SAC minibatches per completed online latent action.
44 :param learning_rate: Offline IQL, representation, and pseudo-reward estimator rate.
45 """
46
47 skill_horizon: int = 8
48 latent_size: int = 2
49 batch_size: int = 64
50 expectile: float = .9
51 advantage_temperature: float = .5
52 advantage_weighted: bool = True
53 kl_weight: float = .1
54 information_weight: float = .1
55 optimism: float = .1
56 offline_fraction: float = .5
57 updates_per_skill: int = 1
58 learning_rate: float = 3e-4
59
60 def __post_init__(self):
61 for name in ("skill_horizon", "latent_size", "batch_size", "updates_per_skill"):
62 object.__setattr__(self, name, _integer(getattr(self, name), name))
63 if (not .5 < self.expectile < 1. or not 0. <= self.offline_fraction <= 1.
64 or type(self.advantage_weighted) is not bool):
65 raise ValueError("Use an upper expectile, a Boolean weighting flag, and offline_fraction in [0, 1].")
66 for name in ("kl_weight", "information_weight", "optimism"):
67 if not 0. <= getattr(self, name) <= _FLOAT_MAX:
68 raise ValueError(f"{name} must be finite, nonnegative and representable in float32.")
69 for name in ("advantage_temperature", "learning_rate"):
70 if not np.finfo(np.float32).tiny <= getattr(self, name) <= _FLOAT_MAX:
71 raise ValueError(f"{name} must be positive and representable as a normal float32.")
72
73
74
76 """Compose primitive actions from a state-to-skill policy and a frozen decoder.
77
78 Call reset() when the simulator resets. Between resets, act() chooses
79 a code every skill_horizon calls and holds it fixed for the decoder.
80 Each inference session needs its own policy instance and episode state.
81 """
82
83 def __init__(self, high, low, skill_horizon):
84 self._high, self._low = high, low
85 self.skill_horizon = _integer(skill_horizon, "skill_horizon")
86 self.reset()
87
88
89 def reset(self):
90 """Start the next action with a freshly selected skill."""
91 self._remaining = 0
92 self._latent = None
93
94
95 def select_skill(self, observation, deterministic=True):
96 """Inspect the high-level policy's choice for an observation."""
97 flat = _flatten_observation(observation, self._high._obs_shape)
98 return self._high._draw(flat, deterministic, self._high._rng)[0]
99
100
101 def act_skill(self, observation, skill, deterministic=True):
102 """Decode one physical action for a skill vector with entries in [-1, 1]."""
103 flat = _flatten_observation(observation, self._high._obs_shape)
104 skill = np.asarray(skill, dtype=float)
105 if skill.shape != self._high._actions.shape or not np.all(np.abs(skill) <= 1.):
106 raise ValueError(f"Use a bounded skill vector of shape {self._high._actions.shape}.")
107 return self._decode(flat, skill.astype(np.float32), deterministic)
108
109 def _decode(self, flat, code, deterministic):
110 return self._low._draw(np.concatenate((flat, code)), deterministic, self._low._rng)[0]
111
112
113 def act(self, observation, deterministic=True):
114 """Accept the original observation shape and return a bounded Box action."""
115 observation = _flatten_observation(observation, self._high._obs_shape)
116 if not self._remaining:
117 self._latent, _, _ = self._high._draw(observation, deterministic, self._high._rng)
118 self._remaining = self.skill_horizon
119 action = self._decode(observation, self._latent, deterministic)
120 self._remaining -= 1
121 return action
122
123
124 def save(self, path):
125 """Write learned weights and spaces. The saved policy starts a new episode."""
126 low = _actor_metadata(self._low, "qdos", self._high._obs_shape)
127 high_parameters = self._high._parameters()
128 low.update(latent_size=prod(self._high._actions.shape), skill_horizon=self.skill_horizon,
129 high_hidden_sizes=self._high.config.hidden_sizes, high_parameters=len(high_parameters))
130 _save_actor(path, low, np.concatenate((high_parameters, self._low._parameters())))
131
132
133 @classmethod
134 def load(cls, path, *, device="cpu", seed=0):
135 """Load the actor pair and initialize new seeded inference generators."""
136 metadata, parameters, shape, action, policy = _load_actor_layout(path, "qdos")
137 latent = _integer(metadata["latent_size"], "latent_size")
138 cut = _integer(metadata["high_parameters"], "high_parameters")
139 high, low = _build_actors(shape, action, latent, PolicyConfig(metadata["high_hidden_sizes"]),
140 policy, np.random.default_rng(_integer(seed, "seed", 0)), device)
141 high._set_parameters(parameters[:cut])
142 low._set_parameters(parameters[cut:])
143 return cls(high, low, metadata["skill_horizon"])
144
145
146
147@dataclass(frozen=True)
149 """Report logged segments, replay reuse, and actual primitive interactions."""
150
151 logged_segments: int = 0
152 unused_logged_steps: int = 0
153 offline_updates: int = 0
154 pseudo_labeled_segments: int = 0
155 online_skills: int = 0
156 discarded_prefix_steps: int = 0
157 offline_samples: int = 0
158 online_samples: int = 0
159
160
161def _build_actors(shape, action, latent, high_policy, low_policy, rng, device):
162 code = _BoxLayout((latent,), (-1.,) * latent, (1.,) * latent, np.dtype(np.float32).str)
163 high = SACPolicy._from_layout(shape, code, high_policy, _seed(rng), device, stochastic=False)
164 low = SACPolicy._from_layout((prod(shape) + latent,), action, low_policy, _seed(rng), device, stochastic=False)
165 return high, low
166
167
168def _segments(episodes, shape, actor, horizon, gamma):
169 """Build fixed-length within-episode chunks with discounted rewards and true successors."""
170 observations, actions, rewards, successors, terminal = [], [], [], [], []
171 unused = 0
172 discount = gamma ** np.arange(horizon)
173 for episode in episodes:
174 if not isinstance(episode, Episode) or not (episode.terminated or episode.truncated):
175 raise ValueError("Supply completed Episode records with explicit termination or truncation.")
176 steps = episode.steps
177 obs, act, reward = (np.asarray(row, dtype=float) for row in
178 (episode.observations, episode.actions, episode.rewards))
179 if (not steps or obs.shape != (steps + 1, *shape) or act.shape != (steps, *actor._actions.shape)
180 or reward.shape != (steps,)
181 or not all(np.all(np.abs(array) <= _FLOAT_MAX) for array in (obs, reward))):
182 raise ValueError("Logged episodes need aligned finite observations, actions, and rewards.")
183 rows, rest = divmod(steps, horizon)
184 unused += rest
185 obs, act = obs.reshape(steps + 1, -1), act.reshape(steps, -1)
186 if not np.all((act >= actor._low) & (act <= actor._high)):
187 raise ValueError("Logged actions must be within the physical Box bounds.")
188 length = rows * horizon
189 observations.extend(obs[:length].reshape(rows, horizon, obs.shape[1]))
190 actions.extend(actor._encode_actions(act[:length]).reshape(rows, horizon, act.shape[1]))
191 rewards.extend(reward[:length].reshape(rows, horizon) @ discount)
192 successors.extend(obs[horizon:length + 1:horizon])
193 terminal.extend((np.arange(1, rows + 1) * horizon == steps) & episode.terminated)
194 if not observations or not np.all(np.abs(rewards) <= _FLOAT_MAX):
195 raise ValueError("Supply at least one complete logged skill segment with representable rewards.")
196 return tuple(np.asarray(array, dtype=dtype) for array, dtype in zip(
197 (observations, actions, rewards, successors, terminal), (np.float32,) * 4 + (bool,))), unused
198
199
201 """Keep an actual per-skill bootstrap discount alongside each macro transition."""
202
203 def __init__(self, capacity, state_size, code_size):
204 super().__init__(capacity, state_size, code_size)
205 self.discounts = np.empty(capacity, dtype=np.float32)
206
207 def add_skill(self, observation, action, reward, successor, terminal, discount):
208 slot = self.position
209 self.add(observation, action, reward, successor, terminal)
210 self.discounts[slot] = discount
211
212 def batch(self, rows, device):
213 return (*super().batch(rows, device), torch.as_tensor(self.discounts[rows], device=device))
214
215
217 """Use ordinary SAC updates with mixed replay and variable-duration bootstrap."""
218
219 def __init__(self, actor, config, seed, counts, offline, fraction):
220 replay = _SkillReplay(config.replay_capacity, prod(actor._obs_shape), prod(actor._actions.shape))
221 super().__init__(actor, config, seed, counts, replay=replay)
222 self.offline, self.fraction = offline, fraction
223
224 def _batch(self):
225 size = self.config.batch_size
226 expected = self.fraction * size
227 count = int(expected)
228 if expected > count:
229 count += int(self.sample_rng.random() < expected - count)
230 batches = []
231 for replay, samples, field in ((self.offline, count, "offline_samples"),
232 (self.replay, size - count, "online_samples")):
233 if samples:
234 batches.append(replay.sample(samples, self.sample_rng, self.device))
235 self.counts[field] += samples
236 return tuple(torch.cat(parts) for parts in zip(*batches))
237
238 def _reward_step(self, states, actions, rewards, successors, terminal, discounts):
239 with torch.no_grad():
240 next_actions, log_prob = self.actor._sample_actions(successors, self.noise_rng)
241 values = self._values(self.critic_targets, successors, next_actions).min(dim=0).values
242 targets = rewards + discounts * (values - self.temperature * log_prob).masked_fill(terminal, 0.)
243 values = self._values(self.critics, states, actions)
244 self._update(_twin_loss(values, targets), self.critic_optimizer, "critic")
245 _polyak(self.critics, self.critic_targets, self.config.tau)
246
247def _normal_parameters(network, inputs):
248 mean, log_std = network(inputs).chunk(2, dim=-1)
249 return mean, log_std.clamp(-8., 2.)
250
251
252def _offline_step(loss, optimizer):
253 if not torch.isfinite(loss):
254 raise ValueError("QDOS produced a nonfinite offline loss.")
255 optimizer.zero_grad(set_to_none=True)
256 loss.backward()
257 _checked_step(optimizer)
258
259
260
261class QDOS:
262 """Discover skills with a trajectory VAE and compose them using semi-Markov SAC.
263
264 :param env_factory: Single Gymnasium environment with fixed Box observations and actions.
265 :param episodes: Completed rollout.Episode records from the same observation and action spaces.
266 :param config: Skill learning, reward relabeling and mixed replay settings.
267 :param sac: SACConfig for primitive discount, critics and high-level SAC.
268 learning_starts is measured in live primitive steps.
269 :param policy: Network architecture for both actors and the trajectory encoder.
270 :param max_episode_steps: External episode safety horizon.
271 :param seed: Nonnegative seed for data sampling, optimizers and reset.
272 :param device: Torch device. CPU by default.
273 """
274
275 def __init__(self, env_factory, *, episodes, config=None, sac=None, policy=None,
276 max_episode_steps=300, seed=0, device="cpu"):
277 if not callable(env_factory):
278 raise TypeError("Provide a callable environment factory.")
279 self.config = QDOSConfig() if config is None else config
280 self.sac = SACConfig() if sac is None else sac
281 if not isinstance(self.config, QDOSConfig) or not isinstance(self.sac, SACConfig):
282 raise TypeError("Supply QDOSConfig and SACConfig settings.")
283 config = self.config
284 policy = PolicyConfig() if policy is None else policy
285 rng = np.random.default_rng(_integer(seed, "seed", 0))
286 self._rng, self._factory = rng, env_factory
287 self._horizon = _integer(max_episode_steps, "max_episode_steps")
288 self._counts = Counter()
289 with _open_environment(env_factory) as env:
290 self._shape = _observation_shape(env.observation_space)
291 self._action = _BoxLayout.from_space(env.action_space)
292 self._high, self._low = _build_actors(self._shape, self._action, config.latent_size, policy, policy, rng, device)
293 self._log, self._unused = _segments(episodes, self._shape, self._low, config.skill_horizon, self.sac.gamma)
294 self._count = len(self._log[0])
295 self._torch_rng = torch.Generator(device=self._low.device).manual_seed(_seed(rng))
296 self._reset_rng = np.random.default_rng(_seed(rng))
297 self._rollout_rng = torch.Generator(device=self._low.device).manual_seed(_seed(rng))
298 width = prod(self._shape)
299 trajectory_width = config.skill_horizon * (width + prod(self._action.shape))
300 self._encoder = _mlp(trajectory_width, 2 * config.latent_size, policy, _seed(rng), self._low.device)
301 self._prior = _mlp(width, 2 * config.latent_size, policy, _seed(rng), self._low.device)
302 self._value = _mlp(width, 1, policy, _seed(rng), self._low.device)
303 self._critics = _twin_critics(self._high, self.sac, rng, rng)
304 self._targets = deepcopy(self._critics).requires_grad_(False)
305 aux_width = width + config.latent_size
306 self._reward = _mlp(aux_width, 1, policy, _seed(rng), self._low.device)
307 self._rnd_target = _mlp(aux_width, 8, policy, _seed(rng), self._low.device).requires_grad_(False)
308 self._rnd = _mlp(aux_width, 8, policy, _seed(rng), self._low.device)
309 rate = config.learning_rate
310 self._iql_optimizer = torch.optim.Adam((*self._value.parameters(), *self._critics.parameters()), lr=rate)
311 self._rep_optimizer = torch.optim.Adam((*self._encoder.parameters(), *self._prior.parameters(),
312 *self._low._trainable_parameters()), lr=rate)
313 self._aux_optimizer = torch.optim.Adam((*self._reward.parameters(), *self._rnd.parameters()), lr=rate)
314 self._learner = None
315
316 @property
317 def stats(self):
318 """Return the updated split of logged, live, and optimizer work."""
319 size = 0 if self._learner is None else self._learner.replay.size
320 temperature = self.sac.initial_temperature if self._learner is None else float(self._learner.temperature)
321 return QDOSStats(**self._counts, logged_segments=self._count, unused_logged_steps=self._unused,
322 replay_size=size, temperature=temperature)
323
324 def _batch(self, rows):
325 return tuple(torch.as_tensor(array[rows], device=self._low.device) for array in self._log)
326
327 def _sample_normal(self, mean, log_std):
328 noise = torch.randn(mean.shape, generator=self._torch_rng, device=mean.device, dtype=mean.dtype)
329 return mean + noise * log_std.exp()
330
331 def _posterior(self, states, actions):
332 return _normal_parameters(self._encoder, torch.cat((states, actions), dim=-1).flatten(1))
333
334
335 def pretrain(self, updates):
336 """Continue offline updates up to the first call to train()."""
337 updates = _integer(updates, "updates", 0)
338 if self._learner is not None:
339 raise RuntimeError("QDOS freezes the decoder and offline labels at the start of online training.")
340 cfg, gamma = self.config, self.sac.gamma ** self.config.skill_horizon
341 for _ in range(updates):
342 states, actions, rewards, successor, terminal = self._batch(self._rng.integers(self._count,
343 size=cfg.batch_size))
344 start = states[:, 0]
345 mean, scale = self._posterior(states, actions)
346 code = self._sample_normal(mean, scale).tanh()
347 value = self._value(start).flatten()
348 with torch.no_grad():
349 target = rewards + gamma * self._value(successor).flatten().masked_fill(terminal, 0.)
350 target_q = torch.stack([_critic(net, start, code) for net in self._targets]).min(dim=0).values
351 advantage = target_q - value
352 expectile = torch.where(advantage > 0., cfg.expectile, 1. - cfg.expectile)
353 critic_loss = sum(F.mse_loss(_critic(net, start, code.detach()), target) for net in self._critics)
354 _offline_step(critic_loss + (expectile * advantage.square()).mean(), self._iql_optimizer)
355 _polyak(self._critics, self._targets, self.sac.tau)
356
357 weights = ((advantage.detach() - advantage.detach().max()) / cfg.advantage_temperature
358 ).softmax(dim=0) if cfg.advantage_weighted else torch.full_like(advantage, 1. / len(start))
359 prior, prior_scale = _normal_parameters(self._prior, start)
360 kl = prior_scale - scale + .5 * ((2 * (scale - prior_scale)).exp()
361 + ((mean - prior) * (-prior_scale).exp()).square() - 1.)
362 inputs = torch.cat((states, code[:, None].expand(-1, cfg.skill_horizon, -1)), dim=-1)
363 predicted, std = self._low._network(inputs).chunk(2, dim=-1)
364 latent_actions = actions.clamp(-1. + 1e-6, 1. - 1e-6).atanh()
365 logp = _squashed_log_prob(predicted, (F.softplus(std) + .001).log(), latent_actions, 0.)
366 loss = cfg.kl_weight * kl.sum(dim=-1).mean() - weights @ logp.mean(dim=-1)
367 if cfg.information_weight:
368 # Decode on logged states to keep pretraining entirely offline.
369 random_code = 2 * torch.rand(code.shape, generator=self._torch_rng, device=code.device) - 1
370 generated = self._low._normalized(
371 torch.cat((states, random_code[:, None].expand(-1, cfg.skill_horizon, -1)), dim=-1))
372 recovered, _ = self._posterior(states, generated)
373 loss = loss + cfg.information_weight * (weights @ (recovered.tanh() - random_code).square().mean(-1))
374 _offline_step(loss, self._rep_optimizer)
375
376 inputs = torch.cat((start, code.detach()), dim=-1)
377 _offline_step(F.mse_loss(self._reward(inputs).flatten(), rewards)
378 + F.mse_loss(self._rnd(inputs), self._rnd_target(inputs)), self._aux_optimizer)
379 self._counts["offline_updates"] += 1
380 self._counts["optimizer_steps"] += 3
381 return self.stats
382
383 @torch.no_grad()
384 def _start_online(self):
385 if not self._counts["offline_updates"]:
386 raise RuntimeError("Call pretrain() with a positive update count before online training.")
387 cfg, gamma = self.config, self.sac.gamma ** self.config.skill_horizon
388 replay = _SkillReplay(self._count, prod(self._shape), cfg.latent_size)
389 if cfg.offline_fraction:
390 for start in range(0, self._count, cfg.batch_size):
391 rows = slice(start, start + cfg.batch_size)
392 states, actions, reward, _, _ = self._batch(rows)
393 code = self._sample_normal(*self._posterior(states, actions)).tanh()
394 if cfg.optimism:
395 inputs = torch.cat((states[:, 0], code), dim=-1)
396 bonus = (self._rnd(inputs) - self._rnd_target(inputs)).square().mean(dim=-1).sqrt()
397 reward = self._reward(inputs).flatten() + cfg.optimism * bonus
398 if not bool(torch.isfinite(reward).all()):
399 raise ValueError("QDOS pseudo-rewards must be finite.")
400 replay.actions[rows], replay.rewards[rows] = code.cpu().numpy(), reward.cpu().numpy()
401 replay.observations[:] = self._log[0][:, 0]
402 replay.next_observations[:] = self._log[3]
403 replay.terminated[:] = self._log[4]
404 replay.discounts.fill(gamma)
405 replay.size = self._count
406 self._counts["pseudo_labeled_segments"] = self._count
407 self._learner = _SkillSAC(self._high, self.sac, _seed(self._rng), self._counts, replay, cfg.offline_fraction)
408
409
410 def train(self, max_env_steps):
411 """Continue high-level SAC in a fresh environment with the same spaces.
412
413 A cut prefix without an environment boundary is counted and
414 omitted from replay. A completed short terminal or truncated
415 skill is kept with its actual duration and last observation.
416 """
417 budget = _StepBudget(max_env_steps, self._counts)
418 horizon, gamma = self.config.skill_horizon, self.sac.gamma
419 with _open_environment(self._factory) as env:
420 if (_observation_shape(env.observation_space) != self._shape
421 or _BoxLayout.from_space(env.action_space) != self._action):
422 raise ValueError("The environment factory changed its observation or action space.")
423 if self._learner is None:
424 self._start_online()
425 cursor = _Cursor(env, self._high, self._horizon, self._reset_rng)
426 while budget.remaining:
427 if cursor.ended:
428 cursor.reset()
429 start = cursor.observation
430 if self._counts["training_steps"] < self.sac.learning_starts:
431 with torch.no_grad():
432 mean, scale = _normal_parameters(self._prior, self._high._tensor(start))
433 code = self._sample_normal(mean, scale).tanh().cpu().numpy()
434 else:
435 code = self._high._draw(start, False, self._rollout_rng)[0]
436 reward, discount, count = 0., 1., 0
437 for count in range(1, min(horizon, budget.remaining) + 1):
438 inputs = np.concatenate((cursor.observation, code))
439 action = self._low._draw(inputs, False, self._rollout_rng)[0]
440 step_reward, terminal, _, _ = cursor.step(action, budget, "training_steps")
441 reward += discount * step_reward
442 discount *= gamma
443 if cursor.ended:
444 break
445 if count < horizon and not cursor.ended:
446 self._counts["discarded_prefix_steps"] += count
447 break
448 self._learner.replay.add_skill(start, code, reward, cursor.observation, terminal, discount)
449 self._counts["online_skills"] += 1
450 if self._counts["training_steps"] >= self.sac.learning_starts:
451 for _ in range(self.config.updates_per_skill):
452 self._learner.update()
453 return self.stats
454
455
456 def policy(self, *, seed=0, device=None):
457 """Return a new episode-state QDOSPolicy for evaluation or export."""
458 rng = np.random.default_rng(_integer(seed, "seed", 0))
459 high, low = [actor._new(_seed(rng), device) for actor in (self._high, self._low)]
460 high._set_parameters(self._high._parameters())
461 low._set_parameters(self._low._parameters())
462 return QDOSPolicy(high, low, self.config.skill_horizon)
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Configure trajectory pretraining, data reuse, and the latent action horizon.
Definition qdos.py:30
Two portable inference networks and a fixed skill duration.
Definition qdos.py:75
_decode(self, flat, code, deterministic)
Definition qdos.py:109
load(cls, path, *, device="cpu", seed=0)
Restore the two actors without an environment or training data.
Definition qdos.py:134
act(self, observation, deterministic=True)
Choose or continue a skill and decode one physical action.
Definition qdos.py:113
act_skill(self, observation, skill, deterministic=True)
Execute a caller-selected code independently of the high-level actor.
Definition qdos.py:101
save(self, path)
Export both actors and the skill horizon in one numeric file.
Definition qdos.py:124
reset(self)
Drop the pending skill at an episode boundary.
Definition qdos.py:89
select_skill(self, observation, deterministic=True)
Select one bounded code without changing the held skill.
Definition qdos.py:95
Offline and online training counts with separate sample origins.
Definition qdos.py:148
Train trajectory skills from a fixed log and adapt a high-level controller online.
Definition qdos.py:261
_start_online(self)
Definition qdos.py:384
train(self, max_env_steps)
Spend exactly the additional primitive-step budget on the deployed hierarchy.
Definition qdos.py:410
policy(self, *, seed=0, device=None)
Copy both inference actors without replay or optimizer state.
Definition qdos.py:456
pretrain(self, updates)
Fit the skill and advantage networks from logged segments only.
Definition qdos.py:335
_posterior(self, states, actions)
Definition qdos.py:331
_batch(self, rows)
Definition qdos.py:324
_sample_normal(self, mean, log_std)
Definition qdos.py:327
Replay, network, optimizer, and entropy settings for Soft Actor-Critic.
Definition sac.py:23
Cumulative SAC budget, replay, optimizer, and entropy statistics.
Definition sac.py:149
_values(networks, observations, actions)
Definition sac.py:232
_update(self, loss, optimizer, name, parameters=None)
Definition sac.py:202
add(self, observation, action, reward, next_observation, terminated)
Definition td3.py:107