A topological sort is a linear ordering of the vertices in a directed acyclic graph (DAG) such that for every directed edge from vertex A to vertex B, vertex A appears before vertex B in the ordering. This algorithm is essential for scheduling tasks with dependencies, such as the operations in a neural network's computational graph, ensuring all prerequisite calculations are completed before a dependent operation executes. It provides a valid sequence for execution or compilation.
Glossary
Topological Sort

What is Topological Sort?
A fundamental algorithm for ordering operations in a computational graph.
The sort is typically performed using Kahn's algorithm (which iteratively removes nodes with no incoming edges) or a depth-first search (DFS) approach. In machine learning frameworks, this ordering is a prerequisite for graph optimizations like constant folding and dead code elimination, and for generating efficient execution schedules on target hardware. Its output is not unique; a single DAG can have multiple valid topological orderings.
Key Properties of Topological Sort
Topological sort is a foundational algorithm for ordering operations in a directed acyclic graph (DAG). Its properties are critical for scheduling tasks, resolving dependencies, and enabling numerous compiler optimizations.
Definition & Core Constraint
A topological sort produces a linear ordering of the vertices in a Directed Acyclic Graph (DAG) such that for every directed edge from vertex u to vertex v, u appears before v in the ordering. This enforces a partial order derived from the graph's dependencies.
- Key Implication: It is only defined for DAGs. The presence of a cycle makes a topological ordering impossible, as it would require a node to appear before itself.
- Primary Use: Scheduling tasks with precedence constraints, such as course prerequisites, build system dependencies, and—most critically—computational graphs in machine learning frameworks.
Non-Uniqueness of Orderings
For most DAGs, a topological sort does not yield a unique ordering. Multiple valid linear orderings can satisfy all dependency constraints.
- Example: In a graph where tasks A and B have no dependency between them, both
[A, B, ...]and[B, A, ...]are valid topological orders if all other constraints are met. - Optimization Leverage: Compilers and schedulers exploit this non-uniqueness. They can choose an ordering that optimizes for specific goals like minimizing memory footprint (via better tensor lifetime analysis) or improving data locality for cache performance.
Algorithmic Approaches
Two primary algorithms are used to compute a topological sort, both with O(V+E) time complexity for a graph with V vertices and E edges.
- Kahn's Algorithm (1962): A BFS-based approach.
- Compute the in-degree (number of incoming edges) for each node.
- Initialize a queue with all nodes of in-degree zero.
- While the queue is not empty, remove a node, add it to the sorted order, and decrement the in-degree of its neighbors. Any neighbor reaching in-degree zero is added to the queue.
- Depth-First Search (DFS) Approach:
- Perform a DFS, marking nodes as visited.
- After fully exploring a node's descendants, prepend the node to a list.
- The final reverse of the DFS finishing times yields a topological order.
- Practical Note: Kahn's algorithm is often preferred in parallel scheduling contexts as it naturally reveals available tasks.
Role in Compute Graph Execution
In ML compilers and frameworks, topological sort is the essential first step for executing a neural network's computational graph.
- Execution Schedule: It determines the sequence in which operators (nodes) like convolutions or matrix multiplications are evaluated, ensuring all input tensors are ready.
- Enables Downstream Optimizations: The canonical ordering provided by a topological sort is a prerequisite for many advanced graph optimizations:
- Static Memory Planning: Analyzing tensor lifetimes to reuse memory buffers.
- Dead Code Elimination: Identifying and removing unsued operations.
- Operator Fusion: Determining which sequential operations can be merged into a single kernel.
- Dynamic Shape Handling: For graphs with dynamic shapes, a topological sort may be performed at runtime to validate and schedule the instantiated graph.
Cycle Detection as a Byproduct
A failed topological sort is a definitive cycle detection mechanism for a directed graph. Both main algorithms will halt before producing a full ordering if a cycle exists.
- In Kahn's Algorithm: The algorithm terminates if the queue empties before all nodes are processed. The remaining nodes are part of a cycle.
- In DFS Approach: A cycle is detected if the DFS encounters a node that is currently in the recursion stack (a "back edge").
- Critical for Graph Validation: In compiler pipelines, this property is used to validate that a user-defined or transformed computational graph is indeed a DAG, which is a fundamental requirement for a well-defined execution schedule.
Related Concepts in Optimization
Topological sort interacts closely with other compiler and graph theory concepts.
- Critical Path: The longest path through the DAG (in terms of operation latency). A topological sort helps identify this path, which determines the minimum possible execution time.
- Graph Partitioning: For distributing a graph across multiple devices, topological sort helps understand dependency chains that cannot be broken across partitions.
- Just-In-Time (JIT) Compilation: A JIT compiler may perform a fast topological sort on a newly generated or specialized subgraph to schedule its execution immediately.
- Contrast with Other Orders: Unlike a breadth-first or depth-first traversal, a topological order is not about exploration but about dependency satisfaction. It is a global property of the entire graph.
Frequently Asked Questions
Topological sort is a foundational algorithm for ordering operations in a computational graph. These questions address its core mechanics, applications, and relationship to other compiler optimizations.
A topological sort is a linear ordering of the nodes in a directed acyclic graph (DAG) such that for every directed edge from node A to node B, node A appears before node B in the ordering. This ordering is not necessarily unique. It is a fundamental prerequisite for scheduling the execution of operations in a neural network's computational graph, ensuring all input dependencies for an operation are satisfied before it runs.
- Key Property: It only applies to DAGs, which have no cycles. This property is guaranteed in a correctly defined computational graph where operations flow from inputs to outputs without creating a loop.
- Algorithmic Approaches: Common algorithms include Kahn's Algorithm (which uses node in-degrees and a queue) and Depth-First Search (DFS) with post-order traversal.
- Result: Produces a valid execution sequence, which is then used by the runtime or compiler for static memory planning and operator dispatch.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Topological sort is a foundational algorithm for scheduling operations in a computational graph. These related concepts are essential for compiler engineers and inference framework developers working on graph optimization.
Directed Acyclic Graph (DAG)
A Directed Acyclic Graph (DAG) is a graph with directed edges and no cycles, which is the prerequisite data structure for a topological sort. In machine learning, a computational graph representing a neural network is a DAG, where nodes are operations (like convolution or addition) and edges represent data dependencies (tensors). The acyclic property ensures a valid, conflict-free execution order can be found.
- Key Property: No path exists that starts and ends at the same node.
- ML Context: Enables deterministic, non-circular forward and backward passes during training and inference.
Kahn's Algorithm
Kahn's Algorithm is the canonical, queue-based algorithm for performing a topological sort on a DAG. It works by repeatedly removing nodes with no incoming edges (in-degree of zero), adding them to the sorted order, and updating the in-degree counts of their neighbors.
- Time Complexity: O(|V| + |E|) for a graph with V vertices and E edges.
- Practical Use: The core scheduling algorithm in deep learning frameworks like TensorFlow and PyTorch for determining operation execution order during graph compilation.
Depth-First Search (DFS) Sort
An alternative method for topological sorting using Depth-First Search (DFS). The algorithm performs a DFS traversal and orders nodes in the reverse order of their post-visit finishing times. This method is often used in recursive implementations or when the graph structure is explored via DFS for other analyses.
- Contrast with Kahn's: DFS-based sort is often simpler to implement recursively but less intuitive for tracking incremental progress.
- Application: Used in compiler passes that naturally traverse the graph structure.
Operator Dispatch
Operator Dispatch is the runtime mechanism that selects the correct kernel implementation for an operation after its execution order has been determined by topological sort. Dispatch decisions are based on the device (CPU, GPU, NPU), data type (float32, int8), and tensor layout.
- Relationship to Sort: Topological sort provides the when; operator dispatch provides the how.
- Performance Critical: Inefficient dispatch can negate the benefits of an optimal execution schedule.
Static Memory Planning
Static Memory Planning is a compile-time optimization that allocates and reuses memory buffers for tensors by analyzing their lifetimes within the topologically sorted execution order. It minimizes peak memory usage and eliminates runtime allocation overhead.
- Dependency: Requires a fixed execution order (from topological sort) to accurately determine when a tensor's memory can be safely reused.
- Result: Produces a memory plan that is often baked into ahead-of-time (AOT) compiled models for edge devices.
Graph Partitioning
Graph Partitioning involves dividing a large computational graph into smaller subgraphs that can be executed in parallel or on different hardware units. Effective partitioning requires understanding data dependencies, which are exposed by the graph's topology.
- Interaction with Sort: A topological sort is often performed within each partition to schedule its internal operations. Dependencies between partitions define a higher-level execution graph.
- Target Use: Enables model parallelism and efficient execution across heterogeneous hardware (e.g., splitting graph across CPU and NPU).

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us