Hierarchical RL: do fewer decisions mean arriving sooner?
层次强化学习
Expand skills into real actions, compute random duration and discounted exit models, and compare primitive, segmented and detouring plans.
hierarchical-rlHow many steps are hidden inside “go to the door”?
A navigation system can say “move right” at every step or “go to the door, then ask again.” The second interface reduces high-level calls without removing the intervening route. If a skill pauses, detours or fails, treating it as one ordinary action can misprice reward and time.
Hierarchical reinforcement learning organizes decisions at different levels. This article focuses on temporal abstraction: a high-level choice starts a closed-loop behavior lasting several steps, while its internal policy still reads the state at each step. It need not be a fixed action sequence or require a coarser state representation. The options framework
Our original example is a corridor from position 0 to 6. Moving right advances with probability 0.8 and otherwise stays put; moving left behaves similarly. An ordinary step earns −0.02, entering position 6 earns one, and discount is 0.9. A policy can move step by step or call “reach 3” followed by “reach 6.” Both take 7.5 environment steps on average, but require 7.5 versus two high-level decisions.
A single “reach the finish” skill can require just one call. Yet if it often moves left at position 2, it takes fifteen steps on average and has lower value. Fewer calls do not imply better task efficiency; that is why our example retains a poor skill.
A skill model needs a clock
An option has an initiation set, an internal policy and a termination probability. They specify where it is available, how to choose the next action and whether control returns to the higher level after arriving at a new state. Definition and termination order
Under this convention, execute at least one step before checking termination. An option that always ends after one step is a primitive action. A timeout depending on elapsed execution requires a clock in the state or a history-dependent semi-Markov option; it cannot silently be represented by termination based only on position.
Let τ be duration. Internal rewards are discounted by actual primitive steps, and continuation value is discounted by the realized execution time. Define the cumulative reward model r and discounted exit kernel K:
A row of K sums to expected gamma-to-duration, not one. It combines exit state and time; renormalizing it would discard time information. The paper calls this a multi-time model, and even a primitive action’s K already includes one discount factor. Equations 6–7
With a fixed option set, the high level obeys a semi-Markov Bellman equation:
There is no continuation value after the terminal state. When learning option Q-values directly from trajectories, a completed execution supplies the following target and update:
This is an option-level sample update. Our program instead estimates models and runs value iteration; those are not the same experimental procedure. A data-collection time limit is also not necessarily natural termination. The program raises an error if its guard is reached rather than fabricating a terminating sample.
A small state space allows exact models. Let C contain probabilities of reaching a nonterminal state and continuing the option after one step. Let E contain probabilities of terminating at each state after one step, and let rπ be expected one-step reward. For an option that terminates with finite expected duration:
B is the undiscounted exit distribution. Starting “reach 3” from zero takes 3/0.8=3.75 steps on average. Expected gamma-to-duration is approximately 0.676949, whereas gamma-to-mean-duration is approximately 0.673611. They differ. If duration and exit state are correlated, multiplying two marginal averages introduces another error.
Skills cannot create returns unavailable through underlying actions. A fixed skill set may restrict policies; including all primitive actions preserves the original choices. Restricted optimality
This concerns the optimal value of representable policies, not finite-sample learning speed. Skill acquisition, model estimation error and decision overhead still need separate accounting.
Skills can also be learned. Option-Critic mixes the value of continuing a skill with reselecting one, and learns internal policies and termination. The following arrival value explains the local direction of changing termination while Q and V are held fixed: Arrival value and termination gradients
When continuing is worse than reselecting, more termination helps locally. Full parameter gradients also involve visitation weights and value propagation; this partial derivative is not a complete trainer. All five internal policies in our program are handcrafted, not trained with Option-Critic.
Record value, environment steps and decisions separately
The code requires NumPy and connects three checkable calculations: exact option models, synchronous value iteration and models estimated from complete skill trajectories. Sampled models receive execution results only; exact models are used for comparison and evaluation, not inserted into sampled planning updates. Each initiation state is sampled separately, so this is a resettable generative experiment rather than learning from one continuous online trajectory.
"""Original stochastic corridor: exact and sampled semi-Markov option models."""
import json
import random
import numpy as np
GAMMA = .9
OPTIONS = {
'left': (tuple(range(6)), True, (0.,) * 6),
'right': (tuple(range(6)), True, (1.,) * 6),
'to_mid': ((0, 1, 2), False, (1.,) * 6),
'to_goal': ((3, 4, 5), False, (1.,) * 6),
'detour': (tuple(range(6)), False, (1., 1., .25, 1., 1., 1.)),
}
def transition(state, action):
if state not in range(6) or action not in (0, 1):
raise ValueError('Nonterminal state and binary action required')
nxt = min(6, state + 1) if action else max(0, state - 1)
return [(nxt, .8), (state, .2)]
def option_parameters(name):
initiation, single, right_probability = OPTIONS[name]
if not initiation or not set(initiation) <= set(range(6)) or len(right_probability) != 6:
raise ValueError('Invalid initiation or policy')
if any(not 0 <= p <= 1 for p in right_probability):
raise ValueError('Invalid intra-option probability')
beta = np.array([float(single or s not in initiation) for s in range(7)])
return initiation, right_probability, beta
def exact_model(name, gamma=GAMMA):
if not 0 <= gamma < 1:
raise ValueError('Discount must be in [0,1)')
initiation, right, beta = option_parameters(name)
p = np.zeros((6, 7))
for s in range(6):
for action, pa in enumerate((1 - right[s], right[s])):
for nxt, chance in transition(s, action):p[s, nxt] += pa * chance
continuation = p[:, :6] * (1 - beta[:6])
exit_kernel = p * beta
if max(abs(np.linalg.eigvals(continuation))) >= 1 - 1e-12:
raise ValueError('This option can fail to terminate')
reward = p @ np.array([-.02] * 6 + [1.])
discounted = np.eye(6) - gamma * continuation
return dict(initiation=initiation,
reward=np.linalg.solve(discounted, reward),
kernel=np.linalg.solve(discounted, gamma * exit_kernel),
exit=np.linalg.solve(np.eye(6) - continuation, exit_kernel),
duration=np.linalg.solve(np.eye(6) - continuation, np.ones(6)))
def rollout(name, start, rng, gamma=GAMMA):
initiation, right, beta = option_parameters(name)
if start not in initiation or not 0 <= gamma < 1:
raise ValueError('Option unavailable or invalid discount')
state, total = start, 0.
for duration in range(1, 10001):
action = int(rng.random() < right[state])
outcomes = transition(state, action)
nxt = outcomes[0][0] if rng.random() < .8 else state
total += gamma ** (duration - 1) * (1. if nxt == 6 else -.02)
state = nxt
if beta[state] == 1:return total, gamma ** duration, state, duration
raise RuntimeError('Guard reached; never silently treat timeout as termination')
def sample_model(name, samples, rng):
if not isinstance(samples, int) or samples < 1:raise ValueError('Positive samples required')
initiation, _, _ = option_parameters(name)
reward, kernel = np.zeros(6), np.zeros((6, 7))
duration, steps = np.zeros(6), 0
for s in initiation:
for _ in range(samples):
r, discount, end, elapsed = rollout(name, s, rng)
reward[s] += r / samples;kernel[s, end] += discount / samples
duration[s] += elapsed / samples;steps += elapsed
return dict(initiation=initiation, reward=reward, kernel=kernel,
duration=duration, real_steps=steps, option_runs=samples * len(initiation))
def plan(models, tolerance=1e-12):
values = np.zeros(7)
for sweeps in range(1, 10001):
updated = np.zeros(7);policy = []
for s in range(6):
candidates = [(m['reward'][s] + m['kernel'][s] @ values, name)
for name, m in models.items() if s in m['initiation']]
if not candidates:raise ValueError('State has no available option')
value, name = max(candidates, key=lambda pair: pair[0])
updated[s] = value;policy.append(name)
if np.max(np.abs(updated - values)) < tolerance:return updated, policy, sweeps
values = updated
raise RuntimeError('Value iteration did not converge')
def evaluate(policy, models):
rewards = np.array([models[o]['reward'][s] for s, o in enumerate(policy)])
kernel = np.array([models[o]['kernel'][s, :6] for s, o in enumerate(policy)])
exits = np.array([models[o]['exit'][s, :6] for s, o in enumerate(policy)])
duration = np.array([models[o]['duration'][s] for s, o in enumerate(policy)])
values = np.linalg.solve(np.eye(6) - kernel, rewards)
if max(abs(np.linalg.eigvals(exits))) >= 1 - 1e-12:
return dict(value=float(values[0]),expected_steps=None,expected_decisions=None)
steps = np.linalg.solve(np.eye(6) - exits, duration)
decisions = np.linalg.solve(np.eye(6) - exits, np.ones(6))
return dict(value=float(values[0]),expected_steps=float(steps[0]),expected_decisions=float(decisions[0]))
def experiment(seed=0, samples=32):
exact = {o: exact_model(o) for o in OPTIONS}
variants = {'primitive': ['left','right'], 'segments': ['to_mid','to_goal'],
'augmented': ['left','right','to_mid','to_goal'], 'restricted': ['detour']}
comparisons = {}
for name, names in variants.items():
model = {o:exact[o] for o in names};values, policy, sweeps = plan(model)
comparisons[name] = dict(evaluate(policy, exact),policy=policy,sweeps=sweeps)
rng = random.Random(seed)
learned = {o:sample_model(o, samples, rng) for o in variants['augmented']}
predicted, policy, sweeps = plan(learned)
return dict(seed=seed,samples_per_option_start=samples,exact=comparisons,
learned=dict(evaluate(policy,exact),predicted=float(predicted[0]),policy=policy,sweeps=sweeps),
real_steps=sum(m['real_steps'] for m in learned.values()),
option_runs=sum(m['option_runs'] for m in learned.values()),
segment_duration=float(exact['to_mid']['duration'][0]),
segment_discount=float(exact['to_mid']['kernel'][0].sum()),
discount_at_mean_duration=float(GAMMA ** exact['to_mid']['duration'][0]))
if __name__ == '__main__':
print(json.dumps(experiment(), indent=2))
Inspect the recorded summary
{
"seed": 0,
"samples_per_option_start": 32,
"exact": {
"primitive": {
"value": 0.41101321165722227,
"expected_steps": 7.5,
"expected_decisions": 7.5,
"policy": [
"right",
"right",
"right",
"right",
"right",
"right"
],
"sweeps": 28
},
"segments": {
"value": 0.4110132116572221,
"expected_steps": 7.5,
"expected_decisions": 2.0,
"policy": [
"to_mid",
"to_mid",
"to_mid",
"to_goal",
"to_goal",
"to_goal"
],
"sweeps": 3
},
"augmented": {
"value": 0.41101321165722227,
"expected_steps": 7.5,
"expected_decisions": 5.999999999999999,
"policy": [
"right",
"right",
"right",
"right",
"to_goal",
"right"
],
"sweeps": 3
},
"restricted": {
"value": 0.16216967870091356,
"expected_steps": 15.000000000000005,
"expected_decisions": 1.0,
"policy": [
"detour",
"detour",
"detour",
"detour",
"detour",
"detour"
],
"sweeps": 2
}
},
"learned": {
"value": 0.41101321165722227,
"expected_steps": 7.5,
"expected_decisions": 7.5,
"predicted": 0.430127744822518,
"policy": [
"right",
"right",
"right",
"right",
"right",
"right"
],
"sweeps": 25
},
"real_steps": 875,
"option_runs": 576,
"segment_duration": 3.75,
"segment_discount": 0.676948970560497,
"discount_at_mean_duration": 0.6736113720383118
}| Scheme | True start value | Expected environment steps | Expected high-level decisions |
|---|---|---|---|
| Primitive left/right | 0.411013 | 7.5 | 7.5 |
| Reach 3, then reach 6 | 0.411013 | 7.5 | 2.0 |
| Detouring skill only | 0.162170 | 15.0 | 1.0 |
Exact augmented planning also permits primitive actions and preserves optimal value. Among equal-valued choices, the program does not additionally minimize decision count. A particular combination selected through floating-point ties is not a strict efficiency advantage. Synchronous sweep counts also omit skill-model construction cost.
Below are model-predicted values for all eight seeds at three sampling budgets. Each cell represents a selected policy after resettable collection and planning. All twenty-four policies have exact true value about 0.411013, so prediction errors can be checked directly.
| Seed | 8 runs per initiation pair | 32 runs per initiation pair | 128 runs per initiation pair |
|---|---|---|---|
| 0 | 0.44073 | 0.43013 | 0.41086 |
| 1 | 0.43780 | 0.42518 | 0.42140 |
| 2 | 0.44505 | 0.42827 | 0.41907 |
| 3 | 0.48125 | 0.45024 | 0.40952 |
| 4 | 0.41723 | 0.42552 | 0.42174 |
| 5 | 0.45624 | 0.45355 | 0.42464 |
| 6 | 0.42615 | 0.42392 | 0.41858 |
| 7 | 0.42424 | 0.42676 | 0.41421 |
The augmented set has eighteen legal state-option initiation pairs, so budget N gives 18N executions. With N=32 and seed 0, 576 option executions consume 875 actual environment steps; they are not 576 environment samples. The three budgets consume 1747, 6912 and 27788 total environment steps across eight seeds, with mean absolute value errors about 0.030074, 0.021933 and 0.006901. Lower aggregate error is not a per-seed monotonic guarantee; the 128-run budget retains underestimates too.
Dense linear solves cost about O(S³) per exact option model. A planning sweep costs about O(S²O), with O(S²O) model storage. Sampling cost depends on total realized duration, not just call count. Fewer high-level decisions here do not shorten the physical route or establish general training acceleration.
When do skills become restrictions?
A poor skill can complicate an easy task. If the high level must wait for termination, it cannot change its mind mid-execution. States needing precise intervention may become inaccessible through coarse skills. Keeping primitives restores expressive choices but does not ensure finite exploration finds them.
Skill models depend on internal policies and termination rules. When those change during learning, old r and K may no longer describe a stable interface. Nested execution also requires tracking the active skill; a flattened policy observing only the original environment state need not be Markov. Composition and history dependence
Specifying subgoals, learning internal behavior and learning when to stop are distinct problems. Immediate termination, prolonged execution or duplicate skill behaviors can make nominal hierarchy unhelpful. This program checks termination, discounting and planning, not complex skill discovery, transfer or robot control.
Include the clock in your answer
-
An option receives rewards zero, zero and one, then naturally terminates the episode after three steps. With gamma 0.9, what is the target?
Answer: It is 0+0.9×0+0.9²×1=0.81, without terminal bootstrap. If only the option ended while the environment continued, add 0.9³ times continuation value.
-
Traversing three cells takes 3.75 steps on average. Why not multiply continuation value by 0.9^3.75?
Answer: Compute discount from each realized duration before averaging. Here E[0.9^τ]≈0.676949 while 0.9^Eτ≈0.673611. Applying an exponential and taking an expectation generally do not commute.
-
Is one call to the detouring skill more efficient than two segmented calls?
Answer: It uses fewer calls, but takes fifteen rather than 7.5 environment steps and returns 0.162170 rather than 0.411013. Specify the resource and task metric instead of selecting one favorable count.
-
Can you make “reach 3” terminate after five execution steps merely by changing position-dependent beta?
Answer: No. The same position could occur at step one or five with different stopping decisions. Add elapsed time to the state or define a history-dependent option and rebuild its model. A collection guard cannot impersonate this deliberately specified termination rule.
From fixed skills to learned skills
Options place primitive actions and extended closed-loop behavior in one value framework; first inspect time, internal rewards and the exit interface. Original framework Option-Critic then learns internal policies and termination. Align call-and-return execution, initiation-everywhere assumptions and arrival-based termination gradients when reading it. Fixed preprint version
The exact model here is a measuring tool, not a capability available in every environment. In an unknown visual environment, locate data costs and model error before deciding whether the high-level interface saves the resource you care about.
Make a prediction, then check
How should continuation value be discounted after an option lasting τ steps?
Learning objectives
- Define initiation, intra-option policy and termination, and derive reward and discounted exit models for random durations.
- Run exact and sampled semi-Markov planning and separate high-level decisions, environment steps and model construction cost.
Prerequisites & connections
Explore related knowledge →References
- Between MDPs and semi-MDPs: A framework for temporal abstraction in reinforcement learning — scoped journal copy
Richard S. Sutton; Doina Precup; Satinder Singh · 1999 - The Option-Critic Architecture — scoped arXiv v2
Pierre-Luc Bacon; Jean Harb; Doina Precup · 2016
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-24 · Single AI author. Scoped reading: Artificial Intelligence112:181–211;31-page journal copy hosted by UMass. Read6/7/9/10/11 and viewed9: initiation/arrival termination, multi-time models and option value iteration. K is a discounted exit kernel, not ordinary probability. Author old site returned502; not a complete proof/experimental audit. v2 dated2016-12-03,9 pages; read2–3 and850 identity characters on page1. Call-and-return, arrival value, intra-option/termination gradients and initiation-everywhere assumption. No full appendix or training reproduction; preprint date is not a conference date. Seven paired equations and four explained exercises. Initiation, termination after at least one step and discounted exit kernels checked by geometric duration and primitive Bellman identities. All24 sampled models retain signed prediction errors; model construction and decision counts separated. Restricted options lose value. Not an Option-Critic training reproduction.
- Initiation, termination after at least one step and discounted exit kernels checked by geometric duration and primitive Bellman identities. All24 sampled models retain signed prediction errors; model construction and decision counts separated. Restricted options lose value. Not an Option-Critic training reproduction.
- Four computed SVG variants per topic;10 numeric/geometry tests and18 current responsive cases passed. All nine selected current captures directly viewed; no figure failure or post-capture asset edit in this group. Actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.
Source locations checked:
- Between MDPs and semi-MDPs: A framework for temporal abstraction in reinforcement learning — scoped journal copy · Artificial Intelligence112:181–211;31-page journal copy hosted by UMass. Read6/7/9/10/11 and viewed9: initiation/arrival termination, multi-time models and option value iteration. K is a discounted exit kernel, not ordinary probability. Author old site returned502; not a complete proof/experimental audit.
- The Option-Critic Architecture — scoped arXiv v2 · v2 dated2016-12-03,9 pages; read2–3 and850 identity characters on page1. Call-and-return, arrival value, intra-option/termination gradients and initiation-everywhere assumption. No full appendix or training reproduction; preprint date is not a conference date.
Related topics