-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGemma4.java
More file actions
3847 lines (3371 loc) · 172 KB
/
Gemma4.java
File metadata and controls
3847 lines (3371 loc) · 172 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
///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.Gemma4
// Gemma 4 inference in pure Java
// Author: Alfonso² Peterssen
// Based on Andrej Karpathy's llama2.c and minbpe projects
// Related project: https://github.com/mukel/llama3.java
//
// Supports GGUF models and multiple tensor formats
// Matrix-vector kernels use Java's Vector API
// CLI modes: --chat and --instruct
//
// Run:
// jbang Gemma4.java --help
package com.llama4j;
import jdk.incubator.vector.ByteVector;
import jdk.incubator.vector.FloatVector;
import jdk.incubator.vector.ShortVector;
import jdk.incubator.vector.VectorOperators;
import jdk.incubator.vector.VectorShape;
import jdk.incubator.vector.VectorSpecies;
import java.lang.reflect.Field;
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.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
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.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
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 int PARSE_BUFFER_SIZE = 1 << 20;
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;
private Map<String, GGUFTensorInfo> tensorInfos;
private long tensorDataOffset;
public Map<String, Object> getMetadata() {
return metadata;
}
public long getTensorDataOffset() {
return tensorDataOffset;
}
public Map<String, GGUFTensorInfo> getTensorInfos() {
return tensorInfos;
}
private static final class ChannelReader {
private final ReadableByteChannel channel;
private final ByteBuffer buffer;
private long position;
private ChannelReader(ReadableByteChannel channel, int bufferSize) {
this.channel = channel;
this.buffer = ByteBuffer.allocateDirect(bufferSize).order(ByteOrder.LITTLE_ENDIAN);
this.buffer.limit(0);
this.position = 0L;
}
long position() {
return position;
}
private void ensure(int required) throws IOException {
if (required > buffer.capacity()) {
throw new IllegalArgumentException("Requested read " + required + " exceeds buffer capacity " + buffer.capacity());
}
if (buffer.remaining() >= required) {
return;
}
buffer.compact();
while (buffer.position() < required) {
int read = channel.read(buffer);
if (read < 0) {
throw new IOException("Unexpected EOF while reading GGUF metadata");
}
}
buffer.flip();
}
byte readByte() throws IOException {
ensure(Byte.BYTES);
position += Byte.BYTES;
return buffer.get();
}
short readShort() throws IOException {
ensure(Short.BYTES);
position += Short.BYTES;
return buffer.getShort();
}
int readInt() throws IOException {
ensure(Integer.BYTES);
position += Integer.BYTES;
return buffer.getInt();
}
long readLong() throws IOException {
ensure(Long.BYTES);
position += Long.BYTES;
return buffer.getLong();
}
float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
double readDouble() throws IOException {
return Double.longBitsToDouble(readLong());
}
byte[] readBytes(int length) throws IOException {
byte[] bytes = new byte[length];
int copied = 0;
while (copied < length) {
if (!buffer.hasRemaining()) {
ensure(1);
}
int chunk = Math.min(length - copied, buffer.remaining());
buffer.get(bytes, copied, chunk);
copied += chunk;
position += chunk;
}
return bytes;
}
void skipBytes(int length) throws IOException {
int remaining = length;
while (remaining > 0) {
if (!buffer.hasRemaining()) {
ensure(1);
}
int chunk = Math.min(remaining, buffer.remaining());
buffer.position(buffer.position() + chunk);
remaining -= chunk;
position += chunk;
}
}
}
public static Map<String, GGMLTensorEntry> loadTensors(FileChannel fileChannel, long tensorDataOffset, Map<String, GGUFTensorInfo> tensorInfos) throws IOException {
Arena arena = Arena.global();
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();
long numberOfElements = FloatTensor.numberOfElementsLong(ti.dimensions());
long sizeInBytes = 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 static GGUF loadModel(Path modelPath) throws IOException {
try (FileChannel fileChannel = FileChannel.open(modelPath)) {
return loadModel(fileChannel, modelPath.toString());
}
}
public static GGUF loadModel(FileChannel fileChannel, String modelLabel) throws IOException {
try (var ignored = Timer.log("Parse " + modelLabel)) {
fileChannel.position(0L);
GGUF gguf = new GGUF();
ChannelReader reader = new ChannelReader(fileChannel, PARSE_BUFFER_SIZE);
gguf.loadModelImpl(reader);
return gguf;
}
}
enum MetadataValueType {
UINT8, INT8, UINT16, INT16, UINT32, INT32, FLOAT32, BOOL, STRING, ARRAY, UINT64, INT64, FLOAT64;
private static final MetadataValueType[] VALUES = values();
public static MetadataValueType fromIndex(int index) {
return VALUES[index];
}
}
private void loadModelImpl(ChannelReader reader) throws IOException {
readHeader(reader);
this.tensorInfos = HashMap.newHashMap(tensorCount);
for (int i = 0; i < tensorCount; ++i) {
GGUF.GGUFTensorInfo ti = readTensorInfo(reader);
assert !tensorInfos.containsKey(ti.name);
tensorInfos.put(ti.name, ti);
}
long position = reader.position();
int padding = (int) ((getAlignment() - (position % getAlignment())) % getAlignment());
skipBytes(reader, padding);
this.tensorDataOffset = reader.position();
}
public record GGUFTensorInfo(String name, int[] dimensions, GGMLType ggmlType, long offset) {
}
private GGMLType readGGMLType(ChannelReader reader) throws IOException {
int ggmlTypeId = readInt(reader);
return GGMLType.fromId(ggmlTypeId);
}
private GGUF.GGUFTensorInfo readTensorInfo(ChannelReader reader) throws IOException {
String name = readString(reader);
assert name.length() <= 64;
int n_dimensions = readInt(reader);
assert n_dimensions <= 4;
int[] dimensions = new int[n_dimensions];
for (int i = 0; i < n_dimensions; ++i) {
dimensions[i] = Math.toIntExact(readLong(reader));
}
GGMLType ggmlType = readGGMLType(reader);
long offset = readLong(reader);
assert offset % getAlignment() == 0;
return new GGUF.GGUFTensorInfo(name, dimensions, ggmlType, offset);
}
private String readString(ChannelReader reader) throws IOException {
int len = Math.toIntExact(readLong(reader));
return new String(readBytes(reader, len), StandardCharsets.UTF_8);
}
private Pair<String, Object> readKeyValuePair(ChannelReader reader) throws IOException {
String key = readString(reader);
assert key.length() < (1 << 16);
assert key.codePoints().allMatch(cp -> ('a' <= cp && cp <= 'z') || ('0' <= cp && cp <= '9') || cp == '_' || cp == '.');
Object value = readMetadataValue(reader);
return new Pair<>(key, value);
}
private Object readMetadataValue(ChannelReader reader) throws IOException {
MetadataValueType valueType = readMetadataValueType(reader);
return readMetadataValueOfType(valueType, reader);
}
void readHeader(ChannelReader reader) throws IOException {
this.magic = readInt(reader);
if (magic != GGUF_MAGIC) {
throw new IllegalArgumentException("unsupported header.magic " + magic);
}
this.version = readInt(reader);
if (!SUPPORTED_GGUF_VERSIONS.contains(version)) {
throw new IllegalArgumentException("unsupported header.version " + version);
}
this.tensorCount = Math.toIntExact(readLong(reader));
this.metadata_kv_count = Math.toIntExact(readLong(reader));
this.metadata = HashMap.newHashMap(metadata_kv_count);
for (int i = 0; i < metadata_kv_count; ++i) {
Pair<String, Object> keyValue = readKeyValuePair(reader);
assert !metadata.containsKey(keyValue.first());
metadata.put(keyValue.first(), keyValue.second());
}
}
private Object readArray(ChannelReader reader) throws IOException {
MetadataValueType valueType = readMetadataValueType(reader);
int len = Math.toIntExact(readLong(reader));
switch (valueType) {
case UINT8, INT8 -> {
return readBytes(reader, len);
}
case UINT16, INT16 -> {
short[] shorts = new short[len];
for (int i = 0; i < len; ++i) {
shorts[i] = readShort(reader);
}
return shorts;
}
case UINT32, INT32 -> {
int[] ints = new int[len];
for (int i = 0; i < len; ++i) {
ints[i] = readInt(reader);
}
return ints;
}
case FLOAT32 -> {
float[] floats = new float[len];
for (int i = 0; i < len; ++i) {
floats[i] = readFloat(reader);
}
return floats;
}
case BOOL -> {
boolean[] booleans = new boolean[len];
for (int i = 0; i < len; ++i) {
booleans[i] = readBoolean(reader);
}
return booleans;
}
case STRING -> {
String[] strings = new String[len];
for (int i = 0; i < len; ++i) {
strings[i] = readString(reader);
}
return strings;
}
case ARRAY -> {
Object[] arrays = new Object[len];
for (int i = 0; i < len; ++i) {
arrays[i] = readArray(reader);
}
return arrays;
}
default -> throw new UnsupportedOperationException("read array of " + valueType);
}
}
private Object readMetadataValueOfType(MetadataValueType valueType, ChannelReader reader) throws IOException {
return switch (valueType) {
case UINT8, INT8 -> readByte(reader);
case UINT16, INT16 -> readShort(reader);
case UINT32, INT32 -> readInt(reader);
case FLOAT32 -> readFloat(reader);
case UINT64, INT64 -> readLong(reader);
case FLOAT64 -> readDouble(reader);
case BOOL -> readBoolean(reader);
case STRING -> readString(reader);
case ARRAY -> readArray(reader);
};
}
private MetadataValueType readMetadataValueType(ChannelReader reader) throws IOException {
int index = readInt(reader);
return MetadataValueType.fromIndex(index);
}
private byte[] readBytes(ChannelReader reader, int length) throws IOException {
return reader.readBytes(length);
}
private void skipBytes(ChannelReader reader, int length) throws IOException {
reader.skipBytes(length);
}
private byte readByte(ChannelReader reader) throws IOException {
return reader.readByte();
}
private boolean readBoolean(ChannelReader reader) throws IOException {
return readByte(reader) != 0;
}
private short readShort(ChannelReader reader) throws IOException {
return reader.readShort();
}
private int readInt(ChannelReader reader) throws IOException {
return reader.readInt();
}
private long readLong(ChannelReader reader) throws IOException {
return reader.readLong();
}
private float readFloat(ChannelReader reader) throws IOException {
return reader.readFloat();
}
private double readDouble(ChannelReader reader) throws IOException {
return reader.readDouble();
}
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 Vocabulary loadVocabulary(Map<String, Object> metadata) {
String[] tokens = (String[]) metadata.get("tokenizer.ggml.tokens");
float[] scores = (float[]) metadata.get("tokenizer.ggml.scores");
return new Vocabulary(tokens, scores);
}
public static Llama loadModel(Path ggufPath, int contextLength) throws IOException {
try (var ignored = Timer.log("Load Gemma4 model")) {
try (FileChannel fileChannel = FileChannel.open(ggufPath, StandardOpenOption.READ)) {
GGUF gguf = GGUF.loadModel(fileChannel, ggufPath.toString());
return loadModel(fileChannel, gguf, contextLength, true);
}
}
}
static Llama loadModel(FileChannel fileChannel, GGUF gguf, int contextLength, boolean loadWeightsFlag) throws IOException {
Map<String, Object> metadata = gguf.getMetadata();
Vocabulary vocabulary = loadVocabulary(metadata);
GemmaTokenizer tokenizer = createTokenizer(metadata, vocabulary);
int modelContextLength = (int) metadata.get("gemma4.context_length");
if (contextLength < 0 || modelContextLength < contextLength) {
contextLength = modelContextLength;
}
int embeddingLength = (int) metadata.get("gemma4.embedding_length");
int numberOfHeads = (int) metadata.get("gemma4.attention.head_count");
int numberOfLayers = (int) metadata.get("gemma4.block_count");
int headSizeFull = (int) metadata.get("gemma4.attention.key_length");
int headSizeSWA = (int) metadata.get("gemma4.attention.key_length_swa");
int slidingWindow = (int) metadata.get("gemma4.attention.sliding_window");
float logitSoftcapping = (float) metadata.getOrDefault("gemma4.final_logit_softcapping", 0f);
float rmsNormEps = (float) metadata.getOrDefault("gemma4.attention.layer_norm_rms_epsilon", 1e-6f);
float ropeTheta = (float) metadata.getOrDefault("gemma4.rope.freq_base", 1000000f);
float ropeThetaSWA = (float) metadata.getOrDefault("gemma4.rope.freq_base_swa", 10000f);
// MoE parameters
int expertCount = (int) metadata.getOrDefault("gemma4.expert_count", 0);
int expertUsedCount = (int) metadata.getOrDefault("gemma4.expert_used_count", 0);
int expertFeedForwardLength = (int) metadata.getOrDefault("gemma4.expert_feed_forward_length", 0);
// Per-layer feed forward lengths (scalar for uniform, array for variable)
int[] feedForwardLength;
Object ffnRaw = metadata.get("gemma4.feed_forward_length");
if (ffnRaw instanceof int[] arr) {
feedForwardLength = arr;
} else {
feedForwardLength = new int[numberOfLayers];
Arrays.fill(feedForwardLength, (int) ffnRaw);
}
Map<String, GGUF.GGUFTensorInfo> tensorInfos = gguf.getTensorInfos();
// Derive isSWA per layer from Q norm weight size (256 = SWA, 512 = full attention)
boolean[] isSWA;
Object swaRaw = metadata.get("gemma4.attention.sliding_window_pattern");
if (swaRaw instanceof boolean[] arr) {
isSWA = arr;
} else {
// Derive from tensor shapes: check Q norm size per layer
isSWA = new boolean[numberOfLayers];
for (int i = 0; i < numberOfLayers; i++) {
GGUF.GGUFTensorInfo qNorm = tensorInfos.get("blk." + i + ".attn_q_norm.weight");
if (qNorm != null) {
long qNormSize = FloatTensor.numberOfElementsLong(qNorm.dimensions());
isSWA[i] = (qNormSize == headSizeSWA);
} else {
isSWA[i] = (i % 5 != 4); // fallback
}
}
}
// Derive per-layer KV head count from K weight shapes
int[] numberOfKeyValueHeadsPerLayer = new int[numberOfLayers];
for (int i = 0; i < numberOfLayers; i++) {
GGUF.GGUFTensorInfo kWeight = tensorInfos.get("blk." + i + ".attn_k.weight");
int headSize = isSWA[i] ? headSizeSWA : headSizeFull;
if (kWeight != null) {
long kDim = kWeight.dimensions()[1];
numberOfKeyValueHeadsPerLayer[i] = (int) (kDim / headSize);
} else {
numberOfKeyValueHeadsPerLayer[i] = numberOfHeads; // fallback
}
}
// Shared KV layers: last N layers reuse KV from earlier layers
int sharedKvLayers = (int) metadata.getOrDefault("gemma4.attention.shared_kv_layers", 0);
int nLayerKvFromStart = numberOfLayers - sharedKvLayers;
int embeddingLengthPerLayer = (int) metadata.getOrDefault("gemma4.embedding_length_per_layer_input", 0);
Llama.Configuration config = new Llama.Configuration(
embeddingLength,
feedForwardLength,
numberOfLayers,
numberOfHeads,
numberOfKeyValueHeadsPerLayer,
vocabulary.size(),
contextLength,
rmsNormEps,
ropeTheta,
ropeThetaSWA,
headSizeFull,
headSizeSWA,
slidingWindow,
logitSoftcapping,
isSWA,
nLayerKvFromStart,
embeddingLengthPerLayer,
expertCount,
expertUsedCount,
expertFeedForwardLength
);
if (!loadWeightsFlag) {
return new Llama(config, tokenizer, null);
}
Map<String, GGMLTensorEntry> tensorEntries = GGUF.loadTensors(fileChannel, gguf.getTensorDataOffset(), tensorInfos);
Llama.Weights qw = loadWeights(tensorEntries, config);
return new Llama(config, tokenizer, qw);
}
public static Llama.Weights loadWeights(Map<String, GGMLTensorEntry> tensorEntries, Llama.Configuration config) {
Pair<float[], float[]> ropeFreqsSWA = RoPE.precomputeFreqsCis(config.contextLength, config.headSizeSWA, config.ropeThetaSWA);
FloatBuffer ropeFreqsBuf = toFloatBuffer(tensorEntries.get("rope_freqs.weight"));
float[] modelRopeFreqs = new float[ropeFreqsBuf.remaining()];
ropeFreqsBuf.get(modelRopeFreqs);
Pair<float[], float[]> ropeFreqsFull = RoPE.precomputeFreqsCisFromFreqs(config.contextLength, config.headSizeFull, config.ropeTheta, modelRopeFreqs);
return loadWeightsWithRoPE(tensorEntries, config, ropeFreqsSWA, ropeFreqsFull);
}
public static Llama.Weights loadWeightsWithRoPE(Map<String, GGMLTensorEntry> tensorEntries, Llama.Configuration config,
Pair<float[], float[]> ropeFreqsSWA, Pair<float[], float[]> ropeFreqsFull) {
int numberOfLayers = config.numberOfLayers;
FloatTensor tokenEmbeddingTable = loadQuantized(tensorEntries.get("token_embd.weight"));
// Load per-layer output scale (scalar per layer)
float[] layerOutputScale = new float[config.numberOfLayers];
for (int i = 0; i < config.numberOfLayers; i++) {
GGMLTensorEntry scaleEntry = tensorEntries.get("blk." + i + ".layer_output_scale.weight");
if (scaleEntry != null) {
layerOutputScale[i] = toFloatBuffer(scaleEntry).get(0);
} else {
layerOutputScale[i] = 1.0f;
}
}
// Load per-layer embedding weights (if present)
FloatTensor perLayerTokenEmbd = null;
FloatTensor perLayerModelProj = null;
FloatBuffer perLayerProjNorm = null;
FloatTensor[] perLayerInpGate = null;
FloatTensor[] perLayerProj = null;
FloatBuffer[] perLayerPostNorm = null;
if (config.embeddingLengthPerLayer > 0 && tensorEntries.containsKey("per_layer_token_embd.weight")) {
perLayerTokenEmbd = loadQuantized(tensorEntries.get("per_layer_token_embd.weight"));
perLayerModelProj = loadQuantized(tensorEntries.get("per_layer_model_proj.weight"));
perLayerProjNorm = toFloatBuffer(tensorEntries.get("per_layer_proj_norm.weight"));
perLayerInpGate = loadArrayOfQuantized(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".inp_gate.weight"));
perLayerProj = loadArrayOfQuantized(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".proj.weight"));
perLayerPostNorm = loadArrayOfFloatBuffer(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".post_norm.weight"));
}
// Load V weights (nullable: layers without V use K as V)
FloatTensor[] wv = new FloatTensor[numberOfLayers];
for (int i = 0; i < numberOfLayers; i++) {
GGMLTensorEntry vEntry = tensorEntries.get("blk." + i + ".attn_v.weight");
wv[i] = vEntry != null ? loadQuantized(vEntry) : null;
}
// Load MoE weights (if present)
FloatTensor[] ffnGateInp = null;
FloatBuffer[] ffnGateInpScale = null;
FloatTensor[] ffnGateUpExps = null;
FloatTensor[] ffnDownExps = null;
FloatBuffer[] ffnDownExpsScale = null;
FloatBuffer[] ffnPostNorm1 = null;
FloatBuffer[] preFfwNorm2 = null;
FloatBuffer[] ffnPostNorm2 = null;
if (config.isMoE()) {
ffnGateInp = loadArrayOfQuantized(numberOfLayers, i -> tensorEntries.get("blk." + i + ".ffn_gate_inp.weight"));
ffnGateInpScale = loadArrayOfFloatBuffer(numberOfLayers, i -> tensorEntries.get("blk." + i + ".ffn_gate_inp.scale"));
ffnGateUpExps = loadArrayOfQuantized(numberOfLayers, i -> tensorEntries.get("blk." + i + ".ffn_gate_up_exps.weight"));
ffnDownExps = loadArrayOfQuantized(numberOfLayers, i -> tensorEntries.get("blk." + i + ".ffn_down_exps.weight"));
ffnDownExpsScale = loadArrayOfFloatBuffer(numberOfLayers, i -> tensorEntries.get("blk." + i + ".ffn_down_exps.scale"));
ffnPostNorm1 = loadArrayOfFloatBuffer(numberOfLayers, i -> tensorEntries.get("blk." + i + ".post_ffw_norm_1.weight"));
preFfwNorm2 = loadArrayOfFloatBuffer(numberOfLayers, i -> tensorEntries.get("blk." + i + ".pre_ffw_norm_2.weight"));
ffnPostNorm2 = loadArrayOfFloatBuffer(numberOfLayers, i -> tensorEntries.get("blk." + i + ".post_ffw_norm_2.weight"));
}
return new Llama.Weights(
tokenEmbeddingTable,
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")),
wv,
loadArrayOfQuantized(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".attn_output.weight")),
loadArrayOfFloatBuffer(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".attn_q_norm.weight")),
loadArrayOfFloatBuffer(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".attn_k_norm.weight")),
loadArrayOfFloatBuffer(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".post_attention_norm.weight")),
loadArrayOfFloatBuffer(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".ffn_norm.weight")),
loadArrayOfQuantized(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".ffn_gate.weight")),
loadArrayOfQuantized(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".ffn_down.weight")),
loadArrayOfQuantized(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".ffn_up.weight")),
loadArrayOfFloatBuffer(config.numberOfLayers, i -> tensorEntries.get("blk." + i + ".post_ffw_norm.weight")),
toFloatBuffer(tensorEntries.get("output_norm.weight")),
layerOutputScale,
FloatBuffer.wrap(ropeFreqsFull.first()),
FloatBuffer.wrap(ropeFreqsFull.second()),
FloatBuffer.wrap(ropeFreqsSWA.first()),
FloatBuffer.wrap(ropeFreqsSWA.second()),
tensorEntries.containsKey("output.weight")
? loadQuantized(tensorEntries.get("output.weight"))
: tokenEmbeddingTable,
perLayerTokenEmbd, perLayerModelProj, perLayerProjNorm,
perLayerInpGate, perLayerProj, perLayerPostNorm,
ffnGateInp, ffnGateInpScale, ffnGateUpExps, ffnDownExps, ffnDownExpsScale,
ffnPostNorm1, preFfwNorm2, ffnPostNorm2
);
}
private static GemmaTokenizer createTokenizer(Map<String, Object> metadata, Vocabulary vocabulary) {
int[] tokenTypes = (int[]) metadata.get("tokenizer.ggml.token_type");
return new GemmaTokenizer(vocabulary, tokenTypes);
}
public static FloatTensor loadQuantized(GGMLTensorEntry entry) {
GGMLType ggmlType = entry.ggmlType();
long numElements = FloatTensor.numberOfElementsLong(entry.shape());
return switch (ggmlType) {
case Q8_0 -> new Q8_0FloatTensor(numElements, entry.memorySegment());
case Q4_0 -> new Q4_0FloatTensor(numElements, entry.memorySegment());
case Q4_1 -> new Q4_1FloatTensor(numElements, entry.memorySegment());
case Q5_1 -> new Q5_1FloatTensor(numElements, entry.memorySegment());
case Q4_K -> new Q4_KFloatTensor(numElements, entry.memorySegment());
case Q5_K -> new Q5_KFloatTensor(numElements, entry.memorySegment());
case Q6_K -> new Q6_KFloatTensor(numElements, entry.memorySegment());
case F32 -> new F32FloatTensor(numElements, entry.memorySegment());
case F16 -> new F16FloatTensor(numElements, entry.memorySegment());
case BF16 -> new BF16FloatTensor(numElements, entry.memorySegment());
case MXFP4 -> new MXFP4FloatTensor(numElements, 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, GemmaTokenizer tokenizer, Weights weights) {
public State createNewState() {
State state = new State(configuration());
state.latestToken = tokenizer.getSpecialTokens().get("<bos>");
return state;
}
public static final class Configuration {
public final int embeddingLength;
public final int[] feedForwardLength; // per-layer (shared MLP)
public final int numberOfLayers;
public final int numberOfHeads;
public final int[] numberOfKeyValueHeadsPerLayer; // per-layer KV head count
public final int vocabularySize;
public final int contextLength;
public final float rmsNormEps;
public final float ropeTheta; // full attention RoPE theta
public final float ropeThetaSWA; // SWA RoPE theta
public final int headSizeFull; // head size for full attention layers
public final int headSizeSWA; // head size for SWA layers
public final int slidingWindow;
public final float logitSoftcapping;
public final boolean[] isSWA; // per-layer: true = SWA, false = full attention
public final int nLayerKvFromStart; // first N layers have own KV cache, rest reuse
public final int embeddingLengthPerLayer; // per-layer embedding dim (0 = disabled)
// MoE fields
public final int expertCount; // 0 = dense model (no MoE)
public final int expertUsedCount; // top-k experts per token
public final int expertFeedForwardLength; // expert FFN hidden dim
public Configuration(int embeddingLength, int[] feedForwardLength, int numberOfLayers,
int numberOfHeads, int[] numberOfKeyValueHeadsPerLayer, int vocabularySize,
int contextLength, float rmsNormEps, float ropeTheta, float ropeThetaSWA,
int headSizeFull, int headSizeSWA, int slidingWindow,
float logitSoftcapping, boolean[] isSWA, int nLayerKvFromStart,
int embeddingLengthPerLayer,
int expertCount, int expertUsedCount, int expertFeedForwardLength) {
this.embeddingLength = embeddingLength;
this.feedForwardLength = feedForwardLength;
this.numberOfLayers = numberOfLayers;
this.numberOfHeads = numberOfHeads;
this.numberOfKeyValueHeadsPerLayer = numberOfKeyValueHeadsPerLayer;
this.vocabularySize = vocabularySize;
this.contextLength = contextLength;
this.rmsNormEps = rmsNormEps;
this.ropeTheta = ropeTheta;
this.ropeThetaSWA = ropeThetaSWA;
this.headSizeFull = headSizeFull;
this.headSizeSWA = headSizeSWA;
this.slidingWindow = slidingWindow;
this.logitSoftcapping = logitSoftcapping;
this.isSWA = isSWA;
this.nLayerKvFromStart = nLayerKvFromStart;
this.embeddingLengthPerLayer = embeddingLengthPerLayer;
this.expertCount = expertCount;
this.expertUsedCount = expertUsedCount;
this.expertFeedForwardLength = expertFeedForwardLength;
}
public boolean isMoE() { return expertCount > 0; }
// For layers without own KV, return the layer whose cache to reuse
public int kvSourceLayer(int layer) {
if (layer < nLayerKvFromStart) return layer; // has own KV
// Reuse the last KV layer of the same attention type
return nLayerKvFromStart - (isSWA[layer] ? 2 : 1);
}
public boolean hasKv(int layer) {
return layer < nLayerKvFromStart;
}
public int headSize(int layer) {
return isSWA[layer] ? headSizeSWA : headSizeFull;
}
public int numberOfKeyValueHeads(int layer) {
return numberOfKeyValueHeadsPerLayer[layer];
}
public int kvDim(int layer) {
return numberOfKeyValueHeadsPerLayer[layer] * headSize(layer);
}
public int queryDim(int layer) {
return numberOfHeads * headSize(layer);
}
public int maxHiddenDim() {
return Arrays.stream(feedForwardLength).max().orElseThrow();
}
public Configuration withContextLength(int newContextLength) {
return new Configuration(embeddingLength, feedForwardLength, numberOfLayers,
numberOfHeads, numberOfKeyValueHeadsPerLayer, vocabularySize,
newContextLength, rmsNormEps, ropeTheta, ropeThetaSWA,
headSizeFull, headSizeSWA, slidingWindow,
logitSoftcapping, isSWA, nLayerKvFromStart,
embeddingLengthPerLayer,
expertCount, expertUsedCount, expertFeedForwardLength);
}
}
public static final class Weights {
public final FloatTensor token_embedding_table;
public final FloatBuffer[] rms_att_weight; // (layer, dim)
public final FloatTensor[] wq; // (layer, queryDim, dim)
public final FloatTensor[] wk; // (layer, kvDim, dim)
public final FloatTensor[] wv; // (layer, kvDim, dim) - null entry if V=K
public final FloatTensor[] wo; // (layer, dim, queryDim)
public final FloatBuffer[] attn_q_norm; // (layer, headSize)
public final FloatBuffer[] attn_k_norm; // (layer, headSize)
public final FloatBuffer[] post_attention_norm; // (layer, dim)
public final FloatBuffer[] rms_ffn_weight; // (layer, dim) - shared MLP norm
public final FloatTensor[] w1; // ffn_gate (layer, hiddenDim, dim)
public final FloatTensor[] w2; // ffn_down (layer, dim, hiddenDim)
public final FloatTensor[] w3; // ffn_up (layer, hiddenDim, dim)
public final FloatBuffer[] post_ffw_norm; // (layer, dim) - overall post-FFW norm
public final FloatBuffer rms_final_weight;
public final float[] layerOutputScale;
// Full attention RoPE
public final FloatBuffer freq_cis_real_full;
public final FloatBuffer freq_cis_imag_full;
// SWA RoPE
public final FloatBuffer freq_cis_real_swa;
public final FloatBuffer freq_cis_imag_swa;
public final FloatTensor wcls;
// Per-layer embedding weights
public final FloatTensor perLayerTokenEmbd;
public final FloatTensor perLayerModelProj;
public final FloatBuffer perLayerProjNorm;
public final FloatTensor[] perLayerInpGate;
public final FloatTensor[] perLayerProj;
public final FloatBuffer[] perLayerPostNorm;
// MoE weights (null if dense model)
public final FloatTensor[] ffnGateInp; // router weight (layer, n_experts, n_embd)
public final FloatBuffer[] ffnGateInpScale; // router input scale (layer, n_embd)
public final FloatTensor[] ffnGateUpExps; // fused gate+up expert (layer, n_experts * 2*expert_ff, n_embd)
public final FloatTensor[] ffnDownExps; // down expert (layer, n_experts * n_embd, expert_ff)
public final FloatBuffer[] ffnDownExpsScale; // expert output scale (layer, n_experts)
public final FloatBuffer[] ffnPostNorm1; // shared MLP post norm (layer, dim) - MoE only
public final FloatBuffer[] preFfwNorm2; // MoE pre-norm (layer, dim)
public final FloatBuffer[] ffnPostNorm2; // MoE post norm (layer, dim)
public Weights(FloatTensor token_embedding_table,
FloatBuffer[] rms_att_weight,
FloatTensor[] wq, FloatTensor[] wk, FloatTensor[] wv, FloatTensor[] wo,
FloatBuffer[] attn_q_norm, FloatBuffer[] attn_k_norm,
FloatBuffer[] post_attention_norm,
FloatBuffer[] rms_ffn_weight,
FloatTensor[] w1, FloatTensor[] w2, FloatTensor[] w3,
FloatBuffer[] post_ffw_norm,
FloatBuffer rms_final_weight,
float[] layerOutputScale,
FloatBuffer freq_cis_real_full, FloatBuffer freq_cis_imag_full,
FloatBuffer freq_cis_real_swa, FloatBuffer freq_cis_imag_swa,
FloatTensor wcls,
FloatTensor perLayerTokenEmbd, FloatTensor perLayerModelProj,
FloatBuffer perLayerProjNorm,
FloatTensor[] perLayerInpGate, FloatTensor[] perLayerProj,
FloatBuffer[] perLayerPostNorm,
FloatTensor[] ffnGateInp, FloatBuffer[] ffnGateInpScale,
FloatTensor[] ffnGateUpExps, FloatTensor[] ffnDownExps,
FloatBuffer[] ffnDownExpsScale,
FloatBuffer[] ffnPostNorm1, FloatBuffer[] preFfwNorm2,
FloatBuffer[] ffnPostNorm2) {
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.attn_q_norm = attn_q_norm;
this.attn_k_norm = attn_k_norm;
this.post_attention_norm = post_attention_norm;
this.rms_ffn_weight = rms_ffn_weight;
this.w1 = w1;
this.w2 = w2;
this.w3 = w3;
this.post_ffw_norm = post_ffw_norm;
this.rms_final_weight = rms_final_weight;
this.layerOutputScale = layerOutputScale;
this.freq_cis_real_full = freq_cis_real_full;
this.freq_cis_imag_full = freq_cis_imag_full;
this.freq_cis_real_swa = freq_cis_real_swa;
this.freq_cis_imag_swa = freq_cis_imag_swa;
this.wcls = wcls;
this.perLayerTokenEmbd = perLayerTokenEmbd;
this.perLayerModelProj = perLayerModelProj;
this.perLayerProjNorm = perLayerProjNorm;
this.perLayerInpGate = perLayerInpGate;
this.perLayerProj = perLayerProj;
this.perLayerPostNorm = perLayerPostNorm;
this.ffnGateInp = ffnGateInp;
this.ffnGateInpScale = ffnGateInpScale;
this.ffnGateUpExps = ffnGateUpExps;
this.ffnDownExps = ffnDownExps;
this.ffnDownExpsScale = ffnDownExpsScale;
this.ffnPostNorm1 = ffnPostNorm1;
this.preFfwNorm2 = preFfwNorm2;
this.ffnPostNorm2 = ffnPostNorm2;
}
}
public static final class State {
public final FloatTensor x; // activation at current time stamp (embeddingLength,)
public final FloatTensor xb; // same, but inside a residual branch (embeddingLength,)
public final FloatTensor xb_k; // attention output before wo projection (max queryDim,)
public final FloatTensor xb2; // an additional buffer (embeddingLength,)
public final FloatTensor hb; // buffer for hidden dimension in the ffn (maxHiddenDim,)
public final FloatTensor hb2; // buffer for hidden dimension in the ffn (maxHiddenDim,)
public final FloatTensor q; // query (max queryDim,)
public final FloatTensor k; // key (max kvDim,)
public final FloatTensor v; // value (max kvDim,)
public final FloatTensor att; // buffer for scores/attention values (n_heads, seq_len)
public final FloatTensor logits; // output logits
// kv cache - variable sizes per layer
public final FloatTensor[] keyCache; // (n_layer, seq_len, kvDim_per_layer)
public final FloatTensor[] valueCache; // (n_layer, seq_len, kvDim_per_layer)
// per-layer embedding buffers
public final FloatTensor perLayerInputs;
public final FloatTensor plGate;
public final FloatTensor plProj;
// MoE buffers
public final FloatTensor routerLogits; // (n_experts,)
public final FloatTensor moeInput; // (n_embd,) pre-normed MoE input
public final FloatTensor moeOutput; // (n_embd,) accumulated expert output
public final FloatTensor expertGateUp; // (2 * expert_ff,)
public final FloatTensor expertDown; // (n_embd,) single expert output
public int latestToken;
State(Configuration config) {
int maxQueryDim = config.numberOfHeads * config.headSizeFull;
int maxKVDim = IntStream.range(0, config.numberOfLayers).map(config::kvDim).max().orElse(0);
int maxHiddenDim = config.maxHiddenDim();
this.x = ArrayFloatTensor.allocate(config.embeddingLength);
this.xb = ArrayFloatTensor.allocate(config.embeddingLength);
this.xb_k = ArrayFloatTensor.allocate(maxQueryDim);
this.xb2 = ArrayFloatTensor.allocate(config.embeddingLength);
this.hb = ArrayFloatTensor.allocate(maxHiddenDim);
this.hb2 = ArrayFloatTensor.allocate(maxHiddenDim);
this.q = ArrayFloatTensor.allocate(maxQueryDim);
this.k = ArrayFloatTensor.allocate(maxKVDim);
this.v = ArrayFloatTensor.allocate(maxKVDim);
this.att = ArrayFloatTensor.allocate(config.numberOfHeads, config.contextLength);
this.logits = ArrayFloatTensor.allocate(config.vocabularySize);
int plDim = config.embeddingLengthPerLayer;
this.perLayerInputs = plDim > 0 ? ArrayFloatTensor.allocate(plDim * config.numberOfLayers) : null;
this.plGate = plDim > 0 ? ArrayFloatTensor.allocate(plDim) : null;
this.plProj = plDim > 0 ? ArrayFloatTensor.allocate(config.embeddingLength) : null;
// MoE buffers
if (config.isMoE()) {
this.routerLogits = ArrayFloatTensor.allocate(config.expertCount);
this.moeInput = ArrayFloatTensor.allocate(config.embeddingLength);
this.moeOutput = ArrayFloatTensor.allocate(config.embeddingLength);
this.expertGateUp = ArrayFloatTensor.allocate(2 * config.expertFeedForwardLength);
this.expertDown = ArrayFloatTensor.allocate(config.embeddingLength);
} else {
this.routerLogits = null;
this.moeInput = null;
this.moeOutput = null;
this.expertGateUp = null;
this.expertDown = null;
}
// Only allocate KV caches for layers that have their own KV (not shared)
this.keyCache = new FloatTensor[config.nLayerKvFromStart];
this.valueCache = new FloatTensor[config.nLayerKvFromStart];
for (int l = 0; l < config.nLayerKvFromStart; l++) {
int kvDim = config.kvDim(l);
keyCache[l] = ArrayFloatTensor.allocate(config.contextLength, kvDim);
valueCache[l] = ArrayFloatTensor.allocate(config.contextLength, kvDim);
}
}
}
static float gelu(float x) {
return (float) (0.5 * x * (1 + Math.tanh(Math.sqrt(2 / Math.PI) * (x + 0.044715 * Math.pow(x, 3)))));
}
static void rmsnorm(FloatTensor out, FloatTensor x, FloatBuffer weight, int size, float rmsNormEps) {
float ss = x.reduce(0, size, 0f, (acc, xi) -> acc + xi * xi);
ss /= size;
ss += rmsNormEps;
ss = (float) (1.0 / Math.sqrt(ss));
final float finalss = ss;
out.mapWithIndexInPlace(0, size, (value, index) -> weight.get(index) * (finalss * x.getFloat(index)));
}
static void rmsnorm(FloatTensor out, int outOffset, FloatTensor x, int xOffset, FloatBuffer weight, int size, float rmsNormEps) {
float ss = 0f;
for (int i = 0; i < size; i++) {
float xi = x.getFloat(xOffset + i);
ss += xi * xi;
}