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
|
//!/usr/bin/env -S java -ea -cp /usr/share/java/org.argeo.jjml.jar
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.ERROR;
import static java.lang.System.Logger.Level.INFO;
import static java.lang.System.Logger.Level.WARNING;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.argeo.jjml.llm.LlamaCppContext.defaultContextParams;
import static org.argeo.jjml.llm.LlamaCppModel.defaultModelParams;
import static org.argeo.jjml.llm.LlamaCppSamplers.newJavaSampler;
import static org.argeo.jjml.llm.params.ContextParam.embeddings;
import static org.argeo.jjml.llm.params.ContextParam.kv_unified;
import static org.argeo.jjml.llm.params.ContextParam.n_batch;
import static org.argeo.jjml.llm.params.ContextParam.n_ctx;
import static org.argeo.jjml.llm.params.ContextParam.n_threads;
import static org.argeo.jjml.llm.params.ContextParam.n_ubatch;
import static org.argeo.jjml.llm.util.InstructRole.ASSISTANT;
import static org.argeo.jjml.llm.util.InstructRole.SYSTEM;
import static org.argeo.jjml.llm.util.InstructRole.USER;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.System.Logger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import org.argeo.jjml.llm.LlamaCppBackend;
import org.argeo.jjml.llm.LlamaCppContext;
import org.argeo.jjml.llm.LlamaCppContextState;
import org.argeo.jjml.llm.LlamaCppEmbeddingProcessor;
import org.argeo.jjml.llm.LlamaCppInstructProcessor;
import org.argeo.jjml.llm.LlamaCppJavaSampler;
import org.argeo.jjml.llm.LlamaCppModel;
import org.argeo.jjml.llm.LlamaCppNative;
import org.argeo.jjml.llm.LlamaCppNativeSampler;
import org.argeo.jjml.llm.LlamaCppSamplerChain;
import org.argeo.jjml.llm.LlamaCppSamplers;
import org.argeo.jjml.llm.LlamaCppTextProcessor;
import org.argeo.jjml.llm.LlamaCppVocabulary;
import org.argeo.jjml.llm.params.ContextParams;
import org.argeo.jjml.llm.params.ModelParams;
import org.argeo.jjml.llm.util.SimpleModelDownload;
import org.argeo.jjml.llm.util.SimpleProgressCallback;
/**
* Minimal set of non-destructive in-memory tests, in order to check that a
* given deployment and/or model are working. Java assertions must be enabled.
*/
class JjmlSmokeTests {
private final static Logger logger = System.getLogger(JjmlSmokeTests.class.getName());
private int parallelism = Runtime.getRuntime().availableProcessors();
public void main(List<String> args) throws Exception, AssertionError {
try {
if (!getClass().desiredAssertionStatus()) {
logger.log(ERROR, "Assertions must be enabled. Please call Java with the -ea option.");
return;
}
long begin = System.currentTimeMillis();
// even without a model we can check whether native libraries are loading
assert ((BooleanSupplier) () -> {
LlamaCppNative.ensureLibrariesLoaded();
return true;
}).getAsBoolean();
logger.log(INFO, "Native libraries loaded properly.");
if (args.isEmpty()) {
logger.log(WARNING, "No model was specified, only loading the native libraries was tested");
return;
}
String arg0 = args.get(0);
Path modelPath = Paths.get(arg0);
if (!Files.exists(modelPath))
modelPath = new SimpleModelDownload().getOrDownloadModel(arg0, new SimpleProgressCallback());
if (!Files.exists(modelPath))
throw new IllegalArgumentException("Could not find GGUF model " + modelPath);
ModelParams modelParams = defaultModelParams();
logger.log(INFO, "Loading model " + modelPath + " ...");
Future<LlamaCppModel> loaded = LlamaCppModel.loadAsync(modelPath, modelParams, new SimpleProgressCallback(),
null);
try (LlamaCppModel model = loaded.get();) {
logger.log(INFO, "Model " + model.getDescription());
logger.log(INFO, model.getLayerCount() + " layers");
logger.log(INFO, model.getEmbeddingSize() + " embedding size");
logger.log(INFO, model.getVocabularySize() + " vocabulary size");
logger.log(INFO, model.getContextTrainingSize() + " context training size");
StringBuilder sb = new StringBuilder();
for (String key : model.getMetadata().keySet())
sb.append(key + "=" + model.getMetadata().get(key) + "\n");
logger.log(DEBUG, "Metadata:\n" + sb);
assertVocabulary(model.getVocabulary());
// TODO return if vocabulary only
// if (true)
// return;
assertLoadUnloadDefaultContext(model);
// assertEmbeddings(model);
assertBatch(model);
assertJavaSampler(model);
assertChat(model);
assertSavedContextState(model);
}
logger.log(INFO, "Smoke tests passed in " + (System.currentTimeMillis() - begin) / 1000 + " s with model "
+ modelPath.getFileName());
} catch (Exception | AssertionError e) {
logger.log(ERROR, "Smoke tests failed", e);
throw e;
} finally {
LlamaCppBackend.destroy();
}
}
void assertVocabulary(LlamaCppVocabulary vocabulary) {
int size = 256;
// in direct, out direct
assertVocabulary(vocabulary, //
ByteBuffer.allocateDirect(size), //
ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder()).asIntBuffer());
// in array, out direct
assertVocabulary(vocabulary, //
ByteBuffer.allocate(size), //
ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder()).asIntBuffer());
// in string, out direct
assertVocabulary(vocabulary, //
null, //
ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder()).asIntBuffer());
// in direct, out array
assertVocabulary(vocabulary, //
ByteBuffer.allocateDirect(size), //
IntBuffer.allocate(size / Integer.BYTES));
// in array, out array
assertVocabulary(vocabulary, //
ByteBuffer.allocate(size), //
IntBuffer.allocate(size / Integer.BYTES));
// in string, out array
assertVocabulary(vocabulary, //
null, //
IntBuffer.allocate(size / Integer.BYTES));
}
void assertVocabulary(LlamaCppVocabulary vocabulary, ByteBuffer in, IntBuffer out) {
assert testTokenizeDetokenize(vocabulary, in, out, "Hello World!");
assert testTokenizeDetokenize(vocabulary, in, out, "Même si je suis Français, je dis bonjour au monde");
assert testTokenizeDetokenize(vocabulary, in, out, "ἔορθoι χθόνιοι"); // according to olmoe-1b-7b-0924
assert testTokenizeDetokenize(vocabulary, in, out, "السلام عليكم"); // according to olmoe-1b-7b-0924
assert testTokenizeDetokenize(vocabulary, in, out, "¡Hola и أَشْكَرُ мир! 👋🏼🌍");
logger.log(INFO, "Vocabulary smoke tests variant PASSED");
}
boolean testTokenizeDetokenize(LlamaCppVocabulary vocabulary, ByteBuffer in, IntBuffer buf, String msg) {
if (in != null)
in.clear();
buf.clear();
logger.log(DEBUG, msg);
if (in == null) {
IntBuffer tokens = vocabulary.tokenize(msg);
buf.put(tokens);
} else {
in.put(msg.getBytes(UTF_8));
in.flip();
vocabulary.tokenize(msg, buf);
}
buf.flip();
logger.log(DEBUG, logIntegers(buf, 32, ", "));
String str;
if (in == null) {
str = vocabulary.deTokenize(buf);
} else {
in.clear();
vocabulary.deTokenize(buf, in);
in.flip();
str = UTF_8.decode(in).toString();
}
assert str.equals(msg);
return true;
}
void assertLoadUnloadDefaultContext(LlamaCppModel model) {
try (LlamaCppContext context = new LlamaCppContext(model);) {
assert context.getContextSize() > 0;
}
logger.log(INFO, "Load default context smoke tests PASSED");
}
void assertEmbeddings(LlamaCppModel model) {
int batchSize = 512;
try (LlamaCppContext context = new LlamaCppContext(model, LlamaCppContext.defaultContextParams() //
.with(embeddings, true) //
.with(n_ctx, 6144) //
.with(n_batch, batchSize) //
.with(n_ubatch, batchSize) // must be same for embeddings
.with(kv_unified, true) // required for robustness
);) {
LlamaCppEmbeddingProcessor embeddingProcessor = new LlamaCppEmbeddingProcessor(context);
List<String> prompts = new ArrayList<>();
prompts.add("Hello world!");
prompts.add("Good night and good luck.");
for (String s : prompts)
logger.log(DEBUG, "=>\n" + s);
float[][] embeddings = embeddingProcessor.processEmbeddings(prompts);
assert embeddings.length != 0;
for (float[] embedding : embeddings) {
logger.log(DEBUG, "<=\n[ " + embedding[0] + ", " + embedding[1] + ", ... ]");
}
}
logger.log(INFO, "Embeddings smoke tests PASSED");
}
void assertBatch(LlamaCppModel model) {
String prompt = "Write HELLO\n"//
+ "HELLO\n"//
+ "Write WORLD\n"//
+ "WORLD\n"//
+ "Write TEST\n" //
;
// !! max seq_id must be < 64
// TODO understand why
Integer[] sequenceIds = { 1, 10, 63 };
try ( //
LlamaCppContext context = new LlamaCppContext(model, defaultContextParams() //
.with(n_ctx, 6144) //
.with(n_batch, sequenceIds.length * prompt.length()) //
.with(kv_unified, true) // required for robustness
); //
LlamaCppSamplerChain chain = LlamaCppSamplers.newDefaultSampler(false); //
LlamaCppNativeSampler validatingSampler = LlamaCppSamplers.newSamplerGrammar(model, //
"root ::= [ \\t\\n]* \"TEST\"", "root");//
) {
// long begin = System.currentTimeMillis();
LlamaCppTextProcessor processor = new LlamaCppTextProcessor(context, chain, validatingSampler,
Set.of(sequenceIds));
System.out.println("=>\n" + prompt);
String str = processor.processBatch(prompt);
System.out.println("<=\n" + str);
// System.out.println("\n\n## Processing took " + (System.currentTimeMillis() -
// begin) + " ms");
}
logger.log(INFO, "Batch smoke tests PASSED");
}
void assertJavaSampler(LlamaCppModel model) {
Integer[] sequenceIds = { 1 };
try ( //
LlamaCppContext context = new LlamaCppContext(model, defaultContextParams() //
.with(n_ctx, 6144) //
.with(n_batch, sequenceIds.length * 64) //
.with(kv_unified, true) // required for robustness
); //
LlamaCppSamplerChain chain = new LlamaCppSamplerChain(
newJavaSampler(new LlamaCppJavaSampler.SimpleGreedy())); //
LlamaCppNativeSampler validatingSampler = LlamaCppSamplers.newSamplerGrammar(model, //
"root ::= [ \\t\\n]* \"TEST\"", "root");//
) {
// long begin = System.currentTimeMillis();
LlamaCppTextProcessor processor = new LlamaCppTextProcessor(context, chain, validatingSampler,
Set.of(sequenceIds));
String prompt = "Write HELLO\n"//
+ "Hello\n"//
+ "Write World\n"//
+ "WORLD\n"//
+ "Write test\n" //
;
System.out.println("=>\n" + prompt);
String str = processor.processBatch(prompt);
System.out.println("<=\n" + str);
// System.out.println("\n\n## Processing took " + (System.currentTimeMillis() -
// begin) + " ms");
}
logger.log(INFO, "Java sampler smoke tests PASSED");
}
void assertChat(LlamaCppModel model) throws IOException {
try (//
LlamaCppContext context = new LlamaCppContext(model, defaultContextParams() //
.with(n_ctx, 20480) //
.with(n_batch, 1024) //
.with(n_threads, parallelism) //
); //
LlamaCppSamplerChain chain = LlamaCppSamplers.newDefaultSampler(false); //
) {
LlamaCppInstructProcessor processor = new LlamaCppInstructProcessor(context, chain);
String systemMsg = "You are a helpful assistant, which answers as briefly as possible.";
System.out.println(SYSTEM.name() + " :\n" + systemMsg);
processor.write(SYSTEM, systemMsg);
String userMsg01 = "Introduce the Java programming language in no more than two sentences.";
System.out.println(USER.name() + " :\n" + userMsg01);
processor.write(USER, userMsg01);
System.out.println(ASSISTANT.name() + " :\n");
processor.readMessage(System.out);
// make sure it can deal with a second message
String userMsg02 = "Thank you!";
System.out.println(USER.name() + " :\n" + userMsg02);
processor.write(USER, userMsg02);
System.out.println(ASSISTANT.name() + " :\n");
processor.readMessage(System.out);
}
logger.log(INFO, "Chat smoke tests PASSED");
}
void assertSavedContextState(LlamaCppModel model) throws IOException {
ContextParams contextParams = LlamaCppContext.defaultContextParams() //
.with(n_ctx, 20480) //
.with(n_batch, 1024) //
.with(n_threads, parallelism) //
; //
final LlamaCppContextState savedState;
final Path sessionFile = Files.createTempFile("jjml_session_", ".llama");
Runtime.getRuntime().addShutdownHook(new Thread((Runnable) () -> {
try {
Files.deleteIfExists(sessionFile);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}));
try (//
LlamaCppContext context = new LlamaCppContext(model, contextParams); //
LlamaCppSamplerChain chain = LlamaCppSamplers.newDefaultSampler(false); //
) {
LlamaCppInstructProcessor processor = new LlamaCppInstructProcessor(context, chain);
long begin = System.currentTimeMillis();
String systemMsg = "You are a travel agent helping the user to chose the best holiday destination.\n"
+ "You answer with a city name, and one sentence explanation of your choice, nothing else.";
System.out.println(SYSTEM.name() + " :\n" + systemMsg);
processor.write(SYSTEM, systemMsg);
String userMsg01 = "I want to spend my vacations in Europe.\n"
+ "I like Italy, but I am open to other destinations, as long as there is nature and culture.\n"
+ "I have never been to Scandinavia, but it can wait.\n"
+ "I would like to avoid the usual touristic destinations, so be creative!\n"
+ "I will travel in autumn, so it should not be too hot.\n"
+ "Also please consider that I speak French and German in addition to English.\n"
+ "And I definitely don't like holiday on the beach...";
System.out.println(USER.name() + " :\n" + userMsg01);
processor.write(USER, userMsg01);
savedState = new LlamaCppContextState.ByteBufferSavedState();
logger.log(INFO, "Wrote context in " + (System.currentTimeMillis() - begin) + " ms");
processor.saveContextState(savedState);
long beginSaveContext = System.currentTimeMillis();
logger.log(INFO, "Saved context in " + (System.currentTimeMillis() - beginSaveContext) + " ms");
long beginSaveSessionFile = System.currentTimeMillis();
processor.saveStateFile(sessionFile);
logger.log(INFO, "Saved session file to " + sessionFile + " in "
+ (System.currentTimeMillis() - beginSaveSessionFile) + " ms");
}
String userMsg02 = "Current Date: March 13th 2020.";
Consumer<LlamaCppInstructProcessor> process = (processor) -> {
System.out.println(USER.name() + " :\n" + userMsg02);
processor.write(USER, userMsg02);
System.out.println(ASSISTANT.name() + " :\n");
long begin = System.currentTimeMillis();
try {
processor.readMessage(System.out);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
logger.log(INFO, "Generation took " + +(System.currentTimeMillis() - begin) + " ms");
};
// deterministic answer
try (LlamaCppContext context = new LlamaCppContext(model, contextParams); //
LlamaCppSamplerChain chain = LlamaCppSamplers.newDefaultSampler(false); //
) {
LlamaCppInstructProcessor processor = new LlamaCppInstructProcessor(context, chain);
long beginLoad = System.currentTimeMillis();
processor.loadContextState(savedState);
logger.log(INFO, "Loaded context from memory in " + (System.currentTimeMillis() - beginLoad) + " ms");
process.accept(processor);
}
// with temperature
try (LlamaCppContext context = new LlamaCppContext(model, contextParams); //
LlamaCppSamplerChain chain = LlamaCppSamplers.newDefaultSampler(true); //
) {
LlamaCppInstructProcessor processor = new LlamaCppInstructProcessor(context, chain);
long beginLoad = System.currentTimeMillis();
processor.loadStateFile(sessionFile);
logger.log(INFO, "Loaded context from file in " + (System.currentTimeMillis() - beginLoad) + " ms");
process.accept(processor);
}
logger.log(INFO, "Saved context state smoke tests PASSED");
}
/*
* STATIC UTILITIES
*/
/** CLI entry point. */
public static void main(String[] args) throws Exception {
new JjmlSmokeTests().main(Arrays.asList(args));
}
/** Print required arguments. */
static void printUsage() {
System.err.println("Usage: java " + JjmlSmokeTests.class.getName() + //
".java path/to/model.gguf | hf_repo/model[:quantization]\n" + //
"e.g. java " + JjmlSmokeTests.class.getName() + ".java allenai/OLMo-2-0425-1B-Instruct-GGUF");
}
/**
* Writes the beginning of an integer buffer as a string. It has no side effect
* on the input buffer.
*/
static String logIntegers(IntBuffer in, int max, String separator) {
StringBuilder sb = new StringBuilder();
integers: for (int i = in.position(); i < in.limit(); i++) {
if (i != in.position())
sb.append(separator);
if (i == max) {
sb.append("...");
break integers;
}
sb.append(Integer.toString(in.get(i)));
}
return sb.toString();
}
}
|