-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathLlama3.java
executable file
·2545 lines (2246 loc) · 111 KB
/
Llama3.java
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
///usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA 21+
//PREVIEW
//COMPILE_OPTIONS --add-modules=jdk.incubator.vector
//RUNTIME_OPTIONS --add-modules=jdk.incubator.vector -Djdk.incubator.vector.VECTOR_ACCESS_OOB_CHECK=0
//MAIN com.llama4j.Llama3
// Practical Llama 3 (and 3.1) inference in a single Java file
// Author: Alfonso² Peterssen
// Based on Andrej Karpathy's llama2.c and minbpe projects
//
// Supports llama.cpp's GGUF format, restricted to Q4_0 and Q8_0 quantized models
// Multi-threaded matrix vector multiplication routines implemented using Java's Vector API
// Simple CLI with --chat and --instruct mode
//
// To run just:
// jbang Llama3.java --help
//
// Enjoy!
package com.llama4j;
import jdk.incubator.vector.*;
import sun.misc.Unsafe;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.IntConsumer;
import java.util.function.IntFunction;
import java.util.function.LongConsumer;
import java.util.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
public class Llama3 {
// Batch-size used in prompt evaluation.
private static final int BATCH_SIZE = Integer.getInteger("llama.BatchSize", 16);
static Sampler selectSampler(int vocabularySize, float temperature, float topp, long rngSeed) {
Sampler sampler;
if (temperature == 0.0f) {
// greedy argmax sampling: take the token with the highest probability
sampler = Sampler.ARGMAX;
} else {
// we sample from this distribution to get the next token
RandomGenerator rng = RandomGeneratorFactory.getDefault().create(rngSeed);
Sampler innerSampler;
if (topp <= 0 || topp >= 1) {
// simply sample from the predicted probability distribution
innerSampler = new CategoricalSampler(rng);
} else {
// top-p (nucleus) sampling, clamping the least likely tokens to zero
innerSampler = new ToppSampler(vocabularySize, topp, rng);
}
sampler = logits -> {
// apply the temperature to the logits
logits.divideInPlace(0, logits.size(), temperature);
// apply softmax to the logits to get the probabilities for next token
logits.softmaxInPlace(0, logits.size());
return innerSampler.sampleToken(logits);
};
}
return sampler;
}
static void runInteractive(Llama model, Sampler sampler, Options options) {
Llama.State state = null;
List<Integer> conversationTokens = new ArrayList<>();
ChatFormat chatFormat = new ChatFormat(model.tokenizer());
conversationTokens.add(chatFormat.beginOfText);
if (options.systemPrompt() != null) {
conversationTokens.addAll(chatFormat.encodeMessage(new ChatFormat.Message(ChatFormat.Role.SYSTEM, options.systemPrompt())));
}
int startPosition = 0;
Scanner in = new Scanner(System.in);
loop: while (true) {
System.out.print("> ");
System.out.flush();
String userText = in.nextLine();
switch (userText) {
case "/quit":
case "/exit": break loop;
case "/context": {
System.out.printf("%d out of %d context tokens used (%d tokens remaining)%n",
conversationTokens.size(),
options.maxTokens(),
options.maxTokens() - conversationTokens.size());
continue;
}
}
if (state == null) {
state = model.createNewState(BATCH_SIZE);
}
conversationTokens.addAll(chatFormat.encodeMessage(new ChatFormat.Message(ChatFormat.Role.USER, userText)));
conversationTokens.addAll(chatFormat.encodeHeader(new ChatFormat.Message(ChatFormat.Role.ASSISTANT, "")));
Set<Integer> stopTokens = chatFormat.getStopTokens();
List<Integer> responseTokens = Llama.generateTokens(model, state, startPosition, conversationTokens.subList(startPosition, conversationTokens.size()), stopTokens, options.maxTokens(), sampler, options.echo(), token -> {
if (options.stream()) {
if (!model.tokenizer().isSpecialToken(token)) {
System.out.print(model.tokenizer().decode(List.of(token)));
}
}
});
// Include stop token in the prompt history, but not in the response displayed to the user.
conversationTokens.addAll(responseTokens);
startPosition = conversationTokens.size();
Integer stopToken = null;
if (!responseTokens.isEmpty() && stopTokens.contains(responseTokens.getLast())) {
stopToken = responseTokens.getLast();
responseTokens.removeLast();
}
if (!options.stream()) {
String responseText = model.tokenizer().decode(responseTokens);
System.out.println(responseText);
}
if (stopToken == null) {
System.err.println("Ran out of context length...");
break;
}
}
}
static void runInstructOnce(Llama model, Sampler sampler, Options options) {
Llama.State state = model.createNewState(BATCH_SIZE);
ChatFormat chatFormat = new ChatFormat(model.tokenizer());
List<Integer> promptTokens = new ArrayList<>();
promptTokens.add(chatFormat.beginOfText);
if (options.systemPrompt() != null) {
promptTokens.addAll(chatFormat.encodeMessage(new ChatFormat.Message(ChatFormat.Role.SYSTEM, options.systemPrompt())));
}
promptTokens.addAll(chatFormat.encodeMessage(new ChatFormat.Message(ChatFormat.Role.USER, options.prompt())));
promptTokens.addAll(chatFormat.encodeHeader(new ChatFormat.Message(ChatFormat.Role.ASSISTANT, "")));
Set<Integer> stopTokens = chatFormat.getStopTokens();
List<Integer> responseTokens = Llama.generateTokens(model, state, 0, promptTokens, stopTokens, options.maxTokens(), sampler, options.echo(), token -> {
if (options.stream()) {
if (!model.tokenizer().isSpecialToken(token)) {
System.out.print(model.tokenizer().decode(List.of(token)));
}
}
});
if (!responseTokens.isEmpty() && stopTokens.contains(responseTokens.getLast())) {
responseTokens.removeLast();
}
if (!options.stream()) {
String responseText = model.tokenizer().decode(responseTokens);
System.out.println(responseText);
}
}
record Options(Path modelPath, String prompt, String systemPrompt, boolean interactive,
float temperature, float topp, long seed, int maxTokens, boolean stream, boolean echo) {
static final int DEFAULT_MAX_TOKENS = 512;
Options {
require(modelPath != null, "Missing argument: --model <path> is required");
require(interactive || prompt != null, "Missing argument: --prompt is required in --instruct mode e.g. --prompt \"Why is the sky blue?\"");
require(0 <= temperature, "Invalid argument: --temperature must be non-negative");
require(0 <= topp && topp <= 1, "Invalid argument: --top-p must be within [0, 1]");
}
static void require(boolean condition, String messageFormat, Object... args) {
if (!condition) {
System.out.println("ERROR " + messageFormat.formatted(args));
System.out.println();
printUsage(System.out);
System.exit(-1);
}
}
static void printUsage(PrintStream out) {
out.println("Usage: jbang Llama3.java [options]");
out.println();
out.println("Options:");
out.println(" --model, -m <path> required, path to .gguf file");
out.println(" --interactive, --chat, -i run in chat mode");
out.println(" --instruct run in instruct (once) mode, default mode");
out.println(" --prompt, -p <string> input prompt");
out.println(" --system-prompt, -sp <string> (optional) system prompt");
out.println(" --temperature, -temp <float> temperature in [0,inf], default 0.1");
out.println(" --top-p <float> p value in top-p (nucleus) sampling in [0,1] default 0.95");
out.println(" --seed <long> random seed, default System.nanoTime()");
out.println(" --max-tokens, -n <int> number of steps to run for < 0 = limited by context length, default " + DEFAULT_MAX_TOKENS);
out.println(" --stream <boolean> print tokens during generation; may cause encoding artifacts for non ASCII text, default true");
out.println(" --echo <boolean> print ALL tokens to stderr, if true, recommended to set --stream=false, default false");
out.println();
out.println("Examples:");
out.println(" jbang Llama3.java --model llama3.2-1b-q4_0.gguf --prompt \"Tell me a joke\"");
out.println(" jbang Llama3.java --model llama3.2-1b-q4_0.gguf --system-prompt \"Reply concisely, in French\" --prompt \"Who was Marie Curie?\"");
out.println(" jbang Llama3.java --model llama3.2-1b-q4_0.gguf --system-prompt \"Answer concisely\" --chat");
out.println(" jbang Llama3.java --model llama3.2-1b-q4_0.gguf --chat");
out.println(" jbang Llama3.java --model llama3.2-1b-q4_0.gguf --prompt \"Print 5 emojis\" --stream=false");
}
static Options parseOptions(String[] args) {
String prompt = null;
String systemPrompt = null;
float temperature = 0.1f;
float topp = 0.95f;
Path modelPath = null;
long seed = System.nanoTime();
// Keep max context length small for low-memory devices.
int maxTokens = DEFAULT_MAX_TOKENS;
boolean interactive = false;
boolean stream = true;
boolean echo = false;
for (int i = 0; i < args.length; i++) {
String optionName = args[i];
require(optionName.startsWith("-"), "Invalid option %s", optionName);
switch (optionName) {
case "--interactive", "--chat", "-i" -> interactive = true;
case "--instruct" -> interactive = false;
case "--help", "-h" -> {
printUsage(System.out);
System.exit(0);
}
default -> {
String nextArg;
if (optionName.contains("=")) {
String[] parts = optionName.split("=", 2);
optionName = parts[0];
nextArg = parts[1];
} else {
require(i + 1 < args.length, "Missing argument for option %s", optionName);
nextArg = args[i + 1];
i += 1; // skip arg
}
switch (optionName) {
case "--prompt", "-p" -> prompt = nextArg;
case "--system-prompt", "-sp" -> systemPrompt = nextArg;
case "--temperature", "--temp" -> temperature = Float.parseFloat(nextArg);
case "--top-p" -> topp = Float.parseFloat(nextArg);
case "--model", "-m" -> modelPath = Paths.get(nextArg);
case "--seed", "-s" -> seed = Long.parseLong(nextArg);
case "--max-tokens", "-n" -> maxTokens = Integer.parseInt(nextArg);
case "--stream" -> stream = Boolean.parseBoolean(nextArg);
case "--echo" -> echo = Boolean.parseBoolean(nextArg);
default -> require(false, "Unknown option: %s", optionName);
}
}
}
}
return new Options(modelPath, prompt, systemPrompt, interactive, temperature, topp, seed, maxTokens, stream, echo);
}
}
public static void main(String[] args) throws IOException {
Options options = Options.parseOptions(args);
Llama model = AOT.tryUsePreLoaded(options.modelPath(), options.maxTokens());
if (model == null) {
// No compatible preloaded model found, fallback to fully parse and load the specified file.
model = ModelLoader.loadModel(options.modelPath(), options.maxTokens(), true);
}
Sampler sampler = selectSampler(model.configuration().vocabularySize, options.temperature(), options.topp(), options.seed());
if (options.interactive()) {
runInteractive(model, sampler, options);
} else {
runInstructOnce(model, sampler, options);
}
}
}
final class GGUF {
private static final int GGUF_MAGIC = 0x46554747;
private static final int DEFAULT_ALIGNMENT = 32; // must be a power of 2
private static final List<Integer> SUPPORTED_GGUF_VERSIONS = List.of(2, 3);
private int magic;
private int version;
private int tensorCount; // uint64_t
private int alignment;
private int metadata_kv_count; // uint64_t
private Map<String, Object> metadata;
public Map<String, GGUFTensorInfo> getTensorInfos() {
return tensorInfos;
}
private Map<String, GGUFTensorInfo> tensorInfos;
private long tensorDataOffset;
public long getTensorDataOffset() {
return tensorDataOffset;
}
public Map<String, Object> getMetadata() {
return metadata;
}
private final ByteBuffer BB_1 = ByteBuffer.allocate(Byte.BYTES).order(ByteOrder.LITTLE_ENDIAN);
private final ByteBuffer BB_2 = ByteBuffer.allocate(Short.BYTES).order(ByteOrder.LITTLE_ENDIAN);
private final ByteBuffer BB_4 = ByteBuffer.allocate(Integer.BYTES).order(ByteOrder.LITTLE_ENDIAN);
private final ByteBuffer BB_8 = ByteBuffer.allocate(Long.BYTES).order(ByteOrder.LITTLE_ENDIAN);
public static GGUF loadModel(Path modelPath) throws IOException {
try (FileChannel fileChannel = FileChannel.open(modelPath);
var ignored = Timer.log("Parse " + modelPath)) {
GGUF gguf = new GGUF();
gguf.loadModelImpl(fileChannel);
return gguf;
}
}
enum MetadataValueType {
// The value is a 8-bit unsigned integer.
UINT8(1),
// The value is a 8-bit signed integer.
INT8(1),
// The value is a 16-bit unsigned little-endian integer.
UINT16(2),
// The value is a 16-bit signed little-endian integer.
INT16(2),
// The value is a 32-bit unsigned little-endian integer.
UINT32(4),
// The value is a 32-bit signed little-endian integer.
INT32(4),
// The value is a 32-bit IEEE754 floating point number.
FLOAT32(4),
// The value is a boolean.
// 1-byte value where 0 is false and 1 is true.
// Anything else is invalid, and should be treated as either the model being invalid or the reader being buggy.
BOOL(1),
// The value is a UTF-8 non-null-terminated string, with length prepended.
STRING(-8),
// The value is an array of other values, with the length and type prepended.
// Arrays can be nested, and the length of the array is the number of elements in the array, not the number of bytes.
ARRAY(-8),
// The value is a 64-bit unsigned little-endian integer.
UINT64(8),
// The value is a 64-bit signed little-endian integer.
INT64(8),
// The value is a 64-bit IEEE754 floating point number.
FLOAT64(8);
private final int byteSize;
MetadataValueType(int byteSize) {
this.byteSize = byteSize;
}
private static final MetadataValueType[] VALUES = values();
public static MetadataValueType fromIndex(int index) {
return VALUES[index];
}
public int byteSize() {
return byteSize;
}
}
private void loadModelImpl(FileChannel fileChannel) throws IOException {
// The header of the file.
readHeader(fileChannel); // gguf_header_t header;
// Tensor infos, which can be used to locate the tensor data.
// gguf_tensor_info_t tensor_infos[header.tensor_count];
this.tensorInfos = HashMap.newHashMap(tensorCount);
for (int i = 0; i < tensorCount; ++i) {
GGUF.GGUFTensorInfo ti = readTensorInfo(fileChannel);
assert !tensorInfos.containsKey(ti.name);
tensorInfos.put(ti.name, ti);
}
// Padding to the nearest multiple of `ALIGNMENT`.
// uint8_t _padding[ALIGNMENT - (sizeof(header + tensor_infos) % ALIGNMENT)];
//long _padding = -fileChannel.position() & (ALIGNMENT - 1);
long _padding = getAlignment() - (fileChannel.position() % getAlignment());
fileChannel.position(fileChannel.position() + _padding);
// Tensor data.
//
// This is arbitrary binary data corresponding to the weights of the model. This data should be close
// or identical to the data in the original model file, but may be different due to quantization or
// other optimizations for inference. Any such deviations should be recorded in the metadata or as
// part of the architecture definition.
//
// Each tensor's data must be stored within this array, and located through its `tensor_infos` entry.
// The offset of each tensor's data must be a multiple of `ALIGNMENT`, and the space between tensors
// should be padded to `ALIGNMENT` bytes.
// uint8_t tensor_data[];
this.tensorDataOffset = fileChannel.position();
}
public static Map<String, GGMLTensorEntry> loadTensors(FileChannel fileChannel, long tensorDataOffset, Map<String, GGUFTensorInfo> tensorInfos) throws IOException {
Arena arena = Arena.ofAuto();
MemorySegment tensorData = fileChannel.map(FileChannel.MapMode.READ_ONLY, tensorDataOffset, fileChannel.size() - tensorDataOffset, arena);
Map<String, GGMLTensorEntry> tensorEntries = HashMap.newHashMap(tensorInfos.size());
for (Map.Entry<String, GGUFTensorInfo> entry : tensorInfos.entrySet()) {
GGUFTensorInfo ti = entry.getValue();
int numberOfElements = FloatTensor.numberOfElements(ti.dimensions());
int sizeInBytes = Math.toIntExact(ti.ggmlType().byteSizeFor(numberOfElements));
MemorySegment memorySegment = tensorData.asSlice(ti.offset(), sizeInBytes);
tensorEntries.put(ti.name(), new GGMLTensorEntry(tensorData, ti.name(), ti.ggmlType(), ti.dimensions(), memorySegment));
}
return tensorEntries;
}
public record GGUFTensorInfo(String name, int[] dimensions, GGMLType ggmlType, long offset) {
}
private GGMLType readGGMLType(FileChannel fileChannel) throws IOException {
int ggmlTypeId = readInt(fileChannel); // ggml_type type;
return GGMLType.fromId(ggmlTypeId);
}
private GGUF.GGUFTensorInfo readTensorInfo(FileChannel fileChannel) throws IOException {
// The name of the tensor. It is a standard GGUF string, with the caveat that
// it must be at most 64 bytes long.
String name = readString(fileChannel); // gguf_string_t name;
assert name.length() <= 64;
// The number of dimensions in the tensor.
// Currently at most 4, but this may change in the future.
int n_dimensions = readInt(fileChannel); // uint32_t n_dimensions;
assert n_dimensions <= 4;
// The dimensions of the tensor.
int[] dimensions = new int[n_dimensions]; // uint64_t dimensions[n_dimensions];
for (int i = 0; i < n_dimensions; ++i) {
dimensions[i] = Math.toIntExact(readLong(fileChannel));
}
// The type of the tensor.
GGMLType ggmlType = readGGMLType(fileChannel); // ggml_type type;
// The offset of the tensor's data in this file in bytes.
// This offset is relative to `tensor_data`, not to the start
// of the file, to make it easier for writers to write the file.
// Readers should consider exposing this offset relative to the
// file to make it easier to read the data.
// Must be a multiple of `ALIGNMENT`.
long offset = readLong(fileChannel); // uint64_t offset;
assert offset % getAlignment() == 0;
return new GGUF.GGUFTensorInfo(name, dimensions, ggmlType, offset);
}
private String readString(FileChannel fileChannel) throws IOException {
// A string in GGUF.
// The length of the string, in bytes.
int len = Math.toIntExact(readLong(fileChannel)); // uint64_t len;
// The string as a UTF-8 non-null-terminated string.
byte[] bytes = new byte[len]; // char string[len];
int bytesRead = fileChannel.read(ByteBuffer.wrap(bytes));
assert len == bytesRead;
return new String(bytes, StandardCharsets.UTF_8);
}
private Pair<String, Object> readKeyValuePair(FileChannel fileChannel) throws IOException {
// The key of the metadata. It is a standard GGUF string, with the following caveats:
// - It must be a valid ASCII string.
// - It must be a hierarchical key, where each segment is `lower_snake_case` and separated by a `.`.
// - It must be at most 2^16-1/65535 bytes long.
// Any keys that do not follow these rules are invalid.
String key = readString(fileChannel); // gguf_string_t key;
assert key.length() < (1 << 16);
assert key.codePoints().allMatch(cp -> ('a' <= cp && cp <= 'z') || ('0' <= cp && cp <= '9') || cp == '_' || cp == '.');
Object value = readMetadataValue(fileChannel);
return new Pair<>(key, value);
}
private Object readMetadataValue(FileChannel fileChannel) throws IOException {
// The type of the value.
// Must be one of the `gguf_metadata_value_type` values.
MetadataValueType value_type = readMetadataValueType(fileChannel); // gguf_metadata_value_type value_type;
// The value.
return readMetadataValueOfType(value_type, fileChannel); // gguf_metadata_value_t value;
}
void readHeader(FileChannel fileChannel) throws IOException {
// Magic number to announce that this is a GGUF file.
// Must be `GGUF` at the byte level: `0x47` `0x47` `0x55` `0x46`.
// Your executor might do little-endian byte order, so it might be
// check for 0x46554747 and letting the endianness cancel out.
// Consider being *very* explicit about the byte order here.
this.magic = readInt(fileChannel); // uint32_t magic;
if (magic != GGUF_MAGIC) {
throw new IllegalArgumentException("unsupported header.magic " + magic);
}
// The version of the format implemented.
// Must be `3` for version described in this spec.
//
// This version should only be increased for structural changes to the format.
// Changes that do not affect the structure of the file should instead update the metadata
// to signify the change.
this.version = readInt(fileChannel); // uint32_t version;
if (!SUPPORTED_GGUF_VERSIONS.contains(version)) {
throw new IllegalArgumentException("unsupported header.version " + version);
}
// The number of tensors in the file.
// This is explicit, instead of being included in the metadata, to ensure it is always present
// for loading the tensors.
this.tensorCount = Math.toIntExact(readLong(fileChannel)); // uint64_t tensor_count;
// The number of metadata key-value pairs.
this.metadata_kv_count = Math.toIntExact(readLong(fileChannel)); // uint64_t metadata_kv_count;
// The metadata key-value pairs.
// gguf_metadata_kv_t metadata_kv[metadata_kv_count];
this.metadata = HashMap.newHashMap(metadata_kv_count);
for (int i = 0; i < metadata_kv_count; ++i) {
Pair<String, Object> keyValue = readKeyValuePair(fileChannel);
assert !metadata.containsKey(keyValue.first());
metadata.put(keyValue.first(), keyValue.second());
}
}
private Object readArray(FileChannel fileChannel) throws IOException {
// Any value type is valid, including arrays.
MetadataValueType value_type = readMetadataValueType(fileChannel); // gguf_metadata_value_type type;
// Number of elements, not bytes
int len = Math.toIntExact(readLong(fileChannel)); // uint64_t len;
// The array of values.
// gguf_metadata_value_t array[len];
switch (value_type) {
case UINT8, INT8 -> {
byte[] bytes = new byte[len];
for (int i = 0; i < len; ++i) {
bytes[i] = readByte(fileChannel);
}
return bytes;
}
case UINT16, INT16 -> {
short[] shorts = new short[len];
for (int i = 0; i < len; ++i) {
shorts[i] = readShort(fileChannel);
}
return shorts;
}
case UINT32, INT32 -> {
int[] ints = new int[len];
for (int i = 0; i < len; ++i) {
ints[i] = readInt(fileChannel);
}
return ints;
}
case FLOAT32 -> {
float[] floats = new float[len];
for (int i = 0; i < len; ++i) {
floats[i] = readFloat(fileChannel);
}
return floats;
}
case BOOL -> {
boolean[] booleans = new boolean[len];
for (int i = 0; i < len; ++i) {
booleans[i] = readBoolean(fileChannel);
}
return booleans;
}
case STRING -> {
String[] strings = new String[len];
for (int i = 0; i < len; ++i) {
strings[i] = readString(fileChannel);
}
return strings;
}
case ARRAY -> {
Object[] arrays = new Object[len];
for (int i = 0; i < len; ++i) {
arrays[i] = readArray(fileChannel);
}
return arrays;
}
default -> throw new UnsupportedOperationException("read array of " + value_type);
}
}
private Object readMetadataValueOfType(MetadataValueType valueType, FileChannel fileChannel) throws IOException {
return switch (valueType) {
case UINT8, INT8 -> readByte(fileChannel);
case UINT16, INT16 -> readShort(fileChannel);
case UINT32, INT32 -> readInt(fileChannel);
case FLOAT32 -> readFloat(fileChannel);
case UINT64, INT64 -> readLong(fileChannel);
case FLOAT64 -> readDouble(fileChannel);
case BOOL -> readBoolean(fileChannel);
case STRING -> readString(fileChannel);
case ARRAY -> readArray(fileChannel);
};
}
private byte readByte(FileChannel fileChannel) throws IOException {
int bytesRead = fileChannel.read(BB_1);
assert bytesRead == 1;
return BB_1.clear().get(0);
}
private boolean readBoolean(FileChannel fileChannel) throws IOException {
return readByte(fileChannel) != 0;
}
private short readShort(FileChannel fileChannel) throws IOException {
int bytesRead = fileChannel.read(BB_2);
assert bytesRead == 2;
return BB_2.clear().getShort(0);
}
private int readInt(FileChannel fileChannel) throws IOException {
int bytesRead = fileChannel.read(BB_4);
assert bytesRead == 4;
return BB_4.clear().getInt(0);
}
private long readLong(FileChannel fileChannel) throws IOException {
int bytesRead = fileChannel.read(BB_8);
assert bytesRead == 8;
return BB_8.clear().getLong(0);
}
private float readFloat(FileChannel fileChannel) throws IOException {
return Float.intBitsToFloat(readInt(fileChannel));
}
private double readDouble(FileChannel fileChannel) throws IOException {
return Double.longBitsToDouble(readLong(fileChannel));
}
private MetadataValueType readMetadataValueType(FileChannel fileChannel) throws IOException {
int index = readInt(fileChannel);
return MetadataValueType.fromIndex(index);
}
public int getAlignment() {
if (alignment != 0) {
return alignment;
}
alignment = (int) metadata.getOrDefault("general.alignment", DEFAULT_ALIGNMENT);
assert Integer.bitCount(alignment) == 1 : "alignment must be a power of two";
return alignment;
}
}
interface Timer extends AutoCloseable {
@Override
void close(); // no Exception
static Timer log(String label) {
return log(label, TimeUnit.MILLISECONDS);
}
static Timer log(String label, TimeUnit timeUnit) {
return new Timer() {
final long startNanos = System.nanoTime();
@Override
public void close() {
long elapsedNanos = System.nanoTime() - startNanos;
System.err.println(label + ": "
+ timeUnit.convert(elapsedNanos, TimeUnit.NANOSECONDS) + " "
+ timeUnit.toChronoUnit().name().toLowerCase());
}
};
}
}
final class ModelLoader {
private static final String TOKENIZER_LLAMA_3_MODEL = "gpt2";
private static final String LLAMA_3_PATTERN = "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+";
private static Vocabulary loadVocabulary(Map<String, Object> metadata) {
String model = (String) metadata.get("tokenizer.ggml.model");
if (!TOKENIZER_LLAMA_3_MODEL.equals(model)) {
throw new IllegalArgumentException("expected " + TOKENIZER_LLAMA_3_MODEL + " but found " + model);
}
String[] tokens = (String[]) metadata.get("tokenizer.ggml.tokens");
return new Vocabulary(tokens, null);
}
public static Llama loadModel(Path ggufPath, int contextLength, boolean loadWeights) throws IOException {
GGUF gguf = GGUF.loadModel(ggufPath);
FileChannel fileChannel = FileChannel.open(ggufPath, StandardOpenOption.READ);
return loadModel(fileChannel, gguf, contextLength, loadWeights);
}
public static Llama loadModel(FileChannel fileChannel, GGUF gguf, int contextLength, boolean loadWeights) throws IOException {
try (var ignored = Timer.log("Load LlaMa model")) {
Map<String, Object> metadata = gguf.getMetadata();
Vocabulary vocabulary = loadVocabulary(metadata);
Tokenizer tokenizer = createTokenizer(metadata, vocabulary);
Llama.Configuration config = new Llama.Configuration(
(int) metadata.get("llama.embedding_length"),
(int) metadata.get("llama.feed_forward_length"),
(int) metadata.get("llama.block_count"),
(int) metadata.get("llama.attention.head_count"),
metadata.containsKey("llama.attention.head_count_kv")
? (int) metadata.get("llama.attention.head_count_kv")
: (int) metadata.get("llama.attention.head_count"),
vocabulary.size(),
(int) metadata.get("llama.context_length"),
(float) metadata.getOrDefault("llama.attention.layer_norm_rms_epsilon", 1e-5f),
(float) metadata.getOrDefault("llama.rope.freq_base", 10000f)
).withContextLength(contextLength);
Llama.Weights weights = null;
if (loadWeights) {
Map<String, GGMLTensorEntry> tensorEntries = GGUF.loadTensors(fileChannel, gguf.getTensorDataOffset(), gguf.getTensorInfos());
weights = loadWeights(tensorEntries, config);
}
return new Llama(config, tokenizer, weights);
}
}
static Llama.Weights loadWeights(Map<String, GGMLTensorEntry> tensorEntries, Llama.Configuration config) {
boolean ropeScaling = tensorEntries.containsKey("rope_freqs");
float scaleFactor = 8;
float loFreqFactor = 1;
float hiFreqFactor = 3;
int oldContextLength = 8192;
Pair<float[], float[]> ropeFreqs = RoPE.precomputeFreqsCis(config.contextLength, config.headSize, config.ropeTheta,
ropeScaling, scaleFactor, loFreqFactor, hiFreqFactor, oldContextLength);
float[] ropeFreqsReal = ropeFreqs.first();
float[] ropeFreqsImag = ropeFreqs.second();
GGMLTensorEntry tokenEmbeddings = tensorEntries.get("token_embd.weight");
Llama.Weights qw = new Llama.Weights(
loadQuantized(tokenEmbeddings),
loadArrayOfFloatBuffer(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".attn_norm.weight")),
loadArrayOfQuantized(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".attn_q.weight")),
loadArrayOfQuantized(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".attn_k.weight")),
loadArrayOfQuantized(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".attn_v.weight")),
loadArrayOfQuantized(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".attn_output.weight")),
loadArrayOfFloatBuffer(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".ffn_norm.weight")),
loadArrayOfQuantized(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".ffn_gate.weight")), // w1
loadArrayOfQuantized(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".ffn_down.weight")), // w2
loadArrayOfQuantized(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".ffn_up.weight")), // w3
toFloatBuffer(tensorEntries.get("output_norm.weight")),
FloatBuffer.wrap(ropeFreqsReal),
FloatBuffer.wrap(ropeFreqsImag),
// If "output.weight" is not present then the embedding weights are tied/shared with the decoder.
// This is commonly referred as "tie word embeddings".
loadQuantized(tensorEntries.getOrDefault("output.weight", tokenEmbeddings))
);
return qw;
}
private static Tokenizer createTokenizer(Map<String, Object> metadata, Vocabulary vocabulary) {
String[] mergeLines = (String[]) metadata.get("tokenizer.ggml.merges");
List<Pair<Integer, Integer>> merges = Arrays.stream(mergeLines)
.map(line -> line.split(" "))
.map(parts ->
new Pair<>(
vocabulary.getIndex(parts[0]).orElseThrow(),
vocabulary.getIndex(parts[1]).orElseThrow())
).toList();
int allTokens = vocabulary.size();
int baseTokens = 128000; // assume all tokens after the base ones are special.
int reservedSpecialTokens = allTokens - baseTokens;
List<String> specialTokensList = Arrays.stream(vocabulary.tokens(), baseTokens, allTokens).toList();
assert specialTokensList.stream().allMatch(token -> vocabulary.getIndex(token).isPresent());
Map<String, Integer> specialTokens =
IntStream.range(0, specialTokensList.size())
.boxed()
.collect(Collectors.toMap(
i -> specialTokensList.get(i),
i -> baseTokens + i)
);
return new Tokenizer(vocabulary, merges, LLAMA_3_PATTERN, specialTokens);
}
public static FloatTensor loadQuantized(GGMLTensorEntry entry) {
GGMLType ggmlType = entry.ggmlType();
return switch (ggmlType) {
//case F32 -> new F32FloatTensor(FloatTensor.numberOfElements(entry.shape()), entry.memorySegment());
case Q8_0 -> new Q8_0FloatTensor(FloatTensor.numberOfElements(entry.shape()), entry.memorySegment());
case Q4_0 -> new Q4_0FloatTensor(FloatTensor.numberOfElements(entry.shape()), entry.memorySegment());
case BF16 -> new BF16FloatTensor(FloatTensor.numberOfElements(entry.shape()), entry.memorySegment());
case F16 -> new F16FloatTensor(FloatTensor.numberOfElements(entry.shape()), entry.memorySegment());
default -> throw new UnsupportedOperationException("Quantization format " + ggmlType);
};
}
public static FloatTensor[] loadArrayOfQuantized(int size, IntFunction<GGMLTensorEntry> getTensorEntry) {
FloatTensor[] array = new FloatTensor[size];
for (int i = 0; i < size; i++) {
array[i] = loadQuantized(getTensorEntry.apply(i));
}
return array;
}
public static FloatBuffer[] loadArrayOfFloatBuffer(int size, IntFunction<GGMLTensorEntry> getTensorEntry) {
FloatBuffer[] array = new FloatBuffer[size];
for (int i = 0; i < size; i++) {
array[i] = toFloatBuffer(getTensorEntry.apply(i));
}
return array;
}
public static FloatBuffer toFloatBuffer(GGMLTensorEntry tensorEntry) {
GGMLType ggmlType = tensorEntry.ggmlType();
return switch (ggmlType) {
case F32 -> tensorEntry.memorySegment().asByteBuffer().order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer();
default -> throw new UnsupportedOperationException("Conversion to " + ggmlType);
};
}
}
record Llama(Configuration configuration, Tokenizer tokenizer, Weights weights) {
public State createNewState(int batchsize) {
State state = new State(configuration(), batchsize);
state.latestToken = tokenizer.getSpecialTokens().get("<|begin_of_text|>");
return state;
}
public static final class Configuration {
public final int dim; // transformer dimension
public final int hiddenDim; // for ffn layers
public final int numberOfLayers; // number of layers
public final int numberOfHeads; // number of query heads
public final int numberOfKeyValueHeads; // number of key/value heads (can be < query heads because of multiquery)
public final int vocabularySize; // vocabulary size, usually 256 (byte-level)
public final int contextLength; // max sequence length
public final float rmsNormEps;
public final float ropeTheta;
public final int headSize;
Configuration withContextLength(int newContextLength) {
if (newContextLength < 0) {
return this; // no change
}
return new Configuration(this.dim, this.hiddenDim, this.numberOfLayers, this.numberOfHeads, this.numberOfKeyValueHeads, this.vocabularySize, newContextLength, this.rmsNormEps, this.ropeTheta);
}
public Configuration(int dim, int hiddenDim, int numberOfLayers, int numberOfHeads, int numberOfKeyValueHeads, int vocabularySize, int contextLength, float rmsNormEps, float ropeTheta) {
this.dim = dim;
this.hiddenDim = hiddenDim;
this.numberOfLayers = numberOfLayers;
this.numberOfHeads = numberOfHeads;
this.numberOfKeyValueHeads = numberOfKeyValueHeads;
this.vocabularySize = vocabularySize;
this.contextLength = contextLength;
this.rmsNormEps = rmsNormEps;
this.ropeTheta = ropeTheta;
this.headSize = dim / numberOfHeads;
}
}
public static final class Weights {
// token embedding table
public final FloatTensor token_embedding_table; // (vocab_size, dim)
// weights for rmsnorms
public final FloatBuffer[] rms_att_weight; // (layer, dim) rmsnorm weights
// weights for matmuls
public final FloatTensor[] wq; // (layer, n_heads * head_size)
public final FloatTensor[] wk; // (layer, n_kv_heads, head_size)
public final FloatTensor[] wv; // (layer, n_kv_heads * head_size)
public final FloatTensor[] wo; // (layer, n_heads * head_size, dim)
public final FloatBuffer[] rms_ffn_weight; // (layer, dim)
// weights for ffn
public final FloatTensor[] w1; // (layer, hidden_dim, dim)
public final FloatTensor[] w2; // (layer, dim, hidden_dim)
public final FloatTensor[] w3; // (layer, hidden_dim, dim)
// public final rmsnorm
public final FloatBuffer rms_final_weight; // (dim,)
// freq_cis for RoPE relatively positional embeddings
public final FloatBuffer freq_cis_real; // (seq_len, head_size/2)
public final FloatBuffer freq_cis_imag; // (seq_len, head_size/2)
// (optional) classifier weights for the logits, on the last layer
public final FloatTensor wcls; // (vocab_size, dim)
public Weights(FloatTensor token_embedding_table, FloatBuffer[] rms_att_weight, FloatTensor[] wq, FloatTensor[] wk, FloatTensor[] wv, FloatTensor[] wo, FloatBuffer[] rms_ffn_weight, FloatTensor[] w1, FloatTensor[] w2, FloatTensor[] w3, FloatBuffer rms_final_weight, FloatBuffer freq_cis_real, FloatBuffer freq_cis_imag, FloatTensor wcls) {
this.token_embedding_table = token_embedding_table;
this.rms_att_weight = rms_att_weight;
this.wq = wq;
this.wk = wk;
this.wv = wv;
this.wo = wo;
this.rms_ffn_weight = rms_ffn_weight;
this.w1 = w1;
this.w2 = w2;
this.w3 = w3;
this.rms_final_weight = rms_final_weight;
this.freq_cis_real = freq_cis_real;
this.freq_cis_imag = freq_cis_imag;
this.wcls = wcls;
}
}
public static final class State {
// current wave of activations
public final int batchsize;
public final FloatTensor[] x; // activation at current time stamp (dim,)
public final FloatTensor[] xb; // same, but inside a residual branch (dim,)
public final FloatTensor[] xb2; // an additional buffer just for convenience (dim,)
public final FloatTensor[] hb; // buffer for hidden dimension in the ffn (hidden_dim,)
public final FloatTensor[] hb2; // buffer for hidden dimension in the ffn (hidden_dim,)
public final FloatTensor[] q; // query (dim,)
public final FloatTensor[] k; // key (dim,)
public final FloatTensor[] v; // value (dim,)
public final FloatTensor[] att; // buffer for scores/attention values (n_heads, seq_len)
public final FloatTensor logits; // output logits
// kv cache
public final FloatTensor[] keyCache; // (n_layer, seq_len, kv_dim)
public final FloatTensor[] valueCache; // (n_layer, seq_len, kv_dim)
/** last index in previous block */
int idxPrevBlock;
public int latestToken;
State(Configuration config, int batchsize) {
this.batchsize = batchsize;
this.x = allocate(batchsize, config.dim);
this.xb = allocate(batchsize, config.dim);
this.xb2 = allocate(batchsize, config.dim);
this.hb = allocate(batchsize, config.hiddenDim);
this.hb2 = allocate(batchsize, config.hiddenDim);
this.q = allocate(batchsize, config.dim);
this.k = allocate(batchsize, config.dim);
this.v = allocate(batchsize, config.dim);
this.att = allocate(batchsize, config.numberOfHeads, config.contextLength);
idxPrevBlock = -1;
this.logits = ArrayFloatTensor.allocate(config.vocabularySize);
int kvDim = (config.dim * config.numberOfKeyValueHeads) / config.numberOfHeads;
this.keyCache = Stream.generate(() -> ArrayFloatTensor.allocate(config.contextLength, kvDim)).limit(config.numberOfLayers).toArray(FloatTensor[]::new);
this.valueCache = Stream.generate(() -> ArrayFloatTensor.allocate(config.contextLength, kvDim)).limit(config.numberOfLayers).toArray(FloatTensor[]::new);
}
}
static FloatTensor[] allocate(int numTokens, int... dims) {
return IntStream.range(0, numTokens)
.mapToObj(i -> ArrayFloatTensor.allocate(dims))
.toArray(FloatTensor[]::new);
}
static void rmsnorm(FloatTensor out, FloatTensor x, FloatBuffer weight, int size, float rmsNormEps) {
// calculate sum of squares
float ss = x.reduce(0, size, 0f, (acc, xi) -> acc + xi * xi);
ss /= size;
ss += rmsNormEps;
ss = (float) (1.0 / Math.sqrt(ss));
// normalize and scale
final float finalss = ss; // for the lambda
out.mapWithIndexInPlace(0, size, (value, index) -> weight.get(index) * (finalss * x.getFloat(index)));
}
static FloatTensor forward(Llama model, State state, int[] tokens, int position, boolean computeLogits) {
// a few convenience variables
Configuration config = model.configuration();
Weights weights = model.weights();
int dim = config.dim;
int headSize = config.headSize;
int kvDim = (config.dim * config.numberOfKeyValueHeads) / config.numberOfHeads;
int kvMul = config.numberOfHeads / config.numberOfKeyValueHeads; // integer multiplier of the kv sharing in multiquery
float sqrtHeadSize = (float) Math.sqrt(headSize);
final int nTokens = tokens.length;
// copy the token embedding into x
Parallel.parallelFor(0, nTokens, t ->
weights.token_embedding_table.copyTo(tokens[t] * dim, state.x[t], 0, dim)
);
// forward all the layers
for (int l = 0; l < config.numberOfLayers; l++) {
// attention rmsnorm
// rmsnorm(state.xb, state.x, weights.rms_att_weight[l], dim, config.rmsNormEps);
final int curLayer = l;
Parallel.parallelFor(0, nTokens, t ->
rmsnorm(state.xb[t], state.x[t], weights.rms_att_weight[curLayer], dim, config.rmsNormEps)
);
// qkv matmuls for this position
weights.wq[l].matmul(nTokens, state.xb, state.q, dim, dim);
weights.wk[l].matmul(nTokens, state.xb, state.k, kvDim, dim);
weights.wv[l].matmul(nTokens, state.xb, state.v, kvDim, dim);
// RoPE relative positional encoding: complex-valued rotate q and k in each head
Parallel.parallelFor(0, nTokens, t -> {
for (int i = 0; i < dim; i += 2) {
int head_dim = i % headSize;
float fcr = weights.freq_cis_real.get((position + t) * (headSize / 2) + (head_dim / 2));
float fci = weights.freq_cis_imag.get((position + t) * (headSize / 2) + (head_dim / 2));
int rotn = i < kvDim ? 2 : 1; // how many vectors? 2 = q & k, 1 = q only
for (int vi = 0; vi < rotn; vi++) {
FloatTensor vec = vi == 0 ? state.q[t] : state.k[t]; // the vector to rotate (query or key)
float v0 = vec.getFloat(i);