forked from lemony-ai/cascadeflow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathedge_device.py
More file actions
463 lines (392 loc) Β· 16.2 KB
/
edge_device.py
File metadata and controls
463 lines (392 loc) Β· 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
"""
Nvidia Jetson Thor/Spark Edge Device with vLLM - cascadeflow Example
This example demonstrates running cascadeflow on edge AI devices like:
- Nvidia Jetson Thor
- Nvidia Jetson Orin (AGX, NX, Nano)
- Nvidia Jetson Xavier
- Spark AI accelerator cards
What it demonstrates:
- Local inference with vLLM on edge device (privacy-first)
- Automatic cascade to cloud (Claude) for complex queries
- Zero-cost local processing with cloud fallback
- Real-time latency optimization for edge computing
- Tool calling support on both tiers
Hardware Requirements:
- Nvidia Jetson Thor / Orin / Xavier device with GPU
- 8GB+ RAM (16GB recommended for larger models)
- Ubuntu 20.04+ (JetPack 5.0+)
- CUDA 11.8+ support
Software Requirements:
- vLLM server running locally (http://localhost:8000)
- Anthropic API key for cloud fallback
- Python 3.9+
Setup Instructions:
1. Install vLLM on Jetson device:
```bash
# Install CUDA-enabled PyTorch
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
# Install vLLM (may need to build from source on Jetson)
pip3 install vllm
```
2. Start vLLM server with a small model optimized for edge:
```bash
# Option 1: Llama 3.2 1B (ultra-fast, 1GB VRAM)
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Llama-3.2-1B-Instruct \
--dtype half \
--max-model-len 2048 \
--gpu-memory-utilization 0.7
# Option 2: Qwen2.5 3B (balanced, 3GB VRAM)
python -m vllm.entrypoints.openai.api_server \
--model Qwen/Qwen2.5-3B-Instruct \
--dtype half \
--max-model-len 4096 \
--gpu-memory-utilization 0.8
# Option 3: Llama 3.2 3B (quality, 3GB VRAM)
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Llama-3.2-3B-Instruct \
--dtype half \
--max-model-len 4096 \
--gpu-memory-utilization 0.8
```
3. Set environment variables:
```bash
export VLLM_BASE_URL="http://localhost:8000/v1"
export ANTHROPIC_API_KEY="sk-ant-..."
```
4. Run the example:
```bash
python nvidia_thor_edge_device.py
```
Expected Results:
- Simple queries: Processed locally on Jetson (<100ms latency)
- Complex queries: Automatically cascade to Claude (~500-1000ms)
- 70-80% of queries stay on device (zero cost, maximum privacy)
- 20-30% cascade to cloud only when needed
- Full tool calling support on both local and cloud tiers
Use Cases:
- Smart factories: Local vision + reasoning, cloud for complex analysis
- Healthcare devices: HIPAA-compliant local processing, cloud consultation
- Retail kiosks: Fast local responses, cloud for inventory management
- Autonomous robots: Real-time local control, cloud for path planning
- Edge AI servers: Process locally, escalate complex queries to cloud
- IoT gateways: Aggregate sensor data locally, cloud for analytics
Cost Analysis (10k queries/month):
Without cascadeflow (all cloud - Claude Sonnet):
10,000 Γ $0.003 = $30.00/month
With cascadeflow (edge-first strategy):
Local (7,000): $0.00 (free - your hardware)
Cloud (3,000): 3,000 Γ $0.003 = $9.00/month
Total: $9.00/month
Savings: $21.00/month (70%) + Enhanced privacy + Lower latency
Documentation:
See docs/guides/edge-devices.md for detailed deployment guide
"""
import asyncio
import os
import sys
import time
from typing import Any
from cascadeflow import CascadeAgent, ModelConfig, QualityConfig
try:
import httpx
except ImportError:
print("β οΈ httpx not installed. Installing...")
import subprocess
subprocess.check_call([sys.executable, "-m", "pip", "install", "httpx"])
import httpx
# ============================================================
# EDGE DEVICE CONFIGURATION
# ============================================================
# Define edge cascade: Local vLLM β Cloud Claude
def create_edge_agent() -> CascadeAgent:
"""
Create CascadeAgent optimized for Nvidia Jetson Thor/Spark edge devices.
Tier 1: Local vLLM (Llama 3.2 3B) - Fast, private, zero-cost
Tier 2: Cloud Claude (Claude Sonnet 4.5) - Complex reasoning fallback
"""
models = [
# Tier 1: Local inference on Jetson device
# - Llama 3.2 3B runs great on Jetson Orin/Thor
# - ~100ms latency for simple queries
# - Zero API cost (your hardware)
# - Maximum privacy (data never leaves device)
ModelConfig(
name="meta-llama/Llama-3.2-3B-Instruct",
provider="vllm",
cost=0.0, # Free - runs on your edge device
metadata={
"device": "jetson-thor",
"location": "edge",
"vram_required": "3GB",
"avg_latency_ms": 100,
},
),
# Tier 2: Cloud fallback for complex queries
# - Claude Sonnet 4.5 for advanced reasoning
# - Only used when local model insufficient (~20-30% of queries)
# - Higher latency but superior quality
# - Cost-effective cloud tier
ModelConfig(
name="claude-sonnet-4-5-20250929",
provider="anthropic",
cost=0.003, # $3 per 1M tokens
metadata={"device": "cloud", "location": "anthropic-datacenter", "avg_latency_ms": 800},
),
]
# Configure quality thresholds optimized for edge devices
quality_config = QualityConfig(
confidence_thresholds={
"trivial": 0.65, # Lower thresholds for fast local responses
"simple": 0.60,
"moderate": 0.55,
"hard": 0.50,
"expert": 0.45,
},
enable_adaptive=True, # Adapt based on query complexity
)
agent = CascadeAgent(
models=models, quality_config=quality_config, enable_cascade=True, verbose=True
)
return agent
# ============================================================
# TEST QUERIES FOR EDGE DEVICES
# ============================================================
def get_test_queries() -> list[dict[str, Any]]:
"""
Test queries spanning edge device use cases.
Categories:
- Simple factual: Should stay on device (Tier 1)
- Moderate reasoning: Might stay on device or cascade
- Complex analysis: Will cascade to cloud (Tier 2)
- Tool-based: Demonstrates tool calling support
"""
return [
# CATEGORY 1: Simple factual (local device)
{
"query": "What is the speed of light?",
"expected_tier": 1,
"category": "factual",
"use_case": "Quick reference lookup",
},
{
"query": "Convert 100 degrees Fahrenheit to Celsius.",
"expected_tier": 1,
"category": "calculation",
"use_case": "Simple math computation",
},
# CATEGORY 2: Moderate reasoning (might cascade)
{
"query": "A factory sensor reads 75Β°C. Is this within normal operating range for a hydraulic pump?",
"expected_tier": 1, # May cascade if model uncertain
"category": "domain-reasoning",
"use_case": "Industrial monitoring",
},
{
"query": "List three common causes of conveyor belt misalignment in manufacturing.",
"expected_tier": 1,
"category": "knowledge-retrieval",
"use_case": "Maintenance assistance",
},
# CATEGORY 3: Complex analysis (cloud cascade)
{
"query": "Analyze the following sensor readings and predict potential failures: "
"Motor temp: 85Β°C (normal: 60-75Β°C), Vibration: 12mm/s (normal: <10mm/s), "
"Current draw: 45A (normal: 35-40A). Provide root cause analysis and maintenance recommendations.",
"expected_tier": 2,
"category": "complex-analysis",
"use_case": "Predictive maintenance",
},
{
"query": "Given these production metrics from the last 30 days (units: 10k, 12k, 8k, 15k, 9k per week), "
"predict next week's output considering seasonal trends and recommend staffing adjustments.",
"expected_tier": 2,
"category": "forecasting",
"use_case": "Production planning",
},
# CATEGORY 4: Real-time edge scenarios
{
"query": "Object detected in restricted zone. Current: 2:45 PM, Location: Assembly Line 3, "
"Object type: Unknown. Recommend immediate action.",
"expected_tier": 1, # Fast response needed
"category": "safety-alert",
"use_case": "Security monitoring",
},
{
"query": "Quality control: Part #A1234 measured dimensions are 10.02mm x 5.01mm (spec: 10.00mm Β± 0.05mm x 5.00mm Β± 0.05mm). "
"Is this part within tolerance? Should it be approved or rejected?",
"expected_tier": 1,
"category": "quality-control",
"use_case": "Automated inspection",
},
]
# ============================================================
# MAIN DEMONSTRATION
# ============================================================
async def main():
"""
Demonstrate cascadeflow on Nvidia Jetson Thor/Spark edge device.
"""
print("=" * 80)
print("NVIDIA JETSON THOR/SPARK EDGE DEVICE - CASCADEFLOW DEMONSTRATION")
print("=" * 80)
print()
print("Edge Device Configuration:")
print(" Hardware: Nvidia Jetson Thor/Orin")
print(" Local Model: Llama 3.2 3B (vLLM)")
print(" Cloud Fallback: Claude Sonnet 4.5 (Anthropic)")
print(" Strategy: Process locally first, cascade to cloud if needed")
print()
# Check if vLLM server is running
vllm_url = os.getenv("VLLM_BASE_URL", "http://localhost:8000/v1")
print(f"π Checking vLLM server at {vllm_url}...")
try:
# Try to connect to vLLM server
response = httpx.get(f"{vllm_url.replace('/v1', '')}/health", timeout=5)
if response.status_code == 200:
print("β
vLLM server is running")
else:
print(f"β οΈ vLLM server returned status {response.status_code}")
print("\nβ This example requires a local vLLM server.")
print("\nπ‘ To run this example:")
print(" 1. Install vLLM: pip install vllm")
print(" 2. Start server:")
print(" python -m vllm.entrypoints.openai.api_server \\")
print(" --model meta-llama/Llama-3.2-3B-Instruct \\")
print(" --dtype half \\")
print(" --max-model-len 4096")
print("\nβ
Exiting gracefully (this is not an error)")
sys.exit(0)
except (httpx.ConnectError, httpx.TimeoutException) as e:
print(f"β Cannot connect to vLLM server: {e}")
print("\nπ‘ This example requires a local vLLM server for edge device simulation.")
print("\nπ Setup instructions:")
print(" 1. Install vLLM: pip install vllm")
print(" 2. Start server:")
print(" python -m vllm.entrypoints.openai.api_server \\")
print(" --model meta-llama/Llama-3.2-3B-Instruct \\")
print(" --dtype half \\")
print(" --max-model-len 4096")
print("\nβ
Exiting gracefully (this is not an error)")
sys.exit(0)
# Check if Anthropic API key is set
if not os.getenv("ANTHROPIC_API_KEY"):
print("β οΈ Warning: ANTHROPIC_API_KEY not set. Cloud fallback will not work.")
print(" Set it with: export ANTHROPIC_API_KEY='sk-ant-...'")
print()
# Create edge-optimized agent
print("π Initializing edge agent...")
agent = create_edge_agent()
print("β
Agent initialized")
print()
# Get test queries
queries = get_test_queries()
print("=" * 80)
print(f"RUNNING {len(queries)} TEST QUERIES")
print("=" * 80)
print()
# Track statistics
total_cost = 0.0
local_count = 0
cloud_count = 0
total_latency = 0.0
# Run queries
for i, query_data in enumerate(queries, 1):
query = query_data["query"]
category = query_data["category"]
use_case = query_data["use_case"]
print(f"Query {i}/{len(queries)}: {category.upper()}")
print(f"Use Case: {use_case}")
print(f"Prompt: {query[:100]}..." if len(query) > 100 else f"Prompt: {query}")
print()
# Run query with timing
start_time = time.time()
try:
result = await agent.run(query)
latency = (time.time() - start_time) * 1000 # Convert to ms
total_latency += latency
# Determine which tier was used
if result.model_used.startswith("meta-llama"):
tier = 1
tier_name = "LOCAL (Jetson)"
tier_color = "π"
local_count += 1
else:
tier = 2
tier_name = "CLOUD (Claude)"
tier_color = "π"
cloud_count += 1
# Display results
print(f" {tier_color} Tier {tier}: {tier_name}")
print(f" β‘ Latency: {latency:.0f}ms")
print(f" π° Cost: ${result.total_cost:.6f}")
print(f" π― Confidence: {result.confidence:.2f}")
if result.cascaded:
print(" π Cascaded: Yes (local model insufficient)")
# Show abbreviated response
response_preview = (
result.content[:150] + "..." if len(result.content) > 150 else result.content
)
print(f" π€ Response: {response_preview}")
print()
# Update cost tracking
total_cost += result.total_cost
except Exception as e:
print(f" β Error: {e}")
print()
# Print summary statistics
print("=" * 80)
print("EDGE DEVICE PERFORMANCE SUMMARY")
print("=" * 80)
print()
print(f"Total Queries: {len(queries)}")
print(f"Local Processing: {local_count} ({local_count/len(queries)*100:.1f}%)")
print(f"Cloud Cascade: {cloud_count} ({cloud_count/len(queries)*100:.1f}%)")
print()
print(f"Total Cost: ${total_cost:.6f}")
print(f"Average Latency: {total_latency/len(queries):.0f}ms")
print("Local Avg Latency: ~100ms (estimated)")
print("Cloud Avg Latency: ~800ms (estimated)")
print()
# Cost comparison
all_cloud_cost = len(queries) * 0.003 # Rough estimate
savings = all_cloud_cost - total_cost
savings_pct = (savings / all_cloud_cost * 100) if all_cloud_cost > 0 else 0
print("Cost Analysis:")
print(f" All-Cloud Cost: ${all_cloud_cost:.6f}")
print(f" Edge-First Cost: ${total_cost:.6f}")
print(f" Savings: ${savings:.6f} ({savings_pct:.1f}%)")
print()
# Key benefits
print("=" * 80)
print("KEY BENEFITS FOR EDGE DEVICES")
print("=" * 80)
print()
print("β
Privacy: Sensitive data stays on device")
print("β
Latency: <100ms response time for local queries")
print("β
Cost: 70%+ cost reduction vs all-cloud")
print("β
Reliability: Works offline for local queries")
print("β
Scalability: No API rate limits for local tier")
print("β
Quality: Cloud fallback ensures complex queries handled well")
print()
print("=" * 80)
print("DEPLOYMENT RECOMMENDATIONS")
print("=" * 80)
print()
print("For Production:")
print(" 1. Use quantized models (GPTQ/AWQ) for lower VRAM")
print(" 2. Enable KV cache optimization in vLLM")
print(" 3. Monitor GPU temperature and throttling")
print(" 4. Implement circuit breaker for cloud cascade failures")
print(" 5. Set up local fallback if cloud unavailable")
print(" 6. Use Jetson power modes (MAXN for performance, 15W for efficiency)")
print()
print("Model Selection by Device:")
print(" Jetson Nano (4GB): Llama 3.2 1B")
print(" Jetson Orin Nano (8GB): Llama 3.2 3B or Qwen 2.5 3B")
print(" Jetson Orin NX (16GB): Llama 3.1 8B or Mistral 7B")
print(" Jetson AGX Orin (32GB): Llama 3.1 70B (quantized) or Mixtral 8x7B")
print()
if __name__ == "__main__":
# Run the demonstration
asyncio.run(main())