1. Home
  2. Explore
  3. Computer Science
  4. Automata Theory and Reinforcement Learning

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Automata Theory and Reinforcement Learning

Formal Languages, Reward Machines, and Reinforcement Learning

Reinforcement learning and reward specification

Reinforcement learning (RL) trains an agent to choose actions that maximize expected cumulative reward. In model-free RL, the agent knows which actions it can take but does not know the environment’s transition dynamics or reward function in advance. It learns through trial and error:

  1. The agent takes an action.

  2. The environment returns a new state and a reward.

  3. The agent uses this experience to improve its action choices.

A policy maps states to actions or action distributions. In a basic approach such as Q-learning, the agent learns a value Q(s,a)Q(s,a)Q(s,a) for each state–action pair, representing the expected quality of taking action aaa in state sss. A typical update is

Q(s,a)←Q(s,a)+α[r+γmax⁡a′Q(s′,a′)−Q(s,a)],Q(s,a) \leftarrow Q(s,a) + \alpha \left[r + \gamma \max_{a'} Q(s',a') - Q(s,a)\right],Q(s,a)←Q(s,a)+α[r+γmaxa′​Q(s′,a′)−Q(s,a)],

where rrr is the observed reward, s′s's′ is the resulting state, α\alphaα is the learning rate, and γ\gammaγ is the discount factor. The agent generally selects the action with the highest learned value.

Why complex reward functions are difficult

An RL agent does not inherently know which behaviors are desirable. A designer must provide a reward function, often as a mapping from a state or state transition to a scalar reward. Designing that function for a complex task can be difficult:

  • A task may involve several actions that must occur in a particular order.

  • Some actions may be conditional on the environment or on earlier events.

  • Reward may be appropriate only after an entire sequence is completed.

  • Partial completion may deserve no reward—or may even be undesirable.

For example, a household agent might be asked to retrieve ice cream, serve it, return it to the freezer, and close the freezer door. Rewarding only the first few actions could encourage the agent to leave the freezer open. A suitable reward must distinguish a completed sequence from an incomplete one.

Such tasks are temporally extended: whether an action is good can depend on what happened earlier and what must happen later. Encoding this behavior as a simple state-based reward can require substantial manual effort.

Sample efficiency

Many RL tasks provide little or no feedback until a long sequence of actions has been completed. This creates a sparse reward problem: the agent may experience many transitions with reward zero before it encounters a successful outcome. Learning can then require a very large number of interactions with the environment.

Two central challenges are therefore:

  • Reward specification: expressing complex desired behavior clearly and accurately.

  • Sample efficiency: learning effective behavior with fewer interactions.

Real-world tasks can add further complications, including safety constraints, partial observability, underspecified rewards, and the need to explain learned policies.


Formal languages for expressing temporal behavior

A formal language offers a structured way to describe which sequences of events count as successful behavior. Linear temporal logic (LTL) is a propositional logic with temporal operators: it describes properties of traces, or sequences of events over time. Depending on the variant, traces may be finite or infinite.

LTL combines ordinary logical connectives such as conjunction, disjunction, and negation with temporal operators. Common operators include:

  • Next, often written ◯ϕ\bigcirc \phi◯ϕ: ϕ\phiϕ must hold at the next step.

  • Until, often written ϕUψ\phi \mathbin{\mathcal{U}} \psiϕUψ: ϕ\phiϕ must hold until ψ\psiψ becomes true.

  • Eventually, often written ◊ϕ\Diamond \phi◊ϕ: ϕ\phiϕ must become true at some point.

  • Always, often written □ϕ\Box \phi□ϕ: ϕ\phiϕ must remain true at all times.

  • Release, another temporal operator expressible through the other operators.

For example, the requirement “never vacuum while someone is sleeping” can be represented as

□(sleeping→¬vacuuming).\Box(\text{sleeping} \rightarrow \neg \text{vacuuming}).□(sleeping→¬vacuuming).

An ice-cream task can be expressed as a sequence of temporal requirements: after the task is initiated, the agent must eventually open the freezer, then remove the ice cream, then serve it, and then return it and close the freezer. The key point is that the whole trace matters; rewarding only one action in the sequence would not capture the intended task.

LTL and other formal languages are valuable in verification, synthesis, and planning. A particularly useful property is that many such specifications can be translated into automata. The resulting automaton tracks which part of the specification has been satisfied so far. This connection between language and automata is central to using temporal structure in RL.


Reward machines

A reward machine (RM) is an automata-based representation of a reward function. It makes temporal structure explicit rather than hiding it inside a black-box reward mapping.

A reward machine contains:

  • A finite set of machine states, including an initial state.

  • Transitions between machine states.

  • A logical guard on each transition, describing the event or condition that causes the transition.

  • A reward associated with the transition or machine state.

  • Optionally, terminal states. A machine intended to operate indefinitely may have no terminal states.

The reward machine reads events or propositions detected in the environment. Its state records relevant history. Thus, a reward that depends on what happened earlier can be made Markovian by including the reward-machine state along with the environment state.

Vocabulary and event detectors

The propositions used by a reward machine form its vocabulary. In an office-like environment, the vocabulary might include events or properties such as:

  • Visiting locations AAA, BBB, CCC, and DDD.

  • Being at a coffee station, mail room, or office.

  • Hitting fragile furniture.

These propositions may be detected from the environment state. A human-readable vocabulary helps a person specify and inspect the task. In some settings, the relevant vocabulary or detectors may themselves be learned.

Example: visiting locations in order

Suppose the task is to visit AAA, then BBB, then CCC, then DDD. A reward machine can use states U0,U1,U2,U3U_0,U_1,U_2,U_3U0​,U1​,U2​,U3​ to record progress:

  • U0U_0U0​ represents that the agent has not yet visited AAA.

  • Visiting AAA moves the machine to U1U_1U1​.

  • Visiting BBB next moves it to U2U_2U2​.

  • Visiting CCC next moves it to U3U_3U3​.

  • Visiting DDD next completes the sequence and gives a reward.

The machine state therefore remembers how far the agent has progressed, even if the environment’s current state does not.

Example: task completion and safety

A reward machine can also represent tasks such as delivering coffee to an office while avoiding fragile objects. It can track whether the agent has collected coffee and whether it has reached the office. A collision with furniture can send the machine to a sink state that remains active thereafter and yields no reward.

For tasks requiring multiple items, the machine can permit either collection order. For example, if the agent must deliver both coffee and mail, it can move through states that record which items have been collected, without requiring coffee to be collected before mail or vice versa.

Non-Markovian rewards made Markovian

A reward is non-Markovian when the reward for the current action depends on the history, not just on the current environment state and action. In the ordered-location example, moving into DDD might yield a reward of one if the agent has already visited AAA, BBB, and CCC, but zero otherwise.

The physical move is the same, but the reward differs according to the reward-machine state. A reward machine explicitly stores that relevant history. Taking the product of the environment state with the reward-machine state yields an augmented state representation in which the reward can be treated as Markovian.

A reward machine makes a temporally extended reward function explicit by tracking progress through an automaton and associating rewards with guarded transitions.


Exploiting reward-machine structure in learning

Once the reward function is represented by a reward machine and provided to the agent, learning algorithms can use its structure directly. The agent is no longer limited to discovering the entire task only through sparse external feedback.

Product-state Q-learning

A direct baseline constructs a product of the environment state and the reward-machine state, then applies ordinary Q-learning to the resulting augmented MDP. This handles history-dependent rewards because the reward-machine state is part of the augmented state.

However, the product construction alone does not necessarily exploit all the learning opportunities available in the reward-machine structure.

Hierarchical reinforcement learning

Hierarchical reinforcement learning (HRL) learns options: temporally extended actions or subpolicies that can be composed to solve a larger task. A meta-controller selects which option to use.

For a task whose reward machine mentions locations AAA, BBB, CCC, and DDD, an HRL system might learn a separate option for reaching each location. It must also learn how to sequence those options.

HRL can decompose a complex task into subproblems, but this decomposition may be myopic. Each option can be optimized for its own immediate subgoal without accounting fully for how its choice affects later parts of the task.

For example, an agent delivering coffee may choose between two coffee stations. One station may be easier to reach, making it locally optimal for the “get coffee” option. Yet that station may leave a long route to the office. A different station may take longer to reach initially but yield a shorter overall delivery route. Optimizing each subtask independently can therefore produce a suboptimal total policy.

Reward-machine-based pruning can improve HRL’s meta-controller: the current machine state indicates which subgoal or option is relevant. For example, if the machine is in the state where the next required event is visiting BBB, options unrelated to reaching BBB can be excluded. This can make learning more efficient, although it does not remove the possibility of myopic suboptimality.

Q-learning for reward machines (QRM)

QRM exploits reward-machine states to learn separate value functions for the different machine states. If the machine has states U0,U1,…U_0,U_1,\ldotsU0​,U1​,…, QRM learns a corresponding value function for each one.

At any moment, the agent chooses actions using the value function associated with its current reward-machine state. The central idea, however, is broader: QRM uses each experience to update value functions for multiple reward-machine states, not only the one the agent actually occupied.

This is a form of off-policy learning and counterfactual reasoning. From an observed environment transition, the learner asks what would have happened if the reward machine had instead been in another state.

For each machine state uuu, let u′u'u′ be the state reached by applying the observed event to the machine, and let rur_uru​ be the reward associated with that transition. An update can be written schematically as

Qu(s,a)←Qu(s,a)+α[ru+γmax⁡a′Qu′(s′,a′)−Qu(s,a)].Q_u(s,a) \leftarrow Q_u(s,a) + \alpha\left[r_u + \gamma \max_{a'}Q_{u'}(s',a') - Q_u(s,a)\right].Qu​(s,a)←Qu​(s,a)+α[ru​+γmaxa′​Qu′​(s′,a′)−Qu​(s,a)].

The actual environment transition (s,a,s′)(s,a,s')(s,a,s′) can therefore contribute to several machine-state value functions. For instance, if moving to DDD would produce reward one from machine state U3U_3U3​, but reward zero from U0U_0U0​, the same observed move can update both cases differently.

This reuse of experience is a major source of QRM’s sample-efficiency advantage. It is especially helpful when the task can be decomposed into multiple reward-machine states but rewards are otherwise sparse.

A related variant, counterfactual reward machines (CRM), was described as an improvement that learns one larger policy rather than separate policies. It is intended to support better generalization while retaining or improving the observed performance of QRM.

Optimality and assumptions

In tabular settings, ordinary Q-learning has convergence guarantees under standard conditions, including adequate exploration and appropriate learning rates. The reward-machine-based Q-learning approaches preserve the relevant tabular optimality guarantees while using the machine structure to improve learning efficiency.

These guarantees do not automatically extend to deep function approximation. When Q-values are represented by neural networks or other function approximators, the theoretical conditions for tabular convergence no longer apply in the same way.


Reward shaping

Reward shaping adds intermediate guidance to an otherwise sparse reward function. If an agent receives a reward only after completing a long task, shaping can distribute useful feedback along the route, making progress easier to learn.

A standard potential-based shaping method augments a reward with a term of the form

F(s,s′)=γΦ(s′)−Φ(s),F(s,s')=\gamma\Phi(s')-\Phi(s),F(s,s′)=γΦ(s′)−Φ(s),

where Φ\PhiΦ is a potential function over states. Under the relevant assumptions, this form of shaping changes the learning signal while preserving the optimal policies for the original reward.

For reward machines, shaping can be applied to the rewards associated with machine transitions. The shaping values can be derived from values over the reward-machine structure, for example by applying value iteration to determine intermediate guidance. The agent then learns with the shaped machine.

Shaping can make it more likely that the agent receives informative feedback before reaching the final state of a temporally extended task. In experiments, it improved learning on some discrete tasks. However, shaping did not help in every setting: in the continuous-state experiment described in the talk, it hindered QRM rather than improving it. The result indicates that shaping’s effectiveness depends on the task and representation; intermediate rewards are not guaranteed to improve learning in all environments.

More general reward machines may associate transitions with reward functions rather than just constant scalar values. In continuous domains, such functions can provide more finely tailored feedback than a single reward at the end of a subtask.


Empirical findings

The approaches were evaluated in discrete domains and a continuous domain. The main comparison included ordinary Q-learning, HRL, HRL with reward-machine-based pruning, QRM, and QRM with reward shaping.

Discrete office tasks

In an office-like grid environment, the agent had to satisfy ordered or otherwise temporally extended tasks. Performance was measured by normalized discounted reward, with the optimal value normalized to one.

QRM reached the optimal policy substantially faster than ordinary Q-learning. HRL methods also made progress, but their performance could plateau at suboptimal policies, consistent with the possibility that locally optimal options do not compose into a globally optimal solution. Ordinary Q-learning improved more slowly because it had to discover sparse, temporally extended reward patterns without exploiting the task structure.

Craft-style tasks

A second discrete domain involved collecting and combining objects—for example, gathering resources and making tools. Across a range of tasks and maps:

  • QRM reached optimal reward relatively quickly.

  • HRL methods benefited from task decomposition but could converge to suboptimal behavior.

  • Ordinary Q-learning made little progress within the tested interaction budget.

The contrast highlights the value of representing task structure explicitly when success requires a sequence of events.

Continuous-state tasks

A continuous-state domain used a moving agent and moving objects of different colors. Tasks involved ordered requirements, such as hitting objects in a particular sequence while avoiding another color.

With deep value-function approximation:

  • Deep QRM performed best among the compared methods.

  • Deep HRL methods performed better than the deep Q-learning baseline.

  • Ordinary deep Q-learning performed poorly.

  • The earlier tabular optimality guarantees did not apply to these function-approximation experiments.

Reward shaping helped in some discrete results but did not improve the continuous-domain results and could hinder learning.


Constructing reward machines

Reward machines can be obtained in several ways. They do not need to be written directly by a person.

Translation from formal specifications

A task can be specified in a language such as a regular language or a suitable fragment of LTL and then translated into an automaton-based representation. A reward machine can serve as a normal form: different specification languages can be translated into a shared structure, allowing algorithms that operate on reward machines to be reused across those languages.

This avoids developing a separate learning algorithm for every possible specification language. The underlying connection between regular languages and finite-state automata makes such translations possible for suitable languages and variants of temporal logic.

Symbolic planning from high-level goals

A person may provide a high-level goal, such as asking a robot to retrieve an object, without specifying a reward machine or a detailed sequence of low-level actions. A symbolic planner can use a high-level model of the world to produce a plan or intermediate waypoints. Those steps can populate a reward machine, which then provides a richer learning signal for RL.

This approach can guide learning when a direct high-level reward would be too sparse. It can also allow learned behavior or existing policies to be adapted to new tasks.

Learning reward machines

Reward machines can also be learned from experience. In the partially observable approach described below, the agent was given high-level binary classifiers or event detectors—for example, detectors for whether a button had been pressed or whether a cookie was present—but did not begin with a reward machine. The machine was learned through discrete optimization, using tabu search.


Partial observability and memory

In a partially observable environment, the agent cannot directly observe the complete state of the world. A visual agent, for example, may only see the current camera view. Relevant information may disappear from view as the agent moves.

One standard response is to maintain a belief state: a representation of what the agent thinks the hidden state might be. Another is to use history—the sequence of observations and actions—to inform decisions. In either case, memory is needed when the correct action depends on past events that are not visible now.

Reward-machine state as memory

A reward machine can function as an explicit memory state. It records a compact summary of history relevant to the task. The policy can then depend on both the current observation and the reward-machine state.

Consider an environment with three rooms and a corridor. A button in one room causes a cookie to appear in one of two other rooms, but the agent cannot see into those rooms from the corridor. The agent must remember whether it has pressed the button, which room it has checked, whether it found and ate a cookie, and which room it should search next.

At the same corridor junction, the correct action can differ depending on this history. The reward-machine state distinguishes these cases, enabling the agent to act appropriately despite having the same current observation.

The learned machine can also be interpretable: its states and transitions reveal which events it tracks and how its decisions depend on them. It can therefore provide both a memory mechanism and a human-inspectable description of task progress.

Learning performance

The example was difficult for several deep RL methods that used recurrent networks such as LSTMs. Learning a reward machine and combining it with Q-learning or QRM solved the task effectively, showing that an explicit automaton can provide useful memory for partially observable tasks.

This approach assumes access to suitable event detectors; it does not necessarily learn the entire perceptual vocabulary from raw observations. Learning the vocabulary and the reward machine together remains a distinct challenge.


Limitations and open considerations

Hierarchical suboptimality

HRL’s decomposition can improve learning, but independently optimizing options can lead to a poor overall policy. A locally efficient subgoal strategy may make later goals harder. Goal-conditioned options or methods that give the controller more lookahead may help account for future subtasks, but guarantees on the degree of suboptimality require further analysis.

Automaton size

Translating a high-level temporal specification into an automaton can cause significant growth in the number of states. Some translations from LTL can be exponentially larger than the original formula, and learning cost may grow with the number of reward-machine states.

Possible approaches to managing this include:

  • Working directly with temporal formulas and progressing them as events are observed.

  • Using nondeterministic or alternating automata where appropriate.

  • Simplifying or decomposing specifications.

  • Using lifted representations to avoid enumerating all combinations.

  • Exploring hierarchical abstract machines or multi-level representations.

The choice of representation involves a trade-off: richer specification languages are convenient, but the automata they produce may be larger.

Reuse, adaptation, and human feedback

A learned reward machine may be interpretable and editable, but adapting it to a new task raises questions about how much must be relearned. Useful capabilities include reusing previously learned components, adding states or transitions, and accepting expert feedback without restarting learning from scratch.

The potential for editing automata is valuable beyond RL. Interpretable automata can also represent sequential classifiers and other functions, enabling inspection, verification, or targeted modification when the vocabulary is meaningful to a human.

Demonstrations and inverse reinforcement learning

Expert demonstrations can provide traces of desired behavior. Learning a reward machine from traces is related to inverse reinforcement learning, but the learning objective can include more than identifying which behavior is rewarded. A learner may also need a predictive model of relevant environment dynamics so that the representation supports effective decision-making.

Noisy demonstrations, sequential classification, and learning temporal rules from traces are related problems. Automata provide a structured output representation for these tasks, though the exact learning method depends on the assumptions about the demonstrations and observations.


Core takeaways

  • Temporally extended tasks are difficult to express with simple state-based rewards because success can depend on event order, history, and task completion.

  • Formal languages such as LTL provide precise ways to describe temporal behavior, and automata can track progress through those descriptions.

  • Reward machines represent reward functions as guarded automata, making task structure explicit and rendering many history-dependent rewards Markovian in an augmented state.

  • QRM uses reward-machine structure to learn value functions for multiple machine states and reuses experiences through counterfactual, off-policy updates.

  • HRL can decompose tasks into options, but independently optimal options may combine into a suboptimal overall policy.

  • Reward shaping can supply intermediate guidance and preserve the original optimal policy under suitable conditions, but its empirical effect depends on the domain.

  • Reward machines can be specified directly, translated from formal languages, generated from symbolic plans, or learned from experience.

  • In partially observable tasks, a reward-machine state can serve as an interpretable, task-focused form of memory.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent