Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
2090 lines (1890 loc) · 84.8 KB
/
Copy pathmain.cpp
File metadata and controls
2090 lines (1890 loc) · 84.8 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 "llama.h"
#include "ggml.h"
#include "ggml-backend.h"
#include <omp.h>
#include <CommonCrypto/CommonDigest.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <zlib.h>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <numeric>
#include <regex>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
// -----------------------------------------------------------------------------
// Types and constants
struct Chunk {
std::string label;
int start;
int end;
std::string text;
};
struct CapturedAttention {
int layer;
int n_heads;
int n_query;
int n_context;
std::vector<float> weights; // shape [n_heads, n_query, n_context], row-major
};
struct CaptureContext {
std::vector<int> context_token_positions; // positions in full sequence
std::vector<int> query_token_positions; // causal-shifted, full-sequence positions
int batch_query_pos_start = 0; // start position (in full sequence) of current batch
int batch_query_pos_end = 0; // exclusive
std::set<int> selected_layers;
// accumulation: per-layer captured attention (filled across batches)
std::unordered_map<int, CapturedAttention> per_layer;
};
static const char * kContextOpen = "<CONTEXT>\n";
static const char * kMiddle = "\n</CONTEXT>\n<QUERY>\n";
static const char * kQueryClose = "\n</QUERY>";
static const char * kDefaultInputPrompt =
"Find implementation evidence in the code for each specification item. "
"Prefer exact implementing functions, branches, data structures, and output fields. "
"Focus on semantic matches, not shared words.";
static std::string make_prefix_text(const std::string & input_prompt) {
if (input_prompt.empty()) return kContextOpen;
std::string out = "<TASK>\n";
out += input_prompt;
if (out.back() != '\n') out += '\n';
out += "</TASK>\n\n";
out += kContextOpen;
return out;
}
struct TokenizedDoc {
std::vector<llama_token> tokens;
std::vector<int> char_start;
std::vector<int> char_end;
};
static TokenizedDoc tokenize_with_offsets(const llama_vocab * vocab, const std::string & text);
static std::string token_piece(const llama_vocab * vocab, llama_token token) {
char buf[256];
int n = llama_token_to_piece(vocab, token, buf, sizeof(buf), 0, false);
if (n >= 0) return std::string(buf, n);
std::vector<char> big(1024);
n = llama_token_to_piece(vocab, token, big.data(), (int32_t) big.size(), 0, false);
if (n >= 0) return std::string(big.data(), n);
return "";
}
// -----------------------------------------------------------------------------
// Logging
static void log_line(const char * fmt, ...) {
va_list ap;
va_start(ap, fmt);
std::fprintf(stderr, "[attn-extract] ");
std::vfprintf(stderr, fmt, ap);
std::fprintf(stderr, "\n");
va_end(ap);
}
// -----------------------------------------------------------------------------
// File I/O
static std::string read_file(const std::string & path) {
std::ifstream in(path, std::ios::binary);
if (!in) {
std::fprintf(stderr, "failed to open %s\n", path.c_str());
std::exit(1);
}
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
}
static void write_file(const std::string & path, const std::string & content) {
std::ofstream out(path, std::ios::binary);
out << content;
}
static bool path_ends_with(const std::string & s, const std::string & suffix) {
if (suffix.size() > s.size()) return false;
return std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
}
static void append_tar_octal(char * dst, size_t width, uint64_t value) {
std::snprintf(dst, width, "%0*llo", (int) width - 1, (unsigned long long) value);
}
static void write_tar_gz_json(const std::string & path, const std::string & json) {
gzFile gz = gzopen(path.c_str(), "wb9");
if (!gz) {
log_line("failed to open gzip output %s", path.c_str());
std::exit(1);
}
char header[512];
std::memset(header, 0, sizeof(header));
const char * name = "heatmap.json";
std::memcpy(header, name, std::strlen(name));
append_tar_octal(header + 100, 8, 0644);
append_tar_octal(header + 108, 8, 0);
append_tar_octal(header + 116, 8, 0);
append_tar_octal(header + 124, 12, (uint64_t) json.size());
append_tar_octal(header + 136, 12, 0);
std::memset(header + 148, ' ', 8);
header[156] = '0';
std::memcpy(header + 257, "ustar", 5);
std::memcpy(header + 263, "00", 2);
unsigned int checksum = 0;
for (unsigned char c : header) checksum += c;
std::snprintf(header + 148, 8, "%06o", checksum);
header[154] = '\0';
header[155] = ' ';
if (gzwrite(gz, header, sizeof(header)) != (int) sizeof(header)) {
log_line("failed to write tar header to %s", path.c_str());
gzclose(gz);
std::exit(1);
}
if (!json.empty() && gzwrite(gz, json.data(), (unsigned int) json.size()) != (int) json.size()) {
log_line("failed to write json payload to %s", path.c_str());
gzclose(gz);
std::exit(1);
}
size_t padding = (512 - (json.size() % 512)) % 512;
if (padding > 0) {
char zeros[512] = {0};
if (gzwrite(gz, zeros, (unsigned int) padding) != (int) padding) {
log_line("failed to write tar padding to %s", path.c_str());
gzclose(gz);
std::exit(1);
}
}
char end_blocks[1024] = {0};
if (gzwrite(gz, end_blocks, sizeof(end_blocks)) != (int) sizeof(end_blocks)) {
log_line("failed to write tar footer to %s", path.c_str());
gzclose(gz);
std::exit(1);
}
if (gzclose(gz) != Z_OK) {
log_line("failed to close gzip output %s", path.c_str());
std::exit(1);
}
}
static void write_heatmap_output(const std::string & path, const std::string & json) {
if (path_ends_with(path, ".tar.gz") || path_ends_with(path, ".tgz")) {
write_tar_gz_json(path, json);
return;
}
log_line("output path must end in .tar.gz or .tgz: %s", path.c_str());
std::exit(1);
}
// -----------------------------------------------------------------------------
// Text preprocessing
static std::string collapse_whitespace(const std::string & text) {
std::string s = std::regex_replace(text, std::regex("[ \\t]+\\n"), "\n");
s = std::regex_replace(s, std::regex("\\n{3,}"), "\n\n");
// trim
size_t start = s.find_first_not_of(" \t\n\r");
if (start == std::string::npos) return "\n";
size_t end = s.find_last_not_of(" \t\n\r");
return s.substr(start, end - start + 1) + "\n";
}
static std::string strip_python(const std::string & text) {
// Triple-quoted strings (greedy across newlines).
std::string s = std::regex_replace(text, std::regex("\"\"\"[\\s\\S]*?\"\"\""), "");
s = std::regex_replace(s, std::regex("'''[\\s\\S]*?'''"), "");
// Line comments. Naive — strips `#` inside string literals too, acceptable for attribution.
s = std::regex_replace(s, std::regex("(?:^|[\\t ])#.*$", std::regex::multiline), "");
return collapse_whitespace(s);
}
static std::string strip_text(const std::string & text, const std::string & mode) {
if (mode == "none" || mode.empty()) return text;
if (mode == "whitespace") return collapse_whitespace(text);
if (mode == "python") return strip_python(text);
log_line("unknown strip mode: %s", mode.c_str());
std::exit(1);
}
// -----------------------------------------------------------------------------
// SHA-256, directory walking, token cache
static std::string sha256_hex(const std::string & data) {
unsigned char digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(data.data(), (CC_LONG) data.size(), digest);
char buf[CC_SHA256_DIGEST_LENGTH * 2 + 1];
for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
snprintf(buf + i * 2, 3, "%02x", digest[i]);
}
return std::string(buf, CC_SHA256_DIGEST_LENGTH * 2);
}
static bool ends_with(const std::string & s, const std::string & suffix) {
if (suffix.size() > s.size()) return false;
return std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
}
static void walk_directory(
const std::string & root,
const std::string & extension,
std::vector<std::string> & out
) {
DIR * d = opendir(root.c_str());
if (!d) return;
struct dirent * entry;
std::vector<std::string> subdirs;
while ((entry = readdir(d))) {
std::string name = entry->d_name;
if (name == "." || name == "..") continue;
std::string path = root + "/" + name;
struct stat st;
if (stat(path.c_str(), &st) != 0) continue;
if (S_ISDIR(st.st_mode)) {
// Skip common large/uninteresting dirs.
if (name == "node_modules" || name == ".git" || name == "dist" || name == "build") continue;
subdirs.push_back(path);
} else if (S_ISREG(st.st_mode) && ends_with(name, extension)) {
out.push_back(path);
}
}
closedir(d);
std::sort(subdirs.begin(), subdirs.end());
for (auto & sd : subdirs) walk_directory(sd, extension, out);
}
static std::string ensure_dir(const std::string & path) {
struct stat st;
if (stat(path.c_str(), &st) != 0) {
mkdir(path.c_str(), 0755);
}
return path;
}
// On-disk format for cached file tokens:
// magic "TOKN" (4) | version (u32) | n_tokens (u32) |
// tokens (i32 * n_tokens) | char_start (i32 * n_tokens) | char_end (i32 * n_tokens)
static constexpr uint32_t kTokenCacheMagic = 0x544f4b4eU;
static constexpr uint32_t kTokenCacheVersion = 1;
struct CachedTokens {
std::vector<llama_token> tokens;
std::vector<int> char_start;
std::vector<int> char_end;
};
static std::vector<Chunk> token_chunks_from_offsets(
const std::string & text,
const CachedTokens & ct,
const std::string & prefix
) {
std::vector<Chunk> chunks;
chunks.reserve(ct.tokens.size());
for (size_t i = 0; i < ct.tokens.size(); i++) {
int start = ct.char_start[i];
int end = ct.char_end[i];
if (start < 0) start = 0;
if (end < start) end = start;
if (start > (int) text.size()) start = (int) text.size();
if (end > (int) text.size()) end = (int) text.size();
if (end <= start) continue;
std::string token_text = text.substr(start, end - start);
if (token_text.empty()) continue;
char label[64];
std::snprintf(label, sizeof(label), ":tok_%06zu", chunks.size());
chunks.push_back({prefix + label, start, end, token_text});
}
return chunks;
}
struct MarkdownQueryItem {
std::string rel_path;
std::string label;
std::string prompt_text;
std::string text;
int active_start; // char offsets in prompt_text
int active_end;
int display_start; // char offsets in displayed query_text
int display_end;
CachedTokens ct; // prompt_text + kQueryClose
};
struct MarkdownQuerySet {
std::string text;
std::vector<Chunk> chunks;
std::vector<MarkdownQueryItem> items;
};
static int markdown_indent_width(const std::string & line) {
int n = 0;
for (char c : line) {
if (c == ' ') n++;
else if (c == '\t') n += 4;
else break;
}
return n;
}
static bool markdown_fence_line(const std::string & line) {
size_t i = 0;
while (i < line.size() && (line[i] == ' ' || line[i] == '\t')) i++;
return line.compare(i, 3, "```") == 0 || line.compare(i, 3, "~~~") == 0;
}
static MarkdownQuerySet build_markdown_query_set(
const std::vector<std::string> & paths,
const std::string & root,
const std::string & strip_mode
) {
MarkdownQuerySet out;
std::regex heading_re(R"(^\s{0,3}(#{1,6})\s+(.+)$)");
std::regex list_item_re(R"(^(\s*)(?:[-*+]\s+|\d+[.)]\s+).+\S.*$)");
std::regex block_item_re(R"(^\s{0,3}>\s*\S.*$)");
struct Ancestor {
int indent;
std::string line;
};
for (auto & p : paths) {
std::string rel = root.empty()
? p
: p.substr(root.size() + (root.back() == '/' ? 0 : 1));
std::string content = strip_text(read_file(p), strip_mode);
if (content.empty() || content == "\n") continue;
std::string header = "\n## === " + rel + " ===\n";
out.text += header;
int doc_offset = (int) out.text.size();
out.text += content;
std::vector<std::string> headings;
std::vector<Ancestor> list_stack;
auto is_blank = [](const std::string & s) {
return s.find_first_not_of(" \t\r") == std::string::npos;
};
auto emit_item = [&](const std::string & text, size_t item_start, size_t item_end) {
std::vector<std::string> prompt_lines;
prompt_lines.insert(prompt_lines.end(), headings.begin(), headings.end());
for (auto & a : list_stack) prompt_lines.push_back(a.line);
int active_start = 0;
for (auto & pl : prompt_lines) active_start += (int) pl.size() + 1;
std::string prompt;
for (auto & pl : prompt_lines) {
prompt += pl;
prompt += '\n';
}
prompt += text;
prompt += '\n';
char suffix[32];
std::snprintf(suffix, sizeof(suffix), ":item_%06zu", out.items.size());
std::string label = rel + suffix;
int display_start = doc_offset + (int) item_start;
int display_end = doc_offset + (int) item_end;
MarkdownQueryItem item;
item.rel_path = rel;
item.label = label;
item.prompt_text = prompt;
item.text = text;
item.active_start = active_start;
item.active_end = active_start + (int) text.size();
item.display_start = display_start;
item.display_end = display_end;
out.items.push_back(std::move(item));
out.chunks.push_back({label, display_start, display_end, text});
};
size_t cursor = 0;
while (cursor < content.size()) {
size_t line_start = cursor;
size_t line_end = content.find('\n', cursor);
if (line_end == std::string::npos) line_end = content.size();
else line_end += 1;
size_t content_end = line_end;
while (content_end > line_start && (content[content_end - 1] == '\n' || content[content_end - 1] == '\r')) {
content_end--;
}
std::string line = content.substr(line_start, content_end - line_start);
if (markdown_fence_line(line)) {
size_t block_start = line_start;
size_t block_content_end = content_end;
size_t next = line_end;
while (next < content.size()) {
size_t inner_start = next;
size_t inner_end = content.find('\n', next);
if (inner_end == std::string::npos) inner_end = content.size();
else inner_end += 1;
size_t inner_content_end = inner_end;
while (inner_content_end > inner_start &&
(content[inner_content_end - 1] == '\n' || content[inner_content_end - 1] == '\r')) {
inner_content_end--;
}
std::string inner_line = content.substr(inner_start, inner_content_end - inner_start);
block_content_end = inner_content_end;
next = inner_end;
if (markdown_fence_line(inner_line)) break;
}
emit_item(content.substr(block_start, block_content_end - block_start),
block_start, block_content_end);
cursor = next;
continue;
}
if (is_blank(line)) {
list_stack.clear();
cursor = line_end;
continue;
}
std::smatch m;
if (std::regex_match(line, m, heading_re)) {
int level = (int) m[1].str().size();
if ((int) headings.size() >= level) headings.resize(level - 1);
headings.push_back(line);
list_stack.clear();
cursor = line_end;
continue;
}
bool is_list_item = std::regex_match(line, m, list_item_re);
bool is_block_item = std::regex_match(line, block_item_re);
if (is_list_item || is_block_item) {
int indent = is_list_item ? markdown_indent_width(m[1].str()) : 0;
while (!list_stack.empty() && list_stack.back().indent >= indent) {
list_stack.pop_back();
}
emit_item(line, line_start, content_end);
list_stack.push_back({indent, line});
cursor = line_end;
continue;
}
size_t paragraph_start = line_start;
size_t paragraph_content_end = content_end;
size_t next = line_end;
while (next < content.size()) {
size_t para_line_start = next;
size_t para_line_end = content.find('\n', next);
if (para_line_end == std::string::npos) para_line_end = content.size();
else para_line_end += 1;
size_t para_content_end = para_line_end;
while (para_content_end > para_line_start &&
(content[para_content_end - 1] == '\n' || content[para_content_end - 1] == '\r')) {
para_content_end--;
}
std::string para_line = content.substr(para_line_start, para_content_end - para_line_start);
std::smatch para_match;
if (is_blank(para_line) ||
markdown_fence_line(para_line) ||
std::regex_match(para_line, para_match, heading_re) ||
std::regex_match(para_line, para_match, list_item_re) ||
std::regex_match(para_line, para_match, block_item_re)) {
break;
}
paragraph_content_end = para_content_end;
next = para_line_end;
}
emit_item(content.substr(paragraph_start, paragraph_content_end - paragraph_start),
paragraph_start, paragraph_content_end);
list_stack.clear();
cursor = next;
}
}
return out;
}
static bool load_token_cache(const std::string & path, CachedTokens & out) {
FILE * f = std::fopen(path.c_str(), "rb");
if (!f) return false;
uint32_t magic = 0, version = 0, n = 0;
if (std::fread(&magic, 4, 1, f) != 1 || magic != kTokenCacheMagic) { std::fclose(f); return false; }
if (std::fread(&version, 4, 1, f) != 1 || version != kTokenCacheVersion) { std::fclose(f); return false; }
if (std::fread(&n, 4, 1, f) != 1) { std::fclose(f); return false; }
out.tokens.assign(n, 0);
out.char_start.assign(n, 0);
out.char_end.assign(n, 0);
if (std::fread(out.tokens.data(), sizeof(llama_token), n, f) != n) { std::fclose(f); return false; }
if (std::fread(out.char_start.data(), sizeof(int), n, f) != n) { std::fclose(f); return false; }
if (std::fread(out.char_end.data(), sizeof(int), n, f) != n) { std::fclose(f); return false; }
std::fclose(f);
return true;
}
static void save_token_cache(const std::string & path, const CachedTokens & ct) {
FILE * f = std::fopen(path.c_str(), "wb");
if (!f) { log_line("warning: cannot write cache %s", path.c_str()); return; }
uint32_t magic = kTokenCacheMagic, version = kTokenCacheVersion;
uint32_t n = (uint32_t) ct.tokens.size();
std::fwrite(&magic, 4, 1, f);
std::fwrite(&version, 4, 1, f);
std::fwrite(&n, 4, 1, f);
std::fwrite(ct.tokens.data(), sizeof(llama_token), n, f);
std::fwrite(ct.char_start.data(), sizeof(int), n, f);
std::fwrite(ct.char_end.data(), sizeof(int), n, f);
std::fclose(f);
}
static CachedTokens tokenize_with_cache(
const llama_vocab * vocab,
const std::string & text,
const std::string & cache_path
) {
CachedTokens ct;
if (!cache_path.empty() && load_token_cache(cache_path, ct)) {
return ct;
}
auto doc = tokenize_with_offsets(vocab, text);
ct.tokens = doc.tokens;
ct.char_start = doc.char_start;
ct.char_end = doc.char_end;
if (!cache_path.empty()) save_token_cache(cache_path, ct);
return ct;
}
// -----------------------------------------------------------------------------
// Multi-file corpus composer
//
// Concatenates many source files into one "context corpus" inside the same
// <CONTEXT>...</CONTEXT><QUERY>...</QUERY> wrapper. Each file's tokens come
// from the per-file cache (so adding/removing files only re-tokenizes deltas).
// Chunks are computed per-file and shifted into corpus coordinates.
struct ContextFile {
std::string path;
std::string rel_path; // relative to source tree root, used for chunk labels
std::string content;
int corpus_offset; // char position of this file's content in corpus
std::vector<Chunk> chunks; // file-local, will be shifted to corpus coords on aggregation
};
struct ComposedInput {
std::vector<llama_token> tokens;
std::vector<int> char_start; // per token, absolute in composed text
std::vector<int> char_end;
int context_body_start;
int context_body_end;
int query_body_start;
int query_body_end;
std::vector<Chunk> context_chunks_corpus; // chunks in corpus coordinates
};
static std::string make_file_header(const std::string & rel_path) {
return "\n// === " + rel_path + " ===\n";
}
// -----------------------------------------------------------------------------
// Tokenization with char offsets
static TokenizedDoc tokenize_with_offsets(
const llama_vocab * vocab,
const std::string & text
) {
TokenizedDoc out;
// First, tokenize without special tokens. add_special=false, parse_special=false.
std::vector<llama_token> tokens(text.size() + 16);
int n = llama_tokenize(
vocab,
text.data(), (int32_t) text.size(),
tokens.data(), (int32_t) tokens.size(),
/*add_special=*/false,
/*parse_special=*/false
);
if (n < 0) {
tokens.resize(-n);
n = llama_tokenize(
vocab,
text.data(), (int32_t) text.size(),
tokens.data(), (int32_t) tokens.size(),
false, false
);
}
tokens.resize(n);
out.tokens = tokens;
out.char_start.reserve(n);
out.char_end.reserve(n);
size_t cursor = 0;
for (auto token : tokens) {
char buf[256];
int piece_n = llama_token_to_piece(vocab, token, buf, sizeof(buf), 0, false);
if (piece_n < 0) {
// try larger buffer
std::vector<char> big(1024);
piece_n = llama_token_to_piece(vocab, token, big.data(), (int32_t) big.size(), 0, false);
if (piece_n < 0) {
out.char_start.push_back((int) cursor);
out.char_end.push_back((int) cursor);
continue;
}
std::string piece(big.data(), piece_n);
size_t pos = text.find(piece, cursor);
if (pos == std::string::npos) pos = cursor;
out.char_start.push_back((int) pos);
out.char_end.push_back((int) (pos + piece.size()));
cursor = pos + piece.size();
continue;
}
std::string piece(buf, piece_n);
size_t pos = text.find(piece, cursor);
if (pos == std::string::npos) {
// Mismatch (e.g., special-token piece). Best-effort: keep cursor.
out.char_start.push_back((int) cursor);
out.char_end.push_back((int) cursor);
continue;
}
out.char_start.push_back((int) pos);
out.char_end.push_back((int) (pos + piece.size()));
cursor = pos + piece.size();
}
return out;
}
// -----------------------------------------------------------------------------
// Chunk → token-index map
static std::vector<int> token_indices_for_range(
const TokenizedDoc & doc,
int region_start,
int region_end
) {
std::vector<int> out;
for (int i = 0; i < (int) doc.tokens.size(); i++) {
int ts = doc.char_start[i];
int te = doc.char_end[i];
if (ts == te) continue;
if (te > region_start && ts < region_end) out.push_back(i);
}
return out;
}
static std::vector<int> token_to_chunk_map(
const TokenizedDoc & doc,
const std::vector<Chunk> & chunks
) {
// For each token, the index of the chunk that contains it, or -1.
std::vector<int> mapping(doc.tokens.size(), -1);
// Build a sorted index by chunk.start.
std::vector<int> order(chunks.size());
std::iota(order.begin(), order.end(), 0);
std::sort(order.begin(), order.end(), [&](int a, int b) {
return chunks[a].start < chunks[b].start;
});
size_t cursor = 0; // index into order
for (size_t i = 0; i < doc.tokens.size(); i++) {
int ts = doc.char_start[i];
int te = doc.char_end[i];
if (ts == te) continue;
while (cursor < order.size() && chunks[order[cursor]].end <= ts) cursor++;
if (cursor >= order.size()) break;
const auto & c = chunks[order[cursor]];
if (c.start < te && c.end > ts) {
mapping[i] = order[cursor];
}
}
return mapping;
}
// -----------------------------------------------------------------------------
// Attention capture callback
struct CallbackUserData {
CaptureContext * cap;
};
static bool eval_callback(struct ggml_tensor * t, bool ask, void * user_data) {
auto * ud = static_cast<CallbackUserData *>(user_data);
auto & cap = *ud->cap;
const char * name = t->name;
if (!name) return false;
// Filter `kq_soft_max-<il>`.
static const std::regex re("^kq_soft_max-(\\d+)$");
std::cmatch m;
if (!std::regex_match(name, m, re)) return false;
int layer = std::atoi(m[1].first);
if (cap.selected_layers.count(layer) == 0) return false;
if (ask) return true;
// Tensor shape: ne0 = n_kv (context size in cache), ne1 = n_tokens (this batch),
// ne2 = n_head, ne3 = 1. Memory: ne0 fastest-varying.
int64_t n_kv = t->ne[0];
int64_t n_tokens = t->ne[1];
int64_t n_heads = t->ne[2];
size_t bytes = ggml_nbytes(t);
std::vector<float> host(bytes / sizeof(float));
ggml_backend_tensor_get(t, host.data(), 0, bytes);
if (t->type != GGML_TYPE_F32) {
// We pass F32 prec on softmax; assume F32. If not, would need a conversion.
log_line("warning: tensor %s is not f32 (type=%d)", name, t->type);
}
// For this batch, the global token positions of the rows are
// [batch_query_pos_start .. batch_query_pos_end).
// We need rows corresponding to causal-shifted query positions in
// cap.query_token_positions whose value is in [batch_query_pos_start, batch_query_pos_end).
// Columns: keep only the context positions in cap.context_token_positions
// (these are <= cache extent so always present in n_kv).
auto & per_layer = cap.per_layer[layer];
if (per_layer.layer == 0 && per_layer.weights.empty()) {
// Initialize.
per_layer.layer = layer;
per_layer.n_heads = (int) n_heads;
per_layer.n_query = (int) cap.query_token_positions.size();
per_layer.n_context = (int) cap.context_token_positions.size();
per_layer.weights.assign((size_t) n_heads * per_layer.n_query * per_layer.n_context, 0.0f);
}
// Map context token positions → column indices in this tensor.
// Cols correspond to positions [0, n_kv). cap.context_token_positions are
// all < cap.batch_query_pos_start (since context precedes query).
// For each context pos, col = position.
std::vector<int> ctx_cols;
ctx_cols.reserve(cap.context_token_positions.size());
for (int p : cap.context_token_positions) {
if (p >= 0 && p < n_kv) ctx_cols.push_back(p);
else ctx_cols.push_back(-1); // shouldn't happen for context
}
// For each row of this batch (q_local in [0, n_tokens)), its global position
// is cap.batch_query_pos_start + q_local. If that global position is in our
// query_token_positions, store.
std::unordered_map<int, int> qpos_to_local;
qpos_to_local.reserve(cap.query_token_positions.size());
for (int i = 0; i < (int) cap.query_token_positions.size(); i++) {
qpos_to_local[cap.query_token_positions[i]] = i;
}
for (int64_t q_local = 0; q_local < n_tokens; q_local++) {
int global_pos = cap.batch_query_pos_start + (int) q_local;
auto it = qpos_to_local.find(global_pos);
if (it == qpos_to_local.end()) continue;
int row_out = it->second;
for (int h = 0; h < (int) n_heads; h++) {
// offset in host: h * n_tokens * n_kv + q_local * n_kv + ...
size_t base = (size_t) h * n_tokens * n_kv + (size_t) q_local * n_kv;
float * row_data = host.data() + base;
for (int c = 0; c < (int) ctx_cols.size(); c++) {
int col = ctx_cols[c];
if (col < 0) continue;
size_t out_idx = (size_t) h * per_layer.n_query * per_layer.n_context
+ (size_t) row_out * per_layer.n_context + c;
per_layer.weights[out_idx] = row_data[col];
}
}
}
return true;
}
// -----------------------------------------------------------------------------
// Aggregation
static void normalize_row(std::vector<float> & row) {
double sum = 0.0;
for (float v : row) sum += v;
if (sum <= 0) {
std::fill(row.begin(), row.end(), 0.0f);
return;
}
for (auto & v : row) v = (float)(v / sum);
}
static std::vector<std::vector<float>> apply_sink_norm(
const std::vector<std::vector<float>> & matrix
) {
// Mask context-key columns with unusually high column-median attention.
// Preserve absolute mass; windowed scans should not inflate the remaining
// visible context columns into a full probability distribution.
if (matrix.empty()) return matrix;
size_t rows = matrix.size();
size_t cols = matrix[0].size();
if (cols == 0) return matrix;
std::vector<float> col_median(cols, 0.0f);
for (size_t c = 0; c < cols; c++) {
std::vector<float> column(rows);
for (size_t r = 0; r < rows; r++) column[r] = matrix[r][c];
std::sort(column.begin(), column.end());
col_median[c] = column[rows / 2];
}
double min_positive = 1e-12;
for (float v : col_median) if (v > 0 && v < min_positive) min_positive = v;
std::vector<float> logs(cols);
for (size_t c = 0; c < cols; c++) logs[c] = std::log(col_median[c] + (float)(min_positive / 2.0 + 1e-12));
double mean = 0;
for (float v : logs) mean += v;
mean /= cols;
double var = 0;
for (float v : logs) { double d = v - mean; var += d * d; }
var /= cols;
double threshold = mean + 3.0 * std::sqrt(var);
std::vector<bool> sink(cols, false);
bool any = false;
for (size_t c = 0; c < cols; c++) if (logs[c] > threshold) { sink[c] = true; any = true; }
if (!any) return matrix;
std::vector<std::vector<float>> out(rows, std::vector<float>(cols, 0.0f));
for (size_t r = 0; r < rows; r++) {
for (size_t c = 0; c < cols; c++) out[r][c] = sink[c] ? 0.0f : matrix[r][c];
}
return out;
}
static std::vector<std::vector<float>> prior_normalize(
const std::vector<std::vector<float>> & scores,
double power = 0.75,
int min_rows = 3
) {
if ((int) scores.size() < min_rows) return scores;
size_t cols = 0;
for (auto & row : scores) cols = std::max(cols, row.size());
if (cols == 0) return scores;
std::vector<double> priors(cols, 0.0);
std::vector<int> counts(cols, 0);
for (auto & row : scores) {
for (size_t c = 0; c < row.size(); c++) {
float v = row[c];
if (std::isfinite(v) && v > 0) {
priors[c] += v;
counts[c] += 1;
}
}
}
for (size_t c = 0; c < cols; c++) priors[c] = counts[c] > 0 ? priors[c] / counts[c] : 0.0;
std::vector<std::vector<float>> out(scores.size(), std::vector<float>(cols, 0.0f));
for (size_t r = 0; r < scores.size(); r++) {
std::vector<float> adjusted(cols, 0.0f);
for (size_t c = 0; c < scores[r].size(); c++) {
float v = scores[r][c];
if (std::isfinite(v) && v > 0 && c < cols && priors[c] > 0) {
adjusted[c] = (float)(v / std::pow(priors[c], power));
}
}
normalize_row(adjusted);
out[r] = adjusted;
}
return out;
}
static std::vector<std::vector<float>> aggregate_captured(
const std::vector<CapturedAttention> & per_layer_captures,
const std::vector<int> & query_local_to_chunk,
const std::vector<int> & context_local_to_chunk,
int num_query_chunks,
int num_context_chunks,
bool sink_normalization,
bool global_normalize = true
) {
// Average all selected layers + heads first.
if (per_layer_captures.empty()) {
return std::vector<std::vector<float>>(num_query_chunks, std::vector<float>(num_context_chunks, 0.0f));
}
int n_q = per_layer_captures[0].n_query;
int n_c = per_layer_captures[0].n_context;
int n_heads = per_layer_captures[0].n_heads;
std::vector<float> avg((size_t) n_q * n_c, 0.0f);
double denom = (double) per_layer_captures.size() * n_heads;
// Parallelize over query rows — each thread owns its slice of `avg`.
#pragma omp parallel for schedule(static)
for (int q = 0; q < n_q; q++) {
size_t out_base = (size_t) q * n_c;
for (auto & cap : per_layer_captures) {
for (int h = 0; h < n_heads; h++) {
size_t in_base = (size_t) h * n_q * n_c + (size_t) q * n_c;
for (int c = 0; c < n_c; c++) {
avg[out_base + c] += cap.weights[in_base + c];
}
}
}
float inv = (float)(1.0 / denom);
for (int c = 0; c < n_c; c++) avg[out_base + c] *= inv;
}
// Per query chunk: select its rows, sink-norm, mean down to per-token,
// then scatter total attention mass to context chunks. Do not renormalize
// over only the visible context columns here; per-window scans need the
// absolute context-attention mass so sparse windows do not become 100%.
std::vector<std::vector<float>> result(num_query_chunks, std::vector<float>(num_context_chunks, 0.0f));
#pragma omp parallel for schedule(dynamic)
for (int q_chunk = 0; q_chunk < num_query_chunks; q_chunk++) {
// collect local query row indices
std::vector<int> rows;
for (int i = 0; i < (int) query_local_to_chunk.size(); i++) {
if (query_local_to_chunk[i] == q_chunk) rows.push_back(i);
}
if (rows.empty()) continue;
std::vector<std::vector<float>> sub(rows.size(), std::vector<float>(n_c, 0.0f));
for (size_t i = 0; i < rows.size(); i++) {
size_t base = (size_t) rows[i] * n_c;
for (int c = 0; c < n_c; c++) sub[i][c] = avg[base + c];
}
if (sink_normalization) sub = apply_sink_norm(sub);
// mean over rows -> per-context-token vector
std::vector<float> ctx_scores(n_c, 0.0f);
for (auto & r : sub) {
for (int c = 0; c < n_c; c++) ctx_scores[c] += r[c];
}
if (!sub.empty()) {
float inv_rows = (float)(1.0 / (double) sub.size());
for (auto & v : ctx_scores) v *= inv_rows;
}
// Scatter to chunks: per chunk, sum per-token scores assigned to it.
std::vector<float> chunk_sum(num_context_chunks, 0.0f);
std::vector<int> chunk_count(num_context_chunks, 0);
for (int c = 0; c < n_c; c++) {
int ch = context_local_to_chunk[c];
if (ch < 0) continue;
chunk_sum[ch] += ctx_scores[c];
chunk_count[ch] += 1;
}
std::vector<float> row(num_context_chunks, 0.0f);
double sum = 0;
for (int c = 0; c < num_context_chunks; c++) {
row[c] = chunk_count[c] > 0 ? chunk_sum[c] : 0.0f;
sum += row[c];
}
if (global_normalize && sum > 0) for (auto & v : row) v = (float)(v / sum);
result[q_chunk] = row;
}
if (global_normalize) return prior_normalize(result);
return result;
}
// -----------------------------------------------------------------------------
// JSON writer (minimal)
struct JsonOut {
std::ostringstream s;
void escape(const std::string & str) {