Repository navigation
Expand file tree
/
Copy pathParallelDecodingScreen.tsx
More file actions
1342 lines (1253 loc) · 40.4 KB
/
Copy pathParallelDecodingScreen.tsx
File metadata and controls
1342 lines (1253 loc) · 40.4 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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useState, useEffect, useRef, useCallback } from 'react'
import {
View,
Text,
ScrollView,
TextInput,
TouchableOpacity,
StyleSheet,
ActivityIndicator,
Alert,
} from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import ReactNativeBlobUtil from 'react-native-blob-util'
import { ExampleModelSetup } from '../components/ExampleModelSetup'
import { useTheme } from '../contexts/ThemeContext'
import { createThemedStyles } from '../styles/commonStyles'
import ContextParamsModal from '../components/ContextParamsModal'
import CompletionParamsModal from '../components/CompletionParamsModal'
import { MODELS } from '../utils/constants'
import type { ContextParams, CompletionParams } from '../utils/storage'
import { loadContextParams, loadCompletionParams } from '../utils/storage'
import {
useStoredCompletionParams,
useStoredContextParams,
useStoredCustomModels,
} from '../hooks/useStoredSetting'
import { useExampleScreenHeader } from '../hooks/useExampleScreenHeader'
import { buildParallelStatePath } from '../features/parallelHelpers'
import {
createExampleModelDefinitions,
isTextGenerationModel,
type ExampleModelKey,
} from '../utils/exampleModels'
import { initLlama, LlamaContext } from '../../../src'
import type { ParallelStatus } from '../../../src'
interface ConversationSlot {
id: string
prompt: string
response: string
status: 'idle' | 'processing' | 'completed' | 'error'
startTime?: number
endTime?: number
requestId: number
stop?: () => Promise<void>
timings?: {
cache_n: number
prompt_n: number
prompt_ms: number
prompt_per_token_ms: number
prompt_per_second: number
predicted_n: number
predicted_ms: number
predicted_per_token_ms: number
predicted_per_second: number
}
}
const PARALLEL_MODELS = createExampleModelDefinitions(
Object.entries(MODELS)
.filter(([_key, model]) => model.mmproj || isTextGenerationModel(model))
.map(([key]) => key as ExampleModelKey),
)
const SYSTEM_PROMPT =
'You are a helpful AI assistant. Be concise and direct in your responses.'
const EXAMPLE_PROMPTS = [
'What is the capital of France?',
'Explain quantum computing in simple terms.',
'Write a haiku about coding.',
'What are the primary colors?',
'What is the meaning of life?',
'What is art?',
]
// Example image URLs from Lorem Picsum (free placeholder image service)
const EXAMPLE_IMAGE_URLS = [
'https://picsum.photos/id/1025/300/300', // Scenic landscape
'https://picsum.photos/id/237/300/300', // Dog image
'https://picsum.photos/id/1/200/300', // People use laptop
]
// Multimodal example prompts with image URLs to download at runtime
const MULTIMODAL_EXAMPLE_PROMPTS = [
{
text: 'What animal do you see in this image? Describe it.',
imageUrl: EXAMPLE_IMAGE_URLS[0],
},
{
text: 'Describe what you see in this image in detail.',
imageUrl: EXAMPLE_IMAGE_URLS[1],
},
{
text: 'Describe what you see in this image in detail.', // Should use same state file with 2nd prompt
imageUrl: EXAMPLE_IMAGE_URLS[2],
},
]
export default function ParallelDecodingScreen({
navigation,
}: {
navigation: any
}) {
const { theme } = useTheme()
const themedStyles = createThemedStyles(theme.colors)
const styles = createStyles(theme, themedStyles)
const insets = useSafeAreaInsets()
const [context, setContext] = useState<LlamaContext | null>(null)
const modelPathRef = useRef<string>('')
const [isModelReady, setIsModelReady] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const [initProgress, setInitProgress] = useState(0)
const [slots, setSlots] = useState<ConversationSlot[]>([])
const [parallelSlots, setParallelSlots] = useState(2)
const [customPrompt, setCustomPrompt] = useState('')
const [isParallelMode, setIsParallelMode] = useState(false)
const [isMultimodalEnabled, setIsMultimodalEnabled] = useState(false)
const [parallelStatus, setParallelStatus] = useState<ParallelStatus | null>(
null,
)
const statusSubscriptionRef = useRef<{ remove: () => void } | null>(null)
const [showContextParamsModal, setShowContextParamsModal] = useState(false)
const [showCompletionParamsModal, setShowCompletionParamsModal] =
useState(false)
const [showCustomModelModal, setShowCustomModelModal] = useState(false)
const slotsRef = useRef<ConversationSlot[]>([])
const imageCache = useRef<Map<string, string>>(new Map())
const { value: contextParams, setValue: setContextParams } =
useStoredContextParams()
const { value: completionParams, setValue: setCompletionParams } =
useStoredCompletionParams()
const { value: customModels, reload: reloadCustomModels } =
useStoredCustomModels()
const handleSaveContextParams = (params: ContextParams) => {
setContextParams(params)
}
const handleSaveCompletionParams = (params: CompletionParams) => {
setCompletionParams(params)
}
const clearSlots = useCallback(async () => {
// Cancel all active/queued requests first
const processingSlots = slotsRef.current.filter(
(t) => t.status === 'processing' || t.status === 'idle',
)
await Promise.all(
processingSlots.map(async (slot) => {
try {
if (slot.stop) await slot.stop()
} catch (err) {
console.error(`Error cancelling request ${slot.requestId}:`, err)
}
}),
)
// Then clear all slots
setSlots([])
slotsRef.current = []
}, [])
const showParallelInfo = useCallback(() => {
Alert.alert(
'Parallel Decoding',
[
`This demo showcases parallel request processing using ${parallelSlots} slots.`,
'',
'Multiple requests are processed concurrently, improving throughput and efficiency.',
'',
isMultimodalEnabled
? 'Multimodal mode is enabled! Try sending multimodal prompts with images.'
: 'Load a multimodal model (SmolVLM, InternVL3, etc.) to enable image understanding.',
'',
'Try sending multiple prompts and watch them process in parallel!',
].join('\n'),
)
}, [parallelSlots, isMultimodalEnabled])
useExampleScreenHeader({
navigation,
isModelReady,
readyActions: [
{
key: 'clear-slots',
iconName: 'refresh',
onPress: clearSlots,
},
{
key: 'completion-settings',
iconName: 'cog-outline',
onPress: () => setShowCompletionParamsModal(true),
},
{
key: 'parallel-info',
iconName: 'information-outline',
onPress: showParallelInfo,
},
],
setupActions: [
{
key: 'context-settings',
iconName: 'cog-outline',
onPress: () => setShowContextParamsModal(true),
},
],
})
// Cleanup on unmount
useEffect(
() => () => {
if (statusSubscriptionRef.current) {
statusSubscriptionRef.current.remove()
statusSubscriptionRef.current = null
}
if (context) {
context.release()
}
},
[context],
)
const initializeModel = async (modelPath: string, mmprojPath?: string) => {
try {
setIsLoading(true)
setInitProgress(0)
const params = contextParams || (await loadContextParams())
const llamaContext = await initLlama(
{
model: modelPath,
n_parallel: 8,
...params,
},
(progress) => {
// Progress is reported as 1 to 100
setInitProgress(progress)
},
)
// Initialize multimodal if mmproj path is provided
if (mmprojPath) {
console.log('Initializing multimodal support...')
const multimodalSuccess = await llamaContext.initMultimodal({
path: mmprojPath,
use_gpu: true,
})
if (!multimodalSuccess) {
console.warn('Failed to initialize multimodal support')
} else {
console.log('Multimodal initialized successfully')
}
}
// Enable parallel mode with configured slot count
const success = await llamaContext.parallel.enable({
n_parallel: parallelSlots,
n_batch: 512,
})
if (!success) {
throw new Error('Failed to enable parallel mode')
}
setContext(llamaContext)
modelPathRef.current = modelPath
setIsModelReady(true)
setIsParallelMode(true)
setInitProgress(100)
// Check if multimodal is enabled
const multimodalEnabled = await llamaContext.isMultimodalEnabled()
setIsMultimodalEnabled(multimodalEnabled)
console.log(`Parallel mode enabled with ${parallelSlots} slots`)
console.log(
`Multimodal support: ${multimodalEnabled ? 'enabled' : 'disabled'}`,
)
// Subscribe to parallel status changes
try {
const subscription = await llamaContext.parallel.subscribeToStatus(
(status) => {
setParallelStatus(status)
},
)
statusSubscriptionRef.current = subscription
// Get initial status
const initialStatus = await llamaContext.parallel.getStatus()
setParallelStatus(initialStatus)
} catch (err) {
console.warn('Failed to subscribe to status:', err)
}
} catch (error: any) {
Alert.alert('Error', `Failed to initialize model: ${error.message}`)
} finally {
setIsLoading(false)
setInitProgress(0)
}
}
const addSlot = (prompt: string) => {
const newSlot: ConversationSlot = {
id: Math.random().toString(36).substring(2, 11),
prompt,
response: '',
status: 'idle',
requestId: -1, // Will be set when request is queued
}
setSlots((prev) => [...prev, newSlot])
slotsRef.current = [...slotsRef.current, newSlot]
return newSlot
}
const updateSlot = (id: string, updates: Partial<ConversationSlot>) => {
setSlots((prev) =>
prev.map((t) => (t.id === id ? { ...t, ...updates } : t)),
)
slotsRef.current = slotsRef.current.map((t) =>
t.id === id ? { ...t, ...updates } : t,
)
}
const settleConversationResult = async (
slotId: string,
completionPromise: Promise<{
text?: string
timings?: ConversationSlot['timings']
}>,
) => {
try {
const result = await completionPromise
updateSlot(slotId, {
status: 'completed',
response: result.text || '',
endTime: Date.now(),
timings: result.timings,
})
console.log('Timings:', result.timings)
} catch (error) {
console.error('Promise error:', error)
updateSlot(slotId, {
status: 'error',
response: `${error}`,
endTime: Date.now(),
})
}
}
const startConversation = async (prompt: string, images?: string[]) => {
if (!context || !isParallelMode) {
Alert.alert('Error', 'Model not ready or parallel mode not enabled')
return
}
const slot = addSlot(prompt)
const slotId = slot.id
updateSlot(slotId, { status: 'processing', startTime: Date.now() })
try {
// Load completion params
const params = completionParams || (await loadCompletionParams())
const messages = buildConversationMessages(prompt, images)
const statePath = buildParallelStatePath(
ReactNativeBlobUtil.fs.dirs.CacheDir,
modelPathRef.current,
prompt,
images,
)
// Check if state file exists on filesystem
const stateFileExists = await ReactNativeBlobUtil.fs.exists(statePath)
const loadStatePath = stateFileExists ? statePath : undefined
// Format chat to get the formatted prompt for tokenization
const formattedChat = await context.getFormattedChat(messages, undefined)
// Tokenize the formatted prompt to get question token count
let questionTokenCount = 0
try {
const tokenizeResult = await context.tokenize(formattedChat.prompt, {
media_paths: images && images.length > 0 ? images : undefined,
})
questionTokenCount = tokenizeResult.tokens.length
console.log(
`Question token count: ${questionTokenCount}, has saved state: ${!!loadStatePath}`,
)
} catch (error) {
console.error('Error tokenizing prompt:', error)
// Continue without state if tokenization fails
questionTokenCount = 0
}
const usePromptState =
!!context.model?.is_recurrent || !!context.model?.is_hybrid
// Use parallel.completion for parallel processing with messages format
const { requestId, promise, stop } = await context.parallel.completion(
{
messages,
...params,
reasoning_format: 'auto',
n_predict: params.n_predict || 50,
// State management: load previous state if exists, always save
load_state_path: loadStatePath,
save_prompt_state_path:
usePromptState && questionTokenCount > 0 ? statePath : undefined,
save_state_path:
!usePromptState && questionTokenCount > 0 ? statePath : undefined,
save_state_size:
!usePromptState && questionTokenCount > 0
? questionTokenCount
: undefined,
},
(_reqId, data) => {
const currentSlot = slotsRef.current.find((t) => t.id === slotId)
if (currentSlot && data.token) {
updateSlot(slotId, {
response: data.accumulated_text,
})
}
},
)
// Update slot with requestId and stop function
updateSlot(slotId, { requestId, stop })
void settleConversationResult(slotId, promise)
} catch (error) {
console.error('Completion error:', error)
updateSlot(slotId, {
status: 'error',
response: `Error: ${error}`,
endTime: Date.now(),
})
}
}
const queueConversationStart = async (prompt: string, images?: string[]) => {
try {
await startConversation(prompt, images)
} catch (error) {
handleStartConversationError(prompt, error)
}
}
// Helper function to download image and convert to base64 data URI (with caching)
const downloadImageAsDataUri = async (url: string): Promise<string> => {
// Check cache first
const cached = imageCache.current.get(url)
if (cached) {
console.log(`Using cached image for ${url}`)
return cached
}
const tempPath = `${
ReactNativeBlobUtil.fs.dirs.CacheDir
}/parallel_image_${Date.now()}_${Math.random().toString(36).slice(2)}.tmp`
try {
console.log(`Downloading image from ${url}`)
const response = await withTimeout(
ReactNativeBlobUtil.config({
fileCache: true,
followRedirect: true,
path: tempPath,
}).fetch('GET', url),
15000,
`Timed out downloading image from ${url}`,
)
const statusCode = response.info().status
if (statusCode < 200 || statusCode >= 300) {
throw new Error(`Image download failed with status ${statusCode}`)
}
const base64 = await withTimeout(
ReactNativeBlobUtil.fs.readFile(tempPath, 'base64'),
5000,
`Timed out reading downloaded image from ${url}`,
)
const contentType =
response.info().headers['content-type'] ||
response.info().headers['Content-Type']
const dataUri = `data:${normalizeImageMimeType(
contentType,
)};base64,${base64}`
// Store in cache
imageCache.current.set(url, dataUri)
return dataUri
} catch (error) {
console.error(`Failed to download image from ${url}:`, error)
throw error
} finally {
try {
const tempFileExists = await ReactNativeBlobUtil.fs.exists(tempPath)
if (tempFileExists) {
await ReactNativeBlobUtil.fs.unlink(tempPath)
}
} catch (cleanupError) {
console.warn('Failed to clean up temporary image file:', cleanupError)
}
}
}
const sendExamplePrompts = async () => {
if (isMultimodalEnabled) {
await runSequentially(MULTIMODAL_EXAMPLE_PROMPTS, async (example) => {
let images: string[] | undefined
if (example.imageUrl) {
try {
const imageDataUri = await downloadImageAsDataUri(example.imageUrl)
images = [imageDataUri]
} catch (error) {
console.error('Failed to download image for example:', error)
}
}
await queueConversationStart(example.text, images)
})
return
}
await runSequentially(EXAMPLE_PROMPTS, async (prompt) => {
await queueConversationStart(prompt)
})
}
const sendCustomPrompt = () => {
const prompt = customPrompt.trim()
if (!prompt) {
return
}
setCustomPrompt('')
void queueConversationStart(prompt)
}
const cancelSlot = async (slot: ConversationSlot) => {
try {
// Use the stop function from queueCompletion
if (slot.stop) await slot.stop()
updateSlot(slot.id, {
status: 'error',
response: slot.response || 'Cancelled',
endTime: Date.now(),
})
} catch (err) {
console.error(`Error cancelling request ${slot.requestId}:`, err)
}
}
const cancelAllRequests = async () => {
if (!context) return
try {
// Cancel all processing requests using the stop function
const processingSlots = slots.filter(
(t) => t.status === 'processing' || t.status === 'idle',
)
await Promise.all(
processingSlots.map(async (slot) => {
await cancelSlot(slot)
}),
)
} catch (error) {
console.error('Error cancelling requests:', error)
}
}
const clearStateFiles = async () => {
try {
const cacheDir = ReactNativeBlobUtil.fs.dirs.CacheDir
// List all files in cache directory
const files = await ReactNativeBlobUtil.fs.ls(cacheDir)
// Filter state files (files starting with "state_" and ending with ".bin")
const stateFiles = files.filter(
(file) => file.startsWith('state_') && file.endsWith('.bin'),
)
if (stateFiles.length === 0) {
Alert.alert('Info', 'No state files found')
return
}
// Confirm before deleting
Alert.alert(
'Clear State Files',
`Found ${stateFiles.length} state file(s). Delete all?`,
[
{ text: 'Cancel', style: 'cancel' },
{
text: 'Delete',
style: 'destructive',
onPress: async () => {
try {
// Delete all state files
await Promise.all(
stateFiles.map((file) =>
ReactNativeBlobUtil.fs.unlink(`${cacheDir}/${file}`),
),
)
console.log(`Deleted ${stateFiles.length} state files`)
Alert.alert(
'Success',
`Deleted ${stateFiles.length} state file(s)`,
)
} catch (error) {
console.error('Error deleting state files:', error)
Alert.alert('Error', 'Failed to delete some state files')
}
},
},
],
)
} catch (error) {
console.error('Error listing state files:', error)
Alert.alert('Error', 'Failed to list state files')
}
}
const updateParallelSlots = async (newSlotCount: number) => {
if (!context || !isParallelMode) {
Alert.alert('Error', 'Model not ready or parallel mode not enabled')
return
}
const currentActiveCount = countActiveSlots(slots)
if (currentActiveCount > 0) {
Alert.alert('Error', 'Cannot change slot count while requests are active')
return
}
try {
const success = await context.parallel.configure({
n_parallel: newSlotCount,
n_batch: 512,
})
if (success) {
setParallelSlots(newSlotCount)
console.log(`Parallel slots updated to ${newSlotCount}`)
} else {
Alert.alert('Error', 'Failed to update parallel slot count')
}
} catch (error: any) {
Alert.alert('Error', `Failed to update parallel slots: ${error.message}`)
}
}
const activeCount = countActiveSlots(slots)
const completedCount = countCompletedSlots(slots)
const avgDuration = calculateAverageDuration(slots)
const activeRequests =
parallelStatus?.requests.filter((request) => request.state !== 'queued') ||
[]
const hasActiveRequests = activeCount > 0
if (!isModelReady) {
return (
<>
<ExampleModelSetup
description="Download a model to see how llama.rn queues multiple requests, reuses prompt state, and runs them across parallel slots."
defaultModels={PARALLEL_MODELS}
customModels={customModels || []}
onInitializeCustomModel={(_model, modelPath, mmprojPath) =>
initializeModel(modelPath, mmprojPath)
}
onInitializeModel={(_model, modelPath, mmprojPath) =>
initializeModel(modelPath, mmprojPath)
}
onReloadCustomModels={reloadCustomModels}
showCustomModelModal={showCustomModelModal}
onOpenCustomModelModal={() => setShowCustomModelModal(true)}
onCloseCustomModelModal={() => setShowCustomModelModal(false)}
customModelModalTitle="Add Custom Parallel Model"
isLoading={isLoading}
initProgress={initProgress}
progressText={`Initializing model... ${initProgress}%`}
/>
<ContextParamsModal
visible={showContextParamsModal}
onClose={() => setShowContextParamsModal(false)}
onSave={handleSaveContextParams}
/>
</>
)
}
return (
<View style={[styles.container, { paddingBottom: insets.bottom }]}>
<View style={styles.section}>
<Text style={styles.sectionTitle}>Parallel Processing Stats</Text>
<View style={styles.statsRow}>
<View style={styles.statBox}>
<Text style={styles.statLabel}>Queued</Text>
<Text style={styles.statValue}>{activeCount}</Text>
</View>
<View style={styles.statBox}>
<Text style={styles.statLabel}>Completed</Text>
<Text style={styles.statValue}>{completedCount}</Text>
</View>
<View style={styles.statBox}>
<Text style={styles.statLabel}>Avg Time</Text>
<Text style={styles.statValue}>{`${avgDuration}s`}</Text>
</View>
</View>
<View style={styles.slotCountSection}>
<View style={styles.slotCountHeader}>
<Text style={styles.slotCountLabel}>Number of Slots:</Text>
<View style={styles.slotCountControls}>
<TouchableOpacity
style={[
styles.slotAdjustButton,
(parallelSlots <= 1 || hasActiveRequests) &&
styles.slotAdjustButtonDisabled,
]}
onPress={() =>
parallelSlots > 1 && updateParallelSlots(parallelSlots - 1)
}
disabled={parallelSlots <= 1 || hasActiveRequests}
>
<Text style={styles.slotAdjustButtonText}>-</Text>
</TouchableOpacity>
<Text style={styles.slotCountValue}>{parallelSlots}</Text>
<TouchableOpacity
style={[
styles.slotAdjustButton,
(parallelSlots >= 8 || hasActiveRequests) &&
styles.slotAdjustButtonDisabled,
]}
onPress={() =>
parallelSlots < 8 && updateParallelSlots(parallelSlots + 1)
}
disabled={parallelSlots >= 8 || hasActiveRequests}
>
<Text style={styles.slotAdjustButtonText}>+</Text>
</TouchableOpacity>
</View>
</View>
{hasActiveRequests && (
<Text style={styles.slotCountHint}>
Cannot change while requests are active
</Text>
)}
</View>
</View>
{parallelStatus && (
<View style={[styles.section, styles.statusSection]}>
<Text style={styles.statusSectionTitle}>Slot Manager Status</Text>
<View style={styles.statusLegendRow}>
<View style={styles.statusLegendItem}>
<View style={[styles.statusDot, styles.statusDotActive]} />
<Text style={styles.statusLegendText}>
{`Active: ${parallelStatus.active_slots}/${parallelStatus.n_parallel}`}
</Text>
</View>
<View style={styles.statusLegendItem}>
<View style={[styles.statusDot, styles.statusDotQueued]} />
<Text style={styles.statusLegendText}>
{`Queued: ${parallelStatus.queued_requests}`}
</Text>
</View>
</View>
{activeRequests.length > 0 && (
<View style={styles.statusRequests}>
<Text style={styles.statusRequestsLabel}>Active Requests:</Text>
{activeRequests.slice(0, 3).map((req) => (
<View key={req.request_id} style={styles.statusRequestRow}>
<Text
style={[
styles.statusRequestState,
{
color: getParallelRequestStatusColor(req.state, theme),
},
]}
>
{`#${req.request_id} ${req.state}`}
</Text>
<Text style={styles.statusRequestDetails}>
{req.tokens_generated > 0
? `${
req.tokens_generated
} tokens @ ${req.tokens_per_second.toFixed(1)} t/s`
: `prompt: ${req.prompt_length} tokens`}
</Text>
</View>
))}
{activeRequests.length > 3 && (
<Text style={styles.statusRequestOverflow}>
{`+${activeRequests.length - 3} more...`}
</Text>
)}
</View>
)}
</View>
)}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Controls</Text>
<View style={styles.controlsRow}>
<TouchableOpacity
style={[styles.button, hasActiveRequests && styles.buttonDisabled]}
onPress={sendExamplePrompts}
// disabled={hasActiveRequests}
>
<Text style={styles.buttonText}>
{isMultimodalEnabled
? `Send ${MULTIMODAL_EXAMPLE_PROMPTS.length} MM Examples`
: `Send ${EXAMPLE_PROMPTS.length} Examples`}
</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={clearSlots}>
<Text style={styles.buttonText}>Clear All</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, !hasActiveRequests && styles.buttonDisabled]}
onPress={cancelAllRequests}
disabled={!hasActiveRequests}
>
<Text style={styles.buttonText}>Cancel All</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={clearStateFiles}>
<Text style={styles.buttonText}>Clear State Files</Text>
</TouchableOpacity>
</View>
<View style={styles.inputRow}>
<TextInput
style={styles.input}
placeholder="Enter custom prompt..."
placeholderTextColor={theme.colors.textSecondary}
value={customPrompt}
onChangeText={setCustomPrompt}
/>
<TouchableOpacity
style={[
styles.sendButton,
!customPrompt.trim() && styles.buttonDisabled,
]}
onPress={sendCustomPrompt}
disabled={!customPrompt.trim()}
>
<Text style={styles.buttonText}>Send</Text>
</TouchableOpacity>
</View>
</View>
<ScrollView style={styles.slotsContainer}>
{slots.length === 0 ? (
<View style={styles.emptyState}>
<Text style={styles.emptyStateText}>
{isMultimodalEnabled
? `No conversations yet.\n\nClick "Send ${MULTIMODAL_EXAMPLE_PROMPTS.length} MM Examples" to see parallel multimodal processing in action,\nor enter a custom prompt below.`
: `No conversations yet.\n\nClick "Send ${EXAMPLE_PROMPTS.length} Examples" to see parallel processing in action,\nor enter a custom prompt below.`}
</Text>
</View>
) : (
slots.map((slot) => (
<View
key={slot.id}
style={[
styles.slot,
slot.status === 'idle' && styles.slotIdle,
slot.status === 'processing' && styles.slotProcessing,
slot.status === 'completed' && styles.slotCompleted,
slot.status === 'error' && styles.slotError,
]}
>
<View style={styles.slotHeader}>
<Text
style={[
styles.slotStatus,
{ color: getSlotStatusColor(slot.status, theme) },
]}
>
{slot.status}
</Text>
<View style={styles.slotMeta}>
<Text style={styles.slotDuration}>
{getSlotDuration(slot)}
</Text>
{(slot.status === 'idle' || slot.status === 'processing') && (
<TouchableOpacity
style={styles.cancelButton}
onPress={() => cancelSlot(slot)}
>
<Text style={styles.cancelButtonText}>Cancel</Text>
</TouchableOpacity>
)}
</View>
</View>
<Text style={styles.slotPrompt}>{slot.prompt}</Text>
{slot.status === 'processing' && !slot.response ? (
<ActivityIndicator color={theme.colors.primary} />
) : (
<Text style={styles.slotResponse}>
{slot.response || 'Waiting...'}
</Text>
)}
{slot.timings && slot.status === 'completed' && (
<View style={styles.timingsSection}>
<Text style={styles.timingsLabel}>Performance:</Text>
<View style={styles.timingsRow}>
{slot.timings.cache_n > 0 && (
<Text style={styles.timingText}>
{`Cache: ${slot.timings.cache_n} tokens`}
</Text>
)}
<Text style={styles.timingText}>
{`Prompt: ${slot.timings.prompt_per_second.toFixed(
2,
)} t/s`}
</Text>
<Text style={styles.timingText}>
{`Generation: ${slot.timings.predicted_per_second.toFixed(
2,
)} t/s`}
</Text>
</View>
</View>
)}
</View>
))
)}
</ScrollView>
<CompletionParamsModal
visible={showCompletionParamsModal}
onClose={() => setShowCompletionParamsModal(false)}
onSave={handleSaveCompletionParams}
/>
</View>
)
}
function buildConversationMessages(prompt: string, images?: string[]) {
const userContent: Array<{
type: 'text' | 'image_url'
text?: string
image_url?: { url: string }
}> = []
if (images && images.length > 0) {
images.forEach((imageUrl) => {
userContent.push({
type: 'image_url',
image_url: { url: imageUrl },
})
})
}
userContent.push({
type: 'text',
text: prompt,
})
return [
{ role: 'system' as const, content: SYSTEM_PROMPT },
{ role: 'user' as const, content: userContent },
]
}
function countActiveSlots(slots: ConversationSlot[]) {
return slots.filter(
(slot) => slot.status === 'processing' || slot.status === 'idle',
).length
}
function countCompletedSlots(slots: ConversationSlot[]) {
return slots.filter((slot) => slot.status === 'completed').length
}
function calculateAverageDuration(slots: ConversationSlot[]) {
const completedSlots = slots.filter((slot) => slot.startTime && slot.endTime)
if (completedSlots.length === 0) {
return '0'
}
const totalDuration = completedSlots.reduce(
(sum, slot) => sum + (slot.endTime! - slot.startTime!) / 1000,
0,
)
return (totalDuration / completedSlots.length).toFixed(2)
}
function runSequentially<T>(items: T[], task: (item: T) => Promise<void>) {
return items.reduce(
(pending, item) => pending.then(() => task(item)),
Promise.resolve(),