Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Big refactor (#545)

uuuvn71f14a4d2c0a
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 68b03ccbf..90a0e4b51 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -46,7 +46,7 @@ jobs:
- name: Lint with clippy
if: ${{ always() && steps.setup.outcome == 'success' }}
- run: cargo +nightly clippy --workspace --all-targets --features tracing -- -D warnings
+ run: cargo +nightly clippy --workspace --all-targets -- -D warnings
- name: Check that Cargo.lock is consistent with Cargo.toml
if: ${{ always() && steps.setup.outcome == 'success' }}
@@ -65,7 +65,6 @@ jobs:
tests:
name: ${{ matrix.backend }}
${{ matrix.host == 'linux' && ' (linux)' || '' }}
- ${{ matrix.tracing && ' (tracing)' || '' }}
${{ matrix.grammar && ' (grammar)' || '' }}
${{ matrix.target != '' && format(' ({0})', matrix.target) || '' }}
runs-on: ${{ matrix.host == 'linux' && 'ubuntu-latest' || fromJSON('["self-hosted","macos","arm64"]') }}
@@ -75,22 +74,16 @@ jobs:
backend: [ 'cpu', 'metal' ]
host: [ 'macos' ]
target: [ '' ]
- tracing: [ false, true ]
include:
- grammar: true
- backend: 'cpu'
host: 'macos'
target: 'wasm32-wasip1-threads'
- tracing: false
grammar: false
- backend: 'cpu'
host: 'linux'
target: ''
- tracing: false
grammar: false
- exclude:
- - backend: 'cpu'
- tracing: true
env:
CARGO_ENCODED_RUSTFLAGS: "-Dwarnings"
@@ -99,7 +92,6 @@ jobs:
${{ matrix.target != '' && format('--target {0}', matrix.target) || '' }}
${{ matrix.backend != 'cpu' && format('--features {0}', matrix.backend) || '' }}
${{ matrix.grammar && '--features grammar' || '' }}
- ${{ matrix.tracing && '--features tracing' || '' }}
steps:
- uses: actions/checkout@v6
@@ -115,11 +107,11 @@ jobs:
run: cargo +stable build --no-default-features $FEATURE_FLAGS ${{ matrix.target == 'wasm32-wasip1-threads' && '-p uzu' || '' }} ${{ matrix.host == 'linux' && '-p cli --features backend-cpu,capability-cli' || '' }}
- name: Build benches
- if: ${{ matrix.backend != 'cpu' && !matrix.tracing }}
+ if: ${{ matrix.backend != 'cpu' }}
run: cargo +nightly bench --no-run --no-default-features $FEATURE_FLAGS
- name: Run tests
- if: ${{ matrix.backend != 'cpu' && matrix.tracing && matrix.grammar || matrix.backend == 'cpu' && !matrix.tracing && !matrix.grammar && matrix.target == 'wasm32-wasip1-threads' }}
+ if: ${{ matrix.backend != 'cpu' && matrix.grammar || matrix.backend == 'cpu' && !matrix.grammar && matrix.target == 'wasm32-wasip1-threads' }}
run: |
cargo +nightly nextest run --profile=ci --no-default-features $FEATURE_FLAGS \
${{ matrix.target == 'wasm32-wasip1-threads' && '-p backend-uzu backends::common::kernel::tests --lib' || '' }}
diff --git a/CODEOWNERS b/CODEOWNERS
index c296890d2..58fbc36d3 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -11,7 +11,6 @@
/crates/backend-uzu/src/session @uuuvn @LuckyIYI
/crates/backend-uzu/src/parameters @uuuvn
/crates/backend-uzu/src/speculators @uuuvn
-/crates/backend-uzu/src/tracer @uuuvn
/crates/benchmarks @uuuvn
/crates/bindings @alexxale
/crates/cli @alexxale
diff --git a/Cargo.lock b/Cargo.lock
index fc97bb867..71dbee88c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -466,6 +466,7 @@ name = "backend-uzu"
version = "0.5.12"
dependencies = [
"anyhow",
+ "async-stream",
"async-trait",
"bindgen",
"bitflags 2.13.0",
@@ -569,15 +570,6 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"
-[[package]]
-name = "benchmarks"
-version = "0.5.12"
-dependencies = [
- "backend-uzu",
- "serde",
- "sysinfo",
-]
-
[[package]]
name = "binascii"
version = "0.1.4"
@@ -1033,7 +1025,7 @@ name = "cli"
version = "0.5.12"
dependencies = [
"anyhow",
- "benchmarks",
+ "backend-uzu",
"clap",
"comfy-table",
"indicatif",
@@ -1041,6 +1033,8 @@ dependencies = [
"rocket",
"serde",
"serde_json",
+ "shoji",
+ "sysinfo",
"tokio",
"tokio-stream",
"uuid",
@@ -3818,6 +3812,7 @@ dependencies = [
"hanashi",
"indexmap 2.14.0",
"inventory",
+ "keisoku",
"napi",
"napi-build",
"napi-derive",
@@ -3832,7 +3827,6 @@ dependencies = [
"shoji",
"thiserror 2.0.18",
"tokio",
- "tokio-stream",
"tokio-util",
"tracing",
"tsify",
@@ -6201,6 +6195,7 @@ dependencies = [
"serde-wasm-bindgen",
"serde_json",
"thiserror 2.0.18",
+ "tokenizers",
"tokio-util",
"tsify",
"uniffi",
diff --git a/Cargo.toml b/Cargo.toml
index 0aeaea46c..9d152fc37 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,7 +13,6 @@ members = [
"crates/download-manager",
"crates/mock-registry",
"crates/uzu",
- "crates/benchmarks",
"crates/cli",
"crates/cli-storage",
"crates/cli-tools",
@@ -59,7 +58,6 @@ hanashi = { path = "crates/hanashi", default-features = false }
nagare = { path = "crates/nagare", default-features = false }
download-manager = { path = "crates/download-manager", default-features = false }
mock-registry = { path = "crates/mock-registry", default-features = false }
-benchmarks = { path = "crates/benchmarks", default-features = false }
keisoku = { path = "crates/keisoku", default-features = false }
kanka = { path = "crates/kanka", default-features = false }
uzu = { path = "crates/uzu", default-features = false }
@@ -110,6 +108,7 @@ tempfile = "3.24"
clang-ast = "0.1"
rangemap = "1.7.1"
futures = "0.3"
+async-stream = "0.3"
tokio = { version = "1.49", features = ["full"] }
blake3 = "1.8"
quote = "1.0"
diff --git a/bindings/python/uzu/__init__.pyi b/bindings/python/uzu/__init__.pyi
index 765830dc6..a3ef47072 100644
--- a/bindings/python/uzu/__init__.pyi
+++ b/bindings/python/uzu/__init__.pyi
@@ -696,6 +696,8 @@ class EngineConfig:
@property
def lalamo_path(self) -> typing.Optional[builtins.str]: ...
@property
+ def local_path(self) -> typing.Optional[builtins.str]: ...
+ @property
def huggingface_api_key(self) -> typing.Optional[builtins.str]: ...
@property
def openai_api_key(self) -> typing.Optional[builtins.str]: ...
@@ -715,12 +717,13 @@ class EngineConfig:
def allow_lmstudio_usage(self) -> builtins.bool: ...
@property
def download_manager_type(self) -> DownloadManagerType: ...
- def __new__(cls, application_identifier: typing.Optional[builtins.str], mirai_api_key: typing.Optional[builtins.str], lalamo_path: typing.Optional[builtins.str], huggingface_api_key: typing.Optional[builtins.str], openai_api_key: typing.Optional[builtins.str], anthropic_api_key: typing.Optional[builtins.str], gemini_api_key: typing.Optional[builtins.str], xai_api_key: typing.Optional[builtins.str], baseten_api_key: typing.Optional[builtins.str], openrouter_api_key: typing.Optional[builtins.str], allow_ollama_usage: builtins.bool, allow_lmstudio_usage: builtins.bool, download_manager_type: DownloadManagerType) -> EngineConfig: ...
+ def __new__(cls, application_identifier: typing.Optional[builtins.str], mirai_api_key: typing.Optional[builtins.str], lalamo_path: typing.Optional[builtins.str], local_path: typing.Optional[builtins.str], huggingface_api_key: typing.Optional[builtins.str], openai_api_key: typing.Optional[builtins.str], anthropic_api_key: typing.Optional[builtins.str], gemini_api_key: typing.Optional[builtins.str], xai_api_key: typing.Optional[builtins.str], baseten_api_key: typing.Optional[builtins.str], openrouter_api_key: typing.Optional[builtins.str], allow_ollama_usage: builtins.bool, allow_lmstudio_usage: builtins.bool, download_manager_type: DownloadManagerType) -> EngineConfig: ...
@staticmethod
def create() -> EngineConfig: ...
def with_application_identifier(self, application_identifier: builtins.str) -> EngineConfig: ...
def with_mirai_api_key(self, mirai_api_key: builtins.str) -> EngineConfig: ...
def with_lalamo_path(self, lalamo_path: builtins.str) -> EngineConfig: ...
+ def with_local_path(self, local_path: builtins.str) -> EngineConfig: ...
def with_huggingface_api_key(self, huggingface_api_key: builtins.str) -> EngineConfig: ...
def with_openai_api_key(self, openai_api_key: builtins.str) -> EngineConfig: ...
def with_anthropic_api_key(self, anthropic_api_key: builtins.str) -> EngineConfig: ...
diff --git a/bindings/swift/Sources/Uzu/Generated/uzu/nagare.swift b/bindings/swift/Sources/Uzu/Generated/uzu/nagare.swift
index c93e7eb86..ec1537b2d 100644
--- a/bindings/swift/Sources/Uzu/Generated/uzu/nagare.swift
+++ b/bindings/swift/Sources/Uzu/Generated/uzu/nagare.swift
@@ -1250,6 +1250,8 @@ public enum ChatSessionError: Swift.Error, Equatable, Hashable, Codable, Foundat
case Backend(message: String
)
+ case Loading(message: String
+ )
case UnsupportedModel
case UnableToPerformOperationInCurrentState
case NoResponse
@@ -1285,9 +1287,12 @@ public struct FfiConverterTypeChatSessionError: FfiConverterRustBuffer {
case 1: return .Backend(
message: try FfiConverterString.read(from: &buf)
)
- case 2: return .UnsupportedModel
- case 3: return .UnableToPerformOperationInCurrentState
- case 4: return .NoResponse
+ case 2: return .Loading(
+ message: try FfiConverterString.read(from: &buf)
+ )
+ case 3: return .UnsupportedModel
+ case 4: return .UnableToPerformOperationInCurrentState
+ case 5: return .NoResponse
default: throw UniffiInternalError.unexpectedEnumCase
}
@@ -1305,16 +1310,21 @@ public struct FfiConverterTypeChatSessionError: FfiConverterRustBuffer {
FfiConverterString.write(message, into: &buf)
- case .UnsupportedModel:
+ case let .Loading(message):
writeInt(&buf, Int32(2))
+ FfiConverterString.write(message, into: &buf)
+
+
+ case .UnsupportedModel:
+ writeInt(&buf, Int32(3))
case .UnableToPerformOperationInCurrentState:
- writeInt(&buf, Int32(3))
+ writeInt(&buf, Int32(4))
case .NoResponse:
- writeInt(&buf, Int32(4))
+ writeInt(&buf, Int32(5))
}
}
diff --git a/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift b/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift
index da479786f..55a6c64a1 100644
--- a/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift
+++ b/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift
@@ -2249,6 +2249,7 @@ public struct EngineConfig: Equatable, Hashable, Codable {
public var applicationIdentifier: String?
public var miraiApiKey: String?
public var lalamoPath: String?
+ public var localPath: String?
public var huggingfaceApiKey: String?
public var openaiApiKey: String?
public var anthropicApiKey: String?
@@ -2262,10 +2263,11 @@ public struct EngineConfig: Equatable, Hashable, Codable {
// Default memberwise initializers are never public by default, so we
// declare one manually.
- public init(applicationIdentifier: String?, miraiApiKey: String?, lalamoPath: String?, huggingfaceApiKey: String?, openaiApiKey: String?, anthropicApiKey: String?, geminiApiKey: String?, xaiApiKey: String?, basetenApiKey: String?, openrouterApiKey: String?, allowOllamaUsage: Bool, allowLmstudioUsage: Bool, downloadManagerType: DownloadManagerType) {
+ public init(applicationIdentifier: String?, miraiApiKey: String?, lalamoPath: String?, localPath: String?, huggingfaceApiKey: String?, openaiApiKey: String?, anthropicApiKey: String?, geminiApiKey: String?, xaiApiKey: String?, basetenApiKey: String?, openrouterApiKey: String?, allowOllamaUsage: Bool, allowLmstudioUsage: Bool, downloadManagerType: DownloadManagerType) {
self.applicationIdentifier = applicationIdentifier
self.miraiApiKey = miraiApiKey
self.lalamoPath = lalamoPath
+ self.localPath = localPath
self.huggingfaceApiKey = huggingfaceApiKey
self.openaiApiKey = openaiApiKey
self.anthropicApiKey = anthropicApiKey
@@ -2360,6 +2362,15 @@ public func withLalamoPath(lalamoPath: String) -> EngineConfig {
})
}
+public func withLocalPath(localPath: String) -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engineconfig_with_local_path(
+ FfiConverterTypeEngineConfig_lower(self),
+ FfiConverterString.lower(localPath),$0
+ )
+})
+}
+
public func withMiraiApiKey(miraiApiKey: String) -> EngineConfig {
return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
uniffi_uzu_fn_method_engineconfig_with_mirai_api_key(
@@ -2414,6 +2425,7 @@ public struct FfiConverterTypeEngineConfig: FfiConverterRustBuffer {
applicationIdentifier: FfiConverterOptionString.read(from: &buf),
miraiApiKey: FfiConverterOptionString.read(from: &buf),
lalamoPath: FfiConverterOptionString.read(from: &buf),
+ localPath: FfiConverterOptionString.read(from: &buf),
huggingfaceApiKey: FfiConverterOptionString.read(from: &buf),
openaiApiKey: FfiConverterOptionString.read(from: &buf),
anthropicApiKey: FfiConverterOptionString.read(from: &buf),
@@ -2431,6 +2443,7 @@ public struct FfiConverterTypeEngineConfig: FfiConverterRustBuffer {
FfiConverterOptionString.write(value.applicationIdentifier, into: &buf)
FfiConverterOptionString.write(value.miraiApiKey, into: &buf)
FfiConverterOptionString.write(value.lalamoPath, into: &buf)
+ FfiConverterOptionString.write(value.localPath, into: &buf)
FfiConverterOptionString.write(value.huggingfaceApiKey, into: &buf)
FfiConverterOptionString.write(value.openaiApiKey, into: &buf)
FfiConverterOptionString.write(value.anthropicApiKey, into: &buf)
diff --git a/bindings/typescript/src/napi/index.d.mts b/bindings/typescript/src/napi/index.d.mts
index 7d3560f0a..b64ba37ea 100644
--- a/bindings/typescript/src/napi/index.d.mts
+++ b/bindings/typescript/src/napi/index.d.mts
@@ -65,6 +65,7 @@ export declare class TextToSpeechSessionStreamChunkOutput {
export type ChatSessionError =
| { type: 'Backend', message: string }
+ | { type: 'Loading', message: string }
| { type: 'UnsupportedModel' }
| { type: 'UnableToPerformOperationInCurrentState' }
| { type: 'NoResponse' }
@@ -933,6 +934,7 @@ export declare class EngineConfig {
applicationIdentifier?: string
miraiApiKey?: string
lalamoPath?: string
+ localPath?: string
huggingfaceApiKey?: string
openaiApiKey?: string
anthropicApiKey?: string
@@ -943,12 +945,13 @@ export declare class EngineConfig {
allowOllamaUsage: boolean
allowLmstudioUsage: boolean
downloadManagerType: DownloadManagerType
- constructor(applicationIdentifier?: string, miraiApiKey?: string, lalamoPath?: string, huggingfaceApiKey?: string, openaiApiKey?: string, anthropicApiKey?: string, geminiApiKey?: string, xaiApiKey?: string, basetenApiKey?: string, openrouterApiKey?: string, allowOllamaUsage: boolean, allowLmstudioUsage: boolean, downloadManagerType: DownloadManagerType)
+ constructor(applicationIdentifier?: string, miraiApiKey?: string, lalamoPath?: string, localPath?: string, huggingfaceApiKey?: string, openaiApiKey?: string, anthropicApiKey?: string, geminiApiKey?: string, xaiApiKey?: string, basetenApiKey?: string, openrouterApiKey?: string, allowOllamaUsage: boolean, allowLmstudioUsage: boolean, downloadManagerType: DownloadManagerType)
static create(): EngineConfig
withApplicationIdentifier(applicationIdentifier: string): EngineConfig
withMiraiApiKey(miraiApiKey: string): EngineConfig
withLalamoPath(lalamoPath: string): EngineConfig
+ withLocalPath(localPath: string): EngineConfig
withHuggingfaceApiKey(huggingfaceApiKey: string): EngineConfig
withOpenaiApiKey(openaiApiKey: string): EngineConfig
withAnthropicApiKey(anthropicApiKey: string): EngineConfig
diff --git a/bindings/typescript/src/napi/index.d.ts b/bindings/typescript/src/napi/index.d.ts
index 7d3560f0a..b64ba37ea 100644
--- a/bindings/typescript/src/napi/index.d.ts
+++ b/bindings/typescript/src/napi/index.d.ts
@@ -65,6 +65,7 @@ export declare class TextToSpeechSessionStreamChunkOutput {
export type ChatSessionError =
| { type: 'Backend', message: string }
+ | { type: 'Loading', message: string }
| { type: 'UnsupportedModel' }
| { type: 'UnableToPerformOperationInCurrentState' }
| { type: 'NoResponse' }
@@ -933,6 +934,7 @@ export declare class EngineConfig {
applicationIdentifier?: string
miraiApiKey?: string
lalamoPath?: string
+ localPath?: string
huggingfaceApiKey?: string
openaiApiKey?: string
anthropicApiKey?: string
@@ -943,12 +945,13 @@ export declare class EngineConfig {
allowOllamaUsage: boolean
allowLmstudioUsage: boolean
downloadManagerType: DownloadManagerType
- constructor(applicationIdentifier?: string, miraiApiKey?: string, lalamoPath?: string, huggingfaceApiKey?: string, openaiApiKey?: string, anthropicApiKey?: string, geminiApiKey?: string, xaiApiKey?: string, basetenApiKey?: string, openrouterApiKey?: string, allowOllamaUsage: boolean, allowLmstudioUsage: boolean, downloadManagerType: DownloadManagerType)
+ constructor(applicationIdentifier?: string, miraiApiKey?: string, lalamoPath?: string, localPath?: string, huggingfaceApiKey?: string, openaiApiKey?: string, anthropicApiKey?: string, geminiApiKey?: string, xaiApiKey?: string, basetenApiKey?: string, openrouterApiKey?: string, allowOllamaUsage: boolean, allowLmstudioUsage: boolean, downloadManagerType: DownloadManagerType)
static create(): EngineConfig
withApplicationIdentifier(applicationIdentifier: string): EngineConfig
withMiraiApiKey(miraiApiKey: string): EngineConfig
withLalamoPath(lalamoPath: string): EngineConfig
+ withLocalPath(localPath: string): EngineConfig
withHuggingfaceApiKey(huggingfaceApiKey: string): EngineConfig
withOpenaiApiKey(openaiApiKey: string): EngineConfig
withAnthropicApiKey(anthropicApiKey: string): EngineConfig
diff --git a/crates/backend-remote/src/openai/instance.rs b/crates/backend-remote/src/openai/instance.rs
index 3d0c0a56c..d7539481a 100644
--- a/crates/backend-remote/src/openai/instance.rs
+++ b/crates/backend-remote/src/openai/instance.rs
@@ -22,11 +22,7 @@ use crate::openai::{
#[derive(Debug, Clone)]
pub struct State;
-impl StateTrait for State {
- fn clone_boxed(&self) -> Box<dyn StateTrait> {
- Box::new(self.clone())
- }
-}
+impl StateTrait for State {}
pub struct Instance {
client: Arc<Client<OpenAIConfig>>,
@@ -70,4 +66,8 @@ impl InstanceTrait for Instance {
) -> Pin<Box<dyn Stream<Item = Result<Self::StreamOutput, BackendError>> + Send + 'a>> {
self.api_stream.stream(self.client.clone(), self.model_identifier.clone(), config, input.clone(), cancel)
}
+
+ fn peak_memory_usage(&self) -> Option<usize> {
+ None
+ }
}
diff --git a/crates/backend-uzu/Cargo.toml b/crates/backend-uzu/Cargo.toml
index 317123e74..398f9f575 100644
--- a/crates/backend-uzu/Cargo.toml
+++ b/crates/backend-uzu/Cargo.toml
@@ -38,6 +38,7 @@ itertools.workspace = true
schemars.workspace = true
rustix.workspace = true
futures.workspace = true
+async-stream.workspace = true
tokio-util.workspace = true
xgrammar = { workspace = true, optional = true }
@@ -104,7 +105,6 @@ metal = [
"dep:obfstr",
]
grammar = ["dep:xgrammar"]
-tracing = []
[lints]
workspace = true
diff --git a/crates/backend-uzu/benches/session/chat_session_bench.rs b/crates/backend-uzu/benches/session/chat_session_bench.rs
deleted file mode 100644
index fab934d7a..000000000
--- a/crates/backend-uzu/benches/session/chat_session_bench.rs
+++ /dev/null
@@ -1,58 +0,0 @@
-use std::time::Duration;
-
-use backend_uzu::{
- backends::common::Backend,
- session::{
- ChatSession,
- config::{DecodingConfig, RunConfig},
- types::{Input, Output},
- },
-};
-use criterion::{BenchmarkId, Criterion};
-use proc_macros::uzu_bench;
-use test_runner::{for_each_non_cpu_backend, metrics::wait_gpu_cooldown, path::get_test_model_path};
-
-fn create_session<B: Backend>() -> ChatSession {
- let model_path = get_test_model_path();
- let decoding_config = DecodingConfig::default();
- ChatSession::new_with_backend::<B>(model_path, decoding_config).unwrap()
-}
-
-fn run_session(
- session: &mut ChatSession,
- input: Input,
- tokens_limit: u64,
-) -> Duration {
- let run_config = RunConfig {
- tokens_limit,
- ..Default::default()
- };
- let result = session.run_internal(input, run_config, None::<fn(Output) -> bool>).unwrap();
- Duration::from_secs_f64(result.stats.total_stats.duration)
-}
-
-#[uzu_bench]
-fn bench_chat_session(c: &mut Criterion) {
- let message = "How are you?";
- let tokens_limit = 64;
-
- for_each_non_cpu_backend!(|B| {
- wait_gpu_cooldown();
-
- let mut session = create_session::<B>();
- let mut group = c.benchmark_group("ChatSession run");
- group.sample_size(10);
- group.bench_function(BenchmarkId::from_parameter(message), |b| {
- b.iter_custom(|n_iter| {
- let mut total_duration = Duration::from_secs(0);
- for _ in 0..n_iter {
- session.reset().unwrap();
- let duration = run_session(&mut session, Input::Text(message.to_string()), tokens_limit);
- total_duration += duration;
- }
- total_duration
- });
- });
- group.finish();
- });
-}
diff --git a/crates/backend-uzu/benches/session/mod.rs b/crates/backend-uzu/benches/session/mod.rs
index 1e8b0be54..cc67c18c7 100644
--- a/crates/backend-uzu/benches/session/mod.rs
+++ b/crates/backend-uzu/benches/session/mod.rs
@@ -1,2 +1 @@
-mod chat_session_bench;
mod model_loading_bench;
diff --git a/crates/backend-uzu/benches/session/model_loading_bench.rs b/crates/backend-uzu/benches/session/model_loading_bench.rs
index 33c8f72eb..ac3adf5b6 100644
--- a/crates/backend-uzu/benches/session/model_loading_bench.rs
+++ b/crates/backend-uzu/benches/session/model_loading_bench.rs
@@ -1,19 +1,24 @@
use std::time::Duration;
-use backend_uzu::session::{ChatSession, config::DecodingConfig};
+use backend_uzu::engine::Engine;
use criterion::{BenchmarkId, Criterion};
use proc_macros::uzu_bench;
-use test_runner::path::get_test_model_path;
+use test_runner::{for_each_non_cpu_backend, path::get_test_model_path};
#[uzu_bench]
fn bench_model_loading(c: &mut Criterion) {
let mut group = c.benchmark_group("Model loading");
group.sample_size(10);
group.warm_up_time(Duration::from_secs(1));
- group.bench_function(BenchmarkId::from_parameter("test model path"), |b| {
- b.iter(|| {
- let model_path = get_test_model_path();
- let _ = ChatSession::new(model_path, DecodingConfig::default());
+ for_each_non_cpu_backend!(|B| {
+ group.bench_function(BenchmarkId::from_parameter("test model path"), |b| {
+ b.iter(|| {
+ // TODO: Should this reuse engine not measure creation?
+ let model_path = get_test_model_path();
+ let engine = Engine::<B>::new().unwrap();
+ // TODO: This should flush caches (maybe both cold/hot benchmarks?)
+ engine.load_language_model(&model_path).unwrap();
+ });
});
});
}
diff --git a/crates/backend-uzu/build/common/mod.rs b/crates/backend-uzu/build/common/mod.rs
index ba929aa48..f34304136 100644
--- a/crates/backend-uzu/build/common/mod.rs
+++ b/crates/backend-uzu/build/common/mod.rs
@@ -12,4 +12,3 @@ pub mod kernel;
pub mod logging;
pub mod mangling;
pub mod traitgen;
-pub mod utils;
diff --git a/crates/backend-uzu/build/common/traitgen.rs b/crates/backend-uzu/build/common/traitgen.rs
index 2c8146739..a27b4c753 100644
--- a/crates/backend-uzu/build/common/traitgen.rs
+++ b/crates/backend-uzu/build/common/traitgen.rs
@@ -10,7 +10,6 @@ use crate::common::{
codegen::write_tokens,
identifiers::KernelPath,
kernel::{Kernel, KernelArgumentType, KernelBufferAccess, KernelParameterType},
- utils::get_generic_name_stream,
};
pub fn traitgen(kernel: &Kernel) -> (TokenStream, TokenStream) {
@@ -30,30 +29,28 @@ pub fn traitgen(kernel: &Kernel) -> (TokenStream, TokenStream) {
quote! { #name: #ty }
});
- let (encode_lifetime_generics, type_generics, mut args) = kernel
+ let (encode_lifetime_generics, mut args) = kernel
.arguments
.iter()
.map(|a| {
let name = format_ident!("{}", a.name.as_ref());
- let (lifetime_generic, type_generic, mut ty) = match &a.ty {
+ let (lifetime_generic, mut ty) = match &a.ty {
KernelArgumentType::Buffer(access) => {
let buffer_lifetime = Lifetime::new(&format!("'{}", a.name.as_ref()), Span::call_site());
- let buffer_type = get_generic_name_stream(a.name.as_ref());
(
Some(quote! { #buffer_lifetime }),
- Some(quote! { #buffer_type }),
match access {
- KernelBufferAccess::Read => quote! { impl BufferArg<#buffer_lifetime, #buffer_type> },
+ KernelBufferAccess::Read => quote! { impl BufferArg<#buffer_lifetime, Self::Backend> },
KernelBufferAccess::ReadWrite => {
- quote! { impl BufferArgMut<#buffer_lifetime, #buffer_type> }
+ quote! { impl BufferArgMut<#buffer_lifetime, Self::Backend> }
},
},
)
},
KernelArgumentType::Constant(ty) => {
let ty: Type = syn::parse_str(ty.as_ref()).unwrap();
- (None, None, quote! { #ty })
+ (None, quote! { #ty })
},
};
@@ -61,28 +58,14 @@ pub fn traitgen(kernel: &Kernel) -> (TokenStream, TokenStream) {
ty = quote! { Option<#ty> };
}
- (lifetime_generic, type_generic, quote! { #name: #ty })
+ (lifetime_generic, quote! { #name: #ty })
})
- .collect::<(Vec<_>, Vec<_>, Vec<_>)>();
+ .collect::<(Vec<_>, Vec<_>)>();
let mut encode_generics = encode_lifetime_generics.into_iter().flatten().collect::<Vec<_>>();
- let type_generics = type_generics.into_iter().flatten().collect::<Vec<_>>();
- let mut where_generics: Vec<TokenStream> = Vec::new();
-
encode_generics.push(quote! { 'encoder });
args.push(quote! { encoder: &'encoder mut crate::backends::common::Encoder<Self::Backend> });
- type_generics.iter().for_each(|generic| {
- encode_generics.push(quote! { #generic });
- where_generics.push(quote! { #generic: Buffer<Backend = Self::Backend> });
- });
-
- let maybe_where_block = if where_generics.is_empty() {
- quote! {}
- } else {
- quote! { where #(#where_generics),* }
- };
-
let kernel_trait = quote! {
#[allow(clippy::style, clippy::complexity, clippy::perf)]
pub trait #trait_name: Sized {
@@ -91,7 +74,7 @@ pub fn traitgen(kernel: &Kernel) -> (TokenStream, TokenStream) {
#[allow(non_snake_case)]
fn new(context: &<Self::Backend as crate::backends::common::Backend>::Context #(, #params)*) -> Result<Self, <Self::Backend as crate::backends::common::Backend>::Error>;
- fn encode<#(#encode_generics),*>(&self, #(#args),*)#maybe_where_block;
+ fn encode<#(#encode_generics),*>(&self, #(#args),*);
}
};
@@ -128,48 +111,6 @@ pub fn traitgen_all(backends_kernels: Vec<HashMap<KernelPath, Box<[Kernel]>>>) -
}
let kernel_traits = quote! {
- use crate::backends::common::{AsBufferRangeMut, AsBufferRangeRef, Buffer};
-
- pub trait BufferArg<'a, B: Buffer> {
- fn into_parts(self) -> (&'a B, usize, usize);
- }
-
- impl<'a, B: Buffer, T: AsBufferRangeRef<Buffer = B>> BufferArg<'a, B> for &'a T {
- fn into_parts(self) -> (&'a B, usize, usize) {
- let buffer_range = self.as_buffer_range_ref();
- let (buffer, range) = (buffer_range.buffer(), buffer_range.range());
- (buffer, range.start, range.end - range.start)
- }
- }
-
- impl<'a, B: Buffer, T: AsBufferRangeRef<Buffer = B>> BufferArg<'a, B> for (&'a T, usize) {
- fn into_parts(self) -> (&'a B, usize, usize) {
- let buffer_range = self.0.as_buffer_range_ref();
- let (buffer, range) = (buffer_range.buffer(), buffer_range.range());
- (buffer, range.start + self.1, range.end - range.start - self.1)
- }
- }
-
- pub trait BufferArgMut<'a, B: Buffer> {
- fn into_parts(self) -> (&'a B, usize, usize);
- }
-
- impl<'a, B: Buffer, T: AsBufferRangeMut<Buffer = B>> BufferArgMut<'a, B> for &'a mut T {
- fn into_parts(self) -> (&'a B, usize, usize) {
- let buffer_range = self.as_buffer_range_mut();
- let (buffer, range) = (buffer_range.buffer(), buffer_range.range());
- (buffer, range.start, range.end - range.start)
- }
- }
-
- impl<'a, B: Buffer, T: AsBufferRangeMut<Buffer = B>> BufferArgMut<'a, B> for (&'a mut T, usize) {
- fn into_parts(self) -> (&'a B, usize, usize) {
- let buffer_range = self.0.as_buffer_range_mut();
- let (buffer, range) = (buffer_range.buffer(), buffer_range.range());
- (buffer, range.start + self.1, range.end - range.start - self.1)
- }
- }
-
#(#kernel_traits)*
macro_rules! autogen_kernels {
diff --git a/crates/backend-uzu/build/common/utils.rs b/crates/backend-uzu/build/common/utils.rs
deleted file mode 100644
index b9abc7e80..000000000
--- a/crates/backend-uzu/build/common/utils.rs
+++ /dev/null
@@ -1,16 +0,0 @@
-use proc_macro2::TokenStream;
-
-pub fn get_generic_name_stream(var_name: &str) -> TokenStream {
- let mut generic_name: String = var_name
- .split('_')
- .map(|word| {
- let mut chars = word.chars();
- match chars.next() {
- None => String::new(),
- Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
- }
- })
- .collect();
- generic_name.insert(0, 'T');
- generic_name.parse().unwrap()
-}
diff --git a/crates/backend-uzu/build/cpu/compiler.rs b/crates/backend-uzu/build/cpu/compiler.rs
index 40f5b1b65..5fa114203 100644
--- a/crates/backend-uzu/build/cpu/compiler.rs
+++ b/crates/backend-uzu/build/cpu/compiler.rs
@@ -18,7 +18,6 @@ use crate::common::{
gpu_types::GpuTypes,
identifiers::{ArgumentName, KernelName, KernelPath},
kernel::{Kernel, KernelArgument, KernelArgumentType, KernelBufferAccess, KernelParameter, KernelParameterType},
- utils::get_generic_name_stream,
};
#[derive(PartialEq, Debug)]
@@ -362,93 +361,89 @@ impl CpuCompiler {
})
.collect::<anyhow::Result<_>>()?;
- let (encode_lifetimes, buffer_generics, mut encode_args_defs): (Vec<_>, Vec<_>, Vec<_>) = kernel_arguments
- .iter()
- .map(|argument| {
- let argument_ident: Ident = syn::parse_str(argument.name.as_ref()).context("cannot parse ident")?;
-
- let (lifetime, generic, mut ty) = match &argument.ty {
- KernelArgumentType::Buffer(access) => {
- let buffer_lifetime = Lifetime::new(&format!("'{}", argument.name.as_ref()), Span::call_site());
- let buffer_type = get_generic_name_stream(argument.name.as_ref());
- (
- Some(quote! { #buffer_lifetime }),
- Some(quote! { #buffer_type }),
- match access {
- KernelBufferAccess::Read => {
- quote! { impl crate::backends::common::kernel::BufferArg<#buffer_lifetime, #buffer_type> }
- }
- KernelBufferAccess::ReadWrite => {
- quote! { impl crate::backends::common::kernel::BufferArgMut<#buffer_lifetime, #buffer_type> }
- }
- },
- )
- }
- KernelArgumentType::Constant(ty) => {
- let ty: Type = syn::parse_str(ty.as_ref()).context("cannot parse type")?;
- (None, None, quote! { #ty })
- }
- };
-
- if argument.conditional {
- ty = quote! { Option<#ty> };
- }
-
- Ok((lifetime, generic, quote! { #argument_ident: #ty }))
- })
- .collect::<anyhow::Result<_>>()?;
+ let (encode_lifetimes, mut encode_args_defs): (Vec<_>, Vec<_>) = kernel_arguments
+ .iter()
+ .map(|argument| {
+ let argument_ident: Ident = syn::parse_str(argument.name.as_ref()).context("cannot parse ident")?;
+
+ let (lifetime, mut ty) = match &argument.ty {
+ KernelArgumentType::Buffer(access) => {
+ let buffer_lifetime = Lifetime::new(&format!("'{}", argument.name.as_ref()), Span::call_site());
+ (
+ Some(quote! { #buffer_lifetime }),
+ match access {
+ KernelBufferAccess::Read => {
+ quote! { impl crate::backends::common::kernel::BufferArg<#buffer_lifetime, crate::backends::cpu::Cpu> }
+ },
+ KernelBufferAccess::ReadWrite => {
+ quote! { impl crate::backends::common::kernel::BufferArgMut<#buffer_lifetime, crate::backends::cpu::Cpu> }
+ },
+ },
+ )
+ },
+ KernelArgumentType::Constant(ty) => {
+ let ty: Type = syn::parse_str(ty.as_ref()).context("cannot parse type")?;
+ (None, quote! { #ty })
+ },
+ };
+ if argument.conditional {
+ ty = quote! { Option<#ty> };
+ }
+
+ Ok((lifetime, quote! { #argument_ident: #ty }))
+ })
+ .collect::<anyhow::Result<_>>()?;
let mut encode_lifetimes = encode_lifetimes.into_iter().flatten().collect::<Vec<_>>();
- let buffer_generics = buffer_generics.into_iter().flatten().collect::<Vec<_>>();
let argument_copies = function_arguments
- .iter()
- .flat_map(|argument| {
- let argument_ident = &argument.name;
- match &argument.ty {
- FunctionArgumentType::Buffer(access) => {
- let (buffer_ptr, buffer_ptr_wrapper) = match access {
- KernelBufferAccess::Read => (
- quote! { (&*crate::backends::cpu::buffer::BufferDowncastExt::downcast(__dsl_buffer).get()).as_ptr() },
- quote! { crate::utils::pointers::SendPtr }
- ),
- KernelBufferAccess::ReadWrite => (
- quote! { (&mut *crate::backends::cpu::buffer::BufferDowncastExt::downcast(__dsl_buffer).get()).as_mut_ptr() },
- quote! { crate::utils::pointers::SendPtrMut },
- ),
- };
-
- if argument.conditional.is_some() {
- Some(quote! {
+ .iter()
+ .flat_map(|argument| {
+ let argument_ident = &argument.name;
+ match &argument.ty {
+ FunctionArgumentType::Buffer(access) => {
+ let (buffer_ptr, buffer_ptr_wrapper) = match access {
+ KernelBufferAccess::Read => (
+ quote! { (&*__dsl_buffer.downcast().get()).as_ptr() },
+ quote! { crate::utils::pointers::SendPtr },
+ ),
+ KernelBufferAccess::ReadWrite => (
+ quote! { (&mut *__dsl_buffer.downcast().get()).as_mut_ptr() },
+ quote! { crate::utils::pointers::SendPtrMut },
+ ),
+ };
+
+ if argument.conditional.is_some() {
+ Some(quote! {
let #argument_ident = #argument_ident.map(|__dsl_buffer_impl| unsafe {
let (__dsl_buffer, __dsl_offset, _) = __dsl_buffer_impl.into_parts();
#buffer_ptr_wrapper(#buffer_ptr.byte_add(__dsl_offset))
});
})
- } else {
- Some(quote! {
+ } else {
+ Some(quote! {
let #argument_ident = unsafe {
let (__dsl_buffer, __dsl_offset, _) = #argument_ident.into_parts();
#buffer_ptr_wrapper(#buffer_ptr.byte_add(__dsl_offset))
};
})
- }
- }
- FunctionArgumentType::Constant(_, None) => {
- Some(quote! { let #argument_ident = #argument_ident.to_vec().into_boxed_slice(); })
- }
- FunctionArgumentType::Constant(_, Some(_)) => {
- Some(quote! { let #argument_ident = Box::new(*#argument_ident); })
- }
- FunctionArgumentType::Scalar(_) => None,
- FunctionArgumentType::Specialization(_) => {
- Some(quote! { let #argument_ident = self.#argument_ident; })
- }
- }
- })
- .collect::<Vec<_>>();
+ }
+ },
+ FunctionArgumentType::Constant(_, None) => {
+ Some(quote! { let #argument_ident = #argument_ident.to_vec().into_boxed_slice(); })
+ },
+ FunctionArgumentType::Constant(_, Some(_)) => {
+ Some(quote! { let #argument_ident = Box::new(*#argument_ident); })
+ },
+ FunctionArgumentType::Scalar(_) => None,
+ FunctionArgumentType::Specialization(_) => {
+ Some(quote! { let #argument_ident = self.#argument_ident; })
+ },
+ }
+ })
+ .collect::<Vec<_>>();
let make_encode = |generics: TokenStream| -> TokenStream {
let monomorphized_function = if !generics.is_empty() {
@@ -584,22 +579,6 @@ impl CpuCompiler {
encode_args_defs
.push(quote! { encoder: &'encoder mut crate::backends::common::Encoder<crate::backends::cpu::Cpu> });
- let mut encode_generics: Vec<&TokenStream> = Vec::new();
- encode_generics.extend(&encode_lifetimes);
- encode_generics.extend(&buffer_generics);
-
- let where_generics = buffer_generics
- .iter()
- .map(|generic| {
- quote! { #generic: crate::backends::common::Buffer<Backend = crate::backends::cpu::Cpu> }
- })
- .collect::<Vec<_>>();
- let where_block = if where_generics.is_empty() {
- quote! {}
- } else {
- quote! { where #(#where_generics),* }
- };
-
let tokens = quote! {
#[allow(non_snake_case)]
pub struct #struct_ident {
@@ -616,7 +595,7 @@ impl CpuCompiler {
})
}
- fn encode<#(#encode_generics),*>(&self, #(#encode_args_defs),*)#where_block {
+ fn encode<#(#encode_lifetimes),*>(&self, #(#encode_args_defs),*) {
#(#argument_copies)*
#encode_body
}
diff --git a/crates/backend-uzu/build/main.rs b/crates/backend-uzu/build/main.rs
index 64d4ff5b5..564194244 100644
--- a/crates/backend-uzu/build/main.rs
+++ b/crates/backend-uzu/build/main.rs
@@ -53,13 +53,11 @@ async fn main() -> anyhow::Result<()> {
let enum_paths = EnumPaths::from_gpu_types(&gpu_types).context("Failed to build enum path map")?;
- #[allow(unused_mut)]
- let mut compilers: Vec<Box<dyn Compiler>> = vec![Box::new(cpu::CpuCompiler::new()?)];
-
- #[cfg(all(feature = "metal", target_os = "macos"))]
- if metal_backend {
- compilers.push(Box::new(metal::MetalCompiler::new()?));
- }
+ let compilers: Vec<Box<dyn Compiler>> = vec![
+ Box::new(cpu::CpuCompiler::new()?),
+ #[cfg(all(feature = "metal", target_os = "macos"))]
+ Box::new(metal::MetalCompiler::new()?),
+ ];
let backends_kernels = try_join_all(compilers.iter().map(|c| c.build(&gpu_types, &enum_paths))).await?;
diff --git a/crates/backend-uzu/build/metal/bindgen/arguments.rs b/crates/backend-uzu/build/metal/bindgen/arguments.rs
index 8015425c5..985f2ab01 100644
--- a/crates/backend-uzu/build/metal/bindgen/arguments.rs
+++ b/crates/backend-uzu/build/metal/bindgen/arguments.rs
@@ -13,7 +13,7 @@ use super::{
},
variant_path_rewriter::VariantPathRewriter,
};
-use crate::common::{enum_paths::EnumPaths, utils::get_generic_name_stream};
+use crate::common::enum_paths::EnumPaths;
pub enum ArgumentEmission {
Buffer(BufferArgument),
@@ -220,7 +220,7 @@ impl ArgumentEmission {
ArgumentEmission::Shared(_) => None,
ArgumentEmission::IndirectDispatch(_) => Some(quote! {
__dsl_indirect_dispatch_buffer: impl crate::backends::common::kernel::BufferArg<
- '__dsl_indirect_dispatch_buffer, TDslIndirectDispatchBuffer
+ '__dsl_indirect_dispatch_buffer, crate::backends::metal::Metal
>
}),
}
@@ -278,30 +278,6 @@ impl ArgumentEmission {
}
}
- pub fn encode_generic(&self) -> Option<TokenStream> {
- match self {
- ArgumentEmission::Buffer(buffer_arg) => {
- let buffer_type = get_generic_name_stream(buffer_arg.name.to_string().as_ref());
- Some(quote! { #buffer_type })
- },
- ArgumentEmission::Constant(_) | ArgumentEmission::Shared(_) => None,
- ArgumentEmission::IndirectDispatch(_) => Some(quote! { TDslIndirectDispatchBuffer }),
- }
- }
-
- pub fn encode_where_generic(&self) -> Option<TokenStream> {
- match self {
- ArgumentEmission::Buffer(buffer_arg) => {
- let buffer_type = get_generic_name_stream(buffer_arg.name.to_string().as_ref());
- Some(quote! { #buffer_type: crate::backends::common::Buffer<Backend = crate::backends::metal::Metal> })
- },
- ArgumentEmission::Constant(_) | ArgumentEmission::Shared(_) => None,
- ArgumentEmission::IndirectDispatch(_) => Some(
- quote! { TDslIndirectDispatchBuffer: crate::backends::common::Buffer<Backend = crate::backends::metal::Metal> },
- ),
- }
- }
-
fn condition(&self) -> Option<&ArgumentCondition> {
match self {
ArgumentEmission::Buffer(buffer) => buffer.condition.as_ref(),
@@ -319,8 +295,7 @@ fn emit_buffer_argument_definition(buffer: &BufferArgument) -> TokenStream {
MetalBufferAccess::Read => quote! { crate::backends::common::kernel::BufferArg },
MetalBufferAccess::ReadWrite => quote! { crate::backends::common::kernel::BufferArgMut },
};
- let buffer_type = get_generic_name_stream(name.to_string().as_ref());
- let buffer_argument_type = quote! { impl #trait_path<#lifetime, #buffer_type> };
+ let buffer_argument_type = quote! { impl #trait_path<#lifetime, crate::backends::metal::Metal> };
if buffer.condition.is_some() {
quote! { #name: Option<#buffer_argument_type> }
} else {
@@ -370,7 +345,7 @@ fn emit_buffer_set(buffer: &BufferArgument) -> TokenStream {
let name = &buffer.name;
let buffer_index = buffer.buffer_index;
let unconditional_set = quote! {
- compute_encoder.set_buffer(Some(crate::backends::metal::buffer::BufferDowncastExt::downcast(#name.0)), #name.1, #buffer_index);
+ compute_encoder.set_buffer(Some(#name.0.downcast()), #name.1, #buffer_index);
};
match &buffer.condition {
Some(condition) => {
diff --git a/crates/backend-uzu/build/metal/bindgen/dispatch.rs b/crates/backend-uzu/build/metal/bindgen/dispatch.rs
index 20310f384..594cd7124 100644
--- a/crates/backend-uzu/build/metal/bindgen/dispatch.rs
+++ b/crates/backend-uzu/build/metal/bindgen/dispatch.rs
@@ -85,7 +85,7 @@ fn build_indirect_dispatch(
let dispatch_code = quote! {
compute_encoder.dispatch_threadgroups_indirect(
- crate::backends::metal::buffer::BufferDowncastExt::downcast(__dsl_indirect_dispatch_buffer.0),
+ __dsl_indirect_dispatch_buffer.0.downcast(),
__dsl_indirect_dispatch_buffer.1,
MTLSize::new(#((#threads) as usize, )*),
);
diff --git a/crates/backend-uzu/build/metal/bindgen/mod.rs b/crates/backend-uzu/build/metal/bindgen/mod.rs
index 7345cd6be..5c0b72e55 100644
--- a/crates/backend-uzu/build/metal/bindgen/mod.rs
+++ b/crates/backend-uzu/build/metal/bindgen/mod.rs
@@ -44,10 +44,6 @@ pub fn bindgen(
argument_emissions.iter().filter_map(|argument| argument.encode_deconstruct()).collect();
let encode_set_calls: Vec<TokenStream> = argument_emissions.iter().map(|argument| argument.encode_set()).collect();
let encode_accesses_call = arguments::encode_accesses_call(&argument_emissions);
- let encode_generics: Vec<TokenStream> =
- argument_emissions.iter().filter_map(|argument| argument.encode_generic()).collect();
- let encode_where_generics: Vec<TokenStream> =
- argument_emissions.iter().filter_map(|argument| argument.encode_where_generic()).collect();
let variant_struct_fields: Vec<TokenStream> =
variant_binds.iter().filter_map(|variant| variant.struct_field(&referenced_parameter_names)).collect();
@@ -75,12 +71,6 @@ pub fn bindgen(
encoder: &'encoder mut crate::backends::common::Encoder<crate::backends::metal::Metal>
});
- let encode_where_block = if encode_where_generics.is_empty() {
- quote! {}
- } else {
- quote! { where #(#encode_where_generics),* }
- };
-
let kernel_tokens = quote! {
pub struct #struct_name {
pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
@@ -103,10 +93,10 @@ pub fn bindgen(
Ok(Self { pipeline #(, #conditional_buffer_initializers)* #(, #variant_struct_initializers)* })
}
- #method_visibility fn encode<#(#encode_lifetimes,)*#(#encode_generics),*>(
+ #method_visibility fn encode<#(#encode_lifetimes),*>(
&self,
#(#encode_argument_definitions),*
- )#encode_where_block {
+ ) {
#empty_dispatch_guards
#(#encode_deconstructs)*
#encode_accesses_call
diff --git a/crates/backend-uzu/src/array/array.rs b/crates/backend-uzu/src/array/array.rs
deleted file mode 100644
index e31223d58..000000000
--- a/crates/backend-uzu/src/array/array.rs
+++ /dev/null
@@ -1,99 +0,0 @@
-use std::fmt;
-
-use crate::{
- array::size_for_shape,
- backends::common::{
- Allocation, AsBufferRangeMut, AsBufferRangeRef, Backend, Buffer, BufferRangeMut, BufferRangeRef,
- },
- data_type::DataType,
-};
-
-pub struct Array<B: Backend, BufferRange: AsBufferRangeMut<Buffer: Buffer<Backend = B>> = Allocation<B>> {
- pub(super) buffer_range: BufferRange,
- pub(super) offset: usize,
- pub(super) shape: Box<[usize]>,
- pub(super) data_type: DataType,
-}
-
-impl<B: Backend, BufferRange: AsBufferRangeMut<Buffer: Buffer<Backend = B>>> Array<B, BufferRange> {
- pub fn offset(&self) -> usize {
- self.offset
- }
-
- pub fn shape(&self) -> &[usize] {
- &self.shape
- }
-
- pub fn data_type(&self) -> DataType {
- self.data_type
- }
-
- pub fn size(&self) -> usize {
- size_for_shape(&self.shape, self.data_type)
- }
-
- pub fn num_elements(&self) -> usize {
- self.shape.iter().product()
- }
-
- pub fn as_buffer_range_ref<'a>(&'a self) -> BufferRangeRef<'a, BufferRange::Buffer> {
- self.buffer_range.as_buffer_range_ref().subrange(self.offset..self.offset + self.size())
- }
-
- pub fn as_buffer_range_mut<'a>(&'a mut self) -> BufferRangeMut<'a, BufferRange::Buffer> {
- let offset = self.offset;
- let size = self.size();
- self.buffer_range.as_buffer_range_mut().subrange(offset..offset + size)
- }
-}
-
-impl<B: Backend> Array<B, Allocation<B>> {
- pub unsafe fn from_allocation(
- allocation: Allocation<B>,
- offset: usize,
- shape: &[usize],
- data_type: DataType,
- ) -> Self {
- let required_bytes = size_for_shape(shape, data_type);
- let allocation_size = allocation.as_buffer_range_ref().range().len();
- assert!(offset + required_bytes <= allocation_size, "Array shape exceeds allocation length",);
- Self {
- buffer_range: allocation,
- offset,
- shape: shape.into(),
- data_type,
- }
- }
-
- pub fn allocation(&self) -> &Allocation<B> {
- &self.buffer_range
- }
-
- pub fn allocation_mut(&mut self) -> &mut Allocation<B> {
- &mut self.buffer_range
- }
-
- pub fn into_allocation(self) -> Allocation<B> {
- assert_eq!(self.offset, 0, "Array view cannot be converted into Allocation");
- assert_eq!(
- size_for_shape(&self.shape, self.data_type),
- self.buffer_range.as_buffer_range_ref().range().len(),
- "Partial Array view cannot be converted into Allocation",
- );
- self.buffer_range
- }
-}
-
-impl<B: Backend, BufferRange: AsBufferRangeMut<Buffer: Buffer<Backend = B>>> fmt::Debug for Array<B, BufferRange> {
- fn fmt(
- &self,
- formatter: &mut fmt::Formatter<'_>,
- ) -> fmt::Result {
- formatter
- .debug_struct("Array")
- .field("offset", &self.offset)
- .field("shape", &self.shape)
- .field("data_type", &self.data_type)
- .finish()
- }
-}
diff --git a/crates/backend-uzu/src/array/context_ext.rs b/crates/backend-uzu/src/array/context_ext.rs
deleted file mode 100644
index dffb97973..000000000
--- a/crates/backend-uzu/src/array/context_ext.rs
+++ /dev/null
@@ -1,48 +0,0 @@
-use crate::{
- array::{Array, ArrayElement, size_for_shape},
- backends::common::{AllocationType, Context},
- data_type::DataType,
-};
-
-pub trait ArrayContextExt: Context {
- fn create_array_uninitialized(
- &self,
- shape: &[usize],
- data_type: DataType,
- ) -> Array<Self::Backend> {
- let size = size_for_shape(shape, data_type);
- let allocation = self.create_allocation(size, AllocationType::Global).expect("Failed to create allocation");
- unsafe { Array::from_allocation(allocation, 0, shape, data_type) }
- }
-
- fn create_array_zeros(
- &self,
- shape: &[usize],
- data_type: DataType,
- ) -> Array<Self::Backend> {
- let mut array = self.create_array_uninitialized(shape, data_type);
- array.as_bytes_mut().fill(0);
- array
- }
-
- fn create_array_from<T: ArrayElement>(
- &self,
- shape: &[usize],
- data: &[T],
- ) -> Array<Self::Backend> {
- let size_from_shape: usize = shape.iter().product();
- assert_eq!(
- data.len(),
- size_from_shape,
- "Shape size {} and data size {} are not equal",
- size_from_shape,
- data.len()
- );
-
- let mut array = self.create_array_uninitialized(shape, T::data_type());
- array.as_slice_mut().copy_from_slice(data);
- array
- }
-}
-
-impl<C: Context> ArrayContextExt for C {}
diff --git a/crates/backend-uzu/src/array/dense.rs b/crates/backend-uzu/src/array/dense.rs
deleted file mode 100644
index 11c3585d8..000000000
--- a/crates/backend-uzu/src/array/dense.rs
+++ /dev/null
@@ -1,72 +0,0 @@
-use std::{os::raw::c_void, ptr::NonNull};
-
-use ndarray::{ArrayView, Dimension, IxDyn};
-
-use crate::{
- array::{Array, ArrayElement},
- backends::common::{AsBufferRangeMut, Backend, DenseBuffer},
-};
-
-impl<B: Backend, BufferRange: AsBufferRangeMut<Buffer: DenseBuffer<Backend = B>>> Array<B, BufferRange> {
- pub fn cpu_ptr(&self) -> NonNull<c_void> {
- let buffer_range = self.as_buffer_range_ref();
- let range = buffer_range.range();
- unsafe { buffer_range.buffer().cpu_ptr().add(range.start) }
- }
-
- pub fn as_bytes(&self) -> &[u8] {
- unsafe { std::slice::from_raw_parts(self.cpu_ptr().as_ptr() as *const u8, self.size()) }
- }
-
- pub fn as_bytes_mut(&mut self) -> &mut [u8] {
- let size = self.size();
- let buffer_range = self.as_buffer_range_mut();
- let range = buffer_range.range();
- unsafe {
- std::slice::from_raw_parts_mut((buffer_range.buffer().cpu_ptr().as_ptr() as *mut u8).add(range.start), size)
- }
- }
-
- pub fn as_slice<T: ArrayElement>(&self) -> &[T] {
- self.validate_element_type::<T>();
- bytemuck::cast_slice(self.as_bytes())
- }
-
- pub fn as_slice_mut<T: ArrayElement>(&mut self) -> &mut [T] {
- self.validate_element_type::<T>();
- bytemuck::cast_slice_mut(self.as_bytes_mut())
- }
-
- pub fn as_view<T: ArrayElement>(&self) -> ArrayView<'_, T, IxDyn> {
- ArrayView::from_shape(IxDyn(self.shape()), self.as_slice::<T>()).expect("Failed to create array view")
- }
-
- pub fn copy_from_view<T: ArrayElement, D: Dimension>(
- &mut self,
- view: ArrayView<T, D>,
- ) {
- assert_eq!(self.data_type(), T::data_type());
-
- let destination_slice = self.as_slice_mut::<T>();
-
- if let Some(source_slice) = view.as_slice_memory_order() {
- assert!(source_slice.len() <= destination_slice.len());
- destination_slice[..source_slice.len()].copy_from_slice(source_slice);
- } else {
- assert!(view.len() <= destination_slice.len());
- for (destination, source) in destination_slice.iter_mut().zip(view.iter()) {
- *destination = *source;
- }
- }
- }
-
- fn validate_element_type<T: ArrayElement>(&self) {
- assert_eq!(
- T::data_type(),
- self.data_type(),
- "Invalid data type, expected {:?}, actual {:?}",
- T::data_type(),
- self.data_type()
- );
- }
-}
diff --git a/crates/backend-uzu/src/array/element.rs b/crates/backend-uzu/src/array/element.rs
index e6ff85670..2d59b779a 100644
--- a/crates/backend-uzu/src/array/element.rs
+++ b/crates/backend-uzu/src/array/element.rs
@@ -2,9 +2,13 @@ use bytemuck::Pod;
use half::{bf16, f16};
use num_traits::NumCast;
+#[cfg(test)]
use crate::data_type::DataType;
+// TODO: remove this
+
pub trait ArrayElement: NumCast + Pod {
+ #[cfg(test)]
fn data_type() -> DataType;
}
@@ -12,6 +16,7 @@ macro_rules! impl_array_element {
($($type:ty => $variant:ident),+ $(,)?) => {
$(
impl ArrayElement for $type {
+ #[cfg(test)]
fn data_type() -> DataType {
DataType::$variant
}
diff --git a/crates/backend-uzu/src/array/mod.rs b/crates/backend-uzu/src/array/mod.rs
index 7a17fdbef..683c7be7a 100644
--- a/crates/backend-uzu/src/array/mod.rs
+++ b/crates/backend-uzu/src/array/mod.rs
@@ -1,10 +1,5 @@
-mod array;
-mod context_ext;
-mod dense;
mod element;
mod util;
-pub use array::Array;
-pub use context_ext::ArrayContextExt;
pub use element::ArrayElement;
pub use util::size_for_shape;
diff --git a/crates/backend-uzu/src/audio/codec.rs b/crates/backend-uzu/src/audio/codec.rs
deleted file mode 100644
index b37497e7b..000000000
--- a/crates/backend-uzu/src/audio/codec.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-use super::{AudioPcmBatch, AudioResult, AudioTokenGrid};
-
-pub trait AudioCodecRuntime {
- #[cfg(test)]
- fn encode(
- &self,
- pcm: &AudioPcmBatch,
- ) -> AudioResult<AudioTokenGrid>;
-
- fn decode(
- &self,
- tokens: &AudioTokenGrid,
- ) -> AudioResult<AudioPcmBatch>;
-}
diff --git a/crates/backend-uzu/src/audio/context.rs b/crates/backend-uzu/src/audio/context.rs
deleted file mode 100644
index bb222682a..000000000
--- a/crates/backend-uzu/src/audio/context.rs
+++ /dev/null
@@ -1,48 +0,0 @@
-use std::{path::Path, rc::Rc};
-
-use super::{AudioResult, NanoCodecFsqRuntime};
-use crate::{backends::common::Backend, config::tts::TTSConfig};
-
-#[derive(Clone)]
-pub struct AudioGenerationContext<B: Backend> {
- runtime: Rc<NanoCodecFsqRuntime<B>>,
- codec_cardinality: usize,
- num_codebooks: usize,
- sample_rate: u32,
-}
-
-impl<B: Backend> AudioGenerationContext<B> {
- pub fn from_tts_config_and_model_path(
- tts_config: &TTSConfig,
- model_path: &Path,
- ) -> AudioResult<Self> {
- Self::with_runtime(NanoCodecFsqRuntime::from_tts_config_and_model_path(tts_config, model_path)?)
- }
-
- fn with_runtime(runtime: NanoCodecFsqRuntime<B>) -> AudioResult<Self> {
- let codec_cardinality = usize::try_from(runtime.config().codec_cardinality())
- .map_err(|_| super::AudioError::Runtime("audio codec cardinality exceeds usize".to_string()))?;
- Ok(Self {
- codec_cardinality,
- num_codebooks: runtime.config().num_groups(),
- sample_rate: runtime.config().sample_rate(),
- runtime: Rc::new(runtime),
- })
- }
-
- pub fn runtime(&self) -> &NanoCodecFsqRuntime<B> {
- self.runtime.as_ref()
- }
-
- pub fn codec_cardinality(&self) -> usize {
- self.codec_cardinality
- }
-
- pub fn num_codebooks(&self) -> usize {
- self.num_codebooks
- }
-
- pub fn sample_rate(&self) -> u32 {
- self.sample_rate
- }
-}
diff --git a/crates/backend-uzu/src/audio/mod.rs b/crates/backend-uzu/src/audio/mod.rs
deleted file mode 100644
index 8faa3c41e..000000000
--- a/crates/backend-uzu/src/audio/mod.rs
+++ /dev/null
@@ -1,18 +0,0 @@
-#[cfg(metal_backend)]
-mod codec;
-#[cfg(metal_backend)]
-mod context;
-pub mod nanocodec;
-mod types;
-
-#[cfg(metal_backend)]
-pub use codec::AudioCodecRuntime;
-#[cfg(metal_backend)]
-pub use context::AudioGenerationContext;
-#[cfg(metal_backend)]
-pub use nanocodec::NanoCodecFsqRuntime;
-#[cfg(all(metal_backend, test))]
-pub use nanocodec::NanoCodecFsqRuntimeConfig;
-pub use types::AudioError;
-#[cfg(metal_backend)]
-pub use types::{AudioPcmBatch, AudioResult, AudioTokenGrid};
diff --git a/crates/backend-uzu/src/audio/nanocodec/mod.rs b/crates/backend-uzu/src/audio/nanocodec/mod.rs
deleted file mode 100644
index fc747aecd..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/mod.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-#[cfg(metal_backend)]
-pub mod runtime;
-
-#[cfg(all(metal_backend, test))]
-pub use runtime::NanoCodecFsqRuntimeConfig;
-#[cfg(metal_backend)]
-pub use runtime::{AudioDecodeStepStats, AudioDecodeStreamState, NanoCodecFsqRuntime};
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime.rs b/crates/backend-uzu/src/audio/nanocodec/runtime.rs
deleted file mode 100644
index 2095c1bbf..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/runtime.rs
+++ /dev/null
@@ -1,778 +0,0 @@
-use std::{
- cell::RefCell,
- collections::{BTreeMap, HashMap},
- fs::File,
- path::Path,
- rc::Rc,
-};
-
-use serde::Deserialize;
-
-#[cfg(test)]
-use crate::backends::common::kernel::AudioFsqEncodeKernel;
-use crate::{
- array::{ArrayContextExt, size_for_shape},
- audio::{AudioCodecRuntime, AudioError, AudioPcmBatch, AudioResult, AudioTokenGrid},
- backends::common::{
- Backend, Context, Encoder, Kernels, Pending,
- kernel::{
- ActivationKernel, AudioAddKernel, AudioCausalConv1dGroupedKernel, AudioCausalConv1dGroupedResidualKernel,
- AudioCausalConv1dKernel, AudioCausalConvTranspose1dCausalPadKernel, AudioConv1dKernel,
- AudioFsqDecodeKernel, AudioHalfSnakeKernel, AudioNormNcsKernel, AudioQuantizerDecodeKernel,
- },
- },
- config::{
- decoder::DecoderConfig,
- embedding::{AnyEmbeddingConfig, untied_embedding::UntiedEmbeddingConfig},
- normalization::NormalizationConfig,
- rope::AnyRoPEConfig,
- tts::{
- TTSConfig,
- audio_decoder::{AnyTTSAudioDecoderConfig, descript_audio_codec::DescriptAudioCodecConfig},
- },
- },
- data_type::DataType,
- encodable_block::{Decoder, LayerExecutables, RMSNorm},
- forward_pass::model_shape::ModelShape,
- parameters::ParameterLoader,
-};
-
-mod loaders;
-mod profile;
-mod stream;
-mod structured;
-mod support;
-
-use loaders::load_audio_runtime_from_tts_config;
-pub(crate) use profile::PendingStreamPcmChunk;
-#[cfg(test)]
-use stream::pack_pcm_to_padded;
-pub use stream::{AudioDecodeStepStats, AudioDecodeStreamState};
-use stream::{extract_delta_from_padded_with_offset_snapshot, unpack_padded_to_pcm};
-use structured::{StructuredAudioCodecGraph, StructuredAudioRuntimeResources};
-use support::{DecodedPaddedAudio, checked_product, convert_lengths_to_i32, usize_to_i32};
-
-fn default_eps() -> f32 {
- 1e-3
-}
-
-fn compute_dim_base_index(num_levels: &[i32]) -> AudioResult<Box<[i32]>> {
- if num_levels.is_empty() {
- return Err(AudioError::InvalidTokenCardinality);
- }
-
- let mut out = vec![0_i32; num_levels.len()];
- let mut base = 1_i32;
-
- for (index, &levels) in num_levels.iter().enumerate() {
- if levels <= 1 {
- return Err(AudioError::InvalidTokenCardinality);
- }
- out[index] = base;
- base = base.checked_mul(levels).ok_or(AudioError::Runtime("dim_base_index overflow".to_string()))?;
- }
-
- Ok(out.into_boxed_slice())
-}
-
-#[derive(Debug, Clone, Deserialize)]
-#[serde(deny_unknown_fields)]
-struct RuntimeConfigJson {
- sample_rate: u32,
- num_groups: usize,
- num_levels_per_group: Vec<i32>,
- #[serde(default = "default_eps")]
- eps: f32,
-}
-
-#[derive(Debug, Clone, PartialEq)]
-pub struct NanoCodecFsqRuntimeConfig {
- sample_rate: u32,
- num_groups: usize,
- num_levels_per_group: Box<[i32]>,
- dim_base_index: Box<[i32]>,
- codebook_dim_per_group: usize,
- channels: usize,
- codec_cardinality: u32,
- eps: f32,
- structured_decoder: Option<StructuredAudioCodecGraph>,
-}
-
-impl NanoCodecFsqRuntimeConfig {
- pub fn from_tts_config_and_model_path(
- tts_config: &TTSConfig,
- model_path: &Path,
- ) -> AudioResult<Self> {
- let (runtime_config, decoder) = load_audio_runtime_from_tts_config(tts_config, model_path)?;
- let mut runtime = Self::from_runtime_config_json(runtime_config)?;
- runtime.structured_decoder = Some(decoder);
- Ok(runtime)
- }
-
- fn from_runtime_config_json(parsed: RuntimeConfigJson) -> AudioResult<Self> {
- Self::new(parsed.sample_rate, parsed.num_groups, parsed.num_levels_per_group.into_boxed_slice(), parsed.eps)
- }
-
- pub fn new(
- sample_rate: u32,
- num_groups: usize,
- num_levels_per_group: Box<[i32]>,
- eps: f32,
- ) -> AudioResult<Self> {
- if sample_rate == 0 {
- return Err(AudioError::InvalidSampleRate);
- }
- if num_groups == 0 || num_levels_per_group.is_empty() {
- return Err(AudioError::InvalidTokenCardinality);
- }
- if !eps.is_finite() || !(0.0..1.0).contains(&eps) {
- return Err(AudioError::Runtime("eps must be finite and satisfy 0.0 <= eps < 1.0".to_string()));
- }
- for &level in num_levels_per_group.iter() {
- if level <= 1 {
- return Err(AudioError::InvalidTokenCardinality);
- }
- }
-
- let codebook_dim_per_group = num_levels_per_group.len();
- let channels = num_groups
- .checked_mul(codebook_dim_per_group)
- .ok_or(AudioError::Runtime("num_groups * codebook_dim_per_group overflow".to_string()))?;
- let dim_base_index = compute_dim_base_index(&num_levels_per_group)?;
-
- let mut codec_cardinality_u64 = 1_u64;
- for &level in num_levels_per_group.iter() {
- codec_cardinality_u64 = codec_cardinality_u64
- .checked_mul(level as u64)
- .ok_or(AudioError::Runtime("codec cardinality overflow".to_string()))?;
- }
-
- if codec_cardinality_u64 > u32::MAX as u64 {
- return Err(AudioError::Runtime("codec cardinality exceeds u32 range".to_string()));
- }
-
- let codec_cardinality = codec_cardinality_u64 as u32;
- if codec_cardinality_u64 > (i32::MAX as u64 + 1) {
- return Err(AudioError::Runtime("codec cardinality exceeds i32 token kernel range".to_string()));
- }
-
- Ok(Self {
- sample_rate,
- num_groups,
- num_levels_per_group,
- dim_base_index,
- codebook_dim_per_group,
- channels,
- codec_cardinality,
- eps,
- structured_decoder: None,
- })
- }
-
- pub fn sample_rate(&self) -> u32 {
- self.sample_rate
- }
-
- pub fn num_groups(&self) -> usize {
- self.num_groups
- }
-
- pub fn num_levels_per_group(&self) -> &[i32] {
- &self.num_levels_per_group
- }
-
- pub fn dim_base_index(&self) -> &[i32] {
- &self.dim_base_index
- }
-
- pub fn codebook_dim_per_group(&self) -> usize {
- self.codebook_dim_per_group
- }
-
- pub fn channels(&self) -> usize {
- self.channels
- }
-
- pub fn codec_cardinality(&self) -> u32 {
- self.codec_cardinality
- }
-
- pub fn semantic_codec_cardinality(&self) -> Option<usize> {
- self.structured_decoder.as_ref().map(|decoder| decoder.semantic_codebook_size)
- }
-
- #[cfg(test)]
- pub fn eps(&self) -> f32 {
- self.eps
- }
-
- fn structured_decoder(&self) -> Option<&StructuredAudioCodecGraph> {
- self.structured_decoder.as_ref()
- }
-}
-
-pub struct NanoCodecFsqRuntime<B: Backend> {
- config: NanoCodecFsqRuntimeConfig,
- structured_resources: RefCell<Option<Rc<StructuredAudioRuntimeResources<B>>>>,
-}
-
-impl<B: Backend> Clone for NanoCodecFsqRuntime<B> {
- fn clone(&self) -> Self {
- Self {
- config: self.config.clone(),
- structured_resources: self.structured_resources.clone(),
- }
- }
-}
-
-impl<B: Backend> std::fmt::Debug for NanoCodecFsqRuntime<B> {
- fn fmt(
- &self,
- f: &mut std::fmt::Formatter<'_>,
- ) -> std::fmt::Result {
- f.debug_struct("NanoCodecFsqRuntime").field("config", &self.config).finish()
- }
-}
-
-impl<B: Backend> NanoCodecFsqRuntime<B> {
- pub fn new(config: NanoCodecFsqRuntimeConfig) -> Self {
- Self {
- config,
- structured_resources: RefCell::new(None),
- }
- }
-
- pub fn from_tts_config_and_model_path(
- tts_config: &TTSConfig,
- model_path: &Path,
- ) -> AudioResult<Self> {
- Ok(Self::new(NanoCodecFsqRuntimeConfig::from_tts_config_and_model_path(tts_config, model_path)?))
- }
-
- pub fn config(&self) -> &NanoCodecFsqRuntimeConfig {
- &self.config
- }
-
- fn validate_fishaudio_token_delta(
- &self,
- tokens: &AudioTokenGrid,
- fishaudio: &StructuredAudioCodecGraph,
- ) -> AudioResult<()> {
- let semantic_cardinality = u32::try_from(fishaudio.semantic_codebook_size).map_err(|_| {
- AudioError::Runtime("FishAudio semantic codebook cardinality exceeds u32 range".to_string())
- })?;
- let residual_cardinality = u32::try_from(fishaudio.codebook_size).map_err(|_| {
- AudioError::Runtime("FishAudio residual codebook cardinality exceeds u32 range".to_string())
- })?;
- let frames = tokens.frames();
- for batch in 0..tokens.batch_size() {
- for codebook in 0..tokens.codebooks() {
- let cardinality = if codebook == 0 {
- semantic_cardinality
- } else {
- residual_cardinality
- };
- for frame in 0..frames {
- let token = tokens.get(batch, codebook, frame);
- if token >= cardinality {
- return Err(AudioError::InvalidCodecToken {
- token,
- cardinality,
- });
- }
- }
- }
- }
- Ok(())
- }
-
- fn fsq_decode_padded(
- &self,
- tokens: &AudioTokenGrid,
- ) -> AudioResult<DecodedPaddedAudio> {
- if tokens.codebooks() != self.config.num_groups() {
- return Err(AudioError::Runtime(format!(
- "token codebook mismatch: expected {}, got {}",
- self.config.num_groups(),
- tokens.codebooks()
- )));
- }
-
- let batch_size = tokens.batch_size();
- let frames = tokens.frames();
- let lengths_usize = tokens.lengths().to_vec();
- let lengths_i32 = convert_lengths_to_i32(&lengths_usize, frames)?;
-
- if batch_size == 0 || frames == 0 {
- return Ok(DecodedPaddedAudio {
- samples: Vec::new(),
- channels: self.config.channels(),
- frames: 0,
- lengths: lengths_usize,
- });
- }
-
- let mut tokens_i32 = vec![0_i32; tokens.tokens().len()];
- for (index, &token) in tokens.tokens().iter().enumerate() {
- if token >= self.config.codec_cardinality() {
- return Err(AudioError::InvalidCodecToken {
- token,
- cardinality: self.config.codec_cardinality(),
- });
- }
- if token > i32::MAX as u32 {
- return Err(AudioError::Runtime(format!("token at index {index} exceeds i32 kernel range: {token}")));
- }
- tokens_i32[index] = token as i32;
- }
-
- let context = Self::create_context()?;
- let kernel = <B::Kernels as Kernels>::AudioFsqDecodeKernel::new(&context, DataType::F32)
- .map_err(|err| AudioError::Runtime(format!("failed to initialize fsq decode kernel: {err}")))?;
-
- let tokens_allocation =
- context.create_array_from(&[batch_size, self.config.num_groups(), frames], &tokens_i32).into_allocation();
-
- let lengths_allocation = context.create_array_from(&[batch_size], &lengths_i32).into_allocation();
-
- let mut output = context
- .create_array_uninitialized(&[batch_size, self.config.channels(), frames], DataType::F32)
- .into_allocation();
-
- let mut encoder = Encoder::new(context.as_ref())
- .map_err(|err| AudioError::Runtime(format!("failed to create encoder: {err}")))?;
-
- let num_groups_i32 = usize_to_i32(self.config.num_groups(), "num_groups")?;
- let frames_i32 = usize_to_i32(frames, "frames")?;
- let codebook_dim_i32 = usize_to_i32(self.config.codebook_dim_per_group(), "codebook_dim_per_group")?;
- let batch_size_i32 = usize_to_i32(batch_size, "batch_size")?;
- kernel.encode(
- &tokens_allocation,
- &mut output,
- &lengths_allocation,
- num_groups_i32,
- frames_i32,
- codebook_dim_i32,
- self.config.num_levels_per_group(),
- self.config.dim_base_index(),
- batch_size_i32,
- &mut encoder,
- );
-
- encoder
- .end_encoding()
- .submit()
- .wait_until_completed()
- .map_err(|err| AudioError::Runtime(format!("failed to wait for FSQ decode command buffer: {err}")))?;
-
- Ok(DecodedPaddedAudio {
- samples: output.copyout::<f32>(),
- channels: self.config.channels(),
- frames,
- lengths: lengths_usize,
- })
- }
-
- #[cfg(test)]
- fn fsq_encode(
- &self,
- pcm: &AudioPcmBatch,
- ) -> AudioResult<AudioTokenGrid> {
- if pcm.sample_rate() != self.config.sample_rate() {
- return Err(AudioError::Runtime(format!(
- "pcm sample-rate mismatch: expected {}, got {}",
- self.config.sample_rate(),
- pcm.sample_rate()
- )));
- }
-
- let (padded_input, lengths_usize, lengths_i32, frames) = pack_pcm_to_padded(pcm, self.config.channels())?;
- let batch_size = pcm.batch_size();
-
- if batch_size == 0 || frames == 0 {
- let empty_tokens = Vec::<u32>::new().into_boxed_slice();
- let grid = AudioTokenGrid::new(
- empty_tokens,
- batch_size,
- self.config.num_groups(),
- frames,
- lengths_usize.into_boxed_slice(),
- )?;
- return Ok(grid);
- }
-
- let context = Self::create_context()?;
- let kernel = <B::Kernels as Kernels>::AudioFsqEncodeKernel::new(&context, DataType::F32)
- .map_err(|err| AudioError::Runtime(format!("failed to initialize fsq encode kernel: {err}")))?;
-
- let input =
- context.create_array_from(&[batch_size, self.config.channels(), frames], &padded_input).into_allocation();
-
- let lengths = context.create_array_from(&[batch_size], &lengths_i32).into_allocation();
-
- let mut tokens = context
- .create_array_uninitialized(&[batch_size, self.config.num_groups(), frames], DataType::I32)
- .into_allocation();
-
- let mut encoder = Encoder::new(context.as_ref())
- .map_err(|err| AudioError::Runtime(format!("failed to create encoder: {err}")))?;
-
- let num_groups_i32 = usize_to_i32(self.config.num_groups(), "num_groups")?;
- let frames_i32 = usize_to_i32(frames, "frames")?;
- let codebook_dim_i32 = usize_to_i32(self.config.codebook_dim_per_group(), "codebook_dim_per_group")?;
- let batch_size_i32 = usize_to_i32(batch_size, "batch_size")?;
- kernel.encode(
- &input,
- &mut tokens,
- &lengths,
- num_groups_i32,
- frames_i32,
- codebook_dim_i32,
- self.config.num_levels_per_group(),
- self.config.dim_base_index(),
- self.config.eps(),
- batch_size_i32,
- &mut encoder,
- );
-
- encoder
- .end_encoding()
- .submit()
- .wait_until_completed()
- .map_err(|err| AudioError::Runtime(format!("failed to wait for FSQ encode command buffer: {err}")))?;
-
- let encoded_tokens = tokens.copyout::<i32>();
- let mut tokens_u32 = vec![0_u32; encoded_tokens.len()];
- for (index, &token) in encoded_tokens.iter().enumerate() {
- if token < 0 {
- return Err(AudioError::Runtime(format!(
- "fsq encode returned negative token at index {index}: {token}"
- )));
- }
-
- let token_u32 = token as u32;
- if token_u32 >= self.config.codec_cardinality() {
- return Err(AudioError::InvalidCodecToken {
- token: token_u32,
- cardinality: self.config.codec_cardinality(),
- });
- }
- tokens_u32[index] = token_u32;
- }
-
- AudioTokenGrid::new(
- tokens_u32.into_boxed_slice(),
- batch_size,
- self.config.num_groups(),
- frames,
- lengths_usize.into_boxed_slice(),
- )
- }
-
- pub fn begin_decode_stream_with_options(
- &self,
- batch_size: usize,
- codebooks: usize,
- max_workspace_frames: usize,
- ) -> AudioResult<AudioDecodeStreamState> {
- if codebooks != self.config.num_groups() {
- return Err(AudioError::Runtime(format!(
- "stream codebook mismatch: expected {}, got {}",
- self.config.num_groups(),
- codebooks
- )));
- }
- AudioDecodeStreamState::new(batch_size, codebooks, max_workspace_frames)
- }
-
- pub(crate) fn decoded_padded_to_pcm_batch(
- &self,
- decoded: &DecodedPaddedAudio,
- ) -> AudioResult<AudioPcmBatch> {
- let samples = unpack_padded_to_pcm(
- &decoded.samples,
- decoded.lengths.len(),
- decoded.channels,
- decoded.frames,
- &decoded.lengths,
- )?;
- AudioPcmBatch::new(
- samples.into_boxed_slice(),
- self.config.sample_rate(),
- decoded.channels,
- decoded.lengths.clone().into_boxed_slice(),
- )
- }
-
- pub fn end_decode_stream(
- &self,
- state: AudioDecodeStreamState,
- ) -> AudioResult<()> {
- drop(state);
- Ok(())
- }
-
- fn create_context() -> AudioResult<Rc<B::Context>> {
- B::Context::new().map_err(|err| AudioError::Runtime(format!("failed to create audio context: {err}")))
- }
-
- fn structured_resources(&self) -> AudioResult<Rc<StructuredAudioRuntimeResources<B>>> {
- if let Some(existing) = self.structured_resources.borrow().as_ref() {
- return Ok(existing.clone());
- }
- let context = Self::create_context()?;
- let created = Rc::new(StructuredAudioRuntimeResources::new(context));
- *self.structured_resources.borrow_mut() = Some(created.clone());
- Ok(created)
- }
-
- fn decode_structured_stream_delta(
- &self,
- state: &mut AudioDecodeStreamState,
- fishaudio: &StructuredAudioCodecGraph,
- input_frames: usize,
- ) -> AudioResult<DecodedPaddedAudio> {
- if state.total_frames() == 0 {
- state.record_last_step_stats(input_frames, 0, 0);
- return Ok(DecodedPaddedAudio {
- samples: Vec::new(),
- channels: 1,
- frames: 0,
- lengths: vec![0usize; state.batch_size],
- });
- }
-
- let resources = self.structured_resources()?;
- let Some(context_frames) = fishaudio.streaming_decode_context_frames(resources.as_ref())? else {
- let full_grid = state.to_full_grid()?;
- let full_padded = self.decode_padded(&full_grid)?;
- state.record_last_step_stats(input_frames, 0, state.total_frames());
- return state.extract_delta_from_padded_with_offset(&full_padded, 0, fishaudio.upsample_factor);
- };
- let mut window_start = state.total_frames();
- for &emitted in &state.emitted_semantic_lengths {
- window_start = window_start.min(emitted.saturating_sub(context_frames));
- }
- let window_end = state.total_frames();
- let batch_size = state.batch_size;
- let codebooks = state.codebooks;
- let (window_tokens, window_lengths, window_frames) = state.flatten_window(window_start, window_end)?;
- let decoded_window = fishaudio.decode_padded(
- resources.as_ref(),
- window_tokens,
- window_lengths,
- batch_size,
- codebooks,
- window_frames,
- )?;
- let audio_offset_frames = window_start
- .checked_mul(fishaudio.upsample_factor)
- .ok_or(AudioError::Runtime("stream audio offset overflow".to_string()))?;
- state.record_last_step_stats(input_frames, window_start, window_frames);
- state.extract_delta_from_padded_with_offset(&decoded_window, audio_offset_frames, fishaudio.upsample_factor)
- }
-
- pub(crate) fn decode_padded(
- &self,
- tokens: &AudioTokenGrid,
- ) -> AudioResult<DecodedPaddedAudio> {
- if tokens.codebooks() != self.config.num_groups() {
- return Err(AudioError::Runtime(format!(
- "token codebook mismatch: expected {}, got {}",
- self.config.num_groups(),
- tokens.codebooks()
- )));
- }
-
- let batch_size = tokens.batch_size();
- let frames = tokens.frames();
- let lengths_usize = tokens.lengths().to_vec();
-
- if batch_size == 0 || frames == 0 {
- let channels = if self.config.structured_decoder().is_some() {
- 1
- } else {
- self.config.channels()
- };
- let out_lengths = if let Some(decoder) = self.config.structured_decoder() {
- lengths_usize
- .iter()
- .map(|&length| {
- length
- .checked_mul(decoder.upsample_factor)
- .ok_or(AudioError::Runtime("decoder length scaling overflow".to_string()))
- })
- .collect::<AudioResult<Vec<_>>>()?
- } else {
- lengths_usize.clone()
- };
- return Ok(DecodedPaddedAudio {
- samples: Vec::new(),
- channels,
- frames: out_lengths.iter().copied().max().unwrap_or(0),
- lengths: out_lengths,
- });
- }
-
- if let Some(fishaudio) = self.config.structured_decoder() {
- self.validate_fishaudio_token_delta(tokens, fishaudio)?;
- let resources = self.structured_resources()?;
- let decoded = fishaudio.decode_padded(
- resources.as_ref(),
- tokens.tokens(),
- &lengths_usize,
- batch_size,
- tokens.codebooks(),
- frames,
- )?;
- return Ok(decoded);
- }
-
- self.fsq_decode_padded(tokens)
- }
-
- pub(crate) fn decode_stream_step(
- &self,
- state: &mut AudioDecodeStreamState,
- new_tokens: &AudioTokenGrid,
- _is_final: bool,
- ) -> AudioResult<DecodedPaddedAudio> {
- if new_tokens.codebooks() != state.codebooks {
- return Err(AudioError::Runtime(format!(
- "stream delta codebook mismatch: expected {}, got {}",
- state.codebooks,
- new_tokens.codebooks()
- )));
- }
- if new_tokens.batch_size() != state.batch_size {
- return Err(AudioError::Runtime(format!(
- "stream delta batch mismatch: expected {}, got {}",
- state.batch_size,
- new_tokens.batch_size()
- )));
- }
- if new_tokens.frames() == 0 {
- state.record_last_step_stats(0, state.total_frames(), 0);
- return Ok(DecodedPaddedAudio {
- samples: Vec::new(),
- channels: if self.config.structured_decoder().is_some() {
- 1
- } else {
- self.config.channels()
- },
- frames: 0,
- lengths: vec![0; state.batch_size],
- });
- }
-
- if let Some(fishaudio) = self.config.structured_decoder() {
- self.validate_fishaudio_token_delta(new_tokens, fishaudio)?;
- state.append_delta(new_tokens)?;
- return self.decode_structured_stream_delta(state, fishaudio, new_tokens.frames());
- }
-
- state.append_delta(new_tokens)?;
- let full_grid = state.to_full_grid()?;
- let full_padded = self.fsq_decode_padded(&full_grid)?;
- state.record_last_step_stats(new_tokens.frames(), 0, state.total_frames());
- state.extract_delta_from_padded_with_offset(&full_padded, 0, 1)
- }
-
- pub(crate) fn submit_decode_stream_step(
- &self,
- state: &mut AudioDecodeStreamState,
- new_tokens: &AudioTokenGrid,
- is_final: bool,
- ) -> AudioResult<Option<PendingStreamPcmChunk<B>>> {
- if is_final {
- return Ok(None);
- }
- if new_tokens.codebooks() != state.codebooks {
- return Err(AudioError::Runtime(format!(
- "stream delta codebook mismatch: expected {}, got {}",
- state.codebooks,
- new_tokens.codebooks()
- )));
- }
- if new_tokens.batch_size() != state.batch_size {
- return Err(AudioError::Runtime(format!(
- "stream delta batch mismatch: expected {}, got {}",
- state.batch_size,
- new_tokens.batch_size()
- )));
- }
- if new_tokens.frames() == 0 {
- return Ok(None);
- }
-
- let Some(fishaudio) = self.config.structured_decoder() else {
- return Ok(None);
- };
- let resources = self.structured_resources()?;
- let Some(context_frames) = fishaudio.streaming_decode_context_frames(resources.as_ref())? else {
- return Ok(None);
- };
-
- self.validate_fishaudio_token_delta(new_tokens, fishaudio)?;
- state.append_delta(new_tokens)?;
-
- let mut window_start = state.total_frames();
- for &emitted in &state.emitted_semantic_lengths {
- window_start = window_start.min(emitted.saturating_sub(context_frames));
- }
- let window_end = state.total_frames();
- let batch_size = state.batch_size;
- let codebooks = state.codebooks;
- let previous_audio_lengths = state.emitted_audio_lengths.clone().into_boxed_slice();
- let semantic_lengths = state.semantic_lengths.clone().into_boxed_slice();
- let (window_tokens, window_lengths, window_frames) = state.flatten_window(window_start, window_end)?;
- let submitted = fishaudio.submit_decode_padded(
- resources.as_ref(),
- window_tokens,
- window_lengths,
- batch_size,
- codebooks,
- window_frames,
- )?;
- let audio_offset_frames = window_start
- .checked_mul(fishaudio.upsample_factor)
- .ok_or(AudioError::Runtime("stream audio offset overflow".to_string()))?;
- state.record_last_step_stats(new_tokens.frames(), window_start, window_frames);
- state.mark_submitted_audio_window(&semantic_lengths, fishaudio.upsample_factor)?;
-
- Ok(Some(PendingStreamPcmChunk {
- runtime: self.clone(),
- submitted,
- previous_audio_lengths,
- semantic_lengths,
- audio_offset_frames,
- upsample_factor: fishaudio.upsample_factor,
- step_stats: state.last_step_stats(),
- }))
- }
-}
-
-impl<B: Backend> AudioCodecRuntime for NanoCodecFsqRuntime<B> {
- #[cfg(test)]
- fn encode(
- &self,
- pcm: &AudioPcmBatch,
- ) -> AudioResult<AudioTokenGrid> {
- if self.config.structured_decoder().is_some() {
- return Err(AudioError::Runtime("encode is not supported when a decoder graph is configured".to_string()));
- }
- self.fsq_encode(pcm)
- }
-
- fn decode(
- &self,
- tokens: &AudioTokenGrid,
- ) -> AudioResult<AudioPcmBatch> {
- let decoded = self.decode_padded(tokens)?;
- self.decoded_padded_to_pcm_batch(&decoded)
- }
-}
-
-#[cfg(test)]
-#[path = "../../../unit/audio/nanocodec/runtime.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/loaders.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/loaders.rs
deleted file mode 100644
index f17497850..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/loaders.rs
+++ /dev/null
@@ -1,45 +0,0 @@
-use super::*;
-
-pub(super) fn load_audio_runtime_from_tts_config(
- tts_config: &TTSConfig,
- model_path: &Path,
-) -> AudioResult<(RuntimeConfigJson, StructuredAudioCodecGraph)> {
- let AnyTTSAudioDecoderConfig::DescriptAudioCodecConfig(cfg) = &tts_config.audio_decoder_config;
- let weights_path = model_path.join("model.safetensors");
- let vocoder_data_type = DataType::BF16;
-
- let total_codebooks = cfg
- .n_codebooks
- .checked_add(1)
- .ok_or(AudioError::Runtime("FishAudio codebook count overflow while building runtime config".to_string()))?;
- let codebook_size_i32 = i32::try_from(cfg.codebook_size)
- .map_err(|_| AudioError::Runtime("FishAudio codebook_size exceeds i32 kernel range".to_string()))?;
- if codebook_size_i32 <= 1 {
- return Err(AudioError::InvalidTokenCardinality);
- }
-
- let upsample_factor = cfg
- .downsample_factor
- .iter()
- .chain(cfg.decoder_rates.iter())
- .try_fold(1usize, |acc, &value| acc.checked_mul(value))
- .ok_or(AudioError::Runtime("FishAudio upsample factor overflow".to_string()))?;
-
- let runtime = RuntimeConfigJson {
- sample_rate: cfg.samplerate,
- num_groups: total_codebooks,
- num_levels_per_group: vec![codebook_size_i32],
- eps: default_eps(),
- };
- let decoder = StructuredAudioCodecGraph {
- config: cfg.clone(),
- weights_path: weights_path.display().to_string(),
- codebook_size: cfg.codebook_size,
- semantic_codebook_size: cfg.semantic_codebook_size,
- input_dim: cfg.input_dim,
- total_codebooks,
- upsample_factor,
- vocoder_data_type,
- };
- Ok((runtime, decoder))
-}
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/profile.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/profile.rs
deleted file mode 100644
index 641349d56..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/profile.rs
+++ /dev/null
@@ -1,105 +0,0 @@
-use std::sync::mpsc::Receiver;
-
-use super::*;
-use crate::{array::Array, backends::common::Allocation};
-
-pub enum SubmittedDecodedPaddedAudio<B: Backend> {
- Ready(DecodedPaddedAudio),
- Pending {
- output: Allocation<B>,
- retained_inputs: Box<[Array<B>]>,
- data_type: DataType,
- channels: usize,
- frames: usize,
- lengths: Vec<usize>,
- final_command_buffer: Pending<B>,
- completion_notification: Receiver<()>,
- },
-}
-
-impl<B: Backend> SubmittedDecodedPaddedAudio<B> {
- pub(crate) fn is_complete(&self) -> bool {
- use std::sync::mpsc::TryRecvError;
-
- match self {
- Self::Ready(_) => true,
- Self::Pending {
- completion_notification,
- ..
- } => match completion_notification.try_recv() {
- Ok(()) | Err(TryRecvError::Disconnected) => true,
- Err(TryRecvError::Empty) => false,
- },
- }
- }
-
- pub(in crate::audio::nanocodec::runtime) fn resolve(self) -> AudioResult<DecodedPaddedAudio> {
- match self {
- Self::Ready(decoded) => Ok(decoded),
- Self::Pending {
- output,
- retained_inputs,
- data_type,
- channels,
- frames,
- lengths,
- final_command_buffer,
- completion_notification: _,
- } => {
- let completed_command_buffer = final_command_buffer.wait_until_completed().map_err(|err| {
- AudioError::Runtime(format!("failed to wait for FishAudio decoder command buffer: {err}"))
- })?;
- drop(retained_inputs);
- let samples_result: AudioResult<Vec<f32>> = match data_type {
- DataType::F32 => Ok(output.copyout::<f32>()),
- DataType::F16 => Ok(output.copyout::<half::f16>().iter().map(|&value| f32::from(value)).collect()),
- DataType::BF16 => {
- Ok(output.copyout::<half::bf16>().iter().map(|&value| f32::from(value)).collect())
- },
- dt => Err(AudioError::Runtime(format!("unsupported vocoder output dtype: {dt:?}"))),
- };
- drop(output);
- drop(completed_command_buffer);
- let samples = samples_result?;
- Ok(DecodedPaddedAudio {
- samples,
- channels,
- frames,
- lengths,
- })
- },
- }
- }
-}
-
-pub(crate) struct PendingStreamPcmChunk<B: Backend> {
- pub(in crate::audio::nanocodec::runtime) runtime: NanoCodecFsqRuntime<B>,
- pub(in crate::audio::nanocodec::runtime) submitted: SubmittedDecodedPaddedAudio<B>,
- pub(in crate::audio::nanocodec::runtime) previous_audio_lengths: Box<[usize]>,
- pub(in crate::audio::nanocodec::runtime) semantic_lengths: Box<[usize]>,
- pub(in crate::audio::nanocodec::runtime) audio_offset_frames: usize,
- pub(in crate::audio::nanocodec::runtime) upsample_factor: usize,
- pub(in crate::audio::nanocodec::runtime) step_stats: AudioDecodeStepStats,
-}
-
-impl<B: Backend> PendingStreamPcmChunk<B> {
- pub(crate) fn step_stats(&self) -> AudioDecodeStepStats {
- self.step_stats
- }
-
- pub(crate) fn is_complete(&self) -> bool {
- self.submitted.is_complete()
- }
-
- pub(crate) fn resolve(self) -> AudioResult<AudioPcmBatch> {
- let decoded_window = self.submitted.resolve()?;
- let delta = extract_delta_from_padded_with_offset_snapshot(
- &decoded_window,
- &self.previous_audio_lengths,
- &self.semantic_lengths,
- self.audio_offset_frames,
- self.upsample_factor,
- )?;
- self.runtime.decoded_padded_to_pcm_batch(&delta)
- }
-}
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/stream.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/stream.rs
deleted file mode 100644
index ea1547231..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/stream.rs
+++ /dev/null
@@ -1,482 +0,0 @@
-use super::*;
-
-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
-pub struct AudioDecodeStepStats {
- pub input_frames: usize,
- pub total_semantic_frames: usize,
- pub decoded_window_start_frame: usize,
- pub decoded_window_frames: usize,
-}
-
-/// Ring-buffer backed stream state for incremental audio decoding.
-///
-/// Token rows are stored in fixed-capacity circular buffers so that evicting
-/// old frames is O(1) (just advance the head pointer) instead of O(N) via
-/// `Vec::drain`.
-#[derive(Debug, Clone)]
-pub struct AudioDecodeStreamState {
- pub(super) batch_size: usize,
- pub(super) codebooks: usize,
- retained_capacity: usize,
- stored_frame_start: usize,
- stored_frames: usize,
- total_frames_generated: usize,
- row_tokens: Vec<Vec<u32>>,
- flattened_tokens: Vec<u32>,
- window_lengths: Vec<usize>,
- pub(super) semantic_lengths: Vec<usize>,
- pub(super) emitted_semantic_lengths: Vec<usize>,
- pub(super) emitted_audio_lengths: Vec<usize>,
- last_step_stats: AudioDecodeStepStats,
-}
-
-impl AudioDecodeStreamState {
- pub(super) fn new(
- batch_size: usize,
- codebooks: usize,
- max_workspace_frames: usize,
- ) -> AudioResult<Self> {
- if batch_size == 0 {
- return Err(AudioError::Runtime("stream state batch_size must be > 0".to_string()));
- }
- if codebooks == 0 {
- return Err(AudioError::Runtime("stream state codebooks must be > 0".to_string()));
- }
- if max_workspace_frames == 0 {
- return Err(AudioError::Runtime("stream state max_workspace_frames must be > 0".to_string()));
- }
-
- let row_count = batch_size
- .checked_mul(codebooks)
- .ok_or(AudioError::Runtime("stream state row count overflow".to_string()))?;
- // Double the workspace for ring capacity so we have room for context
- // overlap without immediate eviction.
- let retained_capacity = max_workspace_frames
- .checked_mul(2)
- .ok_or(AudioError::Runtime("stream retained capacity overflow".to_string()))?;
- let mut row_tokens = Vec::with_capacity(row_count);
- for _ in 0..row_count {
- row_tokens.push(vec![0u32; retained_capacity]);
- }
-
- Ok(Self {
- batch_size,
- codebooks,
- retained_capacity,
- stored_frame_start: 0,
- stored_frames: 0,
- total_frames_generated: 0,
- row_tokens,
- flattened_tokens: Vec::with_capacity(
- row_count
- .checked_mul(max_workspace_frames)
- .ok_or(AudioError::Runtime("stream token capacity overflow".to_string()))?,
- ),
- window_lengths: Vec::with_capacity(batch_size),
- semantic_lengths: vec![0; batch_size],
- emitted_semantic_lengths: vec![0; batch_size],
- emitted_audio_lengths: vec![0; batch_size],
- last_step_stats: AudioDecodeStepStats::default(),
- })
- }
-
- pub(super) fn total_frames(&self) -> usize {
- self.total_frames_generated
- }
-
- pub fn last_step_stats(&self) -> AudioDecodeStepStats {
- self.last_step_stats
- }
-
- /// Global frame index one past the last retained frame.
- fn stored_frame_end(&self) -> usize {
- self.stored_frame_start.saturating_add(self.stored_frames)
- }
-
- /// Physical ring slot for a global frame index.
- #[inline]
- fn slot(
- &self,
- global_frame: usize,
- ) -> usize {
- global_frame % self.retained_capacity
- }
-
- pub(super) fn append_delta(
- &mut self,
- delta_tokens: &AudioTokenGrid,
- ) -> AudioResult<()> {
- if delta_tokens.batch_size() != self.batch_size {
- return Err(AudioError::Runtime(format!(
- "stream delta batch mismatch: expected {}, got {}",
- self.batch_size,
- delta_tokens.batch_size()
- )));
- }
- if delta_tokens.codebooks() != self.codebooks {
- return Err(AudioError::Runtime(format!(
- "stream delta codebook mismatch: expected {}, got {}",
- self.codebooks,
- delta_tokens.codebooks()
- )));
- }
- if delta_tokens.frames() == 0 {
- return Ok(());
- }
-
- let delta_frames = delta_tokens.frames();
- let tokens = delta_tokens.tokens();
- let delta_lengths = delta_tokens.lengths();
-
- for frame_offset in 0..delta_frames {
- let global_frame = self.stored_frame_start + self.stored_frames;
- // Evict oldest frame if ring is full.
- if self.stored_frames == self.retained_capacity {
- self.stored_frame_start += 1;
- self.stored_frames -= 1;
- }
- let physical = self.slot(global_frame);
-
- for batch in 0..self.batch_size {
- for codebook in 0..self.codebooks {
- let row_index = batch * self.codebooks + codebook;
- let src_index = row_index * delta_frames + frame_offset;
- self.row_tokens[row_index][physical] = tokens[src_index];
- }
- }
- self.stored_frames += 1;
- }
- self.total_frames_generated = self.total_frames_generated.saturating_add(delta_frames);
-
- for (length, &delta_len) in self.semantic_lengths.iter_mut().zip(delta_lengths.iter()) {
- *length = length
- .checked_add(delta_len)
- .ok_or(AudioError::Runtime("stream semantic length overflow".to_string()))?;
- }
-
- Ok(())
- }
-
- pub(super) fn to_full_grid(&self) -> AudioResult<AudioTokenGrid> {
- if self.stored_frame_start != 0 {
- return Err(AudioError::Runtime(format!(
- "full-grid decode requires retained prefix, but {} frames were evicted",
- self.stored_frame_start
- )));
- }
- let total_frames = self.stored_frames;
-
- let expected_tokens = self
- .batch_size
- .checked_mul(self.codebooks)
- .and_then(|value| value.checked_mul(total_frames))
- .ok_or(AudioError::Runtime("stream token count overflow".to_string()))?;
- let mut tokens = Vec::with_capacity(expected_tokens);
-
- for row in &self.row_tokens {
- // When stored_frame_start == 0 and no wrap has occurred, frames
- // 0..total_frames map to physical slots 0..total_frames.
- for frame in 0..total_frames {
- let physical = self.slot(frame);
- tokens.push(row[physical]);
- }
- }
- if tokens.len() != expected_tokens {
- return Err(AudioError::Runtime("stream flattened token count mismatch".to_string()));
- }
-
- AudioTokenGrid::new(
- tokens.into_boxed_slice(),
- self.batch_size,
- self.codebooks,
- total_frames,
- self.semantic_lengths.clone().into_boxed_slice(),
- )
- }
-
- pub(super) fn flatten_window(
- &mut self,
- start_frame: usize,
- end_frame: usize,
- ) -> AudioResult<(&[u32], &[usize], usize)> {
- if end_frame < start_frame {
- return Err(AudioError::Runtime(format!(
- "invalid stream window: start_frame={start_frame}, end_frame={end_frame}"
- )));
- }
- let total_frames = self.total_frames();
- if end_frame > total_frames {
- return Err(AudioError::Runtime(format!(
- "stream window end exceeds token frames: end={end_frame}, total={total_frames}"
- )));
- }
- if start_frame < self.stored_frame_start || end_frame > self.stored_frame_end() {
- return Err(AudioError::Runtime(format!(
- "stream window [{start_frame}, {end_frame}) exceeds retained workspace [{}, {})",
- self.stored_frame_start,
- self.stored_frame_end()
- )));
- }
-
- let window_frames = end_frame.saturating_sub(start_frame);
- let row_count = self
- .batch_size
- .checked_mul(self.codebooks)
- .ok_or(AudioError::Runtime("stream row count overflow".to_string()))?;
- let required_capacity = row_count
- .checked_mul(window_frames)
- .ok_or(AudioError::Runtime("stream window token capacity overflow".to_string()))?;
-
- // Grow the scratch buffer if needed (only happens once in practice).
- if self.flattened_tokens.capacity() < required_capacity {
- self.flattened_tokens.reserve(required_capacity - self.flattened_tokens.capacity());
- }
- self.flattened_tokens.clear();
-
- // Read from ring in logical order via modulo indexing.
- for row in &self.row_tokens {
- for global_frame in start_frame..end_frame {
- let physical = self.slot(global_frame);
- self.flattened_tokens.push(row[physical]);
- }
- }
-
- self.window_lengths.clear();
- for &length in &self.semantic_lengths {
- self.window_lengths.push(length.saturating_sub(start_frame));
- }
-
- Ok((&self.flattened_tokens, &self.window_lengths, window_frames))
- }
-
- pub(super) fn extract_delta_from_padded_with_offset(
- &mut self,
- full_padded: &DecodedPaddedAudio,
- audio_offset_frames: usize,
- upsample_factor: usize,
- ) -> AudioResult<DecodedPaddedAudio> {
- let delta = extract_delta_from_padded_with_offset_snapshot(
- full_padded,
- &self.emitted_audio_lengths,
- &self.semantic_lengths,
- audio_offset_frames,
- upsample_factor,
- )?;
- for index in 0..self.semantic_lengths.len() {
- let semantic_length = self.semantic_lengths[index];
- let full_audio_length = semantic_length
- .checked_mul(upsample_factor)
- .ok_or(AudioError::Runtime("stream audio length overflow".to_string()))?;
- self.emitted_audio_lengths[index] = full_audio_length;
- self.emitted_semantic_lengths[index] = semantic_length;
- }
- Ok(delta)
- }
-
- pub(super) fn mark_submitted_audio_window(
- &mut self,
- semantic_lengths: &[usize],
- upsample_factor: usize,
- ) -> AudioResult<()> {
- if semantic_lengths.len() != self.batch_size {
- return Err(AudioError::Runtime(format!(
- "stream semantic lengths mismatch: expected {}, got {}",
- self.batch_size,
- semantic_lengths.len()
- )));
- }
- for (index, &semantic_length) in semantic_lengths.iter().enumerate() {
- let full_audio_length = semantic_length
- .checked_mul(upsample_factor)
- .ok_or(AudioError::Runtime("stream audio length overflow".to_string()))?;
- self.emitted_audio_lengths[index] = full_audio_length;
- self.emitted_semantic_lengths[index] = semantic_length;
- }
- Ok(())
- }
-
- pub(super) fn record_last_step_stats(
- &mut self,
- input_frames: usize,
- decoded_window_start_frame: usize,
- decoded_window_frames: usize,
- ) {
- self.last_step_stats = AudioDecodeStepStats {
- input_frames,
- total_semantic_frames: self.total_frames_generated,
- decoded_window_start_frame,
- decoded_window_frames,
- };
- }
-}
-
-pub(super) fn extract_delta_from_padded_with_offset_snapshot(
- full_padded: &DecodedPaddedAudio,
- previous_audio_lengths: &[usize],
- semantic_lengths: &[usize],
- audio_offset_frames: usize,
- upsample_factor: usize,
-) -> AudioResult<DecodedPaddedAudio> {
- if full_padded.lengths.len() != semantic_lengths.len() || previous_audio_lengths.len() != semantic_lengths.len() {
- return Err(AudioError::Runtime(format!(
- "stream decoded batch mismatch: full_lengths={}, previous_lengths={}, semantic_lengths={}",
- full_padded.lengths.len(),
- previous_audio_lengths.len(),
- semantic_lengths.len()
- )));
- }
- if upsample_factor == 0 {
- return Err(AudioError::Runtime("stream upsample_factor must be > 0".to_string()));
- }
-
- let batch_size = semantic_lengths.len();
- let channels = full_padded.channels;
- let decoded_frames = full_padded.frames;
- let mut delta_lengths = vec![0usize; batch_size];
- let mut max_delta_frames = 0usize;
- let mut local_delta_ranges = vec![(0usize, 0usize); batch_size];
-
- for batch in 0..batch_size {
- let full_audio_length = semantic_lengths[batch]
- .checked_mul(upsample_factor)
- .ok_or(AudioError::Runtime("stream audio length overflow".to_string()))?;
- let previous_audio_length = previous_audio_lengths[batch].min(full_audio_length);
- let decoded_batch_length = full_padded.lengths[batch];
- let target_end_local = full_audio_length.saturating_sub(audio_offset_frames).min(decoded_batch_length);
- let target_start_local = previous_audio_length.saturating_sub(audio_offset_frames).min(target_end_local);
- let delta = target_end_local.saturating_sub(target_start_local);
- local_delta_ranges[batch] = (target_start_local, target_end_local);
- delta_lengths[batch] = delta;
- max_delta_frames = max_delta_frames.max(delta);
- }
-
- let padded_len = checked_product(&[batch_size, channels, max_delta_frames])?;
- let mut delta_padded = vec![0.0_f32; padded_len];
- for (batch, &(start_local, end_local)) in local_delta_ranges.iter().enumerate() {
- let delta_len = end_local.saturating_sub(start_local);
- if delta_len == 0 {
- continue;
- }
- for channel in 0..channels {
- let src_start = (batch * channels + channel)
- .checked_mul(decoded_frames)
- .and_then(|value| value.checked_add(start_local))
- .ok_or(AudioError::Runtime("stream padded source offset overflow".to_string()))?;
- let src_end = src_start
- .checked_add(delta_len)
- .ok_or(AudioError::Runtime("stream padded source offset overflow".to_string()))?;
- let dst_start = (batch * channels + channel)
- .checked_mul(max_delta_frames)
- .ok_or(AudioError::Runtime("stream padded destination offset overflow".to_string()))?;
- let dst_end = dst_start
- .checked_add(delta_len)
- .ok_or(AudioError::Runtime("stream padded destination offset overflow".to_string()))?;
- delta_padded[dst_start..dst_end].copy_from_slice(&full_padded.samples[src_start..src_end]);
- }
- }
-
- Ok(DecodedPaddedAudio {
- samples: delta_padded,
- channels,
- frames: max_delta_frames,
- lengths: delta_lengths,
- })
-}
-
-#[cfg(test)]
-pub(super) fn pack_pcm_to_padded(
- pcm: &AudioPcmBatch,
- expected_channels: usize,
-) -> AudioResult<(Vec<f32>, Vec<usize>, Vec<i32>, usize)> {
- if pcm.channels() != expected_channels {
- return Err(AudioError::Runtime(format!(
- "pcm channel mismatch: expected {expected_channels}, got {}",
- pcm.channels()
- )));
- }
-
- let lengths = pcm.lengths().to_vec();
- let frames = lengths.iter().copied().max().unwrap_or(0);
- let lengths_i32 = convert_lengths_to_i32(&lengths, frames)?;
- let padded_len = checked_product(&[pcm.batch_size(), expected_channels, frames])?;
- let mut padded = vec![0.0_f32; padded_len];
-
- let mut src_offset = 0usize;
- let samples = pcm.samples();
- for (batch, &frame_count) in lengths.iter().enumerate() {
- let sample_count = frame_count
- .checked_mul(expected_channels)
- .ok_or(AudioError::Runtime("pcm frame-count overflow".to_string()))?;
- let src_end =
- src_offset.checked_add(sample_count).ok_or(AudioError::Runtime("pcm indexing overflow".to_string()))?;
- if src_end > samples.len() {
- return Err(AudioError::Runtime("pcm indexing out of bounds".to_string()));
- }
-
- for frame in 0..frame_count {
- let src_frame_base = src_offset + frame * expected_channels;
- for channel in 0..expected_channels {
- let dst_index = (batch * expected_channels + channel) * frames + frame;
- padded[dst_index] = samples[src_frame_base + channel];
- }
- }
-
- src_offset = src_end;
- }
-
- Ok((padded, lengths, lengths_i32, frames))
-}
-
-pub(super) fn unpack_padded_to_pcm(
- padded: &[f32],
- batch_size: usize,
- channels: usize,
- frames: usize,
- lengths: &[usize],
-) -> AudioResult<Vec<f32>> {
- if lengths.len() != batch_size {
- return Err(AudioError::InvalidTokenLengths {
- expected_lengths: batch_size,
- actual_lengths: lengths.len(),
- });
- }
-
- let expected_padded = checked_product(&[batch_size, channels, frames])?;
- if padded.len() != expected_padded {
- return Err(AudioError::InvalidPcmShape {
- expected_samples: expected_padded,
- actual_samples: padded.len(),
- });
- }
-
- let total_frames = lengths.iter().sum::<usize>();
- let packed_len = checked_product(&[total_frames, channels])?;
- let mut packed = vec![0.0_f32; packed_len];
- let mut dst_offset = 0usize;
-
- for (batch, &frame_count) in lengths.iter().enumerate() {
- if frame_count > frames {
- return Err(AudioError::InvalidTokenLengthValue {
- length: frame_count,
- frames,
- });
- }
-
- for frame in 0..frame_count {
- for channel in 0..channels {
- let src_index = (batch * channels + channel) * frames + frame;
- let dst_index = dst_offset + frame * channels + channel;
- packed[dst_index] = padded[src_index];
- }
- }
- dst_offset = dst_offset
- .checked_add(
- frame_count
- .checked_mul(channels)
- .ok_or(AudioError::Runtime("pcm destination indexing overflow".to_string()))?,
- )
- .ok_or(AudioError::Runtime("pcm destination indexing overflow".to_string()))?;
- }
-
- Ok(packed)
-}
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/build.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/build.rs
deleted file mode 100644
index a46652f50..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/build.rs
+++ /dev/null
@@ -1,253 +0,0 @@
-use super::*;
-use crate::{array::Array, backends::common::gpu_types::ActivationType, parameters::ParameterTree};
-
-pub(super) fn copy_to_outer_axis_slice<B: Backend>(
- destination: &mut Array<B>,
- index: usize,
- source: &Array<B>,
- slice_shape: &[usize],
-) -> AudioResult<()> {
- let slice_bytes = size_for_shape(slice_shape, source.data_type());
- let offset =
- index.checked_mul(slice_bytes).ok_or(AudioError::Runtime("outer-axis slice offset overflow".to_string()))?;
- let end =
- offset.checked_add(slice_bytes).ok_or(AudioError::Runtime("outer-axis slice end overflow".to_string()))?;
- if end > destination.size() {
- return Err(AudioError::Runtime(format!(
- "outer-axis slice exceeds destination: end {end}, destination size {}",
- destination.size()
- )));
- }
- destination.as_bytes_mut()[offset..end].copy_from_slice(source.as_bytes());
- Ok(())
-}
-
-pub(super) fn read_conv1d_layer<B: Backend>(
- tree: &ParameterTree<B>,
- data_type: DataType,
- cin: usize,
- cout: usize,
- kernel_size: usize,
- dilation: usize,
- groups: usize,
-) -> AudioResult<StructuredAudioConv1d<B>> {
- if groups == 0 || cin == 0 || cout == 0 || kernel_size == 0 {
- return Err(AudioError::InvalidTokenCardinality);
- }
- if !cin.is_multiple_of(groups) || !cout.is_multiple_of(groups) {
- return Err(AudioError::Runtime(format!(
- "invalid grouped conv dimensions: cin {cin}, cout {cout}, groups {groups}"
- )));
- }
- let weight = tree.leaf("weights")?.validate(&[cout, cin / groups, kernel_size], data_type)?.read_array()?;
- let bias = tree.leaf("biases")?.validate(&[cout], data_type)?.read_array()?;
- Ok(StructuredAudioConv1d {
- weight,
- bias,
- cin,
- cout,
- kernel_size,
- dilation,
- groups,
- })
-}
-
-pub(super) fn read_conv_transpose1d_layer<B: Backend>(
- tree: &ParameterTree<B>,
- data_type: DataType,
- cin: usize,
- cout: usize,
- kernel_size: usize,
- stride: usize,
- groups: usize,
-) -> AudioResult<StructuredAudioConvTranspose1d<B>> {
- if stride == 0 || groups == 0 || cin == 0 || cout == 0 || kernel_size == 0 {
- return Err(AudioError::InvalidTokenCardinality);
- }
- if !cin.is_multiple_of(groups) || !cout.is_multiple_of(groups) {
- return Err(AudioError::InvalidTokenCardinality);
- }
- let weight = tree.leaf("weights")?.validate(&[cout, cin / groups, kernel_size], data_type)?.read_array()?;
- let bias = tree.leaf("biases")?.validate(&[cout], data_type)?.read_array()?;
- Ok(StructuredAudioConvTranspose1d {
- weight,
- bias,
- cin,
- cout,
- kernel_size,
- stride,
- groups,
- })
-}
-
-pub(super) fn read_pointwise_conv_layer<B: Backend>(
- tree: &ParameterTree<B>,
- data_type: DataType,
- expected_out_dim: usize,
- expected_in_dim: usize,
-) -> AudioResult<StructuredAudioPointwiseConv<B>> {
- let weight =
- tree.leaf("weights.weights")?.validate(&[expected_out_dim, expected_in_dim], data_type)?.read_array()?;
- let bias = tree.leaf("biases")?.validate(&[expected_out_dim], data_type)?.read_array()?;
- Ok(StructuredAudioPointwiseConv {
- weight,
- bias,
- cin: expected_in_dim,
- cout: expected_out_dim,
- })
-}
-
-pub(super) fn read_norm_layer<B: Backend>(
- context: &Rc<B::Context>,
- tree: &ParameterTree<B>,
- channels: usize,
- epsilon: f32,
- subtract_mean: bool,
- use_bias: bool,
-) -> AudioResult<StructuredAudioNorm<B>> {
- let norm_data_type = DataType::F32;
- let scales = tree.leaf("scales")?.validate(&[channels], norm_data_type)?.read_array()?;
- let bias = if use_bias {
- tree.leaf("biases")?.validate(&[channels], norm_data_type)?.read_array()?
- } else {
- context.create_array_zeros(&[channels], norm_data_type)
- };
- Ok(StructuredAudioNorm {
- scales,
- bias,
- epsilon,
- subtract_mean,
- })
-}
-
-pub(super) fn read_convnext_layer<B: Backend>(
- context: &Rc<B::Context>,
- tree: &ParameterTree<B>,
- data_type: DataType,
- activation_type: ActivationType,
- norm_config: &NormalizationConfig,
- dim: usize,
-) -> AudioResult<StructuredAudioConvNeXt<B>> {
- let hidden_dim = dim.checked_mul(4).ok_or(AudioError::Runtime("ConvNeXt hidden dimension overflow".to_string()))?;
- let depthwise_conv = read_conv1d_layer::<B>(&tree.subtree("depthwise_conv")?, data_type, dim, dim, 7, 1, dim)?;
- let norm = read_norm_layer::<B>(
- context,
- &tree.subtree("norm")?,
- dim,
- norm_config.epsilon,
- norm_config.subtract_mean,
- norm_config.has_biases,
- )?;
- let pwconv1 = read_pointwise_conv_layer::<B>(&tree.subtree("pointwise_conv_step1")?, data_type, hidden_dim, dim)?;
- let pwconv2 = read_pointwise_conv_layer::<B>(&tree.subtree("pointwise_conv_step2")?, data_type, dim, hidden_dim)?;
- Ok(StructuredAudioConvNeXt {
- activation_type,
- depthwise_conv,
- norm,
- pwconv1,
- pwconv2,
- })
-}
-
-pub(super) fn read_residual_unit_layer<B: Backend>(
- tree: &ParameterTree<B>,
- data_type: DataType,
- dilation: usize,
- dim: usize,
-) -> AudioResult<StructuredAudioResidualUnit<B>> {
- let alpha_shape = [dim];
- let snake1_alpha = tree.leaf("snake1.alpha")?.validate(&alpha_shape, data_type)?.read_array()?;
- let conv1 = read_conv1d_layer::<B>(&tree.subtree("conv1")?, data_type, dim, dim, 7, dilation, 1)?;
- let snake2_alpha = tree.leaf("snake2.alpha")?.validate(&alpha_shape, data_type)?.read_array()?;
- let conv2 = read_conv1d_layer::<B>(&tree.subtree("conv2")?, data_type, dim, dim, 1, 1, 1)?;
- Ok(StructuredAudioResidualUnit {
- snake1_alpha,
- conv1,
- snake2_alpha,
- conv2,
- })
-}
-
-pub(super) fn build_vocoder_graph_from_tree<B: Backend>(
- context: &Rc<B::Context>,
- root: &ParameterTree<B>,
- config: &DescriptAudioCodecConfig,
- data_type: DataType,
-) -> AudioResult<StructuredAudioDecoderGraph<B>> {
- let audio_decoder_tree = root.subtree("audio_decoder")?;
- let quantizer_tree = audio_decoder_tree.subtree("quantizer")?;
- let decoder_tree = audio_decoder_tree.subtree("decoder")?;
-
- let latent_dim = config.encoder_dim * (1usize << config.encoder_rates.len());
- let final_dim = config.decoder_dim / (1usize << config.decoder_rates.len());
-
- let first_conv = read_conv1d_layer::<B>(
- &decoder_tree.subtree("first_conv")?,
- data_type,
- latent_dim,
- config.decoder_dim,
- 7,
- 1,
- 1,
- )?;
- let final_conv = read_conv1d_layer::<B>(&decoder_tree.subtree("final_conv")?, data_type, final_dim, 1, 7, 1, 1)?;
- let final_snake_alpha = decoder_tree.leaf("final_snake.alpha")?.validate(&[final_dim], data_type)?.read_array()?;
-
- let mut upsample_blocks = Vec::with_capacity(config.downsample_factor.len());
- for (index, &stride) in config.downsample_factor.iter().rev().enumerate() {
- let block_tree = quantizer_tree.subtree("upsampler")?.subtree("blocks")?.subtree(&index.to_string())?;
- let trans_conv = read_conv_transpose1d_layer::<B>(
- &block_tree.subtree("trans_conv")?,
- data_type,
- config.input_dim,
- config.input_dim,
- stride,
- stride,
- 1,
- )?;
- let convnext = read_convnext_layer::<B>(
- context,
- &block_tree.subtree("convnext")?,
- data_type,
- config.quantizer_config.upsampler_config.block_configs[index].convnext_config.activation.act_type(),
- &config.quantizer_config.upsampler_config.block_configs[index].convnext_config.norm_config,
- config.input_dim,
- )?;
- upsample_blocks.push((trans_conv, convnext));
- }
-
- let mut decoder_blocks = Vec::with_capacity(config.decoder_rates.len());
- for (index, &stride) in config.decoder_rates.iter().enumerate() {
- let block_tree = decoder_tree.subtree("decoder_blocks")?.subtree(&index.to_string())?;
- let input_dim = config.decoder_dim / (1usize << index);
- let output_dim = config.decoder_dim / (1usize << (index + 1));
- let trans_conv = read_conv_transpose1d_layer::<B>(
- &block_tree.subtree("trans_conv")?,
- data_type,
- input_dim,
- output_dim,
- 2 * stride,
- stride,
- 1,
- )?;
- let snake_alpha = block_tree.leaf("snake.alpha")?.validate(&[input_dim], data_type)?.read_array()?;
- let res_unit1 = read_residual_unit_layer::<B>(&block_tree.subtree("res_unit1")?, data_type, 1, output_dim)?;
- let res_unit2 = read_residual_unit_layer::<B>(&block_tree.subtree("res_unit2")?, data_type, 3, output_dim)?;
- let res_unit3 = read_residual_unit_layer::<B>(&block_tree.subtree("res_unit3")?, data_type, 9, output_dim)?;
- decoder_blocks.push(StructuredAudioDecoderBlock {
- snake_alpha,
- trans_conv,
- res_unit1,
- res_unit2,
- res_unit3,
- });
- }
-
- Ok(StructuredAudioDecoderGraph {
- first_conv,
- upsample_blocks,
- decoder_blocks,
- final_snake_alpha,
- final_conv,
- })
-}
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/context.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/context.rs
deleted file mode 100644
index 3d94a9f7f..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/context.rs
+++ /dev/null
@@ -1,210 +0,0 @@
-use super::*;
-use crate::array::Array;
-
-pub(super) struct QuantizerDecodeOutput<B: Backend> {
- pub(super) output: Array<B>,
- pub(super) retained_inputs: Box<[Array<B>]>,
-}
-
-impl StructuredAudioCodecGraph {
- fn conv1d_input_context<B: Backend>(layer: &StructuredAudioConv1d<B>) -> AudioResult<usize> {
- layer
- .kernel_size
- .checked_sub(1)
- .and_then(|value| value.checked_mul(layer.dilation))
- .ok_or(AudioError::Runtime("conv1d streaming context overflow".to_string()))
- }
-
- fn convtranspose_input_context<B: Backend>(
- output_context: usize,
- layer: &StructuredAudioConvTranspose1d<B>,
- ) -> AudioResult<usize> {
- let kernel_minus_one = layer.kernel_size.saturating_sub(1);
- let numerator = output_context
- .checked_add(kernel_minus_one)
- .ok_or(AudioError::Runtime("transpose streaming context overflow".to_string()))?;
- checked_div_ceil(numerator, layer.stride)
- }
-
- fn residual_unit_input_context<B: Backend>(
- output_context: usize,
- layer: &StructuredAudioResidualUnit<B>,
- ) -> AudioResult<usize> {
- let conv2 = Self::conv1d_input_context(&layer.conv2)?;
- let conv1 = Self::conv1d_input_context(&layer.conv1)?;
- output_context
- .checked_add(conv2)
- .and_then(|value| value.checked_add(conv1))
- .ok_or(AudioError::Runtime("residual-unit streaming context overflow".to_string()))
- }
-
- fn convnext_input_context<B: Backend>(
- output_context: usize,
- layer: &StructuredAudioConvNeXt<B>,
- ) -> AudioResult<usize> {
- output_context
- .checked_add(Self::conv1d_input_context(&layer.depthwise_conv)?)
- .ok_or(AudioError::Runtime("convnext streaming context overflow".to_string()))
- }
-
- fn decoder_block_input_context<B: Backend>(
- output_context: usize,
- layer: &StructuredAudioDecoderBlock<B>,
- ) -> AudioResult<usize> {
- let after_res3 = Self::residual_unit_input_context(output_context, &layer.res_unit3)?;
- let after_res2 = Self::residual_unit_input_context(after_res3, &layer.res_unit2)?;
- let after_res1 = Self::residual_unit_input_context(after_res2, &layer.res_unit1)?;
- Self::convtranspose_input_context(after_res1, &layer.trans_conv)
- }
-
- fn streaming_vocoder_context_frames<B: Backend>(
- &self,
- resources: &StructuredAudioRuntimeResources<B>,
- ) -> AudioResult<usize> {
- let vocoder = self.vocoder_graph(resources)?;
- let mut required = Self::conv1d_input_context(&vocoder.final_conv)?;
-
- for block in vocoder.decoder_blocks.iter().rev() {
- required = Self::decoder_block_input_context(required, block)?;
- }
-
- required = required
- .checked_add(Self::conv1d_input_context(&vocoder.first_conv)?)
- .ok_or(AudioError::Runtime("decoder-first streaming context overflow".to_string()))?;
-
- for (trans_conv, convnext) in vocoder.upsample_blocks.iter().rev() {
- required = Self::convnext_input_context(required, convnext)?;
- required = Self::convtranspose_input_context(required, trans_conv)?;
- }
-
- Ok(required)
- }
-
- fn post_module_streaming_context_frames(&self) -> Option<usize> {
- let mut context = 0usize;
- for layer in &self.config.quantizer_config.post_module_config.layer_configs {
- let window = layer.mixer_config.sliding_window_size()?;
- context = context.max(window.saturating_sub(1));
- }
- Some(context)
- }
-
- pub(in crate::audio::nanocodec::runtime) fn streaming_decode_context_frames<B: Backend>(
- &self,
- resources: &StructuredAudioRuntimeResources<B>,
- ) -> AudioResult<Option<usize>> {
- let vocoder_context = self.streaming_vocoder_context_frames(resources)?;
- let Some(post_module_context) = self.post_module_streaming_context_frames() else {
- return Ok(None);
- };
- Ok(Some(vocoder_context.max(post_module_context)))
- }
-
- pub(super) fn decode_quantizer_to_nsc_array_enqueued<B: Backend>(
- &self,
- resources: &StructuredAudioRuntimeResources<B>,
- encoder: &mut Encoder<B>,
- tokens: &[u32],
- lengths: &[usize],
- batch_size: usize,
- codebooks: usize,
- frames: usize,
- ) -> AudioResult<QuantizerDecodeOutput<B>> {
- if codebooks != self.total_codebooks {
- return Err(AudioError::Runtime(format!(
- "structured audio codebook mismatch: expected {}, got {codebooks}",
- self.total_codebooks
- )));
- }
- let expected_tokens = checked_product(&[batch_size, codebooks, frames])?;
- if tokens.len() != expected_tokens {
- return Err(AudioError::InvalidTokenShape {
- expected_tokens,
- actual_tokens: tokens.len(),
- });
- }
- if lengths.len() != batch_size {
- return Err(AudioError::InvalidTokenLengths {
- expected_lengths: batch_size,
- actual_lengths: lengths.len(),
- });
- }
- for &length in lengths {
- if length > frames {
- return Err(AudioError::InvalidTokenLengthValue {
- length,
- frames,
- });
- }
- }
- let quantizer_resources = self.quantizer_resources(resources)?;
- if quantizer_resources.residual_quantizers + 1 != codebooks {
- return Err(AudioError::Runtime(format!(
- "structured audio residual quantizer count mismatch: expected {}, got {}",
- codebooks.saturating_sub(1),
- quantizer_resources.residual_quantizers
- )));
- }
-
- let lengths_i32 = convert_lengths_to_i32(lengths, frames)?;
-
- let mut tokens_array = resources.token_staging(batch_size * codebooks * frames);
- tokens_array.as_slice_mut::<u32>()[..tokens.len()].copy_from_slice(tokens);
- let mut lengths_array = resources.length_staging(batch_size);
- lengths_array.as_slice_mut::<i32>()[..lengths_i32.len()].copy_from_slice(&lengths_i32);
-
- let output = unsafe {
- Array::from_allocation(
- encoder
- .allocate_scratch(size_for_shape(
- &[batch_size, frames, self.input_dim],
- quantizer_resources.data_type,
- ))
- .map_err(|err| {
- AudioError::Runtime(format!("failed to allocate structured audio quantizer output: {err}"))
- })?,
- 0,
- &[batch_size, frames, self.input_dim],
- quantizer_resources.data_type,
- )
- };
- let output_shape = output.shape().to_vec();
- let output_data_type = output.data_type();
- let mut output = output.into_allocation();
- let batch_i32 = usize_to_i32(batch_size, "batch_size")?;
- let codebooks_i32 = usize_to_i32(codebooks, "codebooks")?;
- let frames_i32 = usize_to_i32(frames, "frames")?;
- let input_dim_i32 = usize_to_i32(self.input_dim, "input_dim")?;
- let codebook_dim_i32 = usize_to_i32(quantizer_resources.codebook_dim, "codebook_dim")?;
- let residual_quantizers_i32 = usize_to_i32(quantizer_resources.residual_quantizers, "residual_quantizers")?;
- let semantic_cardinality_i32 = usize_to_i32(quantizer_resources.semantic_cardinality, "semantic_cardinality")?;
- let residual_cardinality_i32 = usize_to_i32(quantizer_resources.residual_cardinality, "residual_cardinality")?;
-
- quantizer_resources.kernel.encode(
- tokens_array.allocation(),
- lengths_array.allocation(),
- quantizer_resources.semantic_codebook.allocation(),
- quantizer_resources.semantic_out_proj.allocation(),
- quantizer_resources.semantic_out_bias.allocation(),
- quantizer_resources.residual_codebooks.allocation(),
- quantizer_resources.residual_out_proj.allocation(),
- quantizer_resources.residual_out_bias.allocation(),
- &mut output,
- batch_i32,
- codebooks_i32,
- frames_i32,
- input_dim_i32,
- codebook_dim_i32,
- residual_quantizers_i32,
- semantic_cardinality_i32,
- residual_cardinality_i32,
- encoder,
- );
- let retained_inputs = vec![tokens_array, lengths_array].into_boxed_slice();
-
- Ok(QuantizerDecodeOutput {
- output: unsafe { Array::from_allocation(output, 0, &output_shape, output_data_type) },
- retained_inputs,
- })
- }
-}
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/decode.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/decode.rs
deleted file mode 100644
index 08204c37c..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/decode.rs
+++ /dev/null
@@ -1,400 +0,0 @@
-use std::sync::mpsc::channel;
-
-use super::*;
-use crate::{array::Array, audio::nanocodec::runtime::profile::SubmittedDecodedPaddedAudio};
-
-impl StructuredAudioCodecGraph {
- fn run_residual_unit_enqueued<B: Backend>(
- &self,
- resources: &StructuredAudioRuntimeResources<B>,
- encoder: &mut Encoder<B>,
- input: &Array<B>,
- unit: &StructuredAudioResidualUnit<B>,
- lengths: &[i32],
- lengths_array: &Array<B>,
- batch_size: usize,
- channels: usize,
- seq_len: usize,
- kernels: &StructuredAudioKernelCache<B>,
- ) -> AudioResult<Array<B>> {
- let ws = &resources.decode_workspace;
- let res_snake1 = ws.next_scratch(encoder, &[batch_size, channels, seq_len], self.vocoder_data_type);
- let x = snake1d_enqueue(
- encoder,
- input,
- res_snake1,
- &unit.snake1_alpha,
- batch_size,
- channels,
- seq_len,
- self.vocoder_data_type,
- kernels,
- )?;
- let res_conv1 = ws.next_scratch(encoder, &[batch_size, channels, seq_len], self.vocoder_data_type);
- let x = causal_conv1d_grouped_enqueue(
- encoder,
- &x,
- res_conv1,
- &unit.conv1,
- SequenceLayout::Ncs,
- lengths,
- lengths_array,
- batch_size,
- seq_len,
- self.vocoder_data_type,
- kernels,
- )?;
- let res_snake2 = ws.next_scratch(encoder, &[batch_size, channels, seq_len], self.vocoder_data_type);
- let x = snake1d_enqueue(
- encoder,
- &x,
- res_snake2,
- &unit.snake2_alpha,
- batch_size,
- channels,
- seq_len,
- self.vocoder_data_type,
- kernels,
- )?;
- let res_conv2 = ws.next_scratch(encoder, &[batch_size, channels, seq_len], self.vocoder_data_type);
- causal_conv1d_grouped_residual_enqueue(
- encoder,
- &x,
- input,
- res_conv2,
- &unit.conv2,
- lengths,
- lengths_array,
- batch_size,
- seq_len,
- self.vocoder_data_type,
- kernels,
- )
- }
-
- pub(in crate::audio::nanocodec::runtime) fn submit_decode_padded<B: Backend>(
- &self,
- resources: &StructuredAudioRuntimeResources<B>,
- tokens: &[u32],
- lengths: &[usize],
- batch_size: usize,
- codebooks: usize,
- frames: usize,
- ) -> AudioResult<SubmittedDecodedPaddedAudio<B>> {
- if batch_size == 0 || frames == 0 {
- let out_lengths = lengths
- .iter()
- .map(|&length| {
- length
- .checked_mul(self.upsample_factor)
- .ok_or(AudioError::Runtime("structured audio length scaling overflow".to_string()))
- })
- .collect::<AudioResult<Vec<_>>>()?;
- return Ok(SubmittedDecodedPaddedAudio::Ready(DecodedPaddedAudio {
- samples: Vec::new(),
- channels: 1,
- frames: out_lengths.iter().copied().max().unwrap_or(0),
- lengths: out_lengths,
- }));
- }
-
- let mut lengths_i32 = lengths
- .iter()
- .map(|&length| {
- i32::try_from(length)
- .map_err(|_| AudioError::Runtime("structured audio length exceeds i32 range".to_string()))
- })
- .collect::<AudioResult<Vec<_>>>()?;
- let context = resources.context().clone();
- let mut encoder = Encoder::new(context.as_ref()).map_err(|err| {
- AudioError::Runtime(format!("failed to create structured audio decode command buffer: {err}"))
- })?;
-
- let ws = &resources.decode_workspace;
- let vocoder_graph = self.vocoder_graph(resources)?;
- let kernels = resources.kernels(self.vocoder_data_type)?;
-
- let mut x;
- let mut x_layout = SequenceLayout::Nsc;
- let quantized_nsc = self.decode_quantizer_to_nsc_array_enqueued(
- resources,
- &mut encoder,
- tokens,
- lengths,
- batch_size,
- codebooks,
- frames,
- )?;
- let retained_inputs = quantized_nsc.retained_inputs;
- x = self.apply_post_module_enqueued(
- resources,
- &mut encoder,
- quantized_nsc.output,
- lengths,
- batch_size,
- frames,
- )?;
-
- let mut current_channels = self.input_dim;
- let mut current_frames = frames;
- let mut next_lengths_i32 = vec![0_i32; lengths_i32.len()];
- let mut lengths_array = ws.lengths_array(&mut encoder, lengths_i32.len());
- lengths_array.as_slice_mut::<i32>().copy_from_slice(&lengths_i32);
- let mut next_lengths_array = ws.lengths_array(&mut encoder, lengths_i32.len());
-
- for (block_index, (trans_conv, convnext)) in vocoder_graph.upsample_blocks.iter().enumerate() {
- if trans_conv.cin != current_channels {
- return Err(AudioError::Runtime(format!(
- "structured audio upsampler input channel mismatch: expected {}, got {}",
- trans_conv.cin, current_channels
- )));
- }
- let next_frames = current_frames
- .checked_mul(trans_conv.stride)
- .ok_or(AudioError::Runtime("structured audio upsampler frame overflow".to_string()))?;
- scale_lengths_i32_in_place(&lengths_i32, &mut next_lengths_i32, trans_conv.stride)?;
- next_lengths_array.as_slice_mut::<i32>().copy_from_slice(&next_lengths_i32);
-
- let up_tconv =
- ws.next_scratch(&mut encoder, &[batch_size, trans_conv.cout, next_frames], self.vocoder_data_type);
- x = causal_conv_transpose1d_causal_pad_enqueue(
- &mut encoder,
- &x,
- up_tconv,
- trans_conv,
- &next_lengths_i32,
- batch_size,
- current_frames,
- next_frames,
- x_layout,
- &next_lengths_array,
- self.vocoder_data_type,
- &kernels,
- )
- .map_err(|err| {
- AudioError::Runtime(format!(
- "structured audio upsample block {block_index} transpose_conv failed: {err} (x_len={}, batch_size={}, cin={}, seq_len_in={}, seq_len_out={})",
- x.size(),
- batch_size,
- trans_conv.cin,
- current_frames,
- next_frames
- ))
- })?;
- x = self
- .apply_convnext_ncs_enqueued(
- resources,
- &mut encoder,
- &x,
- convnext,
- &next_lengths_i32,
- &next_lengths_array,
- batch_size,
- trans_conv.cout,
- next_frames,
- &kernels,
- )
- .map_err(|err| {
- AudioError::Runtime(format!("structured audio upsample block {block_index} convnext failed: {err}"))
- })?;
-
- x_layout = SequenceLayout::Ncs;
- current_frames = next_frames;
- current_channels = trans_conv.cout;
- std::mem::swap(&mut lengths_i32, &mut next_lengths_i32);
- std::mem::swap(&mut lengths_array, &mut next_lengths_array);
- }
-
- if vocoder_graph.first_conv.cin != current_channels {
- return Err(AudioError::Runtime(format!(
- "structured audio decoder input channels mismatch: expected {}, got {}",
- vocoder_graph.first_conv.cin, current_channels
- )));
- }
- let dec_first_conv = ws.next_scratch(
- &mut encoder,
- &[batch_size, vocoder_graph.first_conv.cout, current_frames],
- self.vocoder_data_type,
- );
- x = causal_conv1d_grouped_enqueue(
- &mut encoder,
- &x,
- dec_first_conv,
- &vocoder_graph.first_conv,
- x_layout,
- &lengths_i32,
- &lengths_array,
- batch_size,
- current_frames,
- self.vocoder_data_type,
- &kernels,
- )?;
- current_channels = vocoder_graph.first_conv.cout;
-
- for block in vocoder_graph.decoder_blocks.iter() {
- if block.trans_conv.cin != current_channels {
- return Err(AudioError::Runtime(format!(
- "structured audio decoder block input mismatch: expected {}, got {}",
- block.trans_conv.cin, current_channels
- )));
- }
- let dec_snake =
- ws.next_scratch(&mut encoder, &[batch_size, current_channels, current_frames], self.vocoder_data_type);
- x = snake1d_enqueue(
- &mut encoder,
- &x,
- dec_snake,
- &block.snake_alpha,
- batch_size,
- current_channels,
- current_frames,
- self.vocoder_data_type,
- &kernels,
- )?;
-
- let next_frames = current_frames
- .checked_mul(block.trans_conv.stride)
- .ok_or(AudioError::Runtime("structured audio decoder frame overflow".to_string()))?;
- scale_lengths_i32_in_place(&lengths_i32, &mut next_lengths_i32, block.trans_conv.stride)?;
- next_lengths_array.as_slice_mut::<i32>().copy_from_slice(&next_lengths_i32);
-
- let dec_tconv = ws.next_scratch(
- &mut encoder,
- &[batch_size, block.trans_conv.cout, next_frames],
- self.vocoder_data_type,
- );
- x = causal_conv_transpose1d_causal_pad_enqueue(
- &mut encoder,
- &x,
- dec_tconv,
- &block.trans_conv,
- &next_lengths_i32,
- batch_size,
- current_frames,
- next_frames,
- SequenceLayout::Ncs,
- &next_lengths_array,
- self.vocoder_data_type,
- &kernels,
- )?;
-
- current_frames = next_frames;
- current_channels = block.trans_conv.cout;
- std::mem::swap(&mut lengths_i32, &mut next_lengths_i32);
- std::mem::swap(&mut lengths_array, &mut next_lengths_array);
-
- x = self.run_residual_unit_enqueued(
- resources,
- &mut encoder,
- &x,
- &block.res_unit1,
- &lengths_i32,
- &lengths_array,
- batch_size,
- current_channels,
- current_frames,
- &kernels,
- )?;
- x = self.run_residual_unit_enqueued(
- resources,
- &mut encoder,
- &x,
- &block.res_unit2,
- &lengths_i32,
- &lengths_array,
- batch_size,
- current_channels,
- current_frames,
- &kernels,
- )?;
- x = self.run_residual_unit_enqueued(
- resources,
- &mut encoder,
- &x,
- &block.res_unit3,
- &lengths_i32,
- &lengths_array,
- batch_size,
- current_channels,
- current_frames,
- &kernels,
- )?;
- }
-
- let final_snake =
- ws.next_scratch(&mut encoder, &[batch_size, current_channels, current_frames], self.vocoder_data_type);
- x = snake1d_enqueue(
- &mut encoder,
- &x,
- final_snake,
- &vocoder_graph.final_snake_alpha,
- batch_size,
- current_channels,
- current_frames,
- self.vocoder_data_type,
- &kernels,
- )?;
- let final_conv = ws.next_scratch(
- &mut encoder,
- &[batch_size, vocoder_graph.final_conv.cout, current_frames],
- self.vocoder_data_type,
- );
- x = causal_conv1d_grouped_enqueue(
- &mut encoder,
- &x,
- final_conv,
- &vocoder_graph.final_conv,
- SequenceLayout::Ncs,
- &lengths_i32,
- &lengths_array,
- batch_size,
- current_frames,
- self.vocoder_data_type,
- &kernels,
- )?;
- let tanh_output = ws.next_scratch(
- &mut encoder,
- &[batch_size, vocoder_graph.final_conv.cout, current_frames],
- self.vocoder_data_type,
- );
- x = tanh_enqueue(&mut encoder, &x, tanh_output, &kernels)?;
-
- let (completion_sender, completion_notification) = channel();
- encoder.add_completion_handler({
- move |_| {
- let _ = completion_sender.send(());
- }
- });
- let out_lengths = lengths_i32
- .into_iter()
- .map(|length| {
- usize::try_from(length).map_err(|_| {
- AudioError::Runtime("structured audio decoder produced invalid negative length".to_string())
- })
- })
- .collect::<AudioResult<Vec<_>>>()?;
- let final_command_buffer = encoder.end_encoding().submit();
- Ok(SubmittedDecodedPaddedAudio::Pending {
- output: x.into_allocation(),
- retained_inputs,
- data_type: self.vocoder_data_type,
- channels: vocoder_graph.final_conv.cout,
- frames: current_frames,
- lengths: out_lengths,
- final_command_buffer,
- completion_notification,
- })
- }
-
- pub(in crate::audio::nanocodec::runtime) fn decode_padded<B: Backend>(
- &self,
- resources: &StructuredAudioRuntimeResources<B>,
- tokens: &[u32],
- lengths: &[usize],
- batch_size: usize,
- codebooks: usize,
- frames: usize,
- ) -> AudioResult<DecodedPaddedAudio> {
- self.submit_decode_padded(resources, tokens, lengths, batch_size, codebooks, frames)?.resolve()
- }
-}
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/enqueue.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/enqueue.rs
deleted file mode 100644
index 1b3fd650f..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/enqueue.rs
+++ /dev/null
@@ -1,452 +0,0 @@
-use super::*;
-use crate::{array::Array, backends::common::gpu_types::ActivationType};
-
-pub(super) fn snake1d_enqueue<B: Backend>(
- encoder: &mut Encoder<B>,
- input: &Array<B>,
- output: Array<B>,
- alpha: &Array<B>,
- batch_size: usize,
- channels: usize,
- seq_len: usize,
- data_type: DataType,
- kernels: &StructuredAudioKernelCache<B>,
-) -> AudioResult<Array<B>> {
- let expected_input = size_for_shape(&[batch_size, channels, seq_len], data_type);
- if input.size() != expected_input {
- return Err(AudioError::InvalidTokenShape {
- expected_tokens: expected_input,
- actual_tokens: input.size(),
- });
- }
- if alpha.size() != size_for_shape(&[channels], data_type) {
- return Err(AudioError::InvalidTokenShape {
- expected_tokens: channels,
- actual_tokens: alpha.num_elements(),
- });
- }
-
- let channels_i32 = usize_to_i32(channels, "channels")?;
- let seq_len_i32 = usize_to_i32(seq_len, "seq_len")?;
- let batch_i32 = usize_to_i32(batch_size, "batch_size")?;
- let output_shape = output.shape().to_vec();
- let output_data_type = output.data_type();
- let mut output = output.into_allocation();
- kernels.half_snake.encode(
- input.allocation(),
- alpha.allocation(),
- &mut output,
- channels_i32,
- seq_len_i32,
- channels_i32,
- 0.0,
- 1e-9,
- batch_i32,
- encoder,
- );
-
- Ok(unsafe { Array::from_allocation(output, 0, &output_shape, output_data_type) })
-}
-
-fn validate_grouped_conv_params<B: Backend>(
- input: &Array<B>,
- data_type: DataType,
- layer: &StructuredAudioConv1d<B>,
- lengths: &[i32],
- batch_size: usize,
- seq_len: usize,
-) -> AudioResult<()> {
- if lengths.len() != batch_size {
- return Err(AudioError::InvalidTokenLengths {
- expected_lengths: batch_size,
- actual_lengths: lengths.len(),
- });
- }
- if layer.groups == 0 || !layer.cin.is_multiple_of(layer.groups) || !layer.cout.is_multiple_of(layer.groups) {
- return Err(AudioError::InvalidTokenCardinality);
- }
- let expected_weight_shape = [layer.cout, layer.cin / layer.groups, layer.kernel_size];
- if layer.weight.size() != size_for_shape(&expected_weight_shape, data_type) {
- return Err(AudioError::Runtime(format!(
- "causal conv1d weight shape mismatch: expected {:?}",
- expected_weight_shape
- )));
- }
- if layer.bias.size() != size_for_shape(&[layer.cout], data_type) {
- return Err(AudioError::Runtime(format!("causal conv1d bias shape mismatch: expected [{}]", layer.cout)));
- }
- let expected_input = size_for_shape(&[batch_size, layer.cin, seq_len], data_type);
- if input.size() != expected_input {
- return Err(AudioError::InvalidTokenShape {
- expected_tokens: expected_input,
- actual_tokens: input.size(),
- });
- }
- Ok(())
-}
-
-pub(super) fn causal_conv1d_grouped_enqueue<B: Backend>(
- encoder: &mut Encoder<B>,
- input: &Array<B>,
- output: Array<B>,
- layer: &StructuredAudioConv1d<B>,
- input_layout: SequenceLayout,
- lengths: &[i32],
- lengths_array: &Array<B>,
- batch_size: usize,
- seq_len: usize,
- data_type: DataType,
- kernels: &StructuredAudioKernelCache<B>,
-) -> AudioResult<Array<B>> {
- validate_grouped_conv_params(input, data_type, layer, lengths, batch_size, seq_len)?;
-
- let cin_i32 = usize_to_i32(layer.cin, "cin")?;
- let cout_i32 = usize_to_i32(layer.cout, "cout")?;
- let seq_len_i32 = usize_to_i32(seq_len, "seq_len")?;
- let kernel_size_i32 = usize_to_i32(layer.kernel_size, "kernel_size")?;
- let dilation_i32 = usize_to_i32(layer.dilation, "dilation")?;
- let input_layout_i32 = input_layout.as_i32();
- let batch_i32 = usize_to_i32(batch_size, "batch_size")?;
- let output_shape = output.shape().to_vec();
- let output_data_type = output.data_type();
- let mut output = output.into_allocation();
- if layer.groups == 1 {
- kernels.causal_conv1d.encode(
- input.allocation(),
- layer.weight.allocation(),
- layer.bias.allocation(),
- &mut output,
- lengths_array.allocation(),
- cin_i32,
- cout_i32,
- seq_len_i32,
- kernel_size_i32,
- dilation_i32,
- input_layout_i32,
- batch_i32,
- encoder,
- );
- } else {
- let groups_i32 = usize_to_i32(layer.groups, "groups")?;
- kernels.causal_conv1d_grouped.encode(
- input.allocation(),
- layer.weight.allocation(),
- layer.bias.allocation(),
- &mut output,
- lengths_array.allocation(),
- cin_i32,
- cout_i32,
- seq_len_i32,
- kernel_size_i32,
- dilation_i32,
- groups_i32,
- input_layout_i32,
- batch_i32,
- encoder,
- );
- }
-
- Ok(unsafe { Array::from_allocation(output, 0, &output_shape, output_data_type) })
-}
-
-pub(super) fn causal_conv1d_grouped_residual_enqueue<B: Backend>(
- encoder: &mut Encoder<B>,
- input: &Array<B>,
- residual: &Array<B>,
- output: Array<B>,
- layer: &StructuredAudioConv1d<B>,
- lengths: &[i32],
- lengths_array: &Array<B>,
- batch_size: usize,
- seq_len: usize,
- data_type: DataType,
- kernels: &StructuredAudioKernelCache<B>,
-) -> AudioResult<Array<B>> {
- validate_grouped_conv_params(input, data_type, layer, lengths, batch_size, seq_len)?;
- let expected_residual = size_for_shape(&[batch_size, layer.cout, seq_len], data_type);
- if residual.size() != expected_residual {
- return Err(AudioError::InvalidTokenShape {
- expected_tokens: expected_residual,
- actual_tokens: residual.size(),
- });
- }
- let cin_i32 = usize_to_i32(layer.cin, "cin")?;
- let cout_i32 = usize_to_i32(layer.cout, "cout")?;
- let seq_len_i32 = usize_to_i32(seq_len, "seq_len")?;
- let kernel_size_i32 = usize_to_i32(layer.kernel_size, "kernel_size")?;
- let dilation_i32 = usize_to_i32(layer.dilation, "dilation")?;
- let groups_i32 = usize_to_i32(layer.groups, "groups")?;
- let batch_i32 = usize_to_i32(batch_size, "batch_size")?;
- let output_shape = output.shape().to_vec();
- let output_data_type = output.data_type();
- let mut output = output.into_allocation();
- kernels.causal_conv1d_grouped_residual.encode(
- input.allocation(),
- residual.allocation(),
- layer.weight.allocation(),
- layer.bias.allocation(),
- &mut output,
- lengths_array.allocation(),
- cin_i32,
- cout_i32,
- seq_len_i32,
- kernel_size_i32,
- dilation_i32,
- groups_i32,
- batch_i32,
- encoder,
- );
-
- Ok(unsafe { Array::from_allocation(output, 0, &output_shape, output_data_type) })
-}
-
-pub(super) fn causal_conv_transpose1d_causal_pad_enqueue<B: Backend>(
- encoder: &mut Encoder<B>,
- input: &Array<B>,
- output: Array<B>,
- layer: &StructuredAudioConvTranspose1d<B>,
- lengths: &[i32],
- batch_size: usize,
- seq_len_in: usize,
- seq_len_out: usize,
- input_layout: SequenceLayout,
- lengths_array: &Array<B>,
- data_type: DataType,
- kernels: &StructuredAudioKernelCache<B>,
-) -> AudioResult<Array<B>> {
- if lengths.len() != batch_size {
- return Err(AudioError::InvalidTokenLengths {
- expected_lengths: batch_size,
- actual_lengths: lengths.len(),
- });
- }
- let expected_input = size_for_shape(&[batch_size, layer.cin, seq_len_in], data_type);
- if input.size() != expected_input {
- return Err(AudioError::InvalidTokenShape {
- expected_tokens: expected_input,
- actual_tokens: input.size(),
- });
- }
- if layer.groups == 0 || !layer.cin.is_multiple_of(layer.groups) || !layer.cout.is_multiple_of(layer.groups) {
- return Err(AudioError::InvalidTokenCardinality);
- }
- let expected_weight_shape = [layer.cout, layer.cin / layer.groups, layer.kernel_size];
- if layer.weight.size() != size_for_shape(&expected_weight_shape, data_type) {
- return Err(AudioError::Runtime(format!(
- "causal transpose weight shape mismatch: expected {:?}",
- expected_weight_shape
- )));
- }
- if layer.bias.size() != size_for_shape(&[layer.cout], data_type) {
- return Err(AudioError::Runtime(format!("causal transpose bias shape mismatch: expected [{}]", layer.cout)));
- }
-
- let cin_i32 = usize_to_i32(layer.cin, "cin")?;
- let cout_i32 = usize_to_i32(layer.cout, "cout")?;
- let seq_in_i32 = usize_to_i32(seq_len_in, "seq_len_in")?;
- let seq_out_i32 = usize_to_i32(seq_len_out, "seq_len_out")?;
- let kernel_size_i32 = usize_to_i32(layer.kernel_size, "kernel_size")?;
- let stride_i32 = usize_to_i32(layer.stride, "stride")?;
- let groups_i32 = usize_to_i32(layer.groups, "groups")?;
- let input_layout_i32 = input_layout.as_i32();
- let batch_i32 = usize_to_i32(batch_size, "batch_size")?;
- let output_shape = output.shape().to_vec();
- let output_data_type = output.data_type();
- let mut output = output.into_allocation();
- kernels.causal_conv_transpose1d_causal_pad.encode(
- input.allocation(),
- layer.weight.allocation(),
- layer.bias.allocation(),
- &mut output,
- lengths_array.allocation(),
- cin_i32,
- cout_i32,
- seq_in_i32,
- seq_out_i32,
- kernel_size_i32,
- stride_i32,
- groups_i32,
- input_layout_i32,
- batch_i32,
- encoder,
- );
-
- Ok(unsafe { Array::from_allocation(output, 0, &output_shape, output_data_type) })
-}
-
-pub(super) fn conv1d_pointwise_ncs_enqueue<B: Backend>(
- encoder: &mut Encoder<B>,
- input: &Array<B>,
- output: Array<B>,
- layer: &StructuredAudioPointwiseConv<B>,
- lengths: &[i32],
- lengths_array: &Array<B>,
- batch_size: usize,
- seq_len: usize,
- data_type: DataType,
- kernels: &StructuredAudioKernelCache<B>,
-) -> AudioResult<Array<B>> {
- if lengths.len() != batch_size {
- return Err(AudioError::InvalidTokenLengths {
- expected_lengths: batch_size,
- actual_lengths: lengths.len(),
- });
- }
- let expected_input = size_for_shape(&[batch_size, layer.cin, seq_len], data_type);
- if input.size() != expected_input {
- return Err(AudioError::Runtime(format!(
- "pointwise conv input shape mismatch: expected {expected_input} bytes ([batch={batch_size}, cin={}, seq_len={seq_len}]), got {}",
- layer.cin,
- input.size()
- )));
- }
- if layer.weight.size() != size_for_shape(&[layer.cout, layer.cin], data_type) {
- return Err(AudioError::Runtime(format!(
- "pointwise conv weight shape mismatch: expected [{}, {}]",
- layer.cout, layer.cin
- )));
- }
- if layer.bias.size() != size_for_shape(&[layer.cout], data_type) {
- return Err(AudioError::Runtime(format!("pointwise conv bias shape mismatch: expected [{}]", layer.cout)));
- }
-
- let cin_i32 = usize_to_i32(layer.cin, "cin")?;
- let cout_i32 = usize_to_i32(layer.cout, "cout")?;
- let seq_len_i32 = usize_to_i32(seq_len, "seq_len")?;
- let batch_i32 = usize_to_i32(batch_size, "batch_size")?;
- let output_shape = output.shape().to_vec();
- let output_data_type = output.data_type();
- let mut output = output.into_allocation();
- kernels.conv1d.encode(
- input.allocation(),
- layer.weight.allocation(),
- layer.bias.allocation(),
- &mut output,
- lengths_array.allocation(),
- cin_i32,
- cout_i32,
- seq_len_i32,
- seq_len_i32,
- 1,
- 1,
- 1,
- 0,
- 0,
- batch_i32,
- encoder,
- );
-
- Ok(unsafe { Array::from_allocation(output, 0, &output_shape, output_data_type) })
-}
-
-pub(super) fn norm_ncs_enqueue<B: Backend>(
- encoder: &mut Encoder<B>,
- input: &Array<B>,
- output: Array<B>,
- norm: &StructuredAudioNorm<B>,
- lengths: &[i32],
- lengths_array: &Array<B>,
- batch_size: usize,
- channels: usize,
- seq_len: usize,
- data_type: DataType,
- kernels: &StructuredAudioKernelCache<B>,
-) -> AudioResult<Array<B>> {
- if lengths.len() != batch_size {
- return Err(AudioError::InvalidTokenLengths {
- expected_lengths: batch_size,
- actual_lengths: lengths.len(),
- });
- }
- let norm_data_type = DataType::F32;
- if norm.scales.size() != size_for_shape(&[channels], norm_data_type) {
- return Err(AudioError::Runtime(format!("norm scale shape mismatch: expected [{channels}]")));
- }
- if norm.bias.size() != size_for_shape(&[channels], norm_data_type) {
- return Err(AudioError::Runtime(format!("norm bias shape mismatch: expected [{channels}]")));
- }
-
- let expected_input = size_for_shape(&[batch_size, channels, seq_len], data_type);
- if input.size() != expected_input {
- return Err(AudioError::InvalidTokenShape {
- expected_tokens: expected_input,
- actual_tokens: input.size(),
- });
- }
-
- let channels_i32 = usize_to_i32(channels, "channels")?;
- let seq_len_i32 = usize_to_i32(seq_len, "seq_len")?;
- let batch_i32 = usize_to_i32(batch_size, "batch_size")?;
- let subtract_mean = if norm.subtract_mean {
- 1
- } else {
- 0
- };
- let output_shape = output.shape().to_vec();
- let output_data_type = output.data_type();
- let mut output = output.into_allocation();
- kernels.norm_ncs.encode(
- input.allocation(),
- norm.scales.allocation(),
- norm.bias.allocation(),
- &mut output,
- lengths_array.allocation(),
- channels_i32,
- seq_len_i32,
- norm.epsilon,
- subtract_mean,
- batch_i32,
- encoder,
- );
-
- Ok(unsafe { Array::from_allocation(output, 0, &output_shape, output_data_type) })
-}
-
-pub(super) fn activation_enqueue<B: Backend>(
- encoder: &mut Encoder<B>,
- input: &Array<B>,
- output: Array<B>,
- activation_type: ActivationType,
- kernels: &StructuredAudioKernelCache<B>,
-) -> AudioResult<Array<B>> {
- let n_u32 = u32::try_from(input.num_elements())
- .map_err(|_| AudioError::Runtime("activation element count exceeds u32 range".to_string()))?;
- let output_shape = output.shape().to_vec();
- let output_data_type = output.data_type();
- let mut output = output.into_allocation();
- kernels.activation.encode(Some(input.allocation()), &mut output, n_u32, activation_type, encoder);
- Ok(unsafe { Array::from_allocation(output, 0, &output_shape, output_data_type) })
-}
-
-pub(super) fn add_enqueue<B: Backend>(
- encoder: &mut Encoder<B>,
- a: &Array<B>,
- b: &Array<B>,
- output: Array<B>,
- kernels: &StructuredAudioKernelCache<B>,
-) -> AudioResult<Array<B>> {
- if a.size() != b.size() {
- return Err(AudioError::Runtime(format!("elementwise add shape mismatch: {} vs {}", a.size(), b.size())));
- }
- let n_i32 = usize_to_i32(a.num_elements(), "n")?;
- let output_shape = output.shape().to_vec();
- let output_data_type = output.data_type();
- let mut output = output.into_allocation();
- kernels.add.encode(a.allocation(), b.allocation(), &mut output, n_i32, encoder);
- Ok(unsafe { Array::from_allocation(output, 0, &output_shape, output_data_type) })
-}
-
-pub(super) fn tanh_enqueue<B: Backend>(
- encoder: &mut Encoder<B>,
- input: &Array<B>,
- output: Array<B>,
- kernels: &StructuredAudioKernelCache<B>,
-) -> AudioResult<Array<B>> {
- let n_u32 = u32::try_from(input.num_elements())
- .map_err(|_| AudioError::Runtime("tanh element count exceeds u32 range".to_string()))?;
- let output_shape = output.shape().to_vec();
- let output_data_type = output.data_type();
- let mut output = output.into_allocation();
- kernels.activation.encode(Some(input.allocation()), &mut output, n_u32, ActivationType::TANH, encoder);
- Ok(unsafe { Array::from_allocation(output, 0, &output_shape, output_data_type) })
-}
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/fishaudio.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/fishaudio.rs
deleted file mode 100644
index 8a77982f6..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/fishaudio.rs
+++ /dev/null
@@ -1,168 +0,0 @@
-use super::*;
-use crate::array::{Array, ArrayContextExt};
-
-pub(super) fn structured_audio_dtype_key(data_type: DataType) -> u8 {
- match data_type {
- DataType::F16 => 1,
- DataType::BF16 => 2,
- _ => 0,
- }
-}
-
-pub(super) struct StructuredAudioPostModuleRuntime<B: Backend> {
- pub(super) context: Rc<B::Context>,
- pub(super) model_shape: ModelShape,
- pub(super) rope_configs: Box<[AnyRoPEConfig]>,
- pub(super) layers: Box<[LayerExecutables<B>]>,
- pub(super) output_norm: RMSNorm<B>,
- pub(super) max_sequence_length: usize,
-}
-
-pub(super) struct StructuredAudioKernelCache<B: Backend> {
- pub(super) half_snake: <B::Kernels as Kernels>::AudioHalfSnakeKernel,
- pub(super) causal_conv1d: <B::Kernels as Kernels>::AudioCausalConv1dKernel,
- pub(super) causal_conv1d_grouped: <B::Kernels as Kernels>::AudioCausalConv1dGroupedKernel,
- pub(super) causal_conv1d_grouped_residual: <B::Kernels as Kernels>::AudioCausalConv1dGroupedResidualKernel,
- pub(super) causal_conv_transpose1d_causal_pad: <B::Kernels as Kernels>::AudioCausalConvTranspose1dCausalPadKernel,
- pub(super) conv1d: <B::Kernels as Kernels>::AudioConv1dKernel,
- pub(super) norm_ncs: <B::Kernels as Kernels>::AudioNormNcsKernel,
- pub(super) activation: <B::Kernels as Kernels>::ActivationKernel,
- pub(super) add: <B::Kernels as Kernels>::AudioAddKernel,
-}
-
-pub(super) struct FishAudioQuantizerResources<B: Backend> {
- pub(super) data_type: DataType,
- pub(super) codebook_dim: usize,
- pub(super) residual_quantizers: usize,
- pub(super) semantic_cardinality: usize,
- pub(super) residual_cardinality: usize,
- pub(super) kernel: <B::Kernels as Kernels>::AudioQuantizerDecodeKernel,
- pub(super) semantic_codebook: Array<B>,
- pub(super) semantic_out_proj: Array<B>,
- pub(super) semantic_out_bias: Array<B>,
- pub(super) residual_codebooks: Array<B>,
- pub(super) residual_out_proj: Array<B>,
- pub(super) residual_out_bias: Array<B>,
-}
-
-pub(super) struct DecodeWorkspace<B: Backend> {
- _marker: std::marker::PhantomData<B>,
-}
-
-impl<B: Backend> DecodeWorkspace<B> {
- fn new() -> Self {
- Self {
- _marker: std::marker::PhantomData,
- }
- }
-
- pub(super) fn lengths_array(
- &self,
- encoder: &mut Encoder<B>,
- min_elements: usize,
- ) -> Array<B> {
- let allocation = encoder
- .allocate_constant(min_elements * std::mem::size_of::<i32>())
- .expect("Failed to allocate structured audio lengths");
- unsafe { Array::from_allocation(allocation, 0, &[min_elements], DataType::I32) }
- }
-
- pub(super) fn next_scratch(
- &self,
- encoder: &mut Encoder<B>,
- shape: &[usize],
- data_type: DataType,
- ) -> Array<B> {
- let allocation =
- encoder.allocate_scratch(size_for_shape(shape, data_type)).expect("Failed to allocate scratch");
- unsafe { Array::from_allocation(allocation, 0, shape, data_type) }
- }
-}
-
-pub(in crate::audio::nanocodec::runtime) struct StructuredAudioRuntimeResources<B: Backend> {
- context: Rc<B::Context>,
- pub(super) kernels_by_dtype: RefCell<HashMap<u8, Rc<StructuredAudioKernelCache<B>>>>,
- pub(super) post_module_runtime: RefCell<Option<Rc<StructuredAudioPostModuleRuntime<B>>>>,
- pub(super) vocoder_graph: RefCell<Option<Rc<StructuredAudioDecoderGraph<B>>>>,
- pub(super) quantizer_resources: RefCell<Option<Rc<FishAudioQuantizerResources<B>>>>,
- pub(super) decode_workspace: DecodeWorkspace<B>,
-}
-
-impl<B: Backend> StructuredAudioRuntimeResources<B> {
- pub(in crate::audio::nanocodec::runtime) fn new(context: Rc<B::Context>) -> Self {
- Self {
- context,
- kernels_by_dtype: RefCell::new(HashMap::new()),
- post_module_runtime: RefCell::new(None),
- vocoder_graph: RefCell::new(None),
- quantizer_resources: RefCell::new(None),
- decode_workspace: DecodeWorkspace::new(),
- }
- }
-
- pub(super) fn context(&self) -> &Rc<B::Context> {
- &self.context
- }
-
- pub(super) fn kernels(
- &self,
- data_type: DataType,
- ) -> AudioResult<Rc<StructuredAudioKernelCache<B>>> {
- let key = structured_audio_dtype_key(data_type);
- if let Some(existing) = self.kernels_by_dtype.borrow().get(&key) {
- return Ok(existing.clone());
- }
- let created = Rc::new(build_structured_audio_kernels(&self.context, data_type)?);
- self.kernels_by_dtype.borrow_mut().insert(key, created.clone());
- Ok(created)
- }
-
- pub(super) fn token_staging(
- &self,
- min_elements: usize,
- ) -> Array<B> {
- self.context.create_array_uninitialized(&[min_elements], DataType::U32)
- }
-
- pub(super) fn length_staging(
- &self,
- min_elements: usize,
- ) -> Array<B> {
- self.context.create_array_uninitialized(&[min_elements], DataType::I32)
- }
-}
-
-pub(super) fn build_structured_audio_kernels<B: Backend>(
- context: &Rc<B::Context>,
- data_type: DataType,
-) -> AudioResult<StructuredAudioKernelCache<B>> {
- Ok(StructuredAudioKernelCache {
- half_snake: <B::Kernels as Kernels>::AudioHalfSnakeKernel::new(context.as_ref(), data_type)
- .map_err(|err| AudioError::Runtime(format!("failed to initialize snake1d kernel: {err}")))?,
- causal_conv1d: <B::Kernels as Kernels>::AudioCausalConv1dKernel::new(context.as_ref(), data_type)
- .map_err(|err| AudioError::Runtime(format!("failed to initialize causal conv1d kernel: {err}")))?,
- causal_conv1d_grouped: <B::Kernels as Kernels>::AudioCausalConv1dGroupedKernel::new(
- context.as_ref(),
- data_type,
- )
- .map_err(|err| AudioError::Runtime(format!("failed to initialize grouped causal conv1d kernel: {err}")))?,
- causal_conv1d_grouped_residual: <B::Kernels as Kernels>::AudioCausalConv1dGroupedResidualKernel::new(
- context.as_ref(),
- data_type,
- )
- .map_err(|err| AudioError::Runtime(format!("failed to initialize grouped residual conv1d kernel: {err}")))?,
- causal_conv_transpose1d_causal_pad: <B::Kernels as Kernels>::AudioCausalConvTranspose1dCausalPadKernel::new(
- context.as_ref(),
- data_type,
- )
- .map_err(|err| AudioError::Runtime(format!("failed to initialize causal transpose-conv kernel: {err}")))?,
- conv1d: <B::Kernels as Kernels>::AudioConv1dKernel::new(context.as_ref(), data_type)
- .map_err(|err| AudioError::Runtime(format!("failed to initialize conv1d kernel: {err}")))?,
- norm_ncs: <B::Kernels as Kernels>::AudioNormNcsKernel::new(context.as_ref(), data_type)
- .map_err(|err| AudioError::Runtime(format!("failed to initialize norm kernel: {err}")))?,
- activation: <B::Kernels as Kernels>::ActivationKernel::new(context.as_ref(), data_type, false)
- .map_err(|err| AudioError::Runtime(format!("failed to initialize activation kernel: {err}")))?,
- add: <B::Kernels as Kernels>::AudioAddKernel::new(context.as_ref(), data_type)
- .map_err(|err| AudioError::Runtime(format!("failed to initialize add kernel: {err}")))?,
- })
-}
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/mod.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/mod.rs
deleted file mode 100644
index 1d204b8fd..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/mod.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-use super::{
- support::{checked_div_ceil, scale_lengths_i32_in_place},
- *,
-};
-
-mod build;
-mod context;
-mod decode;
-mod enqueue;
-mod fishaudio;
-mod post_module;
-mod shared;
-
-use build::*;
-use enqueue::*;
-// Re-export to parent (runtime.rs)
-pub(in crate::audio::nanocodec::runtime) use fishaudio::StructuredAudioRuntimeResources;
-use fishaudio::*;
-pub(super) use shared::StructuredAudioCodecGraph;
-use shared::*;
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/post_module.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/post_module.rs
deleted file mode 100644
index 5cd8d35d4..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/post_module.rs
+++ /dev/null
@@ -1,462 +0,0 @@
-use super::*;
-use crate::{
- array::{Array, ArrayContextExt},
- backends::common::{Allocation, AsBufferRangeRef},
- encodable_block::{LayerArguments, PrecalculatedRope},
- forward_pass::{rope::precalculate_rope, token_inputs::TokenInputs},
-};
-
-impl StructuredAudioCodecGraph {
- pub(super) fn apply_convnext_ncs_enqueued<B: Backend>(
- &self,
- resources: &StructuredAudioRuntimeResources<B>,
- encoder: &mut Encoder<B>,
- input: &Array<B>,
- layer: &StructuredAudioConvNeXt<B>,
- lengths: &[i32],
- lengths_array: &Array<B>,
- batch_size: usize,
- channels: usize,
- seq_len: usize,
- kernels: &StructuredAudioKernelCache<B>,
- ) -> AudioResult<Array<B>> {
- let ws = &resources.decode_workspace;
-
- let cnxt_dw = ws.next_scratch(encoder, &[batch_size, channels, seq_len], self.vocoder_data_type);
- let x = causal_conv1d_grouped_enqueue(
- encoder,
- input,
- cnxt_dw,
- &layer.depthwise_conv,
- SequenceLayout::Ncs,
- lengths,
- lengths_array,
- batch_size,
- seq_len,
- self.vocoder_data_type,
- kernels,
- )?;
- let cnxt_norm = ws.next_scratch(encoder, &[batch_size, channels, seq_len], self.vocoder_data_type);
- let x = norm_ncs_enqueue(
- encoder,
- &x,
- cnxt_norm,
- &layer.norm,
- lengths,
- lengths_array,
- batch_size,
- channels,
- seq_len,
- self.vocoder_data_type,
- kernels,
- )?;
- let cnxt_pw1 = ws.next_scratch(encoder, &[batch_size, layer.pwconv1.cout, seq_len], self.vocoder_data_type);
- let x = conv1d_pointwise_ncs_enqueue(
- encoder,
- &x,
- cnxt_pw1,
- &layer.pwconv1,
- lengths,
- lengths_array,
- batch_size,
- seq_len,
- self.vocoder_data_type,
- kernels,
- )?;
- let cnxt_activation =
- ws.next_scratch(encoder, &[batch_size, layer.pwconv1.cout, seq_len], self.vocoder_data_type);
- let x = activation_enqueue(encoder, &x, cnxt_activation, layer.activation_type, kernels)?;
- let cnxt_pw2 = ws.next_scratch(encoder, &[batch_size, layer.pwconv2.cout, seq_len], self.vocoder_data_type);
- let x = conv1d_pointwise_ncs_enqueue(
- encoder,
- &x,
- cnxt_pw2,
- &layer.pwconv2,
- lengths,
- lengths_array,
- batch_size,
- seq_len,
- self.vocoder_data_type,
- kernels,
- )?;
- let cnxt_add = ws.next_scratch(encoder, &[batch_size, layer.pwconv2.cout, seq_len], self.vocoder_data_type);
- add_enqueue(encoder, &x, input, cnxt_add, kernels)
- }
-
- pub(super) fn build_post_module_runtime<B: Backend>(
- &self,
- context: Rc<B::Context>,
- required_sequence_length: usize,
- ) -> AudioResult<StructuredAudioPostModuleRuntime<B>> {
- let decoder_config = Rc::new(DecoderConfig {
- embedding_config: AnyEmbeddingConfig::UntiedEmbeddingConfig(UntiedEmbeddingConfig::new(None, None)),
- transformer_config: self.config.quantizer_config.post_module_config.clone(),
- vocab_size: 1,
- ple_model_config: None,
- });
- let model_shape = ModelShape::from_decoder_config(&decoder_config, self.vocoder_data_type);
-
- let weights_file = File::open(self.weights_path.as_str()).map_err(|err| {
- AudioError::Runtime(format!("failed to open post_module weights '{}': {err}", self.weights_path))
- })?;
- let loader = ParameterLoader::new(&weights_file, context.as_ref()).map_err(|err| {
- AudioError::Runtime(format!("failed to load post_module weights '{}': {err}", self.weights_path))
- })?;
- let root_loader_view = loader.tree();
- let transformer_subtree_name = "audio_decoder.quantizer.post_module";
-
- let max_sequence_length =
- decoder_config.transformer_config.max_sequence_length().unwrap_or(0).max(required_sequence_length.max(1));
- let (rope_configs, layers, output_norm) = Decoder::build_transformer_layers_and_norm(
- context.as_ref(),
- &decoder_config,
- &root_loader_view,
- transformer_subtree_name,
- None,
- &model_shape,
- )
- .map_err(|error| AudioError::Runtime(format!("failed to build structured audio post_module: {error}")))?;
-
- Ok(StructuredAudioPostModuleRuntime {
- context,
- model_shape,
- rope_configs,
- layers,
- output_norm,
- max_sequence_length,
- })
- }
-
- pub(super) fn post_module_runtime<B: Backend>(
- &self,
- resources: &StructuredAudioRuntimeResources<B>,
- required_sequence_length: usize,
- ) -> AudioResult<Rc<StructuredAudioPostModuleRuntime<B>>> {
- {
- let cached = resources.post_module_runtime.borrow();
- if let Some(runtime) = cached.as_ref()
- && runtime.max_sequence_length >= required_sequence_length.max(1)
- {
- return Ok(runtime.clone());
- }
- }
- let runtime = Rc::new(self.build_post_module_runtime(resources.context().clone(), required_sequence_length)?);
- *resources.post_module_runtime.borrow_mut() = Some(runtime.clone());
- Ok(runtime)
- }
-
- pub(super) fn build_quantizer_resources<B: Backend>(
- &self,
- context: &Rc<B::Context>,
- ) -> AudioResult<FishAudioQuantizerResources<B>> {
- if self.semantic_codebook_size == 0 || self.codebook_size == 0 {
- return Err(AudioError::InvalidTokenCardinality);
- }
- let data_type = self.vocoder_data_type;
- let kernel = <B::Kernels as Kernels>::AudioQuantizerDecodeKernel::new(context.as_ref(), data_type)
- .map_err(|err| AudioError::Runtime(format!("failed to initialize quantizer decode kernel: {err}")))?;
- let weights_file = File::open(self.weights_path.as_str()).map_err(|err| {
- AudioError::Runtime(format!("failed to open structured audio weights '{}': {err}", self.weights_path))
- })?;
- let loader = ParameterLoader::new(&weights_file, context.as_ref()).map_err(|err| {
- AudioError::Runtime(format!("failed to load structured audio weights '{}': {err}", self.weights_path))
- })?;
- let root = loader.tree();
- let audio_decoder_tree = root.subtree("audio_decoder")?;
- let quantizer_tree = audio_decoder_tree.subtree("quantizer")?;
- let semantic_tree = quantizer_tree.subtree("semantic_quantizer")?.subtree("quantizers")?.subtree("0")?;
- let codebook_dim = self.config.codebook_dim;
- let semantic_codebook = semantic_tree
- .leaf("codebook.embedding.weights")?
- .validate(&[self.semantic_codebook_size, codebook_dim], data_type)?
- .read_array()?;
- let semantic_out_proj = semantic_tree
- .leaf("out_proj.weights.weights")?
- .validate(&[self.input_dim, codebook_dim], data_type)?
- .read_array()?;
- let semantic_out_bias =
- semantic_tree.leaf("out_proj.biases")?.validate(&[self.input_dim], data_type)?.read_array()?;
-
- let residual_quantizers = self.config.n_codebooks;
- let residual_count_for_shape = residual_quantizers.max(1);
- let residual_codebook_rows_for_shape = self.codebook_size.max(1);
- let mut residual_codebooks = context
- .create_array_zeros(&[residual_count_for_shape, residual_codebook_rows_for_shape, codebook_dim], data_type);
- let mut residual_out_proj =
- context.create_array_zeros(&[residual_count_for_shape, self.input_dim, codebook_dim], data_type);
- let mut residual_out_bias = context.create_array_zeros(&[residual_count_for_shape, self.input_dim], data_type);
-
- let residual_root = quantizer_tree.subtree("quantizer")?.subtree("quantizers")?;
- for index in 0..residual_quantizers {
- let quantizer_tree = residual_root.subtree(&index.to_string())?;
- let codebook = quantizer_tree
- .leaf("codebook.embedding.weights")?
- .validate(&[self.codebook_size, codebook_dim], data_type)?
- .read_array()?;
- let out_proj = quantizer_tree
- .leaf("out_proj.weights.weights")?
- .validate(&[self.input_dim, codebook_dim], data_type)?
- .read_array()?;
- let out_bias =
- quantizer_tree.leaf("out_proj.biases")?.validate(&[self.input_dim], data_type)?.read_array()?;
-
- copy_to_outer_axis_slice(&mut residual_codebooks, index, &codebook, &[self.codebook_size, codebook_dim])?;
- copy_to_outer_axis_slice(&mut residual_out_proj, index, &out_proj, &[self.input_dim, codebook_dim])?;
- copy_to_outer_axis_slice(&mut residual_out_bias, index, &out_bias, &[self.input_dim])?;
- }
-
- Ok(FishAudioQuantizerResources {
- data_type,
- codebook_dim,
- residual_quantizers,
- semantic_cardinality: self.semantic_codebook_size,
- residual_cardinality: self.codebook_size,
- kernel,
- semantic_codebook,
- semantic_out_proj,
- semantic_out_bias,
- residual_codebooks,
- residual_out_proj,
- residual_out_bias,
- })
- }
-
- pub(super) fn quantizer_resources<B: Backend>(
- &self,
- resources: &StructuredAudioRuntimeResources<B>,
- ) -> AudioResult<Rc<FishAudioQuantizerResources<B>>> {
- if let Some(existing) = resources.quantizer_resources.borrow().as_ref() {
- return Ok(existing.clone());
- }
- let created = Rc::new(self.build_quantizer_resources(resources.context())?);
- *resources.quantizer_resources.borrow_mut() = Some(created.clone());
- Ok(created)
- }
-
- pub(super) fn build_vocoder_graph<B: Backend>(
- &self,
- context: &Rc<B::Context>,
- ) -> AudioResult<StructuredAudioDecoderGraph<B>> {
- let weights_file = File::open(self.weights_path.as_str()).map_err(|err| {
- AudioError::Runtime(format!("failed to open structured audio weights '{}': {err}", self.weights_path))
- })?;
- let loader = ParameterLoader::new(&weights_file, context.as_ref()).map_err(|err| {
- AudioError::Runtime(format!("failed to load structured audio weights '{}': {err}", self.weights_path))
- })?;
- let root = loader.tree();
- build_vocoder_graph_from_tree::<B>(context, &root, &self.config, self.vocoder_data_type)
- }
-
- pub(super) fn vocoder_graph<B: Backend>(
- &self,
- resources: &StructuredAudioRuntimeResources<B>,
- ) -> AudioResult<Rc<StructuredAudioDecoderGraph<B>>> {
- if let Some(existing) = resources.vocoder_graph.borrow().as_ref() {
- return Ok(existing.clone());
- }
- let created = Rc::new(self.build_vocoder_graph(resources.context())?);
- *resources.vocoder_graph.borrow_mut() = Some(created.clone());
- Ok(created)
- }
-
- pub(super) fn encode_post_module_layers<B: Backend>(
- runtime: &StructuredAudioPostModuleRuntime<B>,
- token_inputs: &TokenInputs<B>,
- batch_dim: usize,
- main: Allocation<B>,
- encoder: &mut Encoder<B>,
- ) -> AudioResult<Allocation<B>> {
- let mut main = main;
- let mut shortcut = encoder
- .allocate_scratch(main.as_buffer_range_ref().range().len())
- .map_err(|err| AudioError::Runtime(format!("post_module shortcut allocation failed: {err}")))?;
- let ropes = runtime
- .rope_configs
- .iter()
- .map(|rope_config| {
- let (sines, cosines) = precalculate_rope(rope_config, token_inputs.token_positions());
- let mut sines_allocation = encoder
- .allocate_constant(sines.len() * std::mem::size_of::<f32>())
- .map_err(|err| AudioError::Runtime(format!("post_module rope sines allocation failed: {err}")))?;
- sines_allocation.copyin(sines.as_ref());
- let mut cosines_allocation = encoder
- .allocate_constant(cosines.len() * std::mem::size_of::<f32>())
- .map_err(|err| AudioError::Runtime(format!("post_module rope cosines allocation failed: {err}")))?;
- cosines_allocation.copyin(cosines.as_ref());
- Ok(PrecalculatedRope {
- cosines: cosines_allocation,
- sines: sines_allocation,
- dim: *rope_config.head_dim(),
- })
- })
- .collect::<AudioResult<Box<[_]>>>()?;
- for layer in runtime.layers.iter() {
- main = layer
- .encode(
- LayerArguments {
- batch_dim,
- token_parents: token_inputs.token_parents(),
- token_subtrie_ranges: None,
- rope: layer.rope_kind.get(&ropes),
- per_layer_inputs: None,
- sampling_start: 0,
- sampling_length: batch_dim,
- cache_access: None,
- #[cfg(feature = "tracing")]
- trace: None,
- },
- main,
- &mut shortcut,
- encoder,
- )
- .map_err(|err| AudioError::Runtime(format!("post_module layer encode failed: {err}")))?;
- }
- runtime
- .output_norm
- .encode(&main, 0, batch_dim, Some(&mut shortcut), encoder)
- .map_err(|err| AudioError::Runtime(format!("post_module output norm encode failed: {err}")))
- }
-
- pub(super) fn apply_post_module_single_batch_enqueued<B: Backend>(
- &self,
- resources: &StructuredAudioRuntimeResources<B>,
- encoder: &mut Encoder<B>,
- latent_nsc: Array<B>,
- frames: usize,
- ) -> AudioResult<Array<B>> {
- if frames == 0 {
- return Ok(latent_nsc);
- }
-
- let expected_size = size_for_shape(&[frames, self.input_dim], self.vocoder_data_type);
- if latent_nsc.size() != expected_size {
- return Err(AudioError::InvalidTokenShape {
- expected_tokens: expected_size,
- actual_tokens: latent_nsc.size(),
- });
- }
-
- let runtime = self.post_module_runtime(resources, frames.max(1))?;
- let token_ids = vec![0_u64; frames];
- let token_positions = (0..frames).collect::<Vec<_>>();
- let token_inputs = TokenInputs::new_classifier(runtime.context.as_ref(), &token_ids, &token_positions);
- let main =
- Self::encode_post_module_layers(&runtime, &token_inputs, frames, latent_nsc.into_allocation(), encoder)?;
- Ok(unsafe { Array::from_allocation(main, 0, &[frames, self.input_dim], self.vocoder_data_type) })
- }
-
- pub(super) fn apply_post_module_enqueued<B: Backend>(
- &self,
- resources: &StructuredAudioRuntimeResources<B>,
- encoder: &mut Encoder<B>,
- latent_nsc: Array<B>,
- lengths: &[usize],
- batch_size: usize,
- frames: usize,
- ) -> AudioResult<Array<B>> {
- if lengths.len() != batch_size {
- return Err(AudioError::InvalidTokenLengths {
- expected_lengths: batch_size,
- actual_lengths: lengths.len(),
- });
- }
- let expected_size = size_for_shape(&[batch_size, frames, self.input_dim], self.vocoder_data_type);
- if latent_nsc.size() != expected_size {
- return Err(AudioError::InvalidTokenShape {
- expected_tokens: expected_size,
- actual_tokens: latent_nsc.size(),
- });
- }
- let mut batch_indices_by_length = BTreeMap::<usize, Vec<usize>>::new();
- for (batch_index, &active_len) in lengths.iter().enumerate() {
- if active_len == 0 {
- continue;
- }
- if active_len > frames {
- return Err(AudioError::InvalidTokenLengthValue {
- length: active_len,
- frames,
- });
- }
- batch_indices_by_length.entry(active_len).or_default().push(batch_index);
- }
- if frames == 0 {
- return Ok(latent_nsc);
- }
- if batch_size == 1 && lengths.first().copied() == Some(frames) {
- return self.apply_post_module_single_batch_enqueued(resources, encoder, latent_nsc, frames);
- }
-
- let mut output = encoder.allocate_scratch(expected_size).map_err(|err| {
- AudioError::Runtime(format!("failed to allocate structured audio post_module output: {err}"))
- })?;
- if batch_indices_by_length.is_empty() {
- encoder.encode_copy(
- latent_nsc.allocation(),
- latent_nsc.offset()..latent_nsc.offset() + latent_nsc.size(),
- &mut output,
- 0..latent_nsc.size(),
- );
- return Ok(unsafe {
- Array::from_allocation(output, 0, &[batch_size, frames, self.input_dim], self.vocoder_data_type)
- });
- }
-
- let full_copy_bytes = latent_nsc.size();
- let batch_stride_bytes = size_for_shape(&[frames, self.input_dim], self.vocoder_data_type);
- let mut copied_output_prefix = false;
- for (active_len, batch_indices) in batch_indices_by_length {
- let runtime = self.post_module_runtime(resources, active_len.max(1))?;
- let token_ids = vec![0_u64; active_len];
- let token_positions = (0..active_len).collect::<Vec<_>>();
- let token_inputs = TokenInputs::new_classifier(runtime.context.as_ref(), &token_ids, &token_positions);
-
- let main_shape = runtime.model_shape.main_shape(active_len);
- if main_shape != [active_len, self.input_dim] {
- return Err(AudioError::Runtime(format!(
- "post_module main shape mismatch: expected [{active_len}, {}], got [{}, {}]",
- self.input_dim, main_shape[0], main_shape[1]
- )));
- }
- if runtime.model_shape.data_type != self.vocoder_data_type {
- return Err(AudioError::Runtime(format!(
- "post_module dtype mismatch: main={:?}, latent={:?}",
- runtime.model_shape.data_type, self.vocoder_data_type
- )));
- }
-
- for &batch_index in &batch_indices {
- if !copied_output_prefix {
- encoder.encode_copy(
- latent_nsc.allocation(),
- latent_nsc.offset()..latent_nsc.offset() + full_copy_bytes,
- &mut output,
- 0..full_copy_bytes,
- );
- copied_output_prefix = true;
- }
- let source_range =
- array_batch_byte_range(&latent_nsc, batch_index, frames, self.input_dim, active_len)?;
- let main_array = resources.decode_workspace.next_scratch(
- encoder,
- &[active_len, self.input_dim],
- self.vocoder_data_type,
- );
- let mut main = main_array.into_allocation();
- let source_size = source_range.end - source_range.start;
- encoder.encode_copy(latent_nsc.allocation(), source_range, &mut main, 0..source_size);
- let main = Self::encode_post_module_layers(&runtime, &token_inputs, active_len, main, encoder)?;
- let destination_offset = batch_index * batch_stride_bytes;
- let active_bytes = active_len * self.input_dim * self.vocoder_data_type.size_in_bytes();
- encoder.encode_copy(
- &main,
- 0..active_bytes,
- &mut output,
- destination_offset..destination_offset + active_bytes,
- );
- }
- }
-
- Ok(unsafe { Array::from_allocation(output, 0, &[batch_size, frames, self.input_dim], self.vocoder_data_type) })
- }
-}
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/shared.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/shared.rs
deleted file mode 100644
index a37a2830d..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/shared.rs
+++ /dev/null
@@ -1,125 +0,0 @@
-use std::ops::Range;
-
-use super::*;
-use crate::{array::Array, backends::common::gpu_types::ActivationType};
-
-pub(super) fn array_batch_byte_range<B: Backend>(
- array: &Array<B>,
- batch_index: usize,
- frames: usize,
- channels: usize,
- active_frames: usize,
-) -> AudioResult<Range<usize>> {
- let batch_stride_bytes = size_for_shape(&[frames, channels], array.data_type());
- let batch_offset = batch_index
- .checked_mul(batch_stride_bytes)
- .and_then(|value| value.checked_add(array.offset()))
- .ok_or(AudioError::Runtime("array batch range offset overflow".to_string()))?;
- if active_frames > frames {
- return Err(AudioError::Runtime("array batch range active_frames exceeds frames".to_string()));
- }
- let byte_len = size_for_shape(&[active_frames, channels], array.data_type());
- let end =
- batch_offset.checked_add(byte_len).ok_or(AudioError::Runtime("array batch range end overflow".to_string()))?;
- Ok(batch_offset..end)
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(super) enum SequenceLayout {
- Ncs,
- Nsc,
-}
-
-impl SequenceLayout {
- pub(super) fn as_i32(self) -> i32 {
- match self {
- Self::Ncs => 0,
- Self::Nsc => 1,
- }
- }
-}
-
-#[derive(Debug, Clone, PartialEq)]
-pub struct StructuredAudioCodecGraph {
- pub(in crate::audio::nanocodec::runtime) config: DescriptAudioCodecConfig,
- pub(in crate::audio::nanocodec::runtime) weights_path: String,
- pub(in crate::audio::nanocodec::runtime) codebook_size: usize,
- pub(in crate::audio::nanocodec::runtime) semantic_codebook_size: usize,
- pub(in crate::audio::nanocodec::runtime) input_dim: usize,
- pub(in crate::audio::nanocodec::runtime) total_codebooks: usize,
- pub(in crate::audio::nanocodec::runtime) upsample_factor: usize,
- pub(in crate::audio::nanocodec::runtime) vocoder_data_type: DataType,
-}
-
-#[derive(Debug)]
-pub(super) struct StructuredAudioConv1d<B: Backend> {
- pub(super) weight: Array<B>,
- pub(super) bias: Array<B>,
- pub(super) cin: usize,
- pub(super) cout: usize,
- pub(super) kernel_size: usize,
- pub(super) dilation: usize,
- pub(super) groups: usize,
-}
-
-#[derive(Debug)]
-pub(super) struct StructuredAudioConvTranspose1d<B: Backend> {
- pub(super) weight: Array<B>,
- pub(super) bias: Array<B>,
- pub(super) cin: usize,
- pub(super) cout: usize,
- pub(super) kernel_size: usize,
- pub(super) stride: usize,
- pub(super) groups: usize,
-}
-
-#[derive(Debug)]
-pub(super) struct StructuredAudioPointwiseConv<B: Backend> {
- pub(super) weight: Array<B>,
- pub(super) bias: Array<B>,
- pub(super) cin: usize,
- pub(super) cout: usize,
-}
-
-#[derive(Debug)]
-pub(super) struct StructuredAudioNorm<B: Backend> {
- pub(super) scales: Array<B>,
- pub(super) bias: Array<B>,
- pub(super) epsilon: f32,
- pub(super) subtract_mean: bool,
-}
-
-#[derive(Debug)]
-pub(super) struct StructuredAudioConvNeXt<B: Backend> {
- pub(super) activation_type: ActivationType,
- pub(super) depthwise_conv: StructuredAudioConv1d<B>,
- pub(super) norm: StructuredAudioNorm<B>,
- pub(super) pwconv1: StructuredAudioPointwiseConv<B>,
- pub(super) pwconv2: StructuredAudioPointwiseConv<B>,
-}
-
-#[derive(Debug)]
-pub(super) struct StructuredAudioResidualUnit<B: Backend> {
- pub(super) snake1_alpha: Array<B>,
- pub(super) conv1: StructuredAudioConv1d<B>,
- pub(super) snake2_alpha: Array<B>,
- pub(super) conv2: StructuredAudioConv1d<B>,
-}
-
-#[derive(Debug)]
-pub(super) struct StructuredAudioDecoderBlock<B: Backend> {
- pub(super) snake_alpha: Array<B>,
- pub(super) trans_conv: StructuredAudioConvTranspose1d<B>,
- pub(super) res_unit1: StructuredAudioResidualUnit<B>,
- pub(super) res_unit2: StructuredAudioResidualUnit<B>,
- pub(super) res_unit3: StructuredAudioResidualUnit<B>,
-}
-
-#[derive(Debug)]
-pub(super) struct StructuredAudioDecoderGraph<B: Backend> {
- pub(super) first_conv: StructuredAudioConv1d<B>,
- pub(super) upsample_blocks: Vec<(StructuredAudioConvTranspose1d<B>, StructuredAudioConvNeXt<B>)>,
- pub(super) decoder_blocks: Vec<StructuredAudioDecoderBlock<B>>,
- pub(super) final_snake_alpha: Array<B>,
- pub(super) final_conv: StructuredAudioConv1d<B>,
-}
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/support.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/support.rs
deleted file mode 100644
index 08e8198c6..000000000
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/support.rs
+++ /dev/null
@@ -1,82 +0,0 @@
-use super::*;
-
-#[derive(Debug, Clone, PartialEq)]
-pub struct DecodedPaddedAudio {
- pub samples: Vec<f32>,
- pub channels: usize,
- pub frames: usize,
- pub lengths: Vec<usize>,
-}
-
-pub(in crate::audio::nanocodec::runtime) fn checked_product(values: &[usize]) -> AudioResult<usize> {
- values
- .iter()
- .try_fold(1usize, |acc, &value| acc.checked_mul(value))
- .ok_or(AudioError::Runtime("dimension product overflow".to_string()))
-}
-
-pub(in crate::audio::nanocodec::runtime) fn usize_to_i32(
- value: usize,
- name: &str,
-) -> AudioResult<i32> {
- i32::try_from(value).map_err(|_| AudioError::Runtime(format!("{name} exceeds i32 range")))
-}
-
-pub(in crate::audio::nanocodec::runtime) fn convert_lengths_to_i32(
- lengths: &[usize],
- frames: usize,
-) -> AudioResult<Vec<i32>> {
- let mut out = Vec::with_capacity(lengths.len());
- for &length in lengths {
- if length > frames {
- return Err(AudioError::InvalidTokenLengthValue {
- length,
- frames,
- });
- }
- out.push(usize_to_i32(length, "length")?);
- }
- Ok(out)
-}
-
-pub(in crate::audio::nanocodec::runtime) fn checked_mul_i32(
- value: i32,
- mul: usize,
-) -> AudioResult<i32> {
- i32::try_from(mul)
- .map_err(|_| AudioError::Runtime("length scaling factor exceeds i32 range".to_string()))?
- .checked_mul(value)
- .ok_or(AudioError::Runtime("scaled length overflow".to_string()))
-}
-
-pub(in crate::audio::nanocodec::runtime) fn checked_div_ceil(
- numerator: usize,
- denominator: usize,
-) -> AudioResult<usize> {
- if denominator == 0 {
- return Err(AudioError::Runtime("division by zero".to_string()));
- }
- let addend = denominator.saturating_sub(1);
- numerator
- .checked_add(addend)
- .ok_or(AudioError::Runtime("ceil-division overflow".to_string()))
- .map(|value| value / denominator)
-}
-
-pub(in crate::audio::nanocodec::runtime) fn scale_lengths_i32_in_place(
- source: &[i32],
- destination: &mut [i32],
- factor: usize,
-) -> AudioResult<()> {
- if destination.len() != source.len() {
- return Err(AudioError::Runtime(format!(
- "scaled length buffer mismatch: expected {}, got {}",
- source.len(),
- destination.len()
- )));
- }
- for (dst, &src) in destination.iter_mut().zip(source.iter()) {
- *dst = checked_mul_i32(src, factor)?;
- }
- Ok(())
-}
diff --git a/crates/backend-uzu/src/audio/types.rs b/crates/backend-uzu/src/audio/types.rs
deleted file mode 100644
index c0e4ddeef..000000000
--- a/crates/backend-uzu/src/audio/types.rs
+++ /dev/null
@@ -1,231 +0,0 @@
-#[cfg(metal_backend)]
-use std::num::{NonZeroU32, NonZeroUsize};
-
-use crate::{backends::common::Backend, parameters::ParameterLoaderError};
-
-#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
-pub enum AudioError {
- #[error("sample_rate must be > 0")]
- InvalidSampleRate,
- #[error("channels must be > 0")]
- InvalidChannelCount,
- #[error("pcm samples shape mismatch: expected {expected_samples} samples, got {actual_samples}")]
- InvalidPcmShape {
- expected_samples: usize,
- actual_samples: usize,
- },
- #[error("token lengths shape mismatch: expected {expected_lengths} lengths, got {actual_lengths}")]
- InvalidTokenLengths {
- expected_lengths: usize,
- actual_lengths: usize,
- },
- #[error("token grid shape mismatch: expected {expected_tokens} tokens, got {actual_tokens}")]
- InvalidTokenShape {
- expected_tokens: usize,
- actual_tokens: usize,
- },
- #[error("token length {length} exceeds frame count {frames}")]
- InvalidTokenLengthValue {
- length: usize,
- frames: usize,
- },
- #[error("audio token cardinality must be > 0")]
- InvalidTokenCardinality,
- #[error("codec token {token} is outside codec range 0..{cardinality}")]
- InvalidCodecToken {
- token: u32,
- cardinality: u32,
- },
- #[error("model token {token} is outside audio model range {range_start}..={range_end}")]
- InvalidModelToken {
- token: u64,
- range_start: u64,
- range_end: u64,
- },
- #[error("tokenizer operation failed: {0}")]
- Tokenizer(String),
- #[error("audio runtime rejected input: {0}")]
- Runtime(String),
-}
-
-#[cfg(metal_backend)]
-pub type AudioResult<T> = Result<T, AudioError>;
-
-impl<B: Backend> From<ParameterLoaderError<B>> for AudioError {
- fn from(value: ParameterLoaderError<B>) -> Self {
- Self::Runtime(value.to_string())
- }
-}
-
-#[cfg(metal_backend)]
-#[derive(Debug, Clone, PartialEq)]
-pub struct AudioPcmBatch {
- samples: Box<[f32]>,
- sample_rate: NonZeroU32,
- channels: NonZeroUsize,
- lengths: Box<[usize]>,
-}
-
-#[cfg(metal_backend)]
-impl AudioPcmBatch {
- pub fn new(
- samples: Box<[f32]>,
- sample_rate: u32,
- channels: usize,
- lengths: Box<[usize]>,
- ) -> AudioResult<Self> {
- let sample_rate = NonZeroU32::new(sample_rate).ok_or(AudioError::InvalidSampleRate)?;
- let channels = NonZeroUsize::new(channels).ok_or(AudioError::InvalidChannelCount)?;
- let expected_samples = lengths.iter().sum::<usize>() * channels.get();
- if samples.len() != expected_samples {
- return Err(AudioError::InvalidPcmShape {
- expected_samples,
- actual_samples: samples.len(),
- });
- }
-
- Ok(Self {
- samples,
- sample_rate,
- channels,
- lengths,
- })
- }
-
- pub fn batch_size(&self) -> usize {
- self.lengths.len()
- }
-
- pub fn sample_rate(&self) -> u32 {
- self.sample_rate.get()
- }
-
- pub fn channels(&self) -> usize {
- self.channels.get()
- }
-
- pub fn lengths(&self) -> &[usize] {
- &self.lengths
- }
-
- pub fn total_frames(&self) -> usize {
- self.lengths.iter().sum()
- }
-
- pub fn samples(&self) -> &[f32] {
- &self.samples
- }
-
- pub fn into_parts(self) -> (Box<[f32]>, u32, usize, Box<[usize]>) {
- (self.samples, self.sample_rate.get(), self.channels.get(), self.lengths)
- }
-}
-
-#[cfg(metal_backend)]
-#[derive(Debug, Clone, PartialEq)]
-pub struct AudioTokenGrid {
- tokens: Box<[u32]>,
- batch_size: usize,
- codebooks: usize,
- frames: usize,
- lengths: Box<[usize]>,
-}
-
-#[cfg(metal_backend)]
-impl AudioTokenGrid {
- pub fn new(
- tokens: Box<[u32]>,
- batch_size: usize,
- codebooks: usize,
- frames: usize,
- lengths: Box<[usize]>,
- ) -> AudioResult<Self> {
- if codebooks == 0 {
- return Err(AudioError::InvalidTokenCardinality);
- }
- if lengths.len() != batch_size {
- return Err(AudioError::InvalidTokenLengths {
- expected_lengths: batch_size,
- actual_lengths: lengths.len(),
- });
- }
- for &length in lengths.iter() {
- if length > frames {
- return Err(AudioError::InvalidTokenLengthValue {
- length,
- frames,
- });
- }
- }
-
- let expected_tokens = batch_size.checked_mul(codebooks).and_then(|n| n.checked_mul(frames)).ok_or(
- AudioError::InvalidTokenShape {
- expected_tokens: usize::MAX,
- actual_tokens: tokens.len(),
- },
- )?;
-
- if tokens.len() != expected_tokens {
- return Err(AudioError::InvalidTokenShape {
- expected_tokens,
- actual_tokens: tokens.len(),
- });
- }
-
- Ok(Self {
- tokens,
- batch_size,
- codebooks,
- frames,
- lengths,
- })
- }
-
- pub fn batch_size(&self) -> usize {
- self.batch_size
- }
-
- pub fn codebooks(&self) -> usize {
- self.codebooks
- }
-
- pub fn frames(&self) -> usize {
- self.frames
- }
-
- pub fn lengths(&self) -> &[usize] {
- &self.lengths
- }
-
- pub fn tokens(&self) -> &[u32] {
- &self.tokens
- }
-
- pub fn into_parts(self) -> (Box<[u32]>, usize, usize, usize, Box<[usize]>) {
- (self.tokens, self.batch_size, self.codebooks, self.frames, self.lengths)
- }
-
- pub fn get(
- &self,
- batch: usize,
- codebook: usize,
- frame: usize,
- ) -> u32 {
- let index = Self::token_index(self.codebooks, self.frames, batch, codebook, frame);
- self.tokens[index]
- }
-
- fn token_index(
- codebooks: usize,
- frames: usize,
- batch: usize,
- codebook: usize,
- frame: usize,
- ) -> usize {
- ((batch * codebooks + codebook) * frames) + frame
- }
-}
-
-#[cfg(all(metal_backend, test))]
-#[path = "../../unit/audio/types_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/backends/common/allocator/allocator.rs b/crates/backend-uzu/src/backends/common/allocator/allocator.rs
index fd8262595..8d97cf26d 100644
--- a/crates/backend-uzu/src/backends/common/allocator/allocator.rs
+++ b/crates/backend-uzu/src/backends/common/allocator/allocator.rs
@@ -5,12 +5,11 @@ use std::{
rc::{Rc, Weak},
};
-use crate::{
- array::ArrayElement,
- backends::common::{
- AsBufferRangeMut, AsBufferRangeRef, Backend, Buffer, BufferRangeMut, BufferRangeRef, Context, DenseBuffer,
- allocator::{RangeAllocationType, RangeAllocator},
- },
+use bytemuck::{AnyBitPattern, NoUninit};
+
+use crate::backends::common::{
+ AsBufferRangeMut, AsBufferRangeRef, Backend, Buffer, BufferRangeMut, BufferRangeRef, Context, DenseBuffer,
+ allocator::{RangeAllocationType, RangeAllocator},
};
pub struct Allocation<B: Backend> {
@@ -21,25 +20,37 @@ pub struct Allocation<B: Backend> {
}
impl<B: Backend> Allocation<B> {
- pub fn copyin<T: ArrayElement>(
- &mut self,
- data: &[T],
- ) {
+ pub fn size(&self) -> usize {
+ self.range.len()
+ }
+
+ pub fn as_slice_mut<T: NoUninit + AnyBitPattern>(&mut self) -> &mut [T] {
let buffer_range = self.as_buffer_range_mut();
let (buffer, range) = (buffer_range.buffer(), buffer_range.range());
let bytes = unsafe {
std::slice::from_raw_parts_mut((buffer.cpu_ptr().as_ptr() as *mut u8).add(range.start), range.len())
};
- bytemuck::cast_slice_mut::<u8, T>(bytes).copy_from_slice(data);
+ bytemuck::cast_slice_mut(bytes)
}
- pub fn copyout<T: ArrayElement>(&self) -> Vec<T> {
+ pub fn copyin<T: NoUninit + AnyBitPattern>(
+ &mut self,
+ data: &[T],
+ ) {
+ self.as_slice_mut().copy_from_slice(data);
+ }
+
+ pub fn as_slice<T: AnyBitPattern>(&self) -> &[T] {
let buffer_range = self.as_buffer_range_ref();
let (buffer, range) = (buffer_range.buffer(), buffer_range.range());
let bytes = unsafe {
std::slice::from_raw_parts((buffer.cpu_ptr().as_ptr() as *const u8).add(range.start), range.len())
};
- bytemuck::cast_slice(bytes).to_vec()
+ bytemuck::cast_slice(bytes)
+ }
+
+ pub fn copyout<T: AnyBitPattern>(&self) -> Vec<T> {
+ self.as_slice().to_vec()
}
}
diff --git a/crates/backend-uzu/src/backends/common/buffer/mod.rs b/crates/backend-uzu/src/backends/common/buffer/mod.rs
index f7664eabe..99d0c21fa 100644
--- a/crates/backend-uzu/src/backends/common/buffer/mod.rs
+++ b/crates/backend-uzu/src/backends/common/buffer/mod.rs
@@ -1,11 +1,12 @@
use std::{any::Any, fmt::Debug, ops::Range};
-use crate::backends::common::Backend;
+use crate::backends::common::{AsBufferRangeMut, AsBufferRangeRef, Backend, BufferRangeMut, BufferRangeRef};
pub mod dense;
-pub mod range;
pub mod sparse;
+pub mod range;
+
pub trait Buffer: Any + Debug {
type Backend: Backend;
@@ -14,11 +15,21 @@ pub trait Buffer: Any + Debug {
fn size(&self) -> usize;
}
-pub trait BufferGpuAddressRangeExt: Buffer {
- fn gpu_address_range(&self) -> Range<usize> {
- self.gpu_ptr()..(self.gpu_ptr() + self.size())
+impl<B: Buffer> AsBufferRangeRef for B {
+ type Buffer = B;
+
+ fn as_buffer_range_ref(&self) -> BufferRangeRef<'_, B> {
+ BufferRangeRef::new(self, 0..self.size())
}
+}
+impl<B: Buffer> AsBufferRangeMut for B {
+ fn as_buffer_range_mut(&mut self) -> BufferRangeMut<'_, B> {
+ BufferRangeMut::new_exclusive(self, 0..self.size())
+ }
+}
+
+pub trait BufferGpuAddressRangeExt: Buffer {
fn gpu_address_subrange(
&self,
subrange: Range<usize>,
@@ -29,4 +40,4 @@ pub trait BufferGpuAddressRangeExt: Buffer {
}
}
-impl<B: Buffer> BufferGpuAddressRangeExt for B {}
+impl<B: Buffer + ?Sized> BufferGpuAddressRangeExt for B {}
diff --git a/crates/backend-uzu/src/backends/common/buffer/range.rs b/crates/backend-uzu/src/backends/common/buffer/range.rs
index 45e760836..dd0913f39 100644
--- a/crates/backend-uzu/src/backends/common/buffer/range.rs
+++ b/crates/backend-uzu/src/backends/common/buffer/range.rs
@@ -97,20 +97,6 @@ pub trait AsBufferRangeMut: AsBufferRangeRef {
fn as_buffer_range_mut(&mut self) -> BufferRangeMut<'_, Self::Buffer>;
}
-impl<B: Buffer> AsBufferRangeRef for B {
- type Buffer = B;
-
- fn as_buffer_range_ref(&self) -> BufferRangeRef<'_, B> {
- BufferRangeRef::new(self, 0..self.size())
- }
-}
-
-impl<B: Buffer> AsBufferRangeMut for B {
- fn as_buffer_range_mut(&mut self) -> BufferRangeMut<'_, B> {
- BufferRangeMut::new_exclusive(self, 0..self.size())
- }
-}
-
fn subrange(
buffer_range: Range<usize>,
subrange: Range<usize>,
diff --git a/crates/backend-uzu/src/backends/common/command_buffer.rs b/crates/backend-uzu/src/backends/common/command_buffer.rs
index 1f8a84648..41da4cecb 100644
--- a/crates/backend-uzu/src/backends/common/command_buffer.rs
+++ b/crates/backend-uzu/src/backends/common/command_buffer.rs
@@ -91,17 +91,6 @@ pub trait CommandBufferEncoding {
before: AccessFlags,
);
- fn add_completion_handler(
- &mut self,
- handler: impl FnOnce(
- Result<
- &<Self::CommandBuffer as CommandBuffer>::Completed,
- <<Self::CommandBuffer as CommandBuffer>::Backend as Backend>::Error,
- >,
- ) + Send
- + 'static,
- );
-
fn end_encoding(self) -> <Self::CommandBuffer as CommandBuffer>::Executable;
}
diff --git a/crates/backend-uzu/src/backends/common/context.rs b/crates/backend-uzu/src/backends/common/context.rs
index f76e7678c..6c2df93a2 100644
--- a/crates/backend-uzu/src/backends/common/context.rs
+++ b/crates/backend-uzu/src/backends/common/context.rs
@@ -7,11 +7,6 @@ pub trait Context: Sized {
fn new() -> Result<Rc<Self>, <Self::Backend as Backend>::Error>;
- fn recommended_async_batch_size(
- &self,
- model_path: &Path,
- ) -> Result<usize, <Self::Backend as Backend>::Error>;
-
fn create_command_buffer(
&self
) -> Result<<<Self::Backend as Backend>::CommandBuffer as CommandBuffer>::Initial, <Self::Backend as Backend>::Error>;
diff --git a/crates/backend-uzu/src/backends/common/encoder.rs b/crates/backend-uzu/src/backends/common/encoder.rs
index 81c8ff052..343a985a5 100644
--- a/crates/backend-uzu/src/backends/common/encoder.rs
+++ b/crates/backend-uzu/src/backends/common/encoder.rs
@@ -1,5 +1,6 @@
use std::{
ops::{Bound, Range, RangeBounds},
+ rc::Rc,
time::Duration,
};
@@ -33,14 +34,20 @@ fn resolve_copy_range(
pub struct Encoder<'encoding, B: Backend> {
context: &'encoding B::Context,
command_buffer: <B::CommandBuffer as CommandBuffer>::Encoding,
- allocation_pool: AllocationPool<B>,
+ allocation_pool: Rc<AllocationPool<B>>,
hazard_tracker: HazardTracker,
}
impl<'encoding, B: Backend> Encoder<'encoding, B> {
pub fn new(context: &'encoding B::Context) -> Result<Self, B::Error> {
+ Self::new_with_pool(context, Rc::new(context.create_allocation_pool(false)))
+ }
+
+ pub fn new_with_pool(
+ context: &'encoding B::Context,
+ allocation_pool: Rc<AllocationPool<B>>,
+ ) -> Result<Self, B::Error> {
let command_buffer = context.create_command_buffer()?.start_encoding();
- let allocation_pool = context.create_allocation_pool(false);
let hazard_tracker = HazardTracker::new();
Ok(Self {
@@ -134,13 +141,6 @@ impl<'encoding, B: Backend> Encoder<'encoding, B> {
}
}
- pub fn add_completion_handler(
- &mut self,
- handler: impl FnOnce(Result<&<B::CommandBuffer as CommandBuffer>::Completed, B::Error>) + Send + 'static,
- ) {
- self.command_buffer.add_completion_handler(handler);
- }
-
pub fn as_command_buffer_mut(&mut self) -> &mut <B::CommandBuffer as CommandBuffer>::Encoding {
&mut self.command_buffer
}
@@ -159,7 +159,7 @@ impl<'encoding, B: Backend> Encoder<'encoding, B> {
pub struct Executable<B: Backend> {
command_buffer: <B::CommandBuffer as CommandBuffer>::Executable,
- allocation_pool: AllocationPool<B>,
+ allocation_pool: Rc<AllocationPool<B>>,
}
impl<B: Backend> Executable<B> {
@@ -173,7 +173,7 @@ impl<B: Backend> Executable<B> {
pub struct Pending<B: Backend> {
command_buffer: <B::CommandBuffer as CommandBuffer>::Pending,
- allocation_pool: AllocationPool<B>,
+ allocation_pool: Rc<AllocationPool<B>>,
}
impl<B: Backend> Pending<B> {
@@ -188,7 +188,7 @@ impl<B: Backend> Pending<B> {
pub struct Completed<B: Backend> {
command_buffer: <B::CommandBuffer as CommandBuffer>::Completed,
#[allow(unused)]
- allocation_pool: AllocationPool<B>,
+ allocation_pool: Rc<AllocationPool<B>>,
}
impl<B: Backend> Completed<B> {
diff --git a/crates/backend-uzu/src/backends/common/gpu_types/activation_type.rs b/crates/backend-uzu/src/backends/common/gpu_types/activation_type.rs
index 93b9502c9..fd2e4ceb3 100644
--- a/crates/backend-uzu/src/backends/common/gpu_types/activation_type.rs
+++ b/crates/backend-uzu/src/backends/common/gpu_types/activation_type.rs
@@ -9,7 +9,6 @@ pub enum ActivationType {
SILU,
GELUApprox,
GELUExact,
- TANH,
IDENTITY,
SOFTPLUS,
}
@@ -23,7 +22,6 @@ impl ActivationType {
ActivationType::SILU => silu(x),
ActivationType::GELUApprox => gelu_approx(x),
ActivationType::GELUExact => gelu_exact(x),
- ActivationType::TANH => tanh_activation(x),
ActivationType::IDENTITY => x,
ActivationType::SOFTPLUS => softplus(x),
}
@@ -56,11 +54,6 @@ fn gelu_exact<T: Float>(x: T) -> T {
T::from(y_float).unwrap()
}
-fn tanh_activation<T: Float>(x: T) -> T {
- let x_float = x.to_f32().unwrap();
- T::from(x_float.tanh()).unwrap()
-}
-
fn softplus<T: Float>(x: T) -> T {
let x_float = x.to_f32().unwrap();
if x_float > 20f32 {
diff --git a/crates/backend-uzu/src/backends/common/gpu_types/kv_cache_update.rs b/crates/backend-uzu/src/backends/common/gpu_types/kv_cache_update.rs
index 193175e2b..2131e18b9 100644
--- a/crates/backend-uzu/src/backends/common/gpu_types/kv_cache_update.rs
+++ b/crates/backend-uzu/src/backends/common/gpu_types/kv_cache_update.rs
@@ -1,6 +1,6 @@
#[derive(Clone, Copy, Debug)]
#[repr(C)]
-pub struct Swap {
+pub struct Copy {
pub source: u32,
pub destination: u32,
}
diff --git a/crates/backend-uzu/src/backends/common/gpu_types/trie.rs b/crates/backend-uzu/src/backends/common/gpu_types/trie.rs
index fe23a6ec0..50e54fd71 100644
--- a/crates/backend-uzu/src/backends/common/gpu_types/trie.rs
+++ b/crates/backend-uzu/src/backends/common/gpu_types/trie.rs
@@ -1,4 +1,6 @@
-#[derive(Clone, Copy, Debug)]
+use bytemuck::{Pod, Zeroable};
+
+#[derive(Clone, Copy, Debug, Zeroable, Pod)]
#[repr(C)]
pub struct TrieNode {
pub trie_start: u32,
diff --git a/crates/backend-uzu/src/backends/common/kernel/matmul/arguments.rs b/crates/backend-uzu/src/backends/common/kernel/matmul/arguments.rs
index 8592fd179..594d54c2c 100644
--- a/crates/backend-uzu/src/backends/common/kernel/matmul/arguments.rs
+++ b/crates/backend-uzu/src/backends/common/kernel/matmul/arguments.rs
@@ -1,15 +1,14 @@
use super::{d_ops::MatmulDOps, matmul_b::MatmulB};
-use crate::backends::common::{Allocation, AsBufferRangeRef, Backend};
+use crate::backends::common::{Allocation, Backend, kernel::BufferArg};
-pub struct MatmulArguments<'a, B: Backend, TB: AsBufferRangeRef = Allocation<B>> {
+pub struct MatmulArguments<'a, 'b, 'd, B: Backend, TB: BufferArg<'b, B> = &'b Allocation<B>> {
pub a: &'a Allocation<B>,
pub a_offset: usize,
- pub b: MatmulB<'a, B, TB>,
- pub b_offset: usize,
+ pub b: MatmulB<'b, B, TB>,
pub b_leading_dimension: Option<u32>,
pub b_transpose: bool,
- pub d: &'a mut Allocation<B>,
- pub d_transform: MatmulDOps<'a, B>,
+ pub d: &'d mut Allocation<B>,
+ pub d_transform: MatmulDOps<'d, B>,
pub m: u32,
pub n: u32,
pub k: u32,
diff --git a/crates/backend-uzu/src/backends/common/kernel/matmul/kernel.rs b/crates/backend-uzu/src/backends/common/kernel/matmul/kernel.rs
index c3eee70dc..844d845c6 100644
--- a/crates/backend-uzu/src/backends/common/kernel/matmul/kernel.rs
+++ b/crates/backend-uzu/src/backends/common/kernel/matmul/kernel.rs
@@ -1,6 +1,7 @@
use crate::{
backends::common::{
- AsBufferRangeRef, Backend, Buffer, Encoder, Kernels, kernel::matmul::arguments::MatmulArguments,
+ Backend, Encoder, Kernels,
+ kernel::{BufferArg, matmul::arguments::MatmulArguments},
},
data_type::DataType,
};
@@ -15,9 +16,9 @@ pub trait MatmulKernel: Sized {
output_data_type: DataType,
) -> Result<Self, <Self::Backend as Backend>::Error>;
- fn encode<TB: AsBufferRangeRef<Buffer: Buffer<Backend = Self::Backend>>>(
+ fn encode<'a, 'b, 'd, TB: BufferArg<'b, Self::Backend>>(
&mut self,
- arguments: MatmulArguments<Self::Backend, TB>,
+ arguments: MatmulArguments<'a, 'b, 'd, Self::Backend, TB>,
encoder: &mut Encoder<Self::Backend>,
) -> Result<(), <Self::Backend as Backend>::Error>;
}
diff --git a/crates/backend-uzu/src/backends/common/kernel/matmul/matmul_b.rs b/crates/backend-uzu/src/backends/common/kernel/matmul/matmul_b.rs
index 6e9173281..a795d09d8 100644
--- a/crates/backend-uzu/src/backends/common/kernel/matmul/matmul_b.rs
+++ b/crates/backend-uzu/src/backends/common/kernel/matmul/matmul_b.rs
@@ -1,14 +1,15 @@
use crate::{
backends::common::{
- Allocation, AsBufferRangeRef, Backend,
+ Allocation, Backend,
gpu_types::{QuantizationMode, gemm::GemmBPrologueKind},
+ kernel::BufferArg,
},
data_type::DataType,
};
-pub enum MatmulB<'a, B: Backend, TB: AsBufferRangeRef = Allocation<B>> {
+pub enum MatmulB<'a, B: Backend, TB: BufferArg<'a, B> = &'a Allocation<B>> {
FullPrecision {
- b: &'a TB,
+ b: TB,
},
ScaleBiasDequant {
b: &'a Allocation<B>,
@@ -32,7 +33,7 @@ pub enum MatmulB<'a, B: Backend, TB: AsBufferRangeRef = Allocation<B>> {
},
}
-impl<B: Backend, TB: AsBufferRangeRef> MatmulB<'_, B, TB> {
+impl<'a, B: Backend, TB: BufferArg<'a, B>> MatmulB<'a, B, TB> {
pub fn b_prologue(&self) -> GemmBPrologueKind {
match self {
Self::FullPrecision {
diff --git a/crates/backend-uzu/src/backends/common/kernel/mod.rs b/crates/backend-uzu/src/backends/common/kernel/mod.rs
index 0bd082fc3..b4bf315b2 100644
--- a/crates/backend-uzu/src/backends/common/kernel/mod.rs
+++ b/crates/backend-uzu/src/backends/common/kernel/mod.rs
@@ -1,7 +1,58 @@
-use crate::backends::common::Backend;
+use crate::backends::common::{AsBufferRangeMut, AsBufferRangeRef, Backend, Buffer};
pub mod matmul;
+// TODO: This whole thing is horrible and should be unified with AsBufferRangeRef
+pub trait BufferArg<'a, B: Backend>: Copy {
+ fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize);
+}
+
+impl<'a, B: Backend, T: AsBufferRangeRef<Buffer: Buffer<Backend = B>>> BufferArg<'a, B> for &'a T {
+ fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize) {
+ let buffer_range = self.as_buffer_range_ref();
+ let (buffer, range) = (buffer_range.buffer(), buffer_range.range());
+ (buffer, range.start, range.end - range.start)
+ }
+}
+
+impl<'a, B: Backend> BufferArg<'a, B> for &'a dyn Buffer<Backend = B> {
+ fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize) {
+ (self, 0, self.size())
+ }
+}
+
+impl<'a, B: Backend, T: BufferArg<'a, B>> BufferArg<'a, B> for (T, usize) {
+ fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize) {
+ let (buffer, offset, length) = self.0.into_parts();
+ (buffer, offset + self.1, length - self.1)
+ }
+}
+
+pub trait BufferArgMut<'a, B: Backend> {
+ fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize);
+}
+
+impl<'a, B: Backend, T: AsBufferRangeMut<Buffer: Buffer<Backend = B>>> BufferArgMut<'a, B> for &'a mut T {
+ fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize) {
+ let buffer_range = self.as_buffer_range_mut();
+ let (buffer, range) = (buffer_range.buffer(), buffer_range.range());
+ (buffer, range.start, range.end - range.start)
+ }
+}
+
+impl<'a, B: Backend> BufferArgMut<'a, B> for &'a mut dyn Buffer<Backend = B> {
+ fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize) {
+ (self, 0, self.size())
+ }
+}
+
+impl<'a, B: Backend, T: BufferArgMut<'a, B>> BufferArgMut<'a, B> for (T, usize) {
+ fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize) {
+ let (buffer, offset, length) = self.0.into_parts();
+ (buffer, offset + self.1, length - self.1)
+ }
+}
+
include!(concat!(env!("OUT_DIR"), "/traits.rs"));
pub trait Kernels: Sized {
diff --git a/crates/backend-uzu/src/backends/cpu/buffer.rs b/crates/backend-uzu/src/backends/cpu/buffer.rs
index 1be0b4605..24a771d95 100644
--- a/crates/backend-uzu/src/backends/cpu/buffer.rs
+++ b/crates/backend-uzu/src/backends/cpu/buffer.rs
@@ -5,14 +5,10 @@ use crate::backends::{
cpu::Cpu,
};
-pub trait BufferDowncastExt: Buffer<Backend = Cpu> {
- fn downcast(&self) -> &UnsafeCell<Pin<Box<[u8]>>>;
-}
-
-impl<B: Buffer<Backend = Cpu>> BufferDowncastExt for B {
- fn downcast(&self) -> &UnsafeCell<Pin<Box<[u8]>>> {
+impl dyn Buffer<Backend = Cpu> {
+ pub fn downcast(&self) -> &UnsafeCell<Pin<Box<[u8]>>> {
let buffer = self as &dyn Any;
- if let Some(buffer) = buffer.downcast_ref::<<<B as Buffer>::Backend as Backend>::DenseBuffer>() {
+ if let Some(buffer) = buffer.downcast_ref::<<Cpu as Backend>::DenseBuffer>() {
buffer
} else {
unreachable!("Unsupported Cpu buffer type")
diff --git a/crates/backend-uzu/src/backends/cpu/command_buffer.rs b/crates/backend-uzu/src/backends/cpu/command_buffer.rs
index de5be1dec..fbcf55c3b 100644
--- a/crates/backend-uzu/src/backends/cpu/command_buffer.rs
+++ b/crates/backend-uzu/src/backends/cpu/command_buffer.rs
@@ -9,7 +9,7 @@ use crate::{
AccessFlags, Buffer, BufferRangeMut, BufferRangeRef, CommandBuffer, CommandBufferCompleted,
CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
},
- cpu::{Cpu, buffer::BufferDowncastExt, error::CpuError},
+ cpu::{Cpu, error::CpuError},
},
utils::pointers::{SendPtr, SendPtrMut},
};
@@ -77,10 +77,10 @@ impl CommandBufferEncoding for CpuCommandBufferEncoding {
let dst_range = dst.range();
assert_eq!(src_range.len(), dst_range.len());
- let src_buffer = src.buffer().downcast();
+ let src_buffer = (src.buffer() as &dyn Buffer<Backend = Cpu>).downcast();
let src_ptr = SendPtr(unsafe { (&*src_buffer.get()).as_ptr().add(src_range.start) });
- let dst_buffer = dst.buffer().downcast();
+ let dst_buffer = (dst.buffer() as &dyn Buffer<Backend = Cpu>).downcast();
let dst_ptr = SendPtrMut(unsafe { (&mut *dst_buffer.get()).as_mut_ptr().add(dst_range.start) });
self.push_command(move || unsafe {
@@ -95,7 +95,9 @@ impl CommandBufferEncoding for CpuCommandBufferEncoding {
) {
let range = dst.range();
let size = range.end - range.start;
- let dst = SendPtrMut(unsafe { (&mut *dst.buffer().downcast().get()).as_mut_ptr().add(range.start) });
+ let dst = SendPtrMut(unsafe {
+ (&mut *(dst.buffer() as &dyn Buffer<Backend = Cpu>).downcast().get()).as_mut_ptr().add(range.start)
+ });
self.push_command(move || unsafe {
dst.as_ptr().write_bytes(value, size);
});
@@ -108,13 +110,6 @@ impl CommandBufferEncoding for CpuCommandBufferEncoding {
) {
}
- fn add_completion_handler(
- &mut self,
- handler: impl FnOnce(Result<&CpuCommandBufferCompleted, CpuError>) + Send + 'static,
- ) {
- self.completion_handlers.push(Box::new(handler))
- }
-
fn end_encoding(self) -> CpuCommandBufferExecutable {
CpuCommandBufferExecutable {
command_queue: self.command_queue,
diff --git a/crates/backend-uzu/src/backends/cpu/context.rs b/crates/backend-uzu/src/backends/cpu/context.rs
index 78d340c86..7541c9797 100644
--- a/crates/backend-uzu/src/backends/cpu/context.rs
+++ b/crates/backend-uzu/src/backends/cpu/context.rs
@@ -28,13 +28,6 @@ impl Context for CpuContext {
}))
}
- fn recommended_async_batch_size(
- &self,
- _model_path: &Path,
- ) -> Result<usize, CpuError> {
- Ok(1)
- }
-
fn create_buffer(
&self,
size: usize,
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_prepare.rs b/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_prepare.rs
new file mode 100644
index 000000000..d5bf5e75f
--- /dev/null
+++ b/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_prepare.rs
@@ -0,0 +1,126 @@
+use half::bf16;
+use num_traits::Float;
+use proc_macros::kernel;
+
+use crate::array::ArrayElement;
+
+fn apply_rope<ElementT: ArrayElement + Float, RopeT: ArrayElement + Float>(
+ head: *const ElementT,
+ cosines: *const RopeT,
+ sines: *const RopeT,
+ batch_idx: usize,
+ head_dim_idx: usize,
+ rope_dim: usize,
+) -> ElementT {
+ let half_rope_dim = rope_dim / 2;
+ let paired_idx = if head_dim_idx < half_rope_dim {
+ head_dim_idx + half_rope_dim
+ } else {
+ head_dim_idx - half_rope_dim
+ };
+ let input = unsafe { (*head.add(head_dim_idx)).to_f32().unwrap() };
+ let paired = unsafe { (*head.add(paired_idx)).to_f32().unwrap() };
+ let signed_paired = if head_dim_idx < half_rope_dim {
+ -paired
+ } else {
+ paired
+ };
+ let cos_val = unsafe { (*cosines.add(batch_idx * rope_dim + head_dim_idx)).to_f32().unwrap() };
+ let sin_val = unsafe { (*sines.add(batch_idx * rope_dim + head_dim_idx)).to_f32().unwrap() };
+
+ ElementT::from(input * cos_val + signed_paired * sin_val).unwrap()
+}
+
+#[kernel(AttentionPrepare)]
+#[variants(ElementT, bf16)]
+#[variants(RopeT, f32)]
+pub fn attention_prepare<ElementT: ArrayElement + Float, RopeT: ArrayElement + Float>(
+ qkv: *const ElementT,
+ queries: *mut ElementT,
+ #[optional(has_kv)] keys: Option<*mut ElementT>,
+ #[optional(has_kv)] values: Option<*mut ElementT>,
+ #[optional(has_rope)] cosines: Option<*const RopeT>,
+ #[optional(has_rope)] sines: Option<*const RopeT>,
+ num_q_heads: u32,
+ #[optional(has_kv)] num_kv_heads: Option<u32>,
+ head_dim: u32,
+ #[optional(has_rope)] rope_dim: Option<u32>,
+ #[optional(has_kv)] kv_token_offset: Option<u32>,
+ batch_dim: u32,
+ #[specialize] has_kv: bool,
+ #[specialize] has_rope: bool,
+) {
+ assert!(num_q_heads > 0, "attention prepare requires at least one query head");
+ assert!(head_dim > 0, "attention prepare requires nonzero head_dim");
+ assert_eq!(keys.is_some(), has_kv, "attention prepare keys presence mismatch");
+ assert_eq!(values.is_some(), has_kv, "attention prepare values presence mismatch");
+ assert_eq!(num_kv_heads.is_some(), has_kv, "attention prepare num_kv_heads presence mismatch");
+ assert_eq!(kv_token_offset.is_some(), has_kv, "attention prepare kv_token_offset presence mismatch");
+ assert_eq!(cosines.is_some(), has_rope, "attention prepare cosines presence mismatch");
+ assert_eq!(sines.is_some(), has_rope, "attention prepare sines presence mismatch");
+ assert_eq!(rope_dim.is_some(), has_rope, "attention prepare rope_dim presence mismatch");
+
+ let (keys, values, num_kv_heads, kv_token_offset) =
+ if let (Some(keys), Some(values), Some(num_kv_heads), Some(kv_token_offset)) =
+ (keys, values, num_kv_heads, kv_token_offset)
+ {
+ assert!(num_kv_heads > 0, "attention prepare has_kv requires nonzero num_kv_heads");
+ (keys, values, num_kv_heads as usize, kv_token_offset as usize)
+ } else {
+ (std::ptr::null_mut(), std::ptr::null_mut(), 0, 0)
+ };
+
+ let (cosines, sines, rope_dim) = if let (Some(cosines), Some(sines), Some(rope_dim)) = (cosines, sines, rope_dim) {
+ assert!(rope_dim > 0, "attention prepare has_rope requires nonzero rope_dim");
+ assert!(rope_dim <= head_dim, "attention prepare rope_dim exceeds head_dim");
+ assert!(rope_dim.is_multiple_of(2), "attention prepare rope_dim must be even");
+ (cosines, sines, rope_dim as usize)
+ } else {
+ (std::ptr::null(), std::ptr::null(), 0)
+ };
+
+ let num_q_heads = num_q_heads as usize;
+ let head_dim = head_dim as usize;
+ let batch_dim = batch_dim as usize;
+ let total_heads = if has_kv {
+ num_q_heads + num_kv_heads * 2
+ } else {
+ num_q_heads
+ };
+
+ for batch_idx in 0..batch_dim {
+ for head_idx in 0..total_heads {
+ let qkv_head = unsafe { qkv.add(batch_idx * total_heads * head_dim + head_idx * head_dim) };
+ let is_query = !has_kv || head_idx < num_q_heads;
+ let is_key = has_kv && head_idx >= num_q_heads && head_idx < num_q_heads + num_kv_heads;
+
+ for head_dim_idx in 0..head_dim {
+ let mut element = unsafe { *qkv_head.add(head_dim_idx) };
+ if has_rope && head_dim_idx < rope_dim && (is_query || is_key) {
+ element = apply_rope(qkv_head, cosines, sines, batch_idx, head_dim_idx, rope_dim);
+ }
+
+ if is_query {
+ let query_offset = head_idx * batch_dim * head_dim + batch_idx * head_dim + head_dim_idx;
+ unsafe {
+ *queries.add(query_offset) = element;
+ }
+ } else if is_key {
+ let key_offset = (kv_token_offset + batch_idx) * num_kv_heads * head_dim
+ + (head_idx - num_q_heads) * head_dim
+ + head_dim_idx;
+ unsafe {
+ *keys.add(key_offset) = element;
+ }
+ } else {
+ let value_offset = (kv_token_offset + batch_idx) * num_kv_heads * head_dim
+ + (head_idx - num_q_heads - num_kv_heads) * head_dim
+ + head_dim_idx;
+ unsafe {
+ *values.add(value_offset) = element;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_update_kv_cache.rs b/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_update_kv_cache.rs
deleted file mode 100644
index 5eb496b6b..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/attention/attention_update_kv_cache.rs
+++ /dev/null
@@ -1,52 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(AttentionUpdateKVCache)]
-#[variants(T, f32, f16, bf16)]
-pub fn attention_update_kv_cache<T: ArrayElement + Float>(
- #[optional(!keys_in_place)] rotated_keys: Option<*const T>,
- qkv: *const T,
- key_cache: *mut T,
- value_cache: *mut T,
- num_groups: u32,
- num_heads: u32,
- head_dim: u32,
- suffix_length: u32,
- prefix_segment_length: u32,
- max_sequence_length: u32,
- #[specialize] keys_in_place: bool,
-) {
- let rotated_keys: *const T = match keys_in_place {
- true => key_cache,
- false => rotated_keys.unwrap(),
- };
-
- for group_index in 0..num_groups {
- for token_index in 0..suffix_length {
- for dim_index in 0..head_dim {
- let cache_token_index = prefix_segment_length + token_index;
- let cache_offset = if keys_in_place {
- // destination shares rotated_keys' group-major layout.
- (group_index * max_sequence_length + cache_token_index) * head_dim + dim_index
- } else {
- // KV cache is token-major: [max_sequence_length, num_groups, head_dim].
- (cache_token_index * num_groups + group_index) * head_dim + dim_index
- };
- let rotated_key_offset = (group_index * suffix_length + token_index) * head_dim + dim_index;
- unsafe {
- *key_cache.add(cache_offset as usize) = *rotated_keys.add(rotated_key_offset as usize);
- }
-
- let qkv_stride = (num_heads + 2 * num_groups) * head_dim;
- let value_base_offset = (num_heads + num_groups) * head_dim;
- let value_offset = token_index * qkv_stride + value_base_offset + group_index * head_dim + dim_index;
- unsafe {
- *value_cache.add(cache_offset as usize) = *qkv.add(value_offset as usize);
- }
- }
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/attention/kv_cache_update.rs b/crates/backend-uzu/src/backends/cpu/kernel/attention/kv_cache_update.rs
new file mode 100644
index 000000000..a04dc44b7
--- /dev/null
+++ b/crates/backend-uzu/src/backends/cpu/kernel/attention/kv_cache_update.rs
@@ -0,0 +1,28 @@
+use half::{bf16, f16};
+use num_traits::Float;
+use proc_macros::kernel;
+
+use crate::array::ArrayElement;
+
+#[kernel(KVCacheUpdate)]
+#[variants(T, f32, bf16, f16)]
+pub fn kv_cache_update<T: ArrayElement + Float>(
+ in_place_keys: *mut T,
+ in_place_values: *mut T,
+ copies: &[crate::backends::common::gpu_types::kv_cache_update::Copy],
+ copy_count: u32,
+ element_dim: u32,
+) {
+ let element_dim = element_dim as usize;
+
+ for element_idx in 0..element_dim {
+ for i in 0..copy_count as usize {
+ let source_idx = (copies[i].source as usize) * element_dim + element_idx;
+ let dest_idx = (copies[i].destination as usize) * element_dim + element_idx;
+ unsafe {
+ *in_place_keys.add(dest_idx) = *in_place_keys.add(source_idx);
+ *in_place_values.add(dest_idx) = *in_place_values.add(source_idx);
+ }
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/attention/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/attention/mod.rs
index 65ae02228..c4798489a 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/attention/mod.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/attention/mod.rs
@@ -1,9 +1,10 @@
pub mod attention_fallback;
pub mod attention_gemm;
+pub mod attention_prepare;
pub mod attention_single_pass;
pub mod attention_two_pass;
-pub mod attention_update_kv_cache;
-pub mod qk_unpack;
+pub mod kv_cache_update;
+pub mod qkv_norm;
pub mod sigmoid_gate;
mod mask;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/attention/qk_unpack.rs b/crates/backend-uzu/src/backends/cpu/kernel/attention/qk_unpack.rs
deleted file mode 100644
index 5e784d23e..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/attention/qk_unpack.rs
+++ /dev/null
@@ -1,55 +0,0 @@
-use half::{bf16, f16};
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(QkUnpack)]
-#[variants(T, f32, f16, bf16)]
-pub fn qk_unpack<T: ArrayElement>(
- qkv: *const T,
- unpacked_queries: *mut T,
- unpacked_keys: *mut T,
- head_dim: u32,
- num_heads: u32,
- num_groups: u32,
- suffix_length: u32,
-) {
- if num_groups == 0 || !num_heads.is_multiple_of(num_groups) {
- return;
- }
-
- let head_dim = head_dim as usize;
- let num_heads = num_heads as usize;
- let num_groups = num_groups as usize;
- let suffix_length = suffix_length as usize;
-
- let total_heads = num_heads + 2 * num_groups;
- let heads_per_group = num_heads / num_groups;
-
- for head_index in 0..num_heads {
- let group_index = head_index / heads_per_group;
- let first_head_in_group = group_index * heads_per_group;
-
- for token_index in 0..suffix_length {
- for dim_index in 0..head_dim {
- let q_val =
- unsafe { *qkv.add(token_index * total_heads * head_dim + head_index * head_dim + dim_index) };
- unsafe {
- *unpacked_queries.add(head_index * suffix_length * head_dim + token_index * head_dim + dim_index) =
- q_val;
- }
-
- if head_index == first_head_in_group {
- let key_head_index = num_heads + group_index;
- let k_val = unsafe {
- *qkv.add(token_index * total_heads * head_dim + key_head_index * head_dim + dim_index)
- };
- unsafe {
- *unpacked_keys
- .add(group_index * suffix_length * head_dim + token_index * head_dim + dim_index) = k_val;
- }
- }
- }
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/rms_norm/qkv_norm.rs b/crates/backend-uzu/src/backends/cpu/kernel/attention/qkv_norm.rs
similarity index 100%
rename from crates/backend-uzu/src/backends/cpu/kernel/rms_norm/qkv_norm.rs
rename to crates/backend-uzu/src/backends/cpu/kernel/attention/qkv_norm.rs
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/audio/add.rs b/crates/backend-uzu/src/backends/cpu/kernel/audio/add.rs
deleted file mode 100644
index 62bd69c26..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/audio/add.rs
+++ /dev/null
@@ -1,16 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(AudioAdd)]
-#[variants(T, f32, f16, bf16)]
-pub fn audio_add<T: ArrayElement + Float>(
- #[allow(unused)] a: *const T,
- #[allow(unused)] b: *const T,
- #[allow(unused)] out: *mut T,
- #[allow(unused)] n: i32,
-) {
- todo!()
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv1d.rs b/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv1d.rs
deleted file mode 100644
index 68df2f2f6..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv1d.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(AudioCausalConv1d)]
-#[variants(T, f32, f16, bf16)]
-pub fn audio_causal_conv1d<T: ArrayElement + Float>(
- #[allow(unused)] input: *const T,
- #[allow(unused)] weight: *const T,
- #[allow(unused)] bias: *const T,
- #[allow(unused)] output: *mut T,
- #[allow(unused)] lengths: *const i32,
- #[allow(unused)] cin: i32,
- #[allow(unused)] cout: i32,
- #[allow(unused)] seq_len: i32,
- #[allow(unused)] kernel_size: i32,
- #[allow(unused)] dilation: i32,
- #[allow(unused)] input_layout: i32,
- #[allow(unused)] batch_size: i32,
-) {
- todo!()
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv1d_grouped.rs b/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv1d_grouped.rs
deleted file mode 100644
index 0dde36e6d..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv1d_grouped.rs
+++ /dev/null
@@ -1,25 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(AudioCausalConv1dGrouped)]
-#[variants(T, f32, f16, bf16)]
-pub fn audio_causal_conv1d_grouped<T: ArrayElement + Float>(
- #[allow(unused)] input: *const T,
- #[allow(unused)] weight: *const T,
- #[allow(unused)] bias: *const T,
- #[allow(unused)] output: *mut T,
- #[allow(unused)] lengths: *const i32,
- #[allow(unused)] cin: i32,
- #[allow(unused)] cout: i32,
- #[allow(unused)] seq_len: i32,
- #[allow(unused)] kernel_size: i32,
- #[allow(unused)] dilation: i32,
- #[allow(unused)] groups: i32,
- #[allow(unused)] input_layout: i32,
- #[allow(unused)] batch_size: i32,
-) {
- todo!()
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv1d_grouped_residual.rs b/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv1d_grouped_residual.rs
deleted file mode 100644
index c4b27abcb..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv1d_grouped_residual.rs
+++ /dev/null
@@ -1,25 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(AudioCausalConv1dGroupedResidual)]
-#[variants(T, f32, f16, bf16)]
-pub fn audio_causal_conv1d_grouped_residual<T: ArrayElement + Float>(
- #[allow(unused)] input: *const T,
- #[allow(unused)] residual: *const T,
- #[allow(unused)] weight: *const T,
- #[allow(unused)] bias: *const T,
- #[allow(unused)] output: *mut T,
- #[allow(unused)] lengths: *const i32,
- #[allow(unused)] cin: i32,
- #[allow(unused)] cout: i32,
- #[allow(unused)] seq_len: i32,
- #[allow(unused)] kernel_size: i32,
- #[allow(unused)] dilation: i32,
- #[allow(unused)] groups: i32,
- #[allow(unused)] batch_size: i32,
-) {
- todo!()
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv_transpose1d.rs b/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv_transpose1d.rs
deleted file mode 100644
index b1d401ba1..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv_transpose1d.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(AudioCausalConvTranspose1d)]
-#[variants(T, f32, f16, bf16)]
-pub fn audio_causal_conv_transpose1d<T: ArrayElement + Float>(
- #[allow(unused)] input: *const T,
- #[allow(unused)] weight: *const T,
- #[allow(unused)] bias: *const T,
- #[allow(unused)] output: *mut T,
- #[allow(unused)] lengths: *const i32,
- #[allow(unused)] cin: i32,
- #[allow(unused)] cout: i32,
- #[allow(unused)] seq_len_in: i32,
- #[allow(unused)] seq_len_out: i32,
- #[allow(unused)] stride: i32,
- #[allow(unused)] groups: i32,
- #[allow(unused)] batch_size: i32,
-) {
- todo!()
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv_transpose1d_causal_pad.rs b/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv_transpose1d_causal_pad.rs
deleted file mode 100644
index dbe3a803d..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/audio/causal_conv_transpose1d_causal_pad.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(AudioCausalConvTranspose1dCausalPad)]
-#[variants(T, f32, f16, bf16)]
-pub fn audio_causal_conv_transpose1d_causal_pad<T: ArrayElement + Float>(
- #[allow(unused)] input: *const T,
- #[allow(unused)] weight: *const T,
- #[allow(unused)] bias: *const T,
- #[allow(unused)] output: *mut T,
- #[allow(unused)] lengths: *const i32,
- #[allow(unused)] cin: i32,
- #[allow(unused)] cout: i32,
- #[allow(unused)] seq_len_in: i32,
- #[allow(unused)] seq_len_out: i32,
- #[allow(unused)] kernel_size: i32,
- #[allow(unused)] stride: i32,
- #[allow(unused)] groups: i32,
- #[allow(unused)] input_layout: i32,
- #[allow(unused)] batch_size: i32,
-) {
- todo!()
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/audio/conv1d.rs b/crates/backend-uzu/src/backends/cpu/kernel/audio/conv1d.rs
deleted file mode 100644
index 79701201b..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/audio/conv1d.rs
+++ /dev/null
@@ -1,27 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(AudioConv1d)]
-#[variants(T, f32, f16, bf16)]
-pub fn audio_conv1d<T: ArrayElement + Float>(
- #[allow(unused)] input: *const T,
- #[allow(unused)] weight: *const T,
- #[allow(unused)] bias: *const T,
- #[allow(unused)] output: *mut T,
- #[allow(unused)] lengths: *const i32,
- #[allow(unused)] cin: i32,
- #[allow(unused)] cout: i32,
- #[allow(unused)] seq_len_in: i32,
- #[allow(unused)] seq_len_out: i32,
- #[allow(unused)] kernel_size: i32,
- #[allow(unused)] stride: i32,
- #[allow(unused)] dilation: i32,
- #[allow(unused)] padding: i32,
- #[allow(unused)] pad_mode: i32,
- #[allow(unused)] batch_size: i32,
-) {
- todo!()
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/audio/fsq_decode.rs b/crates/backend-uzu/src/backends/cpu/kernel/audio/fsq_decode.rs
deleted file mode 100644
index a4a75a9dd..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/audio/fsq_decode.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(AudioFsqDecode)]
-#[variants(T, f32, f16, bf16)]
-pub fn audio_fsq_decode<T: ArrayElement + Float>(
- #[allow(unused)] tokens: *const i32,
- #[allow(unused)] out: *mut T,
- #[allow(unused)] lengths: *const i32,
- #[allow(unused)] num_groups: i32,
- #[allow(unused)] seq_len: i32,
- #[allow(unused)] codebook_dim: i32,
- #[allow(unused)] num_levels: &[i32],
- #[allow(unused)] dim_base_index: &[i32],
- #[allow(unused)] batch_size: i32,
-) {
- todo!()
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/audio/fsq_encode.rs b/crates/backend-uzu/src/backends/cpu/kernel/audio/fsq_encode.rs
deleted file mode 100644
index 5f93fc013..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/audio/fsq_encode.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(AudioFsqEncode)]
-#[variants(T, f32, f16, bf16)]
-pub fn audio_fsq_encode<T: ArrayElement + Float>(
- #[allow(unused)] input: *const T,
- #[allow(unused)] tokens: *mut i32,
- #[allow(unused)] lengths: *const i32,
- #[allow(unused)] num_groups: i32,
- #[allow(unused)] seq_len: i32,
- #[allow(unused)] codebook_dim: i32,
- #[allow(unused)] num_levels: &[i32],
- #[allow(unused)] dim_base_index: &[i32],
- #[allow(unused)] eps: f32,
- #[allow(unused)] batch_size: i32,
-) {
- todo!()
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/audio/half_snake.rs b/crates/backend-uzu/src/backends/cpu/kernel/audio/half_snake.rs
deleted file mode 100644
index 0c26a3ba6..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/audio/half_snake.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(AudioHalfSnake)]
-#[variants(T, f32, f16, bf16)]
-pub fn audio_half_snake<T: ArrayElement + Float>(
- #[allow(unused)] input: *const T,
- #[allow(unused)] alpha: *const T,
- #[allow(unused)] output: *mut T,
- #[allow(unused)] channels: i32,
- #[allow(unused)] seq_len: i32,
- #[allow(unused)] snake_channels: i32,
- #[allow(unused)] negative_slope: f32,
- #[allow(unused)] eps: f32,
- #[allow(unused)] batch_size: i32,
-) {
- todo!()
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/audio/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/audio/mod.rs
deleted file mode 100644
index cd7577077..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/audio/mod.rs
+++ /dev/null
@@ -1,12 +0,0 @@
-pub mod add;
-pub mod causal_conv1d;
-pub mod causal_conv1d_grouped;
-pub mod causal_conv1d_grouped_residual;
-pub mod causal_conv_transpose1d;
-pub mod causal_conv_transpose1d_causal_pad;
-pub mod conv1d;
-pub mod fsq_decode;
-pub mod fsq_encode;
-pub mod half_snake;
-pub mod norm_ncs;
-pub mod quantizer_decode;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/audio/norm_ncs.rs b/crates/backend-uzu/src/backends/cpu/kernel/audio/norm_ncs.rs
deleted file mode 100644
index 1c214142d..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/audio/norm_ncs.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(AudioNormNcs)]
-#[variants(T, f32, f16, bf16)]
-pub fn audio_norm_ncs<T: ArrayElement + Float>(
- #[allow(unused)] input: *const T,
- #[allow(unused)] scales: *const f32,
- #[allow(unused)] bias: *const f32,
- #[allow(unused)] output: *mut T,
- #[allow(unused)] lengths: *const i32,
- #[allow(unused)] channels: i32,
- #[allow(unused)] seq_len: i32,
- #[allow(unused)] epsilon: f32,
- #[allow(unused)] subtract_mean: i32,
- #[allow(unused)] batch_size: i32,
-) {
- todo!()
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/audio/quantizer_decode.rs b/crates/backend-uzu/src/backends/cpu/kernel/audio/quantizer_decode.rs
deleted file mode 100644
index fd4d72454..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/audio/quantizer_decode.rs
+++ /dev/null
@@ -1,29 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(AudioQuantizerDecode)]
-#[variants(T, f32, f16, bf16)]
-pub fn audio_quantizer_decode<T: ArrayElement + Float>(
- #[allow(unused)] tokens: *const u32,
- #[allow(unused)] lengths: *const i32,
- #[allow(unused)] semantic_codebook: *const T,
- #[allow(unused)] semantic_out_proj: *const T,
- #[allow(unused)] semantic_out_bias: *const T,
- #[allow(unused)] residual_codebooks: *const T,
- #[allow(unused)] residual_out_proj: *const T,
- #[allow(unused)] residual_out_bias: *const T,
- #[allow(unused)] output: *mut T,
- #[allow(unused)] batch_size: i32,
- #[allow(unused)] total_codebooks: i32,
- #[allow(unused)] seq_len: i32,
- #[allow(unused)] input_dim: i32,
- #[allow(unused)] codebook_dim: i32,
- #[allow(unused)] residual_quantizers: i32,
- #[allow(unused)] semantic_cardinality: i32,
- #[allow(unused)] residual_cardinality: i32,
-) {
- todo!()
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/embedding/embedding_rows_sum.rs b/crates/backend-uzu/src/backends/cpu/kernel/embedding/embedding_rows_sum.rs
deleted file mode 100644
index 6f94bc296..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/embedding/embedding_rows_sum.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(EmbeddingRowsSum)]
-#[variants(T, f32, f16, bf16)]
-pub fn embedding_rows_sum<T: ArrayElement + Float>(
- token_indices: *const u32,
- weights: *const T,
- output: *mut T,
- num_rows: u32,
- total_rows: u32,
- model_dim: u32,
- codebook_stride: u32,
-) {
- let codebook_stride = codebook_stride as usize;
- let total_rows = total_rows as usize;
- let model_dim = model_dim as usize;
-
- unsafe {
- for dim_idx in 0..model_dim {
- let mut sum = 0f32;
- for row_idx in 0..num_rows as usize {
- let token = *token_indices.add(row_idx) as usize;
- let row = row_idx * codebook_stride + token;
- if row < total_rows {
- sum += (*weights.add(row * model_dim + dim_idx)).to_f32().unwrap();
- }
- }
- *output.add(dim_idx) = T::from(sum).unwrap();
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/embedding/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/embedding/mod.rs
index 556c0cfb7..93f7cf1f0 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/embedding/mod.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/embedding/mod.rs
@@ -1,3 +1,2 @@
-pub mod embedding_rows_sum;
pub mod full_precision_embedding;
pub mod quant_embedding;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/kv_cache_update/kv_cache_update.rs b/crates/backend-uzu/src/backends/cpu/kernel/kv_cache_update/kv_cache_update.rs
deleted file mode 100644
index a41cea752..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/kv_cache_update/kv_cache_update.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(KVCacheUpdate)]
-#[variants(T, f32, bf16, f16)]
-pub fn kv_cache_update<T: ArrayElement + Float>(
- in_place_keys: *mut T,
- in_place_values: *mut T,
- swaps: &[crate::backends::common::gpu_types::kv_cache_update::Swap],
- swap_count: u32,
- num_heads: u32,
- head_dim: u32,
-) {
- let num_heads = num_heads as usize;
- let head_dim = head_dim as usize;
-
- // Stride between tokens: num_heads * head_dim;
- // Stride between heads: head_dim.
- for head_idx in 0..num_heads {
- for channel_idx in 0..head_dim {
- for i in 0..swap_count as usize {
- let head_offset = head_idx * head_dim;
- let source_idx = (swaps[i].source as usize) * num_heads * head_dim + head_offset + channel_idx;
- let dest_idx = (swaps[i].destination as usize) * num_heads * head_dim + head_offset + channel_idx;
- unsafe {
- let keys_src_ptr = in_place_keys.add(source_idx);
- let keys_dst_ptr = in_place_keys.add(dest_idx);
- keys_src_ptr.swap(keys_dst_ptr);
-
- let values_src_ptr = in_place_values.add(source_idx);
- let values_dst_ptr = in_place_values.add(dest_idx);
- values_src_ptr.swap(values_dst_ptr);
- }
- }
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/kv_cache_update/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/kv_cache_update/mod.rs
deleted file mode 100644
index 128b5561e..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/kv_cache_update/mod.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub mod kv_cache_update;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/layer_norm/layer_norm.rs b/crates/backend-uzu/src/backends/cpu/kernel/layer_norm/layer_norm.rs
deleted file mode 100644
index a3df51b80..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/layer_norm/layer_norm.rs
+++ /dev/null
@@ -1,76 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(LayerNorm)]
-#[variants(IN, f32, f16, bf16)]
-#[variants(SC, f32, f16, bf16)]
-#[variants(OUT, f32, f16, bf16)]
-#[variants(ACC, f32)]
-pub fn layer_norm<
- IN: ArrayElement + Float,
- SC: ArrayElement + Float,
- OUT: ArrayElement + Float,
- ACC: ArrayElement + Float,
->(
- #[optional(!in_place)] input: Option<*const IN>,
- scales: *const SC,
- output: *mut OUT,
- batch_size: u32,
- model_dim: u32,
- epsilon: f32,
- scale_offset: f32,
- full_layer: u32,
- #[specialize] in_place: bool,
-) {
- let input = match in_place {
- true => output as *const IN,
- false => input.unwrap(),
- };
-
- let model_dim = model_dim as usize;
- let epsilon = ACC::from(epsilon).unwrap();
- let scale_offset = ACC::from(scale_offset).unwrap();
- let element_count_accum = ACC::from(model_dim).unwrap();
- let full_layer = full_layer != 0;
-
- for batch in 0..(batch_size as usize) {
- let batch_offset = batch * model_dim;
-
- // Compute mean
- let mut sum = ACC::zero();
- for i in 0..model_dim {
- let val = unsafe { ACC::from(*input.add(batch_offset + i)).unwrap() };
- sum = sum + val;
- }
- let mean = sum / element_count_accum;
-
- // Compute variance
- let mut var_sum = ACC::zero();
- for i in 0..model_dim {
- let val = unsafe { ACC::from(*input.add(batch_offset + i)).unwrap() };
- let centered = val - mean;
- var_sum = var_sum + centered * centered;
- }
- let variance = var_sum / element_count_accum;
- let inv_std = ACC::from((variance + epsilon).to_f32().unwrap().sqrt().recip()).unwrap();
-
- // Normalize and scale
- for i in 0..model_dim {
- let input_val = unsafe { ACC::from(*input.add(batch_offset + i)).unwrap() };
- let scale_val = unsafe { ACC::from(*scales.add(i)).unwrap() };
- let normalized: ACC = (input_val - mean) * inv_std;
- let result: OUT = if full_layer {
- let scale_with_offset: ACC = scale_val + scale_offset;
- OUT::from(normalized * scale_with_offset).unwrap()
- } else {
- let normalized_out = OUT::from(normalized).unwrap();
- let scale_with_offset_out = OUT::from(scale_val + scale_offset).unwrap();
- normalized_out * scale_with_offset_out
- };
- unsafe { *output.add(batch_offset + i) = result };
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/layer_norm/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/layer_norm/mod.rs
deleted file mode 100644
index 89b2f7b11..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/layer_norm/mod.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub mod layer_norm;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/matmul/kernel.rs b/crates/backend-uzu/src/backends/cpu/kernel/matmul/kernel.rs
index 23a351825..734dca683 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/matmul/kernel.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/matmul/kernel.rs
@@ -2,10 +2,10 @@ use super::reference::{WeightData, read_f32, write_f32};
use crate::{
backends::{
common::{
- AsBufferRangeMut, AsBufferRangeRef, Backend, Buffer, Encoder, Kernels,
+ AsBufferRangeMut, AsBufferRangeRef, Backend, Encoder, Kernels,
gpu_types::HadamardTransformOrder,
kernel::{
- HadamardTransformKernel,
+ BufferArg, HadamardTransformKernel,
matmul::{MatmulArguments, MatmulError, MatmulKernel},
},
},
@@ -49,9 +49,9 @@ impl MatmulKernel for MatmulCpuKernel {
})
}
- fn encode<TB: AsBufferRangeRef<Buffer: Buffer<Backend = Cpu>>>(
+ fn encode<'a, 'b, 'd, TB: BufferArg<'b, Cpu>>(
&mut self,
- arguments: MatmulArguments<Cpu, TB>,
+ arguments: MatmulArguments<'a, 'b, 'd, Cpu, TB>,
encoder: &mut Encoder<Cpu>,
) -> Result<(), CpuError> {
let output_scale = arguments.d_transform.ab_scale;
@@ -63,7 +63,6 @@ impl MatmulKernel for MatmulCpuKernel {
a,
a_offset,
b,
- b_offset,
b_leading_dimension,
b_transpose,
d,
@@ -92,8 +91,7 @@ impl MatmulKernel for MatmulCpuKernel {
(&*d_buffer_range.buffer().get()).as_ptr().wrapping_byte_add(d_buffer_range.range().start) as *mut u8
});
- let weight_data =
- WeightData::from_b(b, b_offset, b_leading_dimension, b_transpose, weights_data_type, k_u, n_u);
+ let weight_data = WeightData::from_b(b, b_leading_dimension, b_transpose, k_u, n_u);
let command_buffer = encoder.as_command_buffer_mut();
command_buffer.push_command(move || {
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/matmul/reference.rs b/crates/backend-uzu/src/backends/cpu/kernel/matmul/reference.rs
index 5076857f0..b570d4c82 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/matmul/reference.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/matmul/reference.rs
@@ -2,8 +2,12 @@ use half::{bf16, f16};
use crate::{
backends::{
- common::{AsBufferRangeRef, Buffer, gpu_types::QuantizationMode, kernel::matmul::MatmulB},
- cpu::{Cpu, buffer::BufferDowncastExt},
+ common::{
+ AsBufferRangeRef,
+ gpu_types::QuantizationMode,
+ kernel::{BufferArg, matmul::MatmulB},
+ },
+ cpu::Cpu,
},
data_type::DataType,
utils::pointers::SendPtr,
@@ -26,12 +30,10 @@ pub(super) enum WeightData {
}
impl WeightData {
- pub(super) fn from_b<TB: AsBufferRangeRef<Buffer: Buffer<Backend = Cpu>>>(
- b: MatmulB<'_, Cpu, TB>,
- b_offset: usize,
+ pub(super) fn from_b<'a, TB: BufferArg<'a, Cpu>>(
+ b: MatmulB<'a, Cpu, TB>,
b_leading_dimension: Option<u32>,
b_transpose: bool,
- weights_data_type: DataType,
k: usize,
n: usize,
) -> Self {
@@ -52,10 +54,9 @@ impl WeightData {
} else {
n
});
- let r = weights.as_buffer_range_ref();
- let byte_off = r.range().start + b_offset * weights_data_type.size_in_bytes();
+ let (buffer, byte_off, _) = weights.into_parts();
WeightData::FullPrecision {
- ptr: SendPtr(unsafe { &*r.buffer().downcast().get() }.as_ptr().wrapping_byte_add(byte_off)),
+ ptr: SendPtr(unsafe { &*buffer.downcast().get() }.as_ptr().wrapping_byte_add(byte_off)),
leading_dimension,
transpose: b_transpose,
}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/mod.rs
index 59e6810e0..f2ee15930 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/mod.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/mod.rs
@@ -2,20 +2,16 @@ use crate::backends::{common::Kernels, cpu::Cpu};
mod activation;
mod attention;
-mod audio;
mod delta_net;
mod embedding;
mod gated_act_mul;
mod gdn_tree_verify;
mod hadamard_transform;
-mod kv_cache_update;
-mod layer_norm;
mod logit_soft_cap;
mod matmul;
mod moe;
+mod normalization;
mod pooling;
-mod rms_norm;
-mod rope;
mod sampling;
mod short_conv;
mod softmax;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/moe/experts_single.rs b/crates/backend-uzu/src/backends/cpu/kernel/moe/experts_single.rs
deleted file mode 100644
index ab8f142da..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/moe/experts_single.rs
+++ /dev/null
@@ -1,139 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::{
- array::ArrayElement,
- backends::common::gpu_types::{ActivationType, activation_silu_alpha},
-};
-
-#[kernel(MoeExpertsDecodeSinglePassA)]
-#[variants(T, f32, f16, bf16)]
-pub fn moe_experts_decode_single_pass_a<T: ArrayElement + Float>(
- x: *const T,
- topk_ids: *const i32,
- w13_all: *const T,
- biases: *const T,
- hidden_out: *mut f32,
- d_model: u32,
- d_ff: u32,
- k: u32,
- silu_alpha: f32,
- gate_clip_min: f32,
- gate_clip_max: f32,
- up_clip_min: f32,
- up_clip_max: f32,
- #[specialize] gating_sel: u32,
-) {
- let dm = d_model as usize;
- let df = d_ff as usize;
-
- for k_slot in 0..k as usize {
- let expert_id = unsafe { *topk_ids.add(k_slot) };
- if expert_id < 0 {
- continue;
- }
- let expert_u = expert_id as usize;
-
- let w13_stride = dm * 2 * df;
- let w13_base = expert_u * w13_stride;
- let bias_base = expert_u * 2 * df;
-
- for h_idx in 0..df {
- // Up projection: dot(x, w_up_row) + bias
- let w_up_offset = w13_base + h_idx * dm;
- let mut acc_up = 0.0f32;
- for d in 0..dm {
- let x_val = unsafe { *x.add(d) }.to_f32().unwrap();
- let w_val = unsafe { *w13_all.add(w_up_offset + d) }.to_f32().unwrap();
- acc_up += x_val * w_val;
- }
-
- // Gate projection (only for SwiGLU/GEGLU)
- let mut acc_gate = 0.0f32;
- if gating_sel > 1 {
- let w_gate_offset = w13_base + (df + h_idx) * dm;
- for d in 0..dm {
- let x_val = unsafe { *x.add(d) }.to_f32().unwrap();
- let w_val = unsafe { *w13_all.add(w_gate_offset + d) }.to_f32().unwrap();
- acc_gate += x_val * w_val;
- }
- }
-
- // Add bias and clip, then activate
- let activated = if gating_sel <= 1 {
- let up_val = (acc_up + unsafe { *biases.add(bias_base + h_idx) }.to_f32().unwrap())
- .clamp(up_clip_min, up_clip_max);
- if gating_sel == 0 {
- ActivationType::GELUApprox.activate(up_val)
- } else {
- activation_silu_alpha(up_val, silu_alpha)
- }
- } else {
- let up_val = (acc_up + unsafe { *biases.add(bias_base + h_idx) }.to_f32().unwrap())
- .clamp(up_clip_min, up_clip_max);
- let gate_val = (acc_gate + unsafe { *biases.add(bias_base + df + h_idx) }.to_f32().unwrap())
- .clamp(gate_clip_min, gate_clip_max);
- let gate_act = if gating_sel == 2 {
- activation_silu_alpha(gate_val, silu_alpha)
- } else {
- ActivationType::GELUApprox.activate(gate_val)
- };
- gate_act * up_val
- };
-
- unsafe {
- *hidden_out.add(k_slot * df + h_idx) = activated;
- }
- }
- }
-}
-
-#[kernel(MoeExpertsDecodeSinglePassB)]
-#[variants(T, f32, f16, bf16)]
-pub fn moe_experts_decode_single_pass_b<T: ArrayElement + Float>(
- hidden: *const f32,
- topk_ids: *const i32,
- topk_probs: *const T,
- w2_all: *const T,
- biases: *const T,
- y: *mut T,
- d_model: u32,
- d_ff: u32,
- k_input: u32,
-) {
- let dm = d_model as usize;
- let df = d_ff as usize;
- let w2_expert_stride = dm * df;
-
- for my_col in 0..dm {
- let mut final_acc = 0.0f32;
-
- for k in 0..k_input as usize {
- let expert_id = unsafe { *topk_ids.add(k) };
- if expert_id < 0 {
- continue;
- }
- let expert_u = expert_id as usize;
- let prob = unsafe { *topk_probs.add(k) }.to_f32().unwrap();
-
- let hidden_offset = k * df;
- let w2_offset = expert_u * w2_expert_stride + my_col * df;
-
- let mut acc = 0.0f32;
- for h in 0..df {
- let h_val = unsafe { *hidden.add(hidden_offset + h) };
- let w_val = unsafe { *w2_all.add(w2_offset + h) }.to_f32().unwrap();
- acc += h_val * w_val;
- }
-
- // Add bias
- acc += unsafe { *biases.add(expert_u * dm + my_col) }.to_f32().unwrap();
- final_acc += prob * acc;
- }
-
- unsafe {
- *y.add(my_col) = T::from(final_acc).unwrap();
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/moe/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/moe/mod.rs
index 5f029d341..fae7fc37e 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/moe/mod.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/moe/mod.rs
@@ -1,5 +1,4 @@
pub mod counts_offsets_fused;
-pub mod experts_single;
pub mod experts_two_pass_decode;
pub mod experts_two_pass_prefill;
pub mod finalize;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/moe/scatter_buckets.rs b/crates/backend-uzu/src/backends/cpu/kernel/moe/scatter_buckets.rs
index 89475c009..a8b4bdc40 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/moe/scatter_buckets.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/moe/scatter_buckets.rs
@@ -17,25 +17,6 @@ pub fn moe_block_bases_from_partials(
todo!()
}
-#[kernel(MoeScatterBuckets)]
-#[variants(T, f32, f16, bf16)]
-pub fn moe_scatter_buckets<T: ArrayElement + Float>(
- #[allow(unused)] topk_ids: *const i32,
- #[allow(unused)] topk_probs: *const T,
- #[allow(unused)] offsets: *const u32,
- #[allow(unused)] block_bases: *const u32,
- #[allow(unused)] block_alloc: *const u32,
- #[allow(unused)] out_ids: *mut i32,
- #[allow(unused)] out_probs: *mut T,
- #[allow(unused)] t: u32,
- #[allow(unused)] e: u32,
- #[allow(unused)] k: u32,
- #[allow(unused)] num_blocks: u32,
- #[allow(unused)] num_tiles: u32,
-) {
- todo!()
-}
-
#[kernel(MoeScatterBucketsMap)]
#[variants(T, f32, f16, bf16)]
pub fn moe_scatter_buckets_map<T: ArrayElement + Float>(
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/normalization/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/normalization/mod.rs
new file mode 100644
index 000000000..2f516bc8a
--- /dev/null
+++ b/crates/backend-uzu/src/backends/cpu/kernel/normalization/mod.rs
@@ -0,0 +1 @@
+pub mod normalization;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/rms_norm/rms_norm.rs b/crates/backend-uzu/src/backends/cpu/kernel/normalization/normalization.rs
similarity index 80%
rename from crates/backend-uzu/src/backends/cpu/kernel/rms_norm/rms_norm.rs
rename to crates/backend-uzu/src/backends/cpu/kernel/normalization/normalization.rs
index 358cf84c3..d15063d4b 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/rms_norm/rms_norm.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/normalization/normalization.rs
@@ -4,12 +4,12 @@ use proc_macros::kernel;
use crate::array::ArrayElement;
-#[kernel(RMSNorm)]
+#[kernel(Normalization)]
#[variants(InputT, f32, f16, bf16)]
#[variants(ScaleT, f32, f16, bf16)]
#[variants(OutputT, f32, f16, bf16)]
-#[variants(AccumT, f32, f16)]
-pub fn rms_norm<
+#[variants(AccumT, f32)]
+pub fn normalization<
InputT: ArrayElement + Float,
ScaleT: ArrayElement + Float,
OutputT: ArrayElement + Float,
@@ -26,6 +26,7 @@ pub fn rms_norm<
scale_offset: f32,
post_layer_scalar: f32,
#[specialize] in_place: bool,
+ #[specialize] subtract_mean: bool,
#[specialize] full_layer: bool,
#[specialize] copy_to_shortcut: bool,
#[specialize] residual_add: bool,
@@ -33,7 +34,9 @@ pub fn rms_norm<
#[specialize] scale_residual_sum: bool,
#[specialize] scale_output: bool,
) {
+ assert_eq!(shortcut.is_some(), copy_to_shortcut);
assert_eq!(hadamard_factors.is_some(), use_hadamard);
+ assert!(copy_to_shortcut || !residual_add);
if use_hadamard {
unimplemented!("not supported yet");
@@ -52,7 +55,8 @@ pub fn rms_norm<
for batch in 0..(batch_size as usize) {
let batch_offset = batch * element_count;
- // Compute rms_inv (+ residual add or copy to shortcut)
+ // Compute mean / rms_inv (+ residual add or copy to shortcut)
+ let mut sum = AccumT::zero();
let mut sum_sq = AccumT::zero();
for i in 0..element_count {
let input_val = unsafe { *input.add(batch_offset + i) };
@@ -62,16 +66,24 @@ pub fn rms_norm<
if residual_add {
val = val + unsafe { *skip_ptr };
if scale_residual_sum {
- val = val * InputT::from(post_layer_scalar).unwrap();
+ val = InputT::from(val.to_f32().unwrap() * post_layer_scalar).unwrap();
}
}
unsafe { *skip_ptr = val };
}
let accum_val = AccumT::from(val).unwrap();
+ if subtract_mean {
+ sum = sum + accum_val;
+ }
sum_sq = sum_sq + accum_val * accum_val;
}
- let mean_sq: AccumT = sum_sq / element_count_accum;
- let rms_inv = AccumT::from((mean_sq + epsilon).to_f32().unwrap().sqrt().recip()).unwrap();
+ let mean = if subtract_mean {
+ sum / element_count_accum
+ } else {
+ AccumT::zero()
+ };
+ let variance = sum_sq / element_count_accum - mean * mean;
+ let rms_inv = AccumT::from((variance + epsilon).to_f32().unwrap().sqrt().recip()).unwrap();
// Normalization and scaling
for i in 0..element_count {
@@ -81,7 +93,7 @@ pub fn rms_norm<
unsafe { AccumT::from(*input.add(batch_offset + i)).unwrap() }
};
let scale_val = unsafe { AccumT::from(*scales.add(i)).unwrap() };
- let normalized: AccumT = input_val * rms_inv;
+ let normalized: AccumT = (input_val - mean) * rms_inv;
let result: OutputT = if full_layer {
// Full-layer: keep everything in accumulation precision
let scale_with_offset: AccumT = scale_val + scale_offset;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/pooling/pooling.rs b/crates/backend-uzu/src/backends/cpu/kernel/pooling/pooling.rs
index 993de1a0d..b01466a54 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/pooling/pooling.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/pooling/pooling.rs
@@ -4,28 +4,6 @@ use proc_macros::kernel;
use crate::array::ArrayElement;
-#[kernel(PoolingCls)]
-#[variants(T, f32, f16, bf16)]
-pub fn pooling_cls<T: ArrayElement + Float>(
- input: *const T,
- output: *mut T,
- seq_len: u32,
- hidden_dim: u32,
- batch_size: u32,
-) {
- let seq_len = seq_len as usize;
- let hidden_dim = hidden_dim as usize;
- let batch_size = batch_size as usize;
-
- for dim_idx in 0..hidden_dim {
- for batch_idx in 0..batch_size {
- unsafe {
- *output.add(batch_idx * hidden_dim + dim_idx) = *input.add(batch_idx * hidden_dim * seq_len + dim_idx);
- }
- }
- }
-}
-
#[kernel(PoolingMean)]
#[variants(T, f32, f16, bf16)]
pub fn pooling_mean<T: ArrayElement + Float>(
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/rms_norm/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/rms_norm/mod.rs
deleted file mode 100644
index a4a62473d..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/rms_norm/mod.rs
+++ /dev/null
@@ -1,2 +0,0 @@
-pub mod qkv_norm;
-pub mod rms_norm;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/rope/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/rope/mod.rs
deleted file mode 100644
index f67f4f08b..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/rope/mod.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub mod rope;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/rope/rope.rs b/crates/backend-uzu/src/backends/cpu/kernel/rope/rope.rs
deleted file mode 100644
index aecc03c90..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/rope/rope.rs
+++ /dev/null
@@ -1,136 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-fn get_paired_val<ElementT: ArrayElement + Float>(
- values: *const ElementT,
- dim_index: usize,
- half_dim: usize,
- token_index: usize,
- total_heads: usize,
- head_dim: usize,
- head_index: usize,
-) -> f32 {
- if dim_index < half_dim {
- let v =
- unsafe { *values.add(token_index * total_heads * head_dim + head_index * head_dim + dim_index + half_dim) };
- -v.to_f32().unwrap()
- } else {
- unsafe {
- (*values.add(token_index * total_heads * head_dim + head_index * head_dim + dim_index - half_dim))
- .to_f32()
- .unwrap()
- }
- }
-}
-
-#[kernel(Rope)]
-#[variants(ElementT, f32, f16, bf16)]
-#[variants(RopeT, f32, f16, bf16)]
-pub fn rope<ElementT: ArrayElement + Float, RopeT: ArrayElement + Float>(
- qkv: *const ElementT,
- cosines: *const RopeT,
- sines: *const RopeT,
- rotated_queries: *mut ElementT,
- #[optional(!query_only)] rotated_keys: Option<*mut ElementT>,
- head_dim: u32,
- rope_dim: u32,
- num_heads: u32,
- #[optional(!query_only)] num_groups: Option<u32>,
- suffix_length: u32,
- #[specialize] query_only: bool,
-) {
- // Query-only projections carry no K/V heads, i.e. num_groups == 0.
- let num_groups = num_groups.unwrap_or(0) as usize;
- if head_dim & 1 != 0 || rope_dim & 1 != 0 || rope_dim > head_dim {
- return;
- }
- if !query_only && (num_groups == 0 || !num_heads.is_multiple_of(num_groups as u32)) {
- return;
- }
-
- let head_dim = head_dim as usize;
- let rope_dim = rope_dim as usize;
- let num_heads = num_heads as usize;
- let suffix_length = suffix_length as usize;
-
- let half_rope_dim = rope_dim / 2;
- let total_heads = num_heads + 2 * num_groups;
- let heads_per_group = num_heads / num_groups.max(1);
-
- for head_index in 0..num_heads {
- let group_index = head_index / heads_per_group;
-
- for token_index in 0..suffix_length {
- // Rotated dimensions: apply RoPE to dims 0..rope_dim
- for dim_index in 0..rope_dim {
- let cos_val = unsafe { (*cosines.add(token_index * rope_dim + dim_index)).to_f32().unwrap() };
- let sin_val = unsafe { (*sines.add(token_index * rope_dim + dim_index)).to_f32().unwrap() };
-
- // Query rotation
- let q_val = unsafe {
- (*qkv.add(token_index * total_heads * head_dim + head_index * head_dim + dim_index))
- .to_f32()
- .unwrap()
- };
- let q_paired =
- get_paired_val(qkv, dim_index, half_rope_dim, token_index, total_heads, head_dim, head_index);
- let q_result = q_val * cos_val + q_paired * sin_val;
- unsafe {
- *rotated_queries.add(head_index * suffix_length * head_dim + token_index * head_dim + dim_index) =
- ElementT::from(q_result).unwrap();
- }
-
- // Key rotation (fused only; first head of each group)
- if !query_only && head_index == group_index * heads_per_group {
- let key_head_index = num_heads + group_index;
- let k_val = unsafe {
- (*qkv.add(token_index * total_heads * head_dim + key_head_index * head_dim + dim_index))
- .to_f32()
- .unwrap()
- };
- let k_paired = get_paired_val(
- qkv,
- dim_index,
- half_rope_dim,
- token_index,
- total_heads,
- head_dim,
- key_head_index,
- );
- let k_result = k_val * cos_val + k_paired * sin_val;
- unsafe {
- *rotated_keys
- .unwrap()
- .add(group_index * suffix_length * head_dim + token_index * head_dim + dim_index) =
- ElementT::from(k_result).unwrap();
- }
- }
- }
-
- // Pass-through dimensions: copy dims rope_dim..head_dim unchanged
- for dim_index in rope_dim..head_dim {
- let q_val =
- unsafe { *qkv.add(token_index * total_heads * head_dim + head_index * head_dim + dim_index) };
- unsafe {
- *rotated_queries.add(head_index * suffix_length * head_dim + token_index * head_dim + dim_index) =
- q_val;
- }
-
- if !query_only && head_index == group_index * heads_per_group {
- let key_head_index = num_heads + group_index;
- let k_val = unsafe {
- *qkv.add(token_index * total_heads * head_dim + key_head_index * head_dim + dim_index)
- };
- unsafe {
- *rotated_keys
- .unwrap()
- .add(group_index * suffix_length * head_dim + token_index * head_dim + dim_index) = k_val;
- }
- }
- }
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/sampling/context_ring_update.rs b/crates/backend-uzu/src/backends/cpu/kernel/sampling/context_ring_update.rs
new file mode 100644
index 000000000..219d76ed6
--- /dev/null
+++ b/crates/backend-uzu/src/backends/cpu/kernel/sampling/context_ring_update.rs
@@ -0,0 +1,29 @@
+use proc_macros::kernel;
+
+use crate::backends::common::gpu_types::ring::RingParams;
+
+#[kernel(ContextRingUpdate)]
+pub fn context_ring_update(
+ input: *const u64,
+ context_ring: *mut u32,
+ suffix_repetition_length: u32,
+ input_length: u32,
+) {
+ unsafe {
+ let ring = &mut *context_ring.cast::<RingParams>();
+ let ring_tokens = context_ring.add(2);
+
+ for input_index in 0..input_length {
+ let slot = if ring.ring_length < suffix_repetition_length {
+ let slot = (ring.ring_offset + ring.ring_length) % suffix_repetition_length;
+ ring.ring_length += 1;
+ slot
+ } else {
+ let slot = ring.ring_offset;
+ ring.ring_offset = (ring.ring_offset + 1) % suffix_repetition_length;
+ slot
+ };
+ *ring_tokens.add(slot as usize) = *input.add(input_index as usize) as u32;
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/sampling/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/sampling/mod.rs
index 6a251ef64..5c44793ca 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/sampling/mod.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/sampling/mod.rs
@@ -1,2 +1,3 @@
+pub mod context_ring_update;
pub mod repetition_penalty;
pub mod unified_sampling;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/sampling/repetition_penalty.rs b/crates/backend-uzu/src/backends/cpu/kernel/sampling/repetition_penalty.rs
index 7546210c3..1b5f3e78b 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/sampling/repetition_penalty.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/sampling/repetition_penalty.rs
@@ -13,34 +13,49 @@ pub fn repetition_penalty<T: ArrayElement + Float + NumCast>(
token_ids: *const u64,
repetition_penalty: f32,
suffix_repetition_length: u32,
+ vocab_size: u32,
+ sampling_start: u32,
+ sampling_length: u32,
) {
fn apply<T: ArrayElement + Float + NumCast>(
original_logits: *const T,
logits_copy: *mut T,
+ vocab_size: usize,
+ sample_index: usize,
token_id: usize,
repetition_penalty: f32,
) {
- let logit = unsafe { (*original_logits.add(token_id)).to_f32().unwrap() };
+ let offset = sample_index * vocab_size + token_id;
+ let logit = unsafe { (*original_logits.add(offset)).to_f32().unwrap() };
let penalized = if logit > 0.0 {
logit / repetition_penalty
} else {
logit * repetition_penalty
};
unsafe {
- *logits_copy.add(token_id) = NumCast::from(penalized).unwrap();
+ *logits_copy.add(offset) = NumCast::from(penalized).unwrap();
}
}
let ring = unsafe { &*context_ring.cast::<RingParams>() };
let ring_tokens = unsafe { context_ring.add(2) };
+ let vocab_size = vocab_size as usize;
- apply(original_logits, logits_copy, unsafe { *token_ids } as usize, repetition_penalty);
+ for sample_index in 0..sampling_length {
+ let batch_prefix_length = sampling_start + sample_index + 1;
+ let total_length = ring.ring_length + batch_prefix_length;
+ let window_length = total_length.min(suffix_repetition_length);
+ let skipped_length = total_length - window_length;
- for ring_index in 0..suffix_repetition_length {
- if ring_index >= ring.ring_length {
- continue;
+ for window_index in 0..window_length {
+ let source_index = skipped_length + window_index;
+ let token_id = if source_index < ring.ring_length {
+ let slot = (ring.ring_offset + source_index) % suffix_repetition_length;
+ (unsafe { *ring_tokens.add(slot as usize) }) as usize
+ } else {
+ (unsafe { *token_ids.add((source_index - ring.ring_length) as usize) }) as usize
+ };
+ apply(original_logits, logits_copy, vocab_size, sample_index as usize, token_id, repetition_penalty);
}
- let slot = (ring.ring_offset + ring_index) % suffix_repetition_length;
- apply(original_logits, logits_copy, unsafe { *ring_tokens.add(slot as usize) } as usize, repetition_penalty)
}
}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/sampling/unified_sampling.rs b/crates/backend-uzu/src/backends/cpu/kernel/sampling/unified_sampling.rs
index 535e1f7f6..2e2b79548 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/sampling/unified_sampling.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/sampling/unified_sampling.rs
@@ -6,7 +6,7 @@ use proc_macros::kernel;
use crate::{
array::ArrayElement,
- language_model::gumbel::{gumbel_float, revidx},
+ encodable_block::sampling::{gumbel_float, revidx},
};
// NOTE: top_k + top_p combination is not exactly matching lalamo ("parallel" here, should be top-k then top-p)
@@ -26,7 +26,6 @@ pub fn unified_sampling<T: ArrayElement + Float>(
#[specialize] is_stochastic: bool,
#[specialize] has_bitmask: bool,
#[specialize] has_temperature: bool,
- #[specialize] temperature_after_filters: bool,
#[specialize] has_top_k: bool,
#[specialize] has_top_p: bool,
#[specialize] has_min_p: bool,
@@ -53,7 +52,7 @@ pub fn unified_sampling<T: ArrayElement + Float>(
}
}
- if has_temperature && !temperature_after_filters {
+ if has_temperature {
let recip_temperature = 1.0 / temperature.unwrap();
for logit in logits.iter_mut() {
*logit *= recip_temperature;
@@ -81,13 +80,6 @@ pub fn unified_sampling<T: ArrayElement + Float>(
}
}
- if has_temperature && temperature_after_filters {
- let recip_temperature = 1.0 / temperature.unwrap();
- for logit in logits.iter_mut() {
- *logit *= recip_temperature;
- }
- }
-
if is_stochastic {
let seed = unsafe { *seeds.unwrap().wrapping_add(batch_idx as usize) };
for (logit_index, logit) in logits.iter_mut().enumerate() {
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/ssm/ssd_prefill.rs b/crates/backend-uzu/src/backends/cpu/kernel/ssm/ssd_prefill.rs
index f44f7f753..20fca667a 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/ssm/ssd_prefill.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/ssm/ssd_prefill.rs
@@ -2,7 +2,7 @@ use half::{bf16, f16};
use num_traits::Float;
use proc_macros::kernel;
-use crate::{array::ArrayElement, backends::common::gpu_types::ActivationType};
+use crate::array::ArrayElement;
#[kernel(SSDPrefill64)]
#[variants(T, f32, f16, bf16)]
@@ -51,67 +51,3 @@ pub fn ssd_prefill<T: ArrayElement + Float>(
) {
todo!()
}
-
-#[kernel(SSDPrefillSequential)]
-#[variants(T, f32, f16, bf16)]
-pub fn ssd_prefill_sequential<T: ArrayElement + Float>(
- x: *const T,
- dt_raw: *const T,
- b: *const T,
- c: *const T,
- d: *const T,
- z: *const T,
- state: *mut T,
- y: *mut T,
- suffix_len: u32,
- group_size: u32,
- state_size: u32,
- x_strides: &[u32; 3],
- dt_strides: &[u32; 2],
- cb_strides: &[u32; 3],
- state_strides: &[u32; 3],
- channels: u32,
- head_dim: u32,
-) {
- let suffix_len = suffix_len as usize;
- let group_size = group_size as usize;
- let state_size = state_size as usize;
- let channels = channels as usize;
- let head_dim = head_dim as usize;
-
- let safe_group = group_size.max(1);
-
- unsafe {
- for h in 0..channels {
- let group_idx = h / safe_group;
- for dh in 0..head_dim {
- let state_base = h * state_strides[0] as usize + dh * state_strides[1] as usize;
- for token in 0..suffix_len {
- let x_idx = token * x_strides[0] as usize + h * x_strides[1] as usize + dh * x_strides[2] as usize;
- let dt_idx = token * dt_strides[0] as usize + h * dt_strides[1] as usize;
- let cb_base = token * cb_strides[0] as usize + group_idx * cb_strides[1] as usize;
-
- let x_val = *x.add(x_idx);
- let dt_raw = *dt_raw.add(dt_idx);
- let dt_val = ActivationType::SOFTPLUS.activate(dt_raw);
- let decay_val = (-dt_val).exp();
- let dt_scaled_input = x_val;
-
- let mut acc = *d.add(h) * x_val;
- for s in 0..state_size {
- let state_idx = state_base + s * state_strides[2] as usize;
- let cb_idx = cb_base + s * cb_strides[2] as usize;
- let b_coeff = *b.add(cb_idx);
- let c_coeff = *c.add(cb_idx);
- let new_state = decay_val * *state.add(state_idx) + dt_scaled_input * b_coeff;
- *state.add(state_idx) = new_state;
- acc = acc + new_state * c_coeff;
- }
-
- let gate = ActivationType::SILU.activate(*z.add(x_idx));
- *y.add(x_idx) = acc * gate;
- }
- }
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/token_copy/token_copy.rs b/crates/backend-uzu/src/backends/cpu/kernel/token_copy/token_copy.rs
index 693ce9517..9fbbb175c 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/token_copy/token_copy.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/token_copy/token_copy.rs
@@ -1,45 +1,12 @@
use proc_macros::kernel;
-use crate::backends::common::gpu_types::ring::RingParams;
-
#[kernel(TokenCopySampled)]
pub fn token_copy_sampled(
- #[allow(unused)] src: *const u32,
- #[allow(unused)] dst: *mut u64,
- #[optional(has_context_ring)] context_ring: Option<*mut u32>,
- #[optional(has_context_ring)] suffix_repetition_length: Option<u32>,
- #[specialize] has_context_ring: bool,
+ src: *const u32,
+ dst: *mut u64,
) {
unsafe {
let token = *src.add(0);
*dst.add(0) = token as u64;
-
- if has_context_ring {
- let suffix_repetition_length = suffix_repetition_length.unwrap();
-
- let context_ring = context_ring.unwrap();
- let ring = &mut *context_ring.cast::<RingParams>();
- let ring_tokens = context_ring.add(2);
- let slot = if ring.ring_length < suffix_repetition_length {
- let slot = (ring.ring_offset + ring.ring_length) % suffix_repetition_length;
- ring.ring_length += 1;
- slot
- } else {
- let slot = ring.ring_offset;
- ring.ring_offset = (ring.ring_offset + 1) % suffix_repetition_length;
- slot
- };
- *ring_tokens.add(slot as usize) = token;
- }
- }
-}
-
-#[kernel(TokenCopyToResults)]
-pub fn token_copy_to_results(
- #[allow(unused)] src: *const u32,
- #[allow(unused)] dst: *mut u32,
-) {
- unsafe {
- *dst.add(0) = *src.add(0);
}
}
diff --git a/crates/backend-uzu/src/backends/metal/buffer.rs b/crates/backend-uzu/src/backends/metal/buffer.rs
index 0e8f82e9d..d7af99e38 100644
--- a/crates/backend-uzu/src/backends/metal/buffer.rs
+++ b/crates/backend-uzu/src/backends/metal/buffer.rs
@@ -8,14 +8,10 @@ use crate::backends::{
metal::{Metal, sparse::MetalSparseBuffer},
};
-pub trait BufferDowncastExt: Buffer<Backend = Metal> {
- fn downcast(&self) -> &Retained<ProtocolObject<dyn MTLBuffer>>;
-}
-
-impl<B: Buffer<Backend = Metal>> BufferDowncastExt for B {
- fn downcast(&self) -> &Retained<ProtocolObject<dyn MTLBuffer>> {
+impl dyn Buffer<Backend = Metal> {
+ pub fn downcast(&self) -> &Retained<ProtocolObject<dyn MTLBuffer>> {
let buffer = self as &dyn Any;
- if let Some(buffer) = buffer.downcast_ref::<<<B as Buffer>::Backend as Backend>::DenseBuffer>() {
+ if let Some(buffer) = buffer.downcast_ref::<<Metal as Backend>::DenseBuffer>() {
buffer
} else if let Some(buffer) = buffer.downcast_ref::<MetalSparseBuffer>() {
buffer.mtl_buffer()
diff --git a/crates/backend-uzu/src/backends/metal/command_buffer.rs b/crates/backend-uzu/src/backends/metal/command_buffer.rs
index b4e96c831..2bf91d8b8 100644
--- a/crates/backend-uzu/src/backends/metal/command_buffer.rs
+++ b/crates/backend-uzu/src/backends/metal/command_buffer.rs
@@ -1,18 +1,17 @@
-use std::{cell::Cell, rc::Rc, time::Duration};
+use std::{rc::Rc, time::Duration};
use metal::{
- MTLBlitCommandEncoder, MTLBlitCommandEncoderExt, MTLCommandBuffer, MTLCommandBufferExt, MTLCommandBufferHandler,
- MTLCommandBufferStatus, MTLCommandEncoder, MTLCommandQueue, MTLComputeCommandEncoder,
+ MTLBlitCommandEncoder, MTLBlitCommandEncoderExt, MTLCommandBuffer, MTLCommandBufferExt, MTLCommandBufferStatus,
+ MTLCommandEncoder, MTLCommandQueue, MTLComputeCommandEncoder,
};
-use objc2::{Message, rc::Retained, runtime::ProtocolObject};
+use objc2::{rc::Retained, runtime::ProtocolObject};
-use super::{Metal, buffer::BufferDowncastExt};
use crate::backends::{
common::{
AccessFlags, Buffer, BufferRangeMut, BufferRangeRef, CommandBuffer, CommandBufferCompleted,
CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
},
- metal::{MetalContext, error::MetalError},
+ metal::{Metal, MetalContext, error::MetalError},
};
pub struct MetalCommandBuffer;
@@ -27,14 +26,6 @@ impl CommandBuffer for MetalCommandBuffer {
type Completed = MetalCommandBufferCompleted;
}
-fn command_buffer_result(command_buffer: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
- match (command_buffer.status(), command_buffer.error()) {
- (MTLCommandBufferStatus::Completed, None) => Ok(()),
- (status, Some(nserror)) => Err(MetalError::CommandBufferExecutionFailed(format!("{status:?}: {nserror:?}"))),
- (status, None) => Err(MetalError::CommandBufferExecutionFailed(format!("{status:?}"))),
- }
-}
-
pub struct MetalCommandBufferInitial {
command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
context: Rc<MetalContext>,
@@ -135,9 +126,9 @@ impl CommandBufferEncoding for MetalCommandBufferEncoding {
assert_eq!(src_range.len(), dst_range.len());
self.ensure_blit().copy_buffer_to_buffer(
- src.buffer().downcast(),
+ (src.buffer() as &dyn Buffer<Backend = Metal>).downcast(),
src_range.start,
- dst.buffer().downcast(),
+ (dst.buffer() as &dyn Buffer<Backend = Metal>).downcast(),
dst_range.start,
src_range.len(),
);
@@ -152,7 +143,11 @@ impl CommandBufferEncoding for MetalCommandBufferEncoding {
assert!(range.end > range.start);
assert!(range.start.is_multiple_of(4) && range.end.is_multiple_of(4));
- self.ensure_blit().fill_buffer_range_value(dst.buffer().downcast(), range, value);
+ self.ensure_blit().fill_buffer_range_value(
+ (dst.buffer() as &dyn Buffer<Backend = Metal>).downcast(),
+ range,
+ value,
+ );
}
fn encode_barrier(
@@ -162,21 +157,6 @@ impl CommandBufferEncoding for MetalCommandBufferEncoding {
) {
}
- fn add_completion_handler(
- &mut self,
- handler: impl FnOnce(Result<&MetalCommandBufferCompleted, MetalError>) + Send + 'static,
- ) {
- let cell = Cell::new(Some(handler));
- self.command_buffer.add_completed_handler(&MTLCommandBufferHandler::new(move |command_buffer| {
- let cbuf_ref = MetalCommandBufferCompleted {
- command_buffer: command_buffer.retain(),
- };
- cell.take().expect("completion handler called more than once")(
- command_buffer_result(command_buffer).map(|_| &cbuf_ref),
- )
- }));
- }
-
fn end_encoding(mut self) -> <Self::CommandBuffer as CommandBuffer>::Executable {
self.ensure_none();
@@ -229,7 +209,15 @@ impl CommandBufferPending for MetalCommandBufferPending {
fn wait_until_completed(self) -> Result<MetalCommandBufferCompleted, MetalError> {
self.command_buffer.wait_until_completed();
- command_buffer_result(&self.command_buffer).map(|_| MetalCommandBufferCompleted {
+ match (self.command_buffer.status(), self.command_buffer.error()) {
+ (MTLCommandBufferStatus::Completed, None) => (),
+ (status, Some(nserror)) => {
+ return Err(MetalError::CommandBufferExecutionFailed(format!("{status:?}: {nserror:?}")));
+ },
+ (status, None) => return Err(MetalError::CommandBufferExecutionFailed(format!("{status:?}"))),
+ }
+
+ Ok(MetalCommandBufferCompleted {
command_buffer: self.command_buffer,
})
}
diff --git a/crates/backend-uzu/src/backends/metal/context.rs b/crates/backend-uzu/src/backends/metal/context.rs
index c82022df5..e2c583fc1 100644
--- a/crates/backend-uzu/src/backends/metal/context.rs
+++ b/crates/backend-uzu/src/backends/metal/context.rs
@@ -22,15 +22,12 @@ use super::{
kernel,
metal_extensions::{DeviceExt, LibraryPipelineExtensions},
};
-use crate::{
- backends::{
- common::{Allocation, AllocationPool, AllocationType, Allocator, Backend, Context},
- metal::{
- command_buffer::MetalCommandBufferInitial,
- sparse::{MetalSparseBuffer, MetalSparseHeapPool, MetalSparseMappingOpsBatch},
- },
+use crate::backends::{
+ common::{Allocation, AllocationPool, AllocationType, Allocator, Backend, Context},
+ metal::{
+ command_buffer::MetalCommandBufferInitial,
+ sparse::{MetalSparseBuffer, MetalSparseHeapPool, MetalSparseMappingOpsBatch},
},
- utils::model_size::ModelSize,
};
pub struct MetalContext {
@@ -41,7 +38,6 @@ pub struct MetalContext {
timeline_value: AtomicU64,
allocator: Rc<Allocator<Metal>>,
peak_memory_usage: RefCell<usize>,
- gpu_core_count: u32,
library: Retained<ProtocolObject<dyn MTLLibrary>>,
pipeline_cache: RefCell<HashMap<String, Retained<ProtocolObject<dyn MTLComputePipelineState>>>>,
sparse_heap_pool: RefCell<MetalSparseHeapPool>,
@@ -152,7 +148,6 @@ impl Context for MetalContext {
timeline_value: AtomicU64::new(0),
allocator: Allocator::new(weak_self.clone()),
peak_memory_usage: RefCell::new(0),
- gpu_core_count,
library,
pipeline_cache: RefCell::new(HashMap::new()),
sparse_heap_pool: RefCell::new(sparse_pool),
@@ -163,22 +158,6 @@ impl Context for MetalContext {
}))
}
- fn recommended_async_batch_size(
- &self,
- model_path: &Path,
- ) -> Result<usize, MetalError> {
- let cores = self.gpu_core_count;
- let model_size = ModelSize::from_path(model_path)?;
- Ok(match (model_size, cores) {
- (ModelSize::Large, c) if c > 20 => 32,
- (ModelSize::Large, c) if c > 10 => 16,
- (ModelSize::Large, _) => 8,
- (ModelSize::Small, c) if c > 20 => 256,
- (ModelSize::Small, c) if c > 10 => 128,
- (ModelSize::Small, _) => 64,
- })
- }
-
fn create_buffer(
&self,
size: usize,
diff --git a/crates/backend-uzu/src/backends/metal/kernel/activation/activations.h b/crates/backend-uzu/src/backends/metal/kernel/activation/activations.h
index a369e4bd6..ae2221399 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/activation/activations.h
+++ b/crates/backend-uzu/src/backends/metal/kernel/activation/activations.h
@@ -79,11 +79,6 @@ inline T activate_softplus(T x) {
return static_cast<T>(result);
}
-template <typename T>
-inline T activate_tanh(T x) {
- return static_cast<T>(metal::tanh(float(x)));
-}
-
template <typename T>
inline T activate(T x, ActivationType type) {
switch (type) {
@@ -93,8 +88,6 @@ inline T activate(T x, ActivationType type) {
return activate_gelu(x);
case ActivationType::GELUExact:
return activate_gelu_exact(x);
- case ActivationType::TANH:
- return activate_tanh(x);
case ActivationType::IDENTITY:
return x;
case ActivationType::SOFTPLUS:
diff --git a/crates/backend-uzu/src/backends/metal/kernel/attention/attention_prepare.metal b/crates/backend-uzu/src/backends/metal/kernel/attention/attention_prepare.metal
new file mode 100644
index 000000000..272505e95
--- /dev/null
+++ b/crates/backend-uzu/src/backends/metal/kernel/attention/attention_prepare.metal
@@ -0,0 +1,73 @@
+#include "../common/dsl.h"
+
+// TODO: very ugly and wasteful, clean up and optimize
+
+template <typename ElementT, typename RopeT>
+METAL_FUNC ElementT apply_rope(
+ const device ElementT* head,
+ const device RopeT* cosines,
+ const device RopeT* sines,
+ uint32_t batch_idx,
+ uint32_t head_dim_idx,
+ uint32_t rope_dim
+) {
+ const uint32_t half_rope_dim = rope_dim / 2;
+ const uint32_t paired_idx =
+ head_dim_idx < half_rope_dim ? head_dim_idx + half_rope_dim : head_dim_idx - half_rope_dim;
+ const float input = float(head[head_dim_idx]);
+ const float paired = float(head[paired_idx]);
+ const float signed_paired = head_dim_idx < half_rope_dim ? -paired : paired;
+ const float cos_val = float(cosines[batch_idx * rope_dim + head_dim_idx]);
+ const float sin_val = float(sines[batch_idx * rope_dim + head_dim_idx]);
+
+ return static_cast<ElementT>(input * cos_val + signed_paired * sin_val);
+}
+
+template <typename ElementT, typename RopeT>
+VARIANTS(ElementT, bfloat)
+VARIANTS(RopeT, float)
+PUBLIC KERNEL(AttentionPrepare) (
+ const device ElementT* qkv, // [token, (q, k, v), head_dim]
+ device ElementT* queries, // [head_idx, token, head_dim]
+ device ElementT* keys OPTIONAL(has_kv), // [(kv_token_offset + token), head_idx, head_dim]
+ device ElementT* values OPTIONAL(has_kv), // [(kv_token_offset + token), head_idx, head_dim]
+ const device RopeT* cosines OPTIONAL(has_rope),
+ const device RopeT* sines OPTIONAL(has_rope),
+ const constant uint32_t& num_q_heads,
+ const constant uint32_t& num_kv_heads OPTIONAL(has_kv),
+ const constant uint32_t& head_dim,
+ const constant uint32_t& rope_dim OPTIONAL(has_rope),
+ const constant uint32_t& kv_token_offset OPTIONAL(has_kv),
+ const constant uint32_t& batch_dim,
+ const bool has_kv SPECIALIZE,
+ const bool has_rope SPECIALIZE,
+ const uint32_t head_dim_idx AXIS(head_dim, 128),
+ const uint32_t head_idx AXIS(num_q_heads + num_kv_heads.unwrap_or(0) * 2, 1),
+ const uint32_t batch_idx AXIS(batch_dim, 1)
+) {
+ const uint32_t total_heads = has_kv ? num_q_heads + num_kv_heads * 2 : num_q_heads;
+ const uint32_t qkv_head_idx = batch_idx * total_heads * head_dim + head_idx * head_dim;
+ const device ElementT* qkv_head = qkv + qkv_head_idx;
+ const bool is_query = !has_kv || head_idx < num_q_heads;
+ const bool is_key = has_kv && head_idx >= num_q_heads && head_idx < num_q_heads + num_kv_heads;
+
+ ElementT element = qkv_head[head_dim_idx];
+ if (has_rope && head_dim_idx < rope_dim && (is_query || is_key)) {
+ element = apply_rope(qkv_head, cosines, sines, batch_idx, head_dim_idx, rope_dim);
+ }
+
+ if (is_query) {
+ const uint32_t q_idx = head_idx * batch_dim * head_dim + batch_idx * head_dim + head_dim_idx;
+ queries[q_idx] = element;
+ } else if (is_key) {
+ const uint32_t k_idx =
+ (kv_token_offset + batch_idx) * num_kv_heads * head_dim + (head_idx - num_q_heads) * head_dim + head_dim_idx;
+
+ keys[k_idx] = element;
+ } else if (has_kv) {
+ const uint32_t v_idx = (kv_token_offset + batch_idx) * num_kv_heads * head_dim +
+ (head_idx - num_q_heads - num_kv_heads) * head_dim + head_dim_idx;
+
+ values[v_idx] = element;
+ }
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/attention/attention_update_kv_cache.metal b/crates/backend-uzu/src/backends/metal/kernel/attention/attention_update_kv_cache.metal
deleted file mode 100644
index f8dcd5365..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/attention/attention_update_kv_cache.metal
+++ /dev/null
@@ -1,44 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(AttentionUpdateKVCache)(
- const device T* rotated_keys OPTIONAL(!keys_in_place),
- const device T* qkv,
- device T* key_cache,
- device T* value_cache,
- const constant uint& num_groups,
- const constant uint& num_heads,
- const constant uint& head_dim,
- const constant uint& suffix_length,
- const constant uint& prefix_segment_length,
- const constant uint& max_sequence_length,
- const uint group_index AXIS(num_groups, 1),
- const uint token_index AXIS(suffix_length, 1),
- const uint dim_index AXIS(head_dim, 64),
- const bool keys_in_place SPECIALIZE
-) {
- if (keys_in_place) {
- rotated_keys = key_cache;
- }
-
- const uint cacheTokenIndex = prefix_segment_length + token_index;
-
- // keys_in_place=true: destination shares rotated_keys' group-major layout.
- // Otherwise, KV cache is token-major:
- // [max_sequence_length, num_groups, head_dim].
- const uint cacheOffset = keys_in_place
- ? ((group_index * max_sequence_length + cacheTokenIndex) * head_dim + dim_index)
- : ((cacheTokenIndex * num_groups + group_index) * head_dim + dim_index);
-
- const uint rotatedKeyOffset = (group_index * suffix_length + token_index) * head_dim + dim_index;
- key_cache[cacheOffset] = rotated_keys[rotatedKeyOffset];
-
- // qkv layout: [suffix_length, (num_heads + 2*num_groups) * head_dim]
- // Values start at offset: (num_heads * head_dim) + (num_groups * head_dim)
- const uint qkvStride = (num_heads + 2 * num_groups) * head_dim;
- const uint valueBaseOffset = (num_heads + num_groups) * head_dim;
- const uint valueOffset = token_index * qkvStride + valueBaseOffset + group_index * head_dim + dim_index;
- value_cache[cacheOffset] = qkv[valueOffset];
-}
\ No newline at end of file
diff --git a/crates/backend-uzu/src/backends/metal/kernel/attention/kv_cache_update.metal b/crates/backend-uzu/src/backends/metal/kernel/attention/kv_cache_update.metal
new file mode 100644
index 000000000..851e8661b
--- /dev/null
+++ b/crates/backend-uzu/src/backends/metal/kernel/attention/kv_cache_update.metal
@@ -0,0 +1,23 @@
+#include <metal_stdlib>
+#include "../common/dsl.h"
+
+#include "kv_cache_update.h"
+
+template <typename T>
+VARIANTS(T, float, bfloat, half)
+PUBLIC KERNEL(KVCacheUpdate) (
+ device T* in_place_keys,
+ device T* in_place_values,
+ const constant uzu::kv_cache_update::Copy* copies,
+ const constant uint& copy_count,
+ const constant uint& element_dim,
+ const uint element_idx AXIS(element_dim, 256)
+) {
+ for (uint i = 0; i < copy_count; ++i) {
+ const uint sourceIdx = copies[i].source * element_dim + element_idx;
+ const uint destIdx = copies[i].destination * element_dim + element_idx;
+
+ in_place_keys[destIdx] = in_place_keys[sourceIdx];
+ in_place_values[destIdx] = in_place_values[sourceIdx];
+ }
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/attention/qk_unpack.metal b/crates/backend-uzu/src/backends/metal/kernel/attention/qk_unpack.metal
deleted file mode 100644
index b2b19ff5e..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/attention/qk_unpack.metal
+++ /dev/null
@@ -1,37 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-#include "../common/tensor_view.h"
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(QkUnpack)(
- device const T* qkv, // [suffix_len, (num_heads + 2*num_groups) * head_dim]
- device T* unpacked_queries, // [num_heads, suffix_len, head_dim]
- device T* unpacked_keys, // [num_groups, suffix_len, head_dim]
- constant uint& head_dim,
- constant uint& num_heads,
- constant uint& num_groups,
- constant uint& suffix_length,
- const uint head_index AXIS(num_heads, 1),
- const uint token_index AXIS(suffix_length, 1),
- const uint dimension_index AXIS(head_dim, 128)
-) {
- const uint group_index = head_index / (num_heads / num_groups);
- const uint total_heads = num_heads + 2 * num_groups;
- const uint first_head_in_group = group_index * (num_heads / num_groups);
-
- TensorView3D<const T> qkv_tensor_view = TensorView3D<const T>(qkv).shaped(suffix_length, total_heads, head_dim);
- TensorView3D<T> unpacked_queries_tensor_view =
- TensorView3D<T>(unpacked_queries).shaped(num_heads, suffix_length, head_dim);
- TensorView3D<T> unpacked_keys_tensor_view =
- TensorView3D<T>(unpacked_keys).shaped(num_groups, suffix_length, head_dim);
-
- unpacked_queries_tensor_view(head_index, token_index, dimension_index) =
- qkv_tensor_view(token_index, head_index, dimension_index);
-
- if (head_index == first_head_in_group) {
- const uint key_head_index = num_heads + group_index;
- unpacked_keys_tensor_view(group_index, token_index, dimension_index) =
- qkv_tensor_view(token_index, key_head_index, dimension_index);
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/rms_norm/qkv_norm.metal b/crates/backend-uzu/src/backends/metal/kernel/attention/qkv_norm.metal
similarity index 100%
rename from crates/backend-uzu/src/backends/metal/kernel/rms_norm/qkv_norm.metal
rename to crates/backend-uzu/src/backends/metal/kernel/attention/qkv_norm.metal
diff --git a/crates/backend-uzu/src/backends/metal/kernel/audio/add.metal b/crates/backend-uzu/src/backends/metal/kernel/audio/add.metal
deleted file mode 100644
index a2cb4ffe5..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/audio/add.metal
+++ /dev/null
@@ -1,24 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-using namespace metal;
-
-template <typename T>
-void add_tensors(device const T* a, device const T* b, device T* out, const constant int& n, const uint tid) {
- if ((int)tid >= n) {
- return;
- }
- out[tid] = a[tid] + b[tid];
-}
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(AudioAdd)(
- device const T* a,
- device const T* b,
- device T* out,
- const constant int& n,
- uint tid AXIS(n, 256)
-) {
- add_tensors<T>(a, b, out, n, tid);
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv1d.metal b/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv1d.metal
deleted file mode 100644
index 2f29db10e..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv1d.metal
+++ /dev/null
@@ -1,160 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-using namespace metal;
-
-constant uint AUDIO_TIME_TILE = 4;
-constant int AUDIO_LAYOUT_NCS = 0;
-constant int AUDIO_LAYOUT_NSC = 1;
-
-template <typename T>
-void causal_conv1d(
- device const T* input, // [B, Cin, T] when NCS, [B, T, Cin] when NSC
- device const T* weight, // [Cout, Cin, K]
- device const T* bias, // [Cout]
- device T* output, // [B, Cout, T]
- device const int* lengths, // [B]
- const constant int& cin,
- const constant int& cout,
- const constant int& seq_len,
- const constant int& kernel_size,
- const constant int& dilation,
- const constant int& input_layout,
- const uint3 gid
-) {
- const uint t = gid.x * AUDIO_TIME_TILE;
- const uint oc = gid.y;
- const uint b = gid.z;
-
- if (t >= (uint)seq_len || oc >= (uint)cout) {
- return;
- }
-
- if (input_layout != AUDIO_LAYOUT_NCS && input_layout != AUDIO_LAYOUT_NSC) {
- return;
- }
-
- const int len_b = lengths ? lengths[b] : seq_len;
- const uint out_base = (b * (uint)cout + oc) * (uint)seq_len + t;
- int lane_count = seq_len - (int)t;
- if (lane_count > (int)AUDIO_TIME_TILE) {
- lane_count = (int)AUDIO_TIME_TILE;
- }
- if (lane_count <= 0) {
- return;
- }
- int valid_count = len_b - (int)t;
- if (valid_count > lane_count) {
- valid_count = lane_count;
- }
- if (valid_count < 0) {
- valid_count = 0;
- }
-
- const int pad = (kernel_size - 1) * dilation;
- const float bias_value = float(bias[oc]);
- float acc0 = bias_value;
- float acc1 = bias_value;
- float acc2 = bias_value;
- float acc3 = bias_value;
-
- if (valid_count > 0) {
- const bool full_tile = valid_count == (int)AUDIO_TIME_TILE;
- for (int ic = 0; ic < cin; ++ic) {
- const uint w_base = (oc * (uint)cin + (uint)ic) * (uint)kernel_size;
- const uint x_base_ncs = (b * (uint)cin + (uint)ic) * (uint)seq_len;
- for (int k = 0; k < kernel_size; ++k) {
- const float w = float(weight[w_base + (uint)k]);
- const int x_t = (int)t + k * dilation - pad;
- if (full_tile && x_t >= 0 && x_t + 3 < seq_len) {
- if (input_layout == AUDIO_LAYOUT_NCS) {
- const uint x_idx = x_base_ncs + (uint)x_t;
- acc0 += w * float(input[x_idx]);
- acc1 += w * float(input[x_idx + 1]);
- acc2 += w * float(input[x_idx + 2]);
- acc3 += w * float(input[x_idx + 3]);
- } else {
- const uint x_idx0 = (b * (uint)seq_len + (uint)x_t) * (uint)cin + (uint)ic;
- acc0 += w * float(input[x_idx0]);
- acc1 += w * float(input[x_idx0 + (uint)cin]);
- acc2 += w * float(input[x_idx0 + (uint)(2 * cin)]);
- acc3 += w * float(input[x_idx0 + (uint)(3 * cin)]);
- }
- continue;
- }
- if (valid_count > 0 && x_t >= 0 && x_t < seq_len) {
- const uint x_idx = (input_layout == AUDIO_LAYOUT_NCS)
- ? (x_base_ncs + (uint)x_t)
- : ((b * (uint)seq_len + (uint)x_t) * (uint)cin + (uint)ic);
- acc0 += w * float(input[x_idx]);
- }
- if (valid_count > 1 && x_t + 1 >= 0 && x_t + 1 < seq_len) {
- const uint x_idx = (input_layout == AUDIO_LAYOUT_NCS)
- ? (x_base_ncs + (uint)(x_t + 1))
- : ((b * (uint)seq_len + (uint)(x_t + 1)) * (uint)cin + (uint)ic);
- acc1 += w * float(input[x_idx]);
- }
- if (valid_count > 2 && x_t + 2 >= 0 && x_t + 2 < seq_len) {
- const uint x_idx = (input_layout == AUDIO_LAYOUT_NCS)
- ? (x_base_ncs + (uint)(x_t + 2))
- : ((b * (uint)seq_len + (uint)(x_t + 2)) * (uint)cin + (uint)ic);
- acc2 += w * float(input[x_idx]);
- }
- if (valid_count > 3 && x_t + 3 >= 0 && x_t + 3 < seq_len) {
- const uint x_idx = (input_layout == AUDIO_LAYOUT_NCS)
- ? (x_base_ncs + (uint)(x_t + 3))
- : ((b * (uint)seq_len + (uint)(x_t + 3)) * (uint)cin + (uint)ic);
- acc3 += w * float(input[x_idx]);
- }
- }
- }
- }
-
- if (lane_count > 0) {
- output[out_base] = valid_count > 0 ? (T)acc0 : (T)0;
- }
- if (lane_count > 1) {
- output[out_base + 1] = valid_count > 1 ? (T)acc1 : (T)0;
- }
- if (lane_count > 2) {
- output[out_base + 2] = valid_count > 2 ? (T)acc2 : (T)0;
- }
- if (lane_count > 3) {
- output[out_base + 3] = valid_count > 3 ? (T)acc3 : (T)0;
- }
-}
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(AudioCausalConv1d)(
- device const T* input,
- device const T* weight,
- device const T* bias,
- device T* output,
- device const int* lengths,
- const constant int& cin,
- const constant int& cout,
- const constant int& seq_len,
- const constant int& kernel_size,
- const constant int& dilation,
- const constant int& input_layout,
- const constant int& batch_size,
- uint t AXIS((seq_len + 3) / 4, 32),
- uint oc AXIS(cout, 1),
- uint b AXIS(batch_size, 1)
-) {
- causal_conv1d<T>(
- input,
- weight,
- bias,
- output,
- lengths,
- cin,
- cout,
- seq_len,
- kernel_size,
- dilation,
- input_layout,
- uint3(t, oc, b)
- );
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv1d_grouped.metal b/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv1d_grouped.metal
deleted file mode 100644
index 35ed3ea05..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv1d_grouped.metal
+++ /dev/null
@@ -1,323 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-using namespace metal;
-
-constant uint AUDIO_TIME_TILE = 8;
-constant int AUDIO_LAYOUT_NCS = 0;
-
-template <typename T>
-void causal_conv1d_grouped_ncs(
- device const T* input, // [B, Cin, T]
- device const T* weight, // [Cout, Cin/groups, K]
- device const T* bias, // [Cout]
- device T* output, // [B, Cout, T]
- device const int* lengths, // [B]
- const constant int& cin,
- const constant int& cout,
- const constant int& seq_len,
- const constant int& kernel_size,
- const constant int& dilation,
- const constant int& groups,
- const uint3 gid
-) {
- const uint t = gid.x * AUDIO_TIME_TILE;
- const uint oc = gid.y;
- const uint b = gid.z;
-
- if (t >= (uint)seq_len || oc >= (uint)cout) {
- return;
- }
-
- if (groups <= 0 || (cin % groups) != 0 || (cout % groups) != 0) {
- return;
- }
-
- const int len_b = lengths ? lengths[b] : seq_len;
- const uint out_base = (b * (uint)cout + oc) * (uint)seq_len + t;
- int lane_count = seq_len - (int)t;
- if (lane_count > (int)AUDIO_TIME_TILE) {
- lane_count = (int)AUDIO_TIME_TILE;
- }
- if (lane_count <= 0) {
- return;
- }
- int valid_count = len_b - (int)t;
- if (valid_count > lane_count) {
- valid_count = lane_count;
- }
- if (valid_count < 0) {
- valid_count = 0;
- }
-
- const int cin_per_group = cin / groups;
- const int cout_per_group = cout / groups;
- const int group_idx = (int)oc / cout_per_group;
- const int oc_in_group = (int)oc - group_idx * cout_per_group;
- const int in_begin = group_idx * cin_per_group;
-
- const int pad = (kernel_size - 1) * dilation;
- const float bias_value = float(bias[oc]);
- float acc0 = bias_value;
- float acc1 = bias_value;
- float acc2 = bias_value;
- float acc3 = bias_value;
- float acc4 = bias_value;
- float acc5 = bias_value;
- float acc6 = bias_value;
- float acc7 = bias_value;
-
- if (valid_count > 0) {
- const bool full_tile = valid_count == (int)AUDIO_TIME_TILE;
- for (int ic_local = 0; ic_local < cin_per_group; ++ic_local) {
- const uint w_base =
- ((group_idx * cout_per_group + oc_in_group) * (uint)cin_per_group + (uint)ic_local) * (uint)kernel_size;
- const int ic = in_begin + ic_local;
- const uint x_base_ncs = (b * (uint)cin + (uint)ic) * (uint)seq_len;
-
- for (int k = 0; k < kernel_size; ++k) {
- const float w = float(weight[w_base + (uint)k]);
- const int x_t = (int)t + k * dilation - pad;
- if (full_tile && x_t >= 0 && x_t + 7 < seq_len) {
- // Fast path: all 8 lanes in bounds, use vectorized loads
- const uint x_idx = x_base_ncs + (uint)x_t;
- vec<T, 4> v0 = *(device const vec<T, 4>*)(input + x_idx);
- vec<T, 4> v1 = *(device const vec<T, 4>*)(input + x_idx + 4);
- acc0 += w * float(v0.x);
- acc1 += w * float(v0.y);
- acc2 += w * float(v0.z);
- acc3 += w * float(v0.w);
- acc4 += w * float(v1.x);
- acc5 += w * float(v1.y);
- acc6 += w * float(v1.z);
- acc7 += w * float(v1.w);
- continue;
- }
- // Slow path: per-lane boundary checks
- if (valid_count > 0 && x_t >= 0 && x_t < seq_len) {
- acc0 += w * float(input[x_base_ncs + (uint)x_t]);
- }
- if (valid_count > 1 && x_t + 1 >= 0 && x_t + 1 < seq_len) {
- acc1 += w * float(input[x_base_ncs + (uint)(x_t + 1)]);
- }
- if (valid_count > 2 && x_t + 2 >= 0 && x_t + 2 < seq_len) {
- acc2 += w * float(input[x_base_ncs + (uint)(x_t + 2)]);
- }
- if (valid_count > 3 && x_t + 3 >= 0 && x_t + 3 < seq_len) {
- acc3 += w * float(input[x_base_ncs + (uint)(x_t + 3)]);
- }
- if (valid_count > 4 && x_t + 4 >= 0 && x_t + 4 < seq_len) {
- acc4 += w * float(input[x_base_ncs + (uint)(x_t + 4)]);
- }
- if (valid_count > 5 && x_t + 5 >= 0 && x_t + 5 < seq_len) {
- acc5 += w * float(input[x_base_ncs + (uint)(x_t + 5)]);
- }
- if (valid_count > 6 && x_t + 6 >= 0 && x_t + 6 < seq_len) {
- acc6 += w * float(input[x_base_ncs + (uint)(x_t + 6)]);
- }
- if (valid_count > 7 && x_t + 7 >= 0 && x_t + 7 < seq_len) {
- acc7 += w * float(input[x_base_ncs + (uint)(x_t + 7)]);
- }
- }
- }
- }
-
- if (lane_count > 0) {
- output[out_base] = valid_count > 0 ? (T)acc0 : (T)0;
- }
- if (lane_count > 1) {
- output[out_base + 1] = valid_count > 1 ? (T)acc1 : (T)0;
- }
- if (lane_count > 2) {
- output[out_base + 2] = valid_count > 2 ? (T)acc2 : (T)0;
- }
- if (lane_count > 3) {
- output[out_base + 3] = valid_count > 3 ? (T)acc3 : (T)0;
- }
- if (lane_count > 4) {
- output[out_base + 4] = valid_count > 4 ? (T)acc4 : (T)0;
- }
- if (lane_count > 5) {
- output[out_base + 5] = valid_count > 5 ? (T)acc5 : (T)0;
- }
- if (lane_count > 6) {
- output[out_base + 6] = valid_count > 6 ? (T)acc6 : (T)0;
- }
- if (lane_count > 7) {
- output[out_base + 7] = valid_count > 7 ? (T)acc7 : (T)0;
- }
-}
-
-template <typename T>
-void causal_conv1d_grouped_nsc(
- device const T* input, // [B, T, Cin]
- device const T* weight, // [Cout, Cin/groups, K]
- device const T* bias, // [Cout]
- device T* output, // [B, Cout, T]
- device const int* lengths, // [B]
- const constant int& cin,
- const constant int& cout,
- const constant int& seq_len,
- const constant int& kernel_size,
- const constant int& dilation,
- const constant int& groups,
- const uint3 gid
-) {
- const uint t = gid.x * AUDIO_TIME_TILE;
- const uint oc = gid.y;
- const uint b = gid.z;
-
- if (t >= (uint)seq_len || oc >= (uint)cout) {
- return;
- }
-
- if (groups <= 0 || (cin % groups) != 0 || (cout % groups) != 0) {
- return;
- }
-
- const int len_b = lengths ? lengths[b] : seq_len;
- const uint out_base = (b * (uint)cout + oc) * (uint)seq_len + t;
- int lane_count = seq_len - (int)t;
- if (lane_count > (int)AUDIO_TIME_TILE) {
- lane_count = (int)AUDIO_TIME_TILE;
- }
- if (lane_count <= 0) {
- return;
- }
- int valid_count = len_b - (int)t;
- if (valid_count > lane_count) {
- valid_count = lane_count;
- }
- if (valid_count < 0) {
- valid_count = 0;
- }
-
- const int cin_per_group = cin / groups;
- const int cout_per_group = cout / groups;
- const int group_idx = (int)oc / cout_per_group;
- const int oc_in_group = (int)oc - group_idx * cout_per_group;
- const int in_begin = group_idx * cin_per_group;
-
- const int pad = (kernel_size - 1) * dilation;
- const float bias_value = float(bias[oc]);
- float acc0 = bias_value;
- float acc1 = bias_value;
- float acc2 = bias_value;
- float acc3 = bias_value;
- float acc4 = bias_value;
- float acc5 = bias_value;
- float acc6 = bias_value;
- float acc7 = bias_value;
-
- if (valid_count > 0) {
- const bool full_tile = valid_count == (int)AUDIO_TIME_TILE;
- for (int ic_local = 0; ic_local < cin_per_group; ++ic_local) {
- const int ic = in_begin + ic_local;
- const uint w_base =
- ((group_idx * cout_per_group + oc_in_group) * (uint)cin_per_group + (uint)ic_local) * (uint)kernel_size;
-
- for (int k = 0; k < kernel_size; ++k) {
- const float w = float(weight[w_base + (uint)k]);
- const int x_t = (int)t + k * dilation - pad;
- if (full_tile && x_t >= 0 && x_t + 7 < seq_len) {
- const uint x_idx0 = (b * (uint)seq_len + (uint)x_t) * (uint)cin + (uint)ic;
- acc0 += w * float(input[x_idx0]);
- acc1 += w * float(input[x_idx0 + (uint)cin]);
- acc2 += w * float(input[x_idx0 + (uint)(2 * cin)]);
- acc3 += w * float(input[x_idx0 + (uint)(3 * cin)]);
- acc4 += w * float(input[x_idx0 + (uint)(4 * cin)]);
- acc5 += w * float(input[x_idx0 + (uint)(5 * cin)]);
- acc6 += w * float(input[x_idx0 + (uint)(6 * cin)]);
- acc7 += w * float(input[x_idx0 + (uint)(7 * cin)]);
- continue;
- }
- if (valid_count > 0 && x_t >= 0 && x_t < seq_len) {
- const uint x_idx = (b * (uint)seq_len + (uint)x_t) * (uint)cin + (uint)ic;
- acc0 += w * float(input[x_idx]);
- }
- if (valid_count > 1 && x_t + 1 >= 0 && x_t + 1 < seq_len) {
- const uint x_idx = (b * (uint)seq_len + (uint)(x_t + 1)) * (uint)cin + (uint)ic;
- acc1 += w * float(input[x_idx]);
- }
- if (valid_count > 2 && x_t + 2 >= 0 && x_t + 2 < seq_len) {
- const uint x_idx = (b * (uint)seq_len + (uint)(x_t + 2)) * (uint)cin + (uint)ic;
- acc2 += w * float(input[x_idx]);
- }
- if (valid_count > 3 && x_t + 3 >= 0 && x_t + 3 < seq_len) {
- const uint x_idx = (b * (uint)seq_len + (uint)(x_t + 3)) * (uint)cin + (uint)ic;
- acc3 += w * float(input[x_idx]);
- }
- if (valid_count > 4 && x_t + 4 >= 0 && x_t + 4 < seq_len) {
- const uint x_idx = (b * (uint)seq_len + (uint)(x_t + 4)) * (uint)cin + (uint)ic;
- acc4 += w * float(input[x_idx]);
- }
- if (valid_count > 5 && x_t + 5 >= 0 && x_t + 5 < seq_len) {
- const uint x_idx = (b * (uint)seq_len + (uint)(x_t + 5)) * (uint)cin + (uint)ic;
- acc5 += w * float(input[x_idx]);
- }
- if (valid_count > 6 && x_t + 6 >= 0 && x_t + 6 < seq_len) {
- const uint x_idx = (b * (uint)seq_len + (uint)(x_t + 6)) * (uint)cin + (uint)ic;
- acc6 += w * float(input[x_idx]);
- }
- if (valid_count > 7 && x_t + 7 >= 0 && x_t + 7 < seq_len) {
- const uint x_idx = (b * (uint)seq_len + (uint)(x_t + 7)) * (uint)cin + (uint)ic;
- acc7 += w * float(input[x_idx]);
- }
- }
- }
- }
-
- if (lane_count > 0) {
- output[out_base] = valid_count > 0 ? (T)acc0 : (T)0;
- }
- if (lane_count > 1) {
- output[out_base + 1] = valid_count > 1 ? (T)acc1 : (T)0;
- }
- if (lane_count > 2) {
- output[out_base + 2] = valid_count > 2 ? (T)acc2 : (T)0;
- }
- if (lane_count > 3) {
- output[out_base + 3] = valid_count > 3 ? (T)acc3 : (T)0;
- }
- if (lane_count > 4) {
- output[out_base + 4] = valid_count > 4 ? (T)acc4 : (T)0;
- }
- if (lane_count > 5) {
- output[out_base + 5] = valid_count > 5 ? (T)acc5 : (T)0;
- }
- if (lane_count > 6) {
- output[out_base + 6] = valid_count > 6 ? (T)acc6 : (T)0;
- }
- if (lane_count > 7) {
- output[out_base + 7] = valid_count > 7 ? (T)acc7 : (T)0;
- }
-}
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(AudioCausalConv1dGrouped)(
- device const T* input,
- device const T* weight,
- device const T* bias,
- device T* output,
- device const int* lengths,
- const constant int& cin,
- const constant int& cout,
- const constant int& seq_len,
- const constant int& kernel_size,
- const constant int& dilation,
- const constant int& groups,
- const constant int& input_layout,
- const constant int& batch_size,
- uint t AXIS((seq_len + 7) / 8, 32),
- uint oc AXIS(cout, 1),
- uint b AXIS(batch_size, 1)
-) {
- if (input_layout == AUDIO_LAYOUT_NCS) {
- causal_conv1d_grouped_ncs<
- T>(input, weight, bias, output, lengths, cin, cout, seq_len, kernel_size, dilation, groups, uint3(t, oc, b));
- } else {
- causal_conv1d_grouped_nsc<
- T>(input, weight, bias, output, lengths, cin, cout, seq_len, kernel_size, dilation, groups, uint3(t, oc, b));
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv1d_grouped_residual.metal b/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv1d_grouped_residual.metal
deleted file mode 100644
index e472b03ac..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv1d_grouped_residual.metal
+++ /dev/null
@@ -1,193 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-using namespace metal;
-
-constant uint AUDIO_TIME_TILE = 8;
-
-template <typename T>
-void causal_conv1d_grouped_residual(
- device const T* input, // [B, Cin, T]
- device const T* residual, // [B, Cout, T]
- device const T* weight, // [Cout, Cin/groups, K]
- device const T* bias, // [Cout]
- device T* output, // [B, Cout, T]
- device const int* lengths, // [B]
- const constant int& cin,
- const constant int& cout,
- const constant int& seq_len,
- const constant int& kernel_size,
- const constant int& dilation,
- const constant int& groups,
- const uint3 gid
-) {
- const uint t = gid.x * AUDIO_TIME_TILE;
- const uint oc = gid.y;
- const uint b = gid.z;
-
- if (t >= (uint)seq_len || oc >= (uint)cout) {
- return;
- }
-
- if (groups <= 0 || (cin % groups) != 0 || (cout % groups) != 0) {
- return;
- }
-
- const int len_b = lengths ? lengths[b] : seq_len;
- const uint out_base = (b * (uint)cout + oc) * (uint)seq_len + t;
- int lane_count = seq_len - (int)t;
- if (lane_count > (int)AUDIO_TIME_TILE) {
- lane_count = (int)AUDIO_TIME_TILE;
- }
- if (lane_count <= 0) {
- return;
- }
- int valid_count = len_b - (int)t;
- if (valid_count > lane_count) {
- valid_count = lane_count;
- }
- if (valid_count < 0) {
- valid_count = 0;
- }
-
- const float bias_value = float(bias[oc]);
- const float residual0 = lane_count > 0 ? float(residual[out_base]) : 0.0f;
- const float residual1 = lane_count > 1 ? float(residual[out_base + 1]) : 0.0f;
- const float residual2 = lane_count > 2 ? float(residual[out_base + 2]) : 0.0f;
- const float residual3 = lane_count > 3 ? float(residual[out_base + 3]) : 0.0f;
- const float residual4 = lane_count > 4 ? float(residual[out_base + 4]) : 0.0f;
- const float residual5 = lane_count > 5 ? float(residual[out_base + 5]) : 0.0f;
- const float residual6 = lane_count > 6 ? float(residual[out_base + 6]) : 0.0f;
- const float residual7 = lane_count > 7 ? float(residual[out_base + 7]) : 0.0f;
- float acc0 = bias_value + residual0;
- float acc1 = bias_value + residual1;
- float acc2 = bias_value + residual2;
- float acc3 = bias_value + residual3;
- float acc4 = bias_value + residual4;
- float acc5 = bias_value + residual5;
- float acc6 = bias_value + residual6;
- float acc7 = bias_value + residual7;
-
- const int cin_per_group = cin / groups;
- const int cout_per_group = cout / groups;
- const int group_idx = (int)oc / cout_per_group;
- const int oc_in_group = (int)oc - group_idx * cout_per_group;
- const int in_begin = group_idx * cin_per_group;
-
- const int pad = (kernel_size - 1) * dilation;
- if (valid_count > 0) {
- const bool full_tile = valid_count == (int)AUDIO_TIME_TILE;
- for (int ic_local = 0; ic_local < cin_per_group; ++ic_local) {
- const int ic = in_begin + ic_local;
- const uint w_base =
- ((group_idx * cout_per_group + oc_in_group) * (uint)cin_per_group + (uint)ic_local) * (uint)kernel_size;
- const uint x_base = (b * (uint)cin + (uint)ic) * (uint)seq_len;
-
- for (int k = 0; k < kernel_size; ++k) {
- const float w = float(weight[w_base + (uint)k]);
- const int x_t = (int)t + k * dilation - pad;
- if (full_tile && x_t >= 0 && x_t + 7 < seq_len) {
- // Fast path: all 8 lanes in bounds, use vectorized loads
- const uint x_idx = x_base + (uint)x_t;
- vec<T, 4> v0 = *(device const vec<T, 4>*)(input + x_idx);
- vec<T, 4> v1 = *(device const vec<T, 4>*)(input + x_idx + 4);
- acc0 += w * float(v0.x);
- acc1 += w * float(v0.y);
- acc2 += w * float(v0.z);
- acc3 += w * float(v0.w);
- acc4 += w * float(v1.x);
- acc5 += w * float(v1.y);
- acc6 += w * float(v1.z);
- acc7 += w * float(v1.w);
- continue;
- }
- if (valid_count > 0 && x_t >= 0 && x_t < seq_len) {
- acc0 += w * float(input[x_base + (uint)x_t]);
- }
- if (valid_count > 1 && x_t + 1 >= 0 && x_t + 1 < seq_len) {
- acc1 += w * float(input[x_base + (uint)(x_t + 1)]);
- }
- if (valid_count > 2 && x_t + 2 >= 0 && x_t + 2 < seq_len) {
- acc2 += w * float(input[x_base + (uint)(x_t + 2)]);
- }
- if (valid_count > 3 && x_t + 3 >= 0 && x_t + 3 < seq_len) {
- acc3 += w * float(input[x_base + (uint)(x_t + 3)]);
- }
- if (valid_count > 4 && x_t + 4 >= 0 && x_t + 4 < seq_len) {
- acc4 += w * float(input[x_base + (uint)(x_t + 4)]);
- }
- if (valid_count > 5 && x_t + 5 >= 0 && x_t + 5 < seq_len) {
- acc5 += w * float(input[x_base + (uint)(x_t + 5)]);
- }
- if (valid_count > 6 && x_t + 6 >= 0 && x_t + 6 < seq_len) {
- acc6 += w * float(input[x_base + (uint)(x_t + 6)]);
- }
- if (valid_count > 7 && x_t + 7 >= 0 && x_t + 7 < seq_len) {
- acc7 += w * float(input[x_base + (uint)(x_t + 7)]);
- }
- }
- }
- }
-
- if (lane_count > 0) {
- output[out_base] = valid_count > 0 ? (T)acc0 : (T)residual0;
- }
- if (lane_count > 1) {
- output[out_base + 1] = valid_count > 1 ? (T)acc1 : (T)residual1;
- }
- if (lane_count > 2) {
- output[out_base + 2] = valid_count > 2 ? (T)acc2 : (T)residual2;
- }
- if (lane_count > 3) {
- output[out_base + 3] = valid_count > 3 ? (T)acc3 : (T)residual3;
- }
- if (lane_count > 4) {
- output[out_base + 4] = valid_count > 4 ? (T)acc4 : (T)residual4;
- }
- if (lane_count > 5) {
- output[out_base + 5] = valid_count > 5 ? (T)acc5 : (T)residual5;
- }
- if (lane_count > 6) {
- output[out_base + 6] = valid_count > 6 ? (T)acc6 : (T)residual6;
- }
- if (lane_count > 7) {
- output[out_base + 7] = valid_count > 7 ? (T)acc7 : (T)residual7;
- }
-}
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(AudioCausalConv1dGroupedResidual)(
- device const T* input,
- device const T* residual,
- device const T* weight,
- device const T* bias,
- device T* output,
- device const int* lengths,
- const constant int& cin,
- const constant int& cout,
- const constant int& seq_len,
- const constant int& kernel_size,
- const constant int& dilation,
- const constant int& groups,
- const constant int& batch_size,
- uint t AXIS((seq_len + 7) / 8, 32),
- uint oc AXIS(cout, 1),
- uint b AXIS(batch_size, 1)
-) {
- causal_conv1d_grouped_residual<T>(
- input,
- residual,
- weight,
- bias,
- output,
- lengths,
- cin,
- cout,
- seq_len,
- kernel_size,
- dilation,
- groups,
- uint3(t, oc, b)
- );
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv_transpose1d.metal b/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv_transpose1d.metal
deleted file mode 100644
index 6e1ee11f2..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv_transpose1d.metal
+++ /dev/null
@@ -1,92 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-using namespace metal;
-
-template <typename T>
-void causal_conv_transpose1d(
- device const T* input, // [B, Cin, Tin]
- device const T* weight, // [Cout, Cin_per_group, 2*stride]
- device const T* bias, // [Cout]
- device T* output, // [B, Cout, Tout]
- device const int* lengths, // [B] (output lengths)
- const constant int& cin,
- const constant int& cout,
- const constant int& seq_len_in,
- const constant int& seq_len_out,
- const constant int& stride,
- const constant int& groups,
- const uint3 gid
-) {
- const uint t_out = gid.x;
- const uint oc = gid.y;
- const uint b = gid.z;
-
- if (t_out >= (uint)seq_len_out || oc >= (uint)cout) {
- return;
- }
-
- const int len_b = lengths ? lengths[b] : seq_len_out;
- const uint out_idx = (b * (uint)cout + oc) * (uint)seq_len_out + t_out;
- if ((int)t_out >= len_b) {
- output[out_idx] = (T)0;
- return;
- }
-
- const int cout_per_group = cout / groups;
- const int cin_per_group = cin / groups;
- const int group_idx = (int)oc / cout_per_group;
-
- const int q = (int)t_out / stride;
- const int r = (int)t_out - q * stride;
-
- float acc = float(bias[oc]);
-
- const uint in_base_b = b * (uint)cin * (uint)seq_len_in;
- const int ic_begin = group_idx * cin_per_group;
- const int ic_end = ic_begin + cin_per_group;
-
- for (int ic = ic_begin; ic < ic_end; ++ic) {
- if (q >= seq_len_in) {
- continue;
- }
- const uint in_base = in_base_b + (uint)ic * (uint)seq_len_in;
-
- // Weight layout: [Cout, Cin_per_group, K]
- const uint ic_local = (uint)(ic - ic_begin);
- const uint w_base = ((uint)oc * (uint)cin_per_group + ic_local) * (uint)(2 * stride);
-
- // Contribution from input[q] with k=r
- acc += float(weight[w_base + (uint)r]) * float(input[in_base + (uint)q]);
-
- // Contribution from input[q-1] with k=stride+r
- if (q > 0) {
- acc += float(weight[w_base + (uint)(stride + r)]) * float(input[in_base + (uint)(q - 1)]);
- }
- }
-
- output[out_idx] = (T)acc;
-}
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(AudioCausalConvTranspose1d)(
- device const T* input,
- device const T* weight,
- device const T* bias,
- device T* output,
- device const int* lengths,
- const constant int& cin,
- const constant int& cout,
- const constant int& seq_len_in,
- const constant int& seq_len_out,
- const constant int& stride,
- const constant int& groups,
- const constant int& batch_size,
- uint t_out AXIS(seq_len_out, 32),
- uint oc AXIS(cout, 1),
- uint b AXIS(batch_size, 1)
-) {
- causal_conv_transpose1d<
- T>(input, weight, bias, output, lengths, cin, cout, seq_len_in, seq_len_out, stride, groups, uint3(t_out, oc, b));
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv_transpose1d_causal_pad.metal b/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv_transpose1d_causal_pad.metal
deleted file mode 100644
index 2481064e6..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/audio/causal_conv_transpose1d_causal_pad.metal
+++ /dev/null
@@ -1,404 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-using namespace metal;
-
-constant uint AUDIO_TIME_TILE = 4;
-
-// Input layout for causal_conv_transpose1d_causal_pad:
-// 0 = NCS ([B, Cin, Tin]), 1 = NSC ([B, Tin, Cin]).
-constant int AUDIO_LAYOUT_NCS = 0;
-constant int AUDIO_LAYOUT_NSC = 1;
-
-// === Causal ConvTranspose1d (causal-pad semantics, arbitrary kernel_size) ===
-//
-// This matches causal_conv_transpose1d_causal_pad_reference():
-// - Expand input by stride with zeros inserted between samples.
-// - Left pad by (kernel_size - 1), no right pad.
-// - Convolve with provided kernel along expanded timeline.
-template <typename T>
-void causal_conv_transpose1d_causal_pad(
- device const T* input, // [B, Cin, Tin] when NCS, [B, Tin, Cin] when NSC
- device const T* weight, // [Cout, Cin_per_group, K]
- device const T* bias, // [Cout]
- device T* output, // [B, Cout, Tout]
- device const int* lengths, // [B]
- const constant int& cin,
- const constant int& cout,
- const constant int& seq_len_in,
- const constant int& seq_len_out,
- const constant int& kernel_size,
- const constant int& stride,
- const constant int& groups,
- const constant int& input_layout,
- const uint3 gid
-) {
- const uint t_out = gid.x * AUDIO_TIME_TILE;
- const uint oc = gid.y;
- const uint b = gid.z;
-
- if (t_out >= (uint)seq_len_out || oc >= (uint)cout) {
- return;
- }
- if ((input_layout != AUDIO_LAYOUT_NCS && input_layout != AUDIO_LAYOUT_NSC) || groups <= 0 || stride <= 0 ||
- kernel_size <= 0 || (cin % groups) != 0 || (cout % groups) != 0) {
- return;
- }
-
- const int len_b = lengths ? lengths[b] : seq_len_out;
- const uint out_base = (b * (uint)cout + oc) * (uint)seq_len_out + t_out;
- int lane_count = seq_len_out - (int)t_out;
- if (lane_count > (int)AUDIO_TIME_TILE) {
- lane_count = (int)AUDIO_TIME_TILE;
- }
- if (lane_count <= 0) {
- return;
- }
- int valid_count = len_b - (int)t_out;
- if (valid_count > lane_count) {
- valid_count = lane_count;
- }
- if (valid_count < 0) {
- valid_count = 0;
- }
-
- const int cout_per_group = cout / groups;
- const int cin_per_group = cin / groups;
- const int group_idx = (int)oc / cout_per_group;
- const int ic_begin = group_idx * cin_per_group;
- const int ic_end = ic_begin + cin_per_group;
-
- const int seq_len_expanded = (seq_len_in > 0) ? (((seq_len_in - 1) * stride) + 1) : 0;
- const int left_pad = kernel_size - 1;
- const bool fast_two_tap = (kernel_size == (stride * 2));
-
- const float bias_value = float(bias[oc]);
- float acc0 = bias_value;
- float acc1 = bias_value;
- float acc2 = bias_value;
- float acc3 = bias_value;
-
- // Process each lane that is valid (within sequence length)
- if (valid_count > 0) {
- // Precompute q and r for lane 0; consecutive lanes have t_out+1, t_out+2,
- // t_out+3.
- const int t0 = (int)t_out;
- const int q0 = t0 / stride;
- const int r0 = t0 % stride;
-
- if (input_layout == AUDIO_LAYOUT_NCS) {
- for (int ic = ic_begin; ic < ic_end; ++ic) {
- const uint in_base = (b * (uint)cin + (uint)ic) * (uint)seq_len_in;
- const uint ic_local = (uint)(ic - ic_begin);
- const uint w_base = ((uint)oc * (uint)cin_per_group + ic_local) * (uint)kernel_size;
- if (fast_two_tap) {
- // When stride >= AUDIO_TIME_TILE (common for decoder blocks with
- // strides 4,8), all 4 lanes share the same q value. This means
- // they all read from the same input positions (q and q-1), just
- // with different weight indices. We load each input value once
- // and broadcast it across lanes.
- if (stride >= (int)AUDIO_TIME_TILE) {
- // All lanes have same q since t_out+3 < t_out+stride means
- // (t_out+3)/stride == t_out/stride.
- const float in_qm1 = (q0 > 0 && q0 - 1 < seq_len_in) ? float(input[in_base + (uint)(q0 - 1)]) : 0.0f;
- const float in_q0 = (q0 >= 0 && q0 < seq_len_in) ? float(input[in_base + (uint)q0]) : 0.0f;
- // Lane 0: r = r0
- if (valid_count > 0) {
- acc0 += in_qm1 * float(weight[w_base + (uint)((stride - 1) - r0)]);
- acc0 += in_q0 * float(weight[w_base + (uint)((kernel_size - 1) - r0)]);
- }
- // Lane 1: r = r0+1
- if (valid_count > 1) {
- const int r1 = r0 + 1;
- acc1 += in_qm1 * float(weight[w_base + (uint)((stride - 1) - r1)]);
- acc1 += in_q0 * float(weight[w_base + (uint)((kernel_size - 1) - r1)]);
- }
- // Lane 2: r = r0+2
- if (valid_count > 2) {
- const int r2 = r0 + 2;
- acc2 += in_qm1 * float(weight[w_base + (uint)((stride - 1) - r2)]);
- acc2 += in_q0 * float(weight[w_base + (uint)((kernel_size - 1) - r2)]);
- }
- // Lane 3: r = r0+3
- if (valid_count > 3) {
- const int r3 = r0 + 3;
- acc3 += in_qm1 * float(weight[w_base + (uint)((stride - 1) - r3)]);
- acc3 += in_q0 * float(weight[w_base + (uint)((kernel_size - 1) - r3)]);
- }
- } else {
- // stride < 4 (e.g., stride=2 for upsampler blocks).
- // Lanes may cross stride boundaries (different q values).
- if (valid_count > 0) {
- const int k_lo = (stride - 1) - r0;
- const int k_hi = (kernel_size - 1) - r0;
- if (q0 > 0 && q0 - 1 < seq_len_in) {
- acc0 += float(input[in_base + (uint)(q0 - 1)]) * float(weight[w_base + (uint)k_lo]);
- }
- if (q0 >= 0 && q0 < seq_len_in) {
- acc0 += float(input[in_base + (uint)q0]) * float(weight[w_base + (uint)k_hi]);
- }
- }
- if (valid_count > 1) {
- const int q1 = (t0 + 1) / stride;
- const int r1 = (t0 + 1) % stride;
- if (q1 > 0 && q1 - 1 < seq_len_in) {
- acc1 += float(input[in_base + (uint)(q1 - 1)]) * float(weight[w_base + (uint)((stride - 1) - r1)]);
- }
- if (q1 >= 0 && q1 < seq_len_in) {
- acc1 += float(input[in_base + (uint)q1]) * float(weight[w_base + (uint)((kernel_size - 1) - r1)]);
- }
- }
- if (valid_count > 2) {
- const int q2 = (t0 + 2) / stride;
- const int r2 = (t0 + 2) % stride;
- if (q2 > 0 && q2 - 1 < seq_len_in) {
- acc2 += float(input[in_base + (uint)(q2 - 1)]) * float(weight[w_base + (uint)((stride - 1) - r2)]);
- }
- if (q2 >= 0 && q2 < seq_len_in) {
- acc2 += float(input[in_base + (uint)q2]) * float(weight[w_base + (uint)((kernel_size - 1) - r2)]);
- }
- }
- if (valid_count > 3) {
- const int q3 = (t0 + 3) / stride;
- const int r3 = (t0 + 3) % stride;
- if (q3 > 0 && q3 - 1 < seq_len_in) {
- acc3 += float(input[in_base + (uint)(q3 - 1)]) * float(weight[w_base + (uint)((stride - 1) - r3)]);
- }
- if (q3 >= 0 && q3 < seq_len_in) {
- acc3 += float(input[in_base + (uint)q3]) * float(weight[w_base + (uint)((kernel_size - 1) - r3)]);
- }
- }
- }
- } else {
- for (int k = 0; k < kernel_size; ++k) {
- const float w = float(weight[w_base + (uint)k]);
- // Lane 0
- if (valid_count > 0) {
- const int expanded_time0 = (int)t_out + k - left_pad;
- if (expanded_time0 >= 0 && expanded_time0 < seq_len_expanded && (expanded_time0 % stride) == 0) {
- const int src_time0 = expanded_time0 / stride;
- if (src_time0 >= 0 && src_time0 < seq_len_in) {
- acc0 += float(input[in_base + (uint)src_time0]) * w;
- }
- }
- }
- // Lane 1
- if (valid_count > 1) {
- const int expanded_time1 = (int)t_out + 1 + k - left_pad;
- if (expanded_time1 >= 0 && expanded_time1 < seq_len_expanded && (expanded_time1 % stride) == 0) {
- const int src_time1 = expanded_time1 / stride;
- if (src_time1 >= 0 && src_time1 < seq_len_in) {
- acc1 += float(input[in_base + (uint)src_time1]) * w;
- }
- }
- }
- // Lane 2
- if (valid_count > 2) {
- const int expanded_time2 = (int)t_out + 2 + k - left_pad;
- if (expanded_time2 >= 0 && expanded_time2 < seq_len_expanded && (expanded_time2 % stride) == 0) {
- const int src_time2 = expanded_time2 / stride;
- if (src_time2 >= 0 && src_time2 < seq_len_in) {
- acc2 += float(input[in_base + (uint)src_time2]) * w;
- }
- }
- }
- // Lane 3
- if (valid_count > 3) {
- const int expanded_time3 = (int)t_out + 3 + k - left_pad;
- if (expanded_time3 >= 0 && expanded_time3 < seq_len_expanded && (expanded_time3 % stride) == 0) {
- const int src_time3 = expanded_time3 / stride;
- if (src_time3 >= 0 && src_time3 < seq_len_in) {
- acc3 += float(input[in_base + (uint)src_time3]) * w;
- }
- }
- }
- }
- }
- }
- } else {
- // NSC layout
- for (int ic = ic_begin; ic < ic_end; ++ic) {
- const uint ic_local = (uint)(ic - ic_begin);
- const uint w_base = ((uint)oc * (uint)cin_per_group + ic_local) * (uint)kernel_size;
- if (fast_two_tap) {
- if (stride >= (int)AUDIO_TIME_TILE) {
- // All lanes share q0; load input once per (q-1, q) pair.
- const float in_qm1 = (q0 > 0 && q0 - 1 < seq_len_in)
- ? float(input[(b * (uint)seq_len_in + (uint)(q0 - 1)) * (uint)cin + (uint)ic])
- : 0.0f;
- const float in_q0 = (q0 >= 0 && q0 < seq_len_in)
- ? float(input[(b * (uint)seq_len_in + (uint)q0) * (uint)cin + (uint)ic])
- : 0.0f;
- if (valid_count > 0) {
- acc0 += in_qm1 * float(weight[w_base + (uint)((stride - 1) - r0)]);
- acc0 += in_q0 * float(weight[w_base + (uint)((kernel_size - 1) - r0)]);
- }
- if (valid_count > 1) {
- const int r1 = r0 + 1;
- acc1 += in_qm1 * float(weight[w_base + (uint)((stride - 1) - r1)]);
- acc1 += in_q0 * float(weight[w_base + (uint)((kernel_size - 1) - r1)]);
- }
- if (valid_count > 2) {
- const int r2 = r0 + 2;
- acc2 += in_qm1 * float(weight[w_base + (uint)((stride - 1) - r2)]);
- acc2 += in_q0 * float(weight[w_base + (uint)((kernel_size - 1) - r2)]);
- }
- if (valid_count > 3) {
- const int r3 = r0 + 3;
- acc3 += in_qm1 * float(weight[w_base + (uint)((stride - 1) - r3)]);
- acc3 += in_q0 * float(weight[w_base + (uint)((kernel_size - 1) - r3)]);
- }
- } else {
- // stride < 4: lanes may have different q values.
- if (valid_count > 0) {
- if (q0 > 0 && q0 - 1 < seq_len_in) {
- const uint in_idx = (b * (uint)seq_len_in + (uint)(q0 - 1)) * (uint)cin + (uint)ic;
- acc0 += float(input[in_idx]) * float(weight[w_base + (uint)((stride - 1) - r0)]);
- }
- if (q0 >= 0 && q0 < seq_len_in) {
- const uint in_idx = (b * (uint)seq_len_in + (uint)q0) * (uint)cin + (uint)ic;
- acc0 += float(input[in_idx]) * float(weight[w_base + (uint)((kernel_size - 1) - r0)]);
- }
- }
- if (valid_count > 1) {
- const int q1 = (t0 + 1) / stride;
- const int r1 = (t0 + 1) % stride;
- if (q1 > 0 && q1 - 1 < seq_len_in) {
- const uint in_idx = (b * (uint)seq_len_in + (uint)(q1 - 1)) * (uint)cin + (uint)ic;
- acc1 += float(input[in_idx]) * float(weight[w_base + (uint)((stride - 1) - r1)]);
- }
- if (q1 >= 0 && q1 < seq_len_in) {
- const uint in_idx = (b * (uint)seq_len_in + (uint)q1) * (uint)cin + (uint)ic;
- acc1 += float(input[in_idx]) * float(weight[w_base + (uint)((kernel_size - 1) - r1)]);
- }
- }
- if (valid_count > 2) {
- const int q2 = (t0 + 2) / stride;
- const int r2 = (t0 + 2) % stride;
- if (q2 > 0 && q2 - 1 < seq_len_in) {
- const uint in_idx = (b * (uint)seq_len_in + (uint)(q2 - 1)) * (uint)cin + (uint)ic;
- acc2 += float(input[in_idx]) * float(weight[w_base + (uint)((stride - 1) - r2)]);
- }
- if (q2 >= 0 && q2 < seq_len_in) {
- const uint in_idx = (b * (uint)seq_len_in + (uint)q2) * (uint)cin + (uint)ic;
- acc2 += float(input[in_idx]) * float(weight[w_base + (uint)((kernel_size - 1) - r2)]);
- }
- }
- if (valid_count > 3) {
- const int q3 = (t0 + 3) / stride;
- const int r3 = (t0 + 3) % stride;
- if (q3 > 0 && q3 - 1 < seq_len_in) {
- const uint in_idx = (b * (uint)seq_len_in + (uint)(q3 - 1)) * (uint)cin + (uint)ic;
- acc3 += float(input[in_idx]) * float(weight[w_base + (uint)((stride - 1) - r3)]);
- }
- if (q3 >= 0 && q3 < seq_len_in) {
- const uint in_idx = (b * (uint)seq_len_in + (uint)q3) * (uint)cin + (uint)ic;
- acc3 += float(input[in_idx]) * float(weight[w_base + (uint)((kernel_size - 1) - r3)]);
- }
- }
- }
- } else {
- for (int k = 0; k < kernel_size; ++k) {
- const float w = float(weight[w_base + (uint)k]);
- // Lane 0
- if (valid_count > 0) {
- const int expanded_time0 = (int)t_out + k - left_pad;
- if (expanded_time0 >= 0 && expanded_time0 < seq_len_expanded && (expanded_time0 % stride) == 0) {
- const int src_time0 = expanded_time0 / stride;
- if (src_time0 >= 0 && src_time0 < seq_len_in) {
- const uint in_idx = (b * (uint)seq_len_in + (uint)src_time0) * (uint)cin + (uint)ic;
- acc0 += float(input[in_idx]) * w;
- }
- }
- }
- // Lane 1
- if (valid_count > 1) {
- const int expanded_time1 = (int)t_out + 1 + k - left_pad;
- if (expanded_time1 >= 0 && expanded_time1 < seq_len_expanded && (expanded_time1 % stride) == 0) {
- const int src_time1 = expanded_time1 / stride;
- if (src_time1 >= 0 && src_time1 < seq_len_in) {
- const uint in_idx = (b * (uint)seq_len_in + (uint)src_time1) * (uint)cin + (uint)ic;
- acc1 += float(input[in_idx]) * w;
- }
- }
- }
- // Lane 2
- if (valid_count > 2) {
- const int expanded_time2 = (int)t_out + 2 + k - left_pad;
- if (expanded_time2 >= 0 && expanded_time2 < seq_len_expanded && (expanded_time2 % stride) == 0) {
- const int src_time2 = expanded_time2 / stride;
- if (src_time2 >= 0 && src_time2 < seq_len_in) {
- const uint in_idx = (b * (uint)seq_len_in + (uint)src_time2) * (uint)cin + (uint)ic;
- acc2 += float(input[in_idx]) * w;
- }
- }
- }
- // Lane 3
- if (valid_count > 3) {
- const int expanded_time3 = (int)t_out + 3 + k - left_pad;
- if (expanded_time3 >= 0 && expanded_time3 < seq_len_expanded && (expanded_time3 % stride) == 0) {
- const int src_time3 = expanded_time3 / stride;
- if (src_time3 >= 0 && src_time3 < seq_len_in) {
- const uint in_idx = (b * (uint)seq_len_in + (uint)src_time3) * (uint)cin + (uint)ic;
- acc3 += float(input[in_idx]) * w;
- }
- }
- }
- }
- }
- }
- }
- }
-
- if (lane_count > 0) {
- output[out_base] = valid_count > 0 ? (T)acc0 : (T)0;
- }
- if (lane_count > 1) {
- output[out_base + 1] = valid_count > 1 ? (T)acc1 : (T)0;
- }
- if (lane_count > 2) {
- output[out_base + 2] = valid_count > 2 ? (T)acc2 : (T)0;
- }
- if (lane_count > 3) {
- output[out_base + 3] = valid_count > 3 ? (T)acc3 : (T)0;
- }
-}
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(AudioCausalConvTranspose1dCausalPad)(
- device const T* input,
- device const T* weight,
- device const T* bias,
- device T* output,
- device const int* lengths,
- const constant int& cin,
- const constant int& cout,
- const constant int& seq_len_in,
- const constant int& seq_len_out,
- const constant int& kernel_size,
- const constant int& stride,
- const constant int& groups,
- const constant int& input_layout,
- const constant int& batch_size,
- uint t_out AXIS((seq_len_out + 3) / 4, 32),
- uint oc AXIS(cout, 1),
- uint b AXIS(batch_size, 1)
-) {
- causal_conv_transpose1d_causal_pad<T>(
- input,
- weight,
- bias,
- output,
- lengths,
- cin,
- cout,
- seq_len_in,
- seq_len_out,
- kernel_size,
- stride,
- groups,
- input_layout,
- uint3(t_out, oc, b)
- );
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/audio/conv1d.metal b/crates/backend-uzu/src/backends/metal/kernel/audio/conv1d.metal
deleted file mode 100644
index 33e61d901..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/audio/conv1d.metal
+++ /dev/null
@@ -1,100 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-using namespace metal;
-
-template <typename T>
-void conv1d(
- device const T* input, // [B, Cin, Tin]
- device const T* weight, // [Cout, Cin, K]
- device const T* bias, // [Cout]
- device T* output, // [B, Cout, Tout]
- device const int* lengths, // [B] (Tout lengths)
- const constant int& cin,
- const constant int& cout,
- const constant int& seq_len_in,
- const constant int& seq_len_out,
- const constant int& kernel_size,
- const constant int& stride,
- const constant int& dilation,
- const constant int& padding,
- const constant int& pad_mode,
- const uint3 gid
-) {
- const uint t_out = gid.x;
- const uint oc = gid.y;
- const uint b = gid.z;
-
- if (t_out >= (uint)seq_len_out || oc >= (uint)cout) {
- return;
- }
-
- const int len_b = lengths ? lengths[b] : seq_len_out;
- const uint out_idx = (b * (uint)cout + oc) * (uint)seq_len_out + t_out;
- if ((int)t_out >= len_b) {
- output[out_idx] = (T)0;
- return;
- }
-
- const int base = (int)t_out * stride - padding;
- float acc = float(bias[oc]);
-
- for (int ic = 0; ic < cin; ++ic) {
- const uint w_base = (oc * (uint)cin + (uint)ic) * (uint)kernel_size;
- const uint x_base = (b * (uint)cin + (uint)ic) * (uint)seq_len_in;
- for (int k = 0; k < kernel_size; ++k) {
- int x_t = base + k * dilation;
- if (pad_mode == 0) {
- if (x_t < 0 || x_t >= seq_len_in) {
- continue;
- }
- } else {
- x_t = clamp(x_t, 0, seq_len_in - 1);
- }
- acc += float(weight[w_base + (uint)k]) * float(input[x_base + (uint)x_t]);
- }
- }
-
- output[out_idx] = (T)acc;
-}
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(AudioConv1d)(
- device const T* input,
- device const T* weight,
- device const T* bias,
- device T* output,
- device const int* lengths,
- const constant int& cin,
- const constant int& cout,
- const constant int& seq_len_in,
- const constant int& seq_len_out,
- const constant int& kernel_size,
- const constant int& stride,
- const constant int& dilation,
- const constant int& padding,
- const constant int& pad_mode,
- const constant int& batch_size,
- uint t_out AXIS(seq_len_out, 32),
- uint oc AXIS(cout, 1),
- uint b AXIS(batch_size, 1)
-) {
- conv1d<T>(
- input,
- weight,
- bias,
- output,
- lengths,
- cin,
- cout,
- seq_len_in,
- seq_len_out,
- kernel_size,
- stride,
- dilation,
- padding,
- pad_mode,
- uint3(t_out, oc, b)
- );
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/audio/fsq_decode.metal b/crates/backend-uzu/src/backends/metal/kernel/audio/fsq_decode.metal
deleted file mode 100644
index 486c4f9ea..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/audio/fsq_decode.metal
+++ /dev/null
@@ -1,73 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-using namespace metal;
-
-template <typename T>
-void fsq_decode(
- device const int* tokens,
- device T* out,
- device const int* lengths,
- const constant int& num_groups,
- const constant int& seq_len,
- const constant int& codebook_dim,
- const constant int* num_levels,
- const constant int* dim_base_index,
- const uint3 gid
-) {
- const uint t = gid.x;
- const uint gd = gid.y;
- const uint b = gid.z;
- const uint channels = (uint)(num_groups * codebook_dim);
-
- if (t >= (uint)seq_len || gd >= channels) {
- return;
- }
-
- const uint g = gd / (uint)codebook_dim;
- const uint d = gd % (uint)codebook_dim;
-
- const int len_b = lengths ? lengths[b] : seq_len;
- const uint out_idx = (b * channels + gd) * (uint)seq_len + t;
- if ((int)t >= len_b) {
- out[out_idx] = (T)0;
- return;
- }
-
- const uint token_idx = (b * (uint)num_groups + g) * (uint)seq_len + t;
- const int token = tokens[token_idx];
-
- const int levels = num_levels[d];
- const int scale = levels / 2; // integer division (matches PyTorch // 2)
- const int offset = scale;
- const int base = dim_base_index[d];
-
- // Euclidean modulo to keep result in [0, levels) even if token is negative
- // (tokens are expected nonnegative, but keep this robust).
- const int div = token / base;
- int code_nonneg = div % levels;
- if (code_nonneg < 0) {
- code_nonneg += levels;
- }
- const float code = ((float)(code_nonneg - offset)) / (float)scale;
- out[out_idx] = (T)code;
-}
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(AudioFsqDecode)(
- device const int* tokens,
- device T* out,
- device const int* lengths,
- const constant int& num_groups,
- const constant int& seq_len,
- const constant int& codebook_dim,
- const constant int* num_levels,
- const constant int* dim_base_index,
- const constant int& batch_size,
- uint t AXIS(seq_len, 32),
- uint gd AXIS(num_groups * codebook_dim, 1),
- uint b AXIS(batch_size, 1)
-) {
- fsq_decode<T>(tokens, out, lengths, num_groups, seq_len, codebook_dim, num_levels, dim_base_index, uint3(t, gd, b));
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/audio/fsq_encode.metal b/crates/backend-uzu/src/backends/metal/kernel/audio/fsq_encode.metal
deleted file mode 100644
index 789bddeee..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/audio/fsq_encode.metal
+++ /dev/null
@@ -1,88 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-using namespace metal;
-
-inline float round_ties_to_even(const float x) {
- const float f = floor(x);
- const float frac = x - f;
- if (frac < 0.5f) {
- return f;
- }
- if (frac > 0.5f) {
- return f + 1.0f;
- }
- const int fi = (int)f; // f is integral
- return ((fi & 1) != 0) ? (f + 1.0f) : f;
-}
-
-template <typename T>
-void fsq_encode(
- device const T* input, // [B, G*D, T]
- device int* tokens, // [B, G, T]
- device const int* lengths, // [B]
- const constant int& num_groups,
- const constant int& seq_len,
- const constant int& codebook_dim,
- const constant int* num_levels,
- const constant int* dim_base_index,
- const constant float& eps,
- const uint3 gid
-) {
- const uint t = gid.x;
- const uint g = gid.y;
- const uint b = gid.z;
-
- if (t >= (uint)seq_len || g >= (uint)num_groups) {
- return;
- }
-
- const int len_b = lengths ? lengths[b] : seq_len;
- const uint out_idx = (b * (uint)num_groups + g) * (uint)seq_len + t;
- if ((int)t >= len_b) {
- tokens[out_idx] = 0;
- return;
- }
-
- const uint in_base = (b * (uint)(num_groups * codebook_dim) + g * (uint)codebook_dim) * (uint)seq_len + t;
-
- int token = 0;
- for (int d = 0; d < codebook_dim; ++d) {
- const int levels = num_levels[d];
- const int scale_i = levels / 2;
- const float output_scale = ((float)(levels - 1)) * 0.5f * (1.0f - eps);
- const float output_offset = (levels % 2 == 0) ? 0.5f : 0.0f;
- const float input_shift = tan(output_offset / output_scale);
-
- const float x = float(input[in_base + (uint)d * (uint)seq_len]);
- const float compressed = output_scale * tanh(x + input_shift) - output_offset;
- const float rounded = round_ties_to_even(compressed);
-
- int code_nonneg = (int)rounded + scale_i;
- code_nonneg = clamp(code_nonneg, 0, levels - 1);
- token += code_nonneg * dim_base_index[d];
- }
-
- tokens[out_idx] = token;
-}
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(AudioFsqEncode)(
- device const T* input,
- device int* tokens,
- device const int* lengths,
- const constant int& num_groups,
- const constant int& seq_len,
- const constant int& codebook_dim,
- const constant int* num_levels,
- const constant int* dim_base_index,
- const constant float& eps,
- const constant int& batch_size,
- uint t AXIS(seq_len, 32),
- uint g AXIS(num_groups, 1),
- uint b AXIS(batch_size, 1)
-) {
- fsq_encode<
- T>(input, tokens, lengths, num_groups, seq_len, codebook_dim, num_levels, dim_base_index, eps, uint3(t, g, b));
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/audio/half_snake.metal b/crates/backend-uzu/src/backends/metal/kernel/audio/half_snake.metal
deleted file mode 100644
index 5ac6454e3..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/audio/half_snake.metal
+++ /dev/null
@@ -1,58 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-#include "../activation/activations.h"
-
-using namespace metal;
-
-template <typename T>
-void half_snake(
- device const T* input, // [B, C, T]
- device const T* alpha, // [1, C_snake, 1] (contiguous, index by channel)
- device T* output, // [B, C, T]
- const constant int& channels,
- const constant int& seq_len,
- const constant int& snake_channels,
- const constant float& negative_slope,
- const constant float& eps,
- const uint3 gid
-) {
- const uint t = gid.x;
- const uint c = gid.y;
- const uint b = gid.z;
-
- if (t >= (uint)seq_len || c >= (uint)channels) {
- return;
- }
-
- const uint idx = (b * (uint)channels + c) * (uint)seq_len + t;
- const float x = float(input[idx]);
-
- if ((int)c < snake_channels) {
- const float a = float(alpha[c]);
- const float ax = a * x;
- const float s = sin(ax);
- const float y = x + (1.0f / (a + eps)) * (s * s);
- output[idx] = (T)y;
- } else {
- output[idx] = activate_leaky_relu((T)x, negative_slope);
- }
-}
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(AudioHalfSnake)(
- device const T* input,
- device const T* alpha,
- device T* output,
- const constant int& channels,
- const constant int& seq_len,
- const constant int& snake_channels,
- const constant float& negative_slope,
- const constant float& eps,
- const constant int& batch_size,
- uint t AXIS(seq_len, 32),
- uint c AXIS(channels, 1),
- uint b AXIS(batch_size, 1)
-) {
- half_snake<T>(input, alpha, output, channels, seq_len, snake_channels, negative_slope, eps, uint3(t, c, b));
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/audio/norm_ncs.metal b/crates/backend-uzu/src/backends/metal/kernel/audio/norm_ncs.metal
deleted file mode 100644
index 3baa8e414..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/audio/norm_ncs.metal
+++ /dev/null
@@ -1,119 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-#include "../common/thread_context.h"
-#include "../common/threadgroup_reduce.h"
-
-using namespace metal;
-
-#define AUDIO_NORM_NCS_BLOCK_SIZE 256
-#define AUDIO_NORM_NCS_MAX_SIMDS 32
-
-template <typename T>
-void norm_ncs(
- device const T* input, // [B, C, T]
- device const float* scales, // [C]
- device const float* bias, // [C]
- device T* output, // [B, C, T]
- device const int* lengths, // [B]
- const constant int& channels,
- const constant int& seq_len,
- const constant float& epsilon,
- const constant int& subtract_mean,
- threadgroup float* shared_mean,
- threadgroup float* shared_variance,
- const thread ThreadContext& thread_context,
- const uint b,
- const uint t,
- const uint lid
-) {
- if (t >= (uint)seq_len || channels <= 0) {
- return;
- }
-
- const int len_b = lengths ? lengths[b] : seq_len;
-
- if ((int)t >= len_b) {
- for (uint c = lid; c < (uint)channels; c += AUDIO_NORM_NCS_BLOCK_SIZE) {
- const uint out_idx = (b * (uint)channels + c) * (uint)seq_len + t;
- output[out_idx] = (T)0;
- }
- return;
- }
-
- float partial_sum = 0.0f;
- if (subtract_mean != 0) {
- for (uint c = lid; c < (uint)channels; c += AUDIO_NORM_NCS_BLOCK_SIZE) {
- const uint idx = (b * (uint)channels + c) * (uint)seq_len + t;
- partial_sum += float(input[idx]);
- }
- }
-
- const float sum = threadgroup_cooperative_reduce<SimdReduceSum<float>, AUDIO_NORM_NCS_BLOCK_SIZE>(
- partial_sum,
- shared_mean,
- thread_context
- );
- const float mean = (subtract_mean != 0) ? (sum / (float)channels) : 0.0f;
-
- float partial_variance = 0.0f;
- for (uint c = lid; c < (uint)channels; c += AUDIO_NORM_NCS_BLOCK_SIZE) {
- const uint idx = (b * (uint)channels + c) * (uint)seq_len + t;
- const float x = float(input[idx]);
- const float centered = (subtract_mean != 0) ? (x - mean) : x;
- partial_variance += centered * centered;
- }
-
- const float variance_sum = threadgroup_cooperative_reduce<SimdReduceSum<float>, AUDIO_NORM_NCS_BLOCK_SIZE>(
- partial_variance,
- shared_variance,
- thread_context
- );
- const float inv_std = rsqrt(variance_sum / (float)channels + epsilon);
-
- for (uint c = lid; c < (uint)channels; c += AUDIO_NORM_NCS_BLOCK_SIZE) {
- const uint idx = (b * (uint)channels + c) * (uint)seq_len + t;
- const float x = float(input[idx]);
- const float centered = (subtract_mean != 0) ? (x - mean) : x;
- const float y = centered * inv_std * float(scales[c]) + float(bias[c]);
- output[idx] = (T)y;
- }
-}
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(AudioNormNcs)(
- device const T* input,
- device const float* scales,
- device const float* bias,
- device T* output,
- device const int* lengths,
- const constant int& channels,
- const constant int& seq_len,
- const constant float& epsilon,
- const constant int& subtract_mean,
- const constant int& batch_size,
- threadgroup float shared_mean[AUDIO_NORM_NCS_MAX_SIMDS],
- threadgroup float shared_variance[AUDIO_NORM_NCS_MAX_SIMDS],
- const ThreadContext thread_context,
- const uint b GROUPS(batch_size),
- const uint t GROUPS(seq_len),
- const uint lid THREADS(AUDIO_NORM_NCS_BLOCK_SIZE)
-) {
- norm_ncs<T>(
- input,
- scales,
- bias,
- output,
- lengths,
- channels,
- seq_len,
- epsilon,
- subtract_mean,
- shared_mean,
- shared_variance,
- thread_context,
- b,
- t,
- lid
- );
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/audio/quantizer_decode.metal b/crates/backend-uzu/src/backends/metal/kernel/audio/quantizer_decode.metal
deleted file mode 100644
index 78b0ebc11..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/audio/quantizer_decode.metal
+++ /dev/null
@@ -1,115 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-using namespace metal;
-
-template <typename T>
-void quantizer_decode(
- device const uint* tokens, // [B, K, T]
- device const int* lengths, // [B]
- device const T* semantic_codebook, // [semantic_cardinality, codebook_dim]
- device const T* semantic_out_proj, // [input_dim, codebook_dim]
- device const T* semantic_out_bias, // [input_dim]
- device const T* residual_codebooks, // [R, residual_cardinality, codebook_dim]
- device const T* residual_out_proj, // [R, input_dim, codebook_dim]
- device const T* residual_out_bias, // [R, input_dim]
- device T* output, // [B, T, input_dim]
- const constant int& batch_size,
- const constant int& total_codebooks,
- const constant int& seq_len,
- const constant int& input_dim,
- const constant int& codebook_dim,
- const constant int& residual_quantizers,
- const constant int& semantic_cardinality,
- const constant int& residual_cardinality,
- const uint3 gid
-) {
- const uint d = gid.x;
- const uint t = gid.y;
- const uint b = gid.z;
-
- if (d >= (uint)input_dim || t >= (uint)seq_len || b >= (uint)batch_size) {
- return;
- }
-
- const int len_b = lengths ? lengths[b] : seq_len;
- const uint out_idx = (b * (uint)seq_len + t) * (uint)input_dim + d;
- if ((int)t >= len_b) {
- output[out_idx] = (T)0;
- return;
- }
-
- const uint token_base = (b * (uint)total_codebooks) * (uint)seq_len + t;
- uint semantic_token = tokens[token_base];
- semantic_token = min(semantic_token, (uint)(semantic_cardinality - 1));
-
- float acc = float(semantic_out_bias[d]);
- const uint semantic_code_base = (uint)semantic_token * (uint)codebook_dim;
- const uint semantic_proj_base = d * (uint)codebook_dim;
- for (uint k = 0; k < (uint)codebook_dim; ++k) {
- acc += float(semantic_out_proj[semantic_proj_base + k]) * float(semantic_codebook[semantic_code_base + k]);
- }
-
- for (int r = 0; r < residual_quantizers; ++r) {
- const uint token_idx = token_base + (uint)(r + 1) * (uint)seq_len;
- uint residual_token = tokens[token_idx];
- residual_token = min(residual_token, (uint)(residual_cardinality - 1));
-
- const uint bias_idx = (uint)r * (uint)input_dim + d;
- acc += float(residual_out_bias[bias_idx]);
-
- const uint code_base = ((uint)r * (uint)residual_cardinality + (uint)residual_token) * (uint)codebook_dim;
- const uint proj_base = ((uint)r * (uint)input_dim + d) * (uint)codebook_dim;
- for (uint k = 0; k < (uint)codebook_dim; ++k) {
- acc += float(residual_out_proj[proj_base + k]) * float(residual_codebooks[code_base + k]);
- }
- }
-
- output[out_idx] = (T)acc;
-}
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(AudioQuantizerDecode)(
- device const uint* tokens,
- device const int* lengths,
- device const T* semantic_codebook,
- device const T* semantic_out_proj,
- device const T* semantic_out_bias,
- device const T* residual_codebooks,
- device const T* residual_out_proj,
- device const T* residual_out_bias,
- device T* output,
- const constant int& batch_size,
- const constant int& total_codebooks,
- const constant int& seq_len,
- const constant int& input_dim,
- const constant int& codebook_dim,
- const constant int& residual_quantizers,
- const constant int& semantic_cardinality,
- const constant int& residual_cardinality,
- uint d AXIS(input_dim, 32),
- uint t AXIS(seq_len, 1),
- uint b AXIS(batch_size, 1)
-) {
- quantizer_decode<T>(
- tokens,
- lengths,
- semantic_codebook,
- semantic_out_proj,
- semantic_out_bias,
- residual_codebooks,
- residual_out_proj,
- residual_out_bias,
- output,
- batch_size,
- total_codebooks,
- seq_len,
- input_dim,
- codebook_dim,
- residual_quantizers,
- semantic_cardinality,
- residual_cardinality,
- uint3(d, t, b)
- );
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/common/defines.h b/crates/backend-uzu/src/backends/metal/kernel/common/defines.h
index f72b10db2..9d3bacc4a 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/common/defines.h
+++ b/crates/backend-uzu/src/backends/metal/kernel/common/defines.h
@@ -5,8 +5,6 @@
#define METAL_PRAGMA_NO_UNROLL _Pragma("clang loop unroll(disable)")
#define METAL_SIMD_SIZE 32
-METAL_FUNC int pow2(int n) { return 1 << n; }
-
template <typename T, typename U>
METAL_FUNC T div_ceil(T dividend, U divisor) {
return (dividend + T(divisor) - T(1)) / T(divisor);
diff --git a/crates/backend-uzu/src/backends/metal/kernel/common/tensor_view.h b/crates/backend-uzu/src/backends/metal/kernel/common/tensor_view.h
deleted file mode 100644
index 76e67c935..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/common/tensor_view.h
+++ /dev/null
@@ -1,65 +0,0 @@
-#pragma once
-
-#include <metal_stdlib>
-using namespace metal;
-
-template <typename T>
-struct TensorView2D {
- device T* data;
- uint dim0, dim1;
- uint stride0, stride1;
-
- TensorView2D(device T* ptr) : data(ptr) {}
-
- TensorView2D(device T* ptr, int d0, int d1) : data(ptr), dim0(d0), dim1(d1) {
- stride0 = d1;
- stride1 = 1;
- }
-
- TensorView2D(device T* ptr, int d0, int d1, int s0, int s1)
- : data(ptr), dim0(d0), dim1(d1), stride0(s0), stride1(s1) {}
-
- thread TensorView2D& shaped(int d0, int d1) {
- dim0 = d0;
- dim1 = d1;
- stride0 = d1;
- stride1 = 1;
- return *this;
- }
-
- device T& at(uint i, uint j) const { return data[i * stride0 + j * stride1]; }
-
- device T& operator()(uint i, uint j) const { return at(i, j); }
-};
-
-template <typename T>
-struct TensorView3D {
- device T* data;
- uint dim0, dim1, dim2;
- uint stride0, stride1, stride2;
-
- TensorView3D(device T* ptr) : data(ptr) {}
-
- TensorView3D(device T* ptr, int d0, int d1, int d2) : data(ptr), dim0(d0), dim1(d1), dim2(d2) {
- stride0 = d1 * d2;
- stride1 = d2;
- stride2 = 1;
- }
-
- TensorView3D(device T* ptr, int d0, int d1, int d2, int s0, int s1, int s2)
- : data(ptr), dim0(d0), dim1(d1), dim2(d2), stride0(s0), stride1(s1), stride2(s2) {}
-
- thread TensorView3D& shaped(int d0, int d1, int d2) {
- dim0 = d0;
- dim1 = d1;
- dim2 = d2;
- stride0 = d1 * d2;
- stride1 = d2;
- stride2 = 1;
- return *this;
- }
-
- device T& at(uint i, uint j, uint k) const { return data[i * stride0 + j * stride1 + k * stride2]; }
-
- device T& operator()(uint i, uint j, uint k) const { return at(i, j, k); }
-};
diff --git a/crates/backend-uzu/src/backends/metal/kernel/embedding/embedding_rows_sum.metal b/crates/backend-uzu/src/backends/metal/kernel/embedding/embedding_rows_sum.metal
deleted file mode 100644
index fa08f9da0..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/embedding/embedding_rows_sum.metal
+++ /dev/null
@@ -1,27 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-#define BLOCK_SIZE 256
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(EmbeddingRowsSum)(
- const device uint32_t* token_indices, // [num_rows]
- const device T* weights, // [total_rows, model_dim]
- device T* output, // [model_dim]
- constant uint32_t& num_rows,
- constant uint32_t& total_rows,
- constant uint32_t& model_dim,
- constant uint32_t& codebook_stride,
- uint dim_idx AXIS(model_dim, BLOCK_SIZE)
-) {
- float sum = 0.0f;
- for (uint row_idx = 0; row_idx < num_rows; row_idx++) {
- uint token = token_indices[row_idx];
- uint row = row_idx * codebook_stride + token;
- if (row < total_rows) {
- sum += float(weights[row * model_dim + dim_idx]);
- }
- }
- output[dim_idx] = T(sum);
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/generated/activation_type.h b/crates/backend-uzu/src/backends/metal/kernel/generated/activation_type.h
index 60b21b5de..e149ae8a9 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/generated/activation_type.h
+++ b/crates/backend-uzu/src/backends/metal/kernel/generated/activation_type.h
@@ -9,8 +9,7 @@ enum class ActivationType : uint32_t {
SILU = 0,
GELUApprox = 1,
GELUExact = 2,
- TANH = 3,
- IDENTITY = 4,
- SOFTPLUS = 5,
+ IDENTITY = 3,
+ SOFTPLUS = 4,
};
} // namespace uzu::activation_type
diff --git a/crates/backend-uzu/src/backends/metal/kernel/generated/kv_cache_update.h b/crates/backend-uzu/src/backends/metal/kernel/generated/kv_cache_update.h
index b4a175e60..ca5bec6f7 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/generated/kv_cache_update.h
+++ b/crates/backend-uzu/src/backends/metal/kernel/generated/kv_cache_update.h
@@ -8,5 +8,5 @@ namespace uzu::kv_cache_update {
typedef struct {
uint32_t source;
uint32_t destination;
-} Swap;
+} Copy;
} // namespace uzu::kv_cache_update
diff --git a/crates/backend-uzu/src/backends/metal/kernel/kv_cache_update/kv_cache_update.metal b/crates/backend-uzu/src/backends/metal/kernel/kv_cache_update/kv_cache_update.metal
deleted file mode 100644
index 76582bca9..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/kv_cache_update/kv_cache_update.metal
+++ /dev/null
@@ -1,36 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-#include "kv_cache_update.h"
-
-template <typename T>
-void swap(device T* buffer, const uint sourceIdx, const uint destIdx) {
- const T temp = buffer[sourceIdx];
- buffer[sourceIdx] = buffer[destIdx];
- buffer[destIdx] = temp;
-}
-
-template <typename T>
-VARIANTS(T, float, bfloat, half)
-PUBLIC KERNEL(KVCacheUpdate) (
- device T* in_place_keys,
- device T* in_place_values,
- const constant uzu::kv_cache_update::Swap* swaps,
- const constant uint& swap_count,
- const constant uint& num_heads,
- const constant uint& head_dim,
- const uint head_idx AXIS(num_heads, 32),
- const uint channel_idx AXIS(head_dim, 32)
-) {
- for (uint i = 0; i < swap_count; ++i) {
- // Token-major layout: [max_sequence_length, num_heads, head_dim]
- // Offset = token_idx * num_heads * head_dim +
- // head_idx * head_dim + channel_idx
- const uint head_offset = head_idx * head_dim;
- const uint sourceIdx = swaps[i].source * num_heads * head_dim + head_offset + channel_idx;
- const uint destIdx = swaps[i].destination * num_heads * head_dim + head_offset + channel_idx;
-
- swap(in_place_keys, sourceIdx, destIdx);
- swap(in_place_values, sourceIdx, destIdx);
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/layer_norm/layer_norm.metal b/crates/backend-uzu/src/backends/metal/kernel/layer_norm/layer_norm.metal
deleted file mode 100644
index 902c624c2..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/layer_norm/layer_norm.metal
+++ /dev/null
@@ -1,143 +0,0 @@
-#include <metal_stdlib>
-#include "../common/defines.h"
-#include "../common/dsl.h"
-#include "../common/thread_context.h"
-#include "../common/threadgroup_reduce.h"
-
-#define BLOCK_SIZE 1024
-#define GRAIN_SIZE 4
-
-// LayerNorm: subtract mean, then normalize (for BERT-style models)
-template <typename InputT, typename ScaleT, typename OutputT, typename AccumT>
-void layer_norm_core(
- const device InputT* input_data,
- const device ScaleT* scales_data,
- device OutputT* output_data,
- uint element_count,
- constant float& epsilon,
- constant float& scale_offset,
- threadgroup AccumT* shared_mean,
- threadgroup AccumT* shared_variance,
- uint thread_in_row,
- bool full_layer,
- const thread ThreadContext& thread_context
-) {
- AccumT partial_sum = static_cast<AccumT>(0.0f);
-
- // Compute mean: sum all elements
- for (uint base_i = thread_in_row * GRAIN_SIZE; base_i < element_count; base_i += BLOCK_SIZE * GRAIN_SIZE) {
- for (uint j = 0; j < GRAIN_SIZE; ++j) {
- uint i = base_i + j;
- if (i < element_count) {
- partial_sum += static_cast<AccumT>(input_data[i]);
- }
- }
- }
-
- // Reduce to get total mean
- AccumT total_sum =
- threadgroup_cooperative_reduce<SimdReduceSum<AccumT>, BLOCK_SIZE>(partial_sum, shared_mean, thread_context);
- AccumT mean = total_sum / static_cast<AccumT>(element_count);
-
- // Compute variance: sum of squared deviations
- AccumT partial_var_sum = static_cast<AccumT>(0.0f);
- for (uint base_i = thread_in_row * GRAIN_SIZE; base_i < element_count; base_i += BLOCK_SIZE * GRAIN_SIZE) {
- for (uint j = 0; j < GRAIN_SIZE; ++j) {
- uint i = base_i + j;
- if (i < element_count) {
- AccumT centered = static_cast<AccumT>(input_data[i]) - mean;
- partial_var_sum += centered * centered;
- }
- }
- }
-
- // Reduce to get total variance
- AccumT total_var = threadgroup_cooperative_reduce<SimdReduceSum<AccumT>, BLOCK_SIZE>(
- partial_var_sum,
- shared_variance,
- thread_context
- );
- AccumT variance = total_var / static_cast<AccumT>(element_count);
- AccumT inv_std = rsqrt(variance + static_cast<AccumT>(epsilon));
-
- // Apply normalization and scaling
- for (uint base_i = thread_in_row * GRAIN_SIZE; base_i < element_count; base_i += BLOCK_SIZE * GRAIN_SIZE) {
- AccumT vals[GRAIN_SIZE];
- AccumT scaled_vals[GRAIN_SIZE];
-
- // Load and center
- for (uint j = 0; j < GRAIN_SIZE; ++j) {
- uint i = base_i + j;
- vals[j] = (i < element_count) ? (static_cast<AccumT>(input_data[i]) - mean) : 0.0f;
- }
-
- // Normalize and scale
- for (uint j = 0; j < GRAIN_SIZE; ++j) {
- uint i = base_i + j;
- if (i >= element_count) {
- continue;
- }
-
- AccumT normalized_high = vals[j] * inv_std;
-
- if (full_layer) {
- AccumT scale_value_high = static_cast<AccumT>(scales_data[i]) + static_cast<AccumT>(scale_offset);
- scaled_vals[j] = normalized_high * scale_value_high;
- } else {
- OutputT normalized_low = static_cast<OutputT>(normalized_high);
- OutputT scale_value_low =
- static_cast<OutputT>(static_cast<AccumT>(scales_data[i]) + static_cast<AccumT>(scale_offset));
- OutputT product_low = normalized_low * scale_value_low;
- scaled_vals[j] = static_cast<AccumT>(product_low);
- }
- }
-
- // Store
- for (uint j = 0; j < GRAIN_SIZE; ++j) {
- uint i = base_i + j;
- if (i < element_count) {
- output_data[i] = static_cast<OutputT>(scaled_vals[j]);
- }
- }
- }
-}
-
-template <typename IN, typename SC, typename OUT, typename ACC>
-VARIANTS(IN, float, half, bfloat)
-VARIANTS(SC, float, half, bfloat)
-VARIANTS(OUT, float, half, bfloat)
-VARIANTS(ACC, float)
-PUBLIC KERNEL(LayerNorm) (
- const device IN* input OPTIONAL(!in_place),
- const device SC* scales,
- device OUT* output,
- constant uint& batch_size,
- constant uint& model_dim,
- constant float& epsilon,
- constant float& scale_offset,
- constant uint& full_layer,
- const bool in_place SPECIALIZE,
- threadgroup ACC shared_mean[METAL_SIMD_SIZE],
- threadgroup ACC shared_variance[METAL_SIMD_SIZE],
- const ThreadContext thread_context,
- uint batch_idx GROUPS(batch_size),
- uint thread_in_row THREADS(BLOCK_SIZE)
-) {
- if (in_place) {
- input = reinterpret_cast<const device IN*>(output);
- }
- const uint input_offset = batch_idx * model_dim;
- layer_norm_core<IN, SC, OUT, ACC>(
- input + input_offset,
- scales,
- output + input_offset,
- model_dim,
- epsilon,
- scale_offset,
- shared_mean,
- shared_variance,
- thread_in_row,
- full_layer,
- thread_context
- );
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/common/loader.h b/crates/backend-uzu/src/backends/metal/kernel/matmul/common/loader.h
index 81eec16f0..03b8ee587 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/common/loader.h
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/common/loader.h
@@ -21,8 +21,6 @@ template <
ushort THREAD_COLS = THREADGROUP_TILE_COLS / READS_PER_THREAD,
ushort THREAD_ROWS = THREADGROUP_SIZE / THREAD_COLS>
struct ThreadgroupLoader {
- METAL_CONST ushort ROW_ITERATIONS = (THREADGROUP_TILE_ROWS + THREAD_ROWS - 1) / THREAD_ROWS;
-
const int source_leading_dimension;
const int tile_stride;
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/common/quant_unpack.h b/crates/backend-uzu/src/backends/metal/kernel/matmul/common/quant_unpack.h
index 137cdb4fd..75c944ddc 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/common/quant_unpack.h
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/common/quant_unpack.h
@@ -50,55 +50,5 @@ METAL_FUNC bfloat4 uint4_to_fp4<bfloat, 8>(uint4 n) {
return bfloat4(_uint4_to_fp4_float<8>(n));
}
-template <typename U, int N, int bits>
-METAL_FUNC void dequantize(const device uint8_t* w, U scale, U bias, threadgroup U* w_local) {
- static_assert(bits == 4 || bits == 8, "Only int4 and int8 supported");
-
- if constexpr (bits == 4) {
- U s0 = scale;
- U s1 = scale / static_cast<U>(16.0f);
- METAL_PRAGMA_UNROLL
- for (int i = 0; i < (N / 2); i++) {
- w_local[2 * i] = s0 * (w[i] & 0x0f) + bias;
- w_local[2 * i + 1] = s1 * (w[i] & 0xf0) + bias;
- }
- } else if constexpr (bits == 8) {
- METAL_PRAGMA_UNROLL
- for (int i = 0; i < N; i++) {
- w_local[i] = scale * w[i] + bias;
- }
- }
-}
-
-template <>
-METAL_FUNC void dequantize<bfloat, 8, 4>(
- const device uint8_t* w,
- bfloat scale,
- bfloat bias,
- threadgroup bfloat* w_local
-) {
- const device uint32_t* w_ptr = reinterpret_cast<const device uint32_t*>(w);
- uint32_t packed = *w_ptr;
-
- bfloat4 v0, v1;
-
- v0.x = static_cast<bfloat>(packed & 0xF);
- v0.y = static_cast<bfloat>((packed >> 4) & 0xF);
- v0.z = static_cast<bfloat>((packed >> 8) & 0xF);
- v0.w = static_cast<bfloat>((packed >> 12) & 0xF);
-
- v1.x = static_cast<bfloat>((packed >> 16) & 0xF);
- v1.y = static_cast<bfloat>((packed >> 20) & 0xF);
- v1.z = static_cast<bfloat>((packed >> 24) & 0xF);
- v1.w = static_cast<bfloat>((packed >> 28) & 0xF);
-
- v0 = v0 * scale + bias;
- v1 = v1 * scale + bias;
-
- threadgroup bfloat4* out_ptr = reinterpret_cast<threadgroup bfloat4*>(w_local);
- out_ptr[0] = v0;
- out_ptr[1] = v1;
-}
-
} // namespace gemm
} // namespace uzu
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/common/threadgroup_tile.h b/crates/backend-uzu/src/backends/metal/kernel/matmul/common/threadgroup_tile.h
index 0cfcfe03c..819da522b 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/common/threadgroup_tile.h
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/common/threadgroup_tile.h
@@ -28,9 +28,6 @@ struct ThreadgroupTile {
METAL_CONST ushort SIMDGROUP_BLOCK_SIZE = 8;
using SimdgroupMMAType = SimdgroupMMA<AccumulatorType, SIMDGROUP_BLOCK_SIZE, SIMDGROUP_BLOCK_SIZE>;
- METAL_CONST ushort TILE_ROW_STRIDE = SIMDGROUP_BLOCK_SIZE * SIMDGROUPS_PER_ROW;
- METAL_CONST ushort TILE_COL_STRIDE = SIMDGROUP_BLOCK_SIZE * SIMDGROUPS_PER_COLUMN;
-
METAL_CONST ushort TILE_ROWS = BLOCK_ROWS / (SIMDGROUP_BLOCK_SIZE * SIMDGROUPS_PER_ROW);
METAL_CONST ushort TILE_COLS = BLOCK_COLS / (SIMDGROUP_BLOCK_SIZE * SIMDGROUPS_PER_COLUMN);
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs
index 09461c16a..a14a5e1b4 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs
@@ -4,13 +4,13 @@ use super::specialization::GemmSpecialization;
use crate::{
backends::{
common::{
- Allocation, AsBufferRangeRef, Backend, Buffer, Encoder,
+ Allocation, Backend, Encoder,
gpu_types::{
GemmParams, HadamardTransformOrder,
gemm::{GemmAlignment, GemmBPrologueKind, GemmDTransform, GemmTiling},
},
kernel::{
- HadamardTransformKernel, Kernels, TensorAddBiasKernel,
+ BufferArg, HadamardTransformKernel, Kernels, TensorAddBiasKernel,
matmul::{MatmulArguments, MatmulB, MatmulError},
},
},
@@ -107,9 +107,9 @@ impl GemmKernel {
}
}
- pub(crate) fn should_skip_gemv_for_mxu<TB: AsBufferRangeRef>(
+ pub(crate) fn should_skip_gemv_for_mxu<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(
&self,
- arguments: &MatmulArguments<'_, Metal, TB>,
+ arguments: &MatmulArguments<'a, 'b, 'd, Metal, TB>,
) -> bool {
match (
arguments.m,
@@ -138,9 +138,9 @@ impl GemmKernel {
)
}
- fn select_mxu_tiling<TB: AsBufferRangeRef>(
+ fn select_mxu_tiling<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(
&self,
- arguments: &MatmulArguments<'_, Metal, TB>,
+ arguments: &MatmulArguments<'a, 'b, 'd, Metal, TB>,
) -> Option<GemmTiling> {
if ![self.weights_data_type, self.input_data_type, self.output_data_type]
.into_iter()
@@ -166,7 +166,7 @@ impl GemmKernel {
| MatmulB::ScaleSymmetricDequant {
..
} => {
- if !arguments.b_transpose || arguments.b_leading_dimension.is_some() || arguments.b_offset != 0 {
+ if !arguments.b_transpose || arguments.b_leading_dimension.is_some() {
return None;
}
let tiling = select_mxu_quant_tiling(arguments.m, arguments.n, arguments.b.group_size().unwrap_or(0));
@@ -175,9 +175,9 @@ impl GemmKernel {
}
}
- pub fn encode<'a, TB: AsBufferRangeRef<Buffer: Buffer<Backend = Metal>>>(
+ pub fn encode<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(
&mut self,
- arguments: MatmulArguments<'a, Metal, TB>,
+ arguments: MatmulArguments<'a, 'b, 'd, Metal, TB>,
encoder: &mut Encoder<Metal>,
) -> Result<(), MetalError> {
let path = if encoder.context().device.supports_mxu() && self.select_mxu_tiling(&arguments).is_some() {
@@ -188,9 +188,9 @@ impl GemmKernel {
self.encode_dispatch_path(arguments, path, encoder)
}
- pub fn encode_dispatch_path<'a, TB: AsBufferRangeRef<Buffer: Buffer<Backend = Metal>>>(
+ pub fn encode_dispatch_path<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(
&mut self,
- arguments: MatmulArguments<'a, Metal, TB>,
+ arguments: MatmulArguments<'a, 'b, 'd, Metal, TB>,
path: GemmDispatchPath,
encoder: &mut Encoder<Metal>,
) -> Result<(), MetalError> {
@@ -224,7 +224,7 @@ impl GemmKernel {
!d_mask.contains(GemmDTransform::BIAS | GemmDTransform::RHT),
"QuantGemm with both output bias and output RHT is not supported: bias must be applied after RHT",
);
- if !arguments.b_transpose || arguments.b_leading_dimension.is_some() || arguments.b_offset != 0 {
+ if !arguments.b_transpose || arguments.b_leading_dimension.is_some() {
return Err(MatmulError::UnsupportedLayout {
path: "QuantGemm",
}
@@ -245,7 +245,6 @@ impl GemmKernel {
a,
a_offset,
b,
- b_offset,
b_leading_dimension,
b_transpose,
d,
@@ -293,7 +292,7 @@ impl GemmKernel {
let alignment =
GemmAlignment::new(m % tiling.block_m() == 0, n % tiling.block_n() == 0, k % tiling.block_k() == 0);
- if b_transpose && b_leading_dimension.is_none() && b_offset == 0 {
+ if b_transpose && b_leading_dimension.is_none() {
let split_k = select_split_k(m, n, k, tiling, use_mxu, 0, true, false);
if split_k > 1
&& split_k_output_supported(output_transform, n, self.weights_data_type, self.output_data_type)
@@ -302,7 +301,6 @@ impl GemmKernel {
a,
a_offset,
weights,
- b_offset,
None,
None,
None,
@@ -359,7 +357,7 @@ impl GemmKernel {
let kernel = self.get_or_create(encoder.context(), specialization)?;
kernel.encode(
(a, a_offset),
- (weights, b_offset),
+ weights,
&mut *d,
None::<&Allocation<Metal>>,
None::<&Allocation<Metal>>,
@@ -423,7 +421,6 @@ impl GemmKernel {
a,
a_offset,
weights,
- b_offset,
scales,
biases,
zero_points,
@@ -460,7 +457,7 @@ impl GemmKernel {
let kernel = self.get_or_create(encoder.context(), specialization)?;
kernel.encode(
(a, a_offset),
- (weights, b_offset),
+ weights,
&mut *d,
scales,
biases,
@@ -480,15 +477,11 @@ impl GemmKernel {
}
#[allow(clippy::too_many_arguments)]
- fn encode_split_k<
- TB: AsBufferRangeRef<Buffer: Buffer<Backend = Metal>>,
- WB: AsBufferRangeRef<Buffer: Buffer<Backend = Metal>>,
- >(
+ fn encode_split_k<'a, WB: BufferArg<'a, Metal>>(
&mut self,
- a: &TB,
+ a: &Allocation<Metal>,
a_offset: usize,
- weights: &WB,
- b_offset: usize,
+ weights: WB,
scales: Option<&Allocation<Metal>>,
biases: Option<&Allocation<Metal>>,
zero_points: Option<&Allocation<Metal>>,
@@ -548,7 +541,7 @@ impl GemmKernel {
let part_kernel = self.get_or_create(encoder.context(), part_spec)?;
part_kernel.encode(
(a, a_offset),
- (weights, b_offset),
+ weights,
&mut temp,
scales,
biases,
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs
index 871e7915e..0e847cfaa 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs
@@ -7,9 +7,12 @@ use super::policy::{self, DEFAULT_RESULTS_PER_SIMDGROUP, FP_K_BLOCK};
use crate::{
backends::{
common::{
- Allocation, AsBufferRangeRef, Buffer, Encoder,
+ Allocation, Encoder,
gpu_types::gemm::{GemmBPrologueKind, GemmDTransform},
- kernel::matmul::{MatmulArguments, MatmulB, MatmulError},
+ kernel::{
+ BufferArg,
+ matmul::{MatmulArguments, MatmulB, MatmulError},
+ },
},
metal::{Metal, context::MetalContext, device_tier::DeviceTier, kernel::GemvMetalKernel},
},
@@ -38,14 +41,14 @@ pub(crate) struct GemvSpecialization {
}
impl GemvSpecialization {
- pub(crate) fn select<TB: AsBufferRangeRef>(
- args: &MatmulArguments<Metal, TB>,
+ pub(crate) fn select<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(
+ args: &MatmulArguments<'a, 'b, 'd, Metal, TB>,
weights_data_type: DataType,
input_data_type: DataType,
output_data_type: DataType,
device_tier: DeviceTier,
) -> Option<GemvSpecialization> {
- if !args.b_transpose || args.b_offset != 0 {
+ if !args.b_transpose {
return None;
}
let is_quant = !matches!(args.b, MatmulB::FullPrecision { .. });
@@ -165,9 +168,9 @@ impl GemvDispatch {
}
}
- pub(crate) fn encode<'a, TB: AsBufferRangeRef<Buffer: Buffer<Backend = Metal>>>(
+ pub(crate) fn encode<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(
&mut self,
- arguments: MatmulArguments<'a, Metal, TB>,
+ arguments: MatmulArguments<'a, 'b, 'd, Metal, TB>,
specialization: GemvSpecialization,
encoder: &mut Encoder<Metal>,
) -> Result<(), MatmulError<Metal>> {
diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/mod.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/mod.rs
index fef09704b..27afb618f 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/mod.rs
+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/mod.rs
@@ -6,8 +6,11 @@ use self::gemv::{GemvDispatch, GemvSpecialization};
use crate::{
backends::{
common::{
- AsBufferRangeRef, Buffer, Encoder,
- kernel::matmul::{MatmulArguments, MatmulError, MatmulKernel},
+ Encoder,
+ kernel::{
+ BufferArg,
+ matmul::{MatmulArguments, MatmulError, MatmulKernel},
+ },
},
metal::{Metal, context::MetalContext, error::MetalError, metal_extensions::DeviceExt},
},
@@ -49,9 +52,9 @@ impl MatmulKernel for MatmulMetalKernel {
})
}
- fn encode<TB: AsBufferRangeRef<Buffer: Buffer<Backend = Metal>>>(
+ fn encode<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(
&mut self,
- arguments: MatmulArguments<Metal, TB>,
+ arguments: MatmulArguments<'a, 'b, 'd, Metal, TB>,
encoder: &mut Encoder<Metal>,
) -> Result<(), MetalError> {
let skip_gemv = encoder.context().device.supports_mxu() && self.gemm.should_skip_gemv_for_mxu(&arguments);
diff --git a/crates/backend-uzu/src/backends/metal/kernel/moe/experts_single.metal b/crates/backend-uzu/src/backends/metal/kernel/moe/experts_single.metal
deleted file mode 100644
index 9f4022cee..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/moe/experts_single.metal
+++ /dev/null
@@ -1,174 +0,0 @@
-#include <metal_stdlib>
-#include <metal_simdgroup>
-#include "../activation/activations.h"
-#include "../common/dsl.h"
-#include "../common/thread_context.h"
-
-// ============================================================================
-// Pass A: x @ W13[expert] → hidden[k]
-// Each threadgroup: 4 simdgroups, outputs 4 elements (1 per simdgroup)
-// Each simdgroup: 32 threads reduce d_model with float4 vectorized loads
-// Grid: (ceil(d_ff/4), K)
-// ============================================================================
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(MoeExpertsDecodeSinglePassA)(
- device const T* x,
- device const int* topk_ids,
- device const T* w13_all,
- device const T* biases,
- device float* hidden_out,
- constant uint& d_model,
- constant uint& d_ff,
- constant uint& k,
- constant float& silu_alpha,
- constant float& gate_clip_min,
- constant float& gate_clip_max,
- constant float& up_clip_min,
- constant float& up_clip_max,
- const uint gating_sel SPECIALIZE, // 0=GELU, 1=SiLU, 2=SwiGLU, 3=GEGLU
- const ThreadContext thread_context,
- const uint h_block_idx GROUPS(d_ff.div_ceil(4)),
- const uint k_slot GROUPS(k),
- const uint tid THREADS(128)
-) {
- const int expert_id = topk_ids[k_slot];
- if (expert_id < 0)
- return;
- const uint expert_u = uint(expert_id);
-
- const uint h_idx = h_block_idx * 4 + thread_context.simdgroup_index;
- if (h_idx >= d_ff)
- return;
-
- const ulong w13_stride = (ulong)d_model * (ulong)(2 * d_ff);
- const ulong w13_base = (ulong)expert_u * w13_stride;
- const ulong bias_base = (ulong)expert_u * (ulong)(2 * d_ff);
-
- device const T* w_up_row = w13_all + w13_base + (ulong)h_idx * (ulong)d_model;
- device const T* w_gate_row = w13_all + w13_base + (ulong)(d_ff + h_idx) * (ulong)d_model;
-
- float acc_up = 0.0f;
- float acc_gate = 0.0f;
-
- const uint vec_iters = d_model / 128;
-
- for (uint i = 0; i < vec_iters; ++i) {
- uint base_idx = i * 128 + thread_context.simd_lane_id * 4;
-
- device const T* x_vec2 = reinterpret_cast<device const T*>(x + base_idx);
- device const T* w_up_vec2 = reinterpret_cast<device const T*>(w_up_row + base_idx);
- acc_up += float(x_vec2[0]) * float(w_up_vec2[0]);
- acc_up += float(x_vec2[1]) * float(w_up_vec2[1]);
- acc_up += float(x_vec2[2]) * float(w_up_vec2[2]);
- acc_up += float(x_vec2[3]) * float(w_up_vec2[3]);
-
- if (gating_sel > 1) {
- device const T* w_gate_vec2 = reinterpret_cast<device const T*>(w_gate_row + base_idx);
- acc_gate += float(x_vec2[0]) * float(w_gate_vec2[0]);
- acc_gate += float(x_vec2[1]) * float(w_gate_vec2[1]);
- acc_gate += float(x_vec2[2]) * float(w_gate_vec2[2]);
- acc_gate += float(x_vec2[3]) * float(w_gate_vec2[3]);
- }
- }
-
- uint leftover_start = vec_iters * 128 + thread_context.simd_lane_id;
- for (uint idx = leftover_start; idx < d_model; idx += 32) {
- float xv = float(x[idx]);
- acc_up += xv * float(w_up_row[idx]);
- if (gating_sel > 1) {
- acc_gate += xv * float(w_gate_row[idx]);
- }
- }
-
- acc_up = simd_sum(acc_up);
- if (gating_sel > 1) {
- acc_gate = simd_sum(acc_gate);
- }
-
- if (thread_context.simd_lane_id == 0) {
- float up_val = clamp(acc_up + float(biases[bias_base + h_idx]), up_clip_min, up_clip_max);
-
- float activated;
- if (gating_sel <= 1) {
- activated = (gating_sel == 0) ? activate_gelu(up_val) : activate_silu_alpha(up_val, silu_alpha);
- } else {
- float gate_val = clamp(acc_gate + float(biases[bias_base + d_ff + h_idx]), gate_clip_min, gate_clip_max);
- float gate_act = (gating_sel == 2) ? activate_silu_alpha(gate_val, silu_alpha) : activate_gelu(gate_val);
- activated = gate_act * up_val;
- }
-
- hidden_out[(ulong)k_slot * (ulong)d_ff + (ulong)h_idx] = activated;
- }
-}
-
-// ============================================================================
-// Pass B (fused with finalize): hidden[k] @ W2[expert] → y (directly)
-// Computes: y[d] = Σ_k prob[k] * (hidden[k] @ W2[expert_k, d] + bias)
-// Each simdgroup computes one final output element
-// Grid: (ceil(d_model/8), 1) - NOT per K!
-// ============================================================================
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(MoeExpertsDecodeSinglePassB)(
- device const float* hidden, // [K, d_ff]
- device const int* topk_ids, // [K]
- device const T* topk_probs, // [K]
- device const T* w2_all, // [E, d_model, d_ff]
- device const T* biases, // [E, d_model]
- device T* y, // [d_model]
- constant uint& d_model,
- constant uint& d_ff,
- constant uint& k_input,
- const ThreadContext thread_context,
- const uint d_block GROUPS(d_model.div_ceil(8)),
- const uint tid THREADS(256)
-) {
- const uint my_col = d_block * 8 + thread_context.simdgroup_index;
- if (my_col >= d_model)
- return;
-
- const uint vec_iters = d_ff / 128;
- const ulong w2_expert_stride = (ulong)d_model * (ulong)d_ff;
-
- float final_acc = 0.0f;
-
- // Loop over k_input experts
- for (uint k = 0; k < k_input; ++k) {
- const uint expert_u = uint(topk_ids[k]);
- const float prob = float(topk_probs[k]);
-
- device const float* hidden_ptr = hidden + (ulong)k * (ulong)d_ff;
- device const T* w2_ptr = w2_all + (ulong)expert_u * w2_expert_stride + (ulong)my_col * (ulong)d_ff;
-
- float acc = 0.0f;
-
- // Vectorized reduction
- for (uint i = 0; i < vec_iters; ++i) {
- uint base_idx = i * 128 + thread_context.simd_lane_id * 4;
-
- float4 h_vec = *reinterpret_cast<device const float4*>(hidden_ptr + base_idx);
- device const T* w_vec2 = reinterpret_cast<device const T*>(w2_ptr + base_idx);
- acc += h_vec.x * float(w_vec2[0]);
- acc += h_vec.y * float(w_vec2[1]);
- acc += h_vec.z * float(w_vec2[2]);
- acc += h_vec.w * float(w_vec2[3]);
- }
-
- // Remainder
- for (uint idx = vec_iters * 128 + thread_context.simd_lane_id; idx < d_ff; idx += 32) {
- acc += hidden_ptr[idx] * float(w2_ptr[idx]);
- }
-
- // Simdgroup reduction and accumulate
- float result = simd_sum(acc);
- if (thread_context.simd_lane_id == 0) {
- result += float(biases[(ulong)expert_u * (ulong)d_model + (ulong)my_col]);
- final_acc += prob * result;
- }
- }
-
- if (thread_context.simd_lane_id == 0) {
- y[my_col] = T(final_acc);
- }
-}
\ No newline at end of file
diff --git a/crates/backend-uzu/src/backends/metal/kernel/moe/experts_two_pass_prefill.metal b/crates/backend-uzu/src/backends/metal/kernel/moe/experts_two_pass_prefill.metal
index 0d7ab3bbc..35576d775 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/moe/experts_two_pass_prefill.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/moe/experts_two_pass_prefill.metal
@@ -9,19 +9,6 @@ static inline uint ceil_div(uint a, uint b) { return (a + b - 1u) / b; }
static inline uint linear_tid(uint3 tid, uint3 tpg) { return tid.z * (tpg.x * tpg.y) + tid.y * tpg.x + tid.x; }
-template <typename T>
-inline void store_vec4(device T* dst, ulong base, float4 vals) {
- dst[base + 0] = T(vals.x);
- dst[base + 1] = T(vals.y);
- dst[base + 2] = T(vals.z);
- dst[base + 3] = T(vals.w);
-}
-
-template <>
-inline void store_vec4<float>(device float* dst, ulong base, float4 vals) {
- *reinterpret_cast<device float4*>(dst + base) = vals;
-}
-
// ------------------------ Pass A (X @ W13 → hidden) ------------------------
// Tile config (tuned for A-series; matches your prior defaults)
constant uint PASSA_BM = 16;
diff --git a/crates/backend-uzu/src/backends/metal/kernel/moe/scatter_buckets.metal b/crates/backend-uzu/src/backends/metal/kernel/moe/scatter_buckets.metal
index 1b7a3269a..85adc349f 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/moe/scatter_buckets.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/moe/scatter_buckets.metal
@@ -23,9 +23,7 @@ inline void moe_scatter_buckets_impl(
uint T,
uint E,
uint K,
- uint num_blocks,
uint num_tiles,
- uint3 tid3,
uint lid,
uint3 tgpig,
threadgroup _atomic<uint>* sg_counts,
@@ -166,53 +164,6 @@ PUBLIC KERNEL(MoeBlockBasesFromPartials)(
}
}
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(MoeScatterBuckets)(
- device const int* topk_ids,
- device const T* topk_probs,
- device const uint* offsets,
- device const uint* block_bases,
- device const uint* block_alloc,
- device int* out_ids,
- device T* out_probs,
- constant uint& t,
- constant uint& e,
- constant uint& k,
- constant uint& num_blocks,
- constant uint& num_tiles,
- threadgroup _atomic<uint> sg_counts[NUM_SG * TILE_E],
- threadgroup uint sg_base[NUM_SG * TILE_E],
- const ThreadContext thread_context,
- const uint tgpig_x GROUPS(num_blocks),
- const uint lid THREADS(256)
-) {
- const uint3 tgpig = {tgpig_x, 0, 0};
- const uint tid_x = tgpig.x * BLOCK_SIZE + lid;
- const uint3 tid3 = {tid_x, 0, 0};
- moe_scatter_buckets_impl<T>(
- topk_ids,
- topk_probs,
- offsets,
- block_bases,
- block_alloc,
- out_ids,
- out_probs,
- (device int*)nullptr,
- t,
- e,
- k,
- num_blocks,
- num_tiles,
- tid3,
- lid,
- tgpig,
- sg_counts,
- sg_base,
- thread_context
- );
-}
-
// Map variants
template <typename T>
VARIANTS(T, float, half, bfloat)
@@ -237,8 +188,6 @@ PUBLIC KERNEL(MoeScatterBucketsMap)(
const uint lid THREADS(256)
) {
const uint3 tgpig = {tgpig_x, 0, 0};
- const uint tid_x = tgpig.x * BLOCK_SIZE + lid;
- const uint3 tid3 = {tid_x, 0, 0};
moe_scatter_buckets_impl<T>(
topk_ids,
topk_probs,
@@ -251,13 +200,11 @@ PUBLIC KERNEL(MoeScatterBucketsMap)(
t,
e,
k,
- num_blocks,
num_tiles,
- tid3,
lid,
tgpig,
sg_counts,
sg_base,
thread_context
);
-}
\ No newline at end of file
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/rms_norm/rms_norm.metal b/crates/backend-uzu/src/backends/metal/kernel/normalization/normalization.metal
similarity index 74%
rename from crates/backend-uzu/src/backends/metal/kernel/rms_norm/rms_norm.metal
rename to crates/backend-uzu/src/backends/metal/kernel/normalization/normalization.metal
index af3911905..5f1a7ada7 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/rms_norm/rms_norm.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/normalization/normalization.metal
@@ -9,12 +9,14 @@ using namespace metal;
#define BLOCK_SIZE 1024
+// TODO: Are numerics of subtract_mean fine?
+
template <typename InputT, typename ScaleT, typename OutputT, typename AccumT>
VARIANTS(InputT, float, half, bfloat)
VARIANTS(ScaleT, float, half, bfloat)
VARIANTS(OutputT, float, half, bfloat)
-VARIANTS(AccumT, float, half)
-PUBLIC KERNEL(RMSNorm)(
+VARIANTS(AccumT, float)
+PUBLIC KERNEL(Normalization)(
const device InputT* input OPTIONAL(!in_place),
const device ScaleT* scales,
device OutputT* output,
@@ -26,6 +28,7 @@ PUBLIC KERNEL(RMSNorm)(
constant float& scale_offset,
constant float& post_layer_scalar,
const bool in_place SPECIALIZE,
+ const bool subtract_mean SPECIALIZE,
const bool full_layer SPECIALIZE,
const bool copy_to_shortcut SPECIALIZE,
const bool residual_add SPECIALIZE,
@@ -35,7 +38,7 @@ PUBLIC KERNEL(RMSNorm)(
threadgroup AccumT shared_sum[METAL_SIMD_SIZE],
const ThreadContext thread_context,
const uint batch_idx GROUPS(batch_size),
- const uint thread_in_row THREADS(1024)
+ const uint thread_in_row THREADS(BLOCK_SIZE)
) {
if (in_place) {
input = reinterpret_cast<const device InputT*>(output);
@@ -48,7 +51,8 @@ PUBLIC KERNEL(RMSNorm)(
shortcut += batch_offset;
}
- // Step 1 - threads read from global and accumulate sum of squares
+ // Step 1 - threads read from global and accumulate sum / sum of squares
+ AccumT thread_sum = static_cast<AccumT>(0.0f);
AccumT thread_sum_of_squares = static_cast<AccumT>(0.0f);
for (uint i = thread_in_row; i < element_count; i += BLOCK_SIZE) {
@@ -56,7 +60,7 @@ PUBLIC KERNEL(RMSNorm)(
// We can also fuse:
// - TensorCopy (copy_to_shortcut)
// - TensorAddSwap (copy_to_shortcut + residual_add)
- // RMSNorm in TensorAddSwap fusion mode operates on input + shortcut
+ // Normalization in TensorAddSwap fusion mode operates on input + shortcut
if (copy_to_shortcut) {
if (residual_add) {
val += shortcut[i];
@@ -67,18 +71,33 @@ PUBLIC KERNEL(RMSNorm)(
shortcut[i] = val;
}
AccumT val_accum_t = static_cast<AccumT>(val);
+ if (subtract_mean) {
+ thread_sum += val_accum_t;
+ }
thread_sum_of_squares += val_accum_t * val_accum_t;
}
- // Step 2 - threads reduce their partial sums of squares
+ // Step 2 - threads reduce their partial sums / sums of squares
+ AccumT total_sum;
+ if (subtract_mean) {
+ total_sum =
+ threadgroup_cooperative_reduce<SimdReduceSum<AccumT>, BLOCK_SIZE>(thread_sum, shared_sum, thread_context);
+ }
AccumT total_sum_of_squares = threadgroup_cooperative_reduce<SimdReduceSum<AccumT>, BLOCK_SIZE>(
thread_sum_of_squares,
shared_sum,
thread_context
);
- // And pre-calculate rms_inv
- AccumT rms_inv = rsqrt(total_sum_of_squares / static_cast<AccumT>(element_count) + static_cast<AccumT>(epsilon));
+ // And calculate mean/var/rms_inv from it
+ AccumT mean = static_cast<AccumT>(0.0f);
+ if (subtract_mean) {
+ mean = total_sum / static_cast<AccumT>(element_count);
+ }
+
+ AccumT var = total_sum_of_squares / static_cast<AccumT>(element_count) - mean * mean;
+
+ AccumT rms_inv = rsqrt(var + static_cast<AccumT>(epsilon));
// Step 3 - elementwise normalization
for (uint i = thread_in_row; i < element_count; i += BLOCK_SIZE) {
@@ -97,9 +116,9 @@ PUBLIC KERNEL(RMSNorm)(
// If not, cast to OutputT after normalize, scale in OutputT
OutputT val;
if (full_layer) {
- val = static_cast<OutputT>(x * rms_inv * scale);
+ val = static_cast<OutputT>((x - mean) * rms_inv * scale);
} else {
- val = static_cast<OutputT>(x * rms_inv) * static_cast<OutputT>(scale);
+ val = static_cast<OutputT>((x - mean) * rms_inv) * static_cast<OutputT>(scale);
}
if (use_hadamard) {
diff --git a/crates/backend-uzu/src/backends/metal/kernel/pooling/pooling.metal b/crates/backend-uzu/src/backends/metal/kernel/pooling/pooling.metal
index f366c77e0..368b7b041 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/pooling/pooling.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/pooling/pooling.metal
@@ -1,22 +1,6 @@
#include <metal_stdlib>
#include "../common/dsl.h"
-// CLS pooling: Extract first token [batch, seq_len, hidden_dim] → [batch,
-// hidden_dim]
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(PoolingCls) (
- const device T* input,
- device T* output,
- constant uint& seq_len,
- constant uint& hidden_dim,
- constant uint& batch_size,
- uint dim_idx AXIS(hidden_dim, 16),
- uint batch_idx AXIS(batch_size, 16)
-) {
- output[batch_idx * hidden_dim + dim_idx] = input[batch_idx * seq_len * hidden_dim + dim_idx];
-}
-
// Mean pooling: Average across sequence [batch, seq_len, hidden_dim] → [batch,
// hidden_dim]
template <typename T>
diff --git a/crates/backend-uzu/src/backends/metal/kernel/rope/rope.metal b/crates/backend-uzu/src/backends/metal/kernel/rope/rope.metal
deleted file mode 100644
index 933f90b0b..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/rope/rope.metal
+++ /dev/null
@@ -1,98 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-#include "../common/tensor_view.h"
-
-template <typename ElementT>
-inline ElementT applyRopeTransform(
- TensorView3D<const ElementT> qkv_tensor_view,
- uint token_idx,
- uint head_idx,
- uint dim_idx,
- uint half_dim,
- float cos_val,
- float sin_val
-) {
- float inputVal = float(qkv_tensor_view(token_idx, head_idx, dim_idx));
- float pairedVal = (dim_idx < half_dim) ? -float(qkv_tensor_view(token_idx, head_idx, dim_idx + half_dim))
- : float(qkv_tensor_view(token_idx, head_idx, dim_idx - half_dim));
- return static_cast<ElementT>(inputVal * cos_val + pairedVal * sin_val);
-}
-
-template <typename ElementT, typename RopeT>
-VARIANTS(ElementT, float, half, bfloat)
-VARIANTS(RopeT, float, half, bfloat)
-PUBLIC KERNEL(Rope)(
- device const ElementT* qkv, // [suffix_len, total_heads, head_dim]
- device const RopeT* cosines, // [suffix_len, rope_dim]
- device const RopeT* sines, // [suffix_len, rope_dim]
- device ElementT* rotated_queries, // [num_heads, suffix_len, head_dim]
- device ElementT* rotated_keys OPTIONAL(!query_only),
- constant uint& head_dim,
- constant uint& rope_dim,
- constant uint& num_heads,
- constant uint& num_groups OPTIONAL(!query_only),
- constant uint& suffix_length,
- const bool query_only SPECIALIZE,
- const uint head_index AXIS(num_heads, 1),
- const uint token_index AXIS(suffix_length, 1),
- const uint dimension_index AXIS(head_dim, 128)
-) {
- if (head_index >= num_heads || token_index >= suffix_length || dimension_index >= head_dim)
- return;
- if (head_dim & 1)
- return;
- if (rope_dim & 1)
- return;
- if (rope_dim > head_dim)
- return;
- if (!query_only && (num_groups == 0 || num_heads % num_groups != 0))
- return;
-
- const uint total_heads = query_only ? num_heads : num_heads + 2 * num_groups;
- const uint half_rope_dim = rope_dim / 2;
-
- TensorView3D<const ElementT> qkv_tensor_view =
- TensorView3D<const ElementT>(qkv).shaped(suffix_length, total_heads, head_dim);
- TensorView2D<const RopeT> cosines_tensor_view = TensorView2D<const RopeT>(cosines).shaped(suffix_length, rope_dim);
- TensorView2D<const RopeT> sines_tensor_view = TensorView2D<const RopeT>(sines).shaped(suffix_length, rope_dim);
- TensorView3D<ElementT> rotated_queries_tensor_view =
- TensorView3D<ElementT>(rotated_queries).shaped(num_heads, suffix_length, head_dim);
-
- if (dimension_index < rope_dim) {
- const float cos_val = float(cosines_tensor_view(token_index, dimension_index));
- const float sin_val = float(sines_tensor_view(token_index, dimension_index));
- rotated_queries_tensor_view(head_index, token_index, dimension_index) =
- applyRopeTransform(qkv_tensor_view, token_index, head_index, dimension_index, half_rope_dim, cos_val, sin_val);
- } else {
- rotated_queries_tensor_view(head_index, token_index, dimension_index) =
- qkv_tensor_view(token_index, head_index, dimension_index);
- }
-
- if (query_only)
- return;
-
- const uint heads_per_group = num_heads / num_groups;
- const uint group_index = head_index / heads_per_group;
- if (head_index != group_index * heads_per_group)
- return;
-
- TensorView3D<ElementT> rotated_keys_tensor_view =
- TensorView3D<ElementT>(rotated_keys).shaped(num_groups, suffix_length, head_dim);
- const uint key_head_index = num_heads + group_index;
- if (dimension_index < rope_dim) {
- const float cos_val = float(cosines_tensor_view(token_index, dimension_index));
- const float sin_val = float(sines_tensor_view(token_index, dimension_index));
- rotated_keys_tensor_view(group_index, token_index, dimension_index) = applyRopeTransform(
- qkv_tensor_view,
- token_index,
- key_head_index,
- dimension_index,
- half_rope_dim,
- cos_val,
- sin_val
- );
- } else {
- rotated_keys_tensor_view(group_index, token_index, dimension_index) =
- qkv_tensor_view(token_index, key_head_index, dimension_index);
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/sampling/context_ring_update.metal b/crates/backend-uzu/src/backends/metal/kernel/sampling/context_ring_update.metal
new file mode 100644
index 000000000..3b67f8729
--- /dev/null
+++ b/crates/backend-uzu/src/backends/metal/kernel/sampling/context_ring_update.metal
@@ -0,0 +1,37 @@
+#include <metal_stdlib>
+#include "../common/dsl.h"
+#include "../generated/ring.h"
+
+using namespace uzu::ring;
+
+#define THREADGROUP_SIZE 256
+
+PUBLIC KERNEL(ContextRingUpdate)(
+ const device uint64_t* input,
+ device uint32_t* context_ring,
+ const constant uint32_t& suffix_repetition_length,
+ const constant uint32_t& input_length,
+ uint32_t thread_index THREADS(THREADGROUP_SIZE)
+) {
+ const RingParams ring = *reinterpret_cast<device RingParams*>(context_ring);
+
+ device uint32_t* ring_tokens = context_ring + 2;
+ const uint32_t write_start = input_length > suffix_repetition_length ? input_length - suffix_repetition_length : 0;
+
+ for (uint32_t input_index = write_start + thread_index; input_index < input_length; input_index += THREADGROUP_SIZE) {
+ const uint32_t slot = (ring.ring_offset + ring.ring_length + input_index) % suffix_repetition_length;
+ ring_tokens[slot] = static_cast<uint32_t>(input[input_index]);
+ }
+
+ threadgroup_barrier(mem_flags::mem_none);
+
+ if (thread_index == 0) {
+ const uint32_t total_length = ring.ring_length + input_length;
+ RingParams next_ring = ring;
+ next_ring.ring_length = min(total_length, suffix_repetition_length);
+ if (total_length > suffix_repetition_length) {
+ next_ring.ring_offset = (ring.ring_offset + total_length - suffix_repetition_length) % suffix_repetition_length;
+ }
+ *reinterpret_cast<device RingParams*>(context_ring) = next_ring;
+ }
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/sampling/repetition_penalty.metal b/crates/backend-uzu/src/backends/metal/kernel/sampling/repetition_penalty.metal
index 265c9bde5..95a00ec67 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/sampling/repetition_penalty.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/sampling/repetition_penalty.metal
@@ -14,24 +14,34 @@ PUBLIC KERNEL(RepetitionPenalty)(
const device uint64_t* token_ids,
const constant float& repetition_penalty,
const constant uint32_t& suffix_repetition_length,
- const uint32_t ring_index AXIS(suffix_repetition_length, 256)
+ const constant uint32_t& vocab_size,
+ const constant uint32_t& sampling_start,
+ const constant uint32_t& sampling_length,
+ const uint32_t position AXIS(sampling_length * suffix_repetition_length, 256)
) {
- const uint32_t input_token_id = static_cast<uint32_t>(token_ids[0]);
- if (ring_index == 0) {
- const float logit = static_cast<float>(original_logits[input_token_id]);
- const float penalized = logit > 0.0 ? logit / repetition_penalty : logit * repetition_penalty;
- logits_copy[input_token_id] = T(penalized);
- }
-
const RingParams ring = *reinterpret_cast<const device RingParams*>(context_ring);
- if (ring_index >= ring.ring_length) {
+
+ const uint32_t sample_index = position / suffix_repetition_length;
+ const uint32_t window_index = position % suffix_repetition_length;
+ const uint32_t batch_prefix_length = sampling_start + sample_index + 1;
+ const uint32_t total_length = ring.ring_length + batch_prefix_length;
+ const uint32_t window_length = min(total_length, suffix_repetition_length);
+ if (window_index >= window_length) {
return;
}
- const device uint32_t* ring_tokens = context_ring + 2;
- const uint32_t slot = (ring.ring_offset + ring_index) % suffix_repetition_length;
- const uint32_t token_id = ring_tokens[slot];
- const float logit = static_cast<float>(original_logits[token_id]);
+ const uint32_t source_index = total_length - window_length + window_index;
+ uint32_t token_id;
+ if (source_index < ring.ring_length) {
+ const device uint32_t* ring_tokens = context_ring + 2;
+ const uint32_t slot = (ring.ring_offset + source_index) % suffix_repetition_length;
+ token_id = ring_tokens[slot];
+ } else {
+ token_id = static_cast<uint32_t>(token_ids[source_index - ring.ring_length]);
+ }
+
+ const uint32_t logit_offset = sample_index * vocab_size + token_id;
+ const float logit = static_cast<float>(original_logits[logit_offset]);
const float penalized = logit > 0.0 ? logit / repetition_penalty : logit * repetition_penalty;
- logits_copy[token_id] = T(penalized);
+ logits_copy[logit_offset] = T(penalized);
}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/sampling/unified_sampling.metal b/crates/backend-uzu/src/backends/metal/kernel/sampling/unified_sampling.metal
index 2bad4b0db..70f9deb24 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/sampling/unified_sampling.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/sampling/unified_sampling.metal
@@ -68,7 +68,6 @@ PUBLIC KERNEL(UnifiedSampling) (
const bool is_stochastic SPECIALIZE,
const bool has_bitmask SPECIALIZE,
const bool has_temperature SPECIALIZE,
- const bool temperature_after_filters SPECIALIZE,
const bool has_top_k SPECIALIZE,
const bool has_top_p SPECIALIZE,
const bool has_min_p SPECIALIZE,
@@ -109,7 +108,7 @@ PUBLIC KERNEL(UnifiedSampling) (
logit.value = mask ? logit.value : -INFINITY;
}
- if (has_temperature && !temperature_after_filters) {
+ if (has_temperature) {
logit.value *= recip_temperature;
}
@@ -125,10 +124,6 @@ PUBLIC KERNEL(UnifiedSampling) (
thread_pre_filter_logit_max = max(thread_pre_filter_logit_max, logit.value);
}
- if (has_temperature && temperature_after_filters) {
- logit.value *= recip_temperature;
- }
-
if (is_stochastic) {
logit.value += -log(-log(uniform_float(&rng)));
}
@@ -162,7 +157,7 @@ PUBLIC KERNEL(UnifiedSampling) (
for (uint32_t iteration = 0; iteration < MAX_ITERS; iteration++) {
Logit candidate_logit_pre_filter = Logit::load(logits, candidate_logit_post_gumbel.index);
- if (has_temperature && !temperature_after_filters) {
+ if (has_temperature) {
candidate_logit_pre_filter.value *= recip_temperature;
}
if (is_stochastic) {
@@ -180,7 +175,7 @@ PUBLIC KERNEL(UnifiedSampling) (
logit.value = mask ? logit.value : -INFINITY;
}
- if (has_temperature && !temperature_after_filters) {
+ if (has_temperature) {
logit.value *= recip_temperature;
}
@@ -195,10 +190,6 @@ PUBLIC KERNEL(UnifiedSampling) (
}
}
- if (has_temperature && temperature_after_filters) {
- logit.value *= recip_temperature;
- }
-
if (is_stochastic) {
logit.value += -log(-log(uniform_float(&rng)));
}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/ssm/ssd_prefill.metal b/crates/backend-uzu/src/backends/metal/kernel/ssm/ssd_prefill.metal
index d351752fd..35c065f3f 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/ssm/ssd_prefill.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/ssm/ssd_prefill.metal
@@ -201,72 +201,3 @@ PUBLIC KERNEL(SSDPrefill)(
}
}
}
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(SSDPrefillSequential)(
- device const T* x, // (suffix, h, dh)
- device const T* dt_raw, // (suffix, h) - raw dt values
- device const T* b, // (suffix, g, n)
- device const T* c, // (suffix, g, n)
- device const T* d, // (h)
- device const T* z, // (suffix, h, dh)
- device T* state, // (h, dh, n)
- device T* y, // (suffix, h, dh)
- constant const uint& suffix_len,
- constant const uint& group_size,
- constant const uint& state_size,
- constant const uint x_strides[3],
- constant const uint dt_strides[2],
- constant const uint cb_strides[3],
- constant const uint state_strides[3],
- constant const uint& channels,
- constant const uint& head_dim,
- const uint h_idx AXIS(channels, 32),
- const uint dh_idx AXIS(head_dim, 32)
-) {
- const uint safe_group = max(group_size, 1u);
- const uint group_idx = h_idx / safe_group;
- device T* state_row = state + size_t(h_idx) * state_strides[0] + size_t(dh_idx) * state_strides[1];
-
- for (uint token = 0; token < suffix_len; ++token) {
- const uint x_idx = token * x_strides[0] + h_idx * x_strides[1] + dh_idx * x_strides[2];
- const uint dt_idx = token * dt_strides[0] + h_idx * dt_strides[1];
- const uint cb_base = token * cb_strides[0] + group_idx * cb_strides[1];
-
- const T this_x = x[x_idx];
- const T dt_raw_val = dt_raw[dt_idx];
- const T this_dt = activate_softplus(dt_raw_val);
- const T this_decay = static_cast<T>(fast::exp(-float(this_dt)));
- const T this_D = d[h_idx];
- const T this_z = activate_silu(z[x_idx]);
- const T dt_scaled_input = this_x;
-
- T acc = T(0);
- int s = 0;
- const int vec_bound = (state_size / 4) * 4;
- for (; s < vec_bound; s += 4) {
- const uint state_idx = s * state_strides[2];
- const uint cb_idx = cb_base + s * cb_strides[2];
- auto prev_state = *reinterpret_cast<device vec<T, 4>*>(state_row + state_idx);
- auto b_vec = *reinterpret_cast<device const vec<T, 4>*>(b + cb_idx);
- auto c_vec = *reinterpret_cast<device const vec<T, 4>*>(c + cb_idx);
- vec<T, 4> new_state = prev_state * this_decay + b_vec * dt_scaled_input;
- *reinterpret_cast<device vec<T, 4>*>(state_row + state_idx) = new_state;
- vec<T, 4> prod = new_state * c_vec;
- acc += prod.x + prod.y + prod.z + prod.w;
- }
- for (; uint(s) < state_size; ++s) {
- const uint state_idx = s * state_strides[2];
- const T prev_state = state_row[state_idx];
- const uint cb_idx = cb_base + s * cb_strides[2];
- const T new_state = prev_state * this_decay + b[cb_idx] * dt_scaled_input;
- state_row[state_idx] = new_state;
- acc += new_state * c[cb_idx];
- }
-
- acc += this_D * this_x;
- acc *= this_z;
- y[x_idx] = acc;
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/token_copy/token_copy.metal b/crates/backend-uzu/src/backends/metal/kernel/token_copy/token_copy.metal
index eeb4ed2d9..61db88105 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/token_copy/token_copy.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/token_copy/token_copy.metal
@@ -1,37 +1,8 @@
#include <metal_stdlib>
#include "../common/dsl.h"
-#include "../generated/ring.h"
-
-using namespace uzu::ring;
/// Copies a single sampled token (u32) to the token_ids buffer (u64).
-/// Used in async pipeline to pass sampled token to next forward pass.
-PUBLIC KERNEL(TokenCopySampled)(
- device const uint32_t* src,
- device uint64_t* dst,
- device uint32_t* context_ring OPTIONAL(has_context_ring),
- const constant uint32_t& suffix_repetition_length OPTIONAL(has_context_ring),
- const bool has_context_ring SPECIALIZE
-) {
- const uint32_t token = src[0];
- dst[0] = static_cast<uint64_t>(token);
-
- if (has_context_ring) {
- RingParams ring = *reinterpret_cast<device RingParams*>(context_ring);
- device uint32_t* ring_tokens = context_ring + 2;
- uint32_t slot;
- if (ring.ring_length < suffix_repetition_length) {
- slot = (ring.ring_offset + ring.ring_length) % suffix_repetition_length;
- ring.ring_length += 1;
- } else {
- slot = ring.ring_offset;
- ring.ring_offset = (ring.ring_offset + 1) % suffix_repetition_length;
- }
- ring_tokens[slot] = token;
- *reinterpret_cast<device RingParams*>(context_ring) = ring;
- }
+/// Used in decoding loop to pass sampled token to next forward pass.
+PUBLIC KERNEL(TokenCopySampled)(device const uint32_t* src, device uint64_t* dst) {
+ dst[0] = static_cast<uint64_t>(src[0]);
}
-
-/// Copies a single sampled token (u32) to an indexed results buffer (u32).
-/// Used in async pipeline to store result for callback access.
-PUBLIC KERNEL(TokenCopyToResults)(device const uint32_t* src, device uint32_t* dst) { dst[0] = src[0]; }
diff --git a/crates/backend-uzu/src/bridge/backend.rs b/crates/backend-uzu/src/bridge/backend.rs
new file mode 100644
index 000000000..67b8c2e94
--- /dev/null
+++ b/crates/backend-uzu/src/bridge/backend.rs
@@ -0,0 +1,83 @@
+use std::pin::Pin;
+
+use shoji::{
+ traits::{
+ Backend as LlmBackend,
+ backend::{
+ Error as BackendError,
+ chat_token::{Backend as ChatTokenBackend, Instance as ChatTokenInstance},
+ classification::{Backend as ClassificationBackend, Config, Instance as ClassificationInstance},
+ },
+ },
+ types::session::chat::ChatConfig,
+};
+use tokenizers::Tokenizer;
+
+use crate::{
+ TOOLCHAIN_VERSION,
+ backends::select_backend,
+ bridge::{
+ chat_token_backend::UzuChatTokenBackendInstance, classification_backend::UzuClassificationBackendInstance,
+ },
+};
+
+pub struct UzuLlmBackend;
+
+impl UzuLlmBackend {
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl LlmBackend for UzuLlmBackend {
+ fn identifier(&self) -> String {
+ "uzu".to_string()
+ }
+
+ fn version(&self) -> String {
+ TOOLCHAIN_VERSION.to_string()
+ }
+
+ fn as_chat_via_token_capable(&self) -> Option<&dyn ChatTokenBackend> {
+ Some(self)
+ }
+
+ fn as_classification_capable(&self) -> Option<&dyn ClassificationBackend> {
+ Some(self)
+ }
+}
+
+impl ChatTokenBackend for UzuLlmBackend {
+ fn instance<'a>(
+ &'a self,
+ reference: String,
+ config: ChatConfig,
+ tokenizer: &'a Tokenizer,
+ ) -> Pin<Box<dyn Future<Output = Result<Box<dyn ChatTokenInstance>, BackendError>> + Send + 'a>> {
+ Box::pin(async move {
+ let instance = select_backend!(
+ UzuChatTokenBackendInstance::<B>::new(reference, config, tokenizer)
+ .map(|i| Box::new(i) as Box<dyn ChatTokenInstance>),
+ BackendError::from("Unable to open any backend")
+ )?;
+ Ok(instance)
+ })
+ }
+}
+
+impl ClassificationBackend for UzuLlmBackend {
+ fn instance(
+ &self,
+ reference: String,
+ _config: Config,
+ ) -> Pin<Box<dyn Future<Output = Result<Box<dyn ClassificationInstance>, BackendError>> + Send + '_>> {
+ Box::pin(async move {
+ let instance = select_backend!(
+ UzuClassificationBackendInstance::<B>::new(reference)
+ .map(|i| Box::new(i) as Box<dyn ClassificationInstance>),
+ BackendError::from("Unable to open any backend")
+ )?;
+ Ok(instance)
+ })
+ }
+}
diff --git a/crates/backend-uzu/src/bridge/chat_token_backend.rs b/crates/backend-uzu/src/bridge/chat_token_backend.rs
new file mode 100644
index 000000000..87ea1ab08
--- /dev/null
+++ b/crates/backend-uzu/src/bridge/chat_token_backend.rs
@@ -0,0 +1,219 @@
+use std::{
+ any::Any,
+ path::PathBuf,
+ pin::Pin,
+ task::{Context, Poll},
+};
+
+use futures::{Stream, StreamExt};
+use shoji::{
+ traits::{
+ State,
+ backend::{
+ Error as BackendError, Instance as BackendInstance,
+ chat_token::{
+ Instance as ChatTokenBackendInstance, StreamInput as ChatTokenStreamInput,
+ StreamOutput as ChatTokenStreamOutput, TokenStreamOutput,
+ },
+ },
+ },
+ types::session::chat::{ChatConfig, ChatReplyConfig},
+};
+use tokenizers::Tokenizer;
+use tokio_util::sync::CancellationToken;
+
+use crate::{
+ backends::common::Backend,
+ bridge::{
+ chat_token_state::UzuChatTokenBackendInstanceState,
+ helpers::{error_stream, get_grammar, get_max_context_length, get_sampling_method, get_speculator},
+ sync_shared::SyncShared,
+ },
+ engine::{
+ Engine,
+ language_model::{
+ LanguageModel,
+ stream::{LanguageModelStreamOptions, LanguageModelStreamSpeculatorOptions},
+ },
+ },
+ speculators::speculator::Speculator,
+};
+
+pub struct UzuChatTokenBackendInstance<B: Backend> {
+ engine: SyncShared<Engine<B>>,
+ model: SyncShared<LanguageModel<B>>,
+ config: ChatConfig,
+ tokenizer: Tokenizer,
+ stop_token_ids: Vec<i32>,
+ speculator: Option<(Box<dyn Speculator>, usize)>,
+ max_context_length: Option<usize>,
+}
+
+impl<B: Backend> UzuChatTokenBackendInstance<B> {
+ pub fn new(
+ model_path: String,
+ config: ChatConfig,
+ tokenizer: &Tokenizer,
+ ) -> Result<Self, BackendError> {
+ let engine = Engine::<B>::new().map_err(|err| err.to_string())?;
+ let model_path = PathBuf::from(model_path);
+ let model = engine.load_language_model(&model_path).map_err(|err| err.to_string())?;
+
+ let stop_token_ids = model.generation_config().stop_token_ids.iter().map(|id| *id as i32).collect();
+
+ let speculator = if let Some(preset) = config.speculation_preset.as_ref() {
+ get_speculator(preset, tokenizer)?
+ } else {
+ None
+ };
+
+ let max_context_length = get_max_context_length(&model, config.context_length.clone());
+
+ Ok(Self {
+ engine: SyncShared::new(engine),
+ model: SyncShared::new(model),
+ config,
+ tokenizer: tokenizer.clone(),
+ stop_token_ids,
+ speculator,
+ max_context_length,
+ })
+ }
+}
+
+impl<B: Backend> BackendInstance for UzuChatTokenBackendInstance<B> {
+ type StreamConfig = ChatReplyConfig;
+ type StreamInput = ChatTokenStreamInput;
+ type StreamOutput = ChatTokenStreamOutput;
+
+ fn state(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn State>, BackendError>> + Send + '_>> {
+ Box::pin(async move {
+ let model = self.model.lock().map_err(|err| BackendError::from(err.to_string()))?;
+ let max_context_length = get_max_context_length(&model, self.config.context_length.clone());
+ model
+ .create_empty_state(max_context_length)
+ .map_err(|err| BackendError::from(err.to_string()))
+ .map(|state| Box::new(UzuChatTokenBackendInstanceState::new(state)) as Box<dyn State>)
+ })
+ }
+
+ fn stream<'a>(
+ &'a self,
+ input: &'a Self::StreamInput,
+ state: &'a mut dyn State,
+ config: Self::StreamConfig,
+ cancel_token: CancellationToken,
+ ) -> Pin<Box<dyn Stream<Item = Result<Self::StreamOutput, BackendError>> + Send + 'a>> {
+ let model = self.model.clone();
+ let state = match (state as &mut dyn Any).downcast_mut::<UzuChatTokenBackendInstanceState<B>>() {
+ Some(state) => state.value.clone(),
+ None => return error_stream("unexpected state type for uzu chat token instance".to_string()),
+ };
+ let token_limit = config.token_limit.map(|count| count as usize).unwrap_or(usize::MAX);
+
+ #[allow(clippy::await_holding_lock)]
+ let stream = async_stream::stream! {
+ let model_guard = match model.lock() {
+ Ok(model) => model,
+ Err(err) => {
+ yield Err(BackendError::from(err.to_string()));
+ return;
+ },
+ };
+ let mut state_guard = match state.lock() {
+ Ok(state) => state,
+ Err(err) => {
+ yield Err(BackendError::from(err.to_string()));
+ return;
+ },
+ };
+
+ let grammar = if let Some(grammar_config) = config.grammar {
+ match get_grammar(grammar_config, &self.tokenizer, &self.stop_token_ids) {
+ Ok(grammar) => Some(grammar),
+ Err(err) => {
+ yield Err(BackendError::from(err.to_string()));
+ return
+ }
+ }
+ } else {
+ None
+ };
+
+ let options = LanguageModelStreamOptions {
+ sampling_method: get_sampling_method::<B>(&model_guard, &config.sampling_policy),
+ grammar,
+ speculator: self.speculator.as_ref().map(|(speculator, budget)| LanguageModelStreamSpeculatorOptions {
+ speculator: speculator.as_ref(),
+ speculation_budget: *budget,
+ trie_creation_config: Default::default(),
+ }),
+ };
+
+ yield Ok(TokenStreamOutput::PrefillStarted);
+ let iterator = match model_guard.stream(input, &mut state_guard, options) {
+ Ok(iter) => iter,
+ Err(err) => {
+ yield Err(BackendError::from(err.to_string()));
+ return;
+ },
+ };
+
+ // here additional condition to prevent iterator start
+ if token_limit == 0 {
+ yield Ok(TokenStreamOutput::LimitReached);
+ return;
+ }
+
+ let mut token_count = 0usize;
+ for result in iterator.take(token_limit) {
+ match result {
+ Ok(token) => {
+ yield Ok(TokenStreamOutput::Token(token));
+ token_count += 1;
+ },
+ Err(err) => {
+ yield Err(BackendError::from(err.to_string()));
+ return;
+ },
+ }
+ }
+ if token_count >= token_limit {
+ yield Ok(TokenStreamOutput::LimitReached);
+ }
+ };
+
+ Box::pin(AssertSend(stream).take_until(cancel_token.cancelled_owned()))
+ }
+
+ fn peak_memory_usage(&self) -> Option<usize> {
+ self.engine.lock().ok().and_then(|engine| engine.peak_memory_usage())
+ }
+}
+
+impl<B: Backend> ChatTokenBackendInstance for UzuChatTokenBackendInstance<B> {
+ fn max_context_length(&self) -> Option<usize> {
+ self.max_context_length
+ }
+
+ fn stop_token_ids(&self) -> Option<Box<[u64]>> {
+ Some(self.stop_token_ids.iter().map(|id| *id as u64).collect())
+ }
+}
+
+struct AssertSend<S>(S);
+
+unsafe impl<S> Send for AssertSend<S> {}
+
+impl<S: Stream> Stream for AssertSend<S> {
+ type Item = S::Item;
+
+ fn poll_next(
+ self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ ) -> Poll<Option<Self::Item>> {
+ // SAFETY: we never move `self.0` out of the pinned reference.
+ let inner = unsafe { self.map_unchecked_mut(|s| &mut s.0) };
+ inner.poll_next(cx)
+ }
+}
diff --git a/crates/backend-uzu/src/bridge/chat_token_state.rs b/crates/backend-uzu/src/bridge/chat_token_state.rs
new file mode 100644
index 000000000..0b5caa52f
--- /dev/null
+++ b/crates/backend-uzu/src/bridge/chat_token_state.rs
@@ -0,0 +1,19 @@
+use shoji::traits::State as LlmInstanceState;
+
+use crate::{
+ backends::common::Backend, bridge::sync_shared::SyncShared, engine::language_model::state::LanguageModelState,
+};
+
+pub struct UzuChatTokenBackendInstanceState<B: Backend> {
+ pub value: SyncShared<LanguageModelState<B>>,
+}
+
+impl<B: Backend> UzuChatTokenBackendInstanceState<B> {
+ pub fn new(value: LanguageModelState<B>) -> Self {
+ Self {
+ value: SyncShared::new(value),
+ }
+ }
+}
+
+impl<B: Backend> LlmInstanceState for UzuChatTokenBackendInstanceState<B> {}
diff --git a/crates/backend-uzu/src/bridge/classification_backend.rs b/crates/backend-uzu/src/bridge/classification_backend.rs
new file mode 100644
index 000000000..b1d75c64c
--- /dev/null
+++ b/crates/backend-uzu/src/bridge/classification_backend.rs
@@ -0,0 +1,70 @@
+use std::{path::PathBuf, pin::Pin};
+
+use futures::{Stream, StreamExt, stream};
+use shoji::traits::{
+ State as ShojiState,
+ backend::{
+ Error as BackendError, Instance as BackendInstance,
+ classification::{
+ StreamConfig as ClassificationStreamConfig, StreamInput as ClassificationStreamInput,
+ StreamOutput as ClassificationStreamOutput,
+ },
+ },
+};
+use tokio_util::sync::CancellationToken;
+
+use crate::{
+ backends::common::Backend,
+ bridge::sync_shared::SyncShared,
+ engine::{Engine, classifier_model::ClassifierModel},
+};
+
+pub struct UzuClassificationBackendInstance<B: Backend> {
+ model: SyncShared<ClassifierModel<B>>,
+}
+
+impl<B: Backend> UzuClassificationBackendInstance<B> {
+ pub fn new(model_path: String) -> Result<Self, BackendError> {
+ let engine = Engine::<B>::new().map_err(|err| err.to_string())?;
+ let model_path = PathBuf::from(model_path);
+ let model = engine.load_classifier_model(&model_path).map_err(|err| err.to_string())?;
+ Ok(Self {
+ model: SyncShared::new(model),
+ })
+ }
+}
+
+impl<B: Backend> BackendInstance for UzuClassificationBackendInstance<B> {
+ type StreamConfig = ClassificationStreamConfig;
+ type StreamInput = ClassificationStreamInput;
+ type StreamOutput = ClassificationStreamOutput;
+
+ fn state(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn ShojiState>, BackendError>> + Send + '_>> {
+ Box::pin(async move { Ok(Box::new(State) as Box<dyn ShojiState>) })
+ }
+
+ fn stream<'a>(
+ &'a self,
+ input: &'a Self::StreamInput,
+ _state: &'a mut dyn ShojiState,
+ _config: Self::StreamConfig,
+ cancel_token: CancellationToken,
+ ) -> Pin<Box<dyn Stream<Item = Result<Self::StreamOutput, BackendError>> + Send + 'a>> {
+ Box::pin(
+ stream::once(async move {
+ let model_guard = self.model.lock().map_err(|err| err.to_string())?;
+ model_guard.classify(input).map_err(|err| BackendError::from(err.to_string()))
+ })
+ .take_until(cancel_token.cancelled_owned()),
+ )
+ }
+
+ fn peak_memory_usage(&self) -> Option<usize> {
+ None
+ }
+}
+
+#[derive(Debug, Clone)]
+struct State;
+
+impl ShojiState for State {}
diff --git a/crates/backend-uzu/src/bridge/helpers.rs b/crates/backend-uzu/src/bridge/helpers.rs
new file mode 100644
index 000000000..9d3e4b63d
--- /dev/null
+++ b/crates/backend-uzu/src/bridge/helpers.rs
@@ -0,0 +1,137 @@
+use std::pin::Pin;
+
+use futures::{Stream, stream};
+use shoji::{
+ traits::backend::{Error as BackendError, chat_token::StreamOutput as ChatTokenStreamOutput},
+ types::{
+ basic::{
+ ContextLength, Grammar as ShojiGrammar, SamplingMethod as ShojiSamplingMethod,
+ SamplingPolicy as ShojiSamplingPolicy,
+ },
+ session::chat::ChatSpeculationPreset,
+ },
+};
+use tokenizers::Tokenizer;
+
+use crate::{
+ backends::common::Backend,
+ encodable_block::sampling::SamplingMethod as UzuSamplingMethod,
+ engine::language_model::{
+ LanguageModel,
+ grammar::{Grammar as UzuGrammar, GrammarConfig, GrammarError},
+ },
+ speculators::{
+ fixed_token_speculator::FixedTokensSpeculator, prompt_lookup_speculator::PromptLookupSpeculator,
+ speculator::Speculator,
+ },
+};
+
+pub fn error_stream<'a>(
+ message: String
+) -> Pin<Box<dyn Stream<Item = Result<ChatTokenStreamOutput, BackendError>> + Send + 'a>> {
+ Box::pin(stream::once(async move {
+ Err::<ChatTokenStreamOutput, BackendError>(Box::<dyn std::error::Error + Send + Sync>::from(message))
+ }))
+}
+
+pub fn get_grammar(
+ grammar: ShojiGrammar,
+ tokenizer: &Tokenizer,
+ stop_token_ids: &[i32],
+) -> Result<Box<dyn UzuGrammar>, GrammarError> {
+ let config = match grammar {
+ ShojiGrammar::JsonAny {
+ ..
+ } => GrammarConfig::builtin_json(),
+ ShojiGrammar::JsonSchema {
+ schema,
+ } => GrammarConfig::json_schema_simple(schema),
+ ShojiGrammar::Regex {
+ pattern,
+ } => GrammarConfig::regex(pattern, false),
+ };
+ <dyn UzuGrammar>::new(&config, tokenizer, None, Some(stop_token_ids))
+}
+
+pub fn get_max_context_length<B: Backend>(
+ model: &LanguageModel<B>,
+ context_length: ContextLength,
+) -> Option<usize> {
+ match context_length {
+ ContextLength::Default {
+ ..
+ } => model.recommended_context_length(),
+ ContextLength::Maximal {
+ ..
+ } => model.max_context_length(),
+ ContextLength::Custom {
+ length,
+ } => Some(length.max(0) as usize),
+ }
+}
+
+pub fn get_sampling_method<B: Backend>(
+ model: &LanguageModel<B>,
+ sampling_method: &ShojiSamplingPolicy,
+) -> UzuSamplingMethod {
+ match sampling_method {
+ ShojiSamplingPolicy::Default {
+ ..
+ } => model.default_sampling_method(),
+ ShojiSamplingPolicy::Custom {
+ method,
+ } => match method {
+ ShojiSamplingMethod::Greedy {
+ ..
+ } => UzuSamplingMethod::Greedy,
+ ShojiSamplingMethod::Stochastic {
+ temperature,
+ top_k,
+ top_p,
+ min_p,
+ repetition_penalty,
+ suffix_repetition_length,
+ } => UzuSamplingMethod::Stochastic {
+ temperature: temperature.map(|value| value as f32),
+ top_k: top_k.map(|value| value as u32),
+ top_p: top_p.map(|value| value as f32),
+ min_p: min_p.map(|value| value as f32),
+ repetition_penalty: repetition_penalty.map(|value| value as f32),
+ suffix_repetition_length: suffix_repetition_length.map(|value| value as usize),
+ },
+ },
+ }
+}
+
+pub fn get_speculator(
+ preset: &ChatSpeculationPreset,
+ tokenizer: &Tokenizer,
+) -> Result<Option<(Box<dyn Speculator>, usize)>, BackendError> {
+ match preset {
+ ChatSpeculationPreset::GeneralChat {
+ ..
+ } => Ok(None),
+ ChatSpeculationPreset::Summarization {
+ ..
+ } => {
+ let speculator = Box::new(PromptLookupSpeculator::new_with_params(3));
+ Ok(Some((speculator, 16)))
+ },
+ ChatSpeculationPreset::Classification {
+ feature,
+ } => {
+ let proposals = feature
+ .values
+ .iter()
+ .map(|value| {
+ let encoding = tokenizer.encode(value.as_str(), false)?;
+ let ids = encoding.get_ids().iter().map(|&id| id as u64).collect::<Vec<_>>();
+ Ok(ids)
+ })
+ .collect::<Result<Vec<Vec<u64>>, BackendError>>()?;
+ let speculator = Box::new(FixedTokensSpeculator::new(proposals));
+ let budget = speculator.max_trie_nodes() + 1;
+ Ok(Some((speculator, budget)))
+ },
+ }
+}
diff --git a/crates/backend-uzu/src/bridge/mod.rs b/crates/backend-uzu/src/bridge/mod.rs
new file mode 100644
index 000000000..78539ab9b
--- /dev/null
+++ b/crates/backend-uzu/src/bridge/mod.rs
@@ -0,0 +1,10 @@
+mod backend;
+mod chat_token_backend;
+mod chat_token_state;
+mod classification_backend;
+mod helpers;
+mod model_metadata;
+mod sync_shared;
+
+pub use backend::UzuLlmBackend;
+pub use model_metadata::resolve_model_specialization;
diff --git a/crates/backend-uzu/src/inference/model_metadata.rs b/crates/backend-uzu/src/bridge/model_metadata.rs
similarity index 92%
rename from crates/backend-uzu/src/inference/model_metadata.rs
rename to crates/backend-uzu/src/bridge/model_metadata.rs
index 2dda242cd..214e733bc 100644
--- a/crates/backend-uzu/src/inference/model_metadata.rs
+++ b/crates/backend-uzu/src/bridge/model_metadata.rs
@@ -19,7 +19,6 @@ pub fn resolve_model_specialization(model_path: &Path) -> Result<ModelSpecializa
Ok(match config {
AnyModelConfig::LanguageModelConfig(_) => ModelSpecialization::Chat {},
AnyModelConfig::ClassifierModelConfig(_) => ModelSpecialization::Classification {},
- AnyModelConfig::TTSModelConfig(_) => ModelSpecialization::TextToSpeech {},
AnyModelConfig::DFlashSpeculatorConfig(_) => ModelSpecialization::Speculation {},
})
}
diff --git a/crates/backend-uzu/src/bridge/sync_shared.rs b/crates/backend-uzu/src/bridge/sync_shared.rs
new file mode 100644
index 000000000..6227cb241
--- /dev/null
+++ b/crates/backend-uzu/src/bridge/sync_shared.rs
@@ -0,0 +1,29 @@
+use std::sync::{Arc, LockResult, Mutex, MutexGuard};
+
+pub struct SyncShared<T> {
+ value: Arc<Mutex<T>>,
+}
+
+impl<T> SyncShared<T> {
+ pub fn new(value: T) -> Self {
+ Self {
+ value: Arc::new(Mutex::new(value)),
+ }
+ }
+
+ pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
+ self.value.lock()
+ }
+}
+
+impl<T> Clone for SyncShared<T> {
+ fn clone(&self) -> Self {
+ Self {
+ value: self.value.clone(),
+ }
+ }
+}
+
+unsafe impl<T> Send for SyncShared<T> {}
+
+unsafe impl<T> Sync for SyncShared<T> {}
diff --git a/crates/backend-uzu/src/classifier/classifier.rs b/crates/backend-uzu/src/classifier/classifier.rs
deleted file mode 100644
index c4dba7b6b..000000000
--- a/crates/backend-uzu/src/classifier/classifier.rs
+++ /dev/null
@@ -1,268 +0,0 @@
-use std::{collections::HashMap, path::Path, time::Instant};
-
-#[cfg(feature = "tracing")]
-use super::ActivationTrace;
-use super::{ClassificationOutput, ClassificationStats, ClassifierContext};
-use crate::{
- backends::common::{Allocation, AllocationType, AsBufferRangeRef, Backend, Context, Encoder},
- config::model::classifier_model::ClassifierModelConfig,
- data_type::DataType,
- encodable_block::{LayerArguments, PrecalculatedRope},
- forward_pass::{rope::precalculate_rope, token_inputs::TokenInputs},
- session::types::Error,
-};
-
-pub struct Classifier<B: Backend> {
- pub context: ClassifierContext<B>,
-}
-
-pub trait ClassifierTrait {
- fn classify_tokens(
- &mut self,
- token_ids: Vec<u64>,
- token_positions: Vec<usize>,
- ) -> Result<ClassificationOutput, Error>;
-}
-
-impl<B: Backend> ClassifierTrait for Classifier<B> {
- fn classify_tokens(
- &mut self,
- token_ids: Vec<u64>,
- token_positions: Vec<usize>,
- ) -> Result<ClassificationOutput, Error> {
- let run_start = Instant::now();
-
- let logits = self.forward_pass(&token_ids, &token_positions)?;
-
- let forward_duration = run_start.elapsed().as_secs_f64();
-
- let postprocessing_start = Instant::now();
- let probabilities = self.logits_to_probabilities(&logits)?;
- let postprocessing_duration = postprocessing_start.elapsed().as_secs_f64();
-
- let (predicted_label, confidence) = probabilities
- .iter()
- .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
- .map(|(label, prob)| (label.clone(), *prob))
- .unwrap_or((String::from("unknown"), 0.0));
-
- let stats = ClassificationStats::new(
- 0.0,
- forward_duration,
- postprocessing_duration,
- run_start.elapsed().as_secs_f64(),
- token_ids.len() as u64,
- predicted_label,
- confidence,
- );
-
- Ok(ClassificationOutput {
- logits,
- probabilities,
- stats,
- })
- }
-}
-
-impl<B: Backend> Classifier<B> {
- pub fn new(
- model_path: &Path,
- model_config: &ClassifierModelConfig,
- ) -> Result<Self, Error> {
- let context = ClassifierContext::new(model_path, model_config)?;
- Ok(Self {
- context,
- })
- }
-
- #[cfg(all(test, feature = "tracing"))]
- pub fn forward_pass_with_traces(
- &mut self,
- token_ids: &[u64],
- token_positions: &[usize],
- ) -> Result<(Box<[f32]>, ActivationTrace<B>), Error> {
- let num_labels = self.context.model_config.classifier_config.num_labels;
- let mut traces = ActivationTrace::new_classifier(
- self.context.context.as_ref(),
- &self.context.model_shape,
- token_ids.len(),
- num_labels,
- );
- let logits = self.forward_pass_impl(token_ids, token_positions, Some(&mut traces))?;
- Ok((logits, traces))
- }
-
- #[cfg(feature = "tracing")]
- fn forward_pass(
- &mut self,
- token_ids: &[u64],
- token_positions: &[usize],
- ) -> Result<Box<[f32]>, Error> {
- self.forward_pass_impl(token_ids, token_positions, None)
- }
-
- fn forward_pass_impl(
- &mut self,
- token_ids: &[u64],
- token_positions: &[usize],
- #[cfg(feature = "tracing")] trace: Option<&mut ActivationTrace<B>>,
- ) -> Result<Box<[f32]>, Error> {
- let batch_dim = token_ids.len();
- let token_inputs = TokenInputs::new_classifier(self.context.context.as_ref(), token_ids, token_positions);
-
- #[cfg(feature = "tracing")]
- let mut trace = trace;
- let mut encoder = Encoder::<B>::new(self.context.context.as_ref())
- .map_err(|e| Error::UnableToCreateCommandBuffer(e.into()))?;
-
- let mut main = self
- .context
- .embed
- .encode_lookup(token_inputs.token_ids(), batch_dim, &mut encoder)
- .map_err(|e| Error::EncodeFailed(Box::new(e)))?;
- main = self
- .context
- .embedding_norm
- .encode(&main, 0, batch_dim, &mut encoder)
- .map_err(|e| Error::EncodeFailed(Box::new(e)))?;
- #[cfg(feature = "tracing")]
- if let Some(trace) = trace.as_deref_mut() {
- let embedding_norm = trace.embedding_norm_mut().allocation_mut();
- encoder.encode_copy(&main, .., embedding_norm, ..);
- }
-
- let mut shortcut = encoder
- .allocate_scratch(main.as_buffer_range_ref().range().len())
- .map_err(|e| Error::EncodeFailed(Box::new(e)))?;
- let ropes = self
- .context
- .rope_configs
- .iter()
- .map(|rope_config| {
- let (sines, cosines) = precalculate_rope(rope_config, token_inputs.token_positions());
- let mut sines_allocation = encoder.allocate_constant(sines.len() * std::mem::size_of::<f32>())?;
- sines_allocation.copyin(sines.as_ref());
- let mut cosines_allocation = encoder.allocate_constant(cosines.len() * std::mem::size_of::<f32>())?;
- cosines_allocation.copyin(cosines.as_ref());
- Ok(PrecalculatedRope {
- cosines: cosines_allocation,
- sines: sines_allocation,
- dim: *rope_config.head_dim(),
- })
- })
- .collect::<Result<Box<[_]>, B::Error>>()
- .map_err(|e| Error::EncodeFailed(Box::new(e)))?;
- for layer in self.context.layers.iter() {
- main = layer
- .encode(
- LayerArguments {
- batch_dim,
- token_parents: token_inputs.token_parents(),
- token_subtrie_ranges: None,
- rope: layer.rope_kind.get(&ropes),
- per_layer_inputs: None,
- sampling_start: 0,
- sampling_length: batch_dim,
- cache_access: None,
- #[cfg(feature = "tracing")]
- trace: trace.as_deref_mut().map(|traces| &mut traces.layer_results[layer.layer_index]),
- },
- main,
- &mut shortcut,
- &mut encoder,
- )
- .map_err(|e| Error::EncodeFailed(Box::new(e)))?;
- }
- main = self
- .context
- .output_norm
- .encode(&main, 0, batch_dim, &mut encoder)
- .map_err(|e| Error::EncodeFailed(Box::new(e)))?;
- #[cfg(feature = "tracing")]
- if let Some(trace) = trace.as_deref_mut() {
- encoder.encode_copy(&main, .., trace.output_norm.allocation_mut(), ..);
- }
- let pooling = self
- .context
- .pooling
- .encode(batch_dim, &main, &mut encoder)
- .map_err(|e| Error::EncodeFailed(Box::new(e)))?;
- #[cfg(feature = "tracing")]
- if let Some(trace) = trace.as_deref_mut() {
- let output_pooling = trace.output_pooling_mut().allocation_mut();
- encoder.encode_copy(&pooling, .., output_pooling, ..);
- }
- let logits =
- self.context.prediction_head.encode(pooling, &mut encoder).map_err(|e| Error::EncodeFailed(Box::new(e)))?;
- #[cfg(feature = "tracing")]
- if let Some(trace) = trace {
- encoder.encode_copy(&logits, .., trace.logits.allocation_mut(), ..);
- }
-
- let mut logits_output = self
- .context
- .context
- .create_allocation(logits.as_buffer_range_ref().range().len(), AllocationType::Global)
- .map_err(|e| Error::EncodeFailed(Box::new(e)))?;
- encoder.encode_copy(&logits, .., &mut logits_output, ..);
-
- drop(logits);
- drop(main);
- drop(shortcut);
- drop(ropes);
-
- let completed = encoder
- .end_encoding()
- .submit()
- .wait_until_completed()
- .map_err(|e| Error::CommandBufferFailed(Box::new(e)))?;
- drop(completed);
-
- self.copy_logits_from_allocation(&logits_output)
- }
-
- #[cfg(not(feature = "tracing"))]
- fn forward_pass(
- &mut self,
- token_ids: &[u64],
- token_positions: &[usize],
- ) -> Result<Box<[f32]>, Error> {
- self.forward_pass_impl(token_ids, token_positions)
- }
-
- fn copy_logits_from_allocation(
- &self,
- logits: &Allocation<B>,
- ) -> Result<Box<[f32]>, Error> {
- match self.context.logits_data_type {
- DataType::F32 => Ok(logits.copyout::<f32>().into()),
- DataType::F16 => Ok(logits.copyout::<half::f16>().into_iter().map(|x| x.to_f32()).collect::<Box<[_]>>()),
- DataType::BF16 => Ok(logits.copyout::<half::bf16>().into_iter().map(|x| x.to_f32()).collect::<Box<[_]>>()),
- data_type => {
- Err(Error::InvalidModelConfig(format!("unsupported classifier logits data type {data_type:?}")))
- },
- }
- }
-
- fn logits_to_probabilities(
- &self,
- logits: &[f32],
- ) -> Result<HashMap<String, f32>, Error> {
- let output_labels = &self.context.model_config.classifier_config.output_labels;
- let mut probabilities = HashMap::new();
-
- for (idx, &logit) in logits.iter().enumerate() {
- let prob = 1.0 / (1.0 + (-logit).exp());
-
- let label = if let Some(labels) = output_labels {
- labels.get(idx).cloned().unwrap_or_else(|| format!("class_{}", idx))
- } else {
- format!("class_{}", idx)
- };
-
- probabilities.insert(label, prob);
- }
-
- Ok(probabilities)
- }
-}
diff --git a/crates/backend-uzu/src/classifier/classifier_context.rs b/crates/backend-uzu/src/classifier/classifier_context.rs
deleted file mode 100644
index 84a10072a..000000000
--- a/crates/backend-uzu/src/classifier/classifier_context.rs
+++ /dev/null
@@ -1,242 +0,0 @@
-use std::{fs::File, path::Path, rc::Rc};
-
-use crate::{
- backends::common::{Backend, Context},
- classifier::ClassifierError,
- config::{decoder::DecoderConfig, model::classifier_model::ClassifierModelConfig, rope::AnyRoPEConfig},
- data_type::DataType,
- encodable_block::{
- ClassifierLayer, ClassifierPredictionHead, Embedding, LayerRopeKind, Linear, Normalization, Pooling, QkUnpack,
- Rope,
- },
- forward_pass::model_shape::ModelShape,
- parameters::ParameterLoader,
- session::types::Error,
-};
-
-pub struct ClassifierContext<B: Backend> {
- pub context: Rc<B::Context>,
-
- pub model_config: ClassifierModelConfig,
- pub rope_configs: Box<[AnyRoPEConfig]>,
- #[cfg(all(test, feature = "tracing"))]
- pub model_shape: ModelShape,
-
- pub embed: Embedding<B>,
- pub embedding_norm: Normalization<B>,
- pub layers: Box<[ClassifierLayer<B>]>,
- pub output_norm: Normalization<B>,
-
- pub pooling: Pooling<B>,
- pub prediction_head: ClassifierPredictionHead<B>,
- pub logits_data_type: DataType,
-}
-
-impl<B: Backend> ClassifierContext<B> {
- pub fn new(
- model_path: &Path,
- model_config: &ClassifierModelConfig,
- ) -> Result<Self, Error> {
- let context = B::Context::new().map_err(|e| Error::UnableToCreateContext(e.into()))?;
- let classifier_config = &model_config.classifier_config;
-
- let decoder_config = Rc::new(DecoderConfig {
- embedding_config: classifier_config.embedding_config.clone(),
- transformer_config: classifier_config.transformer_config.clone(),
- vocab_size: classifier_config.vocab_size,
- ple_model_config: None,
- });
-
- let weights_path = model_path.join("model.safetensors");
- let weights_file = File::open(&weights_path).map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let loader = ParameterLoader::new(&weights_file, context.as_ref())
- .map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let root_loader_view =
- loader.tree().subtree("classifier").map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
-
- let model_shape = ModelShape::from_decoder_config(&decoder_config, DataType::BF16);
-
- let transformer_tree =
- root_loader_view.subtree("transformer").map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let mut rope_configs = Vec::<(AnyRoPEConfig, usize)>::new();
- let layer_rope_kinds: Box<[LayerRopeKind]> = classifier_config
- .transformer_config
- .layer_configs
- .iter()
- .map(|layer_config| {
- let Some(rope_config) = &layer_config.rope_config else {
- return LayerRopeKind::NoKernel;
- };
- let head_dim = *rope_config.head_dim();
- let index = rope_configs
- .iter()
- .position(|(existing_config, existing_head_dim)| {
- existing_config == rope_config && *existing_head_dim == head_dim
- })
- .unwrap_or_else(|| {
- rope_configs.push((rope_config.clone(), head_dim));
- rope_configs.len() - 1
- });
- LayerRopeKind::Indexed(index)
- })
- .collect();
-
- let output_norm_tree =
- transformer_tree.subtree("output_norm").map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
-
- let (embed, readout_input_hadamard_factors) = Embedding::new(
- context.as_ref(),
- decoder_config.vocab_size as u32,
- decoder_config.transformer_config.model_dim as u32,
- &decoder_config.embedding_config,
- &root_loader_view.subtree("embedding").map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?,
- &model_shape,
- )
- .map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- if readout_input_hadamard_factors.is_some() {
- return Err(Error::Classifier(ClassifierError::Custom(
- "classifier does not support embedding readout hadamard".to_string(),
- )));
- }
-
- let rope = Rc::new(
- Rope::<B>::new(context.as_ref(), &model_shape, false)
- .map_err(|e| Error::Classifier(ClassifierError::KernelCreationFailed(format!("RoPE: {:?}", e))))?,
- );
- let qk_unpack = Rc::new(
- QkUnpack::<B>::new(context.as_ref(), model_shape.data_type)
- .map_err(|e| Error::Classifier(ClassifierError::KernelCreationFailed(format!("QkUnpack: {:?}", e))))?,
- );
-
- let layers = classifier_config
- .transformer_config
- .layer_configs
- .iter()
- .enumerate()
- .map(|(layer_index, layer_config)| {
- let layer_tree = transformer_tree
- .subtree(&format!("layers.{}", layer_index))
- .map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
-
- ClassifierLayer::new(
- context.as_ref(),
- &classifier_config.transformer_config,
- layer_config,
- layer_index,
- layer_rope_kinds[layer_index],
- &layer_tree,
- rope.clone(),
- qk_unpack.clone(),
- model_shape.data_type,
- )
- .map_err(|error| Error::UnableToCreateClassifierLayer(Box::new(error)))
- })
- .collect::<Result<Vec<_>, Error>>()?
- .into_boxed_slice();
-
- let output_norm = Normalization::new(
- context.as_ref(),
- model_shape.data_type,
- classifier_config.transformer_config.model_dim,
- classifier_config.transformer_config.output_norm_config.clone(),
- &output_norm_tree,
- )
- .map_err(|e| Error::Classifier(ClassifierError::KernelCreationFailed(format!("output norm: {:?}", e))))?;
-
- let embedding_norm_tree =
- root_loader_view.subtree("embedding_norm").map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let embedding_norm = Normalization::new(
- context.as_ref(),
- model_shape.data_type,
- classifier_config.transformer_config.model_dim,
- classifier_config.embedding_norm_config.clone(),
- &embedding_norm_tree,
- )
- .map_err(|e| Error::Classifier(ClassifierError::KernelCreationFailed(format!("embedding norm: {:?}", e))))?;
-
- let model_dim = classifier_config.model_dim;
- let num_labels = classifier_config.num_labels;
- let prediction_head_config = &classifier_config.prediction_head_config;
- let prediction_head_tree =
- root_loader_view.subtree("prediction_head").map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
-
- let prediction_head_dense_tree =
- prediction_head_tree.subtree("dense").map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let prediction_head_dense = <dyn Linear<B>>::new::<1>(
- model_dim,
- [model_dim],
- prediction_head_config.use_dense_bias,
- context.as_ref(),
- model_shape.data_type,
- &prediction_head_dense_tree,
- )
- .map_err(|e| {
- Error::Classifier(ClassifierError::KernelCreationFailed(format!("prediction head dense: {:?}", e)))
- })?;
-
- let prediction_head_norm_tree =
- prediction_head_tree.subtree("norm").map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let prediction_head_norm = Normalization::new(
- context.as_ref(),
- model_shape.data_type,
- model_dim,
- prediction_head_config.normalization_config.clone(),
- &prediction_head_norm_tree,
- )
- .map_err(|e| {
- Error::Classifier(ClassifierError::KernelCreationFailed(format!("prediction head norm: {:?}", e)))
- })?;
-
- let prediction_head_readout_tree =
- prediction_head_tree.subtree("readout").map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let prediction_head_final_linear = <dyn Linear<B>>::new::<1>(
- model_dim,
- [num_labels],
- true,
- context.as_ref(),
- model_shape.data_type,
- &prediction_head_readout_tree,
- )
- .map_err(|e| {
- Error::Classifier(ClassifierError::KernelCreationFailed(format!("prediction head readout: {:?}", e)))
- })?;
-
- let pooling = Pooling::<B>::new(
- context.as_ref(),
- model_shape.data_type,
- classifier_config.classifier_pooling.clone(),
- model_dim,
- )
- .map_err(|e| Error::UnableToCreateContext(e.into()))?;
-
- let prediction_head = ClassifierPredictionHead::new(
- context.as_ref(),
- prediction_head_dense,
- prediction_head_config.activation.clone(),
- model_shape.data_type,
- prediction_head_norm,
- prediction_head_final_linear,
- model_dim,
- )
- .map_err(|e| {
- Error::Classifier(ClassifierError::KernelCreationFailed(format!("prediction head activation: {:?}", e)))
- })?;
-
- loader.tree().assert_all_tensors_validated().map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
-
- Ok(Self {
- context,
- model_config: model_config.clone(),
- rope_configs: rope_configs.into_iter().map(|(config, _)| config).collect(),
- logits_data_type: model_shape.data_type,
- #[cfg(all(test, feature = "tracing"))]
- model_shape,
- embed,
- embedding_norm,
- layers,
- output_norm,
- pooling,
- prediction_head,
- })
- }
-}
diff --git a/crates/backend-uzu/src/classifier/error.rs b/crates/backend-uzu/src/classifier/error.rs
deleted file mode 100644
index 1afd24f83..000000000
--- a/crates/backend-uzu/src/classifier/error.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-use thiserror::Error;
-
-// Classifier context errors
-#[derive(Debug, Error)]
-pub enum ClassifierError {
- #[error("Missing required config field: {0}")]
- MissingConfigField(String),
- #[error("Model requires attention layers but found non-attention mixer")]
- NonAttentionMixer,
- #[error("Kernel creation failed: {0}")]
- KernelCreationFailed(String),
- #[error("{0}")]
- Custom(String),
-}
diff --git a/crates/backend-uzu/src/classifier/mod.rs b/crates/backend-uzu/src/classifier/mod.rs
deleted file mode 100644
index 8b7ed08d3..000000000
--- a/crates/backend-uzu/src/classifier/mod.rs
+++ /dev/null
@@ -1,12 +0,0 @@
-mod classifier;
-mod classifier_context;
-mod error;
-mod result;
-
-pub use classifier::{Classifier, ClassifierTrait};
-pub use classifier_context::ClassifierContext;
-pub use error::ClassifierError;
-pub use result::{ClassificationOutput, ClassificationStats};
-
-#[cfg(feature = "tracing")]
-pub use crate::forward_pass::traces::ActivationTrace;
diff --git a/crates/backend-uzu/src/classifier/result.rs b/crates/backend-uzu/src/classifier/result.rs
deleted file mode 100644
index 651520b1e..000000000
--- a/crates/backend-uzu/src/classifier/result.rs
+++ /dev/null
@@ -1,53 +0,0 @@
-use std::collections::HashMap;
-
-#[derive(Debug, Clone)]
-pub struct ClassificationOutput {
- pub logits: Box<[f32]>,
- pub probabilities: HashMap<String, f32>,
- pub stats: ClassificationStats,
-}
-
-#[derive(Debug, Clone)]
-pub struct ClassificationStats {
- // Timing breakdown
- pub preprocessing_duration: f64,
- pub forward_pass_duration: f64,
- pub postprocessing_duration: f64,
- pub total_duration: f64,
-
- // Token metrics
- pub tokens_count: u64,
- pub tokens_per_second: f64,
-
- pub predicted_label: String,
- pub confidence: f32,
-}
-
-impl ClassificationStats {
- pub fn new(
- preprocessing_duration: f64,
- forward_pass_duration: f64,
- postprocessing_duration: f64,
- total_duration: f64,
- tokens_count: u64,
- predicted_label: String,
- confidence: f32,
- ) -> Self {
- let tokens_per_second = if forward_pass_duration > 0.0 {
- tokens_count as f64 / forward_pass_duration
- } else {
- 0.0
- };
-
- Self {
- preprocessing_duration,
- forward_pass_duration,
- postprocessing_duration,
- total_duration,
- tokens_count,
- tokens_per_second,
- predicted_label,
- confidence,
- }
- }
-}
diff --git a/crates/backend-uzu/src/config/decoder.rs b/crates/backend-uzu/src/config/decoder.rs
index 4096e7605..3c5831daf 100644
--- a/crates/backend-uzu/src/config/decoder.rs
+++ b/crates/backend-uzu/src/config/decoder.rs
@@ -1,8 +1,7 @@
use proc_macros::uzu_config;
use crate::config::{
- embedding::AnyEmbeddingConfig, per_layer_embedding::PLEModelConfig, token_mixer::attention::AttentionConfig,
- transformer::TransformerConfig,
+ embedding::AnyEmbeddingConfig, per_layer_embedding::PLEModelConfig, transformer::TransformerConfig,
};
#[uzu_config]
@@ -13,9 +12,3 @@ pub struct DecoderConfig {
pub vocab_size: usize,
pub ple_model_config: Option<PLEModelConfig>,
}
-
-impl DecoderConfig {
- pub fn first_attention(&self) -> Option<&AttentionConfig> {
- self.transformer_config.layer_configs.iter().find_map(|layer| layer.mixer_config.as_attention())
- }
-}
diff --git a/crates/backend-uzu/src/config/embedding/untied_embedding.rs b/crates/backend-uzu/src/config/embedding/untied_embedding.rs
index 0376e7cf2..2d7b6da7b 100644
--- a/crates/backend-uzu/src/config/embedding/untied_embedding.rs
+++ b/crates/backend-uzu/src/config/embedding/untied_embedding.rs
@@ -1,18 +1,4 @@
-use monostate::MustBe;
use proc_macros::uzu_config;
#[uzu_config(super::EmbeddingConfig)]
pub struct UntiedEmbeddingConfig;
-
-impl UntiedEmbeddingConfig {
- pub fn new(
- input_scale: Option<f32>,
- logit_soft_cap: Option<f32>,
- ) -> Self {
- Self {
- ty: MustBe!("UntiedEmbeddingConfig"),
- input_scale,
- logit_soft_cap,
- }
- }
-}
diff --git a/crates/backend-uzu/src/config/mod.rs b/crates/backend-uzu/src/config/mod.rs
index 585b0e8bd..eeb01ec99 100644
--- a/crates/backend-uzu/src/config/mod.rs
+++ b/crates/backend-uzu/src/config/mod.rs
@@ -13,5 +13,4 @@ pub mod token_codec;
pub mod token_mixer;
pub mod transformer;
pub mod transformer_layer;
-pub mod tts;
pub mod weight_matrix;
diff --git a/crates/backend-uzu/src/config/model/dflash_speculator.rs b/crates/backend-uzu/src/config/model/dflash_speculator.rs
index 9a59ac8d1..63d05aac4 100644
--- a/crates/backend-uzu/src/config/model/dflash_speculator.rs
+++ b/crates/backend-uzu/src/config/model/dflash_speculator.rs
@@ -2,6 +2,7 @@ use proc_macros::uzu_config;
use crate::config::dflash::DFlashDraftConfig;
+#[allow(unused)] // TODO
#[uzu_config(super::ModelConfig)]
pub struct DFlashSpeculatorConfig {
pub draft_config: DFlashDraftConfig,
diff --git a/crates/backend-uzu/src/config/model/language_model.rs b/crates/backend-uzu/src/config/model/language_model.rs
index 5562f2d39..23b607ac7 100644
--- a/crates/backend-uzu/src/config/model/language_model.rs
+++ b/crates/backend-uzu/src/config/model/language_model.rs
@@ -1,23 +1,9 @@
-use std::{fs::File, io::BufReader, path::Path};
-
use proc_macros::uzu_config;
-use crate::{
- config::{decoder::DecoderConfig, model::generation::GenerationConfig},
- session::types::Error,
-};
+use crate::config::{decoder::DecoderConfig, model::generation::GenerationConfig};
#[uzu_config(super::ModelConfig)]
pub struct LanguageModelConfig {
pub decoder_config: DecoderConfig,
pub generation_config: GenerationConfig,
}
-
-impl LanguageModelConfig {
- pub fn new(model_path: &Path) -> Result<LanguageModelConfig, Error> {
- let config_path = model_path.join("config.json");
- let config_file = File::open(&config_path)?;
- let model_config: LanguageModelConfig = serde_json::from_reader(BufReader::new(config_file))?;
- Ok(model_config)
- }
-}
diff --git a/crates/backend-uzu/src/config/model/mod.rs b/crates/backend-uzu/src/config/model/mod.rs
index 68c5201d7..8b066afd7 100644
--- a/crates/backend-uzu/src/config/model/mod.rs
+++ b/crates/backend-uzu/src/config/model/mod.rs
@@ -6,12 +6,10 @@ pub mod classifier_model;
pub mod dflash_speculator;
pub mod generation;
pub mod language_model;
-pub mod tts_model;
#[uzu_config_abstract(
language_model::LanguageModelConfig,
classifier_model::ClassifierModelConfig,
- tts_model::TTSModelConfig,
dflash_speculator::DFlashSpeculatorConfig
)]
pub struct ModelConfig {
diff --git a/crates/backend-uzu/src/config/model/tts_model.rs b/crates/backend-uzu/src/config/model/tts_model.rs
deleted file mode 100644
index 853ce9f22..000000000
--- a/crates/backend-uzu/src/config/model/tts_model.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-use proc_macros::uzu_config;
-
-use crate::config::tts::TTSConfig;
-
-#[uzu_config(super::ModelConfig)]
-pub struct TTSModelConfig {
- pub tts_config: TTSConfig,
-}
diff --git a/crates/backend-uzu/src/config/token_codec/mod.rs b/crates/backend-uzu/src/config/token_codec/mod.rs
index c65bca1ef..9f259022b 100644
--- a/crates/backend-uzu/src/config/token_codec/mod.rs
+++ b/crates/backend-uzu/src/config/token_codec/mod.rs
@@ -2,7 +2,6 @@ use proc_macros::uzu_config_abstract;
pub mod chat_codec;
pub mod raw_text_codec;
-pub mod tts_codec;
-#[uzu_config_abstract(chat_codec::ChatCodecConfig, tts_codec::TTSCodecConfig, raw_text_codec::RawTextCodecConfig)]
+#[uzu_config_abstract(chat_codec::ChatCodecConfig, raw_text_codec::RawTextCodecConfig)]
pub struct TokenCodecConfig;
diff --git a/crates/backend-uzu/src/config/token_codec/tts_codec.rs b/crates/backend-uzu/src/config/token_codec/tts_codec.rs
deleted file mode 100644
index 17a6555f5..000000000
--- a/crates/backend-uzu/src/config/token_codec/tts_codec.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-use proc_macros::uzu_config;
-
-#[uzu_config(super::TokenCodecConfig)]
-pub struct TTSCodecConfig {
- pub prompt_template: String,
- pub drop_initial_newline: bool,
-}
diff --git a/crates/backend-uzu/src/config/token_mixer/delta_net.rs b/crates/backend-uzu/src/config/token_mixer/delta_net.rs
index b46f9d63c..960559fc7 100644
--- a/crates/backend-uzu/src/config/token_mixer/delta_net.rs
+++ b/crates/backend-uzu/src/config/token_mixer/delta_net.rs
@@ -17,21 +17,3 @@ pub struct DeltaNetConfig {
pub value_head_dim: usize,
pub kernel_size: usize,
}
-
-impl DeltaNetConfig {
- pub fn key_dim(&self) -> usize {
- self.num_groups * self.head_dim
- }
-
- pub fn value_dim(&self) -> usize {
- self.num_heads * self.value_head_dim
- }
-
- pub fn conv_dim(&self) -> usize {
- self.key_dim() * 2 + self.value_dim()
- }
-
- pub fn total_proj_dim(&self) -> usize {
- self.conv_dim() + self.value_dim() + self.num_heads + self.num_heads
- }
-}
diff --git a/crates/backend-uzu/src/config/token_mixer/mamba2.rs b/crates/backend-uzu/src/config/token_mixer/mamba2.rs
index 3a3be17c0..d3139073a 100644
--- a/crates/backend-uzu/src/config/token_mixer/mamba2.rs
+++ b/crates/backend-uzu/src/config/token_mixer/mamba2.rs
@@ -20,13 +20,3 @@ pub struct Mamba2Config {
pub has_in_biases: bool,
pub has_out_biases: bool,
}
-
-impl Mamba2Config {
- pub fn inner_dim(&self) -> usize {
- self.num_heads * self.head_dim
- }
-
- pub fn conv_dim(&self) -> usize {
- self.inner_dim() + 2 * self.num_groups * self.state_dim
- }
-}
diff --git a/crates/backend-uzu/src/config/token_mixer/mod.rs b/crates/backend-uzu/src/config/token_mixer/mod.rs
index fdc0cce81..624c9d2fe 100644
--- a/crates/backend-uzu/src/config/token_mixer/mod.rs
+++ b/crates/backend-uzu/src/config/token_mixer/mod.rs
@@ -13,16 +13,3 @@ pub mod short_conv;
short_conv::ShortConvConfig
)]
pub struct TokenMixerConfig;
-
-impl AnyTokenMixerConfig {
- pub fn as_attention(&self) -> Option<&attention::AttentionConfig> {
- match self {
- AnyTokenMixerConfig::AttentionConfig(config) => Some(config),
- _ => None,
- }
- }
-
- pub fn sliding_window_size(&self) -> Option<usize> {
- self.as_attention().and_then(|config| config.sliding_window_size)
- }
-}
diff --git a/crates/backend-uzu/src/config/transformer.rs b/crates/backend-uzu/src/config/transformer.rs
index 8f3a794c1..9bf25d872 100644
--- a/crates/backend-uzu/src/config/transformer.rs
+++ b/crates/backend-uzu/src/config/transformer.rs
@@ -9,14 +9,3 @@ pub struct TransformerConfig {
pub model_dim: usize,
pub hidden_dim: usize,
}
-
-impl TransformerConfig {
- pub fn max_sequence_length(&self) -> Option<usize> {
- self.layer_configs
- .iter()
- .filter_map(|layer_config| {
- layer_config.rope_config.as_ref().map(|rope_config| *rope_config.max_sequence_length())
- })
- .max()
- }
-}
diff --git a/crates/backend-uzu/src/config/tts/audio_decoder/common.rs b/crates/backend-uzu/src/config/tts/audio_decoder/common.rs
deleted file mode 100644
index c9e3719fd..000000000
--- a/crates/backend-uzu/src/config/tts/audio_decoder/common.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-use monostate::MustBe;
-use proc_macros::uzu_config;
-
-#[uzu_config]
-pub struct CausalConv1dConfig {
- pub has_biases: MustBe!(true),
-}
-
-#[uzu_config]
-pub struct CausalTransposeConv1dConfig {
- pub has_biases: MustBe!(true),
-}
-
-#[uzu_config]
-pub struct Snake1dConfig {}
diff --git a/crates/backend-uzu/src/config/tts/audio_decoder/descript_audio_codec.rs b/crates/backend-uzu/src/config/tts/audio_decoder/descript_audio_codec.rs
deleted file mode 100644
index c1448ee49..000000000
--- a/crates/backend-uzu/src/config/tts/audio_decoder/descript_audio_codec.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use proc_macros::uzu_config;
-
-use crate::config::tts::audio_decoder::fish_audio_modules::{DACDecoderConfig, DownsampleResidualVectorQuantizeConfig};
-
-#[uzu_config(super::TTSAudioDecoderConfig)]
-pub struct DescriptAudioCodecConfig {
- pub quantizer_config: DownsampleResidualVectorQuantizeConfig,
- pub decoder_config: DACDecoderConfig,
- pub samplerate: u32,
-
- pub encoder_dim: usize,
- pub encoder_rates: Box<[usize]>,
- pub decoder_dim: usize,
- pub decoder_rates: Box<[usize]>,
- pub input_dim: usize,
- pub n_codebooks: usize,
- pub codebook_dim: usize,
- pub downsample_factor: Box<[usize]>,
- pub codebook_size: usize,
- pub semantic_codebook_size: usize,
-}
diff --git a/crates/backend-uzu/src/config/tts/audio_decoder/fish_audio_modules.rs b/crates/backend-uzu/src/config/tts/audio_decoder/fish_audio_modules.rs
deleted file mode 100644
index 2730adb3f..000000000
--- a/crates/backend-uzu/src/config/tts/audio_decoder/fish_audio_modules.rs
+++ /dev/null
@@ -1,72 +0,0 @@
-use monostate::MustBe;
-use proc_macros::uzu_config;
-
-use crate::config::{
- activation::AnyActivation,
- embedding::tied_embedding::TiedEmbeddingConfig,
- linear::LinearConfig,
- normalization::NormalizationConfig,
- transformer::TransformerConfig,
- tts::audio_decoder::common::{CausalConv1dConfig, CausalTransposeConv1dConfig, Snake1dConfig},
-};
-
-#[uzu_config]
-pub struct ConvNeXtBlockConfig {
- pub activation: AnyActivation,
- pub dwconv_config: CausalConv1dConfig,
- pub norm_config: NormalizationConfig,
- pub pwconv_config: LinearConfig,
-}
-
-#[uzu_config]
-pub struct UpsamplingBlockConfig {
- pub trans_conv_config: CausalTransposeConv1dConfig,
- pub convnext_config: ConvNeXtBlockConfig,
-}
-
-#[uzu_config]
-pub struct UpsamplerConfig {
- pub block_configs: Box<[UpsamplingBlockConfig]>,
-}
-
-#[uzu_config]
-pub struct VectorQuantizeConfig {
- pub codebook_config: TiedEmbeddingConfig,
- pub out_proj_config: LinearConfig,
-}
-
-#[uzu_config]
-pub struct ResidualVectorQuantizeConfig {
- pub vq_config: VectorQuantizeConfig,
-}
-
-#[uzu_config]
-pub struct DownsampleResidualVectorQuantizeConfig {
- pub semantic_quantizer_config: ResidualVectorQuantizeConfig,
- pub quantizer_config: ResidualVectorQuantizeConfig,
- pub post_module_config: TransformerConfig,
- pub upsampler_config: UpsamplerConfig,
-}
-
-#[uzu_config]
-pub struct ResidualUnitConfig {
- pub snake_config: Snake1dConfig,
- pub conv_config: CausalConv1dConfig,
- pub causal: MustBe!(true),
-}
-
-#[uzu_config]
-pub struct DACDecoderBlockConfig {
- pub snake_config: Snake1dConfig,
- pub trans_conv_config: CausalTransposeConv1dConfig,
- pub res_unit_config: ResidualUnitConfig,
- pub causal: MustBe!(true),
-}
-
-#[uzu_config]
-pub struct DACDecoderConfig {
- pub conv_config: CausalConv1dConfig,
- pub snake_config: Snake1dConfig,
- pub decoder_block_config: DACDecoderBlockConfig,
- pub causal: MustBe!(true),
-}
diff --git a/crates/backend-uzu/src/config/tts/audio_decoder/mod.rs b/crates/backend-uzu/src/config/tts/audio_decoder/mod.rs
deleted file mode 100644
index 20b2759ea..000000000
--- a/crates/backend-uzu/src/config/tts/audio_decoder/mod.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-use proc_macros::uzu_config_abstract;
-
-pub mod common;
-pub mod descript_audio_codec;
-pub mod fish_audio_modules;
-
-#[uzu_config_abstract(descript_audio_codec::DescriptAudioCodecConfig)]
-pub struct TTSAudioDecoderConfig;
diff --git a/crates/backend-uzu/src/config/tts/mod.rs b/crates/backend-uzu/src/config/tts/mod.rs
deleted file mode 100644
index a5dd1a3c9..000000000
--- a/crates/backend-uzu/src/config/tts/mod.rs
+++ /dev/null
@@ -1,16 +0,0 @@
-use proc_macros::uzu_config;
-
-use crate::config::tts::{
- audio_decoder::AnyTTSAudioDecoderConfig, text_decoder::AnyTTSTextDecoderConfig, vocoder::AnyVocoderConfig,
-};
-
-pub mod audio_decoder;
-pub mod text_decoder;
-pub mod vocoder;
-
-#[uzu_config]
-pub struct TTSConfig {
- pub text_decoder_config: AnyTTSTextDecoderConfig,
- pub audio_decoder_config: AnyTTSAudioDecoderConfig,
- pub vocoder_config: AnyVocoderConfig,
-}
diff --git a/crates/backend-uzu/src/config/tts/text_decoder/fish_audio_text_decoder.rs b/crates/backend-uzu/src/config/tts/text_decoder/fish_audio_text_decoder.rs
deleted file mode 100644
index c2de107ee..000000000
--- a/crates/backend-uzu/src/config/tts/text_decoder/fish_audio_text_decoder.rs
+++ /dev/null
@@ -1,34 +0,0 @@
-use proc_macros::uzu_config;
-
-use crate::config::{
- embedding::tied_embedding::TiedEmbeddingConfig, linear::LinearConfig, transformer::TransformerConfig,
-};
-
-#[uzu_config(super::TTSTextDecoderConfig)]
-pub struct FishAudioTextDecoderConfig {
- pub slow_embeddings_config: TiedEmbeddingConfig,
- pub slow_model_config: TransformerConfig,
- pub slow_readout_config: LinearConfig,
-
- pub fast_embeddings_config: TiedEmbeddingConfig,
- pub fast_model_config: TransformerConfig,
- pub fast_readout_config: LinearConfig,
-
- pub codebook_embeddings_config: TiedEmbeddingConfig,
- pub fast_model_projection_config: Option<LinearConfig>,
-
- pub semantic_token_begin_id: u64,
- pub semantic_token_end_id: u64,
- pub im_end_token_id: u64,
- pub codebook_size: usize,
- pub vocab_size: usize,
- pub slow_model_dim: usize,
- pub fast_model_dim: usize,
- pub num_codebooks: usize,
- pub max_seq_len: usize,
-
- pub scale_codebook_embeddings: bool,
-
- pub short_logits_size: usize,
- pub repeat_window_size: usize,
-}
diff --git a/crates/backend-uzu/src/config/tts/text_decoder/mod.rs b/crates/backend-uzu/src/config/tts/text_decoder/mod.rs
deleted file mode 100644
index 3398fb588..000000000
--- a/crates/backend-uzu/src/config/tts/text_decoder/mod.rs
+++ /dev/null
@@ -1,6 +0,0 @@
-use proc_macros::uzu_config_abstract;
-
-pub mod fish_audio_text_decoder;
-
-#[uzu_config_abstract(fish_audio_text_decoder::FishAudioTextDecoderConfig)]
-pub struct TTSTextDecoderConfig;
diff --git a/crates/backend-uzu/src/config/tts/vocoder/mod.rs b/crates/backend-uzu/src/config/tts/vocoder/mod.rs
deleted file mode 100644
index aec73f953..000000000
--- a/crates/backend-uzu/src/config/tts/vocoder/mod.rs
+++ /dev/null
@@ -1,6 +0,0 @@
-use proc_macros::uzu_config_abstract;
-
-pub mod noop_vocoder;
-
-#[uzu_config_abstract(noop_vocoder::NoopVocoderConfig)]
-pub struct VocoderConfig;
diff --git a/crates/backend-uzu/src/config/tts/vocoder/noop_vocoder.rs b/crates/backend-uzu/src/config/tts/vocoder/noop_vocoder.rs
deleted file mode 100644
index 380caba0f..000000000
--- a/crates/backend-uzu/src/config/tts/vocoder/noop_vocoder.rs
+++ /dev/null
@@ -1,4 +0,0 @@
-use proc_macros::uzu_config;
-
-#[uzu_config(super::VocoderConfig)]
-pub struct NoopVocoderConfig;
diff --git a/crates/backend-uzu/src/encodable_block/attention/gemm.rs b/crates/backend-uzu/src/encodable_block/attention/gemm.rs
deleted file mode 100644
index e81d4a4b8..000000000
--- a/crates/backend-uzu/src/encodable_block/attention/gemm.rs
+++ /dev/null
@@ -1,176 +0,0 @@
-use std::{
- cell::RefCell,
- collections::{HashMap, hash_map::Entry},
-};
-
-use crate::{
- backends::common::{
- Allocation, AsBufferRangeRef, Backend, Buffer, Context, Encoder, Kernels,
- gpu_types::{AttnParams, ring::RingParams},
- kernel::AttentionGemmKernel,
- },
- data_type::DataType,
-};
-
-const BQ: usize = 32;
-
-pub struct AttentionGemmArguments<'a, B: Backend, KVBuf: AsBufferRangeRef> {
- pub queries: &'a Allocation<B>,
- pub keys: &'a KVBuf,
- pub values: &'a KVBuf,
- pub output: &'a mut Allocation<B>,
- pub trie: Option<&'a Allocation<B>>,
- pub sinks: Option<&'a Allocation<B>>,
- pub num_heads: usize,
- pub num_groups: usize,
- pub suffix_length: usize,
- pub sequence_length: usize,
- pub segment_prefix_length: usize,
- pub ring_params: Option<RingParams>,
- pub head_dim: usize,
- pub sliding_window_size: Option<usize>,
- pub is_causal: bool,
- pub scale: f32,
- pub k_head_stride: u64,
- pub k_seq_stride: u64,
- pub v_head_stride: u64,
- pub v_seq_stride: u64,
-}
-
-pub struct AttentionGemmBlock<B: Backend> {
- data_type: DataType,
- cache: RefCell<HashMap<KernelKey, <B::Kernels as Kernels>::AttentionGemmKernel>>,
-}
-
-impl<B: Backend> AttentionGemmBlock<B> {
- pub fn new(data_type: DataType) -> Self {
- let cache = RefCell::new(HashMap::new());
- Self {
- data_type,
- cache,
- }
- }
-
- pub fn encode<KVBuf: AsBufferRangeRef<Buffer: Buffer<Backend = B>>>(
- &self,
- encoder: &mut Encoder<B>,
- args: AttentionGemmArguments<B, KVBuf>,
- ) -> Result<(), B::Error> {
- let head_dim = args.head_dim;
- let use_mxu = encoder.context().supports_mxu()
- && self.data_type != DataType::F32
- && head_dim <= 128
- && args.suffix_length >= 64;
- let bk = if use_mxu || head_dim < 128 {
- 32
- } else {
- 16
- };
- let bq = if use_mxu {
- 64
- } else {
- BQ
- };
- let align_q = args.suffix_length.is_multiple_of(bq);
- let align_k = args.sequence_length.is_multiple_of(bk);
- let is_kv_cache_ring = args.ring_params.is_some();
- let is_causal = args.is_causal;
- let is_trie = args.trie.is_some();
- let is_sliding_window = args.sliding_window_size.is_some();
- let has_sinks = args.sinks.is_some();
- let key = KernelKey {
- bk,
- head_dim,
- use_mxu,
- align_q,
- align_k,
- is_kv_cache_ring,
- is_causal,
- is_trie,
- is_sliding_window,
- has_sinks,
- };
-
- let mut map = self.cache.borrow_mut();
- let kernel = match map.entry(key) {
- Entry::Occupied(entry) => entry.into_mut(),
- Entry::Vacant(entry) => {
- let kernel = <B::Kernels as Kernels>::AttentionGemmKernel::new(
- encoder.context(),
- self.data_type,
- bk as u32,
- head_dim as u32,
- use_mxu,
- align_q,
- align_k,
- is_kv_cache_ring,
- is_causal,
- is_trie,
- is_sliding_window,
- has_sinks,
- )?;
- entry.insert(kernel)
- },
- };
-
- let q_head_stride = (args.suffix_length * head_dim) as u64;
- let q_seq_stride = head_dim as u64;
- let o_head_stride = head_dim as u64;
- let o_seq_stride = (args.num_heads * head_dim) as u64;
- let nk = args.sequence_length.div_ceil(bk);
- let nq_aligned = args.suffix_length / bq;
- let nk_aligned = args.sequence_length / bk;
-
- let params = AttnParams {
- q_strides: [0, q_head_stride, q_seq_stride],
- k_strides: [0, args.k_head_stride, args.k_seq_stride],
- v_strides: [0, args.v_head_stride, args.v_seq_stride],
- o_strides: [0, o_head_stride, o_seq_stride],
- gqa_factor: (args.num_heads / args.num_groups) as u32,
- scale: args.scale,
- q_len: args.suffix_length as u32,
- k_len: args.sequence_length as u32,
- q_off: args.segment_prefix_length as u32,
- nq_aligned: nq_aligned as u32,
- q_rem: (args.suffix_length - nq_aligned * bq) as u32,
- nk: nk as u32,
- nk_aligned: nk_aligned as u32,
- k_rem: (args.sequence_length - nk_aligned * bk) as u32,
- };
-
- kernel.encode(
- args.queries,
- args.keys,
- args.values,
- args.output,
- params,
- args.ring_params,
- args.trie,
- args.sliding_window_size.map(|s| s as u32),
- args.sinks,
- args.num_heads as u32,
- args.suffix_length as u32,
- encoder,
- );
-
- Ok(())
- }
-}
-
-#[derive(PartialEq, Eq, Hash, Clone, Copy)]
-struct KernelKey {
- bk: usize,
- head_dim: usize,
- use_mxu: bool,
- align_q: bool,
- align_k: bool,
- is_kv_cache_ring: bool,
- is_causal: bool,
- is_trie: bool,
- is_sliding_window: bool,
- has_sinks: bool,
-}
-
-#[cfg(test)]
-#[path = "../../../unit/encodable_block/attention_gemm_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/attention/mod.rs b/crates/backend-uzu/src/encodable_block/attention/mod.rs
deleted file mode 100644
index 4b972139a..000000000
--- a/crates/backend-uzu/src/encodable_block/attention/mod.rs
+++ /dev/null
@@ -1,879 +0,0 @@
-//! Attention kernel encodable.
-
-mod gemm;
-
-use std::{cell::RefCell, collections::HashMap, rc::Rc};
-
-use gemm::{AttentionGemmArguments, AttentionGemmBlock};
-use itertools::iproduct;
-use thiserror::Error;
-
-use super::{Linear, PrecalculatedRope, QKVNorm, QkUnpack, Rope, linear::LinearBlockError, qkv_norm::QKVNormError};
-use crate::{
- array::size_for_shape,
- backends::common::{
- Allocation, AsBufferRangeRef, Backend, Buffer, Encoder, Kernels,
- gpu_types::ring::RingParams,
- kernel::{
- AttentionFallbackScatterScoresKernel, AttentionFallbackScatterValuesKernel, AttentionSinglePassKernel,
- AttentionTwoPass1Kernel, AttentionTwoPass2Kernel, AttentionUpdateKVCacheKernel, SigmoidGateKernel,
- SoftmaxKernel,
- matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},
- },
- },
- config::token_mixer::attention::AttentionConfig,
- data_type::DataType,
- forward_pass::{
- cache_layers::LayerCacheAccess,
- kv_cache_layer::{KVCacheLayer, KVCacheLayerState},
- },
- parameters::{ParameterLoaderError, ParameterTree},
-};
-
-fn env_gemm_attention_enabled() -> bool {
- static VALUE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- *VALUE.get_or_init(|| {
- let raw = std::env::var("UZU_USE_GEMM_ATTENTION").ok();
- let Some(raw) = raw else {
- return true;
- };
- let v = raw.trim().to_ascii_uppercase();
- match v.as_str() {
- "1" | "YES" | "TRUE" | "ON" => true,
- "0" | "NO" | "FALSE" | "OFF" => false,
- _ => true,
- }
- })
-}
-
-pub struct Attention<B: Backend> {
- qkv_projection: Box<dyn Linear<B>>,
- gate_projection: Option<Box<dyn Linear<B>>>,
- qkv_norm: Option<QKVNorm<B>>,
- rope: Rc<Rope<B>>,
- qk_unpack: Rc<QkUnpack<B>>,
- out_projection: Box<dyn Linear<B>>,
- sinks: Option<Allocation<B>>,
- single_pass_kernels: HashMap<KernelKey, <B::Kernels as Kernels>::AttentionSinglePassKernel>,
- two_pass_1_kernels: HashMap<KernelKey, <B::Kernels as Kernels>::AttentionTwoPass1Kernel>,
- two_pass_2_kernels: HashMap<u32, <B::Kernels as Kernels>::AttentionTwoPass2Kernel>,
- softmax_kernel: <B::Kernels as Kernels>::SoftmaxKernel,
- softmax_sinks_kernel: Option<<B::Kernels as Kernels>::SoftmaxKernel>,
- fallback_scatter_scores_kernels: HashMap<bool, <B::Kernels as Kernels>::AttentionFallbackScatterScoresKernel>,
- fallback_scatter_values_kernel: <B::Kernels as Kernels>::AttentionFallbackScatterValuesKernel,
- matmul_kernel: Option<RefCell<<B::Kernels as Kernels>::MatmulKernel>>,
- update_kv_cache_kernel: <B::Kernels as Kernels>::AttentionUpdateKVCacheKernel,
- update_kv_cache_inplace_kernel: <B::Kernels as Kernels>::AttentionUpdateKVCacheKernel,
- gate_kernel: Option<<B::Kernels as Kernels>::SigmoidGateKernel>,
- gemm_block: AttentionGemmBlock<B>,
- data_type: DataType,
- attention_scale: Option<f32>,
- is_causal: bool,
- sliding_window_size: Option<usize>,
- model_dim: usize,
- num_heads: usize,
- num_groups: usize,
- head_dim: usize,
-}
-
-#[derive(Debug, Error)]
-pub enum AttentionError<B: Backend> {
- #[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
- #[error("Linear block error: {0}")]
- LinearBlockError(#[from] LinearBlockError<B>),
- #[error("QKV norm error: {0}")]
- QKVNormError(#[from] QKVNormError<B>),
- #[error("Parameter loader error: {0}")]
- ParameterLoaderError(#[from] ParameterLoaderError<B>),
-}
-
-impl<B: Backend> Attention<B> {
- pub fn new(
- context: &B::Context,
- model_dim: usize,
- data_type: DataType,
- config: &AttentionConfig,
- parameter_tree: &ParameterTree<B>,
- rope: Rc<Rope<B>>,
- qk_unpack: Rc<QkUnpack<B>>,
- extract_input_hadamard: bool,
- is_kv_sharing: bool,
- ) -> Result<(Self, Option<Allocation<B>>), AttentionError<B>> {
- let q_dim = config.num_heads * config.head_dim;
- let kv_dim = config.num_groups * config.head_dim;
- // KV-sharing layers reuse the source layer's K/V: project queries only, with no key/value norm.
- let (qkv_output_dim, key_norm_config, value_norm_config, kv_norm_groups) = if is_kv_sharing {
- (q_dim, None, None, 0)
- } else {
- (q_dim + 2 * kv_dim, config.key_norm_config.clone(), config.value_norm_config(), config.num_groups)
- };
-
- let qkv_projection_tree = parameter_tree.subtree("qkv_projection")?;
- let (qkv_projection, input_hadamard_factors) = if extract_input_hadamard {
- <dyn Linear<B>>::new_extracting_input_hadamard(
- model_dim,
- [qkv_output_dim],
- config.has_qkv_biases,
- context,
- data_type,
- &qkv_projection_tree,
- )?
- } else {
- (
- <dyn Linear<B>>::new(
- model_dim,
- [qkv_output_dim],
- config.has_qkv_biases,
- context,
- data_type,
- &qkv_projection_tree,
- )?,
- None,
- )
- };
-
- let gate_projection = config
- .gate_projection_config
- .as_ref()
- .map(|_| {
- let gate_projection_tree = parameter_tree.subtree("gate_projection")?;
- <dyn Linear<B>>::new(model_dim, [q_dim], false, context, data_type, &gate_projection_tree)
- })
- .transpose()?;
-
- let qkv_norm = if config.query_norm_config.is_some() || key_norm_config.is_some() || value_norm_config.is_some()
- {
- Some(QKVNorm::new(
- context,
- data_type,
- config.query_norm_config.clone(),
- key_norm_config,
- value_norm_config,
- parameter_tree,
- config.num_heads,
- kv_norm_groups,
- config.head_dim,
- )?)
- } else {
- None
- };
-
- let out_projection_tree = parameter_tree.subtree("out_projection")?;
- let out_projection =
- <dyn Linear<B>>::new(q_dim, [model_dim], config.has_out_biases, context, data_type, &out_projection_tree)?;
-
- let sinks = if config.has_sinks {
- Some(parameter_tree.leaf("sinks")?.validate(&[config.num_heads], data_type)?.read_allocation()?)
- } else {
- None
- };
-
- let mut single_pass_kernels = HashMap::new();
- let mut two_pass_1_kernels = HashMap::new();
- let mut two_pass_2_kernels = HashMap::new();
- let mut fallback_scatter_scores_kernels = HashMap::new();
-
- for (head_dim, is_trie, is_kv_cache_ring) in iproduct!([config.head_dim as u32], [false, true], [false, true]) {
- let key = KernelKey {
- head_dim,
- is_trie,
- is_kv_cache_ring,
- };
-
- let sp_kernel = <B::Kernels as Kernels>::AttentionSinglePassKernel::new(
- context,
- data_type,
- head_dim,
- config.has_sinks,
- is_kv_cache_ring,
- config.is_causal,
- is_trie,
- config.sliding_window_size.is_some(),
- )
- .map_err(AttentionError::BackendError)?;
- single_pass_kernels.insert(key, sp_kernel);
-
- let tp1_kernel = <B::Kernels as Kernels>::AttentionTwoPass1Kernel::new(
- context,
- data_type,
- head_dim,
- config.has_sinks,
- is_kv_cache_ring,
- config.is_causal,
- is_trie,
- config.sliding_window_size.is_some(),
- )
- .map_err(AttentionError::BackendError)?;
- two_pass_1_kernels.insert(key, tp1_kernel);
-
- let tp2_kernel = <B::Kernels as Kernels>::AttentionTwoPass2Kernel::new(context, data_type, head_dim)
- .map_err(AttentionError::BackendError)?;
- two_pass_2_kernels.insert(head_dim, tp2_kernel);
- }
-
- for is_kv_cache_ring in [false, true] {
- let scatter = <B::Kernels as Kernels>::AttentionFallbackScatterScoresKernel::new(
- context,
- data_type,
- is_kv_cache_ring,
- config.is_causal,
- false,
- config.sliding_window_size.is_some(),
- )
- .map_err(AttentionError::BackendError)?;
- fallback_scatter_scores_kernels.insert(is_kv_cache_ring, scatter);
- }
-
- let softmax_kernel = <B::Kernels as Kernels>::SoftmaxKernel::new(context, data_type, false)
- .map_err(AttentionError::BackendError)?;
- let softmax_sinks_kernel = if config.has_sinks {
- Some(
- <B::Kernels as Kernels>::SoftmaxKernel::new(context, data_type, true)
- .map_err(AttentionError::BackendError)?,
- )
- } else {
- None
- };
- let fallback_scatter_values_kernel =
- <B::Kernels as Kernels>::AttentionFallbackScatterValuesKernel::new(context, data_type)
- .map_err(AttentionError::BackendError)?;
- let matmul_kernel =
- <<B as Backend>::Kernels as Kernels>::MatmulKernel::new(context, data_type, data_type, data_type)
- .ok()
- .map(RefCell::new);
- let update_kv_cache_kernel =
- <B::Kernels as Kernels>::AttentionUpdateKVCacheKernel::new(context, data_type, false)
- .map_err(AttentionError::BackendError)?;
- let update_kv_cache_inplace_kernel =
- <B::Kernels as Kernels>::AttentionUpdateKVCacheKernel::new(context, data_type, true)
- .map_err(AttentionError::BackendError)?;
- let gate_kernel = if gate_projection.is_some() {
- Some(
- <B::Kernels as Kernels>::SigmoidGateKernel::new(context, data_type)
- .map_err(AttentionError::BackendError)?,
- )
- } else {
- None
- };
- let gemm_block = AttentionGemmBlock::new(data_type);
-
- Ok((
- Self {
- qkv_projection,
- gate_projection,
- qkv_norm,
- rope,
- qk_unpack,
- out_projection,
- sinks,
- single_pass_kernels,
- two_pass_1_kernels,
- two_pass_2_kernels,
- softmax_kernel,
- softmax_sinks_kernel,
- fallback_scatter_scores_kernels,
- fallback_scatter_values_kernel,
- matmul_kernel,
- update_kv_cache_kernel,
- update_kv_cache_inplace_kernel,
- gate_kernel,
- gemm_block,
- data_type,
- attention_scale: config.scale,
- is_causal: config.is_causal,
- sliding_window_size: config.sliding_window_size,
- model_dim,
- num_heads: config.num_heads,
- num_groups: config.num_groups,
- head_dim: config.head_dim,
- },
- input_hadamard_factors,
- ))
- }
-
- fn select_variant(
- &self,
- gemm_enabled: bool,
- suffix_length: usize,
- head_dim: usize,
- sequence_length: usize,
- is_trie: bool,
- is_kv_cache_ring: bool,
- ) -> KernelVariant {
- // head_dim=512 doesn't fit the fused GEMM tile in threadgroup memory.
- if head_dim == 512 && suffix_length > 8 && !is_trie {
- return KernelVariant::Fallback;
- }
-
- if gemm_enabled && suffix_length > 8 && matches!(head_dim, 64 | 128 | 256) {
- return KernelVariant::Gemm;
- }
-
- let kernel_key = KernelKey {
- head_dim: head_dim as u32,
- is_trie,
- is_kv_cache_ring,
- };
- if sequence_length > 1024
- && self.two_pass_1_kernels.contains_key(&kernel_key)
- && self.two_pass_2_kernels.contains_key(&(head_dim as u32))
- {
- return KernelVariant::TwoPass;
- }
-
- KernelVariant::SinglePass
- }
-
- pub fn encode(
- &self,
- token_subtrie_ranges: Option<&Allocation<B>>,
- rope: Option<&PrecalculatedRope<B>>,
- cache_access: Option<LayerCacheAccess<B>>,
- hidden: Allocation<B>,
- suffix_length: usize,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let (qkv_input, gate) = if let Some(gate_projection) = &self.gate_projection {
- let mut qkv_input =
- encoder.allocate_scratch(size_for_shape(&[suffix_length, self.model_dim], self.data_type))?;
- encoder.encode_copy(&hidden, .., &mut qkv_input, ..);
- let gate = gate_projection.encode(hidden, suffix_length, encoder)?;
- (qkv_input, Some(gate))
- } else {
- (hidden, None)
- };
-
- let mut qkv = self.qkv_projection.encode(qkv_input, suffix_length, encoder)?;
- if let Some(qkv_norm) = &self.qkv_norm {
- qkv_norm.encode(&mut qkv, suffix_length, encoder)?;
- }
- let (queries, rotated_keys) = match rope {
- Some(rope) => {
- self.rope.encode(&qkv, rope, suffix_length, self.num_heads, self.num_groups, self.head_dim, encoder)?
- },
- None => {
- let (queries, keys) = self.qk_unpack.encode(
- &qkv,
- suffix_length,
- self.num_heads,
- self.num_groups,
- self.head_dim,
- encoder,
- )?;
- (queries, Some(keys))
- },
- };
- let attention_output = self.encode_core(
- token_subtrie_ranges,
- cache_access,
- &qkv,
- &queries,
- rotated_keys,
- gate.as_ref(),
- suffix_length,
- encoder,
- )?;
- self.out_projection.encode(attention_output, suffix_length, encoder)
- }
-
- fn encode_core(
- &self,
- token_subtrie_ranges: Option<&Allocation<B>>,
- cache_access: Option<LayerCacheAccess<B>>,
- qkv: &Allocation<B>,
- queries: &Allocation<B>,
- mut rotated_keys: Option<Allocation<B>>,
- gate: Option<&Allocation<B>>,
- suffix_length: usize,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let is_trie = token_subtrie_ranges.is_some();
-
- let cache_layer = cache_access.as_ref().map(|a| {
- match a {
- LayerCacheAccess::Owned {
- entry,
- } => entry.as_transformer(),
- LayerCacheAccess::Shared {
- source,
- } => source.as_transformer(),
- }
- .expect("attention expects transformer cache")
- });
-
- let (max_sequence_length, segment_prefix_length, ring_params) = if let Some(layer) = cache_layer {
- let max_sequence_length = layer.shape()[0];
- let ring_params = match layer.state() {
- KVCacheLayerState::Windowed {
- ring_offset,
- ring_length,
- window_length,
- } => {
- let overflow = ring_length.saturating_sub(window_length);
- Some(RingParams {
- ring_offset: ((ring_offset + overflow) % window_length) as u32,
- ring_length: ring_length.min(window_length) as u32,
- })
- },
- _ => None,
- };
- (max_sequence_length, layer.prefix_segment_length(), ring_params)
- } else {
- (suffix_length, 0, None)
- };
-
- let is_kv_cache_ring = ring_params.is_some();
-
- let sequence_length = segment_prefix_length + suffix_length;
-
- let gqa_factor = self.num_heads / self.num_groups;
- let scale = self.attention_scale.unwrap_or(1.0f32 / (self.head_dim as f32).sqrt());
-
- let gemm_enabled = env_gemm_attention_enabled();
- if !gemm_enabled {
- static PRINT_ONCE: std::sync::Once = std::sync::Once::new();
- PRINT_ONCE.call_once(|| {
- eprintln!("[uzu] Gemm attention disabled via UZU_USE_GEMM_ATTENTION");
- });
- }
- let variant =
- self.select_variant(gemm_enabled, suffix_length, self.head_dim, sequence_length, is_trie, is_kv_cache_ring);
-
- let sinks_allocation = self.sinks.as_ref();
- let trie_allocation = token_subtrie_ranges;
-
- let has_kv_cache = cache_access.is_some();
- let extracted_values = (!has_kv_cache)
- .then(|| {
- let mut values = encoder.allocate_scratch(size_for_shape(
- &[self.num_groups, suffix_length, self.head_dim],
- self.data_type,
- ))?;
- self.update_kv_cache_inplace_kernel.encode(
- None::<&Allocation<B>>,
- qkv,
- rotated_keys.as_mut().expect("classifier attention requires rotated keys"),
- &mut values,
- self.num_groups as u32,
- self.num_heads as u32,
- self.head_dim as u32,
- suffix_length as u32,
- 0u32,
- max_sequence_length as u32,
- encoder,
- );
- Ok::<_, B::Error>(values)
- })
- .transpose()?;
-
- // KV cache layout: [max_sequence_length, num_groups, head_dim] (token-major)
- // For classifier mode (no KV cache) keys/values still come in group-major layout
- // [num_groups, suffix_length, head_dim].
- let (k_head_stride, k_seq_stride, v_head_stride, v_seq_stride) = if has_kv_cache {
- (
- self.head_dim as u32,
- (self.num_groups * self.head_dim) as u32,
- self.head_dim as u32,
- (self.num_groups * self.head_dim) as u32,
- )
- } else {
- (
- (max_sequence_length * self.head_dim) as u32,
- self.head_dim as u32,
- (max_sequence_length * self.head_dim) as u32,
- self.head_dim as u32,
- )
- };
-
- let kernel_key = KernelKey {
- head_dim: self.head_dim as u32,
- is_trie,
- is_kv_cache_ring,
- };
-
- macro_rules! encode_cached_attention {
- ($keys:expr, $values:expr) => {
- self.encode_attention_variant(
- variant,
- &kernel_key,
- queries,
- $keys,
- $values,
- trie_allocation,
- sinks_allocation,
- gqa_factor,
- sequence_length,
- k_head_stride,
- k_seq_stride,
- v_head_stride,
- v_seq_stride,
- ring_params,
- scale,
- self.num_heads,
- self.num_groups,
- suffix_length,
- segment_prefix_length,
- self.head_dim,
- encoder,
- )?
- };
- }
-
- let mut attention_output = if let Some(access) = cache_access {
- match access {
- LayerCacheAccess::Owned {
- entry,
- } => {
- let layer = entry.as_transformer_mut().expect("Attention layer expects transformer cache");
- if let Some(layer) = layer.as_any_mut().downcast_mut::<KVCacheLayer<B, B::SparseBuffer>>() {
- self.update_kv_cache_kernel.encode(
- rotated_keys.as_ref(),
- qkv,
- &mut layer.keys,
- &mut layer.values,
- self.num_groups as u32,
- self.num_heads as u32,
- self.head_dim as u32,
- suffix_length as u32,
- segment_prefix_length as u32,
- max_sequence_length as u32,
- encoder,
- );
- encode_cached_attention!(&layer.keys, &layer.values)
- } else if let Some(layer) = layer.as_any_mut().downcast_mut::<KVCacheLayer<B, B::DenseBuffer>>() {
- self.update_kv_cache_kernel.encode(
- rotated_keys.as_ref(),
- qkv,
- &mut layer.keys,
- &mut layer.values,
- self.num_groups as u32,
- self.num_heads as u32,
- self.head_dim as u32,
- suffix_length as u32,
- segment_prefix_length as u32,
- max_sequence_length as u32,
- encoder,
- );
- encode_cached_attention!(&layer.keys, &layer.values)
- } else {
- panic!("Attention layer expects sparse or dense transformer cache")
- }
- },
- LayerCacheAccess::Shared {
- source,
- } => {
- let source = source.as_transformer().expect("kv_source must be a transformer cache");
- if let Some(source) = source.as_any().downcast_ref::<KVCacheLayer<B, B::SparseBuffer>>() {
- encode_cached_attention!(&source.keys, &source.values)
- } else if let Some(source) = source.as_any().downcast_ref::<KVCacheLayer<B, B::DenseBuffer>>() {
- encode_cached_attention!(&source.keys, &source.values)
- } else {
- panic!("kv_source must be a sparse or dense transformer cache")
- }
- },
- }
- } else {
- let values = extracted_values.as_ref().expect("Missing extracted values for classifier attention");
- let rotated_keys = rotated_keys.as_ref().expect("classifier attention requires rotated keys");
- encode_cached_attention!(rotated_keys, values)
- };
-
- if let Some(gate_kernel) = &self.gate_kernel {
- let total_elements = (suffix_length * self.num_heads * self.head_dim) as u32;
- let gate = gate.expect("Gate allocation not initialized");
- gate_kernel.encode(gate, &mut attention_output, total_elements, encoder);
- }
-
- Ok(attention_output)
- }
-
- fn encode_attention_variant<KVBuf: AsBufferRangeRef<Buffer: Buffer<Backend = B>>>(
- &self,
- variant: KernelVariant,
- kernel_key: &KernelKey,
- queries: &Allocation<B>,
- keys: &KVBuf,
- values: &KVBuf,
- trie_allocation: Option<&Allocation<B>>,
- sinks_allocation: Option<&Allocation<B>>,
- gqa_factor: usize,
- sequence_length: usize,
- k_head_stride: u32,
- k_seq_stride: u32,
- v_head_stride: u32,
- v_seq_stride: u32,
- ring_params: Option<RingParams>,
- scale: f32,
- num_heads: usize,
- num_groups: usize,
- suffix_length: usize,
- segment_prefix_length: usize,
- head_dim: usize,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let mut attention_output =
- encoder.allocate_scratch(size_for_shape(&[suffix_length, num_heads * head_dim], self.data_type))?;
- match variant {
- KernelVariant::Gemm => {
- let args = AttentionGemmArguments {
- queries,
- keys,
- values,
- output: &mut attention_output,
- trie: trie_allocation,
- sinks: sinks_allocation,
- num_heads,
- num_groups,
- suffix_length,
- sequence_length,
- segment_prefix_length,
- ring_params,
- head_dim,
- is_causal: self.is_causal,
- sliding_window_size: self.sliding_window_size,
- scale,
- k_head_stride: k_head_stride as u64,
- k_seq_stride: k_seq_stride as u64,
- v_head_stride: v_head_stride as u64,
- v_seq_stride: v_seq_stride as u64,
- };
- self.gemm_block.encode(encoder, args)?;
- },
- KernelVariant::Fallback => {
- self.encode_fallback(
- kernel_key.is_kv_cache_ring,
- queries,
- keys,
- values,
- &mut attention_output,
- sinks_allocation,
- gqa_factor,
- sequence_length,
- k_head_stride,
- k_seq_stride,
- v_head_stride,
- v_seq_stride,
- ring_params,
- scale,
- num_heads,
- num_groups,
- suffix_length,
- head_dim,
- encoder,
- )?;
- },
- KernelVariant::SinglePass => {
- let kernel = self.single_pass_kernels.get(kernel_key).expect("single_pass kernel missing");
- kernel.encode(
- queries,
- keys,
- values,
- &mut attention_output,
- gqa_factor as u32,
- sequence_length as u32,
- k_head_stride,
- k_seq_stride,
- v_head_stride,
- v_seq_stride,
- ring_params,
- scale,
- trie_allocation,
- self.sliding_window_size.map(|s| s as u32),
- sinks_allocation,
- num_heads as u32,
- suffix_length as u32,
- encoder,
- );
- },
- KernelVariant::TwoPass => {
- let kernel_pass1 = self.two_pass_1_kernels.get(kernel_key).expect("two_pass_1 kernel missing");
- let kernel_pass2 = self.two_pass_2_kernels.get(&(head_dim as u32)).expect("two_pass_2 kernel missing");
- let mut partials = encoder
- .allocate_scratch(size_for_shape(&[num_heads * suffix_length * 32 * head_dim], DataType::F32))?;
- let mut sums =
- encoder.allocate_scratch(size_for_shape(&[num_heads * suffix_length * 32], DataType::F32))?;
- let mut maxs =
- encoder.allocate_scratch(size_for_shape(&[num_heads * suffix_length * 32], DataType::F32))?;
- kernel_pass1.encode(
- queries,
- keys,
- values,
- &mut partials,
- &mut sums,
- &mut maxs,
- gqa_factor as u32,
- sequence_length as u32,
- k_head_stride,
- k_seq_stride,
- v_head_stride,
- v_seq_stride,
- ring_params,
- scale,
- num_heads as u32,
- suffix_length as u32,
- trie_allocation,
- self.sliding_window_size.map(|s| s as u32),
- sinks_allocation,
- encoder,
- );
- kernel_pass2.encode(
- &partials,
- &sums,
- &maxs,
- &mut attention_output,
- num_heads as u32,
- suffix_length as u32,
- encoder,
- );
- },
- }
-
- Ok(attention_output)
- }
-
- fn encode_fallback<
- Keys: AsBufferRangeRef<Buffer: Buffer<Backend = B>>,
- Values: AsBufferRangeRef<Buffer: Buffer<Backend = B>>,
- >(
- &self,
- is_kv_cache_ring: bool,
- queries: &Allocation<B>,
- keys: &Keys,
- values: &Values,
- attention_output: &mut Allocation<B>,
- sinks_allocation: Option<&Allocation<B>>,
- gqa_factor: usize,
- sequence_length: usize,
- k_head_stride: u32,
- k_seq_stride: u32,
- v_head_stride: u32,
- v_seq_stride: u32,
- ring_params: Option<RingParams>,
- scale: f32,
- num_heads: usize,
- num_groups: usize,
- suffix_length: usize,
- head_dim: usize,
- encoder: &mut Encoder<B>,
- ) -> Result<(), B::Error> {
- let matmul = self.matmul_kernel.as_ref().expect("MatmulKernel required for head_dim=512 fallback");
- let scatter_scores =
- self.fallback_scatter_scores_kernels.get(&is_kv_cache_ring).expect("scatter_scores kernel missing");
- let dt_bytes = self.data_type.size_in_bytes();
-
- let mut scores =
- encoder.allocate_scratch(size_for_shape(&[num_heads * suffix_length * sequence_length], self.data_type))?;
- let mut group_scores =
- encoder.allocate_scratch(size_for_shape(&[gqa_factor * suffix_length, sequence_length], self.data_type))?;
-
- for group_index in 0..num_groups {
- matmul.borrow_mut().encode(
- MatmulArguments {
- a: queries,
- a_offset: group_index * gqa_factor * suffix_length * head_dim * dt_bytes,
- b: MatmulB::FullPrecision {
- b: keys,
- },
- b_offset: group_index * k_head_stride as usize * dt_bytes,
- b_leading_dimension: Some(k_seq_stride),
- b_transpose: true,
- d: &mut group_scores,
- d_transform: MatmulDOps {
- ab_scale: scale,
- accumulate: false,
- bias: None,
- rht_factors: None,
- },
- m: (gqa_factor * suffix_length) as u32,
- n: sequence_length as u32,
- k: head_dim as u32,
- },
- encoder,
- )?;
- scatter_scores.encode(
- &group_scores,
- &mut scores,
- ring_params,
- None::<&Allocation<B>>,
- self.sliding_window_size.map(|s| s as u32),
- group_index as u32,
- gqa_factor as u32,
- sequence_length as u32,
- suffix_length as u32,
- (gqa_factor * suffix_length * sequence_length) as u32,
- encoder,
- );
- }
-
- let softmax = if sinks_allocation.is_some() {
- self.softmax_sinks_kernel.as_ref().expect("softmax_sinks_kernel missing but sinks provided")
- } else {
- &self.softmax_kernel
- };
- softmax.encode(
- &mut scores,
- sinks_allocation,
- sequence_length as u32,
- num_heads as u32,
- suffix_length as u32,
- encoder,
- );
-
- let mut group_output =
- encoder.allocate_scratch(size_for_shape(&[gqa_factor * suffix_length, head_dim], self.data_type))?;
-
- for group_index in 0..num_groups {
- matmul.borrow_mut().encode(
- MatmulArguments {
- a: &scores,
- a_offset: group_index * gqa_factor * suffix_length * sequence_length * dt_bytes,
- b: MatmulB::FullPrecision {
- b: values,
- },
- b_offset: group_index * v_head_stride as usize * dt_bytes,
- b_leading_dimension: Some(v_seq_stride),
- b_transpose: false,
- d: &mut group_output,
- d_transform: MatmulDOps::none(),
- m: (gqa_factor * suffix_length) as u32,
- n: head_dim as u32,
- k: sequence_length as u32,
- },
- encoder,
- )?;
- self.fallback_scatter_values_kernel.encode(
- &group_output,
- &mut *attention_output,
- group_index as u32,
- gqa_factor as u32,
- suffix_length as u32,
- num_heads as u32,
- head_dim as u32,
- (gqa_factor * suffix_length * head_dim) as u32,
- encoder,
- );
- }
-
- Ok(())
- }
-}
-
-#[derive(Clone, Copy)]
-enum KernelVariant {
- Gemm,
- Fallback,
- SinglePass,
- TwoPass,
-}
-
-#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
-struct KernelKey {
- pub head_dim: u32,
- pub is_trie: bool,
- pub is_kv_cache_ring: bool,
-}
-
-#[cfg(test)]
-#[path = "../../../unit/encodable_block/attention_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/batch_topology.rs b/crates/backend-uzu/src/encodable_block/batch_topology.rs
new file mode 100644
index 000000000..2c8124247
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/batch_topology.rs
@@ -0,0 +1,62 @@
+use crate::backends::common::gpu_types::trie::TrieNode;
+
+pub struct BatchTopology<'a> {
+ nodes: &'a [TrieNode],
+ parents: Box<[i32]>,
+ is_flat: bool,
+ full_accept: bool,
+}
+
+impl<'a> BatchTopology<'a> {
+ pub fn new(
+ nodes: &'a [TrieNode],
+ full_accept: bool,
+ ) -> Self {
+ let mut stack: Vec<usize> = Vec::new();
+
+ let mut parents = Box::new_uninit_slice(nodes.len());
+ let mut is_flat = true;
+
+ for (index, node) in nodes.iter().enumerate() {
+ stack.truncate(node.height as usize);
+ parents[index].write(stack.last().map(|i| *i as i32).unwrap_or(-1));
+ stack.push(index);
+
+ is_flat &= node.height == index as u32;
+ }
+ let parents = unsafe { parents.assume_init() };
+
+ assert!(is_flat || !full_accept, "full_accept requires trie to be flat");
+
+ Self {
+ nodes,
+ parents,
+ is_flat,
+ full_accept,
+ }
+ }
+
+ pub fn nodes(&self) -> &'a [TrieNode] {
+ self.nodes
+ }
+
+ pub fn size(&self) -> usize {
+ self.nodes.len()
+ }
+
+ pub fn is_flat(&self) -> bool {
+ self.is_flat
+ }
+
+ pub fn full_accept(&self) -> bool {
+ self.full_accept
+ }
+
+ pub fn heights(&self) -> impl Iterator<Item = u32> + 'a {
+ self.nodes.iter().map(|trie| trie.height)
+ }
+
+ pub fn parents(&self) -> &[i32] {
+ &self.parents
+ }
+}
diff --git a/crates/backend-uzu/src/encodable_block/classifier.rs b/crates/backend-uzu/src/encodable_block/classifier.rs
new file mode 100644
index 000000000..19db1bbcc
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/classifier.rs
@@ -0,0 +1,148 @@
+use thiserror::Error;
+
+use crate::{
+ array::size_for_shape,
+ backends::common::{Allocation, Backend, Encoder, Kernels, gpu_types::trie::TrieNode, kernel::PoolingMeanKernel},
+ config::classifier::{ClassifierConfig, PoolingType},
+ data_type::DataType,
+ encodable_block::{
+ batch_topology::BatchTopology,
+ embedding::{Embedding, EmbeddingError},
+ normalization::{Normalization, NormalizationNewError, PostLayerScalar},
+ prediction_head::{PredictionHead, PredictionHeadError},
+ transformer::{Transformer, TransformerNewError},
+ },
+ parameters::{ParameterLoaderError, ParameterTree},
+};
+
+#[derive(Debug, Error)]
+pub enum ClassifierError<B: Backend> {
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+ #[error("Parameter loader error: {0}")]
+ ParameterLoader(#[from] ParameterLoaderError<B>),
+ #[error("Embedding error: {0}")]
+ EmbeddingError(#[from] EmbeddingError<B>),
+ #[error("Normalization error: {0}")]
+ Normalization(#[from] NormalizationNewError<B>),
+ #[error("Transformer error: {0}")]
+ Transformer(#[from] TransformerNewError<B>),
+ #[error("Transformer error: {0}")]
+ PredictionHead(#[from] PredictionHeadError<B>),
+ #[error("Unsupported configuration: {0}")]
+ UnsupportedConfiguration(String),
+}
+
+pub struct Classifier<B: Backend> {
+ hidden_dim: usize,
+ data_type: DataType,
+ embedding: Embedding<B>,
+ embedding_norm: Normalization<B>,
+ transformer: Transformer<B>,
+ pooling: <B::Kernels as Kernels>::PoolingMeanKernel,
+ prediction_head: PredictionHead<B>,
+}
+
+impl<B: Backend> Classifier<B> {
+ pub fn new(
+ context: &B::Context,
+ config: &ClassifierConfig,
+ parameter_tree: &ParameterTree<B>,
+ data_type: DataType,
+ ) -> Result<Self, ClassifierError<B>> {
+ let (embedding, _) = Embedding::new(
+ context,
+ config.vocab_size as u32,
+ config.transformer_config.model_dim as u32,
+ &config.embedding_config,
+ &parameter_tree.subtree("embedding")?,
+ data_type,
+ )?;
+
+ let embedding_norm = Normalization::new(
+ config.transformer_config.model_dim,
+ None,
+ false,
+ false,
+ PostLayerScalar::None,
+ data_type,
+ &config.embedding_norm_config,
+ &parameter_tree.subtree("embedding_norm")?,
+ context,
+ )?;
+
+ let transformer = Transformer::new(
+ context,
+ None,
+ data_type,
+ &config.transformer_config,
+ &parameter_tree.subtree("transformer")?,
+ )?;
+
+ if config.classifier_pooling != PoolingType::Mean {
+ return Err(ClassifierError::UnsupportedConfiguration(format!(
+ "config.classifier_pooling={:?} (only PoolingType::Mean is supported)",
+ config.classifier_pooling
+ )));
+ }
+ let pooling =
+ <B::Kernels as Kernels>::PoolingMeanKernel::new(context, data_type).map_err(ClassifierError::Backend)?;
+
+ let prediction_head = PredictionHead::new(
+ config.hidden_dim,
+ config.num_labels,
+ data_type,
+ &config.prediction_head_config,
+ &parameter_tree.subtree("prediction_head")?,
+ context,
+ )?;
+
+ Ok(Self {
+ hidden_dim: config.hidden_dim,
+ data_type,
+ embedding,
+ embedding_norm,
+ transformer,
+ pooling,
+ prediction_head,
+ })
+ }
+
+ pub fn max_context_length(&self) -> Option<usize> {
+ self.transformer.max_context_length()
+ }
+
+ pub fn encode(
+ &self,
+ token_ids: &Allocation<B>,
+ batch_dim: usize,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, ClassifierError<B>> {
+ let embedded = self.embedding.encode_lookup(token_ids, batch_dim, encoder)?;
+
+ let hidden =
+ self.embedding_norm.encode(&embedded, 0, batch_dim, None, encoder).map_err(ClassifierError::Backend)?;
+
+ let nodes = (0..batch_dim)
+ .map(|index| TrieNode {
+ trie_start: index as u32,
+ trie_end: (batch_dim - 1) as u32,
+ height: index as u32,
+ })
+ .collect::<Box<[TrieNode]>>();
+ let hidden = self
+ .transformer
+ .encode(hidden, None, &BatchTopology::new(&nodes, true), Some(0..batch_dim), None, encoder)
+ .map_err(ClassifierError::Backend)?
+ .unwrap();
+
+ let mut pooled = encoder
+ .allocate_scratch(size_for_shape(&[self.hidden_dim], self.data_type))
+ .map_err(ClassifierError::Backend)?;
+ self.pooling.encode(&hidden, &mut pooled, batch_dim as u32, self.hidden_dim as u32, 1, encoder);
+
+ let logits = self.prediction_head.encode(pooled, 1, encoder).map_err(ClassifierError::Backend)?;
+
+ Ok(logits)
+ }
+}
diff --git a/crates/backend-uzu/src/encodable_block/classifier_layer.rs b/crates/backend-uzu/src/encodable_block/classifier_layer.rs
deleted file mode 100644
index 1811b2ab3..000000000
--- a/crates/backend-uzu/src/encodable_block/classifier_layer.rs
+++ /dev/null
@@ -1,253 +0,0 @@
-use std::rc::Rc;
-
-use thiserror::Error;
-
-use crate::{
- backends::common::{Allocation, AsBufferRangeRef, Backend, Encoder, Kernels, kernel::TensorAddSwapKernel},
- config::{transformer::TransformerConfig, transformer_layer::TransformerLayerConfig},
- data_type::DataType,
- encodable_block::{
- Attention, AttentionError, LayerArguments, LayerRopeKind, Mlp, MlpBlockError, Normalization,
- NormalizationError, QkUnpack, Rope,
- },
- parameters::{ParameterLoaderError, ParameterTree},
-};
-
-#[derive(Debug, Error)]
-pub enum ClassifierLayerError<B: Backend> {
- #[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
- #[error("Parameter loader error: {0}")]
- ParameterLoaderError(#[from] ParameterLoaderError<B>),
- #[error("Attention error: {0}")]
- AttentionError(#[from] AttentionError<B>),
- #[error("MLP error: {0}")]
- MlpBlockError(#[from] MlpBlockError<B>),
- #[error("Normalization error: {0}")]
- NormalizationError(#[from] NormalizationError<B>),
- #[error("classifier layers must use attention")]
- NonAttentionMixer,
- #[error("classifier does not support attention hadamard")]
- AttentionHadamardUnsupported,
- #[error("classifier does not support KV-sharing attention")]
- KvSharingAttentionUnsupported,
- #[error("classifier does not support MLP hadamard")]
- MlpHadamardUnsupported,
-}
-
-pub struct ClassifierLayer<B: Backend> {
- #[cfg(feature = "tracing")]
- pub layer_index: usize,
- pub rope_kind: LayerRopeKind,
- pre_attention_norm: Option<Normalization<B>>,
- attention: Attention<B>,
- post_attention_norm: Option<Normalization<B>>,
- mixer_residual_add: <B::Kernels as Kernels>::TensorAddSwapKernel,
- pre_mlp_norm: Normalization<B>,
- mlp: Box<dyn Mlp<B>>,
- post_mlp_norm: Option<Normalization<B>>,
- mlp_residual_add: <B::Kernels as Kernels>::TensorAddSwapKernel,
- model_dim: usize,
-}
-
-impl<B: Backend> ClassifierLayer<B> {
- pub fn new(
- context: &B::Context,
- transformer_config: &TransformerConfig,
- layer_config: &TransformerLayerConfig,
- #[cfg_attr(not(feature = "tracing"), allow(unused_variables))] layer_index: usize,
- rope_kind: LayerRopeKind,
- layer_loader: &ParameterTree<B>,
- rope: Rc<Rope<B>>,
- qk_unpack: Rc<QkUnpack<B>>,
- data_type: DataType,
- ) -> Result<Self, ClassifierLayerError<B>> {
- let attention_config =
- layer_config.mixer_config.as_attention().ok_or(ClassifierLayerError::NonAttentionMixer)?;
- if attention_config.is_kv_sharing || layer_config.kv_source_layer_index.is_some() {
- return Err(ClassifierLayerError::KvSharingAttentionUnsupported);
- }
-
- let pre_attention_norm = if let Some(norm_config) = &layer_config.pre_mixer_norm_config {
- Some(Normalization::new(
- context,
- data_type,
- transformer_config.model_dim,
- norm_config.clone(),
- &layer_loader.subtree("pre_mixer_norm")?,
- )?)
- } else {
- None
- };
-
- let (attention, attention_hadamard_factors) = Attention::new(
- context,
- transformer_config.model_dim,
- data_type,
- attention_config,
- &layer_loader.subtree("mixer")?,
- rope,
- qk_unpack,
- false,
- false,
- )?;
- if attention_hadamard_factors.is_some() {
- return Err(ClassifierLayerError::AttentionHadamardUnsupported);
- }
-
- let post_attention_norm = if let Some(norm_config) = &layer_config.post_mixer_norm_config {
- Some(Normalization::new(
- context,
- data_type,
- transformer_config.model_dim,
- norm_config.clone(),
- &layer_loader.subtree("post_mixer_norm")?,
- )?)
- } else {
- None
- };
-
- let mixer_residual_add = <B::Kernels as Kernels>::TensorAddSwapKernel::new(context, data_type)
- .map_err(ClassifierLayerError::BackendError)?;
-
- let pre_mlp_norm = Normalization::new(
- context,
- data_type,
- transformer_config.model_dim,
- layer_config.pre_mlp_norm_config.clone(),
- &layer_loader.subtree("pre_mlp_norm")?,
- )?;
-
- let (mlp, mlp_hadamard_factors) = <dyn Mlp<B>>::new(
- &layer_config.mlp_config,
- transformer_config.model_dim,
- layer_config.hidden_dim.unwrap_or(transformer_config.hidden_dim),
- context,
- &layer_loader.subtree("mlp")?,
- data_type,
- )?;
-
- if mlp_hadamard_factors.is_some() {
- return Err(ClassifierLayerError::MlpHadamardUnsupported);
- }
-
- let post_mlp_norm = if let Some(norm_config) = &layer_config.post_mlp_norm_config {
- Some(Normalization::new(
- context,
- data_type,
- transformer_config.model_dim,
- norm_config.clone(),
- &layer_loader.subtree("post_mlp_norm")?,
- )?)
- } else {
- None
- };
-
- let mlp_residual_add = <B::Kernels as Kernels>::TensorAddSwapKernel::new(context, data_type)
- .map_err(ClassifierLayerError::BackendError)?;
-
- Ok(Self {
- #[cfg(feature = "tracing")]
- layer_index,
- rope_kind,
- pre_attention_norm,
- attention,
- post_attention_norm,
- mixer_residual_add,
- pre_mlp_norm,
- mlp,
- post_mlp_norm,
- mlp_residual_add,
- model_dim: transformer_config.model_dim,
- })
- }
-
- pub fn encode(
- &self,
- args: LayerArguments<B>,
- main: Allocation<B>,
- shortcut: &mut Allocation<B>,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let LayerArguments {
- batch_dim,
- token_subtrie_ranges,
- rope,
- #[cfg(feature = "tracing")]
- trace,
- ..
- } = args;
- #[cfg(feature = "tracing")]
- let mut layer_traces = trace;
- let layer_len = batch_dim * self.model_dim;
-
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(&main, .., layer_traces.inputs.allocation_mut(), ..);
- }
-
- debug_assert_eq!(main.as_buffer_range_ref().range().len(), shortcut.as_buffer_range_ref().range().len());
- encoder.encode_copy(&main, .., shortcut, ..);
-
- let mut main = if let Some(ref pre_attn_norm) = self.pre_attention_norm {
- pre_attn_norm.encode(&main, 0, batch_dim, encoder)?
- } else {
- main
- };
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(&main, .., layer_traces.pre_attention_norm.allocation_mut(), ..);
- }
-
- main = self.attention.encode(token_subtrie_ranges, rope, None, main, batch_dim, encoder)?;
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(&main, .., layer_traces.attention.allocation_mut(), ..);
- }
-
- if let Some(ref post_attn_norm) = self.post_attention_norm {
- main = post_attn_norm.encode(&main, 0, batch_dim, encoder)?;
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(&main, .., layer_traces.post_attention_norm.allocation_mut(), ..);
- }
- }
-
- self.mixer_residual_add.encode(&mut *shortcut, &mut main, layer_len as u32, encoder);
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(&main, .., layer_traces.mlp_inputs.allocation_mut(), ..);
- }
-
- debug_assert_eq!(main.as_buffer_range_ref().range().len(), shortcut.as_buffer_range_ref().range().len());
- encoder.encode_copy(&main, .., shortcut, ..);
-
- main = self.pre_mlp_norm.encode(&main, 0, batch_dim, encoder)?;
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(&main, .., layer_traces.pre_mlp_norm.allocation_mut(), ..);
- }
-
- main = self.mlp.encode(main, batch_dim, encoder)?;
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(&main, .., layer_traces.mlp.allocation_mut(), ..);
- }
-
- if let Some(ref post_mlp_norm) = self.post_mlp_norm {
- main = post_mlp_norm.encode(&main, 0, batch_dim, encoder)?;
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(&main, .., layer_traces.post_mlp_norm.allocation_mut(), ..);
- }
- }
-
- self.mlp_residual_add.encode(shortcut, &mut main, layer_len as u32, encoder);
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces {
- encoder.encode_copy(&main, .., layer_traces.outputs.allocation_mut(), ..);
- }
-
- Ok(main)
- }
-}
diff --git a/crates/backend-uzu/src/encodable_block/decoder.rs b/crates/backend-uzu/src/encodable_block/decoder.rs
index 7650e32f2..11764264b 100644
--- a/crates/backend-uzu/src/encodable_block/decoder.rs
+++ b/crates/backend-uzu/src/encodable_block/decoder.rs
@@ -1,424 +1,135 @@
-//! Decoder executables - combines embedding, layers, normalization, and readout.
-
-use std::rc::Rc;
+use std::ops::Range;
use thiserror::Error;
-#[cfg(feature = "tracing")]
-use crate::forward_pass::traces::ActivationTrace;
use crate::{
- backends::common::{Allocation, AsBufferRangeRef, Backend, Encoder},
- config::{decoder::DecoderConfig, rope::AnyRoPEConfig},
+ backends::common::{Allocation, Backend, Encoder},
+ config::decoder::DecoderConfig,
data_type::DataType,
encodable_block::{
- Embedding, LayerArguments, LayerExecutables, LayerRopeKind, PerLayerEmbedding, PostLayerScalar,
- PrecalculatedRope, QkUnpack, RMSNorm, RMSNormError, Rope, embedding::EmbeddingError,
- layer::LayerExecutablesError,
+ batch_topology::BatchTopology,
+ embedding::{Embedding, EmbeddingError},
+ per_layer_embedding::{PerLayerEmbedding, PerLayerEmbeddingError},
+ transformer::{Transformer, TransformerNewError, TransformerState},
},
- forward_pass::{cache_layers::CacheLayers, model_shape::ModelShape, rope::precalculate_rope},
parameters::{ParameterLoaderError, ParameterTree},
};
#[derive(Debug, Error)]
pub enum DecoderError<B: Backend> {
#[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
+ Backend(#[source] B::Error),
+ #[error("Parameter loader error: {0}")]
+ ParameterLoader(#[from] ParameterLoaderError<B>),
#[error("Embedding error: {0}")]
EmbeddingError(#[from] EmbeddingError<B>),
- #[error("Parameter loader error: {0}")]
- ParameterLoaderError(#[from] ParameterLoaderError<B>),
- #[error("Layer error: {0}")]
- LayerError(#[from] LayerExecutablesError<B>),
- #[error("RMSNorm error: {0}")]
- RMSNormError(#[from] RMSNormError<B>),
- #[error("Invalid decode input: {0}")]
- InvalidDecodeInput(&'static str),
+ #[error("Per-layer embedding error: {0}")]
+ PerLayerEmbedding(#[from] PerLayerEmbeddingError<B>),
+ #[error("Transformer error: {0}")]
+ Transformer(#[from] TransformerNewError<B>),
}
-/// Full decoder executable with all layers and components.
pub struct Decoder<B: Backend> {
- pub embed: Embedding<B>,
- pub rope_configs: Box<[AnyRoPEConfig]>,
- pub layers: Box<[LayerExecutables<B>]>,
- pub norm: RMSNorm<B>,
- pub per_layer_embedding: Option<PerLayerEmbedding<B>>,
-}
-
-pub struct DecoderArguments<'a, B: Backend> {
- pub token_positions: &'a [usize],
- pub token_parents: &'a Allocation<B>,
- pub token_subtrie_ranges: Option<&'a Allocation<B>>,
- pub cache_layers: Option<&'a mut CacheLayers<B>>,
- pub batch_dim: usize,
- pub sampling_start: usize,
- pub sampling_length: usize,
- #[cfg(feature = "tracing")]
- pub trace: Option<&'a mut ActivationTrace<B>>,
-}
-
-pub enum DecoderDecodeInput<'a, B: Backend> {
- TokenIds(&'a Allocation<B>),
- #[cfg(metal_backend)]
- Embeddings(Allocation<B>),
+ embedding: Embedding<B>,
+ per_layer_embedding: Option<PerLayerEmbedding<B>>,
+ transformer: Transformer<B>,
}
impl<B: Backend> Decoder<B> {
pub fn new(
context: &B::Context,
- decoder_config: &DecoderConfig,
- root_weight_loader: &ParameterTree<B>,
- model_shape: &ModelShape,
+ config: &DecoderConfig,
+ parameter_tree: &ParameterTree<B>,
+ data_type: DataType,
) -> Result<Self, DecoderError<B>> {
- let embedding_weight_loader = root_weight_loader.subtree("embedding")?;
-
- let (embed, readout_input_hadamard_factors) = Embedding::new(
- context,
- decoder_config.vocab_size as u32,
- decoder_config.transformer_config.model_dim as u32,
- &decoder_config.embedding_config,
- &embedding_weight_loader,
- model_shape,
- )?;
-
- let (rope_configs, layers, norm) = Self::build_transformer_layers_and_norm(
+ let (embedding, readout_input_hadamard_factors) = Embedding::new(
context,
- decoder_config,
- root_weight_loader,
- "transformer",
- readout_input_hadamard_factors,
- model_shape,
+ config.vocab_size as u32,
+ config.transformer_config.model_dim as u32,
+ &config.embedding_config,
+ &parameter_tree.subtree("embedding")?,
+ data_type,
)?;
- let per_layer_embedding =
- Self::build_per_layer_embedding(context, decoder_config, root_weight_loader, model_shape.data_type);
-
- Ok(Self {
- embed,
- rope_configs,
- layers,
- norm,
- per_layer_embedding,
- })
- }
-
- /// Used by TTS models whose token lookup weights live outside the
- /// standard decoder subtree. The TTS runtime owns its separate readout.
- #[cfg(metal_backend)]
- pub fn new_with_embedding_subtree(
- context: &B::Context,
- decoder_config: &DecoderConfig,
- root_weight_loader: &ParameterTree<B>,
- transformer_subtree: &str,
- embedding_subtree: &str,
- model_shape: &ModelShape,
- ) -> Result<Self, DecoderError<B>> {
- let embedding_weight_loader = root_weight_loader.subtree(embedding_subtree)?;
-
- let (embed, readout_input_hadamard_factors) = Embedding::new(
- context,
- decoder_config.vocab_size as u32,
- decoder_config.transformer_config.model_dim as u32,
- &decoder_config.embedding_config,
- &embedding_weight_loader,
- model_shape,
- )?;
+ let per_layer_embedding = if let Some(ple_config) = &config.ple_model_config {
+ assert_eq!(
+ ple_config.num_layers,
+ config.transformer_config.layer_configs.len(),
+ "per-layer embedding num_layers must match transformer layer count"
+ );
+ Some(PerLayerEmbedding::new(
+ context,
+ ple_config,
+ config.transformer_config.model_dim,
+ data_type,
+ &parameter_tree.subtree("per_layer_embedding")?,
+ )?)
+ } else {
+ None
+ };
- let (rope_configs, layers, norm) = Self::build_transformer_layers_and_norm(
+ let transformer = Transformer::new(
context,
- decoder_config,
- root_weight_loader,
- transformer_subtree,
readout_input_hadamard_factors,
- model_shape,
+ data_type,
+ &config.transformer_config,
+ &parameter_tree.subtree("transformer")?,
)?;
- let per_layer_embedding =
- Self::build_per_layer_embedding(context, decoder_config, root_weight_loader, model_shape.data_type);
-
Ok(Self {
- embed,
- rope_configs,
- layers,
- norm,
+ embedding,
per_layer_embedding,
+ transformer,
})
}
- pub fn build_transformer_layers_and_norm(
- context: &B::Context,
- decoder_config: &DecoderConfig,
- root_weight_loader: &ParameterTree<B>,
- transformer_subtree: &str,
- output_norm_hadamard_factors: Option<Allocation<B>>,
- model_shape: &ModelShape,
- ) -> Result<(Box<[AnyRoPEConfig]>, Box<[LayerExecutables<B>]>, RMSNorm<B>), DecoderError<B>> {
- let decoder_weight_loader = root_weight_loader.subtree(transformer_subtree)?;
-
- let tf = &decoder_config.transformer_config;
- let mut rope_configs = Vec::<(AnyRoPEConfig, usize)>::new();
- let layer_rope_kinds: Box<[LayerRopeKind]> = tf
- .layer_configs
- .iter()
- .map(|layer_config| {
- if layer_config.mixer_config.as_attention().is_none() {
- return LayerRopeKind::NoKernel;
- }
- let Some(rope_config) = &layer_config.rope_config else {
- return LayerRopeKind::NoKernel;
- };
- let head_dim = *rope_config.head_dim();
- let index = rope_configs
- .iter()
- .position(|(existing_config, existing_head_dim)| {
- existing_config == rope_config && *existing_head_dim == head_dim
- })
- .unwrap_or_else(|| {
- rope_configs.push((rope_config.clone(), head_dim));
- rope_configs.len() - 1
- });
- LayerRopeKind::Indexed(index)
- })
- .collect();
-
- let rope = Rc::new(Rope::<B>::new(context, model_shape, false).map_err(DecoderError::BackendError)?);
- // Built only when some layer projects queries only (reuses an earlier layer's KV cache).
- let rope_query_only = if tf.layer_configs.iter().any(|l| l.kv_source_layer_index.is_some()) {
- Some(Rc::new(Rope::<B>::new(context, model_shape, true).map_err(DecoderError::BackendError)?))
- } else {
- None
- };
- let qk_unpack =
- Rc::new(QkUnpack::<B>::new(context, model_shape.data_type).map_err(DecoderError::BackendError)?);
-
- let layers = tf
- .layer_configs
- .iter()
- .enumerate()
- .map(|(layer_index, layer_config)| {
- let layer_loader = decoder_weight_loader.subtree(&format!("layers.{}", layer_index))?;
- let layer_rope = if layer_config.kv_source_layer_index.is_some() {
- rope_query_only.as_ref().expect("query-only rope is built whenever a layer shares KV")
- } else {
- &rope
- };
-
- LayerExecutables::new(
- context,
- tf,
- layer_config,
- layer_index,
- layer_rope_kinds[layer_index],
- &layer_loader,
- layer_rope,
- &qk_unpack,
- model_shape.data_type,
- )
- .map_err(DecoderError::LayerError)
- })
- .collect::<Result<Vec<_>, DecoderError<B>>>()?;
-
- let norm_block = RMSNorm::new(
- context,
- model_shape.data_type,
- model_shape.model_dim(),
- tf.output_norm_config.clone(),
- &decoder_weight_loader.subtree("output_norm")?,
- output_norm_hadamard_factors,
- true,
- true,
- PostLayerScalar::None,
- )?;
+ pub fn speculation_supported(&self) -> bool {
+ self.transformer.speculation_supported()
+ }
- Ok((rope_configs.into_iter().map(|(config, _)| config).collect(), layers.into_boxed_slice(), norm_block))
+ pub fn max_context_length(&self) -> Option<usize> {
+ self.transformer.max_context_length()
}
- fn build_per_layer_embedding(
+ pub fn create_empty_state(
+ &self,
+ max_context_length: Option<usize>,
context: &B::Context,
- decoder_config: &DecoderConfig,
- root_weight_loader: &ParameterTree<B>,
- data_type: DataType,
- ) -> Option<PerLayerEmbedding<B>> {
- decoder_config.ple_model_config.as_ref().map(|ple_config| {
- let layer_count = decoder_config.transformer_config.layer_configs.len();
- assert_eq!(
- ple_config.num_layers, layer_count,
- "per-layer embedding num_layers must match transformer layer count"
- );
- let ple_weight_loader =
- root_weight_loader.subtree("per_layer_embedding").expect("Failed to get per_layer_embedding subtree");
- PerLayerEmbedding::new(
- context,
- ple_config,
- decoder_config.transformer_config.model_dim,
- data_type,
- &ple_weight_loader,
- )
- .expect("Failed to create per-layer embedding")
- })
+ ) -> Result<TransformerState<B>, B::Error> {
+ self.transformer.create_empty_state(max_context_length, context)
}
- fn encode_per_layer_inputs(
+ pub fn encode(
&self,
token_ids: &Allocation<B>,
- inner_features: &Allocation<B>,
- batch_dim: usize,
+ batch_dim: &BatchTopology,
+ output_range: Option<Range<usize>>,
+ state: &mut TransformerState<B>,
encoder: &mut Encoder<B>,
) -> Result<Option<Allocation<B>>, DecoderError<B>> {
- if let Some(ple) = &self.per_layer_embedding {
- let output =
- ple.encode(token_ids, inner_features, batch_dim, encoder).map_err(DecoderError::BackendError)?;
- Ok(Some(output))
- } else {
- Ok(None)
- }
- }
+ let embedded = self.embedding.encode_lookup(token_ids, batch_dim.size(), encoder)?;
- fn run_layers(
- &self,
- args: DecoderArguments<B>,
- mut main: Allocation<B>,
- per_layer_inputs: Option<&Allocation<B>>,
- encoder: &mut Encoder<B>,
- ) -> Result<(Allocation<B>, Allocation<B>), DecoderError<B>> {
- let DecoderArguments {
- token_positions,
- token_parents,
- token_subtrie_ranges,
- mut cache_layers,
- batch_dim,
- sampling_start,
- sampling_length,
- #[cfg(feature = "tracing")]
- trace,
- } = args;
- #[cfg(feature = "tracing")]
- let mut trace = trace;
-
- let mut shortcut =
- encoder.allocate_scratch(main.as_buffer_range_ref().range().len()).map_err(DecoderError::BackendError)?;
- let ropes = self
- .rope_configs
- .iter()
- .map(|rope_config| {
- let (sines, cosines) = precalculate_rope(rope_config, token_positions);
- let mut sines_allocation = encoder.allocate_constant(sines.len() * std::mem::size_of::<f32>())?;
- sines_allocation.copyin(sines.as_ref());
- let mut cosines_allocation = encoder.allocate_constant(cosines.len() * std::mem::size_of::<f32>())?;
- cosines_allocation.copyin(cosines.as_ref());
- Ok(PrecalculatedRope {
- cosines: cosines_allocation,
- sines: sines_allocation,
- dim: *rope_config.head_dim(),
- })
- })
- .collect::<Result<Box<[_]>, B::Error>>()
- .map_err(DecoderError::BackendError)?;
-
- for layer in self.layers.iter() {
- #[cfg(feature = "tracing")]
- let layer_trace = trace.as_deref_mut().map(|trace| &mut trace.layer_results[layer.layer_index]);
-
- let cache_access =
- cache_layers.as_deref_mut().map(|cache_layers| cache_layers.cache_for_layer(layer.layer_index));
- main = layer
- .encode(
- LayerArguments {
- batch_dim,
- token_parents,
- token_subtrie_ranges,
- rope: layer.rope_kind.get(&ropes),
- per_layer_inputs,
- sampling_start,
- sampling_length,
- cache_access,
- #[cfg(feature = "tracing")]
- trace: layer_trace,
- },
- main,
- &mut shortcut,
- encoder,
- )
- .map_err(DecoderError::BackendError)?;
- }
-
- Ok((main, shortcut))
- }
+ let per_layer_inputs = if let Some(per_layer_embedding) = &self.per_layer_embedding {
+ Some(
+ per_layer_embedding
+ .encode(token_ids, &embedded, batch_dim.size(), encoder)
+ .map_err(DecoderError::Backend)?,
+ )
+ } else {
+ None
+ };
- pub fn encode_prefill(
- &self,
- args: DecoderArguments<B>,
- token_ids: &Allocation<B>,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, DecoderError<B>> {
- let main = self.embed.encode_lookup(token_ids, args.batch_dim, encoder)?;
- let per_layer_inputs = self.encode_per_layer_inputs(token_ids, &main, args.batch_dim, encoder)?;
- let (main, _) = self.run_layers(args, main, per_layer_inputs.as_ref(), encoder)?;
- Ok(main)
- }
+ let hidden = self
+ .transformer
+ .encode(embedded, per_layer_inputs.as_ref(), batch_dim, output_range.clone(), Some(state), encoder)
+ .map_err(DecoderError::Backend)?;
- pub fn encode_decode<'input>(
- &self,
- args: DecoderArguments<B>,
- input: DecoderDecodeInput<'input, B>,
- hidden_capture: Option<&mut Allocation<B>>,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, DecoderError<B>> {
- let sampling_start = args.sampling_start;
- let sampling_length = args.sampling_length;
- let batch_dim = args.batch_dim;
- #[cfg(feature = "tracing")]
- let mut trace = args.trace;
- let (main, token_ids) = match input {
- DecoderDecodeInput::TokenIds(token_ids) => {
- let main = self.embed.encode_lookup(token_ids, args.batch_dim, encoder)?;
- (main, Some(token_ids))
- },
- #[cfg(metal_backend)]
- DecoderDecodeInput::Embeddings(main) => (main, None),
+ let Some(output_range) = output_range else {
+ return Ok(None);
};
- let per_layer_inputs = match token_ids {
- Some(token_ids) => self.encode_per_layer_inputs(token_ids, &main, batch_dim, encoder)?,
- None if self.per_layer_embedding.is_some() => {
- return Err(DecoderError::InvalidDecodeInput("per-layer embedding requires token ids"));
- },
- None => None,
- };
- let (main, mut shortcut) = self.run_layers(
- DecoderArguments {
- token_positions: args.token_positions,
- token_parents: args.token_parents,
- token_subtrie_ranges: args.token_subtrie_ranges,
- cache_layers: args.cache_layers,
- batch_dim: args.batch_dim,
- sampling_start,
- sampling_length,
- #[cfg(feature = "tracing")]
- trace: trace.as_deref_mut(),
- },
- main,
- per_layer_inputs.as_ref(),
- encoder,
- )?;
- let output_norm = self
- .norm
- .encode(&main, sampling_start, sampling_length, Some(&mut shortcut), encoder)
- .map_err(DecoderError::BackendError)?;
- if let Some(hidden_capture) = hidden_capture {
- let row_size_bytes = shortcut.as_buffer_range_ref().range().len() / batch_dim;
- let input_offset = (batch_dim - 1) * row_size_bytes;
- encoder.encode_copy(&shortcut, input_offset..input_offset + row_size_bytes, hidden_capture, ..);
- }
- #[cfg(feature = "tracing")]
- if let Some(trace) = trace.as_deref_mut() {
- encoder.encode_copy(&output_norm, .., trace.output_norm.allocation_mut(), ..);
- }
+ let logits = self.embedding.encode_readout(output_range.len(), &hidden.unwrap(), encoder)?;
- let logits = self.embed.encode_readout(sampling_length, &output_norm, encoder)?;
- #[cfg(feature = "tracing")]
- if let Some(trace) = trace {
- encoder.encode_copy(&logits, .., trace.logits.allocation_mut(), ..);
- }
- Ok(logits)
+ Ok(Some(logits))
}
}
diff --git a/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs b/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs
deleted file mode 100644
index f2826776c..000000000
--- a/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs
+++ /dev/null
@@ -1,376 +0,0 @@
-use thiserror::Error;
-
-use crate::{
- array::size_for_shape,
- backends::common::{
- Allocation, Backend, Encoder, Kernels,
- kernel::{
- Conv1dPackKernel, DeltaNetConvScanKernel, DeltaNetConvUpdateKernel, DeltaNetNormGateKernel,
- DeltaNetPrefillKernel, DeltaNetPrefillPrepKernel, DeltaNetUpdateKernel,
- },
- },
- config::token_mixer::delta_net::DeltaNetConfig,
- data_type::DataType,
- encodable_block::linear::{Linear, LinearBlockError},
- forward_pass::delta_net_layer::DeltaNetLayer,
- parameters::{ParameterLoaderError, ParameterTree},
-};
-
-#[derive(Debug, Error)]
-pub enum DeltaNetMixerError<B: Backend> {
- #[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
- #[error("Unsupported configuration: {0}")]
- UnsupportedConfiguration(String),
- #[error("Linear error: {0}")]
- InnerLinearError(#[from] LinearBlockError<B>),
- #[error("Parameter loader error: {0}")]
- ParameterLoaderError(#[from] ParameterLoaderError<B>),
-}
-
-pub struct DeltaNetMixer<B: Backend> {
- kernel_size: usize,
- num_heads: usize,
- num_groups: usize,
- value_head_dim: usize,
- key_dim: usize,
- value_dim: usize,
- conv_dim: usize,
- total_proj_dim: usize,
- norm_epsilon: f32,
- in_projection: Box<dyn Linear<B>>,
- out_projection: Box<dyn Linear<B>>,
- // Decode kernels
- conv_update: <B::Kernels as Kernels>::DeltaNetConvUpdateKernel,
- delta_net_update: <B::Kernels as Kernels>::DeltaNetUpdateKernel,
- // Prefill kernels
- conv_pack: <B::Kernels as Kernels>::Conv1dPackKernel,
- conv_scan: <B::Kernels as Kernels>::DeltaNetConvScanKernel,
- prefill_prep: <B::Kernels as Kernels>::DeltaNetPrefillPrepKernel,
- delta_net_prefill: <B::Kernels as Kernels>::DeltaNetPrefillKernel,
- norm_gate: <B::Kernels as Kernels>::DeltaNetNormGateKernel,
- // Parameters
- conv_weight: Allocation<B>,
- conv_bias: Option<Allocation<B>>,
- a_log: Allocation<B>,
- dt_bias: Allocation<B>,
- norm_weight: Allocation<B>,
- // Activation/scratch dtype (model dtype, e.g. bf16). The recurrent ssm_state
- // and small weights (a_log/dt_bias/norm/conv) stay f32 inside the kernels.
- outer_data_type: DataType,
-}
-
-pub struct DeltaNetArguments<'a, B: Backend> {
- pub active_row_count: usize,
- pub layer: &'a mut DeltaNetLayer<B>,
-}
-
-impl<B: Backend> DeltaNetMixer<B> {
- pub fn new(
- context: &B::Context,
- config: &DeltaNetConfig,
- model_dim: usize,
- parameter_tree: &ParameterTree<B>,
- outer_data_type: DataType,
- ) -> Result<(Self, Option<Allocation<B>>), DeltaNetMixerError<B>> {
- let inner_data_type = DataType::F32;
-
- if config.kernel_size < 2 {
- return Err(DeltaNetMixerError::UnsupportedConfiguration(format!(
- "kernel_size must be >= 2, got {}",
- config.kernel_size
- )));
- }
- if config.head_dim != 128 {
- return Err(DeltaNetMixerError::UnsupportedConfiguration(format!(
- "head_dim must be 128, got {}",
- config.head_dim
- )));
- }
- if config.value_head_dim != 128 {
- return Err(DeltaNetMixerError::UnsupportedConfiguration(format!(
- "value_head_dim must be 128, got {}",
- config.value_head_dim
- )));
- }
-
- let has_bias = config.conv_config.has_biases;
- let key_dim = config.key_dim();
- let value_dim = config.value_dim();
- let conv_dim = config.conv_dim();
- let total_proj_dim = config.total_proj_dim();
-
- // Load weights
- let conv_tree = parameter_tree.subtree("conv")?;
-
- let (in_projection, in_projection_input_hadamard_factors) =
- <dyn Linear<B>>::new_extracting_input_hadamard_mixed_precision(
- model_dim,
- [total_proj_dim],
- false,
- context,
- outer_data_type,
- outer_data_type,
- outer_data_type,
- &parameter_tree.subtree("in_proj")?,
- )?;
-
- let out_projection = <dyn Linear<B>>::new_mixed_precision(
- value_dim,
- [model_dim],
- false,
- context,
- outer_data_type,
- outer_data_type,
- outer_data_type,
- &parameter_tree.subtree("out_proj")?,
- )?;
-
- let conv_weight =
- conv_tree.leaf("weights")?.validate(&[conv_dim, config.kernel_size], inner_data_type)?.read_allocation()?;
- let conv_bias = if has_bias {
- Some(conv_tree.leaf("biases")?.validate(&[conv_dim], inner_data_type)?.read_allocation()?)
- } else {
- None
- };
-
- let a_log = parameter_tree.leaf("a_log")?.validate(&[config.num_heads], inner_data_type)?.read_allocation()?;
- let dt_bias =
- parameter_tree.leaf("dt_bias")?.validate(&[config.num_heads], inner_data_type)?.read_allocation()?;
- let norm_weight = parameter_tree
- .leaf("norm.scales")?
- .validate(&[config.value_head_dim], inner_data_type)?
- .read_allocation()?;
-
- // Create kernels
- let conv_update = <B::Kernels as Kernels>::DeltaNetConvUpdateKernel::new(context, outer_data_type, has_bias)
- .map_err(DeltaNetMixerError::BackendError)?;
- let delta_net_update =
- <B::Kernels as Kernels>::DeltaNetUpdateKernel::new(context, outer_data_type, config.head_dim as u32)
- .map_err(DeltaNetMixerError::BackendError)?;
- let conv_pack = <B::Kernels as Kernels>::Conv1dPackKernel::new(context, inner_data_type, outer_data_type)
- .map_err(DeltaNetMixerError::BackendError)?;
- let conv_scan = <B::Kernels as Kernels>::DeltaNetConvScanKernel::new(context, outer_data_type, has_bias)
- .map_err(DeltaNetMixerError::BackendError)?;
- let prefill_prep =
- <B::Kernels as Kernels>::DeltaNetPrefillPrepKernel::new(context, outer_data_type, config.head_dim as u32)
- .map_err(DeltaNetMixerError::BackendError)?;
- let delta_net_prefill =
- <B::Kernels as Kernels>::DeltaNetPrefillKernel::new(context, outer_data_type, config.head_dim as u32)
- .map_err(DeltaNetMixerError::BackendError)?;
- let norm_gate = <B::Kernels as Kernels>::DeltaNetNormGateKernel::new(context, outer_data_type)
- .map_err(DeltaNetMixerError::BackendError)?;
-
- Ok((
- Self {
- kernel_size: config.kernel_size,
- num_heads: config.num_heads,
- num_groups: config.num_groups,
- value_head_dim: config.value_head_dim,
- key_dim,
- value_dim,
- conv_dim,
- total_proj_dim,
- norm_epsilon: config.norm_config.epsilon,
- in_projection,
- out_projection,
- conv_update,
- delta_net_update,
- conv_pack,
- conv_scan,
- prefill_prep,
- delta_net_prefill,
- norm_gate,
- conv_weight,
- conv_bias,
- a_log,
- dt_bias,
- norm_weight,
- outer_data_type,
- },
- in_projection_input_hadamard_factors,
- ))
- }
-
- fn run_conv_update(
- &self,
- layer: &mut DeltaNetLayer<B>,
- in_proj: &mut Allocation<B>,
- encoder: &mut Encoder<B>,
- ) {
- let kernel_size = self.kernel_size;
- self.conv_update.encode(
- &self.conv_weight,
- self.conv_bias.as_ref(),
- in_proj,
- &mut layer.conv_state,
- kernel_size as u32,
- self.conv_dim as u32,
- (kernel_size - 1) as u32,
- encoder,
- );
- }
-
- fn run_conv_scan(
- &self,
- layer: &mut DeltaNetLayer<B>,
- in_proj: &mut Allocation<B>,
- encoder: &mut Encoder<B>,
- suffix_length: usize,
- ) -> Result<(), B::Error> {
- let kernel_size = self.kernel_size;
- let state_stride = kernel_size - 1;
- let conv_dim = self.conv_dim;
- let total_proj_dim = self.total_proj_dim;
- let mut padded =
- encoder.allocate_scratch(size_for_shape(&[suffix_length + state_stride, total_proj_dim], DataType::F32))?;
-
- self.conv_pack.encode(
- &layer.conv_state,
- &*in_proj,
- &mut padded,
- state_stride as u32,
- total_proj_dim as u32,
- suffix_length as u32,
- conv_dim as u32,
- encoder,
- );
-
- self.conv_scan.encode(
- &padded,
- &self.conv_weight,
- self.conv_bias.as_ref(),
- in_proj,
- &mut layer.conv_state,
- suffix_length as u32,
- kernel_size as u32,
- total_proj_dim as u32,
- state_stride as u32,
- conv_dim as u32,
- total_proj_dim as u32,
- encoder,
- );
- Ok(())
- }
-
- fn run_delta_rule(
- &self,
- layer: &mut DeltaNetLayer<B>,
- in_proj: &Allocation<B>,
- active_row_count: usize,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let mut out =
- encoder.allocate_scratch(size_for_shape(&[active_row_count, self.value_dim], self.outer_data_type))?;
- self.delta_net_update.encode(
- in_proj,
- &self.a_log,
- &self.dt_bias,
- &self.norm_weight,
- &mut layer.ssm_state,
- &mut out,
- self.num_heads as u32,
- self.num_groups as u32,
- self.value_head_dim as u32,
- self.key_dim as u32,
- self.value_dim as u32,
- self.norm_epsilon,
- encoder,
- );
- Ok(out)
- }
-
- fn run_delta_rule_prefill(
- &self,
- layer: &mut DeltaNetLayer<B>,
- in_proj: &Allocation<B>,
- suffix_length: usize,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let num_dv_groups = self.value_head_dim.div_ceil(16) as u32;
- let mut prep_q_norm =
- encoder.allocate_scratch(size_for_shape(&[suffix_length * self.key_dim], DataType::F32))?;
- let mut prep_k_norm =
- encoder.allocate_scratch(size_for_shape(&[suffix_length * self.key_dim], DataType::F32))?;
- let mut prep_beta =
- encoder.allocate_scratch(size_for_shape(&[suffix_length * self.num_heads], DataType::F32))?;
- let mut prep_decay =
- encoder.allocate_scratch(size_for_shape(&[suffix_length * self.num_heads], DataType::F32))?;
-
- self.prefill_prep.encode(
- in_proj,
- &self.a_log,
- &self.dt_bias,
- &mut prep_q_norm,
- &mut prep_k_norm,
- &mut prep_beta,
- &mut prep_decay,
- self.num_heads as u32,
- self.num_groups as u32,
- self.key_dim as u32,
- self.value_dim as u32,
- suffix_length as u32,
- encoder,
- );
-
- let mut out =
- encoder.allocate_scratch(size_for_shape(&[suffix_length, self.value_dim], self.outer_data_type))?;
- self.delta_net_prefill.encode(
- &prep_q_norm,
- &prep_k_norm,
- &prep_beta,
- &prep_decay,
- in_proj,
- &mut layer.ssm_state,
- &mut out,
- self.num_heads as u32,
- self.num_groups as u32,
- self.value_head_dim as u32,
- self.key_dim as u32,
- self.value_dim as u32,
- suffix_length as u32,
- num_dv_groups,
- encoder,
- );
-
- self.norm_gate.encode(
- &mut out,
- in_proj,
- &self.norm_weight,
- self.num_heads as u32,
- self.value_head_dim as u32,
- self.value_dim as u32,
- self.conv_dim as u32,
- self.total_proj_dim as u32,
- self.norm_epsilon,
- suffix_length as u32,
- encoder,
- );
- Ok(out)
- }
-
- pub fn encode(
- &self,
- args: DeltaNetArguments<B>,
- input: Allocation<B>,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let DeltaNetArguments {
- active_row_count,
- layer,
- } = args;
- assert!(active_row_count > 0, "DeltaNet mixer requires at least one active row");
-
- let mut in_proj = self.in_projection.encode(input, active_row_count, encoder)?;
-
- let delta_output = if active_row_count == 1 {
- self.run_conv_update(layer, &mut in_proj, encoder);
- self.run_delta_rule(layer, &in_proj, active_row_count, encoder)?
- } else {
- self.run_conv_scan(layer, &mut in_proj, encoder, active_row_count)?;
- self.run_delta_rule_prefill(layer, &in_proj, active_row_count, encoder)?
- };
-
- self.out_projection.encode(delta_output, active_row_count, encoder)
- }
-}
diff --git a/crates/backend-uzu/src/encodable_block/embedding.rs b/crates/backend-uzu/src/encodable_block/embedding.rs
index fddca9bec..51564462c 100644
--- a/crates/backend-uzu/src/encodable_block/embedding.rs
+++ b/crates/backend-uzu/src/encodable_block/embedding.rs
@@ -23,7 +23,6 @@ use crate::{
},
},
data_type::DataType,
- forward_pass::model_shape::ModelShape,
parameters::{ParameterLoaderError, ParameterTree},
};
@@ -114,6 +113,8 @@ struct LogitSoftCap<B: Backend> {
kernel: <B::Kernels as Kernels>::LogitSoftCapKernel,
}
+// TODO: embedding lookup dtype (u64) should match sampling (u32)
+
impl<B: Backend> Embedding<B> {
pub fn new(
context: &B::Context,
@@ -121,7 +122,7 @@ impl<B: Backend> Embedding<B> {
model_dim: u32,
config: &AnyEmbeddingConfig,
parameter_tree: &ParameterTree<B>,
- model_shape: &ModelShape,
+ data_type: DataType,
) -> Result<(Self, Option<Allocation<B>>), EmbeddingError<B>> {
let (tying, readout_input_hadamard_factors) = match config {
AnyEmbeddingConfig::TiedEmbeddingConfig(_) => {
@@ -135,21 +136,15 @@ impl<B: Backend> Embedding<B> {
}) => {
let weights = embedding_tree
.leaf("weights")?
- .validate(&[vocab_size as usize, model_dim as usize], model_shape.data_type)?
+ .validate(&[vocab_size as usize, model_dim as usize], data_type)?
.read_allocation()?;
- let lookup = <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(
- context,
- model_shape.data_type,
- )
- .map_err(EmbeddingError::BackendError)?;
- let readout_kernel = <B::Kernels as Kernels>::MatmulKernel::new(
- context,
- model_shape.data_type,
- model_shape.data_type,
- model_shape.data_type,
- )
- .map_err(EmbeddingError::BackendError)?;
+ let lookup =
+ <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(context, data_type)
+ .map_err(EmbeddingError::BackendError)?;
+ let readout_kernel =
+ <B::Kernels as Kernels>::MatmulKernel::new(context, data_type, data_type, data_type)
+ .map_err(EmbeddingError::BackendError)?;
let readout = RefCell::new(readout_kernel);
(
@@ -168,7 +163,7 @@ impl<B: Backend> Embedding<B> {
&embedding_tree,
vocab_size as usize,
model_dim as usize,
- model_shape.data_type,
+ data_type,
embedding_quantization_mode,
quantization_method,
group_size,
@@ -176,7 +171,7 @@ impl<B: Backend> Embedding<B> {
let lookup = <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel::new(
context,
- model_shape.data_type,
+ data_type,
group_size as u32,
embedding_quantization_mode,
quantization_method,
@@ -185,7 +180,7 @@ impl<B: Backend> Embedding<B> {
.map_err(EmbeddingError::BackendError)?;
let (readout, readout_config) = quantized_readout(
context,
- model_shape.data_type,
+ data_type,
embedding_quantization_mode,
quantization_method,
group_size,
@@ -219,7 +214,7 @@ impl<B: Backend> Embedding<B> {
&quantized_tree,
vocab_size as usize,
model_dim as usize,
- model_shape.data_type,
+ data_type,
embedding_quantization_mode,
quantization_method,
group_size,
@@ -240,7 +235,7 @@ impl<B: Backend> Embedding<B> {
);
let lookup = <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel::new(
context,
- model_shape.data_type,
+ data_type,
group_size as u32,
embedding_quantization_mode,
quantization_method,
@@ -249,7 +244,7 @@ impl<B: Backend> Embedding<B> {
.map_err(EmbeddingError::BackendError)?;
let (readout, readout_config) = quantized_readout(
context,
- model_shape.data_type,
+ data_type,
embedding_quantization_mode,
quantization_method,
group_size,
@@ -290,14 +285,12 @@ impl<B: Backend> Embedding<B> {
}) => {
let weights = input_embedding_tree
.leaf("weights")?
- .validate(&[vocab_size as usize, model_dim as usize], model_shape.data_type)?
+ .validate(&[vocab_size as usize, model_dim as usize], data_type)?
.read_allocation()?;
- let lookup = <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(
- context,
- model_shape.data_type,
- )
- .map_err(EmbeddingError::BackendError)?;
+ let lookup =
+ <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(context, data_type)
+ .map_err(EmbeddingError::BackendError)?;
UntiedEmbeddingLookupType::FullPrecision {
weights,
@@ -311,7 +304,7 @@ impl<B: Backend> Embedding<B> {
&input_embedding_tree,
vocab_size as usize,
model_dim as usize,
- model_shape.data_type,
+ data_type,
embedding_quantization_mode,
quantization_method,
group_size,
@@ -319,7 +312,7 @@ impl<B: Backend> Embedding<B> {
let lookup = <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel::new(
context,
- model_shape.data_type,
+ data_type,
group_size as u32,
embedding_quantization_mode,
quantization_method,
@@ -349,15 +342,11 @@ impl<B: Backend> Embedding<B> {
}) => {
let weights = output_embedding_tree
.leaf("weights")?
- .validate(&[vocab_size as usize, model_dim as usize], model_shape.data_type)?
+ .validate(&[vocab_size as usize, model_dim as usize], data_type)?
.read_allocation()?;
- let readout_kernel = <B::Kernels as Kernels>::MatmulKernel::new(
- context,
- model_shape.data_type,
- model_shape.data_type,
- model_shape.data_type,
- )
- .map_err(EmbeddingError::BackendError)?;
+ let readout_kernel =
+ <B::Kernels as Kernels>::MatmulKernel::new(context, data_type, data_type, data_type)
+ .map_err(EmbeddingError::BackendError)?;
let readout = RefCell::new(readout_kernel);
UntiedEmbeddingReadoutType::FullPrecision {
@@ -372,14 +361,14 @@ impl<B: Backend> Embedding<B> {
&output_embedding_tree,
vocab_size as usize,
model_dim as usize,
- model_shape.data_type,
+ data_type,
embedding_quantization_mode,
quantization_method,
group_size,
)?;
let (readout, readout_config) = quantized_readout(
context,
- model_shape.data_type,
+ data_type,
embedding_quantization_mode,
quantization_method,
group_size,
@@ -408,7 +397,7 @@ impl<B: Backend> Embedding<B> {
let input_scale = config.input_scale().unwrap_or(1.0);
let logit_soft_cap = if let Some(value) = *config.logit_soft_cap() {
- let kernel = <B::Kernels as Kernels>::LogitSoftCapKernel::new(context, model_shape.data_type)
+ let kernel = <B::Kernels as Kernels>::LogitSoftCapKernel::new(context, data_type)
.map_err(EmbeddingError::BackendError)?;
Some(LogitSoftCap {
value,
@@ -422,7 +411,7 @@ impl<B: Backend> Embedding<B> {
Self {
tying,
input_scale,
- data_type: model_shape.data_type,
+ data_type,
logit_soft_cap,
vocab_size,
model_dim,
@@ -555,7 +544,6 @@ impl<B: Backend> Embedding<B> {
b: MatmulB::FullPrecision {
b: weights,
},
- b_offset: 0,
b_leading_dimension: None,
b_transpose: true,
d: &mut output_allocation,
@@ -623,7 +611,6 @@ impl<B: Backend> Embedding<B> {
a: input_allocation,
a_offset: 0,
b,
- b_offset: 0,
b_leading_dimension: None,
b_transpose: true,
d: &mut output_allocation,
diff --git a/crates/backend-uzu/src/encodable_block/kv_cache_update.rs b/crates/backend-uzu/src/encodable_block/kv_cache_update.rs
deleted file mode 100644
index 6bfc30439..000000000
--- a/crates/backend-uzu/src/encodable_block/kv_cache_update.rs
+++ /dev/null
@@ -1,116 +0,0 @@
-use std::mem::size_of;
-
-use thiserror::Error;
-
-use crate::{
- backends::common::{Backend, Buffer, Encoder, Kernels, gpu_types::Swap, kernel::KVCacheUpdateKernel},
- data_type::DataType,
-};
-
-pub struct KVLayerData<'a, B: Backend, Buf: Buffer<Backend = B>> {
- pub key_buffer: &'a mut Buf,
- pub key_shape: [usize; 3],
- pub value_buffer: &'a mut Buf,
- pub value_shape: [usize; 3],
-}
-
-pub struct KVCacheUpdate<B: Backend> {
- kernel: <B::Kernels as Kernels>::KVCacheUpdateKernel,
- max_sequence_length: usize,
-}
-
-#[derive(Debug, Error)]
-pub enum KVCacheUpdateError<B: Backend> {
- #[error("Source and destination indices length mismatch")]
- IndicesCountMismatch,
- #[error("Shape mismatch between key and value tensors")]
- ShapeMismatch,
- #[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
- #[error("Swap count exceeds maximum sequence length")]
- MaxSequenceLengthExceeded,
-}
-
-impl<B: Backend> KVCacheUpdate<B> {
- pub fn new(
- context: &B::Context,
- data_type: DataType,
- max_sequence_length: usize,
- ) -> Result<Self, KVCacheUpdateError<B>> {
- let kernel = <B::Kernels as Kernels>::KVCacheUpdateKernel::new(context, data_type)
- .map_err(KVCacheUpdateError::BackendError)?;
-
- Ok(Self {
- kernel,
- max_sequence_length,
- })
- }
-
- /// Encode the KV cache update operation using a provided command buffer
- pub fn encode<Buf: Buffer<Backend = B>>(
- &self,
- in_place_data: &mut [KVLayerData<B, Buf>],
- source_indices: &[usize],
- destination_indices: &[usize],
- encoder: &mut Encoder<B>,
- ) -> Result<(), KVCacheUpdateError<B>> {
- if source_indices.len() != destination_indices.len() {
- return Err(KVCacheUpdateError::IndicesCountMismatch);
- }
-
- let swaps = create_swaps_direct(source_indices, destination_indices);
- if swaps.len() > self.max_sequence_length {
- return Err(KVCacheUpdateError::MaxSequenceLengthExceeded);
- }
- let max_inline_swaps = (B::MAX_INLINE_BYTES / size_of::<Swap>()).max(1);
-
- for layer_data in in_place_data {
- if layer_data.key_shape != layer_data.value_shape {
- return Err(KVCacheUpdateError::ShapeMismatch);
- }
-
- let [_, num_heads, head_dim] = layer_data.key_shape;
-
- // non-inline is not supported yet (and is broken anyways due to a data race)
- for swaps_chunk in swaps.chunks(max_inline_swaps) {
- self.kernel.encode(
- &mut *layer_data.key_buffer,
- &mut *layer_data.value_buffer,
- swaps_chunk,
- swaps_chunk.len() as u32,
- num_heads as u32,
- head_dim as u32,
- encoder,
- );
- }
- }
-
- Ok(())
- }
-}
-
-pub fn create_swaps_direct(
- source_indices: &[usize],
- destination_indices: &[usize],
-) -> Vec<Swap> {
- if source_indices.len() != destination_indices.len() {
- return Vec::new();
- }
-
- let mut swaps = Vec::with_capacity(source_indices.len());
-
- for (&src, &dst) in source_indices.iter().zip(destination_indices.iter()) {
- if src != dst {
- swaps.push(Swap {
- source: src as u32,
- destination: dst as u32,
- });
- }
- }
-
- swaps
-}
-
-#[cfg(test)]
-#[path = "../../unit/encodable_block/kv_cache_update_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/layer/executables.rs b/crates/backend-uzu/src/encodable_block/layer/executables.rs
deleted file mode 100644
index d39c3b135..000000000
--- a/crates/backend-uzu/src/encodable_block/layer/executables.rs
+++ /dev/null
@@ -1,478 +0,0 @@
-//! Layer executables - a single decoder layer with mixer, norms, and MLP.
-
-use std::rc::Rc;
-
-use thiserror::Error;
-
-use crate::{
- backends::common::{Allocation, Backend, Encoder},
- config::{
- token_mixer::AnyTokenMixerConfig, transformer::TransformerConfig, transformer_layer::TransformerLayerConfig,
- },
- data_type::DataType,
- encodable_block::{
- Attention, AttentionError, DeltaNetArguments, DeltaNetMixer, DeltaNetMixerError, MambaArguments, MambaMixer,
- MambaMixerError, Mlp, MlpBlockError, PerLayerEmbeddingProjection, PostLayerScalar, PrecalculatedRope, QkUnpack,
- RMSNorm, RMSNormError, Rope, ShortConvArguments, ShortConvMixer, ShortConvMixerError, layer::MixerExecutables,
- },
- forward_pass::cache_layers::LayerCacheAccess,
- parameters::{ParameterLoaderError, ParameterTree},
-};
-#[cfg(feature = "tracing")]
-use crate::{
- backends::common::{Kernels, kernel::TensorAddBiasKernel},
- forward_pass::traces::LayerActivationTrace,
-};
-
-#[derive(Debug, Error)]
-pub enum LayerExecutablesError<B: Backend> {
- #[cfg(feature = "tracing")]
- #[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
- #[error("Parameter loader error: {0}")]
- ParameterLoaderError(#[from] ParameterLoaderError<B>),
- #[error("Attention error: {0}")]
- AttentionError(#[from] AttentionError<B>),
- #[error("Mamba mixer error: {0}")]
- MambaMixerError(#[from] MambaMixerError<B>),
- #[error("ShortConv mixer error: {0}")]
- ShortConvMixerError(#[from] ShortConvMixerError<B>),
- #[error("DeltaNet mixer error: {0}")]
- DeltaNetMixerError(#[from] DeltaNetMixerError<B>),
- #[error("MLP error: {0}")]
- MlpBlockError(#[from] MlpBlockError<B>),
- #[error("RMSNorm error: {0}")]
- RMSNormError(#[from] RMSNormError<B>),
- #[error("layer {layer_index} sets post_layer_scalar but has no post_mlp_norm")]
- PostLayerScalarWithoutPostMlpNorm {
- layer_index: usize,
- },
- #[error("Unsupported post_layer_scalar data type: {data_type:?}")]
- UnsupportedPostLayerScalarDataType {
- data_type: DataType,
- },
- #[error(
- "layer {layer_index} AttentionConfig.is_kv_sharing={attention_is_kv_sharing} does not match kv_source_layer_index presence={has_kv_source_layer}"
- )]
- AttentionKvSharingMismatch {
- layer_index: usize,
- attention_is_kv_sharing: bool,
- has_kv_source_layer: bool,
- },
- #[error("decoder layers require pre_mixer_norm_config")]
- MissingPreMixerNormConfig,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum LayerRopeKind {
- NoKernel,
- Indexed(usize),
-}
-
-impl LayerRopeKind {
- pub fn get<B: Backend>(
- self,
- ropes: &[PrecalculatedRope<B>],
- ) -> Option<&PrecalculatedRope<B>> {
- match self {
- LayerRopeKind::NoKernel => None,
- LayerRopeKind::Indexed(index) => Some(&ropes[index]),
- }
- }
-}
-
-/// A single decoder layer with all its components.
-pub struct LayerExecutables<B: Backend> {
- pub layer_index: usize,
- pub rope_kind: LayerRopeKind,
- #[cfg(feature = "tracing")]
- pub tensor_add: <B::Kernels as Kernels>::TensorAddBiasKernel,
- pub pre_mixer_norm: RMSNorm<B>,
- mixer: MixerExecutables<B>,
- pub post_mixer_norm: Option<RMSNorm<B>>,
- pub pre_mlp_norm: RMSNorm<B>,
- pub mlp: Box<dyn Mlp<B>>,
- pub post_mlp_norm: Option<RMSNorm<B>>,
- pub ple_projection: Option<PerLayerEmbeddingProjection<B>>,
- #[cfg(feature = "tracing")]
- model_dim: usize,
-}
-
-impl<B: Backend> LayerExecutables<B> {
- pub fn new(
- context: &B::Context,
- transformer_config: &TransformerConfig,
- layer_config: &TransformerLayerConfig,
- layer_index: usize,
- rope_kind: LayerRopeKind,
- parameter_tree: &ParameterTree<B>,
- rope: &Rc<Rope<B>>,
- qk_unpack: &Rc<QkUnpack<B>>,
- data_type: DataType,
- ) -> Result<Self, LayerExecutablesError<B>> {
- let post_layer_scalar = if layer_config.has_post_layer_scalar {
- if layer_config.post_mlp_norm_config.is_none() {
- return Err(LayerExecutablesError::PostLayerScalarWithoutPostMlpNorm {
- layer_index,
- });
- }
- let leaf = parameter_tree.leaf("post_layer_scalar")?;
- let scalar = match data_type {
- DataType::F32 => leaf.validate(&[1], data_type)?.read_slice::<f32>()?[0],
- DataType::F16 => leaf.validate(&[1], data_type)?.read_slice::<half::f16>()?[0].to_f32(),
- DataType::BF16 => leaf.validate(&[1], data_type)?.read_slice::<half::bf16>()?[0].to_f32(),
- data_type => {
- return Err(LayerExecutablesError::UnsupportedPostLayerScalarDataType {
- data_type,
- });
- },
- };
- Some(scalar)
- } else {
- None
- };
-
- // When a PLE projection is present it owns the post-layer scalar (applied
- // to the combined residual), so the norms must not also apply it.
- let (residual_sum_scalar, output_scalar) = match (post_layer_scalar, layer_config.ple_config.is_none()) {
- (Some(scalar), true) => (PostLayerScalar::ScaleResidualSum(scalar), PostLayerScalar::ScaleOutput(scalar)),
- _ => (PostLayerScalar::None, PostLayerScalar::None),
- };
-
- #[cfg(feature = "tracing")]
- let tensor_add = TensorAddBiasKernel::new(context, data_type, data_type, false)
- .map_err(LayerExecutablesError::BackendError)?;
-
- let mixer_subtree = parameter_tree.subtree("mixer")?;
-
- let (mixer, mixer_hadamard_factors) = match &layer_config.mixer_config {
- AnyTokenMixerConfig::AttentionConfig(attention_config) => {
- let has_kv_source_layer = layer_config.kv_source_layer_index.is_some();
- if attention_config.is_kv_sharing != has_kv_source_layer {
- return Err(LayerExecutablesError::AttentionKvSharingMismatch {
- layer_index,
- attention_is_kv_sharing: attention_config.is_kv_sharing,
- has_kv_source_layer,
- });
- }
-
- let (attention, input_hadamard_factors) = Attention::new(
- context,
- transformer_config.model_dim,
- data_type,
- attention_config,
- &mixer_subtree,
- rope.clone(),
- qk_unpack.clone(),
- attention_config.gate_projection_config.is_none(),
- has_kv_source_layer,
- )?;
-
- (
- MixerExecutables::Attention {
- attention,
- },
- input_hadamard_factors,
- )
- },
- AnyTokenMixerConfig::Mamba2Config(mamba_config) => {
- let (mixer, input_hadamard_factors) =
- MambaMixer::new(context, mamba_config, transformer_config.model_dim, &mixer_subtree, data_type)?;
- (
- MixerExecutables::StateSpace {
- mixer,
- },
- input_hadamard_factors,
- )
- },
- AnyTokenMixerConfig::ShortConvConfig(short_conv_config) => {
- let (mixer, input_hadamard_factors) = ShortConvMixer::new(
- context,
- short_conv_config,
- transformer_config.model_dim,
- &mixer_subtree,
- data_type,
- )?;
- (
- MixerExecutables::ShortConv {
- mixer,
- },
- input_hadamard_factors,
- )
- },
- AnyTokenMixerConfig::DeltaNetConfig(delta_net_config) => {
- let (mixer, input_hadamard_factors) = DeltaNetMixer::new(
- context,
- delta_net_config,
- transformer_config.model_dim,
- &mixer_subtree,
- data_type,
- )?;
- (
- MixerExecutables::DeltaNet {
- mixer,
- },
- input_hadamard_factors,
- )
- },
- };
-
- let pre_mixer_norm = RMSNorm::new(
- context,
- data_type,
- transformer_config.model_dim,
- layer_config.pre_mixer_norm_config.clone().ok_or(LayerExecutablesError::MissingPreMixerNormConfig)?,
- &parameter_tree.subtree("pre_mixer_norm")?,
- mixer_hadamard_factors,
- true,
- layer_index > 0,
- PostLayerScalar::None,
- )?;
-
- let post_mixer_norm = if let Some(norm_config) = &layer_config.post_mixer_norm_config {
- Some(RMSNorm::new(
- context,
- data_type,
- transformer_config.model_dim,
- norm_config.clone(),
- &parameter_tree.subtree("post_mixer_norm")?,
- None,
- false,
- false,
- PostLayerScalar::None,
- )?)
- } else {
- None
- };
-
- let (mlp, mlp_input_hadamard_factors) = <dyn Mlp<B>>::new(
- &layer_config.mlp_config,
- transformer_config.model_dim,
- layer_config.hidden_dim.unwrap_or(transformer_config.hidden_dim),
- context,
- &parameter_tree.subtree("mlp")?,
- data_type,
- )?;
-
- let pre_mlp_norm = RMSNorm::new(
- context,
- data_type,
- transformer_config.model_dim,
- layer_config.pre_mlp_norm_config.clone(),
- &parameter_tree.subtree("pre_mlp_norm")?,
- mlp_input_hadamard_factors,
- true,
- true,
- residual_sum_scalar,
- )?;
-
- let post_mlp_norm = if let Some(norm_config) = &layer_config.post_mlp_norm_config {
- Some(RMSNorm::new(
- context,
- data_type,
- transformer_config.model_dim,
- norm_config.clone(),
- &parameter_tree.subtree("post_mlp_norm")?,
- None,
- false,
- false,
- output_scalar,
- )?)
- } else {
- None
- };
-
- let ple_projection = layer_config.ple_config.as_ref().map(|ple_config| {
- let ple_loader = parameter_tree.subtree("ple").expect("Failed to get ple subtree");
- PerLayerEmbeddingProjection::new(
- context,
- ple_config,
- transformer_config.model_dim,
- transformer_config.layer_configs.len(),
- post_layer_scalar.unwrap_or(1.0),
- data_type,
- &ple_loader,
- )
- .expect("Failed to create per-layer embedding projection")
- });
-
- Ok(Self {
- layer_index,
- rope_kind,
- #[cfg(feature = "tracing")]
- tensor_add,
- pre_mixer_norm,
- mixer,
- post_mixer_norm,
- pre_mlp_norm,
- mlp,
- post_mlp_norm,
- ple_projection,
- #[cfg(feature = "tracing")]
- model_dim: transformer_config.model_dim,
- })
- }
-
- pub fn encode(
- &self,
- args: LayerArguments<B>,
- input: Allocation<B>,
- shortcut: &mut Allocation<B>,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let LayerArguments {
- batch_dim,
- token_parents,
- token_subtrie_ranges,
- rope,
- per_layer_inputs,
- sampling_start,
- sampling_length,
- cache_access,
- #[cfg(feature = "tracing")]
- trace,
- } = args;
- #[cfg(feature = "tracing")]
- let mut layer_traces = trace;
-
- let mut hidden = self.pre_mixer_norm.encode(&input, 0, batch_dim, Some(shortcut), encoder)?;
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(shortcut, .., layer_traces.inputs.allocation_mut(), ..);
- encoder.encode_copy(&hidden, .., layer_traces.pre_attention_norm.allocation_mut(), ..);
- }
-
- hidden = match &self.mixer {
- MixerExecutables::Attention {
- attention,
- } => attention.encode(token_subtrie_ranges, rope, cache_access, hidden, batch_dim, encoder)?,
- MixerExecutables::StateSpace {
- mixer,
- } => {
- let Some(LayerCacheAccess::Owned {
- entry,
- }) = cache_access
- else {
- panic!("State-space layer requires writable cache state");
- };
- let layer = entry.as_state_space_mut().expect("State-space mixer expects SSM cache layer");
- mixer.encode(
- MambaArguments {
- active_row_count: batch_dim,
- layer,
- },
- hidden,
- encoder,
- )?
- },
- MixerExecutables::ShortConv {
- mixer,
- } => {
- let Some(LayerCacheAccess::Owned {
- entry,
- }) = cache_access
- else {
- panic!("ShortConv layer requires writable cache state");
- };
- let layer = entry.as_short_conv_mut().expect("ShortConv mixer expects ShortConv cache layer");
- mixer.encode(
- ShortConvArguments {
- active_row_count: batch_dim,
- sampling_start,
- sampling_length,
- token_parents,
- layer,
- },
- hidden,
- encoder,
- )?
- },
- MixerExecutables::DeltaNet {
- mixer,
- } => {
- let Some(LayerCacheAccess::Owned {
- entry,
- }) = cache_access
- else {
- panic!("DeltaNet layer requires writable cache state");
- };
- let layer = entry.as_delta_net_mut().expect("DeltaNet mixer expects DeltaNet cache layer");
- mixer.encode(
- DeltaNetArguments {
- active_row_count: batch_dim,
- layer,
- },
- hidden,
- encoder,
- )?
- },
- };
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(&hidden, .., layer_traces.attention.allocation_mut(), ..);
- }
-
- if let Some(post_mixer_norm) = &self.post_mixer_norm {
- hidden = post_mixer_norm.encode(&hidden, 0, batch_dim, None, encoder)?;
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(&hidden, .., layer_traces.post_attention_norm.allocation_mut(), ..);
- }
- }
-
- hidden = self.pre_mlp_norm.encode(&hidden, 0, batch_dim, Some(shortcut), encoder)?;
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(shortcut, .., layer_traces.mlp_inputs.allocation_mut(), ..);
- encoder.encode_copy(&hidden, .., layer_traces.pre_mlp_norm.allocation_mut(), ..);
- }
-
- hidden = self.mlp.encode(hidden, batch_dim, encoder)?;
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(&hidden, .., layer_traces.mlp.allocation_mut(), ..);
- }
-
- if let Some(post_mlp_norm) = &self.post_mlp_norm {
- hidden = post_mlp_norm.encode(&hidden, 0, batch_dim, None, encoder)?;
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces.as_deref_mut() {
- encoder.encode_copy(&hidden, .., layer_traces.post_mlp_norm.allocation_mut(), ..);
- }
- }
-
- if let Some(ple_projection) = &self.ple_projection {
- let per_layer_inputs = per_layer_inputs.expect("per-layer inputs required for PLE layer");
- ple_projection.encode(self.layer_index, per_layer_inputs, shortcut, &hidden, batch_dim, encoder)?;
- encoder.encode_fill(&mut hidden, 0);
- }
-
- #[cfg(feature = "tracing")]
- if let Some(layer_traces) = layer_traces {
- let size = (batch_dim * self.model_dim) as u32;
- self.tensor_add.encode(
- Some(&hidden),
- &*shortcut,
- layer_traces.outputs.allocation_mut(),
- size,
- size,
- encoder,
- );
- }
-
- Ok(hidden)
- }
-}
-
-pub struct LayerArguments<'a, B: Backend> {
- pub batch_dim: usize,
- pub token_parents: &'a Allocation<B>,
- pub token_subtrie_ranges: Option<&'a Allocation<B>>,
- pub rope: Option<&'a PrecalculatedRope<B>>,
- pub per_layer_inputs: Option<&'a Allocation<B>>,
- pub sampling_start: usize,
- pub sampling_length: usize,
- pub cache_access: Option<LayerCacheAccess<'a, B>>,
- #[cfg(feature = "tracing")]
- pub trace: Option<&'a mut LayerActivationTrace<B>>,
-}
diff --git a/crates/backend-uzu/src/encodable_block/layer/mixer.rs b/crates/backend-uzu/src/encodable_block/layer/mixer.rs
deleted file mode 100644
index 5c8b412c9..000000000
--- a/crates/backend-uzu/src/encodable_block/layer/mixer.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-//! Mixer component - either attention or state space.
-
-use crate::{
- backends::common::Backend,
- encodable_block::{Attention, DeltaNetMixer, MambaMixer, ShortConvMixer},
-};
-
-/// Mixer component - either attention, state space, short conv, or delta net.
-pub enum MixerExecutables<B: Backend> {
- Attention {
- attention: Attention<B>,
- },
- StateSpace {
- mixer: MambaMixer<B>,
- },
- ShortConv {
- mixer: ShortConvMixer<B>,
- },
- DeltaNet {
- mixer: DeltaNetMixer<B>,
- },
-}
diff --git a/crates/backend-uzu/src/encodable_block/layer/mod.rs b/crates/backend-uzu/src/encodable_block/layer/mod.rs
deleted file mode 100644
index a7949b2b8..000000000
--- a/crates/backend-uzu/src/encodable_block/layer/mod.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-//! Layer executables module.
-
-mod executables;
-mod mixer;
-
-pub use executables::{LayerArguments, LayerExecutables, LayerExecutablesError, LayerRopeKind};
-use mixer::MixerExecutables;
diff --git a/crates/backend-uzu/src/encodable_block/layer_norm.rs b/crates/backend-uzu/src/encodable_block/layer_norm.rs
deleted file mode 100644
index 63ffb204b..000000000
--- a/crates/backend-uzu/src/encodable_block/layer_norm.rs
+++ /dev/null
@@ -1,95 +0,0 @@
-//! LayerNorm encodable.
-
-use thiserror::Error;
-
-use crate::{
- array::size_for_shape,
- backends::common::{
- Allocation, Backend, Encoder,
- kernel::{Kernels, LayerNormKernel},
- },
- config::normalization::{NormalizationConfig, UpcastMode},
- data_type::DataType,
- parameters::{ParameterLoaderError, ParameterTree},
-};
-
-#[derive(Debug, Error)]
-pub enum LayerNormError<B: Backend> {
- #[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
- #[error("Parameter loading error: {0}")]
- ParameterError(#[from] ParameterLoaderError<B>),
-}
-
-pub struct LayerNorm<B: Backend> {
- kernel: <B::Kernels as Kernels>::LayerNormKernel,
- config: NormalizationConfig,
- scales: Allocation<B>,
- element_count: usize,
- input_data_type: DataType,
- output_data_type: DataType,
-}
-
-impl<B: Backend> LayerNorm<B> {
- pub fn new(
- context: &B::Context,
- intermediate_data_type: DataType,
- element_count: usize,
- config: NormalizationConfig,
- parameter_tree: &ParameterTree<B>,
- ) -> Result<Self, LayerNormError<B>> {
- let scale_data_type = super::normalization::NORMALIZATION_SCALE_DATA_TYPE;
- let scales = parameter_tree.leaf("scales")?.validate(&[element_count], scale_data_type)?.read_allocation()?;
-
- let accumulation_data_type = super::normalization::NORMALIZATION_ACCUMULATION_DATA_TYPE;
- let output_data_type = intermediate_data_type;
- let kernel = <B::Kernels as Kernels>::LayerNormKernel::new(
- context,
- intermediate_data_type,
- scale_data_type,
- output_data_type,
- accumulation_data_type,
- false,
- )
- .map_err(LayerNormError::BackendError)?;
-
- Ok(Self {
- kernel,
- config,
- scales,
- element_count,
- input_data_type: intermediate_data_type,
- output_data_type,
- })
- }
-
- pub fn encode(
- &self,
- input: &Allocation<B>,
- row_offset: usize,
- row_count: usize,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let full_layer = if self.config.upcast_mode == UpcastMode::FullLayer {
- 1u32
- } else {
- 0u32
- };
- let row_size = self.element_count * self.input_data_type.size_in_bytes();
- let input_offset = row_offset * row_size;
- let mut output =
- encoder.allocate_scratch(size_for_shape(&[row_count, self.element_count], self.output_data_type))?;
- self.kernel.encode(
- Some((input, input_offset)),
- &self.scales,
- &mut output,
- row_count as u32,
- self.element_count as u32,
- self.config.epsilon,
- self.config.scale_offset.unwrap_or(0.0),
- full_layer,
- encoder,
- );
- Ok(output)
- }
-}
diff --git a/crates/backend-uzu/src/encodable_block/linear/matmul.rs b/crates/backend-uzu/src/encodable_block/linear/matmul.rs
index 779e04071..2960e5fad 100644
--- a/crates/backend-uzu/src/encodable_block/linear/matmul.rs
+++ b/crates/backend-uzu/src/encodable_block/linear/matmul.rs
@@ -2,7 +2,6 @@ use std::cell::RefCell;
use thiserror::Error;
-use super::Linear;
use crate::{
array::size_for_shape,
backends::common::{
@@ -15,6 +14,7 @@ use crate::{
},
config::weight_matrix::{AnyWeightMatrixSpec, Layout, int_spec::IntSpec, mlx_spec::MLXSpec},
data_type::DataType,
+ encodable_block::linear::Linear,
parameters::{ParameterLoaderError, ParameterTree},
};
@@ -275,7 +275,6 @@ impl<B: Backend> Linear<B> for LinearMatmul<B> {
a: &input,
a_offset: 0,
b,
- b_offset: 0,
b_leading_dimension: None,
b_transpose: true,
d: &mut output,
diff --git a/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs b/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs
index eae82b9ff..41475d5ec 100644
--- a/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs
+++ b/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs
@@ -14,10 +14,7 @@ use crate::{
},
config::weight_matrix::{AnyWeightMatrixSpec, hybrid_spec::IncoherenceProcessingMode, low_rank_spec::LowRankSpec},
data_type::DataType,
- encodable_block::{
- Linear,
- linear::{LinearMatmul, LinearMatmulError},
- },
+ encodable_block::linear::{Linear, LinearMatmul, LinearMatmulError},
parameters::{ParameterLoaderError, ParameterTree},
};
@@ -184,7 +181,6 @@ impl<B: Backend> Linear<B> for QLoRALinearWrapper<B> {
b: MatmulB::FullPrecision {
b: &self.adapter_down,
},
- b_offset: 0,
b_leading_dimension: None,
b_transpose: true,
d: &mut intermediate,
@@ -224,7 +220,6 @@ impl<B: Backend> Linear<B> for QLoRALinearWrapper<B> {
b: MatmulB::FullPrecision {
b: &self.adapter_up,
},
- b_offset: 0,
b_leading_dimension: None,
b_transpose: true,
d: &mut output,
diff --git a/crates/backend-uzu/src/encodable_block/linear/rht_wrapper.rs b/crates/backend-uzu/src/encodable_block/linear/rht_wrapper.rs
index 7224bbb84..5348feadf 100644
--- a/crates/backend-uzu/src/encodable_block/linear/rht_wrapper.rs
+++ b/crates/backend-uzu/src/encodable_block/linear/rht_wrapper.rs
@@ -1,6 +1,5 @@
use thiserror::Error;
-use super::{Linear, OutputHadamardLinearError};
use crate::{
backends::common::{
Allocation, Backend, Encoder,
@@ -12,6 +11,7 @@ use crate::{
hybrid_spec::{HybridSpec, IncoherenceProcessingMode},
},
data_type::DataType,
+ encodable_block::linear::{Linear, OutputHadamardLinearError},
parameters::{ParameterLoaderError, ParameterTree},
};
diff --git a/crates/backend-uzu/src/encodable_block/mamba_mixer/mod.rs b/crates/backend-uzu/src/encodable_block/mamba_mixer/mod.rs
deleted file mode 100644
index 5497d7b4d..000000000
--- a/crates/backend-uzu/src/encodable_block/mamba_mixer/mod.rs
+++ /dev/null
@@ -1,439 +0,0 @@
-//! Mamba2 SSM mixer encodable.
-
-mod ssd_prefill;
-
-use std::env;
-
-use ssd_prefill::{SSDPrefillArguments, SSDPrefillBlock, SSDPrefillMode};
-use thiserror::Error;
-
-use crate::{
- array::size_for_shape,
- backends::common::{
- Allocation, Backend, Encoder, Kernels,
- gpu_types::ActivationType,
- kernel::{Conv1dDecodeKernel, Conv1dPackKernel, Conv1dScanKernel, SSDUpdateKernel, SplitInProjKernel},
- },
- config::token_mixer::mamba2::Mamba2Config,
- data_type::DataType,
- encodable_block::linear::{Linear, LinearBlockError},
- forward_pass::ssm_layer::SSMLayer,
- parameters::{ParameterLoaderError, ParameterTree},
-};
-
-#[derive(Debug, Error)]
-pub enum MambaMixerError<B: Backend> {
- #[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
- #[error("Linear error: {0}")]
- LinearError(#[from] LinearBlockError<B>),
- #[error("Parameter loader error: {0}")]
- ParameterLoaderError(#[from] ParameterLoaderError<B>),
-}
-
-pub struct MambaMixer<B: Backend> {
- conv_dim: usize,
- inner_dim: usize,
- num_heads: usize,
- num_groups: usize,
- head_dim: usize,
- state_dim: usize,
- kernel_size: usize,
- activation_type: ActivationType,
- in_projection: Box<dyn Linear<B>>,
- out_projection: Box<dyn Linear<B>>,
- split_inproj: <B::Kernels as Kernels>::SplitInProjKernel,
- conv_decode: <B::Kernels as Kernels>::Conv1dDecodeKernel,
- conv_pack: <B::Kernels as Kernels>::Conv1dPackKernel,
- conv_scan: <B::Kernels as Kernels>::Conv1dScanKernel,
- ssd_prefill: SSDPrefillBlock<B>,
- ssd_update: <B::Kernels as Kernels>::SSDUpdateKernel,
- conv_weight: Allocation<B>,
- conv_bias: Option<Allocation<B>>,
- gate_bias: Allocation<B>,
- skip_connection_weight: Allocation<B>,
- prefill_mode: SSDPrefillMode,
- inner_data_type: DataType,
-}
-
-pub struct MambaArguments<'a, B: Backend> {
- pub active_row_count: usize,
- pub layer: &'a mut SSMLayer<B>,
-}
-
-struct SplitInProjectionOutput<B: Backend> {
- conv_inputs: Allocation<B>,
- gate: Allocation<B>,
- time_step: Allocation<B>,
-}
-
-struct ConvScanOutput<B: Backend> {
- conv_x: Allocation<B>,
- state_b: Allocation<B>,
- state_c: Allocation<B>,
-}
-
-fn resolve_prefill_mode_from_env() -> SSDPrefillMode {
- match env::var("UZU_SSM_PREFILL_MODE") {
- Ok(value) => match value.trim().to_ascii_lowercase().as_str() {
- "seq" | "sequential" | "baseline" => SSDPrefillMode::Sequential,
- "single" | "singlepass" | "single_pass" => SSDPrefillMode::SinglePass,
- _ => SSDPrefillMode::SinglePass,
- },
- Err(_) => SSDPrefillMode::SinglePass,
- }
-}
-
-impl<B: Backend> MambaMixer<B> {
- pub fn new(
- context: &B::Context,
- mamba_config: &Mamba2Config,
- model_dim: usize,
- parameter_tree: &ParameterTree<B>,
- outer_data_type: DataType,
- ) -> Result<(Self, Option<Allocation<B>>), MambaMixerError<B>> {
- let inner_data_type = DataType::F32;
-
- let conv_tree = parameter_tree.subtree("conv")?;
- let conv_dim = mamba_config.conv_dim();
- let inner_dim = mamba_config.inner_dim();
-
- let (in_projection, in_projection_input_hadamard_factors) =
- <dyn Linear<B>>::new_extracting_input_hadamard_mixed_precision(
- model_dim,
- [conv_dim, inner_dim, mamba_config.num_heads],
- mamba_config.has_in_biases,
- context,
- outer_data_type,
- outer_data_type,
- inner_data_type,
- &parameter_tree.subtree("in_projection")?,
- )?;
-
- let out_projection = <dyn Linear<B>>::new_mixed_precision(
- inner_dim,
- [model_dim],
- mamba_config.has_out_biases,
- context,
- outer_data_type,
- inner_data_type,
- outer_data_type,
- &parameter_tree.subtree("out_projection")?,
- )?;
-
- let conv_weight = conv_tree
- .leaf("weights")?
- .validate(&[conv_dim, mamba_config.kernel_size], inner_data_type)?
- .read_allocation()?;
- let conv_bias = if mamba_config.conv_config.has_biases {
- Some(conv_tree.leaf("biases")?.validate(&[conv_dim], inner_data_type)?.read_allocation()?)
- } else {
- None
- };
- let gate_bias = parameter_tree.leaf("gate_bias")?.validate(&[inner_dim], inner_data_type)?.read_allocation()?;
- let skip_connection_weight = parameter_tree
- .leaf("skip_connection_weight")?
- .validate(&[mamba_config.num_heads], inner_data_type)?
- .read_allocation()?;
-
- let split_inproj = <B::Kernels as Kernels>::SplitInProjKernel::new(context, inner_data_type)
- .map_err(MambaMixerError::BackendError)?;
- let conv_scan = <B::Kernels as Kernels>::Conv1dScanKernel::new(
- context,
- inner_data_type,
- mamba_config.conv_config.has_biases,
- )
- .map_err(MambaMixerError::BackendError)?;
- let conv_decode = <B::Kernels as Kernels>::Conv1dDecodeKernel::new(
- context,
- inner_data_type,
- mamba_config.conv_config.has_biases,
- true,
- )
- .map_err(MambaMixerError::BackendError)?;
- let conv_pack = <B::Kernels as Kernels>::Conv1dPackKernel::new(context, inner_data_type, inner_data_type)
- .map_err(MambaMixerError::BackendError)?;
- let ssd_prefill = SSDPrefillBlock::new(context, inner_data_type).map_err(MambaMixerError::BackendError)?;
- let ssd_update = <B::Kernels as Kernels>::SSDUpdateKernel::new(context, inner_data_type, true)
- .map_err(MambaMixerError::BackendError)?;
- let prefill_mode = resolve_prefill_mode_from_env();
-
- Ok((
- Self {
- conv_dim,
- inner_dim,
- num_heads: mamba_config.num_heads,
- num_groups: mamba_config.num_groups,
- head_dim: mamba_config.head_dim,
- state_dim: mamba_config.state_dim,
- kernel_size: mamba_config.kernel_size,
- activation_type: mamba_config.activation.act_type(),
- in_projection,
- out_projection,
- split_inproj,
- conv_decode,
- conv_pack,
- conv_scan,
- ssd_prefill,
- ssd_update,
- conv_weight,
- conv_bias,
- gate_bias,
- skip_connection_weight,
- prefill_mode,
- inner_data_type,
- },
- in_projection_input_hadamard_factors,
- ))
- }
-
- fn run_split_inproj(
- &self,
- in_proj: &Allocation<B>,
- suffix_length: usize,
- encoder: &mut Encoder<B>,
- ) -> Result<SplitInProjectionOutput<B>, B::Error> {
- let conv_dim = self.conv_dim;
- let inner_dim = self.inner_dim;
- let num_heads = self.num_heads;
- let total_dim = conv_dim + inner_dim + num_heads;
- let mut conv_inputs =
- encoder.allocate_scratch(size_for_shape(&[suffix_length, conv_dim], self.inner_data_type))?;
- let mut gate = encoder
- .allocate_scratch(size_for_shape(&[suffix_length, num_heads, self.head_dim], self.inner_data_type))?;
- let mut time_step =
- encoder.allocate_scratch(size_for_shape(&[suffix_length, num_heads], self.inner_data_type))?;
- self.split_inproj.encode(
- in_proj,
- &mut conv_inputs,
- &mut gate,
- &mut time_step,
- &self.gate_bias,
- suffix_length as u32,
- total_dim as u32,
- conv_dim as u32,
- inner_dim as u32,
- num_heads as u32,
- encoder,
- );
- Ok(SplitInProjectionOutput {
- conv_inputs,
- gate,
- time_step,
- })
- }
-
- fn run_conv_scan(
- &self,
- layer: &mut SSMLayer<B>,
- conv_inputs: &Allocation<B>,
- encoder: &mut Encoder<B>,
- suffix_length: usize,
- ) -> Result<ConvScanOutput<B>, B::Error> {
- let conv_dim = self.conv_dim;
- let inner_dim = self.inner_dim;
- let proj_dim = self.num_groups * self.state_dim;
- let state_stride = self.kernel_size.saturating_sub(1);
- let mut conv_x = encoder
- .allocate_scratch(size_for_shape(&[suffix_length, self.num_heads, self.head_dim], self.inner_data_type))?;
- let state_shape = [suffix_length, self.num_groups, self.state_dim];
- let mut state_b = encoder.allocate_scratch(size_for_shape(&state_shape, self.inner_data_type))?;
- let mut state_c = encoder.allocate_scratch(size_for_shape(&state_shape, self.inner_data_type))?;
-
- if suffix_length == 1 {
- if conv_dim > 0 && self.kernel_size > 0 {
- let next_state = layer.conv_state.as_mut().unwrap_or(&mut layer.ssm_state);
- self.conv_decode.encode(
- conv_inputs,
- &self.conv_weight,
- self.conv_bias.as_ref(),
- None::<&Allocation<B>>,
- &mut conv_x,
- &mut state_b,
- &mut state_c,
- next_state,
- self.kernel_size as u32,
- conv_dim as u32,
- state_stride as u32,
- conv_dim as u32,
- suffix_length as u32,
- inner_dim as u32,
- proj_dim as u32,
- self.activation_type,
- encoder,
- );
- }
- } else {
- let mut padded = (conv_dim > 0 && state_stride > 0)
- .then(|| {
- encoder.allocate_scratch(size_for_shape(
- &[suffix_length + state_stride, conv_dim],
- self.inner_data_type,
- ))
- })
- .transpose()?;
- if let Some(padded) = padded.as_mut() {
- let state_in = layer.conv_state.as_ref().unwrap_or(conv_inputs);
- self.conv_pack.encode(
- state_in,
- conv_inputs,
- padded,
- state_stride as u32,
- conv_dim as u32,
- suffix_length as u32,
- conv_dim as u32,
- encoder,
- );
- }
-
- if conv_dim > 0 && self.kernel_size > 0 {
- let conv_source = match &padded {
- Some(padded) => padded,
- None => conv_inputs,
- };
- let next_state = layer.conv_state.as_mut().unwrap_or(&mut layer.ssm_state);
- self.conv_scan.encode(
- conv_source,
- &self.conv_weight,
- self.conv_bias.as_ref(),
- &mut conv_x,
- &mut state_b,
- &mut state_c,
- next_state,
- suffix_length as u32,
- self.kernel_size as u32,
- conv_dim as u32,
- state_stride as u32,
- conv_dim as u32,
- inner_dim as u32,
- proj_dim as u32,
- self.activation_type,
- encoder,
- );
- }
- }
- Ok(ConvScanOutput {
- conv_x,
- state_b,
- state_c,
- })
- }
-
- fn run_prefill_ssm(
- &self,
- layer: &mut SSMLayer<B>,
- conv_x: &Allocation<B>,
- state_b: &Allocation<B>,
- state_c: &Allocation<B>,
- time_step: &Allocation<B>,
- gate: &Allocation<B>,
- encoder: &mut Encoder<B>,
- suffix_length: usize,
- ) -> Result<Allocation<B>, B::Error> {
- self.ssd_prefill.encode(
- encoder,
- SSDPrefillArguments {
- x: conv_x,
- dt: time_step,
- b: state_b,
- c: state_c,
- d: &self.skip_connection_weight,
- z: gate,
- state: &mut layer.ssm_state,
- suffix_len: suffix_length,
- group_size: (self.num_heads / self.num_groups) as u32,
- state_size: self.state_dim as u32,
- x_strides: [self.num_heads * self.head_dim, self.head_dim, 1],
- dt_strides: [self.num_heads, 1],
- cb_strides: [self.num_groups * self.state_dim, self.state_dim, 1],
- state_strides: [self.head_dim * self.state_dim, self.state_dim, 1],
- channels: self.num_heads,
- head_dim: self.head_dim,
- },
- self.prefill_mode,
- )
- }
-
- fn run_decode_ssm(
- &self,
- layer: &mut SSMLayer<B>,
- conv_x: &Allocation<B>,
- state_b: &Allocation<B>,
- state_c: &Allocation<B>,
- time_step: &Allocation<B>,
- gate: &Allocation<B>,
- encoder: &mut Encoder<B>,
- suffix_length: usize,
- ) -> Result<Allocation<B>, B::Error> {
- let mut out =
- encoder.allocate_scratch(size_for_shape(&[suffix_length, self.inner_dim], self.inner_data_type))?;
- let h = self.num_heads as u32;
- let g = self.num_groups as u32;
- let dh = self.head_dim as u32;
- let n = self.state_dim as u32;
-
- let x_strides = [h * dh, dh, 1u32];
- let dt_strides = [h, 1u32];
- let cb_strides = [g * n, n, 1u32];
- let state_strides = [h * dh * n, dh * n, n, 1u32];
- let group_size = (h / g) as i32;
- let state_size = n as i32;
-
- self.ssd_update.encode(
- conv_x,
- time_step,
- state_b,
- state_c,
- &self.skip_connection_weight,
- gate,
- None::<&Allocation<B>>,
- &mut out,
- &mut layer.ssm_state,
- group_size as u32,
- state_size as u32,
- &x_strides,
- &dt_strides,
- &cb_strides,
- &state_strides,
- suffix_length as u32,
- h,
- dh,
- encoder,
- );
- Ok(out)
- }
-
- pub fn encode(
- &self,
- args: MambaArguments<B>,
- input: Allocation<B>,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let MambaArguments {
- active_row_count,
- layer,
- } = args;
- assert!(active_row_count > 0, "Mamba mixer requires at least one active row");
-
- let in_proj = self.in_projection.encode(input, active_row_count, encoder)?;
- let SplitInProjectionOutput {
- conv_inputs,
- gate,
- time_step,
- } = self.run_split_inproj(&in_proj, active_row_count, encoder)?;
- let ConvScanOutput {
- conv_x,
- state_b,
- state_c,
- } = self.run_conv_scan(layer, &conv_inputs, encoder, active_row_count)?;
- if active_row_count == 1 {
- let ssm_output =
- self.run_decode_ssm(layer, &conv_x, &state_b, &state_c, &time_step, &gate, encoder, active_row_count)?;
- self.out_projection.encode(ssm_output, active_row_count, encoder)
- } else {
- let ssm_output =
- self.run_prefill_ssm(layer, &conv_x, &state_b, &state_c, &time_step, &gate, encoder, active_row_count)?;
- self.out_projection.encode(ssm_output, active_row_count, encoder)
- }
- }
-}
diff --git a/crates/backend-uzu/src/encodable_block/mamba_mixer/ssd_prefill.rs b/crates/backend-uzu/src/encodable_block/mamba_mixer/ssd_prefill.rs
deleted file mode 100644
index c7ab33e66..000000000
--- a/crates/backend-uzu/src/encodable_block/mamba_mixer/ssd_prefill.rs
+++ /dev/null
@@ -1,143 +0,0 @@
-use crate::{
- array::size_for_shape,
- backends::common::{
- Allocation, Backend, Encoder, Kernels,
- kernel::{SSDPrefill64Kernel, SSDPrefillKernel, SSDPrefillSequentialKernel},
- },
- data_type::DataType,
-};
-
-#[derive(Copy, Clone, Debug, PartialEq, Eq)]
-pub enum SSDPrefillMode {
- Sequential,
- SinglePass,
-}
-
-pub struct SSDPrefillArguments<'a, B: Backend> {
- pub x: &'a Allocation<B>,
- pub dt: &'a Allocation<B>,
- pub b: &'a Allocation<B>,
- pub c: &'a Allocation<B>,
- pub d: &'a Allocation<B>,
- pub z: &'a Allocation<B>,
- pub state: &'a mut Allocation<B>,
- pub suffix_len: usize,
- pub group_size: u32,
- pub state_size: u32,
- pub x_strides: [usize; 3],
- pub dt_strides: [usize; 2],
- pub cb_strides: [usize; 3],
- pub state_strides: [usize; 3],
- pub channels: usize,
- pub head_dim: usize,
-}
-
-pub struct SSDPrefillBlock<B: Backend> {
- single: <B::Kernels as Kernels>::SSDPrefillKernel,
- single_64: <B::Kernels as Kernels>::SSDPrefill64Kernel,
- sequential: <B::Kernels as Kernels>::SSDPrefillSequentialKernel,
- data_type: DataType,
-}
-
-impl<B: Backend> SSDPrefillBlock<B> {
- pub fn new(
- context: &B::Context,
- data_type: DataType,
- ) -> Result<Self, B::Error> {
- let single = <B::Kernels as Kernels>::SSDPrefillKernel::new(context, data_type)?;
- let single_64 = <B::Kernels as Kernels>::SSDPrefill64Kernel::new(context, data_type)?;
- let sequential = <B::Kernels as Kernels>::SSDPrefillSequentialKernel::new(context, data_type)?;
- Ok(Self {
- single,
- single_64,
- sequential,
- data_type,
- })
- }
-
- pub fn encode(
- &self,
- encoder: &mut Encoder<B>,
- args: SSDPrefillArguments<B>,
- mode: SSDPrefillMode,
- ) -> Result<Allocation<B>, B::Error> {
- let x_strides: [u32; 3] = args.x_strides.map(|x| x as u32);
- let dt_strides: [u32; 2] = args.dt_strides.map(|x| x as u32);
- let cb_strides: [u32; 3] = args.cb_strides.map(|x| x as u32);
- let state_strides: [u32; 3] = args.state_strides.map(|x| x as u32);
- let mut output = encoder
- .allocate_scratch(size_for_shape(&[args.suffix_len, args.channels * args.head_dim], self.data_type))?;
-
- if mode == SSDPrefillMode::SinglePass {
- if args.state_size == 64 {
- self.single_64.encode(
- args.x,
- args.dt,
- args.b,
- args.c,
- args.d,
- args.z,
- args.state,
- &mut output,
- args.suffix_len as u32,
- args.group_size,
- args.state_size,
- &x_strides,
- &dt_strides,
- &cb_strides,
- &state_strides,
- args.channels as u32,
- args.head_dim as u32,
- encoder,
- )
- } else {
- self.single.encode(
- args.x,
- args.dt,
- args.b,
- args.c,
- args.d,
- args.z,
- args.state,
- &mut output,
- args.suffix_len as u32,
- args.group_size,
- args.state_size,
- &x_strides,
- &dt_strides,
- &cb_strides,
- &state_strides,
- args.channels as u32,
- args.head_dim as u32,
- encoder,
- )
- }
- } else if mode == SSDPrefillMode::Sequential {
- self.sequential.encode(
- args.x,
- args.dt,
- args.b,
- args.c,
- args.d,
- args.z,
- args.state,
- &mut output,
- args.suffix_len as u32,
- args.group_size,
- args.state_size,
- &x_strides,
- &dt_strides,
- &cb_strides,
- &state_strides,
- args.channels as u32,
- args.head_dim as u32,
- encoder,
- )
- }
- Ok(output)
- }
-}
-
-#[cfg(test)]
-#[path = "../../../unit/encodable_block/mamba_mixer/ssd_prefill_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/core/fallback.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/core/fallback.rs
new file mode 100644
index 000000000..a6f7691c4
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/core/fallback.rs
@@ -0,0 +1,174 @@
+use std::cell::RefCell;
+
+use crate::{
+ array::size_for_shape,
+ backends::common::{
+ Allocation, Backend, Encoder, Kernels,
+ kernel::{
+ AttentionFallbackScatterScoresKernel, AttentionFallbackScatterValuesKernel, BufferArg, SoftmaxKernel,
+ matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},
+ },
+ },
+ data_type::DataType,
+ encodable_block::mixer::attention::core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments},
+};
+
+pub struct AttentionFallbackCore<B: Backend> {
+ head_dim: usize,
+ num_groups: usize,
+ num_q_heads: usize,
+ sliding_window_size: Option<usize>,
+ scale: Option<f32>,
+ data_type: DataType,
+ scatter_scores: <B::Kernels as Kernels>::AttentionFallbackScatterScoresKernel,
+ scatter_values: <B::Kernels as Kernels>::AttentionFallbackScatterValuesKernel,
+ softmax: <B::Kernels as Kernels>::SoftmaxKernel,
+ matmul: RefCell<<B::Kernels as Kernels>::MatmulKernel>,
+}
+
+impl<B: Backend> AttentionFallbackCore<B> {
+ pub fn new(
+ arguments: &AttentionCoreNewArguments,
+ context: &B::Context,
+ ) -> Result<Self, B::Error> {
+ assert!(!arguments.is_trie, "trie not supported by attention fallback"); // Is it?
+
+ let scatter_scores = <B::Kernels as Kernels>::AttentionFallbackScatterScoresKernel::new(
+ context,
+ arguments.data_type,
+ arguments.is_kv_cache_ring,
+ arguments.is_causal,
+ arguments.is_trie,
+ arguments.sliding_window_size.is_some(),
+ )?;
+ let scatter_values =
+ <B::Kernels as Kernels>::AttentionFallbackScatterValuesKernel::new(context, arguments.data_type)?;
+ let softmax = <B::Kernels as Kernels>::SoftmaxKernel::new(context, arguments.data_type, arguments.has_sinks)?;
+ let matmul = RefCell::new(<B::Kernels as Kernels>::MatmulKernel::new(
+ context,
+ arguments.data_type,
+ arguments.data_type,
+ arguments.data_type,
+ )?);
+
+ Ok(Self {
+ head_dim: arguments.head_dim,
+ num_groups: arguments.num_groups,
+ num_q_heads: arguments.num_q_heads,
+ sliding_window_size: arguments.sliding_window_size,
+ scale: arguments.scale,
+ data_type: arguments.data_type,
+ scatter_scores,
+ scatter_values,
+ softmax,
+ matmul,
+ })
+ }
+
+ pub fn encode<'a, KT: BufferArg<'a, B>, VT: BufferArg<'a, B>>(
+ &self,
+ arguments: AttentionCoreEncodeArguments<'a, B, KT, VT>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error> {
+ let sequence_length = arguments.state_type.physical_prefix_length() + arguments.suffix_length;
+ let gqa_factor = self.num_q_heads / self.num_groups;
+ let scale = self.scale.unwrap_or(1.0f32 / (self.head_dim as f32).sqrt());
+ let dt_bytes = self.data_type.size_in_bytes();
+
+ let mut output = encoder.allocate_constant(size_for_shape(
+ &[arguments.suffix_length, self.num_q_heads, self.head_dim],
+ self.data_type,
+ ))?;
+ let mut scores = encoder.allocate_scratch(size_for_shape(
+ &[self.num_q_heads * arguments.suffix_length * sequence_length],
+ self.data_type,
+ ))?;
+ let mut group_scores = encoder.allocate_scratch(size_for_shape(
+ &[gqa_factor * arguments.suffix_length, sequence_length],
+ self.data_type,
+ ))?;
+
+ for group_index in 0..self.num_groups {
+ self.matmul.borrow_mut().encode(
+ MatmulArguments {
+ a: arguments.queries,
+ a_offset: group_index * gqa_factor * arguments.suffix_length * self.head_dim * dt_bytes,
+ b: MatmulB::FullPrecision {
+ b: (arguments.keys, group_index * self.head_dim * dt_bytes),
+ },
+ b_leading_dimension: Some((self.num_groups * self.head_dim) as u32),
+ b_transpose: true,
+ d: &mut group_scores,
+ d_transform: MatmulDOps {
+ ab_scale: scale,
+ accumulate: false,
+ bias: None,
+ rht_factors: None,
+ },
+ m: (gqa_factor * arguments.suffix_length) as u32,
+ n: sequence_length as u32,
+ k: self.head_dim as u32,
+ },
+ encoder,
+ )?;
+ self.scatter_scores.encode(
+ &group_scores,
+ &mut scores,
+ arguments.state_type.ring_params(),
+ None::<&Allocation<B>>,
+ self.sliding_window_size.map(|sliding_window_size| sliding_window_size as u32),
+ group_index as u32,
+ gqa_factor as u32,
+ sequence_length as u32,
+ arguments.suffix_length as u32,
+ (gqa_factor * arguments.suffix_length * sequence_length) as u32,
+ encoder,
+ );
+ }
+
+ self.softmax.encode(
+ &mut scores,
+ arguments.sinks,
+ sequence_length as u32,
+ self.num_q_heads as u32,
+ arguments.suffix_length as u32,
+ encoder,
+ );
+
+ let mut group_output = encoder
+ .allocate_scratch(size_for_shape(&[gqa_factor * arguments.suffix_length, self.head_dim], self.data_type))?;
+
+ for group_index in 0..self.num_groups {
+ self.matmul.borrow_mut().encode(
+ MatmulArguments {
+ a: &scores,
+ a_offset: group_index * gqa_factor * arguments.suffix_length * sequence_length * dt_bytes,
+ b: MatmulB::FullPrecision {
+ b: (arguments.values, group_index * self.head_dim * dt_bytes),
+ },
+ b_leading_dimension: Some((self.num_groups * self.head_dim) as u32),
+ b_transpose: false,
+ d: &mut group_output,
+ d_transform: MatmulDOps::none(),
+ m: (gqa_factor * arguments.suffix_length) as u32,
+ n: self.head_dim as u32,
+ k: sequence_length as u32,
+ },
+ encoder,
+ )?;
+ self.scatter_values.encode(
+ &group_output,
+ &mut output,
+ group_index as u32,
+ gqa_factor as u32,
+ arguments.suffix_length as u32,
+ self.num_q_heads as u32,
+ self.head_dim as u32,
+ (gqa_factor * arguments.suffix_length * self.head_dim) as u32,
+ encoder,
+ );
+ }
+
+ Ok(output)
+ }
+}
diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/core/gemm.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/core/gemm.rs
new file mode 100644
index 000000000..bbf6dfc33
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/core/gemm.rs
@@ -0,0 +1,142 @@
+use std::mem::MaybeUninit;
+
+use bitflags::bitflags;
+
+use crate::{
+ array::size_for_shape,
+ backends::common::{
+ Allocation, Backend, Encoder, Kernels,
+ gpu_types::AttnParams,
+ kernel::{AttentionGemmKernel, BufferArg},
+ },
+ data_type::DataType,
+ encodable_block::mixer::attention::core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments},
+};
+
+bitflags! {
+ pub struct AttentionGemmKey: usize {
+ const ALIGNED_Q = 1 << 0;
+ const ALIGNED_KV = 1 << 1;
+ }
+}
+
+const ATTENTION_GEMM_KEYS: usize = AttentionGemmKey::all().bits() + 1;
+
+pub struct AttentionGemmCore<B: Backend> {
+ head_dim: usize,
+ num_groups: usize,
+ num_q_heads: usize,
+ bk: usize,
+ bq: usize,
+ sliding_window_size: Option<usize>,
+ scale: Option<f32>,
+ data_type: DataType,
+ kernels: [<B::Kernels as Kernels>::AttentionGemmKernel; ATTENTION_GEMM_KEYS],
+}
+
+impl<B: Backend> AttentionGemmCore<B> {
+ pub fn new(
+ arguments: &AttentionCoreNewArguments,
+ use_mxu: bool,
+ context: &B::Context,
+ ) -> Result<Self, B::Error> {
+ let bk = if arguments.head_dim < 128 || use_mxu {
+ 32
+ } else {
+ 16
+ };
+ let bq = if use_mxu {
+ 64
+ } else {
+ 32
+ };
+
+ let mut kernels = [const { MaybeUninit::uninit() }; ATTENTION_GEMM_KEYS];
+ for (index, kernel) in kernels.iter_mut().enumerate() {
+ let key = AttentionGemmKey::from_bits(index).unwrap();
+
+ kernel.write(<B::Kernels as Kernels>::AttentionGemmKernel::new(
+ context,
+ arguments.data_type,
+ bk as u32,
+ arguments.head_dim as u32,
+ use_mxu,
+ key.contains(AttentionGemmKey::ALIGNED_Q),
+ key.contains(AttentionGemmKey::ALIGNED_KV),
+ arguments.is_kv_cache_ring,
+ arguments.is_causal,
+ arguments.is_trie,
+ arguments.sliding_window_size.is_some(),
+ arguments.has_sinks,
+ )?);
+ }
+
+ Ok(Self {
+ head_dim: arguments.head_dim,
+ num_groups: arguments.num_groups,
+ num_q_heads: arguments.num_q_heads,
+ bk,
+ bq,
+ sliding_window_size: arguments.sliding_window_size,
+ scale: arguments.scale,
+ data_type: arguments.data_type,
+ kernels: kernels.map(|kernel| unsafe { kernel.assume_init() }),
+ })
+ }
+
+ pub fn encode<'a, KT: BufferArg<'a, B>, VT: BufferArg<'a, B>>(
+ &self,
+ arguments: AttentionCoreEncodeArguments<'a, B, KT, VT>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error> {
+ let mut key = AttentionGemmKey::empty();
+
+ if arguments.suffix_length.is_multiple_of(self.bq) {
+ key.insert(AttentionGemmKey::ALIGNED_Q);
+ }
+ if (arguments.state_type.physical_prefix_length() + arguments.suffix_length).is_multiple_of(self.bk) {
+ key.insert(AttentionGemmKey::ALIGNED_KV);
+ }
+
+ let mut output = encoder.allocate_constant(size_for_shape(
+ &[arguments.suffix_length, self.num_q_heads, self.head_dim],
+ self.data_type,
+ ))?;
+ self.kernels[key.bits()].encode(
+ arguments.queries,
+ arguments.keys,
+ arguments.values,
+ &mut output,
+ AttnParams {
+ q_strides: [0, (arguments.suffix_length * self.head_dim) as u64, self.head_dim as u64],
+ k_strides: [0, self.head_dim as u64, (self.num_groups * self.head_dim) as u64],
+ v_strides: [0, self.head_dim as u64, (self.num_groups * self.head_dim) as u64],
+ o_strides: [0, self.head_dim as u64, (self.num_q_heads * self.head_dim) as u64],
+ gqa_factor: (self.num_q_heads / self.num_groups) as u32,
+ scale: self.scale.unwrap_or(1.0f32 / (self.head_dim as f32).sqrt()),
+ q_len: arguments.suffix_length as u32,
+ k_len: (arguments.state_type.physical_prefix_length() + arguments.suffix_length) as u32,
+ q_off: arguments.state_type.physical_prefix_length() as u32,
+ nq_aligned: (arguments.suffix_length / self.bq) as u32,
+ q_rem: (arguments.suffix_length % self.bq) as u32,
+ nk: (arguments.state_type.physical_prefix_length() + arguments.suffix_length).div_ceil(self.bk) as u32,
+ nk_aligned: ((arguments.state_type.physical_prefix_length() + arguments.suffix_length) / self.bk)
+ as u32,
+ k_rem: ((arguments.state_type.physical_prefix_length() + arguments.suffix_length) % self.bk) as u32,
+ },
+ arguments.state_type.ring_params(),
+ arguments.trie,
+ self.sliding_window_size.map(|sliding_window_size| sliding_window_size as u32),
+ arguments.sinks,
+ self.num_q_heads as u32,
+ arguments.suffix_length as u32,
+ encoder,
+ );
+
+ Ok(output)
+ }
+}
+
+#[cfg(test)]
+#[path = "../../../../../unit/encodable_block/attention_gemm_test.rs"]
+mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/core/mod.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/core/mod.rs
new file mode 100644
index 000000000..b741ebadc
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/core/mod.rs
@@ -0,0 +1,110 @@
+use crate::{
+ backends::common::{Allocation, Backend, Context, Encoder, kernel::BufferArg},
+ data_type::DataType,
+ encodable_block::mixer::attention::{
+ core::{
+ fallback::AttentionFallbackCore, gemm::AttentionGemmCore, single_pass::AttentionSinglePassCore,
+ two_pass::AttentionTwoPassCore,
+ },
+ state::AttentionStateType,
+ },
+};
+
+mod fallback;
+mod gemm;
+mod single_pass;
+mod two_pass;
+
+pub struct AttentionCoreNewArguments {
+ pub head_dim: usize,
+ pub num_groups: usize,
+ pub num_q_heads: usize,
+ pub has_sinks: bool,
+ pub is_kv_cache_ring: bool,
+ pub is_causal: bool,
+ pub is_trie: bool,
+ pub sliding_window_size: Option<usize>,
+ pub scale: Option<f32>,
+ pub data_type: DataType,
+}
+
+pub struct AttentionCoreEncodeArguments<'a, B: Backend, KT: BufferArg<'a, B>, VT: BufferArg<'a, B>> {
+ pub queries: &'a Allocation<B>,
+ pub keys: KT,
+ pub values: VT,
+ pub suffix_length: usize,
+ pub trie: Option<&'a Allocation<B>>,
+ pub sinks: Option<&'a Allocation<B>>,
+ pub state_type: &'a AttentionStateType,
+}
+
+pub struct AttentionCores<B: Backend> {
+ gemm_mxu: Option<AttentionGemmCore<B>>,
+ gemm_simd: Option<AttentionGemmCore<B>>,
+ fallback: Option<AttentionFallbackCore<B>>,
+ two_pass: AttentionTwoPassCore<B>,
+ single_pass: AttentionSinglePassCore<B>,
+}
+
+impl<B: Backend> AttentionCores<B> {
+ pub fn new(
+ arguments: AttentionCoreNewArguments,
+ context: &B::Context,
+ ) -> Result<Self, B::Error> {
+ let gemm_mxu = if matches!(arguments.head_dim, 64 | 128)
+ && matches!(arguments.data_type, DataType::BF16 | DataType::F16)
+ && context.supports_mxu()
+ {
+ Some(AttentionGemmCore::new(&arguments, true, context)?)
+ } else {
+ None
+ };
+ let gemm_simd = if matches!(arguments.head_dim, 64 | 128 | 256) {
+ Some(AttentionGemmCore::new(&arguments, false, context)?)
+ } else {
+ None
+ };
+ let fallback = if arguments.head_dim == 512 && !arguments.is_trie {
+ Some(AttentionFallbackCore::new(&arguments, context)?)
+ } else {
+ None
+ };
+ let two_pass = AttentionTwoPassCore::new(&arguments, context)?;
+ let single_pass = AttentionSinglePassCore::new(&arguments, context)?;
+
+ Ok(Self {
+ gemm_mxu,
+ gemm_simd,
+ fallback,
+ two_pass,
+ single_pass,
+ })
+ }
+ pub fn encode<'a, KT: BufferArg<'a, B>, VT: BufferArg<'a, B>>(
+ &self,
+ arguments: AttentionCoreEncodeArguments<'a, B, KT, VT>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, <B as Backend>::Error> {
+ if arguments.suffix_length >= 64
+ && let Some(gemm_mxu) = &self.gemm_mxu
+ {
+ gemm_mxu.encode(arguments, encoder)
+ } else if arguments.suffix_length > 8
+ && let Some(gemm_simd) = &self.gemm_simd
+ {
+ gemm_simd.encode(arguments, encoder)
+ } else if arguments.suffix_length > 8
+ && let Some(fallback) = &self.fallback
+ {
+ fallback.encode(arguments, encoder)
+ } else if arguments.state_type.physical_prefix_length() + arguments.suffix_length > 1024 {
+ self.two_pass.encode(arguments, encoder)
+ } else {
+ self.single_pass.encode(arguments, encoder)
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "../../../../../unit/encodable_block/attention_test.rs"]
+mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/core/single_pass.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/core/single_pass.rs
new file mode 100644
index 000000000..f35ee4d97
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/core/single_pass.rs
@@ -0,0 +1,80 @@
+use crate::{
+ array::size_for_shape,
+ backends::common::{
+ Allocation, Backend, Encoder, Kernels,
+ kernel::{AttentionSinglePassKernel, BufferArg},
+ },
+ data_type::DataType,
+ encodable_block::mixer::attention::core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments},
+};
+
+pub struct AttentionSinglePassCore<B: Backend> {
+ head_dim: usize,
+ num_groups: usize,
+ num_q_heads: usize,
+ sliding_window_size: Option<usize>,
+ scale: Option<f32>,
+ data_type: DataType,
+ kernel: <B::Kernels as Kernels>::AttentionSinglePassKernel,
+}
+
+impl<B: Backend> AttentionSinglePassCore<B> {
+ pub fn new(
+ arguments: &AttentionCoreNewArguments,
+ context: &B::Context,
+ ) -> Result<Self, B::Error> {
+ let kernel = <B::Kernels as Kernels>::AttentionSinglePassKernel::new(
+ context,
+ arguments.data_type,
+ arguments.head_dim as u32,
+ arguments.has_sinks,
+ arguments.is_kv_cache_ring,
+ arguments.is_causal,
+ arguments.is_trie,
+ arguments.sliding_window_size.is_some(),
+ )?;
+
+ Ok(Self {
+ head_dim: arguments.head_dim,
+ num_groups: arguments.num_groups,
+ num_q_heads: arguments.num_q_heads,
+ sliding_window_size: arguments.sliding_window_size,
+ scale: arguments.scale,
+ data_type: arguments.data_type,
+ kernel,
+ })
+ }
+
+ pub fn encode<'a, KT: BufferArg<'a, B>, VT: BufferArg<'a, B>>(
+ &self,
+ arguments: AttentionCoreEncodeArguments<'a, B, KT, VT>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error> {
+ let mut output = encoder.allocate_constant(size_for_shape(
+ &[arguments.suffix_length, self.num_q_heads, self.head_dim],
+ self.data_type,
+ ))?;
+ self.kernel.encode(
+ arguments.queries,
+ arguments.keys,
+ arguments.values,
+ &mut output,
+ (self.num_q_heads / self.num_groups) as u32,
+ (arguments.state_type.physical_prefix_length() + arguments.suffix_length) as u32,
+ self.head_dim as u32,
+ (self.num_groups * self.head_dim) as u32,
+ self.head_dim as u32,
+ (self.num_groups * self.head_dim) as u32,
+ arguments.state_type.ring_params(),
+ self.scale.unwrap_or(1.0f32 / (self.head_dim as f32).sqrt()),
+ arguments.trie,
+ self.sliding_window_size.map(|sliding_window_size| sliding_window_size as u32),
+ arguments.sinks,
+ self.num_q_heads as u32,
+ arguments.suffix_length as u32,
+ encoder,
+ );
+
+ Ok(output)
+ }
+}
diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/core/two_pass.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/core/two_pass.rs
new file mode 100644
index 000000000..0141ed0e4
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/core/two_pass.rs
@@ -0,0 +1,109 @@
+use crate::{
+ array::size_for_shape,
+ backends::common::{
+ Allocation, Backend, Encoder, Kernels,
+ kernel::{AttentionTwoPass1Kernel, AttentionTwoPass2Kernel, BufferArg},
+ },
+ data_type::DataType,
+ encodable_block::mixer::attention::core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments},
+};
+
+pub struct AttentionTwoPassCore<B: Backend> {
+ head_dim: usize,
+ num_groups: usize,
+ num_q_heads: usize,
+ sliding_window_size: Option<usize>,
+ scale: Option<f32>,
+ data_type: DataType,
+ pass_1: <B::Kernels as Kernels>::AttentionTwoPass1Kernel,
+ pass_2: <B::Kernels as Kernels>::AttentionTwoPass2Kernel,
+}
+
+impl<B: Backend> AttentionTwoPassCore<B> {
+ pub fn new(
+ arguments: &AttentionCoreNewArguments,
+ context: &B::Context,
+ ) -> Result<Self, B::Error> {
+ let pass_1 = <B::Kernels as Kernels>::AttentionTwoPass1Kernel::new(
+ context,
+ arguments.data_type,
+ arguments.head_dim as u32,
+ arguments.has_sinks,
+ arguments.is_kv_cache_ring,
+ arguments.is_causal,
+ arguments.is_trie,
+ arguments.sliding_window_size.is_some(),
+ )?;
+
+ let pass_2 = <B::Kernels as Kernels>::AttentionTwoPass2Kernel::new(
+ context,
+ arguments.data_type,
+ arguments.head_dim as u32,
+ )?;
+
+ Ok(Self {
+ head_dim: arguments.head_dim,
+ num_groups: arguments.num_groups,
+ num_q_heads: arguments.num_q_heads,
+ sliding_window_size: arguments.sliding_window_size,
+ scale: arguments.scale,
+ data_type: arguments.data_type,
+ pass_1,
+ pass_2,
+ })
+ }
+
+ pub fn encode<'a, KT: BufferArg<'a, B>, VT: BufferArg<'a, B>>(
+ &self,
+ arguments: AttentionCoreEncodeArguments<'a, B, KT, VT>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error> {
+ let mut partials = encoder.allocate_scratch(size_for_shape(
+ &[self.num_q_heads * arguments.suffix_length * 32 * self.head_dim],
+ DataType::F32,
+ ))?;
+ let mut sums = encoder
+ .allocate_scratch(size_for_shape(&[self.num_q_heads * arguments.suffix_length * 32], DataType::F32))?;
+ let mut maxs = encoder
+ .allocate_scratch(size_for_shape(&[self.num_q_heads * arguments.suffix_length * 32], DataType::F32))?;
+
+ self.pass_1.encode(
+ arguments.queries,
+ arguments.keys,
+ arguments.values,
+ &mut partials,
+ &mut sums,
+ &mut maxs,
+ (self.num_q_heads / self.num_groups) as u32,
+ (arguments.state_type.physical_prefix_length() + arguments.suffix_length) as u32,
+ self.head_dim as u32,
+ (self.num_groups * self.head_dim) as u32,
+ self.head_dim as u32,
+ (self.num_groups * self.head_dim) as u32,
+ arguments.state_type.ring_params(),
+ self.scale.unwrap_or(1.0f32 / (self.head_dim as f32).sqrt()),
+ self.num_q_heads as u32,
+ arguments.suffix_length as u32,
+ arguments.trie,
+ self.sliding_window_size.map(|sliding_window_size| sliding_window_size as u32),
+ arguments.sinks,
+ encoder,
+ );
+
+ let mut output = encoder.allocate_constant(size_for_shape(
+ &[arguments.suffix_length, self.num_q_heads, self.head_dim],
+ self.data_type,
+ ))?;
+ self.pass_2.encode(
+ &partials,
+ &sums,
+ &maxs,
+ &mut output,
+ self.num_q_heads as u32,
+ arguments.suffix_length as u32,
+ encoder,
+ );
+
+ Ok(output)
+ }
+}
diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/mod.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/mod.rs
new file mode 100644
index 000000000..b46f83d75
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/mod.rs
@@ -0,0 +1,404 @@
+use thiserror::Error;
+
+use crate::{
+ array::size_for_shape,
+ backends::common::{
+ Allocation, Backend, Encoder, Kernels,
+ gpu_types::trie::TrieNode,
+ kernel::{AttentionPrepareKernel, SigmoidGateKernel},
+ },
+ config::{rope::AnyRoPEConfig, token_mixer::attention::AttentionConfig},
+ data_type::DataType,
+ encodable_block::{
+ batch_topology::BatchTopology,
+ linear::{Linear, LinearBlockError},
+ mixer::{
+ Mixer, MixerState,
+ attention::{
+ core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments, AttentionCores},
+ qkv_norm::{QKVNorm, QKVNormError},
+ rope::PrecalculatedRoPE,
+ state::{AttentionState, AttentionStateType},
+ },
+ },
+ },
+ parameters::{ParameterLoaderError, ParameterTree},
+ utils::maybe_mut::MaybeMut,
+};
+
+mod core;
+mod qkv_norm;
+mod state;
+
+pub mod rope;
+
+pub struct Attention<B: Backend> {
+ head_dim: usize,
+ num_q_heads: usize,
+ num_kv_heads: Option<usize>,
+ is_causal: bool,
+ sliding_window_size: Option<usize>,
+ max_rope_length: Option<usize>,
+ is_kv_sharing: bool,
+ data_type: DataType,
+ qkv_projection: Box<dyn Linear<B>>,
+ gate_projection: Option<Box<dyn Linear<B>>>,
+ qkv_norm: Option<QKVNorm<B>>,
+ prepare: <B::Kernels as Kernels>::AttentionPrepareKernel,
+ sinks: Option<Allocation<B>>,
+ flat_core: AttentionCores<B>,
+ trie_core: AttentionCores<B>,
+ gate_kernel: Option<<B::Kernels as Kernels>::SigmoidGateKernel>,
+ out_projection: Box<dyn Linear<B>>,
+}
+
+#[derive(Debug, Error)]
+pub enum AttentionNewError<B: Backend> {
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+ #[error("Parameter loader error: {0}")]
+ ParameterLoader(#[from] ParameterLoaderError<B>),
+ #[error("Linear error: {0}")]
+ Linear(#[from] LinearBlockError<B>),
+ #[error("QKVNorm error: {0}")]
+ QKVNorm(#[from] QKVNormError<B>),
+}
+
+impl<B: Backend> Attention<B> {
+ pub fn new(
+ hidden_dim: usize,
+ data_type: DataType,
+ rope_config: Option<&AnyRoPEConfig>,
+ config: &AttentionConfig,
+ parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
+ ) -> Result<(Self, Option<Allocation<B>>), AttentionNewError<B>> {
+ let is_kv_sharing = config.is_kv_sharing;
+
+ let head_dim = config.head_dim;
+ let num_groups = config.num_groups;
+ let num_q_heads = config.num_heads;
+ let num_kv_heads = (!is_kv_sharing).then_some(num_groups);
+
+ let is_causal = config.is_causal;
+ let sliding_window_size = config.sliding_window_size;
+ let max_rope_length = rope_config.map(|rope_config| *rope_config.max_sequence_length());
+
+ let q_dim = num_q_heads * head_dim;
+
+ let has_gate = config.gate_projection_config.is_some();
+
+ // TODO: qkv and gate should be fused to be qkvg in lalamo
+ let qkv_projection_tree = parameter_tree.subtree("qkv_projection")?;
+ let qkv_projection_output_dimension = if let Some(num_kv_heads) = num_kv_heads {
+ let kv_dim = num_kv_heads * head_dim;
+ q_dim + kv_dim + kv_dim
+ } else {
+ q_dim
+ };
+ let (qkv_projection, in_projection_input_hadamard_factors) = if !has_gate {
+ <dyn Linear<B>>::new_extracting_input_hadamard(
+ hidden_dim,
+ [qkv_projection_output_dimension],
+ config.has_qkv_biases,
+ context,
+ data_type,
+ &qkv_projection_tree,
+ )?
+ } else {
+ (
+ <dyn Linear<B>>::new(
+ hidden_dim,
+ [qkv_projection_output_dimension],
+ config.has_qkv_biases,
+ context,
+ data_type,
+ &qkv_projection_tree,
+ )?,
+ None,
+ )
+ };
+
+ let gate_projection = has_gate
+ .then(|| {
+ <dyn Linear<B>>::new(
+ hidden_dim,
+ [q_dim],
+ false,
+ context,
+ data_type,
+ &parameter_tree.subtree("gate_projection")?,
+ )
+ })
+ .transpose()?;
+
+ let query_norm_config = config.query_norm_config.clone();
+ // TODO: Fix lalamo config, those two must be None if kv sharing.
+ let key_norm_config = (!is_kv_sharing).then(|| config.key_norm_config.clone()).flatten();
+ let value_norm_config = (!is_kv_sharing).then(|| config.value_norm_config()).flatten();
+ let qkv_norm = (query_norm_config.is_some() || key_norm_config.is_some() || value_norm_config.is_some())
+ .then(|| {
+ QKVNorm::new(
+ context,
+ data_type,
+ query_norm_config,
+ key_norm_config,
+ value_norm_config,
+ parameter_tree,
+ config.num_heads,
+ num_kv_heads.unwrap_or(0), // TODO: should take option
+ config.head_dim,
+ )
+ })
+ .transpose()?;
+
+ let prepare = <B::Kernels as Kernels>::AttentionPrepareKernel::new(
+ context,
+ data_type,
+ DataType::F32,
+ !is_kv_sharing,
+ rope_config.is_some(),
+ )
+ .map_err(AttentionNewError::Backend)?;
+
+ let sinks = config
+ .has_sinks
+ .then(|| parameter_tree.leaf("sinks")?.validate(&[num_q_heads], data_type)?.read_allocation())
+ .transpose()?;
+
+ let flat_core = AttentionCores::new(
+ AttentionCoreNewArguments {
+ head_dim,
+ num_groups,
+ num_q_heads,
+ has_sinks: sinks.is_some(),
+ is_kv_cache_ring: sliding_window_size.is_some(),
+ is_causal,
+ is_trie: false,
+ sliding_window_size,
+ scale: config.scale,
+ data_type,
+ },
+ context,
+ )
+ .map_err(AttentionNewError::Backend)?;
+
+ let trie_core = AttentionCores::new(
+ AttentionCoreNewArguments {
+ head_dim,
+ num_groups,
+ num_q_heads,
+ has_sinks: sinks.is_some(),
+ is_kv_cache_ring: sliding_window_size.is_some(),
+ is_causal,
+ is_trie: true,
+ sliding_window_size,
+ scale: config.scale,
+ data_type,
+ },
+ context,
+ )
+ .map_err(AttentionNewError::Backend)?;
+
+ let gate_kernel = has_gate
+ .then(|| <B::Kernels as Kernels>::SigmoidGateKernel::new(context, data_type))
+ .transpose()
+ .map_err(AttentionNewError::Backend)?;
+
+ let out_projection = <dyn Linear<B>>::new(
+ q_dim,
+ [hidden_dim],
+ config.has_out_biases,
+ context,
+ data_type,
+ &parameter_tree.subtree("out_projection")?,
+ )?;
+
+ Ok((
+ Self {
+ head_dim,
+ num_q_heads,
+ num_kv_heads,
+ is_causal,
+ sliding_window_size,
+ max_rope_length,
+ is_kv_sharing,
+ data_type,
+ qkv_projection,
+ gate_projection,
+ qkv_norm,
+ prepare,
+ sinks,
+ flat_core,
+ trie_core,
+ gate_kernel,
+ out_projection,
+ },
+ in_projection_input_hadamard_factors,
+ ))
+ }
+}
+
+impl<B: Backend> Mixer<B> for Attention<B> {
+ fn speculation_supported(&self) -> bool {
+ true
+ }
+
+ fn max_context_length(&self) -> Option<usize> {
+ self.max_rope_length
+ }
+
+ fn create_empty_state(
+ &self,
+ max_context_length: Option<usize>,
+ context: &B::Context,
+ ) -> Result<Box<dyn MixerState<B>>, B::Error> {
+ Ok(Box::new(AttentionState::create_empty(self, max_context_length, context)?))
+ }
+
+ fn encode(
+ &self,
+ hidden: Allocation<B>,
+ precalculated_rope: Option<&PrecalculatedRoPE<B>>,
+ batch_dim: &BatchTopology,
+ state: Option<MaybeMut<dyn MixerState<B>>>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error> {
+ assert_eq!(precalculated_rope.is_some(), self.max_rope_length.is_some(), "precalculated rope mismatch");
+
+ let state =
+ state.map(|state| state.downcast::<AttentionState<B>>().expect("incorrect type of attention state"));
+
+ // If we have gate we must duplicate input (linear does hadamard in-place). TODO: fix this properly by adding support for not in place input hadamard
+ let (hidden, gate) = if let Some(gate_projection) = &self.gate_projection {
+ let mut hidden_copy = encoder.allocate_scratch(hidden.size())?;
+ encoder.encode_copy(&hidden, .., &mut hidden_copy, ..);
+ let gate = gate_projection.encode(hidden, batch_dim.size(), encoder)?;
+ (hidden_copy, Some(gate))
+ } else {
+ (hidden, None)
+ };
+
+ let mut qkv = self.qkv_projection.encode(hidden, batch_dim.size(), encoder)?;
+
+ if let Some(qkv_norm) = &self.qkv_norm {
+ qkv_norm.encode(&mut qkv, batch_dim.size(), encoder)?;
+ }
+
+ let mut queries = encoder
+ .allocate_scratch(size_for_shape(&[self.num_q_heads, batch_dim.size(), self.head_dim], self.data_type))?;
+
+ let mut attention_output = if let Some(mut state) = state {
+ assert!(matches!(state, MaybeMut::Mut(_)) == !self.is_kv_sharing);
+
+ let (prepare_keys, prepare_values, kv_token_offset) = match &mut state {
+ MaybeMut::Const(_) => (None, None, None),
+ MaybeMut::Mut(state) => (
+ Some(state.keys.as_mut()),
+ Some(state.values.as_mut()),
+ Some(state.state_type.physical_prefix_length()),
+ ),
+ };
+
+ self.prepare.encode(
+ &qkv,
+ &mut queries,
+ prepare_keys,
+ prepare_values,
+ precalculated_rope.map(|precalculated_rope| &precalculated_rope.cosines),
+ precalculated_rope.map(|precalculated_rope| &precalculated_rope.sines),
+ self.num_q_heads as u32,
+ self.num_kv_heads.map(|num_kv_heads| num_kv_heads as u32),
+ self.head_dim as u32,
+ precalculated_rope.map(|precalculated_rope| precalculated_rope.dim as u32),
+ kv_token_offset.map(|kv_token_offset| kv_token_offset as u32),
+ batch_dim.size() as u32,
+ encoder,
+ );
+
+ let (core, trie) = if batch_dim.is_flat() {
+ (&self.flat_core, None)
+ } else {
+ let mut trie = encoder.allocate_constant(batch_dim.size() * size_of::<TrieNode>())?;
+ trie.copyin(batch_dim.nodes());
+ (&self.trie_core, Some(trie))
+ };
+
+ core.encode(
+ AttentionCoreEncodeArguments {
+ queries: &queries,
+ keys: state.keys.as_ref(),
+ values: state.values.as_ref(),
+ suffix_length: batch_dim.size(),
+ trie: trie.as_ref(),
+ sinks: self.sinks.as_ref(),
+ state_type: &state.state_type,
+ },
+ encoder,
+ )?
+ } else {
+ let Some(num_kv_heads) = self.num_kv_heads else {
+ panic!("stateless attention doesn't support kv sharing");
+ };
+
+ assert!(batch_dim.is_flat(), "stateless attention doesn't support trie");
+
+ let mut keys = encoder
+ .allocate_scratch(size_for_shape(&[batch_dim.size(), num_kv_heads, self.head_dim], self.data_type))?;
+ let mut values = encoder
+ .allocate_scratch(size_for_shape(&[batch_dim.size(), num_kv_heads, self.head_dim], self.data_type))?;
+
+ self.prepare.encode(
+ &qkv,
+ &mut queries,
+ Some(&mut keys),
+ Some(&mut values),
+ precalculated_rope.map(|precalculated_rope| &precalculated_rope.cosines),
+ precalculated_rope.map(|precalculated_rope| &precalculated_rope.sines),
+ self.num_q_heads as u32,
+ self.num_kv_heads.map(|num_kv_heads| num_kv_heads as u32),
+ self.head_dim as u32,
+ precalculated_rope.map(|precalculated_rope| precalculated_rope.dim as u32),
+ Some(0),
+ batch_dim.size() as u32,
+ encoder,
+ );
+
+ // HACK: state_type should be Option.
+ let state_type = if self.sliding_window_size.is_some() {
+ AttentionStateType::Ring {
+ offset: 0,
+ length: 0,
+ max_length: 0,
+ }
+ } else {
+ AttentionStateType::Full {
+ length: 0,
+ }
+ };
+
+ self.flat_core.encode(
+ AttentionCoreEncodeArguments {
+ queries: &queries,
+ keys: &keys,
+ values: &values,
+ suffix_length: batch_dim.size(),
+ trie: None,
+ sinks: self.sinks.as_ref(),
+ state_type: &state_type,
+ },
+ encoder,
+ )?
+ };
+
+ if let Some(gate_kernel) = &self.gate_kernel {
+ gate_kernel.encode(
+ &gate.unwrap(),
+ &mut attention_output,
+ (batch_dim.size() * self.num_q_heads * self.head_dim) as u32,
+ encoder,
+ );
+ }
+ self.out_projection.encode(attention_output, batch_dim.size(), encoder)
+ }
+}
diff --git a/crates/backend-uzu/src/encodable_block/qkv_norm.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/qkv_norm.rs
similarity index 86%
rename from crates/backend-uzu/src/encodable_block/qkv_norm.rs
rename to crates/backend-uzu/src/encodable_block/mixer/attention/qkv_norm.rs
index 01a90055b..a052bcc67 100644
--- a/crates/backend-uzu/src/encodable_block/qkv_norm.rs
+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/qkv_norm.rs
@@ -91,26 +91,19 @@ impl<B: Backend> QKVNorm<B> {
scales_leaf: Option<&str>,
head_dim: usize,
) -> Result<Head<B>, QKVNormError<B>> {
- let (scales, scale_data_type) = if let Some(scales_leaf) = scales_leaf {
- let scale_data_type = super::normalization::NORMALIZATION_SCALE_DATA_TYPE;
- (
- Some(parameter_tree.leaf(scales_leaf)?.validate(&[head_dim], scale_data_type)?.read_allocation()?),
- scale_data_type,
- )
+ let scales = if let Some(scales_leaf) = scales_leaf {
+ Some(parameter_tree.leaf(scales_leaf)?.validate(&[head_dim], DataType::F32)?.read_allocation()?)
} else {
- (None, intermediate_data_type)
+ None
};
- let scale_free = scales.is_none();
- let accumulation_data_type = super::normalization::NORMALIZATION_ACCUMULATION_DATA_TYPE;
- let output_data_type = intermediate_data_type;
let kernel = <B::Kernels as Kernels>::QKVNormKernel::new(
context,
intermediate_data_type,
- scale_data_type,
- output_data_type,
- accumulation_data_type,
+ DataType::F32,
+ intermediate_data_type,
+ DataType::F32,
true,
- scale_free,
+ scales.is_none(),
)
.map_err(QKVNormError::BackendError)?;
Ok(Head {
diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/rope.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/rope.rs
new file mode 100644
index 000000000..2e89c39d2
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/rope.rs
@@ -0,0 +1,103 @@
+use crate::{
+ backends::common::{Allocation, Backend, Encoder},
+ config::rope::AnyRoPEConfig,
+};
+
+pub struct PrecalculatedRoPE<B: Backend> {
+ pub cosines: Allocation<B>,
+ pub sines: Allocation<B>,
+ pub dim: usize,
+}
+
+impl<B: Backend> PrecalculatedRoPE<B> {
+ pub fn precalculate(
+ rope_config: &AnyRoPEConfig,
+ token_positions: &[usize],
+ encoder: &mut Encoder<B>,
+ ) -> Result<Self, B::Error> {
+ let head_dim = *rope_config.head_dim();
+ assert!(head_dim > 0 && head_dim.is_multiple_of(2), "RoPE head_dim must be positive and even");
+ let half_dim = head_dim / 2;
+ let attention_scaling_factor = match rope_config {
+ AnyRoPEConfig::YARNRoPEConfig(config) => 0.1 * config.scaling_factor.ln() + 1.0,
+ _ => 1.0,
+ };
+
+ let element_count = token_positions.len() * head_dim;
+ let mut sines = vec![0.0; element_count];
+ let mut cosines = vec![0.0; element_count];
+ for pair_index in 0..half_dim {
+ let channel_index = pair_index * 2;
+ let inverse_frequency = 1.0 / rope_config.base().powf(channel_index as f32 / head_dim as f32);
+ let inverse_frequency = match rope_config {
+ AnyRoPEConfig::UnscaledRoPEConfig(_) => inverse_frequency,
+ AnyRoPEConfig::LinearScalingRoPEConfig(config) => inverse_frequency / config.scaling_factor,
+ AnyRoPEConfig::LlamaRoPEConfig(config) => {
+ let low_frequency_wavelength = config.original_context_length as f32 / config.low_frequency_factor;
+ let high_frequency_wavelength =
+ config.original_context_length as f32 / config.high_frequency_factor;
+ let wavelength = 2.0 * std::f32::consts::PI / inverse_frequency;
+ let scaled_frequency = inverse_frequency / config.scaling_factor;
+
+ if wavelength < high_frequency_wavelength {
+ inverse_frequency
+ } else if wavelength > low_frequency_wavelength {
+ scaled_frequency
+ } else {
+ let smoothing_factor =
+ config.original_context_length as f32 / wavelength - config.low_frequency_factor;
+ let smoothing_factor =
+ smoothing_factor / (config.high_frequency_factor - config.low_frequency_factor);
+ smoothing_factor * inverse_frequency + (1.0 - smoothing_factor) * scaled_frequency
+ }
+ },
+ AnyRoPEConfig::YARNRoPEConfig(config) => {
+ let dim = config.head_dim as f64;
+ let base = config.base as f64;
+ let original_context_length = config.original_context_length as f64;
+ let beta_fast = config.beta_fast as f64;
+ let beta_slow = config.beta_slow as f64;
+ let mut low = dim * (original_context_length / (beta_fast * 2.0 * std::f64::consts::PI)).ln()
+ / (2.0 * base.ln());
+ let mut high = dim * (original_context_length / (beta_slow * 2.0 * std::f64::consts::PI)).ln()
+ / (2.0 * base.ln());
+ if config.truncate {
+ low = low.floor();
+ high = high.ceil();
+ }
+ let low = low.max(0.0) as f32;
+ let mut high = high.min((config.head_dim - 1) as f64) as f32;
+ if low == high {
+ high += 0.001;
+ }
+ let ramp = ((pair_index as f32 - low) / (high - low)).clamp(0.0, 1.0);
+ let smoothing_factor = 1.0 - ramp;
+ let scaled_frequency = inverse_frequency / config.scaling_factor;
+ scaled_frequency * (1.0 - smoothing_factor) + inverse_frequency * smoothing_factor
+ },
+ };
+
+ for (token_index, token_position) in token_positions.iter().enumerate() {
+ let embedding = *token_position as f32 * inverse_frequency;
+ let sine = embedding.sin() * attention_scaling_factor;
+ let cosine = embedding.cos() * attention_scaling_factor;
+ let row_offset = token_index * head_dim;
+ sines[row_offset + pair_index] = sine;
+ sines[row_offset + half_dim + pair_index] = sine;
+ cosines[row_offset + pair_index] = cosine;
+ cosines[row_offset + half_dim + pair_index] = cosine;
+ }
+ }
+
+ let mut sines_allocation = encoder.allocate_constant(sines.len() * std::mem::size_of::<f32>())?;
+ sines_allocation.copyin(sines.as_ref());
+ let mut cosines_allocation = encoder.allocate_constant(cosines.len() * std::mem::size_of::<f32>())?;
+ cosines_allocation.copyin(cosines.as_ref());
+
+ Ok(Self {
+ cosines: cosines_allocation,
+ sines: sines_allocation,
+ dim: *rope_config.head_dim(),
+ })
+ }
+}
diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/state.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/state.rs
new file mode 100644
index 000000000..90f8673e3
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/state.rs
@@ -0,0 +1,236 @@
+use std::any::Any;
+
+use crate::{
+ backends::common::{
+ Backend, Buffer, Context, Encoder, Kernels, SparseBuffer,
+ gpu_types::{Copy, ring::RingParams},
+ kernel::KVCacheUpdateKernel,
+ },
+ data_type::DataType,
+ encodable_block::mixer::{MixerState, attention::Attention},
+};
+
+pub enum AttentionStateType {
+ Full {
+ length: usize,
+ },
+ Ring {
+ offset: usize,
+ length: usize,
+ max_length: usize,
+ },
+}
+
+impl AttentionStateType {
+ pub fn physical_prefix_length(&self) -> usize {
+ match self {
+ Self::Full {
+ length,
+ } => *length,
+ Self::Ring {
+ max_length,
+ ..
+ } => *max_length,
+ }
+ }
+
+ pub fn ring_params(&self) -> Option<RingParams> {
+ let Self::Ring {
+ offset,
+ length,
+ max_length: _,
+ } = self
+ else {
+ return None;
+ };
+
+ Some(RingParams {
+ ring_offset: *offset as u32,
+ ring_length: *length as u32,
+ })
+ }
+}
+
+pub struct AttentionState<B: Backend> {
+ pub cur_context_length: usize,
+ pub elements_prepared: usize,
+ pub element_dim: usize,
+ pub data_type: DataType,
+ pub state_type: AttentionStateType,
+ pub is_sparse: bool,
+ pub keys: Box<dyn Buffer<Backend = B>>,
+ pub values: Box<dyn Buffer<Backend = B>>,
+ pub kv_cache_update: <B::Kernels as Kernels>::KVCacheUpdateKernel,
+}
+
+impl<B: Backend> AttentionState<B> {
+ pub fn create_empty(
+ attention: &Attention<B>,
+ max_context_length: Option<usize>,
+ context: &B::Context,
+ ) -> Result<Self, B::Error> {
+ assert!(attention.is_causal, "Non-causal attention cannot have state");
+
+ if let Some(max_context_length) = max_context_length {
+ assert!(
+ attention.max_rope_length.is_none_or(|max_rope_length| max_context_length <= max_rope_length),
+ "Attention state max_prefix_elements overflows RoPE"
+ );
+ }
+
+ let data_type = attention.data_type;
+
+ let max_prefix_elements = if let Some(sliding_window_size) = attention.sliding_window_size {
+ sliding_window_size
+ } else if let Some(max_context_length) = max_context_length {
+ max_context_length
+ } else {
+ attention
+ .max_rope_length
+ .expect("Cannot create full attention state with unlimited length for with no RoPE")
+ };
+
+ let suffix_capacity = 1024; // TODO: remove hardcoded suffix capacity
+ let max_elements = max_prefix_elements + suffix_capacity;
+ let element_size = attention.num_kv_heads.unwrap() * attention.head_dim;
+ let kv_buffer_bytes = max_elements * element_size * data_type.size_in_bytes();
+
+ let state_type = if let Some(sliding_window_size) = attention.sliding_window_size {
+ AttentionStateType::Ring {
+ offset: 0,
+ length: 0,
+ max_length: sliding_window_size,
+ }
+ } else {
+ AttentionStateType::Full {
+ length: 0,
+ }
+ };
+
+ let is_ring = attention.sliding_window_size.is_some();
+ let is_sparse = !is_ring && context.sparse_buffers_supported();
+
+ let (keys, values): (Box<dyn Buffer<Backend = B>>, Box<dyn Buffer<Backend = B>>) = if is_sparse {
+ (
+ Box::new(context.create_sparse_buffer(kv_buffer_bytes)?),
+ Box::new(context.create_sparse_buffer(kv_buffer_bytes)?),
+ )
+ } else {
+ (Box::new(context.create_buffer(kv_buffer_bytes)?), Box::new(context.create_buffer(kv_buffer_bytes)?))
+ };
+
+ let kv_cache_update = <B::Kernels as Kernels>::KVCacheUpdateKernel::new(context, data_type)?;
+
+ Ok(Self {
+ cur_context_length: 0,
+ elements_prepared: 0,
+ element_dim: element_size,
+ data_type,
+ state_type,
+ is_sparse,
+ keys,
+ values,
+ kv_cache_update,
+ })
+ }
+}
+
+impl<B: Backend> MixerState<B> for AttentionState<B> {
+ fn prepare(
+ &mut self,
+ context_length: usize,
+ suffix_length: usize,
+ context: &B::Context,
+ ) -> Result<(), B::Error> {
+ if !self.is_sparse {
+ return Ok(());
+ }
+
+ let suffix_capacity = 1024; // TODO: remove hardcoded suffix capacity
+ assert!(suffix_length <= suffix_capacity, "attention suffix length exceeds hardcoded capacity");
+ let elements_required = context_length + suffix_length;
+ let bytes_required = elements_required * self.element_dim * self.data_type.size_in_bytes();
+ let bytes_prepared = self.elements_prepared * self.element_dim * self.data_type.size_in_bytes();
+
+ let keys = (self.keys.as_mut() as &mut dyn Any).downcast_mut::<B::SparseBuffer>().unwrap();
+ let values = (self.values.as_mut() as &mut dyn Any).downcast_mut::<B::SparseBuffer>().unwrap();
+
+ for buffer in [keys, values] {
+ let buffer_page_size = buffer.page_size_bytes();
+ let buffer_start_page = bytes_prepared.div_ceil(buffer_page_size);
+ let buffer_end_page = bytes_required.div_ceil(buffer_page_size);
+
+ if buffer_end_page > buffer_start_page {
+ buffer.map(context, &(buffer_start_page..buffer_end_page))?;
+ }
+ }
+
+ self.elements_prepared = elements_required;
+
+ Ok(())
+ }
+
+ fn encode_accept(
+ &mut self,
+ accepted_indices: &[usize],
+ encoder: &mut Encoder<B>,
+ ) -> Result<(), B::Error> {
+ assert!(accepted_indices.is_sorted_by(|a, b| a < b), "invalid accepted indicies");
+
+ let copies = match &mut self.state_type {
+ AttentionStateType::Full {
+ length,
+ } => {
+ let copies = accepted_indices
+ .iter()
+ .copied()
+ .enumerate()
+ .filter(|(index, accepted_index)| index != accepted_index)
+ .map(|(index, accepted_index)| Copy {
+ source: (*length + accepted_index) as u32,
+ destination: (*length + index) as u32,
+ })
+ .collect::<Vec<Copy>>();
+
+ *length += accepted_indices.len();
+
+ copies
+ },
+ AttentionStateType::Ring {
+ offset,
+ length,
+ max_length,
+ } => {
+ let mut copies = Vec::new();
+ for accepted_index in accepted_indices {
+ copies.push(Copy {
+ source: (*max_length + accepted_index) as u32,
+ destination: ((*offset + *length) % *max_length) as u32,
+ });
+
+ if length < max_length {
+ *length += 1;
+ } else {
+ *offset = (*offset + 1) % *max_length;
+ }
+ }
+ copies
+ },
+ };
+
+ for copies_chunk in copies.chunks(B::MAX_INLINE_BYTES / size_of::<Copy>()) {
+ self.kv_cache_update.encode(
+ self.keys.as_mut(),
+ self.values.as_mut(),
+ copies_chunk,
+ copies_chunk.len() as u32,
+ self.element_dim as u32,
+ encoder,
+ );
+ }
+
+ self.cur_context_length += accepted_indices.len();
+
+ Ok(())
+ }
+}
diff --git a/crates/backend-uzu/src/encodable_block/mixer/delta_net.rs b/crates/backend-uzu/src/encodable_block/mixer/delta_net.rs
new file mode 100644
index 000000000..753544f10
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/mixer/delta_net.rs
@@ -0,0 +1,396 @@
+use thiserror::Error;
+
+use crate::{
+ array::size_for_shape,
+ backends::common::{
+ Allocation, AllocationType, Backend, Context, Encoder, Kernels,
+ kernel::{
+ Conv1dPackKernel, DeltaNetConvScanKernel, DeltaNetConvUpdateKernel, DeltaNetNormGateKernel,
+ DeltaNetPrefillKernel, DeltaNetPrefillPrepKernel, DeltaNetUpdateKernel,
+ },
+ },
+ config::token_mixer::delta_net::DeltaNetConfig,
+ data_type::DataType,
+ encodable_block::{
+ batch_topology::BatchTopology,
+ linear::{Linear, LinearBlockError},
+ mixer::{Mixer, MixerState, attention::rope::PrecalculatedRoPE},
+ },
+ parameters::{ParameterLoaderError, ParameterTree},
+ utils::maybe_mut::MaybeMut,
+};
+
+pub struct DeltaNetState<B: Backend> {
+ conv_state: Allocation<B>,
+ ssm_state: Allocation<B>,
+ suffix_length: Option<usize>,
+}
+
+impl<B: Backend> MixerState<B> for DeltaNetState<B> {
+ fn prepare(
+ &mut self,
+ _context_length: usize,
+ _suffix_length: usize,
+ _context: &B::Context,
+ ) -> Result<(), B::Error> {
+ Ok(())
+ }
+
+ fn encode_accept(
+ &mut self,
+ accepted_indices: &[usize],
+ _encoder: &mut Encoder<B>,
+ ) -> Result<(), B::Error> {
+ assert!(self.suffix_length.take() == Some(*accepted_indices.last().unwrap() + 1));
+ Ok(())
+ }
+}
+
+pub struct DeltaNet<B: Backend> {
+ num_heads: usize,
+ head_dim: usize,
+ num_groups: usize,
+ value_head_dim: usize,
+ key_dim: usize,
+ value_dim: usize,
+ conv_dim: usize,
+ total_proj_dim: usize,
+ kernel_size: usize,
+ outer_data_type: DataType,
+ in_projection: Box<dyn Linear<B>>,
+ conv_weight: Allocation<B>,
+ conv_bias: Option<Allocation<B>>,
+ conv_update: <B::Kernels as Kernels>::DeltaNetConvUpdateKernel,
+ conv_pack: <B::Kernels as Kernels>::Conv1dPackKernel,
+ conv_scan: <B::Kernels as Kernels>::DeltaNetConvScanKernel,
+ a_log: Allocation<B>,
+ dt_bias: Allocation<B>,
+ norm_weight: Allocation<B>,
+ norm_epsilon: f32,
+ delta_net_update: <B::Kernels as Kernels>::DeltaNetUpdateKernel,
+ delta_net_prefill_prep: <B::Kernels as Kernels>::DeltaNetPrefillPrepKernel,
+ delta_net_prefill: <B::Kernels as Kernels>::DeltaNetPrefillKernel,
+ delta_net_norm_gate: <B::Kernels as Kernels>::DeltaNetNormGateKernel,
+ out_projection: Box<dyn Linear<B>>,
+}
+
+#[derive(Debug, Error)]
+pub enum DeltaNetNewError<B: Backend> {
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+ #[error("Parameter loader error: {0}")]
+ ParameterLoader(#[from] ParameterLoaderError<B>),
+ #[error("Linear error: {0}")]
+ Linear(#[from] LinearBlockError<B>),
+ #[error("Unsupported configuration: {0}")]
+ UnsupportedConfiguration(String),
+}
+
+impl<B: Backend> DeltaNet<B> {
+ pub fn new(
+ hidden_dim: usize,
+ outer_data_type: DataType,
+ config: &DeltaNetConfig,
+ parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
+ ) -> Result<(Self, Option<Allocation<B>>), DeltaNetNewError<B>> {
+ if config.kernel_size < 2 {
+ return Err(DeltaNetNewError::UnsupportedConfiguration(format!(
+ "kernel_size must be >= 2, got {}",
+ config.kernel_size
+ )));
+ }
+ if config.head_dim != 128 {
+ return Err(DeltaNetNewError::UnsupportedConfiguration(format!(
+ "head_dim must be 128, got {}",
+ config.head_dim
+ )));
+ }
+ if config.value_head_dim != 128 {
+ return Err(DeltaNetNewError::UnsupportedConfiguration(format!(
+ "value_head_dim must be 128, got {}",
+ config.value_head_dim
+ )));
+ }
+
+ let inner_data_type = DataType::F32;
+
+ let key_dim = config.num_groups * config.head_dim;
+ let value_dim = config.num_heads * config.value_head_dim;
+ let conv_dim = key_dim * 2 + value_dim;
+ let total_proj_dim = conv_dim + value_dim + config.num_heads + config.num_heads;
+
+ let (in_projection, in_projection_input_hadamard_factors) =
+ <dyn Linear<B>>::new_extracting_input_hadamard_mixed_precision(
+ hidden_dim,
+ [total_proj_dim],
+ false,
+ context,
+ outer_data_type,
+ outer_data_type,
+ outer_data_type,
+ &parameter_tree.subtree("in_proj")?,
+ )?;
+
+ let conv_config = &config.conv_config;
+ let conv_tree = parameter_tree.subtree("conv")?;
+
+ let conv_weight =
+ conv_tree.leaf("weights")?.validate(&[conv_dim, config.kernel_size], inner_data_type)?.read_allocation()?;
+ let conv_bias = if conv_config.has_biases {
+ Some(conv_tree.leaf("biases")?.validate(&[conv_dim], inner_data_type)?.read_allocation()?)
+ } else {
+ None
+ };
+ let conv_update =
+ <B::Kernels as Kernels>::DeltaNetConvUpdateKernel::new(context, outer_data_type, conv_config.has_biases)
+ .map_err(DeltaNetNewError::Backend)?;
+ let conv_pack = <B::Kernels as Kernels>::Conv1dPackKernel::new(context, inner_data_type, outer_data_type)
+ .map_err(DeltaNetNewError::Backend)?;
+ let conv_scan =
+ <B::Kernels as Kernels>::DeltaNetConvScanKernel::new(context, outer_data_type, conv_config.has_biases)
+ .map_err(DeltaNetNewError::Backend)?;
+
+ let a_log = parameter_tree.leaf("a_log")?.validate(&[config.num_heads], inner_data_type)?.read_allocation()?;
+ let dt_bias =
+ parameter_tree.leaf("dt_bias")?.validate(&[config.num_heads], inner_data_type)?.read_allocation()?;
+ let norm_weight = parameter_tree
+ .leaf("norm.scales")?
+ .validate(&[config.value_head_dim], inner_data_type)?
+ .read_allocation()?;
+ let norm_epsilon = config.norm_config.epsilon;
+ let delta_net_update =
+ <B::Kernels as Kernels>::DeltaNetUpdateKernel::new(context, outer_data_type, config.head_dim as u32)
+ .map_err(DeltaNetNewError::Backend)?;
+ let delta_net_prefill_prep =
+ <B::Kernels as Kernels>::DeltaNetPrefillPrepKernel::new(context, outer_data_type, config.head_dim as u32)
+ .map_err(DeltaNetNewError::Backend)?;
+ let delta_net_prefill =
+ <B::Kernels as Kernels>::DeltaNetPrefillKernel::new(context, outer_data_type, config.head_dim as u32)
+ .map_err(DeltaNetNewError::Backend)?;
+ let delta_net_norm_gate = <B::Kernels as Kernels>::DeltaNetNormGateKernel::new(context, outer_data_type)
+ .map_err(DeltaNetNewError::Backend)?;
+
+ let out_projection = <dyn Linear<B>>::new_mixed_precision(
+ value_dim,
+ [hidden_dim],
+ false,
+ context,
+ outer_data_type,
+ outer_data_type,
+ outer_data_type,
+ &parameter_tree.subtree("out_proj")?,
+ )?;
+
+ Ok((
+ Self {
+ num_heads: config.num_heads,
+ head_dim: config.head_dim,
+ num_groups: config.num_groups,
+ value_head_dim: config.value_head_dim,
+ key_dim,
+ value_dim,
+ conv_dim,
+ total_proj_dim,
+ kernel_size: config.kernel_size,
+ outer_data_type,
+ in_projection,
+ conv_weight,
+ conv_bias,
+ conv_update,
+ conv_pack,
+ conv_scan,
+ a_log,
+ dt_bias,
+ norm_weight,
+ norm_epsilon,
+ delta_net_update,
+ delta_net_prefill_prep,
+ delta_net_prefill,
+ delta_net_norm_gate,
+ out_projection,
+ },
+ in_projection_input_hadamard_factors,
+ ))
+ }
+}
+
+impl<B: Backend> Mixer<B> for DeltaNet<B> {
+ fn speculation_supported(&self) -> bool {
+ false
+ }
+
+ fn max_context_length(&self) -> Option<usize> {
+ None
+ }
+
+ fn create_empty_state(
+ &self,
+ _max_context_length: Option<usize>,
+ context: &B::Context,
+ ) -> Result<Box<dyn MixerState<B>>, B::Error> {
+ let mut conv_state = context.create_allocation(
+ size_for_shape(&[self.conv_dim, self.kernel_size - 1], DataType::F32),
+ AllocationType::Global,
+ )?;
+
+ let mut ssm_state = context.create_allocation(
+ size_for_shape(&[self.num_heads, self.value_head_dim, self.head_dim], DataType::F32),
+ AllocationType::Global,
+ )?;
+
+ let mut zero_encoder = Encoder::<B>::new(context)?;
+ zero_encoder.encode_fill(&mut conv_state, 0);
+ zero_encoder.encode_fill(&mut ssm_state, 0);
+ zero_encoder.end_encoding().submit().wait_until_completed()?;
+
+ Ok(Box::new(DeltaNetState {
+ conv_state,
+ ssm_state,
+ suffix_length: None,
+ }))
+ }
+
+ fn encode(
+ &self,
+ hidden: Allocation<B>,
+ precalculated_rope: Option<&PrecalculatedRoPE<B>>,
+ batch_dim: &BatchTopology,
+ state: Option<MaybeMut<dyn MixerState<B>>>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error> {
+ assert!(precalculated_rope.is_none(), "unexpected rope for delta net mixer");
+
+ if !batch_dim.full_accept() {
+ panic!("delta net doesn't support speculation");
+ }
+
+ let state = state.expect("delta net requires state");
+ let state = state.downcast::<DeltaNetState<B>>().expect("incorrect type of delta net state");
+ let MaybeMut::Mut(state) = state else {
+ panic!("delta net doesn't support immutable state");
+ };
+
+ assert!(state.suffix_length.is_none(), "delta net called with state with unaccepted tokens");
+
+ let mut in_projected = self.in_projection.encode(hidden, batch_dim.size(), encoder)?;
+
+ let mut delta_output =
+ encoder.allocate_scratch(size_for_shape(&[batch_dim.size(), self.value_dim], self.outer_data_type))?;
+ if batch_dim.size() == 1 {
+ self.conv_update.encode(
+ &self.conv_weight,
+ self.conv_bias.as_ref(),
+ &mut in_projected,
+ &mut state.conv_state,
+ self.kernel_size as u32,
+ self.conv_dim as u32,
+ (self.kernel_size - 1) as u32,
+ encoder,
+ );
+
+ self.delta_net_update.encode(
+ &in_projected,
+ &self.a_log,
+ &self.dt_bias,
+ &self.norm_weight,
+ &mut state.ssm_state,
+ &mut delta_output,
+ self.num_heads as u32,
+ self.num_groups as u32,
+ self.value_head_dim as u32,
+ self.key_dim as u32,
+ self.value_dim as u32,
+ self.norm_epsilon,
+ encoder,
+ );
+ } else {
+ let mut padded = encoder.allocate_scratch(size_for_shape(
+ &[batch_dim.size() + self.kernel_size - 1, self.total_proj_dim],
+ DataType::F32,
+ ))?;
+ self.conv_pack.encode(
+ &state.conv_state,
+ &in_projected,
+ &mut padded,
+ (self.kernel_size - 1) as u32,
+ self.total_proj_dim as u32,
+ batch_dim.size() as u32,
+ self.conv_dim as u32,
+ encoder,
+ );
+ self.conv_scan.encode(
+ &padded,
+ &self.conv_weight,
+ self.conv_bias.as_ref(),
+ &mut in_projected,
+ &mut state.conv_state,
+ batch_dim.size() as u32,
+ self.kernel_size as u32,
+ self.total_proj_dim as u32,
+ (self.kernel_size - 1) as u32,
+ self.conv_dim as u32,
+ self.total_proj_dim as u32,
+ encoder,
+ );
+
+ let mut prep_q_norm =
+ encoder.allocate_scratch(size_for_shape(&[batch_dim.size(), self.key_dim], DataType::F32))?;
+ let mut prep_k_norm =
+ encoder.allocate_scratch(size_for_shape(&[batch_dim.size(), self.key_dim], DataType::F32))?;
+ let mut prep_beta =
+ encoder.allocate_scratch(size_for_shape(&[batch_dim.size(), self.num_heads], DataType::F32))?;
+ let mut prep_decay =
+ encoder.allocate_scratch(size_for_shape(&[batch_dim.size(), self.num_heads], DataType::F32))?;
+ self.delta_net_prefill_prep.encode(
+ &in_projected,
+ &self.a_log,
+ &self.dt_bias,
+ &mut prep_q_norm,
+ &mut prep_k_norm,
+ &mut prep_beta,
+ &mut prep_decay,
+ self.num_heads as u32,
+ self.num_groups as u32,
+ self.key_dim as u32,
+ self.value_dim as u32,
+ batch_dim.size() as u32,
+ encoder,
+ );
+ self.delta_net_prefill.encode(
+ &prep_q_norm,
+ &prep_k_norm,
+ &prep_beta,
+ &prep_decay,
+ &in_projected,
+ &mut state.ssm_state,
+ &mut delta_output,
+ self.num_heads as u32,
+ self.num_groups as u32,
+ self.value_head_dim as u32,
+ self.key_dim as u32,
+ self.value_dim as u32,
+ batch_dim.size() as u32,
+ self.value_head_dim.div_ceil(16) as u32,
+ encoder,
+ );
+ self.delta_net_norm_gate.encode(
+ &mut delta_output,
+ &in_projected,
+ &self.norm_weight,
+ self.num_heads as u32,
+ self.value_head_dim as u32,
+ self.value_dim as u32,
+ self.conv_dim as u32,
+ self.total_proj_dim as u32,
+ self.norm_epsilon,
+ batch_dim.size() as u32,
+ encoder,
+ );
+ }
+
+ state.suffix_length = Some(batch_dim.size());
+
+ self.out_projection.encode(delta_output, batch_dim.size(), encoder)
+ }
+}
diff --git a/crates/backend-uzu/src/encodable_block/mixer/mamba2.rs b/crates/backend-uzu/src/encodable_block/mixer/mamba2.rs
new file mode 100644
index 000000000..757bc9a74
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/mixer/mamba2.rs
@@ -0,0 +1,448 @@
+use thiserror::Error;
+
+use crate::{
+ array::size_for_shape,
+ backends::common::{
+ Allocation, AllocationType, Backend, Context, Encoder, Kernels,
+ gpu_types::ActivationType,
+ kernel::{
+ Conv1dDecodeKernel, Conv1dPackKernel, Conv1dScanKernel, SSDPrefill64Kernel, SSDPrefillKernel,
+ SSDUpdateKernel, SplitInProjKernel,
+ },
+ },
+ config::token_mixer::mamba2::Mamba2Config,
+ data_type::DataType,
+ encodable_block::{
+ batch_topology::BatchTopology,
+ linear::{Linear, LinearBlockError},
+ mixer::{Mixer, MixerState, attention::rope::PrecalculatedRoPE},
+ },
+ parameters::{ParameterLoaderError, ParameterTree},
+ utils::maybe_mut::MaybeMut,
+};
+
+pub struct Mamba2State<B: Backend> {
+ conv_state: Allocation<B>,
+ ssm_state: Allocation<B>,
+ suffix_length: Option<usize>,
+}
+
+impl<B: Backend> MixerState<B> for Mamba2State<B> {
+ fn prepare(
+ &mut self,
+ _context_length: usize,
+ _suffix_length: usize,
+ _context: &B::Context,
+ ) -> Result<(), B::Error> {
+ Ok(())
+ }
+
+ fn encode_accept(
+ &mut self,
+ accepted_indices: &[usize],
+ _encoder: &mut Encoder<B>,
+ ) -> Result<(), <B as Backend>::Error> {
+ assert!(self.suffix_length.take() == Some(*accepted_indices.last().unwrap() + 1));
+ Ok(())
+ }
+}
+
+enum Mamba2SSDPrefillVariant<B: Backend> {
+ Universal(<B::Kernels as Kernels>::SSDPrefillKernel),
+ Special64(<B::Kernels as Kernels>::SSDPrefill64Kernel),
+}
+
+pub struct Mamba2<B: Backend> {
+ kernel_size: usize,
+ num_heads: usize,
+ num_groups: usize,
+ head_dim: usize,
+ state_dim: usize,
+ inner_dim: usize,
+ conv_dim: usize,
+ inner_data_type: DataType,
+ activation_type: ActivationType,
+ in_projection: Box<dyn Linear<B>>,
+ gate_bias: Allocation<B>,
+ split_inproj: <B::Kernels as Kernels>::SplitInProjKernel,
+ conv_weight: Allocation<B>,
+ conv_bias: Option<Allocation<B>>,
+ conv_decode: <B::Kernels as Kernels>::Conv1dDecodeKernel,
+ conv_pack: <B::Kernels as Kernels>::Conv1dPackKernel,
+ conv_scan: <B::Kernels as Kernels>::Conv1dScanKernel,
+ skip_connection_weight: Allocation<B>,
+ ssd_update: <B::Kernels as Kernels>::SSDUpdateKernel,
+ ssd_prefill: Mamba2SSDPrefillVariant<B>,
+ out_projection: Box<dyn Linear<B>>,
+}
+
+#[derive(Debug, Error)]
+pub enum Mamba2NewError<B: Backend> {
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+ #[error("Parameter loader error: {0}")]
+ ParameterLoader(#[from] ParameterLoaderError<B>),
+ #[error("Linear error: {0}")]
+ Linear(#[from] LinearBlockError<B>),
+ #[error("Unsupported configuration: {0}")]
+ UnsupportedConfiguration(String),
+}
+
+impl<B: Backend> Mamba2<B> {
+ pub fn new(
+ hidden_dim: usize,
+ outer_data_type: DataType,
+ config: &Mamba2Config,
+ parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
+ ) -> Result<(Self, Option<Allocation<B>>), Mamba2NewError<B>> {
+ let inner_data_type = DataType::F32;
+
+ let kernel_size = config.kernel_size;
+ let num_heads = config.num_heads;
+ let num_groups = config.num_groups;
+ let head_dim = config.head_dim;
+ let state_dim = config.state_dim;
+
+ let inner_dim = num_heads * head_dim;
+ let conv_dim = inner_dim + 2 * num_groups * state_dim;
+
+ let activation_type = config.activation.act_type();
+
+ if kernel_size <= 1 {
+ return Err(Mamba2NewError::UnsupportedConfiguration(format!("kernel_size = {kernel_size} (must be > 1)")));
+ }
+
+ let (in_projection, in_projection_input_hadamard_factors) =
+ <dyn Linear<B>>::new_extracting_input_hadamard_mixed_precision(
+ hidden_dim,
+ [conv_dim, inner_dim, num_heads],
+ config.has_in_biases,
+ context,
+ outer_data_type,
+ outer_data_type,
+ inner_data_type,
+ &parameter_tree.subtree("in_projection")?,
+ )?;
+
+ let gate_bias = parameter_tree.leaf("gate_bias")?.validate(&[inner_dim], inner_data_type)?.read_allocation()?;
+ let split_inproj = <B::Kernels as Kernels>::SplitInProjKernel::new(context, inner_data_type)
+ .map_err(Mamba2NewError::Backend)?;
+
+ let conv_config = &config.conv_config;
+ let conv_tree = parameter_tree.subtree("conv")?;
+
+ let conv_weight =
+ conv_tree.leaf("weights")?.validate(&[conv_dim, kernel_size], inner_data_type)?.read_allocation()?;
+ let conv_bias = if conv_config.has_biases {
+ Some(conv_tree.leaf("biases")?.validate(&[conv_dim], inner_data_type)?.read_allocation()?)
+ } else {
+ None
+ };
+ let conv_decode =
+ <B::Kernels as Kernels>::Conv1dDecodeKernel::new(context, inner_data_type, conv_config.has_biases, true)
+ .map_err(Mamba2NewError::Backend)?;
+ let conv_pack = <B::Kernels as Kernels>::Conv1dPackKernel::new(context, inner_data_type, inner_data_type)
+ .map_err(Mamba2NewError::Backend)?;
+ let conv_scan =
+ <B::Kernels as Kernels>::Conv1dScanKernel::new(context, inner_data_type, conv_config.has_biases)
+ .map_err(Mamba2NewError::Backend)?;
+
+ let skip_connection_weight = parameter_tree
+ .leaf("skip_connection_weight")?
+ .validate(&[num_heads], inner_data_type)?
+ .read_allocation()?;
+ let ssd_update = <B::Kernels as Kernels>::SSDUpdateKernel::new(context, inner_data_type, true)
+ .map_err(Mamba2NewError::Backend)?;
+
+ let ssd_prefill = if state_dim == 64 {
+ Mamba2SSDPrefillVariant::Special64(
+ <B::Kernels as Kernels>::SSDPrefill64Kernel::new(context, inner_data_type)
+ .map_err(Mamba2NewError::Backend)?,
+ )
+ } else {
+ Mamba2SSDPrefillVariant::Universal(
+ <B::Kernels as Kernels>::SSDPrefillKernel::new(context, inner_data_type)
+ .map_err(Mamba2NewError::Backend)?,
+ )
+ };
+
+ let out_projection = <dyn Linear<B>>::new_mixed_precision(
+ inner_dim,
+ [hidden_dim],
+ config.has_out_biases,
+ context,
+ outer_data_type,
+ inner_data_type,
+ outer_data_type,
+ &parameter_tree.subtree("out_projection")?,
+ )?;
+
+ Ok((
+ Self {
+ kernel_size,
+ num_heads,
+ num_groups,
+ head_dim,
+ state_dim,
+ inner_dim,
+ conv_dim,
+ inner_data_type,
+ activation_type,
+ in_projection,
+ gate_bias,
+ split_inproj,
+ conv_weight,
+ conv_bias,
+ conv_decode,
+ conv_pack,
+ conv_scan,
+ skip_connection_weight,
+ ssd_update,
+ ssd_prefill,
+ out_projection,
+ },
+ in_projection_input_hadamard_factors,
+ ))
+ }
+}
+
+impl<B: Backend> Mixer<B> for Mamba2<B> {
+ fn speculation_supported(&self) -> bool {
+ false
+ }
+
+ fn max_context_length(&self) -> Option<usize> {
+ None
+ }
+
+ fn create_empty_state(
+ &self,
+ _max_context_length: Option<usize>,
+ context: &B::Context,
+ ) -> Result<Box<dyn MixerState<B>>, B::Error> {
+ let mut conv_state = context.create_allocation(
+ size_for_shape(&[self.conv_dim, self.kernel_size - 1], DataType::F32),
+ AllocationType::Global,
+ )?;
+
+ let mut ssm_state = context.create_allocation(
+ size_for_shape(&[self.num_heads, self.head_dim, self.state_dim], DataType::F32),
+ AllocationType::Global,
+ )?;
+
+ let mut zero_encoder = Encoder::<B>::new(context)?;
+ zero_encoder.encode_fill(&mut conv_state, 0);
+ zero_encoder.encode_fill(&mut ssm_state, 0);
+ zero_encoder.end_encoding().submit().wait_until_completed()?;
+
+ Ok(Box::new(Mamba2State {
+ conv_state,
+ ssm_state,
+ suffix_length: None,
+ }))
+ }
+
+ fn encode(
+ &self,
+ hidden: Allocation<B>,
+ precalculated_rope: Option<&PrecalculatedRoPE<B>>,
+ batch_dim: &BatchTopology,
+ state: Option<MaybeMut<dyn MixerState<B>>>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error> {
+ assert!(precalculated_rope.is_none(), "unexpected rope for mamba2 mixer");
+
+ if !batch_dim.full_accept() {
+ panic!("mamba2 doesn't support speculation");
+ }
+
+ let state = state.expect("mamba2 requires state");
+ let state = state.downcast::<Mamba2State<B>>().expect("incorrect type of mamba2 state");
+ let MaybeMut::Mut(state) = state else {
+ panic!("mamba2 doesn't support immutable state");
+ };
+
+ assert!(state.suffix_length.is_none(), "mamba2 called with state with unaccepted tokens");
+
+ let in_projected = self.in_projection.encode(hidden, batch_dim.size(), encoder)?;
+
+ let mut conv_inputs =
+ encoder.allocate_scratch(size_for_shape(&[batch_dim.size(), self.conv_dim], self.inner_data_type))?;
+ let mut gate = encoder.allocate_scratch(size_for_shape(
+ &[batch_dim.size(), self.num_heads, self.head_dim],
+ self.inner_data_type,
+ ))?;
+ let mut time_step =
+ encoder.allocate_scratch(size_for_shape(&[batch_dim.size(), self.num_heads], self.inner_data_type))?;
+ self.split_inproj.encode(
+ &in_projected,
+ &mut conv_inputs,
+ &mut gate,
+ &mut time_step,
+ &self.gate_bias,
+ batch_dim.size() as u32,
+ (self.conv_dim + self.inner_dim + self.num_heads) as u32,
+ self.conv_dim as u32,
+ self.inner_dim as u32,
+ self.num_heads as u32,
+ encoder,
+ );
+
+ let mut conv_x = encoder.allocate_scratch(size_for_shape(
+ &[batch_dim.size(), self.num_heads, self.head_dim],
+ self.inner_data_type,
+ ))?;
+ let mut state_b = encoder.allocate_scratch(size_for_shape(
+ &[batch_dim.size(), self.num_groups, self.state_dim],
+ self.inner_data_type,
+ ))?;
+ let mut state_c = encoder.allocate_scratch(size_for_shape(
+ &[batch_dim.size(), self.num_groups, self.state_dim],
+ self.inner_data_type,
+ ))?;
+ let state_stride = self.kernel_size - 1;
+ if batch_dim.size() == 1 {
+ self.conv_decode.encode(
+ &conv_inputs,
+ &self.conv_weight,
+ self.conv_bias.as_ref(),
+ None::<&Allocation<B>>,
+ &mut conv_x,
+ &mut state_b,
+ &mut state_c,
+ &mut state.conv_state,
+ self.kernel_size as u32,
+ self.conv_dim as u32,
+ state_stride as u32,
+ self.conv_dim as u32,
+ batch_dim.size() as u32,
+ self.inner_dim as u32,
+ (self.num_groups * self.state_dim) as u32,
+ self.activation_type,
+ encoder,
+ );
+ } else {
+ let mut padded = encoder.allocate_scratch(size_for_shape(
+ &[batch_dim.size() + state_stride, self.conv_dim],
+ self.inner_data_type,
+ ))?;
+ self.conv_pack.encode(
+ &state.conv_state,
+ &conv_inputs,
+ &mut padded,
+ state_stride as u32,
+ self.conv_dim as u32,
+ batch_dim.size() as u32,
+ self.conv_dim as u32,
+ encoder,
+ );
+ self.conv_scan.encode(
+ &padded,
+ &self.conv_weight,
+ self.conv_bias.as_ref(),
+ &mut conv_x,
+ &mut state_b,
+ &mut state_c,
+ &mut state.conv_state,
+ batch_dim.size() as u32,
+ self.kernel_size as u32,
+ self.conv_dim as u32,
+ state_stride as u32,
+ self.conv_dim as u32,
+ self.inner_dim as u32,
+ (self.num_groups * self.state_dim) as u32,
+ self.activation_type,
+ encoder,
+ );
+ }
+
+ let mut ssd_output =
+ encoder.allocate_scratch(size_for_shape(&[batch_dim.size(), self.inner_dim], self.inner_data_type))?;
+ let x_strides = [(self.num_heads * self.head_dim) as u32, self.head_dim as u32, 1];
+ let dt_strides = [self.num_heads as u32, 1];
+ let cb_strides = [(self.num_groups * self.state_dim) as u32, self.state_dim as u32, 1];
+ let group_size = self.num_heads / self.num_groups;
+ if batch_dim.size() == 1 {
+ let state_strides = [
+ (self.num_heads * self.head_dim * self.state_dim) as u32,
+ (self.head_dim * self.state_dim) as u32,
+ self.state_dim as u32,
+ 1,
+ ];
+ self.ssd_update.encode(
+ &conv_x,
+ &time_step,
+ &state_b,
+ &state_c,
+ &self.skip_connection_weight,
+ &gate,
+ None::<&Allocation<B>>,
+ &mut ssd_output,
+ &mut state.ssm_state,
+ group_size as u32,
+ self.state_dim as u32,
+ &x_strides,
+ &dt_strides,
+ &cb_strides,
+ &state_strides,
+ batch_dim.size() as u32,
+ self.num_heads as u32,
+ self.head_dim as u32,
+ encoder,
+ );
+ } else {
+ let state_strides = [(self.head_dim * self.state_dim) as u32, self.state_dim as u32, 1];
+ match &self.ssd_prefill {
+ Mamba2SSDPrefillVariant::Universal(ssd_prefill) => ssd_prefill.encode(
+ &conv_x,
+ &time_step,
+ &state_b,
+ &state_c,
+ &self.skip_connection_weight,
+ &gate,
+ &mut state.ssm_state,
+ &mut ssd_output,
+ batch_dim.size() as u32,
+ group_size as u32,
+ self.state_dim as u32,
+ &x_strides,
+ &dt_strides,
+ &cb_strides,
+ &state_strides,
+ self.num_heads as u32,
+ self.head_dim as u32,
+ encoder,
+ ),
+ Mamba2SSDPrefillVariant::Special64(ssd_prefill) => ssd_prefill.encode(
+ &conv_x,
+ &time_step,
+ &state_b,
+ &state_c,
+ &self.skip_connection_weight,
+ &gate,
+ &mut state.ssm_state,
+ &mut ssd_output,
+ batch_dim.size() as u32,
+ group_size as u32,
+ self.state_dim as u32,
+ &x_strides,
+ &dt_strides,
+ &cb_strides,
+ &state_strides,
+ self.num_heads as u32,
+ self.head_dim as u32,
+ encoder,
+ ),
+ }
+ }
+
+ state.suffix_length = Some(batch_dim.size());
+
+ self.out_projection.encode(ssd_output, batch_dim.size(), encoder)
+ }
+}
+
+#[cfg(test)]
+#[path = "../../../unit/encodable_block/mamba_mixer/ssd_prefill_test.rs"]
+mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/mixer/mod.rs b/crates/backend-uzu/src/encodable_block/mixer/mod.rs
new file mode 100644
index 000000000..fd73c1360
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/mixer/mod.rs
@@ -0,0 +1,126 @@
+use std::any::Any;
+
+use thiserror::Error;
+
+use crate::{
+ backends::common::{Allocation, Backend, Encoder},
+ config::{rope::AnyRoPEConfig, token_mixer::AnyTokenMixerConfig},
+ data_type::DataType,
+ encodable_block::{
+ batch_topology::BatchTopology,
+ mixer::{
+ attention::{Attention, AttentionNewError, rope::PrecalculatedRoPE},
+ delta_net::{DeltaNet, DeltaNetNewError},
+ mamba2::{Mamba2, Mamba2NewError},
+ short_conv::{ShortConv, ShortConvNewError},
+ },
+ },
+ parameters::ParameterTree,
+ utils::maybe_mut::MaybeMut,
+};
+
+pub mod attention;
+pub mod delta_net;
+pub mod mamba2;
+pub mod short_conv;
+
+pub trait MixerState<B: Backend>: Any {
+ fn prepare(
+ &mut self,
+ context_length: usize,
+ suffix_length: usize,
+ context: &B::Context,
+ ) -> Result<(), B::Error>;
+
+ fn encode_accept(
+ &mut self,
+ accepted_indices: &[usize],
+ encoder: &mut Encoder<B>,
+ ) -> Result<(), B::Error>;
+}
+
+impl<'a, B: Backend> MaybeMut<'a, dyn MixerState<B>> {
+ pub fn downcast<T: MixerState<B>>(self) -> Option<MaybeMut<'a, T>> {
+ match self {
+ MaybeMut::Const(value) => (value as &dyn Any).downcast_ref::<T>().map(MaybeMut::Const),
+ MaybeMut::Mut(value) => (value as &mut dyn Any).downcast_mut::<T>().map(MaybeMut::Mut),
+ }
+ }
+}
+
+pub trait Mixer<B: Backend> {
+ fn speculation_supported(&self) -> bool;
+
+ fn max_context_length(&self) -> Option<usize>;
+
+ fn create_empty_state(
+ &self,
+ max_context_length: Option<usize>,
+ context: &B::Context,
+ ) -> Result<Box<dyn MixerState<B>>, B::Error>;
+
+ fn encode(
+ &self,
+ hidden: Allocation<B>,
+ precalculated_rope: Option<&PrecalculatedRoPE<B>>,
+ batch_dim: &BatchTopology,
+ state: Option<MaybeMut<dyn MixerState<B>>>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error>;
+}
+
+#[derive(Debug, Error)]
+pub enum MixerNewError<B: Backend> {
+ #[error("Attention mixer error: {0}")]
+ Attention(#[from] AttentionNewError<B>),
+ #[error("Delta net mixer error: {0}")]
+ DeltaNet(#[from] DeltaNetNewError<B>),
+ #[error("Mamba2 mixer error: {0}")]
+ Mamba2(#[from] Mamba2NewError<B>),
+ #[error("Short conv mixer error: {0}")]
+ ShortConv(#[from] ShortConvNewError<B>),
+}
+
+impl<B: Backend> dyn Mixer<B> {
+ pub fn new(
+ hidden_dim: usize,
+ data_type: DataType,
+ rope_config: Option<&AnyRoPEConfig>,
+ config: &AnyTokenMixerConfig,
+ parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
+ ) -> Result<(Box<dyn Mixer<B>>, Option<Allocation<B>>), MixerNewError<B>> {
+ match config {
+ AnyTokenMixerConfig::AttentionConfig(config) => {
+ let (attention, in_projection_input_hadamard_factors) =
+ Attention::new(hidden_dim, data_type, rope_config, config, parameter_tree, context)?;
+
+ Ok((Box::new(attention), in_projection_input_hadamard_factors))
+ },
+ AnyTokenMixerConfig::DeltaNetConfig(config) => {
+ assert!(rope_config.is_none(), "unexpected rope for delta net mixer");
+
+ let (delta_net, in_projection_input_hadamard_factors) =
+ DeltaNet::new(hidden_dim, data_type, config, parameter_tree, context)?;
+
+ Ok((Box::new(delta_net), in_projection_input_hadamard_factors))
+ },
+ AnyTokenMixerConfig::Mamba2Config(config) => {
+ assert!(rope_config.is_none(), "unexpected rope for mamba2 mixer");
+
+ let (mamba2, in_projection_input_hadamard_factors) =
+ Mamba2::new(hidden_dim, data_type, config, parameter_tree, context)?;
+
+ Ok((Box::new(mamba2), in_projection_input_hadamard_factors))
+ },
+ AnyTokenMixerConfig::ShortConvConfig(config) => {
+ assert!(rope_config.is_none(), "unexpected rope for short conv mixer");
+
+ let (short_conv, in_projection_input_hadamard_factors) =
+ ShortConv::new(hidden_dim, data_type, config, parameter_tree, context)?;
+
+ Ok((Box::new(short_conv), in_projection_input_hadamard_factors))
+ },
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/encodable_block/mixer/short_conv.rs b/crates/backend-uzu/src/encodable_block/mixer/short_conv.rs
new file mode 100644
index 000000000..b17c704f6
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/mixer/short_conv.rs
@@ -0,0 +1,355 @@
+use thiserror::Error;
+
+use crate::{
+ array::size_for_shape,
+ backends::common::{
+ Allocation, AllocationType, Backend, Context, Encoder, Kernels,
+ kernel::{ShortConvDecodeKernel, ShortConvPackKernel, ShortConvPrefillKernel, ShortConvTrieKernel},
+ },
+ config::token_mixer::short_conv::ShortConvConfig,
+ data_type::DataType,
+ encodable_block::{
+ batch_topology::BatchTopology,
+ linear::{Linear, LinearBlockError},
+ mixer::{Mixer, MixerState, attention::rope::PrecalculatedRoPE},
+ },
+ parameters::{ParameterLoaderError, ParameterTree},
+ utils::maybe_mut::MaybeMut,
+};
+
+enum ShortConvStateSuffixStatus<B: Backend> {
+ Flat {
+ suffix_length: usize,
+ },
+ Trie {
+ conv_states: Allocation<B>,
+ },
+}
+
+pub struct ShortConvState<B: Backend> {
+ conv_state: Allocation<B>,
+ suffix_state: Option<ShortConvStateSuffixStatus<B>>,
+}
+
+impl<B: Backend> MixerState<B> for ShortConvState<B> {
+ fn prepare(
+ &mut self,
+ _context_length: usize,
+ _suffix_length: usize,
+ _context: &B::Context,
+ ) -> Result<(), B::Error> {
+ Ok(())
+ }
+
+ fn encode_accept(
+ &mut self,
+ accepted_indices: &[usize],
+ encoder: &mut Encoder<B>,
+ ) -> Result<(), B::Error> {
+ let suffix_state_type =
+ self.suffix_state.take().expect("Called short conv state encode accept on a state with nothing to accept");
+
+ let accepted_index = *accepted_indices.last().expect("short conv state attempted to accept zero indicies");
+
+ match suffix_state_type {
+ ShortConvStateSuffixStatus::Flat {
+ suffix_length,
+ } => {
+ assert!(accepted_index == suffix_length - 1, "attempted to do a partial flat short conv state accept");
+ Ok(())
+ },
+ ShortConvStateSuffixStatus::Trie {
+ conv_states,
+ } => {
+ let conv_state_size = self.conv_state.size();
+ encoder.encode_copy(
+ &conv_states,
+ (accepted_index * conv_state_size)..((accepted_index + 1) * conv_state_size),
+ &mut self.conv_state,
+ ..,
+ );
+ Ok(())
+ },
+ }
+ }
+}
+
+pub struct ShortConv<B: Backend> {
+ hidden_dim: usize,
+ data_type: DataType,
+ kernel_size: usize,
+ in_projection: Box<dyn Linear<B>>,
+ out_projection: Box<dyn Linear<B>>,
+ short_conv_pack: <B::Kernels as Kernels>::ShortConvPackKernel,
+ short_conv_prefill: <B::Kernels as Kernels>::ShortConvPrefillKernel,
+ short_conv_decode: <B::Kernels as Kernels>::ShortConvDecodeKernel,
+ short_conv_trie: <B::Kernels as Kernels>::ShortConvTrieKernel,
+ conv_weight: Allocation<B>,
+ conv_bias: Option<Allocation<B>>,
+}
+
+#[derive(Debug, Error)]
+pub enum ShortConvNewError<B: Backend> {
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+ #[error("Parameter loader error: {0}")]
+ ParameterLoader(#[from] ParameterLoaderError<B>),
+ #[error("Linear error: {0}")]
+ Linear(#[from] LinearBlockError<B>),
+ #[error("Unsupported configuration: {0}")]
+ UnsupportedConfiguration(String),
+}
+
+impl<B: Backend> ShortConv<B> {
+ pub fn new(
+ hidden_dim: usize,
+ data_type: DataType,
+ config: &ShortConvConfig,
+ parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
+ ) -> Result<(Self, Option<Allocation<B>>), ShortConvNewError<B>> {
+ let kernel_size = config.kernel_size;
+ if kernel_size < 2 {
+ return Err(ShortConvNewError::UnsupportedConfiguration(format!(
+ "kernel_size must be >= 2, got {}",
+ kernel_size
+ )));
+ }
+
+ let (in_projection, in_projection_input_hadamard_factors) = <dyn Linear<B>>::new_extracting_input_hadamard(
+ hidden_dim,
+ [hidden_dim * 3],
+ false,
+ context,
+ data_type,
+ &parameter_tree.subtree("in_projection")?,
+ )?;
+
+ let out_projection = <dyn Linear<B>>::new(
+ hidden_dim,
+ [hidden_dim],
+ false,
+ context,
+ data_type,
+ &parameter_tree.subtree("out_projection")?,
+ )?;
+
+ let conv_tree = parameter_tree.subtree("conv")?;
+
+ let conv_data_type = DataType::F32;
+ let conv_weight =
+ conv_tree.leaf("weights")?.validate(&[hidden_dim, kernel_size], conv_data_type)?.read_allocation()?;
+
+ let has_bias = config.conv_config.has_biases;
+ let conv_bias = if has_bias {
+ Some(conv_tree.leaf("biases")?.validate(&[hidden_dim], conv_data_type)?.read_allocation()?)
+ } else {
+ None
+ };
+
+ let short_conv_pack = <B::Kernels as Kernels>::ShortConvPackKernel::new(context, data_type)
+ .map_err(ShortConvNewError::Backend)?;
+ let short_conv_prefill =
+ <B::Kernels as Kernels>::ShortConvPrefillKernel::new(context, data_type, conv_data_type, has_bias)
+ .map_err(ShortConvNewError::Backend)?;
+ let short_conv_decode =
+ <B::Kernels as Kernels>::ShortConvDecodeKernel::new(context, data_type, conv_data_type, has_bias, true)
+ .map_err(ShortConvNewError::Backend)?;
+ let short_conv_trie =
+ <B::Kernels as Kernels>::ShortConvTrieKernel::new(context, data_type, conv_data_type, has_bias)
+ .map_err(ShortConvNewError::Backend)?;
+
+ Ok((
+ Self {
+ hidden_dim,
+ data_type,
+ kernel_size,
+ in_projection,
+ out_projection,
+ short_conv_pack,
+ short_conv_prefill,
+ short_conv_decode,
+ short_conv_trie,
+ conv_weight,
+ conv_bias,
+ },
+ in_projection_input_hadamard_factors,
+ ))
+ }
+
+ fn encode_decode_conv(
+ &self,
+ in_projected: &Allocation<B>,
+ state: &mut ShortConvState<B>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error> {
+ let mut conv_output = encoder.allocate_scratch(size_for_shape(&[self.hidden_dim], self.data_type))?;
+ self.short_conv_decode.encode(
+ in_projected,
+ &self.conv_weight,
+ self.conv_bias.as_ref(),
+ None::<&Allocation<B>>,
+ &mut conv_output,
+ &mut state.conv_state,
+ 1,
+ self.kernel_size as u32,
+ self.hidden_dim as u32 * 3,
+ (self.kernel_size - 1) as u32,
+ self.hidden_dim as u32,
+ encoder,
+ );
+ Ok(conv_output)
+ }
+
+ fn encode_prefill_conv(
+ &self,
+ in_projected: &Allocation<B>,
+ batch_dim: usize,
+ state: &mut ShortConvState<B>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error> {
+ let state_stride = self.kernel_size - 1;
+ let padded_rows = state_stride + batch_dim;
+
+ let mut padded = encoder.allocate_scratch(size_for_shape(&[padded_rows, self.hidden_dim], self.data_type))?;
+ self.short_conv_pack.encode(
+ &state.conv_state,
+ in_projected,
+ &mut padded,
+ state_stride as u32,
+ batch_dim as u32,
+ self.hidden_dim as u32 * 3,
+ self.hidden_dim as u32,
+ encoder,
+ );
+
+ let mut conv_output =
+ encoder.allocate_scratch(size_for_shape(&[batch_dim, self.hidden_dim], self.data_type))?;
+ self.short_conv_prefill.encode(
+ &padded,
+ in_projected,
+ &self.conv_weight,
+ self.conv_bias.as_ref(),
+ &mut conv_output,
+ &mut state.conv_state,
+ batch_dim as u32,
+ self.kernel_size as u32,
+ self.hidden_dim as u32 * 3,
+ state_stride as u32,
+ self.hidden_dim as u32,
+ encoder,
+ );
+ Ok(conv_output)
+ }
+
+ fn encode_trie_conv(
+ &self,
+ in_projected: &Allocation<B>,
+ batch_dim: usize,
+ token_parents: &Allocation<B>,
+ state: &mut ShortConvState<B>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<(Allocation<B>, Allocation<B>), B::Error> {
+ let mut conv_output =
+ encoder.allocate_scratch(size_for_shape(&[batch_dim, self.hidden_dim], self.data_type))?;
+ let mut conv_states = encoder
+ .allocate_scratch(size_for_shape(&[batch_dim, self.kernel_size - 1, self.hidden_dim], self.data_type))?;
+ self.short_conv_trie.encode(
+ in_projected,
+ &self.conv_weight,
+ self.conv_bias.as_ref(),
+ &state.conv_state,
+ token_parents,
+ &mut conv_output,
+ &mut conv_states,
+ batch_dim as u32,
+ self.kernel_size as u32,
+ (self.hidden_dim * 3) as u32,
+ (self.kernel_size - 1) as u32,
+ self.hidden_dim as u32,
+ encoder,
+ );
+ Ok((conv_output, conv_states))
+ }
+}
+
+impl<B: Backend> Mixer<B> for ShortConv<B> {
+ fn speculation_supported(&self) -> bool {
+ true
+ }
+
+ fn max_context_length(&self) -> Option<usize> {
+ None
+ }
+
+ fn create_empty_state(
+ &self,
+ _max_context_length: Option<usize>,
+ context: &B::Context,
+ ) -> Result<Box<dyn MixerState<B>>, B::Error> {
+ let mut conv_state = context.create_allocation(
+ size_for_shape(&[self.kernel_size - 1, self.hidden_dim], self.data_type),
+ AllocationType::Global,
+ )?;
+
+ let suffix_capacity = 1024; // TODO: remove hardcoded suffix capacity
+ let mut suffix_state = context.create_allocation(
+ size_for_shape(&[suffix_capacity, self.kernel_size - 1, self.hidden_dim], self.data_type),
+ AllocationType::Global,
+ )?;
+
+ let mut zero_encoder = Encoder::<B>::new(context)?;
+ zero_encoder.encode_fill(&mut conv_state, 0);
+ zero_encoder.encode_fill(&mut suffix_state, 0);
+ zero_encoder.end_encoding().submit().wait_until_completed()?;
+
+ Ok(Box::new(ShortConvState {
+ conv_state,
+ suffix_state: None,
+ }))
+ }
+
+ fn encode(
+ &self,
+ hidden: Allocation<B>,
+ precalculated_rope: Option<&PrecalculatedRoPE<B>>,
+ batch_dim: &BatchTopology,
+ state: Option<MaybeMut<dyn MixerState<B>>>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error> {
+ assert!(precalculated_rope.is_none(), "unexpected rope for short conv mixer");
+
+ let state = state.expect("short conv requires state");
+ let state = state.downcast::<ShortConvState<B>>().expect("incorrect type of short conv state");
+ let MaybeMut::Mut(state) = state else {
+ panic!("incorrect state access for short conv state");
+ };
+
+ assert!(state.suffix_state.is_none(), "short conv called with state with unaccepted tokens");
+
+ let in_projected = self.in_projection.encode(hidden, batch_dim.size(), encoder)?;
+
+ let conv_output = if batch_dim.full_accept() {
+ let conv_output = if batch_dim.size() == 1 {
+ self.encode_decode_conv(&in_projected, state, encoder)?
+ } else {
+ self.encode_prefill_conv(&in_projected, batch_dim.size(), state, encoder)?
+ };
+ state.suffix_state = Some(ShortConvStateSuffixStatus::Flat {
+ suffix_length: batch_dim.size(),
+ });
+ conv_output
+ } else {
+ let mut token_parents = encoder.allocate_constant(batch_dim.size() * DataType::I32.size_in_bytes())?;
+ token_parents.copyin(batch_dim.parents());
+ let (conv_output, conv_states) =
+ self.encode_trie_conv(&in_projected, batch_dim.size(), &token_parents, state, encoder)?;
+ state.suffix_state = Some(ShortConvStateSuffixStatus::Trie {
+ conv_states,
+ });
+ conv_output
+ };
+
+ self.out_projection.encode(conv_output, batch_dim.size(), encoder)
+ }
+}
diff --git a/crates/backend-uzu/src/encodable_block/mlp/dense.rs b/crates/backend-uzu/src/encodable_block/mlp/dense.rs
index b0407a775..f45cadd8b 100644
--- a/crates/backend-uzu/src/encodable_block/mlp/dense.rs
+++ b/crates/backend-uzu/src/encodable_block/mlp/dense.rs
@@ -1,7 +1,12 @@
//! MLP block encodable.
-use super::{super::linear::Linear, Mlp, gate_act_mul::MlpGateActMulEncodable};
-use crate::backends::common::{Allocation, Backend, Encoder};
+use crate::{
+ backends::common::{Allocation, Backend, Encoder},
+ encodable_block::{
+ linear::Linear,
+ mlp::{Mlp, gate_act_mul::MlpGateActMulEncodable},
+ },
+};
pub struct DenseMlp<B: Backend> {
up: Box<dyn Linear<B>>,
diff --git a/crates/backend-uzu/src/encodable_block/mlp/mod.rs b/crates/backend-uzu/src/encodable_block/mlp/mod.rs
index 61a24e287..37c76fbb0 100644
--- a/crates/backend-uzu/src/encodable_block/mlp/mod.rs
+++ b/crates/backend-uzu/src/encodable_block/mlp/mod.rs
@@ -7,11 +7,11 @@ use gate_act_mul::MlpGateActMulEncodable;
pub use moe::{MoeBlock, MoeBlockError};
use thiserror::Error;
-use super::linear::{Linear, LinearBlockError};
use crate::{
backends::common::{Allocation, Backend, Encoder},
config::mlp::AnyMLPConfig,
data_type::DataType,
+ encodable_block::linear::{Linear, LinearBlockError},
parameters::{ParameterLoaderError, ParameterTree},
};
diff --git a/crates/backend-uzu/src/encodable_block/mlp/moe/experts_two_pass_decode.rs b/crates/backend-uzu/src/encodable_block/mlp/moe/experts_two_pass_decode.rs
index 3260540e2..7495f995c 100644
--- a/crates/backend-uzu/src/encodable_block/mlp/moe/experts_two_pass_decode.rs
+++ b/crates/backend-uzu/src/encodable_block/mlp/moe/experts_two_pass_decode.rs
@@ -1,4 +1,3 @@
-use super::MoeExpertsTwoPassArguments;
use crate::{
array::size_for_shape,
backends::common::{
@@ -10,6 +9,7 @@ use crate::{
},
},
data_type::DataType,
+ encodable_block::mlp::moe::experts_two_pass_prefill::MoeExpertsTwoPassArguments,
};
pub struct MoeExpertsTwoPassDecodeBlock<B: Backend> {
diff --git a/crates/backend-uzu/src/encodable_block/mod.rs b/crates/backend-uzu/src/encodable_block/mod.rs
index 115a9119a..f390df8e8 100644
--- a/crates/backend-uzu/src/encodable_block/mod.rs
+++ b/crates/backend-uzu/src/encodable_block/mod.rs
@@ -1,43 +1,13 @@
-mod attention;
-mod classifier_layer;
-mod decoder;
-mod delta_net_mixer;
-mod embedding;
-mod kv_cache_update;
-mod layer;
-mod layer_norm;
-mod linear;
-mod mamba_mixer;
-mod mlp;
-mod normalization;
-mod per_layer_embedding;
-mod pooling;
-mod prediction_head;
-mod qk_unpack;
-mod qkv_norm;
-mod rms_norm;
-mod rope;
-mod sampling;
-mod short_conv_mixer;
-
-pub use attention::{Attention, AttentionError};
-pub use classifier_layer::ClassifierLayer;
-pub use decoder::{Decoder, DecoderArguments, DecoderDecodeInput};
-pub use delta_net_mixer::{DeltaNetArguments, DeltaNetMixer, DeltaNetMixerError};
-pub use embedding::Embedding;
-pub use kv_cache_update::{KVCacheUpdate, KVLayerData};
-pub use layer::{LayerArguments, LayerExecutables, LayerRopeKind};
-pub use layer_norm::{LayerNorm, LayerNormError};
-pub use linear::Linear;
-pub use mamba_mixer::{MambaArguments, MambaMixer, MambaMixerError};
-pub use mlp::{Mlp, MlpBlockError};
-pub use normalization::{Normalization, NormalizationError};
-pub use per_layer_embedding::{PerLayerEmbedding, PerLayerEmbeddingProjection};
-pub use pooling::Pooling;
-pub use prediction_head::ClassifierPredictionHead;
-pub use qk_unpack::QkUnpack;
-pub use qkv_norm::QKVNorm;
-pub use rms_norm::{PostLayerScalar, RMSNorm, RMSNormError};
-pub use rope::{PrecalculatedRope, Rope};
-pub use sampling::Sampling;
-pub use short_conv_mixer::{ShortConvArguments, ShortConvMixer, ShortConvMixerError};
+pub mod batch_topology;
+pub mod classifier;
+pub mod decoder;
+pub mod embedding;
+pub mod linear;
+pub mod mixer;
+pub mod mlp;
+pub mod normalization;
+pub mod per_layer_embedding;
+pub mod prediction_head;
+pub mod sampling;
+pub mod transformer;
+pub mod transformer_layer;
diff --git a/crates/backend-uzu/src/encodable_block/normalization.rs b/crates/backend-uzu/src/encodable_block/normalization.rs
index ad72dc47e..1b6e14e48 100644
--- a/crates/backend-uzu/src/encodable_block/normalization.rs
+++ b/crates/backend-uzu/src/encodable_block/normalization.rs
@@ -1,57 +1,94 @@
-//! Unified normalization encodables.
-
use thiserror::Error;
-use super::{LayerNorm, LayerNormError, PostLayerScalar, RMSNorm, RMSNormError};
use crate::{
- backends::common::{Allocation, Backend, Encoder},
- config::normalization::NormalizationConfig,
+ array::size_for_shape,
+ backends::common::{
+ Allocation, Backend, Encoder,
+ kernel::{Kernels, NormalizationKernel},
+ },
+ config::normalization::{NormalizationConfig, UpcastMode},
data_type::DataType,
- parameters::ParameterTree,
+ parameters::{ParameterLoaderError, ParameterTree},
};
-pub(super) const NORMALIZATION_ACCUMULATION_DATA_TYPE: DataType = DataType::F32;
-pub(super) const NORMALIZATION_SCALE_DATA_TYPE: DataType = DataType::F32;
+// TODO: clean up
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum PostLayerScalar {
+ None,
+ ScaleResidualSum(f32),
+ ScaleOutput(f32),
+}
#[derive(Debug, Error)]
-pub enum NormalizationError<B: Backend> {
- #[error("LayerNorm error: {0}")]
- LayerNormError(#[from] LayerNormError<B>),
- #[error("RMSNorm error: {0}")]
- RMSNormError(#[from] RMSNormError<B>),
+pub enum NormalizationNewError<B: Backend> {
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+ #[error("Parameter loading error: {0}")]
+ Parameter(#[from] ParameterLoaderError<B>),
}
-/// Unified normalization encodable that can be either LayerNorm or RMSNorm.
-pub enum Normalization<B: Backend> {
- LayerNorm(LayerNorm<B>),
- RMSNorm(RMSNorm<B>),
+pub struct Normalization<B: Backend> {
+ epsilon: f32,
+ scale_offset: Option<f32>,
+ scales: Allocation<B>,
+ element_count: usize,
+ hadamard_factors: Option<Allocation<B>>,
+ post_layer_scalar_value: f32,
+ data_type: DataType,
+ kernel: <B::Kernels as Kernels>::NormalizationKernel,
}
impl<B: Backend> Normalization<B> {
- /// Creates the appropriate normalization encodable based on config.
- /// Uses LayerNorm if subtract_mean is true, otherwise RMSNorm.
pub fn new(
- context: &B::Context,
- intermediate_data_type: DataType,
element_count: usize,
- config: NormalizationConfig,
+ hadamard_factors: Option<Allocation<B>>,
+ copy_to_shortcut: bool,
+ residual_add: bool,
+ post_layer_scalar: PostLayerScalar,
+ data_type: DataType,
+ config: &NormalizationConfig,
parameter_tree: &ParameterTree<B>,
- ) -> Result<Self, NormalizationError<B>> {
- if config.subtract_mean {
- Ok(Self::LayerNorm(LayerNorm::new(context, intermediate_data_type, element_count, config, parameter_tree)?))
- } else {
- Ok(Self::RMSNorm(RMSNorm::new(
- context,
- intermediate_data_type,
- element_count,
- config,
- parameter_tree,
- None,
- false,
- false,
- PostLayerScalar::None,
- )?))
- }
+ context: &B::Context,
+ ) -> Result<Self, NormalizationNewError<B>> {
+ assert!(!config.has_biases, "normalization doesn't support biases");
+ assert!(copy_to_shortcut || !residual_add, "residual_add requires shortcut");
+
+ let scales = parameter_tree.leaf("scales")?.validate(&[element_count], DataType::F32)?.read_allocation()?;
+
+ let (scale_residual_sum, scale_output, post_layer_scalar_value) = match post_layer_scalar {
+ PostLayerScalar::None => (false, false, 1.0),
+ PostLayerScalar::ScaleResidualSum(value) => (true, false, value),
+ PostLayerScalar::ScaleOutput(value) => (false, true, value),
+ };
+
+ let kernel = <B::Kernels as Kernels>::NormalizationKernel::new(
+ context,
+ data_type,
+ DataType::F32,
+ data_type,
+ DataType::F32,
+ false,
+ config.subtract_mean,
+ config.upcast_mode == UpcastMode::FullLayer,
+ copy_to_shortcut,
+ residual_add,
+ hadamard_factors.is_some(),
+ scale_residual_sum,
+ scale_output,
+ )
+ .map_err(NormalizationNewError::Backend)?;
+
+ Ok(Self {
+ epsilon: config.epsilon,
+ scale_offset: config.scale_offset,
+ scales,
+ element_count,
+ hadamard_factors,
+ post_layer_scalar_value,
+ data_type,
+ kernel,
+ })
}
pub fn encode(
@@ -59,11 +96,26 @@ impl<B: Backend> Normalization<B> {
input: &Allocation<B>,
row_offset: usize,
row_count: usize,
+ shortcut: Option<&mut Allocation<B>>,
encoder: &mut Encoder<B>,
) -> Result<Allocation<B>, B::Error> {
- match self {
- Self::LayerNorm(layer_norm) => layer_norm.encode(input, row_offset, row_count, encoder),
- Self::RMSNorm(rms_norm) => rms_norm.encode(input, row_offset, row_count, None, encoder),
- }
+ let row_size = self.element_count * self.data_type.size_in_bytes();
+ let row_offset_bytes = row_offset * row_size;
+ let shortcut = shortcut.map(|shortcut| (shortcut, row_offset_bytes));
+ let mut output = encoder.allocate_scratch(size_for_shape(&[row_count, self.element_count], self.data_type))?;
+ self.kernel.encode(
+ Some((input, row_offset_bytes)),
+ &self.scales,
+ &mut output,
+ shortcut,
+ self.hadamard_factors.as_ref(),
+ row_count as u32,
+ self.element_count as u32,
+ self.epsilon,
+ self.scale_offset.unwrap_or(0.0),
+ self.post_layer_scalar_value,
+ encoder,
+ );
+ Ok(output)
}
}
diff --git a/crates/backend-uzu/src/encodable_block/per_layer_embedding.rs b/crates/backend-uzu/src/encodable_block/per_layer_embedding.rs
index b27fcdce9..030c5e769 100644
--- a/crates/backend-uzu/src/encodable_block/per_layer_embedding.rs
+++ b/crates/backend-uzu/src/encodable_block/per_layer_embedding.rs
@@ -13,7 +13,10 @@ use crate::{
per_layer_embedding::{PLELayerConfig, PLEModelConfig},
},
data_type::DataType,
- encodable_block::{Linear, PostLayerScalar, RMSNorm, RMSNormError, linear::LinearBlockError},
+ encodable_block::{
+ linear::{Linear, LinearBlockError},
+ normalization::{Normalization, NormalizationNewError, PostLayerScalar},
+ },
parameters::{ParameterLoaderError, ParameterTree},
};
@@ -23,8 +26,8 @@ pub enum PerLayerEmbeddingError<B: Backend> {
BackendError(#[source] B::Error),
#[error("Parameter loading error: {0}")]
ParameterError(#[from] ParameterLoaderError<B>),
- #[error("RMSNorm error: {0}")]
- RMSNormError(#[from] RMSNormError<B>),
+ #[error("Normalization error: {0}")]
+ Normalization(#[from] NormalizationNewError<B>),
#[error("Linear error: {0}")]
LinearError(#[from] LinearBlockError<B>),
}
@@ -33,7 +36,7 @@ pub struct PerLayerEmbedding<B: Backend> {
token_embedding: Allocation<B>,
token_embedding_lookup: <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel,
model_projection: Box<dyn Linear<B>>,
- projection_norm: RMSNorm<B>,
+ projection_norm: Normalization<B>,
add_scale: <B::Kernels as Kernels>::TensorAddScaleKernel,
ple_dim: usize,
num_layers: usize,
@@ -77,16 +80,16 @@ impl<B: Backend> PerLayerEmbedding<B> {
adjusted.epsilon /= scale_squared;
adjusted
};
- let projection_norm = RMSNorm::new(
- context,
- data_type,
+ let projection_norm = Normalization::new(
config.ple_dim,
- projection_norm_config,
- &parameter_tree.subtree("projection_norm")?,
None,
false,
false,
PostLayerScalar::ScaleOutput(config.input_scale),
+ data_type,
+ &projection_norm_config,
+ &parameter_tree.subtree("projection_norm")?,
+ context,
)?;
let add_scale = <B::Kernels as Kernels>::TensorAddScaleKernel::new(context, data_type, false)
@@ -156,7 +159,7 @@ impl<B: Backend> PerLayerEmbedding<B> {
pub struct PerLayerEmbeddingProjection<B: Backend> {
gate: Box<dyn Linear<B>>,
projection: Box<dyn Linear<B>>,
- norm: RMSNorm<B>,
+ norm: Normalization<B>,
gate_act_mul: <B::Kernels as Kernels>::GatedActMulKernel,
residual_finalize: <B::Kernels as Kernels>::TensorAddBiasKernel,
residual_combine: <B::Kernels as Kernels>::TensorAddScaleKernel,
@@ -194,16 +197,16 @@ impl<B: Backend> PerLayerEmbeddingProjection<B> {
data_type,
&parameter_tree.subtree("projection")?,
)?;
- let norm = RMSNorm::new(
- context,
- data_type,
+ let norm = Normalization::new(
model_dim,
- config.norm_config.clone(),
- &parameter_tree.subtree("norm")?,
None,
false,
false,
PostLayerScalar::None,
+ data_type,
+ &config.norm_config,
+ &parameter_tree.subtree("norm")?,
+ context,
)?;
let gate_act_mul = <B::Kernels as Kernels>::GatedActMulKernel::new(context, data_type, false, false)
diff --git a/crates/backend-uzu/src/encodable_block/pooling.rs b/crates/backend-uzu/src/encodable_block/pooling.rs
deleted file mode 100644
index 6c75761ef..000000000
--- a/crates/backend-uzu/src/encodable_block/pooling.rs
+++ /dev/null
@@ -1,73 +0,0 @@
-//! Pooling encodable for sequence-level aggregation.
-
-use crate::{
- array::size_for_shape,
- backends::common::{
- Allocation, Backend, Encoder,
- kernel::{Kernels, PoolingClsKernel, PoolingMeanKernel},
- },
- config::classifier::PoolingType,
- data_type::DataType,
-};
-
-enum PoolingKernel<B: Backend> {
- Cls(<B::Kernels as Kernels>::PoolingClsKernel),
- Mean(<B::Kernels as Kernels>::PoolingMeanKernel),
-}
-
-impl<B: Backend> PoolingKernel<B> {
- fn encode(
- &self,
- input: &Allocation<B>,
- output: &mut Allocation<B>,
- seq_len: u32,
- hidden_dim: u32,
- batch_dim: u32,
- encoder: &mut Encoder<B>,
- ) {
- match self {
- Self::Cls(kernel) => kernel.encode(input, output, seq_len, hidden_dim, batch_dim, encoder),
- Self::Mean(kernel) => kernel.encode(input, output, seq_len, hidden_dim, batch_dim, encoder),
- }
- }
-}
-
-pub struct Pooling<B: Backend> {
- pooling_kernel: PoolingKernel<B>,
- model_dim: usize,
- data_type: DataType,
-}
-
-impl<B: Backend> Pooling<B> {
- pub fn new(
- context: &B::Context,
- data_type: DataType,
- pooling_type: PoolingType,
- model_dim: usize,
- ) -> Result<Self, B::Error> {
- let pooling_kernel = match pooling_type {
- PoolingType::CLS => PoolingKernel::Cls(<B::Kernels as Kernels>::PoolingClsKernel::new(context, data_type)?),
- PoolingType::Mean => {
- PoolingKernel::Mean(<B::Kernels as Kernels>::PoolingMeanKernel::new(context, data_type)?)
- },
- };
- Ok(Self {
- pooling_kernel,
- model_dim,
- data_type,
- })
- }
-
- pub fn encode(
- &self,
- seq_len: usize,
- main: &Allocation<B>,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let batch_dim = 1;
- let mut pooling = encoder.allocate_scratch(size_for_shape(&[1, self.model_dim], self.data_type))?;
-
- self.pooling_kernel.encode(main, &mut pooling, seq_len as u32, self.model_dim as u32, batch_dim, encoder);
- Ok(pooling)
- }
-}
diff --git a/crates/backend-uzu/src/encodable_block/prediction_head.rs b/crates/backend-uzu/src/encodable_block/prediction_head.rs
index 5d508ebf1..43b45f822 100644
--- a/crates/backend-uzu/src/encodable_block/prediction_head.rs
+++ b/crates/backend-uzu/src/encodable_block/prediction_head.rs
@@ -1,68 +1,109 @@
-//! Prediction head encodable for classification output.
+use thiserror::Error;
use crate::{
- array::size_for_shape,
backends::common::{
Allocation, Backend, Encoder,
gpu_types::ActivationType,
kernel::{ActivationKernel, Kernels},
},
- config::activation::AnyActivation,
+ config::classifier::PredictionHeadConfig,
data_type::DataType,
- encodable_block::{Normalization, linear::Linear},
+ encodable_block::{
+ linear::{Linear, LinearBlockError},
+ normalization::{Normalization, NormalizationNewError, PostLayerScalar},
+ },
+ parameters::{ParameterLoaderError, ParameterTree},
};
-pub struct ClassifierPredictionHead<B: Backend> {
- dense: Box<dyn Linear<B>>,
+#[derive(Debug, Error)]
+pub enum PredictionHeadError<B: Backend> {
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+ #[error("Parameter loading error: {0}")]
+ Parameter(#[from] ParameterLoaderError<B>),
+ #[error("Linear error: {0}")]
+ Linear(#[from] LinearBlockError<B>),
+ #[error("Normalization error: {0}")]
+ Normalization(#[from] NormalizationNewError<B>),
+}
+
+pub struct PredictionHead<B: Backend> {
+ hidden_dim: usize,
+ activation: ActivationType,
+ dense_projection: Box<dyn Linear<B>>,
activation_kernel: <B::Kernels as Kernels>::ActivationKernel,
- activation: AnyActivation,
- activation_data_type: DataType,
- norm: Normalization<B>,
+ normalization: Normalization<B>,
readout: Box<dyn Linear<B>>,
- hidden_dim: usize,
}
-impl<B: Backend> ClassifierPredictionHead<B> {
+impl<B: Backend> PredictionHead<B> {
pub fn new(
- context: &B::Context,
- dense: Box<dyn Linear<B>>,
- activation: AnyActivation,
- activation_data_type: DataType,
- norm: Normalization<B>,
- readout: Box<dyn Linear<B>>,
hidden_dim: usize,
- ) -> Result<Self, B::Error> {
- let activation_kernel = <B::Kernels as Kernels>::ActivationKernel::new(context, activation_data_type, false)?;
+ num_labels: usize,
+ data_type: DataType,
+ config: &PredictionHeadConfig,
+ parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
+ ) -> Result<Self, PredictionHeadError<B>> {
+ let dense_projection = <dyn Linear<B>>::new(
+ hidden_dim,
+ [hidden_dim],
+ config.use_dense_bias,
+ context,
+ data_type,
+ &parameter_tree.subtree("dense")?,
+ )?;
+
+ let activation = config.activation.act_type();
+ let activation_kernel = <B::Kernels as Kernels>::ActivationKernel::new(context, data_type, true)
+ .map_err(PredictionHeadError::Backend)?;
+
+ let normalization = Normalization::new(
+ hidden_dim,
+ None,
+ false,
+ false,
+ PostLayerScalar::None,
+ data_type,
+ &config.normalization_config,
+ &parameter_tree.subtree("norm")?,
+ context,
+ )?;
+
+ let readout = <dyn Linear<B>>::new(
+ hidden_dim,
+ [num_labels],
+ true,
+ context,
+ data_type,
+ &parameter_tree.subtree("readout")?,
+ )?;
+
Ok(Self {
- dense,
- activation_kernel,
+ hidden_dim,
activation,
- activation_data_type,
- norm,
+ dense_projection,
+ activation_kernel,
+ normalization,
readout,
- hidden_dim,
})
}
pub fn encode(
&self,
input: Allocation<B>,
+ batch_dim: usize,
encoder: &mut Encoder<B>,
) -> Result<Allocation<B>, B::Error> {
- let batch_dim = 1;
- let dense = self.dense.encode(input, batch_dim, encoder)?;
- if self.activation.act_type() == ActivationType::IDENTITY {
- panic!("Identity activation is not supported for kernel");
- }
- let mut activated = encoder.allocate_scratch(size_for_shape(&[self.hidden_dim], self.activation_data_type))?;
+ let mut hidden = self.dense_projection.encode(input, batch_dim, encoder)?;
self.activation_kernel.encode(
- Some(&dense),
- &mut activated,
+ None::<&Allocation<B>>,
+ &mut hidden,
self.hidden_dim as u32,
- self.activation.act_type(),
+ self.activation,
encoder,
);
- let normalized = self.norm.encode(&activated, 0, batch_dim, encoder)?;
+ let normalized = self.normalization.encode(&hidden, 0, batch_dim, None, encoder)?;
self.readout.encode(normalized, batch_dim, encoder)
}
}
diff --git a/crates/backend-uzu/src/encodable_block/qk_unpack.rs b/crates/backend-uzu/src/encodable_block/qk_unpack.rs
deleted file mode 100644
index ad9d6653c..000000000
--- a/crates/backend-uzu/src/encodable_block/qk_unpack.rs
+++ /dev/null
@@ -1,51 +0,0 @@
-use crate::{
- array::size_for_shape,
- backends::common::{
- Allocation, Backend, Encoder,
- kernel::{Kernels, QkUnpackKernel},
- },
- data_type::DataType,
-};
-
-pub struct QkUnpack<B: Backend> {
- unpack_kernel: <B::Kernels as Kernels>::QkUnpackKernel,
- data_type: DataType,
-}
-
-impl<B: Backend> QkUnpack<B> {
- pub fn new(
- context: &B::Context,
- data_type: DataType,
- ) -> Result<Self, B::Error> {
- Ok(Self {
- unpack_kernel: <B::Kernels as Kernels>::QkUnpackKernel::new(context, data_type)?,
- data_type,
- })
- }
-
- pub fn encode(
- &self,
- qkv: &Allocation<B>,
- suffix_length: usize,
- num_heads: usize,
- num_groups: usize,
- head_dim: usize,
- encoder: &mut Encoder<B>,
- ) -> Result<(Allocation<B>, Allocation<B>), B::Error> {
- let mut queries =
- encoder.allocate_scratch(size_for_shape(&[num_heads, suffix_length, head_dim], self.data_type))?;
- let mut keys =
- encoder.allocate_scratch(size_for_shape(&[num_groups, suffix_length, head_dim], self.data_type))?;
- self.unpack_kernel.encode(
- qkv,
- &mut queries,
- &mut keys,
- head_dim as u32,
- num_heads as u32,
- num_groups as u32,
- suffix_length as u32,
- encoder,
- );
- Ok((queries, keys))
- }
-}
diff --git a/crates/backend-uzu/src/encodable_block/rms_norm.rs b/crates/backend-uzu/src/encodable_block/rms_norm.rs
deleted file mode 100644
index 915d5b026..000000000
--- a/crates/backend-uzu/src/encodable_block/rms_norm.rs
+++ /dev/null
@@ -1,122 +0,0 @@
-//! RMS Normalization encodable.
-
-use thiserror::Error;
-
-use crate::{
- array::size_for_shape,
- backends::common::{
- Allocation, Backend, Encoder,
- kernel::{Kernels, RMSNormKernel},
- },
- config::normalization::{NormalizationConfig, UpcastMode},
- data_type::DataType,
- parameters::{ParameterLoaderError, ParameterTree},
-};
-
-#[derive(Debug, Clone, Copy, PartialEq)]
-pub enum PostLayerScalar {
- None,
- ScaleResidualSum(f32),
- ScaleOutput(f32),
-}
-
-#[derive(Debug, Error)]
-pub enum RMSNormError<B: Backend> {
- #[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
- #[error("Parameter loading error: {0}")]
- ParameterError(#[from] ParameterLoaderError<B>),
-}
-
-pub struct RMSNorm<B: Backend> {
- kernel: <B::Kernels as Kernels>::RMSNormKernel,
- config: NormalizationConfig,
- scales: Allocation<B>,
- element_count: usize,
- input_data_type: DataType,
- output_data_type: DataType,
- hadamard_factors: Option<Allocation<B>>,
- post_layer_scalar_value: f32,
-}
-
-impl<B: Backend> RMSNorm<B> {
- pub fn new(
- context: &B::Context,
- intermediate_data_type: DataType,
- element_count: usize,
- config: NormalizationConfig,
- parameter_tree: &ParameterTree<B>,
- hadamard_factors: Option<Allocation<B>>,
- use_shortcut: bool,
- residual_add: bool,
- post_layer_scalar: PostLayerScalar,
- ) -> Result<Self, RMSNormError<B>> {
- let scale_data_type = super::normalization::NORMALIZATION_SCALE_DATA_TYPE;
- let scales = parameter_tree.leaf("scales")?.validate(&[element_count], scale_data_type)?.read_allocation()?;
-
- let accumulation_data_type = super::normalization::NORMALIZATION_ACCUMULATION_DATA_TYPE;
- let output_data_type = intermediate_data_type;
-
- let (scale_residual_sum, scale_output, post_layer_scalar_value) = match post_layer_scalar {
- PostLayerScalar::None => (false, false, 1.0),
- PostLayerScalar::ScaleResidualSum(value) => (true, false, value),
- PostLayerScalar::ScaleOutput(value) => (false, true, value),
- };
-
- let kernel = <B::Kernels as Kernels>::RMSNormKernel::new(
- context,
- intermediate_data_type,
- scale_data_type,
- output_data_type,
- accumulation_data_type,
- false,
- config.upcast_mode == UpcastMode::FullLayer,
- use_shortcut,
- residual_add,
- hadamard_factors.is_some(),
- scale_residual_sum,
- scale_output,
- )
- .map_err(RMSNormError::BackendError)?;
-
- Ok(Self {
- kernel,
- config,
- scales,
- element_count,
- input_data_type: intermediate_data_type,
- output_data_type,
- hadamard_factors,
- post_layer_scalar_value,
- })
- }
-
- pub fn encode(
- &self,
- input: &Allocation<B>,
- row_offset: usize,
- row_count: usize,
- shortcut: Option<&mut Allocation<B>>,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let row_size = self.element_count * self.input_data_type.size_in_bytes();
- let row_offset_bytes = row_offset * row_size;
- let shortcut = shortcut.map(|shortcut| (shortcut, row_offset_bytes));
- let mut output =
- encoder.allocate_scratch(size_for_shape(&[row_count, self.element_count], self.output_data_type))?;
- self.kernel.encode(
- Some((input, row_offset_bytes)),
- &self.scales,
- &mut output,
- shortcut,
- self.hadamard_factors.as_ref(),
- row_count as u32,
- self.element_count as u32,
- self.config.epsilon,
- self.config.scale_offset.unwrap_or(0.0),
- self.post_layer_scalar_value,
- encoder,
- );
- Ok(output)
- }
-}
diff --git a/crates/backend-uzu/src/encodable_block/rope.rs b/crates/backend-uzu/src/encodable_block/rope.rs
deleted file mode 100644
index 94750e750..000000000
--- a/crates/backend-uzu/src/encodable_block/rope.rs
+++ /dev/null
@@ -1,75 +0,0 @@
-//! Rope (Rotary Position Embedding) encodable.
-
-use crate::{
- array::size_for_shape,
- backends::common::{
- Allocation, Backend, Encoder,
- kernel::{Kernels, RopeKernel},
- },
- data_type::DataType,
- forward_pass::model_shape::ModelShape,
-};
-
-pub struct Rope<B: Backend> {
- kernel: <B::Kernels as Kernels>::RopeKernel,
- data_type: DataType,
- query_only: bool,
-}
-
-pub struct PrecalculatedRope<B: Backend> {
- pub cosines: Allocation<B>,
- pub sines: Allocation<B>,
- pub dim: usize,
-}
-
-impl<B: Backend> Rope<B> {
- pub fn new(
- context: &B::Context,
- model_shape: &ModelShape,
- query_only: bool,
- ) -> Result<Self, B::Error> {
- Ok(Self {
- kernel: <B::Kernels as Kernels>::RopeKernel::new(
- context,
- model_shape.data_type,
- model_shape.rope_data_type,
- query_only,
- )?,
- data_type: model_shape.data_type,
- query_only,
- })
- }
-
- pub fn encode(
- &self,
- qkv: &Allocation<B>,
- rope: &PrecalculatedRope<B>,
- suffix_length: usize,
- num_heads: usize,
- num_groups: usize,
- head_dim: usize,
- encoder: &mut Encoder<B>,
- ) -> Result<(Allocation<B>, Option<Allocation<B>>), B::Error> {
- let mut rotated_queries =
- encoder.allocate_scratch(size_for_shape(&[num_heads, suffix_length, head_dim], self.data_type))?;
- let mut rotated_keys = if self.query_only {
- None
- } else {
- Some(encoder.allocate_scratch(size_for_shape(&[num_groups, suffix_length, head_dim], self.data_type))?)
- };
- self.kernel.encode(
- qkv,
- &rope.cosines,
- &rope.sines,
- &mut rotated_queries,
- rotated_keys.as_mut(),
- head_dim as u32,
- rope.dim as u32,
- num_heads as u32,
- (!self.query_only).then_some(num_groups as u32),
- suffix_length as u32,
- encoder,
- );
- Ok((rotated_queries, rotated_keys))
- }
-}
diff --git a/crates/backend-uzu/src/language_model/gumbel.rs b/crates/backend-uzu/src/encodable_block/sampling/gumbel.rs
similarity index 98%
rename from crates/backend-uzu/src/language_model/gumbel.rs
rename to crates/backend-uzu/src/encodable_block/sampling/gumbel.rs
index 4d8d0e530..ad74d12ae 100644
--- a/crates/backend-uzu/src/language_model/gumbel.rs
+++ b/crates/backend-uzu/src/encodable_block/sampling/gumbel.rs
@@ -33,7 +33,7 @@ fn philox4x32_bumpkey(key: &mut [u32; 2]) {
key[1] = key[1].wrapping_add(PHILOX_W32_1);
}
-pub fn uniform_float(
+fn uniform_float(
key: u64,
(offset, word): (u32, u32),
) -> f32 {
diff --git a/crates/backend-uzu/src/encodable_block/sampling.rs b/crates/backend-uzu/src/encodable_block/sampling/mod.rs
similarity index 62%
rename from crates/backend-uzu/src/encodable_block/sampling.rs
rename to crates/backend-uzu/src/encodable_block/sampling/mod.rs
index 9683cb8f2..0932ed8df 100644
--- a/crates/backend-uzu/src/encodable_block/sampling.rs
+++ b/crates/backend-uzu/src/encodable_block/sampling/mod.rs
@@ -2,6 +2,7 @@ use std::{
cell::RefCell,
collections::{HashMap, hash_map::Entry},
mem::size_of,
+ ops::Range,
};
use crate::{
@@ -10,19 +11,14 @@ use crate::{
kernel::{RepetitionPenaltyKernel, TensorCopyKernel, UnifiedSamplingKernel},
},
data_type::DataType,
- session::parameter::{SamplingMethod, SamplingProcessingOrder},
+ encodable_block::batch_topology::BatchTopology,
};
-#[derive(PartialEq, Eq, Hash)]
-struct UnifiedSamplingKey {
- has_seeds: bool,
- has_bitmask: bool,
- has_temperature: bool,
- temperature_after_filters: bool,
- has_top_k: bool,
- has_top_p: bool,
- has_min_p: bool,
-}
+mod gumbel;
+mod prng;
+
+pub use gumbel::{gumbel_float, revidx, speculator_sample};
+pub use prng::PRng;
pub struct Sampling<B: Backend> {
vocab_size: usize,
@@ -41,7 +37,46 @@ impl<B: Backend> Sampling<B> {
unified_kernels: RefCell::new(HashMap::new()),
}
}
+}
+#[derive(Clone, PartialEq, Debug)]
+pub enum SamplingMethod {
+ Greedy,
+ Stochastic {
+ temperature: Option<f32>,
+ top_k: Option<u32>,
+ top_p: Option<f32>,
+ min_p: Option<f32>,
+ repetition_penalty: Option<f32>,
+ suffix_repetition_length: Option<usize>,
+ },
+}
+
+impl SamplingMethod {
+ pub fn suffix_repetition_length(&self) -> Option<usize> {
+ match self {
+ SamplingMethod::Greedy => None,
+ SamplingMethod::Stochastic {
+ suffix_repetition_length,
+ ..
+ } => *suffix_repetition_length,
+ }
+ }
+}
+
+#[derive(PartialEq, Eq, Hash)]
+struct UnifiedSamplingKey {
+ is_stochastic: bool,
+ has_bitmask: bool,
+ has_temperature: bool,
+ has_top_k: bool,
+ has_top_p: bool,
+ has_min_p: bool,
+}
+
+// TODO: repetition penalties shouldn't be stochastic only
+
+impl<B: Backend> Sampling<B> {
pub fn encode(
&self,
logits: &Allocation<B>,
@@ -49,63 +84,44 @@ impl<B: Backend> Sampling<B> {
bitmask: Option<&Allocation<B>>,
context_ring: Option<&Allocation<B>>,
token_ids: Option<&Allocation<B>>,
- sampling_method: SamplingMethod,
- batch_size: usize,
+ sampling_method: &SamplingMethod,
+ batch_dim: &BatchTopology,
+ sampling_range: Range<usize>,
encoder: &mut Encoder<B>,
) -> Result<Allocation<B>, B::Error> {
- // TODO: reject seeds with greedy
- let (
- seeds,
- temperature,
- temperature_after_filters,
- top_k,
- top_p,
- min_p,
- repetition_penalty,
- suffix_repetition_length,
- ) = match sampling_method {
- SamplingMethod::Greedy => (None, None, false, None, None, None, None, None),
- SamplingMethod::Stochastic {
- temperature,
- top_k,
- top_p,
- min_p,
- repetition_penalty,
- suffix_repetition_length,
- processing_order,
- } => (
- Some(seeds.unwrap()),
- temperature,
- match processing_order {
- SamplingProcessingOrder::TemperatureThenFilters => false,
- SamplingProcessingOrder::FiltersThenTemperature => true,
- },
- top_k,
- top_p,
- min_p,
- repetition_penalty,
- suffix_repetition_length,
- ),
- };
+ let (is_stochastic, temperature, top_k, top_p, min_p, repetition_penalty, suffix_repetition_length) =
+ match sampling_method {
+ SamplingMethod::Greedy => (false, None, None, None, None, None, None),
+ SamplingMethod::Stochastic {
+ temperature,
+ top_k,
+ top_p,
+ min_p,
+ repetition_penalty,
+ suffix_repetition_length,
+ } => (true, *temperature, *top_k, *top_p, *min_p, *repetition_penalty, *suffix_repetition_length),
+ };
+
+ assert_eq!(is_stochastic, seeds.is_some(), "mismatch between sampling method type and seeds presence");
let key = UnifiedSamplingKey {
- has_seeds: seeds.is_some(),
+ is_stochastic,
has_bitmask: bitmask.is_some(),
has_temperature: temperature.is_some(),
- temperature_after_filters,
has_top_k: top_k.is_some(),
has_top_p: top_p.is_some(),
has_min_p: min_p.is_some(),
};
+ // TODO: repetition penalty is vibe coded garbage, remove or rewrite properly
let penalized_logits = if let Some(repetition_penalty) = repetition_penalty {
+ assert!(batch_dim.is_flat(), "repetition_penalty currently only supports flat batches");
let suffix_repetition_length =
suffix_repetition_length.expect("suffix_repetition_length is required for repetition_penalty");
- assert_eq!(batch_size, 1, "repetition_penalty currently only supports batch_size == 1");
let mut logits_copy = encoder.allocate_scratch(logits.as_buffer_range_ref().range().len())?;
let tensor_copy = <B::Kernels as Kernels>::TensorCopyKernel::new(encoder.context(), self.data_type)?;
- tensor_copy.encode(logits, &mut logits_copy, (self.vocab_size * batch_size) as u32, encoder);
+ tensor_copy.encode(logits, &mut logits_copy, (self.vocab_size * sampling_range.len()) as u32, encoder);
let repetition_penalty_kernel =
<B::Kernels as Kernels>::RepetitionPenaltyKernel::new(encoder.context(), self.data_type)?;
@@ -116,6 +132,9 @@ impl<B: Backend> Sampling<B> {
token_ids.expect("token_ids is required for repetition_penalty"),
repetition_penalty,
suffix_repetition_length as u32,
+ self.vocab_size as u32,
+ sampling_range.start as u32,
+ sampling_range.len() as u32,
encoder,
);
Some(logits_copy)
@@ -134,10 +153,9 @@ impl<B: Backend> Sampling<B> {
let kernel = <B::Kernels as Kernels>::UnifiedSamplingKernel::new(
encoder.context(),
self.data_type,
- key.has_seeds,
+ key.is_stochastic,
key.has_bitmask,
key.has_temperature,
- key.temperature_after_filters,
key.has_top_k,
key.has_top_p,
key.has_min_p,
@@ -147,7 +165,8 @@ impl<B: Backend> Sampling<B> {
},
};
- let mut output = encoder.context().create_allocation(batch_size * size_of::<u32>(), AllocationType::Global)?;
+ let mut output =
+ encoder.context().create_allocation(sampling_range.len() * size_of::<u32>(), AllocationType::Global)?;
kernel.encode(
logits,
@@ -159,7 +178,7 @@ impl<B: Backend> Sampling<B> {
top_p,
min_p,
self.vocab_size as u32,
- batch_size as u32,
+ sampling_range.len() as u32,
encoder,
);
@@ -168,5 +187,5 @@ impl<B: Backend> Sampling<B> {
}
#[cfg(test)]
-#[path = "../../unit/encodable_block/sampling_test.rs"]
+#[path = "../../../unit/encodable_block/sampling_test.rs"]
mod tests;
diff --git a/crates/backend-uzu/src/language_model/rng.rs b/crates/backend-uzu/src/encodable_block/sampling/prng.rs
similarity index 100%
rename from crates/backend-uzu/src/language_model/rng.rs
rename to crates/backend-uzu/src/encodable_block/sampling/prng.rs
diff --git a/crates/backend-uzu/src/encodable_block/short_conv_mixer.rs b/crates/backend-uzu/src/encodable_block/short_conv_mixer.rs
deleted file mode 100644
index 46ac7f108..000000000
--- a/crates/backend-uzu/src/encodable_block/short_conv_mixer.rs
+++ /dev/null
@@ -1,308 +0,0 @@
-use thiserror::Error;
-
-use crate::{
- array::size_for_shape,
- backends::common::{
- Allocation, Backend, Encoder, Kernels,
- kernel::{ShortConvDecodeKernel, ShortConvPackKernel, ShortConvPrefillKernel, ShortConvTrieKernel},
- },
- config::token_mixer::short_conv::ShortConvConfig,
- data_type::DataType,
- encodable_block::linear::{Linear, LinearBlockError},
- forward_pass::short_conv_layer::ShortConvLayer,
- parameters::{ParameterLoaderError, ParameterTree},
-};
-
-#[derive(Debug, Error)]
-pub enum ShortConvMixerError<B: Backend> {
- #[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
- #[error("Unsupported configuration: {0}")]
- UnsupportedConfiguration(String),
- #[error("Linear error: {0}")]
- LinearError(#[from] LinearBlockError<B>),
- #[error("Parameter loader error: {0}")]
- ParameterLoaderError(#[from] ParameterLoaderError<B>),
-}
-
-pub struct ShortConvMixer<B: Backend> {
- model_dim: usize,
- kernel_size: usize,
- in_projection: Box<dyn Linear<B>>,
- out_projection: Box<dyn Linear<B>>,
- short_conv_pack: <B::Kernels as Kernels>::ShortConvPackKernel,
- short_conv_prefill: <B::Kernels as Kernels>::ShortConvPrefillKernel,
- short_conv_decode: <B::Kernels as Kernels>::ShortConvDecodeKernel,
- short_conv_trie: <B::Kernels as Kernels>::ShortConvTrieKernel,
- conv_weight: Allocation<B>,
- conv_bias: Option<Allocation<B>>,
- data_type: DataType,
-}
-
-pub struct ShortConvArguments<'a, B: Backend> {
- pub active_row_count: usize,
- pub sampling_start: usize,
- pub sampling_length: usize,
- pub token_parents: &'a Allocation<B>,
- pub layer: &'a mut ShortConvLayer<B>,
-}
-
-impl<B: Backend> ShortConvMixer<B> {
- pub fn new(
- context: &B::Context,
- short_conv_config: &ShortConvConfig,
- model_dim: usize,
- parameter_tree: &ParameterTree<B>,
- data_type: DataType,
- ) -> Result<(Self, Option<Allocation<B>>), ShortConvMixerError<B>> {
- if short_conv_config.kernel_size < 2 {
- return Err(ShortConvMixerError::UnsupportedConfiguration(format!(
- "kernel_size must be >= 2, got {}",
- short_conv_config.kernel_size
- )));
- }
-
- let conv_tree = parameter_tree.subtree("conv")?;
-
- let (in_projection, in_proj_input_hadamard_factors) = <dyn Linear<B>>::new_extracting_input_hadamard(
- model_dim,
- [model_dim * 3],
- false,
- context,
- data_type,
- &parameter_tree.subtree("in_projection")?,
- )?;
-
- let out_projection = <dyn Linear<B>>::new(
- model_dim,
- [model_dim],
- false,
- context,
- data_type,
- &parameter_tree.subtree("out_projection")?,
- )?;
-
- let conv_data_type = DataType::F32;
- let conv_weight = conv_tree
- .leaf("weights")?
- .validate(&[model_dim, short_conv_config.kernel_size], conv_data_type)?
- .read_allocation()?;
- let conv_bias = if short_conv_config.conv_config.has_biases {
- Some(conv_tree.leaf("biases")?.validate(&[model_dim], conv_data_type)?.read_allocation()?)
- } else {
- None
- };
-
- let has_bias = short_conv_config.conv_config.has_biases;
- let short_conv_pack = <B::Kernels as Kernels>::ShortConvPackKernel::new(context, data_type)
- .map_err(ShortConvMixerError::BackendError)?;
- let short_conv_prefill =
- <B::Kernels as Kernels>::ShortConvPrefillKernel::new(context, data_type, conv_data_type, has_bias)
- .map_err(ShortConvMixerError::BackendError)?;
- let short_conv_decode =
- <B::Kernels as Kernels>::ShortConvDecodeKernel::new(context, data_type, conv_data_type, has_bias, true)
- .map_err(ShortConvMixerError::BackendError)?;
- let short_conv_trie =
- <B::Kernels as Kernels>::ShortConvTrieKernel::new(context, data_type, conv_data_type, has_bias)
- .map_err(ShortConvMixerError::BackendError)?;
-
- Ok((
- Self {
- model_dim,
- kernel_size: short_conv_config.kernel_size,
- in_projection,
- out_projection,
- short_conv_pack,
- short_conv_prefill,
- short_conv_decode,
- short_conv_trie,
- conv_weight,
- conv_bias,
- data_type,
- },
- in_proj_input_hadamard_factors,
- ))
- }
-
- fn run_conv(
- &self,
- layer: &mut ShortConvLayer<B>,
- token_parents: &Allocation<B>,
- sampling_start: usize,
- sampling_length: usize,
- in_proj: &Allocation<B>,
- encoder: &mut Encoder<B>,
- active_row_count: usize,
- ) -> Result<Allocation<B>, B::Error> {
- layer.clear_suffix_state_valid_range();
- let mut out = encoder.allocate_scratch(size_for_shape(&[active_row_count, self.model_dim], self.data_type))?;
-
- if active_row_count == 1 {
- self.run_decode_conv(layer, in_proj, &mut out, encoder, 1)?;
- return Ok(out);
- }
-
- if sampling_length == 0 {
- self.run_prefill_conv(layer, in_proj, &mut out, encoder, active_row_count)?;
- return Ok(out);
- }
-
- let trie_len = sampling_length;
-
- if trie_len <= 1 {
- self.run_prefill_conv(layer, in_proj, &mut out, encoder, active_row_count)?;
- return Ok(out);
- }
-
- if sampling_start > 0 {
- if sampling_start == 1 {
- self.run_decode_conv(layer, in_proj, &mut out, encoder, 1)?;
- } else {
- self.run_prefill_conv(layer, in_proj, &mut out, encoder, sampling_start)?;
- }
- }
-
- self.run_trie_conv(layer, token_parents, in_proj, &mut out, encoder, sampling_start, trie_len)?;
- layer.set_suffix_state_valid_range(sampling_start, trie_len);
- Ok(out)
- }
-
- fn run_prefill_conv(
- &self,
- layer: &mut ShortConvLayer<B>,
- in_proj: &Allocation<B>,
- out: &mut Allocation<B>,
- encoder: &mut Encoder<B>,
- suffix_length: usize,
- ) -> Result<(), B::Error> {
- if self.model_dim == 0 || suffix_length == 0 {
- return Ok(());
- }
-
- let kernel_size = self.kernel_size;
- let state_stride = kernel_size - 1;
-
- let padded_rows = state_stride + suffix_length;
- let mut padded = encoder.allocate_scratch(size_for_shape(&[padded_rows, self.model_dim], self.data_type))?;
- self.short_conv_pack.encode(
- (&layer.conv_state, 0),
- in_proj,
- &mut padded,
- state_stride as u32,
- suffix_length as u32,
- self.model_dim as u32 * 3,
- self.model_dim as u32,
- encoder,
- );
- self.short_conv_prefill.encode(
- &padded,
- in_proj,
- &self.conv_weight,
- self.conv_bias.as_ref(),
- out,
- &mut layer.conv_state,
- suffix_length as u32,
- kernel_size as u32,
- self.model_dim as u32 * 3,
- state_stride as u32,
- self.model_dim as u32,
- encoder,
- );
- Ok(())
- }
-
- fn run_trie_conv(
- &self,
- layer: &mut ShortConvLayer<B>,
- token_parents: &Allocation<B>,
- in_proj: &Allocation<B>,
- out: &mut Allocation<B>,
- encoder: &mut Encoder<B>,
- sampling_start: usize,
- trie_len: usize,
- ) -> Result<(), B::Error> {
- if self.model_dim == 0 || trie_len == 0 {
- return Ok(());
- }
-
- let elem_bytes = self.data_type.size_in_bytes();
-
- let kernel_size = self.kernel_size;
- let state_stride = kernel_size - 1;
- let in_proj_stride = self.model_dim * 3;
-
- let in_proj_view = (in_proj, sampling_start * in_proj_stride * elem_bytes);
- let parents_view = (token_parents, sampling_start * std::mem::size_of::<i32>());
- let out_view = (&mut *out, sampling_start * self.model_dim * elem_bytes);
- self.short_conv_trie.encode(
- in_proj_view,
- &self.conv_weight,
- self.conv_bias.as_ref(),
- (&layer.conv_state, 0),
- parents_view,
- out_view,
- (&mut layer.suffix_state, sampling_start * self.model_dim * state_stride * elem_bytes),
- trie_len as u32,
- kernel_size as u32,
- in_proj_stride as u32,
- state_stride as u32,
- self.model_dim as u32,
- encoder,
- );
- Ok(())
- }
-
- fn run_decode_conv(
- &self,
- layer: &mut ShortConvLayer<B>,
- in_proj: &Allocation<B>,
- out: &mut Allocation<B>,
- encoder: &mut Encoder<B>,
- suffix_length: usize,
- ) -> Result<(), B::Error> {
- if self.model_dim == 0 || suffix_length == 0 {
- return Ok(());
- }
-
- let kernel_size = self.kernel_size;
- let state_stride = kernel_size - 1;
-
- self.short_conv_decode.encode(
- in_proj,
- &self.conv_weight,
- self.conv_bias.as_ref(),
- None::<&Allocation<B>>,
- out,
- &mut layer.conv_state,
- suffix_length as u32,
- kernel_size as u32,
- self.model_dim as u32 * 3,
- state_stride as u32,
- self.model_dim as u32,
- encoder,
- );
- Ok(())
- }
-
- pub fn encode(
- &self,
- args: ShortConvArguments<B>,
- input: Allocation<B>,
- encoder: &mut Encoder<B>,
- ) -> Result<Allocation<B>, B::Error> {
- let ShortConvArguments {
- active_row_count,
- sampling_start,
- sampling_length,
- token_parents,
- layer,
- } = args;
- assert!(active_row_count > 0, "ShortConv mixer requires at least one active row");
-
- let in_proj = self.in_projection.encode(input, active_row_count, encoder)?;
- let conv_output =
- self.run_conv(layer, token_parents, sampling_start, sampling_length, &in_proj, encoder, active_row_count)?;
-
- self.out_projection.encode(conv_output, active_row_count, encoder)
- }
-}
diff --git a/crates/backend-uzu/src/encodable_block/transformer.rs b/crates/backend-uzu/src/encodable_block/transformer.rs
new file mode 100644
index 000000000..5e30554e0
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/transformer.rs
@@ -0,0 +1,243 @@
+use std::ops::Range;
+
+use thiserror::Error;
+
+use crate::{
+ backends::common::{Allocation, Backend, Encoder},
+ config::{rope::AnyRoPEConfig, transformer::TransformerConfig},
+ data_type::DataType,
+ encodable_block::{
+ batch_topology::BatchTopology,
+ mixer::{MixerState, attention::rope::PrecalculatedRoPE},
+ normalization::{Normalization, NormalizationNewError, PostLayerScalar},
+ transformer_layer::{TransformerLayer, TransformerLayerError},
+ },
+ parameters::{ParameterLoaderError, ParameterTree},
+ utils::maybe_mut::MaybeMut,
+};
+
+enum TransformerLayerStateType<B: Backend> {
+ Owned(Box<dyn MixerState<B>>),
+ Shared(usize),
+}
+
+pub struct TransformerState<B: Backend> {
+ layer_states: Box<[TransformerLayerStateType<B>]>,
+ context_length: usize,
+}
+
+impl<B: Backend> TransformerState<B> {
+ pub fn context_length(&self) -> usize {
+ self.context_length
+ }
+
+ pub fn prepare(
+ &mut self,
+ context_length: usize,
+ suffix_length: usize,
+ context: &B::Context,
+ ) -> Result<(), B::Error> {
+ for layer_state in &mut self.layer_states {
+ let TransformerLayerStateType::Owned(layer_state) = layer_state else {
+ continue;
+ };
+
+ layer_state.prepare(context_length, suffix_length, context)?;
+ }
+
+ Ok(())
+ }
+
+ pub fn encode_accept(
+ &mut self,
+ accepted_indices: &[usize],
+ encoder: &mut Encoder<B>,
+ ) -> Result<(), B::Error> {
+ for layer_state in &mut self.layer_states {
+ let TransformerLayerStateType::Owned(layer_state) = layer_state else {
+ continue;
+ };
+
+ layer_state.encode_accept(accepted_indices, encoder)?;
+ }
+
+ self.context_length += accepted_indices.len();
+
+ Ok(())
+ }
+}
+
+#[derive(Debug, Error)]
+pub enum TransformerNewError<B: Backend> {
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+ #[error("Parameter loader error: {0}")]
+ ParameterLoader(#[from] ParameterLoaderError<B>),
+ #[error("Layer error: {0}")]
+ Layer(#[from] TransformerLayerError<B>),
+ #[error("Normalization error: {0}")]
+ Normalization(#[from] NormalizationNewError<B>),
+}
+
+pub struct Transformer<B: Backend> {
+ ropes: Box<[AnyRoPEConfig]>,
+ layers: Box<[(TransformerLayer<B>, Option<usize>)]>,
+ output_norm: Normalization<B>,
+}
+
+impl<B: Backend> Transformer<B> {
+ pub fn new(
+ context: &B::Context,
+ output_norm_hadamard_factors: Option<Allocation<B>>,
+ data_type: DataType,
+ transformer_config: &TransformerConfig,
+ parameter_tree: &ParameterTree<B>,
+ ) -> Result<Self, TransformerNewError<B>> {
+ let mut ropes: Vec<AnyRoPEConfig> = Vec::new();
+
+ let layers = transformer_config
+ .layer_configs
+ .iter()
+ .enumerate()
+ .map(|(layer_index, layer_config)| {
+ let layer_loader = parameter_tree.subtree(&format!("layers.{}", layer_index))?;
+
+ let rope = layer_config.rope_config.as_ref().map(|layer_rope_config| {
+ ropes.iter().position(|rope_config| rope_config == layer_rope_config).unwrap_or_else(|| {
+ ropes.push(layer_rope_config.clone());
+ ropes.len() - 1
+ })
+ });
+
+ let layer = TransformerLayer::new(
+ context,
+ transformer_config,
+ layer_config,
+ layer_index,
+ &layer_loader,
+ data_type,
+ )?;
+
+ Ok((layer, rope))
+ })
+ .collect::<Result<Box<[_]>, TransformerNewError<B>>>()?;
+
+ let output_norm = Normalization::new(
+ transformer_config.model_dim,
+ output_norm_hadamard_factors,
+ true,
+ true,
+ PostLayerScalar::None,
+ data_type,
+ &transformer_config.output_norm_config,
+ &parameter_tree.subtree("output_norm")?,
+ context,
+ )?;
+
+ Ok(Self {
+ ropes: ropes.into_boxed_slice(),
+ layers,
+ output_norm,
+ })
+ }
+
+ pub fn speculation_supported(&self) -> bool {
+ self.layers.iter().all(|(layer, _rope)| layer.mixer.speculation_supported())
+ }
+
+ pub fn max_context_length(&self) -> Option<usize> {
+ self.layers.iter().map(|(layer, _rope_index)| layer.mixer.max_context_length()).fold(None, |acc, el| {
+ match (acc, el) {
+ (Some(a), Some(b)) => Some(usize::min(a, b)),
+ (Some(x), None) | (None, Some(x)) => Some(x),
+ (None, None) => None,
+ }
+ })
+ }
+
+ pub fn create_empty_state(
+ &self,
+ max_context_length: Option<usize>,
+ context: &B::Context,
+ ) -> Result<TransformerState<B>, B::Error> {
+ let layer_states = self
+ .layers
+ .iter()
+ .map(|(layer, _rope)| match layer.kv_source_layer_index {
+ None => {
+ layer.mixer.create_empty_state(max_context_length, context).map(TransformerLayerStateType::Owned)
+ },
+ Some(kv_source_layer_index) => Ok(TransformerLayerStateType::Shared(kv_source_layer_index)),
+ })
+ .collect::<Result<_, B::Error>>()?;
+
+ let context_length = 0;
+
+ Ok(TransformerState {
+ layer_states,
+ context_length,
+ })
+ }
+
+ pub fn encode(
+ &self,
+ input: Allocation<B>,
+ per_layer_inputs: Option<&Allocation<B>>,
+ batch_dim: &BatchTopology,
+ output_range: Option<Range<usize>>,
+ mut state: Option<&mut TransformerState<B>>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Option<Allocation<B>>, B::Error> {
+ let mut hidden = input;
+
+ let mut shortcut = encoder.allocate_scratch(hidden.size())?;
+
+ let context_length = state.as_ref().map(|state| state.context_length).unwrap_or(0);
+ let token_positions =
+ batch_dim.heights().map(|rel_pos| context_length + rel_pos as usize).collect::<Box<[usize]>>();
+
+ let precalculated_ropes = self
+ .ropes
+ .iter()
+ .map(|rope_config| PrecalculatedRoPE::precalculate(rope_config, &token_positions, encoder))
+ .collect::<Result<Box<[_]>, B::Error>>()?;
+
+ for (layer, layer_rope_index) in self.layers.iter() {
+ let precalculated_rope = layer_rope_index.map(|i| &precalculated_ropes[i]);
+
+ let layer_state = if let Some(state) = &mut state {
+ Some(match &mut state.layer_states[layer.layer_index] {
+ TransformerLayerStateType::Owned(layer_state) => MaybeMut::Mut(layer_state.as_mut()),
+ TransformerLayerStateType::Shared(owned_layer_index) => {
+ let TransformerLayerStateType::Owned(owned_layer) = &state.layer_states[*owned_layer_index]
+ else {
+ panic!("shared layer doesn't point to an owned layer");
+ };
+ MaybeMut::Const(owned_layer.as_ref())
+ },
+ })
+ } else {
+ None
+ };
+
+ hidden = layer.encode(
+ hidden,
+ &mut shortcut,
+ per_layer_inputs,
+ precalculated_rope,
+ batch_dim,
+ layer_state,
+ encoder,
+ )?;
+ }
+
+ let Some(output_range) = output_range else {
+ return Ok(None);
+ };
+
+ let output_normalized =
+ self.output_norm.encode(&hidden, output_range.start, output_range.len(), Some(&mut shortcut), encoder)?;
+
+ Ok(Some(output_normalized))
+ }
+}
diff --git a/crates/backend-uzu/src/encodable_block/transformer_layer.rs b/crates/backend-uzu/src/encodable_block/transformer_layer.rs
new file mode 100644
index 000000000..a1bfbe756
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/transformer_layer.rs
@@ -0,0 +1,233 @@
+use thiserror::Error;
+
+use crate::{
+ backends::common::{Allocation, Backend, Encoder},
+ config::{transformer::TransformerConfig, transformer_layer::TransformerLayerConfig},
+ data_type::DataType,
+ encodable_block::{
+ batch_topology::BatchTopology,
+ mixer::{Mixer, MixerNewError, MixerState, attention::rope::PrecalculatedRoPE},
+ mlp::{Mlp, MlpBlockError},
+ normalization::{Normalization, NormalizationNewError, PostLayerScalar},
+ per_layer_embedding::PerLayerEmbeddingProjection,
+ },
+ parameters::{ParameterLoaderError, ParameterTree},
+ utils::maybe_mut::MaybeMut,
+};
+
+#[derive(Debug, Error)]
+pub enum TransformerLayerError<B: Backend> {
+ #[error("Parameter loader error: {0}")]
+ ParameterLoader(#[from] ParameterLoaderError<B>),
+ #[error("Mixer error: {0}")]
+ Mixer(#[from] MixerNewError<B>),
+ #[error("MLP error: {0}")]
+ MlpBlock(#[from] MlpBlockError<B>),
+ #[error("Normalization error: {0}")]
+ Normalization(#[from] NormalizationNewError<B>),
+ #[error("Layer {layer_index} sets post_layer_scalar but has no post_mlp_norm")]
+ PostLayerScalarWithoutPostMlpNorm {
+ layer_index: usize,
+ },
+ #[error("Transformer layers except the first one if it doesn't have rht in mixer require pre_mixer_norm_config")]
+ MissingPreMixerNormConfig,
+}
+
+// TODO: saner shortcut
+
+pub struct TransformerLayer<B: Backend> {
+ pub layer_index: usize,
+ pub pre_mixer_norm: Option<Normalization<B>>,
+ pub kv_source_layer_index: Option<usize>,
+ pub mixer: Box<dyn Mixer<B>>,
+ pub post_mixer_norm: Option<Normalization<B>>,
+ pub pre_mlp_norm: Normalization<B>,
+ pub mlp: Box<dyn Mlp<B>>,
+ pub post_mlp_norm: Option<Normalization<B>>,
+ pub ple_projection: Option<PerLayerEmbeddingProjection<B>>,
+}
+
+impl<B: Backend> TransformerLayer<B> {
+ pub fn new(
+ context: &B::Context,
+ transformer_config: &TransformerConfig,
+ layer_config: &TransformerLayerConfig,
+ layer_index: usize,
+ parameter_tree: &ParameterTree<B>,
+ data_type: DataType,
+ ) -> Result<Self, TransformerLayerError<B>> {
+ let post_layer_scalar = if layer_config.has_post_layer_scalar {
+ if layer_config.post_mlp_norm_config.is_none() {
+ return Err(TransformerLayerError::PostLayerScalarWithoutPostMlpNorm {
+ layer_index,
+ });
+ }
+ let leaf = parameter_tree.leaf("post_layer_scalar")?;
+ let scalar = match data_type {
+ DataType::F32 => leaf.validate(&[1], data_type)?.read_slice::<f32>()?[0],
+ DataType::F16 => leaf.validate(&[1], data_type)?.read_slice::<half::f16>()?[0].to_f32(),
+ DataType::BF16 => leaf.validate(&[1], data_type)?.read_slice::<half::bf16>()?[0].to_f32(),
+ _ => unreachable!(),
+ };
+ Some(scalar)
+ } else {
+ None
+ };
+
+ // When a PLE projection is present it owns the post-layer scalar (applied
+ // to the combined residual), so the norms must not also apply it.
+ let (residual_sum_scalar, output_scalar) = match (post_layer_scalar, layer_config.ple_config.is_none()) {
+ (Some(scalar), true) => (PostLayerScalar::ScaleResidualSum(scalar), PostLayerScalar::ScaleOutput(scalar)),
+ _ => (PostLayerScalar::None, PostLayerScalar::None),
+ };
+
+ let (mixer, mixer_hadamard_factors) = <dyn Mixer<B>>::new(
+ transformer_config.model_dim,
+ data_type,
+ layer_config.rope_config.as_ref(),
+ &layer_config.mixer_config,
+ &parameter_tree.subtree("mixer")?,
+ context,
+ )?;
+
+ let pre_mixer_norm = if let Some(pre_mixer_norm_config) = &layer_config.pre_mixer_norm_config {
+ Some(Normalization::new(
+ transformer_config.model_dim,
+ mixer_hadamard_factors,
+ true,
+ layer_index > 0,
+ PostLayerScalar::None,
+ data_type,
+ pre_mixer_norm_config,
+ &parameter_tree.subtree("pre_mixer_norm")?,
+ context,
+ )?)
+ } else {
+ if layer_index != 0 || mixer_hadamard_factors.is_some() {
+ return Err(TransformerLayerError::MissingPreMixerNormConfig);
+ }
+ None
+ };
+
+ let post_mixer_norm = if let Some(norm_config) = &layer_config.post_mixer_norm_config {
+ Some(Normalization::new(
+ transformer_config.model_dim,
+ None,
+ false,
+ false,
+ PostLayerScalar::None,
+ data_type,
+ norm_config,
+ &parameter_tree.subtree("post_mixer_norm")?,
+ context,
+ )?)
+ } else {
+ None
+ };
+
+ let (mlp, mlp_input_hadamard_factors) = <dyn Mlp<B>>::new(
+ &layer_config.mlp_config,
+ transformer_config.model_dim,
+ layer_config.hidden_dim.unwrap_or(transformer_config.hidden_dim),
+ context,
+ &parameter_tree.subtree("mlp")?,
+ data_type,
+ )?;
+
+ let pre_mlp_norm = Normalization::new(
+ transformer_config.model_dim,
+ mlp_input_hadamard_factors,
+ true,
+ true,
+ residual_sum_scalar,
+ data_type,
+ &layer_config.pre_mlp_norm_config,
+ &parameter_tree.subtree("pre_mlp_norm")?,
+ context,
+ )?;
+
+ let post_mlp_norm = if let Some(norm_config) = &layer_config.post_mlp_norm_config {
+ Some(Normalization::new(
+ transformer_config.model_dim,
+ None,
+ false,
+ false,
+ output_scalar,
+ data_type,
+ norm_config,
+ &parameter_tree.subtree("post_mlp_norm")?,
+ context,
+ )?)
+ } else {
+ None
+ };
+
+ let ple_projection = layer_config.ple_config.as_ref().map(|ple_config| {
+ let ple_loader = parameter_tree.subtree("ple").expect("Failed to get ple subtree");
+ PerLayerEmbeddingProjection::new(
+ context,
+ ple_config,
+ transformer_config.model_dim,
+ transformer_config.layer_configs.len(),
+ post_layer_scalar.unwrap_or(1.0),
+ data_type,
+ &ple_loader,
+ )
+ .expect("Failed to create per-layer embedding projection")
+ });
+
+ Ok(Self {
+ layer_index,
+ pre_mixer_norm,
+ kv_source_layer_index: layer_config.kv_source_layer_index,
+ mixer,
+ post_mixer_norm,
+ pre_mlp_norm,
+ mlp,
+ post_mlp_norm,
+ ple_projection,
+ })
+ }
+
+ pub fn encode(
+ &self,
+ input: Allocation<B>,
+ shortcut: &mut Allocation<B>,
+ per_layer_inputs: Option<&Allocation<B>>,
+ precalculated_rope: Option<&PrecalculatedRoPE<B>>,
+ batch_dim: &BatchTopology,
+ state: Option<MaybeMut<dyn MixerState<B>>>,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error> {
+ let hidden = if let Some(pre_mixer_norm) = &self.pre_mixer_norm {
+ pre_mixer_norm.encode(&input, 0, batch_dim.size(), Some(shortcut), encoder)?
+ } else {
+ assert!(self.layer_index == 0);
+ encoder.encode_copy(&input, .., shortcut, ..);
+ input
+ };
+
+ // TODO: In prefill outside of sampling suffix in last layer part of mixer (ie out projection) and everything after is dead code
+ let mut hidden = self.mixer.encode(hidden, precalculated_rope, batch_dim, state, encoder)?;
+
+ if let Some(post_mixer_norm) = &self.post_mixer_norm {
+ hidden = post_mixer_norm.encode(&hidden, 0, batch_dim.size(), None, encoder)?;
+ }
+
+ hidden = self.pre_mlp_norm.encode(&hidden, 0, batch_dim.size(), Some(shortcut), encoder)?;
+
+ hidden = self.mlp.encode(hidden, batch_dim.size(), encoder)?;
+
+ if let Some(post_mlp_norm) = &self.post_mlp_norm {
+ hidden = post_mlp_norm.encode(&hidden, 0, batch_dim.size(), None, encoder)?;
+ }
+
+ if let Some(ple_projection) = &self.ple_projection {
+ let per_layer_inputs = per_layer_inputs.expect("per-layer inputs required for PLE layer");
+ ple_projection.encode(self.layer_index, per_layer_inputs, shortcut, &hidden, batch_dim.size(), encoder)?;
+ encoder.encode_fill(&mut hidden, 0);
+ }
+
+ Ok(hidden)
+ }
+}
diff --git a/crates/backend-uzu/src/engine/classifier_model.rs b/crates/backend-uzu/src/engine/classifier_model.rs
new file mode 100644
index 000000000..478e82945
--- /dev/null
+++ b/crates/backend-uzu/src/engine/classifier_model.rs
@@ -0,0 +1,147 @@
+use std::{
+ cmp::min,
+ collections::HashMap,
+ fs::File,
+ io::{self, BufReader},
+ path::Path,
+ rc::Rc,
+};
+
+use half::bf16;
+use shoji::traits::backend::classification::ClassifierOutput;
+use thiserror::Error;
+
+use crate::{
+ backends::common::{AllocationType, Backend, Context, Encoder},
+ config::model::classifier_model::ClassifierModelConfig,
+ data_type::DataType,
+ encodable_block::classifier::{Classifier as ClassifierEncodable, ClassifierError as ClassifierEncodableError},
+ engine::Engine,
+ parameters::{HeaderLoadingError, ParameterLoader, ParameterLoaderError},
+};
+
+pub struct ClassifierModel<B: Backend> {
+ context: Rc<B::Context>,
+ classifier: ClassifierEncodable<B>,
+ output_labels: Box<[String]>,
+ data_type: DataType,
+}
+
+#[derive(Debug, Error)]
+pub enum EngineLoadClassifierError<B: Backend> {
+ #[error("I/O error: {0}")]
+ IO(#[from] io::Error),
+ #[error("Serde error: {0}")]
+ Serde(#[from] serde_json::Error),
+ #[error("HeaderLoading error: {0}")]
+ HeaderLoading(#[from] HeaderLoadingError),
+ #[error("ParameterLoader error: {0}")]
+ ParameterLoader(#[from] ParameterLoaderError<B>),
+ #[error("Classifier error: {0}")]
+ Classifier(#[from] ClassifierEncodableError<B>),
+}
+
+impl<B: Backend> Engine<B> {
+ pub fn load_classifier_model(
+ &self,
+ model_path: &Path,
+ ) -> Result<ClassifierModel<B>, EngineLoadClassifierError<B>> {
+ let context = self.context.clone();
+
+ let config: ClassifierModelConfig =
+ serde_json::from_reader(BufReader::new(File::open(model_path.join("config.json"))?))?;
+
+ let data_type = DataType::BF16;
+
+ let weights_file = File::open(model_path.join("model.safetensors"))?;
+ let weight_loader = ParameterLoader::new(&weights_file, context.as_ref())?;
+
+ let classifier = ClassifierEncodable::new(
+ context.as_ref(),
+ &config.classifier_config,
+ &weight_loader.tree().subtree("classifier")?,
+ data_type,
+ )?;
+
+ let output_labels = if let Some(output_labels) = config.classifier_config.output_labels {
+ assert!(output_labels.len() == config.classifier_config.num_labels);
+ output_labels
+ } else {
+ (0..config.classifier_config.num_labels).map(|index| format!("class_{index}")).collect()
+ };
+
+ weight_loader.tree().assert_all_tensors_validated()?;
+
+ Ok(ClassifierModel {
+ context,
+ classifier,
+ output_labels,
+ data_type,
+ })
+ }
+}
+
+#[derive(Debug, Error)]
+pub enum ClassifierModelClassifyError<B: Backend> {
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+ #[error("Classifier error: {0}")]
+ Classifier(#[from] ClassifierEncodableError<B>),
+ #[error("Input is empty")]
+ EmptyInput,
+ #[error("Input larger than model context size")]
+ ContextOverflow,
+}
+
+impl<B: Backend> ClassifierModel<B> {
+ pub fn classify(
+ &self,
+ input: &[u64],
+ ) -> Result<ClassifierOutput, ClassifierModelClassifyError<B>> {
+ if input.is_empty() {
+ return Err(ClassifierModelClassifyError::EmptyInput);
+ }
+
+ if self.classifier.max_context_length().is_some_and(|max_context_length| input.len() > max_context_length) {
+ return Err(ClassifierModelClassifyError::ContextOverflow);
+ }
+
+ let mut encoder = Encoder::<B>::new(&self.context).map_err(ClassifierModelClassifyError::Backend)?;
+
+ let mut token_ids =
+ encoder.allocate_constant(size_of_val(input)).map_err(ClassifierModelClassifyError::Backend)?;
+ token_ids.copyin(input);
+
+ let logits = self.classifier.encode(&token_ids, input.len(), &mut encoder)?;
+
+ let mut output_buffer = self
+ .context
+ .create_allocation(self.output_labels.len() * self.data_type.size_in_bytes(), AllocationType::Global)
+ .map_err(ClassifierModelClassifyError::Backend)?;
+
+ encoder.encode_copy(&logits, .., &mut output_buffer, ..);
+
+ drop(logits);
+ drop(token_ids);
+
+ encoder.end_encoding().submit().wait_until_completed().map_err(ClassifierModelClassifyError::Backend)?;
+
+ assert!(self.data_type == DataType::BF16);
+
+ let logits_bf16: Vec<bf16> = output_buffer.copyout::<bf16>();
+ let count = min(self.output_labels.len(), logits_bf16.len());
+
+ let mut logits: Vec<f32> = vec![0.0f32; count];
+ let mut probabilities = HashMap::new();
+ for i in 0..count {
+ logits[i] = logits_bf16[i].to_f32();
+ let prob = 1.0 / (1.0 + (-logits[i]).exp());
+ probabilities.insert(self.output_labels[i].clone(), prob);
+ }
+
+ Ok(ClassifierOutput {
+ logits,
+ probabilities,
+ })
+ }
+}
diff --git a/crates/backend-uzu/src/session/config/grammar_config.rs b/crates/backend-uzu/src/engine/language_model/grammar/mod.rs
similarity index 59%
rename from crates/backend-uzu/src/session/config/grammar_config.rs
rename to crates/backend-uzu/src/engine/language_model/grammar/mod.rs
index 2b6d9499f..85257a32e 100644
--- a/crates/backend-uzu/src/session/config/grammar_config.rs
+++ b/crates/backend-uzu/src/engine/language_model/grammar/mod.rs
@@ -1,11 +1,11 @@
+use std::error::Error;
+
use schemars::JsonSchema;
-use serde_json::{self, Value};
+use thiserror::Error;
+use tokenizers::Tokenizer;
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum StructuredOutput {
- Schema(String),
- AnyJson,
-}
+#[cfg(grammar_xgrammar)]
+mod xgrammar;
#[derive(Debug, Clone)]
pub enum GrammarConfig {
@@ -50,37 +50,6 @@ impl GrammarConfig {
}
}
- pub fn structured_output_from_schema(raw: &str) -> StructuredOutput {
- let Ok(Value::Object(obj)) = serde_json::from_str::<Value>(raw) else {
- return StructuredOutput::Schema(raw.to_string());
- };
-
- match obj.get("type").and_then(Value::as_str) {
- Some("json_object") => return StructuredOutput::AnyJson,
- Some("json_schema") => {
- if let Some(inner) = obj.get("json_schema") {
- return StructuredOutput::Schema(unwrap_inner_schema(inner));
- }
- if let Some(schema) = obj.get("schema") {
- return StructuredOutput::Schema(schema.to_string());
- }
- },
- _ => {},
- }
-
- if let Some(schema) = obj.get("schema") {
- let looks_like_envelope = obj.get("name").is_some_and(Value::is_string)
- && !obj.contains_key("type")
- && !obj.contains_key("properties")
- && !obj.contains_key("$ref");
- if looks_like_envelope {
- return StructuredOutput::Schema(schema.to_string());
- }
- }
-
- StructuredOutput::Schema(raw.to_string())
- }
-
pub fn regex(
pattern: String,
print_converted_ebnf: bool,
@@ -129,13 +98,47 @@ impl GrammarConfig {
}
}
-fn unwrap_inner_schema(inner: &Value) -> String {
- if let Some(schema) = inner.as_object().and_then(|object| object.get("schema")) {
- return schema.to_string();
- }
- inner.to_string()
+#[derive(Debug, Error)]
+#[error("Grammar error: {0}")]
+pub struct GrammarError(Box<dyn Error>);
+
+#[derive(Debug, Error)]
+#[error("No grammar backend available")]
+pub struct NoGrammarBackend;
+
+// TODO: jumpforward?
+
+pub trait Grammar {
+ fn next_bitmask(
+ &mut self,
+ bitmask: &mut [u32],
+ ) -> bool;
+
+ fn accept_token(
+ &mut self,
+ token_id: u64,
+ ) -> Result<(), GrammarError>;
+
+ fn rollback(
+ &mut self,
+ num_tokens: usize,
+ );
+
+ fn is_terminated(&self) -> bool;
}
-#[cfg(test)]
-#[path = "../../../unit/session/config/grammar_config.rs"]
-mod tests;
+impl dyn Grammar {
+ #[cfg_attr(not(grammar_xgrammar), allow(unused_variables))]
+ pub fn new(
+ config: &GrammarConfig,
+ tokenizer: &Tokenizer,
+ trigger_token_id: Option<u64>,
+ stop_token_ids: Option<&[i32]>,
+ ) -> Result<Box<dyn Grammar>, GrammarError> {
+ #[cfg(grammar_xgrammar)]
+ return Ok(Box::new(xgrammar::XGrammar::new(config, tokenizer, trigger_token_id, stop_token_ids)?));
+
+ #[cfg(not(grammar_xgrammar))]
+ return Err(GrammarError(Box::new(NoGrammarBackend)));
+ }
+}
diff --git a/crates/backend-uzu/src/language_model/grammar/xgram.rs b/crates/backend-uzu/src/engine/language_model/grammar/xgrammar.rs
similarity index 64%
rename from crates/backend-uzu/src/language_model/grammar/xgram.rs
rename to crates/backend-uzu/src/engine/language_model/grammar/xgrammar.rs
index 6eabdf851..f47e99dd9 100644
--- a/crates/backend-uzu/src/language_model/grammar/xgram.rs
+++ b/crates/backend-uzu/src/engine/language_model/grammar/xgrammar.rs
@@ -1,19 +1,16 @@
-#![cfg(grammar_xgrammar)]
-
-use std::iter::repeat_n;
-
+use thiserror::Error;
+use tokenizers::Tokenizer;
use xgrammar::{
- DLDataType, DLDataTypeCode, DLDevice, DLDeviceType, DLTensor, Grammar, GrammarCompiler, GrammarMatcher,
- TokenizerInfo, c_void,
+ DLDataType, DLDataTypeCode, DLDevice, DLDeviceType, DLTensor, Grammar as XGrammarGrammar, GrammarCompiler,
+ GrammarMatcher, TokenizerInfo, c_void,
};
use crate::{
data_type::DataType,
- language_model::grammar::CompiledGrammar,
- session::{config::GrammarConfig, types::Error},
+ engine::language_model::grammar::{Grammar, GrammarConfig, GrammarError},
};
-enum CompiledGrammarEngagementState {
+enum GrammarEngagementState {
Always,
Triggered {
trigger_token_id: u64,
@@ -21,7 +18,7 @@ enum CompiledGrammarEngagementState {
},
}
-impl CompiledGrammarEngagementState {
+impl GrammarEngagementState {
fn is_engaged(&self) -> bool {
match self {
Self::Always => true,
@@ -69,18 +66,36 @@ impl CompiledGrammarEngagementState {
}
}
-pub struct CompiledXGrammar {
+pub struct XGrammar {
vocab_size: usize,
matcher: GrammarMatcher,
- engagement_state: CompiledGrammarEngagementState,
+ engagement_state: GrammarEngagementState,
}
-impl CompiledXGrammar {
- pub fn from_config(
+#[derive(Debug, Error)]
+pub enum XGrammarError {
+ #[error("Grammar rejected the token")]
+ GrammarReject,
+ #[error("XGrammar error: {0}")]
+ XGrammar(String),
+}
+
+impl From<XGrammarError> for GrammarError {
+ fn from(val: XGrammarError) -> Self {
+ GrammarError(Box::new(val))
+ }
+}
+
+impl XGrammar {
+ pub fn new(
config: &GrammarConfig,
+ tokenizer: &Tokenizer,
trigger_token_id: Option<u64>,
- tokenizer_info: &TokenizerInfo,
- ) -> Result<Self, Error> {
+ stop_token_ids: Option<&[i32]>,
+ ) -> Result<Self, GrammarError> {
+ let tokenizer_info =
+ TokenizerInfo::from_huggingface(tokenizer, None, stop_token_ids).map_err(XGrammarError::XGrammar)?;
+
let vocab_size = tokenizer_info.vocab_size();
let grammar = match config {
@@ -92,26 +107,34 @@ impl CompiledXGrammar {
strict_mode,
} => {
let separators_ref = separators.as_ref().map(|(a, b)| (a.as_str(), b.as_str()));
- Grammar::from_json_schema(schema, *any_whitespace, *indent, separators_ref, *strict_mode, None, false)
- .map_err(Error::GrammarError)?
+ XGrammarGrammar::from_json_schema(
+ schema,
+ *any_whitespace,
+ *indent,
+ separators_ref,
+ *strict_mode,
+ None,
+ false,
+ )
+ .map_err(XGrammarError::XGrammar)?
},
GrammarConfig::Regex {
pattern,
print_converted_ebnf,
- } => Grammar::from_regex(pattern, *print_converted_ebnf).map_err(Error::GrammarError)?,
- GrammarConfig::BuiltinJson => Grammar::builtin_json_grammar(),
+ } => XGrammarGrammar::from_regex(pattern, *print_converted_ebnf).map_err(XGrammarError::XGrammar)?,
+ GrammarConfig::BuiltinJson => XGrammarGrammar::builtin_json_grammar(),
};
- let mut compiler = GrammarCompiler::new(tokenizer_info, 8, true, -1).map_err(Error::GrammarError)?;
- let compiled = compiler.compile_grammar(&grammar).map_err(Error::GrammarError)?;
- let matcher = GrammarMatcher::new(&compiled, None, true, -1).map_err(Error::GrammarError)?;
+ let mut compiler = GrammarCompiler::new(&tokenizer_info, 8, true, -1).map_err(XGrammarError::XGrammar)?;
+ let compiled = compiler.compile_grammar(&grammar).map_err(XGrammarError::XGrammar)?;
+ let matcher = GrammarMatcher::new(&compiled, None, true, -1).map_err(XGrammarError::XGrammar)?;
let engagement_state = if let Some(trigger_token_id) = trigger_token_id {
- CompiledGrammarEngagementState::Triggered {
+ GrammarEngagementState::Triggered {
trigger_token_id,
trigger_distance: None,
}
} else {
- CompiledGrammarEngagementState::Always
+ GrammarEngagementState::Always
};
Ok(Self {
@@ -122,15 +145,19 @@ impl CompiledXGrammar {
}
}
-impl CompiledGrammar for CompiledXGrammar {
- fn next_bitmask(&mut self) -> Result<Option<Box<[u32]>>, Error> {
+impl Grammar for XGrammar {
+ fn next_bitmask(
+ &mut self,
+ bitmask: &mut [u32],
+ ) -> bool {
+ let vocab_size_in_u32s = self.vocab_size.div_ceil(DataType::U32.size_in_bits());
+ assert!(bitmask.len() >= vocab_size_in_u32s); // NOTE: tokenizer vocab can be smaller than model vocab
+
if self.engagement_state.is_engaged() {
- let mut cpu_mask = repeat_n(0, self.vocab_size.div_ceil(32)).collect::<Box<[u32]>>();
- let batch_mask_slice = &mut cpu_mask;
- let mut shape_i64 = [self.vocab_size.div_ceil(32) as i64];
+ let mut shape_i64 = [vocab_size_in_u32s as i64];
let mut bitmask_tensor = unsafe {
DLTensor::new(
- batch_mask_slice.as_mut_ptr() as *mut c_void,
+ bitmask.as_mut_ptr() as *mut c_void,
DLDevice {
device_type: DLDeviceType::kDLCPU,
device_id: 0,
@@ -147,29 +174,21 @@ impl CompiledGrammar for CompiledXGrammar {
)
};
- let success = self.matcher.fill_next_token_bitmask(&mut bitmask_tensor, 0, false);
- if !success {
- return Err(Error::GrammarError("Failed to fill next token bitmask".to_string()));
- }
-
- Ok(Some(cpu_mask))
+ bitmask[vocab_size_in_u32s..].fill(0);
+ self.matcher.fill_next_token_bitmask(&mut bitmask_tensor, 0, false)
} else {
- Ok(None)
+ bitmask.fill(u32::MAX);
+
+ false
}
}
fn accept_token(
&mut self,
token_id: u64,
- ) -> Result<(), Error> {
- if self.engagement_state.is_engaged() {
- if (token_id as usize) >= self.vocab_size {
- return Err(Error::TokenOutOfGrammarRange(token_id, self.vocab_size));
- }
-
- if !self.matcher.accept_token(token_id as i32) {
- return Err(Error::GrammarReject);
- }
+ ) -> Result<(), GrammarError> {
+ if self.engagement_state.is_engaged() && !self.matcher.accept_token(token_id as i32) {
+ return Err(XGrammarError::GrammarReject.into());
}
self.engagement_state.accept_token(token_id);
diff --git a/crates/backend-uzu/src/engine/language_model/mod.rs b/crates/backend-uzu/src/engine/language_model/mod.rs
new file mode 100644
index 000000000..929b5a731
--- /dev/null
+++ b/crates/backend-uzu/src/engine/language_model/mod.rs
@@ -0,0 +1,147 @@
+use std::{fs::File, io, io::BufReader, path::Path, rc::Rc};
+
+use thiserror::Error;
+
+use crate::{
+ backends::common::{
+ Backend, Context, Kernels,
+ kernel::{ContextRingUpdateKernel, TokenCopySampledKernel},
+ },
+ config::model::{generation::GenerationConfig, language_model::LanguageModelConfig},
+ data_type::DataType,
+ encodable_block::{
+ decoder::{Decoder, DecoderError},
+ sampling::{Sampling, SamplingMethod},
+ },
+ engine::Engine,
+ parameters::{HeaderLoadingError, ParameterLoader, ParameterLoaderError},
+};
+
+pub mod grammar;
+pub mod state;
+pub mod stream;
+
+pub struct LanguageModel<B: Backend> {
+ context: Rc<B::Context>,
+ decoder: Decoder<B>,
+ sampling: Sampling<B>,
+ token_copy: <B::Kernels as Kernels>::TokenCopySampledKernel,
+ context_ring_update: <B::Kernels as Kernels>::ContextRingUpdateKernel,
+ generation_config: GenerationConfig,
+ vocab_size: usize,
+}
+
+#[derive(Debug, Error)]
+pub enum EngineLoadLanguageModelError<B: Backend> {
+ #[error("I/O error: {0}")]
+ IO(#[from] io::Error),
+ #[error("Serde error: {0}")]
+ Serde(#[from] serde_json::Error),
+ #[error("HeaderLoading error: {0}")]
+ HeaderLoading(#[from] HeaderLoadingError),
+ #[error("ParameterLoader error: {0}")]
+ ParameterLoader(#[from] ParameterLoaderError<B>),
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+ #[error("Decoder error: {0}")]
+ Decoder(#[from] DecoderError<B>),
+}
+
+impl<B: Backend> Engine<B> {
+ pub fn load_language_model(
+ &self,
+ model_path: &Path,
+ ) -> Result<LanguageModel<B>, EngineLoadLanguageModelError<B>> {
+ let context = self.context.clone();
+
+ let config: LanguageModelConfig =
+ serde_json::from_reader(BufReader::new(File::open(model_path.join("config.json"))?))?;
+
+ let data_type = DataType::BF16;
+
+ let weights_file = File::open(model_path.join("model.safetensors"))?;
+ let weight_loader = ParameterLoader::new(&weights_file, context.as_ref())?;
+
+ let decoder = Decoder::new(
+ context.as_ref(),
+ &config.decoder_config,
+ &weight_loader.tree().subtree("decoder")?,
+ data_type,
+ )?;
+
+ let sampling = Sampling::new(data_type, config.decoder_config.vocab_size);
+
+ let token_copy = <B::Kernels as Kernels>::TokenCopySampledKernel::new(&context)
+ .map_err(EngineLoadLanguageModelError::Backend)?;
+ let context_ring_update = <B::Kernels as Kernels>::ContextRingUpdateKernel::new(&context)
+ .map_err(EngineLoadLanguageModelError::Backend)?;
+
+ weight_loader.tree().assert_all_tensors_validated()?;
+
+ let generation_config = config.generation_config;
+
+ let vocab_size = config.decoder_config.vocab_size;
+
+ Ok(LanguageModel {
+ context,
+ decoder,
+ sampling,
+ token_copy,
+ context_ring_update,
+ generation_config,
+ vocab_size,
+ })
+ }
+}
+
+impl<B: Backend> LanguageModel<B> {
+ pub fn max_context_length(&self) -> Option<usize> {
+ self.decoder.max_context_length()
+ }
+
+ pub fn recommended_context_length(&self) -> Option<usize> {
+ let max_context_length = self.max_context_length();
+
+ // TODO: This is not the correct way to do it, there should be a real memory model
+ if self.context.sparse_buffers_supported() {
+ // We just assume that all mixers use sparse if it's available to make max context free until it's actually used
+ // Currenlty true for all mixers in uzu:
+ // - full attention uses sparse if it's available to make max context free until it's actually used
+ // - sliding window attention is bound, usually well below the recommended max context size on non-sparse (but can be made to use sparse if we care about it enough)
+ // - short conv/mamba2/delta net are constant state size
+ max_context_length
+ } else if let Some(max_context_length) = max_context_length {
+ // If sparse buffers aren't supported and model has finite maximum context length we assume that kv cache is expensive enough that we should probably clamp it to
+ // something reasonable-ish for the platform. This is very primitive but works I guess...
+ let platform_recommended_context_length = if cfg!(target_os = "ios") {
+ 8192
+ } else {
+ 16384
+ };
+
+ Some(usize::min(max_context_length, platform_recommended_context_length))
+ } else {
+ // We just assume that unlimited context means constant state size on all mixers and is thus free
+ None
+ }
+ }
+
+ pub fn speculation_supported(&self) -> bool {
+ self.decoder.speculation_supported()
+ }
+
+ pub fn default_sampling_method(&self) -> SamplingMethod {
+ SamplingMethod::Stochastic {
+ temperature: self.generation_config.temperature,
+ top_k: self.generation_config.top_k,
+ top_p: self.generation_config.top_p,
+ min_p: self.generation_config.min_p,
+ repetition_penalty: self.generation_config.repetition_penalty,
+ suffix_repetition_length: self.generation_config.suffix_repetition_length,
+ }
+ }
+
+ pub fn generation_config(&self) -> &GenerationConfig {
+ &self.generation_config
+ }
+}
diff --git a/crates/backend-uzu/src/engine/language_model/state.rs b/crates/backend-uzu/src/engine/language_model/state.rs
new file mode 100644
index 000000000..291e50073
--- /dev/null
+++ b/crates/backend-uzu/src/engine/language_model/state.rs
@@ -0,0 +1,52 @@
+use thiserror::Error;
+
+use crate::{
+ backends::common::Backend,
+ encodable_block::{sampling::PRng, transformer::TransformerState},
+ engine::language_model::LanguageModel,
+};
+
+pub struct LanguageModelState<B: Backend> {
+ pub(super) tokens: Vec<u64>,
+ pub(super) last_output_token: Option<u64>, // TODO: this leaks previous LanguageModelStreamOptions
+ pub(super) prng: PRng,
+ pub(super) transformer_state: TransformerState<B>,
+ pub(super) max_context_length: Option<usize>,
+}
+
+impl<B: Backend> LanguageModelState<B> {
+ pub fn tokens(&self) -> &[u64] {
+ &self.tokens
+ }
+}
+
+#[derive(Debug, Error)]
+pub enum LanguageModelCreateEmptyStateError<B: Backend> {
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+}
+
+impl<B: Backend> LanguageModel<B> {
+ pub fn create_empty_state(
+ &self,
+ max_context_length: Option<usize>,
+ ) -> Result<LanguageModelState<B>, LanguageModelCreateEmptyStateError<B>> {
+ let tokens = Vec::new();
+ let last_output_token = None;
+
+ let prng = PRng::new(rand::random());
+
+ let transformer_state = self
+ .decoder
+ .create_empty_state(max_context_length, &self.context)
+ .map_err(LanguageModelCreateEmptyStateError::Backend)?;
+
+ Ok(LanguageModelState {
+ tokens,
+ last_output_token,
+ prng,
+ transformer_state,
+ max_context_length,
+ })
+ }
+}
diff --git a/crates/backend-uzu/src/engine/language_model/stream/mod.rs b/crates/backend-uzu/src/engine/language_model/stream/mod.rs
new file mode 100644
index 000000000..c1a899538
--- /dev/null
+++ b/crates/backend-uzu/src/engine/language_model/stream/mod.rs
@@ -0,0 +1,64 @@
+use thiserror::Error;
+
+use crate::{
+ backends::common::Backend,
+ encodable_block::decoder::DecoderError,
+ engine::language_model::{
+ LanguageModel,
+ grammar::{Grammar, GrammarError},
+ state::LanguageModelState,
+ stream::stream::LanguageModelStream,
+ },
+ speculators::speculator::Speculator,
+};
+pub use crate::{encodable_block::sampling::SamplingMethod, trie::TrieCreationConfig};
+
+mod stream;
+
+pub struct LanguageModelStreamSpeculatorOptions<'a> {
+ pub speculator: &'a dyn Speculator,
+ pub speculation_budget: usize,
+ pub trie_creation_config: TrieCreationConfig,
+}
+
+pub struct LanguageModelStreamOptions<'a> {
+ pub sampling_method: SamplingMethod,
+ pub grammar: Option<Box<dyn Grammar>>,
+ pub speculator: Option<LanguageModelStreamSpeculatorOptions<'a>>,
+}
+
+#[derive(Debug, Error)]
+pub enum LanguageModelStreamError<B: Backend> {
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+ #[error("Decoder error: {0}")]
+ Decoder(#[from] DecoderError<B>),
+ #[error("Grammar error: {0}")]
+ Grammar(#[from] GrammarError),
+ #[error("Speculators are not supported by this model")]
+ SpeculatorsNotSupported,
+ #[error("No seed token (both state and input are empty)")]
+ NoSeedToken,
+ #[error("Context overflow")]
+ ContextOverflow,
+}
+
+impl<B: Backend> LanguageModel<B> {
+ pub fn default_stream_options<'a>(&'a self) -> LanguageModelStreamOptions<'a> {
+ LanguageModelStreamOptions {
+ sampling_method: self.default_sampling_method(),
+ grammar: None,
+ speculator: None,
+ }
+ }
+
+ pub fn stream<'a>(
+ &'a self,
+ input: &[u64],
+ state: &'a mut LanguageModelState<B>,
+ options: LanguageModelStreamOptions<'a>,
+ ) -> Result<impl Iterator<Item = Result<u64, LanguageModelStreamError<B>>> + Send + 'a, LanguageModelStreamError<B>>
+ {
+ LanguageModelStream::new(self, input, state, options)
+ }
+}
diff --git a/crates/backend-uzu/src/engine/language_model/stream/stream.rs b/crates/backend-uzu/src/engine/language_model/stream/stream.rs
new file mode 100644
index 000000000..7b52d31e1
--- /dev/null
+++ b/crates/backend-uzu/src/engine/language_model/stream/stream.rs
@@ -0,0 +1,581 @@
+use std::{
+ iter::{once, repeat_n},
+ mem::replace,
+ rc::Rc,
+};
+
+use crate::{
+ backends::common::{
+ Allocation, AllocationPool, AllocationType, Backend, Context, Encoder, Pending,
+ gpu_types::trie::TrieNode as GpuTrieNode,
+ kernel::{ContextRingUpdateKernel, TokenCopySampledKernel},
+ },
+ data_type::DataType,
+ encodable_block::{batch_topology::BatchTopology, sampling::SamplingMethod},
+ engine::language_model::{
+ LanguageModel,
+ grammar::Grammar,
+ state::LanguageModelState,
+ stream::{LanguageModelStreamError, LanguageModelStreamOptions},
+ },
+ trie::TrieNode,
+};
+
+enum ForwardPassChaining<B: Backend> {
+ Constant(u64),
+ InFlight(DecodingStatePending<B>),
+}
+
+impl<B: Backend> ForwardPassChaining<B> {
+ fn resolve<'grammar>(
+ &mut self,
+ tokens: &mut Vec<u64>,
+ grammar: Option<&mut (dyn Grammar + 'grammar)>,
+ ) -> Result<u64, LanguageModelStreamError<B>> {
+ match self {
+ Self::Constant(token_id) => Ok(*token_id),
+ Self::InFlight(in_flight) => {
+ assert!(in_flight.full_accept);
+ for pending in replace(&mut in_flight.pending, Box::new([])) {
+ pending.wait_until_completed().map_err(LanguageModelStreamError::Backend)?;
+ }
+ let output = in_flight.output.as_slice::<u32>();
+ assert_eq!(output.len(), 1);
+ let token_id = output[0] as u64;
+ *self = Self::Constant(token_id);
+ tokens.push(token_id);
+ if let Some(grammar) = grammar {
+ grammar.accept_token(token_id)?;
+ }
+ Ok(token_id)
+ },
+ }
+ }
+}
+
+struct DecodingStatePending<B: Backend> {
+ input_trie: TrieNode,
+ full_accept: bool,
+ pending: Box<[Pending<B>]>,
+ output: Allocation<B>,
+}
+
+enum DecodingState<B: Backend> {
+ Seeded {
+ seed_token: u64,
+ },
+ ForwardPassPending(DecodingStatePending<B>),
+ Accepting {
+ full: Box<[(usize, u64, u64)]>,
+ num_accepted: usize,
+ },
+ Halted,
+ Invalid,
+}
+
+pub struct LanguageModelStream<'a, B: Backend> {
+ model: &'a LanguageModel<B>,
+ model_state: &'a mut LanguageModelState<B>,
+ options: LanguageModelStreamOptions<'a>,
+ allocation_pool: Rc<AllocationPool<B>>,
+ context_ring: Option<Allocation<B>>,
+ decoding_state: DecodingState<B>,
+}
+
+impl<'a, B: Backend> LanguageModelStream<'a, B> {
+ pub fn new(
+ model: &'a LanguageModel<B>,
+ input: &[u64],
+ model_state: &'a mut LanguageModelState<B>,
+ mut options: LanguageModelStreamOptions<'a>,
+ ) -> Result<Self, LanguageModelStreamError<B>> {
+ if model_state.tokens.is_empty() && input.is_empty() {
+ return Err(LanguageModelStreamError::NoSeedToken);
+ };
+
+ if options.speculator.is_some() && !model.speculation_supported() {
+ return Err(LanguageModelStreamError::SpeculatorsNotSupported);
+ }
+
+ if model_state
+ .max_context_length
+ .is_some_and(|max_context_length| model_state.tokens.len() + input.len() > max_context_length)
+ {
+ return Err(LanguageModelStreamError::ContextOverflow);
+ }
+
+ let allocation_pool = Rc::new(model.context.create_allocation_pool(false));
+
+ let mut context_ring =
+ if let Some(suffix_repetition_length) = options.sampling_method.suffix_repetition_length() {
+ let mut context_ring = model
+ .context
+ .create_allocation(
+ (2 + suffix_repetition_length) * DataType::U32.size_in_bytes(),
+ AllocationType::Global,
+ )
+ .map_err(LanguageModelStreamError::Backend)?;
+
+ let state_tokens_range =
+ model_state.tokens.len().saturating_sub(suffix_repetition_length)..model_state.tokens.len();
+
+ context_ring.copyin(
+ &once(0) // offset
+ .chain(once(state_tokens_range.len() as u64)) // length
+ .chain(model_state.tokens[state_tokens_range.clone()].iter().copied()) // tokens
+ .chain(repeat_n(0, suffix_repetition_length - state_tokens_range.len())) // pad if not full
+ .map(|x| x as u32)
+ .collect::<Box<[_]>>(),
+ );
+
+ Some(context_ring)
+ } else {
+ None
+ };
+
+ let decoding_state = if !input.is_empty() {
+ model_state.last_output_token.take();
+
+ // NOTE: this is required for attention correctness (hardcoded suffix 1024). This is really bad design, attention should be rewritten to allow on-demand suffix length
+ let max_batch_size = 1024;
+ let number_of_batches = input.len().div_ceil(max_batch_size);
+
+ model_state
+ .transformer_state
+ .prepare(
+ model_state.transformer_state.context_length() + (number_of_batches - 1) * max_batch_size,
+ usize::min(max_batch_size, input.len()),
+ &model.context,
+ )
+ .map_err(LanguageModelStreamError::Backend)?;
+
+ let mut encoder = Encoder::<B>::new_with_pool(&model.context, allocation_pool.clone())
+ .map_err(LanguageModelStreamError::Backend)?;
+
+ let mut output = None;
+
+ for (batch_idx, input_chunk) in input.chunks(max_batch_size).enumerate() {
+ let last_batch = batch_idx == number_of_batches - 1;
+
+ let input_trie = TrieNode::flat(model_state.tokens.len(), input_chunk, &model_state.prng);
+ let input_flat_trie = input_trie.linearize();
+
+ let mut token_ids = encoder
+ .allocate_constant(input_chunk.len() * DataType::U64.size_in_bytes())
+ .map_err(LanguageModelStreamError::Backend)?;
+ token_ids.copyin(input_chunk);
+
+ let input_flat_trie_nodes = input_flat_trie.token_subtrie_ranges().collect::<Box<[GpuTrieNode]>>();
+ let batch_dim = BatchTopology::new(&input_flat_trie_nodes, true);
+
+ let logits = model.decoder.encode(
+ &token_ids,
+ &batch_dim,
+ last_batch.then(|| (input_chunk.len() - 1)..input_chunk.len()),
+ &mut model_state.transformer_state,
+ &mut encoder,
+ )?;
+
+ if last_batch {
+ let logits = logits.unwrap();
+
+ let seeds = if matches!(options.sampling_method, SamplingMethod::Stochastic { .. }) {
+ let mut seeds = encoder
+ .allocate_constant(DataType::U64.size_in_bytes())
+ .map_err(LanguageModelStreamError::Backend)?;
+ seeds.copyin(&[model_state
+ .prng
+ .derive((model_state.tokens.len() + input_chunk.len() - 1) as u64)]);
+ Some(seeds)
+ } else {
+ None
+ };
+
+ let bitmask = if let Some(grammar) = options.grammar.as_deref_mut() {
+ let mut bitmask = encoder
+ .allocate_constant(
+ model.vocab_size.div_ceil(DataType::U32.size_in_bits()) * DataType::U32.size_in_bytes(),
+ )
+ .map_err(LanguageModelStreamError::Backend)?;
+
+ if grammar.next_bitmask(bitmask.as_slice_mut()) {
+ Some(bitmask)
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ output = Some(
+ model
+ .sampling
+ .encode(
+ &logits,
+ seeds.as_ref(),
+ bitmask.as_ref(),
+ context_ring.as_ref(),
+ Some(&token_ids),
+ &options.sampling_method,
+ &batch_dim,
+ (batch_dim.size() - 1)..batch_dim.size(),
+ &mut encoder,
+ )
+ .map_err(LanguageModelStreamError::Backend)?,
+ );
+ }
+
+ model_state
+ .transformer_state
+ .encode_accept(&(0..input_chunk.len()).collect::<Box<[usize]>>(), &mut encoder)
+ .map_err(LanguageModelStreamError::Backend)?;
+
+ if let Some(suffix_repetition_length) = options.sampling_method.suffix_repetition_length() {
+ model.context_ring_update.encode(
+ &token_ids,
+ context_ring.as_mut().unwrap(),
+ suffix_repetition_length as u32,
+ input_chunk.len() as u32,
+ &mut encoder,
+ );
+ }
+
+ model_state.tokens.extend(input_chunk);
+ }
+
+ let pending = Box::new([encoder.end_encoding().submit()]);
+
+ DecodingState::ForwardPassPending(DecodingStatePending {
+ input_trie: TrieNode::new(0, 0),
+ full_accept: true,
+ pending,
+ output: output.unwrap(),
+ })
+ } else {
+ // TODO: this leaks previous LanguageModelStreamOptions
+ DecodingState::Seeded {
+ seed_token: model_state.last_output_token.take().unwrap(),
+ }
+ };
+
+ Ok(LanguageModelStream {
+ model,
+ model_state,
+ options,
+ allocation_pool,
+ context_ring,
+ decoding_state,
+ })
+ }
+
+ fn generate(&mut self) -> Result<Option<u64>, LanguageModelStreamError<B>> {
+ let (mut prev_output, encoder): (ForwardPassChaining<B>, Option<Encoder<B>>) =
+ match replace(&mut self.decoding_state, DecodingState::Invalid) {
+ DecodingState::Seeded {
+ seed_token,
+ } => {
+ self.model_state.tokens.push(seed_token);
+ if let Some(grammar) = self.options.grammar.as_deref_mut() {
+ let _ = grammar.accept_token(seed_token); // TODO: this should not be ignored
+ }
+ (ForwardPassChaining::Constant(seed_token), None)
+ },
+ DecodingState::ForwardPassPending(forward_pass_pending) => {
+ if forward_pass_pending.full_accept {
+ (ForwardPassChaining::InFlight(forward_pass_pending), None)
+ } else {
+ for pending in forward_pass_pending.pending {
+ pending.wait_until_completed().map_err(LanguageModelStreamError::Backend)?;
+ }
+ let sampled_tokens = forward_pass_pending
+ .output
+ .as_slice::<u32>()
+ .iter()
+ .map(|x| *x as u64)
+ .collect::<Box<[u64]>>();
+ let full = forward_pass_pending
+ .input_trie
+ .linearize()
+ .accept(&sampled_tokens, self.options.grammar.as_deref_mut())?;
+ self.decoding_state = DecodingState::Accepting {
+ full,
+ num_accepted: 0,
+ };
+ return self.generate();
+ }
+ },
+ DecodingState::Accepting {
+ full,
+ num_accepted,
+ } => {
+ let output_token_id = full[num_accepted].2;
+
+ if num_accepted < full.len() - 1 {
+ self.decoding_state = DecodingState::Accepting {
+ full,
+ num_accepted: num_accepted + 1,
+ };
+ return Ok(Some(output_token_id));
+ } else {
+ let accepted_token_indicies = full.iter().map(|(i, _, _)| *i).collect::<Box<[usize]>>();
+ let accepted_input_token_ids = full.iter().map(|(_, t, _)| *t).collect::<Box<[u64]>>();
+ let accepted_output_token_ids = full.iter().map(|(_, _, t)| *t).collect::<Box<[u64]>>();
+ let mut encoder =
+ Encoder::<B>::new_with_pool(&self.model.context, self.allocation_pool.clone())
+ .map_err(LanguageModelStreamError::Backend)?;
+ self.model_state
+ .transformer_state
+ .encode_accept(&accepted_token_indicies, &mut encoder)
+ .map_err(LanguageModelStreamError::Backend)?;
+ if let Some(suffix_repetition_length) = self.options.sampling_method.suffix_repetition_length()
+ {
+ let mut accepted_input_token_ids_const = encoder
+ .allocate_constant(full.len() * DataType::U64.size_in_bytes())
+ .map_err(LanguageModelStreamError::Backend)?;
+ accepted_input_token_ids_const.copyin(&accepted_input_token_ids);
+ self.model.context_ring_update.encode(
+ &accepted_input_token_ids_const,
+ self.context_ring.as_mut().unwrap(),
+ suffix_repetition_length as u32,
+ full.len() as u32,
+ &mut encoder,
+ );
+ }
+ self.model_state.tokens.extend(accepted_output_token_ids);
+ (ForwardPassChaining::Constant(output_token_id), Some(encoder))
+ }
+ },
+ DecodingState::Halted => return Ok(None),
+ DecodingState::Invalid => unreachable!(),
+ };
+
+ let context_length = self.model_state.transformer_state.context_length();
+
+ if self.model_state.max_context_length.is_some_and(|max_context_length| context_length >= max_context_length) {
+ self.decoding_state = DecodingState::Halted;
+ return Ok(Some(prev_output.resolve(&mut self.model_state.tokens, self.options.grammar.as_deref_mut())?));
+ }
+
+ let mut pending = Vec::new();
+ let mut encoder = if let Some(encoder) = encoder {
+ encoder
+ } else {
+ Encoder::<B>::new_with_pool(&self.model.context, self.allocation_pool.clone())
+ .map_err(LanguageModelStreamError::Backend)?
+ };
+
+ let (input_trie, chain_copy, full_accept) = if let Some(speculator) = &self.options.speculator {
+ prev_output.resolve(&mut self.model_state.tokens, self.options.grammar.as_deref_mut())?;
+
+ let input_trie = TrieNode::from_speculator(
+ &self.model_state.tokens,
+ &self.model_state.prng,
+ self.options.grammar.as_deref_mut(),
+ speculator.speculator,
+ self.model.vocab_size,
+ &speculator.trie_creation_config,
+ speculator.speculation_budget,
+ self.model_state.max_context_length.map(|max_context_length| max_context_length - context_length),
+ );
+
+ (input_trie, None, false)
+ } else {
+ let (token, chain_copy) = match &prev_output {
+ ForwardPassChaining::Constant(token) => (*token, None),
+ ForwardPassChaining::InFlight(pending) => (0, Some(&pending.output)),
+ };
+ (TrieNode::new(token, self.model_state.prng.derive(context_length as u64)), chain_copy, true)
+ };
+ let input_flat_trie = input_trie.linearize();
+
+ let token_ids = if let Some(chain_copy) = chain_copy {
+ let mut token_ids =
+ encoder.allocate_scratch(DataType::U64.size_in_bytes()).map_err(LanguageModelStreamError::Backend)?;
+ self.model.token_copy.encode(chain_copy, &mut token_ids, &mut encoder);
+ token_ids
+ } else {
+ let mut token_ids = encoder
+ .allocate_constant(input_flat_trie.len() * DataType::U64.size_in_bytes())
+ .map_err(LanguageModelStreamError::Backend)?;
+ token_ids.copyin(&input_flat_trie.token_ids().collect::<Box<[u64]>>());
+ token_ids
+ };
+
+ let input_flat_trie_nodes = input_flat_trie.token_subtrie_ranges().collect::<Box<[GpuTrieNode]>>();
+ let batch_dim = BatchTopology::new(&input_flat_trie_nodes, full_accept);
+
+ self.model_state
+ .transformer_state
+ .prepare(self.model_state.transformer_state.context_length(), batch_dim.size(), &self.model.context)
+ .map_err(LanguageModelStreamError::Backend)?;
+
+ let logits = self
+ .model
+ .decoder
+ .encode(
+ &token_ids,
+ &batch_dim,
+ Some(0..batch_dim.size()),
+ &mut self.model_state.transformer_state,
+ &mut encoder,
+ )?
+ .unwrap();
+
+ let (bitmask, mut encoder) = if let Some(grammar) = self.options.grammar.as_deref_mut() {
+ if chain_copy.is_some() {
+ pending.push(encoder.end_encoding().submit());
+
+ let mut encoder = Encoder::<B>::new_with_pool(&self.model.context, self.allocation_pool.clone())
+ .map_err(LanguageModelStreamError::Backend)?;
+
+ let mut bitmask = encoder
+ .allocate_constant(
+ self.model.vocab_size.div_ceil(DataType::U32.size_in_bits()) * DataType::U32.size_in_bytes(),
+ )
+ .map_err(LanguageModelStreamError::Backend)?;
+
+ prev_output.resolve(&mut self.model_state.tokens, Some(grammar))?;
+ if grammar.next_bitmask(bitmask.as_slice_mut()) {
+ (Some(bitmask), encoder)
+ } else {
+ (None, encoder)
+ }
+ } else {
+ let mut bitmasks = encoder
+ .allocate_constant(
+ input_flat_trie.len()
+ * self.model.vocab_size.div_ceil(DataType::U32.size_in_bits())
+ * DataType::U32.size_in_bytes(),
+ )
+ .map_err(LanguageModelStreamError::Backend)?;
+
+ if input_flat_trie.fill_bitmasks(bitmasks.as_slice_mut(), self.model.vocab_size, grammar) {
+ (Some(bitmasks), encoder)
+ } else {
+ (None, encoder)
+ }
+ }
+ } else {
+ (None, encoder)
+ };
+
+ let seeds = if matches!(self.options.sampling_method, SamplingMethod::Stochastic { .. }) {
+ let mut seeds = encoder
+ .allocate_constant(input_flat_trie.len() * DataType::U64.size_in_bytes())
+ .map_err(LanguageModelStreamError::Backend)?;
+ seeds.copyin(&input_flat_trie.token_seeds().collect::<Box<[u64]>>());
+ Some(seeds)
+ } else {
+ None
+ };
+
+ let output = self
+ .model
+ .sampling
+ .encode(
+ &logits,
+ seeds.as_ref(),
+ bitmask.as_ref(),
+ self.context_ring.as_ref(),
+ Some(&token_ids),
+ &self.options.sampling_method,
+ &batch_dim,
+ 0..batch_dim.size(),
+ &mut encoder,
+ )
+ .map_err(LanguageModelStreamError::Backend)?;
+
+ drop(seeds);
+ drop(bitmask);
+ drop(logits);
+
+ if full_accept {
+ self.model_state
+ .transformer_state
+ .encode_accept(&(0..batch_dim.size()).collect::<Box<[usize]>>(), &mut encoder)
+ .map_err(LanguageModelStreamError::Backend)?;
+
+ if let Some(suffix_repetition_length) = self.options.sampling_method.suffix_repetition_length() {
+ self.model.context_ring_update.encode(
+ &token_ids,
+ self.context_ring.as_mut().unwrap(),
+ suffix_repetition_length as u32,
+ batch_dim.size() as u32,
+ &mut encoder,
+ );
+ }
+ }
+
+ drop(token_ids);
+
+ pending.push(encoder.end_encoding().submit());
+
+ self.decoding_state = DecodingState::ForwardPassPending(DecodingStatePending {
+ input_trie,
+ full_accept,
+ pending: pending.into_boxed_slice(),
+ output,
+ });
+
+ Ok(Some(prev_output.resolve(&mut self.model_state.tokens, self.options.grammar.as_deref_mut())?))
+ }
+}
+
+impl<'a, B: Backend> Iterator for LanguageModelStream<'a, B> {
+ type Item = Result<u64, LanguageModelStreamError<B>>;
+
+ fn next(&mut self) -> Option<Result<u64, LanguageModelStreamError<B>>> {
+ self.generate().transpose()
+ }
+}
+
+impl<'a, B: Backend> Drop for LanguageModelStream<'a, B> {
+ fn drop(&mut self) {
+ let last_output_token = match replace(&mut self.decoding_state, DecodingState::Invalid) {
+ DecodingState::Seeded {
+ seed_token,
+ } => Some(seed_token),
+ DecodingState::ForwardPassPending(in_flight) => {
+ for pending in in_flight.pending {
+ pending.wait_until_completed().unwrap();
+ }
+
+ if !in_flight.full_accept {
+ let mut encoder =
+ Encoder::<B>::new_with_pool(&self.model.context, self.allocation_pool.clone()).unwrap();
+ self.model_state.transformer_state.encode_accept(&[0], &mut encoder).unwrap();
+ encoder.end_encoding().submit().wait_until_completed().unwrap();
+ }
+
+ Some(in_flight.output.as_slice::<u32>()[0] as u64)
+ },
+ DecodingState::Accepting {
+ full,
+ num_accepted,
+ } => {
+ assert!(num_accepted > 0 && num_accepted < full.len());
+
+ let mut encoder =
+ Encoder::<B>::new_with_pool(&self.model.context, self.allocation_pool.clone()).unwrap();
+ self.model_state
+ .transformer_state
+ .encode_accept(
+ &full.iter().take(num_accepted + 1).map(|(i, _, _)| *i).collect::<Box<[usize]>>(),
+ &mut encoder,
+ )
+ .unwrap();
+ encoder.end_encoding().submit().wait_until_completed().unwrap();
+
+ self.model_state.tokens.extend(full.iter().take(num_accepted).map(|(_, _, t)| *t));
+
+ Some(full[num_accepted].2)
+ },
+ DecodingState::Halted => None,
+ DecodingState::Invalid => None, // TODO: proper error handling
+ };
+
+ self.model_state.last_output_token = last_output_token;
+ }
+}
+
+unsafe impl<'a, B: Backend> Send for LanguageModelStream<'a, B> {} // TODO: this should be done properly
diff --git a/crates/backend-uzu/src/engine/mod.rs b/crates/backend-uzu/src/engine/mod.rs
new file mode 100644
index 000000000..d47301419
--- /dev/null
+++ b/crates/backend-uzu/src/engine/mod.rs
@@ -0,0 +1,32 @@
+use std::rc::Rc;
+
+use thiserror::Error;
+
+use crate::backends::common::{Backend, Context};
+
+pub mod classifier_model;
+pub mod language_model;
+
+pub struct Engine<B: Backend> {
+ context: Rc<B::Context>,
+}
+
+#[derive(Debug, Error)]
+pub enum EngineNewError<B: Backend> {
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+}
+
+impl<B: Backend> Engine<B> {
+ pub fn new() -> Result<Self, EngineNewError<B>> {
+ let context = <B::Context as Context>::new().map_err(EngineNewError::Backend)?;
+
+ Ok(Self {
+ context,
+ })
+ }
+
+ pub fn peak_memory_usage(&self) -> Option<usize> {
+ self.context.peak_memory_usage()
+ }
+}
diff --git a/crates/backend-uzu/src/forward_pass/cache_layers.rs b/crates/backend-uzu/src/forward_pass/cache_layers.rs
deleted file mode 100644
index b6bc7011a..000000000
--- a/crates/backend-uzu/src/forward_pass/cache_layers.rs
+++ /dev/null
@@ -1,679 +0,0 @@
-use std::cell::Cell;
-
-use crate::{
- array::size_for_shape,
- backends::common::{AllocationType, Backend, Context, Encoder},
- config::token_mixer::AnyTokenMixerConfig,
- data_type::DataType,
- encodable_block::KVCacheUpdate,
- forward_pass::{
- delta_net_layer::DeltaNetLayer,
- kv_cache_layer::{KVCacheLayerState, KVCacheLayerTrait, KVSlice},
- model_shape::ModelShape,
- short_conv_layer::ShortConvLayer,
- ssm_layer::SSMLayer,
- },
-};
-
-pub enum CacheLayer<B: Backend> {
- Transformer(Box<dyn KVCacheLayerTrait<B>>),
- StateSpace(SSMLayer<B>),
- ShortConv(ShortConvLayer<B>),
- DeltaNet(DeltaNetLayer<B>),
-}
-
-pub enum CacheLayerSlice<B: Backend> {
- Transformer(KVSlice<B>),
- StateSpace,
- ShortConv,
- DeltaNet,
-}
-
-impl<B: Backend> CacheLayer<B> {
- pub fn as_transformer(&self) -> Option<&dyn KVCacheLayerTrait<B>> {
- match self {
- CacheLayer::Transformer(layer) => Some(layer.as_ref()),
- _ => None,
- }
- }
-
- pub fn as_transformer_mut(&mut self) -> Option<&mut dyn KVCacheLayerTrait<B>> {
- match self {
- CacheLayer::Transformer(layer) => Some(layer.as_mut()),
- _ => None,
- }
- }
-
- pub fn as_state_space(&self) -> Option<&SSMLayer<B>> {
- match self {
- CacheLayer::StateSpace(layer) => Some(layer),
- _ => None,
- }
- }
-
- pub fn as_state_space_mut(&mut self) -> Option<&mut SSMLayer<B>> {
- match self {
- CacheLayer::StateSpace(layer) => Some(layer),
- _ => None,
- }
- }
-
- pub fn as_short_conv(&self) -> Option<&ShortConvLayer<B>> {
- match self {
- CacheLayer::ShortConv(layer) => Some(layer),
- _ => None,
- }
- }
-
- pub fn as_short_conv_mut(&mut self) -> Option<&mut ShortConvLayer<B>> {
- match self {
- CacheLayer::ShortConv(layer) => Some(layer),
- _ => None,
- }
- }
-
- pub fn as_delta_net(&self) -> Option<&DeltaNetLayer<B>> {
- match self {
- CacheLayer::DeltaNet(layer) => Some(layer),
- _ => None,
- }
- }
-
- pub fn as_delta_net_mut(&mut self) -> Option<&mut DeltaNetLayer<B>> {
- match self {
- CacheLayer::DeltaNet(layer) => Some(layer),
- _ => None,
- }
- }
-}
-
-pub struct CacheLayers<B: Backend> {
- max_suffix_length: usize,
- max_prefix_length: usize,
- entries: Box<[CacheLayer<B>]>,
- bindings: Box<[LayerCacheBinding]>,
-}
-
-pub struct CacheLayersSlice<B: Backend> {
- pub layers: Vec<CacheLayerSlice<B>>,
-}
-
-#[derive(Clone, Copy)]
-struct CacheEntryIndex {
- index: usize,
-}
-
-#[derive(Clone, Copy)]
-enum LayerCacheBinding {
- Owned {
- entry: CacheEntryIndex,
- },
- Shared {
- source: CacheEntryIndex,
- },
-}
-
-pub enum LayerCacheAccess<'a, B: Backend> {
- Owned {
- entry: &'a mut CacheLayer<B>,
- },
- Shared {
- source: &'a CacheLayer<B>,
- },
-}
-
-impl<B: Backend> CacheLayers<B> {
- pub fn new(
- context: &B::Context,
- model_shape: &ModelShape,
- max_prefix_length: usize,
- max_suffix_length: usize,
- ) -> Self {
- let total_context_length = max_prefix_length.max(max_suffix_length);
-
- let kv_source_layers = model_shape.kv_source_layers();
-
- let mut entries: Vec<CacheLayer<B>> = Vec::with_capacity(model_shape.layer_mixers().len());
- let mut bindings: Vec<LayerCacheBinding> = Vec::with_capacity(model_shape.layer_mixers().len());
- for (layer_index, mixer) in model_shape.layer_mixers().iter().enumerate() {
- if let Some(source_layer_index) = kv_source_layers.get(layer_index).copied().flatten() {
- let LayerCacheBinding::Owned {
- entry: source,
- } = bindings[source_layer_index]
- else {
- panic!("kv_source_layer_index {source_layer_index} (layer {layer_index}) must be a prior owner");
- };
- let geometry = |m: &AnyTokenMixerConfig| {
- m.as_attention().map(|a| (a.num_groups, a.head_dim, a.sliding_window_size))
- };
- assert_eq!(
- geometry(&model_shape.layer_mixers()[source_layer_index]),
- geometry(mixer),
- "KV cache sharing requires identical attention geometry"
- );
- bindings.push(LayerCacheBinding::Shared {
- source,
- });
- continue;
- }
-
- let layer = match mixer {
- AnyTokenMixerConfig::AttentionConfig(attn) => {
- let sliding_window = attn.sliding_window_size;
- let length = sliding_window.unwrap_or(max_prefix_length);
- let shape = [length + max_suffix_length, attn.num_groups, attn.head_dim];
- let window_length = sliding_window.filter(|&window_size| window_size < total_context_length);
-
- let state = if let Some(w) = window_length {
- KVCacheLayerState::Windowed {
- ring_offset: 0,
- ring_length: 0,
- window_length: w,
- }
- } else {
- KVCacheLayerState::Full {
- prefix_len: 0,
- }
- };
- let kv_layer = <dyn KVCacheLayerTrait<B>>::new(context, &state, shape, model_shape.data_type)
- .expect("Failed to create KVCacheLayer");
- CacheLayer::Transformer(kv_layer)
- },
- AnyTokenMixerConfig::Mamba2Config(c) => {
- let data_type = DataType::F32;
- let conv_shape = [c.conv_dim(), c.kernel_size.saturating_sub(1)];
- let ssm_shape = [c.num_heads, c.head_dim, c.state_dim];
- let conv_bytes = size_for_shape(&conv_shape, data_type);
- let ssm_bytes = size_for_shape(&ssm_shape, data_type);
-
- CacheLayer::StateSpace(SSMLayer {
- conv_state: (conv_bytes > 0).then(|| {
- context
- .create_allocation(conv_bytes, AllocationType::Global)
- .expect("Failed to create ssm conv allocation")
- }),
- conv_shape,
- ssm_state: context
- .create_allocation(ssm_bytes, AllocationType::Global)
- .expect("Failed to create ssm state allocation"),
- ssm_shape,
- data_type,
- })
- },
- AnyTokenMixerConfig::ShortConvConfig(c) => {
- assert!(c.kernel_size >= 2, "ShortConv kernel_size must be >= 2, got {}", c.kernel_size);
- let conv_shape = [model_shape.model_dim(), c.kernel_size - 1];
- let suffix_state_shape = [max_suffix_length, model_shape.model_dim(), c.kernel_size - 1];
- let conv_bytes = size_for_shape(&conv_shape, model_shape.data_type);
- let suffix_bytes = size_for_shape(&suffix_state_shape, model_shape.data_type);
-
- CacheLayer::ShortConv(ShortConvLayer {
- conv_state: context
- .create_allocation(conv_bytes, AllocationType::Global)
- .expect("Failed to create short conv allocation"),
- conv_shape,
- suffix_state: context
- .create_allocation(suffix_bytes, AllocationType::Global)
- .expect("Failed to create short conv suffix allocation"),
- suffix_shape: suffix_state_shape,
- data_type: model_shape.data_type,
- suffix_state_valid_start: Cell::new(0),
- suffix_state_valid_len: Cell::new(0),
- })
- },
- AnyTokenMixerConfig::DeltaNetConfig(c) => {
- let conv_data_type = DataType::F32;
- let ssm_data_type = DataType::F32;
- let conv_shape = [c.conv_dim(), c.kernel_size.saturating_sub(1)];
- let ssm_shape = [c.num_heads, c.value_head_dim, c.head_dim];
- let conv_bytes = size_for_shape(&conv_shape, conv_data_type);
- let ssm_bytes = size_for_shape(&ssm_shape, ssm_data_type);
-
- CacheLayer::DeltaNet(DeltaNetLayer {
- conv_state: context
- .create_allocation(conv_bytes, AllocationType::Global)
- .expect("Failed to create delta net conv allocation"),
- conv_shape,
- ssm_state: context
- .create_allocation(ssm_bytes, AllocationType::Global)
- .expect("Failed to create delta net ssm allocation"),
- ssm_shape,
- data_type: ssm_data_type,
- })
- },
- };
- bindings.push(LayerCacheBinding::Owned {
- entry: CacheEntryIndex {
- index: entries.len(),
- },
- });
- entries.push(layer);
- }
- let mut entries = entries.into_boxed_slice();
- let bindings = bindings.into_boxed_slice();
-
- let mut encoder: Encoder<B> = Encoder::new(context).expect("Failed to create cache initialization encoder");
- for layer in entries.iter_mut() {
- match layer {
- CacheLayer::Transformer(layer) => {
- layer.encode_zero(&mut encoder);
- },
- CacheLayer::StateSpace(layer) => {
- if let Some(conv_state) = layer.conv_state.as_mut() {
- encoder.encode_fill(conv_state, 0);
- }
- encoder.encode_fill(&mut layer.ssm_state, 0);
- },
- CacheLayer::ShortConv(layer) => {
- encoder.encode_fill(&mut layer.conv_state, 0);
- encoder.encode_fill(&mut layer.suffix_state, 0);
- },
- CacheLayer::DeltaNet(layer) => {
- encoder.encode_fill(&mut layer.conv_state, 0);
- encoder.encode_fill(&mut layer.ssm_state, 0);
- },
- }
- }
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to initialize cache allocations");
-
- Self {
- max_suffix_length,
- max_prefix_length,
- entries,
- bindings,
- }
- }
-
- pub fn cache_for_layer(
- &mut self,
- layer_index: usize,
- ) -> LayerCacheAccess<'_, B> {
- match self.bindings[layer_index] {
- LayerCacheBinding::Owned {
- entry,
- } => LayerCacheAccess::Owned {
- entry: &mut self.entries[entry.index],
- },
- LayerCacheBinding::Shared {
- source,
- } => LayerCacheAccess::Shared {
- source: &self.entries[source.index],
- },
- }
- }
-
- pub fn iter_layers(&self) -> impl Iterator<Item = (usize, &CacheLayer<B>)> {
- self.bindings.iter().enumerate().filter_map(|(index, binding)| match binding {
- LayerCacheBinding::Owned {
- entry,
- } => Some((index, &self.entries[entry.index])),
- LayerCacheBinding::Shared {
- ..
- } => None,
- })
- }
-
- pub fn clear(
- &mut self,
- context: &B::Context,
- ) {
- let mut encoder: Option<Encoder<B>> = None;
- for layer in self.entries.iter_mut() {
- match layer {
- CacheLayer::Transformer(layer) => layer.clear_state(),
- CacheLayer::StateSpace(layer) => {
- let encoder = encoder
- .get_or_insert_with(|| Encoder::new(context).expect("Failed to create cache clear encoder"));
- if let Some(conv_state) = layer.conv_state.as_mut() {
- encoder.encode_fill(conv_state, 0);
- }
- encoder.encode_fill(&mut layer.ssm_state, 0);
- },
- CacheLayer::ShortConv(layer) => {
- let encoder = encoder
- .get_or_insert_with(|| Encoder::new(context).expect("Failed to create cache clear encoder"));
- encoder.encode_fill(&mut layer.conv_state, 0);
- encoder.encode_fill(&mut layer.suffix_state, 0);
- layer.clear_suffix_state_valid_range();
- },
- CacheLayer::DeltaNet(layer) => {
- let encoder = encoder
- .get_or_insert_with(|| Encoder::new(context).expect("Failed to create cache clear encoder"));
- encoder.encode_fill(&mut layer.conv_state, 0);
- encoder.encode_fill(&mut layer.ssm_state, 0);
- },
- }
- }
- if let Some(encoder) = encoder {
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to clear cache layers");
- }
- }
-
- pub fn max_suffix_length(&self) -> usize {
- self.max_suffix_length
- }
-
- pub fn max_prefix_length(&self) -> usize {
- self.max_prefix_length
- }
-
- pub fn update_after_acceptance(
- &mut self,
- accepted_suffix_indices: &[usize],
- suffix_start: Option<usize>,
- context: &B::Context,
- encoder: &mut Encoder<B>,
- kv_cache_update: &KVCacheUpdate<B>,
- ) {
- let short_conv_commit_index = accepted_suffix_indices.last().copied().unwrap_or(0);
- for layer in self.entries.iter_mut() {
- if let Some(layer) = layer.as_transformer_mut() {
- layer.update_after_acceptance(accepted_suffix_indices, suffix_start, context, encoder, kv_cache_update);
- } else if let Some(layer) = layer.as_short_conv_mut() {
- layer.commit_from_suffix_state_if_valid(short_conv_commit_index, encoder);
- }
- }
- }
-
- pub fn prepare_for_forward_pass(
- &mut self,
- context: &B::Context,
- active_row_count: usize,
- ) {
- if active_row_count == 0 {
- return;
- }
-
- for layer in self.entries.iter_mut() {
- let Some(layer) = layer.as_transformer_mut() else {
- continue;
- };
- let row_range = match layer.state() {
- KVCacheLayerState::Full {
- prefix_len,
- } => prefix_len..prefix_len + active_row_count,
- KVCacheLayerState::Windowed {
- window_length,
- ..
- } => 0..window_length + active_row_count,
- };
- layer.map_row_range(context, row_range).expect("Failed to map KV cache rows for forward pass");
- }
- }
-
- pub fn register_accepted_tokens(
- &mut self,
- number_of_accepted_tokens: usize,
- ) {
- for layer in self.entries.iter_mut() {
- if let Some(layer) = layer.as_transformer_mut() {
- layer.register_accepted_tokens(number_of_accepted_tokens);
- }
- }
- }
-
- pub fn slice(
- &self,
- context: &B::Context,
- range: std::ops::Range<usize>,
- ) -> Option<CacheLayersSlice<B>> {
- let mut layers = Vec::with_capacity(self.entries.len());
- let mut encoder: Option<Encoder<B>> = None;
-
- for layer in self.entries.iter() {
- match layer {
- CacheLayer::Transformer(kv) => {
- let encoder =
- encoder.get_or_insert_with(|| Encoder::new(context).expect("Failed to create Encoder"));
- let slice = kv.slice(context, encoder, range.clone())?;
- layers.push(CacheLayerSlice::Transformer(slice));
- },
- CacheLayer::StateSpace(_) => layers.push(CacheLayerSlice::StateSpace),
- CacheLayer::ShortConv(_) => layers.push(CacheLayerSlice::ShortConv),
- CacheLayer::DeltaNet(_) => layers.push(CacheLayerSlice::DeltaNet),
- }
- }
-
- if let Some(encoder) = encoder {
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to end and wait encoder");
- }
-
- Some(CacheLayersSlice {
- layers,
- })
- }
-
- pub fn apply_slice(
- &mut self,
- context: &B::Context,
- slice: &CacheLayersSlice<B>,
- range: Option<std::ops::Range<usize>>,
- ) {
- let mut encoder: Option<Encoder<B>> = None;
- for (layer, snapshot) in self.entries.iter_mut().zip(slice.layers.iter()) {
- match (layer, snapshot) {
- (CacheLayer::Transformer(kv), CacheLayerSlice::Transformer(s)) => {
- let encoder =
- encoder.get_or_insert_with(|| Encoder::new(context).expect("Failed to create Encoder"));
- kv.apply_slice(context, encoder, s, range.clone());
- },
- (CacheLayer::StateSpace(_), CacheLayerSlice::StateSpace) => {},
- (CacheLayer::ShortConv(_), CacheLayerSlice::ShortConv) => {},
- _ => {},
- }
- }
-
- if let Some(encoder) = encoder {
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to end and wait encoder");
- }
- }
-
- pub fn copy_from(
- &mut self,
- source: &Self,
- context: &B::Context,
- ) {
- self.copy_metadata_and_windowed_data_from(source, context);
-
- let mut encoder = Encoder::new(context).expect("Failed to create cache layer copy encoder");
- self.encode_copy_data_from(source, context, &mut encoder);
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to copy cache layers");
- }
-
- fn copy_metadata_and_windowed_data_from(
- &mut self,
- source: &Self,
- context: &B::Context,
- ) {
- assert_eq!(source.entries.len(), self.entries.len(), "cache layer count mismatch");
-
- // Key/value arrays stay alive until after encoder.submit().wait_until_completed() returns, then explicitly drops them.
- // This prevents the slice buffers from being freed while the GPU is still reading from them during windowed cache cloning.
- let mut pending_slices: Vec<KVSlice<B>> = Vec::new();
- let mut encoder: Option<Encoder<B>> = None;
-
- for (source_layer, destination_layer) in source.entries.iter().zip(self.entries.iter_mut()) {
- match (source_layer, destination_layer) {
- (CacheLayer::Transformer(source), CacheLayer::Transformer(destination)) => {
- let copy_rows = source.prefix_segment_length();
- if copy_rows > 0 && matches!(source.state(), KVCacheLayerState::Windowed { .. }) {
- let encoder =
- encoder.get_or_insert_with(|| Encoder::new(context).expect("Failed to create Encoder"));
- let slice =
- source.slice(context, encoder, 0..copy_rows).expect("Failed to slice KV cache layer");
- destination.apply_slice(context, encoder, &slice, None);
- pending_slices.push(slice);
- }
- destination.set_state(&source.state());
- },
- (CacheLayer::StateSpace(_), CacheLayer::StateSpace(_)) => {},
- (CacheLayer::ShortConv(_), CacheLayer::ShortConv(destination)) => {
- destination.clear_suffix_state_valid_range();
- },
- (CacheLayer::DeltaNet(_), CacheLayer::DeltaNet(_)) => {},
- _ => panic!("cache layer type mismatch while copying cache layers"),
- }
- }
-
- if let Some(encoder) = encoder {
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to end and wait encoder");
- }
- drop(pending_slices);
- }
-
- fn encode_copy_data_from(
- &mut self,
- source: &Self,
- context: &B::Context,
- encoder: &mut Encoder<B>,
- ) {
- assert_eq!(source.entries.len(), self.entries.len(), "cache layer count mismatch");
-
- for (source_layer, destination_layer) in source.entries.iter().zip(self.entries.iter_mut()) {
- match (source_layer, destination_layer) {
- (CacheLayer::Transformer(source), CacheLayer::Transformer(destination)) => {
- if matches!(source.state(), KVCacheLayerState::Full { .. }) {
- source.encode_copy_prefix_rows_to(
- destination.as_mut(),
- source.prefix_segment_length(),
- context,
- encoder,
- );
- }
- },
- (CacheLayer::StateSpace(source), CacheLayer::StateSpace(destination)) => {
- match (source.conv_state.as_ref(), destination.conv_state.as_mut()) {
- (Some(source_conv_state), Some(destination_conv_state)) => {
- encoder.encode_copy(source_conv_state, .., destination_conv_state, ..);
- },
- (None, None) => {},
- _ => panic!("state-space conv_state presence mismatch while copying cache layers"),
- }
- encoder.encode_copy(&source.ssm_state, .., &mut destination.ssm_state, ..);
- },
- (CacheLayer::ShortConv(source), CacheLayer::ShortConv(destination)) => {
- encoder.encode_copy(&source.conv_state, .., &mut destination.conv_state, ..);
- },
- (CacheLayer::DeltaNet(source), CacheLayer::DeltaNet(destination)) => {
- encoder.encode_copy(&source.conv_state, .., &mut destination.conv_state, ..);
- encoder.encode_copy(&source.ssm_state, .., &mut destination.ssm_state, ..);
- },
- _ => panic!("cache layer type mismatch while copying cache layers"),
- }
- }
- }
-
- pub fn clone(
- &self,
- context: &B::Context,
- ) -> Self {
- let mut max_prefix_capacity_across_layers = 0usize;
- let mut entries: Box<[CacheLayer<B>]> = self
- .entries
- .iter()
- .map(|layer| match layer {
- CacheLayer::Transformer(layer) => {
- let shape = layer.shape();
- let [_, num_groups, head_dim] = shape;
- let dtype = layer.data_type();
- let copy_rows = layer.prefix_segment_length();
-
- let new_total_len = copy_rows + self.max_suffix_length;
- if copy_rows > max_prefix_capacity_across_layers {
- max_prefix_capacity_across_layers = copy_rows;
- }
-
- let new_shape = [new_total_len, num_groups, head_dim];
- let kv_layer = <dyn KVCacheLayerTrait<B>>::new(context, &layer.state(), new_shape, dtype)
- .expect("Failed to create KVCacheLayer");
- CacheLayer::Transformer(kv_layer)
- },
- CacheLayer::StateSpace(layer) => {
- let conv_bytes = size_for_shape(&layer.conv_shape, layer.data_type);
- let ssm_bytes = size_for_shape(&layer.ssm_shape, layer.data_type);
- let new_conv = (conv_bytes > 0).then(|| {
- context
- .create_allocation(conv_bytes, AllocationType::Global)
- .expect("Failed to create ssm conv clone allocation")
- });
- let new_ssm = context
- .create_allocation(ssm_bytes, AllocationType::Global)
- .expect("Failed to create ssm state clone allocation");
-
- CacheLayer::StateSpace(SSMLayer {
- conv_state: new_conv,
- conv_shape: layer.conv_shape,
- ssm_state: new_ssm,
- ssm_shape: layer.ssm_shape,
- data_type: layer.data_type,
- })
- },
- CacheLayer::ShortConv(layer) => {
- let conv_bytes = size_for_shape(&layer.conv_shape, layer.data_type);
- let suffix_bytes = size_for_shape(&layer.suffix_shape, layer.data_type);
- let new_conv = context
- .create_allocation(conv_bytes, AllocationType::Global)
- .expect("Failed to create short conv clone allocation");
- let new_suffix = context
- .create_allocation(suffix_bytes, AllocationType::Global)
- .expect("Failed to create short conv suffix clone allocation");
-
- CacheLayer::ShortConv(ShortConvLayer {
- conv_state: new_conv,
- conv_shape: layer.conv_shape,
- suffix_state: new_suffix,
- suffix_shape: layer.suffix_shape,
- data_type: layer.data_type,
- suffix_state_valid_start: Cell::new(0),
- suffix_state_valid_len: Cell::new(0),
- })
- },
- CacheLayer::DeltaNet(layer) => {
- let conv_bytes = size_for_shape(&layer.conv_shape, layer.data_type);
- let ssm_bytes = size_for_shape(&layer.ssm_shape, layer.data_type);
- let new_conv = context
- .create_allocation(conv_bytes, AllocationType::Global)
- .expect("Failed to create delta net conv clone allocation");
- let new_ssm = context
- .create_allocation(ssm_bytes, AllocationType::Global)
- .expect("Failed to create delta net ssm clone allocation");
-
- CacheLayer::DeltaNet(DeltaNetLayer {
- conv_state: new_conv,
- conv_shape: layer.conv_shape,
- ssm_state: new_ssm,
- ssm_shape: layer.ssm_shape,
- data_type: layer.data_type,
- })
- },
- })
- .collect();
-
- let mut zero_encoder: Encoder<B> = Encoder::new(context).expect("Failed to create cache clone zero encoder");
- for layer in entries.iter_mut() {
- match layer {
- CacheLayer::Transformer(layer) => {
- layer.encode_zero(&mut zero_encoder);
- },
- CacheLayer::ShortConv(layer) => {
- zero_encoder.encode_fill(&mut layer.suffix_state, 0);
- },
- _ => {},
- }
- }
- zero_encoder.end_encoding().submit().wait_until_completed().expect("Failed to zero cloned cache layers");
-
- let mut cloned = Self {
- max_suffix_length: self.max_suffix_length,
- max_prefix_length: max_prefix_capacity_across_layers,
- entries,
- bindings: self.bindings.clone(),
- };
- cloned.copy_from(self, context);
- cloned
- }
-}
-
-#[cfg(test)]
-#[path = "../../unit/forward_pass/cache_layers_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/forward_pass/delta_net_layer.rs b/crates/backend-uzu/src/forward_pass/delta_net_layer.rs
deleted file mode 100644
index 818fec419..000000000
--- a/crates/backend-uzu/src/forward_pass/delta_net_layer.rs
+++ /dev/null
@@ -1,12 +0,0 @@
-use crate::{
- backends::common::{Allocation, Backend},
- data_type::DataType,
-};
-
-pub struct DeltaNetLayer<B: Backend> {
- pub conv_state: Allocation<B>,
- pub conv_shape: [usize; 2],
- pub ssm_state: Allocation<B>,
- pub ssm_shape: [usize; 3],
- pub data_type: DataType,
-}
diff --git a/crates/backend-uzu/src/forward_pass/kv_cache_layer.rs b/crates/backend-uzu/src/forward_pass/kv_cache_layer.rs
deleted file mode 100644
index 489ebe7bc..000000000
--- a/crates/backend-uzu/src/forward_pass/kv_cache_layer.rs
+++ /dev/null
@@ -1,607 +0,0 @@
-use std::{any::Any, ops::Range};
-
-use crate::{
- array::{Array, ArrayContextExt, size_for_shape},
- backends::common::{AsBufferRangeMut, AsBufferRangeRef, Backend, Buffer, Context, Encoder, SparseBuffer},
- data_type::DataType,
- encodable_block::{KVCacheUpdate, KVLayerData},
-};
-
-pub enum KVSlice<B: Backend> {
- Full {
- base_prefix_len: usize,
- },
- Window {
- window_length: usize,
- base_ring_offset: usize,
- base_ring_length: usize,
- slots: Vec<usize>,
- keys: Array<B>, // [slots.len(), num_groups, head_dim]
- values: Array<B>, // [slots.len(), num_groups, head_dim]
- },
-}
-
-#[derive(Clone, Debug)]
-pub enum KVCacheLayerState {
- Full {
- /// Prefix length so far (number of tokens in the prefix)
- prefix_len: usize,
- },
- Windowed {
- /// Start of the ring buffer (oldest element index)
- ring_offset: usize,
- /// Current logical length of the window (<= window_length)
- ring_length: usize,
- /// Maximum length of the window
- window_length: usize,
- },
-}
-
-pub const INVALID_POSITION: usize = i32::MAX as usize;
-
-pub trait KVCacheLayerTrait<B: Backend> {
- fn as_any(&self) -> &dyn Any;
-
- fn as_any_mut(&mut self) -> &mut dyn Any;
-
- fn shape(&self) -> [usize; 3];
-
- fn data_type(&self) -> DataType;
-
- fn encode_zero(
- &mut self,
- encoder: &mut Encoder<B>,
- );
-
- fn state(&self) -> KVCacheLayerState;
-
- fn set_state(
- &mut self,
- state: &KVCacheLayerState,
- );
-
- fn clear_state(&mut self);
-
- fn encode_copy_prefix_rows_to(
- &self,
- destination: &mut dyn KVCacheLayerTrait<B>,
- row_count: usize,
- context: &B::Context,
- encoder: &mut Encoder<B>,
- );
-
- fn prefix_segment_length(&self) -> usize;
-
- fn update_after_acceptance(
- &mut self,
- accepted_suffix_indices: &[usize],
- suffix_start: Option<usize>,
- context: &B::Context,
- encoder: &mut Encoder<B>,
- kv_cache_update: &KVCacheUpdate<B>,
- );
-
- fn register_accepted_tokens(
- &mut self,
- number_of_accepted_tokens: usize,
- );
-
- fn slice(
- &self,
- context: &B::Context,
- encoder: &mut Encoder<B>,
- range: Range<usize>,
- ) -> Option<KVSlice<B>>;
-
- fn apply_slice(
- &mut self,
- context: &B::Context,
- encoder: &mut Encoder<B>,
- slice: &KVSlice<B>,
- range: Option<Range<usize>>,
- );
-
- fn map_row_range(
- &mut self,
- context: &B::Context,
- range: Range<usize>,
- ) -> Result<(), B::Error>;
-}
-
-impl<B: Backend> dyn KVCacheLayerTrait<B> {
- pub fn new(
- context: &B::Context,
- state: &KVCacheLayerState,
- shape: [usize; 3],
- data_type: DataType,
- ) -> Result<Box<dyn KVCacheLayerTrait<B>>, B::Error> {
- let buffer_size = size_for_shape(&shape, data_type);
- if context.sparse_buffers_supported() {
- let layer = KVCacheLayer {
- state: state.clone(),
- keys: context.create_sparse_buffer(buffer_size)?,
- values: context.create_sparse_buffer(buffer_size)?,
- shape,
- data_type,
- };
- Ok(Box::new(layer))
- } else {
- let layer = KVCacheLayer {
- state: state.clone(),
- keys: context.create_buffer(buffer_size)?,
- values: context.create_buffer(buffer_size)?,
- shape,
- data_type,
- };
- Ok(Box::new(layer))
- }
- }
-}
-
-pub struct KVCacheLayer<B: Backend, Buf: Buffer<Backend = B>> {
- pub state: KVCacheLayerState,
- /// [max_prefix_length + max_suffix_length, num_groups, head_dim]
- pub keys: Buf,
- /// [max_prefix_length + max_suffix_length, num_groups, head_dim]
- pub values: Buf,
- pub shape: [usize; 3],
- pub data_type: DataType,
-}
-
-impl<B: Backend, Buf: Buffer<Backend = B>> KVCacheLayer<B, Buf> {
- fn scatter_if_required(
- &mut self,
- source_indices: &[usize],
- destination_indices: &[usize],
- encoder: &mut Encoder<B>,
- kv_cache_update: &KVCacheUpdate<B>,
- ) {
- if source_indices == destination_indices {
- return;
- }
-
- let mut layer_data = KVLayerData {
- key_buffer: &mut self.keys,
- key_shape: self.shape,
- value_buffer: &mut self.values,
- value_shape: self.shape,
- };
-
- let data = std::slice::from_mut(&mut layer_data);
- let _ = kv_cache_update.encode(data, source_indices, destination_indices, encoder);
- }
-
- fn copy_rows<
- SrcKeys: AsBufferRangeRef<Buffer: Buffer<Backend = B>>,
- DstKeys: AsBufferRangeMut<Buffer: Buffer<Backend = B>>,
- SrcValues: AsBufferRangeRef<Buffer: Buffer<Backend = B>>,
- DstValues: AsBufferRangeMut<Buffer: Buffer<Backend = B>>,
- >(
- encoder: &mut Encoder<B>,
- src_keys: &SrcKeys,
- dst_keys: &mut DstKeys,
- src_values: &SrcValues,
- dst_values: &mut DstValues,
- row_size: usize,
- row_pairs: impl IntoIterator<Item = (usize, usize)>,
- ) {
- for (src_row, dst_row) in row_pairs {
- let src_offset = src_row * row_size;
- let dst_offset = dst_row * row_size;
- encoder.encode_copy(
- src_keys,
- src_offset..src_offset + row_size,
- dst_keys,
- dst_offset..dst_offset + row_size,
- );
- encoder.encode_copy(
- src_values,
- src_offset..src_offset + row_size,
- dst_values,
- dst_offset..dst_offset + row_size,
- );
- }
- }
-
- fn page_range_for_row_range(
- shape: [usize; 3],
- data_type: DataType,
- page_size_bytes: usize,
- row_range: Range<usize>,
- ) -> Range<usize> {
- if row_range.is_empty() {
- return 0..0;
- }
-
- let [_, num_groups, head_dim] = shape;
- let row_size = size_for_shape(&[1, num_groups, head_dim], data_type);
- let byte_start = row_range.start * row_size;
- let byte_end = row_range.end * row_size;
- byte_start / page_size_bytes..byte_end.div_ceil(page_size_bytes)
- }
-
- fn map_sparse_row_range(
- &mut self,
- context: &B::Context,
- row_range: Range<usize>,
- ) -> Result<(), B::Error> {
- if row_range.is_empty() {
- return Ok(());
- }
-
- if let Some(layer) = self.as_any_mut().downcast_mut::<KVCacheLayer<B, B::SparseBuffer>>() {
- let key_pages = Self::page_range_for_row_range(
- layer.shape,
- layer.data_type,
- layer.keys.page_size_bytes(),
- row_range.clone(),
- );
- layer.keys.map(context, &key_pages)?;
-
- let value_pages =
- Self::page_range_for_row_range(layer.shape, layer.data_type, layer.values.page_size_bytes(), row_range);
- layer.values.map(context, &value_pages)?;
- }
- Ok(())
- }
-}
-
-impl<B: Backend, Buf: Buffer<Backend = B>> KVCacheLayerTrait<B> for KVCacheLayer<B, Buf> {
- fn as_any(&self) -> &dyn Any {
- self
- }
-
- fn as_any_mut(&mut self) -> &mut dyn Any {
- self
- }
-
- fn shape(&self) -> [usize; 3] {
- self.shape
- }
-
- fn data_type(&self) -> DataType {
- self.data_type
- }
-
- fn encode_zero(
- &mut self,
- encoder: &mut Encoder<B>,
- ) {
- if self.as_any().is::<KVCacheLayer<B, B::SparseBuffer>>() {
- return;
- }
- encoder.encode_fill(&mut self.keys, 0);
- encoder.encode_fill(&mut self.values, 0);
- }
-
- fn state(&self) -> KVCacheLayerState {
- self.state.clone()
- }
-
- fn set_state(
- &mut self,
- state: &KVCacheLayerState,
- ) {
- self.state = state.clone();
- }
-
- fn clear_state(&mut self) {
- match &mut self.state {
- KVCacheLayerState::Full {
- prefix_len,
- } => {
- *prefix_len = 0;
- },
- KVCacheLayerState::Windowed {
- ring_offset,
- ring_length,
- ..
- } => {
- *ring_offset = 0;
- *ring_length = 0;
- },
- }
- }
-
- fn encode_copy_prefix_rows_to(
- &self,
- destination: &mut dyn KVCacheLayerTrait<B>,
- row_count: usize,
- context: &B::Context,
- encoder: &mut Encoder<B>,
- ) {
- if row_count == 0 {
- return;
- }
-
- let [source_seq, num_groups, head_dim] = self.shape;
- let [destination_seq, destination_groups, destination_head_dim] = destination.shape();
- assert_eq!(num_groups, destination_groups, "KV cache group count mismatch");
- assert_eq!(head_dim, destination_head_dim, "KV cache head dim mismatch");
- assert_eq!(self.data_type, destination.data_type(), "KV cache dtype mismatch");
- assert!(row_count <= source_seq, "source KV cache copy exceeds source sequence");
- assert!(row_count <= destination_seq, "source KV cache copy exceeds destination sequence");
- destination.map_row_range(context, 0..row_count).expect("Failed to map destination KV cache rows");
-
- let row_size = size_for_shape(&[1, num_groups, head_dim], self.data_type);
- let copy_size = row_count * row_size;
- if let Some(dest) = destination.as_any_mut().downcast_mut::<KVCacheLayer<B, B::SparseBuffer>>() {
- encoder.encode_copy(&self.keys, 0..copy_size, &mut dest.keys, 0..copy_size);
- encoder.encode_copy(&self.values, 0..copy_size, &mut dest.values, 0..copy_size);
- } else if let Some(dest) = destination.as_any_mut().downcast_mut::<KVCacheLayer<B, B::DenseBuffer>>() {
- encoder.encode_copy(&self.keys, 0..copy_size, &mut dest.keys, 0..copy_size);
- encoder.encode_copy(&self.values, 0..copy_size, &mut dest.values, 0..copy_size);
- } else {
- panic!("Wrong destination type!")
- }
- }
-
- fn prefix_segment_length(&self) -> usize {
- match &self.state {
- KVCacheLayerState::Full {
- prefix_len,
- } => *prefix_len,
- KVCacheLayerState::Windowed {
- window_length,
- ..
- } => *window_length,
- }
- }
-
- fn update_after_acceptance(
- &mut self,
- accepted_suffix_indices: &[usize],
- suffix_start: Option<usize>,
- context: &B::Context,
- encoder: &mut Encoder<B>,
- kv_cache_update: &KVCacheUpdate<B>,
- ) {
- match &mut self.state {
- KVCacheLayerState::Full {
- prefix_len,
- } => {
- if accepted_suffix_indices.is_empty() {
- return;
- }
-
- let prefix_len_value = *prefix_len;
-
- // Absolute positions of the *source* rows.
- let source_indices: Vec<usize> =
- accepted_suffix_indices.iter().map(|i| i + suffix_start.unwrap_or(prefix_len_value)).collect();
-
- // Absolute positions of the *destination* rows.
- let destination_indices: Vec<usize> =
- (prefix_len_value..prefix_len_value + accepted_suffix_indices.len()).collect();
-
- self.map_sparse_row_range(context, prefix_len_value..prefix_len_value + accepted_suffix_indices.len())
- .expect("Failed to map accepted KV cache rows");
- self.scatter_if_required(&source_indices, &destination_indices, encoder, kv_cache_update);
- },
-
- KVCacheLayerState::Windowed {
- ring_offset,
- ring_length,
- window_length,
- } => {
- let suffix_indices: Vec<usize> = if accepted_suffix_indices.is_empty() {
- vec![0]
- } else {
- accepted_suffix_indices.to_vec()
- };
-
- let source_indices: Vec<usize> = suffix_indices.iter().map(|i| i + *window_length).collect();
-
- let mut destination_indices = Vec::with_capacity(suffix_indices.len());
-
- for i in 0..suffix_indices.len() {
- destination_indices.push((*ring_length + *ring_offset + i) % *window_length);
- }
-
- for destination_index in destination_indices.iter().copied() {
- self.map_sparse_row_range(context, destination_index..destination_index + 1)
- .expect("Failed to map accepted KV cache row");
- }
- self.scatter_if_required(&source_indices, &destination_indices, encoder, kv_cache_update);
- },
- }
- }
-
- fn register_accepted_tokens(
- &mut self,
- number_of_accepted_tokens: usize,
- ) {
- match &mut self.state {
- KVCacheLayerState::Full {
- prefix_len,
- } => {
- *prefix_len += number_of_accepted_tokens;
- },
- KVCacheLayerState::Windowed {
- ring_offset,
- ring_length,
- window_length,
- } => {
- let ring_advance = number_of_accepted_tokens.saturating_sub(*window_length - *ring_length);
- *ring_offset = (*ring_offset + ring_advance) % *window_length;
- *ring_length = (*ring_length + number_of_accepted_tokens).min(*window_length);
- },
- }
- }
-
- fn slice(
- &self,
- context: &B::Context,
- encoder: &mut Encoder<B>,
- range: Range<usize>,
- ) -> Option<KVSlice<B>> {
- match self.state {
- KVCacheLayerState::Full {
- prefix_len,
- } => Some(KVSlice::Full {
- base_prefix_len: prefix_len,
- }),
- KVCacheLayerState::Windowed {
- ring_offset,
- ring_length,
- window_length,
- } => {
- let len = range.end.saturating_sub(range.start);
- if len == 0 || len > window_length {
- return None;
- }
- let [_, num_groups, head_dim] = self.shape;
- let dtype = self.data_type;
- let row_size = size_for_shape(&[1, num_groups, head_dim], dtype);
-
- let slots: Vec<usize> = (range.start..range.end)
- .enumerate()
- .map(|(offset, _)| {
- let x = ring_length + offset;
- if x < window_length {
- (ring_offset + x) % window_length
- } else {
- (ring_offset + (x - window_length)) % window_length
- }
- })
- .collect();
- let row_pairs = slots.iter().enumerate().map(|(dst_row, &src_row)| (src_row, dst_row));
-
- let slice_shape = [len, num_groups, head_dim];
- let mut dst_keys = context.create_array_uninitialized(&slice_shape, dtype);
- let mut dst_values = context.create_array_uninitialized(&slice_shape, dtype);
- Self::copy_rows(
- encoder,
- &self.keys,
- dst_keys.allocation_mut(),
- &self.values,
- dst_values.allocation_mut(),
- row_size,
- row_pairs,
- );
-
- Some(KVSlice::Window {
- window_length,
- base_ring_offset: ring_offset,
- base_ring_length: ring_length,
- slots,
- keys: dst_keys,
- values: dst_values,
- })
- },
- }
- }
-
- fn apply_slice(
- &mut self,
- context: &B::Context,
- encoder: &mut Encoder<B>,
- slice: &KVSlice<B>,
- range: Option<Range<usize>>,
- ) {
- match (slice, &mut self.state) {
- (
- KVSlice::Full {
- base_prefix_len,
- },
- KVCacheLayerState::Full {
- prefix_len,
- },
- ) => match range {
- None => {
- *prefix_len = *base_prefix_len;
- },
- Some(r) => {
- *prefix_len = base_prefix_len.saturating_add(r.start);
- },
- },
- (
- KVSlice::Window {
- window_length,
- base_ring_offset,
- base_ring_length,
- slots,
- keys,
- values,
- },
- KVCacheLayerState::Windowed {
- ring_offset,
- ring_length,
- window_length: w_len,
- },
- ) => {
- *w_len = *window_length;
- let [_, num_groups, head_dim] = self.shape;
- let row_size = size_for_shape(&[1, num_groups, head_dim], self.data_type);
-
- let row_pairs: Option<Vec<(usize, usize)>> = match &range {
- None => {
- *ring_offset = *base_ring_offset;
- *ring_length = *base_ring_length;
- let pairs = slots.iter().enumerate().map(|(src_row, &dst_row)| (src_row, dst_row)).collect();
- Some(pairs)
- },
- Some(r) => {
- let len = r.end.saturating_sub(r.start);
- if len == 0 {
- None
- } else {
- let accepted = r.start;
- let base_len = *base_ring_length;
- let w = *window_length;
-
- let (new_offset, new_len) = if base_len < w {
- let after = base_len.saturating_add(accepted);
- if after <= w {
- (*base_ring_offset, after)
- } else {
- let overflow = after - w;
- ((base_ring_offset + overflow) % w, w)
- }
- } else {
- ((base_ring_offset + accepted) % w, w)
- };
-
- *ring_offset = new_offset;
- *ring_length = new_len;
-
- let pairs =
- slots[r.clone()].iter().enumerate().map(move |(i, &dst_row)| (r.start + i, dst_row));
- Some(pairs.collect())
- }
- },
- };
- let Some(row_pairs) = row_pairs else {
- return;
- };
- for (_, destination_row) in row_pairs.iter().copied() {
- self.map_sparse_row_range(context, destination_row..destination_row + 1)
- .expect("Failed to map sliced KV cache row");
- }
-
- Self::copy_rows(
- encoder,
- keys.allocation(),
- &mut self.keys,
- values.allocation(),
- &mut self.values,
- row_size,
- row_pairs,
- );
- },
- _ => {},
- }
- }
-
- fn map_row_range(
- &mut self,
- context: &B::Context,
- range: Range<usize>,
- ) -> Result<(), B::Error> {
- self.map_sparse_row_range(context, range)
- }
-}
-
-#[cfg(test)]
-#[path = "../../unit/forward_pass/kv_cache_state_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/forward_pass/mod.rs b/crates/backend-uzu/src/forward_pass/mod.rs
deleted file mode 100644
index 2bbab2cbb..000000000
--- a/crates/backend-uzu/src/forward_pass/mod.rs
+++ /dev/null
@@ -1,12 +0,0 @@
-pub mod model_shape;
-pub mod rope;
-
-pub mod cache_layers;
-pub mod delta_net_layer;
-pub mod kv_cache_layer;
-pub mod short_conv_layer;
-pub mod ssm_layer;
-pub mod token_inputs;
-
-#[cfg(feature = "tracing")]
-pub mod traces;
diff --git a/crates/backend-uzu/src/forward_pass/model_shape.rs b/crates/backend-uzu/src/forward_pass/model_shape.rs
deleted file mode 100644
index 0f2d70308..000000000
--- a/crates/backend-uzu/src/forward_pass/model_shape.rs
+++ /dev/null
@@ -1,95 +0,0 @@
-use crate::{
- config::{decoder::DecoderConfig, token_mixer::AnyTokenMixerConfig},
- data_type::DataType,
-};
-
-#[derive(Debug, Clone)]
-pub struct ModelShape {
- pub data_type: DataType,
- pub rope_data_type: DataType,
-
- pub vocabulary_size: usize,
- model_dim: usize,
-
- num_groups: usize,
- pub num_layers: usize,
- layer_mixers: Box<[AnyTokenMixerConfig]>,
- kv_source_layers: Box<[Option<usize>]>,
-}
-
-impl ModelShape {
- pub fn from_decoder_config(
- decoder_config: &DecoderConfig,
- data_type: DataType,
- ) -> Self {
- let tf = &decoder_config.transformer_config;
- let layer_configs = &tf.layer_configs;
- let num_layers = layer_configs.len();
-
- let (num_heads, num_groups) =
- decoder_config.first_attention().map(|a| (a.num_heads, a.num_groups)).unwrap_or_default();
- for attn in layer_configs.iter().filter_map(|l| l.mixer_config.as_attention()) {
- assert_eq!(attn.num_heads, num_heads, "attention layers must share num_heads");
- assert_eq!(attn.num_groups, num_groups, "attention layers must share num_groups");
- }
-
- let layer_mixers: Box<[AnyTokenMixerConfig]> = layer_configs.iter().map(|l| l.mixer_config.clone()).collect();
- let kv_source_layers: Box<[Option<usize>]> = layer_configs.iter().map(|l| l.kv_source_layer_index).collect();
-
- Self {
- data_type,
- rope_data_type: DataType::F32,
- vocabulary_size: decoder_config.vocab_size,
- model_dim: tf.model_dim,
- num_groups,
- num_layers,
- layer_mixers,
- kv_source_layers,
- }
- }
-
- pub fn num_groups(&self) -> usize {
- self.num_groups
- }
-
- pub fn model_dim(&self) -> usize {
- self.model_dim
- }
-
- pub fn kv_source_layers(&self) -> &[Option<usize>] {
- &self.kv_source_layers
- }
-
- pub fn layer_mixers(&self) -> &[AnyTokenMixerConfig] {
- &self.layer_mixers
- }
-
- pub fn main_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 2] {
- [suffix_length, self.model_dim]
- }
-
- pub fn subtrie_ranges_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 2] {
- [suffix_length, 3]
- }
-
- pub fn bitmask_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 2] {
- let bitmask_size = self.vocabulary_size.div_ceil(32);
- [suffix_length, bitmask_size]
- }
-
- pub fn logits_shape(
- &self,
- suffix_length: usize,
- ) -> [usize; 2] {
- [suffix_length, self.vocabulary_size]
- }
-}
diff --git a/crates/backend-uzu/src/forward_pass/rope.rs b/crates/backend-uzu/src/forward_pass/rope.rs
deleted file mode 100644
index af21e1b24..000000000
--- a/crates/backend-uzu/src/forward_pass/rope.rs
+++ /dev/null
@@ -1,81 +0,0 @@
-use crate::config::rope::AnyRoPEConfig;
-
-pub fn precalculate_rope(
- rope_config: &AnyRoPEConfig,
- token_positions: &[usize],
-) -> (Box<[f32]>, Box<[f32]>) {
- let head_dim = *rope_config.head_dim();
- assert!(head_dim > 0 && head_dim.is_multiple_of(2), "RoPE head_dim must be positive and even");
- let half_dim = head_dim / 2;
- let attention_scaling_factor = match rope_config {
- AnyRoPEConfig::YARNRoPEConfig(config) => 0.1 * config.scaling_factor.ln() + 1.0,
- _ => 1.0,
- };
-
- let element_count = token_positions.len() * head_dim;
- let mut sines = vec![0.0; element_count];
- let mut cosines = vec![0.0; element_count];
- for pair_index in 0..half_dim {
- let channel_index = pair_index * 2;
- let inverse_frequency = 1.0 / rope_config.base().powf(channel_index as f32 / head_dim as f32);
- let inverse_frequency = match rope_config {
- AnyRoPEConfig::UnscaledRoPEConfig(_) => inverse_frequency,
- AnyRoPEConfig::LinearScalingRoPEConfig(config) => inverse_frequency / config.scaling_factor,
- AnyRoPEConfig::LlamaRoPEConfig(config) => {
- let low_frequency_wavelength = config.original_context_length as f32 / config.low_frequency_factor;
- let high_frequency_wavelength = config.original_context_length as f32 / config.high_frequency_factor;
- let wavelength = 2.0 * std::f32::consts::PI / inverse_frequency;
- let scaled_frequency = inverse_frequency / config.scaling_factor;
-
- if wavelength < high_frequency_wavelength {
- inverse_frequency
- } else if wavelength > low_frequency_wavelength {
- scaled_frequency
- } else {
- let smoothing_factor =
- config.original_context_length as f32 / wavelength - config.low_frequency_factor;
- let smoothing_factor =
- smoothing_factor / (config.high_frequency_factor - config.low_frequency_factor);
- smoothing_factor * inverse_frequency + (1.0 - smoothing_factor) * scaled_frequency
- }
- },
- AnyRoPEConfig::YARNRoPEConfig(config) => {
- let dim = config.head_dim as f64;
- let base = config.base as f64;
- let original_context_length = config.original_context_length as f64;
- let beta_fast = config.beta_fast as f64;
- let beta_slow = config.beta_slow as f64;
- let mut low =
- dim * (original_context_length / (beta_fast * 2.0 * std::f64::consts::PI)).ln() / (2.0 * base.ln());
- let mut high =
- dim * (original_context_length / (beta_slow * 2.0 * std::f64::consts::PI)).ln() / (2.0 * base.ln());
- if config.truncate {
- low = low.floor();
- high = high.ceil();
- }
- let low = low.max(0.0) as f32;
- let mut high = high.min((config.head_dim - 1) as f64) as f32;
- if low == high {
- high += 0.001;
- }
- let ramp = ((pair_index as f32 - low) / (high - low)).clamp(0.0, 1.0);
- let smoothing_factor = 1.0 - ramp;
- let scaled_frequency = inverse_frequency / config.scaling_factor;
- scaled_frequency * (1.0 - smoothing_factor) + inverse_frequency * smoothing_factor
- },
- };
-
- for (token_index, token_position) in token_positions.iter().enumerate() {
- let embedding = *token_position as f32 * inverse_frequency;
- let sine = embedding.sin() * attention_scaling_factor;
- let cosine = embedding.cos() * attention_scaling_factor;
- let row_offset = token_index * head_dim;
- sines[row_offset + pair_index] = sine;
- sines[row_offset + half_dim + pair_index] = sine;
- cosines[row_offset + pair_index] = cosine;
- cosines[row_offset + half_dim + pair_index] = cosine;
- }
- }
-
- (sines.into_boxed_slice(), cosines.into_boxed_slice())
-}
diff --git a/crates/backend-uzu/src/forward_pass/short_conv_layer.rs b/crates/backend-uzu/src/forward_pass/short_conv_layer.rs
deleted file mode 100644
index 4ac78db8b..000000000
--- a/crates/backend-uzu/src/forward_pass/short_conv_layer.rs
+++ /dev/null
@@ -1,70 +0,0 @@
-use std::cell::Cell;
-
-use crate::{
- array::size_for_shape,
- backends::common::{Allocation, Backend, Encoder},
- data_type::DataType,
-};
-
-pub struct ShortConvLayer<B: Backend> {
- pub conv_state: Allocation<B>,
- pub conv_shape: [usize; 2],
- /// Per-token post-state written during speculative runs.
- ///
- /// Shape: [max_suffix_length, model_dim, state_stride]
- pub suffix_state: Allocation<B>,
- pub suffix_shape: [usize; 3],
- pub data_type: DataType,
- /// Start index (in the suffix batch) for which `suffix_state` contains
- /// valid post-states for this layer.
- pub suffix_state_valid_start: Cell<usize>,
- /// Number of consecutive tokens (from `suffix_state_valid_start`) for which
- /// `suffix_state` contains valid post-states for this layer.
- pub suffix_state_valid_len: Cell<usize>,
-}
-
-impl<B: Backend> ShortConvLayer<B> {
- pub fn clear_suffix_state_valid_range(&self) {
- self.suffix_state_valid_start.set(0);
- self.suffix_state_valid_len.set(0);
- }
-
- pub fn set_suffix_state_valid_range(
- &self,
- start: usize,
- len: usize,
- ) {
- self.suffix_state_valid_start.set(start);
- self.suffix_state_valid_len.set(len);
- }
-
- pub fn commit_from_suffix_state_if_valid(
- &mut self,
- commit_index: usize,
- encoder: &mut Encoder<B>,
- ) {
- let start = self.suffix_state_valid_start.get();
- let len = self.suffix_state_valid_len.get();
- if len == 0 {
- return;
- }
- if commit_index < start || commit_index >= start + len {
- return;
- }
-
- let [model_dim, state_stride] = self.conv_shape;
- let [suffix_length, suffix_model_dim, suffix_stride] = self.suffix_shape;
- assert_eq!(suffix_model_dim, model_dim, "ShortConv suffix_state model_dim mismatch");
- assert_eq!(suffix_stride, state_stride, "ShortConv suffix_state stride mismatch");
- assert!(commit_index < suffix_length, "ShortConv commit_index {} out of range {}", commit_index, suffix_length);
-
- let bytes_per_token = size_for_shape(&[model_dim, state_stride], self.data_type);
- let src_start = commit_index * bytes_per_token;
- encoder.encode_copy(
- &self.suffix_state,
- src_start..src_start + bytes_per_token,
- &mut self.conv_state,
- 0..bytes_per_token,
- );
- }
-}
diff --git a/crates/backend-uzu/src/forward_pass/ssm_layer.rs b/crates/backend-uzu/src/forward_pass/ssm_layer.rs
deleted file mode 100644
index 75da3c7f5..000000000
--- a/crates/backend-uzu/src/forward_pass/ssm_layer.rs
+++ /dev/null
@@ -1,12 +0,0 @@
-use crate::{
- backends::common::{Allocation, Backend},
- data_type::DataType,
-};
-
-pub struct SSMLayer<B: Backend> {
- pub conv_state: Option<Allocation<B>>,
- pub conv_shape: [usize; 2],
- pub ssm_state: Allocation<B>,
- pub ssm_shape: [usize; 3],
- pub data_type: DataType,
-}
diff --git a/crates/backend-uzu/src/forward_pass/token_inputs.rs b/crates/backend-uzu/src/forward_pass/token_inputs.rs
deleted file mode 100644
index 091f20ec0..000000000
--- a/crates/backend-uzu/src/forward_pass/token_inputs.rs
+++ /dev/null
@@ -1,159 +0,0 @@
-use ndarray::ArrayView2;
-
-#[cfg(feature = "tracing")]
-use crate::forward_pass::traces::ActivationTrace;
-use crate::{
- array::{Array, ArrayContextExt},
- backends::common::{Allocation, Backend},
- data_type::DataType,
- encodable_block::DecoderArguments,
- forward_pass::{cache_layers::CacheLayers, model_shape::ModelShape},
-};
-
-pub struct TokenInputs<B: Backend> {
- token_ids: Array<B>,
- token_subtrie_ranges: Option<Array<B>>,
- token_positions: Box<[usize]>,
- token_parents: Array<B>,
-}
-
-impl<B: Backend> TokenInputs<B> {
- pub fn new_llm(
- context: &B::Context,
- model_shape: &ModelShape,
- token_ids: &[u64],
- token_subtrie_ranges: Option<&[[u32; 3]]>,
- token_positions: &[usize],
- token_ids_array: Option<Array<B>>,
- sampling_start: usize,
- sampling_length: usize,
- ) -> Self {
- let suffix_length = token_ids.len();
- assert_eq!(suffix_length, token_positions.len(), "Tokens and positions must have same length");
-
- Self {
- token_ids: token_ids_array.unwrap_or_else(|| Self::init_token_ids(context, token_ids)),
- token_subtrie_ranges: token_subtrie_ranges
- .map(|ranges| Self::init_token_subtrie_ranges(context, model_shape, suffix_length, ranges)),
- token_positions: token_positions.to_vec().into_boxed_slice(),
- token_parents: Self::init_token_parents(context, token_positions, sampling_start, sampling_length),
- }
- }
-
- pub fn new_classifier(
- context: &B::Context,
- token_ids: &[u64],
- token_positions: &[usize],
- ) -> Self {
- let suffix_length = token_ids.len();
- assert_eq!(suffix_length, token_positions.len(), "Tokens and positions must have same length");
-
- Self {
- token_ids: Self::init_token_ids(context, token_ids),
- token_subtrie_ranges: None,
- token_positions: token_positions.to_vec().into_boxed_slice(),
- token_parents: Self::init_token_parents(context, token_positions, 0, 0),
- }
- }
-
- pub fn token_ids(&self) -> &Allocation<B> {
- self.token_ids.allocation()
- }
-
- pub fn token_positions(&self) -> &[usize] {
- &self.token_positions
- }
-
- pub fn token_parents(&self) -> &Allocation<B> {
- self.token_parents.allocation()
- }
-
- pub fn token_subtrie_ranges(&self) -> Option<&Allocation<B>> {
- self.token_subtrie_ranges.as_ref().map(Array::allocation)
- }
-
- pub fn decoder_arguments<'a>(
- &'a self,
- cache_layers: Option<&'a mut CacheLayers<B>>,
- batch_dim: usize,
- sampling_start: usize,
- sampling_length: usize,
- #[cfg(feature = "tracing")] trace: Option<&'a mut ActivationTrace<B>>,
- ) -> DecoderArguments<'a, B> {
- DecoderArguments {
- token_positions: self.token_positions(),
- token_parents: self.token_parents(),
- token_subtrie_ranges: self.token_subtrie_ranges(),
- cache_layers,
- batch_dim,
- sampling_start,
- sampling_length,
- #[cfg(feature = "tracing")]
- trace,
- }
- }
-
- fn init_token_ids(
- context: &B::Context,
- token_ids: &[u64],
- ) -> Array<B> {
- context.create_array_from(&[token_ids.len()], token_ids)
- }
-
- fn init_token_parents(
- context: &B::Context,
- token_positions: &[usize],
- sampling_start: usize,
- sampling_length: usize,
- ) -> Array<B> {
- let suffix_length = token_positions.len();
- let mut parents = vec![-1i32; suffix_length];
-
- if sampling_length > 0 {
- let root_pos = token_positions.get(sampling_start).copied().unwrap_or(0);
- let mut stack: Vec<usize> = Vec::new();
-
- for local_idx in 0..sampling_length {
- let abs_idx = sampling_start + local_idx;
- let Some(&pos) = token_positions.get(abs_idx) else {
- break;
- };
- let depth = pos.saturating_sub(root_pos);
- let parent_local = if depth == 0 {
- -1
- } else if let Some(&parent) = stack.get(depth - 1) {
- parent as i32
- } else {
- debug_assert!(false, "invalid trie depth ordering: depth={depth}, stack_len={}", stack.len());
- -1
- };
- parents[abs_idx] = parent_local;
-
- if stack.len() <= depth {
- stack.resize(depth + 1, 0);
- }
- stack[depth] = local_idx;
- stack.truncate(depth + 1);
- }
- }
-
- context.create_array_from(&[suffix_length], &parents)
- }
-
- fn init_token_subtrie_ranges(
- context: &B::Context,
- model_shape: &ModelShape,
- suffix_length: usize,
- token_subtrie_ranges: &[[u32; 3]],
- ) -> Array<B> {
- let shape = model_shape.subtrie_ranges_shape(suffix_length);
- let mut array = context.create_array_zeros(&shape, DataType::U32);
- let source = ArrayView2::from_shape(
- (token_subtrie_ranges.len(), 3),
- bytemuck::cast_slice::<_, u32>(token_subtrie_ranges),
- )
- .expect("Invalid token subtrie range shape");
- array.copy_from_view(source);
- array
- }
-}
diff --git a/crates/backend-uzu/src/forward_pass/traces.rs b/crates/backend-uzu/src/forward_pass/traces.rs
deleted file mode 100644
index 919cf36c5..000000000
--- a/crates/backend-uzu/src/forward_pass/traces.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-use crate::{array::Array, backends::common::Backend};
-
-pub struct LayerActivationTrace<B: Backend> {
- pub inputs: Array<B>,
- pub pre_attention_norm: Array<B>,
- pub attention: Array<B>,
- pub post_attention_norm: Array<B>,
- pub mlp_inputs: Array<B>,
- pub pre_mlp_norm: Array<B>,
- pub mlp: Array<B>,
- pub post_mlp_norm: Array<B>,
- pub outputs: Array<B>,
-}
-
-pub struct ActivationTrace<B: Backend> {
- pub embedding_norm: Option<Array<B>>,
- pub layer_results: Box<[LayerActivationTrace<B>]>,
- pub output_norm: Array<B>,
- pub output_pooling: Option<Array<B>>,
- pub logits: Array<B>,
-}
-
-impl<B: Backend> ActivationTrace<B> {
- pub fn embedding_norm_mut(&mut self) -> &mut Array<B> {
- self.embedding_norm.as_mut().expect("embedding_norm is only available for classifier traces")
- }
-
- pub fn output_pooling_mut(&mut self) -> &mut Array<B> {
- self.output_pooling.as_mut().expect("output_pooling is only available for classifier traces")
- }
-}
-
-#[cfg(all(test, feature = "tracing"))]
-#[path = "../../unit/forward_pass/traces/mod.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/inference/chat/bridging.rs b/crates/backend-uzu/src/inference/chat/bridging.rs
deleted file mode 100644
index 0415c90a8..000000000
--- a/crates/backend-uzu/src/inference/chat/bridging.rs
+++ /dev/null
@@ -1,258 +0,0 @@
-use std::{path::Path, sync::Arc};
-
-use shoji::{
- traits::backend::chat_message::Output as ChatMessageOutput,
- types::{
- basic::{
- ContextLength as ShojiContextLength, Grammar as ShojiGrammar, ReasoningEffort,
- SamplingMethod as ShojiSamplingMethod, SamplingPolicy as ShojiSamplingPolicy,
- SamplingSeed as ShojiSamplingSeed,
- },
- session::chat::{
- ChatConfig as ShojiChatConfig, ChatMessage as ShojiMessage, ChatMessageList, ChatReplyConfig,
- ChatReplyFinishReason as ShojiFinishReason, ChatReplyPowerStats as ShojiPowerStats,
- ChatReplyStats as ShojiStats, ChatRole as ShojiRole, ChatSpeculationPreset as ShojiSpeculationPreset,
- },
- },
-};
-use tokenizers::Tokenizer;
-
-use crate::{
- inference::Error,
- session::{
- config::{DecodingConfig, GrammarConfig, RunConfig, SpeculatorConfig, StructuredOutput},
- parameter::{ContextLength, SamplingMethod, SamplingPolicy, SamplingProcessingOrder, SamplingSeed},
- types::{FinishReason, Input, Message, Output, Role, Stats},
- },
- speculators::{fixed_token_speculator::FixedTokensSpeculator, prompt_lookup_speculator::PromptLookupSpeculator},
-};
-
-pub fn build_decoding_config(
- config: &ShojiChatConfig,
- model_path: &Path,
-) -> Result<DecodingConfig, Error> {
- let context_length = match &config.context_length {
- ShojiContextLength::Default {} => ContextLength::Default,
- ShojiContextLength::Maximal {} => ContextLength::Maximal,
- ShojiContextLength::Custom {
- length,
- } => ContextLength::Custom((*length).max(0) as usize),
- };
- let sampling_seed = match &config.sampling_seed {
- ShojiSamplingSeed::Default {} => SamplingSeed::Default,
- ShojiSamplingSeed::Custom {
- seed,
- } => SamplingSeed::Custom(*seed as u64),
- };
- let speculator_config: SpeculatorConfig = match &config.speculation_preset {
- Some(ShojiSpeculationPreset::GeneralChat {
- ..
- }) => SpeculatorConfig::default(),
- Some(ShojiSpeculationPreset::Summarization {
- ..
- }) => {
- let number_of_speculated_tokens = 16 - 1;
- let speculator = PromptLookupSpeculator::new_with_params(3);
- SpeculatorConfig::new(number_of_speculated_tokens, Arc::new(speculator))
- },
- Some(ShojiSpeculationPreset::Classification {
- feature,
- }) => {
- let tokenizer = Tokenizer::from_file(model_path.join("tokenizer.json"))?;
- let proposals: Vec<Vec<u64>> = feature
- .values
- .iter()
- .map(|value| {
- let encoding = tokenizer.encode(value.as_str(), false).map_err(|error| Error::Runtime {
- message: error.to_string(),
- })?;
- Ok(encoding.get_ids().iter().map(|&id| id as u64).collect::<Vec<_>>())
- })
- .collect::<Result<Vec<Vec<u64>>, Error>>()?;
- let speculator = FixedTokensSpeculator::new(proposals);
- SpeculatorConfig::new(speculator.max_trie_nodes(), Arc::new(speculator))
- },
- None => SpeculatorConfig::default(),
- };
- Ok(DecodingConfig::default()
- .with_context_length(context_length)
- .with_sampling_seed(sampling_seed)
- .with_speculator_config(speculator_config))
-}
-
-pub fn build_input_and_run_config(
- messages: &Vec<ShojiMessage>,
- config: &ChatReplyConfig,
-) -> (Input, RunConfig) {
- let input_messages = messages.iter().filter_map(build_message).collect();
- let input = Input::Messages(input_messages);
- let run_config = build_run_config(messages, config);
- (input, run_config)
-}
-
-pub fn build_output(output: &Output) -> ChatMessageOutput {
- let text = output.text.parsed.response.clone();
- let reasoning = output.text.parsed.chain_of_thought.clone();
- let finish_reason = output.finish_reason.as_ref().map(build_finish_reason);
- let stats = build_stats(&output.stats);
- ChatMessageOutput {
- reasoning,
- text,
- tool_calls: vec![],
- finish_reason,
- stats,
- }
-}
-
-fn build_message(message: &ShojiMessage) -> Option<Message> {
- let role = match &message.role {
- ShojiRole::System {} => Role::System,
- ShojiRole::User {} => Role::User,
- ShojiRole::Assistant {} => Role::Assistant,
- ShojiRole::Developer {}
- | ShojiRole::Tool {}
- | ShojiRole::Custom {
- ..
- } => return None,
- };
-
- let content = message.text().unwrap_or_default();
- let reasoning_content = message.reasoning();
- Some(Message {
- role,
- content,
- reasoning_content,
- })
-}
-
-fn build_run_config(
- messages: &Vec<ShojiMessage>,
- config: &ChatReplyConfig,
-) -> RunConfig {
- let sampling_policy = build_sampling_policy(&config.sampling_policy);
- let grammar_config = build_grammar(&config.grammar);
- let tokens_limit = config.token_limit.map(|value| value as u64).unwrap_or(2048);
- let enable_thinking =
- messages.reasoning_effort().map(|effort| !matches!(effort, ReasoningEffort::Disabled)).unwrap_or(true);
- RunConfig::new(tokens_limit, enable_thinking, sampling_policy, grammar_config)
-}
-
-fn build_sampling_policy(sampling_policy: &ShojiSamplingPolicy) -> SamplingPolicy {
- match sampling_policy {
- ShojiSamplingPolicy::Default {} => SamplingPolicy::Default,
- ShojiSamplingPolicy::Custom {
- method,
- } => SamplingPolicy::Custom {
- value: match method {
- ShojiSamplingMethod::Greedy {} => SamplingMethod::Greedy,
- ShojiSamplingMethod::Stochastic {
- temperature,
- top_k,
- top_p,
- min_p,
- repetition_penalty,
- suffix_repetition_length,
- } => SamplingMethod::Stochastic {
- temperature: temperature.map(|value| value as f32),
- top_k: top_k.map(|value| value.max(0) as u32),
- top_p: top_p.map(|value| value as f32),
- min_p: min_p.map(|value| value as f32),
- repetition_penalty: repetition_penalty.map(|value| value as f32),
- suffix_repetition_length: suffix_repetition_length.map(|value| value as usize),
- processing_order: SamplingProcessingOrder::TemperatureThenFilters,
- },
- },
- },
- }
-}
-
-fn build_grammar(grammar: &Option<ShojiGrammar>) -> Option<GrammarConfig> {
- match grammar {
- Some(ShojiGrammar::JsonAny {}) => Some(GrammarConfig::builtin_json()),
- Some(ShojiGrammar::JsonSchema {
- schema,
- }) => Some(match GrammarConfig::structured_output_from_schema(schema) {
- StructuredOutput::Schema(schema) => GrammarConfig::json_schema_simple(schema),
- StructuredOutput::AnyJson => GrammarConfig::builtin_json(),
- }),
- Some(ShojiGrammar::Regex {
- pattern,
- }) => Some(GrammarConfig::regex(pattern.clone(), false)),
- None => None,
- }
-}
-
-fn build_finish_reason(reason: &FinishReason) -> ShojiFinishReason {
- match reason {
- FinishReason::Stop => ShojiFinishReason::Stop,
- FinishReason::Length => ShojiFinishReason::Length,
- FinishReason::Cancelled => ShojiFinishReason::Cancelled,
- FinishReason::ContextLimitReached => ShojiFinishReason::ContextLimitReached,
- }
-}
-
-fn build_stats(stats: &Stats) -> ShojiStats {
- let time_to_first_token = Some(stats.prefill_stats.duration);
- let prefill_tokens_per_second = Some(stats.prefill_stats.processed_tokens_per_second);
- let generate_tokens_per_second = stats.generate_stats.as_ref().map(|step| step.tokens_per_second);
- let power_stats = stats.power_stats.as_ref().map(|power| ShojiPowerStats {
- samples_count: power.samples_count.min(i64::MAX as u64) as i64,
- average_cpu_watts: power.average_cpu_watts,
- average_gpu_watts: power.average_gpu_watts,
- average_gpu_sram_watts: power.average_gpu_sram_watts,
- average_ane_watts: power.average_ane_watts,
- average_ram_watts: power.average_ram_watts,
- average_total_watts: power.average_total_watts,
- average_package_watts: power.average_package_watts,
- max_package_watts: power.max_package_watts,
- energy_joules: power.energy_joules,
- });
- ShojiStats {
- duration: stats.total_stats.duration,
- time_to_first_token,
- prefill_tokens_per_second,
- generate_tokens_per_second,
- tokens_count_input: Some(stats.total_stats.tokens_count_input as u32),
- tokens_count_output: Some(stats.total_stats.tokens_count_output as u32),
- memory_used_bytes: stats.memory_used_bytes.map(|value| value.min(i64::MAX as u64) as i64),
- power_stats,
- }
-}
-
-#[cfg(test)]
-mod tests {
- use proc_macros::uzu_test;
- use shoji::types::session::chat::ChatMessage;
-
- use super::*;
-
- fn enable_thinking_for(messages: Vec<ChatMessage>) -> bool {
- build_run_config(&messages, &ChatReplyConfig::default()).enable_thinking
- }
-
- fn user(reasoning_effort: ReasoningEffort) -> ChatMessage {
- ChatMessage::user().with_text("hi".to_string()).with_reasoning_effort(reasoning_effort)
- }
-
- #[uzu_test]
- fn enable_thinking_defaults_on_without_effort() {
- assert!(enable_thinking_for(vec![ChatMessage::user().with_text("hi".to_string())]));
- }
-
- #[uzu_test]
- fn enable_thinking_follows_latest_turn() {
- let reenabled = vec![
- user(ReasoningEffort::Disabled),
- ChatMessage::assistant().with_text("ok".to_string()),
- user(ReasoningEffort::Default),
- ];
- assert!(enable_thinking_for(reenabled));
-
- let redisabled = vec![
- user(ReasoningEffort::Default),
- ChatMessage::assistant().with_text("ok".to_string()),
- user(ReasoningEffort::Disabled),
- ];
- assert!(!enable_thinking_for(redisabled));
- }
-}
diff --git a/crates/backend-uzu/src/inference/chat/mod.rs b/crates/backend-uzu/src/inference/chat/mod.rs
deleted file mode 100644
index 473451ce6..000000000
--- a/crates/backend-uzu/src/inference/chat/mod.rs
+++ /dev/null
@@ -1,130 +0,0 @@
-mod bridging;
-mod state;
-
-use std::{path::PathBuf, pin::Pin};
-
-use bridging::{build_decoding_config, build_input_and_run_config, build_output};
-use futures::{
- Stream,
- channel::mpsc::{self, UnboundedSender},
-};
-use shoji::{
- traits::{
- Instance as InstanceTrait, State as StateTrait,
- backend::{
- Error as BackendError,
- chat_message::{Output as ChatMessageOutput, StreamInput, StreamOutput},
- },
- },
- types::session::chat::{ChatConfig, ChatReplyConfig},
-};
-use state::State;
-use tokio_util::sync::CancellationToken;
-
-use crate::{
- inference::{Container, Error},
- session::{
- ChatSession,
- config::RunConfig,
- types::{Input, Output},
- },
-};
-
-pub struct Instance {
- session_container: Container<ChatSession>,
-}
-
-impl Instance {
- pub fn new(
- reference: String,
- config: ChatConfig,
- ) -> Result<Self, Error> {
- let model_path = PathBuf::from(reference.clone());
- let decoding_config = build_decoding_config(&config, &model_path)?;
- let session = ChatSession::new(model_path, decoding_config)?;
- let container = Container::new(session);
- Ok(Self {
- session_container: container,
- })
- }
-}
-
-impl InstanceTrait for Instance {
- type StreamConfig = ChatReplyConfig;
- type StreamInput = StreamInput;
- type StreamOutput = StreamOutput;
-
- fn state(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn StateTrait>, BackendError>> + Send + '_>> {
- let result: Result<(), Error> = self
- .session_container
- .value
- .lock()
- .map_err(|error| Error::Runtime {
- message: error.to_string(),
- })
- .and_then(|mut session| {
- session.reset()?;
- Ok(())
- });
- Box::pin(async move {
- result?;
- Ok(Box::new(State) as Box<dyn StateTrait>)
- })
- }
-
- fn stream<'a>(
- &'a self,
- input: &'a Self::StreamInput,
- _state: &'a mut dyn StateTrait,
- config: Self::StreamConfig,
- cancel_token: CancellationToken,
- ) -> Pin<Box<dyn Stream<Item = Result<Self::StreamOutput, BackendError>> + Send + 'a>> {
- let session = self.session_container.clone();
- let messages = input.clone();
- let cancel_token_for_run = cancel_token.clone();
-
- let (sender, receiver) = mpsc::unbounded::<Result<ChatMessageOutput, BackendError>>();
- let (input, run_config) = build_input_and_run_config(&messages, &config);
- std::thread::spawn(move || {
- run(session, input, run_config, cancel_token_for_run, sender);
- });
- Box::pin(receiver)
- }
-}
-
-fn run(
- session_container: Container<ChatSession>,
- uzu_input: Input,
- run_config: RunConfig,
- cancel_token: CancellationToken,
- sender: UnboundedSender<Result<ChatMessageOutput, BackendError>>,
-) {
- let progress = {
- let sender = sender.clone();
- let cancel_token = cancel_token.clone();
- move |output: Output| -> bool {
- let chat_output = build_output(&output);
- let _ = sender.unbounded_send(Ok(chat_output));
- !cancel_token.is_cancelled()
- }
- };
-
- let result = {
- let mut session = match session_container.value.lock() {
- Ok(session) => session,
- Err(error) => {
- let _ = sender.unbounded_send(Err(Box::new(Error::Runtime {
- message: error.to_string(),
- }) as BackendError));
- return;
- },
- };
- session.run(uzu_input, run_config, Some(progress))
- };
-
- let result = match result {
- Ok(output) => Ok(build_output(&output)),
- Err(error) => Err(Box::new(Error::from(error)) as BackendError),
- };
- let _ = sender.unbounded_send(result);
-}
diff --git a/crates/backend-uzu/src/inference/chat/state.rs b/crates/backend-uzu/src/inference/chat/state.rs
deleted file mode 100644
index 9dbbe80a4..000000000
--- a/crates/backend-uzu/src/inference/chat/state.rs
+++ /dev/null
@@ -1,10 +0,0 @@
-use shoji::traits::State as StateTrait;
-
-#[derive(Debug, Clone)]
-pub struct State;
-
-impl StateTrait for State {
- fn clone_boxed(&self) -> Box<dyn StateTrait> {
- Box::new(self.clone())
- }
-}
diff --git a/crates/backend-uzu/src/inference/classification/bridging.rs b/crates/backend-uzu/src/inference/classification/bridging.rs
deleted file mode 100644
index 4cd65003a..000000000
--- a/crates/backend-uzu/src/inference/classification/bridging.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-use std::collections::HashMap;
-
-use shoji::types::session::classification::{
- ClassificationMessage as ShojiMessage, ClassificationOutput as ShojiOutput,
- ClassificationOutputProbabilities as ShojiOutputProbabilities, ClassificationRole as ShojiRole,
- ClassificationStats as ShojiStats,
-};
-
-use crate::{
- classifier::ClassificationOutput,
- session::types::{Input, Message, Role},
-};
-
-pub fn build_input(messages: &[ShojiMessage]) -> Input {
- let input_messages: Vec<Message> = messages
- .iter()
- .map(|message| {
- let role = match message.role {
- ShojiRole::User => Role::User,
- ShojiRole::Assistant => Role::Assistant,
- };
- Message {
- role,
- content: message.content.clone(),
- reasoning_content: None,
- }
- })
- .collect();
- Input::Messages(input_messages)
-}
-
-pub fn build_output(output: &ClassificationOutput) -> ShojiOutput {
- let logits = output.logits.iter().map(|value| *value as f64).collect();
- let probabilities: HashMap<String, f64> =
- output.probabilities.iter().map(|(label, value)| (label.clone(), *value as f64)).collect();
- let probabilities = ShojiOutputProbabilities {
- values: probabilities,
- };
- let stats = ShojiStats {
- preprocessing_duration: output.stats.preprocessing_duration,
- forward_pass_duration: output.stats.forward_pass_duration,
- postprocessing_duration: output.stats.postprocessing_duration,
- total_duration: output.stats.total_duration,
- tokens_count: output.stats.tokens_count as i64,
- tokens_per_second: output.stats.tokens_per_second,
- predicted_label: output.stats.predicted_label.clone(),
- confidence: output.stats.confidence as f64,
- };
- ShojiOutput {
- logits,
- probabilities,
- stats,
- }
-}
diff --git a/crates/backend-uzu/src/inference/classification/mod.rs b/crates/backend-uzu/src/inference/classification/mod.rs
deleted file mode 100644
index 496d540a8..000000000
--- a/crates/backend-uzu/src/inference/classification/mod.rs
+++ /dev/null
@@ -1,94 +0,0 @@
-mod bridging;
-mod state;
-
-use std::{path::PathBuf, pin::Pin};
-
-use bridging::{build_input, build_output};
-use futures::{
- Stream, StreamExt,
- channel::mpsc::{self, UnboundedSender},
-};
-use shoji::{
- traits::{
- Instance as InstanceTrait, State as StateTrait,
- backend::{
- Error as BackendError,
- classification::{StreamInput, StreamOutput},
- },
- },
- types::session::classification::ClassificationOutput as ShojiOutput,
-};
-use state::State;
-use tokio_util::sync::CancellationToken;
-
-use crate::{
- inference::{Container, Error},
- session::{ClassificationSession, types::Input},
-};
-
-pub struct Instance {
- session_container: Container<ClassificationSession>,
-}
-
-impl Instance {
- pub fn new(reference: String) -> Result<Self, Error> {
- let model_path = PathBuf::from(reference);
- let session = ClassificationSession::new(model_path)?;
- let container = Container::new(session);
- Ok(Self {
- session_container: container,
- })
- }
-}
-
-impl InstanceTrait for Instance {
- type StreamConfig = ();
- type StreamInput = StreamInput;
- type StreamOutput = StreamOutput;
-
- fn state(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn StateTrait>, BackendError>> + Send + '_>> {
- Box::pin(async move { Ok(Box::new(State) as Box<dyn StateTrait>) })
- }
-
- fn stream<'a>(
- &'a self,
- input: &'a Self::StreamInput,
- _state: &'a mut dyn StateTrait,
- _config: Self::StreamConfig,
- cancel_token: CancellationToken,
- ) -> Pin<Box<dyn Stream<Item = Result<Self::StreamOutput, BackendError>> + Send + 'a>> {
- let input = build_input(input);
- let session_container = self.session_container.clone();
- let (sender, receiver) = mpsc::unbounded::<Result<ShojiOutput, BackendError>>();
-
- std::thread::spawn(move || {
- run(session_container, input, sender);
- });
-
- Box::pin(receiver.take_until(cancel_token.cancelled_owned()))
- }
-}
-
-fn run(
- session_container: Container<ClassificationSession>,
- input: Input,
- sender: UnboundedSender<Result<ShojiOutput, BackendError>>,
-) {
- let result = {
- let mut session = match session_container.value.lock() {
- Ok(guard) => guard,
- Err(error) => {
- let _ = sender.unbounded_send(Err(Box::new(Error::Runtime {
- message: error.to_string(),
- }) as BackendError));
- return;
- },
- };
- session.classify(input)
- };
- let result = match result {
- Ok(output) => Ok(build_output(&output)),
- Err(error) => Err(Box::new(Error::from(error)) as BackendError),
- };
- let _ = sender.unbounded_send(result);
-}
diff --git a/crates/backend-uzu/src/inference/classification/state.rs b/crates/backend-uzu/src/inference/classification/state.rs
deleted file mode 100644
index 9dbbe80a4..000000000
--- a/crates/backend-uzu/src/inference/classification/state.rs
+++ /dev/null
@@ -1,10 +0,0 @@
-use shoji::traits::State as StateTrait;
-
-#[derive(Debug, Clone)]
-pub struct State;
-
-impl StateTrait for State {
- fn clone_boxed(&self) -> Box<dyn StateTrait> {
- Box::new(self.clone())
- }
-}
diff --git a/crates/backend-uzu/src/inference/container.rs b/crates/backend-uzu/src/inference/container.rs
deleted file mode 100644
index 032b1d4d6..000000000
--- a/crates/backend-uzu/src/inference/container.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-use std::sync::{Arc, Mutex};
-
-pub struct Container<T> {
- pub value: Arc<Mutex<T>>,
-}
-
-unsafe impl<T> Send for Container<T> {}
-unsafe impl<T> Sync for Container<T> {}
-
-impl<T> Container<T> {
- pub fn new(value: T) -> Self {
- Self {
- value: Arc::new(Mutex::new(value)),
- }
- }
-}
-
-impl<T> Clone for Container<T> {
- fn clone(&self) -> Self {
- Self {
- value: self.value.clone(),
- }
- }
-}
diff --git a/crates/backend-uzu/src/inference/error.rs b/crates/backend-uzu/src/inference/error.rs
deleted file mode 100644
index 50100b5a4..000000000
--- a/crates/backend-uzu/src/inference/error.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-use crate::session::types::Error as ChatSessionError;
-
-#[derive(Debug, thiserror::Error)]
-pub enum Error {
- #[error("Runtime error: {message}")]
- Runtime {
- message: String,
- },
- #[error("Session error: {message}")]
- Session {
- message: String,
- },
- #[error("Unable to load tokenizer: {0}")]
- UnableToLoadTokenizer(#[from] tokenizers::Error),
-}
-
-impl From<ChatSessionError> for Error {
- fn from(error: ChatSessionError) -> Self {
- Error::Session {
- message: error.to_string(),
- }
- }
-}
diff --git a/crates/backend-uzu/src/inference/mod.rs b/crates/backend-uzu/src/inference/mod.rs
deleted file mode 100644
index 1d1dbd9d1..000000000
--- a/crates/backend-uzu/src/inference/mod.rs
+++ /dev/null
@@ -1,96 +0,0 @@
-mod chat;
-mod classification;
-mod container;
-mod error;
-mod model_metadata;
-mod text_to_speech;
-
-use std::pin::Pin;
-
-pub use chat::Instance as ChatInstance;
-pub use classification::Instance as ClassificationInstance;
-pub use container::Container;
-pub use error::Error;
-pub use model_metadata::{ModelMetadataError, resolve_model_specialization};
-use shoji::{
- traits::{
- Backend as BackendTrait,
- backend::{
- Error as BackendError, chat_message as chat_message_trait, classification as classification_trait,
- text_to_speech as text_to_speech_trait,
- },
- },
- types::session::chat::ChatConfig as ShojiChatConfig,
-};
-pub use text_to_speech::Instance as TextToSpeechInstance;
-
-use crate::utils::TOOLCHAIN_VERSION;
-
-pub struct Backend;
-
-impl Backend {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl BackendTrait for Backend {
- fn identifier(&self) -> String {
- "uzu".to_string()
- }
-
- fn version(&self) -> String {
- TOOLCHAIN_VERSION.to_string()
- }
-
- fn as_chat_via_message_capable(&self) -> Option<&dyn chat_message_trait::Backend> {
- Some(self)
- }
-
- fn as_classification_capable(&self) -> Option<&dyn classification_trait::Backend> {
- Some(self)
- }
-
- fn as_text_to_speech_capable(&self) -> Option<&dyn text_to_speech_trait::Backend> {
- Some(self)
- }
-}
-
-impl chat_message_trait::Backend for Backend {
- fn instance(
- &self,
- reference: String,
- config: ShojiChatConfig,
- ) -> Pin<Box<dyn Future<Output = Result<Box<dyn chat_message_trait::Instance>, BackendError>> + Send + '_>> {
- Box::pin(async move {
- let instance = ChatInstance::new(reference, config)?;
- Ok(Box::new(instance) as Box<dyn chat_message_trait::Instance>)
- })
- }
-}
-
-impl classification_trait::Backend for Backend {
- fn instance(
- &self,
- reference: String,
- _config: classification_trait::Config,
- ) -> Pin<Box<dyn Future<Output = Result<Box<dyn classification_trait::Instance>, BackendError>> + Send + '_>> {
- Box::pin(async move {
- let instance = ClassificationInstance::new(reference)?;
- Ok(Box::new(instance) as Box<dyn classification_trait::Instance>)
- })
- }
-}
-
-impl text_to_speech_trait::Backend for Backend {
- fn instance(
- &self,
- reference: String,
- _config: text_to_speech_trait::Config,
- ) -> Pin<Box<dyn Future<Output = Result<Box<dyn text_to_speech_trait::Instance>, BackendError>> + Send + '_>> {
- Box::pin(async move {
- let instance = TextToSpeechInstance::new(reference)?;
- Ok(Box::new(instance) as Box<dyn text_to_speech_trait::Instance>)
- })
- }
-}
diff --git a/crates/backend-uzu/src/inference/text_to_speech/bridging.rs b/crates/backend-uzu/src/inference/text_to_speech/bridging.rs
deleted file mode 100644
index acb609440..000000000
--- a/crates/backend-uzu/src/inference/text_to_speech/bridging.rs
+++ /dev/null
@@ -1,16 +0,0 @@
-use shoji::types::basic::PcmBatch as ShojiPcmBatch;
-
-use crate::{audio::AudioPcmBatch, session::types::Input};
-
-pub fn build_input(input: &str) -> Input {
- Input::Text(input.to_string())
-}
-
-pub fn build_pcm_batch(pcm: &AudioPcmBatch) -> ShojiPcmBatch {
- ShojiPcmBatch {
- samples: pcm.samples().iter().map(|value| *value as f64).collect(),
- sample_rate: pcm.sample_rate(),
- channels: pcm.channels() as u32,
- lengths: pcm.lengths().iter().map(|value| *value as u32).collect(),
- }
-}
diff --git a/crates/backend-uzu/src/inference/text_to_speech/mod.rs b/crates/backend-uzu/src/inference/text_to_speech/mod.rs
deleted file mode 100644
index 33c7e1f66..000000000
--- a/crates/backend-uzu/src/inference/text_to_speech/mod.rs
+++ /dev/null
@@ -1,134 +0,0 @@
-#[cfg(metal_backend)]
-mod bridging;
-mod state;
-
-use std::pin::Pin;
-
-#[cfg(metal_backend)]
-use bridging::{build_input, build_pcm_batch};
-use futures::Stream;
-#[cfg(not(metal_backend))]
-use futures::stream;
-#[cfg(metal_backend)]
-use futures::{
- StreamExt,
- channel::mpsc::{self, UnboundedSender},
-};
-#[cfg(metal_backend)]
-use rand::prelude::*;
-use shoji::traits::{
- Instance as InstanceTrait, State as StateTrait,
- backend::{
- Error as BackendError,
- text_to_speech::{StreamInput, StreamOutput},
- },
-};
-#[cfg(metal_backend)]
-use shoji::types::basic::PcmBatch as ShojiPcmBatch;
-use state::State;
-use tokio_util::sync::CancellationToken;
-
-use crate::inference::Error;
-#[cfg(metal_backend)]
-use crate::{
- backends::metal::Metal,
- inference::Container,
- session::{TtsSession, config::TtsRunConfig, types::Input},
-};
-
-pub struct Instance {
- #[cfg(metal_backend)]
- session_container: Container<TtsSession<Metal>>,
-}
-
-impl Instance {
- #[cfg(metal_backend)]
- pub fn new(reference: String) -> Result<Self, Error> {
- let model_path = std::path::PathBuf::from(reference);
- let session = TtsSession::<Metal>::new(model_path)?;
- Ok(Self {
- session_container: Container::new(session),
- })
- }
-
- #[cfg(not(metal_backend))]
- pub fn new(_reference: String) -> Result<Self, Error> {
- Err(Error::Runtime {
- message: "Text-to-speech requires the metal backend".to_string(),
- })
- }
-}
-
-impl InstanceTrait for Instance {
- type StreamConfig = ();
- type StreamInput = StreamInput;
- type StreamOutput = StreamOutput;
-
- fn state(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn StateTrait>, BackendError>> + Send + '_>> {
- Box::pin(async move { Ok(Box::new(State) as Box<dyn StateTrait>) })
- }
-
- #[cfg(metal_backend)]
- fn stream<'a>(
- &'a self,
- input: &'a Self::StreamInput,
- _state: &'a mut dyn StateTrait,
- _config: Self::StreamConfig,
- cancel_token: CancellationToken,
- ) -> Pin<Box<dyn Stream<Item = Result<Self::StreamOutput, BackendError>> + Send + 'a>> {
- let input = build_input(input);
- let session_container = self.session_container.clone();
- let cancel_for_run = cancel_token.clone();
- let (sender, receiver) = mpsc::unbounded::<Result<ShojiPcmBatch, BackendError>>();
-
- std::thread::spawn(move || {
- run(session_container, input, cancel_for_run, sender);
- });
-
- Box::pin(receiver.take_until(cancel_token.cancelled_owned()))
- }
-
- #[cfg(not(metal_backend))]
- fn stream<'a>(
- &'a self,
- _input: &'a Self::StreamInput,
- _state: &'a mut dyn StateTrait,
- _config: Self::StreamConfig,
- _cancel_token: CancellationToken,
- ) -> Pin<Box<dyn Stream<Item = Result<Self::StreamOutput, BackendError>> + Send + 'a>> {
- Box::pin(stream::once(async {
- Err(Box::new(Error::Runtime {
- message: "Text-to-speech requires the metal backend".to_string(),
- }) as BackendError)
- }))
- }
-}
-
-#[cfg(metal_backend)]
-fn run(
- session_container: Container<TtsSession<Metal>>,
- input: Input,
- _cancel_token: CancellationToken,
- sender: UnboundedSender<Result<ShojiPcmBatch, BackendError>>,
-) {
- let result = {
- let mut session = match session_container.value.lock() {
- Ok(session) => session,
- Err(error) => {
- let _ = sender.unbounded_send(Err(Box::new(Error::Runtime {
- message: error.to_string(),
- }) as BackendError));
- return;
- },
- };
- let seed = rand::rng().random::<u64>();
- let config = TtsRunConfig::default();
- let chunk_sender = sender.clone();
- session.synthesize_streaming_with_seed_and_config(input, seed, &config, |pcm| {
- let _ = chunk_sender.unbounded_send(Ok(build_pcm_batch(pcm)));
- })
- };
- if let Err(error) = result {
- let _ = sender.unbounded_send(Err(Box::new(Error::from(error)) as BackendError));
- }
-}
diff --git a/crates/backend-uzu/src/inference/text_to_speech/state.rs b/crates/backend-uzu/src/inference/text_to_speech/state.rs
deleted file mode 100644
index 9dbbe80a4..000000000
--- a/crates/backend-uzu/src/inference/text_to_speech/state.rs
+++ /dev/null
@@ -1,10 +0,0 @@
-use shoji::traits::State as StateTrait;
-
-#[derive(Debug, Clone)]
-pub struct State;
-
-impl StateTrait for State {
- fn clone_boxed(&self) -> Box<dyn StateTrait> {
- Box::new(self.clone())
- }
-}
diff --git a/crates/backend-uzu/src/language_model/gpu_capture.rs b/crates/backend-uzu/src/language_model/gpu_capture.rs
deleted file mode 100644
index 645d5508d..000000000
--- a/crates/backend-uzu/src/language_model/gpu_capture.rs
+++ /dev/null
@@ -1,100 +0,0 @@
-use std::{
- marker::PhantomData,
- path::PathBuf,
- time::{SystemTime, UNIX_EPOCH},
-};
-
-use crate::{
- backends::common::{Backend, Context},
- utils::env_utils::EnvVar,
-};
-
-#[derive(Debug, thiserror::Error)]
-pub enum GpuCaptureError<B: Backend> {
- #[error("Unable to resolve capture timestamp: {0}")]
- Timestamp(#[from] std::time::SystemTimeError),
- #[error("Unable to get current directory: {0}")]
- CurrentDirectory(#[from] std::io::Error),
- #[error("Backend capture failed: {0}")]
- Backend(#[source] B::Error),
-}
-
-pub struct GpuCaptureManager<B: Backend> {
- capture_prefill_enabled: bool,
- capture_decode_enabled: bool,
- first_prefill_captured: bool,
- first_decode_captured: bool,
- phantom: PhantomData<B>,
-}
-
-impl<B: Backend> GpuCaptureManager<B> {
- pub fn new() -> Self {
- let capture_prefill_enabled = EnvVar::CaptureFirstPrefill.is_enabled();
- let capture_decode_enabled = EnvVar::CaptureFirstDecode.is_enabled();
-
- // Enable backend capture BEFORE device creation if any capture is requested
- if capture_prefill_enabled || capture_decode_enabled {
- B::Context::enable_capture();
- }
-
- Self {
- capture_prefill_enabled,
- capture_decode_enabled,
- first_prefill_captured: false,
- first_decode_captured: false,
- phantom: PhantomData,
- }
- }
-
- pub fn should_capture_prefill(
- &self,
- is_first_prefill: bool,
- ) -> bool {
- self.capture_prefill_enabled && is_first_prefill && !self.first_prefill_captured
- }
-
- pub fn should_capture_decode(
- &self,
- is_first_decode: bool,
- ) -> bool {
- self.capture_decode_enabled && is_first_decode && !self.first_decode_captured
- }
-
- pub fn start_capture(
- &self,
- context: &B::Context,
- capture_type: &str,
- ) -> Result<PathBuf, GpuCaptureError<B>> {
- let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
-
- let trace_path = std::env::current_dir()?.join(format!("uzu_first_{}-{}.gputrace", capture_type, timestamp));
-
- context.start_capture(&trace_path).map_err(GpuCaptureError::Backend)?;
-
- println!("GPU capture started for first {}: {:?}", capture_type, trace_path);
-
- Ok(trace_path)
- }
-
- pub fn stop_capture(
- &mut self,
- context: &B::Context,
- capture_type: &str,
- ) -> Result<(), GpuCaptureError<B>> {
- context.stop_capture().map_err(GpuCaptureError::Backend)?;
- println!("GPU capture stopped for {}", capture_type);
-
- match capture_type {
- "prefill" => self.first_prefill_captured = true,
- "decode" => self.first_decode_captured = true,
- _ => {},
- }
-
- Ok(())
- }
-
- pub fn reset(&mut self) {
- self.first_prefill_captured = false;
- self.first_decode_captured = false;
- }
-}
diff --git a/crates/backend-uzu/src/language_model/grammar/mod.rs b/crates/backend-uzu/src/language_model/grammar/mod.rs
deleted file mode 100644
index a58cfd19b..000000000
--- a/crates/backend-uzu/src/language_model/grammar/mod.rs
+++ /dev/null
@@ -1,49 +0,0 @@
-mod xgram;
-
-use tokenizers::Tokenizer;
-
-use crate::session::{config::GrammarConfig, types::Error};
-
-pub trait CompiledGrammar {
- fn next_bitmask(&mut self) -> Result<Option<Box<[u32]>>, Error>;
-
- fn accept_token(
- &mut self,
- token_id: u64,
- ) -> Result<(), Error>;
-
- fn rollback(
- &mut self,
- num_tokens: usize,
- );
-
- fn is_terminated(&self) -> bool;
-}
-
-#[cfg_attr(not(grammar_xgrammar), allow(unused_variables))]
-pub fn create_compiled_grammar(
- config: &GrammarConfig,
- tokenizer: &Tokenizer,
- stop_token_ids: Option<&[i32]>,
-) -> Result<Box<dyn CompiledGrammar>, Error> {
- #[cfg(grammar_xgrammar)]
- {
- use xgrammar::TokenizerInfo;
- let tokenizer_info =
- TokenizerInfo::from_huggingface(tokenizer, None, stop_token_ids).map_err(Error::GrammarError)?;
-
- use xgram::CompiledXGrammar;
- let grammar = CompiledXGrammar::from_config(config, None, &tokenizer_info)?;
-
- Ok(Box::new(grammar))
- }
-
- #[cfg(not(grammar_xgrammar))]
- {
- Err(Error::GrammarNoBackendAvailable)
- }
-}
-
-#[cfg(test)]
-#[path = "../../../unit/language_model/grammar.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/language_model/language_model_generator.rs b/crates/backend-uzu/src/language_model/language_model_generator.rs
deleted file mode 100644
index 604f300a9..000000000
--- a/crates/backend-uzu/src/language_model/language_model_generator.rs
+++ /dev/null
@@ -1,1055 +0,0 @@
-use std::{
- any::Any,
- iter::repeat_n,
- mem::size_of,
- ops::Range,
- path::Path,
- time::{Duration, Instant},
-};
-
-use itertools::{Either, Itertools, izip};
-
-use super::{
- gpu_capture::GpuCaptureManager,
- language_model_generator_context::LanguageModelGeneratorContext,
- result::{GenerateResult, PrefillResult},
- rng::PRng,
-};
-use crate::{
- array::{Array, ArrayContextExt},
- backends::common::{
- Allocation, AllocationType, AsBufferRangeRef, Backend, CommandBuffer, Context, DenseBuffer, Encoder, Pending,
- kernel::TokenCopySampledKernel,
- },
- config::model::language_model::LanguageModelConfig,
- data_type::DataType,
- encodable_block::DecoderDecodeInput,
- forward_pass::{cache_layers::CacheLayersSlice, kv_cache_layer::INVALID_POSITION, token_inputs::TokenInputs},
- language_model::grammar::CompiledGrammar,
- session::{
- config::DecodingConfig,
- helpers::Context as LlmContext,
- parameter::{ConfigResolvableValue, ResolvableValue, SamplingMethod},
- types::Error,
- },
- trie::{FlatTrie, TrieCreationConfig, TrieNode},
- utils::pointers::SendPtr,
-};
-
-#[derive(Debug, Clone)]
-pub struct Task {
- token_ids: Box<[u64]>,
- token_subtrie_ranges: Option<Box<[[u32; 3]]>>,
- token_positions: Box<[usize]>,
- token_bitmask: Option<Box<[u32]>>,
- token_seeds: Box<[u64]>,
- active_row_count: usize,
- sampling_start: usize,
- sampling_length: usize,
- is_prefilling: bool,
-}
-
-struct ForwardPassResources<B: Backend> {
- token_inputs: TokenInputs<B>,
- logits: Option<Allocation<B>>,
- sampling_output: Option<Allocation<B>>,
- sampling_seeds: Option<Allocation<B>>,
- sampling_bitmask: Option<Allocation<B>>,
-}
-
-struct InFlightForwardPass<B: Backend> {
- resources: ForwardPassResources<B>,
- pending: Pending<B>,
-}
-
-pub struct RunModelResult<B: Backend> {
- pub sampling_output: Option<Allocation<B>>,
- pub cpu_run_time: f64,
- #[allow(unused)]
- pub gpu_run_time: Duration,
-}
-
-pub struct LanguageModelGenerator<B: Backend> {
- pub decoding_config: DecodingConfig,
- pub tokens: Vec<u64>,
-
- pub context: LanguageModelGeneratorContext<B>,
- async_in_flight: Vec<Option<InFlightForwardPass<B>>>,
- async_token_ids: Option<Array<B>>,
- registered_prefix_len: usize,
- gpu_capture: GpuCaptureManager<B>,
-}
-
-pub trait LanguageModelGeneratorTrait {
- fn prefill(
- &mut self,
- tokens: Vec<u64>,
- compiled_grammar: Option<&mut (dyn CompiledGrammar + 'static)>,
- sampling_method: SamplingMethod,
- prefix_offset: usize,
- sample_suffix: bool,
- ) -> Result<PrefillResult, Error>;
-
- fn generate(
- &mut self,
- compiled_grammar: Option<&mut (dyn CompiledGrammar + 'static)>,
- sampling_method: SamplingMethod,
- ) -> Result<GenerateResult, Error>;
-
- fn prepare_async(
- &mut self,
- tokens_to_generate: usize,
- );
- fn async_generate(
- &mut self,
- pass_idx: usize,
- sampling_method: SamplingMethod,
- on_complete: Box<dyn FnOnce(u64) + Send>,
- ) -> Result<(), Error>;
- fn finish_async(
- &mut self,
- pass_idx: usize,
- );
-
- fn reset_state(&mut self);
- fn peak_memory_usage(&self) -> Option<usize>;
- fn activation_data_type(&self) -> DataType;
-
- fn tokens_len(&self) -> usize;
- fn tokens_push(
- &mut self,
- token: u64,
- );
- fn generate_suffix_length(&self) -> usize;
- fn async_batch_size(
- &self,
- model_path: &Path,
- ) -> Result<usize, Error>;
-
- fn get_slice(
- &self,
- range: Range<usize>,
- ) -> Option<Box<dyn Any>>;
- fn apply_slice(
- &mut self,
- slice: &dyn Any,
- range: Range<usize>,
- );
-
- fn build_llm_context(&self) -> Box<dyn Any>;
- fn reconfigure_from_context(
- &mut self,
- context: &dyn Any,
- );
-
- fn get_context_length(&self) -> usize;
-}
-
-impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
- fn prefill(
- &mut self,
- tokens: Vec<u64>,
- mut compiled_grammar: Option<&mut (dyn CompiledGrammar + 'static)>,
- sampling_method: SamplingMethod,
- prefix_offset: usize,
- sample_suffix: bool,
- ) -> Result<PrefillResult, Error> {
- assert!(!tokens.is_empty());
-
- self.tokens.extend(tokens.clone());
-
- let tokens_length = tokens.len();
-
- let prefill_step_size = self.decoding_config.prefill_step_size.resolve(&self.context.model_config);
- let prefill_steps = tokens_length.div_ceil(prefill_step_size);
- let prefill_size = prefill_steps * prefill_step_size;
-
- let speculator = &self.decoding_config.speculator_config.speculator;
-
- let suffix_length = if sample_suffix {
- self.decoding_config.generate_suffix_length().saturating_sub(1).min(prefill_size - tokens_length)
- } else {
- prefill_size - tokens_length
- };
- let suffix_root = TrieNode::from_speculator(
- &tokens,
- &self.context.seed,
- compiled_grammar.as_deref_mut(),
- speculator.as_ref(),
- self.context.model_shape.vocabulary_size,
- &TrieCreationConfig::default(),
- suffix_length + 1,
- );
- let flat_trie = suffix_root.linearize();
-
- let has_grammar = compiled_grammar.is_some();
-
- let token_ids =
- tokens.iter().copied().take(tokens_length - 1).chain(flat_trie.token_ids()).chunks(prefill_step_size);
-
- let token_subtrie_ranges = repeat_n(None, tokens_length - 1)
- .chain(flat_trie.token_subtrie_ranges().map(Some))
- .chunks(prefill_step_size);
-
- let token_positions = (prefix_offset..prefix_offset + tokens_length - 1)
- .chain(flat_trie.token_positions().map(|trie_position| prefix_offset + tokens_length - 1 + trie_position))
- .chunks(prefill_step_size);
-
- let single_token_bitmask_size = self.context.model_shape.bitmask_shape(1)[1];
- let token_bitmasks = repeat_n(None, tokens_length - 1).chain(flat_trie.token_masks()).chunks(prefill_step_size);
-
- let token_seeds = repeat_n(0, tokens_length - 1).chain(flat_trie.token_seeds()).chunks(prefill_step_size);
-
- let mut last_sampling_output: Option<Allocation<B>> = None;
- let mut last_sampling_length = 0;
- let mut run_times: Vec<f64> = Vec::new();
-
- // Process each prefill step and update the KV cache.
- for (
- step,
- (step_token_ids, step_token_subtrie_ranges, step_token_positions, step_token_bitmasks, step_token_seeds),
- ) in izip!(&token_ids, &token_subtrie_ranges, &token_positions, &token_bitmasks, &token_seeds).enumerate()
- {
- let tokens_start_index = step * prefill_step_size;
- let tokens_end_index = tokens_start_index + prefill_step_size;
-
- let step_token_ids = step_token_ids.collect::<Box<[u64]>>();
- let step_token_subtrie_ranges = step_token_subtrie_ranges.collect::<Box<[Option<[u32; 3]>]>>();
- let step_token_subtrie_ranges: Option<Box<[[u32; 3]]>> =
- step_token_subtrie_ranges.iter().position(|e| e.is_some()).map(|trie_start| {
- step_token_subtrie_ranges
- .iter()
- .enumerate()
- .map(|(i, me)| {
- if let Some([subtrie_start, subtrie_end, height]) = me {
- [
- trie_start as u32 + subtrie_start,
- trie_start as u32 + subtrie_end,
- trie_start as u32 + height,
- ]
- } else {
- [i as u32, step_token_subtrie_ranges.len() as u32 - 1, i as u32]
- }
- })
- .collect()
- });
- let step_token_positions = step_token_positions.collect::<Box<[usize]>>();
- let step_token_seeds = step_token_seeds.collect::<Box<[u64]>>();
-
- let active_row_count = step_token_positions.len();
- let is_last_prefill_step = step == prefill_steps - 1;
- let should_sample_after_step = sample_suffix && is_last_prefill_step;
-
- // If we sample on the last prefill step, we only need logits/sampling
- // for tokens that are beyond the prompt prefix (i.e. starting at the
- // suffix-root token, which is the last prompt token).
- let (sampling_start, sampling_length) = if should_sample_after_step {
- let suffix_root_index_in_step = (tokens_length - 1).saturating_sub(tokens_start_index);
- let sampling_length = active_row_count.saturating_sub(suffix_root_index_in_step);
- debug_assert!(sampling_length > 0, "Expected at least one token to sample on the last prefill step");
- (suffix_root_index_in_step, sampling_length)
- } else {
- (0, 0)
- };
-
- let step_token_bitmask: Option<Box<[u32]>> = if has_grammar && sampling_length > 0 {
- Some(
- step_token_bitmasks
- .flat_map(|mask| match mask {
- Some(mask) => Either::Left(
- mask.iter()
- .copied()
- .take(single_token_bitmask_size)
- .chain(repeat_n(0u32, single_token_bitmask_size.saturating_sub(mask.len()))),
- ),
- None => Either::Right(repeat_n(u32::MAX, single_token_bitmask_size)),
- })
- .collect::<Box<[u32]>>(),
- )
- } else {
- // Drain the chunk iterator to keep the other chunked iterators aligned.
- let _ = step_token_bitmasks.count();
- None
- };
-
- let should_capture = self.gpu_capture.should_capture_prefill(step == 0);
-
- if should_capture {
- self.gpu_capture
- .start_capture(&self.context.context, "prefill")
- .map_err(|error| Error::CaptureFailed(Box::new(error)))?;
- }
-
- let _ = last_sampling_output.take();
-
- let task = Task {
- token_ids: step_token_ids,
- token_subtrie_ranges: step_token_subtrie_ranges,
- token_positions: step_token_positions,
- token_bitmask: step_token_bitmask,
- token_seeds: step_token_seeds,
- active_row_count,
- sampling_start,
- sampling_length,
- is_prefilling: !should_sample_after_step,
- };
-
- let run_result = self.run_model(task, sampling_method)?;
- if should_capture {
- self.gpu_capture
- .stop_capture(&self.context.context, "prefill")
- .map_err(|error| Error::CaptureFailed(Box::new(error)))?;
- }
-
- // Register the accepted prompt tokens from this step.
- let step_end_token_index = std::cmp::min(tokens_end_index, tokens_length);
- let mut tokens_processed_this_step = step_end_token_index - tokens_start_index;
-
- if step == prefill_steps - 1 && sample_suffix {
- tokens_processed_this_step = tokens_processed_this_step.saturating_sub(1);
- }
-
- if tokens_processed_this_step > 0 {
- self.update_cache_layers(&(0..tokens_processed_this_step).collect::<Vec<usize>>(), None, true)?;
-
- self.context.cache_layers.borrow_mut().register_accepted_tokens(tokens_processed_this_step);
-
- self.registered_prefix_len = prefix_offset + tokens_start_index + tokens_processed_this_step;
- }
-
- last_sampling_length = sampling_length;
- last_sampling_output = run_result.sampling_output;
- run_times.push(run_result.cpu_run_time);
- }
-
- let final_sampling_output = last_sampling_output;
- if !sample_suffix {
- self.sync_prefix();
- return Ok(PrefillResult {
- tokens: Vec::new(),
- forwardpass_durations: run_times,
- });
- }
- let sampled_tokens = self.read_sampling_output(
- final_sampling_output.as_ref().expect("sampling output must exist"),
- last_sampling_length,
- )?;
-
- let last_suffix_start = prefill_step_size * (prefill_steps - 1);
- let suffix_root_index = (tokens_length - last_suffix_start) - 1;
-
- let (accepted_tokens, accepted_token_indices) = flat_trie.accept(&sampled_tokens, compiled_grammar);
-
- self.update_cache_layers(
- &accepted_token_indices.into_iter().map(|p| suffix_root_index + p).collect::<Box<[usize]>>(),
- Some(last_suffix_start),
- false,
- )?;
-
- self.tokens.extend(accepted_tokens.clone());
- self.sync_prefix();
-
- Ok(PrefillResult {
- tokens: accepted_tokens,
- forwardpass_durations: run_times,
- })
- }
-
- fn generate(
- &mut self,
- mut compiled_grammar: Option<&mut (dyn CompiledGrammar + 'static)>,
- sampling_method: SamplingMethod,
- ) -> Result<GenerateResult, Error> {
- let speculator = &self.decoding_config.speculator_config.speculator;
- let suffix_length = self.decoding_config.generate_suffix_length();
- let suffix_root = TrieNode::from_speculator(
- &self.tokens,
- &self.context.seed,
- compiled_grammar.as_deref_mut(),
- speculator.as_ref(),
- self.context.model_shape.vocabulary_size,
- &TrieCreationConfig::default(),
- suffix_length,
- );
- let flat_trie = suffix_root.linearize();
-
- let task = self.get_generate_task(&flat_trie, compiled_grammar.is_some());
-
- let active_row_count = task.active_row_count;
- let sampling_length = task.sampling_length;
- let run_result = self.run_model(task, sampling_method)?;
- let sampled_tokens = self.read_sampling_output(
- run_result.sampling_output.as_ref().expect("sampling output must exist"),
- sampling_length,
- )?;
-
- let (accepted_tokens, accepted_token_indices) = flat_trie.accept(&sampled_tokens, compiled_grammar);
- let speculator_proposed = active_row_count.saturating_sub(1);
- let speculator_accepted = accepted_tokens.len().saturating_sub(1);
-
- self.update_cache_layers(&accepted_token_indices, None, false)?;
-
- self.tokens.extend(accepted_tokens.clone());
- self.sync_prefix();
-
- Ok(GenerateResult {
- tokens: accepted_tokens,
- forwardpass_duration: run_result.cpu_run_time,
- speculator_proposed,
- speculator_accepted,
- })
- }
-
- /// Prepares async buffers for generation.
- /// Must be called after prefill, before async_generate loop.
- fn prepare_async(
- &mut self,
- tokens_to_generate: usize,
- ) {
- let prefill_count = self.tokens.len();
-
- self.context.async_buffers.prepare_positions(prefill_count, tokens_to_generate);
- self.context.async_buffers.prepare_seeds(&self.context.seed, prefill_count, tokens_to_generate);
- self.context.async_buffers.reset_counter();
- self.async_in_flight = (0..self.context.async_buffers.batch_size).map(|_| None).collect();
- self.async_token_ids = None;
- }
-
- /// Submits a single async forward pass.
- /// Does NOT block (except when GPU capture is enabled for the first decode).
- ///
- /// - `pass_idx`: Index of this pass (0, 1, 2, ...)
- /// - `sampling_method`: Sampling configuration
- /// - `on_complete`: Callback receiving sampled token as u64
- fn async_generate(
- &mut self,
- pass_idx: usize,
- sampling_method: SamplingMethod,
- on_complete: Box<dyn FnOnce(u64) + Send>,
- ) -> Result<(), Error> {
- assert_eq!(self.decoding_config.generate_suffix_length(), 1, "async_generate only supports suffix_length=1");
-
- // Extract values from async_buffers before mutable borrow
- let current_counter = self.context.async_buffers.counter.get();
- let is_continuation = current_counter > 0;
- let batch_size = self.context.async_buffers.batch_size;
- let slot = pass_idx % batch_size;
-
- let last_token = *self.tokens.last().ok_or(Error::PrefillFailed)?;
- let token_position = self.context.async_buffers.positions.as_slice::<i32>()[pass_idx] as usize;
- let token_seed = self.context.async_buffers.seeds.as_slice::<u64>()[pass_idx];
-
- let task = Task {
- token_ids: Box::new([last_token]),
- token_subtrie_ranges: None,
- token_positions: Box::new([token_position]),
- token_bitmask: None,
- token_seeds: Box::new([0]), // Ignored, using async buffer
- active_row_count: 1,
- sampling_start: 0,
- sampling_length: 1,
- is_prefilling: false,
- };
-
- let token_ids_array = if pass_idx > 0 {
- Some(self.async_token_ids.take().expect("previous async pass must provide token_ids array"))
- } else {
- None
- };
- let sampling_seed = [token_seed];
- let mut sampling_seeds = self
- .context
- .context
- .create_allocation(std::mem::size_of_val(&sampling_seed), AllocationType::Global)
- .expect("Failed to create sampling seed allocation");
- sampling_seeds.copyin(&sampling_seed);
- let repetition_penalty = Self::repetition_penalty_config(sampling_method);
- if pass_idx == 0
- && let Some((_, suffix_repetition_length)) = repetition_penalty
- {
- let capacity = self.context.async_buffers.repetition_context_ring_capacity;
- Self::copy_repetition_context_ring(
- &mut self.context.async_buffers.repetition_context_ring,
- &self.tokens,
- suffix_repetition_length,
- capacity,
- );
- }
- let sampling_context_ring =
- repetition_penalty.as_ref().map(|_| &self.context.async_buffers.repetition_context_ring);
-
- let is_first_decode = !is_continuation;
- let should_capture = self.gpu_capture.should_capture_decode(is_first_decode);
- if should_capture {
- self.gpu_capture
- .start_capture(&self.context.context, "decode")
- .map_err(|error| Error::CaptureFailed(Box::new(error)))?;
- }
-
- let batch_dim = task.active_row_count;
- let sampling_start = task.sampling_start;
- let sampling_length = task.sampling_length;
- let token_inputs = self.build_token_inputs(task, token_ids_array);
- let mut encoder = Encoder::<B>::new(self.context.context.as_ref())
- .map_err(|e| Error::UnableToCreateCommandBuffer(e.into()))?;
- let resources = Self::encode_forward_pass_on(
- &self.context,
- &mut encoder,
- token_inputs,
- batch_dim,
- sampling_start,
- sampling_length,
- false,
- Some(sampling_method),
- Some(sampling_seeds),
- None,
- sampling_context_ring,
- )?;
-
- // Copy sampled token: sampling_output → token_ids (for next pass)
- let token_ids_shape = [1];
- let token_ids_data_type = DataType::U64;
- let mut async_token_ids_allocation =
- self.context.context.create_array_uninitialized(&token_ids_shape, token_ids_data_type).into_allocation();
- let async_token_ids_buffer_range = async_token_ids_allocation.as_buffer_range_ref();
- let async_token_ids_range = async_token_ids_buffer_range.range();
- let async_token_ptr = SendPtr(unsafe {
- (async_token_ids_buffer_range.buffer().cpu_ptr().as_ptr() as *const u64)
- .add(async_token_ids_range.start / std::mem::size_of::<u64>())
- });
- if let Some((_, suffix_repetition_length)) = repetition_penalty {
- self.context.token_copy_sampled_context_ring.encode(
- resources.sampling_output.as_ref().expect("Sampling output must exist"),
- &mut async_token_ids_allocation,
- Some(&mut self.context.async_buffers.repetition_context_ring),
- Some(suffix_repetition_length as u32),
- &mut encoder,
- );
- } else {
- self.context.token_copy_sampled.encode(
- resources.sampling_output.as_ref().expect("Sampling output must exist"),
- &mut async_token_ids_allocation,
- None::<&mut Allocation<B>>,
- None,
- &mut encoder,
- );
- }
- self.async_token_ids = Some(unsafe {
- Array::from_allocation(async_token_ids_allocation, 0, &token_ids_shape, token_ids_data_type)
- });
-
- // Scatter + register for all transformer layers
- self.context.cache_layers.borrow_mut().update_after_acceptance(
- &[0],
- None,
- &self.context.context,
- &mut encoder,
- &self.context.kv_cache_update,
- );
- self.context.cache_layers.borrow_mut().register_accepted_tokens(1);
-
- // Add completion handler
- let handler = move |result: Result<&<B::CommandBuffer as CommandBuffer>::Completed, B::Error>| {
- result.expect("async decoding forward pass completed with error");
- let token = unsafe { *async_token_ptr.as_ptr() };
- on_complete(token);
- };
-
- encoder.add_completion_handler(handler);
-
- let pending = encoder.end_encoding().submit();
-
- if should_capture {
- let completed = pending.wait_until_completed().map_err(|e| Error::CommandBufferFailed(Box::new(e)))?;
- drop(resources);
- drop(completed);
- self.gpu_capture
- .stop_capture(&self.context.context, "decode")
- .map_err(|error| Error::CaptureFailed(Box::new(error)))?;
- } else {
- assert!(self.async_in_flight[slot].is_none(), "async slot {slot} still holds an in-flight state");
- self.async_in_flight[slot] = Some(InFlightForwardPass {
- resources,
- pending,
- });
- }
-
- Ok(())
- }
-
- fn finish_async(
- &mut self,
- pass_idx: usize,
- ) {
- let slot = pass_idx % self.context.async_buffers.batch_size;
- if let Some(in_flight) = self.async_in_flight[slot].take() {
- let InFlightForwardPass {
- resources,
- pending,
- } = in_flight;
- drop((resources, pending));
- }
- }
-
- fn reset_state(&mut self) {
- self.context.cache_layers.borrow_mut().clear(self.context.context.as_ref());
- self.tokens.clear();
- self.registered_prefix_len = 0;
- self.async_in_flight.clear();
- self.async_token_ids = None;
- self.gpu_capture.reset();
-
- let seed = self.decoding_config.sampling_seed.resolve();
- self.context.seed = PRng::new(seed);
- self.context.async_buffers.reset_counter();
- }
-
- fn peak_memory_usage(&self) -> Option<usize> {
- self.context.context.peak_memory_usage()
- }
-
- fn activation_data_type(&self) -> DataType {
- self.context.model_shape.data_type
- }
-
- fn tokens_len(&self) -> usize {
- self.tokens.len()
- }
- fn tokens_push(
- &mut self,
- token: u64,
- ) {
- self.tokens.push(token);
- }
- fn generate_suffix_length(&self) -> usize {
- self.decoding_config.generate_suffix_length()
- }
- fn async_batch_size(
- &self,
- model_path: &Path,
- ) -> Result<usize, Error> {
- self.decoding_config
- .async_batch_size
- .resolve::<B>(model_path, self.context.context.as_ref())
- .map_err(|error| Error::UnableToLoadWeights(Box::new(error)))
- }
-
- fn get_slice(
- &self,
- range: Range<usize>,
- ) -> Option<Box<dyn Any>> {
- self.context.cache_layers.borrow().slice(&self.context.context, range).map(|s| Box::new(s) as Box<dyn Any>)
- }
- fn apply_slice(
- &mut self,
- slice: &dyn Any,
- range: Range<usize>,
- ) {
- let slice = slice.downcast_ref::<CacheLayersSlice<B>>().unwrap();
- self.context.cache_layers.borrow_mut().apply_slice(&self.context.context, slice, Some(range));
- }
-
- fn build_llm_context(&self) -> Box<dyn Any> {
- let cache_layers = self.context.cache_layers.borrow().clone(&self.context.context);
- let context = LlmContext::new(self.tokens.clone(), cache_layers, self.decoding_config.clone());
- Box::new(context)
- }
- fn reconfigure_from_context(
- &mut self,
- context: &dyn Any,
- ) {
- let ctx = context.downcast_ref::<LlmContext<B>>().unwrap();
- self.context.cache_layers.borrow_mut().copy_from(&ctx.cache_layers, self.context.context.as_ref());
- self.tokens = ctx.tokens.clone();
- self.registered_prefix_len = self.tokens.len().saturating_sub(1);
- }
-
- fn get_context_length(&self) -> usize {
- self.context.get_context_length(&self.decoding_config)
- }
-}
-
-impl<B: Backend> LanguageModelGenerator<B> {
- pub fn new(
- model_path: &Path,
- decoding_config: DecodingConfig,
- model_config: &LanguageModelConfig,
- ) -> Result<Self, Error> {
- let gpu_capture = GpuCaptureManager::new();
-
- let context = LanguageModelGeneratorContext::new(model_path, &decoding_config, model_config)?;
-
- let mut generator = Self {
- decoding_config,
- tokens: Vec::new(),
- context,
- async_in_flight: Vec::new(),
- async_token_ids: None,
- registered_prefix_len: 0,
- gpu_capture,
- };
- generator.warmup();
- Ok(generator)
- }
-
- fn warmup(&mut self) {
- if let Err(error) = self.run_warmup() {
- eprintln!("uzu: model warmup skipped (kernels will compile on first use): {error}");
- }
- self.reset_state();
- }
-
- fn run_warmup(&mut self) -> Result<(), Error> {
- let context_length = self.context.get_context_length(&self.decoding_config);
- let first = 64.min(context_length.saturating_sub(1)).max(1);
- self.prefill(vec![0u64; first], None, SamplingMethod::Greedy, 0, true)?;
- self.generate(None, SamplingMethod::Greedy)?;
- for &len in &[65usize, 16] {
- let offset = self.tokens.len();
- if offset + len >= context_length {
- break;
- }
- self.prefill(vec![0u64; len], None, SamplingMethod::Greedy, offset, false)?;
- }
- Ok(())
- }
-
- fn repetition_penalty_config(sampling_method: SamplingMethod) -> Option<(f32, usize)> {
- match sampling_method {
- SamplingMethod::Stochastic {
- repetition_penalty: Some(repetition_penalty),
- suffix_repetition_length,
- ..
- } => Some((
- repetition_penalty,
- suffix_repetition_length.expect("suffix_repetition_length is required for repetition_penalty"),
- )),
- _ => None,
- }
- }
-
- fn copy_repetition_context_ring(
- context_ring: &mut Allocation<B>,
- tokens: &[u64],
- suffix_repetition_length: usize,
- capacity: usize,
- ) {
- let ring_length = tokens.len().min(suffix_repetition_length);
- let mut packed_ring = vec![0u32; 2 + capacity];
- packed_ring[1] = ring_length as u32;
- for (index, token) in tokens[tokens.len() - ring_length..].iter().enumerate() {
- packed_ring[2 + index] = *token as u32;
- }
- context_ring.copyin(&packed_ring);
- }
-
- pub fn get_generate_task(
- &self,
- flat_trie: &FlatTrie,
- has_grammar: bool,
- ) -> Task {
- let suffix_length = self.decoding_config.generate_suffix_length();
- let active_row_count = flat_trie.len();
-
- let token_ids = flat_trie.token_ids().chain(repeat_n(0, suffix_length - active_row_count)).collect();
-
- let token_subtrie_ranges = flat_trie
- .token_subtrie_ranges()
- .chain(repeat_n([u32::MAX, u32::MAX, u32::MAX], suffix_length - active_row_count))
- .collect();
-
- let token_bitmask: Option<Box<[u32]>> = has_grammar.then(|| {
- let single_token_bitmask_size = self.context.model_shape.bitmask_shape(1)[1];
- flat_trie
- .token_masks()
- .chain(repeat_n(None, suffix_length - active_row_count))
- .flat_map(|mask| match mask {
- Some(mask) => Either::Left(
- mask.iter()
- .copied()
- .take(single_token_bitmask_size)
- .chain(repeat_n(0u32, single_token_bitmask_size.saturating_sub(mask.len()))),
- ),
- None => Either::Right(repeat_n(u32::MAX, single_token_bitmask_size)),
- })
- .collect::<Box<[u32]>>()
- });
-
- let start_position = self.tokens.len() - 1;
- let token_positions = flat_trie
- .token_positions()
- .map(|trie_position| start_position + trie_position)
- .chain(repeat_n(INVALID_POSITION, suffix_length - active_row_count))
- .collect();
-
- let token_seeds = flat_trie.token_seeds().chain(repeat_n(0, suffix_length - active_row_count)).collect();
-
- Task {
- token_ids,
- token_subtrie_ranges: Some(token_subtrie_ranges),
- token_positions,
- token_bitmask,
- token_seeds,
- active_row_count,
- sampling_start: 0,
- sampling_length: active_row_count,
- is_prefilling: false,
- }
- }
-
- pub fn run_model(
- &mut self,
- task: Task,
- sampling_method: SamplingMethod,
- ) -> Result<RunModelResult<B>, Error> {
- let run_start = Instant::now();
- let sample = !task.is_prefilling;
- let is_prefilling = task.is_prefilling;
- let batch_dim = task.active_row_count;
- let sampling_start = task.sampling_start;
- let sampling_length = task.sampling_length;
- let repetition_penalty = if sample {
- Self::repetition_penalty_config(sampling_method)
- } else {
- None
- };
- let sampling_context_ring = if let Some((_, suffix_repetition_length)) = repetition_penalty {
- let mut allocation = self
- .context
- .context
- .create_allocation((2 + suffix_repetition_length) * size_of::<u32>(), AllocationType::Global)
- .map_err(|e| Error::UnableToCreateContext(e.into()))?;
- Self::copy_repetition_context_ring(
- &mut allocation,
- &self.tokens,
- suffix_repetition_length,
- suffix_repetition_length,
- );
- Some(allocation)
- } else {
- None
- };
- let (sampling_seeds, sampling_bitmask) = if sample {
- let seeds = &task.token_seeds[task.sampling_start..task.sampling_start + task.sampling_length];
- let mut seed_allocation = self
- .context
- .context
- .create_allocation(std::mem::size_of_val(seeds), AllocationType::Global)
- .expect("Failed to create sampling seed allocation");
- seed_allocation.copyin(seeds);
-
- let bitmask_allocation = task.token_bitmask.as_deref().map(|mask| {
- let row_len = self.context.model_shape.bitmask_shape(1)[1];
- let start = task.sampling_start * row_len;
- let end = start + task.sampling_length * row_len;
- let bitmask = &mask[start..end];
- let mut allocation = self
- .context
- .context
- .create_allocation(std::mem::size_of_val(bitmask), AllocationType::Global)
- .expect("Failed to create sampling bitmask allocation");
- allocation.copyin(bitmask);
- allocation
- });
-
- (Some(seed_allocation), bitmask_allocation)
- } else {
- (None, None)
- };
-
- let is_first_decode = task.token_ids.len() == 1;
- let should_capture = self.gpu_capture.should_capture_decode(is_first_decode);
- let token_inputs = self.build_token_inputs(task, None);
-
- if should_capture {
- self.gpu_capture
- .start_capture(&self.context.context, "decode")
- .map_err(|error| Error::CaptureFailed(Box::new(error)))?;
- }
-
- let mut encoder = Encoder::<B>::new(self.context.context.as_ref())
- .map_err(|e| Error::UnableToCreateCommandBuffer(e.into()))?;
- let resources = Self::encode_forward_pass_on(
- &self.context,
- &mut encoder,
- token_inputs,
- batch_dim,
- sampling_start,
- sampling_length,
- is_prefilling,
- sample.then_some(sampling_method),
- sampling_seeds,
- sampling_bitmask,
- sampling_context_ring.as_ref(),
- )?;
-
- let pending = encoder.end_encoding().submit();
-
- let completed = pending.wait_until_completed().map_err(|e| Error::CommandBufferFailed(Box::new(e)))?;
- let gpu_run_time = completed.gpu_execution_time();
- let ForwardPassResources {
- token_inputs,
- logits,
- sampling_output,
- sampling_seeds,
- sampling_bitmask,
- } = resources;
- drop((token_inputs, logits, sampling_seeds, sampling_bitmask));
- drop(completed);
-
- let run_time = run_start.elapsed().as_secs_f64();
-
- if should_capture {
- self.gpu_capture
- .stop_capture(&self.context.context, "decode")
- .map_err(|error| Error::CaptureFailed(Box::new(error)))?;
- }
-
- Ok(RunModelResult {
- sampling_output,
- cpu_run_time: run_time,
- gpu_run_time,
- })
- }
-
- fn encode_forward_pass_on(
- context: &LanguageModelGeneratorContext<B>,
- encoder: &mut Encoder<B>,
- token_inputs: TokenInputs<B>,
- batch_dim: usize,
- sampling_start: usize,
- sampling_length: usize,
- is_prefilling: bool,
- sampling_method: Option<SamplingMethod>,
- sampling_seeds: Option<Allocation<B>>,
- sampling_bitmask: Option<Allocation<B>>,
- sampling_context_ring: Option<&Allocation<B>>,
- ) -> Result<ForwardPassResources<B>, Error> {
- let mut sampling_output = None;
- let mut logits = None;
- if is_prefilling {
- let mut cache_layers = context.cache_layers.borrow_mut();
- cache_layers.prepare_for_forward_pass(&context.context, batch_dim);
- let decoder_arguments = token_inputs.decoder_arguments(
- Some(&mut *cache_layers),
- batch_dim,
- sampling_start,
- sampling_length,
- #[cfg(feature = "tracing")]
- None,
- );
- context
- .executables
- .encode_prefill(decoder_arguments, token_inputs.token_ids(), encoder)
- .map_err(|e| Error::EncodeFailed(Box::new(e)))?;
- } else {
- let mut cache_layers = context.cache_layers.borrow_mut();
- cache_layers.prepare_for_forward_pass(&context.context, batch_dim);
- let decoder_arguments = token_inputs.decoder_arguments(
- Some(&mut *cache_layers),
- batch_dim,
- sampling_start,
- sampling_length,
- #[cfg(feature = "tracing")]
- None,
- );
- let retained_logits = context
- .executables
- .encode_decode(decoder_arguments, DecoderDecodeInput::TokenIds(token_inputs.token_ids()), None, encoder)
- .map_err(|e| Error::EncodeFailed(Box::new(e)))?;
-
- let sampling_seeds = sampling_seeds.as_ref().expect("Sampling requires seeds");
- let output = context.gpu_sampler.encode(
- &retained_logits,
- Some(sampling_seeds),
- sampling_bitmask.as_ref(),
- sampling_context_ring,
- Some(token_inputs.token_ids()),
- sampling_method.expect("Sampling requires method"),
- sampling_length,
- encoder,
- );
- sampling_output = Some(output.map_err(|e| Error::EncodeFailed(Box::new(e)))?);
- logits = Some(retained_logits);
- }
-
- Ok(ForwardPassResources {
- token_inputs,
- logits,
- sampling_output,
- sampling_seeds,
- sampling_bitmask,
- })
- }
-
- fn build_token_inputs(
- &self,
- task: Task,
- token_ids_array: Option<Array<B>>,
- ) -> TokenInputs<B> {
- TokenInputs::new_llm(
- self.context.context.as_ref(),
- &self.context.model_shape,
- &task.token_ids,
- task.token_subtrie_ranges.as_deref(),
- &task.token_positions,
- token_ids_array,
- task.sampling_start,
- task.sampling_length,
- )
- }
-
- fn read_sampling_output(
- &self,
- sampling_output: &Allocation<B>,
- batch_size: usize,
- ) -> Result<Vec<u64>, Error> {
- let values = sampling_output.copyout::<u32>();
- Ok(values[..batch_size].iter().map(|value| u64::from(*value)).collect())
- }
-
- fn update_cache_layers(
- &mut self,
- accepted_token_indices: &[usize],
- suffix_start: Option<usize>,
- wait_until_completed: bool,
- ) -> Result<(), Error> {
- let mut encoder = Encoder::<B>::new(self.context.context.as_ref())
- .map_err(|e| Error::UnableToCreateCommandBuffer(e.into()))?;
-
- {
- let mut cache_layers = self.context.cache_layers.borrow_mut();
- cache_layers.update_after_acceptance(
- accepted_token_indices,
- suffix_start,
- &self.context.context,
- &mut encoder,
- &self.context.kv_cache_update,
- );
- }
-
- let pending = encoder.end_encoding().submit();
-
- if wait_until_completed {
- pending.wait_until_completed().map_err(|e| Error::CommandBufferFailed(Box::new(e)))?;
- }
- Ok(())
- }
-
- fn sync_prefix(&mut self) {
- if self.tokens.is_empty() {
- return;
- }
-
- let desired_prefix_len = self.tokens.len() - 1;
- if desired_prefix_len > self.registered_prefix_len {
- let number_of_accepted_tokens = desired_prefix_len - self.registered_prefix_len;
- self.context.cache_layers.borrow_mut().register_accepted_tokens(number_of_accepted_tokens);
- self.registered_prefix_len = desired_prefix_len;
- }
- }
-}
-
-#[cfg(test)]
-#[path = "../../unit/language_model/language_model_generator_bench.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/language_model/language_model_generator_context.rs b/crates/backend-uzu/src/language_model/language_model_generator_context.rs
deleted file mode 100644
index 3f5b4bdb8..000000000
--- a/crates/backend-uzu/src/language_model/language_model_generator_context.rs
+++ /dev/null
@@ -1,220 +0,0 @@
-use std::{
- cell::{Cell, RefCell},
- cmp::min,
- fs::File,
- mem::size_of,
- path::Path,
- rc::Rc,
-};
-
-use crate::{
- array::{Array, ArrayContextExt},
- backends::common::{Allocation, AllocationType, Backend, Context, Kernels, kernel::TokenCopySampledKernel},
- config::{decoder::DecoderConfig, model::language_model::LanguageModelConfig},
- data_type::DataType,
- encodable_block::{Decoder, KVCacheUpdate, Sampling},
- forward_pass::{cache_layers::CacheLayers, model_shape::ModelShape},
- language_model::rng::PRng,
- parameters::ParameterLoader,
- session::{
- config::DecodingConfig,
- parameter::{ConfigResolvableValue, ContextLength, ResolvableValue},
- types::Error,
- },
-};
-
-/// Pre-allocated state for async generation pipeline.
-/// Indexed by pass_idx to avoid race conditions between GPU passes.
-pub struct AsyncBuffers<B: Backend> {
- /// Positions array: [max_tokens] i32
- /// Pre-populated with [prefill_count, prefill_count+1, ...]
- pub positions: Array<B>,
- /// Seeds array: [max_tokens] u64
- /// Pre-populated with deterministic seed sequence
- pub seeds: Array<B>,
- /// Current event counter (pass N waits on N, signals N+1)
- pub counter: Cell<u64>,
- /// Number of tokens after prefill (base for position calculation)
- pub prefill_count: Cell<usize>,
- /// Batch size (number of passes to keep in flight)
- pub batch_size: usize,
- /// Packed [ring_offset, ring_length, token...].
- pub repetition_context_ring: Allocation<B>,
- pub repetition_context_ring_capacity: usize,
-}
-
-impl<B: Backend> AsyncBuffers<B> {
- pub fn new(
- context: &B::Context,
- max_tokens: usize,
- batch_size: usize,
- ) -> Self {
- let positions = context.create_array_uninitialized(&[max_tokens], DataType::I32);
- let seeds = context.create_array_uninitialized(&[max_tokens], DataType::U64);
- let repetition_context_ring_capacity = max_tokens;
- let repetition_context_ring = context
- .create_allocation((2 + repetition_context_ring_capacity) * size_of::<u32>(), AllocationType::Global)
- .expect("Failed to create repetition context ring allocation");
-
- Self {
- positions,
- seeds,
- counter: Cell::new(0),
- prefill_count: Cell::new(0),
- batch_size,
- repetition_context_ring,
- repetition_context_ring_capacity,
- }
- }
-
- /// Prepare positions buffer: [prefill_count-1, prefill_count, ...]
- /// Uses prefill_count-1 to match sync path which uses self.tokens.len()-1
- pub fn prepare_positions(
- &mut self,
- prefill_count: usize,
- tokens_to_generate: usize,
- ) {
- self.prefill_count.set(prefill_count);
- let base_position = prefill_count.saturating_sub(1);
- let positions = self.positions.as_slice_mut::<i32>();
- for (index, position) in positions.iter_mut().take(tokens_to_generate).enumerate() {
- *position = (base_position + index) as i32;
- }
- }
-
- /// Prepare seeds buffer with deterministic sequence
- pub fn prepare_seeds(
- &mut self,
- seed: &PRng,
- prefix_len: usize,
- tokens_to_generate: usize,
- ) {
- let seeds = self.seeds.as_slice_mut::<u64>();
- for (index, value) in seeds.iter_mut().take(tokens_to_generate).enumerate() {
- *value = seed.derive((prefix_len + index - 1) as u64);
- }
- }
-
- /// Reset event counter before async generation
- pub fn reset_counter(&self) {
- self.counter.set(0);
- }
-}
-
-pub struct LanguageModelGeneratorContext<B: Backend> {
- pub context: Rc<B::Context>,
-
- pub cache_layers: Rc<RefCell<CacheLayers<B>>>,
-
- pub model_config: LanguageModelConfig,
- pub model_shape: ModelShape,
- pub executables: Decoder<B>,
- pub kv_cache_update: Box<KVCacheUpdate<B>>,
- pub gpu_sampler: Sampling<B>,
- pub seed: PRng,
-
- /// Kernels for copying sampled tokens in async pipeline
- pub token_copy_sampled: <B::Kernels as Kernels>::TokenCopySampledKernel,
- pub token_copy_sampled_context_ring: <B::Kernels as Kernels>::TokenCopySampledKernel,
- /// Pre-allocated buffers for async generation
- pub async_buffers: AsyncBuffers<B>,
-}
-
-impl<B: Backend> LanguageModelGeneratorContext<B> {
- pub fn new(
- model_path: &Path,
- decoding_config: &DecodingConfig,
- model_config: &LanguageModelConfig,
- ) -> Result<Self, Error> {
- let context = B::Context::new().map_err(|e| Error::UnableToCreateContext(e.into()))?;
-
- let prefill_step_size = decoding_config.prefill_step_size.resolve(model_config);
- let generate_suffix_length = decoding_config.generate_suffix_length();
- let max_prefix_length: usize =
- Self::get_context_length_internal(&context, &model_config.decoder_config, decoding_config);
- let max_suffix_length: usize = std::cmp::max(prefill_step_size, generate_suffix_length);
-
- let weights_path = model_path.join("model.safetensors");
- let weights_file = File::open(&weights_path).map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let loader = ParameterLoader::new(&weights_file, context.as_ref())
- .map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let root_loader_view =
- loader.tree().subtree("decoder").map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let model_shape = ModelShape::from_decoder_config(&model_config.decoder_config, DataType::BF16);
-
- let executables = Decoder::new(context.as_ref(), &model_config.decoder_config, &root_loader_view, &model_shape)
- .map_err(|error| Error::UnableToCreateDecoder(Box::new(error)))?;
-
- let cache_layers = Rc::new(RefCell::new(CacheLayers::new(
- context.as_ref(),
- &model_shape,
- max_prefix_length,
- max_suffix_length,
- )));
-
- let kv_cache_update = Box::new(
- KVCacheUpdate::new(context.as_ref(), model_shape.data_type, max_prefix_length)
- .map_err(|e| Error::UnableToCreateContext(e.into()))?,
- );
-
- let gpu_sampler = Sampling::<B>::new(model_shape.data_type, model_config.decoder_config.vocab_size);
-
- let token_copy_sampled = <B::Kernels as Kernels>::TokenCopySampledKernel::new(&context, false)
- .map_err(|e| Error::UnableToCreateContext(e.into()))?;
- let token_copy_sampled_context_ring = <B::Kernels as Kernels>::TokenCopySampledKernel::new(&context, true)
- .map_err(|e| Error::UnableToCreateContext(e.into()))?;
-
- let async_batch_size = decoding_config
- .async_batch_size
- .resolve::<B>(model_path, context.as_ref())
- .map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let async_buffers = AsyncBuffers::new(context.as_ref(), max_prefix_length, async_batch_size);
-
- loader.tree().assert_all_tensors_validated().map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
-
- let seed = PRng::new(decoding_config.sampling_seed.resolve());
-
- Ok(Self {
- context,
- cache_layers,
- model_config: model_config.clone(),
- model_shape,
- executables,
- kv_cache_update,
- gpu_sampler,
- seed,
- token_copy_sampled,
- token_copy_sampled_context_ring,
- async_buffers,
- })
- }
-
- pub fn get_context_length(
- &self,
- decoding_config: &DecodingConfig,
- ) -> usize {
- Self::get_context_length_internal(&self.context, &self.model_config.decoder_config, decoding_config)
- }
-
- fn get_context_length_internal(
- context: &B::Context,
- decoder_config: &DecoderConfig,
- decoding_config: &DecodingConfig,
- ) -> usize {
- let model_length = decoder_config.transformer_config.max_sequence_length().unwrap_or(65536);
- let proposed_value = match decoding_config.context_length {
- ContextLength::Default => {
- if context.sparse_buffers_supported() {
- model_length
- } else if cfg!(target_os = "ios") {
- 8192
- } else {
- 16384
- }
- },
- ContextLength::Maximal => model_length,
- ContextLength::Custom(value) => value,
- };
- min(proposed_value, model_length)
- }
-}
diff --git a/crates/backend-uzu/src/language_model/mod.rs b/crates/backend-uzu/src/language_model/mod.rs
deleted file mode 100644
index 187ac3bee..000000000
--- a/crates/backend-uzu/src/language_model/mod.rs
+++ /dev/null
@@ -1,10 +0,0 @@
-pub mod gpu_capture;
-pub mod grammar;
-pub mod gumbel;
-pub mod language_model_generator;
-pub mod language_model_generator_context;
-pub mod result;
-pub mod rng;
-
-// Re-export main types
-pub use language_model_generator::{LanguageModelGenerator, LanguageModelGeneratorTrait};
diff --git a/crates/backend-uzu/src/language_model/result.rs b/crates/backend-uzu/src/language_model/result.rs
deleted file mode 100644
index 6a6db174b..000000000
--- a/crates/backend-uzu/src/language_model/result.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-#[derive(Debug, Clone)]
-pub struct PrefillResult {
- pub tokens: Vec<u64>,
- pub forwardpass_durations: Vec<f64>,
-}
-
-#[derive(Debug, Clone)]
-pub struct GenerateResult {
- pub tokens: Vec<u64>,
- pub forwardpass_duration: f64,
- pub speculator_proposed: usize,
- pub speculator_accepted: usize,
-}
diff --git a/crates/backend-uzu/src/lib.rs b/crates/backend-uzu/src/lib.rs
index f547874f4..b7f02056d 100644
--- a/crates/backend-uzu/src/lib.rs
+++ b/crates/backend-uzu/src/lib.rs
@@ -1,24 +1,21 @@
#![cfg_attr(test, feature(custom_test_frameworks, test))]
#![cfg_attr(test, test_runner(test_runner::uzu_harness))]
-pub mod array;
-mod audio;
-mod classifier;
+mod array;
mod config;
mod encodable_block;
-mod forward_pass;
-mod language_model;
mod parameters;
-mod speculators;
+pub mod speculators;
mod trie;
mod utils;
pub mod backends;
+pub mod bridge;
pub mod data_type;
-pub mod inference;
-pub mod session;
-pub use utils::{TOOLCHAIN_VERSION, VERSION};
+pub mod engine;
+
+pub use utils::version::{TOOLCHAIN_VERSION, VERSION};
// needed for tests to resolve `backend_uzu::` imports
#[cfg(test)]
diff --git a/crates/backend-uzu/src/parameters/loader.rs b/crates/backend-uzu/src/parameters/loader.rs
index aa2d98e8f..db557a47c 100644
--- a/crates/backend-uzu/src/parameters/loader.rs
+++ b/crates/backend-uzu/src/parameters/loader.rs
@@ -8,7 +8,7 @@ use thiserror::Error;
use super::safetensors_metadata::{HeaderLoadingError, read_metadata as read_st_metadata};
use crate::{
- array::{Array, ArrayElement, size_for_shape},
+ array::{ArrayElement, size_for_shape},
backends::common::{Allocation, AllocationType, AsBufferRangeRef, Backend, Context, DenseBuffer},
data_type::DataType,
utils::{fs::file_read_exact_at, strict_serde::DeserializeStrictOwned},
@@ -180,12 +180,6 @@ impl<'a, 'leaf, B: Backend> ParameterLeaf<'a, 'leaf, B, true> {
)?;
Ok(allocation)
}
-
- #[allow(unused)]
- pub fn read_array(&self) -> Result<Array<B>, ParameterLoaderError<B>> {
- let allocation = self.read_allocation()?;
- Ok(unsafe { Array::from_allocation(allocation, 0, self.metadata.shape.as_ref(), self.metadata.data_type) })
- }
}
pub struct ParameterTree<'loader, B: Backend> {
@@ -265,7 +259,3 @@ impl<'loader, B: Backend> ParameterTree<'loader, B> {
}
}
}
-
-#[cfg(test)]
-#[path = "../../unit/parameters/loader.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/parameters/mod.rs b/crates/backend-uzu/src/parameters/mod.rs
index 394462308..420646214 100644
--- a/crates/backend-uzu/src/parameters/mod.rs
+++ b/crates/backend-uzu/src/parameters/mod.rs
@@ -1,6 +1,7 @@
+// TODO: This is overdue for a complete rewrite
+
mod loader;
mod safetensors_metadata;
pub use loader::{ParameterLoader, ParameterLoaderError, ParameterTree};
-#[cfg(all(test, feature = "tracing"))]
-pub use safetensors_metadata::read_metadata;
+pub use safetensors_metadata::HeaderLoadingError;
diff --git a/crates/backend-uzu/src/session/chat_session.rs b/crates/backend-uzu/src/session/chat_session.rs
deleted file mode 100644
index 12fadf11c..000000000
--- a/crates/backend-uzu/src/session/chat_session.rs
+++ /dev/null
@@ -1,686 +0,0 @@
-use std::{
- any::Any,
- path::PathBuf,
- sync::{
- Arc,
- atomic::{AtomicU64, Ordering},
- mpsc,
- },
- time::Instant,
-};
-
-use tokenizers::Tokenizer;
-
-use crate::{
- backends::{common::Backend, select_backend},
- config::{
- model::language_model::LanguageModelConfig, token_codec::AnyTokenCodecConfig, token_mixer::AnyTokenMixerConfig,
- },
- data_type::DataType,
- language_model::{
- LanguageModelGenerator, LanguageModelGeneratorTrait,
- grammar::{CompiledGrammar, create_compiled_grammar},
- result::{GenerateResult, PrefillResult},
- },
- session::{
- config::{DecodingConfig, RunConfig},
- helpers::{InputProcessor, InputProcessorDefault, OutputParser, is_directory_fits_ram},
- parameter::{ConfigResolvableValue, ContextMode, SamplingMethod},
- power_recorder::PowerRecorder,
- types::{Error, FinishReason, Input, Output, RunStats, Stats, StepStats, TotalStats},
- },
-};
-
-fn nanos_to_secs(nanos: u64) -> f64 {
- nanos as f64 / 1_000_000_000.0
-}
-
-struct RunContext {
- eos_tokens: Vec<u64>,
- context_length: usize,
- prefix_len_before: usize,
- input_tokens_len: usize,
- tokens_limit: usize,
- prefill_result: PrefillResult,
- prefill_duration: f64,
- prefill_suffix_length: usize,
- enable_thinking: bool,
- run_start: Instant,
-}
-
-pub struct ChatSession {
- pub model_path: PathBuf,
- pub model_config: LanguageModelConfig,
-
- tokenizer: Tokenizer,
- stop_token_ids: Vec<i32>,
- input_processor: Box<dyn InputProcessor>,
- output_parser: OutputParser,
- decoding_config: DecodingConfig,
- llm: Box<dyn LanguageModelGeneratorTrait>,
- static_context: Option<Box<dyn Any>>,
-}
-
-impl ChatSession {
- pub fn new(
- model_path: PathBuf,
- decoding_config: DecodingConfig,
- ) -> Result<Self, Error> {
- select_backend!(Self::new_with_backend::<B>(model_path, decoding_config), Error::UnableToOpenAnyBackend)
- }
-
- pub fn new_with_backend<B: Backend>(
- model_path: PathBuf,
- decoding_config: DecodingConfig,
- ) -> Result<Self, Error> {
- if !model_path.exists() {
- return Err(Error::ModelFolderNotFound);
- }
-
- if !is_directory_fits_ram(&model_path) {
- return Err(Error::NotEnoughMemory);
- }
-
- let model_config = LanguageModelConfig::new(&model_path)?;
- let layers = &model_config.decoder_config.transformer_config.layer_configs;
- let has_non_attention_mixer =
- layers.iter().any(|layer| !matches!(layer.mixer_config, AnyTokenMixerConfig::AttentionConfig(_)));
- let has_mamba_mixer =
- layers.iter().any(|layer| matches!(layer.mixer_config, AnyTokenMixerConfig::Mamba2Config(_)));
- if has_non_attention_mixer {
- match decoding_config.context_mode {
- ContextMode::None => {},
- ContextMode::Static {
- ..
- } => {
- return Err(Error::UnsupportedContextModeForModel);
- },
- ContextMode::Dynamic => {
- return Err(Error::UnsupportedContextModeForModel);
- },
- }
- }
-
- if has_mamba_mixer && decoding_config.speculator_config.number_of_speculated_tokens > 0 {
- return Err(Error::UnsupportedSpeculatorConfigForModel);
- }
-
- let tokenizer_path = model_path.join("tokenizer.json");
- let tokenizer = Tokenizer::from_file(&tokenizer_path).map_err(Error::UnableToLoadTokenizer)?;
-
- let AnyTokenCodecConfig::ChatCodecConfig(token_codec_config) = &model_config.token_codec_config else {
- return Err(Error::InvalidModelConfig("expected ChatCodecConfig token codec".to_string()));
- };
-
- let stop_token_ids: Vec<i32> =
- model_config.generation_config.stop_token_ids.iter().map(|&x| x as i32).collect();
-
- let input_processor = InputProcessorDefault::new(token_codec_config.clone());
-
- let output_parser = OutputParser::new(token_codec_config.output_parser_regex.clone())?;
-
- let llm = Box::new(LanguageModelGenerator::<B>::new(&model_path, decoding_config.clone(), &model_config)?);
-
- Ok(Self {
- model_path,
- model_config,
- tokenizer,
- stop_token_ids,
- input_processor: Box::new(input_processor),
- output_parser,
- decoding_config,
- llm,
- static_context: None,
- })
- }
-
- pub fn activation_data_type(&self) -> DataType {
- self.llm.activation_data_type()
- }
-
- pub fn run(
- &mut self,
- input: Input,
- config: RunConfig,
- progress: Option<impl Fn(Output) -> bool>,
- ) -> Result<Output, Error> {
- match &self.decoding_config.context_mode {
- ContextMode::None => {
- self.llm.reset_state();
- },
- ContextMode::Static {
- input,
- } => {
- if self.static_context.is_none() {
- let mut prefill_config = config.clone();
- prefill_config.tokens_limit = 0;
- let (_, ctx) = self.extend(input.clone(), None, prefill_config)?;
- self.static_context = Some(ctx);
- }
- let tmp = self.static_context.take();
- self.llm.reset_state();
- if let Some(ref ctx) = tmp {
- self.llm.reconfigure_from_context(ctx.as_ref());
- }
- self.static_context = tmp;
- },
- ContextMode::Dynamic => {},
- }
-
- let output = self.run_internal(input, config, progress)?;
-
- match &self.decoding_config.context_mode {
- ContextMode::None
- | ContextMode::Static {
- ..
- } => {
- self.llm.reset_state();
- },
- ContextMode::Dynamic => {},
- }
- Ok(output)
- }
-
- pub fn reset(&mut self) -> Result<(), Error> {
- self.llm.reset_state();
- Ok(())
- }
-
- fn extend(
- &mut self,
- input: Input,
- context: Option<&Box<dyn Any>>,
- config: RunConfig,
- ) -> Result<(Output, Box<dyn Any>), Error> {
- self.llm.reset_state();
- if let Some(ctx) = context {
- self.llm.reconfigure_from_context(ctx.as_ref());
- }
- let output = self.run_internal(input, config, None::<fn(Output) -> bool>)?;
- let new_context = self.llm.build_llm_context();
- self.llm.reset_state();
- Ok((output, new_context))
- }
-
- pub fn run_internal(
- &mut self,
- input: Input,
- config: RunConfig,
- progress: Option<impl Fn(Output) -> bool>,
- ) -> Result<Output, Error> {
- let run_start = Instant::now();
- let power_recorder = PowerRecorder::start();
- let text = self.input_processor.process(&input, config.enable_thinking, config.tokens_limit > 0)?;
- let tokens: Vec<u64> = self
- .tokenizer
- .encode(text.as_str(), false)
- .map_err(Error::UnableToEncodeText)?
- .get_ids()
- .iter()
- .map(|&id| id as u64)
- .collect();
-
- let language_model_generator = self.llm.as_mut();
- let context_length = language_model_generator.get_context_length();
- if tokens.len() >= context_length {
- return Err(Error::ContextLengthExceeded);
- }
-
- let prefix_offset = language_model_generator.tokens_len();
- let prefix_len_before = prefix_offset;
-
- let eos_tokens: Vec<u64> = self.model_config.generation_config.stop_token_ids.to_vec();
-
- let sampling_method = config.sampling_policy.resolve(&self.model_config);
-
- let mut compiled_grammar: Option<Box<dyn CompiledGrammar>> = if let Some(ref config) = config.grammar_config {
- Some(create_compiled_grammar(config, &self.tokenizer, Some(&self.stop_token_ids))?)
- } else {
- None
- };
-
- let prefill_start = Instant::now();
- let sample_suffix = config.tokens_limit > 0;
- let prefill_result = language_model_generator.prefill(
- tokens.clone(),
- compiled_grammar.as_deref_mut(),
- sampling_method,
- prefix_offset,
- sample_suffix,
- )?;
- let prefill_tokens = prefill_result.tokens.clone();
- let prefill_duration = prefill_start.elapsed().as_secs_f64();
-
- let prefill_suffix_length = self.decoding_config.prefill_step_size.resolve(&self.model_config);
-
- let run_context = RunContext {
- eos_tokens,
- context_length,
- prefix_len_before,
- input_tokens_len: tokens.len(),
- tokens_limit: config.tokens_limit as usize,
- prefill_result: prefill_result.clone(),
- prefill_duration,
- prefill_suffix_length,
- enable_thinking: config.enable_thinking,
- run_start,
- };
-
- let grammar_terminated = compiled_grammar.as_ref().map(|g| g.is_terminated()).unwrap_or(false);
-
- let prefill_finish_reason = if grammar_terminated {
- Some(FinishReason::Stop)
- } else {
- Self::check_finish_reason(&run_context, &*language_model_generator, &prefill_tokens)
- };
- let prefill_output = Self::build_output(
- &self.tokenizer,
- &self.output_parser,
- &run_context,
- &*language_model_generator,
- &[],
- &[],
- prefill_finish_reason.clone(),
- )?;
-
- let prefill_should_continue = if let Some(ref p) = progress {
- p(prefill_output.clone())
- } else {
- true
- };
-
- if !prefill_should_continue || prefill_finish_reason.is_some() {
- let output = if prefill_should_continue {
- prefill_output
- } else {
- prefill_output.with_finish_reason(Some(FinishReason::Cancelled))
- };
- return Ok(Self::attach_runtime_stats(
- output,
- run_start.elapsed().as_secs_f64(),
- language_model_generator.peak_memory_usage(),
- power_recorder,
- ));
- }
-
- let can_use_async = language_model_generator.generate_suffix_length() == 1 && compiled_grammar.is_none();
-
- let generate_output = if can_use_async {
- let batch_size = language_model_generator.async_batch_size(&self.model_path)?;
- Self::run_async_batch(
- &self.tokenizer,
- &self.output_parser,
- &run_context,
- language_model_generator,
- sampling_method,
- &progress,
- batch_size,
- )?
- } else {
- Self::run_sync_generate(
- &self.tokenizer,
- &self.output_parser,
- &run_context,
- language_model_generator,
- compiled_grammar.as_deref_mut(),
- sampling_method,
- &progress,
- )?
- };
-
- Ok(Self::attach_runtime_stats(
- generate_output,
- run_start.elapsed().as_secs_f64(),
- language_model_generator.peak_memory_usage(),
- power_recorder,
- ))
- }
-
- fn run_sync_generate(
- tokenizer: &Tokenizer,
- output_parser: &OutputParser,
- run_context: &RunContext,
- language_model_generator: &mut dyn LanguageModelGeneratorTrait,
- compiled_grammar: Option<&mut (dyn CompiledGrammar + 'static)>,
- sampling_method: SamplingMethod,
- progress: &Option<impl Fn(Output) -> bool>,
- ) -> Result<Output, Error> {
- let estimated_generate_capacity =
- Self::remaining_generate_tokens(run_context, language_model_generator.tokens_len());
- let mut generate_results: Vec<GenerateResult> = Vec::with_capacity(estimated_generate_capacity);
- let mut generate_durations: Vec<f64> = Vec::with_capacity(estimated_generate_capacity);
- let mut compiled_grammar_mut = compiled_grammar;
-
- loop {
- let generate_start = Instant::now();
- let generate_result =
- language_model_generator.generate(compiled_grammar_mut.as_deref_mut(), sampling_method)?;
- let generate_duration = generate_start.elapsed().as_secs_f64();
-
- let grammar_terminated = compiled_grammar_mut.as_ref().map(|g| g.is_terminated()).unwrap_or(false);
-
- let generate_finish_reason = if grammar_terminated {
- Some(FinishReason::Stop)
- } else {
- Self::check_finish_reason(run_context, language_model_generator, &generate_result.tokens)
- };
- generate_results.push(generate_result);
- generate_durations.push(generate_duration);
- let generate_output = Self::build_output(
- tokenizer,
- output_parser,
- run_context,
- language_model_generator,
- &generate_results,
- &generate_durations,
- generate_finish_reason.clone(),
- )?;
-
- let generate_should_continue = if let Some(progress_fn) = progress {
- progress_fn(generate_output.clone())
- } else {
- true
- };
-
- if !generate_should_continue || generate_finish_reason.is_some() {
- if generate_should_continue {
- return Ok(generate_output);
- } else {
- return Ok(generate_output.with_finish_reason(Some(FinishReason::Cancelled)));
- }
- }
- }
- }
-
- fn run_async_batch(
- tokenizer: &Tokenizer,
- output_parser: &OutputParser,
- run_context: &RunContext,
- llm: &mut dyn LanguageModelGeneratorTrait,
- sampling_method: SamplingMethod,
- progress: &Option<impl Fn(Output) -> bool>,
- batch_size: usize,
- ) -> Result<Output, Error> {
- let tokens_to_generate = Self::remaining_generate_tokens(run_context, llm.tokens_len());
-
- llm.prepare_async(tokens_to_generate);
-
- let (sender, receiver) = mpsc::channel::<(usize, u64, u64)>();
- let start_time = Instant::now();
- let last_nanos = Arc::new(AtomicU64::new(0));
-
- let mut results: Vec<GenerateResult> = Vec::with_capacity(tokens_to_generate);
- let mut durations: Vec<f64> = Vec::with_capacity(tokens_to_generate);
- let mut finish_reason = FinishReason::Length;
- let mut next_to_submit = 0;
- let mut in_flight = 0;
-
- while in_flight > 0 || next_to_submit < tokens_to_generate {
- let batch_end = std::cmp::min(next_to_submit + batch_size, tokens_to_generate);
- let batch_submitted = batch_end - next_to_submit;
- let accepted_before_batch = results.len();
-
- let cache_slice = llm.get_slice(0..batch_submitted);
-
- for idx in next_to_submit..batch_end {
- let batch_sender = sender.clone();
- let last_callback_nanos = last_nanos.clone();
- let batch_start_time = start_time;
- llm.async_generate(
- idx,
- sampling_method,
- Box::new(move |token| {
- let now_nanos = batch_start_time.elapsed().as_nanos() as u64;
- let prev_nanos = last_callback_nanos.swap(now_nanos, Ordering::SeqCst);
- let _ = batch_sender.send((idx, token, now_nanos.saturating_sub(prev_nanos)));
- }),
- )?;
- in_flight += 1;
- }
- next_to_submit = batch_end;
-
- for _ in 0..batch_submitted {
- let (idx, token, duration_nanos) = receiver.recv().map_err(|_| Error::SamplingFailed)?;
- in_flight -= 1;
- llm.finish_async(idx);
-
- let duration = nanos_to_secs(duration_nanos);
- llm.tokens_push(token);
- results.push(GenerateResult {
- tokens: vec![token],
- forwardpass_duration: duration,
- speculator_proposed: 0,
- speculator_accepted: 0,
- });
- durations.push(duration);
-
- let should_stop = if run_context.eos_tokens.contains(&token) {
- finish_reason = FinishReason::Stop;
- true
- } else if llm.tokens_len() >= run_context.context_length {
- finish_reason = FinishReason::ContextLimitReached;
- true
- } else if let Some(progress_fn) = progress {
- let output =
- Self::build_output(tokenizer, output_parser, run_context, llm, &results, &durations, None)?;
- if !progress_fn(output) {
- finish_reason = FinishReason::Cancelled;
- true
- } else {
- false
- }
- } else {
- false
- };
-
- if should_stop {
- while in_flight > 0 {
- let (idx, _, _) = receiver.recv().map_err(|_| Error::SamplingFailed)?;
- llm.finish_async(idx);
- in_flight -= 1;
- }
- if let Some(slice) = cache_slice {
- let accepted_in_batch = results.len().saturating_sub(accepted_before_batch);
- if accepted_in_batch < batch_submitted {
- llm.apply_slice(slice.as_ref(), accepted_in_batch..batch_submitted);
- }
- }
- return Self::build_output(
- tokenizer,
- output_parser,
- run_context,
- llm,
- &results,
- &durations,
- Some(finish_reason),
- );
- }
- }
- }
-
- Self::build_output(tokenizer, output_parser, run_context, llm, &results, &durations, Some(finish_reason))
- }
-
- fn remaining_generate_tokens(
- run_context: &RunContext,
- current_tokens_len: usize,
- ) -> usize {
- let remaining_by_limit = run_context.tokens_limit.saturating_sub(run_context.prefill_result.tokens.len());
- let remaining_by_context = run_context.context_length.saturating_sub(current_tokens_len);
- remaining_by_limit.min(remaining_by_context)
- }
-
- fn check_finish_reason(
- run_context: &RunContext,
- language_model_generator: &dyn LanguageModelGeneratorTrait,
- new_tokens: &[u64],
- ) -> Option<FinishReason> {
- let start_idx = run_context.prefix_len_before + run_context.input_tokens_len;
- let total_new_tokens = language_model_generator.tokens_len().saturating_sub(start_idx);
- let has_eos = new_tokens.iter().any(|t| run_context.eos_tokens.contains(t));
- let context_limit = language_model_generator.tokens_len() >= run_context.context_length;
-
- if has_eos {
- Some(FinishReason::Stop)
- } else if total_new_tokens >= run_context.tokens_limit {
- Some(FinishReason::Length)
- } else if context_limit {
- Some(FinishReason::ContextLimitReached)
- } else {
- None
- }
- }
-
- fn decode_generated_tokens(
- tokenizer: &Tokenizer,
- prefill_tokens: &[u64],
- generate_results: &[GenerateResult],
- ) -> Result<String, Error> {
- let generated_tokens: Vec<u32> = prefill_tokens
- .iter()
- .chain(generate_results.iter().flat_map(|r| r.tokens.iter()))
- .map(|&v| v as u32)
- .collect();
- tokenizer.decode(&generated_tokens, true).map_err(Error::UnableToDecodeText)
- }
-
- fn build_output(
- tokenizer: &Tokenizer,
- output_parser: &OutputParser,
- run_context: &RunContext,
- language_model_generator: &dyn LanguageModelGeneratorTrait,
- generate_results: &[GenerateResult],
- generate_durations: &[f64],
- finish_reason: Option<FinishReason>,
- ) -> Result<Output, Error> {
- let text = Self::decode_generated_tokens(tokenizer, &run_context.prefill_result.tokens, generate_results)?;
- let parsed = output_parser.parse(text, run_context.enable_thinking);
- let start_idx = run_context.prefix_len_before + run_context.input_tokens_len;
- let output_tokens = language_model_generator.tokens_len().saturating_sub(start_idx);
-
- Ok(Output {
- text: parsed,
- stats: Self::build_stats(
- &run_context.prefill_result,
- run_context.prefill_duration,
- run_context.prefill_suffix_length,
- generate_results,
- generate_durations,
- language_model_generator.generate_suffix_length(),
- run_context.run_start.elapsed().as_secs_f64(),
- run_context.input_tokens_len,
- output_tokens,
- ),
- finish_reason,
- })
- }
-
- fn build_stats(
- prefill_result: &PrefillResult,
- prefill_duration: f64,
- prefill_suffix_length: usize,
- generate_results: &[GenerateResult],
- generate_durations: &[f64],
- generate_suffix_length: usize,
- total_duration: f64,
- tokens_count_input: usize,
- tokens_count_output: usize,
- ) -> Stats {
- let prefill_stats = {
- let tokens_count = prefill_result.tokens.len();
- let tokens_per_second = tokens_count as f64 / prefill_duration;
-
- let processed_tokens = tokens_count_input + tokens_count;
- let processed_tokens_per_second = processed_tokens as f64 / prefill_duration;
-
- let model_run_count = prefill_result.forwardpass_durations.len();
- let model_run_average_duration =
- prefill_result.forwardpass_durations.iter().sum::<f64>() / model_run_count as f64;
-
- StepStats {
- duration: prefill_duration,
- suffix_length: prefill_suffix_length as u64,
- tokens_count: tokens_count as u64,
- tokens_per_second,
- processed_tokens_per_second,
- model_run: RunStats {
- count: model_run_count as u64,
- average_duration: model_run_average_duration,
- },
- run: None,
- speculator_proposed: 0,
- speculator_accepted: 0,
- }
- };
-
- let generate_stats = if !generate_results.is_empty() {
- let duration = generate_durations.iter().sum::<f64>();
- let tokens_count: usize = generate_results.iter().map(|result| result.tokens.len()).sum();
- let tokens_per_second: f64 = tokens_count as f64 / duration;
-
- let model_run_count = generate_results.len();
- let model_run_average_duration =
- generate_results.iter().map(|result| result.forwardpass_duration).sum::<f64>() / model_run_count as f64;
-
- let run_count = generate_durations.len();
- let run_average_duration = generate_durations.iter().sum::<f64>() / run_count as f64;
-
- let speculator_proposed: usize = generate_results.iter().map(|result| result.speculator_proposed).sum();
- let speculator_accepted: usize = generate_results.iter().map(|result| result.speculator_accepted).sum();
-
- Some(StepStats {
- duration,
- suffix_length: generate_suffix_length as u64,
- tokens_count: tokens_count as u64,
- tokens_per_second,
- processed_tokens_per_second: tokens_per_second,
- model_run: RunStats {
- count: model_run_count as u64,
- average_duration: model_run_average_duration,
- },
- run: Some(RunStats {
- count: run_count as u64,
- average_duration: run_average_duration,
- }),
- speculator_proposed: speculator_proposed as u64,
- speculator_accepted: speculator_accepted as u64,
- })
- } else {
- None
- };
-
- let total_stats = TotalStats {
- duration: total_duration,
- tokens_count_input: tokens_count_input as u64,
- tokens_count_output: tokens_count_output as u64,
- };
-
- Stats {
- prefill_stats,
- generate_stats,
- total_stats,
- memory_used_bytes: None,
- power_stats: None,
- }
- }
-
- fn attach_runtime_stats(
- mut output: Output,
- duration: f64,
- memory_used: Option<usize>,
- power_recorder: PowerRecorder,
- ) -> Output {
- output.stats.total_stats.duration = duration;
- output.stats.memory_used_bytes = memory_used.map(|value| value as u64);
- output.stats.power_stats = power_recorder.stop();
- output
- }
-
- pub fn peak_memory_usage(&self) -> Option<usize> {
- self.llm.peak_memory_usage()
- }
-}
-
-#[cfg(test)]
-#[path = "../../unit/session/chat_session.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/session/classification_session.rs b/crates/backend-uzu/src/session/classification_session.rs
deleted file mode 100644
index d9cb15a37..000000000
--- a/crates/backend-uzu/src/session/classification_session.rs
+++ /dev/null
@@ -1,75 +0,0 @@
-use std::{fs::File, io::BufReader, path::PathBuf};
-
-use tokenizers::Tokenizer;
-
-use crate::{
- backends::{common::Backend, select_backend},
- classifier::{ClassificationOutput, Classifier, ClassifierTrait},
- config::{model::classifier_model::ClassifierModelConfig, token_codec::AnyTokenCodecConfig},
- session::{
- helpers::{InputProcessor, InputProcessorDefault},
- types::{Error, Input},
- },
-};
-
-pub struct ClassificationSession {
- tokenizer: Tokenizer,
- classifier: Box<dyn ClassifierTrait>,
- input_processor: Box<dyn InputProcessor>,
-}
-
-impl ClassificationSession {
- pub fn new(model_path: PathBuf) -> Result<Self, Error> {
- select_backend!(Self::new_with_backend::<B>(model_path), Error::UnableToOpenAnyBackend)
- }
-
- pub fn new_with_backend<B: Backend>(model_path: PathBuf) -> Result<Self, Error> {
- if !model_path.exists() {
- return Err(Error::ModelFolderNotFound);
- }
-
- let config_path = model_path.join("config.json");
- let config_file = File::open(&config_path)?;
- let model_config: ClassifierModelConfig = serde_json::from_reader(BufReader::new(config_file))?;
-
- let tokenizer_path = model_path.join("tokenizer.json");
- let tokenizer = Tokenizer::from_file(&tokenizer_path).map_err(Error::UnableToLoadTokenizer)?;
-
- let AnyTokenCodecConfig::ChatCodecConfig(token_codec_config) = &model_config.token_codec_config else {
- return Err(Error::InvalidModelConfig("expected ChatCodecConfig token codec".to_string()));
- };
- let input_processor =
- Box::new(InputProcessorDefault::new(token_codec_config.clone())) as Box<dyn InputProcessor>;
- let classifier = Box::new(Classifier::<B>::new(&model_path, &model_config)?);
-
- Ok(Self {
- tokenizer,
- classifier,
- input_processor,
- })
- }
-
- pub fn classify(
- &mut self,
- input: Input,
- ) -> Result<ClassificationOutput, Error> {
- let preprocessing_start = std::time::Instant::now();
- let text = self.input_processor.process(&input, false, false)?;
- let tokens: Vec<u64> = self
- .tokenizer
- .encode(text.as_str(), false)
- .map_err(Error::UnableToEncodeText)?
- .get_ids()
- .iter()
- .map(|&id| id as u64)
- .collect();
-
- let token_positions: Vec<usize> = (0..tokens.len()).collect();
- let preprocessing_duration = preprocessing_start.elapsed().as_secs_f64();
-
- let mut output = self.classifier.classify_tokens(tokens, token_positions)?;
- output.stats.preprocessing_duration = preprocessing_duration;
-
- Ok(output)
- }
-}
diff --git a/crates/backend-uzu/src/session/config/decoding_config.rs b/crates/backend-uzu/src/session/config/decoding_config.rs
deleted file mode 100644
index c9a7976a1..000000000
--- a/crates/backend-uzu/src/session/config/decoding_config.rs
+++ /dev/null
@@ -1,100 +0,0 @@
-use crate::session::{
- config::SpeculatorConfig,
- parameter::{AsyncBatchSize, ContextLength, ContextMode, PrefillStepSize, SamplingSeed},
-};
-
-#[derive(Clone, Default)]
-pub struct DecodingConfig {
- pub context_mode: ContextMode,
- pub context_length: ContextLength,
- pub prefill_step_size: PrefillStepSize,
- pub speculator_config: SpeculatorConfig,
- pub sampling_seed: SamplingSeed,
- pub async_batch_size: AsyncBatchSize,
-}
-
-impl DecodingConfig {
- pub fn new(
- context_mode: ContextMode,
- context_length: ContextLength,
- prefill_step_size: PrefillStepSize,
- speculator_config: SpeculatorConfig,
- sampling_seed: SamplingSeed,
- async_batch_size: AsyncBatchSize,
- ) -> Self {
- Self {
- context_mode,
- context_length,
- prefill_step_size,
- speculator_config,
- sampling_seed,
- async_batch_size,
- }
- }
-
- pub fn generate_suffix_length(&self) -> usize {
- self.speculator_config.number_of_speculated_tokens + 1
- }
-}
-
-impl DecodingConfig {
- pub fn with_context_mode(
- &self,
- context_mode: ContextMode,
- ) -> Self {
- Self {
- context_mode,
- ..self.clone()
- }
- }
-
- pub fn with_context_length(
- &self,
- context_length: ContextLength,
- ) -> Self {
- Self {
- context_length,
- ..self.clone()
- }
- }
-
- pub fn with_prefill_step_size(
- &self,
- prefill_step_size: PrefillStepSize,
- ) -> Self {
- Self {
- prefill_step_size,
- ..self.clone()
- }
- }
-
- pub fn with_speculator_config(
- &self,
- speculator_config: SpeculatorConfig,
- ) -> Self {
- Self {
- speculator_config,
- ..self.clone()
- }
- }
-
- pub fn with_sampling_seed(
- &self,
- sampling_seed: SamplingSeed,
- ) -> Self {
- Self {
- sampling_seed,
- ..self.clone()
- }
- }
-
- pub fn with_async_batch_size(
- &self,
- async_batch_size: AsyncBatchSize,
- ) -> Self {
- Self {
- async_batch_size,
- ..self.clone()
- }
- }
-}
diff --git a/crates/backend-uzu/src/session/config/mod.rs b/crates/backend-uzu/src/session/config/mod.rs
deleted file mode 100644
index 0e4d54a53..000000000
--- a/crates/backend-uzu/src/session/config/mod.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-mod decoding_config;
-mod grammar_config;
-mod run_config;
-mod speculator_config;
-mod tts_run_config;
-mod tts_session_options;
-
-pub use decoding_config::DecodingConfig;
-pub use grammar_config::{GrammarConfig, StructuredOutput};
-pub use run_config::RunConfig;
-pub use speculator_config::SpeculatorConfig;
-pub use tts_run_config::{TtsChunkPolicy, TtsNonStreamingMode, TtsRunConfig, TtsRunConfigError};
-#[cfg(metal_backend)]
-pub use tts_session_options::TtsSessionOptions;
-pub use tts_session_options::{TextDecoderRuntimeConfig, TextSamplingConfig};
diff --git a/crates/backend-uzu/src/session/config/run_config.rs b/crates/backend-uzu/src/session/config/run_config.rs
deleted file mode 100644
index c364511c5..000000000
--- a/crates/backend-uzu/src/session/config/run_config.rs
+++ /dev/null
@@ -1,63 +0,0 @@
-use crate::session::{config::GrammarConfig, parameter::SamplingPolicy};
-
-#[derive(Debug, Clone)]
-pub struct RunConfig {
- pub tokens_limit: u64,
- pub enable_thinking: bool,
- pub sampling_policy: SamplingPolicy,
- pub grammar_config: Option<GrammarConfig>,
-}
-
-impl RunConfig {
- pub fn new(
- tokens_limit: u64,
- enable_thinking: bool,
- sampling_policy: SamplingPolicy,
- grammar_config: Option<GrammarConfig>,
- ) -> Self {
- Self {
- tokens_limit,
- enable_thinking,
- sampling_policy,
- grammar_config,
- }
- }
-
- pub fn tokens_limit(
- mut self,
- tokens_limit: u64,
- ) -> Self {
- self.tokens_limit = tokens_limit;
- self
- }
-
- pub fn enable_thinking(
- mut self,
- enable_thinking: bool,
- ) -> Self {
- self.enable_thinking = enable_thinking;
- self
- }
-
- pub fn sampling_policy(
- mut self,
- sampling_policy: SamplingPolicy,
- ) -> Self {
- self.sampling_policy = sampling_policy;
- self
- }
-
- pub fn grammar_config(
- mut self,
- grammar_config: GrammarConfig,
- ) -> Self {
- self.grammar_config = Some(grammar_config);
- self
- }
-}
-
-impl Default for RunConfig {
- fn default() -> Self {
- Self::new(1024, true, SamplingPolicy::Default, None)
- }
-}
diff --git a/crates/backend-uzu/src/session/config/speculator_config.rs b/crates/backend-uzu/src/session/config/speculator_config.rs
deleted file mode 100644
index 19e14c25c..000000000
--- a/crates/backend-uzu/src/session/config/speculator_config.rs
+++ /dev/null
@@ -1,33 +0,0 @@
-use std::sync::Arc;
-
-use crate::speculators::{empty_speculator::EmptySpeculator, speculator::Speculator};
-
-#[derive(Clone)]
-pub struct SpeculatorConfig {
- pub number_of_speculated_tokens: usize,
- pub speculator: Arc<dyn Speculator>,
-}
-
-impl SpeculatorConfig {
- pub fn new(
- number_of_speculated_tokens: usize,
- speculator: Arc<dyn Speculator>,
- ) -> Self {
- let max_number_of_speculated_tokens: usize = 64;
- let effective_number_of_speculated_tokens =
- std::cmp::min(number_of_speculated_tokens, max_number_of_speculated_tokens);
- Self {
- number_of_speculated_tokens: effective_number_of_speculated_tokens,
- speculator,
- }
- }
-}
-
-impl Default for SpeculatorConfig {
- fn default() -> Self {
- Self {
- number_of_speculated_tokens: 0,
- speculator: Arc::new(EmptySpeculator {}),
- }
- }
-}
diff --git a/crates/backend-uzu/src/session/config/tts_run_config.rs b/crates/backend-uzu/src/session/config/tts_run_config.rs
deleted file mode 100644
index e76a2081d..000000000
--- a/crates/backend-uzu/src/session/config/tts_run_config.rs
+++ /dev/null
@@ -1,188 +0,0 @@
-use thiserror::Error;
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum TtsChunkPolicy {
- Fixed,
- Adaptive,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum TtsNonStreamingMode {
- FullDecode,
- ChunkedIfNeeded,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq)]
-pub struct TtsRunConfig {
- pub streaming_enabled: bool,
- pub target_emit_latency_ms: u32,
- pub initial_chunk_frames: usize,
- pub min_chunk_frames: usize,
- pub max_chunk_frames: usize,
- pub max_stream_workspace_frames: usize,
- pub max_semantic_frames: usize,
- pub chunk_policy: TtsChunkPolicy,
- pub non_streaming_mode: TtsNonStreamingMode,
- pub default_seed: u64,
- pub chunk_ema_alpha: f64,
- pub chunk_hysteresis_fraction: f64,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
-pub enum TtsRunConfigError {
- #[error("initial_chunk_frames must be greater than zero")]
- InitialChunkFramesMustBePositive,
- #[error("min_chunk_frames must be greater than zero")]
- MinChunkFramesMustBePositive,
- #[error("max_chunk_frames must be greater than or equal to min_chunk_frames")]
- MaxChunkFramesBelowMinChunkFrames,
- #[error("max_stream_workspace_frames must be greater than zero")]
- MaxStreamWorkspaceFramesMustBePositive,
- #[error("target_emit_latency_ms must be greater than zero")]
- TargetEmitLatencyMustBePositive,
- #[error("max_semantic_frames must be greater than zero")]
- MaxSemanticFramesMustBePositive,
- #[error("max_stream_workspace_frames must be greater than or equal to max_chunk_frames")]
- MaxStreamWorkspaceFramesBelowMaxChunkFrames,
-}
-
-impl TtsRunConfig {
- pub fn validate(&self) -> Result<(), TtsRunConfigError> {
- if self.initial_chunk_frames == 0 {
- return Err(TtsRunConfigError::InitialChunkFramesMustBePositive);
- }
- if self.min_chunk_frames == 0 {
- return Err(TtsRunConfigError::MinChunkFramesMustBePositive);
- }
- if self.max_chunk_frames < self.min_chunk_frames {
- return Err(TtsRunConfigError::MaxChunkFramesBelowMinChunkFrames);
- }
- if self.max_stream_workspace_frames == 0 {
- return Err(TtsRunConfigError::MaxStreamWorkspaceFramesMustBePositive);
- }
- if self.target_emit_latency_ms == 0 {
- return Err(TtsRunConfigError::TargetEmitLatencyMustBePositive);
- }
- if self.max_semantic_frames == 0 {
- return Err(TtsRunConfigError::MaxSemanticFramesMustBePositive);
- }
- Ok(())
- }
-
- pub fn validate_stream_decode(&self) -> Result<(), TtsRunConfigError> {
- self.validate()?;
- if self.max_stream_workspace_frames < self.max_chunk_frames {
- return Err(TtsRunConfigError::MaxStreamWorkspaceFramesBelowMaxChunkFrames);
- }
- Ok(())
- }
-
- pub fn fixed_chunk_frames(chunk_frames: usize) -> Self {
- Self {
- chunk_policy: TtsChunkPolicy::Fixed,
- initial_chunk_frames: chunk_frames.max(1),
- min_chunk_frames: chunk_frames.max(1),
- max_chunk_frames: chunk_frames.max(1),
- ..Self::default()
- }
- }
-}
-
-impl Default for TtsRunConfig {
- fn default() -> Self {
- Self {
- streaming_enabled: true,
- target_emit_latency_ms: 80,
- initial_chunk_frames: 1,
- min_chunk_frames: 16,
- max_chunk_frames: 256,
- max_stream_workspace_frames: 768,
- max_semantic_frames: 768,
- chunk_policy: TtsChunkPolicy::Adaptive,
- non_streaming_mode: TtsNonStreamingMode::ChunkedIfNeeded,
- default_seed: 123,
- chunk_ema_alpha: 0.2,
- chunk_hysteresis_fraction: 0.25,
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use proc_macros::uzu_test;
-
- use super::{TtsChunkPolicy, TtsNonStreamingMode, TtsRunConfig};
-
- #[uzu_test]
- fn default_run_config_matches_production_defaults() {
- let config = TtsRunConfig::default();
- assert!(config.streaming_enabled);
- assert_eq!(config.target_emit_latency_ms, 80);
- assert_eq!(config.initial_chunk_frames, 1);
- assert_eq!(config.min_chunk_frames, 16);
- assert_eq!(config.max_chunk_frames, 256);
- assert_eq!(config.max_stream_workspace_frames, 768);
- assert_eq!(config.max_semantic_frames, 768);
- assert_eq!(config.chunk_policy, TtsChunkPolicy::Adaptive);
- assert_eq!(config.non_streaming_mode, TtsNonStreamingMode::ChunkedIfNeeded);
- assert_eq!(config.default_seed, 123);
- assert!((config.chunk_ema_alpha - 0.2).abs() < f64::EPSILON);
- assert!((config.chunk_hysteresis_fraction - 0.25).abs() < f64::EPSILON);
- }
-
- #[uzu_test]
- fn fixed_chunk_constructor_sets_bounds() {
- let config = TtsRunConfig::fixed_chunk_frames(64);
- assert_eq!(config.chunk_policy, TtsChunkPolicy::Fixed);
- assert_eq!(config.initial_chunk_frames, 64);
- assert_eq!(config.min_chunk_frames, 64);
- assert_eq!(config.max_chunk_frames, 64);
- }
-
- #[uzu_test]
- fn run_config_validation_rejects_invalid_bounds() {
- let invalid = TtsRunConfig {
- min_chunk_frames: 32,
- max_chunk_frames: 16,
- ..TtsRunConfig::default()
- };
- assert!(invalid.validate().is_err());
- }
-
- #[uzu_test]
- fn run_config_validation_rejects_zero_initial_chunk() {
- let invalid = TtsRunConfig {
- initial_chunk_frames: 0,
- ..TtsRunConfig::default()
- };
- assert!(invalid.validate().is_err());
- }
-
- #[uzu_test]
- fn run_config_validation_rejects_zero_semantic_cap() {
- let invalid = TtsRunConfig {
- max_semantic_frames: 0,
- ..TtsRunConfig::default()
- };
- assert!(invalid.validate().is_err());
- }
-
- #[uzu_test]
- fn run_config_validation_rejects_zero_workspace_frames() {
- let invalid = TtsRunConfig {
- max_stream_workspace_frames: 0,
- ..TtsRunConfig::default()
- };
- assert!(invalid.validate().is_err());
- }
-
- #[uzu_test]
- fn run_config_validation_rejects_workspace_smaller_than_max_chunk() {
- let invalid = TtsRunConfig {
- max_chunk_frames: 256,
- max_stream_workspace_frames: 128,
- ..TtsRunConfig::default()
- };
- assert!(invalid.validate_stream_decode().is_err());
- }
-}
diff --git a/crates/backend-uzu/src/session/config/tts_session_options.rs b/crates/backend-uzu/src/session/config/tts_session_options.rs
deleted file mode 100644
index d1deca2bc..000000000
--- a/crates/backend-uzu/src/session/config/tts_session_options.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-#[derive(Debug, Clone, Copy, PartialEq)]
-pub struct TextSamplingConfig {
- pub temperature: f32,
- pub top_p: f32,
-}
-
-impl Default for TextSamplingConfig {
- fn default() -> Self {
- Self {
- temperature: 0.8008,
- top_p: 0.8008,
- }
- }
-}
-
-#[derive(Debug, Clone, PartialEq)]
-pub struct TextDecoderRuntimeConfig {
- pub sampling: TextSamplingConfig,
- pub min_frames_before_im_end: usize,
- pub max_new_tokens_override: Option<usize>,
- pub force_semantic_sampling_mask: Option<bool>,
- pub prefill_step_size: usize,
-}
-
-impl Default for TextDecoderRuntimeConfig {
- fn default() -> Self {
- Self {
- sampling: TextSamplingConfig::default(),
- min_frames_before_im_end: 8,
- max_new_tokens_override: None,
- force_semantic_sampling_mask: None,
- prefill_step_size: 128,
- }
- }
-}
-
-#[cfg(metal_backend)]
-#[derive(Debug, Clone, PartialEq, Default)]
-pub struct TtsSessionOptions {
- pub text_decoder: TextDecoderRuntimeConfig,
-}
diff --git a/crates/backend-uzu/src/session/helpers/context.rs b/crates/backend-uzu/src/session/helpers/context.rs
deleted file mode 100644
index 84ee21882..000000000
--- a/crates/backend-uzu/src/session/helpers/context.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use crate::{backends::common::Backend, forward_pass::cache_layers::CacheLayers, session::config::DecodingConfig};
-
-pub struct Context<B: Backend> {
- pub tokens: Vec<u64>,
- pub cache_layers: CacheLayers<B>,
- pub decoding_config: DecodingConfig,
-}
-
-impl<B: Backend> Context<B> {
- pub fn new(
- tokens: Vec<u64>,
- cache_layers: CacheLayers<B>,
- decoding_config: DecodingConfig,
- ) -> Self {
- Self {
- tokens,
- cache_layers,
- decoding_config,
- }
- }
-}
diff --git a/crates/backend-uzu/src/session/helpers/input_processor.rs b/crates/backend-uzu/src/session/helpers/input_processor.rs
deleted file mode 100644
index 7efddadb0..000000000
--- a/crates/backend-uzu/src/session/helpers/input_processor.rs
+++ /dev/null
@@ -1,117 +0,0 @@
-use std::{ffi::CString, mem::MaybeUninit};
-
-use minijinja::{Environment, context};
-use minijinja_contrib::pycompat::unknown_method_callback;
-
-use crate::{
- config::token_codec::chat_codec::ChatCodecConfig,
- session::{
- parameter::ConfigResolvableValue,
- types::{Error, Input, Message, Role},
- },
-};
-
-pub trait InputProcessor: Send + Sync {
- fn process(
- &self,
- input: &Input,
- enable_thinking: bool,
- add_generation_prompt: bool,
- ) -> Result<String, Error>;
-}
-
-pub struct InputProcessorDefault {
- token_codec_config: ChatCodecConfig,
-}
-
-impl InputProcessorDefault {
- pub fn new(token_codec_config: ChatCodecConfig) -> Self {
- Self {
- token_codec_config,
- }
- }
-}
-
-/// Formats the current local time according to the provided `strftime` pattern.
-fn strftime_now(format_string: String) -> String {
- let Ok(c_format) = CString::new(format_string) else {
- return String::new();
- };
-
- unsafe {
- let now = libc::time(std::ptr::null_mut());
- if now == -1 {
- return String::new();
- }
-
- let mut tm = MaybeUninit::<libc::tm>::uninit();
- if libc::localtime_r(&now, tm.as_mut_ptr()).is_null() {
- return String::new();
- }
-
- let tm = tm.assume_init();
- let mut buf_len = 128_usize;
-
- loop {
- let mut buffer = vec![0u8; buf_len];
- let written =
- libc::strftime(buffer.as_mut_ptr() as *mut libc::c_char, buffer.len(), c_format.as_ptr(), &tm);
-
- if written > 0 {
- buffer.truncate(written as usize);
- return String::from_utf8_lossy(&buffer).into_owned();
- }
-
- if buf_len >= 4096 {
- return String::new();
- }
-
- buf_len *= 2;
- }
- }
-}
-
-impl InputProcessor for InputProcessorDefault {
- fn process(
- &self,
- input: &Input,
- enable_thinking: bool,
- add_generation_prompt: bool,
- ) -> Result<String, Error> {
- let mut messages = input.get_messages();
- for message in &messages {
- if message.role != Role::Assistant && message.reasoning_content.is_some() {
- return Err(Error::UnexpectedReasoningContent);
- }
- }
- if let Some(default_system_prompt) = self.token_codec_config.default_system_prompt.clone()
- && messages.first().is_none_or(|message| message.role != Role::System)
- {
- messages.insert(0, Message::system(default_system_prompt));
- }
-
- let messages =
- messages.into_iter().map(|message| message.resolve(&self.token_codec_config)).collect::<Vec<_>>();
- let template = self.token_codec_config.prompt_template.clone();
- let bos_token = self.token_codec_config.bos_token.clone();
- let eos_token = self.token_codec_config.eos_token.clone();
-
- let template_name = "chat_template";
- let mut environment = Environment::new();
- environment.set_unknown_method_callback(unknown_method_callback);
- environment.add_function("strftime_now", strftime_now);
- environment.add_template(template_name, template.as_str()).map_err(Error::UnableToLoadPromptTemplate)?;
- let template = environment.get_template(template_name).map_err(Error::UnableToLoadPromptTemplate)?;
-
- let result = template
- .render(context!(
- messages => messages,
- add_generation_prompt => add_generation_prompt,
- bos_token => bos_token,
- eos_token => eos_token,
- enable_thinking => enable_thinking
- ))
- .map_err(Error::UnableToRenderPromptTemplate)?;
- Ok(result)
- }
-}
diff --git a/crates/backend-uzu/src/session/helpers/memory_checker.rs b/crates/backend-uzu/src/session/helpers/memory_checker.rs
deleted file mode 100644
index 75189a2a1..000000000
--- a/crates/backend-uzu/src/session/helpers/memory_checker.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-use std::path::Path;
-
-use crate::utils::memory::{get_free_ram, get_free_swap};
-
-fn get_directory_size(path: &Path) -> std::io::Result<u64> {
- let mut size = 0u64;
- for entry_result in std::fs::read_dir(path)? {
- let entry = entry_result?;
- let metadata = entry.metadata()?;
- if metadata.is_dir() {
- size += get_directory_size(&entry.path())?;
- } else {
- size += metadata.len();
- }
- }
- Ok(size)
-}
-
-pub fn is_directory_fits_ram(path: &Path) -> bool {
- let model_size_bytes = get_directory_size(path).unwrap_or(0);
- let available_total = get_free_ram() + get_free_swap();
- model_size_bytes <= available_total
-}
diff --git a/crates/backend-uzu/src/session/helpers/mod.rs b/crates/backend-uzu/src/session/helpers/mod.rs
deleted file mode 100644
index 56c9d13e0..000000000
--- a/crates/backend-uzu/src/session/helpers/mod.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-mod context;
-mod input_processor;
-mod memory_checker;
-mod output_parser;
-pub use context::Context;
-pub use input_processor::{InputProcessor, InputProcessorDefault};
-pub use memory_checker::is_directory_fits_ram;
-pub use output_parser::OutputParser;
diff --git a/crates/backend-uzu/src/session/helpers/output_parser.rs b/crates/backend-uzu/src/session/helpers/output_parser.rs
deleted file mode 100644
index a035b2c63..000000000
--- a/crates/backend-uzu/src/session/helpers/output_parser.rs
+++ /dev/null
@@ -1,116 +0,0 @@
-use regex::{Regex, RegexBuilder};
-
-use crate::session::types::{Error, ParsedText, Text};
-
-pub struct OutputParser {
- regex: Option<Regex>,
-}
-
-impl OutputParser {
- pub fn new(regex_str: Option<String>) -> Result<Self, Error> {
- let regex = match regex_str {
- Some(regex_str) => {
- let regex_str = Self::preprocess_regex_string(regex_str);
- let re = RegexBuilder::new(&regex_str).dot_matches_new_line(true).build()?;
- Some(re)
- },
- None => None,
- };
- Ok(Self {
- regex,
- })
- }
-
- pub fn parse(
- &self,
- text: String,
- enable_thinking: bool,
- ) -> Text {
- let parsed_text = match &self.regex {
- Some(regex) => match regex.captures(&text) {
- Some(captures) => {
- let chain_of_thought = captures.name("chain_of_thought").map(|m| m.as_str().to_string());
- let response = captures.name("response").map(|m| m.as_str().to_string());
- if !enable_thinking {
- ParsedText {
- chain_of_thought: None,
- response: Some(response.unwrap_or_else(|| text.clone())),
- }
- } else {
- ParsedText {
- chain_of_thought,
- response,
- }
- }
- },
- None => ParsedText {
- chain_of_thought: None,
- response: Some(text.clone()),
- },
- },
- None => ParsedText {
- chain_of_thought: None,
- response: Some(text.clone()),
- },
- };
- Text {
- original: text.clone(),
- parsed: parsed_text,
- }
- }
-}
-
-impl OutputParser {
- // Needed because of differences in regex syntax between Python and Rust
- fn preprocess_regex_string(regex_str: String) -> String {
- let mut result = regex_str.clone();
-
- // Replace trailing \Z with \z
- if let Some(prefix) = result.strip_suffix("\\Z") {
- result = format!("{}\\z", prefix);
- }
-
- result
- }
-}
-
-#[cfg(test)]
-mod tests {
- use proc_macros::uzu_test;
-
- use super::*;
-
- const QWEN_REGEX: &str = r"(?s)(?:<think>)?(?P<chain_of_thought>.*?)(?:</think>\s*(?P<response>.*))?\Z";
-
- #[uzu_test]
- fn thinking_enabled_splits_on_close_tag() {
- let parser = OutputParser::new(Some(QWEN_REGEX.to_string())).unwrap();
- let parsed = parser.parse("Let me compute.</think>2 + 2 equals 4.".to_string(), true).parsed;
- assert_eq!(parsed.chain_of_thought.as_deref(), Some("Let me compute."));
- assert_eq!(parsed.response.as_deref(), Some("2 + 2 equals 4."));
- }
-
- #[uzu_test]
- fn thinking_disabled_keeps_answer_as_response() {
- let parser = OutputParser::new(Some(QWEN_REGEX.to_string())).unwrap();
- let parsed = parser.parse("2 + 2 equals 4.".to_string(), false).parsed;
- assert_eq!(parsed.chain_of_thought, None);
- assert_eq!(parsed.response.as_deref(), Some("2 + 2 equals 4."));
- }
-
- #[uzu_test]
- fn thinking_disabled_strips_emitted_reasoning_tags() {
- let parser = OutputParser::new(Some(QWEN_REGEX.to_string())).unwrap();
- let parsed = parser.parse("<think>wait, reconsider</think>2 + 2 equals 4.".to_string(), false).parsed;
- assert_eq!(parsed.chain_of_thought, None);
- assert_eq!(parsed.response.as_deref(), Some("2 + 2 equals 4."));
- }
-
- #[uzu_test]
- fn thinking_enabled_without_close_tag_is_still_reasoning() {
- let parser = OutputParser::new(Some(QWEN_REGEX.to_string())).unwrap();
- let parsed = parser.parse("Let me compute".to_string(), true).parsed;
- assert_eq!(parsed.chain_of_thought.as_deref(), Some("Let me compute"));
- assert_eq!(parsed.response, None);
- }
-}
diff --git a/crates/backend-uzu/src/session/mod.rs b/crates/backend-uzu/src/session/mod.rs
deleted file mode 100644
index 210e24039..000000000
--- a/crates/backend-uzu/src/session/mod.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-mod chat_session;
-pub mod classification_session;
-pub mod config;
-pub mod helpers;
-pub mod parameter;
-mod power_recorder;
-#[cfg(metal_backend)]
-mod tts_session;
-pub mod types;
-
-pub use chat_session::{ChatSession, ChatSession as Session};
-pub use classification_session::ClassificationSession;
-#[cfg(metal_backend)]
-pub use tts_session::TtsSession;
diff --git a/crates/backend-uzu/src/session/parameter/async_batch_size.rs b/crates/backend-uzu/src/session/parameter/async_batch_size.rs
deleted file mode 100644
index 5fce6fa3c..000000000
--- a/crates/backend-uzu/src/session/parameter/async_batch_size.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-use std::path::Path;
-
-use crate::backends::common::{Backend, Context};
-
-#[derive(Debug, Clone, Copy, Default)]
-pub enum AsyncBatchSize {
- #[default]
- Default,
- Custom(usize),
-}
-
-impl AsyncBatchSize {
- pub fn resolve<B: Backend>(
- &self,
- model_path: &Path,
- context: &B::Context,
- ) -> Result<usize, B::Error> {
- match self {
- AsyncBatchSize::Default => context.recommended_async_batch_size(model_path),
- AsyncBatchSize::Custom(value) => Ok(*value),
- }
- }
-}
diff --git a/crates/backend-uzu/src/session/parameter/context_length.rs b/crates/backend-uzu/src/session/parameter/context_length.rs
deleted file mode 100644
index 51e1827e2..000000000
--- a/crates/backend-uzu/src/session/parameter/context_length.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-#[derive(Debug, Clone, Copy, Default)]
-pub enum ContextLength {
- #[default]
- Default,
- Maximal,
- Custom(usize),
-}
diff --git a/crates/backend-uzu/src/session/parameter/context_mode.rs b/crates/backend-uzu/src/session/parameter/context_mode.rs
deleted file mode 100644
index e2b892fb6..000000000
--- a/crates/backend-uzu/src/session/parameter/context_mode.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-use crate::session::types::Input;
-
-#[derive(Clone, Debug, Default)]
-pub enum ContextMode {
- #[default]
- None,
- Static {
- input: Input,
- },
- Dynamic,
-}
-
-#[cfg(test)]
-#[path = "../../../unit/session/parameter/context_mode.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/session/parameter/mod.rs b/crates/backend-uzu/src/session/parameter/mod.rs
deleted file mode 100644
index ba653526b..000000000
--- a/crates/backend-uzu/src/session/parameter/mod.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-mod async_batch_size;
-mod context_length;
-mod context_mode;
-mod prefill_step_size;
-mod resolvable_value;
-mod sampling_policy;
-mod sampling_seed;
-pub use async_batch_size::AsyncBatchSize;
-pub use context_length::ContextLength;
-pub use context_mode::ContextMode;
-pub use prefill_step_size::PrefillStepSize;
-pub use resolvable_value::{ConfigResolvableValue, ResolvableValue};
-pub use sampling_policy::{SamplingMethod, SamplingPolicy, SamplingProcessingOrder};
-pub use sampling_seed::SamplingSeed;
diff --git a/crates/backend-uzu/src/session/parameter/prefill_step_size.rs b/crates/backend-uzu/src/session/parameter/prefill_step_size.rs
deleted file mode 100644
index cbe7ad2b1..000000000
--- a/crates/backend-uzu/src/session/parameter/prefill_step_size.rs
+++ /dev/null
@@ -1,61 +0,0 @@
-use crate::{config::model::language_model::LanguageModelConfig, session::parameter::ConfigResolvableValue};
-
-fn env_prefill_step_size_default_override() -> Option<usize> {
- static OVERRIDE: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
- *OVERRIDE.get_or_init(|| {
- let raw = std::env::var("UZU_PREFILL_STEP_SIZE").ok()?;
- let trimmed = raw.trim();
- if trimmed.is_empty() {
- return None;
- }
- trimmed.parse::<usize>().ok()
- })
-}
-
-#[derive(Debug, Clone, Copy, Default)]
-pub enum PrefillStepSize {
- #[default]
- Default,
- Maximal,
- Custom(usize),
-}
-
-impl ConfigResolvableValue<LanguageModelConfig, usize> for PrefillStepSize {
- fn resolve(
- &self,
- config: &LanguageModelConfig,
- ) -> usize {
- let default_limit: usize = 4096;
- let model_context_length =
- config.decoder_config.transformer_config.max_sequence_length().unwrap_or(default_limit);
-
- let minimal_sliding_window_size = config
- .decoder_config
- .transformer_config
- .layer_configs
- .iter()
- .filter_map(|l| l.mixer_config.sliding_window_size())
- .min()
- .unwrap_or(usize::MAX);
-
- let maximal_value = [model_context_length, minimal_sliding_window_size, default_limit]
- .into_iter()
- .min()
- .unwrap_or(default_limit);
-
- let proposed_value = match self {
- PrefillStepSize::Default => {
- if let Some(v) = env_prefill_step_size_default_override() {
- v
- } else if cfg!(target_os = "ios") {
- 512
- } else {
- 2048
- }
- },
- PrefillStepSize::Maximal => maximal_value,
- PrefillStepSize::Custom(value) => *value,
- };
- std::cmp::min(proposed_value, maximal_value)
- }
-}
diff --git a/crates/backend-uzu/src/session/parameter/resolvable_value.rs b/crates/backend-uzu/src/session/parameter/resolvable_value.rs
deleted file mode 100644
index 05f156979..000000000
--- a/crates/backend-uzu/src/session/parameter/resolvable_value.rs
+++ /dev/null
@@ -1,10 +0,0 @@
-pub trait ResolvableValue<Value> {
- fn resolve(&self) -> Value;
-}
-
-pub trait ConfigResolvableValue<Config, Value> {
- fn resolve(
- &self,
- config: &Config,
- ) -> Value;
-}
diff --git a/crates/backend-uzu/src/session/parameter/sampling_policy.rs b/crates/backend-uzu/src/session/parameter/sampling_policy.rs
deleted file mode 100644
index a6b96cf98..000000000
--- a/crates/backend-uzu/src/session/parameter/sampling_policy.rs
+++ /dev/null
@@ -1,52 +0,0 @@
-use crate::{config::model::language_model::LanguageModelConfig, session::parameter::ConfigResolvableValue};
-
-#[derive(Debug, Copy, Clone, PartialEq, Eq)]
-pub enum SamplingProcessingOrder {
- TemperatureThenFilters,
- FiltersThenTemperature,
-}
-
-#[derive(Debug, Copy, Clone, PartialEq)]
-pub enum SamplingMethod {
- Greedy,
- Stochastic {
- temperature: Option<f32>,
- top_k: Option<u32>,
- top_p: Option<f32>,
- min_p: Option<f32>,
- repetition_penalty: Option<f32>,
- suffix_repetition_length: Option<usize>,
- processing_order: SamplingProcessingOrder,
- },
-}
-
-#[derive(Debug, Clone, PartialEq)]
-pub enum SamplingPolicy {
- Default,
- Custom {
- value: SamplingMethod,
- },
-}
-
-impl ConfigResolvableValue<LanguageModelConfig, SamplingMethod> for SamplingPolicy {
- fn resolve(
- &self,
- config: &LanguageModelConfig,
- ) -> SamplingMethod {
- let generation_config = &config.generation_config;
- match self {
- SamplingPolicy::Default => SamplingMethod::Stochastic {
- temperature: generation_config.temperature,
- top_k: generation_config.top_k,
- top_p: generation_config.top_p,
- min_p: generation_config.min_p,
- repetition_penalty: generation_config.repetition_penalty,
- suffix_repetition_length: generation_config.suffix_repetition_length,
- processing_order: SamplingProcessingOrder::TemperatureThenFilters,
- },
- SamplingPolicy::Custom {
- value,
- } => *value,
- }
- }
-}
diff --git a/crates/backend-uzu/src/session/parameter/sampling_seed.rs b/crates/backend-uzu/src/session/parameter/sampling_seed.rs
deleted file mode 100644
index 171f1d7a1..000000000
--- a/crates/backend-uzu/src/session/parameter/sampling_seed.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-use rand::prelude::*;
-
-use crate::session::parameter::ResolvableValue;
-
-#[derive(Debug, Clone, Copy, Default)]
-pub enum SamplingSeed {
- #[default]
- Default,
- Custom(u64),
-}
-
-impl ResolvableValue<u64> for SamplingSeed {
- fn resolve(&self) -> u64 {
- match self {
- SamplingSeed::Default => rand::rng().random::<u64>(),
- SamplingSeed::Custom(seed) => *seed,
- }
- }
-}
diff --git a/crates/backend-uzu/src/session/power_recorder.rs b/crates/backend-uzu/src/session/power_recorder.rs
deleted file mode 100644
index 673b41a03..000000000
--- a/crates/backend-uzu/src/session/power_recorder.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-use crate::session::types::PowerStats;
-
-// Background power sampler for one generation: drives keisoku's recorder on Apple, no-op elsewhere.
-pub(crate) struct PowerRecorder {
- #[cfg(target_vendor = "apple")]
- handle: keisoku::RecorderHandle,
-}
-
-impl PowerRecorder {
- pub(crate) fn start() -> Self {
- #[cfg(target_vendor = "apple")]
- {
- Self {
- handle: keisoku::start(keisoku::Config {
- interval: std::time::Duration::from_millis(100),
- }),
- }
- }
-
- #[cfg(not(target_vendor = "apple"))]
- {
- Self {}
- }
- }
-
- pub(crate) fn stop(self) -> Option<PowerStats> {
- #[cfg(target_vendor = "apple")]
- {
- PowerStats::from_keisoku_session(&self.handle.stop())
- }
-
- #[cfg(not(target_vendor = "apple"))]
- {
- None
- }
- }
-}
diff --git a/crates/backend-uzu/src/session/tts_session.rs b/crates/backend-uzu/src/session/tts_session.rs
deleted file mode 100644
index 889186467..000000000
--- a/crates/backend-uzu/src/session/tts_session.rs
+++ /dev/null
@@ -1,229 +0,0 @@
-#![cfg(metal_backend)]
-
-mod audio_backend;
-mod backend_factory;
-mod decoder_runtime;
-mod decoder_support;
-mod fishaudio;
-mod generator;
-
-use std::{
- cell::RefCell,
- collections::HashMap,
- fs::File,
- io::BufReader,
- path::{Path, PathBuf},
- rc::Rc,
- time::Instant,
-};
-
-use backend_factory::load_tts_runtime;
-use decoder_runtime::*;
-use decoder_support::*;
-use minijinja::{Environment, context};
-use rand::{RngExt, SeedableRng, rngs::StdRng};
-use tokenizers::Tokenizer;
-
-use crate::{
- audio::{
- AudioCodecRuntime, AudioGenerationContext, AudioPcmBatch, AudioTokenGrid,
- nanocodec::{AudioDecodeStepStats, AudioDecodeStreamState},
- },
- backends::common::{
- Backend, Context as BackendContext, Encoder, Kernels,
- kernel::{
- EmbeddingRowsSumKernel, TensorAddScaleKernel, TokenCopySampledKernel,
- matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},
- },
- },
- config::{model::tts_model::TTSModelConfig, token_codec::tts_codec::TTSCodecConfig},
- data_type::DataType,
- encodable_block::{Decoder, KVCacheUpdate, Sampling as GpuSampling},
- forward_pass::{cache_layers::CacheLayers, model_shape::ModelShape},
- parameters::ParameterLoader,
- session::{
- config::{TextDecoderRuntimeConfig, TextSamplingConfig, TtsChunkPolicy, TtsRunConfig, TtsSessionOptions},
- parameter::{ConfigResolvableValue, SamplingMethod, SamplingProcessingOrder},
- types::{Error, Input},
- },
-};
-
-fn unable_to_create_context<E: std::error::Error + 'static>(err: E) -> Error {
- Error::UnableToCreateContext(Box::new(err))
-}
-
-#[derive(Debug, Clone, Default, PartialEq)]
-pub struct TtsExecutionStats {
- pub semantic_decode_seconds: f64,
- pub audio_decode_seconds: f64,
- pub callback_seconds: f64,
- pub first_chunk_seconds: f64,
- pub command_buffers_submitted: usize,
- pub host_waits: usize,
- pub semantic_frames: usize,
- pub first_chunk_frames: usize,
- pub emitted_chunks: usize,
- pub audio_decode_calls: usize,
- pub audio_input_frames: usize,
- pub audio_decoded_window_frames: usize,
- pub audio_max_decoded_window_frames: usize,
-}
-
-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
-pub(super) struct RunnerInstrumentation {
- pub(super) command_buffers_submitted: usize,
- pub(super) host_waits: usize,
-}
-
-#[derive(Debug, Clone, Copy)]
-pub(super) struct AdaptiveChunkController {
- pub(super) ema_ms_per_frame: Option<f64>,
- pub(super) current_chunk_frames: usize,
-}
-
-pub struct TtsSession<B: Backend> {
- tokenizer: Tokenizer,
- audio: AudioGenerationContext<B>,
- audio_decoder: Box<dyn AudioDecoderBackend>,
- token_codec_config: TTSCodecConfig,
- text_decoder: Box<dyn SemanticDecoderBackend>,
- last_execution_stats: Option<TtsExecutionStats>,
-}
-
-trait SemanticDecoderBackend {
- fn generate_semantic_tokens(
- &mut self,
- text_tokens: &[u64],
- codec_cardinality: usize,
- seed: u64,
- max_semantic_frames: usize,
- ) -> Result<AudioTokenGrid, Error>;
-
- fn generate_semantic_tokens_with_callback(
- &mut self,
- text_tokens: &[u64],
- codec_cardinality: usize,
- seed: u64,
- max_semantic_frames: usize,
- on_frame: &mut dyn FnMut(&[u32]) -> Result<(), Error>,
- ) -> Result<AudioTokenGrid, Error>;
-
- fn take_instrumentation(&mut self) -> RunnerInstrumentation;
-}
-
-trait AudioDecoderBackend {
- fn codec_cardinality(&self) -> usize;
-
- fn num_codebooks(&self) -> usize;
-
- fn sample_rate(&self) -> u32;
-
- fn decode(
- &self,
- tokens: &AudioTokenGrid,
- ) -> Result<AudioPcmBatch, Error>;
-
- fn begin_stream(
- &self,
- batch_size: usize,
- codebooks: usize,
- max_workspace_frames: usize,
- ) -> Result<Box<dyn AudioDecoderStreamBackend>, Error>;
-}
-
-trait AudioDecoderStreamBackend {
- fn decode_step(
- &mut self,
- new_tokens: &AudioTokenGrid,
- is_final: bool,
- ) -> Result<AudioPcmBatch, Error>;
-
- fn decode_step_pending(
- &mut self,
- new_tokens: &AudioTokenGrid,
- is_final: bool,
- ) -> Result<Box<dyn PendingAudioChunkBackend>, Error> {
- let pcm = self.decode_step(new_tokens, is_final)?;
- Ok(Box::new(ImmediatePendingAudioChunk {
- pcm: Some(pcm),
- step_stats: self.last_step_stats(),
- }))
- }
-
- fn last_step_stats(&self) -> Option<AudioDecodeStepStats>;
-
- fn finish(self: Box<Self>) -> Result<(), Error>;
-}
-
-pub(super) trait PendingAudioChunkBackend {
- fn step_stats(&self) -> Option<AudioDecodeStepStats>;
-
- fn try_resolve(&mut self) -> Result<Option<AudioPcmBatch>, Error>;
-
- fn resolve(self: Box<Self>) -> Result<AudioPcmBatch, Error>;
-
- fn resolve_with_decode_duration(self: Box<Self>) -> Result<(AudioPcmBatch, std::time::Duration), Error> {
- let start = Instant::now();
- let pcm = self.resolve()?;
- Ok((pcm, start.elapsed()))
- }
-
- fn try_resolve_with_decode_duration(&mut self) -> Result<Option<(AudioPcmBatch, std::time::Duration)>, Error> {
- let start = Instant::now();
- let Some(pcm) = self.try_resolve()? else {
- return Ok(None);
- };
- Ok(Some((pcm, start.elapsed())))
- }
-}
-
-struct ImmediatePendingAudioChunk {
- pcm: Option<AudioPcmBatch>,
- step_stats: Option<AudioDecodeStepStats>,
-}
-
-impl PendingAudioChunkBackend for ImmediatePendingAudioChunk {
- fn step_stats(&self) -> Option<AudioDecodeStepStats> {
- self.step_stats
- }
-
- fn try_resolve(&mut self) -> Result<Option<AudioPcmBatch>, Error> {
- Ok(Some(self.pcm.take().ok_or(Error::GenerateFailed)?))
- }
-
- fn resolve(mut self: Box<Self>) -> Result<AudioPcmBatch, Error> {
- self.pcm.take().ok_or(Error::GenerateFailed)
- }
-}
-
-struct NanoCodecPendingAudioChunk<B: Backend> {
- inner: Option<crate::audio::nanocodec::runtime::PendingStreamPcmChunk<B>>,
-}
-
-impl<B: Backend> PendingAudioChunkBackend for NanoCodecPendingAudioChunk<B> {
- fn step_stats(&self) -> Option<AudioDecodeStepStats> {
- self.inner.as_ref().map(|pending| pending.step_stats())
- }
-
- fn try_resolve(&mut self) -> Result<Option<AudioPcmBatch>, Error> {
- let ready = self.inner.as_ref().is_none_or(|pending| pending.is_complete());
- if !ready {
- return Ok(None);
- }
-
- let pending = self.inner.take().ok_or(Error::GenerateFailed)?;
- Ok(Some(pending.resolve()?))
- }
-
- fn resolve(mut self: Box<Self>) -> Result<AudioPcmBatch, Error> {
- let pending = self.inner.take().ok_or(Error::GenerateFailed)?;
- Ok(pending.resolve()?)
- }
-}
-
-pub(super) struct PendingStreamingChunk {
- pub(super) submission_decode_duration: std::time::Duration,
- pub(super) ready_frames: usize,
- pub(super) next_chunk_frames: usize,
- pub(super) chunk: Box<dyn PendingAudioChunkBackend>,
-}
diff --git a/crates/backend-uzu/src/session/tts_session/audio_backend.rs b/crates/backend-uzu/src/session/tts_session/audio_backend.rs
deleted file mode 100644
index 6d1b6908e..000000000
--- a/crates/backend-uzu/src/session/tts_session/audio_backend.rs
+++ /dev/null
@@ -1,97 +0,0 @@
-use super::*;
-
-pub(super) struct NanoCodecAudioDecoderBackend<B: Backend> {
- audio: AudioGenerationContext<B>,
- codec_cardinality: usize,
-}
-
-pub(super) struct NanoCodecAudioDecoderStream<B: Backend> {
- audio: AudioGenerationContext<B>,
- state: Option<AudioDecodeStreamState>,
-}
-
-impl<B: Backend> NanoCodecAudioDecoderBackend<B> {
- pub(super) fn new(audio: AudioGenerationContext<B>) -> Self {
- let codec_cardinality = audio.codec_cardinality();
- Self {
- audio,
- codec_cardinality,
- }
- }
-}
-
-impl<B: Backend + Send + Sync> AudioDecoderBackend for NanoCodecAudioDecoderBackend<B> {
- fn codec_cardinality(&self) -> usize {
- self.codec_cardinality
- }
-
- fn num_codebooks(&self) -> usize {
- self.audio.runtime().config().num_groups()
- }
-
- fn sample_rate(&self) -> u32 {
- self.audio.sample_rate()
- }
-
- fn decode(
- &self,
- tokens: &AudioTokenGrid,
- ) -> Result<AudioPcmBatch, Error> {
- Ok(self.audio.runtime().decode(tokens)?)
- }
-
- fn begin_stream(
- &self,
- batch_size: usize,
- codebooks: usize,
- max_workspace_frames: usize,
- ) -> Result<Box<dyn AudioDecoderStreamBackend>, Error> {
- let state =
- self.audio.runtime().begin_decode_stream_with_options(batch_size, codebooks, max_workspace_frames)?;
- Ok(Box::new(NanoCodecAudioDecoderStream {
- audio: self.audio.clone(),
- state: Some(state),
- }))
- }
-}
-
-impl<B: Backend> AudioDecoderStreamBackend for NanoCodecAudioDecoderStream<B> {
- fn decode_step(
- &mut self,
- new_tokens: &AudioTokenGrid,
- is_final: bool,
- ) -> Result<AudioPcmBatch, Error> {
- let state = self.state.as_mut().ok_or(Error::GenerateFailed)?;
- let decoded = self.audio.runtime().decode_stream_step(state, new_tokens, is_final)?;
- Ok(self.audio.runtime().decoded_padded_to_pcm_batch(&decoded)?)
- }
-
- fn decode_step_pending(
- &mut self,
- new_tokens: &AudioTokenGrid,
- is_final: bool,
- ) -> Result<Box<dyn PendingAudioChunkBackend>, Error> {
- let state = self.state.as_mut().ok_or(Error::GenerateFailed)?;
- if let Some(pending) = self.audio.runtime().submit_decode_stream_step(state, new_tokens, is_final)? {
- return Ok(Box::new(NanoCodecPendingAudioChunk {
- inner: Some(pending),
- }));
- }
-
- let decoded = self.audio.runtime().decode_stream_step(state, new_tokens, is_final)?;
- let pcm = self.audio.runtime().decoded_padded_to_pcm_batch(&decoded)?;
- Ok(Box::new(ImmediatePendingAudioChunk {
- pcm: Some(pcm),
- step_stats: Some(state.last_step_stats()),
- }))
- }
-
- fn last_step_stats(&self) -> Option<AudioDecodeStepStats> {
- self.state.as_ref().map(AudioDecodeStreamState::last_step_stats)
- }
-
- fn finish(mut self: Box<Self>) -> Result<(), Error> {
- let state = self.state.take().ok_or(Error::GenerateFailed)?;
- Ok(self.audio.runtime().end_decode_stream(state)?)
- }
-}
diff --git a/crates/backend-uzu/src/session/tts_session/backend_factory.rs b/crates/backend-uzu/src/session/tts_session/backend_factory.rs
deleted file mode 100644
index 07a01f392..000000000
--- a/crates/backend-uzu/src/session/tts_session/backend_factory.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-use super::*;
-use crate::{
- audio::AudioGenerationContext,
- config::{
- model::tts_model::TTSModelConfig, token_codec::AnyTokenCodecConfig, tts::text_decoder::AnyTTSTextDecoderConfig,
- },
-};
-
-pub(super) struct LoadedTtsRuntime<B: Backend> {
- pub(super) audio: AudioGenerationContext<B>,
- pub(super) audio_decoder: Box<dyn AudioDecoderBackend>,
- pub(super) text_decoder: Box<dyn SemanticDecoderBackend>,
- pub(super) token_codec_config: TTSCodecConfig,
-}
-
-pub(super) fn build_audio_decoder_backend<B: Backend + Send + Sync>(
- audio: &AudioGenerationContext<B>
-) -> Result<Box<dyn AudioDecoderBackend>, Error> {
- Ok(Box::new(audio_backend::NanoCodecAudioDecoderBackend::new(audio.clone())))
-}
-
-pub(super) fn load_tts_runtime<B: Backend + Send + Sync>(
- model_path: &Path,
- model_config: &TTSModelConfig,
- options: &TtsSessionOptions,
-) -> Result<LoadedTtsRuntime<B>, Error> {
- let audio = AudioGenerationContext::from_tts_config_and_model_path(&model_config.tts_config, model_path)?;
- let text_decoder = build_text_decoder_backend(model_config, &audio, model_path, options)?;
- let audio_decoder = build_audio_decoder_backend(&audio)?;
- let AnyTokenCodecConfig::TTSCodecConfig(token_codec_config) = &model_config.token_codec_config else {
- return Err(Error::InvalidModelConfig("expected TTSCodecConfig token codec".to_string()));
- };
- let token_codec_config = token_codec_config.clone();
-
- Ok(LoadedTtsRuntime {
- audio,
- audio_decoder,
- text_decoder,
- token_codec_config,
- })
-}
-
-pub(super) fn build_text_decoder_backend<B: Backend>(
- tts_model_config: &TTSModelConfig,
- audio: &AudioGenerationContext<B>,
- model_path: &Path,
- options: &TtsSessionOptions,
-) -> Result<Box<dyn SemanticDecoderBackend>, Error> {
- match &tts_model_config.tts_config.text_decoder_config {
- AnyTTSTextDecoderConfig::FishAudioTextDecoderConfig(config) => {
- fishaudio::build_fishaudio_text_decoder_runtime(config, audio, model_path, &options.text_decoder)
- },
- }
-}
diff --git a/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs b/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs
deleted file mode 100644
index 4a9b5f33f..000000000
--- a/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs
+++ /dev/null
@@ -1,1236 +0,0 @@
-use super::{decoder_support::*, *};
-use crate::{
- array::{Array, ArrayContextExt},
- backends::common::{Allocation, AllocationType, AsBufferRangeRef},
- config::decoder::DecoderConfig,
- encodable_block::{DecoderArguments, DecoderDecodeInput, LayerArguments, Linear, PrecalculatedRope},
- forward_pass::{rope::precalculate_rope, token_inputs::TokenInputs},
- session::types::TtsModelConfigError,
-};
-
-struct TokenDecoderLoadedModel<B: Backend> {
- executables: Decoder<B>,
- readout: Box<dyn Linear<B>>,
- sampler: GpuSampling<B>,
- token_copy_sampled: <B::Kernels as Kernels>::TokenCopySampledKernel,
-}
-
-impl<B: Backend> TokenDecoderLoadedModel<B> {
- fn load(
- context: &Rc<B::Context>,
- decoder_config: &Rc<DecoderConfig>,
- model_shape: &ModelShape,
- root_loader_view: &crate::parameters::ParameterTree<B>,
- transformer_subtree: &str,
- embedding_subtree: &str,
- readout_subtree: &str,
- ) -> Result<Self, Error> {
- let executables = Decoder::new_with_embedding_subtree(
- context.as_ref(),
- decoder_config,
- root_loader_view,
- transformer_subtree,
- embedding_subtree,
- model_shape,
- )
- .map_err(|error| Error::UnableToCreateDecoder(Box::new(error)))?;
- let readout_tree =
- root_loader_view.subtree(readout_subtree).map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let readout = <dyn Linear<B>>::new(
- decoder_config.transformer_config.model_dim,
- [decoder_config.vocab_size],
- false,
- context.as_ref(),
- model_shape.data_type,
- &readout_tree,
- )
- .map_err(|error| Error::UnableToCreateDecoder(Box::new(error)))?;
- let sampler = GpuSampling::new(model_shape.data_type, decoder_config.vocab_size);
- let token_copy_sampled = <B::Kernels as Kernels>::TokenCopySampledKernel::new(context.as_ref(), false)
- .map_err(unable_to_create_context)?;
-
- Ok(Self {
- executables,
- readout,
- sampler,
- token_copy_sampled,
- })
- }
-}
-
-struct TokenDecoderContext<B: Backend> {
- context: Rc<B::Context>,
- cache_layers: Rc<RefCell<CacheLayers<B>>>,
- model_shape: ModelShape,
- decoder_config: Rc<DecoderConfig>,
- runtime_config: TextDecoderRuntimeConfig,
- executables: Decoder<B>,
- readout: Box<dyn Linear<B>>,
- sampler: GpuSampling<B>,
- kv_cache_update: KVCacheUpdate<B>,
- token_copy_sampled: <B::Kernels as Kernels>::TokenCopySampledKernel,
- async_chain_positions: Array<B>,
- async_chain_seeds: Array<B>,
- async_chain_results: Allocation<B>,
- async_chain_capacity: usize,
- current_max_prefix_length: usize,
-}
-
-impl<B: Backend> TokenDecoderContext<B> {
- pub(super) fn context(&self) -> &Rc<B::Context> {
- &self.context
- }
-
- fn new(
- context: Rc<B::Context>,
- model_path: &Path,
- decoder_config: Rc<DecoderConfig>,
- transformer_subtree: &str,
- embedding_subtree: &str,
- readout_subtree: &str,
- runtime_config: &TextDecoderRuntimeConfig,
- ) -> Result<Self, Error> {
- let weights_path = model_path.join("model.safetensors");
- let weights_file = File::open(&weights_path).map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let loader = ParameterLoader::new(&weights_file, context.as_ref())
- .map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let root_loader_view = loader.tree();
-
- let model_shape = ModelShape::from_decoder_config(&decoder_config, DataType::BF16);
- let max_suffix_length = text_decoder_prefill_step_size(
- runtime_config,
- decoder_config.transformer_config.max_sequence_length().unwrap_or(usize::MAX),
- )
- .max(32);
- let max_prefix_length = max_suffix_length;
- let loaded_model = TokenDecoderLoadedModel::<B>::load(
- &context,
- &decoder_config,
- &model_shape,
- &root_loader_view,
- transformer_subtree,
- embedding_subtree,
- readout_subtree,
- )?;
- let async_chain_capacity = max_suffix_length.max(1);
- let (async_chain_positions, async_chain_seeds, async_chain_results) =
- Self::build_async_chain_buffers(&context, async_chain_capacity)?;
- let cache_layers = Rc::new(RefCell::new(CacheLayers::new(
- context.as_ref(),
- &model_shape,
- max_prefix_length,
- max_suffix_length,
- )));
- let kv_cache_update = KVCacheUpdate::new(context.as_ref(), model_shape.data_type, max_prefix_length)
- .map_err(unable_to_create_context)?;
-
- Ok(Self {
- context,
- cache_layers,
- model_shape,
- decoder_config,
- runtime_config: runtime_config.clone(),
- executables: loaded_model.executables,
- readout: loaded_model.readout,
- sampler: loaded_model.sampler,
- kv_cache_update,
- token_copy_sampled: loaded_model.token_copy_sampled,
- async_chain_positions,
- async_chain_seeds,
- async_chain_results,
- async_chain_capacity,
- current_max_prefix_length: max_prefix_length,
- })
- }
-
- fn build_async_chain_buffers(
- context: &Rc<B::Context>,
- async_chain_capacity: usize,
- ) -> Result<(Array<B>, Array<B>, Allocation<B>), Error> {
- let positions = context.create_array_uninitialized(&[async_chain_capacity], DataType::I32);
- let seeds = context.create_array_uninitialized(&[async_chain_capacity], DataType::U64);
- let results = context.create_array_uninitialized(&[async_chain_capacity], DataType::U32).into_allocation();
- Ok((positions, seeds, results))
- }
-}
-
-pub(super) struct TokenDecoderRunner<B: Backend> {
- ctx: TokenDecoderContext<B>,
- pub(super) single_hidden_capture: Allocation<B>,
- pub(super) single_override_embedding: Allocation<B>,
- tensor_add_scale: <B::Kernels as Kernels>::TensorAddScaleKernel,
- single_token_vocab_masks: HashMap<usize, Box<[u32]>>,
- two_token_vocab_masks: HashMap<usize, Box<[u32]>>,
- next_position: usize,
- instrumentation: RunnerInstrumentation,
-}
-
-impl<B: Backend> TokenDecoderRunner<B> {
- pub(super) fn activation_data_type(&self) -> DataType {
- self.ctx.model_shape.data_type
- }
-
- pub(super) fn context(&self) -> &Rc<B::Context> {
- self.ctx.context()
- }
-
- pub(super) fn new_with_context(
- context: Rc<B::Context>,
- model_path: &Path,
- decoder_config: Rc<DecoderConfig>,
- transformer_subtree: &str,
- embedding_subtree: &str,
- readout_subtree: &str,
- runtime_config: &TextDecoderRuntimeConfig,
- ) -> Result<Self, Error> {
- let ctx = TokenDecoderContext::new(
- context,
- model_path,
- decoder_config,
- transformer_subtree,
- embedding_subtree,
- readout_subtree,
- runtime_config,
- )?;
- let context: Rc<B::Context> = Rc::clone(ctx.context());
- let model_dim = ctx.decoder_config.transformer_config.model_dim;
- let tensor_add_scale =
- <B::Kernels as Kernels>::TensorAddScaleKernel::new(context.as_ref(), ctx.model_shape.data_type, false)
- .map_err(unable_to_create_context)?;
- let single_hidden_capture =
- context.create_array_zeros(&[1, model_dim], ctx.model_shape.data_type).into_allocation();
- let single_override_embedding =
- context.create_array_zeros(&[1, model_dim], ctx.model_shape.data_type).into_allocation();
-
- Ok(Self {
- ctx,
- single_hidden_capture,
- single_override_embedding,
- tensor_add_scale,
- single_token_vocab_masks: HashMap::new(),
- two_token_vocab_masks: HashMap::new(),
- next_position: 0,
- instrumentation: RunnerInstrumentation::default(),
- })
- }
-
- pub(super) fn reset(&mut self) {
- self.ctx.cache_layers.borrow_mut().clear(self.ctx.context.as_ref());
- self.next_position = 0;
- }
-
- fn llm_token_inputs(
- &self,
- token_ids: &[u64],
- token_positions: &[usize],
- token_ids_array: Option<Array<B>>,
- sampling_start: usize,
- sampling_length: usize,
- ) -> TokenInputs<B> {
- TokenInputs::new_llm(
- self.ctx.context.as_ref(),
- &self.ctx.model_shape,
- token_ids,
- None,
- token_positions,
- token_ids_array,
- sampling_start,
- sampling_length,
- )
- }
-
- fn decoder_arguments<'a>(
- &'a self,
- token_inputs: &'a TokenInputs<B>,
- batch_dim: usize,
- sampling_start: usize,
- sampling_length: usize,
- cache_layers: &'a mut CacheLayers<B>,
- ) -> DecoderArguments<'a, B> {
- DecoderArguments {
- token_positions: token_inputs.token_positions(),
- token_parents: token_inputs.token_parents(),
- token_subtrie_ranges: token_inputs.token_subtrie_ranges(),
- cache_layers: Some(cache_layers),
- batch_dim,
- sampling_start,
- sampling_length,
- #[cfg(feature = "tracing")]
- trace: None,
- }
- }
-
- fn encode_sampling_on(
- &self,
- encoder: &mut Encoder<B>,
- logits: &mut Allocation<B>,
- sampling_method: SamplingMethod,
- batch_size: usize,
- sampling_seeds: Allocation<B>,
- sampling_bitmask: Option<Allocation<B>>,
- pending_sampling_allocations: &mut Vec<Allocation<B>>,
- ) -> Result<Allocation<B>, Error> {
- let seeds_index = pending_sampling_allocations.len();
- pending_sampling_allocations.push(sampling_seeds);
- let bitmask_index = sampling_bitmask.map(|sampling_bitmask| {
- let index = pending_sampling_allocations.len();
- pending_sampling_allocations.push(sampling_bitmask);
- index
- });
- let sampling_seeds = &pending_sampling_allocations[seeds_index];
- let sampling_bitmask = bitmask_index.map(|index| &pending_sampling_allocations[index]);
- self.ctx
- .sampler
- .encode(logits, Some(sampling_seeds), sampling_bitmask, None, None, sampling_method, batch_size, encoder)
- .map_err(|err| Error::EncodeFailed(Box::new(err)))
- }
-
- fn copy_sampling_output_to_async_result_on(
- &mut self,
- encoder: &mut Encoder<B>,
- sampling_output: &Allocation<B>,
- result_slot: usize,
- ) {
- let copy_size = std::mem::size_of::<u32>();
- let result_offset = result_slot * copy_size;
- encoder.encode_copy(
- sampling_output,
- 0..copy_size,
- &mut self.ctx.async_chain_results,
- result_offset..result_offset + copy_size,
- );
- }
-
- pub(super) fn prepare_for_generation(
- &mut self,
- max_prefix_length: usize,
- ) -> Result<(), Error> {
- let max_prefix_length = self
- .ctx
- .decoder_config
- .transformer_config
- .max_sequence_length()
- .map_or(max_prefix_length.max(1), |model_length| max_prefix_length.max(1).min(model_length));
- let max_suffix_length = text_decoder_prefill_step_size(&self.ctx.runtime_config, max_prefix_length).max(32);
- if self.ctx.current_max_prefix_length == max_prefix_length {
- return Ok(());
- }
- let context = self.ctx.context.as_ref();
- *self.ctx.cache_layers.borrow_mut() =
- CacheLayers::new(context, &self.ctx.model_shape, max_prefix_length, max_suffix_length);
- self.ctx.kv_cache_update = KVCacheUpdate::new(context, self.ctx.model_shape.data_type, max_prefix_length)
- .map_err(unable_to_create_context)?;
- self.ctx.current_max_prefix_length = max_prefix_length;
- Ok(())
- }
-
- pub(super) fn prefill_without_sampling(
- &mut self,
- token_ids: &[u64],
- ) -> Result<(), Error> {
- if token_ids.is_empty() {
- return Ok(());
- }
-
- objc2::rc::autoreleasepool(|_| {
- let token_count = token_ids.len();
-
- let positions: Vec<usize> = (self.next_position..self.next_position + token_count).collect();
- let token_inputs = self.llm_token_inputs(token_ids, &positions, None, 0, 0);
-
- let context = Rc::clone(&self.ctx.context);
- let mut encoder = Encoder::new(context.as_ref()).map_err(unable_to_create_context)?;
-
- let mut cache_layers = self.ctx.cache_layers.borrow_mut();
- cache_layers.prepare_for_forward_pass(&context, token_count);
- self.ctx
- .executables
- .encode_prefill(
- self.decoder_arguments(&token_inputs, token_count, 0, 0, &mut *cache_layers),
- token_inputs.token_ids(),
- &mut encoder,
- )
- .map_err(|err| Error::EncodeFailed(Box::new(err)))?;
- drop(cache_layers);
- self.encode_cache_acceptance_update_on(&mut encoder, token_count);
-
- self.submit_and_wait_command_buffer(encoder)?;
- self.register_positions_and_advance(token_count);
- Ok(())
- })
- }
-
- pub(super) fn decode_next_token_with_hidden_capture(
- &mut self,
- token_ids: &[u64],
- embedding_injection: EmbeddingInjection,
- sampling: &mut TextSamplingState,
- precomputed_token_bitmask: Option<&[u32]>,
- ) -> Result<u64, Error> {
- self.decode_next_step(token_ids, embedding_injection, None, sampling, precomputed_token_bitmask, true, None)
- }
-
- /// Encode the first fast token plus followup passes onto the given
- /// command buffer, without submitting or reading results. The caller
- /// must submit the command buffer later (potentially after encoding
- /// more work from another runner).
- ///
- /// Returns `total_count = 1 + followup_count`. After the eventual
- /// submit+wait the results live in `async_chain_results[0..total_count]`.
- pub(super) fn encode_first_and_followup_tokens_on(
- &mut self,
- encoder: &mut Encoder<B>,
- initial_token_ids: &[u64],
- initial_embedding_injection: EmbeddingInjection,
- pre_injection_encode: Option<&mut PreInjectionEncodeCallback<B>>,
- followup_count: usize,
- vocab_limit: Option<usize>,
- sampling: &mut TextSamplingState,
- pending_token_inputs: &mut Vec<TokenInputs<B>>,
- pending_sampling_allocations: &mut Vec<Allocation<B>>,
- pending_sampling_outputs: &mut Vec<Allocation<B>>,
- ) -> Result<usize, Error> {
- let total_count =
- 1_usize.checked_add(followup_count).ok_or(TtsModelConfigError::AsyncChainFollowupCountOverflow)?;
- if total_count > self.ctx.async_chain_capacity {
- return Err(TtsModelConfigError::AsyncChainTokenCountExceedsCapacity {
- total_count,
- capacity: self.ctx.async_chain_capacity,
- }
- .into());
- }
-
- let vocab_mask_limit = if let Some(limit_raw) = vocab_limit {
- let limit = limit_raw.min(self.ctx.decoder_config.vocab_size);
- if limit == 0 || limit >= self.ctx.decoder_config.vocab_size {
- None
- } else {
- self.prepare_two_token_vocab_mask(limit)?;
- self.prepare_single_token_vocab_mask(limit)?;
- Some(limit)
- }
- } else {
- None
- };
-
- let initial_token_count = initial_token_ids.len();
- if initial_token_count == 0 {
- return Err(Error::GenerateFailed);
- }
-
- // Resolve the bitmask into a local copy so that it does not borrow
- // from `self` when we later call `encode_single_forward_pass`.
- let initial_token_bitmask_owned: Option<Box<[u32]>> = if let Some(limit) = vocab_mask_limit {
- if initial_token_count == 1 {
- self.get_single_token_vocab_mask(limit).map(|m| m.into())
- } else if initial_token_count == 2 {
- self.get_two_token_vocab_mask(limit).map(|m| m.into())
- } else {
- return Err(TtsModelConfigError::UnsupportedInitialTokenCountForVocabMask {
- initial_token_count,
- }
- .into());
- }
- } else {
- None
- };
- let initial_token_bitmask: Option<&[u32]> = initial_token_bitmask_owned.as_deref();
-
- // Consume the initial seed FIRST to preserve RNG ordering with the
- // old two-submit path (initial token consumed its seed before followups).
- let initial_seed = if !matches!(sampling.method(), SamplingMethod::Greedy) {
- Some(sampling.next_seed())
- } else {
- None
- };
-
- // Pre-fill followup positions and seeds into the async chain buffers.
- let followup_base_position = self.next_position + initial_token_ids.len();
- {
- let positions = self.ctx.async_chain_positions.as_slice_mut::<i32>();
- for pass in 0..followup_count {
- positions[pass] = (followup_base_position + pass) as i32;
- }
- }
- {
- let seeds = self.ctx.async_chain_seeds.as_slice_mut::<u64>();
- if !matches!(sampling.method(), SamplingMethod::Greedy) {
- for seed in seeds.iter_mut().take(followup_count) {
- *seed = sampling.next_seed();
- }
- } else {
- seeds[..followup_count].fill(0);
- }
- }
-
- // Encode the initial forward pass (no new CB, no submit).
- let sampling_output = self.encode_single_forward_pass_on(
- encoder,
- initial_token_ids,
- initial_embedding_injection,
- sampling,
- initial_token_bitmask,
- false, // capture_hidden
- pre_injection_encode,
- initial_seed,
- pending_token_inputs,
- pending_sampling_allocations,
- )?;
-
- let first_followup_token_ids = if followup_count > 0 {
- let token_ids_shape = [1];
- let token_ids_data_type = DataType::U64;
- let mut next_token_ids =
- self.ctx.context.create_array_uninitialized(&token_ids_shape, token_ids_data_type).into_allocation();
- self.ctx.token_copy_sampled.encode(
- &sampling_output,
- &mut next_token_ids,
- None::<&mut Allocation<B>>,
- None,
- encoder,
- );
- Some(unsafe { Array::from_allocation(next_token_ids, 0, &token_ids_shape, token_ids_data_type) })
- } else {
- None
- };
- self.copy_sampling_output_to_async_result_on(encoder, &sampling_output, 0);
-
- self.encode_cache_acceptance_update_on(encoder, initial_token_count);
- self.register_positions_and_advance(initial_token_count);
-
- if followup_count > 0 {
- self.encode_followup_passes_on(
- encoder,
- followup_count,
- first_followup_token_ids,
- vocab_mask_limit,
- sampling.method(),
- 1,
- pending_token_inputs,
- pending_sampling_allocations,
- pending_sampling_outputs,
- )?;
- }
-
- pending_sampling_outputs.push(sampling_output);
-
- self.next_position = followup_base_position.saturating_add(followup_count);
- // Do NOT submit -- the caller will submit after encoding more work.
- Ok(total_count)
- }
-
- /// Encode `followup_count` autoregressive passes onto the current command
- /// buffer (which must already be open). `first_token` is the embedding
- /// input for the first pass; subsequent passes read from the
- /// `token_copy_sampled` output of the preceding pass.
- ///
- /// `results_offset_slots` is the slot index in `async_chain_results` where
- /// the first pass's result should be written (0 for standalone, 1+ for
- /// merged paths).
- fn encode_followup_passes_on(
- &mut self,
- encoder: &mut Encoder<B>,
- followup_count: usize,
- first_token_ids: Option<Array<B>>,
- vocab_mask_limit: Option<usize>,
- sampling_method: SamplingMethod,
- results_offset_slots: usize,
- pending_token_inputs: &mut Vec<TokenInputs<B>>,
- pending_sampling_allocations: &mut Vec<Allocation<B>>,
- pending_sampling_outputs: &mut Vec<Allocation<B>>,
- ) -> Result<(), Error> {
- let token_bitmask =
- vocab_mask_limit.and_then(|limit| self.get_single_token_vocab_mask(limit)).map(Box::<[u32]>::from);
- let mut next_token_ids = first_token_ids;
-
- for pass in 0..followup_count {
- let results_slot = results_offset_slots + pass;
- let token_ids = [0];
- let sampling_seed = [self.ctx.async_chain_seeds.as_slice::<u64>()[pass]];
- let mut sampling_seeds = self
- .ctx
- .context
- .create_allocation(std::mem::size_of_val(&sampling_seed), AllocationType::Global)
- .expect("Failed to create sampling seed allocation");
- sampling_seeds.copyin(&sampling_seed);
- let sampling_bitmask = token_bitmask.as_deref().map(|bitmask| {
- let mut allocation = self
- .ctx
- .context
- .create_allocation(std::mem::size_of_val(bitmask), AllocationType::Global)
- .expect("Failed to create sampling bitmask allocation");
- allocation.copyin(bitmask);
- allocation
- });
- let token_inputs =
- self.llm_token_inputs(&token_ids, &[self.next_position + pass], next_token_ids.take(), 0, 1);
- pending_token_inputs.push(token_inputs);
- let token_inputs = pending_token_inputs.last().expect("token inputs must be pending");
-
- {
- let mut logits = self.encode_decode_with_fishaudio_readout_on(
- encoder,
- DecoderDecodeInput::TokenIds(token_inputs.token_ids()),
- token_inputs,
- 1,
- 0,
- 1,
- false,
- )?;
- let sampling_output = self.encode_sampling_on(
- encoder,
- &mut logits,
- sampling_method,
- 1,
- sampling_seeds,
- sampling_bitmask,
- pending_sampling_allocations,
- )?;
- if pass + 1 < followup_count {
- let token_ids_shape = [1];
- let token_ids_data_type = DataType::U64;
- let mut updated_token_ids = self
- .ctx
- .context
- .create_array_uninitialized(&token_ids_shape, token_ids_data_type)
- .into_allocation();
- self.ctx.token_copy_sampled.encode(
- &sampling_output,
- &mut updated_token_ids,
- None::<&mut Allocation<B>>,
- None,
- encoder,
- );
- next_token_ids = Some(unsafe {
- Array::from_allocation(updated_token_ids, 0, &token_ids_shape, token_ids_data_type)
- });
- }
- self.copy_sampling_output_to_async_result_on(encoder, &sampling_output, results_slot);
- pending_sampling_outputs.push(sampling_output);
- }
-
- self.ctx.cache_layers.borrow_mut().update_after_acceptance(
- &[0],
- None,
- &self.ctx.context,
- encoder,
- &self.ctx.kv_cache_update,
- );
- self.ctx.cache_layers.borrow_mut().register_accepted_tokens(1);
- }
- Ok(())
- }
-
- pub(super) fn prepare_single_token_vocab_mask(
- &mut self,
- vocab_limit: usize,
- ) -> Result<(), Error> {
- let limit = vocab_limit.min(self.ctx.decoder_config.vocab_size);
- if limit == 0 || limit >= self.ctx.decoder_config.vocab_size {
- return Ok(());
- }
- if self.single_token_vocab_masks.contains_key(&limit) {
- return Ok(());
- }
- let row_words = self.ctx.decoder_config.vocab_size.div_ceil(32);
- let mut mask = vec![0_u32; row_words];
- for token_index in 0..limit {
- let word = token_index / 32;
- mask[word] |= 2_u32.pow((token_index % 32) as u32);
- }
- self.single_token_vocab_masks.insert(limit, mask.into_boxed_slice());
- Ok(())
- }
-
- pub(super) fn prepare_two_token_vocab_mask(
- &mut self,
- vocab_limit: usize,
- ) -> Result<(), Error> {
- let limit = vocab_limit.min(self.ctx.decoder_config.vocab_size);
- if limit == 0 || limit >= self.ctx.decoder_config.vocab_size {
- return Ok(());
- }
- if self.two_token_vocab_masks.contains_key(&limit) {
- return Ok(());
- }
- let row_words = self.ctx.decoder_config.vocab_size.div_ceil(32);
- let mut mask = vec![
- 0_u32;
- row_words.checked_mul(2).ok_or(TtsModelConfigError::TwoTokenVocabMaskSizeOverflow {
- row_words
- })?
- ];
- for token_index in 0..limit {
- let word = token_index / 32;
- mask[row_words + word] |= 2_u32.pow((token_index % 32) as u32);
- }
- self.two_token_vocab_masks.insert(limit, mask.into_boxed_slice());
- Ok(())
- }
-
- fn get_single_token_vocab_mask(
- &self,
- vocab_limit: usize,
- ) -> Option<&[u32]> {
- self.single_token_vocab_masks.get(&vocab_limit).map(|mask| mask.as_ref())
- }
-
- fn get_two_token_vocab_mask(
- &self,
- vocab_limit: usize,
- ) -> Option<&[u32]> {
- self.two_token_vocab_masks.get(&vocab_limit).map(|mask| mask.as_ref())
- }
-
- fn encode_decode_with_fishaudio_readout_on<'input>(
- &mut self,
- encoder: &mut Encoder<B>,
- input: DecoderDecodeInput<'input, B>,
- token_inputs: &TokenInputs<B>,
- batch_dim: usize,
- sampling_start: usize,
- sampling_length: usize,
- capture_hidden: bool,
- ) -> Result<Allocation<B>, Error> {
- let mut main = match input {
- DecoderDecodeInput::TokenIds(token_ids) => self
- .ctx
- .executables
- .embed
- .encode_lookup(token_ids, batch_dim, encoder)
- .map_err(|err| Error::EncodeFailed(Box::new(err)))?,
- DecoderDecodeInput::Embeddings(main) => main,
- };
- let mut shortcut = encoder
- .allocate_scratch(main.as_buffer_range_ref().range().len())
- .map_err(|err| Error::EncodeFailed(Box::new(err)))?;
-
- {
- let mut cache_layers = self.ctx.cache_layers.borrow_mut();
- cache_layers.prepare_for_forward_pass(&self.ctx.context, batch_dim);
- let ropes = self
- .ctx
- .executables
- .rope_configs
- .iter()
- .map(|rope_config| {
- let (sines, cosines) = precalculate_rope(rope_config, token_inputs.token_positions());
- let mut sines_allocation = encoder.allocate_constant(sines.len() * std::mem::size_of::<f32>())?;
- sines_allocation.copyin(sines.as_ref());
- let mut cosines_allocation =
- encoder.allocate_constant(cosines.len() * std::mem::size_of::<f32>())?;
- cosines_allocation.copyin(cosines.as_ref());
- Ok(PrecalculatedRope {
- cosines: cosines_allocation,
- sines: sines_allocation,
- dim: *rope_config.head_dim(),
- })
- })
- .collect::<Result<Box<[_]>, B::Error>>()
- .map_err(|err| Error::EncodeFailed(Box::new(err)))?;
- for layer in self.ctx.executables.layers.iter() {
- main = layer
- .encode(
- LayerArguments {
- batch_dim,
- token_parents: token_inputs.token_parents(),
- token_subtrie_ranges: token_inputs.token_subtrie_ranges(),
- rope: layer.rope_kind.get(&ropes),
- per_layer_inputs: None,
- sampling_start,
- sampling_length,
- cache_access: Some(cache_layers.cache_for_layer(layer.layer_index)),
- #[cfg(feature = "tracing")]
- trace: None,
- },
- main,
- &mut shortcut,
- encoder,
- )
- .map_err(|err| Error::EncodeFailed(Box::new(err)))?;
- }
- }
-
- let output_norm = self
- .ctx
- .executables
- .norm
- .encode(&main, sampling_start, sampling_length, Some(&mut shortcut), encoder)
- .map_err(|err| Error::EncodeFailed(Box::new(err)))?;
- if capture_hidden {
- let row_size_bytes = shortcut.as_buffer_range_ref().range().len() / batch_dim;
- let input_offset = (batch_dim - 1) * row_size_bytes;
- encoder.encode_copy(
- &shortcut,
- input_offset..input_offset + row_size_bytes,
- &mut self.single_hidden_capture,
- ..,
- );
- }
-
- self.ctx.readout.encode(output_norm, sampling_length, encoder).map_err(|err| Error::EncodeFailed(Box::new(err)))
- }
-
- fn encode_single_forward_pass_on(
- &mut self,
- encoder: &mut Encoder<B>,
- token_ids: &[u64],
- embedding_injection: EmbeddingInjection,
- sampling: &mut TextSamplingState,
- token_bitmask: Option<&[u32]>,
- capture_hidden: bool,
- mut pre_injection_encode: Option<&mut PreInjectionEncodeCallback<B>>,
- preconsumed_seed: Option<u64>,
- pending_token_inputs: &mut Vec<TokenInputs<B>>,
- pending_sampling_allocations: &mut Vec<Allocation<B>>,
- ) -> Result<Allocation<B>, Error> {
- if token_ids.is_empty() {
- return Err(Error::GenerateFailed);
- }
-
- let token_count = token_ids.len();
- let sampling_start = token_count - 1;
- let sampling_length = 1usize;
-
- let mut single_position = [0_usize; 1];
- let mut two_positions = [0_usize; 2];
- let positions_storage;
- let positions: &[usize] = if token_count == 1 {
- single_position[0] = self.next_position;
- &single_position
- } else if token_count == 2 {
- two_positions[0] = self.next_position;
- two_positions[1] = self.next_position + 1;
- &two_positions
- } else {
- positions_storage = (self.next_position..self.next_position + token_count).collect::<Vec<_>>();
- positions_storage.as_slice()
- };
-
- let mut single_seed = [0_u64; 1];
- let mut two_seeds = [0_u64; 2];
- let mut token_seeds_storage;
- let token_seeds: &mut [u64] = if token_count == 1 {
- &mut single_seed
- } else if token_count == 2 {
- &mut two_seeds
- } else {
- token_seeds_storage = vec![0_u64; token_count];
- token_seeds_storage.as_mut_slice()
- };
- if !matches!(sampling.method(), SamplingMethod::Greedy) {
- token_seeds[sampling_start] = preconsumed_seed.unwrap_or_else(|| sampling.next_seed());
- }
-
- if let Some(mask) = token_bitmask {
- let row_words = self.ctx.decoder_config.vocab_size.div_ceil(32);
- let expected_words =
- token_count.checked_mul(row_words).ok_or(TtsModelConfigError::TokenBitmaskSizeOverflow)?;
- if mask.len() != expected_words {
- return Err(TtsModelConfigError::TokenBitmaskLengthMismatch {
- actual_words: mask.len(),
- expected_words,
- token_count,
- row_words,
- }
- .into());
- }
- }
-
- if matches!(embedding_injection, EmbeddingInjection::OverrideFirstRowInternal) && capture_hidden {
- return Err(Error::GenerateFailed);
- }
-
- let sampling_seed_end = sampling_start + sampling_length;
- let sampling_token_seeds = &token_seeds[sampling_start..sampling_seed_end];
- let sampling_token_bitmask = token_bitmask.map(|mask| {
- let row_words = self.ctx.decoder_config.vocab_size.div_ceil(32);
- let row_start = sampling_start * row_words;
- let row_end = row_start + sampling_length * row_words;
- &mask[row_start..row_end]
- });
- let mut sampling_seeds = self
- .ctx
- .context
- .create_allocation(std::mem::size_of_val(sampling_token_seeds), AllocationType::Global)
- .expect("Failed to create sampling seed allocation");
- sampling_seeds.copyin(sampling_token_seeds);
- let sampling_bitmask = sampling_token_bitmask.map(|bitmask| {
- let mut allocation = self
- .ctx
- .context
- .create_allocation(std::mem::size_of_val(bitmask), AllocationType::Global)
- .expect("Failed to create sampling bitmask allocation");
- allocation.copyin(bitmask);
- allocation
- });
- let token_inputs = self.llm_token_inputs(token_ids, positions, None, sampling_start, sampling_length);
- pending_token_inputs.push(token_inputs);
- let token_inputs = pending_token_inputs.last().expect("token inputs must be pending");
-
- let mut main = self
- .ctx
- .executables
- .embed
- .encode_lookup(token_inputs.token_ids(), token_count, encoder)
- .map_err(|err| Error::EncodeFailed(Box::new(err)))?;
- if let Some(pre_encode) = pre_injection_encode.as_mut() {
- pre_encode(self, encoder)?;
- }
- match embedding_injection {
- EmbeddingInjection::None => {},
- EmbeddingInjection::AddPreloaded {
- post_scale,
- } => {
- self.encode_add_scale_from_single_bias_on(encoder, &mut main, token_count, post_scale.unwrap_or(1.0))?;
- },
- EmbeddingInjection::OverrideFirstRowInternal => {
- self.encode_override_first_row_from_device_on(encoder, &mut main, &self.single_override_embedding)?;
- },
- }
- let mut logits = self.encode_decode_with_fishaudio_readout_on(
- encoder,
- DecoderDecodeInput::Embeddings(main),
- token_inputs,
- token_count,
- sampling_start,
- sampling_length,
- capture_hidden,
- )?;
- let sampling_output = self.encode_sampling_on(
- encoder,
- &mut logits,
- sampling.method(),
- sampling_length,
- sampling_seeds,
- sampling_bitmask,
- pending_sampling_allocations,
- )?;
-
- Ok(sampling_output)
- }
-
- /// Encode the KV-cache acceptance update for `token_count` tokens onto
- /// the current command buffer.
- fn encode_cache_acceptance_update_on(
- &mut self,
- encoder: &mut Encoder<B>,
- token_count: usize,
- ) {
- let mut single_accepted = [0_usize; 1];
- let two_accepted = [0_usize, 1_usize];
- let accepted_suffix_indices_storage;
- let accepted_suffix_indices: &[usize] = if token_count == 1 {
- single_accepted[0] = 0;
- &single_accepted
- } else if token_count == 2 {
- &two_accepted
- } else {
- accepted_suffix_indices_storage = (0..token_count).collect::<Vec<_>>();
- accepted_suffix_indices_storage.as_slice()
- };
- self.ctx.cache_layers.borrow_mut().update_after_acceptance(
- accepted_suffix_indices,
- None,
- &self.ctx.context,
- encoder,
- &self.ctx.kv_cache_update,
- );
- }
-
- /// Register accepted token positions in the KV cache and advance
- /// `next_position` by `token_count`.
- fn register_positions_and_advance(
- &mut self,
- token_count: usize,
- ) {
- let positions_storage;
- let positions: &[usize] = if token_count == 1 {
- &[self.next_position]
- } else if token_count == 2 {
- positions_storage = [self.next_position, self.next_position + 1];
- &positions_storage[..]
- } else {
- self.ctx.cache_layers.borrow_mut().register_accepted_tokens(token_count);
- self.next_position = self.next_position.saturating_add(token_count);
- return;
- };
- self.ctx.cache_layers.borrow_mut().register_accepted_tokens(positions.len());
- self.next_position = self.next_position.saturating_add(token_count);
- }
-
- pub(super) fn decode_next_step(
- &mut self,
- token_ids: &[u64],
- embedding_injection: EmbeddingInjection,
- vocab_limit: Option<usize>,
- sampling: &mut TextSamplingState,
- precomputed_token_bitmask: Option<&[u32]>,
- capture_hidden: bool,
- pre_injection_encode: Option<&mut PreInjectionEncodeCallback<B>>,
- ) -> Result<u64, Error> {
- objc2::rc::autoreleasepool(|_| {
- if token_ids.is_empty() {
- return Err(Error::GenerateFailed);
- }
-
- let token_count = token_ids.len();
-
- // Resolve the token bitmask into a local copy so that it does not
- // borrow from `self` when we later call `encode_single_forward_pass`.
- let sampling_start = token_count - 1;
- let row_words = self.ctx.decoder_config.vocab_size.div_ceil(32);
- let token_bitmask_owned: Option<Box<[u32]>> = if let Some(mask) = precomputed_token_bitmask {
- let expected_words =
- token_count.checked_mul(row_words).ok_or(TtsModelConfigError::PrecomputedBitmaskSizeOverflow)?;
- if mask.len() != expected_words {
- return Err(TtsModelConfigError::PrecomputedBitmaskLengthMismatch {
- actual_words: mask.len(),
- expected_words,
- }
- .into());
- }
- Some(mask.into())
- } else if let Some(limit_raw) = vocab_limit {
- let limit = limit_raw.min(self.ctx.decoder_config.vocab_size);
- if limit == 0 {
- return Err(TtsModelConfigError::VocabLimitResolvedToZero.into());
- }
- if limit >= self.ctx.decoder_config.vocab_size {
- None
- } else if token_count == 1 {
- if let Some(mask) = self.get_single_token_vocab_mask(limit) {
- Some(mask.into())
- } else {
- let mut mask = vec![0_u32; row_words];
- for token_index in 0..limit {
- let word = token_index / 32;
- mask[word] |= 2_u32.pow((token_index % 32) as u32);
- }
- Some(mask.into_boxed_slice())
- }
- } else if token_count == 2 {
- if let Some(mask) = self.get_two_token_vocab_mask(limit) {
- Some(mask.into())
- } else {
- let total_words = token_count.checked_mul(row_words).ok_or(
- TtsModelConfigError::InlineBitmaskSizeOverflow {
- token_count,
- row_words,
- },
- )?;
- let mut mask = vec![0_u32; total_words];
- for token_index in 0..limit {
- let word = token_index / 32;
- mask[sampling_start * row_words + word] |= 2_u32.pow((token_index % 32) as u32);
- }
- Some(mask.into_boxed_slice())
- }
- } else {
- // token_count > 2 with vocab_limit requires a precomputed bitmask;
- // silently dropping the limit would produce incorrect sampling.
- return Err(TtsModelConfigError::VocabLimitRequiresPrecomputedBitmask {
- token_count,
- }
- .into());
- }
- } else {
- None
- };
-
- let token_bitmask: Option<&[u32]> = token_bitmask_owned.as_deref();
-
- let context = Rc::clone(&self.ctx.context);
- let mut encoder = Encoder::new(context.as_ref()).map_err(unable_to_create_context)?;
- let mut pending_token_inputs = Vec::new();
- let mut pending_sampling_allocations = Vec::new();
-
- let sampling_output = self.encode_single_forward_pass_on(
- &mut encoder,
- token_ids,
- embedding_injection,
- sampling,
- token_bitmask,
- capture_hidden,
- pre_injection_encode,
- None,
- &mut pending_token_inputs,
- &mut pending_sampling_allocations,
- )?;
- self.encode_cache_acceptance_update_on(&mut encoder, token_count);
-
- self.submit_and_wait_command_buffer(encoder)?;
- let token = read_sampled_token_from_sampling_output(&sampling_output)?;
- self.register_positions_and_advance(token_count);
- Ok(token)
- })
- }
-
- fn encode_override_first_row_from_device_on(
- &self,
- encoder: &mut Encoder<B>,
- main: &mut Allocation<B>,
- override_embedding: &Allocation<B>,
- ) -> Result<(), Error> {
- let model_dim = self.ctx.decoder_config.transformer_config.model_dim;
- let model_dim_bytes = model_dim.checked_mul(self.activation_data_type().size_in_bytes()).ok_or(
- TtsModelConfigError::ModelDimExceedsU32 {
- model_dim,
- },
- )?;
- encoder.encode_copy(override_embedding, 0..model_dim_bytes, main, 0..model_dim_bytes);
- Ok(())
- }
-
- fn encode_add_scale_from_single_bias_on(
- &self,
- encoder: &mut Encoder<B>,
- main: &mut Allocation<B>,
- token_count: usize,
- scale: f32,
- ) -> Result<(), Error> {
- if token_count == 0 {
- return Err(Error::GenerateFailed);
- }
- let model_dim = self.ctx.decoder_config.transformer_config.model_dim;
- let model_dim_u32 = u32::try_from(model_dim).map_err(|_| TtsModelConfigError::ModelDimExceedsU32 {
- model_dim,
- })?;
- let total_len = token_count.checked_mul(model_dim).ok_or(TtsModelConfigError::AddScaleTotalLengthOverflow {
- token_count,
- model_dim,
- })?;
- let total_len_u32 =
- u32::try_from(total_len).map_err(|_| TtsModelConfigError::AddScaleTotalLengthExceedsU32 {
- total_len,
- })?;
- let mut output =
- encoder.allocate_scratch(main.as_buffer_range_ref().range().len()).map_err(unable_to_create_context)?;
- self.tensor_add_scale.encode(
- Some(&*main),
- &self.single_override_embedding,
- &mut output,
- model_dim_u32,
- total_len_u32,
- scale,
- encoder,
- );
- *main = output;
- Ok(())
- }
-
- /// Encode a single decode step (embedding, transformer, readout, sampling,
- /// and optionally hidden capture) onto the **current** command buffer.
- /// Does NOT create a new command buffer, does NOT submit.
- ///
- /// The caller is responsible for submitting the command buffer and reading
- /// the sampled token from `async_chain_results[0]` after the eventual
- /// submit.
- pub(super) fn encode_next_step_on(
- &mut self,
- encoder: &mut Encoder<B>,
- token_ids: &[u64],
- embedding_injection: EmbeddingInjection,
- sampling: &mut TextSamplingState,
- precomputed_token_bitmask: Option<&[u32]>,
- capture_hidden: bool,
- pre_injection_encode: Option<&mut PreInjectionEncodeCallback<B>>,
- pending_token_inputs: &mut Vec<TokenInputs<B>>,
- pending_sampling_allocations: &mut Vec<Allocation<B>>,
- pending_sampling_outputs: &mut Vec<Allocation<B>>,
- ) -> Result<(), Error> {
- let token_count = token_ids.len();
-
- let sampling_output = self.encode_single_forward_pass_on(
- encoder,
- token_ids,
- embedding_injection,
- sampling,
- precomputed_token_bitmask,
- capture_hidden,
- pre_injection_encode,
- None,
- pending_token_inputs,
- pending_sampling_allocations,
- )?;
-
- // Copy sampled token to async_chain_results[0] so the caller can
- // read it after the eventual submit.
- self.copy_sampling_output_to_async_result_on(encoder, &sampling_output, 0);
- pending_sampling_outputs.push(sampling_output);
-
- self.encode_cache_acceptance_update_on(encoder, token_count);
- // Do NOT submit -- the caller will submit.
- self.register_positions_and_advance(token_count);
- Ok(())
- }
-
- pub(super) fn submit_and_wait_command_buffer(
- &mut self,
- encoder: Encoder<B>,
- ) -> Result<(), Error> {
- self.instrumentation.command_buffers_submitted += 1;
- let result = encoder
- .end_encoding()
- .submit()
- .wait_until_completed()
- .map_err(|err| Error::CommandBufferFailed(Box::new(err)));
- result?;
- self.instrumentation.host_waits += 1;
- Ok(())
- }
-
- pub(super) fn copy_async_chain_results_to_on(
- &mut self,
- encoder: &mut Encoder<B>,
- src_slot: usize,
- dst: &mut Allocation<B>,
- dst_offset: usize,
- count: usize,
- ) -> Result<(), Error> {
- let src_offset = src_slot.checked_mul(std::mem::size_of::<u32>()).ok_or(
- TtsModelConfigError::AsyncChainCopySourceOffsetOverflow {
- src_slot,
- },
- )?;
- let byte_len =
- count.checked_mul(std::mem::size_of::<u32>()).ok_or(TtsModelConfigError::AsyncChainCopySizeOverflow {
- count,
- })?;
- encoder.encode_copy(
- &self.ctx.async_chain_results,
- src_offset..src_offset + byte_len,
- dst,
- dst_offset..dst_offset + byte_len,
- );
- Ok(())
- }
-
- pub(super) fn read_async_chain_result(
- &self,
- slot: usize,
- ) -> Result<u32, Error> {
- let capacity = self.ctx.async_chain_capacity;
- if slot >= capacity {
- return Err(TtsModelConfigError::AsyncChainResultSlotOutOfBounds {
- slot,
- capacity,
- }
- .into());
- }
- Ok(self.ctx.async_chain_results.copyout::<u32>()[slot])
- }
-
- pub(super) fn take_instrumentation(&mut self) -> RunnerInstrumentation {
- std::mem::take(&mut self.instrumentation)
- }
-
- pub(super) fn clear_instrumentation(&mut self) {
- self.instrumentation = RunnerInstrumentation::default();
- }
-}
-
-fn read_sampled_token_from_sampling_output<B: Backend>(sampling_output: &Allocation<B>) -> Result<u64, Error> {
- let token = sampling_output.copyout::<u32>()[0];
- Ok(u64::from(token))
-}
diff --git a/crates/backend-uzu/src/session/tts_session/decoder_support.rs b/crates/backend-uzu/src/session/tts_session/decoder_support.rs
deleted file mode 100644
index eb93ab76a..000000000
--- a/crates/backend-uzu/src/session/tts_session/decoder_support.rs
+++ /dev/null
@@ -1,599 +0,0 @@
-use super::*;
-
-pub(super) type PreInjectionEncodeCallback<'a, B> =
- dyn FnMut(&mut TokenDecoderRunner<B>, &mut Encoder<B>) -> Result<(), Error> + 'a;
-
-pub(super) enum EmbeddingInjection {
- None,
- AddPreloaded {
- post_scale: Option<f32>,
- },
- OverrideFirstRowInternal,
-}
-
-pub(super) struct TextSamplingState {
- rng: StdRng,
- method: SamplingMethod,
-}
-
-impl TextSamplingState {
- pub(super) fn from_config(
- seed: u64,
- config: &TextSamplingConfig,
- ) -> Self {
- Self::with_params(seed, config.temperature, config.top_p)
- }
-
- pub(super) fn with_params(
- seed: u64,
- temperature: f32,
- top_p: f32,
- ) -> Self {
- let method = if temperature <= 0.0 || top_p <= 0.0 {
- SamplingMethod::Greedy
- } else {
- SamplingMethod::Stochastic {
- temperature: Some(temperature),
- top_k: None,
- top_p: Some(top_p),
- min_p: None,
- repetition_penalty: None,
- suffix_repetition_length: None,
- processing_order: SamplingProcessingOrder::FiltersThenTemperature,
- }
- };
- Self {
- rng: StdRng::seed_from_u64(seed),
- method,
- }
- }
-
- pub(super) fn method(&self) -> SamplingMethod {
- self.method
- }
-
- pub(super) fn next_seed(&mut self) -> u64 {
- self.rng.random::<u64>()
- }
-}
-
-pub(super) fn text_decoder_prefill_step_size(
- config: &TextDecoderRuntimeConfig,
- context_length: usize,
-) -> usize {
- config.prefill_step_size.min(context_length.max(1)).max(1)
-}
-
-pub(super) fn normalize_rendered_prompt(
- mut rendered: String,
- template: &str,
- drop_initial_newline: bool,
-) -> String {
- if drop_initial_newline && rendered.starts_with('\n') {
- rendered.remove(0);
- }
- if template.ends_with('\n') && rendered.ends_with('\n') {
- rendered.pop();
- }
- rendered
-}
-
-impl AdaptiveChunkController {
- pub(super) fn new(config: &TtsRunConfig) -> Self {
- Self {
- ema_ms_per_frame: None,
- current_chunk_frames: config.min_chunk_frames.max(1),
- }
- }
-
- pub(super) fn target_frames(
- &self,
- config: &TtsRunConfig,
- ) -> usize {
- let min_frames = config.min_chunk_frames.max(1);
- let max_frames = config.max_chunk_frames.max(min_frames);
- match config.chunk_policy {
- TtsChunkPolicy::Fixed => min_frames,
- TtsChunkPolicy::Adaptive => {
- let Some(ema_ms_per_frame) = self.ema_ms_per_frame else {
- return min_frames;
- };
- let raw = (config.target_emit_latency_ms as f64 / ema_ms_per_frame).round();
- let candidate = raw.max(min_frames as f64).min(max_frames as f64) as usize;
- if self.current_chunk_frames == 0 {
- return candidate;
- }
- if candidate <= self.current_chunk_frames {
- return self.current_chunk_frames;
- }
- let change = ((candidate as f64 - self.current_chunk_frames as f64).abs()
- / self.current_chunk_frames as f64)
- .max(0.0);
- if change < config.chunk_hysteresis_fraction {
- self.current_chunk_frames
- } else {
- candidate
- }
- },
- }
- }
-
- pub(super) fn observe(
- &mut self,
- config: &TtsRunConfig,
- frames: usize,
- decode_elapsed: std::time::Duration,
- next_chunk_frames: usize,
- ) {
- if frames == 0 {
- return;
- }
- let alpha = config.chunk_ema_alpha;
- let ms_per_frame = (decode_elapsed.as_secs_f64() * 1000.0) / frames as f64;
- self.ema_ms_per_frame = Some(match self.ema_ms_per_frame {
- Some(previous) => previous * (1.0 - alpha) + ms_per_frame * alpha,
- None => ms_per_frame,
- });
- self.current_chunk_frames = next_chunk_frames.max(1);
- }
-
- pub(super) fn adapt_up_for_realtime(
- &mut self,
- config: &TtsRunConfig,
- generated_frames: usize,
- sample_rate: u32,
- decode_elapsed: std::time::Duration,
- emitted_audio_frames: usize,
- ) {
- if generated_frames == 0 || emitted_audio_frames == 0 || sample_rate == 0 {
- return;
- }
- let min_frames = config.min_chunk_frames.max(1);
- let max_frames = config.max_chunk_frames.max(min_frames);
- let decode_ms = decode_elapsed.as_secs_f64() * 1000.0;
- let produced_audio_ms = (emitted_audio_frames as f64) * 1000.0 / f64::from(sample_rate);
- if produced_audio_ms <= 0.0 {
- return;
- }
- let realtime_ratio = decode_ms / produced_audio_ms;
- if realtime_ratio <= 1.0 {
- return;
- }
- let scaled = ((generated_frames as f64) * realtime_ratio * 1.1).ceil() as usize;
- let clamped = scaled.clamp(min_frames, max_frames);
- self.current_chunk_frames = self.current_chunk_frames.max(clamped);
- }
-
- pub(super) fn promote_to_max_chunk(
- &mut self,
- config: &TtsRunConfig,
- ) {
- let min_frames = config.min_chunk_frames.max(1);
- let max_frames = config.max_chunk_frames.max(min_frames);
- self.current_chunk_frames = max_frames;
- }
-}
-
-pub(super) fn next_startup_target_frames(
- current_target_frames: usize,
- startup_cap_frames: usize,
-) -> usize {
- let startup_cap_frames = startup_cap_frames.max(1);
- current_target_frames.max(1).saturating_mul(2).min(startup_cap_frames)
-}
-
-pub(super) struct StreamingTokenAccumulator {
- by_codebook: Vec<Vec<u32>>,
-}
-
-impl StreamingTokenAccumulator {
- pub(super) fn new(num_codebooks: usize) -> Result<Self, Error> {
- if num_codebooks == 0 {
- return Err(Error::InvalidModelConfig("TTS num_codebooks must be greater than 0".to_string()));
- }
- Ok(Self {
- by_codebook: vec![Vec::new(); num_codebooks],
- })
- }
-
- pub(super) fn push_frame(
- &mut self,
- frame_codes: &[u32],
- ) -> Result<(), Error> {
- if frame_codes.len() != self.by_codebook.len() {
- return Err(Error::GenerateFailed);
- }
- for (codebook, &token) in self.by_codebook.iter_mut().zip(frame_codes.iter()) {
- codebook.push(token);
- }
- Ok(())
- }
-
- pub(super) fn frames(&self) -> usize {
- self.by_codebook.first().map_or(0, Vec::len)
- }
-
- pub(super) fn to_grid_range(
- &self,
- frame_start: usize,
- frame_end: usize,
- ) -> Result<AudioTokenGrid, Error> {
- let frames = self.frames();
- if frame_start > frame_end || frame_end > frames {
- return Err(Error::GenerateFailed);
- }
- let range_frames = frame_end - frame_start;
- let mut tokens = Vec::with_capacity(self.by_codebook.len() * range_frames);
- for codebook in &self.by_codebook {
- if codebook.len() != frames {
- return Err(Error::GenerateFailed);
- }
- tokens.extend_from_slice(&codebook[frame_start..frame_end]);
- }
-
- Ok(AudioTokenGrid::new(
- tokens.into_boxed_slice(),
- 1,
- self.by_codebook.len(),
- range_frames,
- vec![range_frames].into_boxed_slice(),
- )?)
- }
-}
-
-pub(super) fn slice_grid_range(
- grid: &AudioTokenGrid,
- frame_start: usize,
- frame_end: usize,
-) -> Result<AudioTokenGrid, Error> {
- if frame_start > frame_end || frame_end > grid.frames() {
- return Err(Error::GenerateFailed);
- }
- let range_frames = frame_end.saturating_sub(frame_start);
- let batch_size = grid.batch_size();
- let codebooks = grid.codebooks();
- let frames = grid.frames();
-
- let mut tokens = Vec::with_capacity(batch_size * codebooks * range_frames);
- let row_stride = frames;
- for batch in 0..batch_size {
- for codebook in 0..codebooks {
- let row_index = batch
- .checked_mul(codebooks)
- .and_then(|value| value.checked_add(codebook))
- .ok_or(Error::GenerateFailed)?;
- let row_start = row_index.checked_mul(row_stride).ok_or(Error::GenerateFailed)?;
- let src_start = row_start.checked_add(frame_start).ok_or(Error::GenerateFailed)?;
- let src_end = row_start.checked_add(frame_end).ok_or(Error::GenerateFailed)?;
- tokens.extend_from_slice(&grid.tokens()[src_start..src_end]);
- }
- }
-
- let mut lengths = Vec::with_capacity(batch_size);
- for &length in grid.lengths() {
- lengths.push(length.saturating_sub(frame_start).min(range_frames));
- }
-
- Ok(AudioTokenGrid::new(tokens.into_boxed_slice(), batch_size, codebooks, range_frames, lengths.into_boxed_slice())?)
-}
-
-pub(super) fn accumulate_audio_decode_step_stats(
- decode_calls: &mut usize,
- input_frames: &mut usize,
- decoded_window_frames: &mut usize,
- max_decoded_window_frames: &mut usize,
- step: Option<AudioDecodeStepStats>,
-) {
- let Some(step) = step else {
- return;
- };
- if step.input_frames == 0 && step.decoded_window_frames == 0 {
- return;
- }
- *decode_calls = decode_calls.saturating_add(1);
- *input_frames = input_frames.saturating_add(step.input_frames);
- *decoded_window_frames = decoded_window_frames.saturating_add(step.decoded_window_frames);
- *max_decoded_window_frames = (*max_decoded_window_frames).max(step.decoded_window_frames);
-}
-
-pub(super) struct StreamingSynthesisState<'a, F: FnMut(&AudioPcmBatch)> {
- pub(super) on_chunk: &'a mut F,
- pub(super) pending_chunk: Option<PendingStreamingChunk>,
- pub(super) callback_seconds: f64,
- pub(super) audio_decode_seconds_in_loop: f64,
- pub(super) audio_decode_seconds: f64,
- pub(super) output_samples: Vec<f32>,
- pub(super) output_frames: usize,
- pub(super) output_sample_rate: u32,
- pub(super) output_channels: usize,
- pub(super) emitted_chunks: usize,
- pub(super) first_emit_pending: bool,
- pub(super) first_chunk_seconds: Option<f64>,
- pub(super) first_chunk_frames: usize,
- pub(super) stream_start: Instant,
- pub(super) startup_target_frames: usize,
- pub(super) startup_cap_frames: usize,
- pub(super) chunk_controller: AdaptiveChunkController,
- pub(super) audio_decode_calls: usize,
- pub(super) audio_input_frames: usize,
- pub(super) audio_decoded_window_frames: usize,
- pub(super) audio_max_decoded_window_frames: usize,
-}
-
-impl<'a, F: FnMut(&AudioPcmBatch)> StreamingSynthesisState<'a, F> {
- pub(super) fn maybe_flush_pending(
- &mut self,
- force: bool,
- count_in_loop: bool,
- config: &TtsRunConfig,
- ) -> Result<(), Error> {
- let (
- step_stats,
- ready_frames,
- next_chunk_frames,
- submission_decode_duration,
- partial_pcm,
- resolve_decode_duration,
- ) = if force {
- let Some(pending) = self.pending_chunk.take() else {
- return Ok(());
- };
- let step_stats = pending.chunk.step_stats();
- let ready_frames = pending.ready_frames;
- let next_chunk_frames = pending.next_chunk_frames;
- let submission_decode_duration = pending.submission_decode_duration;
- let (partial_pcm, resolve_decode_duration) = pending.chunk.resolve_with_decode_duration()?;
- (
- step_stats,
- ready_frames,
- next_chunk_frames,
- submission_decode_duration,
- partial_pcm,
- resolve_decode_duration,
- )
- } else {
- let Some(pending) = self.pending_chunk.as_mut() else {
- return Ok(());
- };
- let Some((partial_pcm, resolve_decode_duration)) = pending.chunk.try_resolve_with_decode_duration()? else {
- return Ok(());
- };
- let step_stats = pending.chunk.step_stats();
- let ready_frames = pending.ready_frames;
- let next_chunk_frames = pending.next_chunk_frames;
- let submission_decode_duration = pending.submission_decode_duration;
- self.pending_chunk.take().ok_or(Error::GenerateFailed)?;
- (
- step_stats,
- ready_frames,
- next_chunk_frames,
- submission_decode_duration,
- partial_pcm,
- resolve_decode_duration,
- )
- };
-
- accumulate_audio_decode_step_stats(
- &mut self.audio_decode_calls,
- &mut self.audio_input_frames,
- &mut self.audio_decoded_window_frames,
- &mut self.audio_max_decoded_window_frames,
- step_stats,
- );
- let decode_elapsed = submission_decode_duration.saturating_add(resolve_decode_duration);
- if count_in_loop {
- self.audio_decode_seconds_in_loop += decode_elapsed.as_secs_f64();
- }
- self.audio_decode_seconds += decode_elapsed.as_secs_f64();
-
- let partial_sample_rate = partial_pcm.sample_rate();
- let callback_start = Instant::now();
- let emitted_frames = if partial_pcm.lengths().len() == 1 {
- partial_pcm.lengths()[0]
- } else {
- return Err(Error::GenerateFailed);
- };
- if emitted_frames > 0 {
- (self.on_chunk)(&partial_pcm);
- }
- self.callback_seconds += callback_start.elapsed().as_secs_f64();
- self.chunk_controller.observe(config, ready_frames, decode_elapsed, next_chunk_frames);
-
- if emitted_frames > 0 {
- self.chunk_controller.adapt_up_for_realtime(
- config,
- ready_frames,
- partial_sample_rate,
- decode_elapsed,
- emitted_frames,
- );
- self.output_samples.extend_from_slice(partial_pcm.samples());
- self.output_frames = self.output_frames.saturating_add(emitted_frames);
- self.output_sample_rate = partial_pcm.sample_rate();
- self.output_channels = partial_pcm.channels();
- self.emitted_chunks = self.emitted_chunks.saturating_add(1);
- if self.first_emit_pending {
- self.first_emit_pending = false;
- self.first_chunk_seconds = Some(self.stream_start.elapsed().as_secs_f64());
- self.first_chunk_frames = emitted_frames;
- self.chunk_controller.promote_to_max_chunk(config);
- }
- } else if self.first_emit_pending {
- self.startup_target_frames =
- next_startup_target_frames(self.startup_target_frames, self.startup_cap_frames);
- }
-
- Ok(())
- }
-}
-
-impl<B: Backend + Send + Sync> TtsSession<B> {
- pub fn new(model_path: PathBuf) -> Result<Self, Error> {
- Self::new_with_options(model_path, TtsSessionOptions::default())
- }
-
- pub fn new_with_options(
- model_path: PathBuf,
- options: TtsSessionOptions,
- ) -> Result<Self, Error> {
- if !model_path.exists() {
- return Err(Error::ModelFolderNotFound);
- }
-
- let config_path = model_path.join("config.json");
- let config_file = File::open(&config_path)?;
- let model_config: TTSModelConfig = serde_json::from_reader(BufReader::new(config_file))?;
-
- Self::from_model_config_with_options(model_path, model_config, options)
- }
-
- pub fn last_execution_stats(&self) -> Option<TtsExecutionStats> {
- self.last_execution_stats.clone()
- }
-
- pub fn sample_rate(&self) -> u32 {
- self.audio.sample_rate()
- }
-
- fn from_model_config_with_options(
- model_path: PathBuf,
- model_config: TTSModelConfig,
- options: TtsSessionOptions,
- ) -> Result<Self, Error> {
- let tokenizer_path = model_path.join("tokenizer.json");
- let tokenizer = Tokenizer::from_file(&tokenizer_path).map_err(Error::UnableToLoadTokenizer)?;
-
- let loaded_runtime = load_tts_runtime(&model_path, &model_config, &options)?;
-
- Ok(Self {
- tokenizer,
- audio: loaded_runtime.audio,
- audio_decoder: loaded_runtime.audio_decoder,
- token_codec_config: loaded_runtime.token_codec_config,
- text_decoder: loaded_runtime.text_decoder,
- last_execution_stats: None,
- })
- }
-
- pub(super) fn render_prompt(
- &self,
- input: &Input,
- ) -> Result<String, Error> {
- let messages = input
- .get_messages()
- .into_iter()
- .map(|message| message.resolve(&self.token_codec_config))
- .collect::<Vec<_>>();
-
- let template_name = "tts_prompt_template";
- let mut environment = Environment::new();
- environment
- .add_template(template_name, self.token_codec_config.prompt_template.as_str())
- .map_err(Error::UnableToLoadPromptTemplate)?;
- let template = environment.get_template(template_name).map_err(Error::UnableToLoadPromptTemplate)?;
-
- let result = template
- .render(context!(
- messages => messages
- ))
- .map_err(Error::UnableToRenderPromptTemplate)?;
-
- Ok(normalize_rendered_prompt(
- result,
- self.token_codec_config.prompt_template.as_str(),
- self.token_codec_config.drop_initial_newline,
- ))
- }
-}
-
-pub(super) fn semantic_token_to_code(
- semantic_token: u64,
- semantic_begin: u64,
- semantic_end: u64,
- token_upper_bound: usize,
-) -> u32 {
- if semantic_begin > semantic_end || token_upper_bound == 0 {
- return 0;
- }
-
- if semantic_token < semantic_begin || semantic_token > semantic_end {
- return 0;
- }
-
- let relative = usize::try_from(semantic_token - semantic_begin).unwrap_or(0);
- let clamped = relative.min(token_upper_bound.saturating_sub(1));
- u32::try_from(clamped).unwrap_or(0)
-}
-
-pub(super) fn build_semantic_sampling_mask_row(
- vocab_size: usize,
- semantic_begin: u64,
- semantic_end: u64,
- im_end: u64,
-) -> Result<Box<[u32]>, Error> {
- if vocab_size == 0 || semantic_begin > semantic_end {
- return Err(Error::InvalidModelConfig(format!(
- "invalid semantic sampling mask range: vocab_size={vocab_size}, semantic_begin={semantic_begin}, semantic_end={semantic_end}",
- )));
- }
-
- let max_token_id = u64::try_from(vocab_size.saturating_sub(1)).map_err(|_| {
- Error::InvalidModelConfig(format!("vocab_size={vocab_size} cannot be represented as a token id"))
- })?;
- if semantic_end > max_token_id || im_end > max_token_id {
- return Err(Error::InvalidModelConfig(format!(
- "semantic sampling mask token id exceeds vocab: semantic_end={semantic_end}, im_end={im_end}, max_token_id={max_token_id}",
- )));
- }
-
- let row_words = vocab_size.div_ceil(32);
- let mut mask = vec![0_u32; row_words];
- for token_index in semantic_begin..=semantic_end {
- let token = usize::try_from(token_index).map_err(|_| {
- Error::InvalidModelConfig(format!("semantic token id {token_index} cannot be represented as usize"))
- })?;
- let word = token / 32;
- mask[word] |= 2_u32.pow((token % 32) as u32);
- }
- let im_end_token = usize::try_from(im_end)
- .map_err(|_| Error::InvalidModelConfig(format!("im_end token id {im_end} cannot be represented as usize")))?;
- let word = im_end_token / 32;
- mask[word] |= 2_u32.pow((im_end_token % 32) as u32);
- Ok(mask.into_boxed_slice())
-}
-
-pub(super) fn clear_token_in_sampling_mask(
- mask: &mut [u32],
- token: u64,
-) -> Result<(), Error> {
- let token = usize::try_from(token)
- .map_err(|_| Error::InvalidModelConfig(format!("token id {token} cannot be represented as usize")))?;
- let word = token / 32;
- if word >= mask.len() {
- return Err(Error::InvalidModelConfig(format!(
- "token id {token} is outside sampling mask with {} words",
- mask.len(),
- )));
- }
- mask[word] &= !2_u32.pow((token % 32) as u32);
- Ok(())
-}
-
-pub(super) fn expand_token_mask_for_sampling_row(
- row_mask: &[u32],
- token_count: usize,
-) -> Result<Box<[u32]>, Error> {
- if token_count == 0 || row_mask.is_empty() {
- return Err(Error::GenerateFailed);
- }
- if token_count == 1 {
- return Ok(row_mask.to_vec().into_boxed_slice());
- }
-
- let row_words = row_mask.len();
- let total_words = token_count.checked_mul(row_words).ok_or(Error::GenerateFailed)?;
- let mut expanded = vec![u32::MAX; total_words];
- let offset = (token_count - 1).checked_mul(row_words).ok_or(Error::GenerateFailed)?;
- expanded[offset..offset + row_words].copy_from_slice(row_mask);
- Ok(expanded.into_boxed_slice())
-}
diff --git a/crates/backend-uzu/src/session/tts_session/fishaudio.rs b/crates/backend-uzu/src/session/tts_session/fishaudio.rs
deleted file mode 100644
index 7191b4838..000000000
--- a/crates/backend-uzu/src/session/tts_session/fishaudio.rs
+++ /dev/null
@@ -1,805 +0,0 @@
-use super::*;
-use crate::{
- array::ArrayContextExt,
- backends::common::{Allocation, AsBufferRangeRef, DenseBuffer},
- config::{
- decoder::DecoderConfig, embedding::AnyEmbeddingConfig,
- tts::text_decoder::fish_audio_text_decoder::FishAudioTextDecoderConfig,
- },
- forward_pass::token_inputs::TokenInputs,
- session::types::TtsModelConfigError,
-};
-
-pub(super) struct FishAudioTextDecoderRuntime<B: Backend> {
- slow_runner: TokenDecoderRunner<B>,
- fast_runner: TokenDecoderRunner<B>,
- semantic_bridge: FishAudioSemanticBridge<B>,
- runtime_config: TextDecoderRuntimeConfig,
- semantic_token_begin_id: u64,
- semantic_token_end_id: u64,
- semantic_cardinality: usize,
- im_end_token_id: u64,
- codebook_size: usize,
- num_codebooks: usize,
- slow_model_dim: usize,
- fast_model_dim: usize,
- max_seq_len: usize,
- scale_codebook_embeddings: bool,
- fast_vocab_limit: usize,
- apply_semantic_sampling_mask: bool,
- semantic_sampling_mask_row: Box<[u32]>,
- semantic_sampling_mask_without_im_end_row: Box<[u32]>,
- current_codes_scratch: Vec<u32>,
- instrumentation: RunnerInstrumentation,
-}
-
-struct FishAudioSemanticBridge<B: Backend> {
- embedding_rows_sum: <B::Kernels as Kernels>::EmbeddingRowsSumKernel,
- projection: <B::Kernels as Kernels>::MatmulKernel,
- codebook_embeddings: Allocation<B>,
- codebook_token_indices: Allocation<B>,
- projection_weights: Option<Allocation<B>>,
- num_codebooks: usize,
- codebook_size: usize,
- slow_model_dim: usize,
- fast_model_dim: usize,
-}
-
-impl<B: Backend> FishAudioSemanticBridge<B> {
- fn load(
- context: &B::Context,
- parameter_tree: &crate::parameters::ParameterTree<B>,
- config: &FishAudioTextDecoderConfig,
- data_type: DataType,
- ) -> Result<Self, Error> {
- let codebook_embedding_rows = config.codebook_size.checked_mul(config.num_codebooks).ok_or_else(|| {
- Error::InvalidModelConfig(format!(
- "FishAudio codebook embedding rows overflow: codebook_size={}, num_codebooks={}",
- config.codebook_size, config.num_codebooks,
- ))
- })?;
- let codebook_embeddings = parameter_tree
- .leaf("text_decoder.codebook_embeddings.embedding.weights")
- .and_then(|leaf| leaf.validate(&[codebook_embedding_rows, config.slow_model_dim], data_type))
- .and_then(|leaf| leaf.read_allocation())
- .map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let fast_model_projection = if config.fast_model_projection_config.is_some() {
- Some(
- parameter_tree
- .leaf("text_decoder.fast_model_projection.weights.weights")
- .and_then(|leaf| leaf.validate(&[config.fast_model_dim, config.slow_model_dim], data_type))
- .and_then(|leaf| leaf.read_allocation())
- .map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?,
- )
- } else {
- None
- };
-
- Self::new(
- context,
- data_type,
- codebook_embeddings,
- fast_model_projection,
- config.num_codebooks,
- config.codebook_size,
- config.slow_model_dim,
- config.fast_model_dim,
- )
- }
-
- fn new(
- context: &B::Context,
- data_type: DataType,
- codebook_embeddings: Allocation<B>,
- fast_model_projection: Option<Allocation<B>>,
- num_codebooks: usize,
- codebook_size: usize,
- slow_model_dim: usize,
- fast_model_dim: usize,
- ) -> Result<Self, Error> {
- let embedding_rows_sum = <B::Kernels as Kernels>::EmbeddingRowsSumKernel::new(context, data_type)
- .map_err(unable_to_create_context)?;
- let projection =
- <<B::Kernels as Kernels>::MatmulKernel as MatmulKernel>::new(context, data_type, data_type, data_type)
- .map_err(unable_to_create_context)?;
- let codebook_token_indices = context.create_array_zeros(&[num_codebooks], DataType::U32).into_allocation();
-
- Ok(Self {
- embedding_rows_sum,
- projection,
- codebook_embeddings,
- codebook_token_indices,
- projection_weights: fast_model_projection,
- num_codebooks,
- codebook_size,
- slow_model_dim,
- fast_model_dim,
- })
- }
-}
-
-fn validate_fishaudio_decoder_contract(
- num_codebooks: usize,
- codebook_size: usize,
- max_seq_len: usize,
- semantic_token_begin_id: u64,
- semantic_token_end_id: u64,
- audio_num_codebooks: usize,
- audio_codec_cardinality: usize,
- audio_semantic_cardinality: usize,
-) -> Result<usize, Error> {
- if num_codebooks <= 1 || codebook_size == 0 || max_seq_len == 0 {
- return Err(TtsModelConfigError::FishAudioDecoderCoreParametersInvalid {
- num_codebooks,
- codebook_size,
- max_seq_len,
- }
- .into());
- }
- if num_codebooks != audio_num_codebooks {
- return Err(TtsModelConfigError::FishAudioDecoderNumCodebooksMismatch {
- decoder_num_codebooks: num_codebooks,
- audio_num_codebooks,
- }
- .into());
- }
- if audio_codec_cardinality == 0 || audio_codec_cardinality > codebook_size {
- return Err(TtsModelConfigError::FishAudioDecoderCodebookSizeTooSmall {
- codebook_size,
- audio_codec_cardinality,
- }
- .into());
- }
- if semantic_token_begin_id > semantic_token_end_id {
- return Err(TtsModelConfigError::FishAudioSemanticTokenRangeInvalid {
- begin: semantic_token_begin_id,
- end: semantic_token_end_id,
- }
- .into());
- }
-
- let semantic_cardinality = semantic_token_end_id
- .checked_sub(semantic_token_begin_id)
- .and_then(|value| value.checked_add(1))
- .and_then(|value| usize::try_from(value).ok())
- .ok_or(TtsModelConfigError::FishAudioSemanticTokenRangeOverflow {
- begin: semantic_token_begin_id,
- end: semantic_token_end_id,
- })?;
- if semantic_cardinality == 0 || semantic_cardinality != audio_semantic_cardinality {
- return Err(TtsModelConfigError::FishAudioSemanticCodecCardinalityMismatch {
- semantic_cardinality,
- audio_semantic_cardinality,
- }
- .into());
- }
-
- Ok(semantic_cardinality)
-}
-
-pub(super) fn build_fishaudio_text_decoder_runtime<B: Backend>(
- config: &FishAudioTextDecoderConfig,
- audio: &AudioGenerationContext<B>,
- model_path: &Path,
- runtime_config: &TextDecoderRuntimeConfig,
-) -> Result<Box<dyn SemanticDecoderBackend>, Error> {
- let audio_semantic_cardinality = audio.runtime().config().semantic_codec_cardinality().ok_or_else(|| {
- Error::InvalidModelConfig("audio decoder does not expose semantic codec cardinality".to_string())
- })?;
- let semantic_cardinality = validate_fishaudio_decoder_contract(
- config.num_codebooks,
- config.codebook_size,
- config.max_seq_len,
- config.semantic_token_begin_id,
- config.semantic_token_end_id,
- audio.num_codebooks(),
- audio.codec_cardinality(),
- audio_semantic_cardinality,
- )?;
- if config.slow_model_config.model_dim != config.slow_model_dim {
- return Err(Error::InvalidModelConfig(format!(
- "FishAudio slow model_dim mismatch: transformer={}, configured={}",
- config.slow_model_config.model_dim, config.slow_model_dim,
- )));
- }
- if config.fast_model_config.model_dim != config.fast_model_dim {
- return Err(Error::InvalidModelConfig(format!(
- "FishAudio fast model_dim mismatch: transformer={}, configured={}",
- config.fast_model_config.model_dim, config.fast_model_dim,
- )));
- }
- if config.short_logits_size == 0 {
- return Err(Error::InvalidModelConfig("FishAudio short_logits_size must be greater than 0".to_string()));
- }
- let semantic_sampling_mask_row = build_semantic_sampling_mask_row(
- config.vocab_size,
- config.semantic_token_begin_id,
- config.semantic_token_end_id,
- config.im_end_token_id,
- )?;
- let mut semantic_sampling_mask_without_im_end_row = semantic_sampling_mask_row.to_vec();
- clear_token_in_sampling_mask(&mut semantic_sampling_mask_without_im_end_row, config.im_end_token_id)?;
-
- let slow_transformer_config = config.slow_model_config.clone();
- let fast_transformer_config = config.fast_model_config.clone();
-
- let slow_decoder_config = Rc::new(DecoderConfig {
- embedding_config: AnyEmbeddingConfig::TiedEmbeddingConfig(config.slow_embeddings_config.clone()),
- transformer_config: slow_transformer_config,
- vocab_size: config.vocab_size,
- ple_model_config: None,
- });
- let fast_decoder_config = Rc::new(DecoderConfig {
- embedding_config: AnyEmbeddingConfig::TiedEmbeddingConfig(config.fast_embeddings_config.clone()),
- transformer_config: fast_transformer_config,
- vocab_size: config.codebook_size,
- ple_model_config: None,
- });
- let text_decoder_context = B::Context::new().map_err(unable_to_create_context)?;
-
- let slow_runner = TokenDecoderRunner::new_with_context(
- text_decoder_context.clone(),
- model_path,
- slow_decoder_config,
- "text_decoder.transformer_slow",
- "text_decoder.embeddings_slow",
- "text_decoder.readout_slow",
- runtime_config,
- )?;
-
- let fast_runner = TokenDecoderRunner::new_with_context(
- text_decoder_context.clone(),
- model_path,
- fast_decoder_config,
- "text_decoder.transformer_fast",
- "text_decoder.embeddings_fast",
- "text_decoder.readout_fast",
- runtime_config,
- )?;
-
- let activation_data_type = slow_runner.activation_data_type();
- let fast_data_type = fast_runner.activation_data_type();
- if fast_data_type != activation_data_type {
- return Err(Error::InvalidModelConfig(format!(
- "FishAudio slow/fast activation data type mismatch: slow={activation_data_type:?}, fast={fast_data_type:?}",
- )));
- }
-
- let weights_path = model_path.join("model.safetensors");
- let weights_file = File::open(&weights_path).map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let loader = ParameterLoader::new(&weights_file, text_decoder_context.as_ref())
- .map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let root_weights = loader.tree();
-
- let apply_semantic_sampling_mask =
- runtime_config.force_semantic_sampling_mask.unwrap_or(!matches!(activation_data_type, DataType::F32));
-
- let semantic_bridge =
- FishAudioSemanticBridge::load(text_decoder_context.as_ref(), &root_weights, config, activation_data_type)?;
-
- Ok(Box::new(FishAudioTextDecoderRuntime::<B> {
- slow_runner,
- fast_runner,
- semantic_bridge,
- runtime_config: runtime_config.clone(),
- semantic_token_begin_id: config.semantic_token_begin_id,
- semantic_token_end_id: config.semantic_token_end_id,
- semantic_cardinality,
- im_end_token_id: config.im_end_token_id,
- codebook_size: config.codebook_size,
- num_codebooks: config.num_codebooks,
- slow_model_dim: config.slow_model_dim,
- fast_model_dim: config.fast_model_dim,
- max_seq_len: config.max_seq_len,
- scale_codebook_embeddings: config.scale_codebook_embeddings,
- fast_vocab_limit: config.short_logits_size.min(config.codebook_size),
- apply_semantic_sampling_mask,
- semantic_sampling_mask_row,
- semantic_sampling_mask_without_im_end_row: semantic_sampling_mask_without_im_end_row.into_boxed_slice(),
- current_codes_scratch: vec![0_u32; config.num_codebooks],
- instrumentation: RunnerInstrumentation::default(),
- }))
-}
-
-impl<B: Backend> FishAudioTextDecoderRuntime<B> {
- fn generate_semantic_tokens_internal(
- &mut self,
- text_tokens: &[u64],
- codec_cardinality: usize,
- seed: u64,
- max_semantic_frames: usize,
- mut on_frame: Option<&mut dyn FnMut(&[u32]) -> Result<(), Error>>,
- ) -> Result<AudioTokenGrid, Error> {
- if text_tokens.is_empty() {
- return Ok(AudioTokenGrid::new(
- Vec::new().into_boxed_slice(),
- 1,
- self.num_codebooks,
- 0,
- vec![0].into_boxed_slice(),
- )?);
- }
- if text_tokens.len() >= self.max_seq_len {
- return Err(Error::GenerateFailed);
- }
-
- if codec_cardinality == 0 || codec_cardinality > self.codebook_size {
- return Err(Error::InvalidModelConfig(format!(
- "FishAudio codec cardinality {codec_cardinality} must be in 1..={}",
- self.codebook_size,
- )));
- }
- let semantic_token_upper_bound = self.semantic_cardinality;
- let residual_token_upper_bound = codec_cardinality;
- if semantic_token_upper_bound == 0 || residual_token_upper_bound == 0 {
- return Err(Error::InvalidModelConfig(format!(
- "FishAudio token upper bounds must be positive: semantic={semantic_token_upper_bound}, residual={residual_token_upper_bound}",
- )));
- }
-
- self.reset_generation_state();
- let mut sampling = TextSamplingState::from_config(seed, &self.runtime_config.sampling);
-
- let mut max_new_tokens = self.max_seq_len.saturating_sub(text_tokens.len());
- max_new_tokens = max_new_tokens.min(max_semantic_frames.max(1));
- if let Some(limit) = self.runtime_config.max_new_tokens_override {
- max_new_tokens = max_new_tokens.min(limit);
- }
- self.slow_runner.prepare_for_generation(text_tokens.len() + max_new_tokens)?;
- self.fast_runner.prepare_for_generation(self.num_codebooks + 1)?;
-
- let mut current_semantic_token = self.decode_initial_semantic_token(text_tokens, &mut sampling)?;
- let post_scale = if self.scale_codebook_embeddings {
- Some(1.0 / ((self.num_codebooks + 1) as f32).sqrt())
- } else {
- None
- };
- let mut by_codebook =
- (0..self.num_codebooks).map(|_| Vec::<u32>::with_capacity(max_new_tokens)).collect::<Vec<_>>();
- if self.current_codes_scratch.len() != self.num_codebooks {
- self.current_codes_scratch = vec![0_u32; self.num_codebooks];
- }
-
- self.prepare_fast_runner_masks(residual_token_upper_bound)?;
-
- for _step in 0..max_new_tokens {
- if current_semantic_token == self.im_end_token_id {
- break;
- }
- let first_code = semantic_token_to_code(
- current_semantic_token,
- self.semantic_token_begin_id,
- self.semantic_token_end_id,
- semantic_token_upper_bound,
- );
- by_codebook[0].push(first_code);
- self.current_codes_scratch[0] = first_code;
-
- current_semantic_token = self.decode_frame_merged(
- current_semantic_token,
- first_code,
- residual_token_upper_bound,
- post_scale,
- &mut sampling,
- &mut by_codebook,
- )?;
-
- if let Some(callback) = on_frame.as_mut() {
- callback(&self.current_codes_scratch)?;
- }
- }
-
- self.instrumentation = self.slow_runner.take_instrumentation();
- let fast = self.fast_runner.take_instrumentation();
- self.instrumentation.command_buffers_submitted += fast.command_buffers_submitted;
- self.instrumentation.host_waits += fast.host_waits;
-
- self.finish_semantic_grid(&by_codebook)
- }
-
- fn reset_generation_state(&mut self) {
- self.instrumentation = RunnerInstrumentation::default();
- self.slow_runner.reset();
- self.slow_runner.clear_instrumentation();
- self.fast_runner.clear_instrumentation();
- }
-
- fn decode_initial_semantic_token(
- &mut self,
- text_tokens: &[u64],
- sampling: &mut TextSamplingState,
- ) -> Result<u64, Error> {
- let slow_runner = &mut self.slow_runner;
- let initial_sampling_row = if self.apply_semantic_sampling_mask {
- if self.runtime_config.min_frames_before_im_end > 0 {
- self.semantic_sampling_mask_without_im_end_row.as_ref()
- } else {
- self.semantic_sampling_mask_row.as_ref()
- }
- } else {
- &[]
- };
- let prefill_step_size = text_decoder_prefill_step_size(&self.runtime_config, self.max_seq_len);
- if text_tokens.len() > prefill_step_size {
- for chunk in text_tokens[..text_tokens.len() - prefill_step_size].chunks(prefill_step_size) {
- slow_runner.prefill_without_sampling(chunk)?;
- }
- }
- let prefill_tail_start = text_tokens.len().saturating_sub(prefill_step_size);
- let prefill_tail = &text_tokens[prefill_tail_start..];
- let prefill_mask = if initial_sampling_row.is_empty() {
- None
- } else {
- Some(expand_token_mask_for_sampling_row(initial_sampling_row, prefill_tail.len())?)
- };
- slow_runner.decode_next_token_with_hidden_capture(
- prefill_tail,
- EmbeddingInjection::None,
- sampling,
- prefill_mask.as_deref(),
- )
- }
-
- fn prepare_fast_runner_masks(
- &mut self,
- residual_token_upper_bound: usize,
- ) -> Result<(), Error> {
- let fast_vocab_limit = self.fast_vocab_limit.min(residual_token_upper_bound);
- if fast_vocab_limit == 0 {
- return Err(Error::InvalidModelConfig(format!(
- "FishAudio fast vocab limit is zero: configured={}, residual={residual_token_upper_bound}",
- self.fast_vocab_limit,
- )));
- }
- self.fast_runner.prepare_single_token_vocab_mask(fast_vocab_limit)?;
- self.fast_runner.prepare_two_token_vocab_mask(fast_vocab_limit)?;
- Ok(())
- }
-
- fn finish_semantic_grid(
- &self,
- by_codebook: &[Vec<u32>],
- ) -> Result<AudioTokenGrid, Error> {
- let frames = by_codebook.first().map_or(0, Vec::len);
- let mut tokens = Vec::with_capacity(self.num_codebooks * frames);
- for codebook_tokens in by_codebook {
- if codebook_tokens.len() != frames {
- return Err(Error::GenerateFailed);
- }
- tokens.extend_from_slice(codebook_tokens);
- }
- Ok(AudioTokenGrid::new(
- tokens.into_boxed_slice(),
- 1,
- self.num_codebooks,
- frames,
- vec![frames].into_boxed_slice(),
- )?)
- }
-
- fn encode_project_slow_hidden_to_fast_on(
- semantic_bridge: &mut FishAudioSemanticBridge<B>,
- slow_hidden_capture: &Allocation<B>,
- output_embedding: &mut Allocation<B>,
- slow_model_dim: usize,
- fast_model_dim: usize,
- encoder: &mut Encoder<B>,
- ) -> Result<(), Error> {
- if let Some(weights) = semantic_bridge.projection_weights.as_ref() {
- if semantic_bridge.fast_model_dim != fast_model_dim || semantic_bridge.slow_model_dim != slow_model_dim {
- return Err(Error::GenerateFailed);
- }
- semantic_bridge
- .projection
- .encode(
- MatmulArguments {
- a: slow_hidden_capture,
- a_offset: 0,
- b: MatmulB::FullPrecision {
- b: weights,
- },
- b_offset: 0,
- b_leading_dimension: None,
- b_transpose: true,
- d: output_embedding,
- d_transform: MatmulDOps::none(),
- m: 1,
- n: fast_model_dim as u32,
- k: slow_model_dim as u32,
- },
- encoder,
- )
- .expect("encode failed");
- return Ok(());
- }
-
- if slow_model_dim != fast_model_dim {
- return Err(Error::InvalidModelConfig(format!(
- "FishAudio slow_model_dim={slow_model_dim} must equal fast_model_dim={fast_model_dim} without projection weights",
- )));
- }
-
- debug_assert_eq!(
- slow_hidden_capture.as_buffer_range_ref().range().len(),
- output_embedding.as_buffer_range_ref().range().len()
- );
- encoder.encode_copy(slow_hidden_capture, .., output_embedding, ..);
- Ok(())
- }
-
- /// Encode the codebook sum reading residual
- /// codes directly from a GPU buffer instead of from CPU memory.
- ///
- /// `first_code` is written into slot 0 of the staging buffer from CPU.
- /// Slots 1..num_codebooks are filled by a GPU blit from
- /// `gpu_tokens_buffer` at the given byte offset.
- fn encode_slow_codebook_sum_from_gpu_tokens_on(
- semantic_bridge: &mut FishAudioSemanticBridge<B>,
- slow_sum_embedding: &mut Allocation<B>,
- first_code: u32,
- source_runner: &mut TokenDecoderRunner<B>,
- source_slot: usize,
- num_codebooks: usize,
- codebook_size: usize,
- slow_model_dim: usize,
- encoder: &mut Encoder<B>,
- ) -> Result<(), Error> {
- if num_codebooks == 0 {
- return Err(Error::InvalidModelConfig("FishAudio num_codebooks must be greater than 0".to_string()));
- }
-
- // Write first_code at position 0 from CPU.
- {
- if semantic_bridge.num_codebooks != num_codebooks {
- return Err(Error::GenerateFailed);
- }
- let buffer_range = semantic_bridge.codebook_token_indices.as_buffer_range_ref();
- let range = buffer_range.range();
- unsafe {
- let ptr = (buffer_range.buffer().cpu_ptr().as_ptr() as *mut u8).add(range.start) as *mut u32;
- *ptr = first_code;
- }
- }
-
- // Blit residual codes from GPU: async_chain_results[0..N-2] -> codebook_token_indices[1..N-1]
- let residual_count = num_codebooks.saturating_sub(1);
- if residual_count > 0 {
- let dst_byte_offset = std::mem::size_of::<u32>(); // skip slot 0
- source_runner.copy_async_chain_results_to_on(
- encoder,
- source_slot,
- &mut semantic_bridge.codebook_token_indices,
- dst_byte_offset,
- residual_count,
- )?;
- }
-
- let total_vocab_u32 = (num_codebooks * codebook_size) as u32;
- let num_codebooks_u32 = num_codebooks as u32;
- let slow_model_dim_u32 = slow_model_dim as u32;
- let codebook_size_u32 = codebook_size as u32;
-
- let codebook_token_indices = &semantic_bridge.codebook_token_indices;
- let codebook_embeddings = &semantic_bridge.codebook_embeddings;
- if semantic_bridge.num_codebooks != num_codebooks
- || semantic_bridge.codebook_size != codebook_size
- || semantic_bridge.slow_model_dim != slow_model_dim
- {
- return Err(Error::GenerateFailed);
- }
- semantic_bridge.embedding_rows_sum.encode(
- codebook_token_indices,
- codebook_embeddings,
- slow_sum_embedding,
- num_codebooks_u32,
- total_vocab_u32,
- slow_model_dim_u32,
- codebook_size_u32,
- encoder,
- );
- Ok(())
- }
-
- /// Merged fast+slow frame: encodes all fast runner forward passes, the
- /// codebook sum (reading GPU tokens directly), and the slow runner
- /// forward pass into a **single** command buffer submission.
- ///
- /// Returns the next semantic token.
- fn decode_frame_merged(
- &mut self,
- current_semantic_token: u64,
- first_code: u32,
- residual_token_upper_bound: usize,
- post_scale: Option<f32>,
- sampling: &mut TextSamplingState,
- by_codebook: &mut [Vec<u32>],
- ) -> Result<u64, Error> {
- let fast_vocab_limit = self.fast_vocab_limit.min(residual_token_upper_bound);
- let followup_count = self.num_codebooks.saturating_sub(2);
-
- self.fast_runner.reset();
-
- let context = Rc::clone(self.fast_runner.context());
- let mut shared_encoder = Encoder::new(context.as_ref()).map_err(unable_to_create_context)?;
-
- let mut pending_token_inputs = Vec::new();
- let mut pending_sampling_allocations = Vec::new();
- let mut pending_sampling_outputs = Vec::new();
- let total_fast_count = self.encode_fast_passes_on(
- &mut shared_encoder,
- first_code,
- fast_vocab_limit,
- followup_count,
- sampling,
- &mut pending_token_inputs,
- &mut pending_sampling_allocations,
- &mut pending_sampling_outputs,
- )?;
- self.encode_slow_pass_on(
- &mut shared_encoder,
- current_semantic_token,
- first_code,
- post_scale,
- sampling,
- by_codebook,
- &mut pending_token_inputs,
- &mut pending_sampling_allocations,
- &mut pending_sampling_outputs,
- )?;
- let submit_result = self.slow_runner.submit_and_wait_command_buffer(shared_encoder);
- submit_result?;
-
- for pass in 0..total_fast_count {
- let sampled = self.fast_runner.read_async_chain_result(pass)?;
- let codebook_index = pass + 1;
- let clamped = (sampled as usize).min(residual_token_upper_bound.saturating_sub(1));
- let clamped = clamped as u32;
- by_codebook[codebook_index].push(clamped);
- self.current_codes_scratch[codebook_index] = clamped;
- }
-
- let slow_token = u64::from(self.slow_runner.read_async_chain_result(0)?);
- Ok(slow_token)
- }
-
- /// Encode the fast runner's initial + followup passes onto the shared
- /// command buffer.
- fn encode_fast_passes_on(
- &mut self,
- encoder: &mut Encoder<B>,
- first_code: u32,
- fast_vocab_limit: usize,
- followup_count: usize,
- sampling: &mut TextSamplingState,
- pending_token_inputs: &mut Vec<TokenInputs<B>>,
- pending_sampling_allocations: &mut Vec<Allocation<B>>,
- pending_sampling_outputs: &mut Vec<Allocation<B>>,
- ) -> Result<usize, Error> {
- let (slow_runner, fast_runner, semantic_bridge) =
- (&mut self.slow_runner, &mut self.fast_runner, &mut self.semantic_bridge);
- let slow_hidden_capture = &slow_runner.single_hidden_capture;
- let slow_model_dim = self.slow_model_dim;
- let fast_model_dim = self.fast_model_dim;
-
- let mut pre_projection = |runner: &mut TokenDecoderRunner<B>, encoder: &mut Encoder<B>| {
- Self::encode_project_slow_hidden_to_fast_on(
- semantic_bridge,
- slow_hidden_capture,
- &mut runner.single_override_embedding,
- slow_model_dim,
- fast_model_dim,
- encoder,
- )
- };
-
- fast_runner.encode_first_and_followup_tokens_on(
- encoder,
- &[0, u64::from(first_code)],
- EmbeddingInjection::OverrideFirstRowInternal,
- Some(&mut pre_projection),
- followup_count,
- Some(fast_vocab_limit),
- sampling,
- pending_token_inputs,
- pending_sampling_allocations,
- pending_sampling_outputs,
- )
- }
-
- /// Encode the slow runner's forward pass onto the shared command buffer.
- fn encode_slow_pass_on(
- &mut self,
- encoder: &mut Encoder<B>,
- current_semantic_token: u64,
- first_code: u32,
- post_scale: Option<f32>,
- sampling: &mut TextSamplingState,
- by_codebook: &[Vec<u32>],
- pending_token_inputs: &mut Vec<TokenInputs<B>>,
- pending_sampling_allocations: &mut Vec<Allocation<B>>,
- pending_sampling_outputs: &mut Vec<Allocation<B>>,
- ) -> Result<(), Error> {
- let (slow_runner, fast_runner, semantic_bridge) =
- (&mut self.slow_runner, &mut self.fast_runner, &mut self.semantic_bridge);
- let num_codebooks = self.num_codebooks;
- let codebook_size = self.codebook_size;
- let slow_model_dim = self.slow_model_dim;
-
- let sampled_frames = by_codebook[0].len();
- let slow_sampling_mask = if self.apply_semantic_sampling_mask {
- if sampled_frames < self.runtime_config.min_frames_before_im_end {
- Some(self.semantic_sampling_mask_without_im_end_row.as_ref())
- } else {
- Some(self.semantic_sampling_mask_row.as_ref())
- }
- } else {
- None
- };
-
- let mut pre_codebook_sum = |runner: &mut TokenDecoderRunner<B>, encoder: &mut Encoder<B>| {
- Self::encode_slow_codebook_sum_from_gpu_tokens_on(
- semantic_bridge,
- &mut runner.single_override_embedding,
- first_code,
- fast_runner,
- 0,
- num_codebooks,
- codebook_size,
- slow_model_dim,
- encoder,
- )
- };
-
- slow_runner.encode_next_step_on(
- encoder,
- &[current_semantic_token],
- EmbeddingInjection::AddPreloaded {
- post_scale,
- },
- sampling,
- slow_sampling_mask,
- true, // capture_hidden
- Some(&mut pre_codebook_sum),
- pending_token_inputs,
- pending_sampling_allocations,
- pending_sampling_outputs,
- )
- }
-
- fn take_instrumentation(&mut self) -> RunnerInstrumentation {
- std::mem::take(&mut self.instrumentation)
- }
-}
-
-impl<B: Backend> SemanticDecoderBackend for FishAudioTextDecoderRuntime<B> {
- fn generate_semantic_tokens(
- &mut self,
- text_tokens: &[u64],
- codec_cardinality: usize,
- seed: u64,
- max_semantic_frames: usize,
- ) -> Result<AudioTokenGrid, Error> {
- self.generate_semantic_tokens_internal(text_tokens, codec_cardinality, seed, max_semantic_frames, None)
- }
-
- fn generate_semantic_tokens_with_callback(
- &mut self,
- text_tokens: &[u64],
- codec_cardinality: usize,
- seed: u64,
- max_semantic_frames: usize,
- on_frame: &mut dyn FnMut(&[u32]) -> Result<(), Error>,
- ) -> Result<AudioTokenGrid, Error> {
- self.generate_semantic_tokens_internal(
- text_tokens,
- codec_cardinality,
- seed,
- max_semantic_frames,
- Some(on_frame),
- )
- }
-
- fn take_instrumentation(&mut self) -> RunnerInstrumentation {
- FishAudioTextDecoderRuntime::take_instrumentation(self)
- }
-}
diff --git a/crates/backend-uzu/src/session/tts_session/generator.rs b/crates/backend-uzu/src/session/tts_session/generator.rs
deleted file mode 100644
index cc282b849..000000000
--- a/crates/backend-uzu/src/session/tts_session/generator.rs
+++ /dev/null
@@ -1,424 +0,0 @@
-use super::*;
-
-impl<B: Backend + Send + Sync> TtsSession<B> {
- pub fn synthesize(
- &mut self,
- input: Input,
- ) -> Result<AudioPcmBatch, Error> {
- self.synthesize_with_seed_and_config(input, TtsRunConfig::default().default_seed, &TtsRunConfig::default())
- }
-
- pub fn synthesize_with_seed(
- &mut self,
- input: Input,
- seed: u64,
- ) -> Result<AudioPcmBatch, Error> {
- self.synthesize_with_seed_and_config(input, seed, &TtsRunConfig::default())
- }
-
- pub fn synthesize_with_config(
- &mut self,
- input: Input,
- config: &TtsRunConfig,
- ) -> Result<AudioPcmBatch, Error> {
- self.synthesize_with_seed_and_config(input, config.default_seed, config)
- }
-
- pub fn synthesize_with_seed_and_config(
- &mut self,
- input: Input,
- seed: u64,
- config: &TtsRunConfig,
- ) -> Result<AudioPcmBatch, Error> {
- config.validate()?;
-
- let prompt = self.render_prompt(&input)?;
- let text_tokens: Vec<u64> = self
- .tokenizer
- .encode(prompt.as_str(), false)
- .map_err(Error::UnableToEncodeText)?
- .get_ids()
- .iter()
- .map(|&token| token as u64)
- .collect();
-
- let semantic_start = Instant::now();
- let semantic_tokens = self.generate_semantic_tokens(&text_tokens, seed, config.max_semantic_frames)?;
- let semantic_decode_seconds = semantic_start.elapsed().as_secs_f64();
- let instrumentation = self.take_text_decoder_instrumentation();
-
- let audio_start = Instant::now();
- let mut audio_decode_calls = 0usize;
- let mut audio_input_frames = 0usize;
- let mut audio_decoded_window_frames = 0usize;
- let mut audio_max_decoded_window_frames = 0usize;
- let pcm = match config.non_streaming_mode {
- crate::session::config::TtsNonStreamingMode::FullDecode => {
- audio_decode_calls = usize::from(semantic_tokens.frames() > 0);
- audio_input_frames = semantic_tokens.frames();
- audio_decoded_window_frames = semantic_tokens.frames();
- audio_max_decoded_window_frames = semantic_tokens.frames();
- self.audio_decoder.decode(&semantic_tokens)?
- },
- crate::session::config::TtsNonStreamingMode::ChunkedIfNeeded => {
- if semantic_tokens.batch_size() != 1 {
- return Err(Error::GenerateFailed);
- }
- config.validate_stream_decode()?;
- let total_frames = semantic_tokens.frames();
- let chunked_threshold = config.max_stream_workspace_frames.max(config.max_chunk_frames.max(1));
- if total_frames <= chunked_threshold {
- audio_decode_calls = usize::from(total_frames > 0);
- audio_input_frames = total_frames;
- audio_decoded_window_frames = total_frames;
- audio_max_decoded_window_frames = total_frames;
- self.audio_decoder.decode(&semantic_tokens)?
- } else {
- let chunk_frames = config.max_chunk_frames.max(config.min_chunk_frames.max(1));
- let mut stream = self.audio_decoder.begin_stream(
- semantic_tokens.batch_size(),
- semantic_tokens.codebooks(),
- config.max_stream_workspace_frames,
- )?;
-
- let mut all_samples = Vec::<f32>::with_capacity(total_frames.saturating_mul(512));
- let mut accumulated_lengths = vec![0usize; semantic_tokens.batch_size()];
- let mut sample_rate = self.audio_decoder.sample_rate();
- let mut channels = 1usize;
-
- let mut frame_start = 0usize;
- while frame_start < total_frames {
- let frame_end = (frame_start + chunk_frames).min(total_frames);
- let delta_grid = slice_grid_range(&semantic_tokens, frame_start, frame_end)?;
- let partial_pcm = stream.decode_step(&delta_grid, frame_end == total_frames)?;
- accumulate_audio_decode_step_stats(
- &mut audio_decode_calls,
- &mut audio_input_frames,
- &mut audio_decoded_window_frames,
- &mut audio_max_decoded_window_frames,
- stream.last_step_stats(),
- );
- if partial_pcm.lengths().len() != accumulated_lengths.len() {
- return Err(Error::GenerateFailed);
- }
- for (acc, &len) in accumulated_lengths.iter_mut().zip(partial_pcm.lengths().iter()) {
- *acc = acc.saturating_add(len);
- }
- if !partial_pcm.samples().is_empty() {
- all_samples.extend_from_slice(partial_pcm.samples());
- }
- sample_rate = partial_pcm.sample_rate();
- channels = partial_pcm.channels();
- frame_start = frame_end;
- }
- stream.finish()?;
- AudioPcmBatch::new(
- all_samples.into_boxed_slice(),
- sample_rate,
- channels,
- accumulated_lengths.into_boxed_slice(),
- )?
- }
- },
- };
- let audio_decode_seconds = audio_start.elapsed().as_secs_f64();
-
- self.record_last_execution_stats(TtsExecutionStats {
- semantic_decode_seconds,
- audio_decode_seconds,
- callback_seconds: 0.0,
- first_chunk_seconds: 0.0,
- command_buffers_submitted: instrumentation.command_buffers_submitted,
- host_waits: instrumentation.host_waits,
- semantic_frames: semantic_tokens.frames(),
- first_chunk_frames: 0,
- emitted_chunks: usize::from(config.streaming_enabled),
- audio_decode_calls,
- audio_input_frames,
- audio_decoded_window_frames,
- audio_max_decoded_window_frames,
- });
-
- Ok(pcm)
- }
-
- pub fn generate_semantic_tokens_with_seed(
- &mut self,
- input: Input,
- seed: u64,
- ) -> Result<AudioTokenGrid, Error> {
- self.generate_semantic_tokens_with_seed_and_config(input, seed, &TtsRunConfig::default())
- }
-
- pub fn generate_semantic_tokens_with_seed_and_config(
- &mut self,
- input: Input,
- seed: u64,
- config: &TtsRunConfig,
- ) -> Result<AudioTokenGrid, Error> {
- config.validate()?;
- let prompt = self.render_prompt(&input)?;
- let text_tokens: Vec<u64> = self
- .tokenizer
- .encode(prompt.as_str(), false)
- .map_err(Error::UnableToEncodeText)?
- .get_ids()
- .iter()
- .map(|&token| token as u64)
- .collect();
-
- self.generate_semantic_tokens(&text_tokens, seed, config.max_semantic_frames)
- }
-
- pub fn synthesize_streaming<F>(
- &mut self,
- input: Input,
- chunk_frames: usize,
- on_chunk: F,
- ) -> Result<AudioPcmBatch, Error>
- where
- F: FnMut(&AudioPcmBatch),
- {
- let config = TtsRunConfig::default();
- self.synthesize_streaming_with_seed(input, config.default_seed, chunk_frames, on_chunk)
- }
-
- pub fn synthesize_streaming_with_seed<F>(
- &mut self,
- input: Input,
- seed: u64,
- chunk_frames: usize,
- on_chunk: F,
- ) -> Result<AudioPcmBatch, Error>
- where
- F: FnMut(&AudioPcmBatch),
- {
- let config = TtsRunConfig::fixed_chunk_frames(chunk_frames);
- self.synthesize_streaming_with_seed_and_config(input, seed, &config, on_chunk)
- }
-
- pub fn synthesize_streaming_with_config<F>(
- &mut self,
- input: Input,
- config: &TtsRunConfig,
- on_chunk: F,
- ) -> Result<AudioPcmBatch, Error>
- where
- F: FnMut(&AudioPcmBatch),
- {
- self.synthesize_streaming_with_seed_and_config(input, config.default_seed, config, on_chunk)
- }
-
- pub fn synthesize_streaming_with_seed_and_config<F>(
- &mut self,
- input: Input,
- seed: u64,
- config: &TtsRunConfig,
- mut on_chunk: F,
- ) -> Result<AudioPcmBatch, Error>
- where
- F: FnMut(&AudioPcmBatch),
- {
- if !config.streaming_enabled {
- let pcm = self.synthesize_with_seed_and_config(input, seed, config)?;
- on_chunk(&pcm);
- return Ok(pcm);
- }
- config.validate_stream_decode()?;
-
- let prompt = self.render_prompt(&input)?;
- let text_tokens: Vec<u64> = self
- .tokenizer
- .encode(prompt.as_str(), false)
- .map_err(Error::UnableToEncodeText)?
- .get_ids()
- .iter()
- .map(|&token| token as u64)
- .collect();
-
- let mut streamed_tokens = StreamingTokenAccumulator::new(self.audio_decoder.num_codebooks())?;
- let mut audio_stream = self.audio_decoder.begin_stream(
- 1,
- self.audio_decoder.num_codebooks(),
- config.max_stream_workspace_frames,
- )?;
- let mut last_decoded_frames = 0usize;
- let startup_cap_frames = config.max_chunk_frames.max(config.min_chunk_frames.max(1));
- let initial_chunk_frames = config.initial_chunk_frames.max(1).min(startup_cap_frames);
-
- let mut ss = StreamingSynthesisState {
- on_chunk: &mut on_chunk,
- pending_chunk: None,
- callback_seconds: 0.0,
- audio_decode_seconds_in_loop: 0.0,
- audio_decode_seconds: 0.0,
- output_samples: Vec::with_capacity(config.max_semantic_frames.saturating_mul(512)),
- output_frames: 0,
- output_sample_rate: self.audio_decoder.sample_rate(),
- output_channels: 1,
- emitted_chunks: 0,
- first_emit_pending: true,
- first_chunk_seconds: None,
- first_chunk_frames: 0,
- stream_start: Instant::now(),
- startup_target_frames: initial_chunk_frames,
- startup_cap_frames,
- chunk_controller: AdaptiveChunkController::new(config),
- audio_decode_calls: 0,
- audio_input_frames: 0,
- audio_decoded_window_frames: 0,
- audio_max_decoded_window_frames: 0,
- };
-
- let semantic_start = Instant::now();
- let semantic_tokens = self.generate_semantic_tokens_with_callback(
- &text_tokens,
- seed,
- config.max_semantic_frames,
- &mut |codes| {
- ss.maybe_flush_pending(false, true, config)?;
- streamed_tokens.push_frame(codes)?;
- let ready_frames = streamed_tokens.frames().saturating_sub(last_decoded_frames);
- let adaptive_target_frames = ss.chunk_controller.target_frames(config);
- let target_frames = if ss.first_emit_pending {
- ss.startup_target_frames
- } else {
- adaptive_target_frames
- };
- if ready_frames >= target_frames && ss.pending_chunk.is_none() {
- let partial_grid = streamed_tokens.to_grid_range(last_decoded_frames, streamed_tokens.frames())?;
- last_decoded_frames = streamed_tokens.frames();
- let pending_next_chunk_frames = if ss.first_emit_pending {
- adaptive_target_frames
- } else {
- target_frames
- };
- let decode_start = Instant::now();
- let pending_audio_chunk = audio_stream.decode_step_pending(&partial_grid, false)?;
- ss.pending_chunk = Some(PendingStreamingChunk {
- submission_decode_duration: decode_start.elapsed(),
- ready_frames,
- next_chunk_frames: pending_next_chunk_frames,
- chunk: pending_audio_chunk,
- });
- ss.maybe_flush_pending(false, true, config)?;
- }
- Ok(())
- },
- )?;
- let semantic_loop_seconds = semantic_start.elapsed().as_secs_f64();
-
- ss.maybe_flush_pending(true, false, config)?;
-
- if last_decoded_frames < semantic_tokens.frames() {
- let final_decode_start = Instant::now();
- let final_delta_grid = streamed_tokens.to_grid_range(last_decoded_frames, semantic_tokens.frames())?;
- let final_pcm = audio_stream.decode_step(&final_delta_grid, true)?;
- accumulate_audio_decode_step_stats(
- &mut ss.audio_decode_calls,
- &mut ss.audio_input_frames,
- &mut ss.audio_decoded_window_frames,
- &mut ss.audio_max_decoded_window_frames,
- audio_stream.last_step_stats(),
- );
- ss.audio_decode_seconds += final_decode_start.elapsed().as_secs_f64();
- let callback_start = Instant::now();
- let emitted_frames = if final_pcm.lengths().len() == 1 {
- final_pcm.lengths()[0]
- } else {
- return Err(Error::GenerateFailed);
- };
- if emitted_frames > 0 {
- (ss.on_chunk)(&final_pcm);
- }
- ss.callback_seconds += callback_start.elapsed().as_secs_f64();
- if emitted_frames > 0 {
- ss.output_samples.extend_from_slice(final_pcm.samples());
- ss.output_frames = ss.output_frames.saturating_add(emitted_frames);
- ss.output_sample_rate = final_pcm.sample_rate();
- ss.output_channels = final_pcm.channels();
- ss.emitted_chunks += 1;
- if ss.first_emit_pending {
- ss.first_chunk_seconds = Some(ss.stream_start.elapsed().as_secs_f64());
- ss.first_chunk_frames = emitted_frames;
- }
- }
- }
- let semantic_decode_seconds =
- (semantic_loop_seconds - ss.audio_decode_seconds_in_loop - ss.callback_seconds).max(0.0);
- audio_stream.finish()?;
-
- let stats = TtsExecutionStats {
- semantic_decode_seconds,
- audio_decode_seconds: ss.audio_decode_seconds,
- callback_seconds: ss.callback_seconds,
- first_chunk_seconds: ss.first_chunk_seconds.unwrap_or(0.0),
- command_buffers_submitted: 0,
- host_waits: 0,
- semantic_frames: semantic_tokens.frames(),
- first_chunk_frames: ss.first_chunk_frames,
- emitted_chunks: ss.emitted_chunks,
- audio_decode_calls: ss.audio_decode_calls,
- audio_input_frames: ss.audio_input_frames,
- audio_decoded_window_frames: ss.audio_decoded_window_frames,
- audio_max_decoded_window_frames: ss.audio_max_decoded_window_frames,
- };
-
- let full_pcm = AudioPcmBatch::new(
- ss.output_samples.into_boxed_slice(),
- ss.output_sample_rate,
- ss.output_channels,
- vec![ss.output_frames].into_boxed_slice(),
- )?;
-
- let instrumentation = self.take_text_decoder_instrumentation();
- self.record_last_execution_stats(TtsExecutionStats {
- command_buffers_submitted: instrumentation.command_buffers_submitted,
- host_waits: instrumentation.host_waits,
- ..stats
- });
-
- Ok(full_pcm)
- }
-
- fn generate_semantic_tokens(
- &mut self,
- text_tokens: &[u64],
- seed: u64,
- max_semantic_frames: usize,
- ) -> Result<AudioTokenGrid, Error> {
- let codec_cardinality = self.audio_decoder.codec_cardinality();
- self.text_decoder.generate_semantic_tokens(text_tokens, codec_cardinality, seed, max_semantic_frames)
- }
-
- fn generate_semantic_tokens_with_callback<F>(
- &mut self,
- text_tokens: &[u64],
- seed: u64,
- max_semantic_frames: usize,
- on_frame: &mut F,
- ) -> Result<AudioTokenGrid, Error>
- where
- F: FnMut(&[u32]) -> Result<(), Error>,
- {
- let codec_cardinality = self.audio_decoder.codec_cardinality();
- self.text_decoder.generate_semantic_tokens_with_callback(
- text_tokens,
- codec_cardinality,
- seed,
- max_semantic_frames,
- on_frame,
- )
- }
-
- fn take_text_decoder_instrumentation(&mut self) -> RunnerInstrumentation {
- self.text_decoder.take_instrumentation()
- }
-
- fn record_last_execution_stats(
- &mut self,
- stats: TtsExecutionStats,
- ) {
- self.last_execution_stats.replace(stats);
- }
-}
diff --git a/crates/backend-uzu/src/session/types/error.rs b/crates/backend-uzu/src/session/types/error.rs
deleted file mode 100644
index 72c54ab8d..000000000
--- a/crates/backend-uzu/src/session/types/error.rs
+++ /dev/null
@@ -1,230 +0,0 @@
-use crate::{classifier::ClassifierError, data_type::DataType, session::config::TtsRunConfigError};
-
-#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
-pub enum TtsModelConfigError {
- #[error("missing TTS model config")]
- MissingTtsModelConfig,
- #[error("FishAudio tensor {key} dtype mismatch: expected {expected:?}, got {actual:?}")]
- FishAudioTensorDataTypeMismatch {
- key: Box<str>,
- expected: DataType,
- actual: DataType,
- },
- #[error(
- "FishAudio decoder requires num_codebooks > 1 plus positive codebook_size and max_seq_len, got num_codebooks={num_codebooks}, codebook_size={codebook_size}, max_seq_len={max_seq_len}"
- )]
- FishAudioDecoderCoreParametersInvalid {
- num_codebooks: usize,
- codebook_size: usize,
- max_seq_len: usize,
- },
- #[error(
- "FishAudio decoder num_codebooks={decoder_num_codebooks} does not match audio num_codebooks={audio_num_codebooks}"
- )]
- FishAudioDecoderNumCodebooksMismatch {
- decoder_num_codebooks: usize,
- audio_num_codebooks: usize,
- },
- #[error(
- "FishAudio decoder codebook_size={codebook_size} must be at least audio residual codec cardinality={audio_codec_cardinality}"
- )]
- FishAudioDecoderCodebookSizeTooSmall {
- codebook_size: usize,
- audio_codec_cardinality: usize,
- },
- #[error("FishAudio semantic token range is invalid: begin={begin}, end={end}")]
- FishAudioSemanticTokenRangeInvalid {
- begin: u64,
- end: u64,
- },
- #[error("FishAudio semantic token range overflow: begin={begin}, end={end}")]
- FishAudioSemanticTokenRangeOverflow {
- begin: u64,
- end: u64,
- },
- #[error(
- "FishAudio semantic codec cardinality={semantic_cardinality} does not match audio semantic codec cardinality={audio_semantic_cardinality}"
- )]
- FishAudioSemanticCodecCardinalityMismatch {
- semantic_cardinality: usize,
- audio_semantic_cardinality: usize,
- },
- #[error("followup_count overflow in async chain")]
- AsyncChainFollowupCountOverflow,
- #[error("async chain token count {total_count} exceeds capacity {capacity}")]
- AsyncChainTokenCountExceedsCapacity {
- total_count: usize,
- capacity: usize,
- },
- #[error("vocab mask not supported for initial_token_count={initial_token_count} (expected 1 or 2)")]
- UnsupportedInitialTokenCountForVocabMask {
- initial_token_count: usize,
- },
- #[error("two-token vocab mask size overflow (row_words={row_words})")]
- TwoTokenVocabMaskSizeOverflow {
- row_words: usize,
- },
- #[error("token bitmask size overflow")]
- TokenBitmaskSizeOverflow,
- #[error(
- "token bitmask length {actual_words}, expected {expected_words} (token_count={token_count}, row_words={row_words})"
- )]
- TokenBitmaskLengthMismatch {
- actual_words: usize,
- expected_words: usize,
- token_count: usize,
- row_words: usize,
- },
- #[error("precomputed bitmask size overflow")]
- PrecomputedBitmaskSizeOverflow,
- #[error("precomputed bitmask length {actual_words}, expected {expected_words}")]
- PrecomputedBitmaskLengthMismatch {
- actual_words: usize,
- expected_words: usize,
- },
- #[error("vocab_limit resolved to 0")]
- VocabLimitResolvedToZero,
- #[error("inline bitmask size overflow (token_count={token_count}, row_words={row_words})")]
- InlineBitmaskSizeOverflow {
- token_count: usize,
- row_words: usize,
- },
- #[error("vocab_limit with token_count={token_count} requires a precomputed bitmask")]
- VocabLimitRequiresPrecomputedBitmask {
- token_count: usize,
- },
- #[error("model_dim {model_dim} exceeds u32 range")]
- ModelDimExceedsU32 {
- model_dim: usize,
- },
- #[error("hidden capture row offset overflow (token_count={token_count}, model_dim={model_dim})")]
- HiddenCaptureRowOffsetOverflow {
- token_count: usize,
- model_dim: usize,
- },
- #[error("hidden capture src offset overflow")]
- HiddenCaptureSourceOffsetOverflow,
- #[error(
- "hidden capture shape/dtype mismatch: expected {expected_shape:?} @ {expected_data_type:?}, got {actual_shape:?} @ {actual_data_type:?}"
- )]
- HiddenCaptureTensorMismatch {
- expected_shape: Box<[usize]>,
- expected_data_type: DataType,
- actual_shape: Box<[usize]>,
- actual_data_type: DataType,
- },
- #[error(
- "override embedding shape/dtype mismatch: expected {expected_shape:?} @ {expected_data_type:?}, got {actual_shape:?} @ {actual_data_type:?}"
- )]
- OverrideEmbeddingTensorMismatch {
- expected_shape: Box<[usize]>,
- expected_data_type: DataType,
- actual_shape: Box<[usize]>,
- actual_data_type: DataType,
- },
- #[error("add_scale total_len overflow (token_count={token_count}, model_dim={model_dim})")]
- AddScaleTotalLengthOverflow {
- token_count: usize,
- model_dim: usize,
- },
- #[error("add_scale total_len {total_len} exceeds u32 range")]
- AddScaleTotalLengthExceedsU32 {
- total_len: usize,
- },
- #[error(
- "add_scale bias shape/dtype mismatch: expected {expected_shape:?} @ {expected_data_type:?}, got {actual_shape:?} @ {actual_data_type:?}"
- )]
- AddScaleBiasTensorMismatch {
- expected_shape: Box<[usize]>,
- expected_data_type: DataType,
- actual_shape: Box<[usize]>,
- actual_data_type: DataType,
- },
- #[error("async chain copy src_offset overflow (src_slot={src_slot})")]
- AsyncChainCopySourceOffsetOverflow {
- src_slot: usize,
- },
- #[error("async chain copy size overflow (count={count})")]
- AsyncChainCopySizeOverflow {
- count: usize,
- },
- #[error("async chain result slot {slot} out of bounds (capacity={capacity})")]
- AsyncChainResultSlotOutOfBounds {
- slot: usize,
- capacity: usize,
- },
-}
-
-#[derive(Debug, thiserror::Error)]
-pub enum Error {
- #[error("Model folder not found")]
- ModelFolderNotFound,
- #[error("Unable to open any backend")]
- UnableToOpenAnyBackend,
- #[error("Unable to create Context: {0}")]
- UnableToCreateContext(Box<dyn std::error::Error>),
- #[error("Unable to create CommandBuffer: {0}")]
- UnableToCreateCommandBuffer(Box<dyn std::error::Error>),
- #[error("Unable to open model configuration: {0}")]
- UnableToOpenConfig(#[from] std::io::Error),
- #[error("Unable to deserialize model configuration: {0}")]
- UnableToDeserializeConfig(#[from] serde_json::Error),
- #[error("Invalid model configuration: {0}")]
- InvalidModelConfig(String),
- #[error("Invalid TTS model config: {0}")]
- InvalidTtsModelConfig(#[from] TtsModelConfigError),
- #[error("Invalid TTS run config: {0}")]
- InvalidTtsRunConfig(#[from] TtsRunConfigError),
- #[error("Unable to load model weights: {0}")]
- UnableToLoadWeights(#[source] Box<dyn std::error::Error>),
- #[error("Unable to create decoder: {0}")]
- UnableToCreateDecoder(#[source] Box<dyn std::error::Error>),
- #[error("Unable to create classifier layer: {0}")]
- UnableToCreateClassifierLayer(#[source] Box<dyn std::error::Error>),
- #[error("Unable to load tokenizer: {0}")]
- UnableToLoadTokenizer(#[source] tokenizers::Error),
- #[error("Model is too large to fit into available RAM")]
- NotEnoughMemory,
- #[error("Command buffer failed: {0}")]
- CommandBufferFailed(Box<dyn std::error::Error>),
- #[error("Encode failed: {0}")]
- EncodeFailed(Box<dyn std::error::Error>),
- #[error("Unsupported context mode for model")]
- UnsupportedContextModeForModel,
- #[error("Unsupported speculator config for model")]
- UnsupportedSpeculatorConfigForModel,
- #[error("Unable to load prompt template: {0}")]
- UnableToLoadPromptTemplate(#[source] minijinja::Error),
- #[error("Unable to render prompt template: {0}")]
- UnableToRenderPromptTemplate(#[source] minijinja::Error),
- #[error("Only assistant messages can have reasoning content")]
- UnexpectedReasoningContent,
- #[error("Unable to build output parser regex: {0}")]
- UnableToBuildOutputParserRegex(#[from] regex::Error),
- #[error("Unable to encode text: {0}")]
- UnableToEncodeText(#[source] tokenizers::Error),
- #[error("Unable to decode text: {0}")]
- UnableToDecodeText(#[source] tokenizers::Error),
- #[error("Context length exceeded")]
- ContextLengthExceeded,
- #[error("Prefill failed")]
- PrefillFailed,
- #[error("Generate failed")]
- GenerateFailed,
- #[error("Sampling failed")]
- SamplingFailed,
- #[error("Grammar error: {0}")]
- GrammarError(String),
- #[error("No grammar backend available")]
- GrammarNoBackendAvailable,
- #[error("Grammar rejected the token")]
- GrammarReject,
- #[error("Token {0} out of grammar vocabulary range (0..{1})")]
- TokenOutOfGrammarRange(u64, usize),
- #[error("Capture failed: {0}")]
- CaptureFailed(#[source] Box<dyn std::error::Error>),
- #[error("Classifier error: {0}")]
- Classifier(#[from] ClassifierError),
- #[error("Audio codec error: {0}")]
- AudioCodec(#[from] crate::audio::AudioError),
-}
diff --git a/crates/backend-uzu/src/session/types/input.rs b/crates/backend-uzu/src/session/types/input.rs
deleted file mode 100644
index 837d5e677..000000000
--- a/crates/backend-uzu/src/session/types/input.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-use crate::session::types::{Message, Role};
-
-#[derive(Debug, Clone)]
-pub enum Input {
- Text(String),
- Messages(Vec<Message>),
-}
-
-impl Input {
- pub fn get_messages(&self) -> Vec<Message> {
- match self {
- Input::Text(content) => vec![Message {
- role: Role::User,
- content: content.clone(),
- reasoning_content: None,
- }],
- Input::Messages(messages) => messages.clone(),
- }
- }
-}
diff --git a/crates/backend-uzu/src/session/types/message.rs b/crates/backend-uzu/src/session/types/message.rs
deleted file mode 100644
index 8d9bfc890..000000000
--- a/crates/backend-uzu/src/session/types/message.rs
+++ /dev/null
@@ -1,84 +0,0 @@
-use std::collections::HashMap;
-
-use serde::{Deserialize, Serialize};
-
-#[cfg(metal_backend)]
-use crate::config::token_codec::tts_codec::TTSCodecConfig;
-use crate::{
- config::token_codec::chat_codec::ChatCodecConfig,
- session::{parameter::ConfigResolvableValue, types::Role},
-};
-
-#[cfg(metal_backend)]
-pub(crate) const DEFAULT_TTS_SPEAKER_ID: &str = "speaker:0";
-#[cfg(metal_backend)]
-pub(crate) const DEFAULT_TTS_STYLE: &str = "interleave";
-
-#[derive(Clone, Debug, Deserialize, Serialize)]
-pub struct Message {
- pub role: Role,
- pub content: String,
- pub reasoning_content: Option<String>,
-}
-
-impl Message {
- pub fn new(
- role: Role,
- content: String,
- reasoning_content: Option<String>,
- ) -> Self {
- Self {
- role,
- content,
- reasoning_content,
- }
- }
-
- pub fn system(content: String) -> Self {
- Self::new(Role::System, content, None)
- }
-
- pub fn user(content: String) -> Self {
- Self::new(Role::User, content, None)
- }
-
- pub fn assistant(
- content: String,
- reasoning_content: Option<String>,
- ) -> Self {
- Self::new(Role::Assistant, content, reasoning_content)
- }
-}
-
-impl ConfigResolvableValue<ChatCodecConfig, HashMap<String, String>> for Message {
- fn resolve(
- &self,
- config: &ChatCodecConfig,
- ) -> HashMap<String, String> {
- let role = match self.role {
- Role::System => config.system_role_name.clone(),
- Role::User => config.user_role_name.clone(),
- Role::Assistant => config.assistant_role_name.clone(),
- };
- let content = self.content.clone();
- let mut result = HashMap::from([(String::from("role"), role), (String::from("content"), content)]);
- if let Some(reasoning_content) = self.reasoning_content.clone() {
- result.insert(String::from("reasoning_content"), reasoning_content);
- }
- result
- }
-}
-
-#[cfg(metal_backend)]
-impl ConfigResolvableValue<TTSCodecConfig, HashMap<String, String>> for Message {
- fn resolve(
- &self,
- _config: &TTSCodecConfig,
- ) -> HashMap<String, String> {
- HashMap::from([
- (String::from("content"), self.content.clone()),
- (String::from("speaker_id"), String::from(DEFAULT_TTS_SPEAKER_ID)),
- (String::from("style"), String::from(DEFAULT_TTS_STYLE)),
- ])
- }
-}
diff --git a/crates/backend-uzu/src/session/types/mod.rs b/crates/backend-uzu/src/session/types/mod.rs
deleted file mode 100644
index ab9dcd0c4..000000000
--- a/crates/backend-uzu/src/session/types/mod.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-mod error;
-mod input;
-mod message;
-mod output;
-mod role;
-mod stats;
-mod text;
-pub use error::{Error, TtsModelConfigError};
-pub use input::Input;
-pub use message::Message;
-pub use output::{FinishReason, Output};
-pub use role::Role;
-pub use stats::{PowerStats, RunStats, Stats, StepStats, TotalStats};
-pub use text::{ParsedText, Text};
diff --git a/crates/backend-uzu/src/session/types/output.rs b/crates/backend-uzu/src/session/types/output.rs
deleted file mode 100644
index 2662eb1e7..000000000
--- a/crates/backend-uzu/src/session/types/output.rs
+++ /dev/null
@@ -1,29 +0,0 @@
-use serde::{Deserialize, Serialize};
-
-use crate::session::types::{Stats, Text};
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "lowercase")]
-pub enum FinishReason {
- Stop,
- Length,
- Cancelled,
- ContextLimitReached,
-}
-
-#[derive(Debug, Clone)]
-pub struct Output {
- pub text: Text,
- pub stats: Stats,
- pub finish_reason: Option<FinishReason>,
-}
-
-impl Output {
- pub fn with_finish_reason(
- mut self,
- finish_reason: Option<FinishReason>,
- ) -> Self {
- self.finish_reason = finish_reason;
- self
- }
-}
diff --git a/crates/backend-uzu/src/session/types/role.rs b/crates/backend-uzu/src/session/types/role.rs
deleted file mode 100644
index 82fd9f854..000000000
--- a/crates/backend-uzu/src/session/types/role.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-use serde::{Deserialize, Serialize};
-
-#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
-#[serde(rename_all = "lowercase")]
-pub enum Role {
- System,
- User,
- Assistant,
-}
diff --git a/crates/backend-uzu/src/session/types/text.rs b/crates/backend-uzu/src/session/types/text.rs
deleted file mode 100644
index 19a4ae708..000000000
--- a/crates/backend-uzu/src/session/types/text.rs
+++ /dev/null
@@ -1,11 +0,0 @@
-#[derive(Debug, Clone)]
-pub struct ParsedText {
- pub chain_of_thought: Option<String>,
- pub response: Option<String>,
-}
-
-#[derive(Debug, Clone)]
-pub struct Text {
- pub original: String,
- pub parsed: ParsedText,
-}
diff --git a/crates/backend-uzu/src/speculators/mod.rs b/crates/backend-uzu/src/speculators/mod.rs
index cf759e9fc..521392b67 100644
--- a/crates/backend-uzu/src/speculators/mod.rs
+++ b/crates/backend-uzu/src/speculators/mod.rs
@@ -1,11 +1,8 @@
-#[cfg(test)]
pub mod chain_acceptance;
pub mod empty_speculator;
pub mod fixed_token_speculator;
-#[allow(dead_code)]
pub mod ngram_speculator;
pub mod prompt_lookup_speculator;
-#[cfg(test)]
pub mod repeat_speculator;
pub mod speculator;
pub mod token_finder;
diff --git a/crates/backend-uzu/src/speculators/repeat_speculator.rs b/crates/backend-uzu/src/speculators/repeat_speculator.rs
index ebdff4680..4ade882bc 100644
--- a/crates/backend-uzu/src/speculators/repeat_speculator.rs
+++ b/crates/backend-uzu/src/speculators/repeat_speculator.rs
@@ -1,5 +1,3 @@
-#![allow(dead_code)]
-
use std::collections::HashMap;
use crate::speculators::speculator::Speculator;
diff --git a/crates/backend-uzu/src/tests/audio/fsq_reference.rs b/crates/backend-uzu/src/tests/audio/fsq_reference.rs
deleted file mode 100644
index a870556f5..000000000
--- a/crates/backend-uzu/src/tests/audio/fsq_reference.rs
+++ /dev/null
@@ -1,147 +0,0 @@
-fn checked_product(values: &[usize]) -> usize {
- values.iter().try_fold(1usize, |acc, &value| acc.checked_mul(value)).expect("dimension product overflow")
-}
-
-fn round_ties_to_even(value: f32) -> f32 {
- let floor = value.floor();
- let fraction = value - floor;
-
- if fraction < 0.5 {
- floor
- } else if fraction > 0.5 || (floor as i64 & 1) != 0 {
- floor + 1.0
- } else {
- floor
- }
-}
-
-fn validate_fsq_common(
- batch_size: usize,
- num_groups: usize,
- seq_len: usize,
- codebook_dim: usize,
- num_levels: &[i32],
- lengths: &[i32],
-) {
- assert!(num_groups != 0 && codebook_dim != 0, "invalid group/codebook configuration");
- assert_eq!(num_levels.len(), codebook_dim, "num_levels size mismatch");
-
- for &levels in num_levels {
- assert!(levels > 1, "invalid levels {levels}");
- }
-
- assert_eq!(lengths.len(), batch_size, "lengths count mismatch");
-
- for &length in lengths {
- assert!(length >= 0 && length as usize <= seq_len, "invalid length {length} for {seq_len} frames");
- }
-}
-
-pub fn fsq_decode_reference(
- tokens: &[i32],
- lengths: &[i32],
- batch_size: usize,
- num_groups: usize,
- seq_len: usize,
- codebook_dim: usize,
- num_levels: &[i32],
-) -> Vec<f32> {
- validate_fsq_common(batch_size, num_groups, seq_len, codebook_dim, num_levels, lengths);
- assert_eq!(tokens.len(), checked_product(&[batch_size, num_groups, seq_len]), "tokens size mismatch");
-
- let output_len = checked_product(&[batch_size, num_groups * codebook_dim, seq_len]);
- let mut output = vec![0.0_f32; output_len];
-
- for batch in 0..batch_size {
- let length = lengths[batch] as usize;
- for group in 0..num_groups {
- for time in 0..seq_len {
- if time >= length {
- continue;
- }
-
- let token_index = (batch * num_groups + group) * seq_len + time;
- let token = tokens[token_index];
- let mut base = 1_i32;
-
- for dim in 0..codebook_dim {
- let levels = num_levels[dim];
- let scale = levels / 2;
- let offset = scale;
-
- let div = token / base;
- let mut code_nonnegative = div % levels;
- if code_nonnegative < 0 {
- code_nonnegative += levels;
- }
-
- let value = (code_nonnegative - offset) as f32 / scale as f32;
- let channel = group * codebook_dim + dim;
- let output_index = (batch * (num_groups * codebook_dim) + channel) * seq_len + time;
- output[output_index] = value;
-
- base = base.checked_mul(levels).expect("fsq decode base overflow");
- }
- }
- }
- }
-
- output
-}
-
-pub fn fsq_encode_reference(
- input: &[f32],
- lengths: &[i32],
- batch_size: usize,
- num_groups: usize,
- seq_len: usize,
- codebook_dim: usize,
- num_levels: &[i32],
- dim_base_index: &[i32],
- eps: f32,
-) -> Vec<i32> {
- validate_fsq_common(batch_size, num_groups, seq_len, codebook_dim, num_levels, lengths);
- assert_eq!(dim_base_index.len(), codebook_dim, "dim_base_index size mismatch");
- assert_eq!(input.len(), checked_product(&[batch_size, num_groups * codebook_dim, seq_len]), "input size mismatch");
-
- let output_len = checked_product(&[batch_size, num_groups, seq_len]);
- let mut tokens = vec![0_i32; output_len];
-
- for batch in 0..batch_size {
- let length = lengths[batch] as usize;
- for group in 0..num_groups {
- for time in 0..seq_len {
- let output_index = (batch * num_groups + group) * seq_len + time;
- if time >= length {
- tokens[output_index] = 0;
- continue;
- }
-
- let mut token = 0_i32;
- for dim in 0..codebook_dim {
- let levels = num_levels[dim];
- let scale_i = levels / 2;
-
- let output_scale = (levels - 1) as f32 * 0.5 * (1.0 - eps);
- let output_offset = if levels % 2 == 0 {
- 0.5
- } else {
- 0.0
- };
- let input_shift = (output_offset / output_scale).tan();
-
- let input_index =
- (batch * (num_groups * codebook_dim) + group * codebook_dim + dim) * seq_len + time;
- let compressed = output_scale * (input[input_index] + input_shift).tanh() - output_offset;
- let rounded = round_ties_to_even(compressed);
- let code_nonnegative = (rounded as i32 + scale_i).clamp(0, levels - 1);
- token += code_nonnegative * dim_base_index[dim];
- }
-
- tokens[output_index] = token;
- }
- }
- }
-
- tokens
-}
diff --git a/crates/backend-uzu/src/tests/audio/mod.rs b/crates/backend-uzu/src/tests/audio/mod.rs
deleted file mode 100644
index 4e553289c..000000000
--- a/crates/backend-uzu/src/tests/audio/mod.rs
+++ /dev/null
@@ -1,2 +0,0 @@
-pub mod fsq_reference;
-pub mod ops_reference;
diff --git a/crates/backend-uzu/src/tests/audio/ops_reference.rs b/crates/backend-uzu/src/tests/audio/ops_reference.rs
deleted file mode 100644
index f1a42c8e4..000000000
--- a/crates/backend-uzu/src/tests/audio/ops_reference.rs
+++ /dev/null
@@ -1,403 +0,0 @@
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum PadMode {
- Zeros,
- Replicate,
-}
-
-fn checked_product(values: &[usize]) -> usize {
- values.iter().try_fold(1usize, |acc, &value| acc.checked_mul(value)).expect("dimension product overflow")
-}
-
-fn validate_lengths(
- lengths: &[i32],
- batch_size: usize,
- frames: usize,
-) {
- assert_eq!(lengths.len(), batch_size, "lengths count mismatch");
-
- for &length in lengths {
- assert!(length >= 0 && length as usize <= frames, "invalid length {length} for {frames} frames");
- }
-}
-
-pub struct Conv1dSpec<'a> {
- pub input: &'a [f32],
- pub weight: &'a [f32],
- pub bias: &'a [f32],
- pub lengths: &'a [i32],
- pub batch_size: usize,
- pub cin: usize,
- pub cout: usize,
- pub seq_len_in: usize,
- pub seq_len_out: usize,
- pub kernel_size: usize,
- pub stride: usize,
- pub dilation: usize,
- pub padding: usize,
- pub pad_mode: PadMode,
-}
-
-pub fn conv1d_reference(spec: Conv1dSpec<'_>) -> Vec<f32> {
- let Conv1dSpec {
- input,
- weight,
- bias,
- lengths,
- batch_size,
- cin,
- cout,
- seq_len_in,
- seq_len_out,
- kernel_size,
- stride,
- dilation,
- padding,
- pad_mode,
- } = spec;
-
- validate_lengths(lengths, batch_size, seq_len_out);
- assert_eq!(input.len(), checked_product(&[batch_size, cin, seq_len_in]), "input size mismatch");
- assert_eq!(weight.len(), checked_product(&[cout, cin, kernel_size]), "weight size mismatch");
- assert_eq!(bias.len(), cout, "bias size mismatch");
-
- let output_len = checked_product(&[batch_size, cout, seq_len_out]);
- let mut output = vec![0.0_f32; output_len];
-
- for batch in 0..batch_size {
- let length = lengths[batch] as usize;
- for out_channel in 0..cout {
- for out_time in 0..seq_len_out {
- let out_index = (batch * cout + out_channel) * seq_len_out + out_time;
- if out_time >= length {
- output[out_index] = 0.0;
- continue;
- }
-
- let mut acc = bias[out_channel];
- let base = (out_time * stride) as isize - padding as isize;
-
- for in_channel in 0..cin {
- let input_base = (batch * cin + in_channel) * seq_len_in;
- let weight_base = (out_channel * cin + in_channel) * kernel_size;
- for kernel_offset in 0..kernel_size {
- let x_time_raw = base + (kernel_offset * dilation) as isize;
- let x_time = match pad_mode {
- PadMode::Zeros => {
- if x_time_raw < 0 || x_time_raw >= seq_len_in as isize {
- continue;
- }
- x_time_raw as usize
- },
- PadMode::Replicate => x_time_raw.clamp(0, seq_len_in as isize - 1) as usize,
- };
-
- let x_index = input_base + x_time;
- let w_index = weight_base + kernel_offset;
- acc += weight[w_index] * input[x_index];
- }
- }
-
- output[out_index] = acc;
- }
- }
- }
-
- output
-}
-
-pub struct CausalConv1dSpec<'a> {
- pub input: &'a [f32],
- pub weight: &'a [f32],
- pub bias: &'a [f32],
- pub lengths: &'a [i32],
- pub batch_size: usize,
- pub cin: usize,
- pub cout: usize,
- pub seq_len: usize,
- pub kernel_size: usize,
- pub dilation: usize,
-}
-
-pub fn causal_conv1d_reference(spec: CausalConv1dSpec<'_>) -> Vec<f32> {
- let CausalConv1dSpec {
- input,
- weight,
- bias,
- lengths,
- batch_size,
- cin,
- cout,
- seq_len,
- kernel_size,
- dilation,
- } = spec;
-
- validate_lengths(lengths, batch_size, seq_len);
- assert_eq!(input.len(), checked_product(&[batch_size, cin, seq_len]), "input size mismatch");
- assert_eq!(weight.len(), checked_product(&[cout, cin, kernel_size]), "weight size mismatch");
- assert_eq!(bias.len(), cout, "bias size mismatch");
-
- let output_len = checked_product(&[batch_size, cout, seq_len]);
- let mut output = vec![0.0_f32; output_len];
- let pad = (kernel_size - 1) * dilation;
-
- for batch in 0..batch_size {
- let length = lengths[batch] as usize;
- for out_channel in 0..cout {
- for time in 0..seq_len {
- let out_index = (batch * cout + out_channel) * seq_len + time;
- if time >= length {
- output[out_index] = 0.0;
- continue;
- }
-
- let mut acc = bias[out_channel];
- for in_channel in 0..cin {
- let input_base = (batch * cin + in_channel) * seq_len;
- let weight_base = (out_channel * cin + in_channel) * kernel_size;
- for kernel_offset in 0..kernel_size {
- let x_time = time as isize + (kernel_offset * dilation) as isize - pad as isize;
- if x_time < 0 || x_time >= seq_len as isize {
- continue;
- }
-
- let x_index = input_base + x_time as usize;
- let w_index = weight_base + kernel_offset;
- acc += weight[w_index] * input[x_index];
- }
- }
-
- output[out_index] = acc;
- }
- }
- }
-
- output
-}
-
-pub struct CausalConvTranspose1dSpec<'a> {
- pub input: &'a [f32],
- pub weight: &'a [f32],
- pub bias: &'a [f32],
- pub lengths: &'a [i32],
- pub batch_size: usize,
- pub cin: usize,
- pub cout: usize,
- pub seq_len_in: usize,
- pub seq_len_out: usize,
- pub stride: usize,
- pub groups: usize,
-}
-
-pub fn causal_conv_transpose1d_reference(spec: CausalConvTranspose1dSpec<'_>) -> Vec<f32> {
- let CausalConvTranspose1dSpec {
- input,
- weight,
- bias,
- lengths,
- batch_size,
- cin,
- cout,
- seq_len_in,
- seq_len_out,
- stride,
- groups,
- } = spec;
-
- validate_lengths(lengths, batch_size, seq_len_out);
- assert!(
- groups != 0 && cin != 0 && cout != 0 && cin % groups == 0 && cout % groups == 0,
- "invalid channel/group configuration"
- );
- assert_eq!(input.len(), checked_product(&[batch_size, cin, seq_len_in]), "input size mismatch");
-
- let kernel_size = 2 * stride;
- let cin_per_group = cin / groups;
- assert_eq!(weight.len(), checked_product(&[cout, cin_per_group, kernel_size]), "weight size mismatch");
- assert_eq!(bias.len(), cout, "bias size mismatch");
-
- let output_len = checked_product(&[batch_size, cout, seq_len_out]);
- let mut output = vec![0.0_f32; output_len];
- let cout_per_group = cout / groups;
-
- for batch in 0..batch_size {
- let length = lengths[batch] as usize;
- for out_channel in 0..cout {
- let group_index = out_channel / cout_per_group;
- let in_channel_begin = group_index * cin_per_group;
- let in_channel_end = in_channel_begin + cin_per_group;
-
- for out_time in 0..seq_len_out {
- let out_index = (batch * cout + out_channel) * seq_len_out + out_time;
- if out_time >= length {
- output[out_index] = 0.0;
- continue;
- }
-
- let q = out_time / stride;
- let r = out_time % stride;
- let mut acc = bias[out_channel];
-
- for in_channel in in_channel_begin..in_channel_end {
- if q >= seq_len_in {
- continue;
- }
-
- let input_base = (batch * cin + in_channel) * seq_len_in;
- let in_channel_in_group = in_channel - in_channel_begin;
- let weight_base = (out_channel * cin_per_group + in_channel_in_group) * kernel_size;
-
- acc += input[input_base + q] * weight[weight_base + r];
- if q > 0 {
- acc += input[input_base + (q - 1)] * weight[weight_base + (stride + r)];
- }
- }
-
- output[out_index] = acc;
- }
- }
- }
-
- output
-}
-
-pub fn causal_conv_transpose1d_causal_pad_reference(spec: CausalConvTranspose1dSpec<'_>) -> Vec<f32> {
- let CausalConvTranspose1dSpec {
- input,
- weight,
- bias,
- lengths,
- batch_size,
- cin,
- cout,
- seq_len_in,
- seq_len_out,
- stride,
- groups,
- } = spec;
-
- validate_lengths(lengths, batch_size, seq_len_out);
- assert!(
- groups != 0 && stride != 0 && cin != 0 && cout != 0 && cin % groups == 0 && cout % groups == 0,
- "invalid channel/group configuration"
- );
- assert_eq!(input.len(), checked_product(&[batch_size, cin, seq_len_in]), "input size mismatch");
-
- let cout_per_group = cout / groups;
- let cin_per_group = cin / groups;
- let weight_plane = checked_product(&[cout, cin_per_group]);
- assert!(weight_plane != 0 && weight.len() % weight_plane == 0, "weight size mismatch");
-
- let kernel_size = weight.len() / weight_plane;
- assert_ne!(kernel_size, 0, "empty kernel");
- assert_eq!(bias.len(), cout, "bias size mismatch");
-
- let output_len = checked_product(&[batch_size, cout, seq_len_out]);
- let mut output = vec![0.0_f32; output_len];
- let seq_len_expanded = if seq_len_in == 0 {
- 0
- } else {
- (seq_len_in - 1)
- .checked_mul(stride)
- .and_then(|value| value.checked_add(1))
- .expect("expanded sequence length overflow")
- };
- let left_pad = kernel_size - 1;
-
- for batch in 0..batch_size {
- let length = lengths[batch] as usize;
- for out_channel in 0..cout {
- let group_index = out_channel / cout_per_group;
- let in_channel_begin = group_index * cin_per_group;
- let in_channel_end = in_channel_begin + cin_per_group;
-
- for out_time in 0..seq_len_out {
- let out_index = (batch * cout + out_channel) * seq_len_out + out_time;
- if out_time >= length {
- output[out_index] = 0.0;
- continue;
- }
-
- let mut acc = bias[out_channel];
-
- for in_channel in in_channel_begin..in_channel_end {
- let input_base = (batch * cin + in_channel) * seq_len_in;
- let in_channel_in_group = in_channel - in_channel_begin;
- let weight_base = (out_channel * cin_per_group + in_channel_in_group) * kernel_size;
-
- for kernel_offset in 0..kernel_size {
- let expanded_time = out_time as isize + kernel_offset as isize - left_pad as isize;
- if expanded_time < 0 || expanded_time >= seq_len_expanded as isize {
- continue;
- }
-
- let expanded_time = expanded_time as usize;
- if !expanded_time.is_multiple_of(stride) {
- continue;
- }
-
- let src_time = expanded_time / stride;
- if src_time >= seq_len_in {
- continue;
- }
-
- acc += input[input_base + src_time] * weight[weight_base + kernel_offset];
- }
- }
-
- output[out_index] = acc;
- }
- }
- }
-
- output
-}
-
-pub struct HalfSnakeSpec<'a> {
- pub input: &'a [f32],
- pub alpha: &'a [f32],
- pub batch_size: usize,
- pub channels: usize,
- pub seq_len: usize,
- pub snake_channels: usize,
- pub negative_slope: f32,
- pub eps: f32,
-}
-
-pub fn half_snake_reference(spec: HalfSnakeSpec<'_>) -> Vec<f32> {
- let HalfSnakeSpec {
- input,
- alpha,
- batch_size,
- channels,
- seq_len,
- snake_channels,
- negative_slope,
- eps,
- } = spec;
-
- assert!(snake_channels <= channels, "snake channels exceed channel count");
- assert_eq!(input.len(), checked_product(&[batch_size, channels, seq_len]), "input size mismatch");
- assert_eq!(alpha.len(), snake_channels, "alpha size mismatch");
-
- let mut output = vec![0.0_f32; input.len()];
- for batch in 0..batch_size {
- for channel in 0..channels {
- for time in 0..seq_len {
- let index = (batch * channels + channel) * seq_len + time;
- let x = input[index];
- output[index] = if channel < snake_channels {
- let a = alpha[channel];
- let sine = (a * x).sin();
- x + (sine * sine) / (a + eps)
- } else if x >= 0.0 {
- x
- } else {
- negative_slope * x
- };
- }
- }
- }
-
- output
-}
diff --git a/crates/backend-uzu/src/tests/matmul/harness.rs b/crates/backend-uzu/src/tests/matmul/harness.rs
index eb1f3ed78..a89023859 100644
--- a/crates/backend-uzu/src/tests/matmul/harness.rs
+++ b/crates/backend-uzu/src/tests/matmul/harness.rs
@@ -4,7 +4,7 @@ use super::Shape;
#[cfg(metal_backend)]
use crate::backends::metal::{GemmDispatchPath, Metal, MetalContext};
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{
AllocationType, Backend, Context, Encoder,
@@ -125,18 +125,14 @@ fn run<B: Backend, T: ArrayElement + Float>(
context: &B::Context,
kernel: &mut <B::Kernels as Kernels>::MatmulKernel,
input: &Input<T>,
- encode: impl FnOnce(&mut <B::Kernels as Kernels>::MatmulKernel, MatmulArguments<B>, &mut Encoder<B>),
+ encode: impl for<'a> FnOnce(&mut <B::Kernels as Kernels>::MatmulKernel, MatmulArguments<'a, 'a, 'a, B>, &mut Encoder<B>),
) -> Vec<T> {
let Shape {
m,
k,
n,
} = input.case.shape;
- let b_array = if input.case.b_transpose {
- context.create_array_from(&[n, k], &input.b)
- } else {
- context.create_array_from(&[k, n], &input.b)
- };
+ let b_allocation = alloc_allocation_with_data::<B, T>(context, &input.b);
let a_allocation = alloc_allocation_with_data::<B, T>(context, &input.a);
let mut d_allocation = if let Some(ref prefill) = input.d_prefill {
alloc_allocation_with_data::<B, T>(context, prefill)
@@ -159,13 +155,12 @@ fn run<B: Backend, T: ArrayElement + Float>(
let mut encoder = Encoder::new(context).expect("encoder");
encode(
kernel,
- MatmulArguments::<'_, B> {
+ MatmulArguments {
a: &a_allocation,
a_offset: 0,
b: MatmulB::FullPrecision {
- b: b_array.allocation(),
+ b: &b_allocation,
},
- b_offset: 0,
b_leading_dimension: None,
b_transpose: input.case.b_transpose,
d: &mut d_allocation,
diff --git a/crates/backend-uzu/src/tests/matmul/quant.rs b/crates/backend-uzu/src/tests/matmul/quant.rs
index 82bec5995..61096e670 100644
--- a/crates/backend-uzu/src/tests/matmul/quant.rs
+++ b/crates/backend-uzu/src/tests/matmul/quant.rs
@@ -130,7 +130,7 @@ impl<B: Backend, T: ArrayElement + Float> QuantBuffers<B, T> {
pub fn quant_arguments<'a, B: Backend, T: ArrayElement + Float>(
buffers: &'a mut QuantBuffers<B, T>,
input: &QuantInput<T>,
-) -> MatmulArguments<'a, B> {
+) -> MatmulArguments<'a, 'a, 'a, B> {
let b_variant = match input.quant_method {
QuantizationMethod::ScaleBias => MatmulB::ScaleBiasDequant {
b: &buffers.w,
@@ -157,7 +157,6 @@ pub fn quant_arguments<'a, B: Backend, T: ArrayElement + Float>(
a: &buffers.x,
a_offset: 0,
b: b_variant,
- b_offset: 0,
b_leading_dimension: None,
b_transpose: true,
d: &mut buffers.y,
diff --git a/crates/backend-uzu/src/tests/mod.rs b/crates/backend-uzu/src/tests/mod.rs
index 69e3af19d..f3bec61b5 100644
--- a/crates/backend-uzu/src/tests/mod.rs
+++ b/crates/backend-uzu/src/tests/mod.rs
@@ -4,7 +4,6 @@
pub extern crate test;
pub mod assert;
-pub mod audio;
pub mod cold_pool;
pub mod helpers;
pub mod matmul;
diff --git a/crates/backend-uzu/src/trie.rs b/crates/backend-uzu/src/trie.rs
index fada32870..cfa46add4 100644
--- a/crates/backend-uzu/src/trie.rs
+++ b/crates/backend-uzu/src/trie.rs
@@ -1,7 +1,11 @@
+use itertools::Itertools;
use thiserror::Error;
use crate::{
- language_model::{grammar::CompiledGrammar, gumbel::speculator_sample, rng::PRng},
+ backends::common::gpu_types::trie::TrieNode as GpuTrieNode,
+ data_type::DataType,
+ encodable_block::sampling::{PRng, speculator_sample},
+ engine::language_model::grammar::{Grammar, GrammarError},
speculators::speculator::Speculator,
};
@@ -26,7 +30,6 @@ impl Default for TrieCreationConfig {
#[derive(Debug)]
pub struct TrieNode {
token: u64,
- mask: Option<Box<[u32]>>,
seed: u64,
next: Vec<TrieNode>,
}
@@ -46,12 +49,10 @@ pub struct FlatTrie<'a> {
impl TrieNode {
pub fn new(
token: u64,
- mask: Option<Box<[u32]>>,
seed: u64,
) -> Self {
Self {
token,
- mask,
seed,
next: Vec::new(),
}
@@ -92,16 +93,18 @@ impl TrieNode {
self.seed
}
- pub fn from_speculator(
+ pub fn from_speculator<'grammar>(
prefix: &[u64],
- seed: &PRng,
- mut compiled_grammar: Option<&mut (dyn CompiledGrammar + 'static)>,
+ prng: &PRng,
+ mut grammar: Option<&mut (dyn Grammar + 'grammar)>,
speculator: &dyn Speculator,
vocab_size: usize,
creation_config: &TrieCreationConfig,
max_length: usize,
+ max_height: Option<usize>,
) -> Self {
assert!(max_length >= 1, "can't have zero sized trie");
+ assert!(max_height.is_none_or(|max_height| max_height > 0), "max height cannot be 0");
assert!(!prefix.is_empty(), "need seed node");
let prefix_length = prefix.len();
@@ -109,8 +112,7 @@ impl TrieNode {
let mut length = 1;
let mut height = 0;
- let mask = compiled_grammar.as_deref_mut().and_then(|g| g.next_bitmask().unwrap());
- let mut root = Self::new(*prefix.last().unwrap(), mask, seed.derive((prefix_length - 1) as u64));
+ let mut root = Self::new(*prefix.last().unwrap(), prng.derive((prefix_length - 1) as u64));
let mut cur_node = &mut root;
let mut cur_node_width = 0;
@@ -118,26 +120,21 @@ impl TrieNode {
let mut next_node = None;
- while length < max_length {
+ while length < max_length && max_height.is_none_or(|max_height| height < max_height) {
// Guuumbel speculator trick: both speculator and llm sample via gumbel max trick using the same noise for increased acceptance rate
if let Some(next_speculated_token) =
speculator_sample(cur_node.seed(), vocab_size, &cur_node_speculator_weights)
{
// Add speculated token to the trie
- let mask = if let Some(compiled_grammar) = compiled_grammar.as_deref_mut() {
- if compiled_grammar.accept_token(next_speculated_token).is_err() {
+ if let Some(grammar) = grammar.as_deref_mut() {
+ if grammar.accept_token(next_speculated_token).is_err() {
cur_node_speculator_weights.remove(&next_speculated_token);
continue;
}
- let next_bitmask = compiled_grammar.next_bitmask().unwrap();
- compiled_grammar.rollback(1);
-
- next_bitmask
- } else {
- None
- };
+ grammar.rollback(1);
+ }
- let leaf_node = Self::new(next_speculated_token, mask, seed.derive((prefix_length + height) as u64));
+ let leaf_node = Self::new(next_speculated_token, prng.derive((prefix_length + height) as u64));
cur_node.add(leaf_node).unwrap();
// If this is the first node we sampled (most likely to be selected after gumbel noise application) - set it as the next one
@@ -156,8 +153,8 @@ impl TrieNode {
} else if let Some(next_node_token) = next_node.take() {
// Out of speculated tokens for this node, move onto the likeliest next node
speculated_suffix.push(next_node_token);
- if let Some(compiled_grammar) = compiled_grammar.as_deref_mut()
- && compiled_grammar.accept_token(next_node_token).is_err()
+ if let Some(grammar) = grammar.as_deref_mut()
+ && grammar.accept_token(next_node_token).is_err()
{
break;
}
@@ -172,8 +169,26 @@ impl TrieNode {
};
}
- if let Some(compiled_grammar) = compiled_grammar {
- compiled_grammar.rollback(height);
+ if let Some(grammar) = grammar {
+ grammar.rollback(height);
+ }
+
+ root
+ }
+
+ pub fn flat(
+ prefix_length: usize,
+ tokens: &[u64],
+ prng: &PRng,
+ ) -> Self {
+ assert!(!tokens.is_empty(), "need seed node");
+
+ let mut root = TrieNode::new(tokens[0], prng.derive(prefix_length as u64));
+ let mut leaf = &mut root;
+
+ for (index, token) in tokens.iter().copied().enumerate().skip(1) {
+ leaf.add(TrieNode::new(token, prng.derive((prefix_length + index) as u64))).unwrap();
+ leaf = &mut leaf.next[0];
}
root
@@ -231,24 +246,53 @@ impl<'a> FlatTrie<'a> {
self.tokens.iter().map(|n| n.node.token)
}
- pub fn token_subtrie_ranges(&self) -> impl Iterator<Item = [u32; 3]> {
+ pub fn token_subtrie_ranges(&self) -> impl Iterator<Item = GpuTrieNode> {
self.tokens.iter().map(|n| {
let (start, end) = n.subtrie_range;
- [start as u32, end as u32, n.height as u32]
+ GpuTrieNode {
+ trie_start: start as u32,
+ trie_end: end as u32,
+ height: n.height as u32,
+ }
})
}
- pub fn token_positions(&self) -> impl Iterator<Item = usize> {
- self.tokens.iter().map(|n| n.height)
+ pub fn token_seeds(&self) -> impl Iterator<Item = u64> {
+ self.tokens.iter().map(|n| n.node.seed)
}
- pub fn token_masks(&self) -> impl Iterator<Item = Option<&[u32]>> {
- self.tokens.iter().map(|n| n.node.mask.as_deref())
- }
+ pub fn fill_bitmasks<'grammar>(
+ &self,
+ bitmasks: &mut [u32],
+ vocab_size: usize,
+ grammar: &mut (dyn Grammar + 'grammar),
+ ) -> bool {
+ let vocab_size_in_u32s = vocab_size.div_ceil(DataType::U32.size_in_bits());
+ assert!(bitmasks.len() == self.tokens.len() * vocab_size_in_u32s);
+
+ let mut any_non_full = false;
+ let mut last_token_height = 0;
+ for ((token_index, token), bitmask) in
+ self.tokens.iter().enumerate().zip_eq(bitmasks.chunks_exact_mut(vocab_size_in_u32s))
+ {
+ if token_index > 0 {
+ if token.height <= last_token_height {
+ grammar.rollback(last_token_height - token.height + 1);
+ }
+ grammar.accept_token(token.node.token).expect("flat trie doesn't match grammar");
+ }
- pub fn token_seeds(&self) -> impl Iterator<Item = u64> {
- self.tokens.iter().map(|n| n.node.seed)
+ any_non_full |= grammar.next_bitmask(bitmask);
+
+ last_token_height = token.height;
+ }
+
+ if last_token_height > 0 {
+ grammar.rollback(last_token_height);
+ }
+
+ any_non_full
}
pub fn root(&self) -> Option<&TrieNode> {
@@ -262,38 +306,36 @@ impl<'a> FlatTrie<'a> {
self.tokens.iter().position(|n| std::ptr::eq(n.node, node))
}
- pub fn accept(
+ pub fn accept<'grammar>(
&self,
sampled_tokens: &[u64],
- mut compiled_grammar: Option<&mut (dyn CompiledGrammar + 'static)>,
- ) -> (Vec<u64>, Vec<usize>) {
+ mut grammar: Option<&mut (dyn Grammar + 'grammar)>,
+ ) -> Result<Box<[(usize, u64, u64)]>, GrammarError> {
let mut current_token = self.root().unwrap();
- let mut accepted_tokens = Vec::new();
- let mut accepted_token_indices = Vec::new();
+ let mut accepted = Vec::new();
loop {
let current_token_index = self.index(current_token).unwrap();
let current_token_id = sampled_tokens[current_token_index];
- accepted_token_indices.push(current_token_index);
- accepted_tokens.push(current_token_id);
- if let Some(compiled_grammar) = compiled_grammar.as_deref_mut()
- && !compiled_grammar.is_terminated()
+ accepted.push((current_token_index, current_token.token, current_token_id));
+ if let Some(grammar) = grammar.as_deref_mut()
+ && !grammar.is_terminated()
{
- compiled_grammar.accept_token(current_token_id).unwrap();
+ grammar.accept_token(current_token_id)?;
}
let Some(next_token) = current_token.get(current_token_id) else {
break;
};
- if let Some(compiled_grammar) = compiled_grammar.as_deref_mut() {
- assert!(!compiled_grammar.is_terminated(), "Grammar has terminated but llm continued generation");
+ if let Some(grammar) = grammar.as_deref_mut() {
+ assert!(!grammar.is_terminated(), "Grammar has terminated but llm continued generation");
}
current_token = next_token;
}
- (accepted_tokens, accepted_token_indices)
+ Ok(accepted.into_boxed_slice())
}
}
diff --git a/crates/backend-uzu/src/utils/env_utils.rs b/crates/backend-uzu/src/utils/env_utils.rs
deleted file mode 100644
index 7bedd5c22..000000000
--- a/crates/backend-uzu/src/utils/env_utils.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-#[derive(Copy, Clone, Debug)]
-pub enum EnvVar {
- CaptureFirstDecode,
- CaptureFirstPrefill,
-}
-
-impl EnvVar {
- pub fn key(&self) -> &'static str {
- match self {
- EnvVar::CaptureFirstDecode => "UZU_CAPTURE_FIRST_DECODE",
- EnvVar::CaptureFirstPrefill => "UZU_CAPTURE_FIRST_PREFILL",
- }
- }
-
- pub fn value(&self) -> String {
- std::env::var(self.key()).unwrap_or_default()
- }
-
- pub fn is_enabled(&self) -> bool {
- let upper = self.value().to_ascii_uppercase();
- matches!(upper.as_str(), "1" | "YES" | "TRUE")
- }
-}
diff --git a/crates/backend-uzu/src/utils/maybe_mut.rs b/crates/backend-uzu/src/utils/maybe_mut.rs
new file mode 100644
index 000000000..f340161d9
--- /dev/null
+++ b/crates/backend-uzu/src/utils/maybe_mut.rs
@@ -0,0 +1,17 @@
+use std::ops::Deref;
+
+pub enum MaybeMut<'a, T: ?Sized> {
+ Const(&'a T),
+ Mut(&'a mut T),
+}
+
+impl<'a, T: ?Sized> Deref for MaybeMut<'a, T> {
+ type Target = T;
+
+ fn deref(&self) -> &T {
+ match self {
+ Self::Const(value) => value,
+ Self::Mut(value) => value,
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/utils/memory.rs b/crates/backend-uzu/src/utils/memory.rs
deleted file mode 100644
index 105cb31f2..000000000
--- a/crates/backend-uzu/src/utils/memory.rs
+++ /dev/null
@@ -1,30 +0,0 @@
-#[cfg(not(target_arch = "wasm32"))]
-pub fn get_free_ram() -> u64 {
- use sysinfo::System;
- let mut sys = System::new();
- sys.refresh_memory();
- sys.total_memory() - sys.used_memory()
-}
-
-#[cfg(target_arch = "wasm32")]
-pub fn get_free_ram() -> u64 {
- use core::arch::wasm32::memory_size;
- const TOTAL_AVAILABLE: u64 = 4 * 1024 * 1024 * 1024;
- const PAGE_SIZE: u64 = 65536;
-
- let used = (memory_size::<0>() as u64) * PAGE_SIZE;
- TOTAL_AVAILABLE - used
-}
-
-#[cfg(not(target_arch = "wasm32"))]
-pub fn get_free_swap() -> u64 {
- use sysinfo::System;
- let mut sys = System::new();
- sys.refresh_memory();
- sys.total_swap() - sys.used_swap()
-}
-
-#[cfg(target_arch = "wasm32")]
-pub fn get_free_swap() -> u64 {
- 0u64
-}
diff --git a/crates/backend-uzu/src/utils/mod.rs b/crates/backend-uzu/src/utils/mod.rs
index 4e523cabc..4b76b2e29 100644
--- a/crates/backend-uzu/src/utils/mod.rs
+++ b/crates/backend-uzu/src/utils/mod.rs
@@ -1,10 +1,6 @@
pub mod dispatch_dtype;
-pub mod env_utils;
pub mod fs;
-pub mod memory;
-#[cfg(metal_backend)]
-pub mod model_size;
+pub mod maybe_mut;
pub mod pointers;
pub mod strict_serde;
pub mod version;
-pub use version::{TOOLCHAIN_VERSION, VERSION};
diff --git a/crates/backend-uzu/src/utils/model_size.rs b/crates/backend-uzu/src/utils/model_size.rs
deleted file mode 100644
index 5b7120d64..000000000
--- a/crates/backend-uzu/src/utils/model_size.rs
+++ /dev/null
@@ -1,30 +0,0 @@
-use std::path::Path;
-
-const FOUR_GB: u64 = 4 * 1024 * 1024 * 1024;
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum ModelSize {
- Large,
- Small,
-}
-
-impl ModelSize {
- pub fn from_path(model_path: &Path) -> std::io::Result<Self> {
- let weights_path = model_path.join("model.safetensors");
- let size_bytes = std::fs::metadata(&weights_path)?.len();
-
- Ok(Self::from_bytes(size_bytes))
- }
-
- pub fn from_bytes(size_bytes: u64) -> Self {
- if size_bytes > FOUR_GB {
- ModelSize::Large
- } else {
- ModelSize::Small
- }
- }
-}
-
-#[cfg(test)]
-#[path = "../../unit/utils/model_size_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/tests/integration_main.rs b/crates/backend-uzu/tests/integration_main.rs
deleted file mode 100644
index 9f8be2e4e..000000000
--- a/crates/backend-uzu/tests/integration_main.rs
+++ /dev/null
@@ -1,4 +0,0 @@
-#![feature(custom_test_frameworks, test)]
-#![test_runner(test_runner::uzu_harness)]
-
-mod session;
diff --git a/crates/backend-uzu/tests/session/chat_session/load_perf_test.rs b/crates/backend-uzu/tests/session/chat_session/load_perf_test.rs
deleted file mode 100644
index f66b7cd8a..000000000
--- a/crates/backend-uzu/tests/session/chat_session/load_perf_test.rs
+++ /dev/null
@@ -1,17 +0,0 @@
-#![cfg(metal_backend)]
-
-use std::{path::PathBuf, time::Instant};
-
-use backend_uzu::session::{Session, config::DecodingConfig};
-use proc_macros::uzu_test;
-use test_tag::tag;
-
-#[ignore = "requires THINKING_TEST_MODEL pointing at a downloaded model"]
-#[tag(heavy)]
-#[uzu_test]
-fn load_time() {
- let path = PathBuf::from(std::env::var("THINKING_TEST_MODEL").expect("set THINKING_TEST_MODEL"));
- let start = Instant::now();
- let _session = Session::new(path, DecodingConfig::default()).expect("load model");
- println!("load_time: {:.3} s", start.elapsed().as_secs_f64());
-}
diff --git a/crates/backend-uzu/tests/session/chat_session/mod.rs b/crates/backend-uzu/tests/session/chat_session/mod.rs
deleted file mode 100644
index e201d2a25..000000000
--- a/crates/backend-uzu/tests/session/chat_session/mod.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-mod load_perf_test;
-mod sampling_test;
-mod thinking_toggle_test;
diff --git a/crates/backend-uzu/tests/session/chat_session/sampling_test.rs b/crates/backend-uzu/tests/session/chat_session/sampling_test.rs
deleted file mode 100644
index cee51ecd1..000000000
--- a/crates/backend-uzu/tests/session/chat_session/sampling_test.rs
+++ /dev/null
@@ -1,86 +0,0 @@
-#![cfg(metal_backend)]
-
-use std::path::{Path, PathBuf};
-
-use backend_uzu::session::{
- Session,
- config::{DecodingConfig, RunConfig},
- parameter::{SamplingMethod, SamplingPolicy, SamplingProcessingOrder, SamplingSeed},
- types::{Input, Message, Output},
-};
-use proc_macros::uzu_test;
-use test_tag::tag;
-
-fn model_path() -> Option<PathBuf> {
- let path = PathBuf::from(std::env::var("THINKING_TEST_MODEL").ok()?);
- path.join("config.json").exists().then_some(path)
-}
-
-fn run(
- path: &Path,
- prompt: &str,
- seed: u64,
- policy: SamplingPolicy,
-) -> String {
- let mut session =
- Session::new(path.to_path_buf(), DecodingConfig::default().with_sampling_seed(SamplingSeed::Custom(seed)))
- .expect("load model");
- session
- .run(
- Input::Messages(vec![Message::user(prompt.to_string())]),
- RunConfig::default().tokens_limit(48).enable_thinking(false).sampling_policy(policy),
- Some(|_: Output| true),
- )
- .expect("run")
- .text
- .original
-}
-
-fn greedy() -> SamplingPolicy {
- SamplingPolicy::Custom {
- value: SamplingMethod::Greedy,
- }
-}
-
-fn stochastic(temperature: f32) -> SamplingPolicy {
- SamplingPolicy::Custom {
- value: SamplingMethod::Stochastic {
- temperature: Some(temperature),
- top_k: None,
- top_p: None,
- min_p: None,
- repetition_penalty: None, // TODO
- suffix_repetition_length: None, // TODO
- processing_order: SamplingProcessingOrder::TemperatureThenFilters,
- },
- }
-}
-
-const PROMPT: &str = "Write one creative sentence about the ocean.";
-
-#[ignore = "requires THINKING_TEST_MODEL pointing at a downloaded model"]
-#[tag(heavy)]
-#[uzu_test]
-fn greedy_sampling_is_deterministic() {
- let Some(path) = model_path() else {
- panic!("set THINKING_TEST_MODEL to a downloaded model directory");
- };
- let a = run(&path, PROMPT, 1, greedy());
- let b = run(&path, PROMPT, 2, greedy());
- println!("greedy (seed 1): {a}\ngreedy (seed 2): {b}");
- assert_eq!(a, b, "greedy sampling must be deterministic regardless of seed");
-}
-
-#[ignore = "requires THINKING_TEST_MODEL pointing at a downloaded model"]
-#[tag(heavy)]
-#[uzu_test]
-fn stochastic_sampling_varies_with_seed() {
- let Some(path) = model_path() else {
- panic!("set THINKING_TEST_MODEL to a downloaded model directory");
- };
- let a = run(&path, PROMPT, 1, stochastic(1.0));
- let b = run(&path, PROMPT, 2, stochastic(1.0));
- let g = run(&path, PROMPT, 1, greedy());
- println!("stochastic (seed 1): {a}\nstochastic (seed 2): {b}\ngreedy: {g}");
- assert_ne!(a, b, "temperature sampling must vary across seeds");
-}
diff --git a/crates/backend-uzu/tests/session/chat_session/thinking_toggle_test.rs b/crates/backend-uzu/tests/session/chat_session/thinking_toggle_test.rs
deleted file mode 100644
index 5074c39a0..000000000
--- a/crates/backend-uzu/tests/session/chat_session/thinking_toggle_test.rs
+++ /dev/null
@@ -1,119 +0,0 @@
-#![cfg(metal_backend)]
-
-use std::path::{Path, PathBuf};
-
-use backend_uzu::session::{
- Session,
- config::{DecodingConfig, RunConfig},
- parameter::SamplingSeed,
- types::{Input, Message, Output},
-};
-use proc_macros::uzu_test;
-use test_tag::tag;
-
-fn model_path() -> Option<PathBuf> {
- let path = PathBuf::from(std::env::var("THINKING_TEST_MODEL").ok()?);
- path.join("config.json").exists().then_some(path)
-}
-
-fn ask(
- path: &Path,
- prompt: &str,
- enable_thinking: bool,
-) -> Output {
- let mut session =
- Session::new(path.to_path_buf(), DecodingConfig::default().with_sampling_seed(SamplingSeed::Custom(42)))
- .expect("load model");
- session
- .run(
- Input::Messages(vec![Message::user(prompt.to_string())]),
- RunConfig::default().tokens_limit(256).enable_thinking(enable_thinking),
- Some(|_: Output| true),
- )
- .expect("run")
-}
-
-fn dump(
- label: &str,
- output: &Output,
-) {
- println!("\n========== {label} ==========");
- println!("[raw generated]\n{}", output.text.original);
- println!("[chain_of_thought] {:?}", output.text.parsed.chain_of_thought);
- println!("[response] {:?}", output.text.parsed.response);
-}
-
-#[ignore = "requires THINKING_TEST_MODEL pointing at a downloaded thinking model"]
-#[tag(heavy)]
-#[uzu_test]
-fn thinking_toggle_end_to_end() {
- let Some(path) = model_path() else {
- panic!("set THINKING_TEST_MODEL to a downloaded thinking-model directory");
- };
- let prompt = "What is 17 + 25? Reply with just the number.";
-
- let on = ask(&path, prompt, true);
- dump("thinking ENABLED", &on);
-
- let off = ask(&path, prompt, false);
- dump("thinking DISABLED", &off);
-
- assert!(
- off.text.parsed.response.as_deref().is_some_and(|response| !response.trim().is_empty()),
- "disabled-thinking output must carry a non-empty response, got {:?}",
- off.text.parsed,
- );
- assert!(
- off.text.parsed.chain_of_thought.is_none(),
- "disabled-thinking output must not render a reasoning chain, got {:?}",
- off.text.parsed.chain_of_thought,
- );
-}
-
-#[ignore = "requires THINKING_TEST_MODEL pointing at a downloaded thinking model"]
-#[tag(heavy)]
-#[uzu_test]
-fn thinking_toggle_within_one_session() {
- let Some(path) = model_path() else {
- panic!("set THINKING_TEST_MODEL to a downloaded thinking-model directory");
- };
- let mut session =
- Session::new(path, DecodingConfig::default().with_sampling_seed(SamplingSeed::Custom(42))).expect("load model");
-
- let turns = [
- ("What is 17 + 25? Reply with just the number.", true),
- ("And what is 8 + 9? Reply with just the number.", false),
- ("And what is 3 + 4? Reply with just the number.", true),
- ];
-
- let mut messages: Vec<Message> = Vec::new();
- for (prompt, enable_thinking) in turns {
- messages.push(Message::user(prompt.to_string()));
- let output = session
- .run(
- Input::Messages(messages.clone()),
- RunConfig::default().tokens_limit(256).enable_thinking(enable_thinking),
- Some(|_: Output| true),
- )
- .expect("run");
- dump(&format!("same-session turn (thinking={enable_thinking})"), &output);
-
- if !enable_thinking {
- assert!(
- output.text.parsed.chain_of_thought.is_none(),
- "disabled turn must not render reasoning, got {:?}",
- output.text.parsed.chain_of_thought,
- );
- assert!(
- output.text.parsed.response.as_deref().is_some_and(|response| !response.trim().is_empty()),
- "disabled turn must carry a non-empty response, got {:?}",
- output.text.parsed,
- );
- }
-
- messages.push(Message::assistant(
- output.text.parsed.response.clone().unwrap_or_default(),
- output.text.parsed.chain_of_thought.clone(),
- ));
- }
-}
diff --git a/crates/backend-uzu/tests/session/mod.rs b/crates/backend-uzu/tests/session/mod.rs
deleted file mode 100644
index 86a373c22..000000000
--- a/crates/backend-uzu/tests/session/mod.rs
+++ /dev/null
@@ -1 +0,0 @@
-mod chat_session;
diff --git a/crates/backend-uzu/unit/audio/nanocodec/runtime.rs b/crates/backend-uzu/unit/audio/nanocodec/runtime.rs
deleted file mode 100644
index a388d1f2c..000000000
--- a/crates/backend-uzu/unit/audio/nanocodec/runtime.rs
+++ /dev/null
@@ -1,204 +0,0 @@
-#![cfg(metal_backend)]
-
-use proc_macros::uzu_test;
-
-use crate::{
- audio::{
- AudioCodecRuntime, AudioError, AudioPcmBatch, AudioTokenGrid, NanoCodecFsqRuntime, NanoCodecFsqRuntimeConfig,
- },
- backends::metal::Metal,
- tests::audio::fsq_reference::{fsq_decode_reference, fsq_encode_reference},
-};
-
-fn create_runtime() -> NanoCodecFsqRuntime<Metal> {
- let config =
- NanoCodecFsqRuntimeConfig::new(24_000, 2, vec![8, 6].into_boxed_slice(), 1e-3).expect("valid runtime config");
- NanoCodecFsqRuntime::new(config)
-}
-
-fn make_pcm(
- channels: usize,
- lengths: &[usize],
-) -> AudioPcmBatch {
- let sample_count = lengths.iter().sum::<usize>() * channels;
- let samples: Vec<f32> = (0..sample_count).map(|index| (index as f32 * 0.071 - 1.3).sin() * 0.9).collect();
- AudioPcmBatch::new(samples.into_boxed_slice(), 24_000, channels, lengths.to_vec().into_boxed_slice()).expect("pcm")
-}
-
-fn pack_for_reference(pcm: &AudioPcmBatch) -> (Vec<f32>, Vec<i32>, usize) {
- let batch_size = pcm.batch_size();
- let channels = pcm.channels();
- let frames = pcm.lengths().iter().copied().max().unwrap_or(0);
- let mut padded = vec![0.0_f32; batch_size * channels * frames];
- let mut lengths_i32 = Vec::with_capacity(batch_size);
-
- let mut src_offset = 0usize;
- for (batch, &length) in pcm.lengths().iter().enumerate() {
- lengths_i32.push(length as i32);
- for frame in 0..length {
- for channel in 0..channels {
- let src_index = src_offset + frame * channels + channel;
- let dst_index = (batch * channels + channel) * frames + frame;
- padded[dst_index] = pcm.samples()[src_index];
- }
- }
- src_offset += length * channels;
- }
-
- (padded, lengths_i32, frames)
-}
-
-fn unpack_reference_output(
- padded: &[f32],
- channels: usize,
- frames: usize,
- lengths: &[usize],
-) -> Vec<f32> {
- let total = lengths.iter().sum::<usize>() * channels;
- let mut out = vec![0.0_f32; total];
- let mut dst_offset = 0usize;
-
- for (batch, &length) in lengths.iter().enumerate() {
- for frame in 0..length {
- for channel in 0..channels {
- let src_index = (batch * channels + channel) * frames + frame;
- let dst_index = dst_offset + frame * channels + channel;
- out[dst_index] = padded[src_index];
- }
- }
- dst_offset += length * channels;
- }
-
- out
-}
-
-#[uzu_test]
-fn nanocodec_runtime_encode_matches_fsq_reference() {
- let runtime = create_runtime();
- let pcm = make_pcm(runtime.config().channels(), &[3, 5]);
- let tokens = runtime.encode(&pcm).expect("encode");
-
- let (padded_input, lengths_i32, frames) = pack_for_reference(&pcm);
- let expected_i32 = fsq_encode_reference(
- &padded_input,
- &lengths_i32,
- pcm.batch_size(),
- runtime.config().num_groups(),
- frames,
- runtime.config().codebook_dim_per_group(),
- runtime.config().num_levels_per_group(),
- runtime.config().dim_base_index(),
- runtime.config().eps(),
- );
- let expected_u32: Vec<u32> = expected_i32.into_iter().map(|value| value as u32).collect();
- let expected = AudioTokenGrid::new(
- expected_u32.into_boxed_slice(),
- pcm.batch_size(),
- runtime.config().num_groups(),
- frames,
- pcm.lengths().to_vec().into_boxed_slice(),
- )
- .expect("expected token grid");
-
- assert_eq!(tokens.batch_size(), expected.batch_size());
- assert_eq!(tokens.codebooks(), expected.codebooks());
- assert_eq!(tokens.frames(), expected.frames());
- assert_eq!(tokens.lengths(), expected.lengths());
- assert_eq!(tokens.tokens(), expected.tokens());
-}
-
-#[uzu_test]
-fn nanocodec_runtime_decode_matches_fsq_reference() {
- let runtime = create_runtime();
- let pcm = make_pcm(runtime.config().channels(), &[4, 2]);
- let encoded = runtime.encode(&pcm).expect("encode");
- let decoded = runtime.decode(&encoded).expect("decode");
-
- let reference_tokens_i32: Vec<i32> = encoded.tokens().iter().map(|&token| token as i32).collect();
- let lengths_i32: Vec<i32> = encoded.lengths().iter().map(|&length| length as i32).collect();
- let reference_padded = fsq_decode_reference(
- &reference_tokens_i32,
- &lengths_i32,
- encoded.batch_size(),
- runtime.config().num_groups(),
- encoded.frames(),
- runtime.config().codebook_dim_per_group(),
- runtime.config().num_levels_per_group(),
- );
- let expected_samples =
- unpack_reference_output(&reference_padded, runtime.config().channels(), encoded.frames(), encoded.lengths());
-
- assert_eq!(decoded.sample_rate(), runtime.config().sample_rate());
- assert_eq!(decoded.channels(), runtime.config().channels());
- assert_eq!(decoded.lengths(), encoded.lengths());
-
- for (index, (&got, &expected)) in decoded.samples().iter().zip(expected_samples.iter()).enumerate() {
- let delta = (got - expected).abs();
- assert!(delta <= 1e-5_f32, "decode mismatch at index={index}: got={got}, expected={expected}, delta={delta}");
- }
-}
-
-#[uzu_test]
-fn nanocodec_runtime_decode_rejects_out_of_range_token() {
- let runtime = create_runtime();
- let cardinality = runtime.config().codec_cardinality();
- let tokens = AudioTokenGrid::new(
- vec![0, cardinality, 1, 2].into_boxed_slice(),
- 1,
- runtime.config().num_groups(),
- 2,
- vec![2usize].into_boxed_slice(),
- )
- .expect("token grid");
-
- let error = runtime.decode(&tokens).expect_err("decode should fail");
- assert_eq!(
- error,
- AudioError::InvalidCodecToken {
- token: cardinality,
- cardinality,
- }
- );
-}
-
-#[uzu_test]
-fn nanocodec_runtime_encode_rejects_channel_mismatch() {
- let runtime = create_runtime();
- let pcm = make_pcm(runtime.config().channels() - 1, &[2]);
-
- let error = runtime.encode(&pcm).expect_err("encode should fail");
- match error {
- AudioError::Runtime(message) => {
- assert!(message.contains("channel mismatch"), "unexpected error message: {message}");
- },
- other => panic!("unexpected error variant: {other:?}"),
- }
-}
-
-#[uzu_test]
-fn fsq_decode_reference_masks_values_beyond_lengths() {
- let output = fsq_decode_reference(&[0, 7, 11, 3, 5, 9], &[2], 1, 2, 3, 2, &[8, 5]);
-
- assert_eq!(output.len(), 12);
- let masked_t2 = [output[2], output[5], output[8], output[11]];
- assert_eq!(masked_t2, [0.0, 0.0, 0.0, 0.0]);
-}
-
-#[uzu_test]
-fn fsq_encode_reference_masks_values_beyond_lengths() {
- let tokens = fsq_encode_reference(
- &[-0.9, -0.1, 0.2, 0.7, 0.8, 0.3, -0.4, -0.7, -0.2, 0.0, 0.4, 0.9, 0.5, -0.5, 0.1, -0.1],
- &[3],
- 1,
- 2,
- 4,
- 2,
- &[8, 6],
- &[1, 8],
- 1e-3,
- );
-
- assert_eq!(tokens.len(), 8);
- assert_eq!(tokens[3], 0);
- assert_eq!(tokens[7], 0);
-}
diff --git a/crates/backend-uzu/unit/audio/types_test.rs b/crates/backend-uzu/unit/audio/types_test.rs
deleted file mode 100644
index 3cc69dbe0..000000000
--- a/crates/backend-uzu/unit/audio/types_test.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-use proc_macros::uzu_test;
-
-use super::{AudioError, AudioTokenGrid};
-
-#[uzu_test]
-fn token_grid_get_reads_expected_slots() {
- let grid = AudioTokenGrid::new(
- vec![
- 0, 1, 2, 3, // b0 f0, f1
- 4, 5, 6, 7, // b1 f0, f1
- ]
- .into_boxed_slice(),
- 2,
- 2,
- 2,
- vec![2, 2].into_boxed_slice(),
- )
- .expect("valid grid");
-
- assert_eq!(grid.get(0, 0, 0), 0);
- assert_eq!(grid.get(0, 1, 1), 3);
- assert_eq!(grid.get(1, 0, 0), 4);
- assert_eq!(grid.get(1, 1, 1), 7);
-}
-
-#[uzu_test]
-fn invalid_grid_shape_is_rejected() {
- let error = AudioTokenGrid::new(vec![0, 1, 2].into_boxed_slice(), 1, 2, 2, vec![2].into_boxed_slice())
- .expect_err("shape mismatch should fail");
-
- assert!(matches!(
- error,
- AudioError::InvalidTokenShape {
- expected_tokens: 4,
- actual_tokens: 3
- }
- ));
-}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/attention/attention_fallback_test.rs b/crates/backend-uzu/unit/backends/common/kernel/attention/attention_fallback_test.rs
index 459e2f306..5298f0743 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/attention/attention_fallback_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/attention/attention_fallback_test.rs
@@ -135,9 +135,8 @@ fn pipeline_output<B: Backend>(
a: &qa,
a_offset: g as usize * GQA as usize * SUFFIX as usize * q_row,
b: MatmulB::FullPrecision {
- b: &ka,
+ b: (&ka, g as usize * head_stride * dt),
},
- b_offset: g as usize * head_stride * dt,
b_leading_dimension: Some(HEAD_DIM),
b_transpose: true,
d: &mut grp_s,
@@ -176,9 +175,8 @@ fn pipeline_output<B: Backend>(
a: &scores,
a_offset: g as usize * GQA as usize * SUFFIX as usize * s_row,
b: MatmulB::FullPrecision {
- b: &va,
+ b: (&va, g as usize * head_stride * dt),
},
- b_offset: g as usize * head_stride * dt,
b_leading_dimension: Some(HEAD_DIM),
b_transpose: false,
d: &mut grp_o,
diff --git a/crates/backend-uzu/unit/backends/common/kernel/attention/attention_two_pass_test.rs b/crates/backend-uzu/unit/backends/common/kernel/attention/attention_two_pass_test.rs
index edc9bac0f..b01cfa1f0 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/attention/attention_two_pass_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/attention/attention_two_pass_test.rs
@@ -6,7 +6,7 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{
Allocation, Backend, Context, Encoder, Kernels,
@@ -15,7 +15,10 @@ use crate::{
cpu::Cpu,
},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
const TOTAL_BLOCKS_COUNT: u32 = 32;
@@ -100,24 +103,24 @@ fn get_first_pass_output<T: ArrayElement + Float, B: Backend>(input: &FirstPassI
)
.expect("Failed to create AttentionTwoPass1Kernel");
- let queries_array = context.create_array_from(&[input.queries.len()], &input.queries);
- let keys_array = context.create_array_from(&[input.keys.len()], &input.keys);
- let values_array = context.create_array_from(&[input.values.len()], &input.values);
+ let queries = alloc_allocation_with_data::<B, T>(&context, &input.queries);
+ let keys = alloc_allocation_with_data::<B, T>(&context, &input.keys);
+ let values = alloc_allocation_with_data::<B, T>(&context, &input.values);
let total_offsets = (input.suffix_length * input.num_heads) as usize;
let partials_size = total_offsets * TOTAL_BLOCKS_COUNT as usize * input.head_dim as usize;
let sums_size = total_offsets * TOTAL_BLOCKS_COUNT as usize;
let maxs_size = total_offsets * TOTAL_BLOCKS_COUNT as usize;
- let mut partials = context.create_array_uninitialized(&[partials_size], DataType::F32).into_allocation();
- let mut sums = context.create_array_uninitialized(&[sums_size], DataType::F32).into_allocation();
- let mut maxs = context.create_array_uninitialized(&[maxs_size], DataType::F32).into_allocation();
+ let mut partials = alloc_allocation::<B, f32>(&context, partials_size);
+ let mut sums = alloc_allocation::<B, f32>(&context, sums_size);
+ let mut maxs = alloc_allocation::<B, f32>(&context, maxs_size);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- queries_array.allocation(),
- keys_array.allocation(),
- values_array.allocation(),
+ &queries,
+ &keys,
+ &values,
&mut partials,
&mut sums,
&mut maxs,
@@ -139,9 +142,9 @@ fn get_first_pass_output<T: ArrayElement + Float, B: Backend>(input: &FirstPassI
encoder.end_encoding().submit().wait_until_completed().unwrap();
FirstPassOutput {
- partials: crate::tests::helpers::allocation_to_vec(&partials),
- sums: crate::tests::helpers::allocation_to_vec(&sums),
- maxs: crate::tests::helpers::allocation_to_vec(&maxs),
+ partials: allocation_to_vec(&partials),
+ sums: allocation_to_vec(&sums),
+ maxs: allocation_to_vec(&maxs),
}
}
@@ -199,26 +202,18 @@ fn get_second_pass_output<T: ArrayElement + Float, B: Backend>(input: &SecondPas
<<B as Backend>::Kernels as Kernels>::AttentionTwoPass2Kernel::new(&context, T::data_type(), input.head_dim)
.expect("Failed to create AttentionTwoPass2Kernel");
- let partials_array = context.create_array_from(&[input.partials.len()], &input.partials);
- let sums_array = context.create_array_from(&[input.sums.len()], &input.sums);
- let maxs_array = context.create_array_from(&[input.maxs.len()], &input.maxs);
+ let partials = alloc_allocation_with_data::<B, f32>(&context, &input.partials);
+ let sums = alloc_allocation_with_data::<B, f32>(&context, &input.sums);
+ let maxs = alloc_allocation_with_data::<B, f32>(&context, &input.maxs);
let output_size = (input.suffix_length * input.num_heads * input.head_dim) as usize;
- let mut output = context.create_array_uninitialized(&[output_size], T::data_type()).into_allocation();
+ let mut output = alloc_allocation::<B, T>(&context, output_size);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- partials_array.allocation(),
- sums_array.allocation(),
- maxs_array.allocation(),
- &mut output,
- input.num_heads,
- input.suffix_length,
- &mut encoder,
- );
+ kernel.encode(&partials, &sums, &maxs, &mut output, input.num_heads, input.suffix_length, &mut encoder);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- crate::tests::helpers::allocation_to_vec(&output)
+ allocation_to_vec(&output)
}
// --- First pass tests ---
diff --git a/crates/backend-uzu/unit/backends/common/kernel/attention/attention_update_kv_cache_test.rs b/crates/backend-uzu/unit/backends/common/kernel/attention/attention_update_kv_cache_test.rs
deleted file mode 100644
index 40b9d42d1..000000000
--- a/crates/backend-uzu/unit/backends/common/kernel/attention/attention_update_kv_cache_test.rs
+++ /dev/null
@@ -1,424 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::uzu_test;
-use test_runner::for_each_non_cpu_backend;
-
-use crate::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{Backend, Context, Encoder, Kernels, kernel::AttentionUpdateKVCacheKernel},
- cpu::Cpu,
- },
- data_type::DataType,
- tests::assert::assert_eq_float,
-};
-
-struct Input<T: ArrayElement + Float> {
- rotated_keys: Option<Box<[T]>>,
- qkv: Box<[T]>,
- key_cache: Box<[T]>,
- value_cache: Box<[T]>,
- num_groups: u32,
- num_heads: u32,
- head_dim: u32,
- suffix_length: u32,
- prefix_segment_length: u32,
- max_sequence_length: u32,
- keys_in_place: bool,
-}
-
-fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>, Vec<T>) {
- let context = B::Context::new().expect("Failed to create Context");
-
- let kernel = <<B as Backend>::Kernels as Kernels>::AttentionUpdateKVCacheKernel::new(
- &context,
- T::data_type(),
- input.keys_in_place,
- )
- .expect("Failed to create AttentionUpdateKVCacheKernel");
-
- let cache_size = input.num_groups as usize * input.max_sequence_length as usize * input.head_dim as usize;
-
- let rotated_keys =
- input.rotated_keys.as_ref().map(|rk| context.create_array_from(&[rk.len()], rk).into_allocation());
-
- let qkv_array = context.create_array_from(&[input.qkv.len()], &input.qkv);
- let mut key_cache = context.create_array_from(&[cache_size], &input.key_cache).into_allocation();
- let mut value_cache = context.create_array_from(&[cache_size], &input.value_cache).into_allocation();
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- rotated_keys.as_ref(),
- qkv_array.allocation(),
- &mut key_cache,
- &mut value_cache,
- input.num_groups,
- input.num_heads,
- input.head_dim,
- input.suffix_length,
- input.prefix_segment_length,
- input.max_sequence_length,
- &mut encoder,
- );
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- (crate::tests::helpers::allocation_to_vec(&key_cache), crate::tests::helpers::allocation_to_vec(&value_cache))
-}
-
-fn get_test_data_basic<T: ArrayElement + Float>(keys_in_place: bool) -> Input<T> {
- let num_groups = 4u32;
- let num_heads = 8u32;
- let head_dim = 4u32;
- let suffix_length = 3u32;
- let prefix_segment_length = 2u32;
- let max_sequence_length = 8u32;
-
- let cache_size = (num_groups * max_sequence_length * head_dim) as usize;
- let qkv_stride = ((num_heads + 2 * num_groups) * head_dim) as usize;
- let qkv_size = suffix_length as usize * qkv_stride;
-
- let mut qkv = vec![T::zero(); qkv_size];
- for i in 0..qkv_size {
- qkv[i] = T::from(((i as f32) * 0.1).sin() * 5.0).unwrap();
- }
-
- let mut key_cache = vec![T::zero(); cache_size];
- let mut value_cache = vec![T::zero(); cache_size];
- for i in 0..cache_size {
- key_cache[i] = T::from(((i as f32) * 0.3 + 1.0).cos() * 2.0).unwrap();
- value_cache[i] = T::from(((i as f32) * 0.2 + 0.5).sin() * 3.0).unwrap();
- }
-
- let rotated_keys = if keys_in_place {
- None
- } else {
- let mut rk = vec![T::zero(); cache_size];
- for i in 0..cache_size {
- rk[i] = T::from(((i as f32) * 0.07 + 2.0).sin() * 4.0).unwrap();
- }
- Some(rk.into_boxed_slice())
- };
-
- Input {
- rotated_keys,
- qkv: qkv.into_boxed_slice(),
- key_cache: key_cache.into_boxed_slice(),
- value_cache: value_cache.into_boxed_slice(),
- num_groups,
- num_heads,
- head_dim,
- suffix_length,
- prefix_segment_length,
- max_sequence_length,
- keys_in_place,
- }
-}
-
-fn get_test_data_single_token<T: ArrayElement + Float>(keys_in_place: bool) -> Input<T> {
- let num_groups = 2u32;
- let num_heads = 8u32;
- let head_dim = 4u32;
- let suffix_length = 1u32;
- let prefix_segment_length = 5u32;
- let max_sequence_length = 16u32;
-
- let cache_size = (num_groups * max_sequence_length * head_dim) as usize;
- let qkv_stride = ((num_heads + 2 * num_groups) * head_dim) as usize;
- let qkv_size = suffix_length as usize * qkv_stride;
-
- let mut qkv = vec![T::zero(); qkv_size];
- for i in 0..qkv_size {
- qkv[i] = T::from((i as f32 + 1.0) * 0.25).unwrap();
- }
-
- let mut key_cache = vec![T::zero(); cache_size];
- let mut value_cache = vec![T::zero(); cache_size];
- for i in 0..cache_size {
- key_cache[i] = T::from(i as f32 * 0.01).unwrap();
- value_cache[i] = T::from(i as f32 * -0.01).unwrap();
- }
-
- let rotated_keys = if keys_in_place {
- None
- } else {
- let mut rk = vec![T::zero(); cache_size];
- for i in 0..cache_size {
- rk[i] = T::from((i as f32 + 0.5) * 0.1).unwrap();
- }
- Some(rk.into_boxed_slice())
- };
-
- Input {
- rotated_keys,
- qkv: qkv.into_boxed_slice(),
- key_cache: key_cache.into_boxed_slice(),
- value_cache: value_cache.into_boxed_slice(),
- num_groups,
- num_heads,
- head_dim,
- suffix_length,
- prefix_segment_length,
- max_sequence_length,
- keys_in_place,
- }
-}
-
-fn get_test_data_prefix_zero<T: ArrayElement + Float>() -> Input<T> {
- let num_groups = 2u32;
- let num_heads = 4u32;
- let head_dim = 8u32;
- let suffix_length = 2u32;
- let prefix_segment_length = 0u32;
- let max_sequence_length = 4u32;
-
- let cache_size = (num_groups * max_sequence_length * head_dim) as usize;
- let qkv_stride = ((num_heads + 2 * num_groups) * head_dim) as usize;
- let qkv_size = suffix_length as usize * qkv_stride;
-
- let mut qkv = vec![T::zero(); qkv_size];
- for i in 0..qkv_size {
- qkv[i] = T::from(((i as f32) * 0.13).sin() * 3.0).unwrap();
- }
-
- let key_cache = vec![T::zero(); cache_size];
- let value_cache = vec![T::zero(); cache_size];
-
- let mut rk = vec![T::zero(); cache_size];
- for i in 0..cache_size {
- rk[i] = T::from(((i as f32) * 0.17 + 1.0).cos() * 2.0).unwrap();
- }
-
- Input {
- rotated_keys: Some(rk.into_boxed_slice()),
- qkv: qkv.into_boxed_slice(),
- key_cache: key_cache.into_boxed_slice(),
- value_cache: value_cache.into_boxed_slice(),
- num_groups,
- num_heads,
- head_dim,
- suffix_length,
- prefix_segment_length,
- max_sequence_length,
- keys_in_place: false,
- }
-}
-
-fn get_test_data_keys_in_place_offset<T: ArrayElement + Float>() -> Input<T> {
- let num_groups = 2u32;
- let num_heads = 4u32;
- let head_dim = 2u32;
- let suffix_length = 1u32;
- let prefix_segment_length = 3u32;
- let max_sequence_length = 5u32;
-
- let cache_size = (num_groups * max_sequence_length * head_dim) as usize;
- let qkv_stride = ((num_heads + 2 * num_groups) * head_dim) as usize;
- let qkv_size = suffix_length as usize * qkv_stride;
-
- let mut qkv = vec![T::zero(); qkv_size];
- let value_base_offset = ((num_heads + num_groups) * head_dim) as usize;
- for g in 0..num_groups as usize {
- for d in 0..head_dim as usize {
- let off = value_base_offset + g * head_dim as usize + d;
- qkv[off] = T::from(200.0 + (g * head_dim as usize + d) as f32).unwrap();
- }
- }
-
- // Place rotated key sentinels at the rotated_key_offset positions of the
- // (in-place) source buffer: (g * suffix_length + t) * head_dim + d.
- let mut key_cache = vec![T::zero(); cache_size];
- for g in 0..num_groups as usize {
- for t in 0..suffix_length as usize {
- for d in 0..head_dim as usize {
- let off = (g * suffix_length as usize + t) * head_dim as usize + d;
- key_cache[off] =
- T::from(100.0 + ((g * suffix_length as usize + t) * head_dim as usize + d) as f32).unwrap();
- }
- }
- }
-
- let value_cache = vec![T::zero(); cache_size];
-
- Input {
- rotated_keys: None,
- qkv: qkv.into_boxed_slice(),
- key_cache: key_cache.into_boxed_slice(),
- value_cache: value_cache.into_boxed_slice(),
- num_groups,
- num_heads,
- head_dim,
- suffix_length,
- prefix_segment_length,
- max_sequence_length,
- keys_in_place: true,
- }
-}
-
-fn test_keys_in_place_cache_offset<T: ArrayElement + Float + Debug + Display>() {
- let input = get_test_data_keys_in_place_offset::<T>();
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 0.01f32
- } else {
- 1e-6
- };
-
- for_each_non_cpu_backend!(|B| {
- let (key_cache_out, value_cache_out) = get_output::<T, B>(&input);
- let backend_name = std::any::type_name::<B>();
-
- for g in 0..input.num_groups {
- for t in 0..input.suffix_length {
- for d in 0..input.head_dim {
- let cache_token_index = input.prefix_segment_length + t;
- // keys_in_place layout:
- // cache_offset = (group * max_sequence_length
- // + cache_token_index) * head_dim + dim
- let cache_offset =
- ((g * input.max_sequence_length + cache_token_index) * input.head_dim + d) as usize;
-
- let rotated_key_offset = ((g * input.suffix_length + t) * input.head_dim + d) as usize;
- let expected_key = T::from(100.0 + rotated_key_offset as f32).unwrap();
- let value_lane = (g * input.head_dim + d) as usize;
- let expected_value = T::from(200.0 + value_lane as f32).unwrap();
-
- assert_eq_float::<T>(
- &[expected_key],
- &[key_cache_out[cache_offset]],
- eps,
- &format!(
- "key_cache[{}] mismatch (backend={}, g={}, t={}, d={})",
- cache_offset, backend_name, g, t, d,
- ),
- );
- assert_eq_float::<T>(
- &[expected_value],
- &[value_cache_out[cache_offset]],
- eps,
- &format!(
- "value_cache[{}] mismatch (backend={}, g={}, t={}, d={})",
- cache_offset, backend_name, g, t, d,
- ),
- );
- }
- }
- }
- });
-}
-
-fn test_internal<T: ArrayElement + Float + Debug + Display>(
- input: &Input<T>,
- expected_key_cache: &[T],
- expected_value_cache: &[T],
-) {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 0.01f32
- } else {
- 1e-6
- };
-
- for_each_non_cpu_backend!(|B| {
- let (key_cache_out, value_cache_out) = get_output::<T, B>(input);
- let backend_name = std::any::type_name::<B>();
- assert_eq_float::<T>(
- expected_key_cache,
- &key_cache_out,
- eps,
- &format!("key_cache mismatch (backend={}, keys_in_place={})", backend_name, input.keys_in_place),
- );
- assert_eq_float::<T>(
- expected_value_cache,
- &value_cache_out,
- eps,
- &format!("value_cache mismatch (backend={}, keys_in_place={})", backend_name, input.keys_in_place),
- );
- });
-}
-
-fn test_basic<T: ArrayElement + Float + Debug + Display>() {
- {
- let keys_in_place = false;
- let input = get_test_data_basic::<T>(keys_in_place);
- let (expected_key_cache, expected_value_cache) = get_output::<T, Cpu>(&input);
- test_internal(&input, &expected_key_cache, &expected_value_cache);
- }
-}
-
-fn test_single_token<T: ArrayElement + Float + Debug + Display>() {
- for keys_in_place in [false, true] {
- let input = get_test_data_single_token::<T>(keys_in_place);
- let (expected_key_cache, expected_value_cache) = get_output::<T, Cpu>(&input);
- test_internal(&input, &expected_key_cache, &expected_value_cache);
- }
-}
-
-fn test_prefix_zero<T: ArrayElement + Float + Debug + Display>() {
- let input = get_test_data_prefix_zero::<T>();
- let (expected_key_cache, expected_value_cache) = get_output::<T, Cpu>(&input);
- test_internal(&input, &expected_key_cache, &expected_value_cache);
-}
-
-// Basic tests
-#[uzu_test]
-fn test_basic_f32() {
- test_basic::<f32>();
-}
-
-#[uzu_test]
-fn test_basic_f16() {
- test_basic::<f16>();
-}
-
-#[uzu_test]
-fn test_basic_bf16() {
- test_basic::<bf16>();
-}
-
-// Single token tests (typical decode step)
-#[uzu_test]
-fn test_single_token_f32() {
- test_single_token::<f32>();
-}
-
-#[uzu_test]
-fn test_single_token_f16() {
- test_single_token::<f16>();
-}
-
-#[uzu_test]
-fn test_single_token_bf16() {
- test_single_token::<bf16>();
-}
-
-// Prefix zero (first fill of empty cache)
-#[uzu_test]
-fn test_prefix_zero_f32() {
- test_prefix_zero::<f32>();
-}
-
-#[uzu_test]
-fn test_prefix_zero_f16() {
- test_prefix_zero::<f16>();
-}
-
-#[uzu_test]
-fn test_prefix_zero_bf16() {
- test_prefix_zero::<bf16>();
-}
-
-// Explicit cache_offset verification when keys_in_place == true.
-#[uzu_test]
-fn test_keys_in_place_cache_offset_f32() {
- test_keys_in_place_cache_offset::<f32>();
-}
-
-#[uzu_test]
-fn test_keys_in_place_cache_offset_f16() {
- test_keys_in_place_cache_offset::<f16>();
-}
-
-#[uzu_test]
-fn test_keys_in_place_cache_offset_bf16() {
- test_keys_in_place_cache_offset::<bf16>();
-}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/attention/mod.rs b/crates/backend-uzu/unit/backends/common/kernel/attention/mod.rs
index 08f4c10bb..d843ffc6d 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/attention/mod.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/attention/mod.rs
@@ -1,5 +1,4 @@
mod attention_fallback_test;
mod attention_single_pass_test;
mod attention_two_pass_test;
-mod attention_update_kv_cache_test;
mod sigmoid_gate_test;
diff --git a/crates/backend-uzu/unit/backends/common/kernel/attention/sigmoid_gate_test.rs b/crates/backend-uzu/unit/backends/common/kernel/attention/sigmoid_gate_test.rs
index c5d98fbed..a39260d63 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/attention/sigmoid_gate_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/attention/sigmoid_gate_test.rs
@@ -6,11 +6,12 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::SigmoidGateKernel},
cpu::Cpu,
},
+ tests::helpers::{alloc_allocation_with_data, allocation_to_vec},
};
struct Config {
@@ -24,20 +25,19 @@ fn get_output<T: ArrayElement + Float, B: Backend>(
output_data: &[T],
config: &Config,
) -> Vec<T> {
- let size = gate_data.len();
let context = B::Context::new().expect("Failed to create Context");
let kernel = <<B as Backend>::Kernels as Kernels>::SigmoidGateKernel::new(&context, T::data_type())
.expect("Failed to create SigmoidGateKernel");
- let gate_array = context.create_array_from(&[size], &gate_data.to_vec().into_boxed_slice());
- let mut output = context.create_array_from(&[size], &output_data.to_vec().into_boxed_slice()).into_allocation();
+ let gate_allocation = alloc_allocation_with_data::<B, T>(&context, gate_data);
+ let mut output = alloc_allocation_with_data::<B, T>(&context, output_data);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
let total_elements = config.suffix_length * config.num_heads * config.head_dim;
- kernel.encode(gate_array.allocation(), &mut output, total_elements, &mut encoder);
+ kernel.encode(&gate_allocation, &mut output, total_elements, &mut encoder);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- crate::tests::helpers::allocation_to_vec(&output)
+ allocation_to_vec(&output)
}
fn run_test<T: ArrayElement + Float + Debug>(config: &Config) {
diff --git a/crates/backend-uzu/unit/backends/common/kernel/audio/audio_kernel_perf.rs b/crates/backend-uzu/unit/backends/common/kernel/audio/audio_kernel_perf.rs
deleted file mode 100644
index c0379ea49..000000000
--- a/crates/backend-uzu/unit/backends/common/kernel/audio/audio_kernel_perf.rs
+++ /dev/null
@@ -1,1416 +0,0 @@
-#![cfg(metal_backend)]
-
-use std::time::Instant;
-
-use proc_macros::uzu_test;
-
-use crate::{
- array::{Array, ArrayContextExt},
- backends::{
- common::{
- Backend, Context, Encoder, Kernels,
- gpu_types::ActivationType,
- kernel::{
- ActivationKernel, AudioAddKernel, AudioCausalConv1dGroupedKernel,
- AudioCausalConv1dGroupedResidualKernel, AudioCausalConv1dKernel,
- AudioCausalConvTranspose1dCausalPadKernel, AudioConv1dKernel, AudioHalfSnakeKernel, AudioNormNcsKernel,
- AudioQuantizerDecodeKernel,
- },
- },
- metal::Metal,
- },
- data_type::DataType,
-};
-
-type Ctx = <Metal as Backend>::Context;
-
-const WARMUP: usize = 5;
-const ITERATIONS: usize = 20;
-
-fn measure<F: FnMut()>(
- label: &str,
- mut f: F,
-) -> f64 {
- for _ in 0..WARMUP {
- f();
- }
- let start = Instant::now();
- for _ in 0..ITERATIONS {
- f();
- }
- let elapsed = start.elapsed();
- let mean_ms = elapsed.as_secs_f64() * 1000.0 / ITERATIONS as f64;
- println!(" {label:<65} {mean_ms:>8.3} ms");
- mean_ms
-}
-
-fn make_lengths(
- context: &Ctx,
- batch_size: usize,
- value: i32,
-) -> Array<Metal> {
- context.create_array_from(&[batch_size], &vec![value; batch_size])
-}
-
-// ==========================================================================
-// FishAudio s1-mini vocoder configuration (from model config JSON)
-//
-// input_dim = 1024
-// decoder_dim = 1536
-// downsample_factor = [2, 2] (reversed for upsampler -> strides [2, 2])
-// decoder_rates = [8, 8, 4, 2]
-// n_codebooks = 9 (+ 1 semantic = 10 total)
-// codebook_dim = 8
-// codebook_size = 1024
-// semantic_codebook_size = 4096
-// samplerate = 44100
-// upsample_factor = 2*2 * 8*8*4*2 = 2048
-//
-// Channel progression (standard DAC with decoder_dim=1536):
-// Upsampler: 1024 -> 512 (s=2) -> 256 (s=2)
-// first_conv: 256 -> 1536 (k=7)
-// Decoder: 1536 -> 768 (s=8) -> 384 (s=8) -> 192 (s=4) -> 96 (s=2)
-// final_conv: 96 -> 1 (k=7)
-//
-// Residual units per decoder block: 3, with dilations [1, 3, 9], k=7
-// ConvNeXt depthwise: k=7, per-channel
-// Transpose conv kernel_size = stride * 2 (fast_two_tap path)
-//
-// For 10 seconds at 44100 Hz:
-// 441000 samples / 2048 upsample_factor = ~215 semantic frames
-// We use 215 frames as the starting point.
-// ==========================================================================
-
-const INPUT_DIM: usize = 1024;
-const DECODER_DIM: usize = 1536;
-const CODEBOOK_DIM: usize = 8;
-const TOTAL_CODEBOOKS: usize = 10;
-const RESIDUAL_QUANTIZERS: usize = 9;
-const SEMANTIC_CARDINALITY: usize = 4096;
-const RESIDUAL_CARDINALITY: usize = 1024;
-
-// Upsample block channel progression: input_dim -> input_dim/2 -> input_dim/4
-const UP_CHANNELS: [usize; 3] = [1024, 512, 256];
-const UP_STRIDES: [usize; 2] = [2, 2]; // downsample_factor reversed
-
-// Decoder block channel progression: decoder_dim -> decoder_dim/2 -> /4 -> /8 -> /16
-const DEC_CHANNELS: [usize; 5] = [1536, 768, 384, 192, 96];
-const DEC_STRIDES: [usize; 4] = [8, 8, 4, 2]; // decoder_rates
-
-const SEMANTIC_FRAMES_10S: usize = 215; // ~10s at 44100 Hz with upsample_factor=2048
-
-#[uzu_test]
-#[ignore] // Heavy benchmark (~240s); run explicitly with --ignored
-fn audio_kernel_perf() {
- let context = <Metal as Backend>::Context::new().unwrap();
- let dt = DataType::F16;
- let batch_size: usize = 1;
-
- let mut results: Vec<(String, f64)> = Vec::new();
-
- println!();
- println!(" FishAudio s1-mini vocoder kernel benchmark (10s audio, 44.1kHz, F16)");
- println!(" =====================================================================");
- println!();
- println!(" {:<65} {:>8}", "Kernel", "Mean (ms)");
- println!(" {:-<65} {:-<8}", "", "");
-
- // -----------------------------------------------------------------------
- // 1. AudioQuantizerDecodeKernel
- // tokens: [B, K, T], output: [B, T, input_dim]
- // -----------------------------------------------------------------------
- {
- let frames = SEMANTIC_FRAMES_10S;
-
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AudioQuantizerDecodeKernel::new(&context, dt).unwrap();
-
- let tokens = context.create_array_zeros(&[batch_size * TOTAL_CODEBOOKS * frames], DataType::U32);
- let lengths = make_lengths(&context, batch_size, frames as i32);
- let semantic_codebook = context.create_array_zeros(&[SEMANTIC_CARDINALITY * CODEBOOK_DIM], dt);
- let semantic_out_proj = context.create_array_zeros(&[INPUT_DIM * CODEBOOK_DIM], dt);
- let semantic_out_bias = context.create_array_zeros(&[INPUT_DIM], dt);
- let residual_codebooks =
- context.create_array_zeros(&[RESIDUAL_QUANTIZERS * RESIDUAL_CARDINALITY * CODEBOOK_DIM], dt);
- let residual_out_proj = context.create_array_zeros(&[RESIDUAL_QUANTIZERS * INPUT_DIM * CODEBOOK_DIM], dt);
- let residual_out_bias = context.create_array_zeros(&[RESIDUAL_QUANTIZERS * INPUT_DIM], dt);
- let mut output = context.create_array_zeros(&[batch_size * frames * INPUT_DIM], dt).into_allocation();
-
- let label = format!(
- "QuantizerDecode [B={}, T={}, K={}, dim={}, cdim={}]",
- batch_size, frames, TOTAL_CODEBOOKS, INPUT_DIM, CODEBOOK_DIM
- );
- let ms = measure(&label, || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
- {
- let tok = tokens.allocation();
- let len = lengths.allocation();
- let scb = semantic_codebook.allocation();
- let sp = semantic_out_proj.allocation();
- let sb = semantic_out_bias.allocation();
- let rcb = residual_codebooks.allocation();
- let rp = residual_out_proj.allocation();
- let rb = residual_out_bias.allocation();
- let out = &mut output;
- kernel.encode(
- tok,
- len,
- scb,
- sp,
- sb,
- rcb,
- rp,
- rb,
- out,
- batch_size as i32,
- TOTAL_CODEBOOKS as i32,
- frames as i32,
- INPUT_DIM as i32,
- CODEBOOK_DIM as i32,
- RESIDUAL_QUANTIZERS as i32,
- SEMANTIC_CARDINALITY as i32,
- RESIDUAL_CARDINALITY as i32,
- &mut encoder,
- );
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push(("QuantizerDecode".into(), ms));
- }
-
- // -----------------------------------------------------------------------
- // 2. ConvTranspose1dCausalPad — all 6 stages where it appears
- // Upsample: 1024->512 s=2, 512->256 s=2
- // Decoder: 1536->768 s=8, 768->384 s=8, 384->192 s=4, 192->96 s=2
- // -----------------------------------------------------------------------
- {
- let kernel =
- <<Metal as Backend>::Kernels as Kernels>::AudioCausalConvTranspose1dCausalPadKernel::new(&context, dt)
- .unwrap();
-
- // Upsample blocks (NSC input for first, NCS for rest)
- let up_configs: [(usize, usize, usize, i32, &str); 2] = [
- (UP_CHANNELS[0], UP_CHANNELS[1], UP_STRIDES[0], 1, "up0 NSC"), // 1024->512, s=2
- (UP_CHANNELS[1], UP_CHANNELS[2], UP_STRIDES[1], 0, "up1 NCS"), // 512->256, s=2
- ];
- let mut frames = SEMANTIC_FRAMES_10S;
- for (cin, cout, stride, layout, tag) in up_configs {
- let seq_in = frames;
- let seq_out = seq_in * stride;
- let ksize = stride * 2;
- let input = context.create_array_zeros(&[batch_size * cin * seq_in], dt);
- let weight = context.create_array_zeros(&[cin * cout * ksize], dt);
- let bias = context.create_array_zeros(&[cout], dt);
- let mut output = context.create_array_zeros(&[batch_size * cout * seq_out], dt).into_allocation();
- let lengths = make_lengths(&context, batch_size, seq_out as i32);
-
- let label = format!("TransConv {tag} [{cin}->{cout}, s={stride}, k={ksize}, {seq_in}->{seq_out}]");
- let ms = measure(&label, || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
- {
- let i = input.allocation();
- let w = weight.allocation();
- let b = bias.allocation();
- let o = &mut output;
- let l = lengths.allocation();
- kernel.encode(
- i,
- w,
- b,
- o,
- l,
- cin as i32,
- cout as i32,
- seq_in as i32,
- seq_out as i32,
- ksize as i32,
- stride as i32,
- 1_i32,
- layout,
- batch_size as i32,
- &mut encoder,
- );
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push((format!("TransConv {tag}"), ms));
- frames = seq_out;
- }
-
- // Decoder blocks (all NCS input)
- frames = SEMANTIC_FRAMES_10S * UP_STRIDES[0] * UP_STRIDES[1]; // 860
- for block_idx in 0..4 {
- let cin = DEC_CHANNELS[block_idx];
- let cout = DEC_CHANNELS[block_idx + 1];
- let stride = DEC_STRIDES[block_idx];
- let seq_in = frames;
- let seq_out = seq_in * stride;
- let ksize = stride * 2;
- let input = context.create_array_zeros(&[batch_size * cin * seq_in], dt);
- let weight = context.create_array_zeros(&[cin * cout * ksize], dt);
- let bias = context.create_array_zeros(&[cout], dt);
- let mut output = context.create_array_zeros(&[batch_size * cout * seq_out], dt).into_allocation();
- let lengths = make_lengths(&context, batch_size, seq_out as i32);
-
- let label = format!("TransConv dec{block_idx} [{cin}->{cout}, s={stride}, k={ksize}, {seq_in}->{seq_out}]");
- let ms = measure(&label, || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
- {
- let i = input.allocation();
- let w = weight.allocation();
- let b = bias.allocation();
- let o = &mut output;
- let l = lengths.allocation();
- kernel.encode(
- i,
- w,
- b,
- o,
- l,
- cin as i32,
- cout as i32,
- seq_in as i32,
- seq_out as i32,
- ksize as i32,
- stride as i32,
- 1_i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push((format!("TransConv dec{block_idx}"), ms));
- frames = seq_out;
- }
- }
-
- // -----------------------------------------------------------------------
- // 3. CausalConv1d (groups=1) — first_conv, final_conv, and residual conv1
- // first_conv: 256->1536, k=7
- // residual conv1: same-channel, k=7, dilations [1,3,9]
- // final_conv: 96->1, k=7
- // -----------------------------------------------------------------------
- {
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AudioCausalConv1dKernel::new(&context, dt).unwrap();
-
- // first_conv after upsampler: 256->1536, k=7
- let fc_seq = SEMANTIC_FRAMES_10S * UP_STRIDES[0] * UP_STRIDES[1]; // 860
- {
- let cin = UP_CHANNELS[2]; // 256
- let cout = DECODER_DIM; // 1536
- let ksize = 7;
- let input = context.create_array_zeros(&[batch_size * cin * fc_seq], dt);
- let weight = context.create_array_zeros(&[cout * cin * ksize], dt);
- let bias = context.create_array_zeros(&[cout], dt);
- let mut output = context.create_array_zeros(&[batch_size * cout * fc_seq], dt).into_allocation();
- let lengths = make_lengths(&context, batch_size, fc_seq as i32);
-
- let label = format!("CausalConv1d first_conv [{cin}->{cout}, k={ksize}, T={fc_seq}]");
- let ms = measure(&label, || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
- {
- let i = input.allocation();
- let w = weight.allocation();
- let b = bias.allocation();
- let o = &mut output;
- let l = lengths.allocation();
- kernel.encode(
- i,
- w,
- b,
- o,
- l,
- cin as i32,
- cout as i32,
- fc_seq as i32,
- ksize as i32,
- 1_i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push(("CausalConv1d first_conv".into(), ms));
- }
-
- // Residual conv1 at each decoder block resolution and dilation
- let mut dec_frames = fc_seq;
- for block_idx in 0..4 {
- dec_frames *= DEC_STRIDES[block_idx];
- let ch = DEC_CHANNELS[block_idx + 1];
- let ksize = 7;
-
- for &dilation in &[1, 3, 9] {
- let label =
- format!("CausalConv1d res dec{block_idx} [{ch}->{ch}, k={ksize}, d={dilation}, T={dec_frames}]");
- let input = context.create_array_zeros(&[batch_size * ch * dec_frames], dt);
- let weight = context.create_array_zeros(&[ch * ch * ksize], dt);
- let bias = context.create_array_zeros(&[ch], dt);
- let mut output = context.create_array_zeros(&[batch_size * ch * dec_frames], dt).into_allocation();
- let lengths = make_lengths(&context, batch_size, dec_frames as i32);
-
- let ms = measure(&label, || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
- {
- let i = input.allocation();
- let w = weight.allocation();
- let b = bias.allocation();
- let o = &mut output;
- let l = lengths.allocation();
- kernel.encode(
- i,
- w,
- b,
- o,
- l,
- ch as i32,
- ch as i32,
- dec_frames as i32,
- ksize as i32,
- dilation,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push((format!("CausalConv1d res dec{block_idx} d={dilation}"), ms));
- }
- }
-
- // final_conv: 96->1, k=7
- {
- let cin = DEC_CHANNELS[4]; // 96
- let cout = 1;
- let ksize = 7;
- let final_frames = SEMANTIC_FRAMES_10S * 2 * 2 * 8 * 8 * 4 * 2; // full resolution
- let input = context.create_array_zeros(&[batch_size * cin * final_frames], dt);
- let weight = context.create_array_zeros(&[cout * cin * ksize], dt);
- let bias = context.create_array_zeros(&[cout], dt);
- let mut output = context.create_array_zeros(&[batch_size * cout * final_frames], dt).into_allocation();
- let lengths = make_lengths(&context, batch_size, final_frames as i32);
-
- let label = format!("CausalConv1d final_conv [{cin}->{cout}, k={ksize}, T={final_frames}]");
- let ms = measure(&label, || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
- {
- let i = input.allocation();
- let w = weight.allocation();
- let b = bias.allocation();
- let o = &mut output;
- let l = lengths.allocation();
- kernel.encode(
- i,
- w,
- b,
- o,
- l,
- cin as i32,
- cout as i32,
- final_frames as i32,
- ksize as i32,
- 1_i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push(("CausalConv1d final_conv".into(), ms));
- }
- }
-
- // -----------------------------------------------------------------------
- // 4. CausalConv1dGroupedResidual — residual conv2 at each decoder stage
- // Same dimensions as conv1 but with residual add, dilation=1
- // -----------------------------------------------------------------------
- {
- let kernel =
- <<Metal as Backend>::Kernels as Kernels>::AudioCausalConv1dGroupedResidualKernel::new(&context, dt)
- .unwrap();
-
- let mut dec_frames = SEMANTIC_FRAMES_10S * UP_STRIDES[0] * UP_STRIDES[1];
- for block_idx in 0..4 {
- dec_frames *= DEC_STRIDES[block_idx];
- let ch = DEC_CHANNELS[block_idx + 1];
- let ksize = 7;
-
- let label = format!("CausalConv1dResidual dec{block_idx} [{ch}->{ch}, k={ksize}, T={dec_frames}]");
- let input = context.create_array_zeros(&[batch_size * ch * dec_frames], dt);
- let residual = context.create_array_zeros(&[batch_size * ch * dec_frames], dt);
- let weight = context.create_array_zeros(&[ch * ch * ksize], dt);
- let bias = context.create_array_zeros(&[ch], dt);
- let mut output = context.create_array_zeros(&[batch_size * ch * dec_frames], dt).into_allocation();
- let lengths = make_lengths(&context, batch_size, dec_frames as i32);
-
- let ms = measure(&label, || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
- {
- let i = input.allocation();
- let r = residual.allocation();
- let w = weight.allocation();
- let b = bias.allocation();
- let o = &mut output;
- let l = lengths.allocation();
- kernel.encode(
- i,
- r,
- w,
- b,
- o,
- l,
- ch as i32,
- ch as i32,
- dec_frames as i32,
- ksize as i32,
- 1_i32,
- 1_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push((format!("CausalConv1dResidual dec{block_idx}"), ms));
- }
- }
-
- // -----------------------------------------------------------------------
- // 5. CausalConv1dGrouped (depthwise) — ConvNeXt depthwise at upsampler resolutions
- // -----------------------------------------------------------------------
- {
- let kernel =
- <<Metal as Backend>::Kernels as Kernels>::AudioCausalConv1dGroupedKernel::new(&context, dt).unwrap();
-
- let mut frames = SEMANTIC_FRAMES_10S;
- for block_idx in 0..2 {
- frames *= UP_STRIDES[block_idx];
- let ch = UP_CHANNELS[block_idx + 1];
- let ksize = 7;
-
- let label = format!("CausalConv1dGrouped dw up{block_idx} [{ch}, g={ch}, k={ksize}, T={frames}]");
- let input = context.create_array_zeros(&[batch_size * ch * frames], dt);
- let weight = context.create_array_zeros(&[ch * ksize], dt);
- let bias = context.create_array_zeros(&[ch], dt);
- let mut output = context.create_array_zeros(&[batch_size * ch * frames], dt).into_allocation();
- let lengths = make_lengths(&context, batch_size, frames as i32);
-
- let ms = measure(&label, || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
- {
- let i = input.allocation();
- let w = weight.allocation();
- let b = bias.allocation();
- let o = &mut output;
- let l = lengths.allocation();
- kernel.encode(
- i,
- w,
- b,
- o,
- l,
- ch as i32,
- ch as i32,
- frames as i32,
- ksize as i32,
- 1_i32,
- ch as i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push((format!("CausalConv1dGrouped dw up{block_idx}"), ms));
- }
- }
-
- // -----------------------------------------------------------------------
- // 6. HalfSnake — at each decoder stage resolution
- // -----------------------------------------------------------------------
- {
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AudioHalfSnakeKernel::new(&context, dt).unwrap();
-
- // Before decoder blocks: snake on decoder_dim channels at upsampled frames
- let fc_frames = SEMANTIC_FRAMES_10S * UP_STRIDES[0] * UP_STRIDES[1];
- let mut dec_frames = fc_frames;
- for block_idx in 0..4 {
- // Snake before trans_conv (at input resolution)
- let ch_in = DEC_CHANNELS[block_idx];
- {
- let label = format!("HalfSnake pre-tconv dec{block_idx} [{ch_in}ch, T={dec_frames}]");
- let input = context.create_array_zeros(&[batch_size * ch_in * dec_frames], dt);
- let alpha = context.create_array_zeros(&[ch_in], dt);
- let mut output = context.create_array_zeros(&[batch_size * ch_in * dec_frames], dt).into_allocation();
-
- let ms = measure(&label, || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
- {
- let i = input.allocation();
- let a = alpha.allocation();
- let o = &mut output;
- kernel.encode(
- i,
- a,
- o,
- ch_in as i32,
- dec_frames as i32,
- ch_in as i32,
- 0.0_f32,
- 1e-9_f32,
- batch_size as i32,
- &mut encoder,
- );
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push((format!("HalfSnake pre dec{block_idx}"), ms));
- }
-
- dec_frames *= DEC_STRIDES[block_idx];
- // Snake in residual units (at output resolution)
- let ch_out = DEC_CHANNELS[block_idx + 1];
- {
- let label = format!("HalfSnake res dec{block_idx} [{ch_out}ch, T={dec_frames}]");
- let input = context.create_array_zeros(&[batch_size * ch_out * dec_frames], dt);
- let alpha = context.create_array_zeros(&[ch_out], dt);
- let mut output = context.create_array_zeros(&[batch_size * ch_out * dec_frames], dt).into_allocation();
-
- let ms = measure(&label, || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
- {
- let i = input.allocation();
- let a = alpha.allocation();
- let o = &mut output;
- kernel.encode(
- i,
- a,
- o,
- ch_out as i32,
- dec_frames as i32,
- ch_out as i32,
- 0.0_f32,
- 1e-9_f32,
- batch_size as i32,
- &mut encoder,
- );
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push((format!("HalfSnake res dec{block_idx}"), ms));
- }
- }
- }
-
- // -----------------------------------------------------------------------
- // 7. NormNcs and Conv1d pointwise — ConvNeXt blocks in upsampler
- // -----------------------------------------------------------------------
- {
- let k_norm = <<Metal as Backend>::Kernels as Kernels>::AudioNormNcsKernel::new(&context, dt).unwrap();
- let k_conv1d = <<Metal as Backend>::Kernels as Kernels>::AudioConv1dKernel::new(&context, dt).unwrap();
- let k_act = <<Metal as Backend>::Kernels as Kernels>::ActivationKernel::new(&context, dt, false).unwrap();
-
- let mut frames = SEMANTIC_FRAMES_10S;
- for block_idx in 0..2 {
- frames *= UP_STRIDES[block_idx];
- let ch = UP_CHANNELS[block_idx + 1];
-
- // Norm
- {
- let label = format!("NormNcs up{block_idx} [{ch}ch, T={frames}]");
- let input = context.create_array_zeros(&[batch_size * ch * frames], dt);
- let scales = context.create_array_zeros(&[ch], dt);
- let bias = context.create_array_zeros(&[ch], dt);
- let mut output = context.create_array_zeros(&[batch_size * ch * frames], dt).into_allocation();
- let lengths = make_lengths(&context, batch_size, frames as i32);
-
- let ms = measure(&label, || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
- {
- let i = input.allocation();
- let s = scales.allocation();
- let b = bias.allocation();
- let o = &mut output;
- let l = lengths.allocation();
- k_norm.encode(
- i,
- s,
- b,
- o,
- l,
- ch as i32,
- frames as i32,
- 1e-6_f32,
- 1_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push((format!("NormNcs up{block_idx}"), ms));
- }
-
- // Pointwise conv1 (ch -> ch)
- {
- let label = format!("Conv1d pw up{block_idx} [{ch}->{ch}, k=1, T={frames}]");
- let input = context.create_array_zeros(&[batch_size * ch * frames], dt);
- let weight = context.create_array_zeros(&[ch * ch], dt);
- let bias = context.create_array_zeros(&[ch], dt);
- let mut output = context.create_array_zeros(&[batch_size * ch * frames], dt).into_allocation();
- let lengths = make_lengths(&context, batch_size, frames as i32);
-
- let ms = measure(&label, || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
- {
- let i = input.allocation();
- let w = weight.allocation();
- let b = bias.allocation();
- let o = &mut output;
- let l = lengths.allocation();
- k_conv1d.encode(
- i,
- w,
- b,
- o,
- l,
- ch as i32,
- ch as i32,
- frames as i32,
- frames as i32,
- 1_i32,
- 1_i32,
- 1_i32,
- 0_i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push((format!("Conv1d pw up{block_idx}"), ms));
- }
-
- // GELU
- {
- let n = ch * frames;
- let label = format!("GELU up{block_idx} [n={n}]");
- let input = context.create_array_zeros(&[n], dt);
- let mut output = context.create_array_zeros(&[n], dt).into_allocation();
-
- let ms = measure(&label, || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
- {
- let i = input.allocation();
- let o = &mut output;
- k_act.encode(Some(i), o, n as u32, ActivationType::GELUApprox, &mut encoder);
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push((format!("GELU up{block_idx}"), ms));
- }
- }
- }
-
- // =======================================================================
- // Full vocoder pipeline simulation — single command buffer
- //
- // Matches submit_decode_padded flow:
- // quantizer -> 2 upsample blocks -> first_conv -> 4 decoder blocks -> final snake+conv+tanh
- // =======================================================================
- println!();
- println!(" {:-<65} {:-<8}", "", "");
- println!(" {:<65} {:>8}", "Full Pipeline Simulation (single command buffer)", "Mean (ms)");
- println!(" {:-<65} {:-<8}", "", "");
-
- // Build all kernels
- let k_quant = <<Metal as Backend>::Kernels as Kernels>::AudioQuantizerDecodeKernel::new(&context, dt).unwrap();
- let k_tconv =
- <<Metal as Backend>::Kernels as Kernels>::AudioCausalConvTranspose1dCausalPadKernel::new(&context, dt).unwrap();
- let k_norm = <<Metal as Backend>::Kernels as Kernels>::AudioNormNcsKernel::new(&context, dt).unwrap();
- let k_conv1d = <<Metal as Backend>::Kernels as Kernels>::AudioConv1dKernel::new(&context, dt).unwrap();
- let k_act = <<Metal as Backend>::Kernels as Kernels>::ActivationKernel::new(&context, dt, false).unwrap();
- let k_add = <<Metal as Backend>::Kernels as Kernels>::AudioAddKernel::new(&context, dt).unwrap();
- let k_snake = <<Metal as Backend>::Kernels as Kernels>::AudioHalfSnakeKernel::new(&context, dt).unwrap();
- let k_conv_grp =
- <<Metal as Backend>::Kernels as Kernels>::AudioCausalConv1dGroupedKernel::new(&context, dt).unwrap();
- let k_conv1d_causal = <<Metal as Backend>::Kernels as Kernels>::AudioCausalConv1dKernel::new(&context, dt).unwrap();
- let k_conv_res =
- <<Metal as Backend>::Kernels as Kernels>::AudioCausalConv1dGroupedResidualKernel::new(&context, dt).unwrap();
-
- let frames = SEMANTIC_FRAMES_10S;
-
- // Quantizer arrays
- let p_q_tok = context.create_array_zeros(&[batch_size * TOTAL_CODEBOOKS * frames], DataType::U32);
- let p_q_len = make_lengths(&context, batch_size, frames as i32);
- let p_q_sem_cb = context.create_array_zeros(&[SEMANTIC_CARDINALITY * CODEBOOK_DIM], dt);
- let p_q_sem_proj = context.create_array_zeros(&[INPUT_DIM * CODEBOOK_DIM], dt);
- let p_q_sem_bias = context.create_array_zeros(&[INPUT_DIM], dt);
- let p_q_res_cbs = context.create_array_zeros(&[RESIDUAL_QUANTIZERS * RESIDUAL_CARDINALITY * CODEBOOK_DIM], dt);
- let p_q_res_proj = context.create_array_zeros(&[RESIDUAL_QUANTIZERS * INPUT_DIM * CODEBOOK_DIM], dt);
- let p_q_res_bias = context.create_array_zeros(&[RESIDUAL_QUANTIZERS * INPUT_DIM], dt);
-
- // Compute frame counts at each stage
- let f_up0 = frames * UP_STRIDES[0]; // 430
- let f_up1 = f_up0 * UP_STRIDES[1]; // 860
- let f_dec0 = f_up1 * DEC_STRIDES[0]; // 6880
- let f_dec1 = f_dec0 * DEC_STRIDES[1]; // 55040
- let f_dec2 = f_dec1 * DEC_STRIDES[2]; // 220160
- let f_dec3 = f_dec2 * DEC_STRIDES[3]; // 440320
-
- // Pipeline scratch: large enough for the biggest intermediate
- // Biggest is decoder_dim * f_up1 or ch * f_dec stages
- let max_elems: usize = batch_size * DECODER_DIM * f_dec3.max(f_up1);
- let mut scratch_a = context.create_array_zeros(&[max_elems], dt).into_allocation();
- let mut scratch_b = context.create_array_zeros(&[max_elems], dt).into_allocation();
- let scratch_r = context.create_array_zeros(&[max_elems], dt).into_allocation();
-
- // Upsample block 0: 1024->512, stride=2
- let u0_w = context.create_array_zeros(&[UP_CHANNELS[0] * UP_CHANNELS[1] * (UP_STRIDES[0] * 2)], dt);
- let u0_b = context.create_array_zeros(&[UP_CHANNELS[1]], dt);
- // ConvNeXt 0 (ch=512)
- let c0_ch = UP_CHANNELS[1];
- let c0_dw_w = context.create_array_zeros(&[c0_ch * 7], dt);
- let c0_dw_b = context.create_array_zeros(&[c0_ch], dt);
- let c0_ns = context.create_array_zeros(&[c0_ch], dt);
- let c0_nb = context.create_array_zeros(&[c0_ch], dt);
- let c0_p1_w = context.create_array_zeros(&[c0_ch * c0_ch], dt);
- let c0_p1_b = context.create_array_zeros(&[c0_ch], dt);
- let c0_p2_w = context.create_array_zeros(&[c0_ch * c0_ch], dt);
- let c0_p2_b = context.create_array_zeros(&[c0_ch], dt);
-
- // Upsample block 1: 512->256, stride=2
- let u1_w = context.create_array_zeros(&[UP_CHANNELS[1] * UP_CHANNELS[2] * (UP_STRIDES[1] * 2)], dt);
- let u1_b = context.create_array_zeros(&[UP_CHANNELS[2]], dt);
- // ConvNeXt 1 (ch=256)
- let c1_ch = UP_CHANNELS[2];
- let c1_dw_w = context.create_array_zeros(&[c1_ch * 7], dt);
- let c1_dw_b = context.create_array_zeros(&[c1_ch], dt);
- let c1_ns = context.create_array_zeros(&[c1_ch], dt);
- let c1_nb = context.create_array_zeros(&[c1_ch], dt);
- let c1_p1_w = context.create_array_zeros(&[c1_ch * c1_ch], dt);
- let c1_p1_b = context.create_array_zeros(&[c1_ch], dt);
- let c1_p2_w = context.create_array_zeros(&[c1_ch * c1_ch], dt);
- let c1_p2_b = context.create_array_zeros(&[c1_ch], dt);
-
- // first_conv: 256->1536, k=7
- let fc_w = context.create_array_zeros(&[DECODER_DIM * UP_CHANNELS[2] * 7], dt);
- let fc_b = context.create_array_zeros(&[DECODER_DIM], dt);
-
- // Decoder block weights for all 4 blocks
- struct DecBlockWeights {
- snake_a: Array<Metal>,
- tconv_w: Array<Metal>,
- tconv_b: Array<Metal>,
- // 3 residual units, each with snake1, conv1, snake2, conv2
- ru_s1: [Array<Metal>; 3],
- ru_c1_w: [Array<Metal>; 3],
- ru_c1_b: [Array<Metal>; 3],
- ru_s2: [Array<Metal>; 3],
- ru_c2_w: [Array<Metal>; 3],
- ru_c2_b: [Array<Metal>; 3],
- }
-
- let dec_blocks: Vec<DecBlockWeights> = (0..4)
- .map(|i| {
- let cin = DEC_CHANNELS[i];
- let cout = DEC_CHANNELS[i + 1];
- let stride = DEC_STRIDES[i];
- let ksize = stride * 2;
- DecBlockWeights {
- snake_a: context.create_array_zeros(&[cin], dt),
- tconv_w: context.create_array_zeros(&[cin * cout * ksize], dt),
- tconv_b: context.create_array_zeros(&[cout], dt),
- ru_s1: std::array::from_fn(|_| context.create_array_zeros(&[cout], dt)),
- ru_c1_w: std::array::from_fn(|_| context.create_array_zeros(&[cout * cout * 7], dt)),
- ru_c1_b: std::array::from_fn(|_| context.create_array_zeros(&[cout], dt)),
- ru_s2: std::array::from_fn(|_| context.create_array_zeros(&[cout], dt)),
- ru_c2_w: std::array::from_fn(|_| context.create_array_zeros(&[cout * cout * 7], dt)),
- ru_c2_b: std::array::from_fn(|_| context.create_array_zeros(&[cout], dt)),
- }
- })
- .collect();
-
- // final snake + conv + tanh
- let final_snake_a = context.create_array_zeros(&[DEC_CHANNELS[4]], dt);
- let final_conv_w = context.create_array_zeros(&[DEC_CHANNELS[4] * 7], dt);
- let final_conv_b = context.create_array_zeros(&[1], dt);
-
- // Length arrays
- let len_up0 = make_lengths(&context, batch_size, f_up0 as i32);
- let len_up1 = make_lengths(&context, batch_size, f_up1 as i32);
- let len_dec0 = make_lengths(&context, batch_size, f_dec0 as i32);
- let len_dec1 = make_lengths(&context, batch_size, f_dec1 as i32);
- let len_dec2 = make_lengths(&context, batch_size, f_dec2 as i32);
- let len_dec3 = make_lengths(&context, batch_size, f_dec3 as i32);
- let dec_lens = [&len_dec0, &len_dec1, &len_dec2, &len_dec3];
- let dec_frame_sizes = [f_dec0, f_dec1, f_dec2, f_dec3];
- let dilations = [1_i32, 3, 9];
-
- let ms = measure("Full pipeline (quant -> 2 up -> first_conv -> 4 dec -> final)", || {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).unwrap();
-
- // --- Quantizer: output [B, T, input_dim] (NSC) ---
- {
- let tok = p_q_tok.allocation();
- let len = p_q_len.allocation();
- let scb = p_q_sem_cb.allocation();
- let sp = p_q_sem_proj.allocation();
- let sbi = p_q_sem_bias.allocation();
- let rcb = p_q_res_cbs.allocation();
- let rp = p_q_res_proj.allocation();
- let rb = p_q_res_bias.allocation();
- k_quant.encode(
- tok,
- len,
- scb,
- sp,
- sbi,
- rcb,
- rp,
- rb,
- &mut scratch_a,
- batch_size as i32,
- TOTAL_CODEBOOKS as i32,
- frames as i32,
- INPUT_DIM as i32,
- CODEBOOK_DIM as i32,
- RESIDUAL_QUANTIZERS as i32,
- SEMANTIC_CARDINALITY as i32,
- RESIDUAL_CARDINALITY as i32,
- &mut encoder,
- );
- }
-
- // --- Upsample block 0: 1024->512, stride=2, NSC input ---
- {
- let w = u0_w.allocation();
- let b = u0_b.allocation();
- let l = len_up0.allocation();
- k_tconv.encode(
- &scratch_a,
- w,
- b,
- &mut scratch_b,
- l,
- UP_CHANNELS[0] as i32,
- UP_CHANNELS[1] as i32,
- frames as i32,
- f_up0 as i32,
- (UP_STRIDES[0] * 2) as i32,
- UP_STRIDES[0] as i32,
- 1_i32,
- 1_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- // ConvNeXt 0
- {
- let w = c0_dw_w.allocation();
- let b = c0_dw_b.allocation();
- let l = len_up0.allocation();
- k_conv_grp.encode(
- &scratch_b,
- w,
- b,
- &mut scratch_a,
- l,
- c0_ch as i32,
- c0_ch as i32,
- f_up0 as i32,
- 7_i32,
- 1_i32,
- c0_ch as i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- {
- let s = c0_ns.allocation();
- let b = c0_nb.allocation();
- let l = len_up0.allocation();
- k_norm.encode(
- &scratch_a,
- s,
- b,
- &mut scratch_b,
- l,
- c0_ch as i32,
- f_up0 as i32,
- 1e-6_f32,
- 1_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- {
- let w = c0_p1_w.allocation();
- let b = c0_p1_b.allocation();
- let l = len_up0.allocation();
- k_conv1d.encode(
- &scratch_b,
- w,
- b,
- &mut scratch_a,
- l,
- c0_ch as i32,
- c0_ch as i32,
- f_up0 as i32,
- f_up0 as i32,
- 1_i32,
- 1_i32,
- 1_i32,
- 0_i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- {
- k_act.encode(
- Some(&scratch_a),
- &mut scratch_b,
- (c0_ch * f_up0) as u32,
- ActivationType::GELUApprox,
- &mut encoder,
- );
- }
- {
- let w = c0_p2_w.allocation();
- let b = c0_p2_b.allocation();
- let l = len_up0.allocation();
- k_conv1d.encode(
- &scratch_b,
- w,
- b,
- &mut scratch_a,
- l,
- c0_ch as i32,
- c0_ch as i32,
- f_up0 as i32,
- f_up0 as i32,
- 1_i32,
- 1_i32,
- 1_i32,
- 0_i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- {
- k_add.encode(&scratch_a, &scratch_a, &mut scratch_b, (c0_ch * f_up0) as i32, &mut encoder);
- }
-
- // --- Upsample block 1: 512->256, stride=2, NCS input ---
- {
- let w = u1_w.allocation();
- let b = u1_b.allocation();
- let l = len_up1.allocation();
- k_tconv.encode(
- &scratch_b,
- w,
- b,
- &mut scratch_a,
- l,
- UP_CHANNELS[1] as i32,
- UP_CHANNELS[2] as i32,
- f_up0 as i32,
- f_up1 as i32,
- (UP_STRIDES[1] * 2) as i32,
- UP_STRIDES[1] as i32,
- 1_i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- // ConvNeXt 1
- {
- let w = c1_dw_w.allocation();
- let b = c1_dw_b.allocation();
- let l = len_up1.allocation();
- k_conv_grp.encode(
- &scratch_a,
- w,
- b,
- &mut scratch_b,
- l,
- c1_ch as i32,
- c1_ch as i32,
- f_up1 as i32,
- 7_i32,
- 1_i32,
- c1_ch as i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- {
- let s = c1_ns.allocation();
- let b = c1_nb.allocation();
- let l = len_up1.allocation();
- k_norm.encode(
- &scratch_b,
- s,
- b,
- &mut scratch_a,
- l,
- c1_ch as i32,
- f_up1 as i32,
- 1e-6_f32,
- 1_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- {
- let w = c1_p1_w.allocation();
- let b = c1_p1_b.allocation();
- let l = len_up1.allocation();
- k_conv1d.encode(
- &scratch_a,
- w,
- b,
- &mut scratch_b,
- l,
- c1_ch as i32,
- c1_ch as i32,
- f_up1 as i32,
- f_up1 as i32,
- 1_i32,
- 1_i32,
- 1_i32,
- 0_i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- {
- k_act.encode(
- Some(&scratch_b),
- &mut scratch_a,
- (c1_ch * f_up1) as u32,
- ActivationType::GELUApprox,
- &mut encoder,
- );
- }
- {
- let w = c1_p2_w.allocation();
- let b = c1_p2_b.allocation();
- let l = len_up1.allocation();
- k_conv1d.encode(
- &scratch_a,
- w,
- b,
- &mut scratch_b,
- l,
- c1_ch as i32,
- c1_ch as i32,
- f_up1 as i32,
- f_up1 as i32,
- 1_i32,
- 1_i32,
- 1_i32,
- 0_i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- {
- k_add.encode(&scratch_b, &scratch_b, &mut scratch_a, (c1_ch * f_up1) as i32, &mut encoder);
- }
-
- // --- first_conv: 256->1536, k=7 ---
- {
- let w = fc_w.allocation();
- let b = fc_b.allocation();
- let l = len_up1.allocation();
- k_conv1d_causal.encode(
- &scratch_a,
- w,
- b,
- &mut scratch_b,
- l,
- UP_CHANNELS[2] as i32,
- DECODER_DIM as i32,
- f_up1 as i32,
- 7_i32,
- 1_i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
-
- // --- 4 Decoder blocks ---
- // State in sb after first_conv
- let mut cur_in_sa = false; // data is in sb
- let mut cur_frames = f_up1;
-
- for block_idx in 0..4 {
- let blk = &dec_blocks[block_idx];
- let cin = DEC_CHANNELS[block_idx];
- let cout = DEC_CHANNELS[block_idx + 1];
- let stride = DEC_STRIDES[block_idx];
- let ksize = stride * 2;
- let next_frames = dec_frame_sizes[block_idx];
- let dec_len = dec_lens[block_idx];
-
- // snake (in-place swap)
- {
- let (i, o) = if cur_in_sa {
- (&scratch_a, &mut scratch_b)
- } else {
- (&scratch_b, &mut scratch_a)
- };
- let a = blk.snake_a.allocation();
- k_snake.encode(
- i,
- a,
- o,
- cin as i32,
- cur_frames as i32,
- cin as i32,
- 0.0_f32,
- 1e-9_f32,
- batch_size as i32,
- &mut encoder,
- );
- }
- cur_in_sa = !cur_in_sa;
-
- // trans_conv
- {
- let (i, o) = if cur_in_sa {
- (&scratch_a, &mut scratch_b)
- } else {
- (&scratch_b, &mut scratch_a)
- };
- let w = blk.tconv_w.allocation();
- let b = blk.tconv_b.allocation();
- let l = dec_len.allocation();
- k_tconv.encode(
- i,
- w,
- b,
- o,
- l,
- cin as i32,
- cout as i32,
- cur_frames as i32,
- next_frames as i32,
- ksize as i32,
- stride as i32,
- 1_i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- cur_in_sa = !cur_in_sa;
- cur_frames = next_frames;
-
- // 3 residual units
- for ru_idx in 0..3 {
- // snake1
- {
- let (i, o) = if cur_in_sa {
- (&scratch_a, &mut scratch_b)
- } else {
- (&scratch_b, &mut scratch_a)
- };
- let a = blk.ru_s1[ru_idx].allocation();
- k_snake.encode(
- i,
- a,
- o,
- cout as i32,
- cur_frames as i32,
- cout as i32,
- 0.0_f32,
- 1e-9_f32,
- batch_size as i32,
- &mut encoder,
- );
- }
- cur_in_sa = !cur_in_sa;
-
- // conv1 (dilation varies: 1, 3, 9)
- {
- let (i, o) = if cur_in_sa {
- (&scratch_a, &mut scratch_b)
- } else {
- (&scratch_b, &mut scratch_a)
- };
- let w = blk.ru_c1_w[ru_idx].allocation();
- let b = blk.ru_c1_b[ru_idx].allocation();
- let l = dec_len.allocation();
- k_conv1d_causal.encode(
- i,
- w,
- b,
- o,
- l,
- cout as i32,
- cout as i32,
- cur_frames as i32,
- 7_i32,
- dilations[ru_idx],
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- cur_in_sa = !cur_in_sa;
-
- // snake2
- {
- let (i, o) = if cur_in_sa {
- (&scratch_a, &mut scratch_b)
- } else {
- (&scratch_b, &mut scratch_a)
- };
- let a = blk.ru_s2[ru_idx].allocation();
- k_snake.encode(
- i,
- a,
- o,
- cout as i32,
- cur_frames as i32,
- cout as i32,
- 0.0_f32,
- 1e-9_f32,
- batch_size as i32,
- &mut encoder,
- );
- }
- cur_in_sa = !cur_in_sa;
-
- // conv2 + residual add
- {
- let (i, o) = if cur_in_sa {
- (&scratch_a, &mut scratch_b)
- } else {
- (&scratch_b, &mut scratch_a)
- };
- let r = &scratch_r;
- let w = blk.ru_c2_w[ru_idx].allocation();
- let b = blk.ru_c2_b[ru_idx].allocation();
- let l = dec_len.allocation();
- k_conv_res.encode(
- i,
- r,
- w,
- b,
- o,
- l,
- cout as i32,
- cout as i32,
- cur_frames as i32,
- 7_i32,
- 1_i32,
- 1_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- cur_in_sa = !cur_in_sa;
- }
- }
-
- // --- final snake + conv + tanh ---
- {
- let (i, o) = if cur_in_sa {
- (&scratch_a, &mut scratch_b)
- } else {
- (&scratch_b, &mut scratch_a)
- };
- let a = final_snake_a.allocation();
- k_snake.encode(
- i,
- a,
- o,
- DEC_CHANNELS[4] as i32,
- f_dec3 as i32,
- DEC_CHANNELS[4] as i32,
- 0.0_f32,
- 1e-9_f32,
- batch_size as i32,
- &mut encoder,
- );
- }
- cur_in_sa = !cur_in_sa;
- {
- let (i, o) = if cur_in_sa {
- (&scratch_a, &mut scratch_b)
- } else {
- (&scratch_b, &mut scratch_a)
- };
- let w = final_conv_w.allocation();
- let b = final_conv_b.allocation();
- let l = len_dec3.allocation();
- k_conv1d_causal.encode(
- i,
- w,
- b,
- o,
- l,
- DEC_CHANNELS[4] as i32,
- 1_i32,
- f_dec3 as i32,
- 7_i32,
- 1_i32,
- 0_i32,
- batch_size as i32,
- &mut encoder,
- );
- }
- cur_in_sa = !cur_in_sa;
- // tanh
- {
- let (i, o) = if cur_in_sa {
- (&scratch_a, &mut scratch_b)
- } else {
- (&scratch_b, &mut scratch_a)
- };
- k_act.encode(Some(i), o, f_dec3 as u32, ActivationType::TANH, &mut encoder);
- }
-
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- });
- results.push(("Full pipeline".into(), ms));
-
- // =======================================================================
- // Summary
- // =======================================================================
- println!();
- println!(" === SUMMARY ===");
- println!(" {:<65} {:>8}", "Kernel", "Mean (ms)");
- println!(" {:-<65} {:-<8}", "", "");
- let mut total_individual = 0.0;
- for (name, ms) in &results {
- println!(" {name:<65} {ms:>8.3}");
- if name != "Full pipeline" {
- total_individual += ms;
- }
- }
- println!(" {:-<65} {:-<8}", "", "");
- println!(" {:<65} {:>8.3}", "Sum of individual kernels", total_individual);
- if let Some((_, pipeline_ms)) = results.iter().find(|(n, _)| n == "Full pipeline") {
- println!(" {:<65} {:>8.3}", "Full pipeline (single CB)", pipeline_ms);
- }
- println!();
-}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/audio/audio_test.rs b/crates/backend-uzu/unit/backends/common/kernel/audio/audio_test.rs
deleted file mode 100644
index 23bc5dd06..000000000
--- a/crates/backend-uzu/unit/backends/common/kernel/audio/audio_test.rs
+++ /dev/null
@@ -1,830 +0,0 @@
-#![cfg(metal_backend)]
-
-use proc_macros::uzu_test;
-
-use crate::{
- array::ArrayContextExt,
- backends::{
- common::{
- Backend, Context, Encoder, Kernels,
- gpu_types::ActivationType,
- kernel::{
- ActivationKernel, AudioAddKernel, AudioCausalConv1dKernel, AudioCausalConvTranspose1dCausalPadKernel,
- AudioCausalConvTranspose1dKernel, AudioConv1dKernel, AudioFsqDecodeKernel, AudioFsqEncodeKernel,
- AudioHalfSnakeKernel, AudioNormNcsKernel,
- },
- },
- metal::Metal,
- },
- data_type::DataType,
- tests::{
- audio::{
- fsq_reference::{fsq_decode_reference, fsq_encode_reference},
- ops_reference::{
- CausalConv1dSpec, CausalConvTranspose1dSpec, Conv1dSpec, HalfSnakeSpec, PadMode,
- causal_conv_transpose1d_causal_pad_reference, causal_conv_transpose1d_reference,
- causal_conv1d_reference, conv1d_reference, half_snake_reference,
- },
- },
- helpers::allocation_to_vec,
- },
-};
-
-macro_rules! borrow_array_buffer {
- ($name:ident = $array:expr) => {
- let $name = $array.allocation();
- };
-}
-
-macro_rules! borrow_array_buffer_mut {
- ($name:ident = $array:expr) => {
- let $name = &mut $array;
- };
-}
-
-fn create_test_context() -> std::rc::Rc<<Metal as Backend>::Context> {
- <Metal as Backend>::Context::new().expect("MetalContext")
-}
-
-fn run_command_buffer(
- context: &std::rc::Rc<<Metal as Backend>::Context>,
- encode: impl FnOnce(&mut Encoder<'_, Metal>),
-) {
- let mut encoder = Encoder::<Metal>::new(context.as_ref()).expect("command buffer");
- encode(&mut encoder);
- encoder.end_encoding().submit().wait_until_completed().expect("command buffer completed");
-}
-
-#[uzu_test]
-fn audio_conv1d_replicate_matches_reference_f32() {
- let context = create_test_context();
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AudioConv1dKernel::new(&context, DataType::F32)
- .expect("audio runtime");
-
- let batch_size = 2usize;
- let cin = 3usize;
- let cout = 4usize;
- let seq_len_in = 9usize;
-
- let stride = 3usize;
- let kernel_size = 2 * stride;
- let dilation = 1usize;
- let padding = 2usize;
-
- let seq_len_out = ((seq_len_in + 2 * padding - dilation * (kernel_size - 1) - 1) / stride) + 1;
- let lengths_out: [i32; 2] = [2, seq_len_out as i32];
-
- let input_len = batch_size * cin * seq_len_in;
- let weight_len = cout * cin * kernel_size;
- let bias_len = cout;
- let output_len = batch_size * cout * seq_len_out;
-
- let input_values: Vec<f32> = (0..input_len).map(|i| (i as f32 * 0.01).sin() * 0.5).collect();
- let weight_values: Vec<f32> = (0..weight_len).map(|i| ((i as f32) * 0.07 - 1.3).cos() * 0.2).collect();
- let bias_values: Vec<f32> = (0..bias_len).map(|i| i as f32 * 0.01 - 0.02).collect();
-
- let mut input = context.create_array_zeros(&[batch_size, cin, seq_len_in], DataType::F32);
- input.as_slice_mut::<f32>().copy_from_slice(&input_values);
-
- let mut weight = context.create_array_zeros(&[cout, cin, kernel_size], DataType::F32);
- weight.as_slice_mut::<f32>().copy_from_slice(&weight_values);
-
- let mut bias = context.create_array_zeros(&[cout], DataType::F32);
- bias.as_slice_mut::<f32>().copy_from_slice(&bias_values);
-
- let mut lengths = context.create_array_zeros(&[batch_size], DataType::I32);
- lengths.as_slice_mut::<i32>().copy_from_slice(&lengths_out);
-
- let mut output = context.create_array_zeros(&[batch_size, cout, seq_len_out], DataType::F32).into_allocation();
- let expected = conv1d_reference(Conv1dSpec {
- input: &input_values,
- weight: &weight_values,
- bias: &bias_values,
- lengths: &lengths_out,
- batch_size,
- cin,
- cout,
- seq_len_in,
- seq_len_out,
- kernel_size,
- stride,
- dilation,
- padding,
- pad_mode: PadMode::Replicate,
- });
-
- run_command_buffer(&context, |command_buffer| {
- borrow_array_buffer!(input_buffer = input);
- borrow_array_buffer!(weight_buffer = weight);
- borrow_array_buffer!(bias_buffer = bias);
- borrow_array_buffer_mut!(output_buffer = output);
- borrow_array_buffer!(lengths_buffer = lengths);
- kernel.encode(
- input_buffer,
- weight_buffer,
- bias_buffer,
- output_buffer,
- lengths_buffer,
- cin as i32,
- cout as i32,
- seq_len_in as i32,
- seq_len_out as i32,
- kernel_size as i32,
- stride as i32,
- dilation as i32,
- padding as i32,
- 1_i32,
- batch_size as i32,
- command_buffer,
- );
- });
-
- let got = allocation_to_vec::<Metal, f32>(&output);
- for index in 0..output_len {
- let delta = (expected[index] - got[index]).abs();
- assert!(
- delta <= 1e-4,
- "Mismatch at index={index}: expected {}, got {}, delta={delta}",
- expected[index],
- got[index]
- );
- }
-}
-
-#[uzu_test]
-fn audio_causal_conv1d_matches_reference_f32() {
- let context = create_test_context();
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AudioCausalConv1dKernel::new(&context, DataType::F32)
- .expect("audio runtime");
-
- let batch_size = 2usize;
- let cin = 3usize;
- let cout = 4usize;
- let seq_len = 8usize;
- let kernel_size = 5usize;
- let dilation = 2usize;
-
- let lengths: [i32; 2] = [5, 8];
-
- let input_len = batch_size * cin * seq_len;
- let weight_len = cout * cin * kernel_size;
- let bias_len = cout;
- let output_len = batch_size * cout * seq_len;
-
- let input_values: Vec<f32> = (0..input_len).map(|i| (i as f32 * 0.01).sin()).collect();
- let weight_values: Vec<f32> = (0..weight_len).map(|i| ((i as f32) * 0.02 - 0.5).cos() * 0.1).collect();
- let bias_values: Vec<f32> = (0..bias_len).map(|i| i as f32 * 0.001 - 0.002).collect();
-
- let mut input = context.create_array_zeros(&[batch_size, cin, seq_len], DataType::F32);
- input.as_slice_mut::<f32>().copy_from_slice(&input_values);
-
- let mut weight = context.create_array_zeros(&[cout, cin, kernel_size], DataType::F32);
- weight.as_slice_mut::<f32>().copy_from_slice(&weight_values);
-
- let mut bias = context.create_array_zeros(&[cout], DataType::F32);
- bias.as_slice_mut::<f32>().copy_from_slice(&bias_values);
-
- let mut lengths_array = context.create_array_zeros(&[batch_size], DataType::I32);
- lengths_array.as_slice_mut::<i32>().copy_from_slice(&lengths);
-
- let mut output = context.create_array_zeros(&[batch_size, cout, seq_len], DataType::F32).into_allocation();
- let expected = causal_conv1d_reference(CausalConv1dSpec {
- input: &input_values,
- weight: &weight_values,
- bias: &bias_values,
- lengths: &lengths,
- batch_size,
- cin,
- cout,
- seq_len,
- kernel_size,
- dilation,
- });
-
- run_command_buffer(&context, |command_buffer| {
- borrow_array_buffer!(input_buffer = input);
- borrow_array_buffer!(weight_buffer = weight);
- borrow_array_buffer!(bias_buffer = bias);
- borrow_array_buffer_mut!(output_buffer = output);
- borrow_array_buffer!(lengths_buffer = lengths_array);
- kernel.encode(
- input_buffer,
- weight_buffer,
- bias_buffer,
- output_buffer,
- lengths_buffer,
- cin as i32,
- cout as i32,
- seq_len as i32,
- kernel_size as i32,
- dilation as i32,
- 0,
- batch_size as i32,
- command_buffer,
- );
- });
-
- let got = allocation_to_vec::<Metal, f32>(&output);
- for index in 0..output_len {
- let delta = (expected[index] - got[index]).abs();
- assert!(
- delta <= 1e-4,
- "Mismatch at index={index}: expected {}, got {}, delta={delta}",
- expected[index],
- got[index]
- );
- }
-}
-
-#[uzu_test]
-fn audio_causal_conv_transpose1d_matches_reference_f32() {
- let context = create_test_context();
- let kernel =
- <<Metal as Backend>::Kernels as Kernels>::AudioCausalConvTranspose1dKernel::new(&context, DataType::F32)
- .expect("audio runtime");
-
- let batch_size = 2usize;
- let cin = 4usize;
- let groups = 2usize;
- let cout = 2usize;
- let stride = 3usize;
- let kernel_size = 2 * stride;
-
- let seq_len_in = 5usize;
- let seq_len_out = seq_len_in * stride;
-
- let lengths_out: [i32; 2] = [9, 15];
-
- let input_len = batch_size * cin * seq_len_in;
- let weight_len = cout * (cin / groups) * kernel_size;
- let output_len = batch_size * cout * seq_len_out;
-
- let input_values: Vec<f32> = (0..input_len).map(|i| (i as f32 * 0.013).sin() * 0.5).collect();
- let weight_values: Vec<f32> = (0..weight_len).map(|i| ((i as f32) * 0.07).cos() * 0.2).collect();
- let bias_values: Vec<f32> = vec![0.01, -0.02];
-
- let mut input = context.create_array_zeros(&[batch_size, cin, seq_len_in], DataType::F32);
- input.as_slice_mut::<f32>().copy_from_slice(&input_values);
-
- let mut weight = context.create_array_zeros(&[cout, cin / groups, kernel_size], DataType::F32);
- weight.as_slice_mut::<f32>().copy_from_slice(&weight_values);
-
- let mut bias = context.create_array_zeros(&[cout], DataType::F32);
- bias.as_slice_mut::<f32>().copy_from_slice(&bias_values);
-
- let mut lengths = context.create_array_zeros(&[batch_size], DataType::I32);
- lengths.as_slice_mut::<i32>().copy_from_slice(&lengths_out);
-
- let mut output = context.create_array_zeros(&[batch_size, cout, seq_len_out], DataType::F32).into_allocation();
- let expected = causal_conv_transpose1d_reference(CausalConvTranspose1dSpec {
- input: &input_values,
- weight: &weight_values,
- bias: &bias_values,
- lengths: &lengths_out,
- batch_size,
- cin,
- cout,
- seq_len_in,
- seq_len_out,
- stride,
- groups,
- });
-
- run_command_buffer(&context, |command_buffer| {
- borrow_array_buffer!(input_buffer = input);
- borrow_array_buffer!(weight_buffer = weight);
- borrow_array_buffer!(bias_buffer = bias);
- borrow_array_buffer_mut!(output_buffer = output);
- borrow_array_buffer!(lengths_buffer = lengths);
- kernel.encode(
- input_buffer,
- weight_buffer,
- bias_buffer,
- output_buffer,
- lengths_buffer,
- cin as i32,
- cout as i32,
- seq_len_in as i32,
- seq_len_out as i32,
- stride as i32,
- groups as i32,
- batch_size as i32,
- command_buffer,
- );
- });
-
- let got = allocation_to_vec::<Metal, f32>(&output);
- for index in 0..output_len {
- let delta = (expected[index] - got[index]).abs();
- assert!(
- delta <= 1e-4,
- "Mismatch at index={index}: expected {}, got {}, delta={delta}",
- expected[index],
- got[index]
- );
- }
-}
-
-#[uzu_test]
-fn audio_causal_conv_transpose1d_causal_pad_matches_reference_f32() {
- let context = create_test_context();
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AudioCausalConvTranspose1dCausalPadKernel::new(
- &context,
- DataType::F32,
- )
- .expect("audio runtime");
-
- let batch_size = 1usize;
- let cin = 2usize;
- let groups = 1usize;
- let cout = 2usize;
- let stride = 2usize;
- let kernel_size = 3usize;
-
- let seq_len_in = 5usize;
- let seq_len_out = 10usize;
- let lengths_out: [i32; 1] = [10];
-
- let input_len = batch_size * cin * seq_len_in;
- let weight_len = cout * (cin / groups) * kernel_size;
- let output_len = batch_size * cout * seq_len_out;
-
- let input_values_ncs: Vec<f32> = (0..input_len).map(|i| (i as f32 * 0.017).sin() * 0.5).collect();
- let weight_values: Vec<f32> = (0..weight_len).map(|i| ((i as f32) * 0.09).cos() * 0.2).collect();
- let bias_values: Vec<f32> = vec![0.01, -0.02];
- let expected = causal_conv_transpose1d_causal_pad_reference(CausalConvTranspose1dSpec {
- input: &input_values_ncs,
- weight: &weight_values,
- bias: &bias_values,
- lengths: &lengths_out,
- batch_size,
- cin,
- cout,
- seq_len_in,
- seq_len_out,
- stride,
- groups,
- });
-
- let mut input_values_nsc = vec![0.0_f32; input_len];
- for b in 0..batch_size {
- for c in 0..cin {
- for t in 0..seq_len_in {
- let src_index = (b * cin + c) * seq_len_in + t;
- let dst_index = (b * seq_len_in + t) * cin + c;
- input_values_nsc[dst_index] = input_values_ncs[src_index];
- }
- }
- }
-
- for (layout_name, layout_code, input_shape, input_values) in [
- ("NCS", 0_i32, [batch_size, cin, seq_len_in], input_values_ncs.as_slice()),
- ("NSC", 1_i32, [batch_size, seq_len_in, cin], input_values_nsc.as_slice()),
- ] {
- let mut input = context.create_array_zeros(&input_shape, DataType::F32);
- input.as_slice_mut::<f32>().copy_from_slice(input_values);
-
- let mut weight = context.create_array_zeros(&[cout, cin / groups, kernel_size], DataType::F32);
- weight.as_slice_mut::<f32>().copy_from_slice(&weight_values);
-
- let mut bias = context.create_array_zeros(&[cout], DataType::F32);
- bias.as_slice_mut::<f32>().copy_from_slice(&bias_values);
-
- let mut lengths = context.create_array_zeros(&[batch_size], DataType::I32);
- lengths.as_slice_mut::<i32>().copy_from_slice(&lengths_out);
-
- let mut output = context.create_array_zeros(&[batch_size, cout, seq_len_out], DataType::F32).into_allocation();
-
- run_command_buffer(&context, |command_buffer| {
- borrow_array_buffer!(input_buffer = input);
- borrow_array_buffer!(weight_buffer = weight);
- borrow_array_buffer!(bias_buffer = bias);
- borrow_array_buffer_mut!(output_buffer = output);
- borrow_array_buffer!(lengths_buffer = lengths);
- kernel.encode(
- input_buffer,
- weight_buffer,
- bias_buffer,
- output_buffer,
- lengths_buffer,
- cin as i32,
- cout as i32,
- seq_len_in as i32,
- seq_len_out as i32,
- kernel_size as i32,
- stride as i32,
- groups as i32,
- layout_code,
- batch_size as i32,
- command_buffer,
- );
- });
-
- let got = allocation_to_vec::<Metal, f32>(&output);
- for index in 0..output_len {
- let delta = (expected[index] - got[index]).abs();
- assert!(
- delta <= 1e-4,
- "layout={layout_name}, index={index}: expected {}, got {}, delta={delta}",
- expected[index],
- got[index]
- );
- }
- }
-}
-
-#[uzu_test]
-fn audio_leaky_relu_matches_reference_f32() {
- let context = create_test_context();
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AudioHalfSnakeKernel::new(&context, DataType::F32)
- .expect("audio runtime");
-
- let n = 1024usize;
- let slope = 0.0f32;
- let eps = 1e-6f32;
- let input_values: Vec<f32> = (0..n).map(|i| i as f32 * 0.01 - 5.12).collect();
-
- let mut input = context.create_array_zeros(&[1, 1, n], DataType::F32);
- input.as_slice_mut::<f32>().copy_from_slice(&input_values);
-
- let alpha = context.create_array_zeros(&[1], DataType::F32);
- let mut output = context.create_array_zeros(&[1, 1, n], DataType::F32).into_allocation();
-
- run_command_buffer(&context, |command_buffer| {
- borrow_array_buffer!(input_buffer = input);
- borrow_array_buffer!(alpha_buffer = alpha);
- borrow_array_buffer_mut!(output_buffer = output);
- kernel.encode(input_buffer, alpha_buffer, output_buffer, 1, n as i32, 0, slope, eps, 1, command_buffer);
- });
-
- let got = allocation_to_vec::<Metal, f32>(&output);
- for index in 0..n {
- let expected = if input_values[index] >= 0.0 {
- input_values[index]
- } else {
- slope * input_values[index]
- };
- let delta = (expected - got[index]).abs();
- assert!(delta <= 1e-6, "Mismatch at index={index}: expected {expected}, got {}, delta={delta}", got[index]);
- }
-}
-
-#[uzu_test]
-fn audio_tanh_matches_reference_f32() {
- let context = create_test_context();
- let kernel = <<Metal as Backend>::Kernels as Kernels>::ActivationKernel::new(&context, DataType::F32, false)
- .expect("audio runtime");
-
- let n = 1024usize;
- let input_values: Vec<f32> = (0..n).map(|i| i as f32 * 0.01 - 5.12).collect();
-
- let mut input = context.create_array_zeros(&[n], DataType::F32);
- input.as_slice_mut::<f32>().copy_from_slice(&input_values);
-
- let mut output = context.create_array_zeros(&[n], DataType::F32).into_allocation();
-
- run_command_buffer(&context, |command_buffer| {
- borrow_array_buffer!(input_buffer = input);
- borrow_array_buffer_mut!(output_buffer = output);
- kernel.encode(Some(input_buffer), output_buffer, n as u32, ActivationType::TANH, command_buffer);
- });
-
- let got = allocation_to_vec::<Metal, f32>(&output);
- for index in 0..n {
- let expected = input_values[index].tanh();
- let delta = (expected - got[index]).abs();
- assert!(delta <= 1e-6, "Mismatch at index={index}: expected {expected}, got {}, delta={delta}", got[index]);
- }
-}
-
-#[uzu_test]
-fn audio_add_matches_reference_f32() {
- let context = create_test_context();
- let add_kernel = <<Metal as Backend>::Kernels as Kernels>::AudioAddKernel::new(&context, DataType::F32)
- .expect("audio add kernel");
-
- let n = 2048usize;
- let a_values: Vec<f32> = (0..n).map(|i| i as f32 * 0.001 - 1.0).collect();
- let b_values: Vec<f32> = (0..n).map(|i| (i as f32 * 0.002).sin()).collect();
-
- let mut a = context.create_array_zeros(&[n], DataType::F32);
- a.as_slice_mut::<f32>().copy_from_slice(&a_values);
-
- let mut b = context.create_array_zeros(&[n], DataType::F32);
- b.as_slice_mut::<f32>().copy_from_slice(&b_values);
-
- let mut sum = context.create_array_zeros(&[n], DataType::F32).into_allocation();
-
- run_command_buffer(&context, |command_buffer| {
- borrow_array_buffer!(a_buffer = a);
- borrow_array_buffer!(b_buffer = b);
- borrow_array_buffer_mut!(sum_buffer = sum);
- add_kernel.encode(a_buffer, b_buffer, sum_buffer, n as i32, command_buffer);
- });
-
- let sum_got = allocation_to_vec::<Metal, f32>(&sum);
-
- for index in 0..n {
- let expected_sum = a_values[index] + b_values[index];
- let sum_delta = (expected_sum - sum_got[index]).abs();
-
- assert!(
- sum_delta <= 1e-6,
- "Add mismatch at index={index}: expected {expected_sum}, got {}, delta={sum_delta}",
- sum_got[index]
- );
- }
-}
-
-#[uzu_test]
-fn audio_half_snake_matches_reference_f32() {
- let context = create_test_context();
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AudioHalfSnakeKernel::new(&context, DataType::F32)
- .expect("audio runtime");
-
- let batch_size = 1usize;
- let channels = 6usize;
- let snake_channels = channels / 2;
- let seq_len = 64usize;
- let n = batch_size * channels * seq_len;
-
- let negative_slope = 0.01f32;
- let eps = 1e-9f32;
-
- let input_values: Vec<f32> = (0..n).map(|i| (i as f32 * 0.01 - 3.2).sin()).collect();
- let alpha_values: Vec<f32> = (0..snake_channels).map(|i| 0.5 + i as f32 * 0.1).collect();
-
- let mut input = context.create_array_zeros(&[batch_size, channels, seq_len], DataType::F32);
- input.as_slice_mut::<f32>().copy_from_slice(&input_values);
-
- let mut alpha = context.create_array_zeros(&[snake_channels], DataType::F32);
- alpha.as_slice_mut::<f32>().copy_from_slice(&alpha_values);
-
- let mut output = context.create_array_zeros(&[batch_size, channels, seq_len], DataType::F32).into_allocation();
-
- run_command_buffer(&context, |command_buffer| {
- borrow_array_buffer!(input_buffer = input);
- borrow_array_buffer!(alpha_buffer = alpha);
- borrow_array_buffer_mut!(output_buffer = output);
- kernel.encode(
- input_buffer,
- alpha_buffer,
- output_buffer,
- channels as i32,
- seq_len as i32,
- snake_channels as i32,
- negative_slope,
- eps,
- batch_size as i32,
- command_buffer,
- );
- });
-
- let got = allocation_to_vec::<Metal, f32>(&output);
- let expected = half_snake_reference(HalfSnakeSpec {
- input: &input_values,
- alpha: &alpha_values,
- batch_size,
- channels,
- seq_len,
- snake_channels,
- negative_slope,
- eps,
- });
- for index in 0..n {
- let delta = (expected[index] - got[index]).abs();
- assert!(
- delta <= 1e-5,
- "Mismatch at index={index}: expected {}, got {}, delta={delta}",
- expected[index],
- got[index]
- );
- }
-}
-
-#[uzu_test]
-fn audio_norm_ncs_matches_reference_f32() {
- let context = create_test_context();
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AudioNormNcsKernel::new(&context, DataType::F32)
- .expect("audio runtime");
-
- let batch_size = 2usize;
- let channels = 7usize;
- let seq_len = 11usize;
- let lengths_values: [i32; 2] = [8, 11];
-
- let input_len = batch_size * channels * seq_len;
- let input_values: Vec<f32> = (0..input_len).map(|i| (i as f32 * 0.013 - 3.0).sin() * 0.7).collect();
- let scales_values: Vec<f32> = (0..channels).map(|i| 0.7 + i as f32 * 0.05).collect();
- let bias_values: Vec<f32> = (0..channels).map(|i| -0.2 + i as f32 * 0.03).collect();
- let epsilon = 1e-5f32;
-
- let reference = |subtract_mean: bool| -> Vec<f32> {
- let mut out = vec![0.0_f32; input_values.len()];
- for batch in 0..batch_size {
- let active_len = lengths_values[batch].max(0) as usize;
- for t in 0..active_len {
- let mut mean = 0.0_f32;
- if subtract_mean {
- for c in 0..channels {
- let idx = (batch * channels + c) * seq_len + t;
- mean += input_values[idx];
- }
- mean /= channels as f32;
- }
- let mut variance_sum = 0.0_f32;
- for c in 0..channels {
- let idx = (batch * channels + c) * seq_len + t;
- let centered = if subtract_mean {
- input_values[idx] - mean
- } else {
- input_values[idx]
- };
- variance_sum += centered * centered;
- }
- let inv_std = 1.0_f32 / (variance_sum / channels as f32 + epsilon).sqrt();
- for c in 0..channels {
- let idx = (batch * channels + c) * seq_len + t;
- let centered = if subtract_mean {
- input_values[idx] - mean
- } else {
- input_values[idx]
- };
- out[idx] = centered * inv_std * scales_values[c] + bias_values[c];
- }
- }
- }
- out
- };
-
- for subtract_mean in [false, true] {
- let mut input = context.create_array_zeros(&[batch_size, channels, seq_len], DataType::F32);
- input.as_slice_mut::<f32>().copy_from_slice(&input_values);
-
- let mut scales = context.create_array_zeros(&[channels], DataType::F32);
- scales.as_slice_mut::<f32>().copy_from_slice(&scales_values);
-
- let mut bias = context.create_array_zeros(&[channels], DataType::F32);
- bias.as_slice_mut::<f32>().copy_from_slice(&bias_values);
-
- let mut lengths = context.create_array_zeros(&[batch_size], DataType::I32);
- lengths.as_slice_mut::<i32>().copy_from_slice(&lengths_values);
-
- let mut output = context.create_array_zeros(&[batch_size, channels, seq_len], DataType::F32).into_allocation();
-
- run_command_buffer(&context, |command_buffer| {
- borrow_array_buffer!(input_buffer = input);
- borrow_array_buffer!(scales_buffer = scales);
- borrow_array_buffer!(bias_buffer = bias);
- borrow_array_buffer_mut!(output_buffer = output);
- borrow_array_buffer!(lengths_buffer = lengths);
- kernel.encode(
- input_buffer,
- scales_buffer,
- bias_buffer,
- output_buffer,
- lengths_buffer,
- channels as i32,
- seq_len as i32,
- epsilon,
- if subtract_mean {
- 1
- } else {
- 0
- },
- batch_size as i32,
- command_buffer,
- );
- });
-
- let got = allocation_to_vec::<Metal, f32>(&output);
- let expected = reference(subtract_mean);
- for index in 0..input_len {
- let delta = (expected[index] - got[index]).abs();
- assert!(
- delta <= 1e-4,
- "subtract_mean={subtract_mean}, index={index}: expected {}, got {}, delta={delta}",
- expected[index],
- got[index]
- );
- }
- }
-}
-
-#[uzu_test]
-fn audio_fsq_decode_matches_reference() {
- let context = create_test_context();
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AudioFsqDecodeKernel::new(&context, DataType::F32)
- .expect("audio runtime");
-
- let batch_size = 1usize;
- let num_groups = 2usize;
- let seq_len = 3usize;
- let codebook_dim = 2usize;
- let num_levels: Vec<i32> = vec![8, 5];
- let dim_base_index: Vec<i32> = vec![1, 8];
-
- let mut tokens = context.create_array_zeros(&[batch_size, num_groups, seq_len], DataType::I32);
- tokens.as_slice_mut::<i32>().copy_from_slice(&[
- 0, 7, 11, // g0 tokens at t0..t2
- 3, 5, 9, // g1 tokens at t0..t2
- ]);
-
- let mut lengths = context.create_array_zeros(&[batch_size], DataType::I32);
- lengths.as_slice_mut::<i32>().copy_from_slice(&[2]);
-
- let mut output =
- context.create_array_zeros(&[batch_size, num_groups * codebook_dim, seq_len], DataType::F32).into_allocation();
-
- run_command_buffer(&context, |command_buffer| {
- borrow_array_buffer!(tokens_buffer = tokens);
- borrow_array_buffer_mut!(output_buffer = output);
- borrow_array_buffer!(lengths_buffer = lengths);
- kernel.encode(
- tokens_buffer,
- output_buffer,
- lengths_buffer,
- num_groups as i32,
- seq_len as i32,
- codebook_dim as i32,
- &num_levels,
- &dim_base_index,
- batch_size as i32,
- command_buffer,
- );
- });
-
- let expected =
- fsq_decode_reference(&[0, 7, 11, 3, 5, 9], &[2], batch_size, num_groups, seq_len, codebook_dim, &num_levels);
- let actual = allocation_to_vec::<Metal, f32>(&output);
-
- for (index, (&a, &e)) in actual.iter().zip(expected.iter()).enumerate() {
- let delta = (a - e).abs();
- assert!(delta <= 1e-5, "index={index}, actual={a}, expected={e}, delta={delta}");
- }
-}
-
-#[uzu_test]
-fn audio_fsq_encode_matches_reference() {
- let context = create_test_context();
- let kernel = <<Metal as Backend>::Kernels as Kernels>::AudioFsqEncodeKernel::new(&context, DataType::F32)
- .expect("audio runtime");
-
- let batch_size = 1usize;
- let num_groups = 2usize;
- let codebook_dim = 2usize;
- let seq_len = 4usize;
- let eps = 1e-3_f32;
- let num_levels: Vec<i32> = vec![8, 6];
- let dim_base_index: Vec<i32> = vec![1, 8];
-
- let input_values = vec![
- -0.9, -0.1, 0.2, 0.7, // g0 d0
- 0.8, 0.3, -0.4, -0.7, // g0 d1
- -0.2, 0.0, 0.4, 0.9, // g1 d0
- 0.5, -0.5, 0.1, -0.1, // g1 d1
- ];
- let lengths_values = vec![3_i32];
-
- let mut input = context.create_array_zeros(&[batch_size, num_groups * codebook_dim, seq_len], DataType::F32);
- input.as_slice_mut::<f32>().copy_from_slice(&input_values);
-
- let mut lengths = context.create_array_zeros(&[batch_size], DataType::I32);
- lengths.as_slice_mut::<i32>().copy_from_slice(&lengths_values);
-
- let mut tokens = context.create_array_zeros(&[batch_size, num_groups, seq_len], DataType::I32).into_allocation();
-
- run_command_buffer(&context, |command_buffer| {
- borrow_array_buffer!(input_buffer = input);
- borrow_array_buffer_mut!(tokens_buffer = tokens);
- borrow_array_buffer!(lengths_buffer = lengths);
- kernel.encode(
- input_buffer,
- tokens_buffer,
- lengths_buffer,
- num_groups as i32,
- seq_len as i32,
- codebook_dim as i32,
- &num_levels,
- &dim_base_index,
- eps,
- batch_size as i32,
- command_buffer,
- );
- });
-
- let expected = fsq_encode_reference(
- &input_values,
- &lengths_values,
- batch_size,
- num_groups,
- seq_len,
- codebook_dim,
- &num_levels,
- &dim_base_index,
- eps,
- );
- let actual = allocation_to_vec::<Metal, i32>(&tokens);
-
- assert_eq!(actual, expected);
-}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/audio/mod.rs b/crates/backend-uzu/unit/backends/common/kernel/audio/mod.rs
deleted file mode 100644
index 3c08930b3..000000000
--- a/crates/backend-uzu/unit/backends/common/kernel/audio/mod.rs
+++ /dev/null
@@ -1,2 +0,0 @@
-mod audio_kernel_perf;
-mod audio_test;
diff --git a/crates/backend-uzu/unit/backends/common/kernel/delta_net_test.rs b/crates/backend-uzu/unit/backends/common/kernel/delta_net_test.rs
index b6d69e05d..791293de5 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/delta_net_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/delta_net_test.rs
@@ -4,7 +4,7 @@ use half::bf16;
use proc_macros::uzu_test;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{
Backend, Context, Encoder, Kernels,
@@ -17,6 +17,7 @@ use crate::{
metal::Metal,
},
data_type::DataType,
+ tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_prefix_to_vec, allocation_to_vec},
};
fn run_conv_update<B: Backend>(
@@ -30,18 +31,18 @@ fn run_conv_update<B: Backend>(
) -> (Vec<f32>, Vec<f32>) {
let context = B::Context::new().expect("Failed to create context");
- let w_array = context.create_array_from(&[w.len()], w);
- let b_array = context.create_array_from(&[b.len()], b);
- let mut in_out = context.create_array_from(&[in_proj.len()], in_proj).into_allocation();
- let mut state_allocation = context.create_array_from(&[state.len()], state).into_allocation();
+ let w_array = alloc_allocation_with_data::<B, f32>(&context, w);
+ let b_array = alloc_allocation_with_data::<B, f32>(&context, b);
+ let mut in_out = alloc_allocation_with_data::<B, f32>(&context, in_proj);
+ let mut state_allocation = alloc_allocation_with_data::<B, f32>(&context, state);
let kernel = <<B as Backend>::Kernels as Kernels>::DeltaNetConvUpdateKernel::new(&context, DataType::F32, true)
.expect("Failed to create kernel");
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- w_array.allocation(),
- Some(b_array.allocation()),
+ &w_array,
+ Some(&b_array),
&mut in_out,
&mut state_allocation,
kernel_size,
@@ -51,8 +52,8 @@ fn run_conv_update<B: Backend>(
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- let out = crate::tests::helpers::allocation_prefix_to_vec::<B, f32>(&in_out, conv_dim as usize);
- let new_state = crate::tests::helpers::allocation_to_vec::<B, f32>(&state_allocation);
+ let out = allocation_prefix_to_vec::<B, f32>(&in_out, conv_dim as usize);
+ let new_state = allocation_to_vec::<B, f32>(&state_allocation);
(out, new_state)
}
@@ -71,22 +72,22 @@ fn run_delta_net_update<B: Backend>(
) -> (Vec<f32>, Vec<f32>) {
let context = B::Context::new().expect("Failed to create context");
- let in_proj_array = context.create_array_from(&[in_proj.len()], in_proj);
- let a_log_array = context.create_array_from(&[a_log.len()], a_log);
- let dt_bias_array = context.create_array_from(&[dt_bias.len()], dt_bias);
- let norm_weight_array = context.create_array_from(&[norm_weight.len()], norm_weight);
- let mut state_allocation = context.create_array_from(&[state.len()], state).into_allocation();
- let mut out = context.create_array_zeros(&[value_dim as usize], DataType::F32).into_allocation();
+ let in_proj_array = alloc_allocation_with_data::<B, f32>(&context, in_proj);
+ let a_log_array = alloc_allocation_with_data::<B, f32>(&context, a_log);
+ let dt_bias_array = alloc_allocation_with_data::<B, f32>(&context, dt_bias);
+ let norm_weight_array = alloc_allocation_with_data::<B, f32>(&context, norm_weight);
+ let mut state_allocation = alloc_allocation_with_data::<B, f32>(&context, state);
+ let mut out = alloc_allocation::<B, f32>(&context, value_dim as usize);
let kernel = <<B as Backend>::Kernels as Kernels>::DeltaNetUpdateKernel::new(&context, DataType::F32, head_k_dim)
.expect("Failed to create kernel");
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- in_proj_array.allocation(),
- a_log_array.allocation(),
- dt_bias_array.allocation(),
- norm_weight_array.allocation(),
+ &in_proj_array,
+ &a_log_array,
+ &dt_bias_array,
+ &norm_weight_array,
&mut state_allocation,
&mut out,
num_v_heads,
@@ -99,8 +100,8 @@ fn run_delta_net_update<B: Backend>(
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- let out = crate::tests::helpers::allocation_to_vec::<B, f32>(&out);
- let new_state = crate::tests::helpers::allocation_to_vec::<B, f32>(&state_allocation);
+ let out = allocation_to_vec::<B, f32>(&out);
+ let new_state = allocation_to_vec::<B, f32>(&state_allocation);
(out, new_state)
}
@@ -179,14 +180,14 @@ fn test_delta_net_conv_scan() {
// Test: Conv1dPack + DeltaNetConvScan on Metal
let context = <Metal as Backend>::Context::new().expect("context");
- let state_array = context.create_array_from(&[init_state.len()], &init_state);
- let mut in_proj_array = context.create_array_from(&[in_proj.len()], &in_proj).into_allocation();
- let w_array = context.create_array_from(&[w.len()], &w);
- let b_array = context.create_array_from(&[b.len()], &b);
+ let state_array = alloc_allocation_with_data::<Metal, f32>(&context, &init_state);
+ let mut in_proj_array = alloc_allocation_with_data::<Metal, bf16>(&context, &in_proj);
+ let w_array = alloc_allocation_with_data::<Metal, f32>(&context, &w);
+ let b_array = alloc_allocation_with_data::<Metal, f32>(&context, &b);
let padded_len = (tap_count + suffix_len) * total_proj_dim;
- let mut padded_array = context.create_array_zeros(&[padded_len], DataType::F32).into_allocation();
- let mut state_out_array = context.create_array_zeros(&[conv_dim * tap_count], DataType::F32).into_allocation();
+ let mut padded_array = alloc_allocation::<Metal, f32>(&context, padded_len);
+ let mut state_out_array = alloc_allocation::<Metal, f32>(&context, conv_dim * tap_count);
let pack_kernel =
<<Metal as Backend>::Kernels as Kernels>::Conv1dPackKernel::new(&context, DataType::F32, DataType::BF16)
@@ -197,7 +198,7 @@ fn test_delta_net_conv_scan() {
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
pack_kernel.encode(
- state_array.allocation(),
+ &state_array,
&in_proj_array,
&mut padded_array,
tap_count as u32,
@@ -208,8 +209,8 @@ fn test_delta_net_conv_scan() {
);
scan_kernel.encode(
&padded_array,
- w_array.allocation(),
- Some(b_array.allocation()),
+ &w_array,
+ Some(&b_array),
&mut in_proj_array,
&mut state_out_array,
suffix_len as u32,
@@ -222,14 +223,14 @@ fn test_delta_net_conv_scan() {
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- let in_proj_result: Vec<bf16> = crate::tests::helpers::allocation_to_vec(&in_proj_array);
+ let in_proj_result: Vec<bf16> = allocation_to_vec(&in_proj_array);
let in_proj_result: Vec<f32> = in_proj_result.into_iter().map(f32::from).collect();
let mut scan_outputs = vec![0.0f32; suffix_len * conv_dim];
for t in 0..suffix_len {
scan_outputs[t * conv_dim..(t + 1) * conv_dim]
.copy_from_slice(&in_proj_result[t * total_proj_dim..t * total_proj_dim + conv_dim]);
}
- let scan_state: Vec<f32> = crate::tests::helpers::allocation_to_vec(&state_out_array);
+ let scan_state: Vec<f32> = allocation_to_vec(&state_out_array);
assert_close(&ref_outputs, &scan_outputs, 1e-4, 1e-3, "ConvScan output");
assert_close(&ref_state, &scan_state, 1e-5, 1e-4, "ConvScan state");
@@ -313,17 +314,17 @@ fn run_prefill_with_norm_gate_typed<T: ArrayElement>(
let num_dv_groups = head_v_dim.div_ceil(16) as u32;
let context = <Metal as Backend>::Context::new().expect("context");
- let in_proj_array = context.create_array_from(&[in_proj.len()], in_proj);
- let a_log_array = context.create_array_from(&[a_log.len()], a_log);
- let dt_bias_array = context.create_array_from(&[dt_bias.len()], dt_bias);
- let norm_weight_array = context.create_array_from(&[norm_weight.len()], norm_weight);
- let mut state_array = context.create_array_from(&[state.len()], state).into_allocation();
- let mut out_array = context.create_array_zeros(&[suffix_len * value_dim], T::data_type()).into_allocation();
- let mut q_norm_array = context.create_array_zeros(&[suffix_len * key_dim], DataType::F32).into_allocation();
- let mut k_norm_array = context.create_array_zeros(&[suffix_len * key_dim], DataType::F32).into_allocation();
-
- let mut beta_array = context.create_array_zeros(&[suffix_len * num_v_heads], DataType::F32).into_allocation();
- let mut decay_array = context.create_array_zeros(&[suffix_len * num_v_heads], DataType::F32).into_allocation();
+ let in_proj_array = alloc_allocation_with_data::<Metal, T>(&context, in_proj);
+ let a_log_array = alloc_allocation_with_data::<Metal, f32>(&context, a_log);
+ let dt_bias_array = alloc_allocation_with_data::<Metal, f32>(&context, dt_bias);
+ let norm_weight_array = alloc_allocation_with_data::<Metal, f32>(&context, norm_weight);
+ let mut state_array = alloc_allocation_with_data::<Metal, f32>(&context, state);
+ let mut out_array = alloc_allocation::<Metal, T>(&context, suffix_len * value_dim);
+ let mut q_norm_array = alloc_allocation::<Metal, f32>(&context, suffix_len * key_dim);
+ let mut k_norm_array = alloc_allocation::<Metal, f32>(&context, suffix_len * key_dim);
+
+ let mut beta_array = alloc_allocation::<Metal, f32>(&context, suffix_len * num_v_heads);
+ let mut decay_array = alloc_allocation::<Metal, f32>(&context, suffix_len * num_v_heads);
let prep_k = <<Metal as Backend>::Kernels as Kernels>::DeltaNetPrefillPrepKernel::new(
&context,
@@ -342,9 +343,9 @@ fn run_prefill_with_norm_gate_typed<T: ArrayElement>(
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
prep_k.encode(
- in_proj_array.allocation(),
- a_log_array.allocation(),
- dt_bias_array.allocation(),
+ &in_proj_array,
+ &a_log_array,
+ &dt_bias_array,
&mut q_norm_array,
&mut k_norm_array,
&mut beta_array,
@@ -361,7 +362,7 @@ fn run_prefill_with_norm_gate_typed<T: ArrayElement>(
&k_norm_array,
&beta_array,
&decay_array,
- in_proj_array.allocation(),
+ &in_proj_array,
&mut state_array,
&mut out_array,
num_v_heads as u32,
@@ -375,8 +376,8 @@ fn run_prefill_with_norm_gate_typed<T: ArrayElement>(
);
norm_k.encode(
&mut out_array,
- in_proj_array.allocation(),
- norm_weight_array.allocation(),
+ &in_proj_array,
+ &norm_weight_array,
num_v_heads as u32,
head_v_dim as u32,
value_dim as u32,
@@ -388,9 +389,9 @@ fn run_prefill_with_norm_gate_typed<T: ArrayElement>(
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- let out: Vec<T> = crate::tests::helpers::allocation_to_vec(&out_array);
+ let out: Vec<T> = allocation_to_vec(&out_array);
let out = out.into_iter().map(|value| value.to_f32().expect("output to f32")).collect();
- let state = crate::tests::helpers::allocation_to_vec(&state_array);
+ let state = allocation_to_vec(&state_array);
(out, state)
}
@@ -495,13 +496,13 @@ fn test_delta_net_prefill_prep() {
// CPU reference via Kernels trait
let cpu_ctx = <Cpu as Backend>::Context::new().expect("cpu context");
- let cpu_in_proj = cpu_ctx.create_array_from(&[in_proj.len()], &in_proj);
- let cpu_a_log = cpu_ctx.create_array_from(&[a_log.len()], &a_log);
- let cpu_dt_bias = cpu_ctx.create_array_from(&[dt_bias.len()], &dt_bias);
- let mut cpu_q = cpu_ctx.create_array_zeros(&[suffix_len * key_dim], DataType::F32).into_allocation();
- let mut cpu_k = cpu_ctx.create_array_zeros(&[suffix_len * key_dim], DataType::F32).into_allocation();
- let mut cpu_beta = cpu_ctx.create_array_zeros(&[suffix_len * num_v_heads], DataType::F32).into_allocation();
- let mut cpu_decay = cpu_ctx.create_array_zeros(&[suffix_len * num_v_heads], DataType::F32).into_allocation();
+ let cpu_in_proj = alloc_allocation_with_data::<Cpu, f32>(&cpu_ctx, &in_proj);
+ let cpu_a_log = alloc_allocation_with_data::<Cpu, f32>(&cpu_ctx, &a_log);
+ let cpu_dt_bias = alloc_allocation_with_data::<Cpu, f32>(&cpu_ctx, &dt_bias);
+ let mut cpu_q = alloc_allocation::<Cpu, f32>(&cpu_ctx, suffix_len * key_dim);
+ let mut cpu_k = alloc_allocation::<Cpu, f32>(&cpu_ctx, suffix_len * key_dim);
+ let mut cpu_beta = alloc_allocation::<Cpu, f32>(&cpu_ctx, suffix_len * num_v_heads);
+ let mut cpu_decay = alloc_allocation::<Cpu, f32>(&cpu_ctx, suffix_len * num_v_heads);
let cpu_prep = <<Cpu as Backend>::Kernels as Kernels>::DeltaNetPrefillPrepKernel::new(
&cpu_ctx,
@@ -511,9 +512,9 @@ fn test_delta_net_prefill_prep() {
.unwrap();
let mut cpu_enc = Encoder::new(cpu_ctx.as_ref()).expect("encoder");
cpu_prep.encode(
- cpu_in_proj.allocation(),
- cpu_a_log.allocation(),
- cpu_dt_bias.allocation(),
+ &cpu_in_proj,
+ &cpu_a_log,
+ &cpu_dt_bias,
&mut cpu_q,
&mut cpu_k,
&mut cpu_beta,
@@ -527,21 +528,21 @@ fn test_delta_net_prefill_prep() {
);
cpu_enc.end_encoding().submit().wait_until_completed().unwrap();
- let ref_q: Vec<f32> = crate::tests::helpers::allocation_to_vec(&cpu_q);
- let ref_k: Vec<f32> = crate::tests::helpers::allocation_to_vec(&cpu_k);
- let ref_beta: Vec<f32> = crate::tests::helpers::allocation_to_vec(&cpu_beta);
- let ref_decay: Vec<f32> = crate::tests::helpers::allocation_to_vec(&cpu_decay);
+ let ref_q: Vec<f32> = allocation_to_vec(&cpu_q);
+ let ref_k: Vec<f32> = allocation_to_vec(&cpu_k);
+ let ref_beta: Vec<f32> = allocation_to_vec(&cpu_beta);
+ let ref_decay: Vec<f32> = allocation_to_vec(&cpu_decay);
// Metal
let context = <Metal as Backend>::Context::new().expect("context");
- let in_proj_array = context.create_array_from(&[in_proj.len()], &in_proj);
- let a_log_array = context.create_array_from(&[a_log.len()], &a_log);
- let dt_bias_array = context.create_array_from(&[dt_bias.len()], &dt_bias);
- let mut q_norm_array = context.create_array_zeros(&[suffix_len * key_dim], DataType::F32).into_allocation();
- let mut k_norm_array = context.create_array_zeros(&[suffix_len * key_dim], DataType::F32).into_allocation();
+ let in_proj_array = alloc_allocation_with_data::<Metal, f32>(&context, &in_proj);
+ let a_log_array = alloc_allocation_with_data::<Metal, f32>(&context, &a_log);
+ let dt_bias_array = alloc_allocation_with_data::<Metal, f32>(&context, &dt_bias);
+ let mut q_norm_array = alloc_allocation::<Metal, f32>(&context, suffix_len * key_dim);
+ let mut k_norm_array = alloc_allocation::<Metal, f32>(&context, suffix_len * key_dim);
- let mut beta_array = context.create_array_zeros(&[suffix_len * num_v_heads], DataType::F32).into_allocation();
- let mut decay_array = context.create_array_zeros(&[suffix_len * num_v_heads], DataType::F32).into_allocation();
+ let mut beta_array = alloc_allocation::<Metal, f32>(&context, suffix_len * num_v_heads);
+ let mut decay_array = alloc_allocation::<Metal, f32>(&context, suffix_len * num_v_heads);
let prep_k = <<Metal as Backend>::Kernels as Kernels>::DeltaNetPrefillPrepKernel::new(
&context,
@@ -552,9 +553,9 @@ fn test_delta_net_prefill_prep() {
let mut encoder = Encoder::new(context.as_ref()).expect("encoder");
prep_k.encode(
- in_proj_array.allocation(),
- a_log_array.allocation(),
- dt_bias_array.allocation(),
+ &in_proj_array,
+ &a_log_array,
+ &dt_bias_array,
&mut q_norm_array,
&mut k_norm_array,
&mut beta_array,
@@ -568,10 +569,10 @@ fn test_delta_net_prefill_prep() {
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- let gpu_q: Vec<f32> = crate::tests::helpers::allocation_to_vec(&q_norm_array);
- let gpu_k: Vec<f32> = crate::tests::helpers::allocation_to_vec(&k_norm_array);
- let gpu_beta: Vec<f32> = crate::tests::helpers::allocation_to_vec(&beta_array);
- let gpu_decay: Vec<f32> = crate::tests::helpers::allocation_to_vec(&decay_array);
+ let gpu_q: Vec<f32> = allocation_to_vec(&q_norm_array);
+ let gpu_k: Vec<f32> = allocation_to_vec(&k_norm_array);
+ let gpu_beta: Vec<f32> = allocation_to_vec(&beta_array);
+ let gpu_decay: Vec<f32> = allocation_to_vec(&decay_array);
assert_close(&gpu_q, &ref_q, 1e-4, 1e-3, "prep q_norm");
assert_close(&gpu_k, &ref_k, 1e-4, 1e-3, "prep k_norm");
@@ -602,16 +603,16 @@ fn bench_delta_net_prefill() {
let norm_weight: Vec<f32> = (0..head_v_dim).map(|i| 0.9 + (i as f32) * 0.001).collect();
let context = <Metal as Backend>::Context::new().expect("context");
- let in_proj_array = context.create_array_from(&[in_proj.len()], &in_proj);
- let a_log_array = context.create_array_from(&[a_log.len()], &a_log);
- let dt_bias_array = context.create_array_from(&[dt_bias.len()], &dt_bias);
- let norm_weight_array = context.create_array_from(&[norm_weight.len()], &norm_weight);
- let mut out_array = context.create_array_zeros(&[suffix_len * value_dim], DataType::F32).into_allocation();
- let mut q_norm_array = context.create_array_zeros(&[suffix_len * key_dim], DataType::F32).into_allocation();
- let mut k_norm_array = context.create_array_zeros(&[suffix_len * key_dim], DataType::F32).into_allocation();
+ let in_proj_array = alloc_allocation_with_data::<Metal, f32>(&context, &in_proj);
+ let a_log_array = alloc_allocation_with_data::<Metal, f32>(&context, &a_log);
+ let dt_bias_array = alloc_allocation_with_data::<Metal, f32>(&context, &dt_bias);
+ let norm_weight_array = alloc_allocation_with_data::<Metal, f32>(&context, &norm_weight);
+ let mut out_array = alloc_allocation::<Metal, f32>(&context, suffix_len * value_dim);
+ let mut q_norm_array = alloc_allocation::<Metal, f32>(&context, suffix_len * key_dim);
+ let mut k_norm_array = alloc_allocation::<Metal, f32>(&context, suffix_len * key_dim);
- let mut beta_array = context.create_array_zeros(&[suffix_len * num_v_heads], DataType::F32).into_allocation();
- let mut decay_array = context.create_array_zeros(&[suffix_len * num_v_heads], DataType::F32).into_allocation();
+ let mut beta_array = alloc_allocation::<Metal, f32>(&context, suffix_len * num_v_heads);
+ let mut decay_array = alloc_allocation::<Metal, f32>(&context, suffix_len * num_v_heads);
let num_dv_groups = head_v_dim.div_ceil(16) as u32;
@@ -639,9 +640,9 @@ fn bench_delta_net_prefill() {
let prep_result = run_perf_with_warmup("prep_only", 5, 50, || {
let mut encoder = Encoder::new(context.as_ref()).expect("encoder");
prep_k.encode(
- in_proj_array.allocation(),
- a_log_array.allocation(),
- dt_bias_array.allocation(),
+ &in_proj_array,
+ &a_log_array,
+ &dt_bias_array,
&mut q_norm_array,
&mut k_norm_array,
&mut beta_array,
@@ -658,15 +659,15 @@ fn bench_delta_net_prefill() {
prep_result.print();
// Benchmark prep + prefill + norm_gate (production path)
- let mut state_array = context.create_array_zeros(&[state_size], DataType::F32).into_allocation();
+ let mut state_array = alloc_allocation::<Metal, f32>(&context, state_size);
let prefill_result = run_perf_with_warmup("prep+prefill+norm_gate", 5, 50, || {
let mut encoder = Encoder::new(context.as_ref()).expect("encoder");
encoder.encode_fill(&mut state_array, 0);
prep_k.encode(
- in_proj_array.allocation(),
- a_log_array.allocation(),
- dt_bias_array.allocation(),
+ &in_proj_array,
+ &a_log_array,
+ &dt_bias_array,
&mut q_norm_array,
&mut k_norm_array,
&mut beta_array,
@@ -683,7 +684,7 @@ fn bench_delta_net_prefill() {
&k_norm_array,
&beta_array,
&decay_array,
- in_proj_array.allocation(),
+ &in_proj_array,
&mut state_array,
&mut out_array,
num_v_heads as u32,
@@ -697,8 +698,8 @@ fn bench_delta_net_prefill() {
);
norm_k.encode(
&mut out_array,
- in_proj_array.allocation(),
- norm_weight_array.allocation(),
+ &in_proj_array,
+ &norm_weight_array,
num_v_heads as u32,
head_v_dim as u32,
value_dim as u32,
diff --git a/crates/backend-uzu/unit/backends/common/kernel/embedding/embedding_rows_sum_test.rs b/crates/backend-uzu/unit/backends/common/kernel/embedding/embedding_rows_sum_test.rs
deleted file mode 100644
index b02cf3d23..000000000
--- a/crates/backend-uzu/unit/backends/common/kernel/embedding/embedding_rows_sum_test.rs
+++ /dev/null
@@ -1,229 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::uzu_test;
-use test_runner::for_each_non_cpu_backend;
-
-use crate::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{Backend, Context, Encoder, Kernels, kernel::EmbeddingRowsSumKernel},
- cpu::Cpu,
- },
- data_type::DataType,
- tests::assert::assert_eq_float,
-};
-
-struct Input<T: ArrayElement + Float> {
- token_indices: Box<[u32]>,
- weights: Box<[T]>,
- num_rows: u32,
- total_rows: u32,
- model_dim: u32,
- codebook_stride: u32,
-}
-
-fn get_test_data_basic<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {
- let num_rows = 4u32;
- let codebook_size = 8u32;
- let codebook_stride = codebook_size;
- let total_rows = num_rows * codebook_size;
- let model_dim = 513u32;
-
- let token_indices: Box<[u32]> = Box::new([3, 7, 1, 5]);
- let weights: Vec<T> = (0..total_rows as usize * model_dim as usize)
- .map(|i| T::from((i as f32 * 0.1).sin() * 10.0).unwrap())
- .collect();
-
- let input = Input {
- token_indices,
- weights: weights.into_boxed_slice(),
- num_rows,
- total_rows,
- model_dim,
- codebook_stride,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_test_data_edge<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {
- // Single row, small dim
- let num_rows = 1u32;
- let codebook_stride = 4u32;
- let total_rows = 4u32;
- let model_dim = 4u32;
-
- let token_indices: Box<[u32]> = Box::new([2]);
- let weights: Vec<T> =
- (0..total_rows as usize * model_dim as usize).map(|i| T::from(i as f32 + 1.0).unwrap()).collect();
-
- let input = Input {
- token_indices,
- weights: weights.into_boxed_slice(),
- num_rows,
- total_rows,
- model_dim,
- codebook_stride,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_test_data_oob<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {
- // Token index causes row to exceed total_rows, should be skipped
- let num_rows = 2u32;
- let codebook_stride = 4u32;
- let total_rows = 4u32;
- let model_dim = 4u32;
-
- // row_idx=0: row = 0*4+1 = 1 (valid)
- // row_idx=1: row = 1*4+3 = 7 (out of bounds, total_rows=4)
- let token_indices: Box<[u32]> = Box::new([1, 3]);
- let weights: Vec<T> =
- (0..total_rows as usize * model_dim as usize).map(|i| T::from(i as f32 + 1.0).unwrap()).collect();
-
- let input = Input {
- token_indices,
- weights: weights.into_boxed_slice(),
- num_rows,
- total_rows,
- model_dim,
- codebook_stride,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
- let context = B::Context::new().expect("Failed to create Context");
-
- let kernel = <<B as Backend>::Kernels as Kernels>::EmbeddingRowsSumKernel::new(&context, T::data_type())
- .expect("Failed to create EmbeddingRowsSumKernel");
-
- let token_indices_array = context.create_array_from(&[input.num_rows as usize], &input.token_indices);
- let weights_array =
- context.create_array_from(&[input.total_rows as usize, input.model_dim as usize], &input.weights);
- let mut output = context.create_array_uninitialized(&[input.model_dim as usize], T::data_type()).into_allocation();
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- token_indices_array.allocation(),
- weights_array.allocation(),
- &mut output,
- input.num_rows,
- input.total_rows,
- input.model_dim,
- input.codebook_stride,
- &mut encoder,
- );
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- crate::tests::helpers::allocation_to_vec(&output)
-}
-
-fn test_basic<T: ArrayElement + Float + Debug + Display>() {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 0.1f32
- } else {
- 1e-4
- };
- let (input, expected) = get_test_data_basic::<T>();
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- assert_eq_float::<T>(
- &expected,
- &output,
- eps,
- &format!("EmbeddingRowsSum basic test failed for backend {}", std::any::type_name::<B>()),
- );
- });
-}
-
-fn test_edge<T: ArrayElement + Float + Debug + Display>() {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 0.05f32
- } else {
- 1e-5
- };
- let (input, expected) = get_test_data_edge::<T>();
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- assert_eq_float::<T>(
- &expected,
- &output,
- eps,
- &format!("EmbeddingRowsSum edge test failed for backend {}", std::any::type_name::<B>()),
- );
- });
-}
-
-fn test_oob<T: ArrayElement + Float + Debug + Display>() {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 0.05f32
- } else {
- 1e-5
- };
- let (input, expected) = get_test_data_oob::<T>();
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- assert_eq_float::<T>(
- &expected,
- &output,
- eps,
- &format!("EmbeddingRowsSum oob test failed for backend {}", std::any::type_name::<B>()),
- );
- });
-}
-
-// basic tests
-#[uzu_test]
-fn test_basic_f32() {
- test_basic::<f32>();
-}
-
-#[uzu_test]
-fn test_basic_f16() {
- test_basic::<f16>();
-}
-
-#[uzu_test]
-fn test_basic_bf16() {
- test_basic::<bf16>();
-}
-
-// edge tests
-#[uzu_test]
-fn test_edge_f32() {
- test_edge::<f32>();
-}
-
-#[uzu_test]
-fn test_edge_f16() {
- test_edge::<f16>();
-}
-
-#[uzu_test]
-fn test_edge_bf16() {
- test_edge::<bf16>();
-}
-
-// out-of-bounds tests
-#[uzu_test]
-fn test_oob_f32() {
- test_oob::<f32>();
-}
-
-#[uzu_test]
-fn test_oob_f16() {
- test_oob::<f16>();
-}
-
-#[uzu_test]
-fn test_oob_bf16() {
- test_oob::<bf16>();
-}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/embedding/full_precision_embedding_test.rs b/crates/backend-uzu/unit/backends/common/kernel/embedding/full_precision_embedding_test.rs
index a1ab98fd7..dfa2c1a1c 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/embedding/full_precision_embedding_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/embedding/full_precision_embedding_test.rs
@@ -6,8 +6,9 @@ use proc_macros::uzu_test;
use test_runner::for_each_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::common::{Backend, Context, Encoder, Kernels, kernel::FullPrecisionEmbeddingLookupKernel},
+ tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
};
struct Input<T: ArrayElement + Float> {
@@ -55,15 +56,14 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
<<B as Backend>::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(&context, T::data_type())
.expect("Failed to create FullPrecisionEmbeddingLookupKernel");
- let token_ids_array = context.create_array_from(&[input.batch_size], &input.token_ids);
- let weights_array = context.create_array_from(&[input.vocab_size, input.model_dim], &input.weights);
- let mut output =
- context.create_array_uninitialized(&[input.batch_size, input.model_dim], T::data_type()).into_allocation();
+ let token_ids_allocation = alloc_allocation_with_data::<B, u64>(&context, &input.token_ids);
+ let weights_allocation = alloc_allocation_with_data::<B, T>(&context, &input.weights);
+ let mut output = alloc_allocation::<B, T>(&context, input.batch_size * input.model_dim);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to get encoder");
kernel.encode(
- token_ids_array.allocation(),
- weights_array.allocation(),
+ &token_ids_allocation,
+ &weights_allocation,
&mut output,
input.batch_size as u32,
input.vocab_size as u32,
@@ -73,7 +73,7 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- crate::tests::helpers::allocation_to_vec(&output)
+ allocation_to_vec(&output)
}
fn test<T: ArrayElement + Float + Debug>() {
diff --git a/crates/backend-uzu/unit/backends/common/kernel/embedding/mod.rs b/crates/backend-uzu/unit/backends/common/kernel/embedding/mod.rs
index 1f2dc0e7d..dd406a5cd 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/embedding/mod.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/embedding/mod.rs
@@ -1,3 +1,2 @@
-mod embedding_rows_sum_test;
mod full_precision_embedding_test;
mod quant_embedding_test;
diff --git a/crates/backend-uzu/unit/backends/common/kernel/embedding/quant_embedding_test.rs b/crates/backend-uzu/unit/backends/common/kernel/embedding/quant_embedding_test.rs
index 6d095b019..e59542304 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/embedding/quant_embedding_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/embedding/quant_embedding_test.rs
@@ -6,7 +6,7 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{
Allocation, Backend, Context, Encoder, Kernels,
@@ -16,7 +16,10 @@ use crate::{
cpu::Cpu,
},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
struct Input<T: ArrayElement + Float> {
@@ -207,34 +210,21 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
)
.expect("Failed to create QuantizedEmbeddingLookupKernel");
- let packing_divisor = input.quant_mode.packing_divisor();
- let weights_stride = input.model_dim as usize / packing_divisor;
- let num_groups = (input.model_dim as usize).div_ceil(input.group_size as usize);
-
- let token_ids_array = context.create_array_from(&[input.batch_size as usize], &input.token_ids);
- let weights_array = context.create_array_from(&[input.vocab_size as usize, weights_stride], &input.weights);
- let scales_array = context.create_array_from(&[input.vocab_size as usize, num_groups], &input.scales);
- let zero_point_stride = match input.quant_mode {
- QuantizationMode::U4 => num_groups.div_ceil(2),
- QuantizationMode::I8 | QuantizationMode::U8 => num_groups,
- };
- let zero_points_array = input
- .zero_points
- .as_ref()
- .map(|zero_points| context.create_array_from(&[input.vocab_size as usize, zero_point_stride], zero_points));
- let biases_array =
- input.biases.as_ref().map(|biases| context.create_array_from(&[input.vocab_size as usize, num_groups], biases));
- let mut output = context
- .create_array_uninitialized(&[input.batch_size as usize, input.model_dim as usize], T::data_type())
- .into_allocation();
+ let token_ids_allocation = alloc_allocation_with_data::<B, u64>(&context, &input.token_ids);
+ let weights_allocation = alloc_allocation_with_data::<B, u8>(&context, &input.weights);
+ let scales_allocation = alloc_allocation_with_data::<B, T>(&context, &input.scales);
+ let zero_points_allocation =
+ input.zero_points.as_ref().map(|zero_points| alloc_allocation_with_data::<B, u8>(&context, zero_points));
+ let biases_allocation = input.biases.as_ref().map(|biases| alloc_allocation_with_data::<B, T>(&context, biases));
+ let mut output = alloc_allocation::<B, T>(&context, input.batch_size as usize * input.model_dim as usize);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- token_ids_array.allocation(),
- weights_array.allocation(),
- scales_array.allocation(),
- zero_points_array.as_ref().map(|array| array.allocation()),
- biases_array.as_ref().map(|array| array.allocation()),
+ &token_ids_allocation,
+ &weights_allocation,
+ &scales_allocation,
+ zero_points_allocation.as_ref(),
+ biases_allocation.as_ref(),
&mut output,
None::<&Allocation<B>>,
input.batch_size,
@@ -245,7 +235,7 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- crate::tests::helpers::allocation_to_vec(&output)
+ allocation_to_vec(&output)
}
fn test_zero_point_group16<T: ArrayElement + Float + Debug + Display>() {
diff --git a/crates/backend-uzu/unit/backends/common/kernel/gram_bench.rs b/crates/backend-uzu/unit/backends/common/kernel/gram_bench.rs
index c5e5bb502..03a95d760 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/gram_bench.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/gram_bench.rs
@@ -7,13 +7,16 @@ use half::bf16;
use proc_macros::uzu_bench;
use crate::{
- array::ArrayContextExt,
backends::{
common::{Allocation, Backend, Context, Encoder, Kernels, kernel::BuildTreeGramKernel},
metal::Metal,
},
data_type::DataType,
- tests::{cold_pool::ColdPool, matmul::iter_encode_loop_named},
+ tests::{
+ cold_pool::ColdPool,
+ helpers::{alloc_allocation, alloc_allocation_with_data},
+ matmul::iter_encode_loop_named,
+ },
};
const K_HEADS: usize = 16;
@@ -95,14 +98,14 @@ fn make_buffers(
let scale = (HEAD_K_DIM as f32).sqrt().recip();
(
TreeGramBuffers {
- q: context.create_array_from(&[q.len()], &q).into_allocation(),
- k: context.create_array_from(&[k.len()], &k).into_allocation(),
- trie: context.create_array_from(&[trie.len()], &trie).into_allocation(),
- prefix: context.create_array_from(&[prefix.len()], &prefix).into_allocation(),
- beta: context.create_array_from(&[beta.len()], &beta).into_allocation(),
- a_mat: context.create_array_uninitialized(&[out_len], DataType::F32).into_allocation(),
- qkd: context.create_array_uninitialized(&[out_len], DataType::F32).into_allocation(),
- ainv: context.create_array_uninitialized(&[out_len], DataType::F32).into_allocation(),
+ q: alloc_allocation_with_data::<Metal, bf16>(context, &q),
+ k: alloc_allocation_with_data::<Metal, bf16>(context, &k),
+ trie: alloc_allocation_with_data::<Metal, u32>(context, &trie),
+ prefix: alloc_allocation_with_data::<Metal, f32>(context, &prefix),
+ beta: alloc_allocation_with_data::<Metal, f32>(context, &beta),
+ a_mat: alloc_allocation::<Metal, f32>(context, out_len),
+ qkd: alloc_allocation::<Metal, f32>(context, out_len),
+ ainv: alloc_allocation::<Metal, f32>(context, out_len),
},
scale,
)
diff --git a/crates/backend-uzu/unit/backends/common/kernel/gram_test.rs b/crates/backend-uzu/unit/backends/common/kernel/gram_test.rs
index 697f90968..98ff730f3 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/gram_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/gram_test.rs
@@ -2,13 +2,15 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::ArrayContextExt,
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::BuildTreeGramKernel},
cpu::Cpu,
},
data_type::DataType,
- tests::{assert::assert_eq_float, helpers::allocation_to_vec},
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
const BATCH_SIZE: usize = 2;
@@ -31,22 +33,22 @@ fn get_output<B: Backend>(
.expect("Failed to create BuildTreeGramKernel");
let output_len = BATCH_SIZE * VALUE_HEADS * tree_size * tree_size;
- let q = context.create_array_from(&[q.len()], q);
- let k = context.create_array_from(&[k.len()], k);
- let trie = context.create_array_from(&[trie.len()], trie);
- let prefix = context.create_array_from(&[prefix.len()], prefix);
- let beta = context.create_array_from(&[beta.len()], beta);
- let mut a_mat = context.create_array_uninitialized(&[output_len], DataType::F32).into_allocation();
- let mut qkd = context.create_array_uninitialized(&[output_len], DataType::F32).into_allocation();
- let mut ainv = context.create_array_uninitialized(&[output_len], DataType::F32).into_allocation();
+ let q = alloc_allocation_with_data::<B, f32>(&context, q);
+ let k = alloc_allocation_with_data::<B, f32>(&context, k);
+ let trie = alloc_allocation_with_data::<B, u32>(&context, trie);
+ let prefix = alloc_allocation_with_data::<B, f32>(&context, prefix);
+ let beta = alloc_allocation_with_data::<B, f32>(&context, beta);
+ let mut a_mat = alloc_allocation::<B, f32>(&context, output_len);
+ let mut qkd = alloc_allocation::<B, f32>(&context, output_len);
+ let mut ainv = alloc_allocation::<B, f32>(&context, output_len);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- q.allocation(),
- k.allocation(),
- trie.allocation(),
- prefix.allocation(),
- beta.allocation(),
+ &q,
+ &k,
+ &trie,
+ &prefix,
+ &beta,
&mut a_mat,
&mut qkd,
&mut ainv,
diff --git a/crates/backend-uzu/unit/backends/common/kernel/hadamard_transform_test.rs b/crates/backend-uzu/unit/backends/common/kernel/hadamard_transform_test.rs
index 844ac926d..101ed729e 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/hadamard_transform_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/hadamard_transform_test.rs
@@ -6,10 +6,11 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::common::{
Backend, Context, Encoder, Kernels, gpu_types::HadamardTransformOrder, kernel::HadamardTransformKernel,
},
+ tests::helpers::{alloc_allocation_with_data, allocation_to_vec},
};
const BLOCK_SIZE: usize = 32;
@@ -108,21 +109,14 @@ fn run_kernel<T: ArrayElement + Float, B: Backend>(input: &TestInput<T>) -> Vec<
)
.expect("Failed to create HadamardTransformKernel");
- let total_elements = input.batch_count * input.channel_count;
- let mut data = context.create_array_from(&[total_elements], &input.data).into_allocation();
- let factors_array = context.create_array_from::<i32>(&[input.channel_count], &input.factors);
+ let mut data = alloc_allocation_with_data::<B, T>(&context, &input.data);
+ let factors_allocation = alloc_allocation_with_data::<B, i32>(&context, &input.factors);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- &mut data,
- factors_array.allocation(),
- input.channel_count as u32,
- input.batch_count as u32,
- &mut encoder,
- );
+ kernel.encode(&mut data, &factors_allocation, input.channel_count as u32, input.batch_count as u32, &mut encoder);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- crate::tests::helpers::allocation_to_vec(&data)
+ allocation_to_vec(&data)
}
fn test_hadamard_transform<T: ArrayElement + Float + Debug>(tolerance: f64) {
diff --git a/crates/backend-uzu/unit/backends/common/kernel/kv_cache_update_test.rs b/crates/backend-uzu/unit/backends/common/kernel/kv_cache_update_test.rs
index 595074ba3..ce3d952e1 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/kv_cache_update_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/kv_cache_update_test.rs
@@ -1,34 +1,42 @@
use std::fmt::{Debug, Display};
use half::{bf16, f16};
+#[cfg(metal_backend)]
+use ndarray::{Array, Array3};
use num_traits::Float;
use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
- common::{Backend, Context, Encoder, Kernels, gpu_types::Swap, kernel::KVCacheUpdateKernel},
+ common::{Backend, Context, Encoder, Kernels, gpu_types::Copy, kernel::KVCacheUpdateKernel},
cpu::Cpu,
},
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation_with_data, allocation_to_vec},
+ },
+};
+#[cfg(metal_backend)]
+use crate::{
+ backends::metal::Metal,
+ data_type::DataType,
+ tests::helpers::{sparse_buffer_create_with, sparse_buffer_read_vec},
};
struct Input<T: ArrayElement + Float> {
keys: Box<[T]>,
values: Box<[T]>,
- swaps: Vec<Swap>,
- num_heads: u32,
- max_sequence_length: u32,
- head_dim: u32,
+ copies: Vec<Copy>,
+ element_dim: u32,
}
fn make_data<T: ArrayElement + Float>(
- num_heads: usize,
max_sequence_length: usize,
- head_dim: usize,
+ element_dim: usize,
) -> (Vec<T>, Vec<T>) {
- let total = num_heads * max_sequence_length * head_dim;
+ let total = max_sequence_length * element_dim;
let mut keys = Vec::with_capacity(total);
let mut values = Vec::with_capacity(total);
for i in 0..total {
@@ -43,34 +51,26 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,
let kernel = <<B as Backend>::Kernels as Kernels>::KVCacheUpdateKernel::new(&context, T::data_type())
.expect("Failed to create KVCacheUpdateKernel");
- let total = input.num_heads as usize * input.max_sequence_length as usize * input.head_dim as usize;
- let mut keys = context.create_array_from(&[total], &input.keys).into_allocation();
- let mut values = context.create_array_from(&[total], &input.values).into_allocation();
+ let mut keys = alloc_allocation_with_data::<B, T>(&context, &input.keys);
+ let mut values = alloc_allocation_with_data::<B, T>(&context, &input.values);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to get encoder");
- kernel.encode(
- &mut keys,
- &mut values,
- &input.swaps,
- input.swaps.len() as u32,
- input.num_heads,
- input.head_dim,
- &mut encoder,
- );
+ kernel.encode(&mut keys, &mut values, &input.copies, input.copies.len() as u32, input.element_dim, &mut encoder);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- (crate::tests::helpers::allocation_to_vec(&keys), crate::tests::helpers::allocation_to_vec(&values))
+ (allocation_to_vec(&keys), allocation_to_vec(&values))
}
-/// Single swap between two different positions.
-fn get_test_data_single_swap<T: ArrayElement + Float>() -> (Input<T>, Vec<T>, Vec<T>) {
+/// Single copy between two different positions.
+fn get_test_data_single_copy<T: ArrayElement + Float>() -> (Input<T>, Vec<T>, Vec<T>) {
let num_heads = 2usize;
let max_sequence_length = 4usize;
let head_dim = 3usize;
+ let element_dim = num_heads * head_dim;
- let (keys, values) = make_data::<T>(num_heads, max_sequence_length, head_dim);
+ let (keys, values) = make_data::<T>(max_sequence_length, element_dim);
- let swaps = vec![Swap {
+ let copies = vec![Copy {
source: 0,
destination: 2,
}];
@@ -78,30 +78,29 @@ fn get_test_data_single_swap<T: ArrayElement + Float>() -> (Input<T>, Vec<T>, Ve
let input = Input {
keys: keys.into_boxed_slice(),
values: values.into_boxed_slice(),
- swaps: swaps.clone(),
- num_heads: num_heads as u32,
- max_sequence_length: max_sequence_length as u32,
- head_dim: head_dim as u32,
+ copies: copies.clone(),
+ element_dim: element_dim as u32,
};
let (expected_keys, expected_values) = get_output::<T, Cpu>(&input);
(input, expected_keys, expected_values)
}
-/// Multiple swaps.
-fn get_test_data_multi_swap<T: ArrayElement + Float>() -> (Input<T>, Vec<T>, Vec<T>) {
+/// Multiple copies.
+fn get_test_data_multi_copy<T: ArrayElement + Float>() -> (Input<T>, Vec<T>, Vec<T>) {
let num_heads = 2usize;
let max_sequence_length = 8usize;
let head_dim = 4usize;
+ let element_dim = num_heads * head_dim;
- let (keys, values) = make_data::<T>(num_heads, max_sequence_length, head_dim);
+ let (keys, values) = make_data::<T>(max_sequence_length, element_dim);
- let swaps = vec![
- Swap {
+ let copies = vec![
+ Copy {
source: 1,
destination: 3,
},
- Swap {
+ Copy {
source: 0,
destination: 5,
},
@@ -110,23 +109,22 @@ fn get_test_data_multi_swap<T: ArrayElement + Float>() -> (Input<T>, Vec<T>, Vec
let input = Input {
keys: keys.into_boxed_slice(),
values: values.into_boxed_slice(),
- swaps: swaps.clone(),
- num_heads: num_heads as u32,
- max_sequence_length: max_sequence_length as u32,
- head_dim: head_dim as u32,
+ copies: copies.clone(),
+ element_dim: element_dim as u32,
};
let (expected_keys, expected_values) = get_output::<T, Cpu>(&input);
(input, expected_keys, expected_values)
}
-/// No swaps — data should remain unchanged.
-fn get_test_data_no_swap<T: ArrayElement + Float>() -> (Input<T>, Vec<T>, Vec<T>) {
+/// No copies — data should remain unchanged.
+fn get_test_data_no_copy<T: ArrayElement + Float>() -> (Input<T>, Vec<T>, Vec<T>) {
let num_heads = 2usize;
let max_sequence_length = 4usize;
let head_dim = 3usize;
+ let element_dim = num_heads * head_dim;
- let (keys, values) = make_data::<T>(num_heads, max_sequence_length, head_dim);
+ let (keys, values) = make_data::<T>(max_sequence_length, element_dim);
let expected_keys = keys.clone();
let expected_values = values.clone();
@@ -134,10 +132,8 @@ fn get_test_data_no_swap<T: ArrayElement + Float>() -> (Input<T>, Vec<T>, Vec<T>
let input = Input {
keys: keys.into_boxed_slice(),
values: values.into_boxed_slice(),
- swaps: vec![],
- num_heads: num_heads as u32,
- max_sequence_length: max_sequence_length as u32,
- head_dim: head_dim as u32,
+ copies: vec![],
+ element_dim: element_dim as u32,
};
(input, expected_keys, expected_values)
@@ -148,19 +144,20 @@ fn get_test_data_large<T: ArrayElement + Float>() -> (Input<T>, Vec<T>, Vec<T>)
let num_heads = 8usize;
let max_sequence_length = 64usize;
let head_dim = 128usize;
+ let element_dim = num_heads * head_dim;
- let (keys, values) = make_data::<T>(num_heads, max_sequence_length, head_dim);
+ let (keys, values) = make_data::<T>(max_sequence_length, element_dim);
- let swaps = vec![
- Swap {
+ let copies = vec![
+ Copy {
source: 0,
destination: 63,
},
- Swap {
+ Copy {
source: 10,
destination: 30,
},
- Swap {
+ Copy {
source: 5,
destination: 20,
},
@@ -169,10 +166,8 @@ fn get_test_data_large<T: ArrayElement + Float>() -> (Input<T>, Vec<T>, Vec<T>)
let input = Input {
keys: keys.into_boxed_slice(),
values: values.into_boxed_slice(),
- swaps: swaps.clone(),
- num_heads: num_heads as u32,
- max_sequence_length: max_sequence_length as u32,
- head_dim: head_dim as u32,
+ copies: copies.clone(),
+ element_dim: element_dim as u32,
};
let (expected_keys, expected_values) = get_output::<T, Cpu>(&input);
@@ -195,19 +190,19 @@ fn test_internal<T: ArrayElement + Float + Debug + Display>(
});
}
-fn test_single_swap_internal<T: ArrayElement + Float + Debug + Display>() {
- let (input, expected_keys, expected_values) = get_test_data_single_swap::<T>();
- test_internal::<T>(&input, &expected_keys, &expected_values, "single_swap");
+fn test_single_copy_internal<T: ArrayElement + Float + Debug + Display>() {
+ let (input, expected_keys, expected_values) = get_test_data_single_copy::<T>();
+ test_internal::<T>(&input, &expected_keys, &expected_values, "single_copy");
}
-fn test_multi_swap_internal<T: ArrayElement + Float + Debug + Display>() {
- let (input, expected_keys, expected_values) = get_test_data_multi_swap::<T>();
- test_internal::<T>(&input, &expected_keys, &expected_values, "multi_swap");
+fn test_multi_copy_internal<T: ArrayElement + Float + Debug + Display>() {
+ let (input, expected_keys, expected_values) = get_test_data_multi_copy::<T>();
+ test_internal::<T>(&input, &expected_keys, &expected_values, "multi_copy");
}
-fn test_no_swap_internal<T: ArrayElement + Float + Debug + Display>() {
- let (input, expected_keys, expected_values) = get_test_data_no_swap::<T>();
- test_internal::<T>(&input, &expected_keys, &expected_values, "no_swap");
+fn test_no_copy_internal<T: ArrayElement + Float + Debug + Display>() {
+ let (input, expected_keys, expected_values) = get_test_data_no_copy::<T>();
+ test_internal::<T>(&input, &expected_keys, &expected_values, "no_copy");
}
fn test_large_internal<T: ArrayElement + Float + Debug + Display>() {
@@ -215,52 +210,52 @@ fn test_large_internal<T: ArrayElement + Float + Debug + Display>() {
test_internal::<T>(&input, &expected_keys, &expected_values, "large");
}
-// Single swap tests
+// Single copy tests
#[uzu_test]
-fn test_single_swap_f32() {
- test_single_swap_internal::<f32>();
+fn test_single_copy_f32() {
+ test_single_copy_internal::<f32>();
}
#[uzu_test]
-fn test_single_swap_f16() {
- test_single_swap_internal::<f16>();
+fn test_single_copy_f16() {
+ test_single_copy_internal::<f16>();
}
#[uzu_test]
-fn test_single_swap_bf16() {
- test_single_swap_internal::<bf16>();
+fn test_single_copy_bf16() {
+ test_single_copy_internal::<bf16>();
}
-// Multi swap tests
+// Multi copy tests
#[uzu_test]
-fn test_multi_swap_f32() {
- test_multi_swap_internal::<f32>();
+fn test_multi_copy_f32() {
+ test_multi_copy_internal::<f32>();
}
#[uzu_test]
-fn test_multi_swap_f16() {
- test_multi_swap_internal::<f16>();
+fn test_multi_copy_f16() {
+ test_multi_copy_internal::<f16>();
}
#[uzu_test]
-fn test_multi_swap_bf16() {
- test_multi_swap_internal::<bf16>();
+fn test_multi_copy_bf16() {
+ test_multi_copy_internal::<bf16>();
}
-// No swap tests
+// No copy tests
#[uzu_test]
-fn test_no_swap_f32() {
- test_no_swap_internal::<f32>();
+fn test_no_copy_f32() {
+ test_no_copy_internal::<f32>();
}
#[uzu_test]
-fn test_no_swap_f16() {
- test_no_swap_internal::<f16>();
+fn test_no_copy_f16() {
+ test_no_copy_internal::<f16>();
}
#[uzu_test]
-fn test_no_swap_bf16() {
- test_no_swap_internal::<bf16>();
+fn test_no_copy_bf16() {
+ test_no_copy_internal::<bf16>();
}
// Large dimension tests
@@ -278,3 +273,115 @@ fn test_large_f16() {
fn test_large_bf16() {
test_large_internal::<bf16>();
}
+
+#[cfg(metal_backend)]
+fn apply_copies_3d<T: Clone>(
+ array: &mut Array3<T>,
+ copies: &[Copy],
+) {
+ let (_seq_len, num_heads, head_dim) = array.dim();
+ for head in 0..num_heads {
+ for channel in 0..head_dim {
+ for copy in copies {
+ let src = copy.source as usize;
+ let dst = copy.destination as usize;
+ array[(dst, head, channel)] = array[(src, head, channel)].clone();
+ }
+ }
+ }
+}
+
+#[cfg(metal_backend)]
+#[uzu_test]
+fn test_sparse_random_pattern_f32() {
+ let context = match <Metal as Backend>::Context::new() {
+ Ok(context) => context,
+ Err(error) => {
+ eprintln!("Failed to create Metal context: {error:?}. Skipping test.");
+ return;
+ },
+ };
+
+ let kernel = <<Metal as Backend>::Kernels as Kernels>::KVCacheUpdateKernel::new(&context, DataType::F32)
+ .expect("Failed to create KVCacheUpdateKernel");
+
+ let num_heads = 3usize;
+ let seq_len = 15usize;
+ let head_dim = 7usize;
+ let element_dim = num_heads * head_dim;
+
+ let key_data = Array3::<f32>::from_shape_fn((seq_len, num_heads, head_dim), |(token, head, channel)| {
+ (token * 1_000_000 + head * 100 + channel * 10) as f32
+ });
+
+ let value_data = Array3::<f32>::from_shape_fn((seq_len, num_heads, head_dim), |(token, head, channel)| {
+ (token * 1_000_000 + head * 100 + channel * 10 + 1_000) as f32
+ });
+
+ let copies = vec![
+ Copy {
+ source: 0,
+ destination: 14,
+ },
+ Copy {
+ source: 3,
+ destination: 11,
+ },
+ Copy {
+ source: 6,
+ destination: 8,
+ },
+ Copy {
+ source: 9,
+ destination: 5,
+ },
+ Copy {
+ source: 12,
+ destination: 2,
+ },
+ Copy {
+ source: 2,
+ destination: 12,
+ },
+ Copy {
+ source: 5,
+ destination: 9,
+ },
+ Copy {
+ source: 8,
+ destination: 6,
+ },
+ Copy {
+ source: 11,
+ destination: 3,
+ },
+ Copy {
+ source: 14,
+ destination: 0,
+ },
+ ];
+
+ let mut expected_keys = key_data.clone();
+ let mut expected_values = value_data.clone();
+ apply_copies_3d(&mut expected_keys, &copies);
+ apply_copies_3d(&mut expected_values, &copies);
+
+ let mut key_buffer = sparse_buffer_create_with::<Metal, f32>(&context, key_data.as_slice().unwrap());
+ let mut value_buffer = sparse_buffer_create_with::<Metal, f32>(&context, value_data.as_slice().unwrap());
+
+ let mut encoder = Encoder::<Metal>::new(&context).unwrap();
+ kernel.encode(&mut key_buffer, &mut value_buffer, &copies, copies.len() as u32, element_dim as u32, &mut encoder);
+ encoder.end_encoding().submit().wait_until_completed().unwrap();
+
+ let elements_count = seq_len * num_heads * head_dim;
+ let key_values: Vec<f32> = sparse_buffer_read_vec::<Metal, f32>(&context, &key_buffer, elements_count);
+ let key_result = Array::from_shape_vec((seq_len, num_heads, head_dim), key_values)
+ .expect("Failed to convert key result to ndarray");
+
+ let value_values: Vec<f32> = sparse_buffer_read_vec::<Metal, f32>(&context, &value_buffer, elements_count);
+ let value_result = Array::from_shape_vec((seq_len, num_heads, head_dim), value_values)
+ .expect("Failed to convert value result to ndarray");
+
+ assert_eq!(key_result, expected_keys);
+ assert_eq!(value_result, expected_values);
+}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/layer_norm_test.rs b/crates/backend-uzu/unit/backends/common/kernel/layer_norm_test.rs
deleted file mode 100644
index cbbe58505..000000000
--- a/crates/backend-uzu/unit/backends/common/kernel/layer_norm_test.rs
+++ /dev/null
@@ -1,311 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::uzu_test;
-use test_runner::for_each_non_cpu_backend;
-
-use crate::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{Backend, Context, Encoder, Kernels, kernel::LayerNormKernel},
- cpu::Cpu,
- },
- data_type::DataType,
- tests::assert::assert_eq_float,
-};
-
-static BOOL_ALL: &[bool] = &[true, false];
-static BOOL_FALSE: &[bool] = &[false];
-
-struct Input<IN: ArrayElement + Float, SC: ArrayElement + Float, OUT: ArrayElement + Float> {
- input: Box<[IN]>,
- scales: Box<[SC]>,
- output: Box<[OUT]>,
- batch_size: u32,
- model_dim: u32,
- epsilon: f32,
- scale_offset: f32,
- full_layer: u32,
- in_place: bool,
-}
-
-fn get_test_data_basic<
- IN: ArrayElement + Float,
- SC: ArrayElement + Float,
- OUT: ArrayElement + Float,
- ACC: ArrayElement + Float,
->(
- full_layer: u32,
- in_place: bool,
-) -> (Input<IN, SC, OUT>, Vec<OUT>) {
- let batch_size = 2usize;
- let model_dim = 4096usize;
- let epsilon = 1e-5f32;
- let scale_offset = 0.123f32;
-
- let total = batch_size * model_dim;
- let mut input_data: Vec<IN> = vec![IN::zero(); total];
- let mut output_data: Vec<OUT> = vec![OUT::zero(); total];
- let scales_data: Vec<SC> = (0..model_dim).map(|i| SC::from(1.0 + 0.01 * (i as f32).sin()).unwrap()).collect();
-
- for i in 0..total {
- let val = 2.0 * f32::sin(i as f32 * 0.01) + 0.1 * (i as f32 / total as f32);
- input_data[i] = IN::from(val).unwrap();
- output_data[i] = OUT::from(val).unwrap();
- }
-
- let input = Input::<IN, SC, OUT> {
- input: input_data.into_boxed_slice(),
- scales: scales_data.into_boxed_slice(),
- output: output_data.into_boxed_slice(),
- batch_size: batch_size as u32,
- model_dim: model_dim as u32,
- epsilon,
- scale_offset,
- full_layer,
- in_place,
- };
-
- let output = get_output::<Cpu, IN, SC, OUT, ACC>(&input);
- (input, output)
-}
-
-fn get_test_data_edge<
- IN: ArrayElement + Float,
- SC: ArrayElement + Float,
- OUT: ArrayElement + Float,
- ACC: ArrayElement + Float,
->(
- full_layer: u32,
- in_place: bool,
-) -> (Input<IN, SC, OUT>, Vec<OUT>) {
- let batch_size = 1usize;
- let model_dim = 4usize;
- let epsilon = 1e-6f32;
- let scale_offset = 0.0f32;
-
- let input_data_f32: Vec<f32> = vec![1.0, -2.0, 3.0, -4.0];
- let scales_data_f32: Vec<f32> = vec![2.0, 0.5, 1.5, 0.8];
- let input_data: Vec<IN> = input_data_f32.iter().map(|&x| IN::from(x).unwrap()).collect();
- let output_data: Vec<OUT> = input_data_f32.iter().map(|&x| OUT::from(x).unwrap()).collect();
- let scales_data: Vec<SC> = scales_data_f32.iter().map(|&x| SC::from(x).unwrap()).collect();
-
- let input = Input::<IN, SC, OUT> {
- input: input_data.into_boxed_slice(),
- scales: scales_data.into_boxed_slice(),
- output: output_data.into_boxed_slice(),
- batch_size: batch_size as u32,
- model_dim: model_dim as u32,
- epsilon,
- scale_offset,
- full_layer,
- in_place,
- };
-
- let output = get_output::<Cpu, IN, SC, OUT, ACC>(&input);
- (input, output)
-}
-
-fn get_output<
- B: Backend,
- IN: ArrayElement + Float,
- SC: ArrayElement + Float,
- OUT: ArrayElement + Float,
- ACC: ArrayElement + Float,
->(
- input: &Input<IN, SC, OUT>
-) -> Vec<OUT> {
- let context = B::Context::new().expect("Failed to create Context");
- let kernel = <<B as Backend>::Kernels as Kernels>::LayerNormKernel::new(
- &context,
- IN::data_type(),
- SC::data_type(),
- OUT::data_type(),
- ACC::data_type(),
- input.in_place,
- )
- .expect("Failed to create LayerNormKernel");
-
- let input_size = input.input.len();
- let input_buffer =
- (!input.in_place).then(|| context.create_array_from(&[input_size], &input.input).into_allocation());
-
- let scales_array = context.create_array_from(&[input.scales.len()], &input.scales);
- let mut output = match input.in_place {
- true => context.create_array_from(&[input_size], &input.output).into_allocation(),
- false => context.create_array_uninitialized(&[input_size], OUT::data_type()).into_allocation(),
- };
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- input_buffer.as_ref(),
- scales_array.allocation(),
- &mut output,
- input.batch_size,
- input.model_dim,
- input.epsilon,
- input.scale_offset,
- input.full_layer,
- &mut encoder,
- );
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- crate::tests::helpers::allocation_to_vec(&output)
-}
-
-fn test_internal<
- IN: ArrayElement + Float,
- SC: ArrayElement + Float,
- OUT: ArrayElement + Float + Debug + Display,
- ACC: ArrayElement + Float,
->(
- input: &Input<IN, SC, OUT>,
- expected: &[OUT],
-) {
- let eps = if matches!(IN::data_type(), DataType::F16 | DataType::BF16)
- || matches!(SC::data_type(), DataType::F16 | DataType::BF16)
- || matches!(OUT::data_type(), DataType::F16 | DataType::BF16)
- {
- 0.012f32
- } else {
- 1e-5
- };
-
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<B, IN, SC, OUT, ACC>(input);
- let msg = format!(
- "LayerNorm kernel test failed with backend={}, full_layer={}, in_place={}",
- std::any::type_name::<B>(),
- input.full_layer,
- input.in_place,
- );
- assert_eq_float::<OUT>(expected, &output, eps, &msg);
- });
-}
-
-fn test_basic<
- IN: ArrayElement + Float,
- SC: ArrayElement + Float,
- OUT: ArrayElement + Float + Debug + Display,
- ACC: ArrayElement + Float,
->() {
- let in_place_values: &[bool] = if IN::data_type() == OUT::data_type() {
- BOOL_ALL
- } else {
- BOOL_FALSE
- };
-
- for in_place in in_place_values {
- for full_layer in [1u32, 0u32] {
- let (input, expected) = get_test_data_basic::<IN, SC, OUT, ACC>(full_layer, *in_place);
- test_internal::<IN, SC, OUT, ACC>(&input, expected.as_slice())
- }
- }
-}
-
-fn test_edge<
- IN: ArrayElement + Float,
- SC: ArrayElement + Float,
- OUT: ArrayElement + Float + Debug + Display,
- ACC: ArrayElement + Float,
->() {
- let in_place_values: &[bool] = if IN::data_type() == OUT::data_type() {
- BOOL_ALL
- } else {
- BOOL_FALSE
- };
-
- for in_place in in_place_values {
- let (input, expected) = get_test_data_edge::<IN, SC, OUT, ACC>(0, *in_place);
- test_internal::<IN, SC, OUT, ACC>(&input, expected.as_slice())
- }
-}
-
-// basic tests - AccumT f32
-#[uzu_test]
-fn test_f32_f32_f32_f32() {
- test_basic::<f32, f32, f32, f32>();
-}
-
-#[uzu_test]
-fn test_f16_f32_f32_f32() {
- test_basic::<f16, f32, f32, f32>();
-}
-
-#[uzu_test]
-fn test_f32_f16_f32_f32() {
- test_basic::<f32, f16, f32, f32>();
-}
-
-#[uzu_test]
-fn test_f32_f32_f16_f32() {
- test_basic::<f32, f32, f16, f32>();
-}
-
-#[uzu_test]
-fn test_f16_f16_f32_f32() {
- test_basic::<f16, f16, f32, f32>();
-}
-
-#[uzu_test]
-fn test_f16_f32_f16_f32() {
- test_basic::<f16, f32, f16, f32>();
-}
-
-#[uzu_test]
-fn test_f32_f16_f16_f32() {
- test_basic::<f32, f16, f16, f32>();
-}
-
-#[uzu_test]
-fn test_f16_f16_f16_f32() {
- test_basic::<f16, f16, f16, f32>();
-}
-
-// basic tests - AccumT f32 + bf16
-#[uzu_test]
-fn test_bf16_f32_f32_f32() {
- test_basic::<bf16, f32, f32, f32>();
-}
-
-#[uzu_test]
-fn test_f32_bf16_f32_f32() {
- test_basic::<f32, bf16, f32, f32>();
-}
-
-#[uzu_test]
-fn test_f32_f32_bf16_f32() {
- test_basic::<f32, f32, bf16, f32>();
-}
-
-#[uzu_test]
-fn test_bf16_bf16_f32_f32() {
- test_basic::<bf16, bf16, f32, f32>();
-}
-
-#[uzu_test]
-fn test_bf16_f32_bf16_f32() {
- test_basic::<bf16, f32, bf16, f32>();
-}
-
-#[uzu_test]
-fn test_bf16_bf16_bf16_f32() {
- test_basic::<bf16, bf16, bf16, f32>();
-}
-
-// edge tests
-#[uzu_test]
-fn test_edge_f32_f32_f32_f32() {
- test_edge::<f32, f32, f32, f32>();
-}
-
-#[uzu_test]
-fn test_edge_f32_f16_f16_f32() {
- test_edge::<f32, f16, f16, f32>();
-}
-
-#[uzu_test]
-fn test_edge_f16_f16_f16_f32() {
- test_edge::<f16, f16, f16, f32>();
-}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/matmul/gemm_bench.rs b/crates/backend-uzu/unit/backends/common/kernel/matmul/gemm_bench.rs
index 1d794105f..49d66ab7d 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/matmul/gemm_bench.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/matmul/gemm_bench.rs
@@ -5,10 +5,10 @@ use half::bf16;
use proc_macros::uzu_bench;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{
- AllocationType, Backend, Context,
+ Backend,
kernel::{
Kernels,
matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},
@@ -17,6 +17,7 @@ use crate::{
metal::{GemmDispatchPath, Metal},
},
tests::{
+ helpers::alloc_allocation,
matmul::{bench_fp_gemm_shapes, iter_encode_loop},
util::type_short_name,
},
@@ -44,13 +45,9 @@ fn bench_gemm(c: &mut Criterion) {
for shape in bench_fp_gemm_shapes() {
let (m, k, n) = (shape.m, shape.k, shape.n);
- let a = context
- .create_allocation(m * k * std::mem::size_of::<bf16>(), AllocationType::Global)
- .expect("a allocation");
- let b_array = context.create_array_uninitialized(&[n, k], bf16::data_type());
- let mut d = context
- .create_allocation(m * n * std::mem::size_of::<bf16>(), AllocationType::Global)
- .expect("d allocation");
+ let a = alloc_allocation::<Metal, bf16>(&context, m * k);
+ let b_weights = alloc_allocation::<Metal, bf16>(&context, n * k);
+ let mut d = alloc_allocation::<Metal, bf16>(&context, m * n);
group.throughput(Throughput::Elements((2 * m * k * n) as u64));
group.bench_function(BenchmarkId::new("BF16", shape.to_string()), |b| {
@@ -62,9 +59,8 @@ fn bench_gemm(c: &mut Criterion) {
a: &a,
a_offset: 0,
b: MatmulB::FullPrecision {
- b: b_array.allocation(),
+ b: &b_weights,
},
- b_offset: 0,
b_leading_dimension: None,
b_transpose: true,
d: &mut d,
diff --git a/crates/backend-uzu/unit/backends/common/kernel/matmul/gemv_test.rs b/crates/backend-uzu/unit/backends/common/kernel/matmul/gemv_test.rs
index 85de32dcc..d383f063d 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/matmul/gemv_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/matmul/gemv_test.rs
@@ -7,10 +7,10 @@ use rstest::rstest;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{
- AllocationType, Backend, Context, Encoder,
+ Backend, Context, Encoder,
kernel::{
Kernels,
matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},
@@ -20,7 +20,7 @@ use crate::{
},
tests::{
assert::assert_eq_float,
- helpers::{alloc_allocation_with_data, allocation_to_vec},
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
},
};
@@ -59,11 +59,9 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
let k = input.k as u32;
let n = input.n as u32;
- let b_array = context.create_array_from(&[input.n, input.k], &input.b);
+ let b_allocation = alloc_allocation_with_data::<B, T>(&context, &input.b);
let a_allocation = alloc_allocation_with_data::<B, T>(&context, &input.a);
- let mut d_allocation = context
- .create_allocation(input.m * input.n * std::mem::size_of::<T>(), AllocationType::Global)
- .expect("Failed to create allocation");
+ let mut d_allocation = alloc_allocation::<B, T>(&context, input.m * input.n);
let mut kernel =
<B::Kernels as Kernels>::MatmulKernel::new(&context, T::data_type(), T::data_type(), T::data_type())
@@ -76,9 +74,8 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
a: &a_allocation,
a_offset: 0,
b: MatmulB::FullPrecision {
- b: b_array.allocation(),
+ b: &b_allocation,
},
- b_offset: 0,
b_leading_dimension: None,
b_transpose: true,
d: &mut d_allocation,
diff --git a/crates/backend-uzu/unit/backends/common/kernel/matmul/quant_dispatch_test.rs b/crates/backend-uzu/unit/backends/common/kernel/matmul/quant_dispatch_test.rs
index 2774faf21..2b336c65f 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/matmul/quant_dispatch_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/matmul/quant_dispatch_test.rs
@@ -427,40 +427,6 @@ fn parity_bf16_gemv_quant_rht() {
assert_parity::<bf16>("gemv_quant_rht", &reference, &actual, 0.05, 0.6);
}
-#[uzu_test]
-fn quant_gemm_nonzero_b_offset_returns_unsupported_layout() {
- let context = MetalContext::new().expect("Metal context");
- let input = QuantInput::<bf16>::new(64, 256, 64, 32, 4, QuantizationMethod::ScaleBias, 0);
- let mut buffers = QuantBuffers::<Metal, bf16>::allocate(&context, &input);
- let mut matmul = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel::new(
- &context,
- bf16::data_type(),
- bf16::data_type(),
- bf16::data_type(),
- )
- .expect("MatmulMetalKernel");
-
- let mut encoder = Encoder::<Metal>::new(&context).expect("encoder");
- let mut args = quant_arguments(&mut buffers, &input);
- args.b_offset = 16;
- let result = matmul.encode(args, &mut encoder);
-
- let err = result.expect_err("expected error");
- let matmul: &MatmulError<Metal> = (&err as &dyn StdError)
- .source()
- .and_then(|s| s.downcast_ref::<MatmulError<Metal>>())
- .expect("expected MatmulError source");
- assert!(
- matches!(
- matmul,
- MatmulError::UnsupportedLayout {
- path: "QuantGemm"
- }
- ),
- "got {matmul:?}"
- );
-}
-
#[uzu_test]
fn quant_gemm_accumulate_returns_unsupported_dop() {
let context = MetalContext::new().expect("Metal context");
diff --git a/crates/backend-uzu/unit/backends/common/kernel/mod.rs b/crates/backend-uzu/unit/backends/common/kernel/mod.rs
index df6ce3c0d..c5090f69c 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/mod.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/mod.rs
@@ -1,6 +1,5 @@
mod activation_test;
mod attention;
-mod audio;
mod delta_net_test;
mod embedding;
mod gated_act_mul_test;
@@ -8,7 +7,6 @@ mod gram_bench;
mod gram_test;
mod hadamard_transform_test;
mod kv_cache_update_test;
-mod layer_norm_test;
mod logit_soft_cap_test;
mod matmul;
mod moe;
@@ -17,11 +15,7 @@ mod out_test;
mod pooling;
mod prefix_beta_bench;
mod prefix_beta_test;
-mod qk_unpack_test;
mod qkv_norm_test;
-mod rms_norm_bench;
-mod rms_norm_test;
-mod rope_test;
mod short_conv;
mod ssm;
mod tensor_add_bias_test;
diff --git a/crates/backend-uzu/unit/backends/common/kernel/moe/mod.rs b/crates/backend-uzu/unit/backends/common/kernel/moe/mod.rs
index ec94c9afb..82c2e9a28 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/moe/mod.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/moe/mod.rs
@@ -1,4 +1,3 @@
mod moe_counts_offsets_fused_test;
mod moe_finalize_test;
mod moe_router_topk_test;
-mod moe_scatter_test;
diff --git a/crates/backend-uzu/unit/backends/common/kernel/moe/moe_counts_offsets_fused_test.rs b/crates/backend-uzu/unit/backends/common/kernel/moe/moe_counts_offsets_fused_test.rs
index 48441d722..e97eebf8b 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/moe/moe_counts_offsets_fused_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/moe/moe_counts_offsets_fused_test.rs
@@ -3,11 +3,11 @@ use rand::{RngExt, SeedableRng, rngs::StdRng};
use test_runner::{for_each_backend, for_each_non_cpu_backend};
use crate::{
- array::{ArrayContextExt, ArrayElement},
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::MoeCountsOffsetsFusedKernel},
cpu::Cpu,
},
+ tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_prefix_to_vec, allocation_to_vec},
};
fn gen_random_topk_ids(
@@ -38,19 +38,19 @@ fn get_output<B: Backend>(
.expect("Failed to create MoeCountsOffsetsFusedKernel");
let topk_ids_len = (t * k).max(1);
- let topk_ids_array = if topk_ids.is_empty() {
- context.create_array_uninitialized(&[topk_ids_len], i32::data_type())
+ let topk_ids_allocation = if topk_ids.is_empty() {
+ alloc_allocation::<B, i32>(&context, topk_ids_len)
} else {
- context.create_array_from(&[topk_ids_len], topk_ids)
+ alloc_allocation_with_data::<B, i32>(&context, topk_ids)
};
- let mut offsets = context.create_array_uninitialized(&[e + 1], u32::data_type()).into_allocation();
- let mut sum_k = context.create_array_uninitialized(&[1], u32::data_type()).into_allocation();
+ let mut offsets = alloc_allocation::<B, u32>(&context, e + 1);
+ let mut sum_k = alloc_allocation::<B, u32>(&context, 1);
let num_tiles = e.div_ceil(512).max(1);
- let mut partials = context.create_array_uninitialized(&[num_tiles * 512], u32::data_type()).into_allocation();
+ let mut partials = alloc_allocation::<B, u32>(&context, num_tiles * 512);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- topk_ids_array.allocation(),
+ &topk_ids_allocation,
&mut offsets,
&mut sum_k,
&mut partials,
@@ -61,9 +61,9 @@ fn get_output<B: Backend>(
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- let offsets = crate::tests::helpers::allocation_to_vec::<B, u32>(&offsets);
- let sum_k = crate::tests::helpers::allocation_to_vec::<B, u32>(&sum_k)[0];
- let partials = crate::tests::helpers::allocation_prefix_to_vec::<B, u32>(&partials, e);
+ let offsets = allocation_to_vec::<B, u32>(&offsets);
+ let sum_k = allocation_to_vec::<B, u32>(&sum_k)[0];
+ let partials = allocation_prefix_to_vec::<B, u32>(&partials, e);
(offsets, sum_k, partials)
}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/moe/moe_finalize_test.rs b/crates/backend-uzu/unit/backends/common/kernel/moe/moe_finalize_test.rs
index 4bf2ff740..d4c676a4a 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/moe/moe_finalize_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/moe/moe_finalize_test.rs
@@ -5,13 +5,16 @@ use rand::{RngExt, SeedableRng, rngs::StdRng};
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Backend, Encoder, Kernels, kernel::MoeFinalizeKernel},
cpu::Cpu,
},
data_type::DataType,
- tests::{assert::assert_eq_float, helpers::create_context},
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, create_context},
+ },
};
struct Input<T: ArrayElement + Float> {
@@ -25,17 +28,17 @@ struct Input<T: ArrayElement + Float> {
fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {
let context = create_context::<B>();
- let tok2row_array = context.create_array_from(&[input.tok2row.len()], &input.tok2row);
- let probs_array = context.create_array_from(&[input.probs.len()], &input.probs);
- let y_partial_array = context.create_array_from(&[input.y_partial.len()], &input.y_partial);
- let mut y_out = context.create_array_uninitialized(&[input.t * input.d_model], T::data_type()).into_allocation();
+ let tok2row = alloc_allocation_with_data::<B, i32>(&context, &input.tok2row);
+ let probs = alloc_allocation_with_data::<B, T>(&context, &input.probs);
+ let y_partial = alloc_allocation_with_data::<B, T>(&context, &input.y_partial);
+ let mut y_out = alloc_allocation::<B, T>(&context, input.t * input.d_model);
let finalize = <B::Kernels as Kernels>::MoeFinalizeKernel::new(&context, DataType::BF16).expect("finalize kernel");
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
finalize.encode(
- tok2row_array.allocation(),
- probs_array.allocation(),
- y_partial_array.allocation(),
+ &tok2row,
+ &probs,
+ &y_partial,
&mut y_out,
input.t as u32,
input.d_model as u32,
@@ -44,7 +47,7 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- crate::tests::helpers::allocation_to_vec(&y_out)
+ allocation_to_vec(&y_out)
}
fn test_finalize_internal(
diff --git a/crates/backend-uzu/unit/backends/common/kernel/moe/moe_router_topk_test.rs b/crates/backend-uzu/unit/backends/common/kernel/moe/moe_router_topk_test.rs
index 2c1fb4869..40e6c1cba 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/moe/moe_router_topk_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/moe/moe_router_topk_test.rs
@@ -7,13 +7,12 @@ use rand::{RngExt, SeedableRng, rngs::StdRng};
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Backend, Encoder, Kernels, kernel::MoeRouterTopKKernel},
cpu::Cpu,
},
- data_type::DataType,
- tests::helpers::create_context,
+ tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, create_context},
};
#[derive(Copy, Clone, Debug)]
@@ -39,33 +38,33 @@ fn get_output<B: Backend, T: ArrayElement + Float>(
) -> (Vec<i32>, Vec<T>) {
let ctx = create_context::<B>();
- let input_array = ctx.create_array_from(&[input.len()], input);
- let weights_array = ctx.create_array_from(&[weights.len()], weights);
- let bias_array = bias.map(|bias| ctx.create_array_from(&[bias.len()], bias));
- let router_scale_array =
- router_scale.map(|router_scale| ctx.create_array_from(&[router_scale.len()], router_scale));
- let per_expert_scale_array =
- per_expert_scale.map(|per_expert_scale| ctx.create_array_from(&[per_expert_scale.len()], per_expert_scale));
- let mut ids = ctx.create_array_uninitialized(&[t * k], DataType::I32).into_allocation();
- let mut probs = ctx.create_array_uninitialized(&[t * k], T::data_type()).into_allocation();
+ let input_allocation = alloc_allocation_with_data::<B, T>(&ctx, input);
+ let weights_allocation = alloc_allocation_with_data::<B, T>(&ctx, weights);
+ let bias_allocation = bias.map(|bias| alloc_allocation_with_data::<B, T>(&ctx, bias));
+ let router_scale_allocation =
+ router_scale.map(|router_scale| alloc_allocation_with_data::<B, T>(&ctx, router_scale));
+ let per_expert_scale_allocation =
+ per_expert_scale.map(|per_expert_scale| alloc_allocation_with_data::<B, T>(&ctx, per_expert_scale));
+ let mut ids = alloc_allocation::<B, i32>(&ctx, t * k);
+ let mut probs = alloc_allocation::<B, T>(&ctx, t * k);
let kernel = <<B as Backend>::Kernels as Kernels>::MoeRouterTopKKernel::new(
&ctx,
T::data_type(),
- bias_array.is_some(),
- router_scale_array.is_some(),
- per_expert_scale_array.is_some(),
+ bias_allocation.is_some(),
+ router_scale_allocation.is_some(),
+ per_expert_scale_allocation.is_some(),
router_input_scale.is_some(),
router_norm_epsilon.is_some(),
)
.expect("kernel");
let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");
kernel.encode(
- input_array.allocation(),
- weights_array.allocation(),
- bias_array.as_ref().map(|bias| bias.allocation()),
- router_scale_array.as_ref().map(|router_scale| router_scale.allocation()),
- per_expert_scale_array.as_ref().map(|per_expert_scale| per_expert_scale.allocation()),
+ &input_allocation,
+ &weights_allocation,
+ bias_allocation.as_ref(),
+ router_scale_allocation.as_ref(),
+ per_expert_scale_allocation.as_ref(),
&mut ids,
&mut probs,
t as u32,
@@ -79,7 +78,7 @@ fn get_output<B: Backend, T: ArrayElement + Float>(
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- (crate::tests::helpers::allocation_to_vec(&ids), crate::tests::helpers::allocation_to_vec(&probs))
+ (allocation_to_vec(&ids), allocation_to_vec(&probs))
}
fn run_router_topk_once<B: Backend, T: ArrayElement + Debug + Float>(
diff --git a/crates/backend-uzu/unit/backends/common/kernel/moe/moe_scatter_test.rs b/crates/backend-uzu/unit/backends/common/kernel/moe/moe_scatter_test.rs
deleted file mode 100644
index 2021b19c1..000000000
--- a/crates/backend-uzu/unit/backends/common/kernel/moe/moe_scatter_test.rs
+++ /dev/null
@@ -1,247 +0,0 @@
-use half::bf16;
-use num_traits::Float;
-use proc_macros::uzu_test;
-use rand::{RngExt, SeedableRng, rngs::StdRng};
-use test_runner::for_each_non_cpu_backend;
-
-use crate::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{
- Allocation, Backend, Encoder, Kernels,
- kernel::{
- MoeBlockBasesFromPartialsKernel, MoeCountsOffsetsFusedKernel, MoeRouterTopKKernel,
- MoeScatterBucketsKernel,
- },
- },
- cpu::Cpu,
- },
- data_type::DataType,
- tests::helpers::create_context,
-};
-
-fn cpu_expert_buckets<T: ArrayElement + Float>(
- topk_ids: &[i32],
- topk_probs: &[T],
- t: usize,
- e: usize,
- k: usize,
-) -> (Vec<i32>, Vec<T>, Vec<u32>) {
- let mut per_e: Vec<Vec<(i32, T)>> = vec![Vec::new(); e];
- for ti in 0..t {
- for kk in 0..k {
- let id = topk_ids[ti * k + kk];
- if id >= 0 {
- let ue = id as usize;
- if ue < e {
- per_e[ue].push((ti as i32, topk_probs[ti * k + kk]));
- }
- }
- }
- }
- let mut offsets = Vec::with_capacity(e + 1);
- offsets.push(0u32);
- for ei in 0..e {
- offsets.push(offsets[ei] + per_e[ei].len() as u32);
- }
- let sumk = *offsets.last().unwrap() as usize;
- let mut ids = vec![0i32; sumk];
- let mut probs = vec![T::zero(); sumk];
- for ei in 0..e {
- let mut entries = per_e[ei].clone();
- entries.sort_by_key(|&(id, _)| id);
- let start = offsets[ei] as usize;
- for (i, (id, p)) in entries.into_iter().enumerate() {
- ids[start + i] = id;
- probs[start + i] = p;
- }
- }
- (ids, probs, offsets)
-}
-
-fn get_output_topk<B: Backend, T: ArrayElement + Float>(
- ctx: &B::Context,
- input: &[T],
- weights: &[T],
- bias: &[T],
- t: usize,
- d_model: usize,
- e: usize,
- k: usize,
-) -> (Allocation<B>, Allocation<B>) {
- let input_array = ctx.create_array_from(&[input.len()], input);
- let weights_array = ctx.create_array_from(&[weights.len()], weights);
- let bias_array = ctx.create_array_from(&[bias.len()], bias);
- let mut topk_ids = ctx.create_array_uninitialized(&[t * k], DataType::I32).into_allocation();
- let mut topk_probs = ctx.create_array_uninitialized(&[t * k], T::data_type()).into_allocation();
-
- let topk_kernel = <<B as Backend>::Kernels as Kernels>::MoeRouterTopKKernel::new(
- ctx,
- T::data_type(),
- true,
- false,
- false,
- false,
- false,
- )
- .expect("router_topk");
- let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");
- topk_kernel.encode(
- input_array.allocation(),
- weights_array.allocation(),
- Some(bias_array.allocation()),
- None::<&Allocation<B>>,
- None::<&Allocation<B>>,
- &mut topk_ids,
- &mut topk_probs,
- t as u32,
- d_model as u32,
- e as u32,
- k as u32,
- true,
- None::<f32>,
- None::<f32>,
- &mut encoder,
- );
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- (topk_ids, topk_probs)
-}
-
-fn get_output<B: Backend, T: ArrayElement + Float>(
- input: &[T],
- weights: &[T],
- bias: &[T],
- t: usize,
- d_model: usize,
- e: usize,
- k: usize,
-) -> (Vec<i32>, Vec<T>, Vec<u32>) {
- let ctx = create_context::<B>();
-
- // top-k
- let (topk_ids, topk_probs) = get_output_topk::<B, T>(ctx.as_ref(), input, weights, bias, t, d_model, e, k);
-
- // fused
- let mut offsets = ctx.create_array_uninitialized(&[e + 1], DataType::U32).into_allocation();
- let mut sumk = ctx.create_array_uninitialized(&[1], DataType::U32).into_allocation();
- let num_tiles = e.div_ceil(512).max(1);
- let mut partials = ctx.create_array_uninitialized(&[num_tiles * 512], DataType::U32).into_allocation();
- let fused_kernel =
- <<B as Backend>::Kernels as Kernels>::MoeCountsOffsetsFusedKernel::new(&ctx).expect("fused kernel");
- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");
- fused_kernel.encode(&topk_ids, &mut offsets, &mut sumk, &mut partials, t as u32, e as u32, k as u32, &mut encoder);
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- // scatter bases
- // Partials already created by fused kernel above
- let num_blocks = 1; // Fused kernel uses single block
- let entries = num_blocks * num_tiles * 512usize;
- let mut block_bases = ctx.create_array_uninitialized(&[entries], DataType::U32).into_allocation();
- let mut block_alloc = ctx.create_array_uninitialized(&[entries], DataType::U32).into_allocation();
- let scatter_bases_kernel = <<B as Backend>::Kernels as Kernels>::MoeBlockBasesFromPartialsKernel::new(ctx.as_ref())
- .expect("Failed to create <<Metal as Backend>::Kernels as Kernels>::MoeBlockBasesFromPartialsKernel");
- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");
- scatter_bases_kernel.encode(
- &partials,
- &mut block_bases,
- &mut block_alloc,
- e as u32,
- num_blocks as u32,
- num_tiles as u32,
- 0u32,
- &mut encoder,
- );
- encoder.end_encoding().submit().wait_until_completed().unwrap();
- let sumk = crate::tests::helpers::allocation_to_vec::<B, u32>(&sumk)[0] as usize;
-
- // scatter
- let scatter_kernel = <<B as Backend>::Kernels as Kernels>::MoeScatterBucketsKernel::new(&ctx, T::data_type())
- .expect("Failed to create <<B as Backend>::Kernels as Kernels>::MoeScatterBucketsKernel");
- let mut out_ids = ctx.create_array_uninitialized(&[sumk], DataType::I32).into_allocation();
- let mut out_probs = ctx.create_array_uninitialized(&[sumk], T::data_type()).into_allocation();
- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");
- scatter_kernel.encode(
- &topk_ids,
- &topk_probs,
- &offsets,
- &block_bases,
- &block_alloc,
- &mut out_ids,
- &mut out_probs,
- t as u32,
- e as u32,
- k as u32,
- num_blocks as u32,
- num_tiles as u32,
- &mut encoder,
- );
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- (
- crate::tests::helpers::allocation_to_vec(&out_ids),
- crate::tests::helpers::allocation_to_vec(&out_probs),
- crate::tests::helpers::allocation_to_vec(&offsets),
- )
-}
-
-fn test_scatter_internal<B: Backend, T: ArrayElement + Float>(
- t: usize,
- d_model: usize,
- e: usize,
- k: usize,
-) {
- let mut rng = StdRng::seed_from_u64(7);
-
- // Generate random input and router weights for fused kernel
- let input: Vec<T> = (0..t * d_model).map(|_| T::from(rng.random_range(-1.0..1.0)).unwrap()).collect();
- let weight: Vec<T> = (0..e * d_model).map(|_| T::from(rng.random_range(-1.0..1.0)).unwrap()).collect();
- let bias: Vec<T> = (0..e).map(|_| T::from(rng.random_range(-0.5..0.5)).unwrap()).collect();
-
- let (out_ids, out_probs_h, out_offsets_array) =
- get_output::<B, T>(input.as_slice(), weight.as_slice(), bias.as_slice(), t, d_model, e, k);
- let _out_probs: Vec<f32> = out_probs_h.iter().map(|&h| h.to_f32().unwrap()).collect();
-
- // CPU reference
- let cpu_ctx = create_context::<Cpu>();
- let (topk_ids_cpu, topk_probs_cpu) = get_output_topk::<Cpu, T>(
- cpu_ctx.as_ref(),
- input.as_slice(),
- weight.as_slice(),
- bias.as_slice(),
- t,
- d_model,
- e,
- k,
- );
- let cpu_topk_ids: Vec<i32> = crate::tests::helpers::allocation_to_vec(&topk_ids_cpu);
- let cpu_topk_probs: Vec<T> = crate::tests::helpers::allocation_to_vec(&topk_probs_cpu);
- let (cpu_ids, _cpu_probs, offsets_cpu) = cpu_expert_buckets(&cpu_topk_ids, &cpu_topk_probs, t, e, k);
- assert_eq!(out_offsets_array, offsets_cpu);
-
- // Compare per-expert multisets of ids
- for ei in 0..e {
- let s = offsets_cpu[ei] as usize;
- let epos = offsets_cpu[ei + 1] as usize;
- let mut a = out_ids[s..epos].to_vec();
- a.sort();
- let mut b = cpu_ids[s..epos].to_vec();
- b.sort();
- assert_eq!(a, b, "ids multiset mismatch for expert {}", ei);
- }
-}
-
-#[uzu_test]
-fn test_scatter_buckets_small() {
- for_each_non_cpu_backend!(|B| test_scatter_internal::<B, bf16>(1, 64, 4, 1));
-}
-
-#[uzu_test]
-fn test_scatter_buckets_medium() {
- for_each_non_cpu_backend!(|B| test_scatter_internal::<B, bf16>(7, 64, 16, 2));
-}
-
-#[uzu_test]
-fn test_scatter_buckets_big() {
- for_each_non_cpu_backend!(|B| test_scatter_internal::<B, bf16>(128, 64, 64, 2));
-}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/out_bench.rs b/crates/backend-uzu/unit/backends/common/kernel/out_bench.rs
index f0db6d0f9..1c7c0b260 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/out_bench.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/out_bench.rs
@@ -8,12 +8,15 @@ use num_traits::Float;
use proc_macros::uzu_bench;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Allocation, Backend, Context, Kernels, kernel::BuildTreeOutKernel},
metal::Metal,
},
- tests::matmul::iter_encode_loop_named,
+ tests::{
+ helpers::{alloc_allocation, alloc_allocation_with_data},
+ matmul::iter_encode_loop_named,
+ },
};
const QK_HEADS: usize = 16;
@@ -62,13 +65,13 @@ fn make_buffers<T: ArrayElement + Float>(
let h0_indices = (0..batch_size as i32).collect::<Vec<_>>();
TreeOutBuffers {
- q: context.create_array_from(&[q.len()], &q).into_allocation(),
- prefix: context.create_array_from(&[prefix.len()], &prefix).into_allocation(),
- qkd: context.create_array_from(&[qkd.len()], &qkd).into_allocation(),
- u: context.create_array_from(&[u.len()], &u).into_allocation(),
- h0: context.create_array_from(&[h0.len()], &h0).into_allocation(),
- h0_indices: context.create_array_from(&[h0_indices.len()], &h0_indices).into_allocation(),
- o: context.create_array_uninitialized(&[uv_len], T::data_type()).into_allocation(),
+ q: alloc_allocation_with_data::<Metal, T>(context, &q),
+ prefix: alloc_allocation_with_data::<Metal, f32>(context, &prefix),
+ qkd: alloc_allocation_with_data::<Metal, f32>(context, &qkd),
+ u: alloc_allocation_with_data::<Metal, T>(context, &u),
+ h0: alloc_allocation_with_data::<Metal, f32>(context, &h0),
+ h0_indices: alloc_allocation_with_data::<Metal, i32>(context, &h0_indices),
+ o: alloc_allocation::<Metal, T>(context, uv_len),
}
}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/out_test.rs b/crates/backend-uzu/unit/backends/common/kernel/out_test.rs
index ca8b72a20..d459c6684 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/out_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/out_test.rs
@@ -4,12 +4,15 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::BuildTreeOutKernel},
cpu::Cpu,
},
- tests::{assert::assert_eq_float, helpers::allocation_to_vec},
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
#[derive(Clone, Copy)]
@@ -81,20 +84,14 @@ fn run_build_tree_out<B: Backend, T: ArrayElement + Float>(
use_h0,
)
.expect("BuildTreeOutKernel");
- let q = context.as_ref().create_array_from(&[inputs.q.len()], &inputs.q).into_allocation();
- let prefix = context.as_ref().create_array_from(&[inputs.prefix.len()], &inputs.prefix).into_allocation();
- let qkd = context.as_ref().create_array_from(&[inputs.qkd.len()], &inputs.qkd).into_allocation();
- let u = context.as_ref().create_array_from(&[inputs.u.len()], &inputs.u).into_allocation();
- let h0 = use_h0.then(|| context.as_ref().create_array_from(&[inputs.h0.len()], &inputs.h0).into_allocation());
- let h0_indices = use_h0
- .then(|| context.as_ref().create_array_from(&[inputs.h0_indices.len()], &inputs.h0_indices).into_allocation());
- let mut o = context
- .as_ref()
- .create_array_uninitialized(
- &[shape.batch_size * shape.tree_size * shape.value_heads * shape.head_v_dim],
- T::data_type(),
- )
- .into_allocation();
+ let q = alloc_allocation_with_data::<B, T>(&context, &inputs.q);
+ let prefix = alloc_allocation_with_data::<B, f32>(&context, &inputs.prefix);
+ let qkd = alloc_allocation_with_data::<B, f32>(&context, &inputs.qkd);
+ let u = alloc_allocation_with_data::<B, T>(&context, &inputs.u);
+ let h0 = use_h0.then(|| alloc_allocation_with_data::<B, f32>(&context, &inputs.h0));
+ let h0_indices = use_h0.then(|| alloc_allocation_with_data::<B, i32>(&context, &inputs.h0_indices));
+ let mut o =
+ alloc_allocation::<B, T>(&context, shape.batch_size * shape.tree_size * shape.value_heads * shape.head_v_dim);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
diff --git a/crates/backend-uzu/unit/backends/common/kernel/pooling/mod.rs b/crates/backend-uzu/unit/backends/common/kernel/pooling/mod.rs
index 22da4b449..82afb4293 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/pooling/mod.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/pooling/mod.rs
@@ -1,2 +1 @@
-mod pooling_cls_test;
mod pooling_mean_test;
diff --git a/crates/backend-uzu/unit/backends/common/kernel/pooling/pooling_cls_test.rs b/crates/backend-uzu/unit/backends/common/kernel/pooling/pooling_cls_test.rs
deleted file mode 100644
index f74c36698..000000000
--- a/crates/backend-uzu/unit/backends/common/kernel/pooling/pooling_cls_test.rs
+++ /dev/null
@@ -1,157 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::uzu_test;
-use test_runner::for_each_non_cpu_backend;
-
-use crate::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{Backend, Context, Encoder, Kernels, kernel::PoolingClsKernel},
- cpu::Cpu,
- },
- data_type::DataType,
- tests::assert::assert_eq_float,
-};
-
-struct Input<T: ArrayElement + Float> {
- input: Box<[T]>,
- seq_len: u32,
- hidden_dim: u32,
- batch_size: u32,
-}
-
-fn get_test_data<T: ArrayElement + Float>(
- batch_size: u32,
- seq_len: u32,
- hidden_dim: u32,
-) -> (Input<T>, Vec<T>) {
- let len = (batch_size * seq_len * hidden_dim) as usize;
- let input: Vec<T> = (0..len).map(|i| T::from((i as f32 * 0.1).sin() * 2.0).unwrap()).collect();
-
- let input = Input {
- input: input.into_boxed_slice(),
- seq_len,
- hidden_dim,
- batch_size,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
- let context = B::Context::new().expect("Failed to create Context");
-
- let kernel = <<B as Backend>::Kernels as Kernels>::PoolingClsKernel::new(&context, T::data_type())
- .expect("Failed to create PoolingClsKernel");
-
- let input_len = (input.batch_size * input.seq_len * input.hidden_dim) as usize;
- let output_len = (input.batch_size * input.hidden_dim) as usize;
-
- let input_array = context.create_array_from(&[input_len], &input.input);
- let mut output = context.create_array_uninitialized(&[output_len], T::data_type()).into_allocation();
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- input_array.allocation(),
- &mut output,
- input.seq_len,
- input.hidden_dim,
- input.batch_size,
- &mut encoder,
- );
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- crate::tests::helpers::allocation_to_vec(&output)
-}
-
-fn test_internal<T: ArrayElement + Float + Debug + Display>(
- batch_size: u32,
- seq_len: u32,
- hidden_dim: u32,
-) {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 1e-3
- } else {
- 1e-5
- };
-
- let (input, expected) = get_test_data::<T>(batch_size, seq_len, hidden_dim);
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- let msg = format!("PoolingCls test failed for backend {}", std::any::type_name::<B>());
- assert_eq_float::<T>(&expected, &output, eps, &msg);
- });
-}
-
-// Basic tests
-#[uzu_test]
-fn test_basic_f32() {
- test_internal::<f32>(2, 16, 64);
-}
-
-#[uzu_test]
-fn test_basic_f16() {
- test_internal::<f16>(2, 16, 64);
-}
-
-#[uzu_test]
-fn test_basic_bf16() {
- test_internal::<bf16>(2, 16, 64);
-}
-
-// Single batch
-#[uzu_test]
-fn test_single_batch_f32() {
- test_internal::<f32>(1, 32, 128);
-}
-
-#[uzu_test]
-fn test_single_batch_f16() {
- test_internal::<f16>(1, 32, 128);
-}
-
-#[uzu_test]
-fn test_single_batch_bf16() {
- test_internal::<bf16>(1, 32, 128);
-}
-
-// Single token sequence
-#[uzu_test]
-fn test_single_token_f32() {
- test_internal::<f32>(2, 1, 64);
-}
-
-#[uzu_test]
-fn test_single_token_f16() {
- test_internal::<f16>(2, 1, 64);
-}
-
-#[uzu_test]
-fn test_single_token_bf16() {
- test_internal::<bf16>(2, 1, 64);
-}
-
-// Large hidden dim
-#[uzu_test]
-fn test_large_hidden_dim_f32() {
- test_internal::<f32>(2, 8, 512);
-}
-
-// Non-aligned hidden dim
-#[uzu_test]
-fn test_non_aligned_f32() {
- test_internal::<f32>(3, 10, 100);
-}
-
-#[uzu_test]
-fn test_non_aligned_f16() {
- test_internal::<f16>(3, 10, 100);
-}
-
-#[uzu_test]
-fn test_non_aligned_bf16() {
- test_internal::<bf16>(3, 10, 100);
-}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/pooling/pooling_mean_test.rs b/crates/backend-uzu/unit/backends/common/kernel/pooling/pooling_mean_test.rs
index f9685e6da..ec06a1e54 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/pooling/pooling_mean_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/pooling/pooling_mean_test.rs
@@ -6,13 +6,16 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::PoolingMeanKernel},
cpu::Cpu,
},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
struct Input<T: ArrayElement + Float> {
@@ -47,24 +50,16 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
let kernel = <<B as Backend>::Kernels as Kernels>::PoolingMeanKernel::new(&context, T::data_type())
.expect("Failed to create PoolingMeanKernel");
- let input_len = (input.batch_size * input.seq_len * input.hidden_dim) as usize;
let output_len = (input.batch_size * input.hidden_dim) as usize;
- let input_array = context.create_array_from(&[input_len], &input.input);
- let mut output = context.create_array_uninitialized(&[output_len], T::data_type()).into_allocation();
+ let input_allocation = alloc_allocation_with_data::<B, T>(&context, &input.input);
+ let mut output = alloc_allocation::<B, T>(&context, output_len);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- input_array.allocation(),
- &mut output,
- input.seq_len,
- input.hidden_dim,
- input.batch_size,
- &mut encoder,
- );
+ kernel.encode(&input_allocation, &mut output, input.seq_len, input.hidden_dim, input.batch_size, &mut encoder);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- crate::tests::helpers::allocation_to_vec(&output)
+ allocation_to_vec(&output)
}
fn test_internal<T: ArrayElement + Float + Debug + Display>(
diff --git a/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_bench.rs b/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_bench.rs
index 0a108079a..dbde90093 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_bench.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_bench.rs
@@ -6,13 +6,17 @@ use criterion::{BenchmarkId, Criterion, Throughput};
use proc_macros::uzu_bench;
use crate::{
- array::ArrayContextExt,
backends::{
common::{Allocation, Backend, Kernels, kernel::BuildPrefixBetaKernel},
metal::Metal,
},
data_type::DataType,
- tests::{cold_pool::ColdPool, matmul::iter_encode_loop_named, util::type_short_name},
+ tests::{
+ cold_pool::ColdPool,
+ helpers::{alloc_allocation, alloc_allocation_with_data},
+ matmul::iter_encode_loop_named,
+ util::type_short_name,
+ },
};
// chain trie: node `row` covers [row, T-1].
@@ -50,15 +54,15 @@ fn bench_build_prefix_beta(c: &mut Criterion) {
let a_log = (0..value_heads).map(|i| -0.2 + i as f32 * 0.03).collect::<Vec<_>>();
let dt_bias = (0..value_heads).map(|i| 0.1 - i as f32 * 0.02).collect::<Vec<_>>();
- let a_log = context.create_array_from(&[a_log.len()], &a_log);
- let dt_bias = context.create_array_from(&[dt_bias.len()], &dt_bias);
+ let a_log = alloc_allocation_with_data::<Metal, f32>(&context, &a_log);
+ let dt_bias = alloc_allocation_with_data::<Metal, f32>(&context, &dt_bias);
let bytes_per_copy = trie.len() * size_of::<u32>() + len * size_of::<f32>() * 4;
let mut buffers = ColdPool::new(bytes_per_copy, || PrefixBetaBuffers {
- trie: context.create_array_from(&[trie.len()], &trie).into_allocation(),
- a_transposed: context.create_array_from(&[a_transposed.len()], &a_transposed).into_allocation(),
- b: context.create_array_from(&[b_data.len()], &b_data).into_allocation(),
- prefix: context.create_array_uninitialized(&[len], DataType::F32).into_allocation(),
- beta: context.create_array_uninitialized(&[len], DataType::F32).into_allocation(),
+ trie: alloc_allocation_with_data::<Metal, u32>(&context, &trie),
+ a_transposed: alloc_allocation_with_data::<Metal, f32>(&context, &a_transposed),
+ b: alloc_allocation_with_data::<Metal, f32>(&context, &b_data),
+ prefix: alloc_allocation::<Metal, f32>(&context, len),
+ beta: alloc_allocation::<Metal, f32>(&context, len),
});
group.throughput(Throughput::Elements((len * tree_size) as u64));
@@ -73,8 +77,8 @@ fn bench_build_prefix_beta(c: &mut Criterion) {
&buffers.trie,
&buffers.a_transposed,
&buffers.b,
- a_log.allocation(),
- dt_bias.allocation(),
+ &a_log,
+ &dt_bias,
&mut buffers.prefix,
&mut buffers.beta,
batch_size as u32,
diff --git a/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_test.rs b/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_test.rs
index feb53f91b..980ef8936 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/prefix_beta_test.rs
@@ -2,13 +2,15 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::ArrayContextExt,
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::BuildPrefixBetaKernel},
cpu::Cpu,
},
data_type::DataType,
- tests::{assert::assert_eq_float, helpers::allocation_to_vec},
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
fn get_output<B: Backend>(
@@ -26,21 +28,21 @@ fn get_output<B: Backend>(
.expect("Failed to create BuildPrefixBetaKernel");
let output_len = a_transposed.len();
- let trie = context.create_array_from(&[trie.len()], trie);
- let a_transposed = context.create_array_from(&[a_transposed.len()], a_transposed);
- let b = context.create_array_from(&[b.len()], b);
- let a_log = context.create_array_from(&[a_log.len()], a_log);
- let dt_bias = context.create_array_from(&[dt_bias.len()], dt_bias);
- let mut prefix = context.create_array_uninitialized(&[output_len], DataType::F32).into_allocation();
- let mut beta = context.create_array_uninitialized(&[output_len], DataType::F32).into_allocation();
+ let trie = alloc_allocation_with_data::<B, u32>(&context, trie);
+ let a_transposed = alloc_allocation_with_data::<B, f32>(&context, a_transposed);
+ let b = alloc_allocation_with_data::<B, f32>(&context, b);
+ let a_log = alloc_allocation_with_data::<B, f32>(&context, a_log);
+ let dt_bias = alloc_allocation_with_data::<B, f32>(&context, dt_bias);
+ let mut prefix = alloc_allocation::<B, f32>(&context, output_len);
+ let mut beta = alloc_allocation::<B, f32>(&context, output_len);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- trie.allocation(),
- a_transposed.allocation(),
- b.allocation(),
- a_log.allocation(),
- dt_bias.allocation(),
+ &trie,
+ &a_transposed,
+ &b,
+ &a_log,
+ &dt_bias,
&mut prefix,
&mut beta,
batch_size,
diff --git a/crates/backend-uzu/unit/backends/common/kernel/qk_unpack_test.rs b/crates/backend-uzu/unit/backends/common/kernel/qk_unpack_test.rs
deleted file mode 100644
index 87e478ee9..000000000
--- a/crates/backend-uzu/unit/backends/common/kernel/qk_unpack_test.rs
+++ /dev/null
@@ -1,80 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use half::bf16;
-use num_traits::Float;
-use proc_macros::uzu_test;
-use test_runner::for_each_non_cpu_backend;
-
-use crate::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{Backend, Context, Encoder, Kernels, kernel::QkUnpackKernel},
- cpu::Cpu,
- },
- tests::assert::assert_eq_float,
-};
-
-fn run<T: ArrayElement + Float + Debug + Display, B: Backend>(
- num_heads: u32,
- num_groups: u32,
- head_dim: u32,
- suffix_length: u32,
-) -> (Vec<T>, Vec<T>) {
- let total_heads = (num_heads + 2 * num_groups) as usize;
- let qkv_len = suffix_length as usize * total_heads * head_dim as usize;
- let qkv: Box<[T]> = (0..qkv_len).map(|index| T::from(((index as f32) * 0.1).sin() * 2.0).unwrap()).collect();
-
- let context = B::Context::new().expect("Failed to create Context");
- let kernel = <<B as Backend>::Kernels as Kernels>::QkUnpackKernel::new(&context, T::data_type())
- .expect("Failed to create QkUnpackKernel");
-
- let queries_len = num_heads as usize * suffix_length as usize * head_dim as usize;
- let keys_len = num_groups as usize * suffix_length as usize * head_dim as usize;
- let qkv_array = context.create_array_from(&[qkv_len], &qkv);
- let mut queries = context.create_array_uninitialized(&[queries_len], T::data_type()).into_allocation();
- let mut keys = context.create_array_uninitialized(&[keys_len], T::data_type()).into_allocation();
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- qkv_array.allocation(),
- &mut queries,
- &mut keys,
- head_dim,
- num_heads,
- num_groups,
- suffix_length,
- &mut encoder,
- );
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- (crate::tests::helpers::allocation_to_vec(&queries), crate::tests::helpers::allocation_to_vec(&keys))
-}
-
-fn check<T: ArrayElement + Float + Debug + Display>(
- num_heads: u32,
- num_groups: u32,
- head_dim: u32,
- suffix_length: u32,
-) {
- let (expected_queries, expected_keys) = run::<T, Cpu>(num_heads, num_groups, head_dim, suffix_length);
- for_each_non_cpu_backend!(|B| {
- let (queries, keys) = run::<T, B>(num_heads, num_groups, head_dim, suffix_length);
- assert_eq_float::<T>(&expected_queries, &queries, 0.0, "QkUnpack queries");
- assert_eq_float::<T>(&expected_keys, &keys, 0.0, "QkUnpack keys");
- });
-}
-
-#[uzu_test]
-fn test_qk_unpack_gqa_f32() {
- check::<f32>(8, 2, 64, 4);
-}
-
-#[uzu_test]
-fn test_qk_unpack_single_token_f32() {
- check::<f32>(16, 4, 64, 1);
-}
-
-#[uzu_test]
-fn test_qk_unpack_bf16() {
- check::<bf16>(8, 2, 64, 4);
-}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/qkv_norm_test.rs b/crates/backend-uzu/unit/backends/common/kernel/qkv_norm_test.rs
index 8276e6f5d..6cdfb49a9 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/qkv_norm_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/qkv_norm_test.rs
@@ -6,13 +6,16 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Allocation, Backend, Context, Encoder, Kernels, kernel::QKVNormKernel},
cpu::Cpu,
},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation_with_data, allocation_to_vec},
+ },
};
struct Input<InputT: ArrayElement + Float, ScaleT: ArrayElement + Float, OutputT: ArrayElement + Float> {
@@ -129,20 +132,13 @@ fn get_output<
)
.expect("Failed to create QKVNormKernel");
- let qkv_len = input.qkv.len();
- let mut qkv = context.create_array_from(&[qkv_len], &input.qkv).into_allocation();
- let scales_array = context.create_array_from(&[input.scales.len()], &input.scales);
-
- let scales = if input.scale_free {
- None
- } else {
- Some(scales_array.allocation())
- };
+ let mut qkv = alloc_allocation_with_data::<B, OutputT>(&context, &input.qkv);
+ let scales = (!input.scale_free).then(|| alloc_allocation_with_data::<B, ScaleT>(&context, &input.scales));
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
None::<&Allocation<B>>,
- scales,
+ scales.as_ref(),
&mut qkv,
input.batch_size,
input.num_q_heads,
@@ -157,7 +153,7 @@ fn get_output<
);
encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
- crate::tests::helpers::allocation_to_vec(&qkv)
+ allocation_to_vec(&qkv)
}
fn test_internal<
diff --git a/crates/backend-uzu/unit/backends/common/kernel/rms_norm_bench.rs b/crates/backend-uzu/unit/backends/common/kernel/rms_norm_bench.rs
deleted file mode 100644
index fcf05bbb1..000000000
--- a/crates/backend-uzu/unit/backends/common/kernel/rms_norm_bench.rs
+++ /dev/null
@@ -1,104 +0,0 @@
-use criterion::{BenchmarkId, Criterion, Throughput};
-use itertools::iproduct;
-use proc_macros::uzu_bench;
-use rand::{RngExt, SeedableRng, rngs::SmallRng};
-use test_runner::for_each_backend;
-
-use crate::{
- array::{ArrayContextExt, ArrayElement},
- backends::common::{Allocation, Backend, Context, Encoder, Kernels, kernel::RMSNormKernel},
- tests::util::type_short_name,
-};
-
-fn get_rms_norm_data(
- seed: u64,
- batch_size: usize,
- model_dim: usize,
-) -> (Box<[f32]>, Box<[f32]>) {
- let mut rng = SmallRng::seed_from_u64(seed);
- let input_size = batch_size * model_dim;
- let mut input_data = vec![0.0f32; input_size];
- for x in input_data.iter_mut() {
- *x = rng.random_range(-2.0f32..2.0f32);
- }
- let mut scale_data = vec![0.0f32; model_dim];
- for x in scale_data.iter_mut() {
- *x = rng.random_range(0.1f32..3.0f32);
- }
- (input_data.into_boxed_slice(), scale_data.into_boxed_slice())
-}
-
-#[uzu_bench]
-fn bench_rms_norm(c: &mut Criterion) {
- type T = f32;
- let epsilon = 1e-6f32;
- let scale_offset = 0.0f32;
-
- for_each_backend!(|B| {
- let context = <B as Backend>::Context::new().unwrap();
-
- let kernel = <<B as Backend>::Kernels as Kernels>::RMSNormKernel::new(
- &context,
- T::data_type(),
- T::data_type(),
- T::data_type(),
- T::data_type(),
- false,
- false,
- false,
- false,
- false,
- false,
- false,
- )
- .unwrap();
-
- let mut group = c.benchmark_group(format!("{}/Kernel/RMSNorm", type_short_name::<B>()));
-
- for (batch_size, model_dim) in iproduct!(
- [1, 4, 32, 128, 1024], // Batch sizes
- [
- 1024, // LFM2-350M
- 1152, // Gemma-3-1b
- 2048, // Llama-3.2-1B
- 2560, // Qwen3-4B
- 3072, // Llama-3.2-3B
- 4096, // Qwen3-8B
- 5120, // Qwen2.5-32B
- ]
- ) {
- let (input_data, scale_data) = get_rms_norm_data(1337, batch_size, model_dim);
- let input_size = batch_size * model_dim;
-
- let input_buffer = context.create_array_from(&[input_size], input_data.as_ref()).into_allocation();
- let scales_buffer = context.create_array_from(&[model_dim], scale_data.as_ref()).into_allocation();
- let mut output_buffer = context.create_array_uninitialized(&[input_size], T::data_type()).into_allocation();
-
- group.throughput(Throughput::Elements((batch_size * model_dim) as u64));
-
- group.bench_function(BenchmarkId::from_parameter(format!("Batch[{batch_size}]Dim[{model_dim}]")), |b| {
- b.iter_custom(|n_iters| {
- let mut encoder = Encoder::<B>::new(&context).unwrap();
-
- for _ in 0..n_iters {
- kernel.encode(
- Some(&input_buffer),
- &scales_buffer,
- &mut output_buffer,
- None::<&mut Allocation<B>>,
- None::<&Allocation<B>>,
- batch_size as u32,
- model_dim as u32,
- epsilon,
- scale_offset,
- 1.0,
- &mut encoder,
- );
- }
-
- encoder.end_encoding().submit().wait_until_completed().unwrap().gpu_execution_time()
- })
- });
- }
- });
-}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/rms_norm_test.rs b/crates/backend-uzu/unit/backends/common/kernel/rms_norm_test.rs
deleted file mode 100644
index f66756305..000000000
--- a/crates/backend-uzu/unit/backends/common/kernel/rms_norm_test.rs
+++ /dev/null
@@ -1,436 +0,0 @@
-use std::{
- fmt::{Debug, Display},
- time::{Duration, Instant},
-};
-
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::uzu_test;
-use rand::{RngExt, SeedableRng, rngs::SmallRng};
-use test_runner::for_each_non_cpu_backend;
-
-use crate::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{Allocation, Backend, Context, Encoder, Kernels, kernel::RMSNormKernel},
- cpu::Cpu,
- },
- data_type::DataType,
- tests::assert::assert_eq_float,
-};
-
-static BOOL_ALL: &[bool] = &[true, false];
-static BOOL_FALSE: &[bool] = &[false];
-
-struct Input<InputT: ArrayElement + Float, ScaleT: ArrayElement + Float, OutputT: ArrayElement + Float> {
- input: Box<[InputT]>,
- scales: Box<[ScaleT]>,
- output: Box<[OutputT]>,
- batch_size: u32,
- element_count: u32,
- epsilon: f32,
- scale_offset: f32,
- full_layer: bool,
- in_place: bool,
-}
-
-fn get_test_data_basic<
- InputT: ArrayElement + Float,
- ScaleT: ArrayElement + Float,
- OutputT: ArrayElement + Float,
- AccumT: ArrayElement + Float,
->(
- full_layer: bool,
- in_place: bool,
-) -> (Input<InputT, ScaleT, OutputT>, Vec<OutputT>) {
- let batch_size = 1usize;
- let model_dim = 4096usize;
- let epsilon = 1e-5f32;
- let scale_offset = 0.123f32;
-
- let mut input_data: Vec<InputT> = vec![InputT::zero(); model_dim];
- let mut output_data: Vec<OutputT> = vec![OutputT::zero(); model_dim];
- let scales_data: Vec<ScaleT> = vec![ScaleT::one(); model_dim];
- for i in 0..model_dim {
- let input_value = 2.0 * f32::sin(i as f32 * 0.01) + 0.1 * (i as f32 / model_dim as f32);
- input_data[i] = InputT::from(input_value).unwrap();
- output_data[i] = OutputT::from(input_value).unwrap();
- }
-
- let input = Input::<InputT, ScaleT, OutputT> {
- input: input_data.into_boxed_slice(),
- scales: scales_data.into_boxed_slice(),
- output: output_data.into_boxed_slice(),
- batch_size: batch_size as u32,
- element_count: model_dim as u32,
- epsilon,
- scale_offset,
- full_layer,
- in_place,
- };
-
- let (output, _, _) = get_output::<Cpu, InputT, ScaleT, OutputT, AccumT>(&input);
- (input, output)
-}
-
-fn get_test_data_edge<
- InputT: ArrayElement + Float,
- ScaleT: ArrayElement + Float,
- OutputT: ArrayElement + Float,
- AccumT: ArrayElement + Float,
->(
- full_layer: bool,
- in_place: bool,
-) -> (Input<InputT, ScaleT, OutputT>, Vec<OutputT>) {
- let batch_size = 1usize;
- let model_dim = 4usize;
- let epsilon = 1e-6f32;
- let scale_offset = 0.0f32;
-
- // Test with very small values (near epsilon)
- let input_data_f32: Vec<f32> = vec![1e-4, 2e-4, 3e-4, 4e-4]; // Scaled up for F16 precision
- let scales_data_f32: Vec<f32> = vec![2.0, 0.5, 1.5, 0.8]; // Non-unit scales
- let input_data: Vec<InputT> = input_data_f32.iter().map(|&x| InputT::from(x).unwrap()).collect();
- let output_data: Vec<OutputT> = input_data_f32.iter().map(|&x| OutputT::from(x).unwrap()).collect();
- let scales_data: Vec<ScaleT> = scales_data_f32.iter().map(|&x| ScaleT::from(x).unwrap()).collect();
-
- let input = Input::<InputT, ScaleT, OutputT> {
- input: input_data.into_boxed_slice(),
- scales: scales_data.into_boxed_slice(),
- output: output_data.into_boxed_slice(),
- batch_size: batch_size as u32,
- element_count: model_dim as u32,
- epsilon,
- scale_offset,
- full_layer,
- in_place,
- };
-
- let (output, _, _) = get_output::<Cpu, InputT, ScaleT, OutputT, AccumT>(&input);
- (input, output)
-}
-
-fn get_output<
- B: Backend,
- InputT: ArrayElement + Float,
- ScaleT: ArrayElement + Float,
- OutputT: ArrayElement + Float,
- AccumT: ArrayElement + Float,
->(
- input: &Input<InputT, ScaleT, OutputT>
-) -> (Vec<OutputT>, f64, Duration) {
- let context = B::Context::new().expect("Failed to create Context");
- let kernel = <<B as Backend>::Kernels as Kernels>::RMSNormKernel::new(
- &context,
- InputT::data_type(),
- ScaleT::data_type(),
- OutputT::data_type(),
- AccumT::data_type(),
- input.in_place,
- input.full_layer,
- false,
- false,
- false,
- false,
- false,
- )
- .expect("Failed to create RMSNormKernel");
-
- let input_size = input.input.len();
- let input_buffer =
- (!input.in_place).then(|| context.create_array_from(&[input_size], &input.input).into_allocation());
-
- let scales_array = context.create_array_from(&[input.scales.len()], &input.scales);
- let mut output = match input.in_place {
- true => context.create_array_from(&[input_size], &input.output).into_allocation(),
- false => context.create_array_uninitialized(&[input_size], OutputT::data_type()).into_allocation(),
- };
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- input_buffer.as_ref(),
- scales_array.allocation(),
- &mut output,
- None::<&mut Allocation<B>>,
- None::<&Allocation<B>>,
- input.batch_size,
- input.element_count,
- input.epsilon,
- input.scale_offset,
- 1.0,
- &mut encoder,
- );
-
- let instant = Instant::now();
- let completed = encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
- let host_elapsed_ms = instant.elapsed().as_secs_f64() * 1e3;
- let gpu_elapsed_ms = completed.gpu_execution_time();
-
- (crate::tests::helpers::allocation_to_vec(&output), host_elapsed_ms, gpu_elapsed_ms)
-}
-
-fn test_internal<
- InputT: ArrayElement + Float,
- ScaleT: ArrayElement + Float,
- OutputT: ArrayElement + Float + Debug + Display,
- AccumT: ArrayElement + Float,
->(
- input: &Input<InputT, ScaleT, OutputT>,
- expected: &[OutputT],
-) {
- let eps = if matches!(InputT::data_type(), DataType::F16 | DataType::BF16)
- || matches!(ScaleT::data_type(), DataType::F16 | DataType::BF16)
- || matches!(OutputT::data_type(), DataType::F16 | DataType::BF16)
- || matches!(AccumT::data_type(), DataType::F16 | DataType::BF16)
- {
- 0.016f32
- } else {
- 1e-5
- };
-
- for_each_non_cpu_backend!(|B| {
- let (output, _, _) = get_output::<B, InputT, ScaleT, OutputT, AccumT>(input);
- let msg = format!(
- "RMSNorm kernel test failed with backend={}, full_layer={}, in_place={}",
- std::any::type_name::<B>(),
- input.full_layer,
- input.in_place,
- );
- assert_eq_float::<OutputT>(expected, &output, eps, &msg);
- });
-}
-
-fn test_basic<
- InputT: ArrayElement + Float,
- ScaleT: ArrayElement + Float,
- OutputT: ArrayElement + Float + Debug + Display,
- AccumT: ArrayElement + Float,
->() {
- let in_place_values: &[bool] = if InputT::data_type() == OutputT::data_type() {
- BOOL_ALL
- } else {
- BOOL_FALSE
- };
-
- for in_place in in_place_values {
- for full_layer in [true, false] {
- let (input, expected) = get_test_data_basic::<InputT, ScaleT, OutputT, AccumT>(full_layer, *in_place);
- test_internal::<InputT, ScaleT, OutputT, AccumT>(&input, expected.as_slice())
- }
- }
-}
-
-fn test_edge<
- InputT: ArrayElement + Float,
- ScaleT: ArrayElement + Float,
- OutputT: ArrayElement + Float + Debug + Display,
- AccumT: ArrayElement + Float,
->() {
- let in_place_values: &[bool] = if InputT::data_type() == OutputT::data_type() {
- BOOL_ALL
- } else {
- BOOL_FALSE
- };
-
- for in_place in in_place_values {
- let (input, expected) = get_test_data_edge::<InputT, ScaleT, OutputT, AccumT>(false, *in_place);
- test_internal::<InputT, ScaleT, OutputT, AccumT>(&input, expected.as_slice())
- }
-}
-
-// AccumT f32
-#[uzu_test]
-fn test_f32_f32_f32_f32() {
- test_basic::<f32, f32, f32, f32>();
-}
-
-// AccumT f32 + f16
-#[uzu_test]
-fn test_f16_f32_f32_f32() {
- test_basic::<f16, f32, f32, f32>();
-}
-
-#[uzu_test]
-fn test_f32_f16_f32_f32() {
- test_basic::<f32, f16, f32, f32>();
-}
-
-#[uzu_test]
-fn test_f32_f32_f16_f32() {
- test_basic::<f32, f32, f16, f32>();
-}
-
-#[uzu_test]
-fn test_f16_f16_f32_f32() {
- test_basic::<f16, f16, f32, f32>();
-}
-
-#[uzu_test]
-fn test_f16_f32_f16_f32() {
- test_basic::<f16, f32, f16, f32>();
-}
-
-#[uzu_test]
-fn test_f32_f16_f16_f32() {
- test_basic::<f32, f16, f16, f32>();
-}
-
-#[uzu_test]
-fn test_f16_f16_f16_f32() {
- test_basic::<f16, f16, f16, f32>();
-}
-
-// AccumT f32 + bf16
-#[uzu_test]
-fn test_bf16_f32_f32_f32() {
- test_basic::<bf16, f32, f32, f32>();
-}
-
-#[uzu_test]
-fn test_f32_bf16_f32_f32() {
- test_basic::<f32, bf16, f32, f32>();
-}
-
-#[uzu_test]
-fn test_f32_f32_bf16_f32() {
- test_basic::<f32, f32, bf16, f32>();
-}
-
-#[uzu_test]
-fn test_bf16_bf16_f32_f32() {
- test_basic::<bf16, bf16, f32, f32>();
-}
-
-#[uzu_test]
-fn test_bf16_f32_bf16_f32() {
- test_basic::<bf16, f32, bf16, f32>();
-}
-
-#[uzu_test]
-fn test_bf16_bf16_bf16_f32() {
- test_basic::<bf16, bf16, bf16, f32>();
-}
-
-// AccumT f16
-#[uzu_test]
-fn test_f32_f32_f32_f16() {
- test_basic::<f32, f32, f32, f16>();
-}
-
-#[uzu_test]
-fn test_f16_f32_f32_f16() {
- test_basic::<f16, f32, f32, f16>();
-}
-
-#[uzu_test]
-fn test_f32_f16_f32_f16() {
- test_basic::<f32, f16, f32, f16>();
-}
-
-#[uzu_test]
-fn test_f32_f32_f16_f16() {
- test_basic::<f32, f32, f16, f16>();
-}
-
-#[uzu_test]
-fn test_f16_f16_f32_f16() {
- test_basic::<f16, f16, f32, f16>();
-}
-
-#[uzu_test]
-fn test_f16_f32_f16_f16() {
- test_basic::<f16, f32, f16, f16>();
-}
-
-#[uzu_test]
-fn test_f32_f16_f16_f16() {
- test_basic::<f32, f16, f16, f16>();
-}
-
-#[uzu_test]
-fn test_f16_f16_f16_f16() {
- test_basic::<f16, f16, f16, f16>();
-}
-
-// edge cases
-#[uzu_test]
-fn test_edge_f32_f32_f32_f32() {
- test_edge::<f32, f32, f32, f32>();
-}
-
-#[uzu_test]
-fn test_edge_f32_f16_f16_f32() {
- test_edge::<f32, f16, f16, f32>();
-}
-
-#[uzu_test]
-fn test_edge_f16_f16_f16_f16() {
- test_edge::<f16, f16, f16, f16>();
-}
-
-fn run_scaled_rms<B: Backend>(
- with_shortcut: bool,
- scale_residual_sum: bool,
- scale_output: bool,
-) -> (Vec<f32>, Vec<f32>) {
- let (batch, dim) = (2usize, 64usize);
- let total = batch * dim;
- let mut rng = SmallRng::seed_from_u64(99);
- let input: Vec<f32> = (0..total).map(|_| rng.random_range(-2.0f32..2.0f32)).collect();
- let scales: Vec<f32> = (0..dim).map(|_| rng.random_range(0.1f32..3.0f32)).collect();
- let shortcut: Vec<f32> = (0..total).map(|_| rng.random_range(-1.0f32..1.0f32)).collect();
-
- let context = B::Context::new().expect("Failed to create Context");
- let kernel = <<B as Backend>::Kernels as Kernels>::RMSNormKernel::new(
- &context,
- f32::data_type(),
- f32::data_type(),
- f32::data_type(),
- f32::data_type(),
- false,
- false,
- with_shortcut,
- with_shortcut,
- false,
- scale_residual_sum,
- scale_output,
- )
- .expect("Failed to create RMSNormKernel");
-
- let input_buffer = context.create_array_from(&[total], &input).into_allocation();
- let scales_buffer = context.create_array_from(&[dim], &scales).into_allocation();
- let mut output = context.create_array_uninitialized(&[total], f32::data_type()).into_allocation();
- let mut shortcut_buffer = with_shortcut.then(|| context.create_array_from(&[total], &shortcut).into_allocation());
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- Some(&input_buffer),
- &scales_buffer,
- &mut output,
- shortcut_buffer.as_mut(),
- None::<&Allocation<B>>,
- batch as u32,
- dim as u32,
- 1e-6,
- 0.0,
- 0.7,
- &mut encoder,
- );
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
-
- let output_values = crate::tests::helpers::allocation_to_vec(&output);
- let shortcut_values = shortcut_buffer.as_ref().map(crate::tests::helpers::allocation_to_vec).unwrap_or_default();
- (output_values, shortcut_values)
-}
-
-#[uzu_test]
-fn test_post_layer_scalar_metal_matches_cpu() {
- for &(shortcut, residual_sum, output) in &[(false, false, true), (true, true, false)] {
- let (cpu_out, cpu_shortcut) = run_scaled_rms::<Cpu>(shortcut, residual_sum, output);
- for_each_non_cpu_backend!(|B| {
- let (out, sc) = run_scaled_rms::<B>(shortcut, residual_sum, output);
- assert_eq_float::<f32>(&cpu_out, &out, 1e-5, "post_layer_scalar output: metal != cpu");
- assert_eq_float::<f32>(&cpu_shortcut, &sc, 1e-5, "post_layer_scalar shortcut: metal != cpu");
- });
- }
-}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/rope_test.rs b/crates/backend-uzu/unit/backends/common/kernel/rope_test.rs
deleted file mode 100644
index ed2d517f6..000000000
--- a/crates/backend-uzu/unit/backends/common/kernel/rope_test.rs
+++ /dev/null
@@ -1,315 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::uzu_test;
-use test_runner::for_each_non_cpu_backend;
-
-use crate::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{Allocation, Backend, Context, Encoder, Kernels, kernel::RopeKernel},
- cpu::Cpu,
- },
- data_type::DataType,
- tests::assert::assert_eq_float,
-};
-
-struct Input<T: ArrayElement + Float> {
- qkv: Box<[T]>,
- cosines: Box<[f32]>,
- sines: Box<[f32]>,
- token_positions: Box<[i32]>,
- head_dim: u32,
- rope_dim: u32,
- num_heads: u32,
- num_groups: u32,
- suffix_length: u32,
- max_sequence_length: u32,
-}
-
-fn get_test_data<T: ArrayElement + Float>(
- num_heads: u32,
- num_groups: u32,
- head_dim: u32,
- rope_dim: u32,
- suffix_length: u32,
- max_sequence_length: u32,
-) -> Input<T> {
- let total_heads = (num_heads + 2 * num_groups) as usize;
- let qkv_size = suffix_length as usize * total_heads * head_dim as usize;
- let cos_sin_size = max_sequence_length as usize * rope_dim as usize;
-
- let mut qkv = vec![T::zero(); qkv_size];
- for i in 0..qkv_size {
- qkv[i] = T::from(((i as f32) * 0.1).sin() * 2.0).unwrap();
- }
-
- let mut cosines = vec![0.0f32; cos_sin_size];
- let mut sines = vec![0.0f32; cos_sin_size];
- for i in 0..cos_sin_size {
- cosines[i] = ((i as f32) * 0.05).cos();
- sines[i] = ((i as f32) * 0.05).sin();
- }
-
- let mut token_positions = vec![0i32; suffix_length as usize];
- for i in 0..suffix_length as usize {
- token_positions[i] = i as i32;
- }
-
- Input {
- qkv: qkv.into_boxed_slice(),
- cosines: cosines.into_boxed_slice(),
- sines: sines.into_boxed_slice(),
- token_positions: token_positions.into_boxed_slice(),
- head_dim,
- rope_dim,
- num_heads,
- num_groups,
- suffix_length,
- max_sequence_length,
- }
-}
-
-fn get_output<T: ArrayElement + Float, B: Backend>(
- input: &Input<T>,
- query_only: bool,
-) -> (Vec<T>, Option<Vec<T>>) {
- let context = B::Context::new().expect("Failed to create Context");
-
- let element_data_type = T::data_type();
- let rope_data_type = DataType::F32;
- let kernel =
- <<B as Backend>::Kernels as Kernels>::RopeKernel::new(&context, element_data_type, rope_data_type, query_only)
- .expect("Failed to create RopeKernel");
-
- let total_heads = (input.num_heads + 2 * input.num_groups) as usize;
- let qkv_len = input.suffix_length as usize * total_heads * input.head_dim as usize;
- let cos_sin_len = input.suffix_length as usize * input.rope_dim as usize;
- let queries_len = input.num_heads as usize * input.suffix_length as usize * input.head_dim as usize;
- let keys_len = input.num_groups as usize * input.suffix_length as usize * input.head_dim as usize;
- let mut cosines = Vec::with_capacity(cos_sin_len);
- let mut sines = Vec::with_capacity(cos_sin_len);
- for token_index in 0..input.suffix_length as usize {
- let raw_position = input.token_positions[token_index] as usize;
- let absolute_position = if raw_position >= input.max_sequence_length as usize {
- 0
- } else {
- raw_position
- };
- let offset = absolute_position * input.rope_dim as usize;
- let end = offset + input.rope_dim as usize;
- cosines.extend_from_slice(&input.cosines[offset..end]);
- sines.extend_from_slice(&input.sines[offset..end]);
- }
-
- let qkv_array = if query_only {
- context.create_array_from(&[queries_len], &input.qkv[..queries_len])
- } else {
- context.create_array_from(&[qkv_len], &input.qkv)
- };
- let cosines_array = context.create_array_from(&[cos_sin_len], &cosines);
- let sines_array = context.create_array_from(&[cos_sin_len], &sines);
- let mut rotated_queries = context.create_array_uninitialized(&[queries_len], T::data_type()).into_allocation();
- let mut rotated_keys = context.create_array_uninitialized(&[keys_len], T::data_type()).into_allocation();
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- qkv_array.allocation(),
- cosines_array.allocation(),
- sines_array.allocation(),
- &mut rotated_queries,
- if query_only {
- None::<&mut Allocation<B>>
- } else {
- Some(&mut rotated_keys)
- },
- input.head_dim,
- input.rope_dim,
- input.num_heads,
- if query_only {
- None
- } else {
- Some(input.num_groups)
- },
- input.suffix_length,
- &mut encoder,
- );
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- let queries = crate::tests::helpers::allocation_to_vec(&rotated_queries);
- let keys = if query_only {
- None
- } else {
- Some(crate::tests::helpers::allocation_to_vec(&rotated_keys))
- };
- (queries, keys)
-}
-
-fn test_internal<T: ArrayElement + Float + Debug + Display>(input: &Input<T>) {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 0.02f32
- } else {
- 1e-5
- };
-
- let (expected_queries, expected_keys) = get_output::<T, Cpu>(input, false);
- let expected_keys = expected_keys.expect("full rope returns keys");
-
- for_each_non_cpu_backend!(|B| {
- let (queries, keys) = get_output::<T, B>(input, false);
- let keys = keys.expect("full rope returns keys");
- let msg = format!("Rope queries test failed with backend={}", std::any::type_name::<B>(),);
- assert_eq_float::<T>(&expected_queries, &queries, eps, &msg);
-
- let msg = format!("Rope keys test failed with backend={}", std::any::type_name::<B>(),);
- assert_eq_float::<T>(&expected_keys, &keys, eps, &msg);
- });
-}
-
-fn test_basic<T: ArrayElement + Float + Debug + Display>() {
- // Typical GQA config: 32 query heads, 8 KV groups, head_dim=128, 4 tokens
- let input = get_test_data::<T>(32, 8, 128, 128, 4, 512);
- test_internal(&input);
-}
-
-fn test_mha<T: ArrayElement + Float + Debug + Display>() {
- // MHA: num_heads == num_groups
- let input = get_test_data::<T>(8, 8, 64, 64, 2, 256);
- test_internal(&input);
-}
-
-fn test_single_token<T: ArrayElement + Float + Debug + Display>() {
- // Single token (decode)
- let input = get_test_data::<T>(16, 4, 64, 64, 1, 1024);
- test_internal(&input);
-}
-
-fn test_small<T: ArrayElement + Float + Debug + Display>() {
- // Minimal config
- let input = get_test_data::<T>(2, 1, 4, 4, 1, 8);
- test_internal(&input);
-}
-
-fn test_partial_rope_basic<T: ArrayElement + Float + Debug + Display>() {
- let input = get_test_data::<T>(32, 8, 128, 64, 4, 512);
- test_internal(&input);
-}
-
-fn test_partial_rope_small<T: ArrayElement + Float + Debug + Display>() {
- let input = get_test_data::<T>(2, 1, 8, 4, 1, 8);
- test_internal(&input);
-}
-
-fn test_nonzero_positions<T: ArrayElement + Float + Debug + Display>() {
- let mut input = get_test_data::<T>(4, 2, 8, 8, 3, 64);
- input.token_positions = vec![10, 11, 12].into_boxed_slice();
- test_internal(&input);
-}
-
-fn test_query_only<T: ArrayElement + Float + Debug + Display>(input: &Input<T>) {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 0.02f32
- } else {
- 1e-5
- };
- let (expected, _) = get_output::<T, Cpu>(input, true);
- for_each_non_cpu_backend!(|B| {
- let (actual, _) = get_output::<T, B>(input, true);
- let msg = format!("Rope query-only test failed with backend={}", std::any::type_name::<B>());
- assert_eq_float::<T>(&expected, &actual, eps, &msg);
- });
-}
-
-// f32 tests
-#[uzu_test]
-fn test_basic_f32() {
- test_basic::<f32>();
-}
-
-#[uzu_test]
-fn test_mha_f32() {
- test_mha::<f32>();
-}
-
-#[uzu_test]
-fn test_single_token_f32() {
- test_single_token::<f32>();
-}
-
-#[uzu_test]
-fn test_small_f32() {
- test_small::<f32>();
-}
-
-#[uzu_test]
-fn test_nonzero_positions_f32() {
- test_nonzero_positions::<f32>();
-}
-
-#[uzu_test]
-fn test_query_only_f32() {
- test_query_only::<f32>(&get_test_data::<f32>(8, 2, 64, 64, 4, 512));
-}
-
-#[uzu_test]
-fn test_query_only_partial_f32() {
- test_query_only::<f32>(&get_test_data::<f32>(8, 2, 256, 128, 4, 512));
-}
-
-#[uzu_test]
-fn test_query_only_bf16() {
- test_query_only::<bf16>(&get_test_data::<bf16>(8, 2, 64, 64, 4, 512));
-}
-
-// f16 tests
-#[uzu_test]
-fn test_basic_f16() {
- test_basic::<f16>();
-}
-
-#[uzu_test]
-fn test_mha_f16() {
- test_mha::<f16>();
-}
-
-#[uzu_test]
-fn test_single_token_f16() {
- test_single_token::<f16>();
-}
-
-#[uzu_test]
-fn test_small_f16() {
- test_small::<f16>();
-}
-
-// bf16 tests
-#[uzu_test]
-fn test_basic_bf16() {
- test_basic::<bf16>();
-}
-
-#[uzu_test]
-fn test_mha_bf16() {
- test_mha::<bf16>();
-}
-
-#[uzu_test]
-fn test_single_token_bf16() {
- test_single_token::<bf16>();
-}
-
-#[uzu_test]
-fn test_small_bf16() {
- test_small::<bf16>();
-}
-
-#[uzu_test]
-fn test_partial_rope_basic_f32() {
- test_partial_rope_basic::<f32>();
-}
-
-#[uzu_test]
-fn test_partial_rope_small_f32() {
- test_partial_rope_small::<f32>();
-}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_decode_test.rs b/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_decode_test.rs
index 5b3fed681..b2799be35 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_decode_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_decode_test.rs
@@ -6,13 +6,16 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::ShortConvDecodeKernel},
cpu::Cpu,
},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
struct Input<T: ArrayElement + Float> {
@@ -43,12 +46,12 @@ fn get_output<T: ArrayElement + Float, B: Backend>(
)
.expect("Failed to create ShortConvDecodeKernel");
- let in_proj_array = context.create_array_from(&[input.in_proj.len()], &input.in_proj);
- let w_array = context.create_array_from(&[input.w.len()], &input.w);
- let b_array = input.b.as_ref().map(|b| context.create_array_from(&[b.len()], b));
+ let in_proj = alloc_allocation_with_data::<B, T>(&context, &input.in_proj);
+ let w = alloc_allocation_with_data::<B, f32>(&context, &input.w);
+ let b = input.b.as_ref().map(|b| alloc_allocation_with_data::<B, f32>(&context, b));
let out_size = input.suffix_len as usize * input.model_dim as usize;
- let mut out = context.create_array_uninitialized(&[out_size], T::data_type()).into_allocation();
+ let mut out = alloc_allocation::<B, T>(&context, out_size);
let state_size = input.model_dim as usize * input.state_stride as usize;
let state_allocation_size = state_size.max(1);
@@ -56,19 +59,19 @@ fn get_output<T: ArrayElement + Float, B: Backend>(
input.state.iter().copied().chain(std::iter::repeat(T::zero())).take(state_allocation_size).collect();
let mut next_state = if state_in_place {
- context.create_array_from(&[state_allocation_size], &state_data).into_allocation()
+ alloc_allocation_with_data::<B, T>(&context, &state_data)
} else {
- context.create_array_uninitialized(&[state_allocation_size], T::data_type()).into_allocation()
+ alloc_allocation::<B, T>(&context, state_allocation_size)
};
- let state_array = (!state_in_place).then(|| context.create_array_from(&[state_allocation_size], &state_data));
+ let state = (!state_in_place).then(|| alloc_allocation_with_data::<B, T>(&context, &state_data));
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- in_proj_array.allocation(),
- w_array.allocation(),
- b_array.as_ref().map(|bias| bias.allocation()),
- state_array.as_ref().map(|state| state.allocation()),
+ &in_proj,
+ &w,
+ b.as_ref(),
+ state.as_ref(),
&mut out,
&mut next_state,
input.suffix_len,
@@ -80,7 +83,7 @@ fn get_output<T: ArrayElement + Float, B: Backend>(
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- (crate::tests::helpers::allocation_to_vec(&out), crate::tests::helpers::allocation_to_vec(&next_state))
+ (allocation_to_vec(&out), allocation_to_vec(&next_state))
}
fn get_test_data_basic<T: ArrayElement + Float>(
diff --git a/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_pack_test.rs b/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_pack_test.rs
index 28c7f6234..a591d58ac 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_pack_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_pack_test.rs
@@ -6,13 +6,16 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::ShortConvPackKernel},
cpu::Cpu,
},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
struct Input<T: ArrayElement + Float> {
@@ -30,17 +33,17 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
let kernel = <<B as Backend>::Kernels as Kernels>::ShortConvPackKernel::new(&context, T::data_type())
.expect("Failed to create ShortConvPackKernel");
- let state_in_array = context.create_array_from(&[input.state_in.len()], &input.state_in);
- let in_proj_array = context.create_array_from(&[input.in_proj.len()], &input.in_proj);
+ let state_in = alloc_allocation_with_data::<B, T>(&context, &input.state_in);
+ let in_proj = alloc_allocation_with_data::<B, T>(&context, &input.in_proj);
let padded_rows = (input.state_stride + input.suffix_len) as usize;
let padded_size = padded_rows * input.model_dim as usize;
- let mut padded = context.create_array_uninitialized(&[padded_size], T::data_type()).into_allocation();
+ let mut padded = alloc_allocation::<B, T>(&context, padded_size);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- state_in_array.allocation(),
- in_proj_array.allocation(),
+ &state_in,
+ &in_proj,
&mut padded,
input.state_stride,
input.suffix_len,
@@ -50,7 +53,7 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- crate::tests::helpers::allocation_to_vec(&padded)
+ allocation_to_vec(&padded)
}
/// Build test input for ShortConvPack.
diff --git a/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_prefill_test.rs b/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_prefill_test.rs
index f2a3f73e5..1c9a3f845 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_prefill_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_prefill_test.rs
@@ -6,13 +6,16 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::ShortConvPrefillKernel},
cpu::Cpu,
},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
struct Input<T: ArrayElement + Float> {
@@ -39,23 +42,23 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,
)
.expect("Failed to create ShortConvPrefillKernel");
- let padded_array = context.create_array_from(&[input.padded.len()], &input.padded);
- let in_proj_array = context.create_array_from(&[input.in_proj.len()], &input.in_proj);
- let w_array = context.create_array_from(&[input.w.len()], &input.w);
- let b_array = input.b.as_ref().map(|b| context.create_array_from(&[b.len()], b));
+ let padded = alloc_allocation_with_data::<B, T>(&context, &input.padded);
+ let in_proj = alloc_allocation_with_data::<B, T>(&context, &input.in_proj);
+ let w = alloc_allocation_with_data::<B, f32>(&context, &input.w);
+ let b = input.b.as_ref().map(|b| alloc_allocation_with_data::<B, f32>(&context, b));
let out_size = input.suffix_len as usize * input.model_dim as usize;
- let mut out = context.create_array_uninitialized(&[out_size], T::data_type()).into_allocation();
+ let mut out = alloc_allocation::<B, T>(&context, out_size);
let state_out_size = input.model_dim as usize * input.state_stride as usize;
- let mut state_out = context.create_array_uninitialized(&[state_out_size], T::data_type()).into_allocation();
+ let mut state_out = alloc_allocation::<B, T>(&context, state_out_size);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- padded_array.allocation(),
- in_proj_array.allocation(),
- w_array.allocation(),
- b_array.as_ref().map(|bias| bias.allocation()),
+ &padded,
+ &in_proj,
+ &w,
+ b.as_ref(),
&mut out,
&mut state_out,
input.suffix_len,
@@ -67,7 +70,7 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- (crate::tests::helpers::allocation_to_vec(&out), crate::tests::helpers::allocation_to_vec(&state_out))
+ (allocation_to_vec(&out), allocation_to_vec(&state_out))
}
fn get_test_data_basic<T: ArrayElement + Float>(
diff --git a/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_trie_test.rs b/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_trie_test.rs
index 2c254e4b3..e99a83442 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_trie_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/short_conv/short_conv_trie_test.rs
@@ -6,13 +6,16 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::ShortConvTrieKernel},
cpu::Cpu,
},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
struct Input<T: ArrayElement + Float> {
@@ -40,12 +43,12 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,
)
.expect("Failed to create ShortConvTrieKernel");
- let in_proj_array = context.create_array_from(&[input.in_proj.len()], &input.in_proj);
- let w_array = context.create_array_from(&[input.w.len()], &input.w);
- let b_array = input.b.as_ref().map(|b| context.create_array_from(&[b.len()], b));
+ let in_proj = alloc_allocation_with_data::<B, T>(&context, &input.in_proj);
+ let w = alloc_allocation_with_data::<B, f32>(&context, &input.w);
+ let b = input.b.as_ref().map(|b| alloc_allocation_with_data::<B, f32>(&context, b));
let out_size = input.suffix_len as usize * input.model_dim as usize;
- let mut out = context.create_array_uninitialized(&[out_size], T::data_type()).into_allocation();
+ let mut out = alloc_allocation::<B, T>(&context, out_size);
let state_stride = input.state_stride as usize;
let model_dim = input.model_dim as usize;
@@ -55,21 +58,20 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,
let base_state_allocation_size = base_state_size.max(1);
let base_state_data: Vec<T> =
input.base_state.iter().copied().chain(std::iter::repeat(T::zero())).take(base_state_allocation_size).collect();
- let base_state_array = context.create_array_from(&[base_state_allocation_size], &base_state_data);
+ let base_state = alloc_allocation_with_data::<B, T>(&context, &base_state_data);
- let parents_array = context.create_array_from(&[input.parents.len()], &input.parents);
+ let parents = alloc_allocation_with_data::<B, i32>(&context, &input.parents);
let suffix_state_size = suffix_len * model_dim * state_stride;
- let mut suffix_state =
- context.create_array_uninitialized(&[suffix_state_size.max(1)], T::data_type()).into_allocation();
+ let mut suffix_state = alloc_allocation::<B, T>(&context, suffix_state_size.max(1));
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- in_proj_array.allocation(),
- w_array.allocation(),
- b_array.as_ref().map(|bias| bias.allocation()),
- base_state_array.allocation(),
- parents_array.allocation(),
+ &in_proj,
+ &w,
+ b.as_ref(),
+ &base_state,
+ &parents,
&mut out,
&mut suffix_state,
input.suffix_len,
@@ -81,7 +83,7 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,
);
encoder.end_encoding().submit().wait_until_completed().unwrap();
- (crate::tests::helpers::allocation_to_vec(&out), crate::tests::helpers::allocation_to_vec(&suffix_state))
+ (allocation_to_vec(&out), allocation_to_vec(&suffix_state))
}
/// Linear chain: node 0 has parent -1 (root), node i has parent i-1.
diff --git a/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_conv1d_decode_test.rs b/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_conv1d_decode_test.rs
index c5d9e3270..a8e894bb3 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_conv1d_decode_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_conv1d_decode_test.rs
@@ -6,7 +6,7 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{
Allocation, Backend, Context, Encoder, Kernels, gpu_types::ActivationType, kernel::Conv1dDecodeKernel,
@@ -14,7 +14,10 @@ use crate::{
cpu::Cpu,
},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
struct Input<T: ArrayElement + Float> {
@@ -103,22 +106,22 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<T
let c_out_size = input.suffix_len as usize * input.proj_dim as usize;
let state_size = input.num_channels as usize * input.state_stride as usize;
- let x_array = context.create_array_from(&[input.x.len()], &input.x);
- let w_array = context.create_array_from(&[input.w.len()], &input.w);
- let b_array = input.b.as_ref().map(|b| context.create_array_from(&[b.len()], b));
+ let x = alloc_allocation_with_data::<B, T>(&context, &input.x);
+ let w = alloc_allocation_with_data::<B, T>(&context, &input.w);
+ let b = input.b.as_ref().map(|b| alloc_allocation_with_data::<B, T>(&context, b));
- let mut x_out = context.create_array_uninitialized(&[x_out_size], T::data_type()).into_allocation();
- let mut b_out = context.create_array_uninitialized(&[b_out_size], T::data_type()).into_allocation();
- let mut c_out = context.create_array_uninitialized(&[c_out_size], T::data_type()).into_allocation();
+ let mut x_out = alloc_allocation::<B, T>(&context, x_out_size);
+ let mut b_out = alloc_allocation::<B, T>(&context, b_out_size);
+ let mut c_out = alloc_allocation::<B, T>(&context, c_out_size);
if input.state_in_place {
- let mut next_state = context.create_array_from(&[state_size], &input.state).into_allocation();
+ let mut next_state = alloc_allocation_with_data::<B, T>(&context, &input.state);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- x_array.allocation(),
- w_array.allocation(),
- b_array.as_ref().map(|bias| bias.allocation()),
+ &x,
+ &w,
+ b.as_ref(),
None::<&Allocation<B>>,
&mut x_out,
&mut b_out,
@@ -137,21 +140,21 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<T
encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
Output {
- x_out: crate::tests::helpers::allocation_to_vec(&x_out),
- b_out: crate::tests::helpers::allocation_to_vec(&b_out),
- c_out: crate::tests::helpers::allocation_to_vec(&c_out),
- next_state: crate::tests::helpers::allocation_to_vec(&next_state),
+ x_out: allocation_to_vec(&x_out),
+ b_out: allocation_to_vec(&b_out),
+ c_out: allocation_to_vec(&c_out),
+ next_state: allocation_to_vec(&next_state),
}
} else {
- let state_array = context.create_array_from(&[state_size], &input.state);
- let mut next_state = context.create_array_uninitialized(&[state_size], T::data_type()).into_allocation();
+ let state = alloc_allocation_with_data::<B, T>(&context, &input.state);
+ let mut next_state = alloc_allocation::<B, T>(&context, state_size);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- x_array.allocation(),
- w_array.allocation(),
- b_array.as_ref().map(|bias| bias.allocation()),
- Some(state_array.allocation()),
+ &x,
+ &w,
+ b.as_ref(),
+ Some(&state),
&mut x_out,
&mut b_out,
&mut c_out,
@@ -169,10 +172,10 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<T
encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
Output {
- x_out: crate::tests::helpers::allocation_to_vec(&x_out),
- b_out: crate::tests::helpers::allocation_to_vec(&b_out),
- c_out: crate::tests::helpers::allocation_to_vec(&c_out),
- next_state: crate::tests::helpers::allocation_to_vec(&next_state),
+ x_out: allocation_to_vec(&x_out),
+ b_out: allocation_to_vec(&b_out),
+ c_out: allocation_to_vec(&c_out),
+ next_state: allocation_to_vec(&next_state),
}
}
}
@@ -277,11 +280,6 @@ fn test_gelu_activation<T: ArrayElement + Float + Debug + Display>() {
test_internal(&input, &expected, "gelu_activation");
}
-fn test_tanh_activation<T: ArrayElement + Float + Debug + Display>() {
- let (input, expected) = get_test_data::<T>(4, 8, 4, 2, 1, true, true, ActivationType::TANH);
- test_internal(&input, &expected, "tanh_activation");
-}
-
// f32
#[uzu_test]
fn test_basic_f32() {
@@ -308,11 +306,6 @@ fn test_gelu_activation_f32() {
test_gelu_activation::<f32>();
}
-#[uzu_test]
-fn test_tanh_activation_f32() {
- test_tanh_activation::<f32>();
-}
-
// f16
#[uzu_test]
fn test_basic_f16() {
diff --git a/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_conv1d_pack_test.rs b/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_conv1d_pack_test.rs
index a79b0d8fb..76c143920 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_conv1d_pack_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_conv1d_pack_test.rs
@@ -6,13 +6,16 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::Conv1dPackKernel},
cpu::Cpu,
},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
struct Input<T: ArrayElement + Float> {
@@ -51,19 +54,17 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {
let kernel = <<B as Backend>::Kernels as Kernels>::Conv1dPackKernel::new(&context, T::data_type(), T::data_type())
.expect("Failed to create Conv1dPackKernel");
- let state_size = input.state_in.len();
- let x_size = input.x.len();
let total_rows = input.state_stride as usize + input.suffix_len as usize;
let padded_size = total_rows * input.row_stride as usize;
- let state_array = context.create_array_from(&[state_size], &input.state_in);
- let x_array = context.create_array_from(&[x_size], &input.x);
- let mut padded = context.create_array_uninitialized(&[padded_size], T::data_type()).into_allocation();
+ let state = alloc_allocation_with_data::<B, T>(&context, &input.state_in);
+ let x = alloc_allocation_with_data::<B, T>(&context, &input.x);
+ let mut padded = alloc_allocation::<B, T>(&context, padded_size);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- state_array.allocation(),
- x_array.allocation(),
+ &state,
+ &x,
&mut padded,
input.state_stride,
input.row_stride,
@@ -73,7 +74,7 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {
);
encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
- crate::tests::helpers::allocation_to_vec(&padded)
+ allocation_to_vec(&padded)
}
fn get_test_data<T: ArrayElement + Float>(
diff --git a/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_conv1d_scan_test.rs b/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_conv1d_scan_test.rs
index 7b7e74476..b4258d4e2 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_conv1d_scan_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_conv1d_scan_test.rs
@@ -6,13 +6,16 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Backend, Context, Encoder, Kernels, gpu_types::ActivationType, kernel::Conv1dScanKernel},
cpu::Cpu,
},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
struct Input<T: ArrayElement + Float> {
@@ -90,20 +93,20 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<T
let c_out_size = input.suffix_len as usize * input.proj_dim as usize;
let state_size = input.num_channels as usize * input.state_stride as usize;
- let padded_array = context.create_array_from(&[input.padded.len()], &input.padded);
- let w_array = context.create_array_from(&[input.w.len()], &input.w);
- let b_array = input.b.as_ref().map(|b| context.create_array_from(&[b.len()], b));
+ let padded = alloc_allocation_with_data::<B, T>(&context, &input.padded);
+ let w = alloc_allocation_with_data::<B, T>(&context, &input.w);
+ let b = input.b.as_ref().map(|b| alloc_allocation_with_data::<B, T>(&context, b));
- let mut x_out = context.create_array_uninitialized(&[x_out_size], T::data_type()).into_allocation();
- let mut b_out = context.create_array_uninitialized(&[b_out_size], T::data_type()).into_allocation();
- let mut c_out = context.create_array_uninitialized(&[c_out_size], T::data_type()).into_allocation();
- let mut state_out = context.create_array_uninitialized(&[state_size], T::data_type()).into_allocation();
+ let mut x_out = alloc_allocation::<B, T>(&context, x_out_size);
+ let mut b_out = alloc_allocation::<B, T>(&context, b_out_size);
+ let mut c_out = alloc_allocation::<B, T>(&context, c_out_size);
+ let mut state_out = alloc_allocation::<B, T>(&context, state_size);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- padded_array.allocation(),
- w_array.allocation(),
- b_array.as_ref().map(|bias| bias.allocation()),
+ &padded,
+ &w,
+ b.as_ref(),
&mut x_out,
&mut b_out,
&mut c_out,
@@ -121,10 +124,10 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<T
encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
Output {
- x_out: crate::tests::helpers::allocation_to_vec(&x_out),
- b_out: crate::tests::helpers::allocation_to_vec(&b_out),
- c_out: crate::tests::helpers::allocation_to_vec(&c_out),
- state_out: crate::tests::helpers::allocation_to_vec(&state_out),
+ x_out: allocation_to_vec(&x_out),
+ b_out: allocation_to_vec(&b_out),
+ c_out: allocation_to_vec(&c_out),
+ state_out: allocation_to_vec(&state_out),
}
}
@@ -228,11 +231,6 @@ fn test_gelu_activation<T: ArrayElement + Float + Debug + Display>() {
test_internal(&input, &expected, "gelu_activation");
}
-fn test_tanh_activation<T: ArrayElement + Float + Debug + Display>() {
- let (input, expected) = get_test_data::<T>(4, 8, 4, 2, 2, true, ActivationType::TANH);
- test_internal(&input, &expected, "tanh_activation");
-}
-
// f32
#[uzu_test]
fn test_basic_f32() {
@@ -269,11 +267,6 @@ fn test_gelu_activation_f32() {
test_gelu_activation::<f32>();
}
-#[uzu_test]
-fn test_tanh_activation_f32() {
- test_tanh_activation::<f32>();
-}
-
// f16
#[uzu_test]
fn test_basic_f16() {
diff --git a/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_prefill_test.rs b/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_prefill_test.rs
index 465ac3984..9ac944410 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_prefill_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_prefill_test.rs
@@ -6,16 +6,13 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{
- Backend, Context, Encoder, Kernels,
- kernel::{SSDPrefillKernel, SSDPrefillSequentialKernel},
- },
- cpu::Cpu,
- },
+ array::ArrayElement,
+ backends::common::{Backend, Context, Encoder, Kernels, gpu_types::ActivationType, kernel::SSDPrefillKernel},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
struct Input<T: ArrayElement + Float> {
@@ -42,11 +39,6 @@ struct Output<T: ArrayElement + Float> {
state: Vec<T>,
}
-enum KernelType {
- Prefill,
- Sequential,
-}
-
fn get_input<T: ArrayElement + Float>(
suffix_len: usize,
num_heads: usize,
@@ -94,22 +86,19 @@ fn get_input<T: ArrayElement + Float>(
}
}
-fn get_output<B: Backend, T: ArrayElement + Float>(
- input: &Input<T>,
- kernel_type: &KernelType,
-) -> Output<T> {
+fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<T> {
let context = B::Context::new().expect("Failed to create Context");
let total_x = input.suffix_len * input.num_heads * input.head_dim;
- let x_array = context.create_array_from(&[input.x.len()], &input.x);
- let dt_array = context.create_array_from(&[input.dt.len()], &input.dt);
- let b_array = context.create_array_from(&[input.b.len()], &input.b);
- let c_array = context.create_array_from(&[input.c.len()], &input.c);
- let d_array = context.create_array_from(&[input.d.len()], &input.d);
- let z_array = context.create_array_from(&[input.z.len()], &input.z);
- let mut state = context.create_array_from(&[input.state.len()], &input.state).into_allocation();
- let mut y = context.create_array_uninitialized(&[total_x], T::data_type()).into_allocation();
+ let x = alloc_allocation_with_data::<B, T>(&context, &input.x);
+ let dt = alloc_allocation_with_data::<B, T>(&context, &input.dt);
+ let b = alloc_allocation_with_data::<B, T>(&context, &input.b);
+ let c = alloc_allocation_with_data::<B, T>(&context, &input.c);
+ let d = alloc_allocation_with_data::<B, T>(&context, &input.d);
+ let z = alloc_allocation_with_data::<B, T>(&context, &input.z);
+ let mut state = alloc_allocation_with_data::<B, T>(&context, &input.state);
+ let mut y = alloc_allocation::<B, T>(&context, total_x);
let x_strides: [u32; 3] = input.x_strides.map(|s| s as u32);
let dt_strides: [u32; 2] = input.dt_strides.map(|s| s as u32);
@@ -117,69 +106,78 @@ fn get_output<B: Backend, T: ArrayElement + Float>(
let state_strides: [u32; 3] = input.state_strides.map(|s| s as u32);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- match kernel_type {
- KernelType::Prefill => {
- let kernel = <<B as Backend>::Kernels as Kernels>::SSDPrefillKernel::new(&context, T::data_type())
- .expect("Failed to create SSDPrefillKernel");
- kernel.encode(
- x_array.allocation(),
- dt_array.allocation(),
- b_array.allocation(),
- c_array.allocation(),
- d_array.allocation(),
- z_array.allocation(),
- &mut state,
- &mut y,
- input.suffix_len as u32,
- input.group_size,
- input.state_dim as u32,
- &x_strides,
- &dt_strides,
- &cb_strides,
- &state_strides,
- input.num_heads as u32,
- input.head_dim as u32,
- &mut encoder,
- );
- },
- KernelType::Sequential => {
- let kernel =
- <<B as Backend>::Kernels as Kernels>::SSDPrefillSequentialKernel::new(&context, T::data_type())
- .expect("Failed to create SSDPrefillSequentialKernel");
- kernel.encode(
- x_array.allocation(),
- dt_array.allocation(),
- b_array.allocation(),
- c_array.allocation(),
- d_array.allocation(),
- z_array.allocation(),
- &mut state,
- &mut y,
- input.suffix_len as u32,
- input.group_size,
- input.state_dim as u32,
- &x_strides,
- &dt_strides,
- &cb_strides,
- &state_strides,
- input.num_heads as u32,
- input.head_dim as u32,
- &mut encoder,
- );
- },
- };
+ let kernel = <<B as Backend>::Kernels as Kernels>::SSDPrefillKernel::new(&context, T::data_type())
+ .expect("Failed to create SSDPrefillKernel");
+ kernel.encode(
+ &x,
+ &dt,
+ &b,
+ &c,
+ &d,
+ &z,
+ &mut state,
+ &mut y,
+ input.suffix_len as u32,
+ input.group_size,
+ input.state_dim as u32,
+ &x_strides,
+ &dt_strides,
+ &cb_strides,
+ &state_strides,
+ input.num_heads as u32,
+ input.head_dim as u32,
+ &mut encoder,
+ );
encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
Output {
- y: crate::tests::helpers::allocation_to_vec(&y),
- state: crate::tests::helpers::allocation_to_vec(&state),
+ y: allocation_to_vec(&y),
+ state: allocation_to_vec(&state),
+ }
+}
+
+fn reference_output<T: ArrayElement + Float>(input: &Input<T>) -> Output<T> {
+ let safe_group = input.group_size.max(1) as usize;
+ let mut state = input.state.to_vec();
+ let mut y = vec![T::zero(); input.suffix_len * input.num_heads * input.head_dim];
+
+ for h in 0..input.num_heads {
+ let group_idx = h / safe_group;
+ for dh in 0..input.head_dim {
+ let state_base = h * input.state_strides[0] + dh * input.state_strides[1];
+ for token in 0..input.suffix_len {
+ let x_idx = token * input.x_strides[0] + h * input.x_strides[1] + dh * input.x_strides[2];
+ let dt_idx = token * input.dt_strides[0] + h * input.dt_strides[1];
+ let cb_base = token * input.cb_strides[0] + group_idx * input.cb_strides[1];
+
+ let x_val = input.x[x_idx];
+ let dt_val = ActivationType::SOFTPLUS.activate(input.dt[dt_idx]);
+ let decay_val = (-dt_val).exp();
+
+ let mut acc = input.d[h] * x_val;
+ for s in 0..input.state_dim {
+ let state_idx = state_base + s * input.state_strides[2];
+ let cb_idx = cb_base + s * input.cb_strides[2];
+ let new_state = decay_val * state[state_idx] + x_val * input.b[cb_idx];
+ state[state_idx] = new_state;
+ acc = acc + new_state * input.c[cb_idx];
+ }
+
+ let gate = ActivationType::SILU.activate(input.z[x_idx]);
+ y[x_idx] = acc * gate;
+ }
+ }
+ }
+
+ Output {
+ y,
+ state,
}
}
fn test_internal<T: ArrayElement + Float + Debug + Display>(
input: &Input<T>,
expected: &Output<T>,
- kernel_type: &KernelType,
label: &str,
) {
let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
@@ -189,7 +187,7 @@ fn test_internal<T: ArrayElement + Float + Debug + Display>(
};
for_each_non_cpu_backend!(|B| {
- let output = get_output::<B, T>(input, kernel_type);
+ let output = get_output::<B, T>(input);
let backend_name = std::any::type_name::<B>();
let type_name = std::any::type_name::<T>();
@@ -197,13 +195,13 @@ fn test_internal<T: ArrayElement + Float + Debug + Display>(
&expected.y,
&output.y,
eps,
- &format!("SSDPrefillSequential y {backend_name} {label} (type={type_name})"),
+ &format!("SSDPrefill y {backend_name} {label} (type={type_name})"),
);
assert_eq_float::<T>(
&expected.state,
&output.state,
eps,
- &format!("SSDPrefillSequential state {backend_name} {label} (type={type_name})"),
+ &format!("SSDPrefill state {backend_name} {label} (type={type_name})"),
);
});
}
@@ -211,7 +209,6 @@ fn test_internal<T: ArrayElement + Float + Debug + Display>(
// --- test shapes ---
fn test_shape(
- kernel_type: &KernelType,
suffix_len: usize,
num_heads: usize,
head_dim: usize,
@@ -220,7 +217,6 @@ fn test_shape(
label: &str,
) {
fn run<T: ArrayElement + Float + Debug + Display>(
- kernel_type: &KernelType,
suffix_len: usize,
num_heads: usize,
head_dim: usize,
@@ -229,62 +225,36 @@ fn test_shape(
label: &str,
) {
let input = get_input::<T>(suffix_len, num_heads, head_dim, state_dim, group_size);
- let expected = get_output::<Cpu, T>(&input, &KernelType::Sequential);
- test_internal(&input, &expected, kernel_type, label);
+ let expected = reference_output(&input);
+ test_internal(&input, &expected, label);
}
- run::<f32>(kernel_type, suffix_len, num_heads, head_dim, state_dim, group_size, label);
- run::<f16>(kernel_type, suffix_len, num_heads, head_dim, state_dim, group_size, label);
- run::<bf16>(kernel_type, suffix_len, num_heads, head_dim, state_dim, group_size, label);
-}
-
-// --- Sequential ---
-#[uzu_test]
-fn test_sequential_basic() {
- test_shape(&KernelType::Sequential, 512, 32, 64, 64, 1, "sequential_basic");
-}
-
-#[uzu_test]
-fn test_sequential_small() {
- test_shape(&KernelType::Sequential, 4, 4, 4, 8, 1, "sequential_small");
-}
-
-#[uzu_test]
-fn test_sequential_minimal() {
- test_shape(&KernelType::Sequential, 1, 1, 1, 1, 1, "sequential_minimal");
-}
-
-#[uzu_test]
-fn test_sequential_multi_group() {
- test_shape(&KernelType::Sequential, 8, 8, 4, 16, 4, "sequential_multi_group");
-}
-
-#[uzu_test]
-fn test_sequential_group_per_head() {
- test_shape(&KernelType::Sequential, 8, 4, 4, 8, 1, "sequential_group_per_head");
+ run::<f32>(suffix_len, num_heads, head_dim, state_dim, group_size, label);
+ run::<f16>(suffix_len, num_heads, head_dim, state_dim, group_size, label);
+ run::<bf16>(suffix_len, num_heads, head_dim, state_dim, group_size, label);
}
// --- Prefill ---
#[uzu_test]
fn test_prefill_basic() {
- test_shape(&KernelType::Prefill, 512, 32, 64, 64, 1, "prefill_basic");
+ test_shape(512, 32, 64, 64, 1, "prefill_basic");
}
#[uzu_test]
fn test_prefill_small() {
- test_shape(&KernelType::Prefill, 4, 4, 4, 8, 1, "prefill_small");
+ test_shape(4, 4, 4, 8, 1, "prefill_small");
}
#[uzu_test]
fn test_prefill_minimal() {
- test_shape(&KernelType::Prefill, 1, 1, 1, 1, 1, "prefill_minimal");
+ test_shape(1, 1, 1, 1, 1, "prefill_minimal");
}
#[uzu_test]
fn test_prefill_multi_group() {
- test_shape(&KernelType::Prefill, 8, 8, 4, 16, 4, "prefill_multi_group");
+ test_shape(8, 8, 4, 16, 4, "prefill_multi_group");
}
#[uzu_test]
fn test_prefill_group_per_head() {
- test_shape(&KernelType::Prefill, 8, 4, 4, 8, 1, "prefill_group_per_head");
+ test_shape(8, 4, 4, 8, 1, "prefill_group_per_head");
}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_split_inproj_test.rs b/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_split_inproj_test.rs
index 272949b4c..6d6f662de 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_split_inproj_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_split_inproj_test.rs
@@ -6,13 +6,16 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Backend, Context, Encoder, Kernels, kernel::SplitInProjKernel},
cpu::Cpu,
},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
struct Input<T: ArrayElement + Float> {
@@ -63,20 +66,20 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<T
let z_out_size = input.suffix_length as usize * input.inner_dim as usize;
let dt_out_size = input.suffix_length as usize * input.num_heads as usize;
- let input_array = context.create_array_from(&[input.input.len()], &input.input);
- let z_bias_array = context.create_array_from(&[input.z_bias.len()], &input.z_bias);
+ let input_allocation = alloc_allocation_with_data::<B, T>(&context, &input.input);
+ let z_bias = alloc_allocation_with_data::<B, T>(&context, &input.z_bias);
- let mut conv_out = context.create_array_uninitialized(&[conv_out_size], T::data_type()).into_allocation();
- let mut z_out = context.create_array_uninitialized(&[z_out_size], T::data_type()).into_allocation();
- let mut dt_out = context.create_array_uninitialized(&[dt_out_size], T::data_type()).into_allocation();
+ let mut conv_out = alloc_allocation::<B, T>(&context, conv_out_size);
+ let mut z_out = alloc_allocation::<B, T>(&context, z_out_size);
+ let mut dt_out = alloc_allocation::<B, T>(&context, dt_out_size);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- input_array.allocation(),
+ &input_allocation,
&mut conv_out,
&mut z_out,
&mut dt_out,
- z_bias_array.allocation(),
+ &z_bias,
input.suffix_length,
input.total_dim,
input.conv_dim,
@@ -87,9 +90,9 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<T
encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
Output {
- conv_out: crate::tests::helpers::allocation_to_vec(&conv_out),
- z_out: crate::tests::helpers::allocation_to_vec(&z_out),
- dt_out: crate::tests::helpers::allocation_to_vec(&dt_out),
+ conv_out: allocation_to_vec(&conv_out),
+ z_out: allocation_to_vec(&z_out),
+ dt_out: allocation_to_vec(&dt_out),
}
}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_update_test.rs b/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_update_test.rs
index 5f4173047..e89ed54d5 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_update_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/ssm/ssm_update_test.rs
@@ -6,13 +6,16 @@ use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
use crate::{
- array::{ArrayContextExt, ArrayElement},
+ array::ArrayElement,
backends::{
common::{Allocation, Backend, Context, Encoder, Kernels, kernel::SSDUpdateKernel},
cpu::Cpu,
},
data_type::DataType,
- tests::assert::assert_eq_float,
+ tests::{
+ assert::assert_eq_float,
+ helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
+ },
};
struct Input<T: ArrayElement + Float> {
@@ -96,26 +99,26 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<T
let y_size = bsz * h * dh;
let ns_size = bsz * h * dh * n;
- let x_array = context.create_array_from(&[input.x.len()], &input.x);
- let dt_array = context.create_array_from(&[input.dt.len()], &input.dt);
- let b_array = context.create_array_from(&[input.b.len()], &input.b);
- let c_array = context.create_array_from(&[input.c.len()], &input.c);
- let d_array = context.create_array_from(&[input.d.len()], &input.d);
- let z_array = context.create_array_from(&[input.z.len()], &input.z);
+ let x = alloc_allocation_with_data::<B, T>(&context, &input.x);
+ let dt = alloc_allocation_with_data::<B, T>(&context, &input.dt);
+ let b = alloc_allocation_with_data::<B, T>(&context, &input.b);
+ let c = alloc_allocation_with_data::<B, T>(&context, &input.c);
+ let d = alloc_allocation_with_data::<B, T>(&context, &input.d);
+ let z = alloc_allocation_with_data::<B, T>(&context, &input.z);
- let mut y = context.create_array_uninitialized(&[y_size], T::data_type()).into_allocation();
+ let mut y = alloc_allocation::<B, T>(&context, y_size);
if input.state_in_place {
- let mut next_state = context.create_array_from(&[ns_size], &input.state).into_allocation();
+ let mut next_state = alloc_allocation_with_data::<B, T>(&context, &input.state);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- x_array.allocation(),
- dt_array.allocation(),
- b_array.allocation(),
- c_array.allocation(),
- d_array.allocation(),
- z_array.allocation(),
+ &x,
+ &dt,
+ &b,
+ &c,
+ &d,
+ &z,
None::<&Allocation<B>>,
&mut y,
&mut next_state,
@@ -133,22 +136,22 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<T
encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
Output {
- y: crate::tests::helpers::allocation_to_vec(&y),
- next_state: crate::tests::helpers::allocation_to_vec(&next_state),
+ y: allocation_to_vec(&y),
+ next_state: allocation_to_vec(&next_state),
}
} else {
- let state_array = context.create_array_from(&[ns_size], &input.state);
- let mut next_state = context.create_array_uninitialized(&[ns_size], T::data_type()).into_allocation();
+ let state = alloc_allocation_with_data::<B, T>(&context, &input.state);
+ let mut next_state = alloc_allocation::<B, T>(&context, ns_size);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
kernel.encode(
- x_array.allocation(),
- dt_array.allocation(),
- b_array.allocation(),
- c_array.allocation(),
- d_array.allocation(),
- z_array.allocation(),
- Some(state_array.allocation()),
+ &x,
+ &dt,
+ &b,
+ &c,
+ &d,
+ &z,
+ Some(&state),
&mut y,
&mut next_state,
(h / g) as u32,
@@ -165,8 +168,8 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<T
encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");
Output {
- y: crate::tests::helpers::allocation_to_vec(&y),
- next_state: crate::tests::helpers::allocation_to_vec(&next_state),
+ y: allocation_to_vec(&y),
+ next_state: allocation_to_vec(&next_state),
}
}
}
diff --git a/crates/backend-uzu/unit/backends/common/kernel/token_copy_test.rs b/crates/backend-uzu/unit/backends/common/kernel/token_copy_test.rs
index 4af4d17a9..14a4c05d1 100644
--- a/crates/backend-uzu/unit/backends/common/kernel/token_copy_test.rs
+++ b/crates/backend-uzu/unit/backends/common/kernel/token_copy_test.rs
@@ -2,47 +2,27 @@ use proc_macros::uzu_test;
use test_runner::for_each_backend;
use crate::{
- backends::common::{
- Allocation, Backend, Context, Encoder, Kernels,
- kernel::{TokenCopySampledKernel, TokenCopyToResultsKernel},
- },
+ backends::common::{Backend, Context, Encoder, Kernels, kernel::TokenCopySampledKernel},
tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
};
fn test_token_copy_sampled_impl<B: Backend>(src_value: u32) {
let context = B::Context::new().expect("Failed to create Context");
- let kernel = <<B as Backend>::Kernels as Kernels>::TokenCopySampledKernel::new(&context, false)
+ let kernel = <<B as Backend>::Kernels as Kernels>::TokenCopySampledKernel::new(&context)
.expect("Failed to create TokenCopySampledKernel");
let src_allocation = alloc_allocation_with_data::<B, u32>(&context, &[src_value]);
let mut dst_allocation = alloc_allocation::<B, u64>(&context, 1);
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(&src_allocation, &mut dst_allocation, None::<&mut Allocation<B>>, None, &mut encoder);
+ kernel.encode(&src_allocation, &mut dst_allocation, &mut encoder);
encoder.end_encoding().submit().wait_until_completed().unwrap();
let output = allocation_to_vec::<B, u64>(&dst_allocation);
assert_eq!(output[0], src_value as u64, "TokenCopySampled failed for backend {}", std::any::type_name::<B>());
}
-fn test_token_copy_to_results_impl<B: Backend>(src_value: u32) {
- let context = B::Context::new().expect("Failed to create Context");
-
- let kernel = <<B as Backend>::Kernels as Kernels>::TokenCopyToResultsKernel::new(&context)
- .expect("Failed to create TokenCopyToResultsKernel");
-
- let src_allocation = alloc_allocation_with_data::<B, u32>(&context, &[src_value]);
- let mut dst_allocation = alloc_allocation::<B, u32>(&context, 1);
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(&src_allocation, &mut dst_allocation, &mut encoder);
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- let output = allocation_to_vec::<B, u32>(&dst_allocation);
- assert_eq!(output[0], src_value, "TokenCopyToResults failed for backend {}", std::any::type_name::<B>());
-}
-
#[uzu_test]
fn test_token_copy_sampled() {
for_each_backend!(|B| {
@@ -51,12 +31,3 @@ fn test_token_copy_sampled() {
test_token_copy_sampled_impl::<B>(u32::MAX);
});
}
-
-#[uzu_test]
-fn test_token_copy_to_results() {
- for_each_backend!(|B| {
- test_token_copy_to_results_impl::<B>(0);
- test_token_copy_to_results_impl::<B>(42);
- test_token_copy_to_results_impl::<B>(u32::MAX);
- });
-}
diff --git a/crates/backend-uzu/unit/encodable_block/attention_gemm_test.rs b/crates/backend-uzu/unit/encodable_block/attention_gemm_test.rs
index cfdd1eb01..0cce33bdb 100644
--- a/crates/backend-uzu/unit/encodable_block/attention_gemm_test.rs
+++ b/crates/backend-uzu/unit/encodable_block/attention_gemm_test.rs
@@ -5,14 +5,18 @@ use num_traits::Float;
use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
-use super::{AttentionGemmArguments, AttentionGemmBlock};
+use super::AttentionGemmCore;
use crate::{
array::ArrayElement,
backends::{
- common::{Allocation, Backend, Context, Encoder},
+ common::{Backend, Context, Encoder},
cpu::Cpu,
},
data_type::DataType,
+ encodable_block::mixer::attention::{
+ core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments},
+ state::AttentionStateType,
+ },
tests::{
assert::assert_eq_float,
helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
@@ -46,13 +50,13 @@ fn get_test_data<T: ArrayElement + Float>(
queries[i] = T::from((i as f32 * 0.13 + 0.5).sin() * 0.5).unwrap();
}
- let k_size = num_kv_heads * sequence_length * head_dim;
+ let k_size = sequence_length * num_kv_heads * head_dim;
let mut keys = vec![T::zero(); k_size];
for i in 0..k_size {
keys[i] = T::from((i as f32 * 0.07 + 1.0).cos() * 0.5).unwrap();
}
- let v_size = num_kv_heads * sequence_length * head_dim;
+ let v_size = sequence_length * num_kv_heads * head_dim;
let mut values = vec![T::zero(); v_size];
for i in 0..v_size {
values[i] = T::from((i as f32 * 0.11 + 2.0).sin() * 0.5).unwrap();
@@ -80,43 +84,51 @@ fn get_test_data<T: ArrayElement + Float>(
fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
let context = B::Context::new().expect("Failed to create Context");
- let block = AttentionGemmBlock::<B>::new(T::data_type());
+ let core = AttentionGemmCore::<B>::new(
+ &AttentionCoreNewArguments {
+ head_dim: input.head_dim,
+ num_groups: input.num_kv_heads,
+ num_q_heads: input.num_heads,
+ has_sinks: false,
+ is_kv_cache_ring: false,
+ is_causal: input.do_causal,
+ is_trie: false,
+ sliding_window_size: None,
+ scale: Some(input.scale),
+ data_type: T::data_type(),
+ },
+ false,
+ context.as_ref(),
+ )
+ .expect("Failed to create AttentionGemmCore");
let queries_allocation = alloc_allocation_with_data::<B, T>(context.as_ref(), &input.queries);
let keys_allocation = alloc_allocation_with_data::<B, T>(context.as_ref(), &input.keys);
let values_allocation = alloc_allocation_with_data::<B, T>(context.as_ref(), &input.values);
- let output_size = input.suffix_length * input.num_heads * input.head_dim;
- let mut output_allocation = alloc_allocation::<B, T>(context.as_ref(), output_size);
-
let segment_prefix_length = input.sequence_length - input.suffix_length;
+ let state_type = AttentionStateType::Full {
+ length: segment_prefix_length,
+ };
- let args = AttentionGemmArguments::<B, Allocation<B>> {
+ let args = AttentionCoreEncodeArguments {
queries: &queries_allocation,
keys: &keys_allocation,
values: &values_allocation,
- output: &mut output_allocation,
+ suffix_length: input.suffix_length,
trie: None,
sinks: None,
- num_heads: input.num_heads,
- num_groups: input.num_kv_heads,
- suffix_length: input.suffix_length,
- sequence_length: input.sequence_length,
- segment_prefix_length,
- ring_params: None,
- head_dim: input.head_dim,
- sliding_window_size: None,
- is_causal: input.do_causal,
- scale: input.scale,
- k_head_stride: (input.sequence_length * input.head_dim) as u64,
- k_seq_stride: input.head_dim as u64,
- v_head_stride: (input.sequence_length * input.head_dim) as u64,
- v_seq_stride: input.head_dim as u64,
+ state_type: &state_type,
};
let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- block.encode(&mut encoder, args).expect("Failed to encode AttentionGemm");
- encoder.end_encoding().submit().wait_until_completed().unwrap();
+ let pooled_output = core.encode(args, &mut encoder).expect("Failed to encode AttentionGemm");
+ let mut output_allocation =
+ alloc_allocation::<B, T>(context.as_ref(), input.suffix_length * input.num_heads * input.head_dim);
+ encoder.encode_copy(&pooled_output, .., &mut output_allocation, ..);
+ let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
+ drop(pooled_output);
+ drop(completed);
allocation_to_vec::<B, T>(&output_allocation)
}
diff --git a/crates/backend-uzu/unit/encodable_block/attention_test.rs b/crates/backend-uzu/unit/encodable_block/attention_test.rs
index a51a245cb..1c67c16ba 100644
--- a/crates/backend-uzu/unit/encodable_block/attention_test.rs
+++ b/crates/backend-uzu/unit/encodable_block/attention_test.rs
@@ -4,7 +4,7 @@ use ndarray::{Array4, s};
use proc_macros::uzu_test;
use test_tag::tag;
-use super::{AttentionGemmArguments, AttentionGemmBlock};
+use super::{AttentionCoreEncodeArguments, AttentionCoreNewArguments, gemm::AttentionGemmCore};
use crate::{
backends::{
common::{
@@ -14,6 +14,7 @@ use crate::{
metal::Metal,
},
data_type::DataType,
+ encodable_block::mixer::attention::state::AttentionStateType,
tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, submit_encoder},
};
@@ -301,7 +302,6 @@ fn create_two_pass_kernels(
}
fn run_gemm_attention(
- kernel: &AttentionGemmBlock<Metal>,
context: &<Metal as Backend>::Context,
queries: &Array4<f32>,
keys: &Array4<f32>,
@@ -313,41 +313,50 @@ fn run_gemm_attention(
let (batch_size, num_heads, seq_len, head_dim) = queries.dim();
let (_batch_size, num_kv_heads, _seq_len, _head_dim) = keys.dim();
+ let core = AttentionGemmCore::<Metal>::new(
+ &AttentionCoreNewArguments {
+ head_dim,
+ num_groups: num_kv_heads,
+ num_q_heads: num_heads,
+ has_sinks: sinks.is_some(),
+ is_kv_cache_ring: false,
+ is_causal,
+ is_trie: false,
+ sliding_window_size: None,
+ scale: Some(scale),
+ data_type: DataType::F32,
+ },
+ false,
+ context,
+ )?;
+
let query_allocation = create_query_allocation(queries, context);
let key_allocation = create_attention_cache_allocation(keys, seq_len, context);
let value_allocation = create_attention_cache_allocation(values, seq_len, context);
let sinks_allocation = sinks.map(|sinks| create_sinks_allocation(sinks, context));
-
- let mut output_allocation = alloc_allocation::<Metal, f32>(context, num_heads * seq_len * head_dim);
+ let state_type = AttentionStateType::Full {
+ length: 0,
+ };
let mut encoder = Encoder::new(context).expect("Failed to create encoder");
- let args = AttentionGemmArguments {
+ let args = AttentionCoreEncodeArguments {
queries: &query_allocation,
keys: &key_allocation,
values: &value_allocation,
- output: &mut output_allocation,
+ suffix_length: seq_len,
trie: None,
sinks: sinks_allocation.as_ref(),
- num_heads,
- num_groups: num_kv_heads,
- suffix_length: seq_len,
- sequence_length: seq_len,
- segment_prefix_length: 0,
- ring_params: None,
- head_dim,
- sliding_window_size: None,
- is_causal,
- scale,
- k_head_stride: head_dim as u64,
- k_seq_stride: (num_kv_heads * head_dim) as u64,
- v_head_stride: head_dim as u64,
- v_seq_stride: (num_kv_heads * head_dim) as u64,
+ state_type: &state_type,
};
- kernel.encode(&mut encoder, args)?;
- submit_encoder(encoder);
+ let pooled_output = core.encode(args, &mut encoder)?;
+ let mut output_allocation = alloc_allocation::<Metal, f32>(context, num_heads * seq_len * head_dim);
+ encoder.encode_copy(&pooled_output, .., &mut output_allocation, ..);
+ let completed = encoder.end_encoding().submit().wait_until_completed()?;
+ drop(pooled_output);
+ drop(completed);
let output: Vec<f32> = allocation_to_vec(&output_allocation);
@@ -408,10 +417,9 @@ fn test_gemm_attention_basic() {
let (queries, keys, values) = create_test_data(batch_size, num_heads, num_kv_heads, seq_len, head_dim, 123);
- let kernel = AttentionGemmBlock::new(DataType::F32);
let reference_output = reference_attention(&queries, &keys, &values, None, scale, false);
- let kernel_output = run_gemm_attention(&kernel, &context, &queries, &keys, &values, None, scale, false)
- .expect("run gemm attention");
+ let kernel_output =
+ run_gemm_attention(&context, &queries, &keys, &values, None, scale, false).expect("run gemm attention");
compare_results(&kernel_output, &reference_output, 1e-2, "Gemm attention").unwrap();
}
@@ -429,9 +437,8 @@ fn test_gemm_attention_f32_head_dim_128() {
let (queries, keys, values) = create_test_data(batch_size, num_heads, num_kv_heads, seq_len, head_dim, 456);
- let kernel = AttentionGemmBlock::new(DataType::F32);
let reference_output = reference_attention(&queries, &keys, &values, None, scale, false);
- let kernel_output = run_gemm_attention(&kernel, &context, &queries, &keys, &values, None, scale, false)
+ let kernel_output = run_gemm_attention(&context, &queries, &keys, &values, None, scale, false)
.expect("run gemm attention f32 head_dim=128");
compare_results(&kernel_output, &reference_output, 1e-2, "Gemm attention f32 head_dim=128").unwrap();
@@ -455,9 +462,8 @@ fn test_matrix_attention_matches_vector_and_cpu_seq256() {
let kernel = create_single_pass_kernel(&context, head_dim, false, is_causal);
let vector_output = run_single_pass_attention(&kernel, &context, &queries, &keys, &values, None, scale)
.expect("run vector attention");
- let gemm_kernel = AttentionGemmBlock::new(DataType::F32);
- let matrix_output = run_gemm_attention(&gemm_kernel, &context, &queries, &keys, &values, None, scale, is_causal)
- .expect("run matrix attention");
+ let matrix_output =
+ run_gemm_attention(&context, &queries, &keys, &values, None, scale, is_causal).expect("run matrix attention");
let tol_cpu = 5e-2;
compare_results(&vector_output, &reference_output, tol_cpu, "vector single-pass attention vs CPU").unwrap();
compare_results(&matrix_output, &reference_output, tol_cpu, "matrix attention vs CPU").unwrap();
diff --git a/crates/backend-uzu/unit/encodable_block/kv_cache_update_test.rs b/crates/backend-uzu/unit/encodable_block/kv_cache_update_test.rs
deleted file mode 100644
index ecad546e2..000000000
--- a/crates/backend-uzu/unit/encodable_block/kv_cache_update_test.rs
+++ /dev/null
@@ -1,136 +0,0 @@
-#![cfg(metal_backend)]
-
-use ndarray::{Array, Array3, s};
-use proc_macros::uzu_test;
-
-use super::*;
-use crate::{
- backends::{
- common::{Context, Encoder},
- metal::Metal,
- },
- tests::helpers::{sparse_buffer_create_with, sparse_buffer_read_vec},
-};
-
-fn apply_swaps_3d<T: Clone>(
- array: &mut Array3<T>,
- swaps: &[Swap],
-) {
- let (_seq_len, num_heads, head_dim) = array.dim();
- for head in 0..num_heads {
- for channel in 0..head_dim {
- for swap in swaps {
- let src = swap.source as usize;
- let dst = swap.destination as usize;
- let temp = array[(src, head, channel)].clone();
- array[(src, head, channel)] = array[(dst, head, channel)].clone();
- array[(dst, head, channel)] = temp;
- }
- }
- }
-}
-
-fn test_random_pattern<B: Backend>(context: &B::Context) {
- println!("Testing with random pattern...");
-
- let max_sequence_length = 256usize;
- let kv_cache_update = match KVCacheUpdate::new(context, DataType::F32, max_sequence_length) {
- Ok(update) => update,
- Err(e) => {
- println!("Warning: Failed to create KV cache update: {:?}. Skipping test.", e);
- return;
- },
- };
-
- let num_heads = 3usize;
- let seq_len = 15usize;
- let head_dim = 7usize;
-
- let key_data = Array3::<f32>::from_shape_fn((seq_len, num_heads, head_dim), |(h, t, c)| {
- (h * 1_000_000 + t * 100 + c * 10) as f32
- });
-
- let value_data = Array3::<f32>::from_shape_fn((seq_len, num_heads, head_dim), |(h, t, c)| {
- (h * 1_000_000 + t * 100 + c * 10 + 1_000) as f32
- });
-
- let source_indices = vec![0, 3, 6, 9, 12, 2, 5, 8, 11, 14];
- let destination_indices = vec![14, 11, 8, 5, 2, 12, 9, 6, 3, 0];
-
- let mut expected_keys = key_data.clone();
- let mut expected_values = value_data.clone();
-
- let swaps = create_swaps_direct(&source_indices, &destination_indices);
- apply_swaps_3d(&mut expected_keys, &swaps);
- apply_swaps_3d(&mut expected_values, &swaps);
-
- let mut key_buffer = sparse_buffer_create_with::<B, f32>(context, key_data.as_slice().unwrap());
- let mut value_buffer = sparse_buffer_create_with::<B, f32>(context, value_data.as_slice().unwrap());
- let mut encoder = Encoder::<B>::new(context).unwrap();
- {
- let mut kv_layers = [KVLayerData::<B, B::SparseBuffer> {
- key_buffer: &mut key_buffer,
- key_shape: [seq_len, num_heads, head_dim],
- value_buffer: &mut value_buffer,
- value_shape: [seq_len, num_heads, head_dim],
- }];
- match kv_cache_update.encode(&mut kv_layers, &source_indices, &destination_indices, &mut encoder) {
- Ok(_) => {},
- Err(e) => {
- println!("Warning: Failed to encode KV cache update: {:?}. Skipping test.", e);
- return;
- },
- }
- }
-
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- let shape = [seq_len, num_heads, head_dim];
- let elements_count = shape.iter().product();
-
- let key_values: Vec<f32> = sparse_buffer_read_vec::<B, f32>(context, &key_buffer, elements_count);
- let key_result = Array::from_shape_vec((seq_len, num_heads, head_dim), key_values)
- .expect("Failed to convert key result to ndarray");
-
- let value_values: Vec<f32> = sparse_buffer_read_vec::<B, f32>(context, &value_buffer, elements_count);
- let value_result = Array::from_shape_vec((seq_len, num_heads, head_dim), value_values)
- .expect("Failed to convert value result to ndarray");
-
- println!("Original keys tokens 0,14 head 0:");
- println!("Token 0: {:?}", key_data.slice(s![0, 0, ..]));
- println!("Token 14: {:?}", key_data.slice(s![14, 0, ..]));
-
- println!("Result keys tokens 0,14 head 0:");
- println!("Token 0: {:?}", key_result.slice(s![0, 0, ..]));
- println!("Token 14: {:?}", key_result.slice(s![14, 0, ..]));
-
- assert_eq!(key_result, expected_keys);
- assert_eq!(value_result, expected_values);
-}
-
-#[uzu_test]
-fn test_kv_cache_update_kernel() {
- let metal_context = match <Metal as Backend>::Context::new() {
- Ok(ctx) => ctx,
- Err(e) => {
- println!("Failed to create MetalContext: {:?}. Skipping test.", e);
- return;
- },
- };
-
- test_random_pattern::<Metal>(&metal_context);
-}
-
-#[uzu_test]
-fn test_direct_swaps() {
- let sources = [0, 2, 4];
- let destinations = [1, 3, 5];
- let swaps = create_swaps_direct(&sources, &destinations);
- assert_eq!(swaps.len(), 3);
- assert_eq!(swaps[0].source, 0);
- assert_eq!(swaps[0].destination, 1);
- assert_eq!(swaps[1].source, 2);
- assert_eq!(swaps[1].destination, 3);
- assert_eq!(swaps[2].source, 4);
- assert_eq!(swaps[2].destination, 5);
-}
diff --git a/crates/backend-uzu/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs b/crates/backend-uzu/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs
index 8e3d14528..55c90e314 100644
--- a/crates/backend-uzu/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs
+++ b/crates/backend-uzu/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs
@@ -1,13 +1,22 @@
use proc_macros::uzu_test;
use test_runner::for_each_non_cpu_backend;
-use super::{SSDPrefillArguments, SSDPrefillBlock, SSDPrefillMode};
use crate::{
- backends::common::{Backend, Context, Encoder, Kernels, gpu_types::ActivationType, kernel::Conv1dScanKernel},
+ backends::common::{
+ Backend, Context, Encoder, Kernels,
+ gpu_types::ActivationType,
+ kernel::{Conv1dScanKernel, SSDPrefill64Kernel, SSDPrefillKernel},
+ },
data_type::DataType,
- tests::helpers::{alloc_allocation_with_data, allocation_to_vec},
+ tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
};
+#[derive(Debug, Clone, Copy)]
+enum SSDPrefillMode {
+ Universal,
+ Special64,
+}
+
fn ssd_prefill_cpu_reference(
suffix_len: usize,
num_heads: usize,
@@ -135,10 +144,9 @@ impl SSDPrefillFixture {
fn run_prefill_kernel_mode<B: Backend>(
ctx: &B::Context,
- block: &SSDPrefillBlock<B>,
fixture: &SSDPrefillFixture,
mode: SSDPrefillMode,
-) -> (Vec<f32>, Vec<f32>, Option<(Vec<f32>, Vec<f32>, Vec<f32>, Vec<f32>)>) {
+) -> (Vec<f32>, Vec<f32>) {
let x_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.x_data);
let dt_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.dt_data);
let b_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.b_data);
@@ -146,35 +154,72 @@ fn run_prefill_kernel_mode<B: Backend>(
let d_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.d_data);
let z_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.z_data);
let mut state_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.state_init);
+ let mut y_buf = alloc_allocation::<B, f32>(ctx, fixture.suffix_len * fixture.num_heads * fixture.head_dim);
- let args = SSDPrefillArguments {
- x: &x_buf,
- dt: &dt_buf,
- b: &b_buf,
- c: &c_buf,
- d: &d_buf,
- z: &z_buf,
- state: &mut state_buf,
- suffix_len: fixture.suffix_len,
- group_size: fixture.group_size as u32,
- state_size: fixture.state_dim as u32,
- x_strides: fixture.x_strides,
- dt_strides: fixture.dt_strides,
- cb_strides: fixture.cb_strides,
- state_strides: fixture.state_strides,
- channels: fixture.num_heads,
- head_dim: fixture.head_dim,
- };
+ let x_strides = fixture.x_strides.map(|stride| stride as u32);
+ let dt_strides = fixture.dt_strides.map(|stride| stride as u32);
+ let cb_strides = fixture.cb_strides.map(|stride| stride as u32);
+ let state_strides = fixture.state_strides.map(|stride| stride as u32);
let mut encoder = Encoder::new(ctx).unwrap();
- let y_buf = block.encode(&mut encoder, args, mode).expect("Failed to encode SSD prefill");
+ match mode {
+ SSDPrefillMode::Universal => {
+ let kernel = <<B as Backend>::Kernels as Kernels>::SSDPrefillKernel::new(ctx, DataType::F32)
+ .expect("Failed to create SSD prefill kernel");
+ kernel.encode(
+ &x_buf,
+ &dt_buf,
+ &b_buf,
+ &c_buf,
+ &d_buf,
+ &z_buf,
+ &mut state_buf,
+ &mut y_buf,
+ fixture.suffix_len as u32,
+ fixture.group_size as u32,
+ fixture.state_dim as u32,
+ &x_strides,
+ &dt_strides,
+ &cb_strides,
+ &state_strides,
+ fixture.num_heads as u32,
+ fixture.head_dim as u32,
+ &mut encoder,
+ );
+ },
+ SSDPrefillMode::Special64 => {
+ assert_eq!(fixture.state_dim, 64);
+ let kernel = <<B as Backend>::Kernels as Kernels>::SSDPrefill64Kernel::new(ctx, DataType::F32)
+ .expect("Failed to create SSD prefill64 kernel");
+ kernel.encode(
+ &x_buf,
+ &dt_buf,
+ &b_buf,
+ &c_buf,
+ &d_buf,
+ &z_buf,
+ &mut state_buf,
+ &mut y_buf,
+ fixture.suffix_len as u32,
+ fixture.group_size as u32,
+ fixture.state_dim as u32,
+ &x_strides,
+ &dt_strides,
+ &cb_strides,
+ &state_strides,
+ fixture.num_heads as u32,
+ fixture.head_dim as u32,
+ &mut encoder,
+ );
+ },
+ }
let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
let y_vec = allocation_to_vec::<B, f32>(&y_buf);
let state_vec = allocation_to_vec::<B, f32>(&state_buf);
drop(y_buf);
drop(completed);
- (y_vec, state_vec, None)
+ (y_vec, state_vec)
}
fn run_conv_scan_once<B: Backend>(
@@ -198,14 +243,14 @@ fn run_conv_scan_once<B: Backend>(
let mut y_buf = if alias_io {
alloc_allocation_with_data::<B, _>(ctx, x_data)
} else {
- alloc_allocation_with_data::<B, _>(ctx, &vec![0.0f32; total_x])
+ alloc_allocation::<B, f32>(ctx, total_x)
};
- let mut b_out_buf = alloc_allocation_with_data::<B, _>(ctx, &vec![0.0f32; total_x]);
- let mut c_out_buf = alloc_allocation_with_data::<B, _>(ctx, &vec![0.0f32; total_x]);
+ let mut b_out_buf = alloc_allocation::<B, f32>(ctx, total_x);
+ let mut c_out_buf = alloc_allocation::<B, f32>(ctx, total_x);
let w_buf = alloc_allocation_with_data::<B, _>(ctx, w_data);
let b_buf = alloc_allocation_with_data::<B, _>(ctx, b_data);
let mut state_buf = alloc_allocation_with_data::<B, _>(ctx, state_init);
- let scratch_buf = alloc_allocation_with_data::<B, _>(ctx, &vec![0.0f32; total_state]);
+ let mut scratch_buf = alloc_allocation::<B, f32>(ctx, total_state);
let padded_len = tap_count + suffix_len;
let mut padded_host = vec![0.0f32; padded_len * channels];
@@ -222,6 +267,9 @@ fn run_conv_scan_once<B: Backend>(
let padded_buf = alloc_allocation_with_data::<B, _>(ctx, &padded_host);
let mut encoder = Encoder::new(ctx).unwrap();
+ if use_scratch && tap_count > 0 {
+ encoder.encode_fill(&mut scratch_buf, 0);
+ }
kernel.encode(
&padded_buf,
&w_buf,
@@ -258,11 +306,10 @@ fn assert_deterministic_for_mode<B: Backend>(mode: SSDPrefillMode) {
eprintln!("Skipping SSD prefill determinism test: no Metal device");
return;
};
- let block = SSDPrefillBlock::<B>::new(&ctx, DataType::F32).unwrap();
let fixture = SSDPrefillFixture::new();
- let (y_a, state_a, _) = run_prefill_kernel_mode::<B>(&ctx, &block, &fixture, mode);
- let (y_b, state_b, _) = run_prefill_kernel_mode::<B>(&ctx, &block, &fixture, mode);
+ let (y_a, state_a) = run_prefill_kernel_mode::<B>(&ctx, &fixture, mode);
+ let (y_b, state_b) = run_prefill_kernel_mode::<B>(&ctx, &fixture, mode);
assert_eq!(y_a, y_b, "Prefill outputs differ in {:?} mode", mode);
assert_eq!(state_a, state_b, "Prefill states differ in {:?} mode", mode);
@@ -273,7 +320,6 @@ fn assert_matches_cpu_reference<B: Backend>(mode: SSDPrefillMode) {
eprintln!("Skipping SSD prefill reference test: no Metal device");
return;
};
- let block = SSDPrefillBlock::<B>::new(&ctx, DataType::F32).unwrap();
let fixture = SSDPrefillFixture::new();
let (y_ref, state_ref) = ssd_prefill_cpu_reference(
@@ -295,7 +341,7 @@ fn assert_matches_cpu_reference<B: Backend>(mode: SSDPrefillMode) {
fixture.state_strides,
);
- let (y_gpu, state_gpu, _) = run_prefill_kernel_mode::<B>(&ctx, &block, &fixture, mode);
+ let (y_gpu, state_gpu) = run_prefill_kernel_mode::<B>(&ctx, &fixture, mode);
let tolerance = 5e-5f32;
let mut max_y_diff = 0.0f32;
@@ -391,30 +437,30 @@ fn conv1d_scan_deterministic_internal<B: Backend>() {
}
#[uzu_test]
-fn ssd_prefill_sequential_is_deterministic() {
+fn ssd_prefill_universal_is_deterministic() {
for_each_non_cpu_backend!(|B| {
- assert_deterministic_for_mode::<B>(SSDPrefillMode::Sequential);
+ assert_deterministic_for_mode::<B>(SSDPrefillMode::Universal);
});
}
#[uzu_test]
-fn ssd_prefill_single_pass_is_deterministic() {
+fn ssd_prefill_special64_is_deterministic() {
for_each_non_cpu_backend!(|B| {
- assert_deterministic_for_mode::<B>(SSDPrefillMode::SinglePass);
+ assert_deterministic_for_mode::<B>(SSDPrefillMode::Special64);
});
}
#[uzu_test]
-fn ssd_prefill_sequential_matches_cpu_reference() {
+fn ssd_prefill_universal_matches_cpu_reference() {
for_each_non_cpu_backend!(|B| {
- assert_matches_cpu_reference::<B>(SSDPrefillMode::Sequential);
+ assert_matches_cpu_reference::<B>(SSDPrefillMode::Universal);
});
}
#[uzu_test]
-fn ssd_prefill_single_pass_matches_cpu_reference() {
+fn ssd_prefill_special64_matches_cpu_reference() {
for_each_non_cpu_backend!(|B| {
- assert_matches_cpu_reference::<B>(SSDPrefillMode::SinglePass);
+ assert_matches_cpu_reference::<B>(SSDPrefillMode::Special64);
});
}
diff --git a/crates/backend-uzu/unit/encodable_block/sampling_test.rs b/crates/backend-uzu/unit/encodable_block/sampling_test.rs
index 6f878b24f..6b6e5f80f 100644
--- a/crates/backend-uzu/unit/encodable_block/sampling_test.rs
+++ b/crates/backend-uzu/unit/encodable_block/sampling_test.rs
@@ -8,11 +8,13 @@ use rand_distr::Normal;
use crate::{
array::ArrayElement,
- backends::common::{AllocationType, Backend, Context, Encoder},
+ backends::common::{AllocationType, Backend, Context, Encoder, gpu_types::trie::TrieNode},
data_type::DataType,
dispatch_dtype,
- encodable_block::Sampling,
- session::parameter::{SamplingMethod, SamplingProcessingOrder},
+ encodable_block::{
+ batch_topology::BatchTopology,
+ sampling::{Sampling, SamplingMethod},
+ },
tests::proptest::{ComparableTestResults, TestContextes, for_each_context, kernel_data_type},
};
@@ -36,7 +38,7 @@ fn do_sampling_backend<B: Backend, T: ArrayElement + Float>(
seeds: Option<&[u64]>,
bitmask: Option<&[u32]>,
vocab_size: usize,
- method: SamplingMethod,
+ method: &SamplingMethod,
batch_size: usize,
) -> Result<SamplingTestResults, TestCaseError> {
let sampling = Sampling::new(T::data_type(), vocab_size);
@@ -59,6 +61,15 @@ fn do_sampling_backend<B: Backend, T: ArrayElement + Float>(
None
};
+ let nodes = (0..batch_size)
+ .map(|index| TrieNode {
+ trie_start: index as u32,
+ trie_end: (batch_size - 1) as u32,
+ height: index as u32,
+ })
+ .collect::<Box<[_]>>();
+ let batch_topology = BatchTopology::new(&nodes, true);
+
let mut encoder = Encoder::new(context).unwrap();
let sampled_allocation = sampling
.encode(
@@ -68,7 +79,8 @@ fn do_sampling_backend<B: Backend, T: ArrayElement + Float>(
None, // TODO
None, // TODO
method,
- batch_size,
+ &batch_topology,
+ 0..batch_size,
&mut encoder,
)
.unwrap();
@@ -130,26 +142,18 @@ fn sampling_case() -> impl Strategy<Value = SamplingCase> {
let min_p = prop_oneof![Just(None), (0.0f32..=1.0).prop_map(Some),];
- let order = prop_oneof![
- Just(SamplingProcessingOrder::TemperatureThenFilters),
- Just(SamplingProcessingOrder::FiltersThenTemperature),
- ];
-
prop_oneof![
Just(SamplingMethod::Greedy),
- (temperature, top_k, top_p, min_p, order).prop_map(
- |(temperature, top_k, top_p, min_p, processing_order)| {
- SamplingMethod::Stochastic {
- temperature,
- top_k,
- top_p,
- min_p,
- repetition_penalty: None, // TODO
- suffix_repetition_length: None, // TODO
- processing_order,
- }
- },
- ),
+ (temperature, top_k, top_p, min_p).prop_map(|(temperature, top_k, top_p, min_p)| {
+ SamplingMethod::Stochastic {
+ temperature,
+ top_k,
+ top_p,
+ min_p,
+ repetition_penalty: None, // TODO
+ suffix_repetition_length: None, // TODO
+ }
+ },),
]
.prop_map(move |method| SamplingCase {
data_type,
@@ -177,7 +181,7 @@ fn test_sampling_prop() {
seeds.as_ref().map(Box::as_ref),
bitmask.as_ref().map(Box::as_ref),
sampling_case.vocab_size,
- sampling_case.method,
+ &sampling_case.method,
sampling_case.batch_size,
))
.compare_results()?
diff --git a/crates/backend-uzu/unit/forward_pass/cache_layers_test.rs b/crates/backend-uzu/unit/forward_pass/cache_layers_test.rs
deleted file mode 100644
index 26fa2607e..000000000
--- a/crates/backend-uzu/unit/forward_pass/cache_layers_test.rs
+++ /dev/null
@@ -1,204 +0,0 @@
-#![cfg(metal_backend)]
-
-use std::{mem::size_of, ops::Range};
-
-use proc_macros::uzu_test;
-
-use super::{CacheEntryIndex, CacheLayer, CacheLayers, LayerCacheBinding};
-use crate::{
- array::ArrayContextExt,
- backends::{
- common::{Allocation, AllocationType, Backend, Context, Encoder, SparseBuffer},
- metal::Metal,
- },
- data_type::DataType,
- forward_pass::kv_cache_layer::{KVCacheLayer, KVCacheLayerState, KVCacheLayerTrait},
-};
-
-fn submit_encoder(encoder: Encoder<Metal>) {
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to submit encoder");
-}
-
-fn allocation_from_slice(
- context: &<Metal as Backend>::Context,
- data: &[f32],
-) -> Allocation<Metal> {
- context.create_array_from(&[data.len()], data).into_allocation()
-}
-
-fn copy_allocation_to_sparse_row(
- context: &<Metal as Backend>::Context,
- allocation: &Allocation<Metal>,
- buffer: &mut <Metal as Backend>::SparseBuffer,
- row_size: usize,
- row_index: usize,
-) {
- let row_range = row_byte_range(row_size, row_index);
- let mut encoder = Encoder::<Metal>::new(context).expect("Failed to create encoder");
- encoder.encode_copy(allocation, 0..row_size, buffer, row_range);
- submit_encoder(encoder);
-}
-
-fn read_sparse_row(
- context: &<Metal as Backend>::Context,
- buffer: &<Metal as Backend>::SparseBuffer,
- row_size: usize,
- row_index: usize,
-) -> Vec<f32> {
- let mut allocation =
- context.create_allocation(row_size, AllocationType::Global).expect("Failed to create allocation");
- let mut encoder = Encoder::<Metal>::new(context).expect("Failed to create encoder");
- encoder.encode_copy(buffer, row_byte_range(row_size, row_index), &mut allocation, 0..row_size);
- submit_encoder(encoder);
- allocation.copyout()
-}
-
-fn row_byte_range(
- row_size: usize,
- row_index: usize,
-) -> Range<usize> {
- row_index * row_size..(row_index + 1) * row_size
-}
-
-fn row_data(
- elements_per_row: usize,
- base_value: f32,
-) -> Vec<f32> {
- (0..elements_per_row).map(|element_index| base_value + element_index as f32).collect()
-}
-
-fn make_cache_layers(
- context: &<Metal as Backend>::Context,
- state: KVCacheLayerState,
- elements_per_row: usize,
-) -> CacheLayers<Metal> {
- let window_length = match state {
- KVCacheLayerState::Windowed {
- window_length,
- ..
- } => window_length,
- KVCacheLayerState::Full {
- ..
- } => panic!("test expects windowed state"),
- };
- let shape = [window_length, elements_per_row, 1];
- let buffer_size = window_length * elements_per_row * size_of::<f32>();
- let layer = KVCacheLayer {
- state,
- keys: context.create_sparse_buffer(buffer_size).expect("Failed to create key buffer"),
- values: context.create_sparse_buffer(buffer_size).expect("Failed to create value buffer"),
- shape,
- data_type: DataType::F32,
- };
-
- CacheLayers {
- max_suffix_length: 0,
- max_prefix_length: window_length,
- entries: vec![CacheLayer::Transformer(Box::new(layer))].into_boxed_slice(),
- bindings: vec![LayerCacheBinding::Owned {
- entry: CacheEntryIndex {
- index: 0,
- },
- }]
- .into_boxed_slice(),
- }
-}
-
-#[uzu_test]
-fn test_cache_layers_copy_from_clones_only_live_window_rows() {
- let Some(context) = <Metal as Backend>::Context::new().ok() else {
- return;
- };
-
- let page_size = context.create_sparse_buffer(1).expect("Failed to create sparse buffer").page_size_bytes();
- let elements_per_row = page_size / size_of::<f32>();
- let row_size = page_size;
-
- let state = KVCacheLayerState::Windowed {
- ring_offset: 1,
- ring_length: 2,
- window_length: 4,
- };
- let mut source = make_cache_layers(&context, state.clone(), elements_per_row);
- let mut destination = make_cache_layers(
- &context,
- KVCacheLayerState::Windowed {
- ring_offset: 0,
- ring_length: 0,
- window_length: 4,
- },
- elements_per_row,
- );
-
- let CacheLayer::Transformer(source_layer) = &mut source.entries[0] else {
- panic!("expected transformer layer");
- };
- let source_layer = source_layer
- .as_any_mut()
- .downcast_mut::<KVCacheLayer<Metal, <Metal as Backend>::SparseBuffer>>()
- .expect("expected sparse KV layer");
-
- source_layer.map_row_range(&context, 1..2).expect("Failed to map source row 1");
- source_layer.map_row_range(&context, 2..3).expect("Failed to map source row 2");
-
- let row_1_keys = row_data(elements_per_row, 101.0);
- let row_2_keys = row_data(elements_per_row, 102.0);
- let row_1_values = row_data(elements_per_row, 201.0);
- let row_2_values = row_data(elements_per_row, 202.0);
-
- copy_allocation_to_sparse_row(
- &context,
- &allocation_from_slice(&context, &row_1_keys),
- &mut source_layer.keys,
- row_size,
- 1,
- );
- copy_allocation_to_sparse_row(
- &context,
- &allocation_from_slice(&context, &row_2_keys),
- &mut source_layer.keys,
- row_size,
- 2,
- );
- copy_allocation_to_sparse_row(
- &context,
- &allocation_from_slice(&context, &row_1_values),
- &mut source_layer.values,
- row_size,
- 1,
- );
- copy_allocation_to_sparse_row(
- &context,
- &allocation_from_slice(&context, &row_2_values),
- &mut source_layer.values,
- row_size,
- 2,
- );
-
- destination.copy_from(&source, &context);
-
- let CacheLayer::Transformer(destination_layer) = &destination.entries[0] else {
- panic!("expected transformer layer");
- };
- let destination_layer = destination_layer
- .as_any()
- .downcast_ref::<KVCacheLayer<Metal, <Metal as Backend>::SparseBuffer>>()
- .expect("expected sparse KV layer");
-
- assert_eq!(read_sparse_row(&context, &destination_layer.keys, row_size, 1), row_1_keys);
- assert_eq!(read_sparse_row(&context, &destination_layer.keys, row_size, 2), row_2_keys);
- assert_eq!(read_sparse_row(&context, &destination_layer.values, row_size, 1), row_1_values);
- assert_eq!(read_sparse_row(&context, &destination_layer.values, row_size, 2), row_2_values);
-
- let KVCacheLayerState::Windowed {
- ring_offset,
- ring_length,
- window_length,
- } = destination_layer.state
- else {
- panic!("expected windowed state");
- };
- assert_eq!(ring_offset, 1);
- assert_eq!(ring_length, 2);
- assert_eq!(window_length, 4);
-}
diff --git a/crates/backend-uzu/unit/forward_pass/kv_cache_state_test.rs b/crates/backend-uzu/unit/forward_pass/kv_cache_state_test.rs
deleted file mode 100644
index e13b2b6c8..000000000
--- a/crates/backend-uzu/unit/forward_pass/kv_cache_state_test.rs
+++ /dev/null
@@ -1,409 +0,0 @@
-#![cfg(metal_backend)]
-
-use proc_macros::uzu_test;
-
-use crate::{
- backends::{
- common::{Backend, Context, Encoder},
- metal::Metal,
- },
- data_type::DataType,
- encodable_block::KVCacheUpdate,
- forward_pass::kv_cache_layer::{KVCacheLayer, KVCacheLayerState, KVCacheLayerTrait},
- tests::helpers::{sparse_buffer_create_with, sparse_buffer_read_vec, sparse_buffer_write},
-};
-
-#[derive(Debug)]
-struct Scenario {
- name: &'static str,
- state: KVCacheLayerState,
- prefix_capacity: usize,
- suffix_capacity: usize,
- accepted_suffix_indices: Vec<usize>,
- number_of_accepted_tokens: usize,
- suffix_start: Option<usize>,
- expected_ring_offset: Option<usize>,
- expected_ring_length: Option<usize>,
- expected_prefix_len: Option<usize>,
- expected_prefix_segment_length: usize,
-}
-
-fn make_test_layer<B: Backend>(
- context: &B::Context,
- state: KVCacheLayerState,
- prefix_capacity: usize,
- suffix_capacity: usize,
-) -> (KVCacheLayer<B, B::SparseBuffer>, [usize; 3]) {
- let total_len = match &state {
- KVCacheLayerState::Full {
- ..
- } => prefix_capacity + suffix_capacity,
- KVCacheLayerState::Windowed {
- window_length,
- ..
- } => window_length + suffix_capacity,
- };
- let shape = [total_len.max(1), 1, 1];
-
- let zeroes = vec![0.0_f32; shape.iter().product()];
- let keys = sparse_buffer_create_with::<B, f32>(context, &zeroes);
- let values = sparse_buffer_create_with::<B, f32>(context, &zeroes);
- let layer = KVCacheLayer {
- state,
- keys,
- values,
- shape,
- data_type: DataType::F32,
- };
- (layer, shape)
-}
-
-fn overwrite_sparse_buffer<B: Backend>(
- context: &B::Context,
- buffer: &mut B::SparseBuffer,
- elements_count: usize,
- updates: &[(usize, f32)],
-) {
- let mut data: Vec<f32> = sparse_buffer_read_vec::<B, f32>(context, buffer, elements_count);
- for (index, value) in updates {
- data[*index] = *value;
- }
- sparse_buffer_write::<B, f32>(context, buffer, &data);
-}
-
-fn fill_arrays<B: Backend>(
- context: &B::Context,
- layer: &mut KVCacheLayer<B, B::SparseBuffer>,
-) -> (Vec<f32>, Vec<f32>) {
- let initial_keys = {
- let len = layer.shape.iter().product();
- let data: Vec<f32> = (0..len).map(|idx| 1_000.0 + idx as f32).collect();
- sparse_buffer_write::<B, f32>(context, &mut layer.keys, &data);
- data
- };
-
- let initial_values = {
- let len = layer.shape.iter().product();
- let data: Vec<f32> = (0..len).map(|idx| 2_000.0 + idx as f32).collect();
- sparse_buffer_write::<B, f32>(context, &mut layer.values, &data);
- data
- };
-
- (initial_keys, initial_values)
-}
-
-fn expected_after_update(
- state: &KVCacheLayerState,
- accepted_indices: &[usize],
- initial: &[f32],
-) -> Vec<f32> {
- let mut expected = initial.to_vec();
- let effective_indices: Vec<usize> =
- if accepted_indices.is_empty() && matches!(state, KVCacheLayerState::Windowed { .. }) {
- vec![0]
- } else {
- accepted_indices.to_vec()
- };
- match state {
- KVCacheLayerState::Full {
- prefix_len,
- } => {
- let prefix_start = *prefix_len;
- for (offset, suffix_idx) in effective_indices.iter().enumerate() {
- let src = prefix_start + *suffix_idx;
- let dst = prefix_start + offset;
- if src != dst {
- expected.swap(dst, src);
- }
- }
- },
- KVCacheLayerState::Windowed {
- ring_offset,
- ring_length,
- window_length,
- } => {
- for (offset, suffix_idx) in effective_indices.iter().enumerate() {
- let src = window_length + *suffix_idx;
- let dst = (ring_length + ring_offset + offset) % *window_length;
- expected.swap(dst, src);
- }
- },
- }
- expected
-}
-
-fn run_scenario<B: Backend>(
- context: &B::Context,
- scenario: &Scenario,
-) {
- let (mut layer, _) =
- make_test_layer(context, scenario.state.clone(), scenario.prefix_capacity, scenario.suffix_capacity);
-
- let state_before_update = layer.state.clone();
-
- let (initial_keys, initial_values) = fill_arrays::<B>(context, &mut layer);
-
- let expected_keys = expected_after_update(&state_before_update, &scenario.accepted_suffix_indices, &initial_keys);
- let expected_values =
- expected_after_update(&state_before_update, &scenario.accepted_suffix_indices, &initial_values);
-
- let total_sequence_length = match &layer.state {
- KVCacheLayerState::Full {
- ..
- } => scenario.prefix_capacity + scenario.suffix_capacity,
- KVCacheLayerState::Windowed {
- window_length,
- ..
- } => window_length + scenario.suffix_capacity,
- };
-
- let kv_cache_update = match KVCacheUpdate::new(context, DataType::F32, total_sequence_length) {
- Ok(update) => update,
- Err(e) => {
- panic!("Failed to create KV cache update for scenario {}: {:?}", scenario.name, e);
- },
- };
-
- let mut encoder = Encoder::new(context).unwrap();
- layer.update_after_acceptance(
- &scenario.accepted_suffix_indices,
- scenario.suffix_start,
- context,
- &mut encoder,
- &kv_cache_update,
- );
-
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- layer.register_accepted_tokens(scenario.number_of_accepted_tokens);
-
- let actual_keys: Vec<f32> = sparse_buffer_read_vec::<B, f32>(context, &layer.keys, expected_keys.len());
- assert_eq!(actual_keys, expected_keys, "{}: key buffer mismatch", scenario.name);
-
- let actual_values: Vec<f32> = sparse_buffer_read_vec::<B, f32>(context, &layer.values, expected_values.len());
- assert_eq!(actual_values, expected_values, "{}: value buffer mismatch", scenario.name);
-
- match &layer.state {
- KVCacheLayerState::Full {
- prefix_len,
- } => {
- if let Some(expected_len) = scenario.expected_prefix_len {
- assert_eq!(*prefix_len, expected_len, "{}: prefix length mismatch", scenario.name);
- }
- },
- KVCacheLayerState::Windowed {
- ring_offset,
- ring_length,
- ..
- } => {
- if let Some(expected_offset) = scenario.expected_ring_offset {
- assert_eq!(*ring_offset, expected_offset, "{}: ring offset mismatch", scenario.name);
- }
- if let Some(expected_length) = scenario.expected_ring_length {
- assert_eq!(*ring_length, expected_length, "{}: ring length mismatch", scenario.name);
- }
- },
- }
-
- assert_eq!(
- layer.prefix_segment_length(),
- scenario.expected_prefix_segment_length,
- "{}: prefix segment length mismatch",
- scenario.name
- );
-}
-
-#[uzu_test]
-fn kv_cache_state_scenarios() {
- let Some(context) = <Metal as Backend>::Context::new().ok() else {
- return;
- };
-
- let scenarios = vec![
- Scenario {
- name: "windowed_after_crossing_window",
- state: KVCacheLayerState::Windowed {
- ring_offset: 1,
- ring_length: 6,
- window_length: 6,
- },
- prefix_capacity: 6,
- suffix_capacity: 3,
- accepted_suffix_indices: vec![0, 1, 2],
- number_of_accepted_tokens: 3,
- suffix_start: None,
- expected_ring_offset: Some(4),
- expected_ring_length: Some(6),
- expected_prefix_len: None,
- expected_prefix_segment_length: 6,
- },
- Scenario {
- name: "windowed_during_crossing_window",
- state: KVCacheLayerState::Windowed {
- ring_offset: 0,
- ring_length: 4,
- window_length: 6,
- },
- prefix_capacity: 6,
- suffix_capacity: 3,
- accepted_suffix_indices: vec![0, 1, 2],
- number_of_accepted_tokens: 3,
- suffix_start: None,
- expected_ring_offset: Some(1),
- expected_ring_length: Some(6),
- expected_prefix_len: None,
- expected_prefix_segment_length: 6,
- },
- Scenario {
- name: "windowed_single_accept_second_wrap",
- state: KVCacheLayerState::Windowed {
- ring_offset: 5,
- ring_length: 6,
- window_length: 6,
- },
- prefix_capacity: 6,
- suffix_capacity: 1,
- accepted_suffix_indices: vec![0],
- number_of_accepted_tokens: 1,
- suffix_start: None,
- expected_ring_offset: Some(0),
- expected_ring_length: Some(6),
- expected_prefix_len: None,
- expected_prefix_segment_length: 6,
- },
- Scenario {
- name: "full_mode_pure_causal",
- state: KVCacheLayerState::Full {
- prefix_len: 4,
- },
- prefix_capacity: 6,
- suffix_capacity: 3,
- accepted_suffix_indices: vec![0, 1, 2],
- number_of_accepted_tokens: 3,
- suffix_start: None,
- expected_ring_offset: None,
- expected_ring_length: None,
- expected_prefix_len: Some(7),
- expected_prefix_segment_length: 7,
- },
- ];
-
- for scenario in &scenarios {
- run_scenario::<Metal>(&context, scenario);
- }
-}
-
-#[uzu_test]
-fn kv_cache_slice_apply_contiguous_window() {
- let Some(context) = <Metal as Backend>::Context::new().ok() else {
- return;
- };
-
- let (mut layer, shape) = make_test_layer::<Metal>(
- &context,
- KVCacheLayerState::Windowed {
- ring_offset: 1,
- ring_length: 3,
- window_length: 4,
- },
- 4,
- 0,
- );
- let (initial_keys, initial_values) = fill_arrays::<Metal>(&context, &mut layer);
-
- let mut encoder = Encoder::<Metal>::new(&context).expect("Failed to create encoder");
- let slice = layer.slice(&context, &mut encoder, 0..2).expect("slice should exist");
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to end and wait encoder");
-
- // Mutate the captured slots.
- let elements_count = shape.iter().product();
- overwrite_sparse_buffer::<Metal>(&context, &mut layer.keys, elements_count, &[(0, -1.0), (1, -2.0)]);
- overwrite_sparse_buffer::<Metal>(&context, &mut layer.values, elements_count, &[(0, -3.0), (1, -4.0)]);
-
- let mut encoder = Encoder::<Metal>::new(&context).expect("Failed to create encoder");
- layer.apply_slice(&context, &mut encoder, &slice, None);
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to end and wait encoder");
-
- let keys_after: Vec<f32> = sparse_buffer_read_vec::<Metal, f32>(&context, &layer.keys, elements_count);
- let values_after: Vec<f32> = sparse_buffer_read_vec::<Metal, f32>(&context, &layer.values, elements_count);
- assert_eq!(keys_after[0..4], initial_keys[0..4], "keys restored for contiguous slice");
- assert_eq!(values_after[0..4], initial_values[0..4], "values restored for contiguous slice");
-}
-
-#[uzu_test]
-fn kv_cache_slice_apply_wrap_window() {
- let Some(context) = <Metal as Backend>::Context::new().ok() else {
- return;
- };
-
- let (mut layer, shape) = make_test_layer::<Metal>(
- &context,
- KVCacheLayerState::Windowed {
- ring_offset: 3,
- ring_length: 3,
- window_length: 4,
- },
- 4,
- 0,
- );
- let (initial_keys, initial_values) = fill_arrays::<Metal>(&context, &mut layer);
-
- let mut encoder = Encoder::<Metal>::new(&context).expect("Failed to create encoder");
- let slice = layer.slice(&context, &mut encoder, 2..4).expect("slice should exist");
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to end and wait encoder");
-
- // Captured slots are expected to wrap; mutate them.
- let elements_count = shape.iter().product();
- overwrite_sparse_buffer::<Metal>(&context, &mut layer.keys, elements_count, &[(2, -11.0), (3, -12.0)]);
- overwrite_sparse_buffer::<Metal>(&context, &mut layer.values, elements_count, &[(2, -13.0), (3, -14.0)]);
-
- let mut encoder = Encoder::<Metal>::new(&context).expect("Failed to create encoder");
- layer.apply_slice(&context, &mut encoder, &slice, None);
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to end and wait encoder");
-
- let keys_after: Vec<f32> = sparse_buffer_read_vec::<Metal, f32>(&context, &layer.keys, elements_count);
- let values_after: Vec<f32> = sparse_buffer_read_vec::<Metal, f32>(&context, &layer.values, elements_count);
- assert_eq!(keys_after[0..4], initial_keys[0..4], "keys restored for wrapped slice");
- assert_eq!(values_after[0..4], initial_values[0..4], "values restored for wrapped slice");
-}
-
-#[uzu_test]
-fn kv_cache_slice_apply_full_restores_metadata() {
- let Some(context) = <Metal as Backend>::Context::new().ok() else {
- return;
- };
-
- let (mut layer, _) = make_test_layer::<Metal>(
- &context,
- KVCacheLayerState::Full {
- prefix_len: 3,
- },
- 6,
- 0,
- );
-
- let mut encoder = Encoder::<Metal>::new(&context).expect("Failed to create encoder");
- let slice = layer.slice(&context, &mut encoder, 0..2).expect("full slice exists");
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to end and wait encoder");
-
- // Mutate metadata.
- if let KVCacheLayerState::Full {
- prefix_len,
- } = &mut layer.state
- {
- *prefix_len = 1;
- }
-
- let mut encoder = Encoder::<Metal>::new(&context).expect("Failed to create encoder");
- layer.apply_slice(&context, &mut encoder, &slice, None);
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to end and wait encoder");
-
- if let KVCacheLayerState::Full {
- prefix_len,
- } = &layer.state
- {
- assert_eq!(*prefix_len, 3, "full slice restores prefix_len");
- } else {
- panic!("expected full state");
- }
-}
diff --git a/crates/backend-uzu/unit/forward_pass/traces/mod.rs b/crates/backend-uzu/unit/forward_pass/traces/mod.rs
deleted file mode 100644
index f68a82f99..000000000
--- a/crates/backend-uzu/unit/forward_pass/traces/mod.rs
+++ /dev/null
@@ -1,79 +0,0 @@
-mod trace_validator;
-mod trace_validator_test;
-
-use crate::{
- array::ArrayContextExt,
- backends::common::Backend,
- classifier::ActivationTrace,
- forward_pass::{model_shape::ModelShape, traces::LayerActivationTrace},
-};
-
-fn create_layer_results<B: Backend>(
- context: &B::Context,
- model_shape: &ModelShape,
- suffix_length: usize,
-) -> Box<[LayerActivationTrace<B>]> {
- (0..model_shape.num_layers).map(|_| LayerActivationTrace::new(context, model_shape, suffix_length)).collect()
-}
-
-impl<B: Backend> LayerActivationTrace<B> {
- #[cfg(all(test, feature = "tracing"))]
- pub fn new(
- context: &B::Context,
- model_shape: &ModelShape,
- suffix_length: usize,
- ) -> Self {
- let main_shape = model_shape.main_shape(suffix_length);
- let main = || context.create_array_uninitialized(&main_shape, model_shape.data_type);
-
- Self {
- inputs: main(),
- pre_attention_norm: main(),
- attention: main(),
- post_attention_norm: main(),
- mlp_inputs: main(),
- pre_mlp_norm: main(),
- mlp: main(),
- post_mlp_norm: main(),
- outputs: main(),
- }
- }
-}
-
-impl<B: Backend> ActivationTrace<B> {
- pub fn new_llm(
- context: &B::Context,
- model_shape: &ModelShape,
- suffix_length: usize,
- ) -> Self {
- let main_shape = model_shape.main_shape(suffix_length);
- let layer_results = create_layer_results(context, model_shape, suffix_length);
-
- Self {
- embedding_norm: None,
- layer_results,
- output_norm: context.create_array_uninitialized(&main_shape, model_shape.data_type),
- output_pooling: None,
- logits: context.create_array_uninitialized(&model_shape.logits_shape(suffix_length), model_shape.data_type),
- }
- }
-
- pub fn new_classifier(
- context: &B::Context,
- model_shape: &ModelShape,
- suffix_length: usize,
- num_labels: usize,
- ) -> Self {
- let main_shape = model_shape.main_shape(suffix_length);
- let layer_results = create_layer_results(context, model_shape, suffix_length);
- let model_dim = model_shape.main_shape(1)[1];
-
- Self {
- embedding_norm: Some(context.create_array_uninitialized(&main_shape, model_shape.data_type)),
- layer_results,
- output_norm: context.create_array_uninitialized(&main_shape, model_shape.data_type),
- output_pooling: Some(context.create_array_uninitialized(&[1, model_dim], model_shape.data_type)),
- logits: context.create_array_uninitialized(&[1, num_labels], model_shape.data_type),
- }
- }
-}
diff --git a/crates/backend-uzu/unit/forward_pass/traces/trace_validator.rs b/crates/backend-uzu/unit/forward_pass/traces/trace_validator.rs
deleted file mode 100644
index f10676b44..000000000
--- a/crates/backend-uzu/unit/forward_pass/traces/trace_validator.rs
+++ /dev/null
@@ -1,1048 +0,0 @@
-//! Unified trace validation for any model type (LLM or classifier).
-//!
-//! This module provides a single `TraceValidator` that can validate activation
-//! traces for any model type. It automatically detects the model type from the
-//! config and runs the appropriate validation.
-
-use std::{
- cell::RefCell,
- collections::HashMap,
- fs::File,
- io::BufReader,
- path::{Path, PathBuf},
- rc::Rc,
-};
-
-use half::{bf16, f16};
-use ndarray::{ArrayView, IxDyn, s};
-use num_traits::NumCast;
-
-use crate::{
- array::{Array, ArrayElement},
- backends::common::{Allocation, AllocationType, Backend, Context, Encoder},
- classifier::{ActivationTrace, Classifier},
- config::model::AnyModelConfig,
- data_type::DataType,
- encodable_block::DecoderDecodeInput,
- forward_pass::{cache_layers::CacheLayers, kv_cache_layer::KVCacheLayer, token_inputs::TokenInputs},
- language_model::language_model_generator_context::LanguageModelGeneratorContext,
- parameters::{ParameterLoader, ParameterLoaderError, ParameterTree, read_metadata},
- session::{
- config::{DecodingConfig, SpeculatorConfig},
- parameter::{AsyncBatchSize, ConfigResolvableValue, ContextLength, ContextMode, PrefillStepSize, SamplingSeed},
- types::Error,
- },
- tests::helpers::sparse_buffer_read_allocation,
-};
-
-fn argmax<T: ArrayElement>(input: &[T]) -> usize {
- input
- .iter()
- .enumerate()
- .fold((0, f32::NEG_INFINITY), |(best_index, best_value), (index, &value)| {
- let value_f32 = NumCast::from(value).unwrap_or(f32::NEG_INFINITY);
- if value_f32 > best_value || (value_f32 == best_value && index < best_index) {
- (index, value_f32)
- } else {
- (best_index, best_value)
- }
- })
- .0
-}
-
-fn sample_argmax<T: ArrayElement>(logits: ArrayView<T, IxDyn>) -> Vec<u64> {
- let mut result = Vec::with_capacity(logits.shape()[0]);
- for row in logits.rows() {
- let max_index = if let Some(slice) = row.as_slice_memory_order() {
- argmax(slice)
- } else {
- let data: Vec<T> = row.iter().copied().collect();
- argmax(&data)
- };
- result.push(max_index as u64);
- }
- result
-}
-// ============================================================================
-// Validation Types
-// ============================================================================
-
-/// Metrics from validating a single tensor.
-pub struct TracerValidationMetrics {
- pub atol: f32,
- pub rtol: f32,
- #[allow(unused)]
- pub fraction_of_allowed_violations: f32,
- pub reference_shape: Vec<usize>,
- pub result_shape: Vec<usize>,
- pub num_violations: usize,
- pub max_allowed_violations: usize,
- pub max_err_idx: usize,
- pub max_err: f32,
- pub max_err_rel: f32,
- pub max_err_reference_value: f32,
- pub rms_diff: f32,
- pub rms_result: f32,
- pub rms_reference: f32,
- pub rel_rms_reference: f32,
- pub diff_max: f32,
- pub diff_avg: f32,
- pub result_nan: bool,
-}
-
-impl TracerValidationMetrics {
- pub fn is_valid(&self) -> bool {
- self.num_violations <= self.max_allowed_violations && !self.result_nan
- }
-
- pub fn message(&self) -> String {
- if self.result_nan {
- return "Result contains NaN values".to_string();
- }
-
- let allowed_violation_explainer = if self.max_allowed_violations > 0 {
- format!(" (Max {} allowed)", self.max_allowed_violations)
- } else {
- String::new()
- };
-
- let reference_size: usize = self.reference_shape.iter().product();
-
- format!(
- "{} violations > {:.1e} + {:.2}% out of total {} elements{}.\n\
- Worst violation: {:.3} ({:.2}%) at index {} (reference value: {:.3}).\n\
- Error RMS: {:.3}.\n\
- RMS of result: {:.3}, RMS of reference: {:.3}.\n\
- Relative error RMS: {:.2}% of RMS of reference.\n\
- Shape: {:?}\n\
- Max diff: {:.3}, Avg diff: {:.3}",
- self.num_violations,
- self.atol,
- self.rtol * 100.0,
- reference_size,
- allowed_violation_explainer,
- self.max_err,
- self.max_err_rel * 100.0,
- self.max_err_idx,
- self.max_err_reference_value,
- self.rms_diff,
- self.rms_result,
- self.rms_reference,
- self.rel_rms_reference * 100.0,
- self.result_shape,
- self.diff_max,
- self.diff_avg,
- )
- }
-}
-
-/// Result of validating a single tensor.
-pub struct TracerValidationResult {
- pub name: String,
- pub metrics: TracerValidationMetrics,
-}
-
-/// Results from validating all traces.
-pub struct TracerValidationResults {
- pub suffix_length: usize,
- pub results: Vec<TracerValidationResult>,
- pub tokens_violation_indices: Vec<usize>,
-}
-
-impl TracerValidationResults {
- pub fn number_of_tokens_violations(&self) -> usize {
- self.tokens_violation_indices.len()
- }
-
- pub fn number_of_allowed_tokens_violations(&self) -> usize {
- let threshold: f64 = 0.01;
- (self.suffix_length as f64 * threshold).ceil() as usize
- }
-}
-
-/// Transform to apply to produced arrays before comparison.
-pub enum ArrayTransform {
- /// Slice KV cache to match expected shape.
- KVCacheSlice,
- /// Transform SSM conv state layout.
- SsmConvState,
-}
-
-// ============================================================================
-// Model Context (internal)
-// ============================================================================
-
-#[derive(Clone, Copy)]
-struct LayerTraceRequirements {
- post_mixer_norm: bool,
- post_mlp_norm: bool,
-}
-
-enum ModelContext<B: Backend> {
- LanguageModelGenerator {
- context: LanguageModelGeneratorContext<B>,
- layer_trace_requirements: Box<[LayerTraceRequirements]>,
- },
- Classifier {
- classifier: Classifier<B>,
- layer_trace_requirements: Box<[LayerTraceRequirements]>,
- },
-}
-
-// ============================================================================
-// Unified TraceValidator
-// ============================================================================
-
-/// Unified trace validator for any model type.
-///
-/// Automatically detects whether the model is an LLM or classifier and
-/// runs the appropriate validation.
-pub struct TraceValidator<B: Backend> {
- model_path: PathBuf,
- context: ModelContext<B>,
-}
-
-impl<B: Backend> TraceValidator<B> {
- /// Create a new trace validator for the given model path.
- ///
- /// Automatically detects the model type from config.json.
- pub fn new(model_path: &Path) -> Result<Self, Error> {
- if !model_path.exists() {
- return Err(Error::ModelFolderNotFound);
- }
-
- let config_path = model_path.join("config.json");
- let config_file = File::open(&config_path)?;
- let model_config: AnyModelConfig = serde_json::from_reader(BufReader::new(config_file))?;
-
- let context = match model_config {
- AnyModelConfig::ClassifierModelConfig(model_config) => {
- let layer_trace_requirements = model_config
- .classifier_config
- .transformer_config
- .layer_configs
- .iter()
- .map(|layer_config| LayerTraceRequirements {
- post_mixer_norm: layer_config.post_mixer_norm_config.is_some(),
- post_mlp_norm: layer_config.post_mlp_norm_config.is_some(),
- })
- .collect();
- ModelContext::Classifier {
- classifier: Classifier::new(model_path, &model_config)?,
- layer_trace_requirements,
- }
- },
- AnyModelConfig::LanguageModelConfig(model_config) => {
- let layer_trace_requirements = model_config
- .decoder_config
- .transformer_config
- .layer_configs
- .iter()
- .map(|layer_config| LayerTraceRequirements {
- post_mixer_norm: layer_config.post_mixer_norm_config.is_some(),
- post_mlp_norm: layer_config.post_mlp_norm_config.is_some(),
- })
- .collect();
- let prefill_step_size = Self::determine_prefill_step_size(model_path)?;
- let decoding_config = DecodingConfig::new(
- ContextMode::default(),
- ContextLength::default(),
- PrefillStepSize::Custom(prefill_step_size),
- SpeculatorConfig::default(),
- SamplingSeed::default(),
- AsyncBatchSize::default(),
- );
- let mut llm_context = LanguageModelGeneratorContext::new(model_path, &decoding_config, &model_config)?;
- let desired_suffix_length = prefill_step_size.max(decoding_config.generate_suffix_length());
- Self::ensure_llm_context_capacity(&decoding_config, desired_suffix_length, &mut llm_context);
- ModelContext::LanguageModelGenerator {
- context: llm_context,
- layer_trace_requirements,
- }
- },
- AnyModelConfig::TTSModelConfig(_) => {
- return Err(Error::InvalidModelConfig("TTS trace validation is not supported".to_string()));
- },
- AnyModelConfig::DFlashSpeculatorConfig(_) => {
- return Err(Error::InvalidModelConfig(
- "DFlash speculator trace validation is not supported".to_string(),
- ));
- },
- };
-
- Ok(Self {
- model_path: model_path.to_path_buf(),
- context,
- })
- }
-
- /// Run trace validation and return results.
- pub fn run(&mut self) -> Result<TracerValidationResults, Error> {
- let traces_path = self.model_path.join("traces.safetensors");
- match &mut self.context {
- ModelContext::LanguageModelGenerator {
- context,
- layer_trace_requirements,
- } => Self::run_llm_validation(context, layer_trace_requirements, &traces_path),
- ModelContext::Classifier {
- classifier,
- layer_trace_requirements,
- } => Self::run_classifier_validation(classifier, layer_trace_requirements, &traces_path),
- }
- }
-
- // ========================================================================
- // LLM Validation
- // ========================================================================
-
- fn run_llm_validation(
- ctx: &LanguageModelGeneratorContext<B>,
- layer_trace_requirements: &[LayerTraceRequirements],
- traces_path: &Path,
- ) -> Result<TracerValidationResults, Error> {
- let traces_file = File::open(traces_path).map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let (_header_len, traces_metadata) =
- read_metadata(&traces_file).map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let trace_shapes: HashMap<String, Vec<usize>> =
- traces_metadata.tensors.iter().map(|(name, tensor)| (name.clone(), tensor.shape.clone())).collect();
- let token_shape = Self::trace_shape(&trace_shapes, "activation_trace.token_ids");
- let position_shape = Self::trace_shape(&trace_shapes, "activation_trace.token_positions");
- let suffix_length = Self::trace_token_count("activation_trace.token_ids", token_shape);
- assert_eq!(
- Self::trace_token_count("activation_trace.token_positions", position_shape),
- suffix_length,
- "trace token ids and token positions must have the same suffix length"
- );
-
- let traces_loader = ParameterLoader::new(&traces_file, ctx.context.as_ref())
- .map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let traces_view = traces_loader.tree();
-
- let token_ids = Self::load_array_as_vec::<i32, u64>(&traces_view, &trace_shapes, "activation_trace.token_ids");
- let token_positions =
- Self::load_array_as_vec::<i32, usize>(&traces_view, &trace_shapes, "activation_trace.token_positions");
- let token_inputs = TokenInputs::new_llm(
- ctx.context.as_ref(),
- &ctx.model_shape,
- &token_ids,
- None,
- &token_positions,
- None,
- /*sampling_start=*/ 0,
- /*sampling_length=*/ suffix_length,
- );
- let mut traces = ActivationTrace::new_llm(ctx.context.as_ref(), &ctx.model_shape, suffix_length);
-
- let mut encoder =
- Encoder::<B>::new(ctx.context.as_ref()).map_err(|e| Error::UnableToCreateCommandBuffer(e.into()))?;
- {
- let mut cache_layers = ctx.cache_layers.borrow_mut();
- let decoder_arguments = token_inputs.decoder_arguments(
- Some(&mut *cache_layers),
- suffix_length,
- /*sampling_start=*/ 0,
- /*sampling_length=*/ suffix_length,
- Some(&mut traces),
- );
- ctx.executables
- .encode_decode(
- decoder_arguments,
- DecoderDecodeInput::TokenIds(token_inputs.token_ids()),
- None,
- &mut encoder,
- )
- .map_err(|e| Error::EncodeFailed(Box::new(e)))?;
- }
- let pending = encoder.end_encoding().submit();
- pending.wait_until_completed().map_err(|e| Error::CommandBufferFailed(Box::new(e)))?;
-
- // Common layer validation
- let mut results = Self::validate_layer_traces(
- &traces,
- &traces_view,
- &trace_shapes,
- ctx.model_shape.data_type,
- layer_trace_requirements,
- );
-
- // LLM-specific state validation
- let cache = ctx.cache_layers.borrow();
- for (index, layer) in cache.iter_layers() {
- if let Some(kv) = layer.as_transformer() {
- let shape = kv.shape();
- let keys_path = format!("activation_trace.layer_results.{}.updated_state.keys", index);
- let expected =
- Self::read_required_array(&traces_view, &trace_shapes, &keys_path, ctx.model_shape.data_type);
- let size = shape.iter().product::<usize>() * ctx.model_shape.data_type.size_in_bytes();
- let keys = if let Some(layer) = kv.as_any().downcast_ref::<KVCacheLayer<B, B::SparseBuffer>>() {
- sparse_buffer_read_allocation(ctx.context.as_ref(), &layer.keys, size)
- } else if let Some(layer) = kv.as_any().downcast_ref::<KVCacheLayer<B, B::DenseBuffer>>() {
- let mut allocation = ctx
- .context
- .create_allocation(size, AllocationType::Global)
- .expect("Failed to create KV cache keys read allocation");
- let mut encoder =
- Encoder::<B>::new(ctx.context.as_ref()).expect("Failed to create KV cache keys read encoder");
- encoder.encode_copy(&layer.keys, 0..size, &mut allocation, 0..size);
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to read KV cache keys");
- allocation
- } else {
- panic!("Wrong keys type")
- };
- results.push(TracerValidationResult {
- name: keys_path,
- metrics: Self::validate_allocation(
- ctx.model_shape.data_type,
- &expected,
- &keys,
- &shape,
- Some(ArrayTransform::KVCacheSlice),
- ),
- });
-
- let values_path = format!("activation_trace.layer_results.{}.updated_state.values", index);
- let expected =
- Self::read_required_array(&traces_view, &trace_shapes, &values_path, ctx.model_shape.data_type);
- let values = if let Some(layer) = kv.as_any().downcast_ref::<KVCacheLayer<B, B::SparseBuffer>>() {
- sparse_buffer_read_allocation(ctx.context.as_ref(), &layer.values, size)
- } else if let Some(layer) = kv.as_any().downcast_ref::<KVCacheLayer<B, B::DenseBuffer>>() {
- let mut allocation = ctx
- .context
- .create_allocation(size, AllocationType::Global)
- .expect("Failed to create KV cache values read allocation");
- let mut encoder =
- Encoder::<B>::new(ctx.context.as_ref()).expect("Failed to create KV cache values read encoder");
- encoder.encode_copy(&layer.values, 0..size, &mut allocation, 0..size);
- encoder.end_encoding().submit().wait_until_completed().expect("Failed to read KV cache values");
- allocation
- } else {
- panic!("Wrong values type")
- };
- results.push(TracerValidationResult {
- name: values_path,
- metrics: Self::validate_allocation(
- ctx.model_shape.data_type,
- &expected,
- &values,
- &shape,
- Some(ArrayTransform::KVCacheSlice),
- ),
- });
- } else if let Some(ssm) = layer.as_state_space() {
- let conv_path = format!("activation_trace.layer_results.{}.updated_state.conv_state", index);
- let expected =
- Self::read_required_array(&traces_view, &trace_shapes, &conv_path, ctx.model_shape.data_type);
- let conv_state = ssm.conv_state.as_ref().expect("SSM trace requires a produced conv state");
- results.push(TracerValidationResult {
- name: conv_path,
- metrics: Self::validate_allocation(
- ctx.model_shape.data_type,
- &expected,
- conv_state,
- &ssm.conv_shape,
- Some(ArrayTransform::SsmConvState),
- ),
- });
-
- let ssm_path = format!("activation_trace.layer_results.{}.updated_state.ssm_state", index);
- let expected =
- Self::read_required_array(&traces_view, &trace_shapes, &ssm_path, ctx.model_shape.data_type);
- results.push(TracerValidationResult {
- name: ssm_path,
- metrics: Self::validate_allocation(
- ctx.model_shape.data_type,
- &expected,
- &ssm.ssm_state,
- &ssm.ssm_shape,
- None,
- ),
- });
- } else if let Some(delta) = layer.as_delta_net() {
- let conv_path = format!("activation_trace.layer_results.{}.updated_state.conv_state", index);
- let expected =
- Self::read_required_array(&traces_view, &trace_shapes, &conv_path, ctx.model_shape.data_type);
- results.push(TracerValidationResult {
- name: conv_path,
- metrics: Self::validate_allocation(
- ctx.model_shape.data_type,
- &expected,
- &delta.conv_state,
- &delta.conv_shape,
- Some(ArrayTransform::SsmConvState),
- ),
- });
-
- let ssm_path = format!("activation_trace.layer_results.{}.updated_state.ssm_state", index);
- let expected =
- Self::read_required_array(&traces_view, &trace_shapes, &ssm_path, ctx.model_shape.data_type);
- results.push(TracerValidationResult {
- name: ssm_path,
- metrics: Self::validate_allocation(
- ctx.model_shape.data_type,
- &expected,
- &delta.ssm_state,
- &delta.ssm_shape,
- None,
- ),
- });
- } else if let Some(short_conv) = layer.as_short_conv() {
- let conv_path = format!("activation_trace.layer_results.{}.updated_state.conv_state", index);
- let expected =
- Self::read_required_array(&traces_view, &trace_shapes, &conv_path, ctx.model_shape.data_type);
- results.push(TracerValidationResult {
- name: conv_path,
- metrics: Self::validate_allocation(
- ctx.model_shape.data_type,
- &expected,
- &short_conv.conv_state,
- &short_conv.conv_shape,
- Some(ArrayTransform::SsmConvState),
- ),
- });
- } else {
- panic!("Unsupported cache layer type at layer {index}");
- }
- }
-
- // LLM-specific: Token comparison
- let expected_logits =
- Self::read_required_array(&traces_view, &trace_shapes, "logits", ctx.model_shape.data_type);
- let expected_tokens = Self::get_tokens_from_logits(&expected_logits);
- let produced_tokens = Self::get_tokens_from_logits(&traces.logits);
- let tokens_violation_indices = expected_tokens
- .iter()
- .zip(produced_tokens.iter())
- .enumerate()
- .filter_map(|(i, (a, b))| {
- if a != b {
- Some(i)
- } else {
- None
- }
- })
- .collect();
-
- traces_view.assert_all_tensors_validated().unwrap_or_else(|error| {
- panic!("Trace contains tensors that Uzu tracer did not validate: {error}");
- });
-
- Ok(TracerValidationResults {
- suffix_length,
- results,
- tokens_violation_indices,
- })
- }
-
- // ========================================================================
- // Classifier Validation
- // ========================================================================
-
- fn run_classifier_validation(
- classifier: &mut Classifier<B>,
- layer_trace_requirements: &[LayerTraceRequirements],
- traces_path: &Path,
- ) -> Result<TracerValidationResults, Error> {
- let traces_file = File::open(traces_path).map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let (_header_len, traces_metadata) =
- read_metadata(&traces_file).map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let trace_shapes: HashMap<String, Vec<usize>> =
- traces_metadata.tensors.iter().map(|(name, tensor)| (name.clone(), tensor.shape.clone())).collect();
- let context = classifier.context.context.clone();
- let traces_loader = ParameterLoader::new(&traces_file, context.as_ref())
- .map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let traces_view = traces_loader.tree();
-
- let token_shape = Self::trace_shape(&trace_shapes, "activation_trace.token_ids");
- let position_shape = Self::trace_shape(&trace_shapes, "activation_trace.token_positions");
- let suffix_length = Self::trace_token_count("activation_trace.token_ids", token_shape);
- assert_eq!(
- Self::trace_token_count("activation_trace.token_positions", position_shape),
- suffix_length,
- "trace token ids and token positions must have the same suffix length"
- );
-
- let token_ids = Self::load_array_as_vec::<i32, u64>(&traces_view, &trace_shapes, "activation_trace.token_ids");
- let token_positions =
- Self::load_array_as_vec::<i32, usize>(&traces_view, &trace_shapes, "activation_trace.token_positions");
-
- let (_logits, traces) = classifier.forward_pass_with_traces(&token_ids, &token_positions)?;
-
- // Common layer validation
- let mut results = Self::validate_layer_traces(
- &traces,
- &traces_view,
- &trace_shapes,
- classifier.context.model_shape.data_type,
- layer_trace_requirements,
- );
-
- // Classifier-specific: embedding_norm, output_pooling
- let classifier_results = Self::validate_classifier_traces(
- &traces,
- &traces_view,
- &trace_shapes,
- classifier.context.model_shape.data_type,
- );
- results.extend(classifier_results);
- traces_view.assert_all_tensors_validated().unwrap_or_else(|error| {
- panic!("Trace contains tensors that Uzu tracer did not validate: {error}");
- });
-
- Ok(TracerValidationResults {
- suffix_length,
- results,
- tokens_violation_indices: Vec::new(), // Classifiers don't compare tokens
- })
- }
-
- // ========================================================================
- // Common Validation Helpers
- // ========================================================================
-
- fn validate_layer_traces(
- traces: &ActivationTrace<B>,
- traces_view: &ParameterTree<B>,
- trace_shapes: &HashMap<String, Vec<usize>>,
- data_type: DataType,
- layer_trace_requirements: &[LayerTraceRequirements],
- ) -> Vec<TracerValidationResult> {
- let mut results = Vec::new();
-
- assert_eq!(
- traces.layer_results.len(),
- layer_trace_requirements.len(),
- "trace layer count must match model layer count"
- );
-
- let validate = |path: &str, array: &Array<B>| -> TracerValidationResult {
- let expected = Self::read_required_array(traces_view, trace_shapes, path, data_type);
- TracerValidationResult {
- name: path.to_string(),
- metrics: Self::validate_allocation(data_type, &expected, array.allocation(), array.shape(), None),
- }
- };
-
- for (index, layer_traces) in traces.layer_results.iter().enumerate() {
- let requirements = layer_trace_requirements[index];
- let path = |suffix: &str| -> String {
- format!("activation_trace.layer_results.{}.activation_trace.{}", index, suffix)
- };
-
- results.push(validate(&path("inputs"), &layer_traces.inputs));
- results.push(validate(&path("pre_mixer_norm"), &layer_traces.pre_attention_norm));
- results.push(validate(&path("mixer"), &layer_traces.attention));
- if requirements.post_mixer_norm {
- results.push(validate(&path("post_mixer_norm"), &layer_traces.post_attention_norm));
- }
- results.push(validate(&path("mlp_inputs"), &layer_traces.mlp_inputs));
- results.push(validate(&path("pre_mlp_norm"), &layer_traces.pre_mlp_norm));
- results.push(validate(&path("mlp"), &layer_traces.mlp));
- if requirements.post_mlp_norm {
- results.push(validate(&path("post_mlp_norm"), &layer_traces.post_mlp_norm));
- }
-
- let outputs_path = format!("activation_trace.layer_results.{}.outputs", index);
- results.push(validate(&outputs_path, &layer_traces.outputs));
- }
-
- // Output norm (common to all models)
- results.push(validate("activation_trace.output_norm", &traces.output_norm));
-
- // Logits live on DecoderResult/ClassifierResult, not inside activation_trace.
- results.push(validate("logits", &traces.logits));
-
- results
- }
-
- fn validate_classifier_traces(
- traces: &ActivationTrace<B>,
- traces_view: &ParameterTree<B>,
- trace_shapes: &HashMap<String, Vec<usize>>,
- data_type: DataType,
- ) -> Vec<TracerValidationResult> {
- let mut results = Vec::new();
-
- let embedding_norm =
- traces.embedding_norm.as_ref().expect("classifier traces must include produced embedding norm output");
- let expected =
- Self::read_required_array(traces_view, trace_shapes, "activation_trace.embedding_norm_output", data_type);
- results.push(TracerValidationResult {
- name: "activation_trace.embedding_norm_output".to_string(),
- metrics: Self::validate_allocation(
- data_type,
- &expected,
- embedding_norm.allocation(),
- embedding_norm.shape(),
- None,
- ),
- });
-
- if let Some(output_pooling) = &traces.output_pooling {
- let expected =
- Self::read_required_array(traces_view, trace_shapes, "activation_trace.output_pooling", data_type);
- results.push(TracerValidationResult {
- name: "activation_trace.output_pooling".to_string(),
- metrics: Self::validate_allocation(
- data_type,
- &expected,
- output_pooling.allocation(),
- output_pooling.shape(),
- None,
- ),
- });
- } else {
- panic!("classifier traces must include produced output pooling");
- };
-
- results
- }
-
- // ========================================================================
- // Allocation Validation
- // ========================================================================
-
- fn validate_allocation(
- data_type: DataType,
- expected_array: &Array<B>,
- produced_allocation: &Allocation<B>,
- produced_shape: &[usize],
- transform: Option<ArrayTransform>,
- ) -> TracerValidationMetrics {
- match data_type {
- DataType::F16 => {
- Self::validate_allocation_of_type::<f16>(expected_array, produced_allocation, produced_shape, transform)
- },
- DataType::BF16 => Self::validate_allocation_of_type::<bf16>(
- expected_array,
- produced_allocation,
- produced_shape,
- transform,
- ),
- DataType::F32 => {
- Self::validate_allocation_of_type::<f32>(expected_array, produced_allocation, produced_shape, transform)
- },
- _ => panic!("Unsupported data type: {:?}", data_type),
- }
- }
-
- fn validate_allocation_of_type<Precision: ArrayElement>(
- expected_array: &Array<B>,
- produced_allocation: &Allocation<B>,
- produced_shape: &[usize],
- transform: Option<ArrayTransform>,
- ) -> TracerValidationMetrics {
- let produced = produced_allocation.copyout::<Precision>();
- Self::validate_allocation_data_of_type(expected_array, &produced, produced_shape, transform)
- }
-
- fn validate_allocation_data_of_type<Precision: ArrayElement>(
- expected_array: &Array<B>,
- produced_slice: &[Precision],
- produced_shape: &[usize],
- transform: Option<ArrayTransform>,
- ) -> TracerValidationMetrics {
- let expected_view = expected_array.as_view::<Precision>();
- let produced_view = ndarray::ArrayView::from_shape(IxDyn(produced_shape), produced_slice)
- .expect("Failed to reshape allocation");
-
- let (expected_data, mut produced_data) = match transform {
- Some(ArrayTransform::KVCacheSlice) => {
- let expected_shape = expected_view.shape();
- let expected_tokens = expected_view.shape()[1];
- let sliced = produced_view.slice(s![..expected_tokens, .., ..]);
- let reshaped = sliced
- .into_owned()
- .to_shape(IxDyn(expected_shape))
- .expect("Failed to reshape KV cache slice")
- .to_owned();
- (expected_view.to_owned(), reshaped)
- },
- Some(ArrayTransform::SsmConvState) => {
- let produced_shape = produced_view.shape();
- let history_len = produced_shape[1];
- let dim = produced_shape[0];
-
- let permuted = expected_view.permuted_axes(IxDyn(&[0, 2, 1]));
- let total_time = permuted.shape()[2];
- let start = total_time.saturating_sub(history_len);
- let sliced = permuted.slice(s![.., .., start..]);
-
- let reshaped_expected = sliced
- .into_owned()
- .to_shape(IxDyn(&[dim, history_len]))
- .expect("Failed to reshape SSM conv state slice")
- .to_owned();
-
- (reshaped_expected, produced_view.to_owned())
- },
- None => (expected_view.to_owned(), produced_view.to_owned()),
- };
-
- let expected_shape = expected_data.shape().to_vec();
- let produced_shape = produced_data.shape().to_vec();
-
- if expected_shape != produced_shape {
- if expected_shape.len() == produced_shape.len() + 1
- && expected_shape.first() == Some(&1)
- && expected_shape[1..] == produced_shape[..]
- {
- produced_data = produced_data
- .to_shape(IxDyn(&expected_shape))
- .expect("Failed to reshape produced data to trace shape")
- .to_owned();
- } else {
- panic!(
- "Shape mismatch: expected trace shape {expected_shape:?}, produced Uzu shape {produced_shape:?}"
- );
- }
- }
-
- if expected_data.shape() != produced_data.shape() {
- panic!(
- "Shape mismatch after alignment: expected {:?}, produced {:?}",
- expected_data.shape(),
- produced_data.shape()
- );
- }
-
- let reference: Vec<f32> = expected_data
- .iter()
- .map(|value| NumCast::from(*value).expect("Failed to cast reference trace value"))
- .collect();
- let result: Vec<f32> = produced_data
- .iter()
- .map(|value| NumCast::from(*value).expect("Failed to cast produced trace value"))
- .collect();
-
- let (atol, rtol, allowed_voilations_tol) = match expected_array.data_type() {
- DataType::BF16 => (0.04, 0.06, 0.03),
- _ => (0.01, 0.03, 0.01),
- };
-
- Self::compare_arrays(
- &reference,
- expected_data.shape().to_vec(),
- &result,
- produced_data.shape().to_vec(),
- atol,
- rtol,
- allowed_voilations_tol,
- )
- }
-
- fn compare_arrays(
- reference: &[f32],
- reference_shape: Vec<usize>,
- result: &[f32],
- result_shape: Vec<usize>,
- atol: f32,
- rtol: f32,
- fraction_of_allowed_violations: f32,
- ) -> TracerValidationMetrics {
- assert_eq!(result.len(), reference.len());
- if reference.is_empty() {
- return TracerValidationMetrics {
- atol,
- rtol,
- fraction_of_allowed_violations,
- reference_shape,
- result_shape,
- num_violations: 0,
- max_allowed_violations: 0,
- max_err_idx: 0,
- max_err: 0.0,
- max_err_rel: 0.0,
- max_err_reference_value: 0.0,
- rms_diff: 0.0,
- rms_result: 0.0,
- rms_reference: 0.0,
- rel_rms_reference: 0.0,
- diff_max: 0.0,
- diff_avg: 0.0,
- result_nan: false,
- };
- }
-
- let mut num_violations = 0;
- let mut max_err = 0.0f32;
- let mut max_err_idx = 0;
- let mut max_err_rel = 0.0f32;
- let mut max_err_reference_value = 0.0f32;
- let mut sum_sq_diff = 0.0f32;
- let mut sum_sq_result = 0.0f32;
- let mut sum_sq_reference = 0.0f32;
- let mut diff_sum = 0.0f32;
- let mut diff_max = 0.0f32;
- let mut result_nan = false;
-
- for (i, (&exp, &prod)) in reference.iter().zip(result.iter()).enumerate() {
- if prod.is_nan() {
- result_nan = true;
- }
-
- let abs_diff = (exp - prod).abs();
- let rel_diff = if exp.abs() > 1e-8 {
- abs_diff / exp.abs()
- } else {
- abs_diff
- };
-
- diff_sum += abs_diff;
- diff_max = diff_max.max(abs_diff);
- sum_sq_diff += abs_diff * abs_diff;
- sum_sq_result += prod * prod;
- sum_sq_reference += exp * exp;
-
- if abs_diff > atol && rel_diff > rtol {
- num_violations += 1;
- }
-
- if abs_diff > max_err {
- max_err = abs_diff;
- max_err_idx = i;
- max_err_rel = rel_diff;
- max_err_reference_value = exp;
- }
- }
-
- let n = reference.len() as f32;
- let rms_diff = (sum_sq_diff / n).sqrt();
- let rms_result = (sum_sq_result / n).sqrt();
- let rms_reference = (sum_sq_reference / n).sqrt();
- let rel_rms_reference = if rms_reference > 1e-8 {
- rms_diff / rms_reference
- } else {
- rms_diff
- };
- let diff_avg = diff_sum / n;
-
- let max_allowed_violations = (fraction_of_allowed_violations * n).ceil() as usize;
-
- TracerValidationMetrics {
- atol,
- rtol,
- fraction_of_allowed_violations,
- reference_shape,
- result_shape,
- num_violations,
- max_allowed_violations,
- max_err_idx,
- max_err,
- max_err_rel,
- max_err_reference_value,
- rms_diff,
- rms_result,
- rms_reference,
- rel_rms_reference,
- diff_max,
- diff_avg,
- result_nan,
- }
- }
-
- // ========================================================================
- // Utility Functions
- // ========================================================================
-
- fn load_array_as_vec<SourcePrecision: ArrayElement, TargetPrecision: NumCast>(
- traces_view: &ParameterTree<B>,
- trace_shapes: &HashMap<String, Vec<usize>>,
- name: &str,
- ) -> Vec<TargetPrecision> {
- let expected_shape = Self::trace_shape(trace_shapes, name);
- let leaf = traces_view
- .leaf(name)
- .unwrap_or_else(|error| panic!("Missing required trace tensor {name}: {error}"))
- .validate(expected_shape, SourcePrecision::data_type())
- .unwrap_or_else(|error| panic!("Invalid trace tensor {name}: {error}"));
- let slice = leaf.read_slice::<SourcePrecision>().unwrap_or_else(|error| {
- panic!("Failed to read trace tensor {name}: {error}");
- });
- slice.iter().map(|x| NumCast::from(*x).expect("Failed to cast trace tensor value")).collect()
- }
-
- fn trace_shape<'shape>(
- trace_shapes: &'shape HashMap<String, Vec<usize>>,
- name: &str,
- ) -> &'shape [usize] {
- trace_shapes.get(name).unwrap_or_else(|| panic!("Missing required trace tensor {name}"))
- }
-
- fn trace_token_count(
- name: &str,
- shape: &[usize],
- ) -> usize {
- let [batch_size, suffix_length] = shape else {
- panic!("Trace tensor {name} must have shape [1, suffix_tokens], got {shape:?}");
- };
- assert_eq!(*batch_size, 1, "Trace tensor {name} must have batch size 1, got {shape:?}");
- *suffix_length
- }
-
- fn read_required_array(
- traces_view: &ParameterTree<B>,
- trace_shapes: &HashMap<String, Vec<usize>>,
- name: &str,
- data_type: DataType,
- ) -> Array<B> {
- let expected_shape = Self::trace_shape(trace_shapes, name);
- Self::read_array(traces_view, name, expected_shape, data_type)
- .unwrap_or_else(|error| panic!("Invalid trace tensor {name}: {error}"))
- }
-
- fn read_array(
- traces_view: &ParameterTree<B>,
- name: &str,
- expected_shape: &[usize],
- data_type: DataType,
- ) -> Result<Array<B>, ParameterLoaderError<B>> {
- traces_view.leaf(name)?.validate(expected_shape, data_type)?.read_array()
- }
-
- fn determine_prefill_step_size(model_path: &Path) -> Result<usize, Error> {
- let traces_path = model_path.join("traces.safetensors");
- let file = File::open(&traces_path).map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let (_header_len, metadata) =
- read_metadata(&file).map_err(|error| Error::UnableToLoadWeights(Box::new(error)))?;
- let token_shape =
- metadata.tensors.get("activation_trace.token_ids").map(|tensor| tensor.shape.as_slice()).ok_or_else(
- || Error::InvalidModelConfig("missing required trace tensor activation_trace.token_ids".to_string()),
- )?;
- let suffix_length = Self::trace_token_count("activation_trace.token_ids", token_shape);
- assert!(suffix_length > 0, "trace must contain at least one token");
- Ok(suffix_length)
- }
-
- fn ensure_llm_context_capacity(
- decoding_config: &DecodingConfig,
- desired_suffix_length: usize,
- context: &mut LanguageModelGeneratorContext<B>,
- ) {
- let resolved_prefix_length = context.get_context_length(decoding_config);
- let current_suffix_length = std::cmp::max(
- decoding_config.prefill_step_size.resolve(&context.model_config),
- decoding_config.generate_suffix_length(),
- );
-
- if desired_suffix_length <= current_suffix_length {
- return;
- }
-
- context.cache_layers = Rc::new(RefCell::new(CacheLayers::new(
- context.context.as_ref(),
- &context.model_shape,
- resolved_prefix_length,
- desired_suffix_length,
- )));
- }
-
- fn get_tokens_from_logits(logits: &Array<B>) -> Vec<u64> {
- let data_type = logits.data_type();
- match data_type {
- DataType::F16 => sample_argmax(logits.as_view::<f16>()),
- DataType::BF16 => sample_argmax(logits.as_view::<bf16>()),
- DataType::F32 => sample_argmax(logits.as_view::<f32>()),
- _ => panic!("Unsupported data type: {:?}", data_type),
- }
- }
-}
diff --git a/crates/backend-uzu/unit/forward_pass/traces/trace_validator_test.rs b/crates/backend-uzu/unit/forward_pass/traces/trace_validator_test.rs
deleted file mode 100644
index 648b13b6e..000000000
--- a/crates/backend-uzu/unit/forward_pass/traces/trace_validator_test.rs
+++ /dev/null
@@ -1,42 +0,0 @@
-use std::path::PathBuf;
-
-use proc_macros::uzu_test;
-use test_runner::{for_each_non_cpu_backend, path::get_test_model_path};
-
-use crate::{backends::common::Backend, forward_pass::traces::tests::trace_validator::TraceValidator};
-
-const TRACES_FILE_NAME: &str = "traces.safetensors";
-
-fn get_traces_path() -> PathBuf {
- get_test_model_path().join(TRACES_FILE_NAME)
-}
-
-fn test_tracer_internal<B: Backend>() {
- let model_path = get_test_model_path();
- let mut tracer = TraceValidator::<B>::new(&model_path).expect("Failed to create TraceValidator");
- let results = tracer.run().expect("Failed to run tracer");
- for result in results.results.iter() {
- assert!(result.metrics.is_valid(), "{} error:\n{}", result.name, result.metrics.message().as_str());
- }
-
- let total_token_violations = results.number_of_tokens_violations();
- let allowed_token_violations = results.number_of_allowed_tokens_violations();
- assert!(
- total_token_violations < allowed_token_violations,
- "Too much token violations: {} / {}. Indices: {:?}",
- total_token_violations,
- allowed_token_violations,
- results.tokens_violation_indices
- );
-}
-
-#[uzu_test]
-#[ignore = "Lalamo 0.10.0 doesn't support exporting traces"] // TODO: this is horrible, should be resolved asap
-fn test_tracer() {
- let traces_path = get_traces_path();
- assert!(traces_path.exists(), "Traces file missing at {:?}", traces_path);
-
- for_each_non_cpu_backend!(|B| {
- test_tracer_internal::<B>();
- })
-}
diff --git a/crates/backend-uzu/unit/language_model/grammar.rs b/crates/backend-uzu/unit/language_model/grammar.rs
deleted file mode 100644
index 18f5e294a..000000000
--- a/crates/backend-uzu/unit/language_model/grammar.rs
+++ /dev/null
@@ -1,93 +0,0 @@
-#![cfg(all(metal_backend, grammar_xgrammar))]
-
-use metal::MTLDevice;
-use proc_macros::uzu_test;
-use schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
-use test_runner::path::get_test_model_path;
-use tokenizers::Tokenizer;
-use xgrammar::{DLDevice, DLDeviceType, DLTensor, Grammar, GrammarCompiler, GrammarMatcher, TokenizerInfo, c_void};
-
-use crate::{
- array::Array,
- backends::{
- common::{AllocationType, Backend, Context},
- metal::Metal,
- },
- data_type::DataType,
-};
-
-#[derive(Debug, Serialize, Deserialize, JsonSchema)]
-struct Person {
- name: String,
- age: u32,
-}
-
-#[uzu_test]
-fn person_schema_metal_bitmask() {
- let model_dir = get_test_model_path();
-
- let tokenizer_path = model_dir.join("tokenizer.json");
- if !tokenizer_path.exists() {
- eprintln!(
- "Skipping test: tokenizer.json not found at {}.\nRun scripts/download_test_model.sh first.",
- tokenizer_path.display()
- );
- return;
- }
-
- let schema_root = schemars::schema_for!(Person);
- let schema_str = serde_json::to_string(&schema_root).expect("schema to string");
-
- let tokenizer = Tokenizer::from_file(&tokenizer_path).expect("load tokenizer.json");
- let tokenizer_info = TokenizerInfo::from_huggingface(&tokenizer, None, None).unwrap();
-
- let grammar = Grammar::from_json_schema(&schema_str, true, Some(2), Some((",", ":")), true, None, false).unwrap();
- let mut compiler = GrammarCompiler::new(&tokenizer_info, 8, true, -1).unwrap();
- let compiled = compiler.compile_grammar(&grammar).unwrap();
-
- let mut matcher = GrammarMatcher::new(&compiled, None, true, -1).unwrap();
-
- let device = match <dyn MTLDevice>::system_default() {
- Some(d) => d,
- None => {
- eprintln!("Skipping test: no Metal device available");
- return;
- },
- };
- let device_id = device.registry_id() as i32;
- let batch: usize = 1;
- let vocab = tokenizer_info.vocab_size();
- // xgrammar uses a dynamic bitset over the vocab, packed into i32 words
- let buffer_size = vocab.div_ceil(32); // number of i32s required
- let shape = [batch, buffer_size];
-
- // xgrammar expects an int32 mask tensor of shape [buffer_size]
- let elems = batch * buffer_size;
- let bytes = elems * core::mem::size_of::<i32>();
- let context = <Metal as Backend>::Context::new().expect("Metal context");
- let allocation =
- context.create_allocation(bytes.max(1), AllocationType::Global).expect("Failed to create allocation");
- let metal_bitmask = unsafe { Array::<Metal>::from_allocation(allocation, 0, &shape, DataType::I32) };
-
- let mut shape_i64 = [buffer_size as i64];
- let mut bitmask_tensor = unsafe {
- DLTensor::new(
- metal_bitmask.cpu_ptr().as_ptr() as *mut c_void,
- DLDevice {
- device_type: DLDeviceType::kDLCPU,
- device_id,
- },
- 1,
- DataType::I32.into(),
- shape_i64.as_mut_ptr(),
- core::ptr::null_mut(),
- 0,
- )
- };
-
- let _ok = matcher.fill_next_token_bitmask(&mut bitmask_tensor, 0, false);
-
- assert_eq!(metal_bitmask.shape(), &shape);
- assert_eq!(metal_bitmask.as_slice::<i32>().len(), elems);
-}
diff --git a/crates/backend-uzu/unit/language_model/language_model_generator_bench.rs b/crates/backend-uzu/unit/language_model/language_model_generator_bench.rs
deleted file mode 100644
index 092ce2cbd..000000000
--- a/crates/backend-uzu/unit/language_model/language_model_generator_bench.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-use std::time::Duration;
-
-use criterion::{BenchmarkId, Criterion, Throughput};
-use proc_macros::uzu_bench;
-use test_runner::{for_each_non_cpu_backend, metrics::wait_gpu_cooldown, path::get_test_model_path};
-
-use crate::{
- backends::common::Backend,
- config::model::language_model::LanguageModelConfig,
- language_model::{LanguageModelGenerator, language_model_generator::RunModelResult},
- session::{config::DecodingConfig, parameter::SamplingMethod},
- trie::{TrieCreationConfig, TrieNode},
-};
-
-fn create_generator<B: Backend>() -> LanguageModelGenerator<B> {
- let model_path = get_test_model_path();
- let decoding_config = DecodingConfig::default();
- let model_config = LanguageModelConfig::new(&model_path).unwrap();
- LanguageModelGenerator::new(&model_path, decoding_config, &model_config).unwrap()
-}
-
-fn run_generator<B: Backend>(
- generator: &mut LanguageModelGenerator<B>,
- tokens: &[u64],
-) -> RunModelResult<B> {
- generator.tokens = tokens.to_vec();
- let speculator = &generator.decoding_config.speculator_config.speculator;
- let suffix_length = generator.decoding_config.generate_suffix_length();
- let suffix_root = TrieNode::from_speculator(
- &generator.tokens,
- &generator.context.seed,
- None,
- speculator.as_ref(),
- 1024, // greedy, doesn't matter
- &TrieCreationConfig::default(),
- suffix_length,
- );
- let flat_trie = suffix_root.linearize();
-
- let task = generator.get_generate_task(&flat_trie, false);
- generator.run_model(task, SamplingMethod::Greedy).unwrap()
-}
-
-#[uzu_bench]
-fn bench_forward_pass(c: &mut Criterion) {
- // Empty prompt first decode: the generate path requires one seed token.
- let tokens: Vec<u64> = vec![0];
- for_each_non_cpu_backend!(|B| {
- wait_gpu_cooldown();
-
- let mut group = c.benchmark_group("Forward pass");
- group.sample_size(10);
- group.throughput(Throughput::Elements(tokens.len() as u64));
- group.bench_function(BenchmarkId::from_parameter("empty prompt first decode"), |b| {
- b.iter_custom(|n_iters| {
- let mut total_duration = Duration::from_secs(0);
- for _ in 0..n_iters {
- let mut generator = create_generator::<B>();
- let result = run_generator(&mut generator, &tokens);
- total_duration += result.gpu_run_time
- }
- total_duration
- });
- });
- group.finish()
- })
-}
diff --git a/crates/backend-uzu/unit/parameters/loader.rs b/crates/backend-uzu/unit/parameters/loader.rs
deleted file mode 100644
index d4e48384c..000000000
--- a/crates/backend-uzu/unit/parameters/loader.rs
+++ /dev/null
@@ -1,45 +0,0 @@
-use std::fs::File;
-
-use half::bf16;
-use proc_macros::uzu_test;
-use test_runner::{for_each_backend, path::get_test_weights_path};
-use test_tag::tag;
-
-use crate::{
- backends::common::{Backend, Context},
- data_type::DataType,
- parameters::{ParameterLoader, safetensors_metadata::read_metadata},
-};
-
-const EMBEDDING_PATH: &str = "decoder.embedding.embedding.weights";
-const EMBEDDING_TREE_PATH: &str = "decoder.embedding.embedding";
-
-fn check_tree_api<B: Backend>(context: &B::Context) {
- let weights_path = get_test_weights_path();
- let file = File::open(&weights_path).expect("Weights file not found; run download script");
- let (_header_len, metadata) = read_metadata(&file).expect("read weights metadata");
- let embedding_shape = metadata.tensors.get(EMBEDDING_PATH).expect("weights embeddings metadata").shape.clone();
- assert_eq!(embedding_shape.len(), 2);
-
- let loader = ParameterLoader::<B>::new(&file, context).expect("create loader");
- let tree = loader.tree();
- let embeddings_leaf =
- tree.leaf(EMBEDDING_PATH).expect("weights embeddings").validate(&embedding_shape, DataType::BF16).unwrap();
- let embeddings = embeddings_leaf.read_array().unwrap();
- let view = embeddings.as_view::<bf16>();
-
- // tree API check
- let subtree = tree.subtree(EMBEDDING_TREE_PATH).unwrap();
- let weights_leaf = subtree.leaf("weights").unwrap().validate(&embedding_shape, DataType::BF16).unwrap();
- let same = weights_leaf.read_array().unwrap();
- assert_eq!(view, same.as_view::<bf16>());
-}
-
-#[tag(heavy)]
-#[uzu_test]
-fn test_parameter_loader_basic() {
- for_each_backend!(|B| {
- let context = <B as Backend>::Context::new().expect("Failed to create context");
- check_tree_api::<B>(&context);
- })
-}
diff --git a/crates/backend-uzu/unit/session/chat_session.rs b/crates/backend-uzu/unit/session/chat_session.rs
deleted file mode 100644
index 6b1d7b6e8..000000000
--- a/crates/backend-uzu/unit/session/chat_session.rs
+++ /dev/null
@@ -1,172 +0,0 @@
-use std::sync::Arc;
-
-use proc_macros::uzu_test;
-use shoji::types::basic::Feature;
-use test_runner::path::get_test_model_path;
-use test_tag::tag;
-use tokenizers::Tokenizer;
-
-use crate::{
- session::{
- Session,
- config::{DecodingConfig, RunConfig, SpeculatorConfig},
- parameter::{AsyncBatchSize, SamplingSeed},
- types::{Input, Message, Output},
- },
- speculators::{fixed_token_speculator::FixedTokensSpeculator, prompt_lookup_speculator::PromptLookupSpeculator},
-};
-
-fn build_decoding_config() -> DecodingConfig {
- DecodingConfig::default().with_sampling_seed(SamplingSeed::Custom(42))
-}
-
-fn build_default_text() -> String {
- String::from("Tell about London")
-}
-
-#[tag(heavy)]
-#[uzu_test]
-fn test_text_session_base() {
- run(build_default_text(), build_decoding_config(), 128);
-}
-
-#[tag(heavy)]
-#[uzu_test]
-fn test_text_session_base_async_batch_1() {
- run(build_default_text(), build_decoding_config().with_async_batch_size(AsyncBatchSize::Custom(1)), 128);
-}
-
-#[tag(heavy)]
-#[uzu_test]
-fn test_text_session_with_prompt_lookup_speculator() {
- let number_of_speculated_tokens = 16 - 1;
- let speculator = PromptLookupSpeculator::new_with_params(3);
- let speculator_config = SpeculatorConfig {
- number_of_speculated_tokens,
- speculator: Arc::new(speculator),
- };
- let decoding_config = build_decoding_config().with_speculator_config(speculator_config);
-
- let text_to_summarize = "A Large Language Model (LLM) is a type of artificial intelligence that processes and generates human-like text. It is trained on vast datasets containing books, articles, and web content, allowing it to understand and predict language patterns. LLMs use deep learning, particularly transformer-based architectures, to analyze text, recognize context, and generate coherent responses. These models have a wide range of applications, including chatbots, content creation, translation, and code generation. One of the key strengths of LLMs is their ability to generate contextually relevant text based on prompts. They utilize self-attention mechanisms to weigh the importance of words within a sentence, improving accuracy and fluency. Examples of popular LLMs include OpenAI's GPT series, Google's BERT, and Meta's LLaMA. As these models grow in size and sophistication, they continue to enhance human-computer interactions, making AI-powered communication more natural and effective.";
- let text = format!("Text is: \"{}\". Write only summary itself.", text_to_summarize);
-
- run(text, decoding_config, 256);
-}
-
-#[tag(heavy)]
-#[uzu_test]
-fn test_text_session_with_fixed_speculator() {
- let tokenizer = Tokenizer::from_file(get_test_model_path().join("tokenizer.json")).unwrap();
-
- let feature = Feature {
- name: String::from("sentiment"),
- values: vec!["Happy", "Sad", "Angry", "Fearful", "Surprised", "Disgusted"]
- .into_iter()
- .map(String::from)
- .collect(),
- };
- let proposals: Vec<Vec<u64>> = feature
- .values
- .iter()
- .map(|value| {
- tokenizer.encode(value.clone().as_str(), false).unwrap().get_ids().iter().map(|&id| id as u64).collect()
- })
- .collect();
- let speculator = FixedTokensSpeculator::new(proposals);
- let speculator_config = SpeculatorConfig {
- number_of_speculated_tokens: speculator.max_trie_nodes(),
- speculator: Arc::new(speculator),
- };
- let decoding_config = build_decoding_config().with_speculator_config(speculator_config);
-
- let text_to_detect_feature = "Today's been awesome! Everything just feels right, and I can't stop smiling.";
- let text = format!(
- "Text is: \"{}\". Choose {} from the list: {}. Answer with one word. Dont't add dot at the end.",
- text_to_detect_feature,
- feature.name,
- feature.values.join(", ")
- );
-
- run(text, decoding_config, 32);
-}
-
-#[ignore]
-#[tag(heavy)]
-#[uzu_test]
-fn test_text_session_ngram_speculator_chat() {
- todo!("Implement test_text_session_ngram_speculator_chat")
-}
-
-#[tag(heavy)]
-#[uzu_test]
-fn test_text_session_scenario() {
- let system_prompt = String::from("You are a helpful assistant.");
- let user_prompts = vec![String::from("Tell about London"), String::from("Compare with New York")];
- run_scenario(Some(system_prompt), user_prompts);
-}
-
-#[tag(heavy)]
-#[uzu_test]
-fn test_text_session_stability() {
- let mut session = Session::new(get_test_model_path(), build_decoding_config()).unwrap();
- println!("Index | TTFT, s | Prompt t/s | Generate t/s");
- for index in 0..10 {
- let input = Input::Text(build_default_text());
- let output = session.run(input, RunConfig::default().tokens_limit(128), Some(|_: Output| true)).unwrap();
- println!(
- "{:.5} | {:.5} | {:.5} | {:.5}",
- index,
- output.stats.prefill_stats.duration,
- output.stats.prefill_stats.processed_tokens_per_second,
- output.stats.generate_stats.unwrap().tokens_per_second
- );
- }
-}
-
-fn run(
- text: String,
- decoding_config: DecodingConfig,
- tokens_limit: u64,
-) {
- let mut session = Session::new(get_test_model_path(), decoding_config).unwrap();
- let input = Input::Text(text);
- let output = session.run(input, RunConfig::default().tokens_limit(tokens_limit), Some(|_: Output| true)).unwrap();
-
- let empty_response = String::from("None");
-
- println!("-------------------------");
- println!("{}", output.text.parsed.chain_of_thought.unwrap_or(empty_response.clone()));
- println!("-------------------------");
- println!("{}", output.text.parsed.response.unwrap_or(empty_response.clone()));
- println!("-------------------------");
- println!("{:#?}", output.stats);
- println!("-------------------------");
- println!("Finish reason: {:?}", output.finish_reason);
- println!("-------------------------");
-}
-
-fn run_scenario(
- system_prompt: Option<String>,
- user_prompts: Vec<String>,
-) {
- let mut session = Session::new(get_test_model_path(), build_decoding_config()).unwrap();
-
- let mut messages: Vec<Message> = vec![];
- if let Some(system_prompt) = system_prompt {
- messages.push(Message::system(system_prompt.clone()));
- println!("System > {}", system_prompt.clone());
- }
-
- for user_prompt in user_prompts {
- messages.push(Message::user(user_prompt.clone()));
- println!("User > {}", user_prompt.clone());
-
- let input = Input::Messages(messages.clone());
- let output = session.run(input, RunConfig::default(), Some(|_: Output| true)).unwrap();
- messages.push(Message::assistant(
- output.text.parsed.response.clone().unwrap_or_default(),
- output.text.parsed.chain_of_thought.clone(),
- ));
- println!("Assistant > {}", output.text.original.clone());
- }
-}
diff --git a/crates/backend-uzu/unit/session/config/grammar_config.rs b/crates/backend-uzu/unit/session/config/grammar_config.rs
deleted file mode 100644
index b4650ec4e..000000000
--- a/crates/backend-uzu/unit/session/config/grammar_config.rs
+++ /dev/null
@@ -1,156 +0,0 @@
-#![cfg(metal_backend)]
-
-use std::sync::Arc;
-
-use proc_macros::uzu_test;
-use schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
-use test_runner::path::get_test_model_path;
-use test_tag::tag;
-
-use crate::{
- session::{
- Session,
- config::{DecodingConfig, GrammarConfig, RunConfig, SpeculatorConfig, StructuredOutput},
- parameter::{SamplingPolicy, SamplingSeed},
- types::Input,
- },
- speculators::repeat_speculator::RepeatSpeculator,
-};
-
-#[derive(Debug, Serialize, Deserialize, JsonSchema)]
-struct Address {
- street: String,
- city: String,
- country: String,
- postal_code: String,
-}
-
-#[derive(Debug, Serialize, Deserialize, JsonSchema)]
-struct Person {
- name: String,
- age: u32,
- email: String,
- address: Address,
- hobbies: Vec<String>,
-}
-
-fn test_grammar(speculator_config: SpeculatorConfig) {
- let model_dir = get_test_model_path();
-
- if !model_dir.exists() {
- eprintln!(
- "Skipping test: model not found at {}.\nRun scripts/download_test_model.sh first.",
- model_dir.display()
- );
- return;
- }
-
- let decoding_config = DecodingConfig::default()
- .with_sampling_seed(SamplingSeed::Custom(42))
- .with_speculator_config(speculator_config);
- let mut session = Session::new(model_dir, decoding_config).expect("Failed to create session");
-
- let input = Input::Text("Generate a detailed person profile with address and hobbies in JSON format.".to_string());
-
- let grammar_config = GrammarConfig::from_json_schema_type::<Person>().expect("Failed to create grammar config");
-
- let run_config =
- RunConfig::default().tokens_limit(1024).sampling_policy(SamplingPolicy::Default).grammar_config(grammar_config);
-
- let output = session
- .run(input, run_config, None::<fn(crate::session::types::Output) -> bool>)
- .expect("Failed to run session");
-
- let stats = output.stats;
- let total_tokens = stats.total_stats.tokens_count_input + stats.total_stats.tokens_count_output;
-
- println!("\n=== Test Results ===");
- println!("Generated output length: {} chars", output.text.original.len());
- println!(
- "Input tokens: {}, Output tokens: {}",
- stats.total_stats.tokens_count_input, stats.total_stats.tokens_count_output
- );
- println!("Total time: {:.2}s", stats.total_stats.duration);
- println!("Throughput: {:.2} tokens/s", total_tokens as f64 / stats.total_stats.duration);
-
- match serde_json::from_str::<Person>(&output.text.original) {
- Ok(person) => {
- println!("✓ Valid Person JSON!");
- println!(" Name: {}", person.name);
- println!(" Age: {}", person.age);
- println!(" Email: {}", person.email);
- println!(" Address: {}, {}", person.address.city, person.address.country);
- println!(" Hobbies: {:?}", person.hobbies);
-
- assert!(!person.name.is_empty());
- assert!(person.age > 0);
- assert!(person.email.contains('@'));
- assert!(!person.address.city.is_empty());
- assert!(!person.hobbies.is_empty());
- },
- Err(e) => {
- panic!("✗ Generated invalid JSON: {}\nOutput: {}", e, output.text.original);
- },
- }
-}
-
-#[tag(heavy)]
-#[uzu_test]
-fn test_grammar_json_schema() {
- test_grammar(SpeculatorConfig::default());
-}
-
-#[tag(heavy)]
-#[uzu_test]
-fn test_grammar_json_schema_with_speculator() {
- test_grammar(SpeculatorConfig {
- number_of_speculated_tokens: 16,
- speculator: Arc::new(RepeatSpeculator),
- });
-}
-
-fn unwrapped_schema(raw: &str) -> String {
- match GrammarConfig::structured_output_from_schema(raw) {
- StructuredOutput::Schema(schema) => schema,
- StructuredOutput::AnyJson => panic!("expected schema for: {raw}"),
- }
-}
-
-#[uzu_test]
-fn unwraps_nested_response_format_envelope() {
- let raw = r#"{"type":"json_schema","json_schema":{"name":"person","strict":true,"schema":{"type":"object","properties":{"name":{"type":"string"}}}}}"#;
- let normalized: serde_json::Value = serde_json::from_str(&unwrapped_schema(raw)).unwrap();
- assert_eq!(normalized, serde_json::json!({"type":"object","properties":{"name":{"type":"string"}}}));
-}
-
-#[uzu_test]
-fn unwraps_flattened_response_format_envelope() {
- let raw = r#"{"type":"json_schema","name":"person","schema":{"type":"object"}}"#;
- let normalized: serde_json::Value = serde_json::from_str(&unwrapped_schema(raw)).unwrap();
- assert_eq!(normalized, serde_json::json!({"type":"object"}));
-}
-
-#[uzu_test]
-fn unwraps_bare_inner_json_schema_object() {
- let raw = r#"{"name":"person","schema":{"type":"object"}}"#;
- let normalized: serde_json::Value = serde_json::from_str(&unwrapped_schema(raw)).unwrap();
- assert_eq!(normalized, serde_json::json!({"type":"object"}));
-}
-
-#[uzu_test]
-fn json_object_maps_to_any_json() {
- assert_eq!(GrammarConfig::structured_output_from_schema(r#"{"type":"json_object"}"#), StructuredOutput::AnyJson,);
-}
-
-#[uzu_test]
-fn passes_through_bare_json_schema() {
- let raw = r#"{"type":"object","properties":{"schema":{"type":"string"}}}"#;
- let normalized: serde_json::Value = serde_json::from_str(&unwrapped_schema(raw)).unwrap();
- assert_eq!(normalized, serde_json::from_str::<serde_json::Value>(raw).unwrap());
-}
-
-#[uzu_test]
-fn passes_through_unparseable_input() {
- assert_eq!(unwrapped_schema("not json"), "not json");
-}
diff --git a/crates/backend-uzu/unit/session/parameter/context_mode.rs b/crates/backend-uzu/unit/session/parameter/context_mode.rs
deleted file mode 100644
index 349b0fb71..000000000
--- a/crates/backend-uzu/unit/session/parameter/context_mode.rs
+++ /dev/null
@@ -1,180 +0,0 @@
-use proc_macros::uzu_test;
-use test_runner::path::get_test_model_path;
-use test_tag::tag;
-
-use crate::session::{
- Session,
- config::{DecodingConfig, RunConfig, SpeculatorConfig},
- parameter::{
- AsyncBatchSize, ContextLength, ContextMode, PrefillStepSize, SamplingMethod, SamplingPolicy, SamplingSeed,
- },
- types::{Input, Message, Output},
-};
-
-fn build_decoding_config() -> DecodingConfig {
- DecodingConfig::new(
- ContextMode::default(),
- ContextLength::default(),
- PrefillStepSize::default(),
- SpeculatorConfig::default(),
- SamplingSeed::Custom(42),
- AsyncBatchSize::default(),
- )
-}
-
-fn request(
- session: &mut Session,
- input_text: String,
- tokens_limit: u64,
-) -> String {
- session
- .run(
- Input::Text(input_text.clone()),
- RunConfig::new(
- tokens_limit,
- false,
- SamplingPolicy::Custom {
- value: SamplingMethod::Greedy,
- },
- None,
- ),
- None::<fn(Output) -> bool>,
- )
- .unwrap()
- .text
- .original
- .trim()
- .to_string()
-}
-
-fn is_unknown_answer(response: &str) -> bool {
- let response = response.to_lowercase();
- [
- "not sure",
- "not able",
- "not aware",
- "don't know",
- "do not know",
- "can't tell",
- "cannot tell",
- "no information",
- "any information",
- "more context",
- "more details",
- ]
- .iter()
- .any(|pattern| response.contains(pattern))
-}
-
-#[tag(heavy)]
-#[uzu_test]
-fn test_context_mode_none() {
- let decoding_config = build_decoding_config().with_context_mode(ContextMode::None);
- let mut session = Session::new(get_test_model_path(), decoding_config).unwrap();
-
- let tokens_limit = 48;
- let input_text = "What is Alice's occupation?".to_string();
- let response_1 = request(&mut session, input_text.clone(), tokens_limit);
- let response_2 = request(&mut session, input_text.clone(), tokens_limit);
-
- println!("response_1: {}", response_1);
- println!("response_2: {}", response_2);
-
- assert!(is_unknown_answer(&response_1));
- assert!(is_unknown_answer(&response_2));
-}
-
-#[tag(heavy)]
-#[uzu_test]
-fn test_context_mode_static() {
- let parameter_name = "Alice".to_string();
- let parameter_age = "30".to_string();
- let parameter_occupation = "Engineer".to_string();
- let parameter_city = "London".to_string();
-
- let decoding_config = build_decoding_config().with_context_mode(ContextMode::Static {
- input: Input::Messages(vec![
- Message::system("Always answer with one word or number, no punctuation".to_string()),
- Message::user(
- format!(
- "Name: {}\nAge: {}\nOccupation: {}\nCity: {}",
- parameter_name, parameter_age, parameter_occupation, parameter_city
- )
- .to_string(),
- ),
- ]),
- });
- let mut session = Session::new(get_test_model_path(), decoding_config).unwrap();
-
- let tokens_limit = 48;
- let response_occupation = request(&mut session, format!("What is {}'s occupation?", parameter_name), tokens_limit);
- let response_age = request(&mut session, format!("What is {}'s age?", parameter_name), tokens_limit);
- let response_city = request(&mut session, format!("What is {}'s city?", parameter_name), tokens_limit);
-
- println!("Occupation: {}", response_occupation);
- println!("Age: {}", response_age);
- println!("City: {}", response_city);
-
- assert!(response_occupation.to_lowercase().contains(parameter_occupation.to_lowercase().as_str()));
- assert!(response_age.to_lowercase().contains(parameter_age.to_lowercase().as_str()));
- assert!(response_city.to_lowercase().contains(parameter_city.to_lowercase().as_str()));
-}
-
-#[tag(heavy)]
-#[uzu_test]
-#[ignore = "Flaky test - depends on LLM output which varies even with fixed seed"]
-fn test_context_mode_dynamic() {
- let decoding_config = build_decoding_config().with_context_mode(ContextMode::Dynamic);
- let mut session = Session::new(get_test_model_path(), decoding_config).unwrap();
-
- let update = |session: &mut Session, input_text: String| request(session, input_text, 0);
- let ask = |session: &mut Session, input_text: String| request(session, input_text, 48);
-
- update(&mut session, "Name: Dave. Occupation: Nurse. Age: 30.".to_string());
- let answer_1 = ask(&mut session, "What is Dave's occupation?".to_string());
- println!("Answer 1: {}", answer_1);
- assert!(answer_1.to_lowercase().contains("nurse"));
-
- update(&mut session, "Update: Name: Dave. Occupation: Doctor. Age: 30.".to_string());
- let answer_2 = ask(&mut session, "What is Dave's occupation?".to_string());
- println!("Answer 2: {}", answer_2);
- assert!(answer_2.to_lowercase().contains("doctor"));
-
- update(&mut session, "Update: Name: Dave. Occupation: Doctor. Age: 31.".to_string());
- let answer_3 = ask(&mut session, "How old is Dave?".to_string());
- println!("Answer 3: {}", answer_3);
- assert!(answer_3.to_lowercase().contains("31"));
-
- update(
- &mut session,
- "Important update, Dave got promoted! Update: Name: Dave. Occupation: Director. Age: 32.".to_string(),
- );
- let answer_4 = ask(&mut session, "What is Dave's current occupation?".to_string());
- println!("Answer 4: {}", answer_4);
- assert!(answer_4.to_lowercase().contains("director"));
-
- /*
- let answer_5 = ask(
- &mut session,
- "At what age did the last promotion occur?".to_string(),
- );
- println!("Answer 5: {}", answer_5);
- assert!(answer_5.to_lowercase().contains("32"));
- */ // TODO: Fix this test
-}
-
-#[tag(heavy)]
-#[uzu_test]
-fn test_context_mode_dynamic_scenario() {
- let decoding_config = build_decoding_config().with_context_mode(ContextMode::Dynamic);
- let mut session = Session::new(get_test_model_path(), decoding_config).unwrap();
-
- let user_prompts = vec![String::from("Tell about London"), String::from("Compare with New York")];
-
- println!("-------------------------");
- for user_prompt in user_prompts {
- let answer = request(&mut session, user_prompt.clone(), 1024);
- println!("{} -> {}", user_prompt, answer);
- println!("-------------------------");
- }
-}
diff --git a/crates/backend-uzu/unit/trie_test.rs b/crates/backend-uzu/unit/trie_test.rs
index 0da4f21b0..4aa9fec76 100644
--- a/crates/backend-uzu/unit/trie_test.rs
+++ b/crates/backend-uzu/unit/trie_test.rs
@@ -3,7 +3,7 @@ use std::collections::HashMap;
use proc_macros::uzu_test;
use crate::{
- language_model::rng::PRng,
+ encodable_block::sampling::PRng,
speculators::{empty_speculator::EmptySpeculator, speculator::Speculator},
trie::{TrieCreationConfig, TrieNode},
};
@@ -39,17 +39,17 @@ fn verify_sprout(
assert_eq!(flat_trie.len(), 1);
assert_eq!(flat_trie.index(trie_root), Some(0));
- assert_eq!(flat_trie.index(&TrieNode::new(1, None, 0)), None);
- assert_eq!(flat_trie.index(&TrieNode::new(0, None, 1)), None);
- assert_eq!(flat_trie.index(&TrieNode::new(0, None, 0)), None);
+ assert_eq!(flat_trie.index(&TrieNode::new(1, 0)), None);
+ assert_eq!(flat_trie.index(&TrieNode::new(0, 1)), None);
+ assert_eq!(flat_trie.index(&TrieNode::new(0, 0)), None);
assert_eq!(flat_trie.token_ids().collect::<Vec<u64>>(), vec![0]);
- assert_eq!(flat_trie.token_positions().collect::<Vec<usize>>(), vec![0]);
+ assert_eq!(flat_trie.token_subtrie_ranges().map(|node| node.height as usize).collect::<Vec<_>>(), vec![0]);
assert_eq!(flat_trie.token_seeds().collect::<Vec<u64>>(), vec![expected_seed]);
}
#[uzu_test]
fn test_trie_manual_sprout() {
- let trie_root = TrieNode::new(0, None, 0);
+ let trie_root = TrieNode::new(0, 0);
verify_sprout(&trie_root, 0);
}
@@ -70,6 +70,7 @@ fn test_trie_from_speculator_sprout() {
width: 5,
},
10,
+ None,
);
verify_sprout(&trie_root, rng.derive(0));
@@ -83,7 +84,7 @@ fn verify_stick(
assert_eq!(flat_trie.len(), 10);
let token_ids = flat_trie.token_ids().collect::<Vec<u64>>();
- let token_positions = flat_trie.token_positions().collect::<Vec<usize>>();
+ let token_positions = flat_trie.token_subtrie_ranges().map(|node| node.height as usize).collect::<Vec<_>>();
let token_seeds = flat_trie.token_seeds().collect::<Vec<u64>>();
assert_eq!(token_ids.len(), 10);
assert_eq!(token_positions.len(), 10);
@@ -111,11 +112,11 @@ fn verify_stick(
#[uzu_test]
fn test_trie_manual_stick() {
let rng = PRng::new(0);
- let mut trie_root = TrieNode::new(0, None, rng.derive(0));
+ let mut trie_root = TrieNode::new(0, rng.derive(0));
let mut trie_leaf = &mut trie_root;
for i in 1..10u64 {
- trie_leaf.add(TrieNode::new(i, None, rng.derive(i))).unwrap();
+ trie_leaf.add(TrieNode::new(i, rng.derive(i))).unwrap();
trie_leaf = trie_leaf.get_mut(i).unwrap();
}
@@ -142,6 +143,7 @@ fn test_trie_from_speculator_stick() {
width: 1,
},
10,
+ None,
);
verify_stick(&trie_root, &rng);
@@ -155,7 +157,7 @@ fn verify_bush(
assert_eq!(flat_trie.len(), 4);
let token_ids = flat_trie.token_ids().collect::<Vec<u64>>();
- let token_positions = flat_trie.token_positions().collect::<Vec<usize>>();
+ let token_positions = flat_trie.token_subtrie_ranges().map(|node| node.height as usize).collect::<Vec<_>>();
let token_seeds = flat_trie.token_seeds().collect::<Vec<u64>>();
assert_eq!(token_ids.len(), 4);
assert_eq!(token_positions.len(), 4);
@@ -181,14 +183,14 @@ fn verify_bush(
#[uzu_test]
fn test_trie_manual_bush() {
let rng = PRng::new(0);
- let mut trie_root = TrieNode::new(0, None, rng.derive(0));
+ let mut trie_root = TrieNode::new(0, rng.derive(0));
- assert!(trie_root.add(TrieNode::new(1, None, rng.derive(1))).is_ok());
- assert!(trie_root.add(TrieNode::new(1, None, rng.derive(1))).is_err());
- assert!(trie_root.add(TrieNode::new(1, None, 10)).is_err());
+ assert!(trie_root.add(TrieNode::new(1, rng.derive(1))).is_ok());
+ assert!(trie_root.add(TrieNode::new(1, rng.derive(1))).is_err());
+ assert!(trie_root.add(TrieNode::new(1, 10)).is_err());
- assert!(trie_root.add(TrieNode::new(2, None, rng.derive(1))).is_ok());
- assert!(trie_root.add(TrieNode::new(3, None, rng.derive(1))).is_ok());
+ assert!(trie_root.add(TrieNode::new(2, rng.derive(1))).is_ok());
+ assert!(trie_root.add(TrieNode::new(3, rng.derive(1))).is_ok());
verify_bush(&trie_root, &rng);
}
@@ -211,6 +213,7 @@ fn test_trie_from_speculator_bush() {
width: 3,
},
10,
+ None,
);
verify_bush(&trie_root, &rng);
@@ -224,7 +227,7 @@ fn verify_tree(
assert_eq!(flat_trie.len(), 7);
let token_ids = flat_trie.token_ids().collect::<Vec<u64>>();
- let token_positions = flat_trie.token_positions().collect::<Vec<usize>>();
+ let token_positions = flat_trie.token_subtrie_ranges().map(|node| node.height as usize).collect::<Vec<_>>();
let token_seeds = flat_trie.token_seeds().collect::<Vec<u64>>();
assert_eq!(token_ids.len(), 7);
assert_eq!(token_positions.len(), 7);
@@ -255,21 +258,21 @@ fn verify_tree(
#[uzu_test]
fn test_trie_manual_tree() {
let rng = PRng::new(0);
- let mut trie_root = TrieNode::new(0, None, rng.derive(0));
+ let mut trie_root = TrieNode::new(0, rng.derive(0));
- assert!(trie_root.add(TrieNode::new(1, None, rng.derive(1))).is_ok());
- assert!(trie_root.add(TrieNode::new(1, None, rng.derive(1))).is_err());
- assert!(trie_root.add(TrieNode::new(1, None, 10)).is_err());
+ assert!(trie_root.add(TrieNode::new(1, rng.derive(1))).is_ok());
+ assert!(trie_root.add(TrieNode::new(1, rng.derive(1))).is_err());
+ assert!(trie_root.add(TrieNode::new(1, 10)).is_err());
- assert!(trie_root.add(TrieNode::new(2, None, rng.derive(1))).is_ok());
- assert!(trie_root.add(TrieNode::new(3, None, rng.derive(1))).is_ok());
+ assert!(trie_root.add(TrieNode::new(2, rng.derive(1))).is_ok());
+ assert!(trie_root.add(TrieNode::new(3, rng.derive(1))).is_ok());
let mid_b = trie_root.get_mut(2).unwrap();
- assert!(mid_b.add(TrieNode::new(10, None, rng.derive(2))).is_ok());
+ assert!(mid_b.add(TrieNode::new(10, rng.derive(2))).is_ok());
let mid_c = trie_root.get_mut(3).unwrap();
- assert!(mid_c.add(TrieNode::new(20, None, rng.derive(2))).is_ok());
- assert!(mid_c.add(TrieNode::new(21, None, rng.derive(2))).is_ok());
+ assert!(mid_c.add(TrieNode::new(20, rng.derive(2))).is_ok());
+ assert!(mid_c.add(TrieNode::new(21, rng.derive(2))).is_ok());
verify_tree(&trie_root, &rng)
}
diff --git a/crates/backend-uzu/unit/utils/model_size_test.rs b/crates/backend-uzu/unit/utils/model_size_test.rs
deleted file mode 100644
index 32b3b64a8..000000000
--- a/crates/backend-uzu/unit/utils/model_size_test.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-use std::path::PathBuf;
-
-use proc_macros::uzu_test;
-
-use super::*;
-use crate::utils::VERSION;
-pub const MODEL_DIR_NAME: &str = "Llama-3.2-1B-Instruct";
-
-pub fn get_test_model_path() -> PathBuf {
- let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
- .join("..")
- .join("..")
- .join("workspace")
- .join("models")
- .join(VERSION)
- .join(MODEL_DIR_NAME);
- if !path.exists() {
- panic!("Test model not found at {:?}. Run `./scripts/download_test_model.sh` to fetch it.", path);
- }
- path
-}
-
-#[uzu_test]
-fn test_model_size_from_path() {
- let model_path = get_test_model_path();
-
- if model_path.exists() {
- let size = ModelSize::from_path(&model_path).expect("load model size");
- println!("Model size: {:?}", size);
- assert_eq!(size, ModelSize::Small);
- }
-}
diff --git a/crates/benchmarks/Cargo.toml b/crates/benchmarks/Cargo.toml
deleted file mode 100644
index a0aa1bbe3..000000000
--- a/crates/benchmarks/Cargo.toml
+++ /dev/null
@@ -1,22 +0,0 @@
-[package]
-name = "benchmarks"
-edition.workspace = true
-rust-version.workspace = true
-version.workspace = true
-authors.workspace = true
-homepage.workspace = true
-repository.workspace = true
-license.workspace = true
-
-[dependencies]
-backend-uzu.workspace = true
-serde.workspace = true
-sysinfo.workspace = true
-
-[features]
-default = ["metal"]
-
-metal = ["backend-uzu/metal"]
-
-[lints]
-workspace = true
diff --git a/crates/benchmarks/src/lib.rs b/crates/benchmarks/src/lib.rs
deleted file mode 100644
index 7a7c54c23..000000000
--- a/crates/benchmarks/src/lib.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-pub mod runner;
-
-pub use runner::*;
diff --git a/crates/benchmarks/src/runner/mod.rs b/crates/benchmarks/src/runner/mod.rs
deleted file mode 100644
index b42669338..000000000
--- a/crates/benchmarks/src/runner/mod.rs
+++ /dev/null
@@ -1,4 +0,0 @@
-mod runner;
-pub mod types;
-
-pub use runner::Runner;
diff --git a/crates/benchmarks/src/runner/runner.rs b/crates/benchmarks/src/runner/runner.rs
deleted file mode 100644
index d66bd6186..000000000
--- a/crates/benchmarks/src/runner/runner.rs
+++ /dev/null
@@ -1,118 +0,0 @@
-use std::{
- path::PathBuf,
- time::{SystemTime, UNIX_EPOCH},
-};
-
-use backend_uzu::{
- VERSION,
- session::{
- ChatSession,
- config::{DecodingConfig, RunConfig},
- parameter::{PrefillStepSize, SamplingMethod, SamplingPolicy},
- types::{Input, Output},
- },
-};
-use sysinfo::System;
-
-use crate::runner::types::{Device, Result as TaskResult, Task};
-
-pub struct Runner {
- pub task: Task,
- pub model_path: String,
- pub prefill_step_size: Option<usize>,
-}
-
-impl Runner {
- pub fn new(
- task: Task,
- model_path: String,
- prefill_step_size: Option<usize>,
- ) -> Self {
- Self {
- task,
- model_path,
- prefill_step_size,
- }
- }
-
- pub fn run<F>(
- &self,
- mut progress: Option<F>,
- ) -> Result<Vec<TaskResult>, Box<dyn std::error::Error>>
- where
- F: FnMut(f64),
- {
- let mut decoding_config = DecodingConfig::default();
- if let Some(prefill_step_size) = self.prefill_step_size {
- decoding_config = decoding_config.with_prefill_step_size(PrefillStepSize::Custom(prefill_step_size));
- }
-
- let mut session = ChatSession::new(PathBuf::from(self.model_path.clone()), decoding_config)?;
- let data_type = session.activation_data_type();
-
- let device = self.get_device_info();
-
- let input = Input::Messages(self.task.messages.clone());
-
- let warmup_config = RunConfig::default().tokens_limit(1);
- session.run(input.clone(), warmup_config, Option::<fn(Output) -> bool>::None)?;
-
- let mut results: Vec<TaskResult> = Vec::new();
- for run_index in 0..self.task.number_of_runs {
- let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
-
- let mut run_config = RunConfig::default().tokens_limit(self.task.tokens_limit);
- if self.task.greedy {
- run_config = run_config.sampling_policy(SamplingPolicy::Custom {
- value: SamplingMethod::Greedy,
- });
- }
- let output = session.run(input.clone(), run_config, Option::<fn(Output) -> bool>::None)?;
-
- let memory_used =
- output.stats.memory_used_bytes.map(|value| value as usize).or_else(|| session.peak_memory_usage());
- let power_stats = output.stats.power_stats.clone();
- let generate_tokens_per_second = output.stats.generate_stats.as_ref().map(|stats| stats.tokens_per_second);
-
- let result = TaskResult {
- task: self.task.clone(),
- device: device.clone(),
- engine_version: VERSION.to_string(),
- timestamp,
- data_type,
- memory_used,
- power_stats,
- tokens_count_input: output.stats.total_stats.tokens_count_input,
- tokens_count_output: output.stats.total_stats.tokens_count_output,
- time_to_first_token: output.stats.prefill_stats.duration,
- prompt_tokens_per_second: output.stats.prefill_stats.processed_tokens_per_second,
- generate_tokens_per_second,
- text: output.text.original,
- };
- results.push(result);
-
- if let Some(progress) = progress.as_mut() {
- progress((run_index + 1) as f64 / self.task.number_of_runs as f64);
- }
- }
-
- Ok(results)
- }
-}
-
-impl Runner {
- fn get_device_info(&self) -> Device {
- let mut system_info = System::new_all();
- system_info.refresh_all();
-
- let os_name = System::long_os_version();
- let cpu_name = system_info.cpus().first().map(|cpu| cpu.brand().to_string());
- let memory_total = system_info.total_memory();
-
- Device {
- os_name,
- cpu_name,
- memory_total,
- }
- }
-}
diff --git a/crates/benchmarks/src/runner/types/device.rs b/crates/benchmarks/src/runner/types/device.rs
deleted file mode 100644
index ba267435d..000000000
--- a/crates/benchmarks/src/runner/types/device.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Device {
- pub os_name: Option<String>,
- pub cpu_name: Option<String>,
- pub memory_total: u64,
-}
diff --git a/crates/benchmarks/src/runner/types/mod.rs b/crates/benchmarks/src/runner/types/mod.rs
deleted file mode 100644
index 034ae4765..000000000
--- a/crates/benchmarks/src/runner/types/mod.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-mod device;
-mod result;
-mod task;
-
-pub use device::Device;
-pub use result::Result;
-pub use task::Task;
diff --git a/crates/benchmarks/src/runner/types/result.rs b/crates/benchmarks/src/runner/types/result.rs
deleted file mode 100644
index 6df1898e8..000000000
--- a/crates/benchmarks/src/runner/types/result.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use backend_uzu::{data_type::DataType, session::types::PowerStats};
-use serde::{Deserialize, Serialize};
-
-use crate::runner::types::{Device, Task};
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Result {
- pub task: Task,
- pub device: Device,
- pub engine_version: String,
- pub timestamp: u64,
- pub data_type: DataType,
- pub memory_used: Option<usize>,
- pub power_stats: Option<PowerStats>,
- pub tokens_count_input: u64,
- pub tokens_count_output: u64,
- pub time_to_first_token: f64,
- pub prompt_tokens_per_second: f64,
- pub generate_tokens_per_second: Option<f64>,
- pub text: String,
-}
diff --git a/crates/benchmarks/src/runner/types/task.rs b/crates/benchmarks/src/runner/types/task.rs
deleted file mode 100644
index 0d64e52cc..000000000
--- a/crates/benchmarks/src/runner/types/task.rs
+++ /dev/null
@@ -1,12 +0,0 @@
-use backend_uzu::session::types::Message;
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Task {
- pub identifier: String,
- pub repo_id: String,
- pub number_of_runs: u64,
- pub tokens_limit: u64,
- pub messages: Vec<Message>,
- pub greedy: bool,
-}
diff --git a/crates/cli-tools/src/types/capability.rs b/crates/cli-tools/src/types/capability.rs
index 4c241ea42..19085f15d 100644
--- a/crates/cli-tools/src/types/capability.rs
+++ b/crates/cli-tools/src/types/capability.rs
@@ -5,7 +5,6 @@ use serde::{Deserialize, Serialize};
#[serde(rename_all = "snake_case")]
pub enum Capability {
Grammar,
- Tracing,
#[serde(rename = "cli")]
CLI,
}
@@ -14,7 +13,6 @@ impl Capability {
pub fn feature(&self) -> String {
match self {
Capability::Grammar => "capability-grammar".to_string(),
- Capability::Tracing => "capability-tracing".to_string(),
Capability::CLI => "capability-cli".to_string(),
}
}
diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml
index ba19d2e81..cb2bc5a5b 100644
--- a/crates/cli/Cargo.toml
+++ b/crates/cli/Cargo.toml
@@ -15,14 +15,13 @@ path = "src/main.rs"
[features]
default = ["backend-metal", "capability-grammar", "capability-cli"]
backend-cpu = ["uzu/backend-cpu"]
-backend-metal = ["uzu/backend-metal", "benchmarks/metal"]
+backend-metal = ["uzu/backend-metal"]
capability-grammar = ["uzu/capability-grammar"]
-capability-tracing = ["uzu/capability-tracing"]
capability-cli = ["uzu/capability-cli"]
[dependencies]
+backend-uzu.workspace = true
uzu = { workspace = true, default-features = false }
-benchmarks = { workspace = true, default-features = false }
tokio.workspace = true
anyhow.workspace = true
clap.workspace = true
@@ -34,6 +33,8 @@ jsonschema.workspace = true
rocket.workspace = true
uuid.workspace = true
tokio-stream.workspace = true
+sysinfo.workspace = true
+shoji.workspace = true
[lints]
workspace = true
diff --git a/crates/cli/src/bench.rs b/crates/cli/src/bench.rs
deleted file mode 100644
index 29cf10126..000000000
--- a/crates/cli/src/bench.rs
+++ /dev/null
@@ -1,139 +0,0 @@
-use std::fs;
-
-use anyhow::{Context, Result, bail};
-use benchmarks::runner::{
- Runner,
- types::{Result as BenchmarkResult, Task},
-};
-use comfy_table::{CellAlignment, ContentArrangement, Table, modifiers::UTF8_ROUND_CORNERS, presets::UTF8_FULL};
-use indicatif::ProgressBar;
-
-pub fn run_bench(
- model_path: String,
- task_path: String,
- output_path: String,
-) -> Result<()> {
- let task_data = fs::read_to_string(&task_path).with_context(|| format!("Failed to read task file: {task_path}"))?;
- let task: Task =
- serde_json::from_str(&task_data).with_context(|| format!("Failed to parse task file: {task_path}"))?;
-
- println!("Model: {}", task.repo_id);
-
- let progress_bar = ProgressBar::new(task.number_of_runs);
- progress_bar.set_position(0);
-
- let runner = Runner::new(task.clone(), model_path, None);
- let results = runner
- .run(Some(|_progress| {
- progress_bar.inc(1);
- }))
- .map_err(|error| anyhow::anyhow!(error.to_string()))?;
- progress_bar.finish();
-
- let results_data = serde_json::to_string_pretty(&results).context("Failed to serialize benchmark results")?;
- fs::write(&output_path, results_data).with_context(|| format!("Failed to write output file: {output_path}"))?;
-
- print_summary(&results)
-}
-
-fn print_summary(results: &[BenchmarkResult]) -> Result<()> {
- let Some(first_result) = results.first() else {
- bail!("Benchmark produced no results");
- };
-
- println!("Input tokens count: {}", first_result.tokens_count_input);
-
- let memory_used_list = results
- .iter()
- .filter_map(|result| result.memory_used)
- .map(|memory_used| (memory_used as f64) / 1024.0 / 1024.0 / 1024.0)
- .collect::<Vec<f64>>();
- let time_to_first_token_list = results.iter().map(|result| result.time_to_first_token).collect::<Vec<f64>>();
- let prompt_tokens_per_second_list =
- results.iter().map(|result| result.prompt_tokens_per_second).collect::<Vec<f64>>();
- let generate_tokens_per_second_list =
- results.iter().filter_map(|result| result.generate_tokens_per_second).collect::<Vec<f64>>();
- let average_package_power_list = results
- .iter()
- .filter_map(|result| result.power_stats.as_ref().map(|power| power.average_package_watts))
- .collect::<Vec<f64>>();
- let max_package_power_list = results
- .iter()
- .filter_map(|result| result.power_stats.as_ref().map(|power| power.max_package_watts))
- .collect::<Vec<f64>>();
- let package_energy_list = results
- .iter()
- .filter_map(|result| result.power_stats.as_ref().map(|power| power.energy_joules))
- .collect::<Vec<f64>>();
-
- let memory_used_metric = calculate_metric(&memory_used_list);
- let time_to_first_token_metric = calculate_metric(&time_to_first_token_list);
- let prompt_tokens_per_second_metric = calculate_metric(&prompt_tokens_per_second_list);
- let generate_tokens_per_second_metric = calculate_metric(&generate_tokens_per_second_list);
- let average_package_power_metric = calculate_metric(&average_package_power_list);
- let max_package_power_metric = calculate_metric(&max_package_power_list);
- let package_energy_metric = calculate_metric(&package_energy_list);
-
- let mut table = Table::new();
- table
- .load_preset(UTF8_FULL)
- .apply_modifier(UTF8_ROUND_CORNERS)
- .set_content_arrangement(ContentArrangement::Dynamic)
- .set_header(vec!["Metric", "Value"])
- .add_row(vec!["Used memory, GB", memory_used_metric.as_str()])
- .add_row(vec!["TTFT, s", time_to_first_token_metric.as_str()])
- .add_row(vec!["Prompt, t/s", prompt_tokens_per_second_metric.as_str()])
- .add_row(vec!["Generate, t/s", generate_tokens_per_second_metric.as_str()])
- .add_row(vec!["Avg package power, W", average_package_power_metric.as_str()])
- .add_row(vec!["Max package power, W", max_package_power_metric.as_str()])
- .add_row(vec!["Package energy, J", package_energy_metric.as_str()]);
-
- let Some(column) = table.column_mut(1) else {
- bail!("Benchmark summary table value column is missing");
- };
- column.set_cell_alignment(CellAlignment::Right);
-
- println!("{table}");
-
- Ok(())
-}
-
-fn calculate_metric(data: &[f64]) -> String {
- let mean = mean(data);
- let standard_deviation = standard_deviation(data);
- if let (Some(mean), Some(standard_deviation)) = (mean, standard_deviation) {
- format!("{mean:.3} ± {standard_deviation:.3}")
- } else if let Some(mean) = mean {
- format!("{mean:.3}")
- } else {
- "-".to_string()
- }
-}
-
-fn mean(data: &[f64]) -> Option<f64> {
- if data.is_empty() {
- return None;
- }
-
- Some(data.iter().sum::<f64>() / data.len() as f64)
-}
-
-fn standard_deviation(data: &[f64]) -> Option<f64> {
- let samples_count = data.len();
- if samples_count < 2 {
- return None;
- }
-
- let mean = mean(data)?;
-
- let variance = data
- .iter()
- .map(|value| {
- let difference = value - mean;
- difference * difference
- })
- .sum::<f64>()
- / (samples_count as f64 - 1.0);
-
- Some(variance.sqrt())
-}
diff --git a/crates/cli/src/bench/mod.rs b/crates/cli/src/bench/mod.rs
new file mode 100644
index 000000000..7262b07c2
--- /dev/null
+++ b/crates/cli/src/bench/mod.rs
@@ -0,0 +1,79 @@
+mod model;
+mod runner;
+mod stat;
+
+use anyhow::{Context, Result, bail};
+use comfy_table::{CellAlignment, ContentArrangement, Table, modifiers::UTF8_ROUND_CORNERS, presets::UTF8_FULL};
+use indicatif::ProgressBar;
+use tokio::fs;
+
+use crate::bench::{model::BenchTask, runner::BenchRunner, stat::calculate_metric};
+
+pub async fn run_bench(
+ model_path: String,
+ task_path: String,
+ output_path: String,
+) -> Result<()> {
+ let task_content =
+ fs::read_to_string(&task_path).await.with_context(|| format!("Failed to read task file: {task_path}"))?;
+ let task: BenchTask =
+ serde_json::from_str(&task_content).with_context(|| format!("Failed to parse task file: {task_path}"))?;
+ println!("Model: {}", task.repo_id);
+
+ let progress_bar = ProgressBar::new(task.number_of_runs);
+ progress_bar.set_position(0);
+
+ let runner = BenchRunner::new(task.clone(), model_path);
+ let results = runner
+ .run(Some(|_progress| {
+ progress_bar.inc(1);
+ }))
+ .await
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ progress_bar.finish();
+
+ // Results
+ let results_data = serde_json::to_string_pretty(&results).context("Failed to serialize benchmark results")?;
+ fs::write(&output_path, results_data)
+ .await
+ .with_context(|| format!("Failed to write output file: {output_path}"))?;
+
+ let Some(first_result) = results.first() else {
+ bail!("Benchmark produced no results");
+ };
+ println!("Input tokens count: {}", first_result.tokens_count_input);
+
+ let memory_used_list = results
+ .iter()
+ .filter_map(|result| result.memory_used)
+ .map(|memory_used| (memory_used as f64) / 1024.0 / 1024.0 / 1024.0)
+ .collect::<Vec<f64>>();
+ let time_to_first_token_list = results.iter().map(|result| result.time_to_first_token).collect::<Vec<f64>>();
+ let prompt_tokens_per_second_list =
+ results.iter().map(|result| result.prompt_tokens_per_second).collect::<Vec<f64>>();
+ let generate_tokens_per_second_list =
+ results.iter().filter_map(|result| result.generate_tokens_per_second).collect::<Vec<f64>>();
+
+ let memory_used_metric = calculate_metric(&memory_used_list);
+ let time_to_first_token_metric = calculate_metric(&time_to_first_token_list);
+ let prompt_tokens_per_second_metric = calculate_metric(&prompt_tokens_per_second_list);
+ let generate_tokens_per_second_metric = calculate_metric(&generate_tokens_per_second_list);
+
+ let mut table = Table::new();
+ table
+ .load_preset(UTF8_FULL)
+ .apply_modifier(UTF8_ROUND_CORNERS)
+ .set_content_arrangement(ContentArrangement::Dynamic)
+ .set_header(vec!["Metric", "Value"])
+ .add_row(vec!["Used memory, GB", memory_used_metric.as_str()])
+ .add_row(vec!["TTFT, s", time_to_first_token_metric.as_str()])
+ .add_row(vec!["Prompt, t/s", prompt_tokens_per_second_metric.as_str()])
+ .add_row(vec!["Generate, t/s", generate_tokens_per_second_metric.as_str()]);
+ let Some(column) = table.column_mut(1) else {
+ bail!("Benchmark summary table value column is missing");
+ };
+ column.set_cell_alignment(CellAlignment::Right);
+ println!("{table}");
+
+ Ok(())
+}
diff --git a/crates/cli/src/bench/model.rs b/crates/cli/src/bench/model.rs
new file mode 100644
index 000000000..5131c8a9b
--- /dev/null
+++ b/crates/cli/src/bench/model.rs
@@ -0,0 +1,68 @@
+use backend_uzu::data_type::DataType;
+use rocket::serde::{Deserialize, Serialize};
+use uzu::types::session::chat::{ChatMessage, ChatRole};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BenchTask {
+ pub identifier: String,
+ pub repo_id: String,
+ pub number_of_runs: u64,
+ pub tokens_limit: u64,
+ pub messages: Vec<BenchMessage>,
+ pub greedy: bool,
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct BenchMessage {
+ pub role: BenchMessageRole,
+ pub content: String,
+ pub reasoning_content: Option<String>,
+}
+
+impl BenchMessage {
+ pub fn to_chat_message(&self) -> ChatMessage {
+ let role = match self.role {
+ BenchMessageRole::Assistant => ChatRole::Assistant {},
+ BenchMessageRole::System => ChatRole::System {},
+ BenchMessageRole::User => ChatRole::User {},
+ };
+
+ let mut message = ChatMessage::for_role(role).with_text(self.content.clone());
+ if let Some(reasoning) = &self.reasoning_content {
+ message = message.with_reasoning(reasoning.clone())
+ };
+
+ message
+ }
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum BenchMessageRole {
+ System,
+ User,
+ Assistant,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BenchDevice {
+ pub os_name: Option<String>,
+ pub cpu_name: Option<String>,
+ pub memory_total: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BenchResult {
+ pub task: BenchTask,
+ pub device: BenchDevice,
+ pub engine_version: String,
+ pub timestamp: u64,
+ pub data_type: DataType,
+ pub memory_used: Option<usize>,
+ pub tokens_count_input: u64,
+ pub tokens_count_output: u64,
+ pub time_to_first_token: f64,
+ pub prompt_tokens_per_second: f64,
+ pub generate_tokens_per_second: Option<f64>,
+ pub text: String,
+}
diff --git a/crates/cli/src/bench/runner.rs b/crates/cli/src/bench/runner.rs
new file mode 100644
index 000000000..eba48f645
--- /dev/null
+++ b/crates/cli/src/bench/runner.rs
@@ -0,0 +1,183 @@
+use std::{
+ path::{Path, PathBuf},
+ time::{SystemTime, UNIX_EPOCH},
+};
+
+use anyhow::{Context, Result};
+use backend_uzu::{VERSION, data_type::DataType};
+use shoji::types::model::{ModelFamily, ModelReference};
+use sysinfo::System;
+use uzu::{
+ engine::{Engine, EngineConfig},
+ types::{
+ basic::SamplingMethod,
+ model::ModelAccessibility,
+ session::chat::{ChatConfig, ChatMessage, ChatReplyConfig},
+ },
+};
+
+use crate::bench::{
+ model::{BenchDevice, BenchResult, BenchTask},
+ stat::mean,
+};
+
+pub struct BenchRunner {
+ pub task: BenchTask,
+ pub model_path: String,
+}
+
+impl BenchRunner {
+ pub fn new(
+ task: BenchTask,
+ model_path: String,
+ ) -> Self {
+ Self {
+ task,
+ model_path,
+ }
+ }
+
+ pub async fn run<F: FnMut(f64)>(
+ &self,
+ mut progress: Option<F>,
+ ) -> Result<Vec<BenchResult>> {
+ let model_path_string = self.model_path.trim_end_matches('/').to_string();
+ let model_path = PathBuf::from(&model_path_string);
+ let parent_path = model_path.parent().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default();
+ let engine_config = EngineConfig::default().with_local_path(parent_path);
+ let engine = Engine::new(engine_config).await.with_context(|| "Can not create engine".to_string())?;
+
+ let mut model = engine
+ .model_by_path(model_path_string.clone())
+ .await?
+ .with_context(|| format!("Model not found at path: {model_path_string}"))?;
+ if model.family.is_none()
+ && let Some(model_family) = self.get_remote_model_family(&model_path, &engine).await?
+ {
+ model.family = Some(model_family);
+ }
+
+ let device = self.get_device_info();
+
+ let messages: Vec<ChatMessage> = self.task.messages.iter().map(|msg| msg.to_chat_message()).collect();
+
+ let session_config = ChatConfig::default();
+ let session = engine.chat(model, session_config).await?;
+
+ let warmup_config = ChatReplyConfig::default().with_token_limit(Some(1));
+ let _ = session.reply(messages.clone(), warmup_config).await?;
+
+ let mut results = Vec::<BenchResult>::new();
+ for run_idx in 0..self.task.number_of_runs {
+ session.reset().await?;
+
+ let mut reply_config = ChatReplyConfig::default().with_token_limit(Some(self.task.tokens_limit as u32));
+ if self.task.greedy {
+ reply_config = reply_config.with_sampling_method(SamplingMethod::Greedy {})
+ }
+
+ let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
+ let replies = session.reply(messages.clone(), reply_config).await?;
+
+ let mut tokens_count_input = 0u64;
+ let mut tokens_count_output = 0u64;
+ let mut time_to_first_token = 0.0f64;
+ let mut prompt_tokens_per_second = 0.0f64;
+ let mut generate_tokens_per_second = Vec::new();
+ for reply in replies.iter() {
+ tokens_count_input += reply.stats.tokens_count_input.unwrap_or(0) as u64;
+ tokens_count_output += reply.stats.tokens_count_output.unwrap_or(0) as u64;
+ time_to_first_token += reply.stats.time_to_first_token.unwrap_or(0.0f64);
+ prompt_tokens_per_second += reply.stats.prefill_tokens_per_second.unwrap_or(0.0f64);
+ if let Some(value) = reply.stats.generate_tokens_per_second {
+ generate_tokens_per_second.push(value);
+ }
+ }
+
+ let mut text: Option<String> = None;
+ if !replies.is_empty() {
+ let replies_count = replies.len() as f64;
+ time_to_first_token /= replies_count;
+ prompt_tokens_per_second /= replies_count;
+ text = replies.last().unwrap().message.text();
+ }
+ let generate_tokens_per_second = mean(&generate_tokens_per_second);
+
+ let result = BenchResult {
+ task: self.task.clone(),
+ device: device.clone(),
+ engine_version: VERSION.to_string(),
+ timestamp,
+ data_type: DataType::BF16,
+ memory_used: session.peak_memory_usage().await,
+ tokens_count_input,
+ tokens_count_output,
+ time_to_first_token,
+ prompt_tokens_per_second,
+ generate_tokens_per_second,
+ text: text.unwrap_or("".to_string()),
+ };
+ results.push(result);
+
+ if let Some(progress) = progress.as_mut() {
+ progress((run_idx + 1) as f64 / self.task.number_of_runs as f64);
+ }
+ }
+
+ Ok(results)
+ }
+
+ fn get_device_info(&self) -> BenchDevice {
+ let mut system_info = System::new_all();
+ system_info.refresh_all();
+
+ let os_name = System::long_os_version();
+ let cpu_name = system_info.cpus().first().map(|cpu| cpu.brand().to_string());
+ let memory_total = system_info.total_memory();
+
+ BenchDevice {
+ os_name,
+ cpu_name,
+ memory_total,
+ }
+ }
+
+ async fn get_remote_model_family(
+ &self,
+ model_path: &Path,
+ engine: &Engine,
+ ) -> Result<Option<ModelFamily>> {
+ let dir_name = model_path
+ .file_name()
+ .ok_or(anyhow::format_err!("Can not get directory name"))?
+ .to_string_lossy()
+ .into_owned()
+ .to_lowercase();
+ let all_models = engine.models().await?;
+ for model in all_models {
+ if let ModelAccessibility::Local {
+ reference:
+ ModelReference::Mirai {
+ toolchain_version: _toolchain_version,
+ repository,
+ source_repository,
+ files: _files,
+ },
+ } = model.accessibility
+ {
+ if let Some(repo) = source_repository
+ && repo.identifier.to_lowercase().contains(&dir_name)
+ {
+ return Ok(model.family);
+ }
+ if let Some(repo) = repository
+ && repo.identifier.to_lowercase().contains(&dir_name)
+ {
+ return Ok(model.family);
+ }
+ }
+ }
+
+ Ok(None)
+ }
+}
diff --git a/crates/cli/src/bench/stat.rs b/crates/cli/src/bench/stat.rs
new file mode 100644
index 000000000..b980b8a79
--- /dev/null
+++ b/crates/cli/src/bench/stat.rs
@@ -0,0 +1,39 @@
+pub fn calculate_metric(data: &[f64]) -> String {
+ let mean = mean(data);
+ let standard_deviation = standard_deviation(data);
+ if let (Some(mean), Some(standard_deviation)) = (mean, standard_deviation) {
+ format!("{mean:.3} ± {standard_deviation:.3}")
+ } else if let Some(mean) = mean {
+ format!("{mean:.3}")
+ } else {
+ "-".to_string()
+ }
+}
+
+pub fn mean(data: &[f64]) -> Option<f64> {
+ if data.is_empty() {
+ return None;
+ }
+
+ Some(data.iter().sum::<f64>() / data.len() as f64)
+}
+
+pub fn standard_deviation(data: &[f64]) -> Option<f64> {
+ let samples_count = data.len();
+ if samples_count < 2 {
+ return None;
+ }
+
+ let mean = mean(data)?;
+
+ let variance = data
+ .iter()
+ .map(|value| {
+ let difference = value - mean;
+ difference * difference
+ })
+ .sum::<f64>()
+ / (samples_count as f64 - 1.0);
+
+ Some(variance.sqrt())
+}
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index 0a4d19213..306fbe3e5 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -40,7 +40,7 @@ async fn main() -> Result<()> {
model_path,
task_path,
output_path,
- }) => bench::run_bench(model_path, task_path, output_path)?,
+ }) => bench::run_bench(model_path, task_path, output_path).await?,
Some(Commands::Server {
model,
port,
diff --git a/crates/hanashi/src/chat/hanashi/error.rs b/crates/hanashi/src/chat/hanashi/error.rs
index a5277a47c..839b5b7ba 100644
--- a/crates/hanashi/src/chat/hanashi/error.rs
+++ b/crates/hanashi/src/chat/hanashi/error.rs
@@ -4,6 +4,7 @@ use crate::chat::{
SynchronizationError,
hanashi::{messages::Error as MessageError, ordering::Error as OrderingError, renderer::Error as RendererError},
};
+
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
diff --git a/crates/hanashi/src/chat/hanashi/mod.rs b/crates/hanashi/src/chat/hanashi/mod.rs
index 1a5c23678..c9658c77b 100644
--- a/crates/hanashi/src/chat/hanashi/mod.rs
+++ b/crates/hanashi/src/chat/hanashi/mod.rs
@@ -5,8 +5,6 @@ mod ordering;
pub mod renderer;
mod token;
-use std::path::PathBuf;
-
pub use config::Config;
pub use error::Error;
use shoji::types::{
@@ -20,13 +18,12 @@ use self::{config::ResolvedConfig, messages::streamed::Message as StreamedMessag
use crate::{
Encoding as EncodingTrait,
chat::{
- Context, State, SynchronizationError, SynchronizationResult, TokenizerLocation,
+ Context, State, SynchronizationError, SynchronizationResult,
hanashi::{messages::rendered::FieldConfig, renderer::Renderer, token::ToParserToken},
},
+ util::tokenizer::load_tokenizer,
};
-const DEFAULT_TOKENIZER_FILENAME: &str = "tokenizer.json";
-
pub struct Encoding {
config: ResolvedConfig,
tokenizer: Tokenizer,
@@ -53,19 +50,7 @@ impl EncodingTrait for Encoding {
context: Self::Context,
) -> Result<Self, Self::Error> {
let config = config.resolve()?;
- let tokenizer_path = match &context.tokenizer_location {
- TokenizerLocation::File {
- path,
- } => PathBuf::from(path),
- TokenizerLocation::Directory {
- path,
- name,
- } => match name {
- Some(name) => PathBuf::from(path).join(name),
- None => PathBuf::from(path).join(DEFAULT_TOKENIZER_FILENAME),
- },
- };
- let tokenizer = Tokenizer::from_file(&tokenizer_path).map_err(|_| Error::UnableToLoadTokenizer)?;
+ let tokenizer = load_tokenizer(&context.tokenizer_location).map_err(|_| Error::UnableToLoadTokenizer)?;
let parser = TokenStreamParser::new(config.parsing.clone())?;
let renderer = Renderer::new(config.rendering.clone());
let validator = Validator::new(config.ordering.clone());
@@ -133,6 +118,10 @@ impl EncodingTrait for Encoding {
self.update_messages_from_parser_state()?;
Ok(())
}
+
+ fn tokenizer(&self) -> Option<&Tokenizer> {
+ Some(&self.tokenizer)
+ }
}
impl Encoding {
diff --git a/crates/hanashi/src/chat/hanashi/renderer/mod.rs b/crates/hanashi/src/chat/hanashi/renderer/mod.rs
index cf7bc76e5..fbd84bfd1 100644
--- a/crates/hanashi/src/chat/hanashi/renderer/mod.rs
+++ b/crates/hanashi/src/chat/hanashi/renderer/mod.rs
@@ -4,7 +4,7 @@ mod functions;
pub use config::{JinjaFunction, RendererConfig};
pub use error::Error;
-use functions::{raise_exception, strftime_now, to_json};
+pub use functions::{raise_exception, strftime_now, to_json};
use indexmap::IndexMap;
use minijinja::Environment;
use minijinja_contrib::pycompat::unknown_method_callback;
@@ -12,7 +12,7 @@ use shoji::types::{basic::Token, session::chat::ChatMessage};
use crate::chat::hanashi::messages::rendered::Message as RenderedMessage;
-static TEMPLATE_NAME: &str = "chat_template";
+pub static TEMPLATE_NAME: &str = "chat_template";
pub struct Renderer {
config: RendererConfig,
diff --git a/crates/hanashi/src/chat/harmony/mod.rs b/crates/hanashi/src/chat/harmony/mod.rs
index 5aabc08ef..feeb2eb2d 100644
--- a/crates/hanashi/src/chat/harmony/mod.rs
+++ b/crates/hanashi/src/chat/harmony/mod.rs
@@ -19,6 +19,7 @@ use shoji::types::{
basic::{Token, TokenId},
session::chat::ChatMessage,
};
+use tokenizers::Tokenizer;
use crate::{
Encoding as EncodingTrait,
@@ -110,6 +111,10 @@ impl EncodingTrait for Encoding {
self.update_messages_from_parser_state()?;
Ok(())
}
+
+ fn tokenizer(&self) -> Option<&Tokenizer> {
+ None
+ }
}
impl Encoding {
diff --git a/crates/hanashi/src/chat/mod.rs b/crates/hanashi/src/chat/mod.rs
index 751624e13..f50dd6830 100644
--- a/crates/hanashi/src/chat/mod.rs
+++ b/crates/hanashi/src/chat/mod.rs
@@ -8,8 +8,10 @@ mod state;
pub use config::Config;
pub use context::{Context, TokenizerLocation};
pub use error::Error;
+pub use hanashi::renderer::strftime_now;
use shoji::types::{basic::TokenId, session::chat::ChatMessage};
pub use state::{State, SynchronizationError, SynchronizationResult};
+use tokenizers::Tokenizer;
use crate::{
Encoding as EncodingTrait,
@@ -75,4 +77,8 @@ impl EncodingTrait for Encoding {
) -> Result<(), Self::Error> {
dispatch!(self, decode, value)
}
+
+ fn tokenizer(&self) -> Option<&Tokenizer> {
+ dispatch!(infallible self, tokenizer)
+ }
}
diff --git a/crates/hanashi/src/classification/config.rs b/crates/hanashi/src/classification/config.rs
new file mode 100644
index 000000000..059ff78cb
--- /dev/null
+++ b/crates/hanashi/src/classification/config.rs
@@ -0,0 +1,39 @@
+use std::{io, io::ErrorKind};
+
+use serde_json::Value;
+
+pub enum TokenCodecConfig {
+ Chat(ChatTokenCodecConfig),
+ RawText,
+}
+
+impl TokenCodecConfig {
+ pub fn from_value(value: Value) -> Result<Self, io::Error> {
+ let typ = value.get("type");
+ match typ {
+ Some(Value::String(codec_type)) if codec_type == "RawTextCodecConfig" => Ok(Self::RawText),
+ Some(Value::String(codec_type)) if codec_type == "ChatCodecConfig" => {
+ let config = serde_json::from_value::<ChatTokenCodecConfig>(value)?;
+ Ok(Self::Chat(config))
+ },
+ None => {
+ let config = serde_json::from_value::<ChatTokenCodecConfig>(value)?;
+ Ok(Self::Chat(config))
+ },
+ _ => Err(io::Error::new(ErrorKind::InvalidData, format!("Invalid config: unknown type \"{typ:?}\""))),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, ::serde::Serialize, ::serde::Deserialize)]
+pub struct ChatTokenCodecConfig {
+ pub prompt_template: String,
+ pub output_parser_regex: Option<String>,
+ pub system_role_name: String,
+ pub user_role_name: String,
+ pub assistant_role_name: String,
+ pub eos_token: Option<String>,
+ pub bos_token: Option<String>,
+ pub end_of_thinking_tag: Option<String>,
+ pub default_system_prompt: Option<String>,
+}
diff --git a/crates/hanashi/src/classification/encoding.rs b/crates/hanashi/src/classification/encoding.rs
new file mode 100644
index 000000000..fc5f1d6ba
--- /dev/null
+++ b/crates/hanashi/src/classification/encoding.rs
@@ -0,0 +1,118 @@
+use std::{collections::HashMap, fs::File, path::PathBuf, string::ToString};
+
+use minijinja::{Environment, context};
+use minijinja_contrib::pycompat::unknown_method_callback;
+use serde_json::Value;
+use shoji::types::session::classification::{ClassificationMessage, ClassificationRole};
+use tokenizers::Tokenizer;
+
+use crate::{
+ chat::{
+ TokenizerLocation,
+ hanashi::{
+ Error,
+ renderer::{TEMPLATE_NAME, raise_exception, to_json},
+ },
+ strftime_now,
+ },
+ classification::config::{ChatTokenCodecConfig, TokenCodecConfig},
+ util::tokenizer::load_tokenizer,
+};
+
+const CONFIG_FILE_NAME: &str = "config.json";
+
+pub struct ClassificationEncoding {
+ tokenizer: Tokenizer,
+ config: TokenCodecConfig,
+}
+
+impl ClassificationEncoding {
+ pub fn new(model_dir: &str) -> Result<Self, Error> {
+ let model_path = PathBuf::from(model_dir);
+ let config_file = File::open(model_path.join(CONFIG_FILE_NAME))
+ .map_err(|_| Error::ConfigNotFound(CONFIG_FILE_NAME.to_string()))?;
+ let config = serde_json::from_reader::<File, Value>(config_file)
+ .map_err(|_| Error::InvalidConfig(CONFIG_FILE_NAME.to_string()))?;
+ let codec_config =
+ config.get("token_codec_config").ok_or_else(|| Error::InvalidConfig(CONFIG_FILE_NAME.to_string()))?;
+ let config = TokenCodecConfig::from_value(codec_config.clone())
+ .map_err(|_| Error::InvalidConfig(CONFIG_FILE_NAME.to_string()))?;
+
+ let tokenizer_location = TokenizerLocation::Directory {
+ path: model_dir.to_string(),
+ name: None,
+ };
+ let tokenizer = load_tokenizer(&tokenizer_location).map_err(|_| Error::UnableToLoadTokenizer)?;
+
+ Ok(Self {
+ tokenizer,
+ config,
+ })
+ }
+
+ pub fn encode(
+ &mut self,
+ input: &[ClassificationMessage],
+ ) -> Result<Vec<u32>, Error> {
+ match &self.config {
+ TokenCodecConfig::Chat(config) => Self::encode_chat(&self.tokenizer, config, input),
+ TokenCodecConfig::RawText => Self::encode_raw_text(&self.tokenizer, input),
+ }
+ }
+
+ fn encode_chat(
+ tokenizer: &Tokenizer,
+ config: &ChatTokenCodecConfig,
+ input: &[ClassificationMessage],
+ ) -> Result<Vec<u32>, Error> {
+ let mut environment = Environment::new();
+ environment.set_unknown_method_callback(unknown_method_callback);
+ environment.add_function("strftime_now", strftime_now);
+ environment.add_function("raise_exception", raise_exception);
+ environment.add_filter("tojson", to_json);
+ environment
+ .add_template(TEMPLATE_NAME, config.prompt_template.as_str())
+ .map_err(|_| Error::UnableToEncodeText)?;
+
+ let messages: Vec<HashMap<String, String>> = input
+ .iter()
+ .map(|message| {
+ let role = match message.role {
+ ClassificationRole::Assistant => config.assistant_role_name.as_str(),
+ ClassificationRole::User => config.user_role_name.as_str(),
+ };
+
+ let mut map: HashMap<String, String> = HashMap::new();
+ map.insert("role".to_string(), role.to_string());
+ map.insert("content".to_string(), message.content.clone());
+ map
+ })
+ .collect();
+
+ let rendered_message = environment
+ .get_template(TEMPLATE_NAME)
+ .unwrap()
+ .render(context!(
+ messages => messages,
+ add_generation_prompt => false,
+ bos_token => config.bos_token.clone(),
+ eos_token => config.eos_token.clone(),
+ enable_thinking => false,
+ ))
+ .map_err(|_| Error::UnableToEncodeText)?;
+
+ let tokens = tokenizer.encode(rendered_message, false).map_err(|_| Error::UnableToEncodeText)?;
+
+ Ok(tokens.get_ids().to_vec())
+ }
+
+ fn encode_raw_text(
+ tokenizer: &Tokenizer,
+ input: &[ClassificationMessage],
+ ) -> Result<Vec<u32>, Error> {
+ let text = input.iter().map(|message| message.content.as_str()).collect::<String>();
+ let tokens = tokenizer.encode(text, false).map_err(|_| Error::UnableToEncodeText)?;
+
+ Ok(tokens.get_ids().to_vec())
+ }
+}
diff --git a/crates/hanashi/src/classification/mod.rs b/crates/hanashi/src/classification/mod.rs
new file mode 100644
index 000000000..6f2940021
--- /dev/null
+++ b/crates/hanashi/src/classification/mod.rs
@@ -0,0 +1,2 @@
+mod config;
+pub mod encoding;
diff --git a/crates/hanashi/src/lib.rs b/crates/hanashi/src/lib.rs
index f5ed42200..2307a6180 100644
--- a/crates/hanashi/src/lib.rs
+++ b/crates/hanashi/src/lib.rs
@@ -1,5 +1,12 @@
+use tokenizers::Tokenizer;
+
+mod classification;
+mod util;
+
pub mod chat;
+pub use classification::encoding::ClassificationEncoding;
+
pub trait Encoding {
type Config;
type Context;
@@ -25,4 +32,6 @@ pub trait Encoding {
&mut self,
value: Self::Output,
) -> Result<(), Self::Error>;
+
+ fn tokenizer(&self) -> Option<&Tokenizer>;
}
diff --git a/crates/hanashi/src/util/mod.rs b/crates/hanashi/src/util/mod.rs
new file mode 100644
index 000000000..d9b8fd121
--- /dev/null
+++ b/crates/hanashi/src/util/mod.rs
@@ -0,0 +1 @@
+pub mod tokenizer;
diff --git a/crates/hanashi/src/util/tokenizer.rs b/crates/hanashi/src/util/tokenizer.rs
new file mode 100644
index 000000000..522fc6d00
--- /dev/null
+++ b/crates/hanashi/src/util/tokenizer.rs
@@ -0,0 +1,23 @@
+use std::path::PathBuf;
+
+use tokenizers::Tokenizer;
+
+use crate::chat::TokenizerLocation;
+
+const DEFAULT_TOKENIZER_FILENAME: &str = "tokenizer.json";
+
+pub fn load_tokenizer(location: &TokenizerLocation) -> Result<Tokenizer, Box<dyn std::error::Error + Send + Sync>> {
+ let tokenizer_path = match location {
+ TokenizerLocation::File {
+ path,
+ } => PathBuf::from(path),
+ TokenizerLocation::Directory {
+ path,
+ name,
+ } => match name {
+ Some(name) => PathBuf::from(path).join(name),
+ None => PathBuf::from(path).join(DEFAULT_TOKENIZER_FILENAME),
+ },
+ };
+ Tokenizer::from_file(&tokenizer_path)
+}
diff --git a/crates/nagare/Cargo.toml b/crates/nagare/Cargo.toml
index 72291db47..bfa96d1ca 100644
--- a/crates/nagare/Cargo.toml
+++ b/crates/nagare/Cargo.toml
@@ -64,7 +64,6 @@ reqwest.workspace = true
futures.workspace = true
tokio-util.workspace = true
tokio.workspace = true
-tokio-stream.workspace = true
uniffi = { workspace = true, optional = true }
napi = { workspace = true, optional = true }
napi-derive = { workspace = true, optional = true }
@@ -80,6 +79,9 @@ tsify = { workspace = true, optional = true }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
uuid.workspace = true
+[target.'cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "visionos"))'.dependencies]
+keisoku.workspace = true
+
[build-dependencies]
napi-build = { workspace = true, optional = true }
pyo3-build-config = { workspace = true, optional = true }
diff --git a/crates/nagare/src/chat/error.rs b/crates/nagare/src/chat/error.rs
index 77b0f85de..255fafbdd 100644
--- a/crates/nagare/src/chat/error.rs
+++ b/crates/nagare/src/chat/error.rs
@@ -8,6 +8,10 @@ pub enum ChatSessionError {
Backend {
message: String,
},
+ #[error("Unable to load model: {message}")]
+ Loading {
+ message: String,
+ },
#[error("Unsupported model")]
UnsupportedModel {},
#[error("Unable to perform operation in current state")]
diff --git a/crates/nagare/src/chat/message.rs b/crates/nagare/src/chat/message.rs
index 39e84080a..332b4f769 100644
--- a/crates/nagare/src/chat/message.rs
+++ b/crates/nagare/src/chat/message.rs
@@ -57,4 +57,8 @@ impl Session {
})
.boxed()
}
+
+ pub fn peak_memory_usage(&self) -> Option<usize> {
+ self.instance.peak_memory_usage()
+ }
}
diff --git a/crates/nagare/src/chat/mod.rs b/crates/nagare/src/chat/mod.rs
index aa62f297b..e4fcc3a71 100644
--- a/crates/nagare/src/chat/mod.rs
+++ b/crates/nagare/src/chat/mod.rs
@@ -76,6 +76,15 @@ enum Instance {
Message(message::Session),
}
+impl Instance {
+ pub fn peak_memory_usage(&self) -> Option<usize> {
+ match self {
+ Instance::Token(session) => session.peak_memory_usage(),
+ Instance::Message(session) => session.peak_memory_usage(),
+ }
+ }
+}
+
#[bindings::export(Class)]
#[derive(Clone)]
pub struct ChatSession {
@@ -102,7 +111,7 @@ impl ChatSession {
let instance = tokio::spawn(async move {
if let Some(token_backend) = backend.as_chat_via_token_capable() {
- token::Session::new(token_backend, config, reference).await.map(Instance::Token)
+ token::Session::new(token_backend, config, reference, &model).await.map(Instance::Token)
} else if let Some(message_backend) = backend.as_chat_via_message_capable() {
message::Session::new(message_backend, config, reference).await.map(Instance::Message)
} else {
@@ -122,6 +131,10 @@ impl ChatSession {
telemetry,
})
}
+
+ pub async fn peak_memory_usage(&self) -> Option<usize> {
+ self.instance.lock().await.peak_memory_usage()
+ }
}
#[bindings::export(Implementation)]
@@ -230,7 +243,7 @@ impl ChatSession {
let mut instance = instance.lock().await;
let mut stream = match &mut *instance {
- Instance::Token(session) => session.stream(&all_messages, config, cancel_token),
+ Instance::Token(session) => session.stream(&all_messages, config, cancel_token).await,
Instance::Message(session) => session.stream(&all_messages, config, cancel_token),
};
@@ -240,10 +253,11 @@ impl ChatSession {
match partial_output {
Ok(backend_output) => {
let message = build_message(&backend_output);
+ let finish_reason = backend_output.finish_reason;
let output = ChatReply {
message: message.clone(),
stats: backend_output.stats.clone(),
- finish_reason: backend_output.finish_reason.clone(),
+ finish_reason: finish_reason.clone(),
};
let is_new = outputs.insert(turn_index, output).is_none();
@@ -259,6 +273,9 @@ impl ChatSession {
if sender.send(Ok(outputs.values().cloned().collect())).is_err() {
break;
}
+ if finish_reason.is_some() {
+ break;
+ }
},
Err(error) => {
errored = true;
diff --git a/crates/nagare/src/chat/token.rs b/crates/nagare/src/chat/token.rs
index 1cd7fc8f6..6d654706e 100644
--- a/crates/nagare/src/chat/token.rs
+++ b/crates/nagare/src/chat/token.rs
@@ -1,23 +1,43 @@
-use std::pin::Pin;
+use std::{
+ pin::Pin,
+ time::{Duration, Instant},
+};
-use futures::{Stream, stream};
+use futures::{Stream, StreamExt, stream};
+use hanashi::{Encoding as EncodingTrait, chat::Encoding};
use shoji::{
traits::{
State,
backend::{
- chat_message::Output,
- chat_token::{Backend, Instance},
+ Error,
+ chat_message::{Output, ToolCallState},
+ chat_token::{Backend, Instance as ChatTokenBackendInstance, StreamInput, StreamOutput},
+ },
+ },
+ types::{
+ basic::TokenId,
+ model::Model,
+ session::chat::{
+ ChatConfig, ChatContentBlock, ChatMessage, ChatReplyConfig, ChatReplyFinishReason, ChatReplyStats,
},
},
- types::session::chat::{ChatConfig, ChatMessage, ChatReplyConfig},
};
use tokio_util::sync::CancellationToken;
-use crate::chat::ChatSessionError;
+use crate::{
+ chat::ChatSessionError,
+ util::{
+ helpers::{build_encoding, error_stream},
+ power::PowerRecorder,
+ },
+};
pub struct Session {
- _instance: Box<dyn Instance>,
- _state: Box<dyn State>,
+ instance: Box<dyn ChatTokenBackendInstance>,
+ state: Box<dyn State>,
+ encoding: Encoding,
+ input_tokens: Vec<u64>,
+ stop_token_ids: Box<[u64]>,
}
impl Session {
@@ -25,35 +45,319 @@ impl Session {
backend: &dyn Backend,
config: ChatConfig,
reference: String,
+ model: &Model,
) -> Result<Self, ChatSessionError> {
- let instance = backend.instance(reference, config).await.map_err(|error| ChatSessionError::Backend {
- message: error.to_string(),
+ let encoding = build_encoding(reference.clone(), model).map_err(|err| ChatSessionError::Loading {
+ message: err.to_string(),
+ })?;
+ let tokenizer = encoding.tokenizer().ok_or_else(|| ChatSessionError::Loading {
+ message: "tokenizer is empty".to_string(),
})?;
+
+ let instance =
+ backend.instance(reference, config, tokenizer).await.map_err(|error| ChatSessionError::Backend {
+ message: error.to_string(),
+ })?;
let state = instance.state().await.map_err(|error| ChatSessionError::Backend {
message: error.to_string(),
})?;
+ let stop_token_ids = instance.stop_token_ids().ok_or_else(|| ChatSessionError::Loading {
+ message: "stop_token_ids is None".to_string(),
+ })?;
+
Ok(Self {
- _instance: instance,
- _state: state,
+ instance,
+ state,
+ encoding,
+ input_tokens: Vec::new(),
+ stop_token_ids,
})
}
pub async fn reset(&mut self) -> Result<(), ChatSessionError> {
- Err(ChatSessionError::Backend {
- message: "token chat session reset not implemented".to_string(),
- })
+ self.encoding.reset().map_err(|error| ChatSessionError::Backend {
+ message: error.to_string(),
+ })?;
+ self.state_reset().await?;
+ Ok(())
}
- pub fn stream<'a>(
+ pub async fn stream<'a>(
&'a mut self,
- _input: &'a Vec<ChatMessage>,
- _config: ChatReplyConfig,
- _cancel_token: CancellationToken,
+ input: &'a [ChatMessage],
+ config: ChatReplyConfig,
+ cancel_token: CancellationToken,
) -> Pin<Box<dyn Stream<Item = Result<Output, ChatSessionError>> + Send + 'a>> {
- Box::pin(stream::once(async {
- Err(ChatSessionError::Backend {
- message: "Token chat session stream not implemented".to_string(),
+ let time_start = Instant::now();
+ let power_recorder = <dyn PowerRecorder>::start();
+
+ let curr_all_tokens = self.encoding.state().tokens.clone();
+ let new_all_tokens = match self.build_input(input) {
+ Ok(input) => input,
+ Err(err) => {
+ return error_stream(ChatSessionError::Backend {
+ message: err.to_string(),
+ });
+ },
+ };
+
+ // if new_all_tokens = curr_all_tokens + suffix, then just encode suffix,
+ // else reset state and encode all tokens
+ let mut reset = new_all_tokens.len() <= curr_all_tokens.len();
+ if !reset {
+ for i in 0..curr_all_tokens.len() {
+ if new_all_tokens[i] != curr_all_tokens[i].id as u64 {
+ reset = true;
+ break;
+ }
+ }
+ }
+ self.input_tokens = if reset {
+ if let Err(err) = self.state_reset().await {
+ return error_stream(err);
+ }
+ new_all_tokens
+ } else {
+ new_all_tokens[curr_all_tokens.len()..].to_vec()
+ };
+
+ let stream_state = StreamingState {
+ config: config.clone(),
+ cancel_token: cancel_token.clone(),
+ encoding: &mut self.encoding,
+ max_context_length: self.instance.max_context_length(),
+ stop_token_ids: self.stop_token_ids.clone(),
+ power_recorder,
+
+ time_start,
+ time_last_token: None,
+ time_prefill_start: None,
+ time_first_token: None,
+ total_tokens_input: self.input_tokens.len(),
+ total_tokens_output: 0,
+ memory_usage: None,
+ };
+
+ let instance = self.instance.as_ref();
+ let stream = instance.stream(&self.input_tokens, self.state.as_mut(), config.clone(), cancel_token);
+ stream::unfold(
+ (stream, stream_state, false, false),
+ move |(mut inner, mut state, terminated, tail_done)| async move {
+ if tail_done {
+ return None;
+ }
+
+ match inner.next().await {
+ Some(event) => {
+ state.memory_usage = instance.peak_memory_usage();
+ let output = Self::build_output(event, &mut state);
+ let terminated = terminated || matches!(&output, Ok(out) if out.finish_reason.is_some());
+ Some((output, (inner, state, terminated, false)))
+ },
+ None => {
+ if !terminated && state.cancel_token.is_cancelled() {
+ let output = Ok(Self::render_output(&state, Some(ChatReplyFinishReason::Cancelled)));
+ Some((output, (inner, state, true, true)))
+ } else {
+ None
+ }
+ },
+ }
+ },
+ )
+ .boxed()
+ }
+
+ pub fn peak_memory_usage(&self) -> Option<usize> {
+ self.instance.peak_memory_usage()
+ }
+
+ async fn state_reset(&mut self) -> Result<(), ChatSessionError> {
+ self.state = self.instance.state().await.map_err(|error| ChatSessionError::Backend {
+ message: error.to_string(),
+ })?;
+ Ok(())
+ }
+
+ fn build_input(
+ &mut self,
+ all_messages: &[ChatMessage],
+ ) -> Result<StreamInput, ChatSessionError> {
+ self.encoding.reset().map_err(|err| ChatSessionError::Backend {
+ message: err.to_string(),
+ })?;
+ self.encoding.encode(all_messages.to_vec()).map_err(|err| ChatSessionError::Backend {
+ message: err.to_string(),
+ })?;
+ let all_tokens = self.encoding.state().tokens.iter().map(|token| token.id as u64).collect::<Vec<u64>>();
+ Ok(all_tokens)
+ }
+
+ fn build_output(
+ event: Result<StreamOutput, Error>,
+ state: &mut StreamingState,
+ ) -> Result<Output, ChatSessionError> {
+ let now = Instant::now();
+ let result = event.map_err(|err| ChatSessionError::Backend {
+ message: err.to_string(),
+ })?;
+
+ match result {
+ StreamOutput::LimitReached => Ok(Self::render_output(state, Some(ChatReplyFinishReason::Length))),
+ StreamOutput::PrefillStarted => {
+ state.time_prefill_start = Some(now);
+ // No token has been decoded yet, so the encoding's last message is still the
+ // input message. Emit a stats-only chunk instead of rendering it as the reply.
+ Ok(Output {
+ stats: state.get_stats(false),
+ ..Default::default()
+ })
+ },
+ StreamOutput::Token(token) => {
+ if state.total_tokens_output == 0 {
+ state.time_first_token = Some(now)
+ }
+ state.total_tokens_output += 1;
+ state.time_last_token = Some(now);
+
+ if let Err(err) = state.encoding.decode(vec![token as TokenId]) {
+ return Err(ChatSessionError::Backend {
+ message: err.to_string(),
+ });
+ }
+
+ let finish_reason = state.get_finish_reason(token);
+ Ok(Self::render_output(state, finish_reason))
+ },
+ }
+ }
+
+ fn render_output(
+ state: &StreamingState,
+ finish_reason: Option<ChatReplyFinishReason>,
+ ) -> Output {
+ let have_finish_reason = finish_reason.is_some();
+ let Some(message) = state.encoding.state().messages.last() else {
+ return Output {
+ finish_reason,
+ stats: state.get_stats(have_finish_reason),
+ ..Default::default()
+ };
+ };
+
+ let tool_calls = message
+ .content
+ .iter()
+ .filter_map(|block| match block {
+ ChatContentBlock::ToolCall {
+ value,
+ } => Some(ToolCallState::Finished(value.clone())),
+ ChatContentBlock::ToolCallCandidate {
+ value,
+ } => Some(ToolCallState::Candidate(value.json.clone())),
+ _ => None,
})
- }))
+ .collect();
+
+ Output {
+ reasoning: message.reasoning(),
+ text: message.text(),
+ tool_calls,
+ finish_reason,
+ stats: state.get_stats(have_finish_reason),
+ }
+ }
+}
+
+struct StreamingState<'a> {
+ config: ChatReplyConfig,
+ cancel_token: CancellationToken,
+ encoding: &'a mut Encoding,
+ max_context_length: Option<usize>,
+ stop_token_ids: Box<[u64]>,
+ power_recorder: Box<dyn PowerRecorder>,
+
+ time_start: Instant,
+ time_last_token: Option<Instant>,
+ time_prefill_start: Option<Instant>,
+ time_first_token: Option<Instant>,
+ total_tokens_input: usize,
+ total_tokens_output: usize,
+ memory_usage: Option<usize>,
+}
+
+impl StreamingState<'_> {
+ fn get_finish_reason(
+ &self,
+ token: u64,
+ ) -> Option<ChatReplyFinishReason> {
+ let tokens_count = self.encoding.state().tokens.len();
+ if self.cancel_token.is_cancelled() {
+ Some(ChatReplyFinishReason::Cancelled)
+ } else if self.stop_token_ids.contains(&token) {
+ Some(ChatReplyFinishReason::Stop)
+ } else if let Some(token_limit) = self.config.token_limit
+ && self.total_tokens_output >= token_limit as usize
+ {
+ Some(ChatReplyFinishReason::Length)
+ } else if let Some(length) = self.max_context_length
+ && tokens_count >= length
+ {
+ Some(ChatReplyFinishReason::ContextLimitReached)
+ } else {
+ None
+ }
+ }
+
+ fn get_stats(
+ &self,
+ last_stat: bool,
+ ) -> ChatReplyStats {
+ let power_stats = last_stat.then(|| self.power_recorder.stop()).flatten();
+
+ let total_duration = self.time_last_token.unwrap_or(Instant::now()).duration_since(self.time_start);
+ let ttft_duration = if let (Some(start), Some(finish)) = (self.time_prefill_start, self.time_first_token) {
+ Some(finish.duration_since(start))
+ } else {
+ None
+ };
+ let prefill_tps = ttft_duration.and_then(|duration| {
+ (self.total_tokens_input > 0 && !duration.is_zero())
+ .then(|| self.total_tokens_input as f64 / duration.as_secs_f64())
+ });
+
+ let generate_duration = if let (Some(start), Some(finish)) = (self.time_first_token, self.time_last_token) {
+ Some(finish.duration_since(start))
+ } else {
+ None
+ };
+ let generate_tps = calculate_rate(self.total_tokens_output, generate_duration);
+
+ ChatReplyStats {
+ duration: total_duration.as_secs_f64(),
+ time_to_first_token: ttft_duration.map(|time| time.as_secs_f64()),
+ prefill_tokens_per_second: prefill_tps,
+ generate_tokens_per_second: generate_tps,
+ tokens_count_input: Some(self.total_tokens_input as u32),
+ tokens_count_output: Some(self.total_tokens_output as u32),
+ memory_used_bytes: last_stat.then(|| self.memory_usage.map(|bytes| bytes as i64)).flatten(),
+ power_stats,
+ }
+ }
+}
+
+fn calculate_rate(
+ tokens: usize,
+ duration: Option<Duration>,
+) -> Option<f64> {
+ if tokens < 2 {
+ return None;
}
+
+ let duration = duration?;
+ if duration.is_zero() {
+ return None;
+ }
+
+ Some((tokens - 1) as f64 / duration.as_secs_f64())
}
diff --git a/crates/nagare/src/classification/mod.rs b/crates/nagare/src/classification/mod.rs
index c30865770..312a1ef2f 100644
--- a/crates/nagare/src/classification/mod.rs
+++ b/crates/nagare/src/classification/mod.rs
@@ -1,16 +1,22 @@
mod error;
-use std::sync::Arc;
+use std::{
+ sync::Arc,
+ time::{Duration, Instant},
+};
pub use error::ClassificationSessionError;
use futures::StreamExt;
+use hanashi::ClassificationEncoding;
use serde::{Deserialize, Serialize};
use shoji::{
traits::{Backend, State as StateTrait, backend::classification::Instance},
types::{
basic::CancelToken,
model::{Model, ModelSpecialization},
- session::classification::{ClassificationMessage, ClassificationOutput},
+ session::classification::{
+ ClassificationMessage, ClassificationOutput, ClassificationOutputProbabilities, ClassificationStats,
+ },
},
};
use tokio::sync::{Mutex, mpsc};
@@ -25,6 +31,7 @@ pub enum ClassificationSessionState {
struct InstanceHolder {
instance: Box<dyn Instance>,
state: Box<dyn StateTrait>,
+ encoding: ClassificationEncoding,
}
#[bindings::export(Class)]
@@ -48,7 +55,7 @@ impl ClassificationSession {
let holder = tokio::spawn(async move {
let classification_backend =
backend.as_classification_capable().ok_or(ClassificationSessionError::UnsupportedModel {})?;
- let instance = classification_backend.instance(reference, ()).await.map_err(|error| {
+ let instance = classification_backend.instance(reference.clone(), ()).await.map_err(|error| {
ClassificationSessionError::Backend {
message: error.to_string(),
}
@@ -56,9 +63,15 @@ impl ClassificationSession {
let instance_state = instance.state().await.map_err(|error| ClassificationSessionError::Backend {
message: error.to_string(),
})?;
+ let encoding =
+ ClassificationEncoding::new(reference.as_str()).map_err(|err| ClassificationSessionError::Backend {
+ message: err.to_string(),
+ })?;
+
Ok(InstanceHolder {
instance,
state: instance_state,
+ encoding,
})
})
.await
@@ -85,6 +98,8 @@ impl ClassificationSession {
&self,
input: Vec<ClassificationMessage>,
) -> Result<ClassificationOutput, ClassificationSessionError> {
+ let time_start = Instant::now();
+
let cancel_token_to_return = CancelToken::new();
let (sender, mut receiver) =
mpsc::unbounded_channel::<Result<ClassificationOutput, ClassificationSessionError>>();
@@ -107,26 +122,84 @@ impl ClassificationSession {
}
}
+ let mut duration_preprocessing = Duration::from_millis(0);
+ let mut duration_forward_pass = Duration::from_millis(0);
+ let mut tokens_count = 0usize;
let result = {
let mut holder = holder.lock().await;
let InstanceHolder {
instance,
state: backend_state,
+ encoding,
} = &mut *holder;
- let mut stream = instance.stream(&input, backend_state.as_mut(), (), cancel_token);
- let output = stream.next().await;
- drop(stream);
-
- match output {
- Some(Ok(output)) => Ok(output),
- Some(Err(error)) => Err(ClassificationSessionError::Backend {
- message: error.to_string(),
+ let time_before_encoding = Instant::now();
+ match encoding.encode(input.as_slice()) {
+ Ok(tokens) => {
+ tokens_count = tokens.len();
+ let input = tokens.iter().map(|token| u64::from(*token)).collect();
+ duration_preprocessing = Instant::now().duration_since(time_before_encoding);
+
+ let time_before_forward_pass = Instant::now();
+ let mut stream = instance.stream(&input, backend_state.as_mut(), (), cancel_token);
+ let output = stream.next().await;
+ duration_forward_pass = time_before_forward_pass.elapsed();
+ drop(stream);
+
+ match output {
+ Some(Ok(output)) => Ok(output),
+ Some(Err(error)) => Err(ClassificationSessionError::Backend {
+ message: error.to_string(),
+ }),
+ None => Err(ClassificationSessionError::NoResponse {}),
+ }
+ },
+ Err(err) => Err(ClassificationSessionError::Backend {
+ message: err.to_string(),
}),
- None => Err(ClassificationSessionError::NoResponse {}),
}
};
- let _ = sender.send(result);
+
+ let output = result.map(|result| {
+ let time_before_postprocessing = Instant::now();
+ let logits_f64 = result.logits.iter().map(|&value| value as f64).collect::<Vec<f64>>();
+ let (predicted_label, confidence) = result
+ .probabilities
+ .iter()
+ .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
+ .map(|(label, prob)| (label.clone(), *prob as f64))
+ .unwrap_or((String::new(), 0.0f64));
+
+ let preprocessing_duration = duration_preprocessing.as_secs_f64();
+ let forward_pass_duration = duration_forward_pass.as_secs_f64();
+
+ let postprocessing_duration = time_before_postprocessing.elapsed().as_secs_f64();
+ let total_duration = time_start.elapsed().as_secs_f64();
+
+ let tokens_per_second = if forward_pass_duration > 0.0 {
+ tokens_count as f64 / forward_pass_duration
+ } else {
+ 0.0f64
+ };
+
+ ClassificationOutput {
+ logits: logits_f64,
+ probabilities: ClassificationOutputProbabilities {
+ values: result.probabilities.into_iter().map(|entry| (entry.0, entry.1 as f64)).collect(),
+ },
+ stats: ClassificationStats {
+ preprocessing_duration,
+ forward_pass_duration,
+ postprocessing_duration,
+ total_duration,
+ tokens_count: tokens_count as i64,
+ tokens_per_second,
+ predicted_label,
+ confidence,
+ },
+ }
+ });
+ let _ = sender.send(output);
*state.lock().await = ClassificationSessionState::Idle;
});
diff --git a/crates/nagare/src/lib.rs b/crates/nagare/src/lib.rs
index 3aa2d5625..65698a0d0 100644
--- a/crates/nagare/src/lib.rs
+++ b/crates/nagare/src/lib.rs
@@ -6,3 +6,4 @@ pub mod chat;
pub mod classification;
pub mod telemetry;
pub mod text_to_speech;
+mod util;
diff --git a/crates/nagare/src/util/helpers.rs b/crates/nagare/src/util/helpers.rs
new file mode 100644
index 000000000..24c1b1dca
--- /dev/null
+++ b/crates/nagare/src/util/helpers.rs
@@ -0,0 +1,37 @@
+use std::{io, pin::Pin};
+
+use futures::{Stream, stream};
+use hanashi::{
+ Encoding as EncodingTrait,
+ chat::{Config, Context as HanashiContext, Encoding, TokenizerLocation, hanashi::Config as HanashiConfig},
+};
+use shoji::{traits::backend::chat_message::Output, types::model::Model};
+
+use crate::chat::ChatSessionError;
+
+pub fn error_stream<'a>(
+ err: ChatSessionError
+) -> Pin<Box<dyn Stream<Item = Result<Output, ChatSessionError>> + Send + 'a>> {
+ Box::pin(stream::once(async move { Err(err) }))
+}
+
+pub fn build_encoding(
+ reference: String,
+ model: &Model,
+) -> Result<Encoding, io::Error> {
+ let model_name = match model.family.as_ref() {
+ Some(family) => family.metadata.name.clone(),
+ None => model.identifier.clone(),
+ }
+ .to_lowercase();
+ let hanashi_config: HanashiConfig = serde_json::from_value(serde_json::json!({ "name": model_name }))
+ .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
+ let encoding_config = Config::Hanashi(hanashi_config);
+ let encoding_context = HanashiContext {
+ tokenizer_location: TokenizerLocation::Directory {
+ path: reference,
+ name: Some("tokenizer.json".to_string()),
+ },
+ };
+ Encoding::new(encoding_config, encoding_context).map_err(io::Error::other)
+}
diff --git a/crates/nagare/src/util/mod.rs b/crates/nagare/src/util/mod.rs
new file mode 100644
index 000000000..adf0e9387
--- /dev/null
+++ b/crates/nagare/src/util/mod.rs
@@ -0,0 +1,2 @@
+pub mod helpers;
+pub mod power;
diff --git a/crates/backend-uzu/src/session/types/stats.rs b/crates/nagare/src/util/power/apple.rs
similarity index 65%
rename from crates/backend-uzu/src/session/types/stats.rs
rename to crates/nagare/src/util/power/apple.rs
index 29ce9e15d..4beb079fc 100644
--- a/crates/backend-uzu/src/session/types/stats.rs
+++ b/crates/nagare/src/util/power/apple.rs
@@ -1,23 +1,32 @@
-use serde::{Deserialize, Serialize};
+#![cfg(target_vendor = "apple")]
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct PowerStats {
- pub samples_count: u64,
- pub average_cpu_watts: f64,
- pub average_gpu_watts: f64,
- pub average_gpu_sram_watts: f64,
- pub average_ane_watts: f64,
- pub average_ram_watts: f64,
- pub average_total_watts: f64,
- pub average_package_watts: f64,
- pub max_package_watts: f64,
- pub energy_joules: f64,
+use std::sync::Mutex;
+
+use shoji::types::session::chat::ChatReplyPowerStats;
+
+use crate::util::power::PowerRecorder;
+
+pub struct ApplePowerRecorder {
+ // Option so stop() can take ownership of the handle through a shared reference.
+ handle: Mutex<Option<keisoku::RecorderHandle>>,
+}
+
+impl ApplePowerRecorder {
+ pub fn new() -> Self {
+ Self {
+ handle: Mutex::new(Some(keisoku::start(keisoku::Config {
+ interval: std::time::Duration::from_millis(100),
+ }))),
+ }
+ }
}
-#[cfg(target_vendor = "apple")]
-impl PowerStats {
- pub(crate) fn from_keisoku_session(session: &keisoku::Session) -> Option<Self> {
- let mut samples_count = 0_u64;
+impl PowerRecorder for ApplePowerRecorder {
+ fn stop(&self) -> Option<ChatReplyPowerStats> {
+ let handle = self.handle.lock().ok()?.take()?;
+ let session = handle.stop();
+
+ let mut samples_count = 0_i64;
// Each accumulator integrates watts over time (watts × seconds); the time-weighted
// average is the integral divided by total_elapsed_secs.
let mut cpu_joules = 0.0_f64;
@@ -68,7 +77,7 @@ impl PowerStats {
return None;
}
- Some(Self {
+ Some(ChatReplyPowerStats {
samples_count,
average_cpu_watts: cpu_joules / total_elapsed_secs,
average_gpu_watts: gpu_joules / total_elapsed_secs,
@@ -82,38 +91,3 @@ impl PowerStats {
})
}
}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct RunStats {
- pub count: u64,
- pub average_duration: f64,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct StepStats {
- pub duration: f64,
- pub suffix_length: u64,
- pub tokens_count: u64,
- pub tokens_per_second: f64,
- pub processed_tokens_per_second: f64,
- pub model_run: RunStats,
- pub run: Option<RunStats>,
- pub speculator_proposed: u64,
- pub speculator_accepted: u64,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct TotalStats {
- pub duration: f64,
- pub tokens_count_input: u64,
- pub tokens_count_output: u64,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct Stats {
- pub prefill_stats: StepStats,
- pub generate_stats: Option<StepStats>,
- pub total_stats: TotalStats,
- pub memory_used_bytes: Option<u64>,
- pub power_stats: Option<PowerStats>,
-}
diff --git a/crates/nagare/src/util/power/mod.rs b/crates/nagare/src/util/power/mod.rs
new file mode 100644
index 000000000..1b407c7ee
--- /dev/null
+++ b/crates/nagare/src/util/power/mod.rs
@@ -0,0 +1,26 @@
+#![allow(dead_code)]
+
+mod apple;
+mod stub;
+
+use shoji::types::session::chat::ChatReplyPowerStats;
+
+pub trait PowerRecorder: Send {
+ fn stop(&self) -> Option<ChatReplyPowerStats>;
+}
+
+impl dyn PowerRecorder {
+ pub fn start() -> Box<dyn PowerRecorder> {
+ #[cfg(target_vendor = "apple")]
+ {
+ use crate::util::power::apple::ApplePowerRecorder;
+ Box::new(ApplePowerRecorder::new()) as Box<dyn PowerRecorder>
+ }
+
+ #[cfg(not(target_vendor = "apple"))]
+ {
+ use crate::util::power::stub::StubPowerRecorder;
+ Box::new(StubPowerRecorder::new()) as Box<dyn PowerRecorder>
+ }
+ }
+}
diff --git a/crates/nagare/src/util/power/stub.rs b/crates/nagare/src/util/power/stub.rs
new file mode 100644
index 000000000..c1c00762e
--- /dev/null
+++ b/crates/nagare/src/util/power/stub.rs
@@ -0,0 +1,17 @@
+use shoji::types::session::chat::ChatReplyPowerStats;
+
+use crate::util::power::PowerRecorder;
+
+pub struct StubPowerRecorder {}
+
+impl StubPowerRecorder {
+ pub fn new() -> Self {
+ Self {}
+ }
+}
+
+impl PowerRecorder for StubPowerRecorder {
+ fn stop(&self) -> Option<ChatReplyPowerStats> {
+ None
+ }
+}
diff --git a/crates/shoji/Cargo.toml b/crates/shoji/Cargo.toml
index 1ff46b9ce..b94bcb06e 100644
--- a/crates/shoji/Cargo.toml
+++ b/crates/shoji/Cargo.toml
@@ -63,6 +63,7 @@ wasm-bindgen = { workspace = true, optional = true }
serde-wasm-bindgen = { workspace = true, optional = true }
wasm-bindgen-futures = { workspace = true, optional = true }
tsify = { workspace = true, optional = true }
+tokenizers.workspace = true
[build-dependencies]
napi-build = { workspace = true, optional = true }
diff --git a/crates/shoji/src/traits/backend/chat_token.rs b/crates/shoji/src/traits/backend/chat_token.rs
index 932e47c8a..2dc8ac499 100644
--- a/crates/shoji/src/traits/backend/chat_token.rs
+++ b/crates/shoji/src/traits/backend/chat_token.rs
@@ -1,27 +1,34 @@
use std::pin::Pin;
+use tokenizers::Tokenizer;
+
use crate::{
traits::backend::{Error, Instance as InstanceTrait},
types::session::chat::{ChatConfig, ChatReplyConfig},
};
+pub enum TokenStreamOutput {
+ LimitReached,
+ PrefillStarted,
+ Token(u64),
+}
+
pub type StreamInput = Vec<u64>;
-pub type StreamOutput = u64;
+pub type StreamOutput = TokenStreamOutput;
pub trait Backend: Send + Sync {
- fn instance(
- &self,
+ fn instance<'a>(
+ &'a self,
reference: String,
config: ChatConfig,
- ) -> Pin<Box<dyn Future<Output = Result<Box<dyn Instance>, Error>> + Send + '_>>;
+ tokenizer: &'a Tokenizer,
+ ) -> Pin<Box<dyn Future<Output = Result<Box<dyn Instance>, Error>> + Send + 'a>>;
}
pub trait Instance:
InstanceTrait<StreamConfig = ChatReplyConfig, StreamInput = StreamInput, StreamOutput = StreamOutput>
{
-}
+ fn max_context_length(&self) -> Option<usize>;
-impl<T> Instance for T where
- T: InstanceTrait<StreamConfig = ChatReplyConfig, StreamInput = StreamInput, StreamOutput = StreamOutput>
-{
+ fn stop_token_ids(&self) -> Option<Box<[u64]>>;
}
diff --git a/crates/shoji/src/traits/backend/classification.rs b/crates/shoji/src/traits/backend/classification.rs
index 7d238e3a2..ff84172c4 100644
--- a/crates/shoji/src/traits/backend/classification.rs
+++ b/crates/shoji/src/traits/backend/classification.rs
@@ -1,14 +1,16 @@
-use std::pin::Pin;
+use std::{collections::HashMap, pin::Pin};
-use crate::{
- traits::backend::{Error, Instance as InstanceTrait},
- types::session::classification::{ClassificationMessage, ClassificationOutput},
-};
+use crate::traits::backend::{Error, Instance as InstanceTrait};
+
+pub struct ClassifierOutput {
+ pub logits: Vec<f32>,
+ pub probabilities: HashMap<String, f32>,
+}
pub type Config = ();
pub type StreamConfig = ();
-pub type StreamInput = Vec<ClassificationMessage>;
-pub type StreamOutput = ClassificationOutput;
+pub type StreamInput = Vec<u64>;
+pub type StreamOutput = ClassifierOutput;
pub trait Backend: Send + Sync {
fn instance(
diff --git a/crates/shoji/src/traits/backend/mod.rs b/crates/shoji/src/traits/backend/mod.rs
index db41a35a3..36396d954 100644
--- a/crates/shoji/src/traits/backend/mod.rs
+++ b/crates/shoji/src/traits/backend/mod.rs
@@ -3,7 +3,7 @@ pub mod chat_token;
pub mod classification;
pub mod text_to_speech;
-use std::pin::Pin;
+use std::{any::Any, pin::Pin};
use futures::Stream;
use tokio_util::sync::CancellationToken;
@@ -45,8 +45,8 @@ pub trait Instance: Send + Sync {
config: Self::StreamConfig,
cancel_token: CancellationToken,
) -> Pin<Box<dyn Stream<Item = Result<Self::StreamOutput, Error>> + Send + 'a>>;
-}
-pub trait State: Send + Sync + 'static {
- fn clone_boxed(&self) -> Box<dyn State>;
+ fn peak_memory_usage(&self) -> Option<usize>;
}
+
+pub trait State: Send + Sync + Any + 'static {}
diff --git a/crates/uzu/Cargo.toml b/crates/uzu/Cargo.toml
index 1510d5920..7812de672 100644
--- a/crates/uzu/Cargo.toml
+++ b/crates/uzu/Cargo.toml
@@ -16,7 +16,6 @@ default = ["backend-metal", "capability-grammar", "capability-cli"]
backend-cpu = []
backend-metal = ["backend-uzu/metal"]
capability-grammar = ["backend-uzu/grammar"]
-capability-tracing = ["backend-uzu/tracing"]
capability-cli = ["dep:iocraft", "dep:indoc"]
bindings = [
"bindings-uniffi",
diff --git a/crates/uzu/src/cli/sessions/chat.rs b/crates/uzu/src/cli/sessions/chat.rs
index a09c31b0a..d1ed11b74 100644
--- a/crates/uzu/src/cli/sessions/chat.rs
+++ b/crates/uzu/src/cli/sessions/chat.rs
@@ -138,10 +138,15 @@ pub async fn run_session(
let preferences = state.read().preferences;
let thinking_support =
state.read().model_state.as_ref().map(|model_state| model_state.capabilities.thinking).unwrap_or_default();
- let mut user_message = ChatMessage::user().with_text(text);
- if let Some(reasoning_effort) = thinking_support.with_preference(&preferences.thinking).reasoning_effort() {
- user_message = user_message.with_reasoning_effort(reasoning_effort);
- }
+
+ let user_message = ChatMessage::user().with_text(text);
+ let mut messages = vec![user_message];
+ if let Some(reasoning_effort) = thinking_support.with_preference(&preferences.thinking).reasoning_effort()
+ && session.messages().await.is_empty()
+ {
+ let system_message = ChatMessage::system().with_reasoning_effort(reasoning_effort);
+ messages.insert(0, system_message);
+ };
let reply_config = ChatReplyConfig::default().with_sampling_policy(preferences.sampling_policy());
{
let mut state = state.write();
@@ -152,7 +157,7 @@ pub async fn run_session(
}
}
- let stream = session.reply_with_stream(vec![user_message], reply_config).await;
+ let stream = session.reply_with_stream(messages, reply_config).await;
let mut latest_reply: Option<ChatReply> = None;
{
let mut state = state.write();
diff --git a/crates/uzu/src/engine/config.rs b/crates/uzu/src/engine/config.rs
index 3991a027c..4c63aec0e 100644
--- a/crates/uzu/src/engine/config.rs
+++ b/crates/uzu/src/engine/config.rs
@@ -9,6 +9,7 @@ use crate::{
pub const KEY_MIRAI_API_KEY: &str = "MIRAI_API_KEY";
pub const KEY_LALAMO_PATH: &str = "LALAMO_PATH";
+pub const KEY_LOCAL_PATH: &str = "LOCAL_PATH";
pub const KEY_HF_TOKEN: &str = "HF_TOKEN";
pub const KEY_OPENAI_API_KEY: &str = "OPENAI_API_KEY";
pub const KEY_ANTHROPIC_API_KEY: &str = "ANTHROPIC_API_KEY";
@@ -24,6 +25,7 @@ pub struct EngineConfig {
pub application_identifier: Option<String>,
pub mirai_api_key: Option<String>,
pub lalamo_path: Option<String>,
+ pub local_path: Option<String>,
pub huggingface_api_key: Option<String>,
pub openai_api_key: Option<String>,
pub anthropic_api_key: Option<String>,
@@ -43,6 +45,7 @@ impl Default for EngineConfig {
application_identifier: None,
mirai_api_key: env::var(KEY_MIRAI_API_KEY).ok(),
lalamo_path: env::var(KEY_LALAMO_PATH).ok(),
+ local_path: env::var(KEY_LOCAL_PATH).ok(),
huggingface_api_key: env::var(KEY_HF_TOKEN).ok(),
openai_api_key: env::var(KEY_OPENAI_API_KEY).ok(),
anthropic_api_key: env::var(KEY_ANTHROPIC_API_KEY).ok(),
@@ -127,6 +130,17 @@ impl EngineConfig {
}
}
+ #[bindings::export(Method)]
+ pub fn with_local_path(
+ &self,
+ local_path: String,
+ ) -> Self {
+ Self {
+ local_path: Some(local_path),
+ ..self.clone()
+ }
+ }
+
#[bindings::export(Method)]
pub fn with_huggingface_api_key(
&self,
diff --git a/crates/uzu/src/engine/mod.rs b/crates/uzu/src/engine/mod.rs
index 674d015c1..b0662de98 100644
--- a/crates/uzu/src/engine/mod.rs
+++ b/crates/uzu/src/engine/mod.rs
@@ -7,7 +7,7 @@ mod error;
use std::{collections::HashMap, sync::Arc, time::Duration};
use backend_remote::openai::Backend as OpenAIBackend;
-use backend_uzu::inference::Backend as UzuBackend;
+use backend_uzu::bridge::UzuLlmBackend;
pub use callback::{EngineCallback, EngineCallbackType};
pub use config::EngineConfig;
pub use download_manager::DownloadManagerType;
@@ -115,7 +115,7 @@ impl Engine {
engine.spawn_storage_listener().await;
{
- let uzu_backend = UzuBackend::new();
+ let uzu_backend = UzuLlmBackend::new();
let uzu_backend_identifier = uzu_backend.identifier();
let uzu_backend_version = uzu_backend.version();
@@ -136,12 +136,20 @@ impl Engine {
if let Some(lalamo_path) = config.lalamo_path {
let lalamo_registry = LocalRegistry::new(LocalRegistryConfig::lalamo(
- uzu_backend_identifier,
- uzu_backend_version,
+ uzu_backend_identifier.clone(),
+ uzu_backend_version.clone(),
lalamo_path,
))?;
engine.add_registry(Box::new(lalamo_registry)).await?;
}
+ if let Some(local_path) = config.local_path {
+ let local_registry = LocalRegistry::new(LocalRegistryConfig::local(
+ uzu_backend_identifier.clone(),
+ uzu_backend_version.clone(),
+ local_path,
+ ))?;
+ engine.add_registry(Box::new(local_registry)).await?;
+ }
}
let mut openai_configs: Vec<OpenAIConfig> = vec![];
diff --git a/crates/uzu/src/registry/local/config.rs b/crates/uzu/src/registry/local/config.rs
index 9ffadcdc6..7fd9380a9 100644
--- a/crates/uzu/src/registry/local/config.rs
+++ b/crates/uzu/src/registry/local/config.rs
@@ -1,6 +1,6 @@
use std::{path::PathBuf, sync::Arc};
-use backend_uzu::inference::resolve_model_specialization;
+use backend_uzu::bridge::resolve_model_specialization;
use shoji::types::model::Model;
use crate::registry::RegistryError;
@@ -42,18 +42,7 @@ impl Config {
path: String,
) -> Self {
let models_path = PathBuf::from(&path).join("models");
- let resolver: ModelResolver = Arc::new(move |mut model: Model| -> Result<Model, RegistryError> {
- let model_path = model.local_external_path().ok_or_else(|| RegistryError::UnableToGetModels {
- message: format!("Local model {} has no local path", model.identifier),
- })?;
- let model_path = PathBuf::from(model_path);
- let specialization =
- resolve_model_specialization(&model_path).map_err(|error| RegistryError::UnableToGetModels {
- message: format!("Unable to resolve specialization for {}: {error}", model_path.display()),
- })?;
- model.specializations = vec![specialization];
- Ok(model)
- });
+ let resolver: ModelResolver = Arc::new(Self::resolve_model);
Self::new(
"lalamo".to_string(),
backend_identifier,
@@ -63,4 +52,26 @@ impl Config {
Some(resolver),
)
}
+
+ pub fn local(
+ backend_identifier: String,
+ backend_version: String,
+ path: String,
+ ) -> Self {
+ let resolver: ModelResolver = Arc::new(Self::resolve_model);
+ Self::new("local".to_string(), backend_identifier, backend_version, "Local".to_string(), path, Some(resolver))
+ }
+
+ fn resolve_model(mut model: Model) -> Result<Model, RegistryError> {
+ let model_path = model.local_external_path().ok_or_else(|| RegistryError::UnableToGetModels {
+ message: format!("Local model {} has no local path", model.identifier),
+ })?;
+ let model_path = PathBuf::from(model_path);
+ let specialization =
+ resolve_model_specialization(&model_path).map_err(|error| RegistryError::UnableToGetModels {
+ message: format!("Unable to resolve specialization for {}: {error}", model_path.display()),
+ })?;
+ model.specializations = vec![specialization];
+ Ok(model)
+ }
}
diff --git a/crates/uzu/src/registry/local/mod.rs b/crates/uzu/src/registry/local/mod.rs
index 4a9de94a3..1360e2aa6 100644
--- a/crates/uzu/src/registry/local/mod.rs
+++ b/crates/uzu/src/registry/local/mod.rs
@@ -62,7 +62,13 @@ impl RegistryTrait for Registry {
let model = self.model(name);
let model = match self.config.resolver.as_ref() {
- Some(resolver) => resolver(model)?,
+ Some(resolver) => match resolver(model) {
+ Ok(model) => model,
+ Err(error) => {
+ tracing::warn!(?error, path = %path.display(), "skipping invalid local model");
+ continue;
+ },
+ },
None => model,
};
models.push(model);
diff --git a/platforms.toml b/platforms.toml
index 96c126543..b45c93d41 100644
--- a/platforms.toml
+++ b/platforms.toml
@@ -17,7 +17,7 @@ maturin = { provider = "uv", version = "1.13.1" }
[targets."aarch64-apple-darwin"]
backend = "metal"
aliases = ["apple", "macos"]
-capabilities_supported = ["grammar", "tracing", "cli"]
+capabilities_supported = ["grammar", "cli"]
capabilities_default = ["grammar", "cli"]
required_envs = ["MACOSX_DEPLOYMENT_TARGET"]
@@ -31,14 +31,14 @@ required_envs = ["MACOSX_DEPLOYMENT_TARGET"]
[targets."aarch64-apple-ios"]
backend = "metal"
aliases = ["apple", "ios"]
-capabilities_supported = ["grammar", "tracing", "cli"]
+capabilities_supported = ["grammar", "cli"]
capabilities_default = ["grammar", "cli"]
required_envs = ["IPHONEOS_DEPLOYMENT_TARGET"]
[targets."aarch64-apple-ios-sim"]
backend = "metal"
aliases = ["apple", "ios-sim", "ios-simulator"]
-capabilities_supported = ["grammar", "tracing", "cli"]
+capabilities_supported = ["grammar", "cli"]
capabilities_default = ["grammar", "cli"]
required_envs = ["IPHONEOS_DEPLOYMENT_TARGET"]