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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AICL Example: Reinforcement Learning Agent
|
| 2 |
+
# Comprehensive RL agent system covering environment interaction, policy learning, reward shaping,
|
| 3 |
+
# exploration/exploitation balance, and multi-agent coordination with safety constraints.
|
| 4 |
+
|
| 5 |
+
Goal Build a reinforcement learning agent system that learns optimal policies through environment interaction, supports multiple algorithm families, implements safe exploration, handles reward shaping, and enables multi-agent coordination for complex sequential decision-making tasks
|
| 6 |
+
|
| 7 |
+
Constraint Agent must never take unsafe actions; safety constraints must be enforced as hard constraints regardless of learned policy
|
| 8 |
+
Constraint Reward shaping must be transparent and not introduce reward hacking opportunities
|
| 9 |
+
Constraint Multi-agent communication must be bandwidth-limited and latency-bounded
|
| 10 |
+
Constraint Policy updates must be reversible to enable rollback from catastrophic forgetting
|
| 11 |
+
Constraint Episode replay buffers must support deterministic replay for reproducibility
|
| 12 |
+
|
| 13 |
+
Risk Catastrophic forgetting during policy updates on new tasks
|
| 14 |
+
Recovery Maintain replay buffer of critical experiences; implement elastic weight consolidation; checkpoint policy networks before each update; enable rollback to last stable policy
|
| 15 |
+
|
| 16 |
+
Risk Reward hacking where agent exploits specification gaps instead of intended behavior
|
| 17 |
+
Recovery Implement adversarial reward auditing; compare agent behavior against human demonstrations; add auxiliary penalties for suspicious reward patterns; enable human-in-the-loop reward validation
|
| 18 |
+
|
| 19 |
+
Risk Unsafe action execution during exploration in safety-critical environments
|
| 20 |
+
Recovery Deploy action masking with safety constraint checker; use constrained policy optimization with safety Lagrangian; implement fallback to safe default action on constraint violation
|
| 21 |
+
|
| 22 |
+
Risk Environment simulation-reality gap causing poor transfer
|
| 23 |
+
Recovery Apply domain randomization during training; use systematic sim-to-real adaptation; deploy progressive transfer with online fine-tuning in real environment
|
| 24 |
+
|
| 25 |
+
Risk Multi-agent coordination collapse into suboptimal equilibria
|
| 26 |
+
Recovery Implement communication protocol with shared reward signals; deploy counterfactual credit assignment; enable centralized training with decentralized execution paradigm
|
| 27 |
+
|
| 28 |
+
Risk Training instability from large policy gradient variance
|
| 29 |
+
Recovery Use generalized advantage estimation with GAE-lambda; clip policy ratios using PPO-style objectives; monitor KL divergence between consecutive policies
|
| 30 |
+
|
| 31 |
+
Layer AgentCore
|
| 32 |
+
SubLayer: PolicyNetwork
|
| 33 |
+
SubLayer: ValueNetwork
|
| 34 |
+
SubLayer: ActionSelection
|
| 35 |
+
Layer Learning
|
| 36 |
+
SubLayer: PolicyGradient
|
| 37 |
+
SubLayer: ValueBased
|
| 38 |
+
SubLayer: ModelBased
|
| 39 |
+
SubLayer: RewardShaping
|
| 40 |
+
Layer Safety
|
| 41 |
+
SubLayer: ConstraintEnforcement
|
| 42 |
+
SubLayer: SafeExploration
|
| 43 |
+
SubLayer: ActionMasking
|
| 44 |
+
Layer MultiAgent
|
| 45 |
+
SubLayer: CommunicationProtocol
|
| 46 |
+
SubLayer: CoordinationStrategy
|
| 47 |
+
SubLayer: CreditAssignment
|
| 48 |
+
|
| 49 |
+
Validation Policy must achieve at least 80% of expert performance on benchmark environment within 1M steps
|
| 50 |
+
Validation Safety constraint violations must remain at zero during evaluation
|
| 51 |
+
Validation Reward shaping must not reduce true task performance by more than 5%
|
| 52 |
+
Validation Multi-agent team reward must exceed sum of independent agent rewards by at least 10%
|
| 53 |
+
Validation Policy KL divergence between consecutive updates must remain below 0.1
|
| 54 |
+
Validation Replay buffer must support deterministic replay with identical results
|
| 55 |
+
Validation Agent must recover from 90% of environment perturbations within 10 steps
|
| 56 |
+
|
| 57 |
+
# Level 2 - Entities
|
| 58 |
+
|
| 59 |
+
Entity Environment
|
| 60 |
+
envId: string
|
| 61 |
+
envType: string
|
| 62 |
+
observationSpace: dict
|
| 63 |
+
actionSpace: dict
|
| 64 |
+
rewardRange: dict
|
| 65 |
+
maxSteps: integer
|
| 66 |
+
safetyConstraints: list
|
| 67 |
+
simulationConfig: dict
|
| 68 |
+
domainRandomization: dict
|
| 69 |
+
|
| 70 |
+
Entity AgentPolicy
|
| 71 |
+
policyId: string
|
| 72 |
+
algorithmType: string
|
| 73 |
+
networkArchitecture: dict
|
| 74 |
+
hyperparameters: dict
|
| 75 |
+
learningRateSchedule: dict
|
| 76 |
+
explorationConfig: dict
|
| 77 |
+
safetyConfig: dict
|
| 78 |
+
trainingStepCount: integer
|
| 79 |
+
version: string
|
| 80 |
+
createdAt: datetime
|
| 81 |
+
|
| 82 |
+
Entity Experience
|
| 83 |
+
experienceId: string
|
| 84 |
+
agentId: string
|
| 85 |
+
environmentId: string
|
| 86 |
+
observation: dict
|
| 87 |
+
action: dict
|
| 88 |
+
reward: float
|
| 89 |
+
nextObservation: dict
|
| 90 |
+
done: boolean
|
| 91 |
+
truncated: boolean
|
| 92 |
+
safetyViolation: boolean
|
| 93 |
+
timestamp: datetime
|
| 94 |
+
episodeId: string
|
| 95 |
+
|
| 96 |
+
Entity RewardFunction
|
| 97 |
+
rewardId: string
|
| 98 |
+
primaryReward: dict
|
| 99 |
+
shapingRewards: list
|
| 100 |
+
penaltyTerms: list
|
| 101 |
+
constraintPenalties: list
|
| 102 |
+
intrinsicReward: dict
|
| 103 |
+
totalRewardExpression: string
|
| 104 |
+
version: string
|
| 105 |
+
lastModified: datetime
|
| 106 |
+
|
| 107 |
+
Entity MultiAgentTeam
|
| 108 |
+
teamId: string
|
| 109 |
+
agentIds: list
|
| 110 |
+
communicationProtocol: dict
|
| 111 |
+
coordinationStrategy: string
|
| 112 |
+
sharedRewardWeight: float
|
| 113 |
+
individualRewardWeight: float
|
| 114 |
+
messageBandwidth: integer
|
| 115 |
+
teamPerformanceMetrics: dict
|
| 116 |
+
|
| 117 |
+
Entity TrainingEpisode
|
| 118 |
+
episodeId: string
|
| 119 |
+
environmentId: string
|
| 120 |
+
agentId: string
|
| 121 |
+
totalReward: float
|
| 122 |
+
stepCount: integer
|
| 123 |
+
safetyViolations: integer
|
| 124 |
+
explorationRate: float
|
| 125 |
+
policyKL: float
|
| 126 |
+
startTime: datetime
|
| 127 |
+
endTime: datetime
|
| 128 |
+
outcome: string
|
| 129 |
+
|
| 130 |
+
# Level 3 - Behaviors
|
| 131 |
+
|
| 132 |
+
Behavior SelectAction
|
| 133 |
+
Input:
|
| 134 |
+
observation: dict
|
| 135 |
+
policy: AgentPolicy
|
| 136 |
+
safetyConfig: dict
|
| 137 |
+
Output:
|
| 138 |
+
action: dict
|
| 139 |
+
actionLogProb: float
|
| 140 |
+
valueEstimate: float
|
| 141 |
+
safetyApproved: boolean
|
| 142 |
+
Action:
|
| 143 |
+
Encode observation using policy network encoder
|
| 144 |
+
Compute action distribution parameters from policy head
|
| 145 |
+
Sample action from distribution with exploration noise
|
| 146 |
+
Check action against safety constraint mask
|
| 147 |
+
If action violates constraint, project to nearest safe action
|
| 148 |
+
Compute log probability and value estimate
|
| 149 |
+
Return action with safety approval status
|
| 150 |
+
|
| 151 |
+
Behavior UpdatePolicy
|
| 152 |
+
Input:
|
| 153 |
+
experiences: list
|
| 154 |
+
policy: AgentPolicy
|
| 155 |
+
updateConfig: dict
|
| 156 |
+
Output:
|
| 157 |
+
updatedPolicy: AgentPolicy
|
| 158 |
+
trainingMetrics: dict
|
| 159 |
+
Action:
|
| 160 |
+
Compute advantage estimates using GAE-lambda
|
| 161 |
+
Compute policy gradient with clipped surrogate objective
|
| 162 |
+
Compute value function loss with optional TD-lambda returns
|
| 163 |
+
Compute entropy bonus for exploration encouragement
|
| 164 |
+
Compute total loss and apply gradient clipping
|
| 165 |
+
Check KL divergence against threshold before applying update
|
| 166 |
+
If KL exceeds threshold, reduce learning rate and retry
|
| 167 |
+
Return updated policy with training metrics
|
| 168 |
+
|
| 169 |
+
Behavior ShapeReward
|
| 170 |
+
Input:
|
| 171 |
+
experience: Experience
|
| 172 |
+
rewardFunction: RewardFunction
|
| 173 |
+
Output:
|
| 174 |
+
shapedReward: float
|
| 175 |
+
rewardBreakdown: dict
|
| 176 |
+
Action:
|
| 177 |
+
Evaluate primary reward from environment signal
|
| 178 |
+
Add potential-based shaping rewards if configured
|
| 179 |
+
Subtract constraint violation penalties
|
| 180 |
+
Add intrinsic curiosity reward for novel states
|
| 181 |
+
Compute any auxiliary reward terms
|
| 182 |
+
Validate total reward does not exceed reward hacking threshold
|
| 183 |
+
Return shaped reward with detailed breakdown
|
| 184 |
+
|
| 185 |
+
Behavior CoordinateMultiAgent
|
| 186 |
+
Input:
|
| 187 |
+
teamState: MultiAgentTeam
|
| 188 |
+
observations: dict
|
| 189 |
+
communicationBudget: integer
|
| 190 |
+
Output:
|
| 191 |
+
coordinatedActions: dict
|
| 192 |
+
messages: dict
|
| 193 |
+
teamReward: float
|
| 194 |
+
Action:
|
| 195 |
+
Each agent computes individual action proposals
|
| 196 |
+
Agents exchange compressed messages within budget
|
| 197 |
+
Aggregate team information using attention mechanism
|
| 198 |
+
Compute coordinated actions considering team objectives
|
| 199 |
+
Estimate team value function for shared reward allocation
|
| 200 |
+
Apply counterfactual credit assignment for individual contributions
|
| 201 |
+
Return coordinated actions, messages, and team reward estimate
|
| 202 |
+
|
| 203 |
+
Behavior ExploreEnvironment
|
| 204 |
+
Input:
|
| 205 |
+
agentPolicy: AgentPolicy
|
| 206 |
+
environment: Environment
|
| 207 |
+
explorationConfig: dict
|
| 208 |
+
Output:
|
| 209 |
+
experiences: list
|
| 210 |
+
episodeSummary: TrainingEpisode
|
| 211 |
+
Action:
|
| 212 |
+
Reset environment and initialize episode
|
| 213 |
+
For each step until done or max steps:
|
| 214 |
+
Select action with exploration strategy
|
| 215 |
+
Execute action in environment
|
| 216 |
+
Observe reward and next state
|
| 217 |
+
Check safety constraints
|
| 218 |
+
Store experience in replay buffer
|
| 219 |
+
Compute episode summary statistics
|
| 220 |
+
Return collected experiences and episode summary
|
| 221 |
+
|
| 222 |
+
Behavior EnforceSafety
|
| 223 |
+
Input:
|
| 224 |
+
proposedAction: dict
|
| 225 |
+
safetyConstraints: list
|
| 226 |
+
environment: Environment
|
| 227 |
+
Output:
|
| 228 |
+
safeAction: dict
|
| 229 |
+
violations: list
|
| 230 |
+
correctionApplied: boolean
|
| 231 |
+
Action:
|
| 232 |
+
Evaluate each safety constraint against proposed action
|
| 233 |
+
If any hard constraint violated, project to constraint-satisfying action
|
| 234 |
+
Log any constraint violations with context
|
| 235 |
+
Apply graduated penalties for soft constraint violations
|
| 236 |
+
If no safe projection found, execute safe default action
|
| 237 |
+
Return safe action with violation report
|
| 238 |
+
|
| 239 |
+
# Level 4 - Conditions
|
| 240 |
+
|
| 241 |
+
Condition: KL divergence exceeds threshold
|
| 242 |
+
When KL divergence between new and old policy exceeds 0.1
|
| 243 |
+
Then reduce learning rate by factor of 0.5; recompute update with smaller step; log divergence event; if persistent, revert to last stable policy checkpoint
|
| 244 |
+
|
| 245 |
+
Condition: Safety constraint violated during exploration
|
| 246 |
+
When agent action violates hard safety constraint
|
| 247 |
+
Then immediately override with safe default action; apply penalty reward; log violation for constraint analysis; increase safety margin for future exploration
|
| 248 |
+
|
| 249 |
+
Condition: Reward hacking detected
|
| 250 |
+
When agent achieves unusually high shaped reward with low primary reward
|
| 251 |
+
Then halt training; audit reward function for specification gaps; remove or redesign problematic shaping terms; resume training with corrected reward function
|
| 252 |
+
|
| 253 |
+
Condition: Multi-agent communication failure
|
| 254 |
+
When inter-agent message delivery latency exceeds timeout or messages are lost
|
| 255 |
+
Then fall back to independent execution mode; cache last known team state; log communication failure; retry connection with exponential backoff
|
| 256 |
+
|
| 257 |
+
Condition: Training plateau detected
|
| 258 |
+
When average episode reward has not improved by more than 1% over last 100K steps
|
| 259 |
+
Then increase exploration rate temporarily; reset learning rate schedule; evaluate curriculum progression; consider algorithm switch
|
| 260 |
+
|
| 261 |
+
# Level 5 - Events
|
| 262 |
+
|
| 263 |
+
Event: EpisodeCompleted
|
| 264 |
+
On training episode reaching terminal state or max steps
|
| 265 |
+
Action: compute episode metrics; update training statistics; check for improvement; emit progress to monitoring dashboard
|
| 266 |
+
|
| 267 |
+
Event: SafetyViolation
|
| 268 |
+
On agent action violating safety constraint
|
| 269 |
+
Action: override action; apply penalty; log detailed violation context; alert safety monitoring system; update safety constraint statistics
|
| 270 |
+
|
| 271 |
+
Event: PolicyCheckpoint
|
| 272 |
+
On policy network checkpoint saved
|
| 273 |
+
Action: register checkpoint in version control; compute validation metrics; update best-policy tracker; clean up old checkpoints beyond retention limit
|
| 274 |
+
|
| 275 |
+
Event: RewardHackingSuspected
|
| 276 |
+
On shaped reward significantly exceeding primary reward trend
|
| 277 |
+
Action: pause training; trigger reward audit; notify human supervisor; log full reward breakdown for analysis
|
| 278 |
+
|
| 279 |
+
Event: MultiAgentCoordinationUpdate
|
| 280 |
+
On team coordination strategy parameters updated
|
| 281 |
+
Action: broadcast new coordination parameters to all agents; reset team performance baseline; log coordination change for audit trail
|
| 282 |
+
|
| 283 |
+
# Level 6 - Concurrency
|
| 284 |
+
|
| 285 |
+
Parallel:
|
| 286 |
+
Multiple environment instances for experience collection simultaneously
|
| 287 |
+
Policy gradient computation across batch of experiences
|
| 288 |
+
Value function bootstrapping for multi-step returns
|
| 289 |
+
Multi-agent action computation with parallel message passing
|
| 290 |
+
Safety constraint checking for proposed actions
|
| 291 |
+
Replay buffer insertion alongside policy training
|
| 292 |
+
|
| 293 |
+
# Level 7 - Optimization
|
| 294 |
+
|
| 295 |
+
Optimize: Sample efficiency of policy learning
|
| 296 |
+
Priority: Maximize learning per environment step; use off-policy correction; prioritize high-advantage experiences in replay
|
| 297 |
+
|
| 298 |
+
Optimize: Exploration-exploitation trade-off
|
| 299 |
+
Priority: Adaptive entropy coefficient scheduling; upper confidence bound for novel states; curiosity-driven exploration for sparse reward environments
|
| 300 |
+
|
| 301 |
+
Optimize: Multi-agent communication efficiency
|
| 302 |
+
Priority: Minimize message bits while preserving coordination quality; learn when to communicate; compress state representations for inter-agent messages
|
| 303 |
+
|
| 304 |
+
# Level 8 - Learning
|
| 305 |
+
|
| 306 |
+
Learn: Optimal exploration schedule
|
| 307 |
+
Goal: Balance exploration and exploitation to maximize cumulative reward
|
| 308 |
+
Adapt: Exploration rate, entropy coefficient, and noise schedule
|
| 309 |
+
Based: Learning curve analysis and plateau detection across training runs
|
| 310 |
+
|
| 311 |
+
Learn: Reward shaping hyperparameters
|
| 312 |
+
Goal: Maximize true task performance while accelerating learning with shaped rewards
|
| 313 |
+
Adapt: Shaping reward weights and potential function parameters
|
| 314 |
+
Based: Comparison of shaped vs unshaped reward training outcomes and transfer performance
|
| 315 |
+
|
| 316 |
+
Learn: Safety constraint margins
|
| 317 |
+
Goal: Minimize safety violations while maintaining exploration capability
|
| 318 |
+
Adapt: Constraint penalty coefficients and safety margin thresholds
|
| 319 |
+
Based: Violation frequency analysis and near-miss event statistics
|
| 320 |
+
|
| 321 |
+
Learn: Multi-agent communication protocol
|
| 322 |
+
Goal: Learn what, when, and how to communicate for effective team coordination
|
| 323 |
+
Adapt: Message content, communication triggers, and attention weights
|
| 324 |
+
Based: Team performance with and without communication in varied scenarios
|
| 325 |
+
|
| 326 |
+
# Level 9 - Security
|
| 327 |
+
|
| 328 |
+
Security:
|
| 329 |
+
Encrypt: Policy network weights and training checkpoints at rest using AES-256
|
| 330 |
+
Encrypt: Inter-agent communication channels with TLS 1.3 and message authentication
|
| 331 |
+
Protect: Reward function specifications from unauthorized modification via signed configuration
|
| 332 |
+
Protect: Safety constraint definitions with integrity verification and tamper detection
|
| 333 |
+
Protect: Replay buffer data with access controls preventing unauthorized extraction
|
| 334 |
+
Encrypt: Environment state observations containing sensitive information with field-level encryption
|
| 335 |
+
Protect: Multi-agent team membership and coordination parameters with RBAC
|
| 336 |
+
|
| 337 |
+
# Level 10 - Native
|
| 338 |
+
|
| 339 |
+
Native: python
|
| 340 |
+
{
|
| 341 |
+
import numpy as np
|
| 342 |
+
from typing import Dict, List, Optional, Tuple
|
| 343 |
+
from dataclasses import dataclass, field
|
| 344 |
+
from collections import deque
|
| 345 |
+
|
| 346 |
+
@dataclass
|
| 347 |
+
class PPOPolicy:
|
| 348 |
+
clip_range: float = 0.2
|
| 349 |
+
entropy_coeff: float = 0.01
|
| 350 |
+
value_loss_coeff: float = 0.5
|
| 351 |
+
max_grad_norm: float = 0.5
|
| 352 |
+
gae_lambda: float = 0.95
|
| 353 |
+
gamma: float = 0.99
|
| 354 |
+
kl_threshold: float = 0.1
|
| 355 |
+
learning_rate: float = 3e-4
|
| 356 |
+
|
| 357 |
+
def compute_advantages(self, rewards: List[float], values: List[float],
|
| 358 |
+
dones: List[bool]) -> np.ndarray:
|
| 359 |
+
advantages = []
|
| 360 |
+
gae = 0.0
|
| 361 |
+
next_value = 0.0
|
| 362 |
+
for t in reversed(range(len(rewards))):
|
| 363 |
+
if dones[t]:
|
| 364 |
+
next_value = 0.0
|
| 365 |
+
gae = 0.0
|
| 366 |
+
delta = rewards[t] + self.gamma * next_value - values[t]
|
| 367 |
+
gae = delta + self.gamma * self.gae_lambda * gae
|
| 368 |
+
advantages.insert(0, gae)
|
| 369 |
+
next_value = values[t]
|
| 370 |
+
return np.array(advantages)
|
| 371 |
+
|
| 372 |
+
def clipped_surrogate_loss(self, old_log_probs: np.ndarray,
|
| 373 |
+
new_log_probs: np.ndarray,
|
| 374 |
+
advantages: np.ndarray) -> Tuple[float, float]:
|
| 375 |
+
ratio = np.exp(new_log_probs - old_log_probs)
|
| 376 |
+
surr1 = ratio * advantages
|
| 377 |
+
surr2 = np.clip(ratio, 1 - self.clip_range, 1 + self.clip_range) * advantages
|
| 378 |
+
loss = -np.minimum(surr1, surr2).mean()
|
| 379 |
+
kl = np.mean(ratio - 1 - np.log(ratio))
|
| 380 |
+
return loss, kl
|
| 381 |
+
|
| 382 |
+
@dataclass
|
| 383 |
+
class SafetyConstraintEnforcer:
|
| 384 |
+
constraints: List[Dict] = field(default_factory=list)
|
| 385 |
+
default_safe_action: Dict = field(default_factory=dict)
|
| 386 |
+
|
| 387 |
+
def check_action(self, action: Dict, state: Dict) -> Tuple[Dict, List[str], bool]:
|
| 388 |
+
violations = []
|
| 389 |
+
safe_action = action.copy()
|
| 390 |
+
correction_applied = False
|
| 391 |
+
|
| 392 |
+
for constraint in self.constraints:
|
| 393 |
+
constraint_type = constraint["type"]
|
| 394 |
+
if constraint_type == "bound":
|
| 395 |
+
param = constraint["parameter"]
|
| 396 |
+
if param in action:
|
| 397 |
+
low, high = constraint["bounds"]
|
| 398 |
+
if action[param] < low or action[param] > high:
|
| 399 |
+
violations.append(f"{param} out of bounds: {action[param]} not in [{low}, {high}]")
|
| 400 |
+
safe_action[param] = np.clip(action[param], low, high)
|
| 401 |
+
correction_applied = True
|
| 402 |
+
|
| 403 |
+
elif constraint_type == "exclude":
|
| 404 |
+
excluded_set = constraint["excluded_actions"]
|
| 405 |
+
if action.get("discrete") in excluded_set:
|
| 406 |
+
violations.append(f"Excluded action: {action.get('discrete')}")
|
| 407 |
+
safe_action = self.default_safe_action.copy()
|
| 408 |
+
correction_applied = True
|
| 409 |
+
|
| 410 |
+
return safe_action, violations, correction_applied
|
| 411 |
+
|
| 412 |
+
@dataclass
|
| 413 |
+
class ReplayBuffer:
|
| 414 |
+
capacity: int = 100000
|
| 415 |
+
buffer: deque = field(default_factory=lambda: deque(maxlen=100000))
|
| 416 |
+
|
| 417 |
+
def add(self, experience: Dict):
|
| 418 |
+
self.buffer.append(experience)
|
| 419 |
+
|
| 420 |
+
def sample(self, batch_size: int) -> List[Dict]:
|
| 421 |
+
indices = np.random.choice(len(self.buffer), size=min(batch_size, len(self.buffer)), replace=False)
|
| 422 |
+
return [self.buffer[i] for i in indices]
|
| 423 |
+
|
| 424 |
+
def prioritized_sample(self, batch_size: int, alpha: float = 0.6) -> List[Dict]:
|
| 425 |
+
if len(self.buffer) == 0:
|
| 426 |
+
return []
|
| 427 |
+
priorities = np.array([
|
| 428 |
+
max(abs(exp.get("advantage", 0.0)), 1e-6) for exp in self.buffer
|
| 429 |
+
])
|
| 430 |
+
probs = priorities ** alpha
|
| 431 |
+
probs /= probs.sum()
|
| 432 |
+
indices = np.random.choice(len(self.buffer), size=min(batch_size, len(self.buffer)), p=probs, replace=False)
|
| 433 |
+
return [self.buffer[i] for i in indices]
|
| 434 |
+
|
| 435 |
+
@dataclass
|
| 436 |
+
class RewardShaper:
|
| 437 |
+
potential_function: Dict = field(default_factory=dict)
|
| 438 |
+
intrinsic_scale: float = 0.1
|
| 439 |
+
constraint_penalty: float = -10.0
|
| 440 |
+
|
| 441 |
+
def shape(self, primary_reward: float, state: Dict, next_state: Dict,
|
| 442 |
+
violation: bool, novelty: float) -> Tuple[float, Dict]:
|
| 443 |
+
shaping_reward = 0.0
|
| 444 |
+
if self.potential_function:
|
| 445 |
+
current_potential = self._evaluate_potential(state)
|
| 446 |
+
next_potential = self._evaluate_potential(next_state)
|
| 447 |
+
shaping_reward = self.potential_function.get("gamma", 0.99) * next_potential - current_potential
|
| 448 |
+
|
| 449 |
+
intrinsic_reward = self.intrinsic_scale * novelty
|
| 450 |
+
penalty = self.constraint_penalty if violation else 0.0
|
| 451 |
+
total = primary_reward + shaping_reward + intrinsic_reward + penalty
|
| 452 |
+
|
| 453 |
+
breakdown = {
|
| 454 |
+
"primary": primary_reward,
|
| 455 |
+
"shaping": shaping_reward,
|
| 456 |
+
"intrinsic": intrinsic_reward,
|
| 457 |
+
"constraint_penalty": penalty,
|
| 458 |
+
"total": total
|
| 459 |
+
}
|
| 460 |
+
return total, breakdown
|
| 461 |
+
|
| 462 |
+
def _evaluate_potential(self, state: Dict) -> float:
|
| 463 |
+
weights = self.potential_function.get("weights", {})
|
| 464 |
+
return sum(state.get(k, 0.0) * v for k, v in weights.items())
|
| 465 |
+
}
|