TransitLM: A Large-Scale Dataset and Benchmark for Map-Free Transit Route Generation
A Comprehensive Technical Tutorial
Abstract
TransitLM represents a paradigm shift in public transit route planning—treating what was traditionally a graph algorithm problem as a learned sequence generation task. This tutorial provides an in-depth exploration of TransitLM, the dataset, benchmark, and methodology that together demonstrate the feasibility of end-to-end, map-free transit route generation. We walk through the core concepts step-by-step, explain the model architecture and training pipeline, break down the benchmark tasks and evaluation metrics, analyze experimental results, and discuss practical applications, limitations, and future directions. By the end of this tutorial, you will understand how TransitLM learns to generate valid transit routes from 13.9 million route planning records without any explicit map infrastructure—and why this matters for the future of AI-assisted mobility.
Target Audience: Advanced beginners to intermediate AI engineers with familiarity with LLMs and basic machine learning concepts. Prioritize intuition first, then technical depth.
1. Introduction: Why Transit Route Planning?
1.1 The Daily Challenge of Urban Mobility
Every day, millions of people ask themselves: "How do I get from Point A to Point B using public transit?" This seemingly simple question involves complex decision-making:
- Which bus or subway lines serve my origin?
- Where do I transfer?
- How many transfers is too many?
- Should I prefer subway over bus, or vice versa?
- What's the fastest route?
Behind the scenes, traditional transit route planning systems rely on sophisticated algorithms working over detailed digital maps of transit networks. These systems are engineering marvels—but they have fundamental limitations.
1.2 Traditional Route Planning: The Old Paradigm
For decades, public transit route planning has followed this workflow:
┌─────────────────────────────────────────────────────────────────────┐
│ TRADITIONAL ROUTE PLANNING │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ 1. User Input │
│ Origin: "Guangzhou East Railway Station" │
│ Destination: "Tianhe City Station" │
│ │
│ 2. Map Data Retrieval (Requires external map infrastructure) │
│ • Retrieve road network data │
│ • Fetch station locations and line geometries │
│ • Load transfer relationships between lines │
│ │
│ 3. Routing Algorithm │
│ • Dijkstra's algorithm (shortest path) │
│ • A* (heuristic-guided search) │
│ • RAPTOR (round-based public transit routing) │
│ • Connection Scan Algorithm │
│ • Transfer Patterns │
│ │
│ 4. Ranking Model / Rules │
│ • Score candidate routes │
│ • Apply user preferences │
│ • Return top result │
│ │
└─────────────────────────────────────────────────────────────────────┘
Key Characteristics:
- Requires structured map infrastructure (digital maps with stations, lines, transfer data)
- Relies on complex engineering pipelines for candidate retrieval and ranking
- Depends on real-time schedule data for accurate timing
- Changes to the network require re-indexing the entire system
1.3 The Problem with Traditional Approaches
While industrially proven, traditional methods have significant drawbacks:
| Limitation | Impact |
|---|---|
| Map dependency | Cannot function without accurate, up-to-date map data |
| Coverage gaps | Poor performance in regions with incomplete mapping |
| Brittle to changes | Routing engines are hard-coded; fail on novel inputs |
| No learning | System learns nothing from user behavior patterns |
| Engineering complexity | Requires maintaining complex graph algorithms |
1.4 A Surprising Observation
Here's an insight that motivated TransitLM's approach: massive route planning logs continuously generated by transit platforms implicitly encode rich routing knowledge:
- Boarding stations
- Transfer points
- User preferences (speed vs. convenience vs. line preference)
- Common route patterns
This data already exists! The question is: Can we learn route planning directly from such data, bypassing maps and routing engines entirely?
1.5 The TransitLM Insight
TransitLM poses a radically different question:
What if we treat transit route planning as a natural language generation task?
Instead of feeding coordinates into a graph algorithm, what if we ask an LLM: "What's the best route from Station A to Station B?" and let it generate a valid route sequence based on patterns it learned from millions of real examples?
This is analogous to how LLMs learned to write code by training on code repositories—they didn't execute a compiler; they learned the patterns of valid code. TransitLM applies the same insight to transit route planning.
2. The Three Paradigms in Transit Route Planning
To understand TransitLM's contribution, it helps to visualize the three distinct paradigms for transit route planning (directly from Figure 1 of the paper):
2.1 Paradigm 1: Traditional Map-Based Pipeline
User Input → Map Data Retrieval → Routing Algorithm → Ranking Model
(A, B) (Road/station network) (Dijkstra/A*) (Rules/Score)
- Strengths: Industrially proven, optimal results, handles complex networks
- Limitations: Requires map infrastructure, high costs, static configuration only
2.2 Paradigm 2: General-Purpose LLMs
User Query → LLM Output
(No map lookup)
- Strengths: Flexible, natural language interface
- Failure Modes (documented in TransitLM paper):
- Hallucinated stations (invented station IDs that don't exist)
- Disconnected routes (stations that can't actually connect)
- Invalid boarding/alighting points (stations too far from origin/destination)
- The bottleneck is domain knowledge, not model capacity
Evidence from the Paper (Table 2 in paper):
- GPT-4 class models achieve only 45-75% connectivity
- Route Exact Match ranges from 15-40%
- Even under lenient evaluation (predicting only boarding/alighting stations), all struggle substantially
2.3 Paradigm 3: TransitLM (The New Approach)
User Query (GPS coordinates only, no map) → TransitData (13M records) → LLM Output
(Pre-train/Fine-tune)
- Strengths:
- End-to-end, map-free
- Implicit spatial grounding
- Structurally valid continuous routes
- Strong benchmark performance
- No external dependencies
3. The TransitLM Dataset: By the Numbers
TransitLM's dataset is massive and meticulously constructed. Let's break it down:
3.1 Dataset Statistics
| Metric | Value |
|---|---|
| Total Route Planning Sessions | 12,945,264 |
| Station Descriptions | 880,854 |
| Line Descriptions | 147,918 |
| Total CPT Corpus | 13,973,036 records |
| Cities Covered | Beijing, Shanghai, Shenzhen, Chengdu |
| Unique Stations | 120,845 |
| Unique Transit Lines | 13,666 |
| Total Tokens | 20+ billion |
3.2 Per-City Breakdown (Table 1 from paper)
| City | Sessions | Stations | Lines | Routes/Sess | Avg Stops | Avg Transfers | Avg Fare (¥) |
|---|---|---|---|---|---|---|---|
| Beijing | 4,802,588 | 38,792 | 4,234 | 6.14 | 14.29 | 1.57 | 8.36 |
| Shanghai | 3,144,747 | 35,617 | 3,702 | 6.54 | 13.42 | 1.51 | 8.38 |
| Shenzhen | 2,877,449 | 14,980 | 2,307 | 6.41 | 12.45 | 1.23 | 7.17 |
| Chengdu | 2,120,480 | 31,456 | 3,423 | 6.28 | 13.82 | 1.49 | 6.99 |
| Total | 12,945,264 | 120,845 | 13,666 | 6.32 | 13.58 | 1.47 | 7.88 |
3.3 Route Modality Distribution
| Route Type | Percentage | Description |
|---|---|---|
| Bus-only | 33.0% | Entire route uses buses |
| Subway-only | 19.0% | Entire route uses subway/metro |
| Bus + Subway | 16.8% | Combines both transit types |
| Mixed (with taxi/cycling) | 30.5% | First/last-mile via taxi or cycling |
| Non-transit | 0.7% | Taxi-only, cycling-only, etc. |
The balanced distribution ensures models encounter the full continuum of urban commuting scenarios.
3.4 Route Distance and Travel Time
| Distance Range | Percentage |
|---|---|
| Short-range (< 5 km) | 22.8% |
| Mid-range (5-20 km) | 47.4% |
| Long-range (> 20 km) | 29.7% |
Travel times span 15-90 minutes for the majority of routes.
3.5 Corpus Sequence Length
- Average length: 2,377 Chinese characters per record
- Distribution:
- 58.4% in 2,000-5,000 range
- 23.6% in 1,000-2,000 range
- 2.4% exceeds 5,000 characters (long-distance routes with many stops)
3.6 Data Source and Quality
The data comes from Amap (Alibaba Group), a leading navigation platform in China:
- 12.9 million route planning sessions from a single day of navigation logs
- All candidate routes are generated by Amap's production routing engine
- This means all routes inherently satisfy connectivity and feasibility constraints
- High-quality training signal without manual verification
- Fully de-identified with privacy safeguards (Appendix H of paper)
4. Data Schema: Format and Structure
TransitLM releases two complementary data resources:
4.1 Continual Pre-Training (CPT) Corpus
A textual corpus designed for next-token prediction training:
Session Records (12,945,264):
- Query header specifying city, origin-destination coordinates, POI names
- Candidate routes with per-segment details
- User-selected route placed first among candidates (enables implicit preference learning)
Static Descriptions:
- Station attributes: line length, stop sequences, operating hours, connectivity
- Line attributes: route length, stop count, operating hours, fare policy
Example Session Record (from Appendix B of paper, translated):
Query: How to get to Yongtai Dongli?
City: Beijing
Origin: 116.398261, 39.889556
Dest: 116.358844, 40.034880
Option 1 (Subway, 21.3 km, 55 min, 5 yuan):
Walk 170 m (2 min) to bus-899931 (Zhushikou, 116.398375, 39.889961).
Take Subway Line 8 to bus-893448 (Yongtaizhuang, 116.354580, 40.037728), 20.3 km, 41 min.
Walk 880 m to destination.
Stations: bus-899931, bus-900093, ..., bus-893448.
Option 2 (Bus, 20.8 km, 1h 55min, 5 yuan):
Walk 524 m to bus-899401 (Banzhang Rd, 116.394073, 39.890199).
Take Bus 5 to bus-897760 (Madian Bridge S., 116.397834, 39.959271), 10.7 km, 54 min.
[Transfer] Take Bus 625 to bus-892356 (Qinghe, 116.348232, 40.030627), 8.3 km, 34 min.
Walk 1.4 km to destination.
Stations: bus-899401, ..., bus-897760, [transfer], bus-897760, ..., bus-892356.
Example Station Description:
Station: Pinggu No.4 Middle School (bus-1000071)
District: Pinggu, Beijing
Lines served: 2
Coordinates: (117.089436, 40.130547)
Connectivity: From this station, take Line Ping-2 (Passenger Terminal – Pinggu No.7 Primary School)
to Yuming School (bus-1000202).
4.2 Benchmark SFT Data
Task-specific data for the three evaluation tasks:
- 30,000 training examples per task
- 10,000 test examples per task
- Standardized prompt-label format (enables reproducible comparison)
5. TransitBench: The Three Evaluation Tasks
TransitBench defines three evaluation tasks with complementary metrics (Section 4 of the paper):
5.1 Task 1: Optimal Route Generation (ORG)
Task: Given origin-destination information and a natural-language query, generate a single optimal transit route as structured JSON.
Input format:
{
"query": "How to get to BIT (South Gate)?",
"start": "116.395310,39.963284",
"end": "116.316356,39.957053",
"city": "Beijing"
}
Output format (structured JSON):
{
"line sequence": ["Subway Line 12", "Subway Line 4"],
"station sequence": ["bus-899733", "bus-898054", ..., "bus-888019", "[Transfer]", "bus-887631", "bus-887990"],
"total distance": "9.2 km",
"total time": "49 min",
"total fare": "4 yuan",
"start transfer mode": "walking",
"start transfer distance": "896 m",
"end transfer mode": "walking",
"end transfer distance": "759 m"
}
Ground-truth label: The top-ranked route that was also selected by the user.
Intuition: This is the most basic task—finding the best route from A to B, where "best" is determined by the platform's ranking and confirmed by user selection.
5.2 Task 2: Preference-Aware Planning (PRG)
Task: Same as ORG, but the query includes an explicit user preference. The model must satisfy the stated preference while maintaining overall route quality.
Four preference categories (from Section 4.1 of paper):
| Preference | Compliance Rule |
|---|---|
| Subway-first | Predicted route contains at least one subway segment |
| Bus-first | Predicted route contains at least one bus segment |
| Fewer transfers | N_transfers_pred ≤ N_transfers_gt |
| Shortest time | T_pred ≤ 1.1 × T_gt |
Example query:
{
"query": "How to get to Jingshan Park by bus? Bus-first.",
"start": "116.421180,39.880405",
"end": "116.396551,39.925875",
"city": "Beijing"
}
Intuition: Real users have preferences—some prioritize speed (subway-first), others prefer buses due to cost, and some want to minimize transfers. This task evaluates whether the model can understand and satisfy these constraints.
Important note: The theoretical upper bound of Preference Compliance is below 100% because ground-truth labels prioritize overall route quality and don't always strictly comply with the hard preference rule.
5.3 Task 3: Multi-Route Generation (DRG)
Task: Given the same OD input, generate three diverse transit routes in a single JSON response.
Output format:
{
"first": {
"route tag": "Subway",
"line sequence": ["Subway Line 18", "Subway Line 2"],
"station sequence": ["bus-1670095", ..., "bus-1677113", "[Transfer]", "bus-1677227", ..., "bus-1701975"],
"total distance": "41.1 km",
"total time": "1h 22min",
"total fare": "7 yuan",
"start transfer mode": "walking",
"start transfer distance": "169 m",
"end transfer mode": "walking",
"end transfer distance": "22 m"
},
"second": {
"route tag": "Bus+Subway",
"line sequence": ["Subway Line 18", "Maglev Line"],
...
},
"third": {
"route tag": "Bus",
"line sequence": ["Airport Express Line 4"],
...
}
}
Ground-truth assembly (in priority order):
- User-clicked route (as first)
- Routes with distinct tags or non-overlapping lines for diversity
- Top-scored routes by expert scoring function as fallback
Intuition: When planning a trip, users often want options—"Give me a few alternatives." This task evaluates whether the model can generate meaningfully diverse routes that offer real choice.
6. The Ten Evaluation Metrics Explained
TransitBench evaluates routes along four complementary dimensions, supplemented by task-specific metrics (Section 4.2 and Appendix D of the paper):
6.1 Category 1: Connectivity
Metric: Connectivity (Conn)
Definition: Verifies that every consecutive station pair in the predicted sequence is reachable via a shared transit line or a valid transfer.
Formula (Equation 1 from paper):
Conn = (1/N) × Σ_i 1[∀ 1 ≤ j < L(i), (s_j, s_{j+1}) ∈ E]
Where:
- L(i) is the length of the predicted station sequence for sample i
- E is the set of station pairs that are adjacent on a shared line or connected via an inter-line transfer
Interpretation: If your route has 10 stations (s1, s2, ..., s10), this metric checks that each consecutive pair (s1→s2, s2→s3, ..., s9→s10) is actually connected in the real transit network. A disconnected route means the model is hallucinating impossible journeys.
Why it matters: Connectivity is the prerequisite for all subsequent metrics. If a route isn't connected, nothing else matters.
6.2 Category 2: Access Feasibility
This category validates the first/last-mile segments connecting the origin/destination to the transit network.
Metric 1: Station Grounding (SG)
Definition: Checks whether the predicted boarding/alighting station is within a mode-specific distance threshold of the origin/destination.
Mode-specific thresholds (Table in Appendix D):
| Access Mode | Threshold |
|---|---|
| Walking | 3 km |
| Cycling | 5 km |
| Taxi | 10 km |
Formula (Equation 2 from paper):
SG = (1/N) × Σ_i 1[d_geo(a_s^(i)) ≤ τ_m ∧ d_geo(a_e^(i)) ≤ τ_m]
Intuition: This is the most remarkable finding in TransitLM—the model learns to map GPS coordinates to transit stations without any explicit coordinate-to-station database. Station Grounding verifies this implicit spatial grounding works.
Metric 2: Distance Plausibility (DP)
Definition: Verifies that the predicted access distance is physically realistic.
Two conditions:
d_pred ≥ d_geo— predicted distance must not fall below the geometric lower boundd_pred ≤ 3 × d_geo— predicted distance not unreasonably large
Intuition: Walking distance should be at least the straight-line distance (you can't walk through walls), but shouldn't be more than 3× the straight-line distance (that's an unreasonably indirect path). This filters out hallucinated access distances.
6.3 Category 3: Route Overlap
These metrics quantify the structural match between predicted and ground-truth routes using Intersection-over-Union (IoU).
Formula (Equation 4 from paper):
IoU(A, B) = |A ∩ B| / |A ∪ B|
Metric 1: Line Overlap (LO)
- A and B are the full line sets of the predicted and ground-truth routes
- Includes first/last-mile access segments (cycling, taxi)
Metric 2: Station Sequence Overlap (SSO)
- A and B are the corresponding station ID sets
- Note: Order doesn't matter for SSO; only the set of stations visited
Metric 3: Route Exact Match (REM)
- The fraction of samples achieving both LO = 1 AND SSO = 1
- In other words, the route is structurally identical in both lines and stations
6.4 Category 4: Numeric Field Accuracy
Measures how accurately the model predicts route-level numeric attributes.
Metric 1: Estimation Accuracy (EA)
For each field f ∈ F (where F = {distance, time, fare}), a prediction passes if it satisfies either:
- Relative tolerance: |ŷ_f - y_f| / y_f ≤ 10%, OR
- Absolute tolerance: |ŷ_f - y_f| ≤ ϵ_f
Where the absolute tolerances are:
- ϵ_time = 5 minutes
- ϵ_distance = 500 meters
- ϵ_fare = 1 CNY
Intuition: The dual-tolerance design ensures predictions with small absolute error but inflated relative error (due to small denominators) aren't penalized—and vice versa.
Metric 2: Mean Absolute Percentage Error (MAPE)
Quantifies continuous error magnitude for each field:
MAPE_f = (1/|M|) × Σ_i |ŷ_f^(i) - y_f^(i)| / y_f^(i)
MAPE is the average across all fields. Lower is better.
Note: EA and MAPE are computed only on samples that achieve Route Exact Match (REM), because ground-truth numeric fields only serve as valid references when the routes themselves match.
6.5 Category 5: Task-Specific Metrics
Preference Compliance (PC) — for PRG task:
- Checks whether the predicted route satisfies the stated preference via hard rules
- Reported as percentage of test samples passing
Route Diversity (RD) — for DRG task:
- Measures average pairwise line-set dissimilarity among the three generated routes
- Range: 0 (all routes identical) to 1 (no shared lines)
- Should be evaluated jointly with the four evaluation dimensions
7. Methodology: How TransitLM Works
7.1 Problem Formulation
TransitLM frames transit route planning as a sequence generation task (Section 5 of the paper):
Input: Natural language description + GPS coordinates
"How to get to Jingshan Park by bus? Bus-first."
Origin GPS: 116.421180, 39.880405
Destination GPS: 116.396551, 39.925875
City: Beijing
Output: Structured JSON with complete route information
{
"line sequence": ["Bus 128 (...)"],
"station sequence": ["bus-903008", "bus-902952", ..., "bus-899614"],
...
}
Analogy: This is exactly like machine translation (source sentence → target sentence) or code generation (problem description → code solution)—but for transit routes.
7.2 Base Model Architecture
TransitLM uses Qwen3 as the backbone (three sizes tested):
| Model | Parameters |
|---|---|
| Qwen3-0.6B-Base | 0.6 billion |
| Qwen3-1.7B-Base | 1.7 billion |
| Qwen3-4B-Base | 4 billion |
Why Qwen3?
- Strong performance at small parameter counts
- Good reasoning capabilities
- Well-documented pre-training setup
- The paper notes: "the 4B model already achieves strong performance across all tasks while larger variants would incur substantially higher training cost with diminishing returns"
7.3 Key Innovation: Vocabulary Expansion
Critical technical detail: TransitLM registers all 120,845 station IDs as dedicated tokens in the vocabulary.
Why this matters:
-
Prevents hallucination: Without dedicated station tokens, the model might try to compose station names character-by-character, potentially inventing non-existent station IDs.
-
Single-token representation: Each station is represented as a single token, enabling:
- Efficient learning of station-level relationships
- Direct station ID prediction in output
- Faster inference (no token-by-token spelling)
-
Spatial learning: Station tokens learn spatial relationships through co-occurrence patterns with:
- GPS coordinates
- Other stations on the same line
- Transfer station patterns
7.4 Two-Stage Training Pipeline
TransitLM trains through two stages (Section 5.1 and Appendix E):
Stage 1: Continual Pre-Training (CPT)
Objective: Internalize transit network topology and spatial relationships.
Method: Standard next-token prediction on the TransitLM corpus.
Key hyperparameters:
| Parameter | Value |
|---|---|
| Learning rate | 2e-5 |
| LR scheduler | Cosine |
| Optimizer | AdamW (weight decay 0.01) |
| Warmup steps | 500 |
| Sequence length | 4,096 (packed) |
| Per-device batch size | 4 |
| Gradient accumulation | 4 |
| Training budget | 15,000 steps |
| Distributed strategy | DeepSpeed ZeRO-3 |
| Precision | bf16 |
| Devices | 64 PPUs (96 GB) |
Training duration: ~6 days for 4B model, ~3 days for 1.7B, ~1.5 days for 0.6B
What happens during CPT:
- The model learns that certain station sequences follow each other
- Transfer patterns emerge naturally
- The model learns GPS coordinates → station mappings implicitly
- Spatial relationships between stations are encoded in embeddings
Stage 2: Supervised Fine-Tuning (SFT)
Objective: Teach the model the specific benchmark tasks.
Method: Standard instruction fine-tuning with task-specific prompts.
Key hyperparameters:
| Parameter | Value |
|---|---|
| Learning rate | 2e-5 |
| Epochs | 1 |
| Loss masking | Response tokens only (prompt tokens masked) |
| Devices | 8 PPUs (96 GB) |
Note: SFT data comes from a separate time period with no overlap with CPT corpus, preventing data leakage.
7.5 Joint Training Variant
The paper also trains a joint variant (4B-Joint):
- Fine-tuned on combined SFT data of all three tasks
- Tests whether transit knowledge learned during CPT transfers across planning objectives
- Evaluates unified deployment with a single model
8. Experimental Results: Key Findings
8.1 General LLMs Fail (Table 2)
Setup: 1,000 test samples across 4 cities, simplified output (only boarding/alighting stations per leg—a lenient evaluation).
| Model | Connectivity | Station Grounding | Line Overlap | Station Seq Overlap | Route Exact Match |
|---|---|---|---|---|---|
| GPT-5.4 | 60.5% | 60.5% | 0.407 | 0.361 | 18.4% |
| DeepSeek-V4 | 75.5% | 93.9% | 0.600 | 0.569 | 40.2% |
| Gemini-3.1-Pro | 64.9% | 72.0% | 0.447 | 0.425 | 23.7% |
| Claude-Opus-4.6 | 48.1% | 50.7% | 0.396 | 0.314 | 15.4% |
| Qwen-3.6-Plus | 45.0% | 64.2% | 0.475 | 0.386 | 19.8% |
| Doubao-Seed-2.0-Pro | 61.6% | 83.9% | 0.584 | 0.517 | 33.6% |
Key insight: Even under lenient evaluation, all general-purpose LLMs struggle. The best performer (Gemini-3.1-Pro) achieves only 75.5% connectivity and 40.2% Route Exact Match. The bottleneck is domain knowledge, not model capacity.
8.2 TransitLM Models Dominate (Table 3)
Optimal Route Generation (10,000 test samples):
| Model | Connectivity | Station Grounding | Line Overlap | Station Seq Overlap | Route Exact Match | MAPE |
|---|---|---|---|---|---|---|
| Qwen3-0.6B | 93.5% | 96.3% | 0.812 | 0.805 | 62.1% | 2.03% |
| Qwen3-1.7B | 95.0% | 96.6% | 0.827 | 0.818 | 64.1% | 1.60% |
| Qwen3-4B-25 | 95.9% | 97.7% | 0.811 | 0.816 | 65.6% | 1.88% |
| Qwen3-4B | 97.0% | 98.5% | 0.828 | 0.838 | 71.0% | 1.33% |
| 4B-Joint | 97.9% | 98.9% | 0.835 | 0.847 | 73.7% | 1.30% |
Key insight: Even the smallest TransitLM model (0.6B) outperforms all general-purpose LLMs. This proves data is the critical enabler, not model scale.
8.3 Preference-Aware Planning Results (Table 4)
| Model | Connectivity | Station Grounding | Route Exact Match | Preference Compliance |
|---|---|---|---|---|
| Qwen3-0.6B | 85.0% | 92.2% | 38.7% | 81.8% |
| Qwen3-1.7B | 88.5% | 92.9% | 39.4% | 81.6% |
| Qwen3-4B-25 | 90.1% | 94.2% | 43.9% | 88.8% |
| Qwen3-4B | 93.2% | 96.5% | 50.4% | 89.8% |
| 4B-Joint | 95.3% | 97.4% | 52.6% | 90.5% |
Note: Performance is lower than ORG because PRG must satisfy additional hard constraints (subway-first, bus-first, fewer transfers, shortest time) while maintaining route quality.
8.4 Multi-Route Generation Results (Table 5)
| Model | Connectivity | Station Grounding | Route Exact Match | Route Diversity |
|---|---|---|---|---|
| Qwen3-0.6B | 92.3% | 95.4% | 52.6% | 0.514 |
| Qwen3-1.7B | 95.2% | 95.6% | 52.9% | 0.532 |
| Qwen3-4B-25 | 94.9% | 97.0% | 57.9% | 0.534 |
| Qwen3-4B | 96.3% | 98.0% | 64.5% | 0.545 |
| 4B-Joint | 97.1% | 98.8% | 67.2% | 0.547 |
8.5 The GPS-Only Ablation: Most Compelling Result
Setup: Remove all textual cues (origin/destination names, POI names) and provide only GPS coordinates as input.
General LLMs (Table 7):
| Model | Connectivity | Station Grounding | Route Exact Match |
|---|---|---|---|
| GPT-5.4 | 78.9% | 14.4% | 0.6% |
| DeepSeek-V4 | 81.3% | 79.9% | 17.7% |
| Claude-Opus-4.6 | 64.9% | 15.3% | 0.6% |
| Qwen-3.6 | 65.5% | 11.3% | 0.2% |
TransitLM models (Table 8):
| Model | Connectivity | Station Grounding | Route Exact Match |
|---|---|---|---|
| Qwen3-0.6B | 93.5% | 95.9% | 61.0% |
| Qwen3-1.7B | 95.6% | 96.4% | 62.5% |
| Qwen3-4B | 97.2% | 98.3% | 70.4% |
| 4B-Joint | 98.0% | 98.8% | 72.9% |
Key findings:
- General LLMs collapse to <1% Route Exact Match without text
- TransitLM models have near-zero degradation (70.4% vs 71.0% with text)
- This proves the planning capability is grounded in spatial representations learned through CPT, not dependent on textual input
8.6 Data Scaling Study (Table 6)
Performance scales monotonically with CPT data volume:
| Data Fraction | Connectivity | Route Exact Match | MAPE |
|---|---|---|---|
| 6.25% | 94.0% | 49.9% | 3.26% |
| 12.5% | 95.4% | 61.2% | 2.27% |
| 25% | 95.9% | 65.6% | 1.88% |
| 50% | 96.8% | 68.9% | 1.51% |
| 100% | 97.0% | 71.0% | 1.33% |
Learning hierarchy revealed:
- Basic network topology is acquired first (connectivity reaches 94% even at 6.25% data)
- Route Exact Match and numeric calibration require denser coverage
- This suggests the model learns the structural "grammar" of transit networks rapidly but needs more data for fine-grained preferences
Practical insight: Even at 6.25% of the CPT data, the model achieves 94.0% connectivity and 49.9% Route Exact Match, demonstrating that end-to-end map-free route planning is practically viable with modest data collection effort.
9. Why TransitLM Matters: Broader Implications
9.1 Paradigm Shift from Algorithms to Learning
| Aspect | Traditional Routers | TransitLM |
|---|---|---|
| Knowledge representation | Explicit graph | Implicit (learned) |
| Algorithm | Dijkstra/CSA/Raptor | Next-token prediction |
| Map dependency | Required | Not needed |
| Updates | Re-index entire network | Retrain on new data |
| Flexibility | Limited to encoded rules | Handles novel queries |
| User behavior | Not captured | Learns from data |
9.2 What "Implicit Spatial Grounding" Means
The GPS-only ablation demonstrates something remarkable: the model learns to map arbitrary GPS coordinates to transit stations without any explicit geocoding database.
This is "implicit grounding" because:
- No coordinate-to-station mapping function is provided
- The association emerges from co-occurrence patterns in training data
- GPS coordinates and station names appear together in route records
- The model learns that certain coordinates are near certain stations
Analogy: This is like how language models learn word meanings from context rather than explicit dictionaries—they don't have a dictionary lookup; they learned from patterns.
9.3 Data > Model Scale
The most important lesson from TransitLM: domain-specific data is the critical enabler.
Evidence:
- Qwen3-0.6B (600M parameters) > GPT-4 class models on transit route planning
- All six general-purpose LLMs struggle even with simplified evaluation
- Performance scales with data volume more than model size
This has implications for AI development:
- Collecting high-quality domain data may be more valuable than scaling model size
- Domain-specific continual pre-training can unlock capabilities that general models cannot achieve
- Small, specialized models can outperform large, general models in targeted domains
9.4 Unified Multi-Task Deployment Works
The 4B-Joint model achieves:
- No negative transfer across all three tasks
- Often outperforms single-task counterparts
- Connectivity improves by +2.1pp, Route Exact Match by +2.2pp on PRG
This suggests the three planning tasks share underlying transit topology representations. Rather than competing for model capacity, complementary planning objectives reinforce shared spatial knowledge.
10. Practical Applications
10.1 Transit Customer Information Systems
Current state: Users interact with transit apps through search or map interfaces, then get algorithmic routing results.
With TransitLM-style systems:
- Natural language route queries: "How do I get from here to the train station using only subway?"
- No map required (useful for low-connectivity devices)
- Personalized preferences automatically understood
- Multiple route options presented naturally
10.2 Low-Resource Regions
Problem: Building and maintaining routing engines requires significant infrastructure:
- Detailed digital maps
- Schedule data in GTFS format
- Ongoing maintenance and updates
TransitLM opportunity: Regions without detailed mapping can still provide transit route planning by training on whatever route data is available.
10.3 Disaster Response and Network Disruptions
Challenge: When transit networks are disrupted (storms, accidents, strikes), traditional routing engines need updated network data.
TransitLM advantage: The model learns route patterns that may generalize to disrupted scenarios because it has seen similar patterns in training data (detours, alternatives, etc.).
10.4 Transit Data Analysis
The TransitLM dataset enables:
- Pattern discovery: What are the most common route patterns?
- Transfer analysis: Where do people typically transfer?
- Route efficiency comparison: How do generated routes compare to algorithmic baselines?
- User preference modeling: What trade-offs do users make?
11. Limitations
11.1 Route Optimality
Language models generate routes based on patterns in training data, not by optimizing an objective function:
- May not find globally optimal route: The model generates routes similar to what it's seen, not necessarily the mathematically shortest/fastest
- No real-time awareness: Doesn't consider live delays, schedule changes, or disruptions
- Plausible-but-wrong routes: May occasionally generate routes that look valid but miss optimal alternatives
11.2 Geographic and Temporal Coverage
| Limitation | Impact |
|---|---|
| 4 Chinese cities only | May not generalize to other regions |
| Static training data | Route information may become outdated |
| No real-time integration | Cannot incorporate live schedule updates |
| Single platform data | Platform-specific routing patterns |
11.3 Station Grounding Precision
The implicit GPS grounding is emergent, not explicit:
- May be imprecise for locations between stations
- No confidence intervals or uncertainty estimates
- Hard to debug why the model picked a particular station
11.4 Evaluation Bounds
- Preference Compliance has theoretical upper bound below 100%
- Route Exact Match varies significantly across tasks (71% ORG, 50% PRG, 65% DRG)
- Ground-truth routes may not always be the truly optimal choice
12. Future Directions
12.1 Geographic Expansion
- Extend to more cities and countries
- Multi-language transit planning support
- Cross-city transfer patterns (regional rail, intercity transit)
12.2 Temporal Dynamics
- Incorporate schedules for time-dependent routing
- Add real-time delay information
- Dynamic rerouting based on disruptions
- Time-of-day and day-of-week variations
12.3 Hybrid Approaches
- Combine learned route generation with algorithmic verification
- Use TransitLM for candidate generation, traditional routers for scoring
- Incorporate explicit map knowledge as a hybrid signal
12.4 Multimodal Extensions
- Vision-language models for transit map understanding
- Integration with outdoor navigation (last-mile routing)
- Multi-modal trip planning (transit + walking + bike-sharing + ride-hailing)
12.5 Better Evaluation
- Human evaluation of route quality
- Real-world user studies (A/B testing against production routers)
- Temporal generalization (train on past data, test on future)
13. Implementation Guide
13.1 Accessing the Dataset
HuggingFace Dataset:
from datasets import load_dataset
# Load the TransitLM dataset
dataset = load_dataset("GD-ML/TransitLM")
# Explore the structure
print(dataset)
# Expected output: DatasetDict with CPT corpus and SFT data
GitHub Repository:
git clone https://github.com/HotTricker/TransitLM
cd TransitLM
# Explore the evaluation code
ls evaluation/
13.2 Understanding the Data Format
CPT Corpus structure:
# Each record is a text string with query and route options
# Format varies between session records, station descriptions, and line descriptions
# Session record example:
# "Query: How to get to Yongtai Dongli?\nCity: Beijing\nOrigin: 116.398261, 39.889556\nDest: 116.358844, 40.034880\n\nOption 1 (Subway, 21.3 km, 55 min, 5 yuan):\nWalk 170 m..."
SFT Benchmark data format:
# Standardized prompt-label format
example = {
"prompt": "System: You are a public transit route planning expert...\nUser: How to get to BIT (South Gate)?...",
"label": '{"line sequence": [...], "station sequence": [...], ...}'
}
13.3 Setting Up Vocabulary Expansion
Key innovation: Station ID tokens
from transformers import AutoTokenizer
# Load base tokenizer
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B")
# Add station IDs as special tokens
# 120,845 station IDs become dedicated tokens
station_tokens = [f"station_{i}" for i in range(120845)]
tokenizer.add_special_tokens({"additional_special_tokens": station_tokens})
# Verify vocabulary expansion
print(f"Original vocab size: {tokenizer.vocab_size}")
# After expansion: ~151K tokens (base + stations)
13.4 Training Pipeline
Stage 1: Continual Pre-Training (CPT)
from transformers import AutoModelForCausalLM
from deepspeed import DeepSpeedConfig
import deepspeed
# Initialize model with expanded vocabulary
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-4B")
model.resize_token_embeddings(len(tokenizer))
# CPT configuration
cpt_config = {
"learning_rate": 2e-5,
"lr_scheduler_type": "cosine",
"warmup_steps": 500,
"max_steps": 15000,
"per_device_batch_size": 4,
"gradient_accumulation_steps": 4,
"zero_optimization": 3, # ZeRO-3
"bf16": True,
}
# DeepSpeed initialization
model_engine, optimizer, _, _ = deepspeed.initialize(
model=model,
config=deepspeed.Config(cpt_config)
)
# Training loop (simplified)
for step in range(15000):
# Pack sequences to fixed length
batch = pack_sequences(tokenizer, transitlm_corpus, max_length=4096)
# Forward pass
outputs = model_engine(**batch)
loss = outputs.loss
# Backward pass
model_engine.backward(loss)
model_engine.step()
Stage 2: Supervised Fine-Tuning (SFT)
# SFT configuration
sft_config = {
"learning_rate": 2e-5,
"per_device_batch_size": 4,
"gradient_accumulation_steps": 8,
"epochs": 1,
"bf16": True,
}
# SFT training (loss only on response tokens)
for batch in sft_dataloader:
inputs = tokenizer(batch["prompt"], return_tensors="pt")
labels = tokenizer(batch["label"], return_tensors="pt")
# Mask prompt tokens from loss
prompt_length = inputs["input_ids"].shape[1]
outputs = model(**inputs)
# Compute loss only on response portion
shifted_labels = labels["input_ids"][..., 1:].clone()
loss = outputs.loss
model_engine.backward(loss)
model_engine.step()
13.5 Evaluation Implementation
Connectivity Check:
def check_connectivity(predicted_stations, station_network):
"""
Verify every consecutive station pair is reachable.
Args:
predicted_stations: List of station IDs in predicted route
station_network: Dict mapping station -> connected stations
Returns:
bool: True if all consecutive pairs are connected
"""
for i in range(len(predicted_stations) - 1):
current = predicted_stations[i]
next_station = predicted_stations[i + 1]
# Check if adjacent on same line or valid transfer
if not is_adjacent(current, next_station, station_network):
return False
return True
def is_adjacent(station_a, station_b, network):
"""Check if two stations are adjacent (same line or transfer)."""
# Same line adjacency
for line in network["lines"]:
if station_a in line["stations"] and station_b in line["stations"]:
idx_a = line["stations"].index(station_a)
idx_b = line["stations"].index(station_b)
if abs(idx_a - idx_b) == 1:
return True
# Transfer adjacency
if station_b in network["transfers"].get(station_a, []):
return True
return False
Station Grounding Check:
import math
def haversine_distance(lat1, lon1, lat2, lon2):
"""Calculate distance between two GPS coordinates in meters."""
R = 6371000 # Earth radius in meters
phi1 = math.radians(lat1)
phi2 = math.radians(lat2)
delta_phi = math.radians(lat2 - lat1)
delta_lambda = math.radians(lon2 - lon1)
a = math.sin(delta_phi/2)**2 + \
math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda/2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
return R * c
def check_station_grounding(origin_gps, boarding_station, mode='walking'):
"""
Check if predicted boarding station is within threshold of origin.
Mode-specific thresholds:
- Walking: 3 km
- Cycling: 5 km
- Taxi: 10 km
"""
thresholds = {'walking': 3000, 'cycling': 5000, 'taxi': 10000}
threshold = thresholds[mode]
origin_lat, origin_lon = parse_gps(origin_gps)
station_lat, station_lon = boarding_station['coords']
distance = haversine_distance(origin_lat, origin_lon, station_lat, station_lon)
return distance <= threshold
IoU Computation:
def compute_iou(set_a, set_b):
"""Compute Intersection over Union for two sets."""
intersection = len(set_a & set_b)
union = len(set_a | set_b)
return intersection / union if union > 0 else 0
def compute_route_overlap(predicted_route, ground_truth_route):
"""Compute Line Overlap, Station Sequence Overlap, and Route Exact Match."""
# Line Overlap (IoU of line sets)
pred_lines = set(predicted_route['lines'])
gt_lines = set(ground_truth_route['lines'])
lo = compute_iou(pred_lines, gt_lines)
# Station Sequence Overlap (IoU of station ID sets)
pred_stations = set(predicted_route['stations'])
gt_stations = set(ground_truth_route['stations'])
sso = compute_iou(pred_stations, gt_stations)
# Route Exact Match (both = 1)
rem = 1.0 if (lo == 1.0 and sso == 1.0) else 0.0
return {'LO': lo, 'SSO': sso, 'REM': rem}
13.6 Inference Example
from transformers import AutoTokenizer, AutoModelForCausalLM
import json
def generate_route(query, start_gps, end_gps, city, preference=None):
"""
Generate a transit route using TransitLM.
Args:
query: Natural language query
start_gps: Origin GPS coordinates (lng, lat)
end_gps: Destination GPS coordinates (lng, lat)
city: City name
preference: Optional preference ('subway-first', 'bus-first', etc.)
Returns:
dict: Generated route in structured JSON format
"""
# Construct prompt
if preference:
prompt = f"""You are a public transit route planning expert.
Task: Given the user's origin and destination coordinates along with a stated preference,
plan a transit route that satisfies the preference while maintaining overall route quality.
Input: query (with preference), start (lng, lat), end (lng, lat), city.
Output (JSON): line sequence, station sequence (with [Transfer]), total distance,
total time, total fare, start transfer mode/distance, end transfer mode/distance.
Query: {query}
Start: {start_gps}
End: {end_gps}
City: {city}
Preference: {preference}"""
else:
prompt = f"""You are a public transit route planning expert.
Task: Given the user's origin and destination coordinates, plan an optimal transit route.
Input: query, start (lng, lat), end (lng, lat), city.
Output (JSON): line sequence, station sequence (with [Transfer]), total distance,
total time, total fare, start transfer mode/distance, end transfer mode/distance.
Query: {query}
Start: {start_gps}
End: {end_gps}
City: {city}"""
# Tokenize
inputs = tokenizer(prompt, return_tensors="pt")
# Generate
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=4096,
do_sample=False, # Greedy for reproducibility
pad_token_id=tokenizer.eos_token_id
)
# Decode and parse JSON
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Extract JSON from response
try:
# Find JSON in generated text
json_start = generated_text.find('{')
json_end = generated_text.rfind('}') + 1
route_json = json.loads(generated_text[json_start:json_end])
return route_json
except:
return {"error": "Failed to parse generated route"}
14. Key Takeaways
14.1 The Core Insight
Transit route planning can be learned from data, bypassing maps and routing engines entirely. This is the fundamental contribution of TransitLM.
14.2 What Makes TransitLM Work
- Large-scale, high-quality data: 13.9 million route records with implicit connectivity and feasibility guarantees
- Vocabulary expansion: 120,845 station IDs as dedicated tokens prevents hallucination
- Continual pre-training: Domain adaptation before task-specific fine-tuning
- Implicit spatial grounding: GPS coordinates → stations learned without explicit mapping
14.3 The Critical Lesson: Data > Model Scale
Even the smallest TransitLM model (0.6B parameters) outperforms all general-purpose LLMs including GPT-4 class models. Domain-specific data is the critical enabler, not model scale.
14.4 The Compelling GPS-Only Result
The GPS-only ablation proves the model is grounded in spatial representations learned through training, not dependent on textual semantics. General LLMs collapse to <1% Route Exact Match without text; TransitLM has near-zero degradation.
14.5 Unified Multi-Task Deployment
Joint training on all three tasks (ORG, PRG, DRG) achieves no negative transfer and often outperforms single-task counterparts. The transit knowledge is task-agnostic and supports unified deployment.
14.6 Implications for AI Development
TransitLM demonstrates:
- Collecting high-quality domain data may be more valuable than scaling model size
- Small, specialized models can outperform large, general models in targeted domains
- Continual pre-training unlocks capabilities that instruction tuning alone cannot achieve
- Sequence-to-sequence learning can replace traditional algorithms for structured output tasks
15. Resources and Links
15.1 Official Project Resources
| Resource | URL |
|---|---|
| Paper | https://arxiv.org/abs/2605.22355 |
| Dataset | https://huggingface.co/datasets/GD-ML/TransitLM |
| Code | https://github.com/HotTricker/TransitLM |
15.2 Base Model
| Resource | URL |
|---|---|
| Qwen3 Technical Report | https://arxiv.org/abs/2505.09388 |
| Qwen3 Models | Available via HuggingFace |
15.3 Related Algorithms
| Algorithm | Reference |
|---|---|
| RAPTOR | Delling et al., Transportation Science, 2015 |
| Connection Scan Algorithm | Dibbelt et al., JEA, 2018 |
| Transfer Patterns | Bast et al., ESA, 2010 |
15.4 Related Datasets
| Dataset | Description |
|---|---|
| GTFS | General Transit Feed Specification |
| T-Drive | Taxi trajectory dataset (Yuan et al., 2010) |
| CPTOND-2025 | China Public Transport Operation Network Dataset |
15.5 Related Benchmarks
| Benchmark | Focus |
|---|---|
| TravelPlanner | Real-world planning with language agents |
| NATURAL PLAN | LLMs on natural language planning |
| TravelBench | Multi-turn travel planning |
| MobilityBench | Route-planning agents |
Appendix A: Complete Metric Reference
| Metric | Abbreviation | Category | Formula Reference |
|---|---|---|---|
| Connectivity | Conn | 1. Connectivity | Eq. 1 |
| Station Grounding | SG | 2. Access Feasibility | Eq. 2 |
| Distance Plausibility | DP | 2. Access Feasibility | Section D.2 |
| Line Overlap | LO | 3. Route Overlap | Eq. 4 |
| Station Sequence Overlap | SSO | 3. Route Overlap | Eq. 4 |
| Route Exact Match | REM | 3. Route Overlap | Eq. 5 |
| Estimation Accuracy | EA | 4. Numeric Field Accuracy | Eq. 6 |
| MAPE | MAPE | 4. Numeric Field Accuracy | Eq. 7 |
| Preference Compliance | PC | 5. Task-Specific | Section D.5 |
| Route Diversity | RD | 5. Task-Specific | Eq. 8 |
Appendix B: Complete Hyperparameter Reference
CPT Training
| Parameter | Value |
|---|---|
| Backbone | Qwen3-Base (0.6B / 1.7B / 4B) |
| Initialization | Base weights |
| Added tokens | 120,845 station IDs |
| Learning rate | 2e-5 |
| LR scheduler | Cosine |
| Warmup steps | 500 |
| Optimizer | AdamW |
| Weight decay | 0.01 |
| Precision | bf16 |
| Sequence length | 4,096 (packed) |
| Per-device batch size | 4 |
| Gradient accumulation | 4 |
| Devices | 64 PPUs (96 GB) |
| Effective batch size | 1,024 |
| Training budget | 15,000 steps |
SFT Training
| Parameter | Value |
|---|---|
| Learning rate | 2e-5 |
| LR scheduler | Cosine |
| Warmup steps | 15 |
| Optimizer | AdamW |
| Weight decay | 0.01 |
| Precision | bf16 |
| Sequence length | Natural (with padding) |
| Per-device batch size | 4 |
| Gradient accumulation | 8 |
| Devices | 8 PPUs (96 GB) |
| Effective batch size | 256 |
| Epochs | 1 |
Inference
| Parameter | Value |
|---|---|
| Decoding strategy | Greedy |
| Max new tokens | 4,096 |
| Input cutoff length | 2,048 |
| Seed | 1 |
Appendix C: Ecosystem Map
TransitLM
├── Data Source: Amap (Alibaba Maps)
│ └── 13M+ route planning records
├── Base Model: Qwen3
│ └── Qwen3-0.6B / 1.7B / 4B
├── Training
│ ├── Stage 1: Continual Pre-Training (CPT)
│ │ └── 15K steps, 64 PPUs
│ └── Stage 2: Supervised Fine-Tuning (SFT)
│ └── 1 epoch, 8 PPUs
├── Benchmark: TransitBench
│ ├── Task 1: Optimal Route Generation (ORG)
│ ├── Task 2: Preference-Aware Planning (PRG)
│ └── Task 3: Multi-Route Generation (DRG)
└── Evaluation: 10 metrics across 5 categories
├── Connectivity
├── Access Feasibility
├── Route Overlap
├── Numeric Field Accuracy
└── Task-Specific
Related Work
├── Traditional Routers
│ ├── Dijkstra, A*
│ ├── RAPTOR
│ ├── Connection Scan Algorithm
│ └── Transfer Patterns
├── LLM-Augmented Approaches
│ ├── LLM-A*
│ ├── GridRoute
│ ├── MapBench
│ └── TraveLLM
└── Related Datasets
├── T-Drive (taxi trajectories)
├── GTFS (transit schedules)
└── CPTOND-2025 (China transit network)
End of Tutorial
This tutorial is designed to provide comprehensive understanding of TransitLM for AI engineers and researchers. It covers all aspects requested: core concepts, architecture, methodology, datasets, training, inference, comparisons, applications, limitations, and future directions. The content is structured for easy extraction of blog posts, social posts, and educational assets.
References
- Guo, H., et al. (2026). TransitLM: A Large-Scale Dataset and Benchmark for Map-Free Transit Route Generation. arXiv:2605.22355.
- Yang, A., et al. (2025). Qwen3 Technical Report. arXiv:2505.09388.
- Delling, D., Pajor, T., & Werneck, R. (2015). Round-based public transit routing. Transportation Science.
- Dibbelt, J., et al. (2018). Connection scan algorithm. Journal of Experimental Algorithmics.
- Bast, H., et al. (2010). Fast routing in very large public transportation networks using transfer patterns. ESA.