Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
## Unreleased

- A negative `ModelParams.gpuLayers` now means all layers on every runtime,
as in llama.cpp, exactly like `ModelParams.maxGpuLayers`. Native llama.cpp
now also offloads the KV cache and reports the GPU backend instead of
`CPU`, LiteRT-LM under `ComputeDevice.auto` uses its GPU backend instead
of the CPU, and the Web applies its GPU safety caps and CPU fallback
([#920](https://github.com/leehack/llamadart/issues/920)).

## 0.13.0

- Pair this release with Apple companions `llamadart_llama_cpp_flutter`,
Expand Down
5 changes: 3 additions & 2 deletions lib/src/backends/litert_lm/litert_lm_backend_web.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import '../../core/models/config/gpu_backend.dart';
import '../../core/models/config/kv_cache_type.dart';
import '../../core/models/config/log_level.dart';
import '../../core/models/inference/generation_params.dart';
import '../../core/models/inference/gpu_layer_count.dart';
import '../../core/models/inference/model_params.dart';
import '../../core/models/model_format.dart';
import '../../core/url_redaction.dart';
Expand Down Expand Up @@ -1267,7 +1268,7 @@ class LiteRtLmBackend
}
return explicit;
}
if (params.gpuLayers <= 0) {
if (resolveGpuLayerCount(params.gpuLayers) == 0) {
return 'cpu';
}
return _backendNameForGpuPreference(params.preferredBackend);
Expand Down Expand Up @@ -1308,7 +1309,7 @@ class LiteRtLmBackend
if (explicit != null) {
return explicit;
}
if (params.gpuLayers <= 0) {
if (resolveGpuLayerCount(params.gpuLayers) == 0) {
return 'cpu';
}
if (params.preferredBackend != GpuBackend.auto) {
Expand Down
5 changes: 3 additions & 2 deletions lib/src/backends/litert_lm/litert_lm_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import '../../core/models/config/gpu_backend.dart';
import '../../core/models/config/kv_cache_type.dart';
import '../../core/models/config/log_level.dart';
import '../../core/models/inference/generation_params.dart';
import '../../core/models/inference/gpu_layer_count.dart';
import '../../core/models/inference/model_params.dart';
import '../../core/models/inference/tool_choice.dart';
import '../../core/models/model_format.dart';
Expand Down Expand Up @@ -1357,7 +1358,7 @@ class LiteRtLmService {
if (explicit != null) {
return explicit;
}
if (params.gpuLayers <= 0) {
if (resolveGpuLayerCount(params.gpuLayers) == 0) {
return liteRtLmCpuBackend;
}
return _backendNameForGpuPreference(params.preferredBackend);
Expand Down Expand Up @@ -1481,7 +1482,7 @@ class LiteRtLmService {
if (explicit != null) {
return explicit;
}
if (params.gpuLayers <= 0) {
if (resolveGpuLayerCount(params.gpuLayers) == 0) {
return liteRtLmCpuBackend;
}
if (params.preferredBackend != GpuBackend.auto) {
Expand Down
8 changes: 6 additions & 2 deletions lib/src/backends/llama_cpp/llama_cpp_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import '../../core/models/config/gpu_device_info.dart';
import '../../core/models/config/log_level.dart';
import '../../core/models/diagnostics/model_file_type.dart';
import '../../core/models/inference/generation_params.dart';
import '../../core/models/inference/gpu_layer_count.dart';
import '../../core/template/media_placeholders.dart';
import '../../core/models/inference/model_params.dart';
import '../../core/models/inference/next_token_scores.dart';
Expand Down Expand Up @@ -857,7 +858,10 @@ class LlamaCppService {

/// Resolves the effective GPU layer count for model loading.
///
/// CPU backend preference always forces zero offloaded layers.
/// CPU backend preference always forces zero offloaded layers, and a
/// negative [ModelParams.gpuLayers] resolves to [ModelParams.maxGpuLayers]:
/// llama.cpp offloads every layer for it, so the context offload, backend
/// name and reported layer count must treat it as a GPU load.
static int resolveGpuLayersForLoad(
ModelParams modelParams, {
bool isAndroid = false,
Expand All @@ -870,7 +874,7 @@ class LlamaCppService {
) ==
GpuBackend.cpu
? 0
: modelParams.gpuLayers;
: resolveGpuLayerCount(modelParams.gpuLayers);
}

/// The warning for a model an iOS simulator loaded with [resolvedGpuLayers]
Expand Down
7 changes: 2 additions & 5 deletions lib/src/backends/webgpu/webgpu_backend.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import '../../core/models/config/llama_cpp_param_values.dart';
import '../../core/models/config/log_level.dart';
import '../../core/models/inference/generation_params.dart';
import '../../core/models/inference/generation_usage.dart';
import '../../core/models/inference/gpu_layer_count.dart';
import '../../core/models/inference/model_params.dart';
import '../../core/models/inference/next_token_scores.dart';
import '../../core/template/media_placeholders.dart';
Expand Down Expand Up @@ -866,10 +867,6 @@ class WebGpuLlamaBackend
return requestedGpuLayers;
}

if (requestedGpuLayers < 0) {
return _qwen35SmallSafeWebGpuLayers;
}

return math.min(requestedGpuLayers, _qwen35SmallSafeWebGpuLayers);
}

Expand Down Expand Up @@ -1129,7 +1126,7 @@ class WebGpuLlamaBackend
params.preferredBackend == GpuBackend.cpu ||
params.device == ComputeDevice.cpu
? 0
: params.gpuLayers;
: resolveGpuLayerCount(params.gpuLayers);

if (requestedGpuLayers > 0 &&
_isSafariBrowser() &&
Expand Down
10 changes: 10 additions & 0 deletions lib/src/core/models/inference/gpu_layer_count.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import 'model_params.dart';

/// The layer count a load offloads for a [ModelParams.gpuLayers] of
/// [gpuLayers].
///
/// A negative value means every layer, as `n_gpu_layers` does in llama.cpp,
/// and resolves to [ModelParams.maxGpuLayers]; any other value is returned
/// unchanged.
int resolveGpuLayerCount(int gpuLayers) =>
gpuLayers < 0 ? ModelParams.maxGpuLayers : gpuLayers;
7 changes: 6 additions & 1 deletion lib/src/core/models/inference/model_params.dart
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@ class ModelParams {
/// `LlamaUnsupportedException`; it never runs elsewhere:
/// - [ComputeDevice.cpu] loads no GPU layers. On llama.cpp it loads only
/// the CPU module, whatever [gpuLayers] and [preferredBackend] say;
/// LiteRT-LM still rejects a [gpuLayers] other than 0 or [maxGpuLayers].
/// LiteRT-LM still rejects a positive [gpuLayers] other than
/// [maxGpuLayers].
/// - [ComputeDevice.gpu] on llama.cpp needs a GPU module and device for
/// [preferredBackend] (Vulkan on Android and Metal on an iOS simulator
/// when it is [GpuBackend.auto]), and on the Web an active WebGPU
Expand All @@ -135,6 +136,10 @@ class ModelParams {
final ComputeDevice device;

/// Number of model layers to offload to the GPU (n_gpu_layers).
///
/// `0` keeps every layer on the CPU. A negative value means all layers, as
/// llama.cpp defines `n_gpu_layers`, and every runtime treats it exactly
/// like [maxGpuLayers].
final int gpuLayers;

/// Preferred GPU backend for inference.
Expand Down
5 changes: 5 additions & 0 deletions test/support/recording_exit_teardown.dart
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ final class RecordingExitTeardown {
/// no devices.
final List<List<int>?> loadDevices = <List<int>?>[];

/// The `llama_model_params.n_gpu_layers` of each
/// `llama_dart_model_load_from_file` so far.
final List<int> loadGpuLayers = <int>[];

/// Token count of the batch of each `llama_dart_decode` so far.
final List<int> decodedTokens = <int>[];

Expand Down Expand Up @@ -140,6 +144,7 @@ final class RecordingExitTeardown {
? null
: [for (var i = 0; devices[i] != nullptr; i++) devices[i].address],
);
loadGpuLayers.add(params.n_gpu_layers);
if (!_proceeds('llama_dart_model_load_from_file')) return nullptr;
final model = real.modelLoadFromFile(path, params);
owned.add(model.address);
Expand Down
43 changes: 43 additions & 0 deletions test/unit/backends/litert_lm/litert_lm_backend_web_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1374,6 +1374,49 @@ void main() {
expect(createdBackends, [2]);
});

for (final (gpuLayers, backend) in const [
(-1, 2),
(-2, 2),
(ModelParams.maxGpuLayers, 2),
(0, 3),
]) {
test('auto with gpuLayers $gpuLayers creates backend $backend', () async {
addTearDown(fakeNavigatorGpu(FakeWebGpu.missing));

await LiteRtLmBackend().modelLoadFromUrl(
url,
ModelParams(gpuLayers: gpuLayers),
);

expect(createdBackends, [backend]);
});
}

test('a context with negative gpuLayers keeps a GPU model', () async {
addTearDown(fakeNavigatorGpu(FakeWebGpu.missing));
final backend = LiteRtLmBackend();
final modelHandle = await backend.modelLoadFromUrl(
url,
const ModelParams(),
);

await backend.contextCreate(
modelHandle,
const ModelParams(gpuLayers: -1),
);
await expectLater(
() =>
backend.contextCreate(modelHandle, const ModelParams(gpuLayers: 0)),
throwsA(
isA<ArgumentError>().having(
(error) => error.message.toString(),
'message',
contains('from gpu to cpu'),
),
),
);
});

test('cpu runs on the CPU', () async {
await LiteRtLmBackend().modelLoadFromUrl(
url,
Expand Down
49 changes: 49 additions & 0 deletions test/unit/backends/litert_lm/litert_lm_service_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1786,6 +1786,55 @@ void main() {
});
});

test('treats negative gpuLayers as every layer, not the CPU', () async {
final service = LiteRtLmService();
final throwsUnavailableGpu = liteRtLmGateAbi() == Abi.macosX64
? throwsA(isA<LlamaUnsupportedException>())
: throwsArgumentError;

try {
for (final gpuLayers in [-1, -2]) {
var modelHandle = await service.loadModel(
modelFile.path,
ModelParams(gpuLayers: gpuLayers),
);
expect(
service.getActiveBackendName(),
'LiteRT-LM ${_expectedAutoLiteRtLmBackend()}',
);
service.freeModel(modelHandle);

final metal = ModelParams(
gpuLayers: gpuLayers,
preferredBackend: GpuBackend.metal,
);
if (service.getAvailableBackendInfo().contains('gpu')) {
modelHandle = await service.loadModel(modelFile.path, metal);
expect(service.getActiveBackendName(), 'LiteRT-LM gpu');
expect(service.getResolvedGpuLayers(), ModelParams.maxGpuLayers);
service.freeModel(modelHandle);
} else {
expect(
() => service.loadModel(modelFile.path, metal),
throwsUnavailableGpu,
);
}

modelHandle = await service.loadModel(
modelFile.path,
const ModelParams(gpuLayers: 0),
);
expect(
() => service.createContext(modelHandle, metal),
anyOf(throwsArgumentError, throwsUnavailableGpu),
);
service.freeModel(modelHandle);
}
} finally {
service.dispose();
}
});

test('rejects explicit backend changes during context creation', () async {
final service = LiteRtLmService();

Expand Down
Loading
Loading