-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.cpp
More file actions
2218 lines (1968 loc) · 125 KB
/
Copy pathmodel.cpp
File metadata and controls
2218 lines (1968 loc) · 125 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
#include "model.h"
#ifdef HAS_CUDA
#include "cuda_kernels.h"
#endif
#include <algorithm>
#include <cmath>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <limits>
#include <memory>
#include <sstream>
#include <stdexcept>
#ifdef _WIN32
#include <windows.h>
#endif
#include <cassert>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <variant>
#include "cpu_attention.h"
#include "cpu_batch_processor.h"
#include "gguf_parser.h"
#include "gpu_initialization.h"
#include "kv_cache.h"
#include "logger.h"
#include "model_config.h"
#include "model_constants.h"
#include "model_macros.h"
#include "model_utils.h"
#include "quantization.h"
#include "safetensors_loader.h"
#include "utils.h"
#include "weight_management.h"
void TinyLlamaModel::initialize_weights(const SafeTensorsLoader* loader,
const GGUFData* gguf) {
Logger::info("Initializing model weights...");
int hs = config_.hidden_size;
int is = config_.intermediate_size;
int nhl = config_.num_hidden_layers;
int vs = config_.vocab_size;
layers.resize(nhl);
if (gguf) {
Logger::info("Processing weights from GGUF data source...");
if (gguf && (gguf->mapped_tensor_data || !gguf->tensor_data.empty())) {
map_gguf_weights(*gguf, *this);
Logger::info("[INIT_WEIGHTS_GGUF] map_gguf_weights(*gguf, *this) CALLED (using function parameter).");
} else if (gguf_data_ && (gguf_data_->mapped_tensor_data || !gguf_data_->tensor_data.empty())) {
map_gguf_weights(*gguf_data_, *this);
Logger::info("[INIT_WEIGHTS_GGUF] map_gguf_weights(*gguf_data_, *this) CALLED (using member gguf_data_).");
} else {
Logger::error("[INIT_WEIGHTS_GGUF] map_gguf_weights failed - tensor data not available. No GGUF weights mapped.");
}
// LAZY DEQUANTIZATION: Only dequantize what's immediately needed
Logger::info("[INIT_WEIGHTS_GGUF] Using lazy dequantization to prevent OOM");
// Only dequantize embed_tokens and final_norm immediately (small and always needed)
if (this->embed_tokens_f32.empty()) {
size_t total_elements_embed = static_cast<size_t>(config_.vocab_size) * config_.hidden_size;
if (!this->embed_tokens_q6k.empty()) {
dequantize_vector_q6k_to_f32(this->embed_tokens_q6k, this->embed_tokens_f32, total_elements_embed, 1);
} else if (!this->embed_tokens_q4k.empty()) {
dequantize_vector_q4k_to_f32(this->embed_tokens_q4k, this->embed_tokens_f32, total_elements_embed, 1);
} else if (!this->embed_tokens_q8k.empty()) {
dequantize_q8_k(this->embed_tokens_q8k, this->embed_tokens_f32, total_elements_embed, true);
} else if (!this->embed_tokens_q8_0.empty()) {
dequantize_vector_q8_0_to_f32(this->embed_tokens_q8_0, this->embed_tokens_f32, total_elements_embed, 1);
} else if (!this->embed_tokens.empty()) {
this->embed_tokens_f32 = bf16vec_to_float_vec(this->embed_tokens);
}
if (!this->embed_tokens_f32.empty()) {
Logger::info("[INIT_WEIGHTS_GGUF_DEQUANT] embed_tokens_f32 populated. Size: " + std::to_string(this->embed_tokens_f32.size()));
}
}
if (this->final_norm_f32.empty()) {
if (!this->final_norm.empty()) {
this->final_norm_f32 = bf16vec_to_float_vec(this->final_norm);
if (!this->final_norm_f32.empty()) {
Logger::info("[INIT_WEIGHTS_GGUF_DEQUANT] Successfully converted final_norm (BF16) to final_norm_f32. Size: " + std::to_string(this->final_norm_f32.size()));
}
}
}
// DEFER lm_head dequantization until actually needed (it's huge)
Logger::info("[INIT_WEIGHTS_GGUF] Deferring lm_head dequantization until needed to save memory");
// DEFER all layer weight dequantization until the layer is actually used
Logger::info("[INIT_WEIGHTS_GGUF] Deferring all layer weight dequantization until layers are used");
// Only populate layer norms immediately (small and needed for validation)
for (int l = 0; l < nhl; ++l) {
auto& lw = layers[l];
if (lw.input_layernorm_f32.empty() && !lw.input_layernorm.empty()) {
lw.input_layernorm_f32 = bf16vec_to_float_vec(lw.input_layernorm);
if (!lw.input_layernorm_f32.empty()) Logger::info(" L" + std::to_string(l) + " input_layernorm_f32 populated from BF16. Size: " + std::to_string(lw.input_layernorm_f32.size()));
}
if (lw.post_attention_layernorm_f32.empty() && !lw.post_attention_layernorm.empty()) {
lw.post_attention_layernorm_f32 = bf16vec_to_float_vec(lw.post_attention_layernorm);
if (!lw.post_attention_layernorm_f32.empty()) Logger::info(" L" + std::to_string(l) + " post_attention_layernorm_f32 populated from BF16. Size: " + std::to_string(lw.post_attention_layernorm_f32.size()));
}
}
// Validation checks for layer norms
for (int l = 0; l < nhl; ++l) {
const auto& lw = layers[l];
if (lw.input_layernorm_f32.empty()) {
Logger::error("[INIT_WEIGHTS_GGUF_CHECK] Layer " + std::to_string(l) +
": input_layernorm_f32 is EMPTY post-GGUF. This WILL cause GPU init errors if this layer is on GPU.");
}
if (lw.post_attention_layernorm_f32.empty()) {
Logger::error("[INIT_WEIGHTS_GGUF_CHECK] Layer " + std::to_string(l) +
": post_attention_layernorm_f32 is EMPTY post-GGUF. This WILL cause GPU init errors if this layer is on GPU.");
}
}
Logger::info("[INIT_WEIGHTS_GGUF] Finished per-layer NORM F32 vector checks post-GGUF.");
} else {
Logger::fatal("TinyLlamaModel::initialize_weights called with neither GGUF nor SafeTensors loader. Cannot initialize weights.");
throw std::runtime_error("Model weights source (GGUF or SafeTensors) not provided to initialize_weights.");
}
Logger::info("Finished initializing model weights logic block.");
if (this->final_norm_f32.empty()) {
Logger::error("[INIT_WEIGHTS_FINAL_CHECK] final_norm_f32 is EMPTY. This WILL cause errors if final normalization is needed in F32.");
} else {
Logger::info("[INIT_WEIGHTS_FINAL_CHECK] final_norm_f32 is POPULATED. Size: " + std::to_string(this->final_norm_f32.size()));
}
if (this->embed_tokens_f32.empty()) {
Logger::error("[INIT_WEIGHTS_FINAL_CHECK] embed_tokens_f32 is EMPTY. This WILL cause errors if token embeddings are needed in F32.");
} else {
Logger::info("[INIT_WEIGHTS_FINAL_CHECK] embed_tokens_f32 is POPULATED. Size: " + std::to_string(this->embed_tokens_f32.size()));
}
}
TinyLlamaModel::TinyLlamaModel(const ModelConfig& config,
const SafeTensorsLoader& loader)
: config_(config) { // Copies the potentially faulty config first
config_.is_gguf_file_loaded = false; // Explicitly set to false for SafeTensors path
Logger::info("Constructing TinyLlamaModel from SafeTensorsLoader (is_gguf_file_loaded set to false).");
initialize_weights(&loader, nullptr);
initialize_gpu_and_rope();
Logger::info("TinyLlamaModel construction from SafeTensorsLoader complete.");
}
TinyLlamaModel::TinyLlamaModel(const ModelConfig& initial_config,
const std::string& model_path)
: model_path_(model_path)
#ifdef HAS_CUDA
, cublas_handle_(nullptr), token_embedding_table_dev_(nullptr), lm_head_dev_(nullptr), final_norm_dev(nullptr), w_q_dev_(nullptr), w_k_dev_(nullptr), w_v_dev_(nullptr), w_o_dev_(nullptr), w_gate_dev_(nullptr), w_up_dev_(nullptr), w_down_dev_(nullptr), all_freqs_cis_dev(nullptr), x_dev_(nullptr), x_norm_dev_(nullptr), x_resid1_dev_(nullptr), x_resid2_dev_(nullptr), q_dev_(nullptr), k_dev_(nullptr), v_dev_(nullptr), attn_out_dev_(nullptr), attn_proj_dev_(nullptr), gate_vec_dev_(nullptr), up_vec_dev_(nullptr), swiglu_vec_dev_(nullptr), mlp_down_dev_(nullptr), logits_dev_(nullptr), token_embedding_table_f32_dev_(nullptr), lm_head_f32_dev_(nullptr), w_q_f32_dev_(nullptr), w_k_f32_dev_(nullptr), w_v_f32_dev_(nullptr), w_o_f32_dev_(nullptr), w_gate_f32_dev_(nullptr), w_up_f32_dev_(nullptr), w_down_f32_dev_(nullptr)
#endif
{
Logger::info("TinyLlamaModel constructor entered. Model path (from string): " + model_path);
int cli_gpu_layer_request = initial_config.num_cpu_offload_layers;
bool cli_mmap_preference = initial_config.use_mmap_for_gguf;
this->config_ = initial_config;
if (this->model_path_.empty() && !model_path.empty()) {
this->model_path_ = model_path;
}
std::unique_ptr<SafeTensorsLoader> loader = nullptr;
if (!this->model_path_.empty() && this->model_path_.size() > 5 &&
this->model_path_.substr(this->model_path_.size() - 5) == ".gguf") {
Logger::info("GGUF file detected by path in Model Constructor: " + this->model_path_);
try {
bool force_mmap_for_gguf_load = cli_mmap_preference;
Logger::info("TinyLlamaModel GGUF path: Using mmap setting " + std::string(force_mmap_for_gguf_load ? "true" : "false") +
" for gguf_meta/weight loading based on CLI mmap preference: " +
std::string(cli_mmap_preference ? "true" : "false"));
this->gguf_data_ = std::make_unique<GGUFData>(load_gguf_meta(this->model_path_, force_mmap_for_gguf_load));
ModelConfig config_from_gguf = parse_model_config_from_gguf(*(this->gguf_data_));
this->config_ = config_from_gguf;
this->config_.use_mmap_for_gguf = cli_mmap_preference;
this->config_.is_gguf_file_loaded = true;
if (cli_gpu_layer_request < 0) {
this->config_.num_cpu_offload_layers = 0;
Logger::info("TinyLlamaModel GGUF Ctor CALC: CLI hint < 0 (all GPU). num_cpu_offload_layers set to 0.");
} else if (cli_gpu_layer_request == 0) {
this->config_.num_cpu_offload_layers = this->config_.num_hidden_layers;
Logger::info("TinyLlamaModel GGUF Ctor CALC: CLI hint == 0 (all CPU). num_cpu_offload_layers set to num_hidden_layers (" + std::to_string(this->config_.num_cpu_offload_layers) + ").");
} else { // CLI hint > 0, meaning cli_gpu_layer_request is the number of desired GPU layers
if (this->config_.num_hidden_layers > 0) {
if (cli_gpu_layer_request >= this->config_.num_hidden_layers) {
this->config_.num_cpu_offload_layers = 0; // More GPU layers requested than available -> all on GPU
Logger::info("TinyLlamaModel GGUF Ctor CALC: CLI GPU layer request ("+ std::to_string(cli_gpu_layer_request) +") >= total layers. num_cpu_offload_layers set to 0.");
} else {
this->config_.num_cpu_offload_layers = this->config_.num_hidden_layers - cli_gpu_layer_request;
Logger::info("TinyLlamaModel GGUF Ctor CALC: Partial GPU. CLI GPU req: " + std::to_string(cli_gpu_layer_request) + ". num_cpu_offload_layers set to " + std::to_string(this->config_.num_cpu_offload_layers));
}
} else { // num_hidden_layers is 0 or negative, something is wrong with GGUF. Default to all CPU.
this->config_.num_cpu_offload_layers = 0;
Logger::warning("TinyLlamaModel GGUF Ctor CALC: num_hidden_layers from GGUF is <= 0. Defaulting num_cpu_offload_layers to 0. CLI GPU req: " + std::to_string(cli_gpu_layer_request));
}
}
Logger::info("TinyLlamaModel GGUF Ctor: POST-CALC (within GGUF block) final num_cpu_offload_layers = " + std::to_string(this->config_.num_cpu_offload_layers));
Logger::info("[CTOR_GGUF_DEBUG_L1860] After CLI hint logic: this->config_.num_cpu_offload_layers = " + std::to_string(this->config_.num_cpu_offload_layers) +
", this->config_.num_hidden_layers = " + std::to_string(this->config_.num_hidden_layers));
} catch (const std::exception& e) {
Logger::error("Failed to load or parse GGUF file: " + std::string(e.what()));
throw;
}
} else if (model_path.size() > 12 &&
model_path.substr(model_path.size() - 12) == ".safetensors") {
Logger::info("SafeTensors file detected: " + model_path);
ModelConfig config_from_json;
bool json_loaded_successfully = SafeTensorsLoader::load_model_config_from_json(model_path, config_from_json);
// For SafeTensors, start with JSON config, then layer CLI preferences.
if (json_loaded_successfully) {
Logger::info("Successfully loaded and parsed config.json for SafeTensors model.");
this->config_ = config_from_json; // Base is from JSON
} else {
Logger::warning("Failed to load config.json or it was not found for SafeTensors model. Proceeding with initial_config defaults and CLI overrides.");
}
this->config_.is_gguf_file_loaded = false;
this->config_.use_mmap_for_gguf = cli_mmap_preference; // This field is GGUF specific, but store CLI pref anyway.
if (cli_gpu_layer_request < 0) {
this->config_.num_cpu_offload_layers = 0;
} else if (cli_gpu_layer_request == 0) {
this->config_.num_cpu_offload_layers = this->config_.num_hidden_layers;
} else {
if (this->config_.num_hidden_layers > 0) {
if (cli_gpu_layer_request >= this->config_.num_hidden_layers) {
this->config_.num_cpu_offload_layers = 0;
} else {
this->config_.num_cpu_offload_layers = this->config_.num_hidden_layers - cli_gpu_layer_request;
}
} else {
this->config_.num_cpu_offload_layers = 0; // Fallback if num_hidden_layers not known
Logger::warning("SafeTensors path: num_hidden_layers is 0 from JSON/default. Defaulting num_cpu_offload_layers to 0 despite CLI GPU request: " + std::to_string(cli_gpu_layer_request));
}
}
Logger::info("SafeTensors path: Calculated num_cpu_offload_layers = " + std::to_string(this->config_.num_cpu_offload_layers));
try {
loader = std::make_unique<SafeTensorsLoader>(model_path);
Logger::info("SafeTensorsLoader initialized for: " + model_path);
} catch (const std::exception& e) {
Logger::error("Failed to initialize SafeTensorsLoader: " + std::string(e.what()));
throw;
}
} else {
throw std::runtime_error(
"Unsupported model file type. Please use .gguf or .safetensors");
}
Logger::info("TinyLlamaModel constructor: After specific loader block. Current config_.num_cpu_offload_layers = " + std::to_string(this->config_.num_cpu_offload_layers) +
", config_.num_hidden_layers = " + std::to_string(this->config_.num_hidden_layers));
Logger::info("TinyLlamaModel constructor: Current config_.use_mmap_for_gguf = " + std::string(this->config_.use_mmap_for_gguf ? "true" : "false"));
if (this->config_.num_cpu_offload_layers < 0) { // Should not happen if logic above is correct for -1 CLI hint
this->config_.num_cpu_offload_layers = 0;
Logger::warning("Clamping num_cpu_offload_layers: was < 0, set to 0.");
}
if (this->config_.num_hidden_layers > 0 && this->config_.num_cpu_offload_layers > this->config_.num_hidden_layers) {
Logger::warning("Clamping num_cpu_offload_layers: Requested CPU offload layers (" + std::to_string(this->config_.num_cpu_offload_layers) +
") exceeds total hidden layers (" + std::to_string(this->config_.num_hidden_layers) +
"). Clamping to " + std::to_string(this->config_.num_hidden_layers) + " (all CPU).");
this->config_.num_cpu_offload_layers = this->config_.num_hidden_layers;
}
Logger::info("TinyLlamaModel constructor: Final clamped num_cpu_offload_layers = " + std::to_string(this->config_.num_cpu_offload_layers));
Logger::info("[CTOR_DEBUG_L1921] End of Model Ctor (before initialize_weights/rope call): this->config_.num_cpu_offload_layers = " + std::to_string(this->config_.num_cpu_offload_layers) +
", this->config_.num_hidden_layers = " + std::to_string(this->config_.num_hidden_layers));
Logger::info("Final ModelConfig (before initialize_weights/rope):");
Logger::info(" hidden_size: " + std::to_string(config_.hidden_size));
Logger::info(" intermediate_size: " + std::to_string(config_.intermediate_size));
Logger::info(" num_attention_heads: " + std::to_string(config_.num_attention_heads));
Logger::info(" num_key_value_heads: " + std::to_string(config_.num_key_value_heads));
Logger::info(" num_hidden_layers: " + std::to_string(config_.num_hidden_layers));
Logger::info(" vocab_size: " + std::to_string(config_.vocab_size));
Logger::info(" max_position_embeddings: " + std::to_string(config_.max_position_embeddings));
Logger::info(" architecture: " + config_.architecture);
Logger::info(" is_gguf_file_loaded: " + std::string(config_.is_gguf_file_loaded ? "true" : "false"));
Logger::info(" use_mmap_for_gguf: " + std::string(config_.use_mmap_for_gguf ? "true" : "false"));
// --- BEGIN GGUFData Integrity Check ---
if (this->config_.is_gguf_file_loaded && this->gguf_data_) {
if (this->gguf_data_->tensor_infos_map.empty()) {
Logger::error("[CTOR_GGUF_PRE_INIT_W] CRITICAL: gguf_data_->tensor_infos_map is EMPTY. Weights will not be loaded by map_gguf_weights.");
}
} else if (this->config_.is_gguf_file_loaded && !this->gguf_data_) {
Logger::error("[CTOR_GGUF_PRE_INIT_W] CRITICAL: config_.is_gguf_file_loaded is TRUE, but gguf_data_ pointer IS NULL. Weights cannot be loaded.");
} else if (!this->config_.is_gguf_file_loaded) {
Logger::info("[CTOR_GGUF_PRE_INIT_W] Not a GGUF file load context (e.g., SafeTensors). Skipping gguf_data_ check here.");
}
// --- END GGUFData Integrity Check ---
initialize_weights(loader.get(), this->gguf_data_.get());
initialize_gpu_and_rope();
Logger::info("TinyLlamaModel (from path string) constructed and initialized successfully.");
}
TinyLlamaModel::TinyLlamaModel(const ModelConfig& config_from_session,
std::unique_ptr<GGUFData> gguf_data_from_session)
: config_(config_from_session),
gguf_data_(std::move(gguf_data_from_session)),
model_path_("loaded_from_gguf_data_memory")
#ifdef HAS_CUDA
// Initialize all CUDA pointers to nullptr as in the other constructor
, cublas_handle_(nullptr), token_embedding_table_dev_(nullptr), lm_head_dev_(nullptr), final_norm_dev(nullptr), w_q_dev_(nullptr), w_k_dev_(nullptr), w_v_dev_(nullptr), w_o_dev_(nullptr), w_gate_dev_(nullptr), w_up_dev_(nullptr), w_down_dev_(nullptr), all_freqs_cis_dev(nullptr), x_dev_(nullptr), x_norm_dev_(nullptr), x_resid1_dev_(nullptr), x_resid2_dev_(nullptr), q_dev_(nullptr), k_dev_(nullptr), v_dev_(nullptr), attn_out_dev_(nullptr), attn_proj_dev_(nullptr), gate_vec_dev_(nullptr), up_vec_dev_(nullptr), swiglu_vec_dev_(nullptr), mlp_down_dev_(nullptr), logits_dev_(nullptr), token_embedding_table_f32_dev_(nullptr), lm_head_f32_dev_(nullptr), w_q_f32_dev_(nullptr), w_k_f32_dev_(nullptr), w_v_f32_dev_(nullptr), w_o_f32_dev_(nullptr), w_gate_f32_dev_(nullptr), w_up_f32_dev_(nullptr), w_down_f32_dev_(nullptr)
#endif
{
Logger::info("TinyLlamaModel constructor entered (with pre-loaded GGUFData). Model path placeholder: " + model_path_);
this->config_.is_gguf_file_loaded = true; // Ensure this is set
if (this->config_.num_cpu_offload_layers < 0) {
this->config_.num_cpu_offload_layers = 0;
}
if (this->config_.num_hidden_layers > 0 && this->config_.num_cpu_offload_layers > this->config_.num_hidden_layers) {
Logger::warning("Requested CPU offload layers (" + std::to_string(this->config_.num_cpu_offload_layers) +
") exceeds total hidden layers (" + std::to_string(this->config_.num_hidden_layers) +
"). Clamping to " + std::to_string(this->config_.num_hidden_layers) + " layers on CPU (all CPU).");
this->config_.num_cpu_offload_layers = this->config_.num_hidden_layers;
}
Logger::info("TinyLlamaModel (pre-loaded GGUF): Final clamped num_cpu_offload_layers = " + std::to_string(this->config_.num_cpu_offload_layers));
initialize_weights(nullptr, gguf_data_.get()); // Pass raw GGUFData pointer
initialize_gpu_and_rope();
Logger::info("TinyLlamaModel (with pre-loaded GGUFData) constructed and initialized successfully.");
}
TinyLlamaModel::~TinyLlamaModel() {
#ifdef HAS_CUDA
// Only perform GPU cleanup if GPU layers were actually used
int active_num_gpu_layers = config_.num_hidden_layers - config_.num_cpu_offload_layers;
if (active_num_gpu_layers > 0) {
Logger::info("Freeing TinyLlamaModel CUDA resources...");
if (cublas_handle_) {
cublasStatus_t cublas_status = cublasDestroy(cublas_handle_);
if (cublas_status != CUBLAS_STATUS_SUCCESS) {
Logger::error("cuBLAS handle destruction failed with error code: " +
std::to_string(cublas_status));
}
cublas_handle_ = nullptr;
Logger::info("cuBLAS handle destroyed.");
}
} else {
// CPU-only mode: just clean up cuBLAS handle if it exists
if (cublas_handle_) {
cublasStatus_t cublas_status = cublasDestroy(cublas_handle_);
if (cublas_status != CUBLAS_STATUS_SUCCESS) {
Logger::error("cuBLAS handle destruction failed with error code: " +
std::to_string(cublas_status));
}
cublas_handle_ = nullptr;
}
}
// Continue GPU cleanup only if GPU layers were active
if (active_num_gpu_layers > 0) {
if (final_norm_dev) {
gpuErrchk(cudaFree(final_norm_dev));
final_norm_dev = nullptr;
}
for (auto& layer : layers) {
if (layer.input_layernorm_dev) {
gpuErrchk(cudaFree(layer.input_layernorm_dev));
layer.input_layernorm_dev = nullptr;
}
if (layer.post_attention_layernorm_dev) {
gpuErrchk(cudaFree(layer.post_attention_layernorm_dev));
layer.post_attention_layernorm_dev = nullptr;
}
}
if (all_freqs_cis_dev) {
gpuErrchk(cudaFree(all_freqs_cis_dev));
all_freqs_cis_dev = nullptr;
}
if (token_embedding_table_dev_) {
gpuErrchk(cudaFree(token_embedding_table_dev_));
token_embedding_table_dev_ = nullptr;
}
if (lm_head_dev_) {
gpuErrchk(cudaFree(lm_head_dev_));
lm_head_dev_ = nullptr;
}
if (w_q_dev_) {
gpuErrchk(cudaFree(w_q_dev_));
w_q_dev_ = nullptr;
}
if (w_k_dev_) {
gpuErrchk(cudaFree(w_k_dev_));
w_k_dev_ = nullptr;
}
if (w_v_dev_) {
gpuErrchk(cudaFree(w_v_dev_));
w_v_dev_ = nullptr;
}
if (w_o_dev_) {
gpuErrchk(cudaFree(w_o_dev_));
w_o_dev_ = nullptr;
}
if (w_gate_dev_) {
gpuErrchk(cudaFree(w_gate_dev_));
w_gate_dev_ = nullptr;
}
if (w_up_dev_) {
gpuErrchk(cudaFree(w_up_dev_));
w_up_dev_ = nullptr;
}
if (w_down_dev_) {
gpuErrchk(cudaFree(w_down_dev_));
w_down_dev_ = nullptr;
}
if (token_embedding_table_f32_dev_) {
gpuErrchk(cudaFree(token_embedding_table_f32_dev_));
token_embedding_table_f32_dev_ = nullptr;
}
if (lm_head_f32_dev_) {
gpuErrchk(cudaFree(lm_head_f32_dev_));
lm_head_f32_dev_ = nullptr;
}
if (w_q_f32_dev_) {
gpuErrchk(cudaFree(w_q_f32_dev_));
w_q_f32_dev_ = nullptr;
}
if (w_k_f32_dev_) {
gpuErrchk(cudaFree(w_k_f32_dev_));
w_k_f32_dev_ = nullptr;
}
if (w_v_f32_dev_) {
gpuErrchk(cudaFree(w_v_f32_dev_));
w_v_f32_dev_ = nullptr;
}
if (w_o_f32_dev_) {
gpuErrchk(cudaFree(w_o_f32_dev_));
w_o_f32_dev_ = nullptr;
}
if (w_gate_f32_dev_) {
gpuErrchk(cudaFree(w_gate_f32_dev_));
w_gate_f32_dev_ = nullptr;
}
if (w_up_f32_dev_) {
gpuErrchk(cudaFree(w_up_f32_dev_));
w_up_f32_dev_ = nullptr;
}
if (w_down_f32_dev_) {
gpuErrchk(cudaFree(w_down_f32_dev_));
w_down_f32_dev_ = nullptr;
}
if (x_dev_) {
gpuErrchk(cudaFree(x_dev_));
x_dev_ = nullptr;
}
if (x_norm_dev_) {
gpuErrchk(cudaFree(x_norm_dev_));
x_norm_dev_ = nullptr;
}
if (x_resid1_dev_) {
gpuErrchk(cudaFree(x_resid1_dev_));
x_resid1_dev_ = nullptr;
}
if (x_resid2_dev_) {
gpuErrchk(cudaFree(x_resid2_dev_));
x_resid2_dev_ = nullptr;
}
if (q_dev_) {
gpuErrchk(cudaFree(q_dev_));
q_dev_ = nullptr;
}
if (k_dev_) {
gpuErrchk(cudaFree(k_dev_));
k_dev_ = nullptr;
}
if (v_dev_) {
gpuErrchk(cudaFree(v_dev_));
v_dev_ = nullptr;
}
if (attn_out_dev_) {
gpuErrchk(cudaFree(attn_out_dev_));
attn_out_dev_ = nullptr;
}
if (attn_proj_dev_) {
gpuErrchk(cudaFree(attn_proj_dev_));
attn_proj_dev_ = nullptr;
}
if (gate_vec_dev_) {
gpuErrchk(cudaFree(gate_vec_dev_));
gate_vec_dev_ = nullptr;
}
if (up_vec_dev_) {
gpuErrchk(cudaFree(up_vec_dev_));
up_vec_dev_ = nullptr;
}
if (swiglu_vec_dev_) {
gpuErrchk(cudaFree(swiglu_vec_dev_));
swiglu_vec_dev_ = nullptr;
}
if (mlp_down_dev_) {
gpuErrchk(cudaFree(mlp_down_dev_));
mlp_down_dev_ = nullptr;
}
if (logits_dev_) {
gpuErrchk(cudaFree(logits_dev_));
logits_dev_ = nullptr;
}
// Free KVCache dequantization buffers
if (dequant_k_cache_buffer_dev_) {
gpuErrchk(cudaFree(dequant_k_cache_buffer_dev_));
dequant_k_cache_buffer_dev_ = nullptr;
}
if (dequant_v_cache_buffer_dev_) {
gpuErrchk(cudaFree(dequant_v_cache_buffer_dev_));
dequant_v_cache_buffer_dev_ = nullptr;
}
// Free selective KVCache dequantization buffers
if (selective_k_dequant_buffer_dev_) {
gpuErrchk(cudaFree(selective_k_dequant_buffer_dev_));
selective_k_dequant_buffer_dev_ = nullptr;
}
if (selective_v_dequant_buffer_dev_) {
gpuErrchk(cudaFree(selective_v_dequant_buffer_dev_));
selective_v_dequant_buffer_dev_ = nullptr;
}
// Free persistent batch processing buffers
free_persistent_batch_buffers();
Logger::info("Freed persistent GPU workspace buffers.");
Logger::info("Finished freeing TinyLlamaModel CUDA weight memory.");
} else {
Logger::info("CPU-only mode: No GPU resources to free.");
}
#endif
}
std::vector<float> TinyLlamaModel::forward(
std::vector<float>& input,
int n_tokens, KVCache* kv_cache,
const std::vector<int>* attention_mask) {
Logger::info("[CPU_FWD] Entered. Processing up to layer " + std::to_string(config_.num_cpu_offload_layers -1) + ". Input n_tokens: " + std::to_string(n_tokens));
int hs = config_.hidden_size;
int vs = config_.vocab_size;
int is = config_.intermediate_size;
int n_heads = config_.num_attention_heads;
int n_kv_heads = config_.num_key_value_heads;
int head_dim = hs / n_heads;
float eps = config_.rms_norm_eps;
int max_pos_embeddings = config_.max_position_embeddings;
bool log_first_gen_step = (n_tokens == 0);
bool log_this_step = log_first_gen_step || (n_tokens == 12) || (n_tokens == 13);
// Layer processing loop - ONLY for CPU-offloaded layers
for (int l = 0; l < config_.num_cpu_offload_layers; ++l) {
Logger::info("[CPU_FWD_MEM] Starting layer " + std::to_string(l) + " processing");
bool log_this_layer = log_this_step && (l == 0); // Log details only for layer 0 on specific steps
if (log_this_layer) {
Logger::info("[CPU_FWD] ------ START Layer " + std::to_string(l) +
" (pos=" + std::to_string(n_tokens) + ") ------");
log_vector_summary("Layer " + std::to_string(l) + " Input (input)", input);
}
const auto& lw = layers[l];
std::vector<float> x_norm_vec1(hs);
const std::vector<float>& w_input_norm_vec =
lw.input_layernorm_f32.empty()
? bf16vec_to_float_vec(lw.input_layernorm)
: lw.input_layernorm_f32;
rmsnorm_vector_cpu(input, w_input_norm_vec, x_norm_vec1, eps);
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": Allocating QKV vectors");
std::vector<float> q_vec(hs), k_vec(n_kv_heads * head_dim), v_vec(n_kv_heads * head_dim);
bool enable_debug_logging = (l == 0);
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": About to ensure_q_proj_dequantized");
ensure_q_proj_dequantized(l);
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": ensure_q_proj_dequantized completed");
if (!lw.q_proj_f32.empty()) matvec_f32_f32_vector_cpu(lw.q_proj_f32, x_norm_vec1, q_vec, hs, hs);
else if (!lw.q_proj_q8k.empty() && config_.is_gguf_file_loaded) matvec_q8k_f32_vector_cpu(lw.q_proj_q8k, x_norm_vec1, q_vec, hs, hs, enable_debug_logging);
else if (!lw.q_proj_q8_0.empty() && config_.is_gguf_file_loaded) matvec_q8_0_f32_vector_cpu(lw.q_proj_q8_0, x_norm_vec1, q_vec, hs, hs, enable_debug_logging);
else if (!lw.q_proj_q4k.empty() && config_.is_gguf_file_loaded) matvec_q4k_f32_vector_cpu(lw.q_proj_q4k, x_norm_vec1, q_vec, hs, hs, enable_debug_logging);
else if (!lw.q_proj_q6k.empty() && config_.is_gguf_file_loaded) matvec_q6k_f32_vector_cpu(lw.q_proj_q6k, x_norm_vec1, q_vec, hs, hs, enable_debug_logging);
else if (!lw.q_proj.empty()) matvec_bf16_f32_vector_cpu(lw.q_proj, x_norm_vec1, q_vec, hs, hs); // BF16 from SafeTensors
else throw std::runtime_error("Layer " + std::to_string(l) + ": No Q proj weights (f32, q8k, q8, q4k, q6k, bf16) for CPU");
// ... K, V projections ...
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": About to ensure_k_proj_dequantized");
ensure_k_proj_dequantized(l);
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": ensure_k_proj_dequantized completed");
if (!lw.k_proj_f32.empty()) matvec_f32_f32_vector_cpu(lw.k_proj_f32, x_norm_vec1, k_vec, n_kv_heads * head_dim, hs);
else if (!lw.k_proj_q8k.empty() && config_.is_gguf_file_loaded) matvec_q8k_f32_vector_cpu(lw.k_proj_q8k, x_norm_vec1, k_vec, n_kv_heads * head_dim, hs, enable_debug_logging);
else if (!lw.k_proj_q8_0.empty() && config_.is_gguf_file_loaded) matvec_q8_0_f32_vector_cpu(lw.k_proj_q8_0, x_norm_vec1, k_vec, n_kv_heads * head_dim, hs, enable_debug_logging);
else if (!lw.k_proj_q4k.empty() && config_.is_gguf_file_loaded) matvec_q4k_f32_vector_cpu(lw.k_proj_q4k, x_norm_vec1, k_vec, n_kv_heads * head_dim, hs, enable_debug_logging);
else if (!lw.k_proj_q6k.empty() && config_.is_gguf_file_loaded) matvec_q6k_f32_vector_cpu(lw.k_proj_q6k, x_norm_vec1, k_vec, n_kv_heads * head_dim, hs, enable_debug_logging);
else if (!lw.k_proj.empty()) matvec_bf16_f32_vector_cpu(lw.k_proj, x_norm_vec1, k_vec, n_kv_heads * head_dim, hs);
else throw std::runtime_error("Layer " + std::to_string(l) + ": No K proj weights (f32, q8k, q8, q4k, q6k, bf16) for CPU");
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": About to ensure_v_proj_dequantized");
ensure_v_proj_dequantized(l);
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": ensure_v_proj_dequantized completed");
if (!lw.v_proj_f32.empty()) matvec_f32_f32_vector_cpu(lw.v_proj_f32, x_norm_vec1, v_vec, n_kv_heads * head_dim, hs);
else if (!lw.v_proj_q8k.empty() && config_.is_gguf_file_loaded) matvec_q8k_f32_vector_cpu(lw.v_proj_q8k, x_norm_vec1, v_vec, n_kv_heads * head_dim, hs, enable_debug_logging);
else if (!lw.v_proj_q8_0.empty() && config_.is_gguf_file_loaded) matvec_q8_0_f32_vector_cpu(lw.v_proj_q8_0, x_norm_vec1, v_vec, n_kv_heads * head_dim, hs, enable_debug_logging);
else if (!lw.v_proj_q4k.empty() && config_.is_gguf_file_loaded) matvec_q4k_f32_vector_cpu(lw.v_proj_q4k, x_norm_vec1, v_vec, n_kv_heads * head_dim, hs, enable_debug_logging);
else if (!lw.v_proj_q6k.empty() && config_.is_gguf_file_loaded) matvec_q6k_f32_vector_cpu(lw.v_proj_q6k, x_norm_vec1, v_vec, n_kv_heads * head_dim, hs, enable_debug_logging);
else if (!lw.v_proj.empty()) matvec_bf16_f32_vector_cpu(lw.v_proj, x_norm_vec1, v_vec, n_kv_heads * head_dim, hs);
else throw std::runtime_error("Layer " + std::to_string(l) + ": No V proj weights (f32, q8k, q8, q4k, q6k, bf16) for CPU");
apply_rope_vector(q_vec, n_heads, head_dim, n_tokens, precomputed_freqs_cis_, max_pos_embeddings, config_.is_gguf_file_loaded);
apply_rope_vector(k_vec, n_kv_heads, head_dim, n_tokens, precomputed_freqs_cis_, max_pos_embeddings, config_.is_gguf_file_loaded);
if (kv_cache) {
if (static_cast<size_t>(l) < kv_cache->layers.size()) {
KVCacheLayer& kv_layer = kv_cache->layers[l];
size_t layer_max_seq_len = static_cast<size_t>(kv_cache->max_seq_len_config_);
if (static_cast<size_t>(n_tokens) >= layer_max_seq_len && layer_max_seq_len > 0) {
Logger::error("KV Cache access out of bounds in CPU forward. Layer " + std::to_string(l) +
", n_tokens: " + std::to_string(n_tokens) +
", configured layer_max_seq_len: " + std::to_string(layer_max_seq_len) + ". Skipping KV update.");
} else if (layer_max_seq_len == 0 && n_tokens > 0) {
Logger::error("KV Cache layer_max_seq_len is 0, but n_tokens > 0. Layer " + std::to_string(l) + ". Skipping KV update.");
} else {
for(int h=0; h < n_kv_heads; ++h) {
std::copy(k_vec.begin() + h * head_dim, k_vec.begin() + (h+1) * head_dim, kv_layer.k.begin() + n_tokens * (n_kv_heads * head_dim) + h * head_dim);
std::copy(v_vec.begin() + h * head_dim, v_vec.begin() + (h+1) * head_dim, kv_layer.v.begin() + n_tokens * (n_kv_heads * head_dim) + h * head_dim);
}
}
} else {
Logger::error("KV Cache layer index " + std::to_string(l) + " out of bounds for kv_cache->layers.size() = " + std::to_string(kv_cache->layers.size()));
}
}
std::vector<float> attn_out_vec(hs);
std::vector<float> x_resid1_vec = input; // Store residual
float att_scale = 1.0f / std::sqrt(static_cast<float>(head_dim));
std::fill(attn_out_vec.begin(), attn_out_vec.end(), 0.0f);
for (int h = 0; h < n_heads; ++h) {
std::vector<float> q_head(head_dim);
std::copy(q_vec.begin() + h * head_dim, q_vec.begin() + (h + 1) * head_dim, q_head.begin());
std::vector<float> current_multihead_attn_out(head_dim, 0.0f);
int kv_cache_num_kv_heads = n_kv_heads; // from KVCache struct if available
int kv_group = n_heads / kv_cache_num_kv_heads;
int kv_head_idx = h / kv_group;
if (kv_cache && static_cast<size_t>(l) < kv_cache->layers.size()) {
const KVCacheLayer& kv_layer = kv_cache->layers[l];
int current_seq_len = n_tokens + 1;
std::vector<float> scores(current_seq_len);
for (int t = 0; t < current_seq_len; ++t) {
float score = 0.0f;
for (int d = 0; d < head_dim; ++d) {
score += q_head[d] * kv_layer.k[t * (n_kv_heads * head_dim) + kv_head_idx * head_dim + d];
}
scores[t] = score * att_scale;
}
softmax_vector_cpu(scores, scores); // In-place softmax
for (int t = 0; t < current_seq_len; ++t) {
for (int d = 0; d < head_dim; ++d) {
current_multihead_attn_out[d] += scores[t] * kv_layer.v[t * (n_kv_heads * head_dim) + kv_head_idx * head_dim + d];
}
}
}
std::copy(current_multihead_attn_out.begin(), current_multihead_attn_out.end(), attn_out_vec.begin() + h * head_dim);
}
std::vector<float> attn_proj_vec(hs);
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": About to ensure_o_proj_dequantized");
ensure_o_proj_dequantized(l);
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": ensure_o_proj_dequantized completed");
if(!lw.o_proj_f32.empty()) matvec_f32_f32_vector_cpu(lw.o_proj_f32, attn_out_vec, attn_proj_vec, hs, hs);
else if (!lw.o_proj_q8k.empty() && config_.is_gguf_file_loaded) matvec_q8k_f32_vector_cpu(lw.o_proj_q8k, attn_out_vec, attn_proj_vec, hs, hs, enable_debug_logging);
else if (!lw.o_proj_q8_0.empty() && config_.is_gguf_file_loaded) matvec_q8_0_f32_vector_cpu(lw.o_proj_q8_0, attn_out_vec, attn_proj_vec, hs, hs, enable_debug_logging);
else if (!lw.o_proj_q4k.empty() && config_.is_gguf_file_loaded) matvec_q4k_f32_vector_cpu(lw.o_proj_q4k, attn_out_vec, attn_proj_vec, hs, hs, enable_debug_logging);
else if (!lw.o_proj_q6k.empty() && config_.is_gguf_file_loaded) matvec_q6k_f32_vector_cpu(lw.o_proj_q6k, attn_out_vec, attn_proj_vec, hs, hs, enable_debug_logging);
else if(!lw.o_proj.empty()) matvec_bf16_f32_vector_cpu(lw.o_proj, attn_out_vec, attn_proj_vec, hs, hs);
else throw std::runtime_error("Layer " + std::to_string(l) + ": No O proj weights (f32, q8k, q8, q4k, q6k, bf16) for CPU");
for(size_t i=0; i<input.size(); ++i) input[i] = x_resid1_vec[i] + attn_proj_vec[i]; // Update input by reference
// MLP part
std::vector<float> x_norm_vec2(hs);
std::vector<float> x_resid2_vec = input; // Store residual for MLP
const std::vector<float>& w_post_attn_norm_vec =
lw.post_attention_layernorm_f32.empty()
? bf16vec_to_float_vec(lw.post_attention_layernorm)
: lw.post_attention_layernorm_f32;
rmsnorm_vector_cpu(input, w_post_attn_norm_vec, x_norm_vec2, eps);
std::vector<float> gate_vec(is), up_vec(is);
// Gate-projection
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": About to ensure_gate_proj_dequantized");
ensure_gate_proj_dequantized(l);
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": ensure_gate_proj_dequantized completed");
if(!lw.gate_proj_f32.empty()) matvec_f32_f32_vector_cpu(lw.gate_proj_f32, x_norm_vec2, gate_vec, is, hs);
else if (!lw.gate_proj_q8k.empty() && config_.is_gguf_file_loaded) matvec_q8k_f32_vector_cpu(lw.gate_proj_q8k, x_norm_vec2, gate_vec, is, hs, enable_debug_logging);
else if (!lw.gate_proj_q8_0.empty() && config_.is_gguf_file_loaded) matvec_q8_0_f32_vector_cpu(lw.gate_proj_q8_0, x_norm_vec2, gate_vec, is, hs, enable_debug_logging);
else if (!lw.gate_proj_q4k.empty() && config_.is_gguf_file_loaded) matvec_q4k_f32_vector_cpu(lw.gate_proj_q4k, x_norm_vec2, gate_vec, is, hs, enable_debug_logging);
else if (!lw.gate_proj_q6k.empty() && config_.is_gguf_file_loaded) matvec_q6k_f32_vector_cpu(lw.gate_proj_q6k, x_norm_vec2, gate_vec, is, hs, enable_debug_logging);
else if(!lw.gate_proj.empty()) matvec_bf16_f32_vector_cpu(lw.gate_proj, x_norm_vec2, gate_vec, is, hs);
else throw std::runtime_error("Layer " + std::to_string(l) + ": No Gate proj weights (f32, q8k, q8, q4k, q6k, bf16) for CPU");
// Up-projection
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": About to ensure_up_proj_dequantized");
ensure_up_proj_dequantized(l);
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": ensure_up_proj_dequantized completed");
if(!lw.up_proj_f32.empty()) matvec_f32_f32_vector_cpu(lw.up_proj_f32, x_norm_vec2, up_vec, is, hs);
else if (!lw.up_proj_q8k.empty() && config_.is_gguf_file_loaded) matvec_q8k_f32_vector_cpu(lw.up_proj_q8k, x_norm_vec2, up_vec, is, hs, enable_debug_logging);
else if (!lw.up_proj_q8_0.empty() && config_.is_gguf_file_loaded) matvec_q8_0_f32_vector_cpu(lw.up_proj_q8_0, x_norm_vec2, up_vec, is, hs, enable_debug_logging);
else if (!lw.up_proj_q4k.empty() && config_.is_gguf_file_loaded) matvec_q4k_f32_vector_cpu(lw.up_proj_q4k, x_norm_vec2, up_vec, is, hs, enable_debug_logging);
else if (!lw.up_proj_q6k.empty() && config_.is_gguf_file_loaded) matvec_q6k_f32_vector_cpu(lw.up_proj_q6k, x_norm_vec2, up_vec, is, hs, enable_debug_logging);
else if(!lw.up_proj.empty()) matvec_bf16_f32_vector_cpu(lw.up_proj, x_norm_vec2, up_vec, is, hs);
else throw std::runtime_error("Layer " + std::to_string(l) + ": No Up proj weights (f32, q8k, q8, q4k, q6k, bf16) for CPU");
std::vector<float> silu_out_vec(is);
silu_cpu(gate_vec, silu_out_vec);
std::vector<float> swiglu_result_vec(is);
for(size_t i=0; i<is; ++i) swiglu_result_vec[i] = silu_out_vec[i] * up_vec[i];
std::vector<float> mlp_out_vec(hs);
// Down-projection
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": About to ensure_down_proj_dequantized");
ensure_down_proj_dequantized(l);
Logger::info("[CPU_FWD_MEM] Layer " + std::to_string(l) + ": ensure_down_proj_dequantized completed");
if(!lw.down_proj_f32.empty()) matvec_f32_f32_vector_cpu(lw.down_proj_f32, swiglu_result_vec, mlp_out_vec, hs, is);
else if (!lw.down_proj_q8k.empty() && config_.is_gguf_file_loaded) matvec_q8k_f32_vector_cpu(lw.down_proj_q8k, swiglu_result_vec, mlp_out_vec, hs, is, enable_debug_logging);
else if (!lw.down_proj_q8_0.empty() && config_.is_gguf_file_loaded) matvec_q8_0_f32_vector_cpu(lw.down_proj_q8_0, swiglu_result_vec, mlp_out_vec, hs, is, enable_debug_logging);
else if (!lw.down_proj_q4k.empty() && config_.is_gguf_file_loaded) matvec_q4k_f32_vector_cpu(lw.down_proj_q4k, swiglu_result_vec, mlp_out_vec, hs, is, enable_debug_logging);
else if (!lw.down_proj_q6k.empty() && config_.is_gguf_file_loaded) matvec_q6k_f32_vector_cpu(lw.down_proj_q6k, swiglu_result_vec, mlp_out_vec, hs, is, enable_debug_logging);
else if(!lw.down_proj.empty()) matvec_bf16_f32_vector_cpu(lw.down_proj, swiglu_result_vec, mlp_out_vec, hs, is);
else throw std::runtime_error("Layer " + std::to_string(l) + ": No Down proj weights (f32, q8k, q8, q4k, q6k, bf16) for CPU");
for(size_t i=0; i<input.size(); ++i) input[i] = x_resid2_vec[i] + mlp_out_vec[i]; // Update input by reference
if (log_this_layer) {
Logger::info("[CPU_FWD] ------ END Layer " + std::to_string(l) +
" (pos=" + std::to_string(n_tokens) + ") ------");
}
if (config_.enable_memory_efficient_layers && l >= 2) {
int layer_to_clear = l - 2;
int first_gpu_layer = config_.num_cpu_offload_layers;
if (layer_to_clear < first_gpu_layer) {
clear_layer_dequantized_weights(layer_to_clear);
}
}
}
if (config_.num_cpu_offload_layers == config_.num_hidden_layers) {
Logger::info("[CPU_FWD] All layers processed on CPU. Performing final RMSNorm and Logits.");
const std::vector<float>& w_final_norm_vec =
final_norm_f32.empty() ? bf16vec_to_float_vec(final_norm)
: final_norm_f32;
std::vector<float> x_final_norm_vec(hs);
rmsnorm_vector_cpu(input, w_final_norm_vec, x_final_norm_vec, eps);
std::vector<float> logits(vs);
ensure_lm_head_dequantized();
bool enable_lm_head_debug_logging = true; // Always log LM head for debugging
if (!lm_head_f32.empty()) matvec_f32_f32_vector_cpu(lm_head_f32, x_final_norm_vec, logits, vs, hs);
else if (!lm_head_q8k.empty() && config_.is_gguf_file_loaded) matvec_q8k_f32_vector_cpu(lm_head_q8k, x_final_norm_vec, logits, vs, hs, enable_lm_head_debug_logging);
else if (!lm_head_q8_0.empty() && config_.is_gguf_file_loaded) matvec_q8_0_f32_vector_cpu(lm_head_q8_0, x_final_norm_vec, logits, vs, hs, enable_lm_head_debug_logging);
else if (!lm_head_q4k.empty() && config_.is_gguf_file_loaded) matvec_q4k_f32_vector_cpu(lm_head_q4k, x_final_norm_vec, logits, vs, hs, enable_lm_head_debug_logging);
else if (!lm_head_q6k.empty() && config_.is_gguf_file_loaded) matvec_q6k_f32_vector_cpu(lm_head_q6k, x_final_norm_vec, logits, vs, hs, enable_lm_head_debug_logging);
else if (!lm_head.empty()) matvec_bf16_f32_vector_cpu(lm_head, x_final_norm_vec, logits, vs, hs); // Fallback for BF16 SafeTensors
else throw std::runtime_error("No valid LM Head weights (f32, q8k, q8, q4k, q6k, bf16) found for CPU final stage.");
if (log_this_step || log_first_gen_step) {
log_vector_summary("[CPU_FWD] Final Logits (all CPU, pos=" + std::to_string(n_tokens) + ")", logits, 15);
}
return logits; // Return final logits if all layers were CPU
}
Logger::info("[CPU_FWD] Finished processing " + std::to_string(config_.num_cpu_offload_layers) + " CPU layers. Output is intermediate activation.");
return input; // Return the intermediate activations if not all layers were processed here.
}
#ifdef HAS_CUDA
std::vector<float> TinyLlamaModel::forward_device(
float* x_input_dev,
int pos, KVCache* kv_cache,
const std::vector<int>* attention_mask, cudaStream_t stream) {
int hs = config_.hidden_size;
int vs = config_.vocab_size;
int n_heads = config_.num_attention_heads;
int n_kv_heads = config_.num_key_value_heads;
if (n_heads == 0) {
Logger::fatal("Number of attention heads is zero during forward_device.");
throw std::runtime_error("Division by zero: n_heads is zero.");
}
int head_dim = hs / n_heads;
int total_model_layers = config_.num_hidden_layers;
int num_cpu_layers = config_.num_cpu_offload_layers;
int num_gpu_layers = total_model_layers - num_cpu_layers;
if (num_gpu_layers <= 0) {
Logger::warning("forward_device called with no GPU layers to process (num_gpu_layers = " + std::to_string(num_gpu_layers) + "). Returning empty.");
return {};
}
if (!x_input_dev) {
Logger::error("forward_device called with null x_input_dev. This should be model_->x_dev_.");
return {};
}
if (!kv_cache) {
Logger::error("forward_device called with null KVCache.");
return {};
}
int is = config_.intermediate_size;
float eps = config_.rms_norm_eps;
std::vector<float> h_x_input_dev(config_.hidden_size);
cublasStatus_t stream_status = cublasSetStream(cublas_handle_, stream);
gpuErrchk(cudaMemcpyAsync(h_x_input_dev.data(), x_input_dev, config_.hidden_size * sizeof(float), cudaMemcpyDeviceToHost, stream));
gpuErrchk(cudaStreamSynchronize(stream));
if (stream_status != CUBLAS_STATUS_SUCCESS) {
Logger::error("cublasSetStream failed in forward_device");
return {};
}
float* current_x_dev = x_input_dev;
for (int l_gpu_idx = 0; l_gpu_idx < num_gpu_layers; ++l_gpu_idx) {
int l_model_idx = num_cpu_layers + l_gpu_idx;
// Layer-specific norm weights are indexed by the model layer index (l_model_idx)
const float* lw_in_norm_dev = layers[l_model_idx].input_layernorm_dev;
const float* lw_post_norm_dev = layers[l_model_idx].post_attention_layernorm_dev;
gpuErrchk(cudaMemcpyAsync(x_resid1_dev_, x_dev_, hs * sizeof(float),
cudaMemcpyDeviceToDevice, stream));
if (!lw_in_norm_dev) {
throw std::runtime_error("[TM::fw_dev pos=" + std::to_string(pos) + " L" + std::to_string(l_model_idx) + "] Error: input_layernorm_dev is nullptr. GPU layer cannot proceed.");
}
// Use optimized kernels if enabled, fallback to standard if needed
if (config_.use_optimized_cuda_kernels) {
rmsnorm_vector_cuda_optimized(x_dev_, lw_in_norm_dev, x_norm_dev_, hs, eps, stream);
} else {
rmsnorm_vector_cuda(x_dev_, lw_in_norm_dev, x_norm_dev_, hs, eps, stream);
}
// Use concatenated weights for optimal performance
ensure_f32_concatenated_weights_loaded();
if (w_q_f32_dev_ && w_k_f32_dev_ && w_v_f32_dev_) {
const float* w_q_layer_ptr = w_q_f32_dev_ + (size_t)l_gpu_idx * hs * hs;
const float* w_k_layer_ptr = w_k_f32_dev_ + (size_t)l_gpu_idx * n_kv_heads * head_dim * hs;
const float* w_v_layer_ptr = w_v_f32_dev_ + (size_t)l_gpu_idx * n_kv_heads * head_dim * hs;
matvec_f32_f32_cuda(cublas_handle_, w_q_layer_ptr, x_norm_dev_,
q_dev_, hs, hs, stream);
matvec_f32_f32_cuda(cublas_handle_, w_k_layer_ptr, x_norm_dev_,
k_dev_, n_kv_heads * head_dim, hs, stream);
matvec_f32_f32_cuda(cublas_handle_, w_v_layer_ptr, x_norm_dev_,
v_dev_, n_kv_heads * head_dim, hs, stream);
} else {
Logger::error("GPU L" + std::to_string(l_model_idx) + " (gpu_idx " + std::to_string(l_gpu_idx) + "): No valid concatenated QKV weights."); return {};
}
rope_cuda(q_dev_, n_heads, head_dim, all_freqs_cis_dev, pos, config_.is_gguf_file_loaded, stream);
rope_cuda(k_dev_, n_kv_heads, head_dim, all_freqs_cis_dev, pos, config_.is_gguf_file_loaded, stream);
// K/V Cache Update Logic
if (static_cast<size_t>(l_model_idx) < kv_cache->layers.size()) {
KVCacheLayer& current_kv_layer = kv_cache->layers[l_model_idx];
if (config_.use_kvcache_quantization) {
for (int kvh = 0; kvh < n_kv_heads; ++kvh) {
const float* current_k_head_ptr_fp32 = k_dev_ + kvh * head_dim;
const float* current_v_head_ptr_fp32 = v_dev_ + kvh * head_dim;
size_t token_head_offset_quant = (static_cast<size_t>(pos) * n_kv_heads + kvh) * head_dim;
int8_t* k_quant_target_ptr = current_kv_layer.k_dev_quantized + token_head_offset_quant;
int8_t* v_quant_target_ptr = current_kv_layer.v_dev_quantized + token_head_offset_quant;
size_t scale_offset = static_cast<size_t>(pos) * n_kv_heads + kvh;
float* k_scale_target_ptr = current_kv_layer.k_dev_scales + scale_offset;
float* v_scale_target_ptr = current_kv_layer.v_dev_scales + scale_offset;
quantize_fp32_to_int8_symmetric_per_tensor_cuda(
current_k_head_ptr_fp32, k_quant_target_ptr, k_scale_target_ptr, head_dim, stream);
quantize_fp32_to_int8_symmetric_per_tensor_cuda(
current_v_head_ptr_fp32, v_quant_target_ptr, v_scale_target_ptr, head_dim, stream);
}
} else {
for (int kvh = 0; kvh < n_kv_heads; ++kvh) {
const float* current_k_head_ptr = k_dev_ + kvh * head_dim;
const float* current_v_head_ptr = v_dev_ + kvh * head_dim;
update_kv_cache_cuda(current_kv_layer.k_dev_fp32, current_k_head_ptr, pos,
kvh, kv_cache->allocated_max_seq_len,
kv_cache->allocated_num_kv_heads,
kv_cache->allocated_head_dim, stream);
update_kv_cache_cuda(current_kv_layer.v_dev_fp32, current_v_head_ptr, pos,
kvh, kv_cache->allocated_max_seq_len,
kv_cache->allocated_num_kv_heads,
kv_cache->allocated_head_dim, stream);
}
}
} else {
Logger::error("KVCache layer index " + std::to_string(l_model_idx) + " out of bounds for kv_cache->layers access in forward_device.");
return {};
}
float scale = 1.0f / SAFE_SQRT(static_cast<float>(head_dim));
const float* attention_k_cache_ptr_dev = nullptr;
const float* attention_v_cache_ptr_dev = nullptr;
KVCacheLayer& attention_kv_layer = kv_cache->layers[l_model_idx];
if (config_.use_kvcache_quantization) {
Logger::info("[GPU L" + std::to_string(l_model_idx) + "] Using SELECTIVE KVCache dequantization");
} else {
attention_k_cache_ptr_dev = attention_kv_layer.k_dev_fp32;
attention_v_cache_ptr_dev = attention_kv_layer.v_dev_fp32;
}
float current_attention_scale = 1.0f / sqrtf((float)head_dim);
if (config_.use_kvcache_quantization &&
selective_k_dequant_buffer_dev_ && selective_v_dequant_buffer_dev_) {
attention_cuda_selective_dequant(
q_dev_,
attention_kv_layer.k_dev_quantized,
attention_kv_layer.v_dev_quantized,
attention_kv_layer.k_dev_scales,
attention_kv_layer.v_dev_scales,
selective_k_dequant_buffer_dev_,
selective_v_dequant_buffer_dev_,
attn_out_dev_,
config_.num_attention_heads,
pos + 1,
head_dim,
current_attention_scale,
kv_cache->allocated_max_seq_len,
config_.num_key_value_heads,
stream
);
} else {
// Use optimized kernels if enabled, fallback to standard if needed
if (config_.use_optimized_cuda_kernels) {
attention_cuda_optimized(
q_dev_,
attention_k_cache_ptr_dev,
attention_v_cache_ptr_dev,
attn_out_dev_,
config_.num_attention_heads,
pos + 1,
head_dim,
current_attention_scale,
kv_cache->allocated_max_seq_len,
config_.num_key_value_heads,
stream
);
} else {
attention_cuda(
q_dev_,
attention_k_cache_ptr_dev,
attention_v_cache_ptr_dev,
attn_out_dev_,
config_.num_attention_heads,
pos + 1,
head_dim,
current_attention_scale,
kv_cache->allocated_max_seq_len,
config_.num_key_value_heads,
stream
);
}
}
if (w_o_f32_dev_) {
const float* lw_o_proj_f32_dev = w_o_f32_dev_ + (size_t)l_gpu_idx * hs * hs;
matvec_f32_f32_cuda(cublas_handle_, lw_o_proj_f32_dev, attn_out_dev_, attn_proj_dev_, hs, hs, stream);
} else {
Logger::error("GPU L" + std::to_string(l_model_idx) + " (gpu_idx " + std::to_string(l_gpu_idx) + "): No valid O proj weights (FP32/BF16)."); return {};
}
add_residual_cuda(attn_proj_dev_, x_resid1_dev_, current_x_dev, hs, stream);
gpuErrchk(cudaMemcpyAsync(x_resid2_dev_, current_x_dev, hs * sizeof(float), cudaMemcpyDeviceToDevice, stream));
if (!lw_post_norm_dev) { Logger::error("Missing post_attention_layernorm_dev for GPU layer model_idx=" + std::to_string(l_model_idx)); return {}; }
// Use optimized kernels if enabled, fallback to standard if needed
if (config_.use_optimized_cuda_kernels) {
rmsnorm_vector_cuda_optimized(current_x_dev, lw_post_norm_dev, x_norm_dev_, hs, eps, stream);
} else {
rmsnorm_vector_cuda(current_x_dev, lw_post_norm_dev, x_norm_dev_, hs, eps, stream);
}
if (w_o_f32_dev_) {
const float* w_o_layer_ptr = w_o_f32_dev_ + (size_t)l_gpu_idx * hs * hs;
matvec_f32_f32_cuda(cublas_handle_, w_o_layer_ptr, attn_out_dev_, attn_proj_dev_, hs, hs, stream);
} else {
Logger::error("GPU L" + std::to_string(l_model_idx) + ": No valid O projection weights."); return {};
}
add_residual_cuda(attn_proj_dev_, x_resid1_dev_, current_x_dev, hs, stream);
gpuErrchk(cudaMemcpyAsync(x_resid2_dev_, current_x_dev, hs * sizeof(float), cudaMemcpyDeviceToDevice, stream));