lib.rs 11 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use async_once_cell::OnceCell as AsyncOnceCell;
use libc::c_char;
use once_cell::sync::OnceCell;
use std::ffi::CStr;
use std::sync::atomic::{AtomicU32, Ordering};

Neelay Shah's avatar
Neelay Shah committed
22
use dynamo_llm::kv_router::{
GuanLuo's avatar
GuanLuo committed
23
    indexer::compute_block_hash_for_seq, protocols::*, publisher::KvEventPublisher,
24
};
Neelay Shah's avatar
Neelay Shah committed
25
use dynamo_runtime::{DistributedRuntime, Worker};
26
27
28
static WK: OnceCell<Worker> = OnceCell::new();
static DRT: AsyncOnceCell<DistributedRuntime> = AsyncOnceCell::new();
// [FIXME] shouldn't the publisher be instance passing between API calls?
GuanLuo's avatar
GuanLuo committed
29
static KV_PUB: OnceCell<KvEventPublisher> = OnceCell::new();
30
31
32
33
34
35
36
37

fn initialize_tracing() {
    // Sets up RUST_LOG environment variable for logging while KV Publishing
    // Example: os.environ["RUST_LOG"] = "debug"
    let subscriber = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .finish();

Ryan Olson's avatar
Ryan Olson committed
38
    tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
39

40
    tracing::debug!("Tracing initialized");
41
42
43
}

#[repr(u32)]
Neelay Shah's avatar
Neelay Shah committed
44
pub enum DynamoLlmResult {
45
46
47
48
49
    OK = 0,
    ERR = 1,
}

/// # Safety
GuanLuo's avatar
GuanLuo committed
50
/// the namespace_c_str and component_c_str are passed as pointers to C strings
51
#[no_mangle]
Neelay Shah's avatar
Neelay Shah committed
52
pub unsafe extern "C" fn dynamo_llm_init(
GuanLuo's avatar
GuanLuo committed
53
54
55
    namespace_c_str: *const c_char,
    component_c_str: *const c_char,
    worker_id: i64,
Neelay Shah's avatar
Neelay Shah committed
56
) -> DynamoLlmResult {
57
58
59
60
61
    initialize_tracing();
    let wk = match WK.get_or_try_init(Worker::from_settings) {
        Ok(wk) => wk.clone(),
        Err(e) => {
            eprintln!("Failed to initialize runtime: {:?}", e);
Neelay Shah's avatar
Neelay Shah committed
62
            return DynamoLlmResult::ERR;
63
64
65
66
67
68
69
70
71
72
73
74
75
        }
    };
    let rt = wk.runtime();
    let secondary = rt.secondary().clone();
    let result = secondary.block_on(async {
        // Initialize the distributed runtime
        match DRT
            .get_or_try_init(async { DistributedRuntime::from_settings(rt.clone()).await })
            .await
        {
            Ok(_) => Ok(()),
            Err(e) => {
                eprintln!("Failed to initialize distributed runtime: {:?}", e);
Neelay Shah's avatar
Neelay Shah committed
76
                Err(DynamoLlmResult::ERR)
77
78
79
            }
        }
    });
GuanLuo's avatar
GuanLuo committed
80
    let namespace = match unsafe { CStr::from_ptr(namespace_c_str) }.to_str() {
81
82
83
        Ok(s) => s.to_string(),
        Err(e) => {
            eprintln!("Failed to convert C string to Rust string: {:?}", e);
Neelay Shah's avatar
Neelay Shah committed
84
            return DynamoLlmResult::ERR;
85
86
87
        }
    };

GuanLuo's avatar
GuanLuo committed
88
89
    let component = match unsafe { CStr::from_ptr(component_c_str) }.to_str() {
        Ok(s) => s.to_string(),
90
91
        Err(e) => {
            eprintln!("Failed to convert C string to Rust string: {:?}", e);
Neelay Shah's avatar
Neelay Shah committed
92
            return DynamoLlmResult::ERR;
93
94
95
96
97
        }
    };

    match result {
        Ok(_) => match KV_PUB
Neelay Shah's avatar
Neelay Shah committed
98
            .get_or_try_init(move || dynamo_create_kv_publisher(namespace, component, worker_id))
99
        {
Neelay Shah's avatar
Neelay Shah committed
100
            Ok(_) => DynamoLlmResult::OK,
101
102
            Err(e) => {
                eprintln!("Failed to initialize distributed runtime: {:?}", e);
Neelay Shah's avatar
Neelay Shah committed
103
                DynamoLlmResult::ERR
104
105
106
107
108
109
110
            }
        },
        Err(e) => e,
    }
}

#[no_mangle]
Neelay Shah's avatar
Neelay Shah committed
111
pub extern "C" fn dynamo_llm_shutdown() -> DynamoLlmResult {
112
113
114
115
    let wk = match WK.get() {
        Some(wk) => wk,
        None => {
            eprintln!("Runtime not initialized");
Neelay Shah's avatar
Neelay Shah committed
116
            return DynamoLlmResult::ERR;
117
118
119
120
121
        }
    };

    wk.runtime().shutdown();

Neelay Shah's avatar
Neelay Shah committed
122
    DynamoLlmResult::OK
123
124
125
}

#[no_mangle]
Neelay Shah's avatar
Neelay Shah committed
126
127
pub extern "C" fn dynamo_llm_load_publisher_create() -> DynamoLlmResult {
    DynamoLlmResult::OK
128
129
130
131
}

// instantiate a kv publisher
// this will bring up the task to publish and the channels to await publishing events
Neelay Shah's avatar
Neelay Shah committed
132
133
// the [`dynamo_kv_publish_store_event`] call will use a handle to the publisher to send events
// store and the [`dynamo_kv_event_create_removed`] will create remove events
134
135
136
// these call mus be driving by external c++ threads that are consuming the kv events from the
// c++ executor api

Neelay Shah's avatar
Neelay Shah committed
137
fn dynamo_create_kv_publisher(
GuanLuo's avatar
GuanLuo committed
138
139
140
141
    namespace: String,
    component: String,
    worker_id: i64,
) -> Result<KvEventPublisher, anyhow::Error> {
142
    tracing::info!("Creating KV Publisher for model: {}", component);
143
144
145
146
147
    match DRT
        .get()
        .ok_or(anyhow::Error::msg("Could not get Distributed Runtime"))
    {
        Ok(drt) => {
GuanLuo's avatar
GuanLuo committed
148
149
            let backend = drt.namespace(namespace)?.component(component)?;
            KvEventPublisher::new(drt.clone(), backend, worker_id)
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
        }
        Err(e) => Err(e),
    }
}

fn kv_event_create_stored_block_from_parts(
    block_hash: u64,
    token_ids: *const u32,
    num_tokens: usize,
    _lora_id: u64,
) -> KvCacheStoredBlockData {
    let tokens_hash =
        compute_block_hash_for_seq(unsafe { std::slice::from_raw_parts(token_ids, num_tokens) })[0];
    KvCacheStoredBlockData {
        block_hash: ExternalSequenceBlockHash(block_hash),
        tokens_hash,
    }
}
static WARN_COUNT: AtomicU32 = AtomicU32::new(0);

fn kv_event_create_stored_from_parts(
    event_id: u64,
    token_ids: *const u32,
    num_block_tokens: *const usize,
    block_ids: *const u64,
    num_blocks: usize,
    parent_hash: Option<u64>,
    lora_id: u64,
) -> KvCacheEvent {
    let mut blocks: Vec<KvCacheStoredBlockData> = Vec::new();

    let mut token_offset: usize = 0;
    for block_idx in 0..num_blocks {
        let block_hash = unsafe { *block_ids.offset(block_idx.try_into().unwrap()) };
        let tokens = unsafe { token_ids.offset(token_offset.try_into().unwrap()) };
        let num_toks = unsafe { *num_block_tokens.offset(block_idx.try_into().unwrap()) };
        // compute hash only apply to full block (KV_BLOCK_SIZE token)
        if num_toks != 64 {
Ryan Olson's avatar
Ryan Olson committed
188
189
190
191
192
193
194
195
196
197
            if WARN_COUNT
                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |c| {
                    if c < 3 {
                        Some(c + 1)
                    } else {
                        None
                    }
                })
                .is_ok()
            {
198
                tracing::warn!(
Ryan Olson's avatar
Ryan Olson committed
199
200
201
                    "Block size must be 64 tokens to be published. Block size is: {}",
                    num_toks
                );
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
            }
            break;
        }
        token_offset += num_toks;
        blocks.push(kv_event_create_stored_block_from_parts(
            block_hash, tokens, num_toks, lora_id,
        ));
    }

    KvCacheEvent {
        data: KvCacheEventData::Stored(KvCacheStoreData {
            blocks,
            parent_hash: parent_hash.map(ExternalSequenceBlockHash),
        }),
        event_id,
    }
}

fn kv_event_create_removed_from_parts(
    event_id: u64,
    block_ids: *const u64,
    num_blocks: usize,
) -> KvCacheEvent {
    let block_hashes: Vec<ExternalSequenceBlockHash> =
        unsafe { std::slice::from_raw_parts(block_ids, num_blocks) }
            .to_vec()
            .iter()
            .map(|&v| ExternalSequenceBlockHash(v))
            .collect();
    KvCacheEvent {
        event_id,
        data: KvCacheEventData::Removed(KvCacheRemoveData { block_hashes }),
    }
}

/// # Safety
/// parent_hash is passed as pointer to indicate whether the blocks
/// has a parent hash or not. nullptr is used to represent no parent hash
#[no_mangle]
Neelay Shah's avatar
Neelay Shah committed
241
pub unsafe extern "C" fn dynamo_kv_event_publish_stored(
242
243
244
245
246
247
248
    event_id: u64,
    token_ids: *const u32,
    num_block_tokens: *const usize,
    block_ids: *const u64,
    num_blocks: usize,
    parent_hash: *const u64,
    lora_id: u64,
Neelay Shah's avatar
Neelay Shah committed
249
) -> DynamoLlmResult {
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
    let publisher = KV_PUB.get().unwrap();
    let parent_hash = {
        if parent_hash.is_null() {
            None
        } else {
            Some(unsafe { *parent_hash })
        }
    };
    let event = kv_event_create_stored_from_parts(
        event_id,
        token_ids,
        num_block_tokens,
        block_ids,
        num_blocks,
        parent_hash,
        lora_id,
    );
    match publisher.publish(event) {
Neelay Shah's avatar
Neelay Shah committed
268
        Ok(_) => DynamoLlmResult::OK,
269
270
        Err(e) => {
            eprintln!("Error publishing stored kv event {:?}", e);
Neelay Shah's avatar
Neelay Shah committed
271
            DynamoLlmResult::ERR
272
273
274
275
276
        }
    }
}

#[no_mangle]
Neelay Shah's avatar
Neelay Shah committed
277
pub extern "C" fn dynamo_kv_event_publish_removed(
278
279
280
    event_id: u64,
    block_ids: *const u64,
    num_blocks: usize,
Neelay Shah's avatar
Neelay Shah committed
281
) -> DynamoLlmResult {
282
283
284
    let publisher = KV_PUB.get().unwrap();
    let event = kv_event_create_removed_from_parts(event_id, block_ids, num_blocks);
    match publisher.publish(event) {
Neelay Shah's avatar
Neelay Shah committed
285
        Ok(_) => DynamoLlmResult::OK,
286
287
        Err(e) => {
            eprintln!("Error publishing removed kv event {:?}", e);
Neelay Shah's avatar
Neelay Shah committed
288
            DynamoLlmResult::ERR
289
290
291
292
293
        }
    }
}

// #[no_mangle]
Neelay Shah's avatar
Neelay Shah committed
294
// pub extern "C" fn dynamo_kv_publish_store_event(
295
296
297
298
//     event_id: u64,
//     token_ids: *const u32,
//     num_tokens: usize,
//     lora_id: u64,
Neelay Shah's avatar
Neelay Shah committed
299
// ) -> DynamoLlmResult {
300
//     // if event.is_null() || token_ids.is_null() {
Neelay Shah's avatar
Neelay Shah committed
301
//     //     return dynamoKvErrorType::INVALID_TOKEN_IDS;
302
303
304
305
306
307
308
309
310
311
312
313
//     // }

//     // let tokens = unsafe { std::slice::from_raw_parts(token_ids, num_tokens) }.to_vec();
//     // let new_event = Box::new(KvCacheStoreData {
//     //     event_id,
//     //     lora_id,
//     //     token_ids: tokens,
//     //     block_hashes: Vec::new(),
//     // });

//     // unsafe { *event = Box::into_raw(new_event) };

Neelay Shah's avatar
Neelay Shah committed
314
//     DynamoLlmResult::OK
315
316
317
// }

// #[no_mangle]
Neelay Shah's avatar
Neelay Shah committed
318
// pub extern "C" fn dynamo_kv_event_create_removed(
319
320
321
//     event_id: u64,
//     block_hashes: *const u64,
//     num_hashes: usize,
Neelay Shah's avatar
Neelay Shah committed
322
// ) -> DynamoLlmResult {
323
324
325
326
327
328
329
330
331
332
333
334
335
336
//     // if event.is_null() || block_hashes.is_null() {
//     //     return -1;
//     // }

//     // let hashes = unsafe { std::slice::from_raw_parts(block_hashes, num_hashes) }.to_vec();
//     // let new_event = Box::new(KvCacheRemoveData {
//     //     event_id,
//     //     lora_id: 0,
//     //     token_ids: Vec::new(),
//     //     block_hashes: hashes,
//     // });

//     // unsafe { *event = Box::into_raw(new_event) };
//     // 0
Neelay Shah's avatar
Neelay Shah committed
337
//     DynamoLlmResult::OK
338
339
340
341
342
// }

// /// create load publisher object and return a handle
// /// load publisher will instantiate the nats service and tie its stats handler to
// /// a watch channel receiver.  the watch channel sender will be attach to the
Neelay Shah's avatar
Neelay Shah committed
343
344
// /// handle and calls to [`dynamo_load_stats_publish`] issue the stats to the watch t
// pub extern "C" fn dynamo_load_publisher_create() -> *mut LoadPublisher {
345
346
347
348
//     // let publisher = Box::new(LoadPublisher::new());
//     // Box::into_raw(publisher)
// }

Neelay Shah's avatar
Neelay Shah committed
349
// pub extern "C" fn dynamo_load_stats_publish(
350
351
352
353
354
355
356
357
//     publisher: *mut LoadPublisher,
//     active_slots: u64,
//     total_slots: u64,
//     active_kv: u64,
//     total_kv: u64,
// ) {
//     // let publisher = unsafe { &mut *publisher };
// }