|
| 1 | +/* |
| 2 | + * Copyright (C) 2025 Shubham Panchal |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package io.shubham0204.smollm |
| 18 | + |
| 19 | +import kotlinx.coroutines.Dispatchers |
| 20 | +import kotlinx.coroutines.withContext |
| 21 | + |
| 22 | +class GGUFReader { |
| 23 | + companion object { |
| 24 | + init { |
| 25 | + System.loadLibrary("ggufreader") |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + private var nativeHandle: Long = 0L |
| 30 | + |
| 31 | + suspend fun load(modelPath: String) = |
| 32 | + withContext(Dispatchers.IO) { |
| 33 | + nativeHandle = getGGUFContextNativeHandle(modelPath) |
| 34 | + } |
| 35 | + |
| 36 | + fun getContextSize(): Long? { |
| 37 | + assert(nativeHandle != 0L) { "Use GGUFReader.load() to initialize the reader" } |
| 38 | + val contextSize = getContextSize(nativeHandle) |
| 39 | + return if (contextSize == -1L) { |
| 40 | + null |
| 41 | + } else { |
| 42 | + contextSize |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Returns the native handle (pointer to gguf_context created on the native side) |
| 48 | + */ |
| 49 | + private external fun getGGUFContextNativeHandle(modelPath: String): Long |
| 50 | + |
| 51 | + /** |
| 52 | + * Read the context size (in no. of tokens) from the GGUF file, given the native handle |
| 53 | + */ |
| 54 | + private external fun getContextSize(nativeHandle: Long): Long |
| 55 | +} |
0 commit comments