"lib/vscode:/vscode.git/clone" did not exist on "bba70a41d8a9c962f272a2de72fe2cc40a11dd27"
compute_pool_example.rs 7.13 KB
Newer Older
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
// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Example demonstrating the use of ComputePool for CPU-intensive operations
//!
//! This example shows various patterns for using Rayon with Tokio:
//! - Fork-join with scope
//! - Parallel batch processing
//! - Dynamic task spawning
//! - Integration with async services

use anyhow::Result;
use dynamo_runtime::{
    Worker,
    compute::{ComputePool, ComputePoolExt},
};
use std::sync::{Arc, Mutex};
use std::time::Instant;

/// Simulate expensive CPU-bound computation
fn expensive_computation(input: u64) -> u64 {
    // Simulate work with a simple prime check
    let mut sum = 0u64;
    for i in 2..input {
        if is_prime(i) {
            sum += i;
        }
    }
    sum
}

fn is_prime(n: u64) -> bool {
    if n <= 1 {
        return false;
    }
    for i in 2..((n as f64).sqrt() as u64 + 1) {
        if n.is_multiple_of(i) {
            return false;
        }
    }
    true
}

/// Example 1: Simple fork-join pattern
async fn example_fork_join(pool: &ComputePool) -> Result<()> {
    println!("\n=== Example 1: Fork-Join Pattern ===");

    let start = Instant::now();

    // Run two expensive computations in parallel
    let (result1, result2) = pool
        .join(
            || expensive_computation(10000),
            || expensive_computation(20000),
        )
        .await?;

    println!("Fork-join results: {} and {}", result1, result2);
    println!("Time: {:?}", start.elapsed());

    Ok(())
}

/// Example 2: Scope-based parallel execution
async fn example_scope(pool: &ComputePool) -> Result<()> {
    println!("\n=== Example 2: Scope-based Execution ===");

    let data = [1000, 2000, 3000, 4000, 5000];
    let start = Instant::now();

    let results = pool
        .execute_scoped(move |scope| {
            let results = Arc::new(Mutex::new(vec![0u64; data.len()]));

            for (i, &value) in data.iter().enumerate() {
                let results = results.clone();
                scope.spawn(move |_| {
                    let result = expensive_computation(value);
                    let mut r = results.lock().unwrap();
                    r[i] = result;
                });
            }

            Arc::try_unwrap(results).unwrap().into_inner().unwrap()
        })
        .await?;

    println!("Scope results: {:?}", results);
    println!("Time: {:?}", start.elapsed());

    Ok(())
}

/// Example 3: Parallel map using extension trait
async fn example_parallel_map(pool: &ComputePool) -> Result<()> {
    println!("\n=== Example 3: Parallel Map ===");

    let items: Vec<u64> = (1..=10).map(|i| i * 1000).collect();
    let start = Instant::now();

    let results = pool
        .parallel_map(items.clone(), expensive_computation)
        .await?;

    println!("Parallel map processed {} items", results.len());
    println!("Time: {:?}", start.elapsed());

    // Compare with sequential processing
    let start_seq = Instant::now();
    let _sequential: Vec<_> = items.iter().map(|&i| expensive_computation(i)).collect();
    println!("Sequential time: {:?}", start_seq.elapsed());

    Ok(())
}

/// Example 4: Simulating tokenization workload
async fn example_tokenization(pool: &ComputePool) -> Result<()> {
    println!("\n=== Example 4: Batch Tokenization Simulation ===");

    // Simulate batch of texts to tokenize
    let texts: Vec<String> = (0..100)
        .map(|i| {
            format!(
                "This is sample text number {} that needs to be tokenized",
                i
            )
        })
        .collect();

    let start = Instant::now();
    let texts_len = texts.len();

    // Process in parallel using scope
    let token_counts = pool
        .execute_scoped(move |scope| {
            let counts = Arc::new(Mutex::new(vec![0usize; texts_len]));

            for (i, text) in texts.iter().enumerate() {
                let text = text.clone();
                let counts = counts.clone();
                scope.spawn(move |_| {
                    // Simulate tokenization by counting words
                    let count = text.split_whitespace().count();
                    // Simulate more work
                    std::thread::sleep(std::time::Duration::from_micros(100));
                    let mut c = counts.lock().unwrap();
                    c[i] = count;
                });
            }

            Arc::try_unwrap(counts).unwrap().into_inner().unwrap()
        })
        .await?;

    let total_tokens: usize = token_counts.iter().sum();
    println!(
        "Tokenized {} texts, total tokens: {}",
        texts_len, total_tokens
    );
    println!("Time: {:?}", start.elapsed());

    Ok(())
}

/// Example 5: Hierarchical computation
async fn example_hierarchical(pool: &ComputePool) -> Result<()> {
    println!("\n=== Example 5: Hierarchical Computation ===");

    let start = Instant::now();

    let result = pool
        .execute_scoped(move |scope| {
            let phase1_results = Arc::new(Mutex::new(vec![0u64; 4]));

            // First level: compute initial values
            for i in 0..4 {
                let phase1_results = phase1_results.clone();
                scope.spawn(move |s2| {
                    let intermediate = expensive_computation((i + 1) as u64 * 1000);

                    // Second level: further process each result
                    let phase2_results = Arc::new(Mutex::new(vec![0u64; 2]));

                    for j in 0..2 {
                        let value = intermediate + (j as u64 * 100);
                        let phase2_results = phase2_results.clone();
                        s2.spawn(move |_| {
                            let result = expensive_computation(value);
                            let mut r = phase2_results.lock().unwrap();
                            r[j] = result;
                        });
                    }

                    let sum: u64 = phase2_results.lock().unwrap().iter().sum();
                    let mut p1 = phase1_results.lock().unwrap();
                    p1[i] = sum;
                });
            }

            phase1_results.lock().unwrap().iter().sum::<u64>()
        })
        .await?;

    println!("Hierarchical computation result: {}", result);
    println!("Time: {:?}", start.elapsed());

    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize logging
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        .init();

    // Create worker and runtime
    let worker = Worker::from_settings()?;
    let runtime = worker.runtime().clone();

    // Get compute pool
    let pool = runtime
        .compute_pool()
        .ok_or_else(|| anyhow::anyhow!("Compute pool not initialized"))?
        .clone();

    println!(
        "Compute pool initialized with {} threads",
        pool.num_threads()
    );

    // Run examples
    example_fork_join(&pool).await?;
    example_scope(&pool).await?;
    example_parallel_map(&pool).await?;
    example_tokenization(&pool).await?;
    example_hierarchical(&pool).await?;

    // Print metrics
    let metrics = pool.metrics();
    println!("\n=== Compute Pool Metrics ===");
    println!("{}", metrics);

    Ok(())
}