learners
learners
¶
Learning units for continual learning.
Implements learners that combine function approximation with optimizers for temporally-uniform learning. Uses JAX's scan for efficient JIT-compiled training loops.
UpdateResult
¶
Result of a learner update step.
Attributes: state: Updated learner state prediction: Prediction made before update error: Prediction error metrics: Array of metrics -- shape (3,) without normalizer, (4,) with normalizer
MLPUpdateResult
¶
Result of an MLP learner update step.
Attributes: state: Updated MLP learner state prediction: Prediction made before update error: Prediction error metrics: Array of metrics -- shape (3,) without normalizer, (4,) with normalizer
LinearLearner(optimizer=None, normalizer=None)
¶
Linear function approximator with pluggable optimizer and optional normalizer.
Computes predictions as: y = w @ x + b
The learner maintains weights and bias, delegating the adaptation of learning rates to the optimizer (e.g., LMS or IDBD).
This follows the Alberta Plan philosophy of temporal uniformity: every component updates at every time step.
Attributes: optimizer: The optimizer to use for weight updates normalizer: Optional online feature normalizer
Args: optimizer: Optimizer for weight updates. Defaults to LMS(0.01) normalizer: Optional feature normalizer (e.g. EMANormalizer, WelfordNormalizer)
Source code in src/alberta_framework/core/learners.py
normalizer
property
¶
The feature normalizer, or None if normalization is disabled.
init(feature_dim)
¶
Initialize learner state.
Args: feature_dim: Dimension of the input feature vector
Returns: Initial learner state with zero weights and bias
Source code in src/alberta_framework/core/learners.py
predict(state, observation)
¶
Compute prediction for an observation.
Args: state: Current learner state observation: Input feature vector
Returns:
Scalar prediction y = w @ x + b
Source code in src/alberta_framework/core/learners.py
update(state, observation, target)
¶
Update learner given observation and target.
Performs one step of the learning algorithm: 1. Optionally normalize observation 2. Compute prediction 3. Compute error 4. Get weight updates from optimizer 5. Apply updates to weights and bias
Args: state: Current learner state observation: Input feature vector target: Desired output
Returns: UpdateResult with new state, prediction, error, and metrics
Source code in src/alberta_framework/core/learners.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 | |
MLPLearner(hidden_sizes=(128, 128), optimizer=None, step_size=1.0, bounder=None, gamma=0.0, lamda=0.0, normalizer=None, sparsity=0.9, leaky_relu_slope=0.01, use_layer_norm=True, head_optimizer=None)
¶
Multi-layer perceptron with composable optimizer, bounder, and normalizer.
Architecture: Input -> [Dense(H) -> LayerNorm -> LeakyReLU] x N -> Dense(1)
When use_layer_norm=False, the architecture simplifies to:
Input -> [Dense(H) -> LeakyReLU] x N -> Dense(1)
Uses parameterless layer normalization and sparse initialization following Elsayed et al. 2024. Accepts a pluggable optimizer (LMS, Autostep), an optional bounder (ObGDBounding), and an optional feature normalizer (EMANormalizer, WelfordNormalizer).
The update flow:
1. If normalizer: normalize observation, update normalizer state
2. Forward pass + jax.grad to get per-layer prediction gradients
3. Update eligibility traces: z = gamma * lamda * z + grad
4. Per-layer optimizer step: step, new_opt = optimizer.update_from_gradient(state, z)
5. If bounder: bound all steps globally
6. Apply: param += scale * error * step
Reference: Elsayed et al. 2024, "Streaming Deep Reinforcement Learning Finally Works"
Attributes: hidden_sizes: Tuple of hidden layer sizes optimizer: Optimizer for per-weight step-size adaptation bounder: Optional update bounder (e.g. ObGDBounding) normalizer: Optional feature normalizer use_layer_norm: Whether to apply parameterless layer normalization gamma: Discount factor for trace decay lamda: Eligibility trace decay parameter sparsity: Fraction of weights zeroed out per output neuron leaky_relu_slope: Negative slope for LeakyReLU activation
Single-Step (Daemon) Usage
Both predict() and update() work with single unbatched
observations (1D arrays of shape (feature_dim,)). This is the
intended usage for daemon-style deployments.
For low-latency daemon use, pre-compile predict and update
at startup by running a dummy warmup call:
Args:
hidden_sizes: Tuple of hidden layer sizes (default: two layers of 128)
optimizer: Optimizer for weight updates. Defaults to LMS(step_size).
Must support init_for_shape and update_from_gradient.
step_size: Base learning rate (used only when optimizer is None,
default: 1.0)
bounder: Optional update bounder (e.g. ObGDBounding for ObGD-style
bounding). When None, no bounding is applied.
gamma: Discount factor for trace decay (default: 0.0 for supervised)
lamda: Eligibility trace decay parameter (default: 0.0 for supervised)
normalizer: Optional feature normalizer. When provided, features are
normalized before prediction and learning.
sparsity: Fraction of weights zeroed out per output neuron (default: 0.9)
leaky_relu_slope: Negative slope for LeakyReLU (default: 0.01)
use_layer_norm: Whether to apply parameterless layer normalization
between hidden layers (default: True). Set to False for ablation
studies.
head_optimizer: Optional separate optimizer for the output (head) layer.
When None (default), all layers use optimizer. When set, hidden
layers use optimizer while the output layer uses
head_optimizer. This enables hybrid configurations like
stable LMS for the trunk with adaptive Autostep for the head.
Source code in src/alberta_framework/core/learners.py
normalizer
property
¶
The feature normalizer, or None if normalization is disabled.
to_config()
¶
Serialize learner configuration to dict.
Returns:
Dict with all constructor arguments needed to recreate
the learner via from_config().
Source code in src/alberta_framework/core/learners.py
from_config(config)
classmethod
¶
Reconstruct learner from a config dict.
Args:
config: Dict as produced by to_config()
Returns: Reconstructed MLPLearner instance
Source code in src/alberta_framework/core/learners.py
init(feature_dim, key)
¶
Initialize MLP learner state with sparse weights.
Args: feature_dim: Dimension of the input feature vector key: JAX random key for weight initialization
Returns: Initial MLP learner state with sparse weights and zero biases
Source code in src/alberta_framework/core/learners.py
predict(state, observation)
¶
Compute prediction for an observation.
JIT-compiled automatically. First call triggers tracing; subsequent calls with the same learner instance use the cached compilation.
Args: state: Current MLP learner state observation: Input feature vector
Returns: Scalar prediction
Source code in src/alberta_framework/core/learners.py
update(state, observation, target)
¶
Update MLP given observation and target.
JIT-compiled automatically. Performs one step of the learning algorithm:
- Optionally normalize observation
- Compute prediction and error
- Compute gradients via jax.grad on the forward pass
- Update eligibility traces
- Per-layer optimizer step from traces
- Optionally bound steps
- Apply bounded weight updates
Args: state: Current MLP learner state observation: Input feature vector target: Desired output
Returns: MLPUpdateResult with new state, prediction, error, and metrics
Source code in src/alberta_framework/core/learners.py
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 | |
TDUpdateResult
¶
Result of a TD learner update step.
Attributes: state: Updated TD learner state prediction: Value prediction V(s) before update td_error: TD error delta = R + gamma*V(s') - V(s) metrics: Array of metrics [squared_td_error, td_error, mean_step_size, ...]
TDLinearLearner(optimizer=None)
¶
Linear function approximator for TD learning.
Computes value predictions as: V(s) = w @ phi(s) + b
The learner maintains weights, bias, and eligibility traces, delegating the adaptation of learning rates to the TD optimizer (e.g., TDIDBD).
This follows the Alberta Plan philosophy of temporal uniformity: every component updates at every time step.
Reference: Kearney et al. 2019, "Learning Feature Relevance Through Step Size Adaptation in Temporal-Difference Learning"
Attributes: optimizer: The TD optimizer to use for weight updates
Args: optimizer: TD optimizer for weight updates. Defaults to TDIDBD()
Source code in src/alberta_framework/core/learners.py
init(feature_dim)
¶
Initialize TD learner state.
Args: feature_dim: Dimension of the input feature vector
Returns: Initial TD learner state with zero weights and bias
Source code in src/alberta_framework/core/learners.py
predict(state, observation)
¶
Compute value prediction for an observation.
Args: state: Current TD learner state observation: Input feature vector phi(s)
Returns:
Scalar value prediction V(s) = w @ phi(s) + b
Source code in src/alberta_framework/core/learners.py
update(state, observation, reward, next_observation, gamma)
¶
Update learner given a TD transition.
Performs one step of TD learning: 1. Compute V(s) and V(s') 2. Compute TD error delta = R + gamma*V(s') - V(s) 3. Get weight updates from TD optimizer 4. Apply updates to weights and bias
Args: state: Current TD learner state observation: Current observation phi(s) reward: Reward R received next_observation: Next observation phi(s') gamma: Discount factor gamma (0 at terminal states)
Returns: TDUpdateResult with new state, prediction, TD error, and metrics
Source code in src/alberta_framework/core/learners.py
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 | |
TDStream
¶
Bases: Protocol[StateT]
Protocol for TD experience streams.
TD streams produce (s, r, s', gamma) tuples for temporal-difference learning.
init(key)
¶
run_learning_loop(learner, stream, num_steps, key, learner_state=None, step_size_tracking=None, normalizer_tracking=None)
¶
Run the learning loop using jax.lax.scan.
This is a JIT-compiled learning loop that uses scan for efficiency. It returns metrics as a fixed-size array rather than a list of dicts.
Supports both plain and normalized learners. When the learner has a normalizer, metrics have 4 columns; otherwise 3 columns.
Args: learner: The learner to train stream: Experience stream providing (observation, target) pairs num_steps: Number of learning steps to run key: JAX random key for stream initialization learner_state: Initial state (if None, will be initialized from stream) step_size_tracking: Optional config for recording per-weight step-sizes. When provided, returns StepSizeHistory. normalizer_tracking: Optional config for recording per-feature normalizer state. When provided, returns NormalizerHistory with means and variances over time.
Returns: If no tracking: Tuple of (final_state, metrics_array) where metrics_array has shape (num_steps, 3) or (num_steps, 4) depending on normalizer If step_size_tracking only: Tuple of (final_state, metrics_array, step_size_history) If normalizer_tracking only: Tuple of (final_state, metrics_array, normalizer_history) If both: Tuple of (final_state, metrics_array, step_size_history, normalizer_history)
Raises: ValueError: If tracking interval is invalid
Source code in src/alberta_framework/core/learners.py
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 | |
run_learning_loop_batched(learner, stream, num_steps, keys, learner_state=None, step_size_tracking=None, normalizer_tracking=None)
¶
Run learning loop across multiple seeds in parallel using jax.vmap.
This function provides GPU parallelization for multi-seed experiments, typically achieving 2-5x speedup over sequential execution.
Supports both plain and normalized learners.
Args: learner: The learner to train stream: Experience stream providing (observation, target) pairs num_steps: Number of learning steps to run per seed keys: JAX random keys with shape (num_seeds,) or (num_seeds, 2) learner_state: Initial state (if None, will be initialized from stream). The same initial state is used for all seeds. step_size_tracking: Optional config for recording per-weight step-sizes. When provided, history arrays have shape (num_seeds, num_recordings, ...) normalizer_tracking: Optional config for recording normalizer state. When provided, history arrays have shape (num_seeds, num_recordings, ...)
Returns: BatchedLearningResult containing: - states: Batched final states with shape (num_seeds, ...) for each array - metrics: Array of shape (num_seeds, num_steps, num_cols) - step_size_history: Batched history or None if tracking disabled - normalizer_history: Batched history or None if tracking disabled
Examples:
import jax.random as jr
from alberta_framework import LinearLearner, IDBD, RandomWalkStream
from alberta_framework import run_learning_loop_batched
stream = RandomWalkStream(feature_dim=10)
learner = LinearLearner(optimizer=IDBD())
# Run 30 seeds in parallel
keys = jr.split(jr.key(42), 30)
result = run_learning_loop_batched(learner, stream, num_steps=10000, keys=keys)
# result.metrics has shape (30, 10000, 3)
mean_error = result.metrics[:, :, 0].mean(axis=0) # Average over seeds
Source code in src/alberta_framework/core/learners.py
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 | |
metrics_to_dicts(metrics, normalized=False)
¶
Convert metrics array to list of dicts for backward compatibility.
Args: metrics: Array of shape (num_steps, 3) or (num_steps, 4) normalized: If True, expects 4 columns including normalizer_mean_var
Returns: List of metric dictionaries
Source code in src/alberta_framework/core/learners.py
run_mlp_learning_loop(learner, stream, num_steps, key, learner_state=None, normalizer_tracking=None)
¶
Run the MLP learning loop using jax.lax.scan.
This is a JIT-compiled learning loop that uses scan for efficiency.
Args: learner: The MLP learner to train stream: Experience stream providing (observation, target) pairs num_steps: Number of learning steps to run key: JAX random key for stream and weight initialization learner_state: Initial state (if None, will be initialized from stream) normalizer_tracking: Optional config for recording per-feature normalizer state. When provided, returns NormalizerHistory.
Returns: If no tracking: Tuple of (final_state, metrics_array) where metrics_array has shape (num_steps, 3) or (num_steps, 4) If normalizer_tracking: Tuple of (final_state, metrics_array, normalizer_history)
Raises: ValueError: If normalizer_tracking.interval is invalid
Source code in src/alberta_framework/core/learners.py
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 | |
run_mlp_learning_loop_batched(learner, stream, num_steps, keys, learner_state=None, normalizer_tracking=None)
¶
Run MLP learning loop across multiple seeds in parallel using jax.vmap.
This function provides GPU parallelization for multi-seed MLP experiments, typically achieving 2-5x speedup over sequential execution.
Args: learner: The MLP learner to train stream: Experience stream providing (observation, target) pairs num_steps: Number of learning steps to run per seed keys: JAX random keys with shape (num_seeds,) or (num_seeds, 2) learner_state: Initial state (if None, will be initialized from stream). The same initial state is used for all seeds. normalizer_tracking: Optional config for recording normalizer state. When provided, history arrays have shape (num_seeds, num_recordings, ...)
Returns: BatchedMLPResult containing: - states: Batched final states with shape (num_seeds, ...) for each array - metrics: Array of shape (num_seeds, num_steps, num_cols) - normalizer_history: Batched history or None if tracking disabled
Examples:
import jax.random as jr
from alberta_framework import MLPLearner, RandomWalkStream
from alberta_framework import run_mlp_learning_loop_batched
stream = RandomWalkStream(feature_dim=10)
learner = MLPLearner(hidden_sizes=(128, 128))
# Run 30 seeds in parallel
keys = jr.split(jr.key(42), 30)
result = run_mlp_learning_loop_batched(learner, stream, num_steps=10000, keys=keys)
# result.metrics has shape (30, 10000, 3)
mean_error = result.metrics[:, :, 0].mean(axis=0) # Average over seeds
Source code in src/alberta_framework/core/learners.py
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 | |
run_td_learning_loop(learner, stream, num_steps, key, learner_state=None)
¶
Run the TD learning loop using jax.lax.scan.
This is a JIT-compiled learning loop that uses scan for efficiency. It returns metrics as a fixed-size array rather than a list of dicts.
Args: learner: The TD learner to train stream: TD experience stream providing (s, r, s', gamma) tuples num_steps: Number of learning steps to run key: JAX random key for stream initialization learner_state: Initial state (if None, will be initialized from stream)
Returns: Tuple of (final_state, metrics_array) where metrics_array has shape (num_steps, 4) with columns [squared_td_error, td_error, mean_step_size, mean_eligibility_trace]