Module contents
Lesson 15 of 31Advanced 100 min

Planning and problem decomposition with language models

Study decomposition from least to most, plan-then-execute with replanning, on-demand decomposition, and dependency graphs with parallel execution. Compare direct language-model planning with classical planning and generate-and-validate approaches, and measure when planning helps.

After this lesson you can

  • Implement least-to-most decomposition and compare generalization to problems longer than the examples.
  • Implement plan-and-execute with a dependency graph, parallel execution, and replanning on failure.
  • Implement on-demand decomposition and analyze its depth relative to executor capability.
  • Validate model-proposed plans using a formal checker and measure validity.
  • Compare plan-and-execute with ReAct on success, tokens, and latency.

Before you start

Think before acting?

An analysis task may require locating several CSV files, checking columns, filtering rows, joining tables, and computing a number. If the agent chooses its next action from only the latest observation, it may repeat searches or discover missing data late. A plan makes dependencies explicit; it also costs compute to generate and can become stale as the environment changes. Compare it with the ReAct loop by counting planner calls, executor calls, and repairs.

Least-to-most decomposition solves a sequence of subproblems and uses earlier results in later ones. Zhou et al. study it for generalization to problems harder than the examples. Khot et al. also propose specialized modules that can be delegated to models or symbolic functions. An intermediate error can contaminate what follows; decomposition alone does not guarantee a correct result.

InteractiveDecompose when the executor falls short

One call solves any task whose size does not exceed capacity. Otherwise it splits into two integer-sized tasks and repeats. ‘Split all’ applies the same rule until size one.

On demand7
Down to units23

This is an illustrative simulation without detection errors or coordination cost, not a model measurement.

12
3
On-demand calls7
Calls when splitting all23
On-demand depth2
Adjust size and capacity. The figure implements an explicit deterministic rule; compare calls and depth with splitting into units, without claiming results from a real model.

As-needed decomposition first attempts execution and splits a task only upon failure. ADaPT proposes recursive decomposition when the executor cannot solve a subtask. The figure assumes perfect failure recognition and no decomposition calls beyond those counted; in a real system detecting failure, coordinating results, and verifying each subtask also cost resources.

The signal triggering decomposition is a design decision. A timeout, invalid result, and apparently correct answer that does not satisfy the task provide different information. If the executor misses an error, it may stop without splitting; if it declares failure on a valid answer, it may waste calls. A useful evaluation records both cases, depth reached, and verifier cost. Perfect detection simplifies the example but should not be transferred to a real measurement without checking.

Splitting also changes the error distribution. Consider a task whose answer depends on three partial results: even if each step is often correct, any failure can contaminate the final answer. If steps share a mistaken interpretation of the question, errors may be correlated and multiplying independent probabilities no longer describes them. Conversely, if a partial result can be verified and repaired locally, the whole task need not necessarily be repeated. This benefit depends on detecting the error and earlier information remaining valid.

There is coordination cost in addition to execution cost. The plan must name subtasks, pass inputs, and combine outputs; each context or format boundary adds potential information loss. A subtask that is too small may generate more communication than useful work, while one too large may exceed executor capacity. To compare granularities, fix the same task and measure final success, action count, tokens, and latency. Optimal granularity on one benchmark is not a universal property of decomposition.

Plans, dependencies, and repair

Plan-and-execute separates proposing a plan from the executor that carries it out. It differs from Plan-and-Solve, which asks for a plan and solution within one response. Separation allows step verification and reaction to observations, but an external planner adds cost and another possible error source.

A task dependency graph is a DAG: each node represents a task and each edge identifies a required prior result. A topological ordering respects the edges. Independent nodes can execute in parallel only if their effects and resources are compatible too: a missing edge does not prove two writes to the same file are safe. Ideal time is at least the critical-path duration; with limited resources it can be greater.

Replanning updates the part of a plan affected by failure or a state change. If a read fails, its descendants lack valid data; an independent completed branch can be retained if its results remain current. Reusing results without checking that they still match observed state is another error. Actions with external effects also need retry and compensation semantics, not just a new topological order.

From graph to execution

Before launching work, an executor can check that every dependency exists and the graph has no cycles. Validation prevents indefinitely waiting for a node that depends on itself through others. It then identifies nodes whose predecessors finished and supplies each with needed results. A failure must block descendants, but an independent branch can continue. The report should distinguish “failed during execution” from “never executed because a dependency was missing”: these require different responses.

Concurrency needs a second review beyond the graph. Two reads of immutable files can usually overlap; two writes to the same resource can interfere even if the planner drew no edge between them. For actions with effects, retrying after a timeout is especially ambiguous: the first request may have completed and only the response was lost. An idempotent operation or deduplication key can facilitate retry when supported. Without that information, blindly retrying can duplicate the effect.

The critical path sums durations along the longest dependent path and gives a latency lower bound with sufficient resources. It does not automatically include waiting for a shared tool or coordination cost, and node durations can vary between runs. If two two-second reads run in parallel and a subsequent combination takes one second, the ideal minimum is three seconds; if only one resource can read, it is at least five. This calculation is a planning assumption, not a model performance measurement.

Keeping a result after replanning requires knowing its input dependencies. File fingerprints or a state version can detect changes, provided they cover all relevant dependencies. If an action used unversioned external information, the executor cannot guarantee the result remains current merely because node text is unchanged. The CSV experiment avoids this ambiguity by keeping inputs read-only during each attempt; other environments need a richer validity contract.

In a trace, record node identity, resolved arguments, and input versions. Two nodes with the same name may query different files; reusing the first for the second would be incorrect even if the plan retains an identical label. A cache key must reflect those dependencies, not just the visible name.

Imagine two independent queries, one against a sales CSV and another against a customer CSV, followed by a combination. If the customer query fails before producing a value, the sales result can be retained while the sales file stays unchanged. The combination must wait for the new customer result: running that node with missing data can yield a plausible number that does not answer the question. The trace should show which version of each result was used, not just call completion order.

If repair changes the goal rather than an input, the entire plan merits review: a formerly useful node may no longer contribute and another may be needed. The executor should therefore validate new plan references and decide which prior results are compatible, rather than merely replacing the list of names. In some systems rebuilding the plan is cheaper than proving which fragments remain valid. Evaluate that choice by cost and success; graph shape alone does not determine it.

InteractiveRepair a task graph

Read A (2) and read B (3) finish in parallel; join (2) requires both reads and sum (1) requires the join.

Read A
failed
Read B
complete
Join
blocked
Sum
blocked

Dependencies: A and B → join → sum. After a failure, one local retry succeeds by construction; earlier results do not change.

Calls2
Total time (units)3
Choose a failure and continue with a local retry. Durations and retry success follow hypothetical rules; the counter includes every attempt.

The local lab generates 60 reproducible tasks on fictional CSVs, with eight families and 12 rows per instance. To run it, download csv_tasks.py, csv_tools.py, planning.py, plan_executor.py, compare_agents.py, and the ReAct engine into the same directory. The model is Qwen2.5-0.5B-Instruct, revision 7ae557604adf67be50417f59c2c2f167def9a775; first prepare that revision in the Transformers cache and run python compare_agents.py. It requires PyTorch and Transformers. ORYON_PLAN_DEVICE can be cpu or cuda; it saves rows as JSONL and permits resumption without duplicating completed conditions.

The server_compare.py variant instead uses Qwen2.5-7B-Instruct Q4_K_M through a local llama.cpp-compatible server. It queries that server’s template and tokenizer to count input; if the provider count differs, the harness rejects the call. Do not mix its logs with those of the 0.5B model: versions and weights are part of the experimental condition.

Both systems have a cap of 4096 input and output tokens, a context of 2048, and up to four steps or proposals. The planner can repair a failed plan and reuses results of identical nodes. Both have query, which reads the task’s two CSVs, and combine, which adds or subtracts integer results. Three families require combining two queries: a graph can run them in parallel and pass both results to the dependent node. Questions use repeated templates and wall times on a shared machine depend on load: the experiment compares these systems and does not establish a general planning advantage.

A graph proposal can contain up to four nodes, whereas a ReAct step emits one action. Equal proposals or steps therefore do not imply equal tool calls. When interpreting a difference, also count executed nodes and tool cost; isolating the effect of planning under the same operation count would require imposing and measuring that additional budget. Node reuse assumes its input files remain unchanged: in this benchmark they are read-only during an attempt.

The two proposal interfaces also use different formats. ReAct must wrap tool arguments in a JSON string; the planner must put an object in each node and the executor serializes it before calling the tool. The common description says tools receive a string, while the plan instruction requires objects: this difference in levels may confuse the model. Therefore a success difference includes format and prompt effects, not just planning. Traces allow invalid plans and actions actually executed to be counted separately.

When finished, download analyze_comparison.py and run python analyze_comparison.py plan-comparison.jsonl. Analysis requires all 60 pairs, computes success and costs per condition, and resamples families and paired tasks for the difference. With only eight synthetic families, that interval describes limited variation and does not replace evaluation on diverse, independent tasks.

The complete campaign with the pinned model on CPU produced 0/60 exact answers in each condition; the analysis retains pairs and their costs. ReAct had 219 parsing errors in 240 proposals and dispatched 21 tool actions; the planner produced 240 invalid plans and executed no graph. Thus the experiment cannot compare performance of executed graphs: difficulty complying with requested interfaces dominated this setup. An independent audit computed all 60 answers directly from the CSVs using SQLite queries.

Mean costs were 1,228.48 tokens for ReAct and 1,506.67 for plan-and-execute. Observed mean times were 47.27 and 91.51 seconds respectively, on a shared machine with conditions run in order; they do not establish a causal latency difference. The paired bootstrap for the success difference gives [0, 0] for these observations: zero width does not imply certainty about other tasks, formats, or models.

InteractiveCompare the 60 CSV pairs

Loading analysis…

Measure
Real Qwen2.5-0.5B-Instruct results on CPU. Switch between success, tokens, and time; differences include each interface’s format.

A pair is the same file instance and question under both systems. This structure allows counting tasks solved by both, only the planner, only ReAct, or neither. The aggregate difference is the second group’s count minus the third’s, divided by total pairs. A small difference can hide many changes in both directions, so inspect transitions rather than only two percentages. An infrastructure error should not be confused with a failed answer by an agent.

Analysis retains family grouping because several questions share a template. Resampling each row separately as though these were sixty independently designed tasks can underestimate variation among problem types. Even a grouped interval depends on these eight families and generated data. External evaluation would require other table structures, questions, and tools; regenerating numbers for the same templates is insufficient.

The trace explains how the budget was spent. One variant may generate a plan that fails format parsing and spend calls correcting it without executing tools; another may execute valid queries and finish with an incorrect combination. Both are final failures but need different interventions. Count input and output tokens, proposal attempts, tool calls, and time, and remember a shared cap does not mean both methods spend exactly the same. Latencies on a shared machine are not a stable algorithm property either.

Family analysis can reveal a mechanism hidden by the average. Families requiring one query show added planning cost on a simple task; those needing two queries and a combination test dependency representation. This is a descriptive comparison of those families, not perfect causal attribution: wording, difficulty, or result sizes may differ too. Attributing a change to one component requires an intervention holding other conditions as similar as possible.

Plan quality must also be separated from execution quality. A graph may specify the correct operation but fail due to incorrectly serialized arguments, or execute without error while combining quantities that do not answer the question. Saving the proposed graph, resolved arguments, and observations enables both to be reviewed. Repair that reuses a correct result saves work only if that result remains valid for the new proposal and current state.

Partial campaign outputs should not be treated as a completed random sample if ordering is fixed. In this protocol families follow a reproducible sequence, so early interruption may omit whole task types. The analyzer requires all 60 pairs to calculate the intended summary. Partial rows still help diagnose format or infrastructure errors, but do not justify a conclusion about the complete benchmark.

Keep partial logs and the exact configuration to resume without duplicating pairs or mixing model versions or devices.

Validation simulates consequences

In STRIPS a state is a set of facts; an action requires preconditions and applies deletions and additions. A validator checks each action in order and then the goal. Rejecting an unmet precondition does not by itself identify the best alternative plan. The code below uses the same fields nombre, pre, add, and dele of Accion in m10-l20; facts are strings to keep the example small.

[ ]Validate and repair a STRIPS chainBrowser
from types import SimpleNamespace

def validar(inicial, meta, plan):
    estado = set(inicial)
    for i, accion in enumerate(plan):
        faltan = set(accion.pre) - estado
        if faltan:
            return False, i, sorted(faltan)
        estado = (estado - set(accion.dele)) | set(accion.add)
    faltan = set(meta) - estado
    return not faltan, len(plan), sorted(faltan)

def cadena(n):
    return [SimpleNamespace(nombre=str(i), pre={f'f{i}'},
                            add={f'f{i+1}'}, dele=set()) for i in range(n)]

def reparar(n):
    acciones = cadena(n)
    propuesta = [acciones[-1]]
    rondas = 0
    while True:
        rondas += 1
        valido, indice, faltan = validar({'f0'}, {f'f{n}'}, propuesta)
        if valido:
            return rondas
        # Proponente simulado específico: añade el productor del hecho faltante.
        hecho = faltan[0]
        productor = next(a for a in acciones if hecho in a.add)
        propuesta.insert(indice, productor)

print('rondas por longitud:', [(n, reparar(n)) for n in range(1, 7)])

This cell’s proposer knows all producers and the example is an acyclic chain: these are deliberate assumptions. Taking exactly nn rounds here does not predict language-model behavior or a general domain. A real problem also requires detection of unknown actions, impossible goals, unmodeled effects, and costs.

PlanBench proposes evaluating plans and reasoning about changes in structured domains; a plausible-looking plan is not evidence that it satisfies preconditions. LLM+P connects translation into a formal representation to a classical planner. Formal output validity also depends on translation faithfully representing the original problem. The LLM-Modulo framework separates approximate proposals from external checkers; a checker guarantees only the properties expressed by its model.

Translation introduces two distinct obligations. First, the formal representation must match the original problem’s state and goal. Second, the plan must be valid in that representation. A planner can perfectly solve a mistranslated version and return a plan that does not satisfy the initial request. The lab therefore compares translated initial facts and goal with the known instance before accepting the result, then simulates the plan’s actions. Its restricted syntax checker can also reject equivalent translations; that limitation matters when interpreting acceptance rate.

Validator feedback can identify the first missing precondition and enable a localized correction. That does not guarantee the next proposal is valid or a reachable plan exists. If up to three proposals are allowed, record all three, errors, and cumulative cost, and compare with a baseline receiving an explicit budget. In small domains classical search gives a reproducible reference within its formal model; in real settings effects, resources, or uncertainty may be missing from the representation.

Check order affects diagnosis. An unknown action name should be rejected before examining its preconditions; an out-of-domain argument is not equivalent to a false precondition; and an executable sequence may end without reaching the goal. Recording the first violation helps propose a repair, but may hide later errors revealed only after correction. A round limit prevents indefinite search and the report should include cases unresolved within that limit.

If a formal action omits a real-world effect, simulating it will not reveal that omission. For example, a model that includes block locations but no load restriction may accept a plan impossible under that physical constraint. The validator demonstrates consistency with its rules and initial state; the fidelity of those rules requires other evidence. This distinction avoids confusing a well-defined formal guarantee with a guarantee about every unmodeled situation.

The blocks and validator lab generates small PDDL problems and checks each action against its preconditions and the original goal. With pyperplan 2.1 and breadth-first search, classical plans of length 1 to 5 have been verified for towers of 2 to 6 blocks. Pyperplan is a teaching and prototyping tool, not a state-of-the-art performance baseline. To reproduce this part install pyperplan==2.1 locally and specify its Python when running the comparison campaign. This adds direct proposals, up to two corrections, and a model-requested PDDL translation. It rejects translations whose state or goal do not match and also checks the resulting plan. The PDDL checker accepts a restricted form: it may reject an equivalent expression with different syntax. Classical plans use an exact deterministic translation separate from model translation.

With Qwen2.5-7B-Instruct Q4_K_M, revision bb5d59e06d9551d752d08b292a50eb208b07ab1f, ten seeds ran for each of five templates with two to six blocks. All 50 direct plans were valid, as were all 50 deterministic baseline plans. Since all initial proposals passed, no correction was triggered and this sample does not measure repair feedback effectiveness. The model’s PDDL translation passed the checker and produced a valid plan in 5, 8, 1, 0, and 0 cases out of ten, respectively. The restricted parser may reject equivalent syntax and the 256-output-token limit also affects the experiment: six-block translations reached that limit on all ten seeds. Traces and analysis allow each case to be inspected.

InteractivePlans against the validator

Loading analysis…

Real results of 50 runs over five fixed templates. Intervals describe variation across seeds, not distinct tasks; the deterministic baseline does not use model translation.

Exercises

Numeric
An executor solves the initial task with probability 0.5. If it fails, it splits it into three independent subtasks, each with success probability 0.9. What is the total success probability?
Proof
Prove: With n independent subtasks and success probability q per attempt, success without retries is qⁿ; with k independent retries per node it is (1−(1−q)^(k+1))ⁿ.
0
All subtasks are required; each attempt has the same probability q and is independent of the others.

Step 1 of 3. What must happen to complete the plan without retries?

Code
Implement execute_dag(plan, run_task), with plan mapping id→dependency list. Check references and cycles before execution; run ready nodes concurrently, passing run_task(id, dependency_values). If a node fails, mark its descendants blocked and return status, values, and replan containing failed and blocked nodes. Independent branches must be able to continue.
def execute_dag(plan, run_task):
  pass
Shift+Enter to run
Quiz
A plan seems reasonable when read. What is needed to claim it solves a formal instance?
Quiz
When is a detailed initial plan most likely to become obsolete quickly?

Summary

Key idea
Decomposition makes work assignment and dependency checking easier, but a proposed plan must be validated and revised against observed state, including planning cost.