Automata Theory and Reinforcement Learning
Reward Machines: Using Formal Languages to Make Reinforcement Learning More Efficient
1. The central challenge: telling an agent what to do
A reinforcement-learning agent learns through experience. It takes an action, observes what happens, and receives a reward signal from the environment. Over time, it tries to learn a policy: a rule for choosing actions in different situations so that its total expected reward is as high as possible.
In model-free reinforcement learning, the agent does not begin with a complete model of how the environment works. It may know which actions are available, but it does not know the transition probabilities or the reward function. It must learn by acting and observing—much like someone navigating an unfamiliar building without a map or instructions.
A common approach is Q-learning. It estimates the quality of taking action a in state s, written Q(s,a). An action’s estimated quality depends on the reward received now and the value of what the agent expects to achieve later. A standard update is:
Q(s,a)←Q(s,a)+α[r+γa′maxQ(s′,a′)−Q(s,a)]Here, r is the reward just received, s′ is the resulting state, α is the learning rate, and γ is the discount factor. The learning rate controls how strongly new experience changes the current estimate; the discount factor controls how much future rewards matter. Once the estimates improve, the agent can choose the action with the highest estimated value in its current state.
The difficulty is that the agent needs a reward function that captures the task. For simple tasks, this may be easy. For complex behavior, it can be surprisingly hard. A household robot might need to retrieve ice cream, serve it, return the container to the freezer, and close the freezer door. Rewarding the robot merely for reaching the ice cream could encourage it to leave the freezer open. The desired behavior is a sequence, not a single destination.
Complex task descriptions often have three properties:
- They extend over time: Success depends on a sequence of events.
- They are conditional: What should happen next depends on what has happened already.
- They include constraints: Some actions must not occur in certain situations.
For example, a robot might be asked to run a dishwasher when it is full or when dishes are needed for a meal; check bath temperature immediately before someone enters; or avoid vacuuming while someone in the home is asleep. These instructions are much richer than a single reward attached to a state.
A central problem in reinforcement learning is that a human often has to translate a rich task into a reward signal that is simple enough for an agent to learn from.
Sparse rewards make the problem harder. If the agent receives a reward only after completing a long sequence, it may spend many interactions exploring without learning which actions were useful. The goal of using formal languages and automata is to represent the task structure explicitly, so the agent can use that structure during learning.
Think About It: Why might a robot that receives a reward for reaching the ice cream fail to learn to close the freezer afterward?
2. Temporal logic: expressing tasks over time
Linear temporal logic, or LTL, is a formal language for describing how propositions should hold across a sequence of events. A proposition might mean “the agent is at location A,” “the button has been pressed,” or “a cookie is present.”
LTL combines ordinary logical connectives such as “and,” “or,” and “not” with temporal operators. Common operators include:
- Next: A condition must hold at the next point in the sequence.
- Eventually: A condition must hold at some later point.
- Always: A condition must hold at every point.
- Until: One condition must continue to hold until another condition becomes true.
- Release: A temporal operator related to “until” that can express continuing constraints.
These operators make it possible to describe tasks that depend on order and time. “Never vacuum while someone is sleeping” can be expressed as an always-enforced restriction: whenever someone is sleeping, vacuuming must not occur. “Visit A, then B, then C, then D” describes an ordered task in which reaching each location advances the task.
LTL is useful in verification and synthesis because a formula can be checked against a sequence of events, or trace, to determine whether the sequence satisfies the specification. Depending on the logic variant and whether traces are finite or infinite, an LTL formula can be translated into an automaton. The automaton has states that record how much of the specification has been satisfied so far.
That translation suggests a bridge between formal specifications and reinforcement learning. Instead of treating the reward function as an opaque program, the task can be represented by an automaton whose states make its progress visible.
3. Reward machines: representing reward structure as an automaton
A reward machine is an automaton-based representation of a reward function. Its states track the task’s progress, and its transitions are triggered when relevant propositions become true. Each transition is associated with a reward or, in a more general form, a reward function.
A reward machine can be understood through four ingredients:
- A vocabulary of propositions. These describe meaningful events or properties, such as visiting a location, finding coffee, or encountering an obstacle.
- A set of machine states. Each state represents a stage in the task.
- An initial state. This represents the task before any progress has been made.
- Transitions and rewards. A logical condition determines when a transition occurs, and the transition supplies the relevant reward.
A simple reward machine can be a Mealy-machine-like structure: its response depends on the current machine state and the input events. In a more general reward machine, the transitions can be associated with reward functions rather than only fixed scalar rewards. Some machines have terminal states; others have no terminal state and continue to operate indefinitely.
A sequential office task
Consider an office environment with locations A, B, C, and D, as well as coffee stations, a mail room, an office, and fragile furniture. Suppose the task is to visit A, then B, then C, and finally D.
The reward machine begins in a state representing “nothing has been visited yet.” Reaching A moves it to a state representing “A has been visited.” Reaching B advances it again, and so on. Reaching D after the required sequence completes the task and produces a reward.
The machine’s state is important because the same physical location can mean different things depending on the route taken. Reaching D after visiting A, B, and C can earn a reward; reaching D without that history should not. The reward machine records the relevant history compactly.
The same idea can describe other tasks. A machine for delivering coffee to the office can require the agent to visit a coffee station first and the office afterward. A safety condition can send the machine to a sink state if the agent bumps into fragile furniture. In a sink state, the machine remains after the violation, representing that the task can no longer be completed as specified.
A reward machine can also allow multiple valid sequences. For “deliver coffee and mail to the office,” the agent might collect coffee first or mail first. If the order does not matter, the machine can represent both routes as acceptable ways to reach the office.
Why this changes the learning problem
A reward machine can describe a non-Markovian reward: a reward that depends on the history of events, not merely on the current physical state and action. This creates a problem for ordinary Q-learning. If the agent sees the same physical state twice, but one visit followed the correct sequence and the other did not, the appropriate reward may differ.
The standard remedy is to combine the environment state with the reward-machine state. If the environment state is s and the reward-machine state is u, the combined learning state is the pair (s,u). The machine state supplies the relevant memory of the past. The same physical situation can now be distinguished according to the task progress that led to it.
Think About It: In the office task, why is knowing the agent’s current location not enough to decide whether reaching D should earn a reward?
4. Using reward machines during learning
Once a task is represented by a reward machine, there are several ways to learn a policy. They differ in how they use task structure, and in whether they preserve the possibility of finding a globally optimal policy.
Q-learning on the combined state
A straightforward approach takes the cross product of the environment and reward-machine states, then runs ordinary Q-learning on that combined system. The reward-machine state makes the task’s relevant history part of the learning state, allowing the combined problem to be treated as a Markov decision process.
This is a useful baseline, but it may still require many samples. The agent is learning from its actual experience, and a reward that occurs only at the end of a long task can remain difficult to discover.
Hierarchical reinforcement learning
Hierarchical reinforcement learning (HRL) learns reusable sub-policies, often called options, and a higher-level controller that chooses among them. An option can act like a learned macro-action: for example, “go to the coffee station” or “reach location A.”
For a reward machine that refers to propositions A, B, C, and D, an HRL approach might learn one option for reaching each proposition. A meta-controller then selects which option to use.
The reward machine can help the controller by indicating which subgoal matters next. For example, if the current machine state says that A must be reached first, the controller can focus on the option for reaching A and ignore options that are not currently relevant. This is reward-machine-based pruning: the machine’s progress state narrows the choices available to the higher-level controller.
The limitation is that the options may be optimized separately. Each option can be locally good but lead to a poor overall sequence. For example, a locally shortest route to a coffee station might leave the agent far from the office. A different coffee station might take slightly longer to reach but make the complete delivery much faster. A controller that commits to the locally best coffee option can therefore produce a globally suboptimal task policy.
QRM: learning from counterfactual experience
QRM, or Q-learning for reward machines, is designed to use the reward-machine structure more directly. It learns a Q-function for each reward-machine state. The action selection for the agent uses the Q-function associated with its current machine state.
The key idea is that an observed transition can update more than one Q-function. The agent has actually experienced the environment transition while the reward machine was in one state. But the same physical transition can also be evaluated counterfactually: what reward-machine transition and reward would have occurred if the machine had been in another state?
Suppose an agent moves to D. If the reward machine is in a state where the task is already ready for D, that move may complete the sequence and earn a reward. If it is in an earlier state, the same move may earn no reward. QRM uses the observed transition to update the estimates for the relevant machine states, including states the machine was not actually in during that experience.
This is an off-policy form of learning: experience gathered under the current behavior can help estimate what would happen under other task-progress conditions. Because one experience can update several Q-functions, the agent can learn more from each interaction than it would by updating only the currently active task state.
QRM therefore combines two benefits. The reward machine decomposes a complex reward into state-dependent pieces, and counterfactual updates reuse experience across those pieces. A later variant called CRM, for Counterfactual Reward Machines, was described as learning a single larger policy rather than separate policies, with the aim of improving generalization.
Preserving optimality and the role of function approximation
In the tabular setting—where the agent stores a separate value for each relevant state-action pair—Q-learning is guaranteed to converge to an optimal policy under the usual learning conditions, though it may require many samples. QRM preserves this kind of optimality guarantee in the tabular case because it uses Q-learning updates while exploiting the reward-machine structure.
Hierarchical methods can be more sample-efficient than unstructured learning, but their separate sub-policies may be locally rather than globally optimal. This can explain why an HRL method sometimes learns quickly yet settles on a suboptimal overall route.
When Q-learning is replaced by a deep neural function approximator, such as a Double DQN-style learner, the tabular optimality guarantees no longer automatically apply. Nevertheless, the reward-machine decomposition can still improve learning in practice by exposing the task’s structure.
Think About It: How can a single move help the agent learn about a task stage it has not actually reached yet?
5. Reward shaping: providing intermediate guidance
A second way to address sparse rewards is reward shaping. The basic idea is to provide intermediate guidance along the way to a final reward. If an agent receives a reward only after a long journey, shaping can provide smaller signals that encourage progress before the journey is complete.
A useful analogy is leaving breadcrumbs along a route to a final destination. The agent receives feedback as it makes progress, rather than having to discover the entire successful sequence before receiving any signal. In the reward-machine setting, shaping can adjust rewards associated with machine transitions so that progress receives intermediate encouragement.
A crucial property of well-designed reward shaping is that it should not change which policy is optimal for the original task. The shaping reward guides learning, but the best policy under the shaped rewards remains optimal with respect to the original rewards. In the approach described, the shaping values can be calculated using value iteration over the reward machine, and QRM can then be applied to the shaped machine.
In experiments with discrete, tabular tasks, adding shaping sometimes helped QRM reach an optimal policy more quickly. However, the benefit was not universal: in the continuous-state experiments described, shaping did not help and could hinder performance. This illustrates an important practical point: additional feedback can be useful, but it must fit the structure of the task and learning method.
In continuous domains, reward machines can also use reward functions on transitions rather than only constant scalar rewards. Such functions can provide more tailored feedback than a simple jump from zero reward to a fixed positive reward. Combining those richer transition rewards with shaping may provide useful intermediate guidance, although the results described do not establish that this will always improve learning.
Think About It: Why might intermediate rewards speed up learning in one environment but make learning worse in another?
6. What the experiments show
The methods were evaluated in both discrete and continuous environments. The experiments illustrate how task structure affects sample efficiency and how the benefits of a method depend on the environment.
Discrete environments
In the office-world tasks, the agent had to complete ordered tasks while navigating around obstacles. QRM learned the optimal behavior with fewer training steps than ordinary Q-learning. HRL approaches also learned relatively quickly, but could settle on suboptimal policies because locally effective options did not always combine into the best overall route.
In craft-style tasks, the agent had to collect resources and make items. Ordinary Q-learning struggled with the sparse rewards and did not solve the tested problems within the reported training budget, while reward-machine and hierarchical approaches made more progress. The contrast demonstrates why representing a task as a sequence of meaningful stages can matter: the agent can use the decomposition rather than treating success as one distant event.
Continuous environments
A continuous domain involved controlling an agent among moving colored objects. Tasks included ordered goals and avoidance requirements, such as hitting certain colors in a specified sequence while never hitting another color.
With deep function approximation, QRM performed better in the reported experiments than the tested deep Q-learning and hierarchical alternatives. However, function approximation removes the tabular optimality guarantee. The results show empirical advantages, not a general proof that QRM will always outperform other methods.
Reward shaping improved learning in some of the discrete tasks, but did not help in the continuous setting described. The results underline that reward shaping and function approximation need to be assessed in the particular environment where they will be used.
7. Where reward machines come from
A reward machine does not have to be written directly by hand. There are several ways to construct one.
Translating formal specifications
A task can first be written in a formal language and then translated into an automaton-based reward machine. Regular languages and suitable LTL specifications can be translated into finite-state automata, which can then serve as reward-machine representations.
This makes the reward machine a kind of normal form: people can express tasks in different formal languages, while learning algorithms can operate on a common automaton structure. The approach avoids needing a separate learning algorithm for every language.
The translation can have a cost. Translating some specifications, especially LTL formulas, into deterministic automata can produce much larger automata than the original formulas. Large machines mean more states for the learning algorithm to consider. Possible approaches to this issue include using nondeterministic or alternating automata, decomposing specifications, using lifted representations, or organizing abstract machines hierarchically. These are potential ways to manage representation size, not a guarantee that the size problem disappears.
Generating structure from symbolic plans
A high-level goal can also be given to a symbolic planner. The planner generates a plan, and the plan can be used to build a reward machine that provides useful intermediate targets or waypoints.
For example, a person might tell a household robot to retrieve an object from a room. The task can be represented at a high level, and a planner can generate a sequence of subgoals. Reinforcement learning can then use those subgoals as a richer structure than a single sparse reward at the end.
This approach links symbolic planning with reinforcement learning: planning supplies task structure, while learning helps the agent acquire behavior for carrying out the plan in an environment.
Learning reward machines
A reward machine can also be learned from interaction data. In this setting, the agent is given a vocabulary of high-level event detectors—for example, detectors that recognize whether a button was pressed or a cookie is present—and learns an automaton describing how those events relate to reward.
Learning the reward machine can reveal both which event sequences are valuable and what memory is required to make the task Markovian. The learned automaton can be inspected by people, which makes it more interpretable than a reward function hidden inside a large program.
Think About It: What advantages might come from writing a task in a language suited to a person, then translating it into a structure suited to a learning algorithm?
8. Partial observability: the reward machine as memory
Many real environments are partially observable. The agent cannot see the complete state of the world at every moment. A robot’s camera, for example, shows only the current view. Once it turns a corner, details from the previous view may no longer be visible.
A partially observable agent may need memory. It must use earlier events to decide what to do now. One formal approach is to maintain a belief state, a representation of what the agent thinks might be true. Another way to understand the problem is that the agent’s effective state must summarize relevant history.
A reward machine can provide such a summary when the task’s history can be captured by its automaton state. Consider an environment with three rooms: blue, yellow, and red. The agent cannot see inside a room from the corridor. Pressing a button in the yellow room causes a cookie to appear in either the blue or red room, but the agent does not immediately know which one.
At a particular junction, the best action depends on what happened earlier:
- Before pressing the button, the agent must go to the yellow room.
- After pressing it, the agent must search for the cookie.
- If the agent searches one room and finds no cookie, it must remember which room it checked and search the other.
- Once it finds and eats the cookie, the task is complete and the agent can begin again.
The physical observation at the junction may be identical each time, but the correct action differs according to the history. A learned reward machine can encode that history in its current state. In this sense, the machine acts as external memory for the policy.
In the described approach, the agent learned a reward machine using a known set of event detectors and a discrete optimization method called tabu search. The learned machine was interpretable: its states and transitions indicated the task stages, such as pressing the button, checking rooms, and finding or eating the cookie. The reported example was difficult for several contemporary deep reinforcement-learning approaches using recurrent networks, while learning with reward machines solved it effectively.
Think About It: If an agent sees the same corridor twice, what past event might make the correct next action different?
9. Benefits, limitations, and open challenges
Reward machines help make reward structure explicit. They can represent ordered tasks, constraints, alternative valid sequences, and history-dependent rewards. They also offer a way to turn formal-language specifications into structures that learning algorithms can exploit.
Several limitations remain important:
- Machine size: Translating a compact specification into an automaton can produce many states.
- Dependence on the vocabulary: The propositions and event detectors must capture the parts of the environment relevant to the task.
- Generalization: A machine learned for one task may not automatically transfer to a related task, such as a task with additional objects or events.
- Optimality in hierarchical learning: Locally optimal options can combine into a globally suboptimal policy.
- Continuous environments: Tabular optimality guarantees do not carry over automatically to deep function approximation, and shaping may help or hurt depending on the setting.
- Human interaction: An interpretable machine may allow experts to inspect or revise a learned representation, but incorporating revisions without relearning from scratch remains a challenge.
The broader goal is to let people communicate tasks in meaningful, structured forms while allowing agents to learn efficiently from experience. Formal languages provide expressive task descriptions; automata summarize progress and relevant history; reinforcement learning supplies the mechanism for acquiring behavior in an environment.
Comprehensive Review
A model-free reinforcement-learning agent learns a policy through interaction, but a complex task can be difficult to encode as a simple reward function. Temporally extended tasks often depend on event order, conditional requirements, and restrictions. LTL offers a formal way to describe such requirements over traces, and automata can track how much of a requirement has been satisfied.
A reward machine uses automaton states to represent task progress and transitions to connect events with rewards. Pairing the machine state with the environment state makes history-dependent rewards manageable. QRM builds on this structure by learning values for machine states and reusing experience through counterfactual, off-policy updates. HRL instead learns sub-policies and a controller, which can be efficient but may combine locally optimal choices into a globally suboptimal plan. Reward shaping can provide intermediate guidance while preserving the original objective when designed appropriately, though its empirical effect depends on the environment.
Reward machines can be written directly, translated from suitable formal specifications, generated with the help of symbolic planning, or learned from data. In partially observable environments, a machine state can also serve as memory by summarizing the past events needed to choose the next action. Together, these ideas show how explicit task structure can help reinforcement-learning agents learn from fewer interactions and make their behavior easier to interpret.

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