-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathLlamaInternal.cpp
More file actions
1463 lines (1232 loc) · 49.4 KB
/
Copy pathLlamaInternal.cpp
File metadata and controls
1463 lines (1232 loc) · 49.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
// Copyright 2025-current Getnamo.
#include "Internal/LlamaInternal.h"
#include "common/common.h"
#include "common/sampling.h"
#include "mtmd/mtmd.h"
#include "mtmd/mtmd-helper.h"
#include "LlamaDataTypes.h"
#include "LlamaUtility.h"
#include "HardwareInfo.h"
// Cross-platform strdup. MSVC ships `_strdup` and warns about plain `strdup`;
// POSIX (glibc/clang on Linux) ships `strdup` and never had `_strdup`.
#if PLATFORM_WINDOWS
#define LLAMA_STRDUP _strdup
#else
#define LLAMA_STRDUP strdup
#endif
// ---------------------------------------------------------------------------
// Allocator-safe wrappers around common_* helpers.
//
// Helpers in `llama-common*.lib` that return STL containers by value
// (std::vector, std::string) allocate the container's backing storage with
// the LIB's allocator. When that container destructs inside our module —
// where operator new/delete is overridden to mimalloc via PerModuleInline.inl
// — the free path tries to release CRT-allocated memory through mimalloc and
// crashes inside _mi_free_block_mt with EXCEPTION_ACCESS_VIOLATION reading
// 0xfff...f. This was latent before the b9090 split of common.lib into
// llama-common.lib + llama-common-base.lib (which changed STL/allocator
// linkage relative to our module).
//
// Fix pattern: bypass the std-returning helpers and call the raw C-ABI
// `llama_*` entry points against buffers we own, so allocation and free both
// go through the same allocator (mimalloc).
// ---------------------------------------------------------------------------
namespace
{
// Replacement for `common_tokenize(ctx, text, add_special, parse_special)`.
// Output vector is owned by the caller's module.
static std::vector<llama_token> SafeTokenize(
const llama_vocab* Vocab,
const std::string& Text,
bool bAddSpecial,
bool bParseSpecial)
{
std::vector<llama_token> Out;
if (!Vocab) return Out;
const int32_t Needed = -llama_tokenize(
Vocab, Text.data(), (int32_t)Text.size(),
/*tokens*/ nullptr, /*n_tokens_max*/ 0,
bAddSpecial, bParseSpecial);
if (Needed <= 0) return Out;
Out.resize((size_t)Needed);
const int32_t Wrote = llama_tokenize(
Vocab, Text.data(), (int32_t)Text.size(),
Out.data(), (int32_t)Out.size(),
bAddSpecial, bParseSpecial);
if (Wrote < 0 || Wrote > Needed)
{
Out.clear();
return Out;
}
Out.resize((size_t)Wrote);
return Out;
}
// Replacement for `common_token_to_piece(vocab, token, special)`.
// Output string is owned by the caller's module.
static std::string SafeTokenToPiece(
const llama_vocab* Vocab,
llama_token Token,
bool bSpecial)
{
if (!Vocab) return std::string();
// Common case: pieces are short. Single attempt with a small buffer
// covers virtually all tokens; fall back to the size-probe path on
// the rare overflow.
char StackBuf[128];
const int32_t Wrote = llama_token_to_piece(
Vocab, Token, StackBuf, (int32_t)sizeof(StackBuf),
/*lstrip*/ 0, bSpecial);
if (Wrote >= 0)
{
return std::string(StackBuf, (size_t)Wrote);
}
// Negative return = required size (negated). Allocate and retry.
const int32_t Needed = -Wrote;
std::string Out;
Out.resize((size_t)Needed);
const int32_t Wrote2 = llama_token_to_piece(
Vocab, Token, Out.data(), (int32_t)Out.size(),
/*lstrip*/ 0, bSpecial);
if (Wrote2 < 0 || Wrote2 > Needed)
{
return std::string();
}
Out.resize((size_t)Wrote2);
return Out;
}
}
bool FLlamaInternal::LoadModelFromParams(const FLLMModelParams& InModelParams)
{
FString RHI = FHardwareInfo::GetHardwareDetailsString();
FString GPU = FPlatformMisc::GetPrimaryGPUBrand();
UE_LOG(LogTemp, Log, TEXT("Device Found: %s %s"), *GPU, *RHI);
LastLoadedParams = InModelParams;
// only print errors
llama_log_set([](enum ggml_log_level level, const char* text, void* /* user_data */)
{
if (level >= GGML_LOG_LEVEL_ERROR) {
// Route to UE log so it appears in editor Output Log, not just stderr
UE_LOG(LlamaLog, Warning, TEXT("[llama] %hs"), text);
}
}, nullptr);
// load dynamic backends
ggml_backend_load_all();
std::string ModelPath = TCHAR_TO_UTF8(*FLlamaPaths::ParsePathIntoFullPath(InModelParams.PathToModel));
//Regular init
llama_model_params LlamaModelParams = llama_model_default_params();
LlamaModelParams.n_gpu_layers = InModelParams.GPULayers;
LlamaModel = llama_model_load_from_file(ModelPath.c_str(), LlamaModelParams);
if (!LlamaModel)
{
FString ErrorMessage = FString::Printf(TEXT("Unable to load model at <%hs>"), ModelPath.c_str());
EmitErrorMessage(ErrorMessage, 10, __func__);
return false;
}
llama_context_params ContextParams = llama_context_default_params();
ContextParams.n_ctx = InModelParams.MaxContextLength;
ContextParams.n_batch = InModelParams.MaxBatchLength;
ContextParams.n_threads = InModelParams.Threads;
ContextParams.n_threads_batch = InModelParams.Threads;
if (InModelParams.Advanced.bEmbeddingMode)
{
ContextParams.embeddings = InModelParams.Advanced.bEmbeddingMode;
}
// Let the model decide flash attention — AUTO picks the best supported mode.
// Required for vision models (Qwen2.5-Omni etc.) where the mmproj encoder needs it.
if (!InModelParams.MmprojPath.IsEmpty())
{
ContextParams.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_AUTO;
}
SavedFlashAttnType = ContextParams.flash_attn_type;
Context = llama_init_from_model(LlamaModel, ContextParams);
if (!Context)
{
FString ErrorMessage = FString::Printf(TEXT("Unable to initialize model with given context params."));
EmitErrorMessage(ErrorMessage, 11, __func__);
return false;
}
//Only standard mode uses sampling
if (!InModelParams.Advanced.bEmbeddingMode)
{
//common sampler strategy
if (InModelParams.Advanced.Sampling.bUseCommonSampler)
{
common_params_sampling SamplingParams;
if (InModelParams.Advanced.Sampling.MinP != -1.f)
{
SamplingParams.min_p = InModelParams.Advanced.Sampling.MinP;
}
if (InModelParams.Advanced.Sampling.TopK != -1.f)
{
SamplingParams.top_k = InModelParams.Advanced.Sampling.TopK;
}
if (InModelParams.Advanced.Sampling.TopP != -1.f)
{
SamplingParams.top_p = InModelParams.Advanced.Sampling.TopP;
}
if (InModelParams.Advanced.Sampling.TypicalP != -1.f)
{
SamplingParams.typ_p = InModelParams.Advanced.Sampling.TypicalP;
}
if (InModelParams.Advanced.Sampling.Mirostat != -1)
{
SamplingParams.mirostat = InModelParams.Advanced.Sampling.Mirostat;
SamplingParams.mirostat_eta = InModelParams.Advanced.Sampling.MirostatEta;
SamplingParams.mirostat_tau = InModelParams.Advanced.Sampling.MirostatTau;
}
//Seed is either default or the one specifically passed in for deterministic results
if (InModelParams.Seed != -1)
{
SamplingParams.seed = InModelParams.Seed;
}
CommonSampler = common_sampler_init(LlamaModel, SamplingParams);
}
Sampler = llama_sampler_chain_init(llama_sampler_chain_default_params());
//Temperature is always applied
llama_sampler_chain_add(Sampler, llama_sampler_init_temp(InModelParams.Advanced.Sampling.Temp));
//If any of the repeat penalties are set, apply penalties to sampler
if (InModelParams.Advanced.Sampling.PenaltyLastN != 0 ||
InModelParams.Advanced.Sampling.PenaltyRepeat != 1.f ||
InModelParams.Advanced.Sampling.PenaltyFrequency != 0.f ||
InModelParams.Advanced.Sampling.PenaltyPresence != 0.f)
{
llama_sampler_chain_add(Sampler, llama_sampler_init_penalties(
InModelParams.Advanced.Sampling.PenaltyLastN, InModelParams.Advanced.Sampling.PenaltyRepeat,
InModelParams.Advanced.Sampling.PenaltyFrequency, InModelParams.Advanced.Sampling.PenaltyPresence));
}
//Optional sampling strategies - MinP should be applied by default of 0.05f
if (InModelParams.Advanced.Sampling.MinP != -1.f)
{
llama_sampler_chain_add(Sampler, llama_sampler_init_min_p(InModelParams.Advanced.Sampling.MinP, 1));
}
if (InModelParams.Advanced.Sampling.TopK != -1.f)
{
llama_sampler_chain_add(Sampler, llama_sampler_init_top_k(InModelParams.Advanced.Sampling.TopK));
}
if (InModelParams.Advanced.Sampling.TopP != -1.f)
{
llama_sampler_chain_add(Sampler, llama_sampler_init_top_p(InModelParams.Advanced.Sampling.TopP, 1));
}
if (InModelParams.Advanced.Sampling.TypicalP != -1.f)
{
llama_sampler_chain_add(Sampler, llama_sampler_init_typical(InModelParams.Advanced.Sampling.TypicalP, 1));
}
if (InModelParams.Advanced.Sampling.Mirostat != -1)
{
llama_sampler_chain_add(Sampler, llama_sampler_init_mirostat_v2(
InModelParams.Advanced.Sampling.Mirostat, InModelParams.Advanced.Sampling.MirostatTau, InModelParams.Advanced.Sampling.MirostatEta));
}
//Seed is either default or the one specifically passed in for deterministic results
if (InModelParams.Seed == -1)
{
llama_sampler_chain_add(Sampler, llama_sampler_init_dist(LLAMA_DEFAULT_SEED));
}
else
{
llama_sampler_chain_add(Sampler, llama_sampler_init_dist(InModelParams.Seed));
}
//NB: this is just a starting heuristic,
ContextHistory.reserve(1024);
}//End non-embedding mode
//empty by default
Template = std::string();
TemplateSource = FLlamaString::ToStd(InModelParams.CustomChatTemplate.TemplateSource);
//Prioritize: custom jinja, then name, then default
if (!InModelParams.CustomChatTemplate.Jinja.IsEmpty())
{
Template = FLlamaString::ToStd(InModelParams.CustomChatTemplate.Jinja);
if (InModelParams.CustomChatTemplate.TemplateSource.IsEmpty())
{
TemplateSource = std::string("Custom Jinja");
}
}
else if ( !InModelParams.CustomChatTemplate.TemplateSource.IsEmpty() &&
InModelParams.CustomChatTemplate.TemplateSource != TEXT("tokenizer.chat_template"))
{
//apply template source name, this may fail
std::string TemplateName = FLlamaString::ToStd(InModelParams.CustomChatTemplate.TemplateSource);
const char* TemplatePtr = llama_model_chat_template(LlamaModel, TemplateName.c_str());
if (TemplatePtr != nullptr)
{
Template = std::string(TemplatePtr);
}
}
if (InModelParams.Advanced.bEmbeddingMode)
{
Template = std::string("");
TemplateSource = std::string("embedding mode, templates not used");
}
else
{
if (Template.empty())
{
const char* TemplatePtr = llama_model_chat_template(LlamaModel, nullptr);
if (TemplatePtr != nullptr)
{
Template = std::string(TemplatePtr);
TemplateSource = std::string("tokenizer.chat_template");
}
}
}
FilledContextCharLength = 0;
//Detect thinking mode support from template
bThinkingEnabled = InModelParams.Advanced.Thinking.bEnableThinking;
bStripThinkingFromResponse = InModelParams.Advanced.Thinking.bStripThinkingFromResponse;
//Auto-detect thinking tags from template source (Qwen3, DeepSeek, etc.)
if (Template.find("<think>") != std::string::npos || Template.find("enable_thinking") != std::string::npos)
{
ThinkingOpenTag = "<think>";
ThinkingCloseTag = "</think>";
bModelSupportsThinking = true;
UE_LOG(LlamaLog, Log, TEXT("Thinking mode detected from template. Thinking %s."),
bThinkingEnabled ? TEXT("enabled") : TEXT("disabled (empty think block will be injected)"));
}
else
{
ThinkingOpenTag.clear();
ThinkingCloseTag.clear();
bModelSupportsThinking = false;
}
bIsModelLoaded = true;
//Initialize multimodal if mmproj path is provided
if (!InModelParams.MmprojPath.IsEmpty())
{
InitMultimodal(InModelParams.MmprojPath);
}
return true;
}
void FLlamaInternal::UnloadModel()
{
//Free mtmd before context/model since it holds references to them
FreeMultimodal();
if (Sampler)
{
llama_sampler_free(Sampler);
Sampler = nullptr;
}
if (Context)
{
llama_free(Context);
Context = nullptr;
}
if (LlamaModel)
{
llama_model_free(LlamaModel);
LlamaModel = nullptr;
}
if (CommonSampler)
{
common_sampler_free(CommonSampler);
CommonSampler = nullptr;
}
ContextHistory.clear();
bIsModelLoaded = false;
}
std::string FLlamaInternal::WrapPromptForRole(const std::string& Text, EChatTemplateRole Role, const std::string& OverrideTemplate, bool bAddAssistantBoS)
{
std::vector<llama_chat_message> MessageListWrapper;
MessageListWrapper.push_back({ RoleForEnum(Role), LLAMA_STRDUP(Text.c_str()) });
//pre-allocate buffer 2x the size of text
std::vector<char> Buffer;
int32 NewLen = 0;
if (OverrideTemplate.empty())
{
NewLen = ApplyTemplateFromMessagesToBuffer(Template, MessageListWrapper, Buffer, bAddAssistantBoS);
}
else
{
NewLen = ApplyTemplateFromMessagesToBuffer(OverrideTemplate, MessageListWrapper, Buffer, bAddAssistantBoS);
}
if(NewLen > 0)
{
return std::string(Buffer.data(), Buffer.data() + NewLen);
}
else
{
return std::string("");
}
}
void FLlamaInternal::StopGeneration()
{
bGenerationActive = false;
}
bool FLlamaInternal::IsGenerating()
{
return bGenerationActive;
}
int32 FLlamaInternal::MaxContext()
{
if (Context)
{
return llama_n_ctx(Context);
}
else
{
return 0;
}
}
int32 FLlamaInternal::UsedContext()
{
if (Context)
{
return llama_memory_seq_pos_max(llama_get_memory(Context), 0);
}
else
{
return 0;
}
}
bool FLlamaInternal::IsModelLoaded()
{
return bIsModelLoaded;
}
void FLlamaInternal::ResetContextHistory(bool bKeepSystemsPrompt)
{
if (!bIsModelLoaded)
{
return;
}
if (IsGenerating())
{
StopGeneration();
}
if (bKeepSystemsPrompt)
{
//Valid trim case
if (Messages.size() > 1)
{
//Rollback all the messages except the first one
RollbackContextHistoryByMessages(Messages.size() - 1);
return;
}
else
{
//Only message is the system's prompt, nothing to do
return;
}
}
//Full Reset
ContextHistory.clear();
Messages.clear();
llama_memory_clear(llama_get_memory(Context), false);
FilledContextCharLength = 0;
}
void FLlamaInternal::RollbackContextHistoryByTokens(int32 NTokensToErase)
{
// clear the last n_regen tokens from the KV cache and update n_past
// seq_pos_max returns the max position (0-indexed), so token count = seq_pos_max + 1
int32 TokenCount = llama_memory_seq_pos_max(llama_get_memory(Context), 0) + 1;
llama_memory_seq_rm(llama_get_memory(Context), 0, TokenCount - NTokensToErase, -1);
//FilledContextCharLength -= NTokensToErase;
//Run a decode to sync everything else
//llama_decode(Context, llama_batch_get_one(nullptr, 0));
}
void FLlamaInternal::RollbackContextHistoryByMessages(int32 NMessagesToErase)
{
//cannot do rollback if model isn't loaded, ignore.
if (!bIsModelLoaded)
{
return;
}
if (IsGenerating())
{
StopGeneration();
}
if (NMessagesToErase <= Messages.size())
{
Messages.resize(Messages.size() - NMessagesToErase);
}
//Obtain full prompt before it gets deleted
std::string FullPrompt(ContextHistory.data(), ContextHistory.data() + FilledContextCharLength);
//resize the context history
int32 NewLen = ApplyTemplateToContextHistory(false);
//tokenize to find out how many tokens we need to remove
//Obtain new prompt, find delta
std::string FormattedPrompt(ContextHistory.data(), ContextHistory.data() + NewLen);
std::string PromptToRemove(FullPrompt.substr(FormattedPrompt.length()));
const llama_vocab* Vocab = llama_model_get_vocab(LlamaModel);
const int NPromptTokens = -llama_tokenize(Vocab, PromptToRemove.c_str(), PromptToRemove.size(), NULL, 0, false, true);
//now rollback KV-cache
RollbackContextHistoryByTokens(NPromptTokens);
//Sync resized length;
FilledContextCharLength = NewLen;
//Shrink to fit
ContextHistory.resize(FilledContextCharLength);
}
std::string FLlamaInternal::InsertRawPrompt(const std::string& Prompt, bool bGenerateReply)
{
if (!bIsModelLoaded)
{
UE_LOG(LlamaLog, Warning, TEXT("Model isn't loaded"));
return 0;
}
int32 TokensProcessed = ProcessPrompt(Prompt);
FLlamaString::AppendToCharVector(ContextHistory, Prompt);
if (bGenerateReply)
{
std::string Response = Generate("", false);
FLlamaString::AppendToCharVector(ContextHistory, Response);
}
return "";
}
std::string FLlamaInternal::InsertTemplatedPrompt(const std::string& Prompt, EChatTemplateRole Role, bool bAddAssistantBoS, bool bGenerateReply, const std::string& AssistantPrefill)
{
if (!bIsModelLoaded)
{
UE_LOG(LlamaLog, Warning, TEXT("Model isn't loaded"));
return std::string();
}
int32 NewLen = FilledContextCharLength;
if (!Prompt.empty())
{
Messages.push_back({ RoleForEnum(Role), LLAMA_STRDUP(Prompt.c_str()) });
NewLen = ApplyTemplateToContextHistory(bAddAssistantBoS);
}
//Check for invalid lengths
if (NewLen < 0)
{
UE_LOG(LlamaLog, Warning, TEXT("Inserted prompt after templating has an invalid length of %d, skipping generation. Check your jinja template or model gguf. NB: some templates merge system prompts with user prompts (e.g. gemma) and it's considered normal behavior."), NewLen);
return std::string();
}
//Inject empty think block when thinking is disabled on a thinking-capable model
if (!bThinkingEnabled && bAddAssistantBoS && bModelSupportsThinking && NewLen > 0)
{
std::string EmptyThinkBlock = ThinkingOpenTag + "\n\n" + ThinkingCloseTag + "\n\n";
size_t InjLen = EmptyThinkBlock.size();
if (ContextHistory.size() < (size_t)NewLen + InjLen)
{
ContextHistory.resize(NewLen + InjLen);
}
memcpy(ContextHistory.data() + NewLen, EmptyThinkBlock.data(), InjLen);
NewLen += (int32)InjLen;
}
//Inject assistant prefill (raw bytes appended after the assistant turn header so the model
//continues from this text without an intervening EOT). Only valid when add_ass=true; ignored
//otherwise to avoid corrupting non-assistant turns.
if (bAddAssistantBoS && !AssistantPrefill.empty() && NewLen > 0)
{
size_t PrefillLen = AssistantPrefill.size();
if (ContextHistory.size() < (size_t)NewLen + PrefillLen)
{
ContextHistory.resize(NewLen + PrefillLen);
}
memcpy(ContextHistory.data() + NewLen, AssistantPrefill.data(), PrefillLen);
NewLen += (int32)PrefillLen;
}
else if (!bAddAssistantBoS && !AssistantPrefill.empty())
{
UE_LOG(LlamaLog, Warning, TEXT("InsertTemplatedPrompt: AssistantPrefill ignored because bAddAssistantBoS=false"));
}
//Only process non-zero prompts
if (NewLen > 0)
{
std::string FormattedPrompt(ContextHistory.data() + FilledContextCharLength, ContextHistory.data() + NewLen);
int32 TokensProcessed = ProcessPrompt(FormattedPrompt, Role);
}
FilledContextCharLength = NewLen;
//Check for a reply if we want to generate one, otherwise return an empty reply
std::string Response;
if (bGenerateReply)
{
//Run generation. AssistantPrefill is forwarded so Generate() can seed the response
//accumulator and emit the prefill through OnTokenGenerated before sampling resumes.
Response = Generate("", true, bAddAssistantBoS ? AssistantPrefill : std::string());
}
return Response;
}
void FLlamaInternal::RebuildContextFromHistory(const TArray<FStructuredChatMessage>& InMessages)
{
if (!bIsModelLoaded)
{
UE_LOG(LlamaLog, Warning, TEXT("RebuildContextFromHistory: model not loaded, skipping."));
return;
}
if (IsGenerating())
{
StopGeneration();
}
//Cheap KV+state wipe (mirrors ResetContextHistory full-reset path)
ContextHistory.clear();
Messages.clear();
llama_memory_clear(llama_get_memory(Context), false);
FilledContextCharLength = 0;
//Replay each message through the existing template+decode pipeline without generating
for (const FStructuredChatMessage& Msg : InMessages)
{
const std::string Content = TCHAR_TO_UTF8(*Msg.Content);
InsertTemplatedPrompt(Content, Msg.Role, /*bAddAssistantBoS=*/false, /*bGenerateReply=*/false);
}
}
std::string FLlamaInternal::ResumeGeneration()
{
//Todo: erase last assistant message to merge the two messages if the last message was the assistant one.
//run an empty user prompt
return Generate();
}
void FLlamaInternal::GetPromptEmbeddings(const std::string& Text, std::vector<float>& Embeddings)
{
//apply https://github.com/ggml-org/llama.cpp/blob/master/examples/embedding/embedding.cpp wrapping logic
if (!Context)
{
EmitErrorMessage(TEXT("Context invalid, did you load the model?"), 43, __func__);
return;
}
//Tokenize prompt - we're crashing out here...
//Check if our sampling/etc params are wrong or vocab is wrong.
//Try tokenizing using normal method?
//CONTINUE HERE:
// SafeTokenize replaces `common_tokenize` to keep the result vector's
// backing storage on our side of the static-lib boundary. See helper
// definition at the top of this file for the cross-allocator background.
const llama_vocab* Vocab = llama_model_get_vocab(LlamaModel);
std::vector<llama_token> Input = SafeTokenize(Vocab, Text, /*add_special*/ true, /*parse_special*/ true);
if (Input.empty())
{
UE_LOG(LlamaLog, Error, TEXT("GetPromptEmbeddings: tokenize produced 0 tokens (text bytes=%d)"),
(int32)Text.size());
return;
}
//int32 NBatch = llama_n_ctx(Context); //todo: get this from our params
int32 NBatch = Input.size(); //todo: get this from our params
llama_batch Batch = llama_batch_init(NBatch, 0, 1);
//llama_batch Batch = llama_batch_get_one(Input.data(), Input.size());
//add single batch
BatchAddSeq(Batch, Input, 0);
enum llama_pooling_type PoolingType = llama_pooling_type(Context);
//Count number of embeddings
int32 EmbeddingCount = 0;
if (PoolingType == llama_pooling_type::LLAMA_POOLING_TYPE_NONE)
{
EmbeddingCount = Input.size();
}
else
{
EmbeddingCount = 1;
}
int32 NEmbd = llama_model_n_embd(LlamaModel);
//allocate raw output buffer
std::vector<float> Raw((size_t)EmbeddingCount * NEmbd, 0.f);
//decode
BatchDecodeEmbedding(Context, Batch, Raw.data(), 0, NEmbd, 2, EmbeddingCount);
//Always return a single pooled vector. For NONE pooling, mean-pool per-token rows then re-normalize L2.
if (EmbeddingCount > 1)
{
Embeddings.assign(NEmbd, 0.f);
for (int32 t = 0; t < EmbeddingCount; ++t)
{
const float* Row = Raw.data() + t * NEmbd;
for (int32 d = 0; d < NEmbd; ++d)
{
Embeddings[d] += Row[d];
}
}
const float Inv = 1.f / static_cast<float>(EmbeddingCount);
for (int32 d = 0; d < NEmbd; ++d) { Embeddings[d] *= Inv; }
//L2 renormalize after pooling
double SumSq = 0.0;
for (int32 d = 0; d < NEmbd; ++d) { SumSq += static_cast<double>(Embeddings[d]) * Embeddings[d]; }
const float Norm = SumSq > 0.0 ? static_cast<float>(1.0 / sqrt(SumSq)) : 1.f;
for (int32 d = 0; d < NEmbd; ++d) { Embeddings[d] *= Norm; }
}
else
{
Embeddings = std::move(Raw);
}
llama_batch_free(Batch);
UE_LOG(LlamaLog, Verbose, TEXT("FLlamaInternal::GetPromptEmbeddings: %d floats (pooling=%d, tokens=%d)"),
static_cast<int32>(Embeddings.size()),
static_cast<int32>(PoolingType),
static_cast<int32>(Input.size()));
}
int32 FLlamaInternal::GetEmbeddingDimension() const
{
return LlamaModel ? llama_model_n_embd(LlamaModel) : 0;
}
int32 FLlamaInternal::ProcessPrompt(const std::string& Prompt, EChatTemplateRole Role)
{
const auto StartTime = ggml_time_us();
//Grab vocab
const llama_vocab* Vocab = llama_model_get_vocab(LlamaModel);
const bool IsFirst = llama_memory_seq_pos_max(llama_get_memory(Context), 0) == 0;
// tokenize the prompt
const int NPromptTokens = -llama_tokenize(Vocab, Prompt.c_str(), Prompt.size(), NULL, 0, IsFirst, true);
std::vector<llama_token> PromptTokens(NPromptTokens);
if (llama_tokenize(Vocab, Prompt.c_str(), Prompt.size(), PromptTokens.data(), PromptTokens.size(), IsFirst, true) < 0)
{
EmitErrorMessage(TEXT("failed to tokenize the prompt"), 21, __func__);
return NPromptTokens;
}
//All in one batch
if (LastLoadedParams.Advanced.Output.PromptProcessingPacingSleep == 0.f)
{
// prepare a batch for the prompt
llama_batch Batch = llama_batch_get_one(PromptTokens.data(), PromptTokens.size());
//check sizing before running prompt decode
int NContext = llama_n_ctx(Context);
int NContextUsed = llama_memory_seq_pos_max(llama_get_memory(Context), 0);
if (NContextUsed + NPromptTokens > NContext)
{
EmitErrorMessage(FString::Printf(
TEXT("Failed to insert, tried to insert %d tokens to currently used %d tokens which is more than the max %d context size. Try increasing the context size and re-run prompt."),
NPromptTokens, NContextUsed, NContext
), 22, __func__);
return 0;
}
// run it through the decode (input)
if (llama_decode(Context, Batch))
{
EmitErrorMessage(TEXT("Failed to decode, could not find a KV slot for the batch (try reducing the size of the batch or increase the context)."), 23, __func__);
return NPromptTokens;
}
}
//Split it and sleep between batches for pacing purposes
else
{
int32 BatchCount = LastLoadedParams.Advanced.Output.PromptProcessingPacingSplitN;
int32 TotalTokens = PromptTokens.size();
int32 TokensPerBatch = TotalTokens / BatchCount;
int32 Remainder = TotalTokens % BatchCount;
int32 StartIndex = 0;
for (int32 i = 0; i < BatchCount; i++)
{
// Calculate how many tokens to put in this batch
int32 CurrentBatchSize = TokensPerBatch + (i < Remainder ? 1 : 0);
// Slice the relevant tokens for this batch
std::vector<llama_token> BatchTokens(
PromptTokens.begin() + StartIndex,
PromptTokens.begin() + StartIndex + CurrentBatchSize
);
// Prepare the batch
llama_batch Batch = llama_batch_get_one(BatchTokens.data(), BatchTokens.size());
// Check context before running decode
int NContext = llama_n_ctx(Context);
int NContextUsed = llama_memory_seq_pos_max(llama_get_memory(Context), 0);
if (NContextUsed + BatchTokens.size() > NContext)
{
EmitErrorMessage(FString::Printf(
TEXT("Failed to insert, tried to insert %d tokens to currently used %d tokens which is more than the max %d context size. Try increasing the context size and re-run prompt."),
BatchTokens.size(), NContextUsed, NContext
), 22, __func__);
return 0;
}
// Decode this batch
if (llama_decode(Context, Batch))
{
EmitErrorMessage(TEXT("Failed to decode, could not find a KV slot for the batch (try reducing the size of the batch or increase the context)."), 23, __func__);
return BatchTokens.size();
}
StartIndex += CurrentBatchSize;
FPlatformProcess::Sleep(LastLoadedParams.Advanced.Output.PromptProcessingPacingSleep);
}
}
const auto StopTime = ggml_time_us();
const float Duration = (StopTime - StartTime) / 1000000.0f;
if (OnPromptProcessed)
{
float Speed = NPromptTokens / Duration;
OnPromptProcessed(NPromptTokens, Role, Speed);
}
return NPromptTokens;
}
std::string FLlamaInternal::Generate(const std::string& Prompt, bool bAppendToMessageHistory, const std::string& AssistantPrefill)
{
const auto StartTime = ggml_time_us();
bGenerationActive = true;
if (!Prompt.empty())
{
int32 TokensProcessed = ProcessPrompt(Prompt);
}
//Seed response accumulator with prefill so it shows up in the final response and in the
//assistant message history. The prefill bytes are assumed to already be in the KV cache
//(InsertTemplatedPrompt injects them into the prompt-eval batch). We also emit through
//OnTokenGenerated as a single piece so subscribers see one continuous stream.
std::string Response = AssistantPrefill;
if (!AssistantPrefill.empty() && OnTokenGenerated)
{
OnTokenGenerated(AssistantPrefill);
}
const llama_vocab* Vocab = llama_model_get_vocab(LlamaModel);
llama_token NewTokenId;
int32 NDecoded = 0;
// check if we have enough space in the context to evaluate this batch - might need to be inside loop
int NContext = llama_n_ctx(Context);
bool bEOGExit = false;
// For M-RoPE models (e.g. Qwen2VL), seq_pos_max reflects the max 2D spatial position of
// image tokens and is NOT the correct next text position. Use NextGenerationNPast when it has
// been set by ProcessMultimodalPrompt; otherwise fall back to seq_pos_max+1 (text-only path).
llama_pos SeqPosMaxAtGenStart = llama_memory_seq_pos_max(llama_get_memory(Context), 0);
llama_pos NPast = (NextGenerationNPast > 0)
? NextGenerationNPast
: SeqPosMaxAtGenStart + 1;
NextGenerationNPast = 0; // consumed
UE_LOG(LlamaLog, Log, TEXT("[Generate] NPast=%d seq_pos_max=%d (from_mtmd=%s)"),
(int32)NPast, (int32)SeqPosMaxAtGenStart,
(NPast != SeqPosMaxAtGenStart + 1) ? TEXT("yes") : TEXT("no"));
bool bFirstToken = true;
while (bGenerationActive) //processing can be aborted by flipping the boolean
{
//Common sampler is a bit faster
if (CommonSampler)
{
NewTokenId = common_sampler_sample(CommonSampler, Context, -1); //sample using common sampler
common_sampler_accept(CommonSampler, NewTokenId, true);
}
else
{
NewTokenId = llama_sampler_sample(Sampler, Context, -1);
}
if (bFirstToken)
{
bFirstToken = false;
const std::string FirstPiece = SafeTokenToPiece(Vocab, NewTokenId, true);
UE_LOG(LlamaLog, Log, TEXT("[Generate] first token id=%d piece='%hs'"),
(int32)NewTokenId, FirstPiece.c_str());
}
// is it an end of generation?
if (llama_vocab_is_eog(Vocab, NewTokenId))
{
bEOGExit = true;
break;
}
// convert the token to a string, print it and add it to the response.
// SafeTokenToPiece keeps the string allocation on our side of the static-lib
// boundary; see helper definition for the cross-allocator background.
std::string Piece = SafeTokenToPiece(Vocab, NewTokenId, true);
Response += Piece;
NDecoded += 1;
if (NPast + NDecoded > NContext)
{
FString ErrorMessage = FString::Printf(TEXT("Context size %d exceeded on generation. Try increasing the context size and re-run prompt"), NContext);
EmitErrorMessage(ErrorMessage, 31, __func__);
return Response;
}
if (OnTokenGenerated)
{
OnTokenGenerated(Piece);
}
// Use explicit n_past position (mirrors mtmd-cli reference implementation).
// This is critical for M-RoPE models where seq_pos_max != true next text position.
llama_batch SingleBatch = llama_batch_get_one(&NewTokenId, 1);
SingleBatch.pos = &NPast; // override auto-position with tracked n_past
if (llama_decode(Context, SingleBatch))
{
bGenerationActive = false;
FString ErrorMessage = TEXT("Failed to decode. Could not find a KV slot for the batch (try reducing the size of the batch or increase the context)");
EmitErrorMessage(ErrorMessage, 32, __func__);
//Return partial response
return Response;
}
NPast++;
//sleep pacing
if (LastLoadedParams.Advanced.Output.TokenGenerationPacingSleep > 0.f)
{
FPlatformProcess::Sleep(LastLoadedParams.Advanced.Output.TokenGenerationPacingSleep);
}
}
bGenerationActive = false;
const auto StopTime = ggml_time_us();
const float Duration = (StopTime - StartTime) / 1000000.0f;
if (bAppendToMessageHistory)
{
//Add the raw response (with thinking) to our templated messages for context preservation
Messages.push_back({ RoleForEnum(EChatTemplateRole::Assistant), LLAMA_STRDUP(Response.c_str()) });
//Sync ContextHistory
FilledContextCharLength = ApplyTemplateToContextHistory(false);
}