A high-performance inference engine for AI models
Clippy (#480)
uuuvn8cf3630aeb56
diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.ymlindex d75e4a49f..57092dc88 100644--- a/.github/actions/setup/action.yml+++ b/.github/actions/setup/action.yml@@ -51,7 +51,7 @@ runs:- uses: dtolnay/rust-toolchain@nightlywith:- components: ${{ inputs.linters == 'true' && 'rustfmt' || '' }}+ components: ${{ inputs.linters == 'true' && 'rustfmt,clippy' || '' }}- if: inputs.linux == 'true'run: sudo apt-get update && sudo apt-get install -y libasound2-dev@@ -103,4 +103,4 @@ runs:- if: inputs.bindings == 'true'uses: pnpm/action-setup@v4with:- version: 10.33.0\ No newline at end of file+ version: 10.33.0diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex f22f0219b..392383e47 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -30,6 +30,7 @@ jobs:uses: ./.github/actions/setupwith:linters: true+ metal: true- name: Check backend-uzu rustfmt discoveryif: ${{ always() && steps.setup.outcome == 'success' }}@@ -43,6 +44,10 @@ jobs:if: ${{ always() && steps.setup.outcome == 'success' }}run: ./scripts/clang-format.sh --check+ - name: Lint with clippy+ if: ${{ always() && steps.setup.outcome == 'success' }}+ run: cargo +nightly clippy --workspace --all-targets --features tracing -- -D warnings+- name: Check that Cargo.lock is consistent with Cargo.tomlif: ${{ always() && steps.setup.outcome == 'success' }}run: |@@ -51,7 +56,7 @@ jobs:- name: Check with cargo-denyif: ${{ always() && steps.setup.outcome == 'success' }}- run: cargo deny check+ run: cargo deny check -D warnings- name: Check syncif: ${{ always() && steps.setup.outcome == 'success' }}diff --git a/.helix/languages.toml b/.helix/languages.tomlindex 86bc3d100..e2f05a3e3 100644--- a/.helix/languages.toml+++ b/.helix/languages.toml@@ -9,3 +9,6 @@ file-types = [][[language]]name = "metal"file-types = ["metal", "h"]++[language-server.rust-analyzer.config.check]+command = "clippy"diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex 25f57d46d..ecba113e7 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -13,6 +13,7 @@"editor.formatOnSave": true,"editor.defaultFormatter": "rust-lang.rust-analyzer",},+ "rust-analyzer.check.command": "clippy","rust-analyzer.check.workspace": false,"rust-analyzer.cargo.allTargets": false,"rust-analyzer.check.noDefaultFeatures": true,diff --git a/.zed/settings.json b/.zed/settings.jsonindex d3bfc8185..0b4fdc81c 100644--- a/.zed/settings.json+++ b/.zed/settings.json@@ -12,6 +12,13 @@}},"lsp": {+ "rust-analyzer": {+ "initialization_options": {+ "check": {+ "command": "clippy"+ }+ }+ },"metal-analyzer": {"initialization_options": {"metal-analyzer": {diff --git a/Cargo.toml b/Cargo.tomlindex 946b5207c..cbc72228c 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -207,6 +207,18 @@ rodio = { version = "0.22.2", default-features = false, features = ["wav",] }+[workspace.lints.clippy]+# TODO: add large_stack_frames, large_stack_arrays, trivially_copy_pass_by_ref, needless_pass_by_value, map_err_ignore, use_self, cloned_instead_of_copied, manual_let_else, semicolon_if_nothing_returned, uninlined_format_args, lossy_float_literal+module_inception = "allow"+type_complexity = "allow"+upper_case_acronyms = "allow"+large_enum_variant = "allow" # TODO: remove+enum_variant_names = "allow"+new_without_default = "allow"+too_many_arguments = "allow"+needless_range_loop = "allow" # TODO: remove+missing_safety_doc = "allow" # TODO: maybe remove?+[workspace.metadata.dinghy]forward-cfgs = ["metal_backend", "grammar_xgrammar"]diff --git a/README.md b/README.mdindex 801cb1643..cc2feae96 100644--- a/README.md+++ b/README.md@@ -1080,11 +1080,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {schema: schema_string,}));let replies = session.reply(messages, chat_reply_config).await?;- if let Some(reply) = replies.first() {- if let Some(text) = reply.message.text() {- let parsed: CountryList = serde_json::from_str(&text)?;- println!("{parsed:#?}");- }+ if let Some(reply) = replies.first()+ && let Some(text) = reply.message.text()+ {+ let parsed: CountryList = serde_json::from_str(&text)?;+ println!("{parsed:#?}");}Ok(())diff --git a/clippy.toml b/clippy.tomlnew file mode 100644index 000000000..cda8d17ee--- /dev/null+++ b/clippy.toml@@ -0,0 +1 @@+avoid-breaking-exported-api = falsediff --git a/crates/backend-remote/Cargo.toml b/crates/backend-remote/Cargo.tomlindex 1196a0c33..7e767343e 100644--- a/crates/backend-remote/Cargo.toml+++ b/crates/backend-remote/Cargo.toml@@ -18,3 +18,6 @@ tokio-util.workspace = trueserde.workspace = truereqwest.workspace = trueindexmap.workspace = true++[lints]+workspace = truediff --git a/crates/backend-remote/src/openai/bridging/chat/message.rs b/crates/backend-remote/src/openai/bridging/chat/message.rsindex 2182cef19..564dd92f3 100644--- a/crates/backend-remote/src/openai/bridging/chat/message.rs+++ b/crates/backend-remote/src/openai/bridging/chat/message.rs@@ -69,11 +69,7 @@ pub fn build(message: &ChatMessage) -> Result<ChatCompletionRequestMessage, Erro}}),ResolvedRole::Assistant => {- let text_content = if let Some(content) = content {- Some(ChatCompletionRequestAssistantMessageContent::Text(content))- } else {- None- };+ let text_content = content.map(ChatCompletionRequestAssistantMessageContent::Text);#[allow(deprecated)]ChatCompletionRequestMessage::Assistant(ChatCompletionRequestAssistantMessage {content: text_content,diff --git a/crates/backend-remote/src/openai/bridging/chat/request.rs b/crates/backend-remote/src/openai/bridging/chat/request.rsindex 91c596bf0..ab01a938c 100644--- a/crates/backend-remote/src/openai/bridging/chat/request.rs+++ b/crates/backend-remote/src/openai/bridging/chat/request.rs@@ -45,7 +45,7 @@ pub fn build(request.reasoning_effort = Some(effort);}if let Some(token_limit) = config.token_limit {- request.max_completion_tokens = Some(token_limit as u32);+ request.max_completion_tokens = Some(token_limit);}match &config.sampling_policy {SamplingPolicy::Default {} => {},diff --git a/crates/backend-remote/src/openai/bridging/responses/request.rs b/crates/backend-remote/src/openai/bridging/responses/request.rsindex 2ef924de6..2426da638 100644--- a/crates/backend-remote/src/openai/bridging/responses/request.rs+++ b/crates/backend-remote/src/openai/bridging/responses/request.rs@@ -55,7 +55,7 @@ pub fn build(input: InputParam::Items(input_items),model: Some(model.to_string()),stream: Some(true),- max_output_tokens: config.token_limit.map(|value| value as u32),+ max_output_tokens: config.token_limit,temperature,top_p,reasoning,diff --git a/crates/backend-remote/src/openai/tool_call_state.rs b/crates/backend-remote/src/openai/tool_call_state.rsindex 991783046..b93793472 100644--- a/crates/backend-remote/src/openai/tool_call_state.rs+++ b/crates/backend-remote/src/openai/tool_call_state.rs@@ -32,16 +32,14 @@ impl ToolCallState {&self,finalize: bool,) -> OutputToolCallState {- if finalize {- if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&self.arguments) {- return OutputToolCallState::Finished(ToolCall {- identifier: Some(self.id.clone()),- name: self.name.clone(),- arguments: Value {- json: parsed.to_string(),- },- });- }+ if finalize && let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&self.arguments) {+ return OutputToolCallState::Finished(ToolCall {+ identifier: Some(self.id.clone()),+ name: self.name.clone(),+ arguments: Value {+ json: parsed.to_string(),+ },+ });}OutputToolCallState::Candidate(self.arguments.clone())}diff --git a/crates/backend-uzu/Cargo.toml b/crates/backend-uzu/Cargo.tomlindex 083b4fe64..7093bfc36 100644--- a/crates/backend-uzu/Cargo.toml+++ b/crates/backend-uzu/Cargo.toml@@ -105,6 +105,9 @@ metal = [grammar = ["dep:xgrammar"]tracing = []+[lints]+workspace = true+[[test]]name = "integration"path = "tests/integration/mod.rs"diff --git a/crates/backend-uzu/build/common/codegen.rs b/crates/backend-uzu/build/common/codegen.rsindex ce2f29194..e0e11e379 100644--- a/crates/backend-uzu/build/common/codegen.rs+++ b/crates/backend-uzu/build/common/codegen.rs@@ -10,12 +10,10 @@ pub fn write_tokens(let tokens = tokens.into();let file = file.as_ref();- let parsed = syn::parse2(tokens.clone().into())- .with_context(|| format!("cannot parse generated bindings: {}", tokens.to_string()))?;- fs::write(&file, prettyplease::unparse(&parsed))- .with_context(|| format!("cannot write file {}", file.display()))?;+ let parsed = syn::parse2(tokens.clone()).with_context(|| format!("cannot parse generated bindings: {}", tokens))?;+ fs::write(file, prettyplease::unparse(&parsed)).with_context(|| format!("cannot write file {}", file.display()))?;- std::process::Command::new("rustfmt").arg(&file).status().context("rustfmt failed")?;+ std::process::Command::new("rustfmt").arg(file).status().context("rustfmt failed")?;Ok(())}diff --git a/crates/backend-uzu/build/common/expr_rewrite.rs b/crates/backend-uzu/build/common/expr_rewrite.rsindex 05e474b62..813d90e50 100644--- a/crates/backend-uzu/build/common/expr_rewrite.rs+++ b/crates/backend-uzu/build/common/expr_rewrite.rs@@ -30,10 +30,9 @@ impl<F: FnMut(&Path) -> Option<Expr>> VisitMut for Walker<F> {path,..}) = expr+ && let Some(replacement) = (self.rewriter)(path){- if let Some(replacement) = (self.rewriter)(path) {- *expr = replacement;- }+ *expr = replacement;}}}diff --git a/crates/backend-uzu/build/common/mangling.rs b/crates/backend-uzu/build/common/mangling.rsindex 8fe99edc6..060cfef17 100644--- a/crates/backend-uzu/build/common/mangling.rs+++ b/crates/backend-uzu/build/common/mangling.rs@@ -16,7 +16,7 @@ pub fn static_mangle() -> String {format!("_D{}{}{}",- &function_name.as_ref().len().to_string(),+ function_name.as_ref().len(),function_name.as_ref(),variant.into_iter()@@ -36,7 +36,7 @@ pub fn dynamic_mangle(let format_string = format!("_D{}{}{}",- &function_name.as_ref().len().to_string(),+ function_name.as_ref().len(),function_name.as_ref(),repeat_n("S{}V{}", variant.len()).join(""));diff --git a/crates/backend-uzu/build/common/traitgen.rs b/crates/backend-uzu/build/common/traitgen.rsindex fa715831b..2c8146739 100644--- a/crates/backend-uzu/build/common/traitgen.rs+++ b/crates/backend-uzu/build/common/traitgen.rs@@ -84,6 +84,7 @@ pub fn traitgen(kernel: &Kernel) -> (TokenStream, TokenStream) {};let kernel_trait = quote! {+ #[allow(clippy::style, clippy::complexity, clippy::perf)]pub trait #trait_name: Sized {type Backend: crate::backends::common::Backend<Kernels: Kernels<#trait_name = Self>>;diff --git a/crates/backend-uzu/build/common/utils.rs b/crates/backend-uzu/build/common/utils.rsindex d755c0c25..b9abc7e80 100644--- a/crates/backend-uzu/build/common/utils.rs+++ b/crates/backend-uzu/build/common/utils.rs@@ -11,6 +11,6 @@ pub fn get_generic_name_stream(var_name: &str) -> TokenStream {}}).collect();- generic_name.insert_str(0, "T");+ 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.rsindex 84aee33c8..40f5b1b65 100644--- a/crates/backend-uzu/build/cpu/compiler.rs+++ b/crates/backend-uzu/build/cpu/compiler.rs@@ -50,7 +50,7 @@ impl FunctionArgument {format!("&[{}]", canonicalize_type_text(ty, enum_paths)).into_boxed_str(),),FunctionArgumentType::Constant(ty, Some(size)) => KernelArgumentType::Constant(- format!("&[{}; {}]", canonicalize_type_text(ty, enum_paths), size.to_token_stream().to_string(),)+ format!("&[{}; {}]", canonicalize_type_text(ty, enum_paths), size.to_token_stream(),).into_boxed_str(),),FunctionArgumentType::Scalar(ty) => {@@ -208,7 +208,7 @@ impl CpuCompiler {let expr = attr.parse_args::<Expr>().context("cannot parse constraint attribute")?;function_constraints.push(expr);},- _ => bail!("Unexpected attr {attr:?}"),+ _ => {},}}@@ -266,7 +266,7 @@ impl CpuCompiler {bail!("conditional argument type path must have one segment");}let seg = &ty.path.segments[0];- if seg.ident.to_string() != "Option" {+ if seg.ident != "Option" {bail!("conditional argument type must be Option<...>");}let PathArguments::AngleBracketed(option_arguments) = &seg.arguments else {@@ -313,11 +313,7 @@ impl CpuCompiler {for (parameter, (variant_name, _)) in std::iter::zip(function_parameters.iter(), function_variants.iter()) {if ¶meter.name != variant_name {- bail!(- "Parameter name doesn't match variant name: {} | {}",- parameter.name.to_string(),- variant_name.to_string(),- );+ bail!("Parameter name doesn't match variant name: {} | {}", parameter.name, variant_name,);}}@@ -492,7 +488,7 @@ impl CpuCompiler {}};- let encode_body = if function_parameters.len() > 0 {+ let encode_body = if !function_parameters.is_empty() {let mut parameter_idents = function_parameters.iter().map(|p| p.name.clone()).fold(quote! {}, |a, b| {if !a.is_empty() {quote! {#a , self.#b}@@ -610,6 +606,7 @@ impl CpuCompiler {#(#struct_fields_defs ,)*}+ #[allow(clippy::style, clippy::complexity, clippy::perf)]impl crate::backends::common::kernel::#trait_ident for #struct_ident {type Backend = crate::backends::cpu::Cpu;@@ -646,10 +643,10 @@ impl CpuCompiler {Type::Reference(ty) => match *ty.elem {Type::Slice(ty) => FunctionArgumentType::Constant(*ty.elem, None),Type::Array(ty) => FunctionArgumentType::Constant(*ty.elem, Some(ty.len)),- ty => bail!("unsupported reference type: {} ({:?})", ty.to_token_stream().to_string(), ty),+ ty => bail!("unsupported reference type: {} ({:?})", ty.to_token_stream(), ty),},Type::Path(ty) => FunctionArgumentType::Scalar(Type::Path(ty)),- ty => bail!("unsupported type: {} ({:?})", ty.to_token_stream().to_string(), ty),+ ty => bail!("unsupported type: {} ({:?})", ty.to_token_stream(), ty),})}diff --git a/crates/backend-uzu/build/main.rs b/crates/backend-uzu/build/main.rsindex 21fbc856b..3e8599c58 100644--- a/crates/backend-uzu/build/main.rs+++ b/crates/backend-uzu/build/main.rs@@ -54,9 +54,8 @@ async fn main() -> anyhow::Result<()> {let enum_paths = EnumPaths::from_gpu_types(&gpu_types).context("Failed to build enum path map")?;- let mut compilers: Vec<Box<dyn Compiler>> = Vec::new();-- compilers.push(Box::new(cpu::CpuCompiler::new()?));+ #[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 {diff --git a/crates/backend-uzu/build/metal/ast.rs b/crates/backend-uzu/build/metal/ast.rsindex ba24dba9d..aef2459c6 100644--- a/crates/backend-uzu/build/metal/ast.rs+++ b/crates/backend-uzu/build/metal/ast.rs@@ -86,7 +86,7 @@ fn annotation_from_ast_node(annotation_node: MetalAstNode) -> anyhow::Result<Box};// NOTE: string literal includes "" (and is probably not parsed?), using json parse here for now- Ok(serde_json::from_str(&value).context("failed to parse string literal")?)+ serde_json::from_str(&value).context("failed to parse string literal")}).collect()}@@ -284,7 +284,7 @@ fn parse_argument_type(bail!("dsl.specialize takes no arguments, got {}", annotation.len());}let rust_type = MetalArgument::scalar_type_to_rust(c_type)?;- Ok(MetalArgumentType::Specialize(rust_type.into()))+ Ok(MetalArgumentType::Specialize(rust_type))},"dsl.axis" => {if annotation.len() != 2 {@@ -326,7 +326,7 @@ fn parse_argument_type(if let ["const", "constant", c_type_scalar, "&"] = c_type.split_whitespace().collect::<Vec<_>>().as_slice() {return Ok(MetalArgumentType::Constant((- MetalArgument::scalar_type_to_rust(c_type_scalar)?.into(),+ MetalArgument::scalar_type_to_rust(c_type_scalar)?,MetalConstantType::Scalar,)));}@@ -341,7 +341,7 @@ fn parse_argument_type(};return Ok(MetalArgumentType::Constant((- MetalArgument::scalar_type_to_rust(c_type_scalar)?.into(),+ MetalArgument::scalar_type_to_rust(c_type_scalar)?,MetalConstantType::Array(size),)));}@@ -573,7 +573,8 @@ impl MetalKernelInfo {}).collect::<anyhow::Result<_>>()?;- if variants.is_empty() != !is_template {+ let has_variants = !variants.is_empty();+ if has_variants != is_template {bail!("mismatch between AST nodes and variants annotation");}@@ -587,7 +588,7 @@ impl MetalKernelInfo {Some(template_parameters.into_iter()- .zip(variants.into_iter())+ .zip(variants).map(|((name, ty), (v_name, variants))| {assert_eq!(name, v_name);diff --git a/crates/backend-uzu/build/metal/bindgen/mod.rs b/crates/backend-uzu/build/metal/bindgen/mod.rsindex d1a9c42ad..7345cd6be 100644--- a/crates/backend-uzu/build/metal/bindgen/mod.rs+++ b/crates/backend-uzu/build/metal/bindgen/mod.rs@@ -88,6 +88,7 @@ pub fn bindgen(#(#variant_struct_fields,)*}+ #[allow(clippy::style, clippy::complexity, clippy::perf)]impl #trait_implementation_for #struct_name {#associate_backenddiff --git a/crates/backend-uzu/build/metal/bindgen/specialize.rs b/crates/backend-uzu/build/metal/bindgen/specialize.rsindex 4f8715d3c..631ba85b2 100644--- a/crates/backend-uzu/build/metal/bindgen/specialize.rs+++ b/crates/backend-uzu/build/metal/bindgen/specialize.rs@@ -42,7 +42,7 @@ pub fn parse(.enumerate().map(|(offset, (argument, rust_type_text))| -> Result<SpecializeArgument> {let name = format_ident!("{}", argument.name.as_ref());- let rust_type: Type = syn::parse_str(&rust_type_text).with_context(|| {+ let rust_type: Type = syn::parse_str(rust_type_text).with_context(|| {format!("specialize type `{}` in kernel `{}` cannot be parsed", rust_type_text, kernel_name)})?;let function_constant_index = base_function_constant_index.unwrap_or(0) + offset;diff --git a/crates/backend-uzu/build/metal/compiler.rs b/crates/backend-uzu/build/metal/compiler.rsindex 2852b596c..33216a235 100644--- a/crates/backend-uzu/build/metal/compiler.rs+++ b/crates/backend-uzu/build/metal/compiler.rs@@ -121,8 +121,7 @@ impl MetalCompiler {source_path: PathBuf,enum_paths: &EnumPaths,) -> anyhow::Result<ObjectInfo> {- let buildsystem_hash =- caching::build_system_hash().context("cannot get build system cache")?.as_bytes().clone();+ let buildsystem_hash = *caching::build_system_hash().context("cannot get build system cache")?.as_bytes();let source_path_pretty = source_path.file_name().unwrap().to_str().unwrap();debug_log!("compile start: {source_path_pretty}");diff --git a/crates/backend-uzu/build/metal/gpu_types/mod.rs b/crates/backend-uzu/build/metal/gpu_types/mod.rsindex f98c7ebea..5dcda01aa 100644--- a/crates/backend-uzu/build/metal/gpu_types/mod.rs+++ b/crates/backend-uzu/build/metal/gpu_types/mod.rs@@ -48,7 +48,7 @@ async fn gpu_type_gen_file(let new_contents = format!(include_str!("template.ht"), module_name = module_name, generated = generated);// Avoid advancing mtime if the contents are the same- if !tokio::fs::read(&file_path).await.is_ok_and(|old_contents| &old_contents == new_contents.as_bytes()) {+ if !tokio::fs::read(&file_path).await.is_ok_and(|old_contents| old_contents == new_contents.as_bytes()) {tokio::fs::write(&file_path, new_contents).await.context("cannot write output")?;}diff --git a/crates/backend-uzu/build/metal/wrapper.rs b/crates/backend-uzu/build/metal/wrapper.rsindex 61539c519..9b4acc338 100644--- a/crates/backend-uzu/build/metal/wrapper.rs+++ b/crates/backend-uzu/build/metal/wrapper.rs@@ -158,10 +158,10 @@ fn kernel_wrappers(} else {vec![None]} {- if let Some(ref tv) = type_variant {- if !evaluator.satisfied(tv, &kernel.constraints) {- continue;- }+ if let Some(ref tv) = type_variant+ && !evaluator.satisfied(tv, &kernel.constraints)+ {+ continue;}let (wrapper_name, underlying_name) = if let Some(type_variant) = &type_variant {@@ -197,10 +197,10 @@ fn kernel_wrappers(let condition_field = format!("__dsl_buffer_condition_{}_{}", wrapper_name, a.name);match a.condition.as_deref() {Some(condition) => (- format!("{} {} [[buffer({}), function_constant({})]]", &a.c_type, a.name, i, condition_field,),+ format!("{} {} [[buffer({}), function_constant({})]]", a.c_type, a.name, i, condition_field,),Some(format!("constant bool {} = ({});", condition_field, condition)),),- None => (format!("{} {} [[buffer({})]]", &a.c_type, a.name, i), None),+ None => (format!("{} {} [[buffer({})]]", a.c_type, a.name, i), None),}}).unzip();diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/build.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/build.rsindex 514497050..ceacd730b 100644--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/build.rs+++ b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/build.rs@@ -34,7 +34,7 @@ pub(super) fn read_conv1d_layer<B: Backend>(if groups == 0 || cin == 0 || cout == 0 || kernel_size == 0 {return Err(AudioError::InvalidTokenCardinality);}- if cin % groups != 0 || cout % groups != 0 {+ 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}")));@@ -64,7 +64,7 @@ pub(super) fn read_conv_transpose1d_layer<B: Backend>(if stride == 0 || groups == 0 || cin == 0 || cout == 0 || kernel_size == 0 {return Err(AudioError::InvalidTokenCardinality);}- if cin % groups != 0 || cout % groups != 0 {+ 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()?;diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/enqueue.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/enqueue.rsindex 46838e677..68e52515f 100644--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/enqueue.rs+++ b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/enqueue.rs@@ -62,7 +62,7 @@ fn validate_grouped_conv_params<B: Backend>(actual_lengths: lengths.len(),});}- if layer.groups == 0 || layer.cin % layer.groups != 0 || layer.cout % layer.groups != 0 {+ 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];@@ -227,7 +227,7 @@ pub(super) fn causal_conv_transpose1d_causal_pad_enqueue<B: Backend>(actual_tokens: input.size(),});}- if layer.groups == 0 || layer.cin % layer.groups != 0 || layer.cout % layer.groups != 0 {+ 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];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.rsindex a15cffa08..763848eac 100644--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/post_module.rs+++ b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/post_module.rs@@ -145,10 +145,10 @@ impl StructuredAudioCodecGraph {) -> AudioResult<Rc<StructuredAudioPostModuleRuntime<B>>> {{let cached = resources.post_module_runtime.borrow();- if let Some(runtime) = cached.as_ref() {- if runtime.max_sequence_length >= required_sequence_length.max(1) {- return Ok(runtime.clone());- }+ 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)?);diff --git a/crates/backend-uzu/src/backends/common/allocator/allocator.rs b/crates/backend-uzu/src/backends/common/allocator/allocator.rsindex 614aed0f9..75836fc0a 100644--- a/crates/backend-uzu/src/backends/common/allocator/allocator.rs+++ b/crates/backend-uzu/src/backends/common/allocator/allocator.rs@@ -190,9 +190,7 @@ impl<B: Backend> Allocator<B> {let allocator_buffer_index = allocator_buffers.iter()- .position(|allocator_buffer| {- (allocator_buffer.buffer.as_ref().get_ref() as *const B::DenseBuffer) == allocation.buffer- })+ .position(|allocator_buffer| std::ptr::eq(allocator_buffer.buffer.as_ref().get_ref(), allocation.buffer)).unwrap(); // Can never failallocator_buffers[allocator_buffer_index]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.rsindex 654236249..93b9502c9 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@@ -1,7 +1,7 @@use num_traits::Float;const GELU_K0: f32 = 0.044715;-const GELU_K1: f32 = 0.7978845608; // sqrt(2/pi)+const GELU_K1: f32 = 0.7978846; // sqrt(2/pi)#[repr(C)]#[derive(Debug, Copy, Clone, PartialEq)]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.rsindex 0b3112ab1..5e784d23e 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/attention/qk_unpack.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/attention/qk_unpack.rs@@ -14,7 +14,7 @@ pub fn qk_unpack<T: ArrayElement>(num_groups: u32,suffix_length: u32,) {- if num_groups == 0 || num_heads % num_groups != 0 {+ if num_groups == 0 || !num_heads.is_multiple_of(num_groups) {return;}diff --git a/crates/backend-uzu/src/backends/cpu/kernel/delta_net/update.rs b/crates/backend-uzu/src/backends/cpu/kernel/delta_net/update.rsindex 54dc5ad9a..9ea29360f 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/delta_net/update.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/delta_net/update.rs@@ -31,7 +31,7 @@ pub fn delta_net_update<T: ArrayElement + Float, const HEAD_K_DIM: u32>(let num_v_heads = num_v_heads as usize;let num_k_heads = num_k_heads as usize;- debug_assert!(num_v_heads % num_k_heads == 0, "num_v_heads must be a multiple of num_k_heads");+ debug_assert!(num_v_heads.is_multiple_of(num_k_heads), "num_v_heads must be a multiple of num_k_heads");let head_k_dim = HEAD_K_DIM as usize;let head_v_dim = head_v_dim as usize;let key_dim = key_dim as usize;diff --git a/crates/backend-uzu/src/backends/cpu/kernel/embedding/quant_embedding.rs b/crates/backend-uzu/src/backends/cpu/kernel/embedding/quant_embedding.rsindex b39e9d3c6..7864642fd 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/embedding/quant_embedding.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/embedding/quant_embedding.rs@@ -47,7 +47,7 @@ pub fn quantized_embedding_lookup<T: ArrayElement + Float>(let packing_divisor = quantization_mode.packing_divisor() as u32;let weights_stride = model_dim / packing_divisor;- let num_groups = (model_dim + group_size - 1) / group_size;+ let num_groups = model_dim.div_ceil(group_size);let zero_points_stride = match quantization_mode {QuantizationMode::U4 => num_groups.div_ceil(2),QuantizationMode::I8 | QuantizationMode::U8 => num_groups,diff --git a/crates/backend-uzu/src/backends/cpu/kernel/moe/experts_two_pass_decode.rs b/crates/backend-uzu/src/backends/cpu/kernel/moe/experts_two_pass_decode.rsindex 5fda74d60..d68ea501b 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/moe/experts_two_pass_decode.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/moe/experts_two_pass_decode.rs@@ -32,6 +32,7 @@ pub fn moe_experts_decode_pass_a<T: ArrayElement + Float>(#[kernel(MoeExpertsDecodeDownFused2D)]#[variants(T, f32, f16, bf16)]#[variants(AccumT, f32)]+#[allow(clippy::extra_unused_type_parameters)]pub fn moe_experts_decode_down_fused2_d<T: ArrayElement + Float, AccumT: ArrayElement + Float>(hidden: *const f32,row_expert_map: *const u32,diff --git a/crates/backend-uzu/src/backends/cpu/kernel/moe/finalize.rs b/crates/backend-uzu/src/backends/cpu/kernel/moe/finalize.rsindex a997273be..ecaca2cfe 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/moe/finalize.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/moe/finalize.rs@@ -37,7 +37,7 @@ pub fn moe_finalize<T: ArrayElement + Float>(if !val.is_finite() {val = 0.0;}- acc = prob * val + acc;+ acc += prob * val;}}if !acc.is_finite() {diff --git a/crates/backend-uzu/src/backends/cpu/kernel/rope/rope.rs b/crates/backend-uzu/src/backends/cpu/kernel/rope/rope.rsindex 904bff673..00afc9a55 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/rope/rope.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/rope/rope.rs@@ -49,7 +49,7 @@ pub fn rope<ElementT: ArrayElement + Float, RopeT: ArrayElement + Float>(if head_dim & 1 != 0 || rope_dim & 1 != 0 || rope_dim > head_dim {return;}- if !query_only && (num_groups == 0 || num_heads % num_groups as u32 != 0) {+ if !query_only && (num_groups == 0 || !num_heads.is_multiple_of(num_groups as u32)) {return;}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.rsindex f98abf2af..f44f7f753 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@@ -79,7 +79,7 @@ pub fn ssd_prefill_sequential<T: ArrayElement + Float>(let channels = channels as usize;let head_dim = head_dim as usize;- let safe_group = group_size.max(1) as usize;+ let safe_group = group_size.max(1);unsafe {for h in 0..channels {diff --git a/crates/backend-uzu/src/backends/cpu/kernel/tensor_copy/tensor_copy.rs b/crates/backend-uzu/src/backends/cpu/kernel/tensor_copy/tensor_copy.rsindex 974c5902d..4460b6877 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/tensor_copy/tensor_copy.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/tensor_copy/tensor_copy.rs@@ -13,7 +13,7 @@ pub fn tensor_copy<T: ArrayElement + Float>() {unsafe {for i in 0usize..(length as usize) {- *dst_buffer.offset(i as isize) = *src_buffer.offset(i as isize);+ *dst_buffer.add(i) = *src_buffer.add(i);}}}diff --git a/crates/backend-uzu/src/backends/metal/command_buffer.rs b/crates/backend-uzu/src/backends/metal/command_buffer.rsindex 3a29cc4df..ab2cd58bf 100644--- a/crates/backend-uzu/src/backends/metal/command_buffer.rs+++ b/crates/backend-uzu/src/backends/metal/command_buffer.rs@@ -153,7 +153,7 @@ impl CommandBufferEncoding for MetalCommandBufferEncoding {) {let range = dst.range();assert!(range.end > range.start);- assert!(range.start % 4 == 0 && range.end % 4 == 0);+ 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);}diff --git a/crates/backend-uzu/src/backends/metal/context.rs b/crates/backend-uzu/src/backends/metal/context.rsindex 61b28844d..4afabff72 100644--- a/crates/backend-uzu/src/backends/metal/context.rs+++ b/crates/backend-uzu/src/backends/metal/context.rs@@ -215,7 +215,7 @@ impl Context for MetalContext {) -> Result<<Self::Backend as Backend>::SparseBuffer, <Self::Backend as Backend>::Error> {let sparse_page_size = self.sparse_heap_pool.borrow().page_size();let context = self.weak_self.upgrade().ok_or(MetalError::CannotCreateBuffer)?;- Ok(MetalSparseBuffer::new(context, capacity, sparse_page_size)?)+ MetalSparseBuffer::new(context, capacity, sparse_page_size)}fn peak_memory_usage(&self) -> Option<usize> {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.rsindex 0a19a29a2..73737be31 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@@ -126,7 +126,7 @@ impl GemmKernel {arguments.b_transpose&& arguments.b_leading_dimension.is_none_or(|ld| ld == arguments.k)&& arguments.b_offset == 0- && arguments.k % select_mxu_tiling(arguments.m, arguments.n).block_k() == 0+ && arguments.k.is_multiple_of(select_mxu_tiling(arguments.m, arguments.n).block_k())},};let path = if encoder.context().device.supports_mxu()@@ -441,7 +441,7 @@ fn select_quant_tiling(GemmTiling::Tile8x32x32_Simdgroups1x1} else if m >= 64 && n <= 2048 {GemmTiling::Tile64x32x32_Simdgroups2x2- } else if m >= 64 && n >= 6144 && n % 64 == 0 {+ } else if m >= 64 && n >= 6144 && n.is_multiple_of(64) {GemmTiling::Tile64x64x32_Simdgroups2x2} else {GemmTiling::Tile32x32x32_Simdgroups2x2diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/specialization.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/specialization.rsindex 78cafb8cc..82869aa87 100644--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/specialization.rs+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/specialization.rs@@ -31,25 +31,25 @@ impl GemmSpecialization {use_mxu: self.use_mxu,});}- if self.use_mxu && self.b_prologue != GemmBPrologueKind::FullPrecision {- if let Some(group_size) = self.group_size {- if !self.tiling.fits_quant_group_size(group_size) {- return Err(GemmSpecializationError::MxuQuantTileTooLarge {- tiling: self.tiling,- group_size,- });- }- }+ if self.use_mxu+ && self.b_prologue != GemmBPrologueKind::FullPrecision+ && let Some(group_size) = self.group_size+ && !self.tiling.fits_quant_group_size(group_size)+ {+ return Err(GemmSpecializationError::MxuQuantTileTooLarge {+ tiling: self.tiling,+ group_size,+ });}- if !self.use_mxu {- if let Some(group_size) = self.group_size {- let simdgroup_block_k = self.tiling.simdgroup_block_k();- if simdgroup_block_k > group_size {- return Err(GemmSpecializationError::SimdgroupKExceedsGroupSize {- simdgroup_k: simdgroup_block_k,- group_size,- });- }+ if !self.use_mxu+ && let Some(group_size) = self.group_size+ {+ let simdgroup_block_k = self.tiling.simdgroup_block_k();+ if simdgroup_block_k > group_size {+ return Err(GemmSpecializationError::SimdgroupKExceedsGroupSize {+ simdgroup_k: simdgroup_block_k,+ group_size,+ });}}if self.b_prologue != GemmBPrologueKind::FullPrecision && !self.transpose_b {@@ -165,7 +165,7 @@ impl GemmSpecialization {}}for &tiling in mxu_tiling_set(weights_data_type) {- if group_size % 32 != 0 {+ if !group_size.is_multiple_of(32) {continue;}if !tiling.fits_quant_group_size(group_size) {diff --git a/crates/backend-uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_set_value.rs b/crates/backend-uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_set_value.rsindex 92266224c..8794f48d2 100644--- a/crates/backend-uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_set_value.rs+++ b/crates/backend-uzu/src/backends/metal/metal_extensions/compute_command_encoder_extensions_set_value.rs@@ -36,6 +36,6 @@ impl ComputeEncoderSetValue for ProtocolObject<dyn MTLComputeCommandEncoder> {index: usize,) {let ptr = NonNull::new(slice.as_ptr() as *mut c_void).expect("slice pointer should never be null");- self.set_bytes(ptr, size_of::<T>() * slice.len(), index);+ self.set_bytes(ptr, size_of_val(slice), index);}}diff --git a/crates/backend-uzu/src/backends/metal/sparse/sparse_buffer.rs b/crates/backend-uzu/src/backends/metal/sparse/sparse_buffer.rsindex f3a3c3dbe..28f31542a 100644--- a/crates/backend-uzu/src/backends/metal/sparse/sparse_buffer.rs+++ b/crates/backend-uzu/src/backends/metal/sparse/sparse_buffer.rs@@ -90,7 +90,7 @@ impl SparseBuffer for MetalSparseBuffer {context: &<Self::Backend as Backend>::Context,pages: &Range<usize>,) -> Result<(), <Self::Backend as Backend>::Error> {- if pages.len() == 0 {+ if pages.is_empty() {return Ok(());}@@ -102,14 +102,9 @@ impl SparseBuffer for MetalSparseBuffer {for gap in gaps.iter() {let mut pool = context.sparse_heap_pool_mut();- let result = pool.create_map_operations(context, &self.buffer, gap);- match result {- Ok(batches) => {- pool.apply_map_operations(&batches);- all_batches.extend(batches);- },- Err(err) => return Err(err),- };+ let operations = pool.create_map_operations(context, &self.buffer, gap)?;+ pool.apply_map_operations(&operations);+ all_batches.extend(operations);}// execute operations@@ -126,7 +121,7 @@ impl SparseBuffer for MetalSparseBuffer {context: &<Self::Backend as Backend>::Context,pages: &Range<usize>,) -> Result<(), <Self::Backend as Backend>::Error> {- if pages.len() == 0 {+ if pages.is_empty() {return Ok(());}diff --git a/crates/backend-uzu/src/classifier/classifier.rs b/crates/backend-uzu/src/classifier/classifier.rsindex 29433a82e..4193a642c 100644--- a/crates/backend-uzu/src/classifier/classifier.rs+++ b/crates/backend-uzu/src/classifier/classifier.rs@@ -179,7 +179,7 @@ impl<B: Backend> Classifier<B> {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.as_deref_mut() {+ if let Some(trace) = trace {encoder.encode_copy(&logits, .., trace.logits.allocation_mut(), ..);}@@ -232,7 +232,7 @@ impl<B: Backend> Classifier<B> {let prob = 1.0 / (1.0 + (-logit).exp());let label = if let Some(labels) = output_labels {- labels.get(idx).map(|s| s.clone()).unwrap_or_else(|| format!("class_{}", idx))+ labels.get(idx).cloned().unwrap_or_else(|| format!("class_{}", idx))} else {format!("class_{}", idx)};diff --git a/crates/backend-uzu/src/encodable_block/attention/gemm.rs b/crates/backend-uzu/src/encodable_block/attention/gemm.rsindex b1a8b7e3a..8fae372ad 100644--- a/crates/backend-uzu/src/encodable_block/attention/gemm.rs+++ b/crates/backend-uzu/src/encodable_block/attention/gemm.rs@@ -66,8 +66,8 @@ impl<B: Backend> AttentionGemmBlock<B> {16};let head_dim = args.head_dim;- let align_q = (args.suffix_length % BQ) == 0;- let align_k = (args.sequence_length % bk) == 0;+ 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();@@ -113,7 +113,7 @@ impl<B: Backend> AttentionGemmBlock<B> {let o_head_stride = head_dim as u64;let o_seq_stride = (args.num_heads * head_dim) as u64;- let nk = (args.sequence_length + bk - 1) / bk;+ let nk = args.sequence_length.div_ceil(bk);let nq_aligned = args.suffix_length / BQ;let nk_aligned = args.sequence_length / bk;diff --git a/crates/backend-uzu/src/encodable_block/attention/mod.rs b/crates/backend-uzu/src/encodable_block/attention/mod.rsindex 113535476..221c3a614 100644--- a/crates/backend-uzu/src/encodable_block/attention/mod.rs+++ b/crates/backend-uzu/src/encodable_block/attention/mod.rs@@ -90,7 +90,6 @@ pub enum AttentionError<B: Backend> {}impl<B: Backend> Attention<B> {- #[allow(clippy::too_many_arguments)]pub fn new(context: &B::Context,model_dim: usize,@@ -323,7 +322,6 @@ impl<B: Backend> Attention<B> {KernelVariant::SinglePass}- #[allow(clippy::too_many_arguments)]pub fn encode(&self,token_positions: &Allocation<B>,@@ -589,7 +587,6 @@ impl<B: Backend> Attention<B> {Ok(attention_output)}- #[allow(clippy::too_many_arguments)]fn encode_attention_variant<KVBuf: AsBufferRangeRef<Buffer: Buffer<Backend = B>>>(&self,variant: KernelVariant,@@ -734,7 +731,6 @@ impl<B: Backend> Attention<B> {Ok(attention_output)}- #[allow(clippy::too_many_arguments)]fn encode_fallback<Keys: AsBufferRangeRef<Buffer: Buffer<Backend = B>>,Values: AsBufferRangeRef<Buffer: Buffer<Backend = B>>,diff --git a/crates/backend-uzu/src/encodable_block/classifier_layer.rs b/crates/backend-uzu/src/encodable_block/classifier_layer.rsindex 238bacebd..f183ae3bc 100644--- a/crates/backend-uzu/src/encodable_block/classifier_layer.rs+++ b/crates/backend-uzu/src/encodable_block/classifier_layer.rs@@ -239,7 +239,7 @@ impl<B: Backend> ClassifierLayer<B> {self.mlp_residual_add.encode(shortcut, &mut main, layer_len as u32, encoder);#[cfg(feature = "tracing")]- if let Some(layer_traces) = layer_traces.as_deref_mut() {+ if let Some(layer_traces) = layer_traces {encoder.encode_copy(&main, .., layer_traces.outputs.allocation_mut(), ..);}diff --git a/crates/backend-uzu/src/encodable_block/decoder.rs b/crates/backend-uzu/src/encodable_block/decoder.rsindex e82f45ac1..2ff72a269 100644--- a/crates/backend-uzu/src/encodable_block/decoder.rs+++ b/crates/backend-uzu/src/encodable_block/decoder.rs@@ -363,7 +363,7 @@ impl<B: Backend> Decoder<B> {let logits = self.embed.encode_readout(sampling_length, &output_norm, encoder)?;#[cfg(feature = "tracing")]- if let Some(trace) = trace.as_deref_mut() {+ if let Some(trace) = trace {encoder.encode_copy(&logits, .., trace.logits.allocation_mut(), ..);}Ok(logits)diff --git a/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs b/crates/backend-uzu/src/encodable_block/delta_net_mixer.rsindex 9e02c2973..89e60f0c2 100644--- a/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs+++ b/crates/backend-uzu/src/encodable_block/delta_net_mixer.rs@@ -285,7 +285,7 @@ impl<B: Backend> DeltaNetMixer<B> {suffix_length: usize,encoder: &mut Encoder<B>,) -> Result<Allocation<B>, B::Error> {- let num_dv_groups = ((self.value_head_dim + 7) / 8) as u32;+ let num_dv_groups = self.value_head_dim.div_ceil(8) 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 =diff --git a/crates/backend-uzu/src/encodable_block/layer/executables.rs b/crates/backend-uzu/src/encodable_block/layer/executables.rsindex b1a4e0d37..07bc6461e 100644--- a/crates/backend-uzu/src/encodable_block/layer/executables.rs+++ b/crates/backend-uzu/src/encodable_block/layer/executables.rs@@ -72,7 +72,6 @@ pub struct LayerExecutables<B: Backend> {}impl<B: Backend> LayerExecutables<B> {- #[allow(clippy::too_many_arguments)]pub fn new(context: &B::Context,transformer_config: &TransformerConfig,@@ -419,7 +418,7 @@ impl<B: Backend> LayerExecutables<B> {}#[cfg(feature = "tracing")]- if let Some(layer_traces) = layer_traces.as_deref_mut() {+ if let Some(layer_traces) = layer_traces {let size = (batch_dim * self.model_dim) as u32;self.tensor_add.encode(Some(&hidden),diff --git a/crates/backend-uzu/src/encodable_block/mlp/moe/mod.rs b/crates/backend-uzu/src/encodable_block/mlp/moe/mod.rsindex 4f8b3f1e8..96300007d 100644--- a/crates/backend-uzu/src/encodable_block/mlp/moe/mod.rs+++ b/crates/backend-uzu/src/encodable_block/mlp/moe/mod.rs@@ -88,7 +88,7 @@ impl<B: Backend> MoeBlock<B> {data_type: DataType,parameter_tree: &ParameterTree<B>,) -> Result<Self, MoeBlockError<B>> {- if model_dim % 4 != 0 {+ if !model_dim.is_multiple_of(4) {return Err(MoeBlockError::InvalidModelDim);}if moe_config.num_active_routed_experts == 0 || moe_config.num_active_routed_experts > 128 {diff --git a/crates/backend-uzu/src/forward_pass/cache_layers.rs b/crates/backend-uzu/src/forward_pass/cache_layers.rsindex ace51b425..044f12a03 100644--- a/crates/backend-uzu/src/forward_pass/cache_layers.rs+++ b/crates/backend-uzu/src/forward_pass/cache_layers.rs@@ -422,11 +422,9 @@ impl<B: Backend> CacheLayers<B> {for layer in self.entries.iter() {match layer {CacheLayer::Transformer(kv) => {- let mut encoder =+ let encoder =encoder.get_or_insert_with(|| Encoder::new(context).expect("Failed to create Encoder"));- let Some(slice) = kv.slice(context, &mut encoder, range.clone()) else {- return None;- };+ let slice = kv.slice(context, encoder, range.clone())?;layers.push(CacheLayerSlice::Transformer(slice));},CacheLayer::StateSpace(_) => layers.push(CacheLayerSlice::StateSpace),@@ -454,9 +452,9 @@ impl<B: Backend> CacheLayers<B> {for (layer, snapshot) in self.entries.iter_mut().zip(slice.layers.iter()) {match (layer, snapshot) {(CacheLayer::Transformer(kv), CacheLayerSlice::Transformer(s)) => {- let mut encoder =+ let encoder =encoder.get_or_insert_with(|| Encoder::new(context).expect("Failed to create Encoder"));- kv.apply_slice(context, &mut encoder, &s, range.clone());+ kv.apply_slice(context, encoder, s, range.clone());},(CacheLayer::StateSpace(_), CacheLayerSlice::StateSpace) => {},(CacheLayer::ShortConv(_), CacheLayerSlice::ShortConv) => {},diff --git a/crates/backend-uzu/src/forward_pass/model_shape.rs b/crates/backend-uzu/src/forward_pass/model_shape.rsindex 39ed89f8f..9d43be9ab 100644--- a/crates/backend-uzu/src/forward_pass/model_shape.rs+++ b/crates/backend-uzu/src/forward_pass/model_shape.rs@@ -82,7 +82,7 @@ impl ModelShape {&self,suffix_length: usize,) -> [usize; 2] {- let bitmask_size = (self.vocabulary_size + 31) / 32;+ let bitmask_size = self.vocabulary_size.div_ceil(32);[suffix_length, bitmask_size]}diff --git a/crates/backend-uzu/src/language_model/grammar/mod.rs b/crates/backend-uzu/src/language_model/grammar/mod.rsindex 4082cc2d2..bab57a718 100644--- a/crates/backend-uzu/src/language_model/grammar/mod.rs+++ b/crates/backend-uzu/src/language_model/grammar/mod.rs@@ -30,7 +30,7 @@ pub fn create_compiled_grammar({use xgrammar::TokenizerInfo;let tokenizer_info =- TokenizerInfo::from_huggingface(&tokenizer, None, stop_token_ids).map_err(Error::GrammarError)?;+ TokenizerInfo::from_huggingface(tokenizer, None, stop_token_ids).map_err(Error::GrammarError)?;use xgram::CompiledXGrammar;let grammar = CompiledXGrammar::from_config(config, None, &tokenizer_info)?;diff --git a/crates/backend-uzu/src/language_model/grammar/xgram.rs b/crates/backend-uzu/src/language_model/grammar/xgram.rsindex da4d667e3..e9731354b 100644--- a/crates/backend-uzu/src/language_model/grammar/xgram.rs+++ b/crates/backend-uzu/src/language_model/grammar/xgram.rs@@ -79,7 +79,7 @@ impl CompiledXGrammar {trigger_token_id: Option<u64>,tokenizer_info: &TokenizerInfo,) -> Result<Self, Error> {- let vocab_size = tokenizer_info.vocab_size() as usize;+ let vocab_size = tokenizer_info.vocab_size();let grammar = match config {GrammarConfig::JsonSchema {diff --git a/crates/backend-uzu/src/language_model/language_model_generator.rs b/crates/backend-uzu/src/language_model/language_model_generator.rsindex a54765cd1..ebbafaa8b 100644--- a/crates/backend-uzu/src/language_model/language_model_generator.rs+++ b/crates/backend-uzu/src/language_model/language_model_generator.rs@@ -200,27 +200,23 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {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]]>> =- if let Some(trie_start) = step_token_subtrie_ranges.iter().position(|e| e.is_some()) {- Some(- 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(),- )- } else {- None- };+ 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]>>();@@ -243,7 +239,7 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {let step_token_bitmask: Option<Box<[u32]>> = if has_grammar && sampling_length > 0 {Some(step_token_bitmasks- .map(|mask| match mask {+ .flat_map(|mask| match mask {Some(mask) => Either::Left(mask.iter().copied()@@ -252,7 +248,6 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {),None => Either::Right(repeat_n(u32::MAX, single_token_bitmask_size)),})- .flatten().collect::<Box<[u32]>>(),)} else {@@ -328,8 +323,7 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {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.as_deref_mut());+ 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]>>(),@@ -379,7 +373,7 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {flat_trie.token_masks().chain(repeat_n(None, suffix_length - active_row_count))- .map(|mask| match mask {+ .flat_map(|mask| match mask {Some(mask) => Either::Left(mask.iter().copied()@@ -388,7 +382,6 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {),None => Either::Right(repeat_n(u32::MAX, single_token_bitmask_size)),})- .flatten().collect::<Box<[u32]>>()});@@ -419,8 +412,7 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {let sampled_tokens =self.read_sampling_output(sampling_output.as_ref().expect("sampling output must exist"), sampling_length)?;- let (accepted_tokens, accepted_token_indices) =- flat_trie.accept(&sampled_tokens, compiled_grammar.as_deref_mut());+ 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);diff --git a/crates/backend-uzu/src/lib.rs b/crates/backend-uzu/src/lib.rsindex 7e032f3b7..2b2ff699a 100644--- a/crates/backend-uzu/src/lib.rs+++ b/crates/backend-uzu/src/lib.rs@@ -2,6 +2,11 @@#[cfg(test)]extern crate self as backend_uzu;+#[cfg(test)]+#[macro_use]+#[path = "../tests/common/mod.rs"]+mod common;+pub mod array;mod audio;mod classifier;diff --git a/crates/backend-uzu/src/parameters/safetensors_metadata.rs b/crates/backend-uzu/src/parameters/safetensors_metadata.rsindex b95c4699e..654bea6ce 100644--- a/crates/backend-uzu/src/parameters/safetensors_metadata.rs+++ b/crates/backend-uzu/src/parameters/safetensors_metadata.rs@@ -119,7 +119,7 @@ pub fn read_metadata(file: &File) -> Result<(usize, HashMetadata), HeaderLoading}let stop = metadata_size.checked_add(8).ok_or(HeaderLoadingError::InvalidHeaderLength)?;- let mut json_buffer: Box<[u8]> = core::iter::repeat(0).take(stop - size_of::<u64>()).collect();+ let mut json_buffer: Box<[u8]> = core::iter::repeat_n(0, stop - size_of::<u64>()).collect();file_read_exact_at(file, &mut json_buffer, 8).map_err(HeaderLoadingError::UnableToReadHeaderJson)?;let string = core::str::from_utf8(&json_buffer)?;let metadata: HashMetadata = serde_json::from_str(string)?;diff --git a/crates/backend-uzu/src/session/chat_session.rs b/crates/backend-uzu/src/session/chat_session.rsindex 952c93328..965ae91bf 100644--- a/crates/backend-uzu/src/session/chat_session.rs+++ b/crates/backend-uzu/src/session/chat_session.rs@@ -231,7 +231,7 @@ impl ChatSession {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.iter().copied().collect();+ 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);@@ -595,8 +595,7 @@ impl ChatSession {}};- let generate_stats: Option<StepStats>;- if generate_results.len() != 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;@@ -611,7 +610,7 @@ impl ChatSession {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();- generate_stats = Some(StepStats {+ Some(StepStats {duration,suffix_length: generate_suffix_length as u64,tokens_count: tokens_count as u64,@@ -627,10 +626,10 @@ impl ChatSession {}),speculator_proposed: speculator_proposed as u64,speculator_accepted: speculator_accepted as u64,- });+ })} else {- generate_stats = None;- }+ None+ };let total_stats = TotalStats {duration: total_duration,@@ -638,13 +637,11 @@ impl ChatSession {tokens_count_output: tokens_count_output as u64,};- let stats = Stats {+ Stats {prefill_stats,generate_stats,total_stats,- };-- stats+ }}pub fn peak_memory_usage(&self) -> Option<usize> {diff --git a/crates/backend-uzu/src/session/config/decoding_config.rs b/crates/backend-uzu/src/session/config/decoding_config.rsindex 27fbd1d57..c9a7976a1 100644--- a/crates/backend-uzu/src/session/config/decoding_config.rs+++ b/crates/backend-uzu/src/session/config/decoding_config.rs@@ -3,7 +3,7 @@ use crate::session::{parameter::{AsyncBatchSize, ContextLength, ContextMode, PrefillStepSize, SamplingSeed},};-#[derive(Clone)]+#[derive(Clone, Default)]pub struct DecodingConfig {pub context_mode: ContextMode,pub context_length: ContextLength,@@ -37,19 +37,6 @@ impl DecodingConfig {}}-impl Default for DecodingConfig {- fn default() -> Self {- Self {- context_mode: ContextMode::default(),- context_length: ContextLength::default(),- prefill_step_size: PrefillStepSize::default(),- speculator_config: SpeculatorConfig::default(),- sampling_seed: SamplingSeed::default(),- async_batch_size: AsyncBatchSize::default(),- }- }-}-impl DecodingConfig {pub fn with_context_mode(&self,diff --git a/crates/backend-uzu/src/session/helpers/input_processor.rs b/crates/backend-uzu/src/session/helpers/input_processor.rsindex 04e392c7b..7efddadb0 100644--- a/crates/backend-uzu/src/session/helpers/input_processor.rs+++ b/crates/backend-uzu/src/session/helpers/input_processor.rs@@ -84,10 +84,10 @@ impl InputProcessor for InputProcessorDefault {return Err(Error::UnexpectedReasoningContent);}}- if let Some(default_system_prompt) = self.token_codec_config.default_system_prompt.clone() {- if messages.first().is_none_or(|message| message.role != Role::System) {- messages.insert(0, Message::system(default_system_prompt));- }+ 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 =diff --git a/crates/backend-uzu/src/session/parameter/async_batch_size.rs b/crates/backend-uzu/src/session/parameter/async_batch_size.rsindex 5e728fc2c..5fce6fa3c 100644--- a/crates/backend-uzu/src/session/parameter/async_batch_size.rs+++ b/crates/backend-uzu/src/session/parameter/async_batch_size.rs@@ -2,18 +2,13 @@ use std::path::Path;use crate::backends::common::{Backend, Context};-#[derive(Debug, Clone, Copy)]+#[derive(Debug, Clone, Copy, Default)]pub enum AsyncBatchSize {+ #[default]Default,Custom(usize),}-impl Default for AsyncBatchSize {- fn default() -> Self {- AsyncBatchSize::Default- }-}-impl AsyncBatchSize {pub fn resolve<B: Backend>(&self,diff --git a/crates/backend-uzu/src/session/parameter/context_length.rs b/crates/backend-uzu/src/session/parameter/context_length.rsindex 1de733c17..51e1827e2 100644--- a/crates/backend-uzu/src/session/parameter/context_length.rs+++ b/crates/backend-uzu/src/session/parameter/context_length.rs@@ -1,12 +1,7 @@-#[derive(Debug, Clone, Copy)]+#[derive(Debug, Clone, Copy, Default)]pub enum ContextLength {+ #[default]Default,Maximal,Custom(usize),}--impl Default for ContextLength {- fn default() -> Self {- ContextLength::Default- }-}diff --git a/crates/backend-uzu/src/session/parameter/context_mode.rs b/crates/backend-uzu/src/session/parameter/context_mode.rsindex 38244388d..acd05add8 100644--- a/crates/backend-uzu/src/session/parameter/context_mode.rs+++ b/crates/backend-uzu/src/session/parameter/context_mode.rs@@ -1,16 +1,11 @@use crate::session::types::Input;-#[derive(Clone, Debug)]+#[derive(Clone, Debug, Default)]pub enum ContextMode {+ #[default]None,Static {input: Input,},Dynamic,}--impl Default for ContextMode {- fn default() -> Self {- ContextMode::None- }-}diff --git a/crates/backend-uzu/src/session/parameter/prefill_step_size.rs b/crates/backend-uzu/src/session/parameter/prefill_step_size.rsindex 1d9caffb8..cbe7ad2b1 100644--- a/crates/backend-uzu/src/session/parameter/prefill_step_size.rs+++ b/crates/backend-uzu/src/session/parameter/prefill_step_size.rs@@ -12,19 +12,14 @@ fn env_prefill_step_size_default_override() -> Option<usize> {})}-#[derive(Debug, Clone, Copy)]+#[derive(Debug, Clone, Copy, Default)]pub enum PrefillStepSize {+ #[default]Default,Maximal,Custom(usize),}-impl Default for PrefillStepSize {- fn default() -> Self {- PrefillStepSize::Default- }-}-impl ConfigResolvableValue<LanguageModelConfig, usize> for PrefillStepSize {fn resolve(&self,diff --git a/crates/backend-uzu/src/session/parameter/sampling_policy.rs b/crates/backend-uzu/src/session/parameter/sampling_policy.rsindex 86f76b7a4..23238ce99 100644--- a/crates/backend-uzu/src/session/parameter/sampling_policy.rs+++ b/crates/backend-uzu/src/session/parameter/sampling_policy.rs@@ -18,12 +18,6 @@ pub enum SamplingMethod {},}-impl Default for SamplingMethod {- fn default() -> Self {- SamplingMethod::Greedy- }-}-#[derive(Debug, Clone, PartialEq)]pub enum SamplingPolicy {Default,@@ -32,12 +26,6 @@ pub enum SamplingPolicy {},}-impl Default for SamplingPolicy {- fn default() -> Self {- SamplingPolicy::Default- }-}-impl ConfigResolvableValue<LanguageModelConfig, SamplingMethod> for SamplingPolicy {fn resolve(&self,diff --git a/crates/backend-uzu/src/session/parameter/sampling_seed.rs b/crates/backend-uzu/src/session/parameter/sampling_seed.rsindex 77098926e..171f1d7a1 100644--- a/crates/backend-uzu/src/session/parameter/sampling_seed.rs+++ b/crates/backend-uzu/src/session/parameter/sampling_seed.rs@@ -2,18 +2,13 @@ use rand::prelude::*;use crate::session::parameter::ResolvableValue;-#[derive(Debug, Clone, Copy)]+#[derive(Debug, Clone, Copy, Default)]pub enum SamplingSeed {+ #[default]Default,Custom(u64),}-impl Default for SamplingSeed {- fn default() -> Self {- SamplingSeed::Default- }-}-impl ResolvableValue<u64> for SamplingSeed {fn resolve(&self) -> u64 {match self {diff --git a/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs b/crates/backend-uzu/src/session/tts_session/decoder_runtime.rsindex 806c4b9b8..93666d948 100644--- a/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs+++ b/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs@@ -35,7 +35,7 @@ impl<B: Backend> TokenDecoderLoadedModel<B> {)?;let executables = Decoder::new_with_embedding_subtree(context.as_ref(),- &decoder_config,+ decoder_config,root_loader_view,transformer_subtree,embedding_subtree,diff --git a/crates/backend-uzu/src/session/types/output.rs b/crates/backend-uzu/src/session/types/output.rsindex c2ede36a3..fbdac3ccd 100644--- a/crates/backend-uzu/src/session/types/output.rs+++ b/crates/backend-uzu/src/session/types/output.rs@@ -26,7 +26,7 @@ impl Output {Self {text: self.text.clone(),stats: self.stats.clone(),- finish_reason: finish_reason,+ finish_reason,}}@@ -40,7 +40,7 @@ impl Output {prefill_stats: self.stats.prefill_stats.clone(),generate_stats: self.stats.generate_stats.clone(),total_stats: TotalStats {- duration: duration,+ duration,..self.stats.total_stats.clone()},},diff --git a/crates/backend-uzu/src/trie.rs b/crates/backend-uzu/src/trie.rsindex 8fd52b8cd..afbcd51d3 100644--- a/crates/backend-uzu/src/trie.rs+++ b/crates/backend-uzu/src/trie.rs@@ -101,7 +101,7 @@ impl TrieNode {max_length: usize,) -> Self {assert!(max_length >= 1, "can't have zero sized trie");- assert!(prefix.len() >= 1, "need seed node");+ assert!(!prefix.is_empty(), "need seed node");let prefix_length = prefix.len();let mut speculated_suffix = prefix.to_vec();@@ -153,10 +153,10 @@ impl TrieNode {} else if let Some(next_node_token) = next_node.take() {// Out of speculated tokens for this node, move onto the likeliest next nodespeculated_suffix.push(next_node_token);- if let Some(compiled_grammar) = compiled_grammar.as_deref_mut() {- if compiled_grammar.accept_token(next_node_token).is_err() {- break;- }+ if let Some(compiled_grammar) = compiled_grammar.as_deref_mut()+ && compiled_grammar.accept_token(next_node_token).is_err()+ {+ break;}height += 1;cur_node = cur_node.get_mut(next_node_token).unwrap();@@ -169,7 +169,7 @@ impl TrieNode {};}- if let Some(compiled_grammar) = compiled_grammar.as_deref_mut() {+ if let Some(compiled_grammar) = compiled_grammar {compiled_grammar.rollback(height);}diff --git a/crates/backend-uzu/tests/common/audio/fsq_reference.rs b/crates/backend-uzu/tests/common/audio/fsq_reference.rsindex b756b4bd2..8692e3658 100644--- a/crates/backend-uzu/tests/common/audio/fsq_reference.rs+++ b/crates/backend-uzu/tests/common/audio/fsq_reference.rs@@ -13,9 +13,7 @@ fn round_ties_to_even(value: f32) -> f32 {if fraction < 0.5 {floor- } else if fraction > 0.5 {- floor + 1.0- } else if (floor as i64 & 1) != 0 {+ } else if fraction > 0.5 || (floor as i64 & 1) != 0 {floor + 1.0} else {floordiff --git a/crates/backend-uzu/tests/common/audio/ops_reference.rs b/crates/backend-uzu/tests/common/audio/ops_reference.rsindex aa9f55a7f..724ec7eff 100644--- a/crates/backend-uzu/tests/common/audio/ops_reference.rs+++ b/crates/backend-uzu/tests/common/audio/ops_reference.rs@@ -426,7 +426,7 @@ pub fn causal_conv_transpose1d_causal_pad_reference(spec: CausalConvTranspose1dS}let expanded_time = expanded_time as usize;- if expanded_time % stride != 0 {+ if !expanded_time.is_multiple_of(stride) {continue;}diff --git a/crates/backend-uzu/tests/common/helpers.rs b/crates/backend-uzu/tests/common/helpers.rsindex 51069863b..0a91f81f9 100644--- a/crates/backend-uzu/tests/common/helpers.rs+++ b/crates/backend-uzu/tests/common/helpers.rs@@ -63,7 +63,7 @@ pub fn write_allocation<B: Backend, T: ArrayElement>(}pub fn create_context<B: Backend>() -> Rc<<B as Backend>::Context> {- B::Context::new().expect(format!("Failed to create context for {}", std::any::type_name::<B>()).as_str())+ B::Context::new().unwrap_or_else(|_| panic!("Failed to create context for {}", std::any::type_name::<B>()))}pub fn submit_encoder<B: Backend>(encoder: Encoder<B>) {diff --git a/crates/backend-uzu/tests/integration/parameters/safetensors_metadata_test.rs b/crates/backend-uzu/tests/integration/parameters/safetensors_metadata_test.rsindex 2fa94373f..cfeee4ca6 100644--- a/crates/backend-uzu/tests/integration/parameters/safetensors_metadata_test.rs+++ b/crates/backend-uzu/tests/integration/parameters/safetensors_metadata_test.rs@@ -9,5 +9,5 @@ fn test_metadata_loading() {let path = get_test_weights_path();let file = File::open(&path).expect("weights not found");let (_offset, metadata) = read_safetensors_metadata(&file).expect("read metadata");- assert!(metadata.tensors.len() > 0);+ assert!(!metadata.tensors.is_empty());}diff --git a/crates/backend-uzu/tests/integration/person_schema_metal_bitmask_test.rs b/crates/backend-uzu/tests/integration/person_schema_metal_bitmask_test.rsindex 107f7b245..7120dd725 100644--- a/crates/backend-uzu/tests/integration/person_schema_metal_bitmask_test.rs+++ b/crates/backend-uzu/tests/integration/person_schema_metal_bitmask_test.rs@@ -60,9 +60,9 @@ fn person_schema_metal_bitmask() {};let device_id = device.registry_id() as i32;let batch: usize = 1;- let vocab = tokenizer_info.vocab_size() as usize;+ let vocab = tokenizer_info.vocab_size();// xgrammar uses a dynamic bitset over the vocab, packed into i32 words- let buffer_size = (vocab + 31) / 32; // number of i32s required+ let buffer_size = vocab.div_ceil(32); // number of i32s requiredlet shape = [batch, buffer_size];// xgrammar expects an int32 mask tensor of shape [buffer_size]diff --git a/crates/backend-uzu/tests/integration/session/chat_session/text_session_test.rs b/crates/backend-uzu/tests/integration/session/chat_session/text_session_test.rsindex 94648abe6..bd461e1b2 100644--- a/crates/backend-uzu/tests/integration/session/chat_session/text_session_test.rs+++ b/crates/backend-uzu/tests/integration/session/chat_session/text_session_test.rs@@ -113,15 +113,7 @@ fn test_text_session_stability() {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| {- return true;- }),- )- .unwrap();+ let output = session.run(input, RunConfig::default().tokens_limit(128), Some(|_: Output| true)).unwrap();println!("{:.5} | {:.5} | {:.5} | {:.5}",index,@@ -139,15 +131,7 @@ fn run() {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| {- return true;- }),- )- .unwrap();+ let output = session.run(input, RunConfig::default().tokens_limit(tokens_limit), Some(|_: Output| true)).unwrap();let empty_response = String::from("None");@@ -179,17 +163,9 @@ fn run_scenario(println!("User > {}", user_prompt.clone());let input = Input::Messages(messages.clone());- let output = session- .run(- input,- RunConfig::default(),- Some(|_: Output| {- return true;- }),- )- .unwrap();+ let output = session.run(input, RunConfig::default(), Some(|_: Output| true)).unwrap();messages.push(Message::assistant(- output.text.parsed.response.clone().unwrap_or(String::new()),+ 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/tests/integration/tracer/trace_validator.rs b/crates/backend-uzu/tests/integration/tracer/trace_validator.rsindex d58fed306..b3d55326b 100644--- a/crates/backend-uzu/tests/integration/tracer/trace_validator.rs+++ b/crates/backend-uzu/tests/integration/tracer/trace_validator.rs@@ -780,7 +780,7 @@ impl<B: Backend> TraceValidator<B> {if expected_shape != produced_shape {if expected_shape.len() == produced_shape.len() + 1- && expected_shape.get(0) == Some(&1)+ && expected_shape.first() == Some(&1)&& expected_shape[1..] == produced_shape[..]{produced_data = produced_datadiff --git a/crates/backend-uzu/tests/performance/audio_kernel_perf_test.rs b/crates/backend-uzu/tests/performance/audio_kernel_perf_test.rsindex 0b79e0f26..1b069b96c 100644--- a/crates/backend-uzu/tests/performance/audio_kernel_perf_test.rs+++ b/crates/backend-uzu/tests/performance/audio_kernel_perf_test.rs@@ -368,7 +368,7 @@ fn audio_kernel_perf() {ch as i32,dec_frames as i32,ksize as i32,- dilation as i32,+ dilation,0_i32,batch_size as i32,&mut encoder,@@ -493,7 +493,7 @@ fn audio_kernel_perf() {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 * 1 * ksize], 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);@@ -775,7 +775,7 @@ fn audio_kernel_perf() {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 * 1 * 7], dt);+ 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);@@ -789,7 +789,7 @@ fn audio_kernel_perf() {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 * 1 * 7], dt);+ 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);@@ -838,7 +838,7 @@ fn audio_kernel_perf() {// final snake + conv + tanhlet final_snake_a = context.create_array_zeros(&[DEC_CHANNELS[4]], dt);- let final_conv_w = context.create_array_zeros(&[1 * DEC_CHANNELS[4] * 7], 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 arraysdiff --git a/crates/backend-uzu/tests/performance/encodable_block/moe/moe_experts_perf_test.rs b/crates/backend-uzu/tests/performance/encodable_block/moe/moe_experts_perf_test.rsindex 05c1d2874..4700a271f 100644--- a/crates/backend-uzu/tests/performance/encodable_block/moe/moe_experts_perf_test.rs+++ b/crates/backend-uzu/tests/performance/encodable_block/moe/moe_experts_perf_test.rs@@ -6,15 +6,10 @@ use rand::{RngExt, SeedableRng, rngs::StdRng};use super::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeBlock, MoeExpertsTwoPassPrefillBlock};use crate::{backends::common::{Backend, Encoder},+ common::helpers::{alloc_allocation_with_data, create_context},data_type::DataType,};-#[macro_use]-#[path = "../../../common/mod.rs"]-mod common;--use common::helpers::{alloc_allocation_with_data, create_context};-fn build_offsets(e: usize,sum_k: usize,@@ -75,12 +70,12 @@ fn run_decode_case<B: Backend>(let experts_kernel = MoeExpertsTwoPassDecodeBlock::<B>::new(ctx, DataType::BF16, 2).expect("experts decode kernel");- let x_perm_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &x_perm);- let offsets_buf = alloc_allocation_with_data::<B, u32>(&ctx, &offsets);- let w13_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w13);- let w2_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w2);- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &up_biases);- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &down_biases);+ let x_perm_buf = alloc_allocation_with_data::<B, bf16>(ctx, &x_perm);+ let offsets_buf = alloc_allocation_with_data::<B, u32>(ctx, &offsets);+ let w13_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w13);+ let w2_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w2);+ let up_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &up_biases);+ let down_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &down_biases);for _ in 0..warmup {let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");@@ -196,12 +191,12 @@ fn run_two_pass_prefill_case<B: Backend>(let experts_kernel =MoeExpertsTwoPassPrefillBlock::<B>::new(ctx, DataType::BF16, 2).expect("experts prefill kernel");- let x_perm_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &x_perm);- let offsets_buf = alloc_allocation_with_data::<B, u32>(&ctx, &offsets);- let w13_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w13);- let w2_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w2);- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &up_biases);- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &down_biases);+ let x_perm_buf = alloc_allocation_with_data::<B, bf16>(ctx, &x_perm);+ let offsets_buf = alloc_allocation_with_data::<B, u32>(ctx, &offsets);+ let w13_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w13);+ let w2_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w2);+ let up_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &up_biases);+ let down_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &down_biases);for _ in 0..warmup {let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");diff --git a/crates/backend-uzu/tests/performance/encodable_block/moe/moe_perf_test.rs b/crates/backend-uzu/tests/performance/encodable_block/moe/moe_perf_test.rsindex 369cb4457..2e15ba0c9 100644--- a/crates/backend-uzu/tests/performance/encodable_block/moe/moe_perf_test.rs+++ b/crates/backend-uzu/tests/performance/encodable_block/moe/moe_perf_test.rs@@ -10,18 +10,13 @@ use crate::{MoeScatterBucketsMapKernel,},},+ common::{+ helpers::{alloc_allocation, alloc_allocation_with_data, create_context},+ perf::run_perf_with_warmup,+ },data_type::DataType,};-#[macro_use]-#[path = "../../../common/mod.rs"]-mod common;--use common::{- helpers::{alloc_allocation, alloc_allocation_with_data, create_context},- perf::run_perf_with_warmup,-};-// Test E2E MoE performance with timing breakdown (decode mode, T=1)#[test]#[ignore]@@ -161,8 +156,8 @@ fn test_moe_pipeline_breakdown_decode() {let router_b_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &router_b);let mut topk_ids_buf = alloc_allocation::<B, i32>(&ctx, t * k);let mut topk_probs_buf = alloc_allocation::<B, bf16>(&ctx, t * k);- let num_blocks = ((t + 255) / 256).max(1);- let num_tiles = ((e + 512 - 1) / 512).max(1);+ let num_blocks = t.div_ceil(256).max(1);+ let num_tiles = e.div_ceil(512).max(1);let mut partials_buf = alloc_allocation::<B, i32>(&ctx, num_blocks * num_tiles * e);let mut offsets_buf = alloc_allocation::<B, u32>(&ctx, e + 1);let mut sumk_buf = alloc_allocation::<B, u32>(&ctx, 1);diff --git a/crates/backend-uzu/tests/unit/backends/metal/sparse/sparse_buffer_test.rs b/crates/backend-uzu/tests/unit/backends/metal/sparse/sparse_buffer_test.rsindex 8466d1970..c11581e2a 100644--- a/crates/backend-uzu/tests/unit/backends/metal/sparse/sparse_buffer_test.rs+++ b/crates/backend-uzu/tests/unit/backends/metal/sparse/sparse_buffer_test.rs@@ -1,19 +1,11 @@-#[path = "../../../../common/mod.rs"]-mod common;+use std::ops::Range;-use std::{ops::Range, rc::Rc};--use backend_uzu::{- backends::{- common::{Backend, SparseBuffer},- metal::Metal,- },- prelude::MetalContext,+use backend_uzu::backends::{+ common::{Backend, SparseBuffer},+ metal::Metal,};-fn create_context() -> Rc<MetalContext> {- common::helpers::create_context::<Metal>()-}+use crate::common::helpers::{create_context, sparse_buffer_create};/// Capacity sized to fit `heap_count` worth of heaps.fn buffer_capacity(@@ -35,45 +27,45 @@ fn pages_for_heaps(#[test]fn test_mapping_succeeds() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let capacity = buffer_capacity(ctx.as_ref(), 4);let pages = pages_for_heaps(ctx.as_ref(), 0, 4);- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(&ctx, capacity);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to map sparse buffer");}#[test]fn test_unmapping_succeeds() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let capacity = buffer_capacity(ctx.as_ref(), 4);let pages = pages_for_heaps(ctx.as_ref(), 0, 4);- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(&ctx, capacity);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to map sparse buffer");sparse_buffer.unmap(ctx.as_ref(), &pages).expect("Failed to unmap sparse buffer");}#[test]fn test_partial_unmapping_succeeds() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let capacity = buffer_capacity(ctx.as_ref(), 4);let mapped = pages_for_heaps(ctx.as_ref(), 0, 4);let unmapped = pages_for_heaps(ctx.as_ref(), 1, 2);- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(&ctx, capacity);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);sparse_buffer.map(ctx.as_ref(), &mapped).expect("Failed to map sparse buffer");sparse_buffer.unmap(ctx.as_ref(), &unmapped).expect("Failed to unmap sparse buffer");}#[test]fn test_mapping_uses_minimum_heaps() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let heap_count = 4;let capacity = buffer_capacity(ctx.as_ref(), heap_count);let pages = pages_for_heaps(ctx.as_ref(), 0, heap_count);- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(&ctx, capacity);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to map sparse buffer");let heaps = ctx.sparse_heap_pool();@@ -83,13 +75,13 @@ fn test_mapping_uses_minimum_heaps() {#[test]fn test_remapping_reuses_freed_pages() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let capacity = buffer_capacity(ctx.as_ref(), 6);let initial_pages = pages_for_heaps(ctx.as_ref(), 0, 4);let unmapped_pages = pages_for_heaps(ctx.as_ref(), 1, 1);let extra_pages = pages_for_heaps(ctx.as_ref(), 4, 1);- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(&ctx, capacity);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);sparse_buffer.map(ctx.as_ref(), &initial_pages).expect("Failed to map sparse buffer");let initial_heaps = ctx.sparse_heap_pool().heaps_count();@@ -105,11 +97,11 @@ fn test_remapping_reuses_freed_pages() {#[test]fn test_full_unmap_then_remap_reuses_heaps() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let capacity = buffer_capacity(ctx.as_ref(), 4);let pages = pages_for_heaps(ctx.as_ref(), 0, 4);- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(&ctx, capacity);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to map sparse buffer");let initial_heaps = ctx.sparse_heap_pool().heaps_count();@@ -125,11 +117,11 @@ fn test_full_unmap_then_remap_reuses_heaps() {#[test]fn test_remapping_same_pages_is_noop() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let capacity = buffer_capacity(ctx.as_ref(), 4);let pages = pages_for_heaps(ctx.as_ref(), 0, 4);- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(&ctx, capacity);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to map sparse buffer");let initial_heaps = ctx.sparse_heap_pool().heaps_count();@@ -144,11 +136,11 @@ fn test_remapping_same_pages_is_noop() {#[test]fn test_mapping_multiple_gaps_reserves_pages_between_gaps() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let capacity = buffer_capacity(ctx.as_ref(), 2);- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(&ctx, capacity);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);sparse_buffer.map(ctx.as_ref(), &(1..2)).expect("Failed to map initial page");sparse_buffer.map(ctx.as_ref(), &(0..pages_per_heap + 1)).expect("Failed to map range with multiple gaps");@@ -163,12 +155,12 @@ fn test_mapping_multiple_gaps_reserves_pages_between_gaps() {fn test_drop_releases_pool_heaps() {// Regression: a mapped buffer dropped without an explicit unmap must// still release its heap pages back to the shared pool.- let ctx = create_context();+ let ctx = create_context::<Metal>();let capacity = buffer_capacity(ctx.as_ref(), 2);let pages = pages_for_heaps(ctx.as_ref(), 0, 2);{- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(&ctx, capacity);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to map sparse buffer");assert!(ctx.sparse_heap_pool().heaps_count() > 0);}@@ -184,16 +176,16 @@ fn test_drop_releases_pool_heaps() {fn test_drop_does_not_disturb_other_buffer_mappings() {// Dropping one buffer must not unmap heap pages held by another buffer// sharing the same pool.- let ctx = create_context();+ let ctx = create_context::<Metal>();let capacity = buffer_capacity(ctx.as_ref(), 1);let pages = pages_for_heaps(ctx.as_ref(), 0, 1);- let mut keeper = common::helpers::sparse_buffer_create::<Metal>(&ctx, capacity);+ let mut keeper = sparse_buffer_create::<Metal>(&ctx, capacity);keeper.map(ctx.as_ref(), &pages).expect("Failed to map keeper buffer");let baseline = ctx.sparse_heap_pool().heaps_count();{- let mut transient = common::helpers::sparse_buffer_create::<Metal>(&ctx, capacity);+ let mut transient = sparse_buffer_create::<Metal>(&ctx, capacity);transient.map(ctx.as_ref(), &pages).expect("Failed to map transient buffer");}@@ -203,12 +195,12 @@ fn test_drop_does_not_disturb_other_buffer_mappings() {#[test]fn test_sequential_mappings_are_compact() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let capacity = buffer_capacity(ctx.as_ref(), 4);let first = pages_for_heaps(ctx.as_ref(), 0, 2);let second = pages_for_heaps(ctx.as_ref(), 2, 2);- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(&ctx, capacity);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);sparse_buffer.map(ctx.as_ref(), &first).expect("Failed to map first range");sparse_buffer.map(ctx.as_ref(), &second).expect("Failed to map second range");diff --git a/crates/backend-uzu/tests/unit/backends/metal/sparse/sparse_heap_pool_test.rs b/crates/backend-uzu/tests/unit/backends/metal/sparse/sparse_heap_pool_test.rsindex 77c928463..a6d4c794c 100644--- a/crates/backend-uzu/tests/unit/backends/metal/sparse/sparse_heap_pool_test.rs+++ b/crates/backend-uzu/tests/unit/backends/metal/sparse/sparse_heap_pool_test.rs@@ -1,31 +1,22 @@-#[path = "../../../../common/mod.rs"]-mod common;--use std::rc::Rc;-use crate::{backends::{common::SparseBuffer,metal::{Metal, metal_extensions::SparsePageSizeExt},},- prelude::MetalContext,+ common::helpers::{create_context, sparse_buffer_create},};-fn create_context() -> Rc<MetalContext> {- common::helpers::create_context::<Metal>()-}-#[test]fn test_new_pool_is_empty() {- let ctx = create_context();+ let ctx = create_context::<Metal>();assert_eq!(ctx.sparse_heap_pool().heaps_count(), 0);}#[test]fn test_map_empty_range_allocates_no_heaps() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer.map(&ctx, &(0..0)).expect("map empty range");@@ -34,10 +25,10 @@ fn test_map_empty_range_allocates_no_heaps() {#[test]fn test_map_single_heap_allocates_one_heap() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer.map(&ctx, &(0..pages_per_heap)).expect("map");@@ -46,10 +37,10 @@ fn test_map_single_heap_allocates_one_heap() {#[test]fn test_map_multi_heap_allocates_minimum_heaps() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let cap = 4 * ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer.map(&ctx, &(0..4 * pages_per_heap)).expect("map");@@ -58,10 +49,10 @@ fn test_map_multi_heap_allocates_minimum_heaps() {#[test]fn test_map_partial_heap_rounds_up_heap_count() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let cap = 2 * ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer.map(&ctx, &(0..pages_per_heap + 1)).expect("map");@@ -70,11 +61,11 @@ fn test_map_partial_heap_rounds_up_heap_count() {#[test]fn test_sequential_mappings_pack_into_one_heap() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let half = pages_per_heap / 2;let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer.map(&ctx, &(0..half)).expect("map first");sparse_buffer.map(&ctx, &(half..pages_per_heap)).expect("map second");@@ -84,11 +75,11 @@ fn test_sequential_mappings_pack_into_one_heap() {#[test]fn test_map_overflows_existing_heap_into_new_heap() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let half = pages_per_heap / 2;let cap = 2 * ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer.map(&ctx, &(0..half)).expect("map first");sparse_buffer.map(&ctx, &(half..half + pages_per_heap)).expect("map overflow");@@ -98,12 +89,12 @@ fn test_map_overflows_existing_heap_into_new_heap() {#[test]fn test_two_buffers_share_one_heap() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let half = pages_per_heap / 2;let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer_a = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_b = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");sparse_buffer_b.map(&ctx, &(0..half)).expect("map b");@@ -113,10 +104,10 @@ fn test_two_buffers_share_one_heap() {#[test]fn test_full_unmap_removes_heaps() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let cap = 2 * ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let pages = 0..2 * pages_per_heap;sparse_buffer.map(&ctx, &pages).expect("map");@@ -127,10 +118,10 @@ fn test_full_unmap_removes_heaps() {#[test]fn test_partial_unmap_keeps_heap() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer.map(&ctx, &(0..pages_per_heap)).expect("map");sparse_buffer.unmap(&ctx, &(0..pages_per_heap / 2)).expect("partial unmap");@@ -140,11 +131,11 @@ fn test_partial_unmap_keeps_heap() {#[test]fn test_unmap_with_other_buffer_keeps_mappings() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer_a = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_b = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let pages = 0..pages_per_heap;sparse_buffer_a.map(&ctx, &pages).expect("map a");@@ -155,12 +146,12 @@ fn test_unmap_with_other_buffer_keeps_mappings() {#[test]fn test_unmap_one_buffer_keeps_heap_for_other() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let half = pages_per_heap / 2;let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer_a = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_b = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");sparse_buffer_b.map(&ctx, &(0..half)).expect("map b");@@ -171,10 +162,10 @@ fn test_unmap_one_buffer_keeps_heap_for_other() {#[test]fn test_remap_after_unmap_does_not_grow_pool() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let cap = 2 * ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let pages = 0..2 * pages_per_heap;sparse_buffer.map(&ctx, &pages).expect("map");@@ -187,11 +178,11 @@ fn test_remap_after_unmap_does_not_grow_pool() {#[test]fn test_remap_into_freed_gap_reuses_heap() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let half = pages_per_heap / 2;let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer.map(&ctx, &(0..pages_per_heap)).expect("map full");sparse_buffer.unmap(&ctx, &(0..half)).expect("unmap half");@@ -205,11 +196,11 @@ fn test_sequential_partial_unmaps_release_full_heap() {// Regression: after a partial unmap splits a rangemap entry, the surviving// entry must still report the correct buffer↔heap correspondence so that a// subsequent unmap of the remaining suffix targets the right heap pages.- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let half = pages_per_heap / 2;let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer.map(&ctx, &(0..pages_per_heap)).expect("map");sparse_buffer.unmap(&ctx, &(0..half)).expect("unmap prefix");@@ -220,13 +211,13 @@ fn test_sequential_partial_unmaps_release_full_heap() {#[test]fn test_three_buffers_share_one_heap() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let third = pages_per_heap / 3;let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer_a = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_b = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_c = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_c = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer_a.map(&ctx, &(0..third)).expect("map a");sparse_buffer_b.map(&ctx, &(0..third)).expect("map b");@@ -237,12 +228,12 @@ fn test_three_buffers_share_one_heap() {#[test]fn test_two_buffers_exactly_fill_one_heap() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let half = pages_per_heap / 2;let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer_a = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_b = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");sparse_buffer_b.map(&ctx, &(0..pages_per_heap - half)).expect("map b fills heap");@@ -252,13 +243,13 @@ fn test_two_buffers_exactly_fill_one_heap() {#[test]fn test_third_buffer_spills_when_heap_filled_by_others() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let half = pages_per_heap / 2;let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer_a = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_b = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_c = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_c = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");sparse_buffer_b.map(&ctx, &(0..pages_per_heap - half)).expect("map b fills heap");@@ -269,13 +260,13 @@ fn test_third_buffer_spills_when_heap_filled_by_others() {#[test]fn test_unmap_buffer_frees_pages_for_another_in_same_heap() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let half = pages_per_heap / 2;let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer_a = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_b = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_c = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_c = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");sparse_buffer_b.map(&ctx, &(0..pages_per_heap - half)).expect("map b fills heap");@@ -287,13 +278,13 @@ fn test_unmap_buffer_frees_pages_for_another_in_same_heap() {#[test]fn test_unmap_middle_of_three_buffers_keeps_heap() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let third = pages_per_heap / 3;let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer_a = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_b = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_c = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_c = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer_a.map(&ctx, &(0..third)).expect("map a");sparse_buffer_b.map(&ctx, &(0..third)).expect("map b");@@ -305,13 +296,13 @@ fn test_unmap_middle_of_three_buffers_keeps_heap() {#[test]fn test_unmap_all_shared_buffers_releases_heap() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let third = pages_per_heap / 3;let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer_a = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_b = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_c = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_c = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer_a.map(&ctx, &(0..third)).expect("map a");sparse_buffer_b.map(&ctx, &(0..third)).expect("map b");@@ -325,12 +316,12 @@ fn test_unmap_all_shared_buffers_releases_heap() {#[test]fn test_second_buffer_spans_existing_and_new_heap() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let half = pages_per_heap / 2;let cap = 2 * ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer_a = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_b = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");sparse_buffer_b.map(&ctx, &(0..pages_per_heap)).expect("map b spans heaps");@@ -340,12 +331,12 @@ fn test_second_buffer_spans_existing_and_new_heap() {#[test]fn test_unmap_spanning_buffer_keeps_heap_with_other_buffer() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let half = pages_per_heap / 2;let cap = 2 * ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer_a = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_b = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");sparse_buffer_b.map(&ctx, &(0..pages_per_heap)).expect("map b spans heaps");@@ -356,12 +347,12 @@ fn test_unmap_spanning_buffer_keeps_heap_with_other_buffer() {#[test]fn test_remap_two_buffers_after_unmap_does_not_grow_pool() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let half = pages_per_heap / 2;let cap = ctx.sparse_heap_pool().heap_capacity_bytes();- let mut sparse_buffer_a = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let mut sparse_buffer_b = common::helpers::sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);+ let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");sparse_buffer_b.map(&ctx, &(0..half)).expect("map b");@@ -376,7 +367,7 @@ fn test_remap_two_buffers_after_unmap_does_not_grow_pool() {#[test]fn test_heap_capacity_pages_matches_byte_capacity() {- let ctx = create_context();+ let ctx = create_context::<Metal>();let pool = ctx.sparse_heap_pool();let page_size_bytes = pool.page_size().in_bytes();diff --git a/crates/backend-uzu/tests/unit/encodable_block/attention_gemm_test.rs b/crates/backend-uzu/tests/unit/encodable_block/attention_gemm_test.rsindex 81bcc75ae..6e547fe54 100644--- a/crates/backend-uzu/tests/unit/encodable_block/attention_gemm_test.rs+++ b/crates/backend-uzu/tests/unit/encodable_block/attention_gemm_test.rs@@ -12,12 +12,7 @@ use half::{bf16, f16};use num_traits::Float;use super::{AttentionGemmArguments, AttentionGemmBlock};--#[macro_use]-#[path = "../../common/mod.rs"]-mod common;--use common::{+use crate::common::{assert::assert_eq_float,helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},};diff --git a/crates/backend-uzu/tests/unit/encodable_block/attention_test.rs b/crates/backend-uzu/tests/unit/encodable_block/attention_test.rsindex 53e754ce1..fcc747468 100644--- a/crates/backend-uzu/tests/unit/encodable_block/attention_test.rs+++ b/crates/backend-uzu/tests/unit/encodable_block/attention_test.rs@@ -12,14 +12,10 @@ use crate::{},metal::Metal,},+ common::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, submit_encoder},data_type::DataType,};-#[path = "../../common/mod.rs"]-mod common;--use common::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, submit_encoder};-fn reference_attention(queries: &Array4<f32>,keys: &Array4<f32>,@@ -246,7 +242,7 @@ fn run_single_pass_attention(scale,None::<&Allocation<Metal>>,None,- sinks_buffer.as_ref().map(|b| b),+ sinks_buffer.as_ref(),num_heads as u32,seq_len as u32,&mut encoder,@@ -592,7 +588,7 @@ fn run_two_pass_attention(seq_len as u32,None::<&Allocation<Metal>>,None,- sinks_buffer.as_ref().map(|b| b),+ sinks_buffer.as_ref(),&mut encoder,);kernel_pass2.encode(@@ -680,7 +676,7 @@ fn perf_two_pass_attention() {let (queries, keys, values) = create_test_data(batch_size, num_heads, num_kv_heads, seq_len, head_dim, 123);let (kernel_pass1, kernel_pass2) = create_two_pass_kernels(&context, head_dim, is_causal);- let suffix_start = (seq_len - suffix_length) as usize;+ let suffix_start = seq_len - suffix_length;let queries_suffix = queries.slice(s![.., .., suffix_start.., ..]).to_owned();let queries_buffer = create_query_allocation(&queries_suffix, &context);let keys_buffer = create_attention_cache_allocation(&keys, seq_len, &context);@@ -717,7 +713,7 @@ fn perf_two_pass_attention() {suffix_length as u32,None::<&Allocation<Metal>>,None,- sinks_allocation.as_ref().map(|b| b),+ sinks_allocation.as_ref(),&mut encoder,);kernel_pass2.encode(diff --git a/crates/backend-uzu/tests/unit/encodable_block/kv_cache_update_test.rs b/crates/backend-uzu/tests/unit/encodable_block/kv_cache_update_test.rsindex a3b53f41c..948b816fd 100644--- a/crates/backend-uzu/tests/unit/encodable_block/kv_cache_update_test.rs+++ b/crates/backend-uzu/tests/unit/encodable_block/kv_cache_update_test.rs@@ -1,15 +1,14 @@#![cfg(metal_backend)]-#[macro_use]-#[path = "../../common/mod.rs"]-mod common;-use ndarray::{Array, Array3, s};use super::*;-use crate::backends::{- common::{Context, Encoder},- metal::Metal,+use crate::{+ backends::{+ common::{Context, Encoder},+ metal::Metal,+ },+ common::helpers::{sparse_buffer_create_with, sparse_buffer_read_vec},};fn apply_swaps_3d<T: Clone>(@@ -64,9 +63,8 @@ fn test_random_pattern<B: Backend>(context: &B::Context) {apply_swaps_3d(&mut expected_keys, &swaps);apply_swaps_3d(&mut expected_values, &swaps);- let mut key_buffer = common::helpers::sparse_buffer_create_with::<B, f32>(context, key_data.as_slice().unwrap());- let mut value_buffer =- common::helpers::sparse_buffer_create_with::<B, f32>(context, value_data.as_slice().unwrap());+ 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> {@@ -89,12 +87,11 @@ fn test_random_pattern<B: Backend>(context: &B::Context) {let shape = [seq_len, num_heads, head_dim];let elements_count = shape.iter().product();- let key_values: Vec<f32> = common::helpers::sparse_buffer_read_vec::<B, f32>(context, &key_buffer, elements_count);+ 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> =- common::helpers::sparse_buffer_read_vec::<B, f32>(context, &value_buffer, elements_count);+ 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");diff --git a/crates/backend-uzu/tests/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs b/crates/backend-uzu/tests/unit/encodable_block/mamba_mixer/ssd_prefill_test.rsindex 56714b7e6..c4a301759 100644--- a/crates/backend-uzu/tests/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs+++ b/crates/backend-uzu/tests/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs@@ -1,25 +1,10 @@use super::{SSDPrefillArguments, SSDPrefillBlock, SSDPrefillMode};use crate::{- array::ArrayElement,- backends::common::{- Allocation, Backend, Context, Encoder, Kernels, gpu_types::ActivationType, kernel::Conv1dScanKernel,- },+ backends::common::{Backend, Context, Encoder, Kernels, gpu_types::ActivationType, kernel::Conv1dScanKernel},+ common::helpers::{alloc_allocation_with_data, allocation_to_vec},data_type::DataType,};-#[macro_use]-#[path = "../../../common/mod.rs"]-mod common;--use common::helpers::allocation_to_vec;--fn allocation_from_slice<B: Backend, T: ArrayElement>(- context: &B::Context,- data: &[T],-) -> Allocation<B> {- common::helpers::alloc_allocation_with_data(context, data)-}-fn ssd_prefill_cpu_reference(suffix_len: usize,num_heads: usize,@@ -151,13 +136,13 @@ fn run_prefill_kernel_mode<B: Backend>(fixture: &SSDPrefillFixture,mode: SSDPrefillMode,) -> (Vec<f32>, Vec<f32>, Option<(Vec<f32>, Vec<f32>, Vec<f32>, Vec<f32>)>) {- let x_buf = allocation_from_slice::<B, _>(ctx, &fixture.x_data);- let dt_buf = allocation_from_slice::<B, _>(ctx, &fixture.dt_data);- let b_buf = allocation_from_slice::<B, _>(ctx, &fixture.b_data);- let c_buf = allocation_from_slice::<B, _>(ctx, &fixture.c_data);- let d_buf = allocation_from_slice::<B, _>(ctx, &fixture.d_data);- let z_buf = allocation_from_slice::<B, _>(ctx, &fixture.z_data);- let mut state_buf = allocation_from_slice::<B, _>(ctx, &fixture.state_init);+ 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);+ let c_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.c_data);+ 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 args = SSDPrefillArguments {x: &x_buf,@@ -208,16 +193,16 @@ fn run_conv_scan_once<B: Backend>(let total_state = channels * tap_count;let mut y_buf = if alias_io {- allocation_from_slice::<B, _>(ctx, x_data)+ alloc_allocation_with_data::<B, _>(ctx, x_data)} else {- allocation_from_slice::<B, _>(ctx, &vec![0.0f32; total_x])+ alloc_allocation_with_data::<B, _>(ctx, &vec![0.0f32; total_x])};- let mut b_out_buf = allocation_from_slice::<B, _>(ctx, &vec![0.0f32; total_x]);- let mut c_out_buf = allocation_from_slice::<B, _>(ctx, &vec![0.0f32; total_x]);- let w_buf = allocation_from_slice::<B, _>(ctx, w_data);- let b_buf = allocation_from_slice::<B, _>(ctx, b_data);- let mut state_buf = allocation_from_slice::<B, _>(ctx, state_init);- let scratch_buf = allocation_from_slice::<B, _>(ctx, &vec![0.0f32; total_state]);+ 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 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 padded_len = tap_count + suffix_len;let mut padded_host = vec![0.0f32; padded_len * channels];@@ -231,7 +216,7 @@ fn run_conv_scan_once<B: Backend>(padded_host[(tap_count + token) * channels + ch] = x_data[token * channels + ch];}}- let padded_buf = allocation_from_slice::<B, _>(ctx, &padded_host);+ let padded_buf = alloc_allocation_with_data::<B, _>(ctx, &padded_host);let mut encoder = Encoder::new(ctx).unwrap();kernel.encode(diff --git a/crates/backend-uzu/tests/unit/encodable_block/moe/mod.rs b/crates/backend-uzu/tests/unit/encodable_block/moe/mod.rsindex b9e801ad4..75ba76114 100644--- a/crates/backend-uzu/tests/unit/encodable_block/moe/mod.rs+++ b/crates/backend-uzu/tests/unit/encodable_block/moe/mod.rs@@ -1,7 +1,3 @@-#[macro_use]-#[path = "../../../common/mod.rs"]-mod common;-use super::{experts_two_pass_decode::MoeExpertsTwoPassDecodeBlock,experts_two_pass_prefill::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassPrefillBlock},@@ -35,7 +31,7 @@ pub fn cpu_tile_counts(tile_counts[expert] = if seg_len == 0 {0} else {- ((seg_len as usize + bm - 1) / bm) as u32+ (seg_len as usize).div_ceil(bm) as u32};}tile_countsdiff --git a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_block_e2e_test.rs b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_block_e2e_test.rsindex adf138b7e..310ed0184 100644--- a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_block_e2e_test.rs+++ b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_block_e2e_test.rs@@ -12,11 +12,9 @@ use backend_uzu::{use half::bf16;use rand::{RngExt, SeedableRng, rngs::StdRng};-use super::{- MoeExpertsTwoPassArguments, MoeExpertsTwoPassPrefillBlock, MoeGather,- common::helpers::{- alloc_allocation, alloc_allocation_with_data, allocation_prefix_to_vec, allocation_to_vec, create_context,- },+use super::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassPrefillBlock, MoeGather};+use crate::common::helpers::{+ alloc_allocation, alloc_allocation_with_data, allocation_prefix_to_vec, allocation_to_vec, create_context,};fn moe_cpu_reference(@@ -286,37 +284,37 @@ fn run_moe_parity_test_internal<B: Backend>(let down_biases: Vec<bf16> = (0..e * d_model).map(|_| bf16::from_f32(rng.random_range(-0.1..0.1))).collect();// Create Metal buffers- let x_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &x);- let router_w_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &router_weight_bf16);- let router_b_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &router_bias_bf16);- let w13_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w13_gpu);- let w2_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w2_gpu);- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &up_biases);- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &down_biases);+ let x_buf = alloc_allocation_with_data::<B, bf16>(ctx, &x);+ let router_w_buf = alloc_allocation_with_data::<B, bf16>(ctx, &router_weight_bf16);+ let router_b_buf = alloc_allocation_with_data::<B, bf16>(ctx, &router_bias_bf16);+ let w13_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w13_gpu);+ let w2_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w2_gpu);+ let up_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &up_biases);+ let down_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &down_biases);// Allocate intermediate buffers (max capacity)let max_sumk = t * k;- let mut topk_ids_buf = alloc_allocation::<B, i32>(&ctx, t * k);- let mut topk_probs_buf = alloc_allocation::<B, bf16>(&ctx, t * k);- let mut offsets_buf = alloc_allocation::<B, u32>(&ctx, e + 1);- let mut sumk_buf = alloc_allocation::<B, u32>(&ctx, 1);- let num_blocks = ((t + 255) / 256).max(1);- let num_tiles = ((e + 512 - 1) / 512).max(1);+ let mut topk_ids_buf = alloc_allocation::<B, i32>(ctx, t * k);+ let mut topk_probs_buf = alloc_allocation::<B, bf16>(ctx, t * k);+ let mut offsets_buf = alloc_allocation::<B, u32>(ctx, e + 1);+ let mut sumk_buf = alloc_allocation::<B, u32>(ctx, 1);+ let num_blocks = t.div_ceil(256).max(1);+ let num_tiles = e.div_ceil(512).max(1);let entries = num_blocks * num_tiles * 512usize;- let mut partials_buf = alloc_allocation::<B, u32>(&ctx, entries);- let mut block_bases_buf = alloc_allocation::<B, u32>(&ctx, entries);- let mut block_alloc_buf = alloc_allocation::<B, u32>(&ctx, entries);- let mut bucketed_ids_buf = alloc_allocation::<B, i32>(&ctx, max_sumk);- let mut bucketed_probs_buf = alloc_allocation::<B, bf16>(&ctx, max_sumk);- let mut tok2row_buf = alloc_allocation::<B, i32>(&ctx, t * k);- let mut y_out_buf = alloc_allocation::<B, bf16>(&ctx, t * d_model);+ let mut partials_buf = alloc_allocation::<B, u32>(ctx, entries);+ let mut block_bases_buf = alloc_allocation::<B, u32>(ctx, entries);+ let mut block_alloc_buf = alloc_allocation::<B, u32>(ctx, entries);+ let mut bucketed_ids_buf = alloc_allocation::<B, i32>(ctx, max_sumk);+ let mut bucketed_probs_buf = alloc_allocation::<B, bf16>(ctx, max_sumk);+ let mut tok2row_buf = alloc_allocation::<B, i32>(ctx, t * k);+ let mut y_out_buf = alloc_allocation::<B, bf16>(ctx, t * d_model);// Encode ALL kernels in one command buffereprintln!("[E2E] Encoding entire MoE pipeline in single command buffer...");let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");// Router + TopK (fused kernel)- let router_topk = <B::Kernels as Kernels>::MoeRouterTopKKernel::new(&ctx, DataType::BF16).expect("router+topk");+ let router_topk = <B::Kernels as Kernels>::MoeRouterTopKKernel::new(ctx, DataType::BF16).expect("router+topk");router_topk.encode(&x_buf,&router_w_buf,@@ -331,7 +329,7 @@ fn run_moe_parity_test_internal<B: Backend>(&mut encoder,);- let fused_kernel = <B::Kernels as Kernels>::MoeCountsOffsetsFusedKernel::new(&ctx).expect("fused kernel");+ let fused_kernel = <B::Kernels as Kernels>::MoeCountsOffsetsFusedKernel::new(ctx).expect("fused kernel");fused_kernel.encode(&topk_ids_buf,&mut offsets_buf,@@ -344,7 +342,7 @@ fn run_moe_parity_test_internal<B: Backend>();let scatter_bases_kernel =- <B::Kernels as Kernels>::MoeBlockBasesFromPartialsKernel::new(&ctx).expect("scatter bases kernel");+ <B::Kernels as Kernels>::MoeBlockBasesFromPartialsKernel::new(ctx).expect("scatter bases kernel");scatter_bases_kernel.encode(&partials_buf,&mut block_bases_buf,@@ -356,7 +354,7 @@ fn run_moe_parity_test_internal<B: Backend>(&mut encoder,);- let scatter_map_kernel = <B::Kernels as Kernels>::MoeScatterBucketsMapKernel::new(&ctx, DataType::BF16)+ let scatter_map_kernel = <B::Kernels as Kernels>::MoeScatterBucketsMapKernel::new(ctx, DataType::BF16).expect("Failed to create <<Metal as Backend>::Kernels as Kernels>::MoeScatterBucketsMapKernel");scatter_map_kernel.encode(&topk_ids_buf,@@ -375,12 +373,12 @@ fn run_moe_parity_test_internal<B: Backend>(&mut encoder,);- let gather = MoeGather::<B>::new(&ctx, DataType::BF16).expect("gather");+ let gather = MoeGather::<B>::new(ctx, DataType::BF16).expect("gather");let x_perm_buf = gather.encode(&x_buf, &bucketed_ids_buf, &sumk_buf, t, k, d_model, &mut encoder).expect("gather");let total_rows = t * k;- let experts = MoeExpertsTwoPassPrefillBlock::<B>::new(&ctx, DataType::BF16, gating_code).expect("experts");+ let experts = MoeExpertsTwoPassPrefillBlock::<B>::new(ctx, DataType::BF16, gating_code).expect("experts");let args = MoeExpertsTwoPassArguments {x_perm: &x_perm_buf,expert_offsets: &offsets_buf,@@ -400,7 +398,7 @@ fn run_moe_parity_test_internal<B: Backend>(};let y_partial_buf = experts.encode(args, &mut encoder).expect("failed to encode MoE experts");- let finalize = <B::Kernels as Kernels>::MoeFinalizeKernel::new(&ctx, DataType::BF16).expect("finalize");+ let finalize = <B::Kernels as Kernels>::MoeFinalizeKernel::new(ctx, DataType::BF16).expect("finalize");finalize.encode(&tok2row_buf,&topk_probs_buf,@@ -448,19 +446,19 @@ fn run_moe_parity_test_internal<B: Backend>(if t > 1 && d_ff >= 256 {let x_perm_cpu = allocation_prefix_to_vec::<B, bf16>(&x_perm_buf, sumk_val * d_model);eprintln!("[E2E] x_perm diagnostics (sumk={}):", sumk_val);- eprintln!("[E2E] Row 0 [0:8]: {:?}", &x_perm_cpu[0..8].iter().map(|&v| f32::from(v)).collect::<Vec<_>>());+ eprintln!("[E2E] Row 0 [0:8]: {:?}", x_perm_cpu[0..8].iter().map(|&v| f32::from(v)).collect::<Vec<_>>());if sumk_val > 1 {eprintln!("[E2E] Row 1 [{}:{}]: {:?}",d_model,d_model + 8,- &x_perm_cpu[d_model..d_model + 8].iter().map(|&v| f32::from(v)).collect::<Vec<_>>()+ x_perm_cpu[d_model..d_model + 8].iter().map(|&v| f32::from(v)).collect::<Vec<_>>());}// CRITICAL: Check tok2row mapping for multi-token testslet tok2row_cpu = allocation_prefix_to_vec::<B, i32>(&tok2row_buf, t * k);- eprintln!("[E2E] tok2row[0..{}]: {:?}", t * k, &tok2row_cpu);+ eprintln!("[E2E] tok2row[0..{}]: {:?}", t * k, tok2row_cpu);eprintln!("[E2E] Expected: token 0→row {}, token 1→row {}",0,@@ -479,7 +477,7 @@ fn run_moe_parity_test_internal<B: Backend>(// Check positions where mismatches occur (odd indices near tile boundaries)eprintln!("[E2E] Row 1 positions (even=working, odd=corrupted?):");for &pos in &[48, 56, 57, 58, 59, 60, 61, 62, 63, 64, 120, 121, 122, 123, 124, 125, 126, 127, 128] {- let idx = 1 * d_model + pos;+ let idx = d_model + pos;if idx < y_partial_full.len() {eprintln!("[E2E] y_partial[row1, col {}] = {:.3}", pos, f32::from(y_partial_full[idx]));}@@ -568,7 +566,7 @@ fn run_moe_parity_test_internal<B: Backend>(eprintln!("[E2E] y_partial sample (first {}): {:?}",sample_size,- &y_partial_gpu[..sample_size].iter().map(|&v| f32::from(v)).collect::<Vec<_>>()+ y_partial_gpu[..sample_size].iter().map(|&v| f32::from(v)).collect::<Vec<_>>());// For multi-row debugging: print both rows@@ -577,16 +575,13 @@ fn run_moe_parity_test_internal<B: Backend>("[E2E] y_partial row 1 [{}-{}]: {:?}",d_model,d_model + 16,- &y_partial_gpu[d_model..d_model + 16].iter().map(|&v| f32::from(v)).collect::<Vec<_>>()+ y_partial_gpu[d_model..d_model + 16].iter().map(|&v| f32::from(v)).collect::<Vec<_>>());}let out_sample_size = 16.min(t * d_model);eprintln!("[E2E] y_out sample (token 0): {:?}", &y_out_gpu[..out_sample_size]);if t > 1 && d_model >= 512 {- eprintln!(- "[E2E] y_out sample (token 1, first 32): {:?}",- &y_out_gpu[d_model..d_model + 32].iter().map(|&v| f32::from(v)).collect::<Vec<_>>()- );+ eprintln!("[E2E] y_out sample (token 1, first 32): {:?}", y_out_gpu[d_model..d_model + 32].to_vec());}eprintln!("[E2E] CPU ref sample (token 0): {:?}", &y_cpu[..out_sample_size]);if t > 1 && d_model >= 512 {@@ -598,14 +593,14 @@ fn run_moe_parity_test_internal<B: Backend>(eprintln!("[E2E] Token 1 detailed comparison:");for i in [0, 1, 2, 3, 4, 5, 6, 7, 15, 16, 17, 18, 48, 64, 121, 128].iter() {if *i < d_model {- let diff = (f32::from(gpu_t1[*i]) - cpu_t1[*i]).abs();- eprintln!("[E2E] [{}]: GPU={:.6}, CPU={:.6}, diff={:.6}", i, f32::from(gpu_t1[*i]), cpu_t1[*i], diff);+ let diff = (gpu_t1[*i] - cpu_t1[*i]).abs();+ eprintln!("[E2E] [{}]: GPU={:.6}, CPU={:.6}, diff={:.6}", i, gpu_t1[*i], cpu_t1[*i], diff);}}}- let k0_iters = (d_model + 31) / 32;- let ff0_iters = (d_ff + 31) / 32;+ let k0_iters = d_model.div_ceil(32);+ let ff0_iters = d_ff.div_ceil(32);let product = k0_iters * ff0_iters;let sqrt_product = (product as f32).sqrt();diff --git a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_experts_test.rs b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_experts_test.rsindex f63b5e145..e1ed6fb1c 100644--- a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_experts_test.rs+++ b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_experts_test.rs@@ -17,12 +17,12 @@ use half::bf16;use rand::{RngExt, SeedableRng, rngs::StdRng};use super::{- MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeBlock, MoeExpertsTwoPassPrefillBlock,- common::{- assert::assert_eq_float,- helpers::{alloc_allocation_with_data, allocation_prefix_to_vec, create_context},- },- cpu_tile_counts, cpu_tile_scan,+ MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeBlock, MoeExpertsTwoPassPrefillBlock, cpu_tile_counts,+ cpu_tile_scan,+};+use crate::common::{+ assert::assert_eq_float,+ helpers::{alloc_allocation_with_data, allocation_prefix_to_vec, create_context},};/// Test data for MoE experts@@ -166,7 +166,6 @@ fn gather_and_finalize(/// - 1: SiLU(up)/// - 2: SwiGLU = SiLU(gate) * up/// - 3: GEGLU = GELU(gate) * up-#[allow(clippy::too_many_arguments)]fn cpu_moe_reference(x: &[bf16], // [T, d_model]topk_ids: &[i32], // [T * K]diff --git a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_gather_test.rs b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_gather_test.rsindex 9d353c44d..acf131ead 100644--- a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_gather_test.rs+++ b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_gather_test.rs@@ -10,12 +10,7 @@ use num_traits::Float;use rand::{RngExt, SeedableRng, rngs::StdRng};use super::MoeGather;--#[macro_use]-#[path = "../../../common/mod.rs"]-mod common;--use common::{+use crate::common::{assert::assert_eq_float,helpers::{alloc_allocation_with_data, allocation_to_vec, create_context},};diff --git a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_tiles_test.rs b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_tiles_test.rsindex dddfa407f..6ac329ca6 100644--- a/crates/backend-uzu/tests/unit/encodable_block/moe/moe_tiles_test.rs+++ b/crates/backend-uzu/tests/unit/encodable_block/moe/moe_tiles_test.rs@@ -4,11 +4,11 @@ use backend_uzu::backends::common::{};use rand::{RngExt, SeedableRng, rngs::StdRng};-use crate::encodable_block::mlp::moe::tests::{+use crate::{common::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_prefix_to_vec, allocation_to_vec, create_context,},- cpu_tile_counts, cpu_tile_scan,+ encodable_block::mlp::moe::tests::{cpu_tile_counts, cpu_tile_scan},};#[test]diff --git a/crates/backend-uzu/tests/unit/encodable_block/sampling_test.rs b/crates/backend-uzu/tests/unit/encodable_block/sampling_test.rsindex 90ea28017..f789bd0e2 100644--- a/crates/backend-uzu/tests/unit/encodable_block/sampling_test.rs+++ b/crates/backend-uzu/tests/unit/encodable_block/sampling_test.rs@@ -12,15 +12,11 @@ use crate::{},metal::Metal,},+ common::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},data_type::DataType,session::parameter::{SamplingMethod, SamplingProcessingOrder},};-#[path = "../../common/mod.rs"]-mod common;--use common::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec};-// Constant seed for reproducible test resultsconst TEST_SAMPLING_SEED: u64 = 42;@@ -316,7 +312,7 @@ fn test_categorical_sampling_statistical() {}// Compute expected probabilities (softmax)- let mut expected_probs = vec![0.0f32; BATCH * VOCAB];+ let mut expected_probs = [0.0f32; BATCH * VOCAB];for batch_idx in 0..BATCH {let batch_logits = &logits[batch_idx * VOCAB..(batch_idx + 1) * VOCAB];let max_logit = batch_logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);@@ -336,7 +332,7 @@ fn test_categorical_sampling_statistical() {let mut output_buffer = alloc_allocation::<Metal, u32>(context.as_ref(), BATCH);- let mut counts = vec![0; BATCH * VOCAB];+ let mut counts = [0; BATCH * VOCAB];// Sample many timesfor sample_idx in 0..NUM_SAMPLES {diff --git a/crates/backend-uzu/tests/unit/encodable_block/sampling_top_p_test.rs b/crates/backend-uzu/tests/unit/encodable_block/sampling_top_p_test.rsindex e07f72afc..33ac4f994 100644--- a/crates/backend-uzu/tests/unit/encodable_block/sampling_top_p_test.rs+++ b/crates/backend-uzu/tests/unit/encodable_block/sampling_top_p_test.rs@@ -17,12 +17,7 @@ use num_traits::Float;use rand::{RngExt, SeedableRng, rngs::StdRng, seq::SliceRandom};use super::SamplingBlock;--#[macro_use]-#[path = "../../common/mod.rs"]-mod common;--use common::helpers::{alloc_allocation_with_data, allocation_to_vec};+use crate::common::helpers::{alloc_allocation_with_data, allocation_to_vec};const TEST_SAMPLING_SEED: u64 = 42;diff --git a/crates/backend-uzu/tests/unit/forward_pass/kv_cache_state_test.rs b/crates/backend-uzu/tests/unit/forward_pass/kv_cache_state_test.rsindex 9119b49ea..f4c3436f8 100644--- a/crates/backend-uzu/tests/unit/forward_pass/kv_cache_state_test.rs+++ b/crates/backend-uzu/tests/unit/forward_pass/kv_cache_state_test.rs@@ -7,14 +7,12 @@ use crate::{common::{Backend, Context, Encoder},metal::Metal,},+ common::helpers::{sparse_buffer_create_with, sparse_buffer_read_vec, sparse_buffer_write},data_type::DataType,encodable_block::KVCacheUpdate,forward_pass::kv_cache_layer::{KVCacheLayer, KVCacheLayerState},};-#[path = "../../common/mod.rs"]-mod common;-#[derive(Debug)]struct Scenario {name: &'static str,@@ -48,8 +46,8 @@ fn make_test_layer<B: Backend>(let shape = [total_len.max(1), 1, 1];let zeroes = vec![0.0_f32; shape.iter().product()];- let keys = common::helpers::sparse_buffer_create_with::<B, f32>(context, &zeroes);- let values = common::helpers::sparse_buffer_create_with::<B, f32>(context, &zeroes);+ 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,@@ -66,11 +64,11 @@ fn overwrite_sparse_buffer<B: Backend>(elements_count: usize,updates: &[(usize, f32)],) {- let mut data: Vec<f32> = common::helpers::sparse_buffer_read_vec::<B, f32>(context, buffer, elements_count);+ let mut data: Vec<f32> = sparse_buffer_read_vec::<B, f32>(context, buffer, elements_count);for (index, value) in updates {data[*index] = *value;}- common::helpers::sparse_buffer_write::<B, f32>(context, buffer, &data);+ sparse_buffer_write::<B, f32>(context, buffer, &data);}fn fill_arrays<B: Backend>(@@ -80,14 +78,14 @@ fn fill_arrays<B: Backend>(let initial_keys = {let len = layer.shape.iter().product();let data: Vec<f32> = (0..len).map(|idx| 1_000.0 + idx as f32).collect();- common::helpers::sparse_buffer_write::<B, f32>(context, &mut layer.keys, &data);+ 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();- common::helpers::sparse_buffer_write::<B, f32>(context, &mut layer.values, &data);+ sparse_buffer_write::<B, f32>(context, &mut layer.values, &data);data};@@ -179,12 +177,10 @@ fn run_scenario<B: Backend>(layer.register_accepted_tokens(scenario.number_of_accepted_tokens);- let actual_keys: Vec<f32> =- common::helpers::sparse_buffer_read_vec::<B, f32>(context, &layer.keys, expected_keys.len());+ 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> =- common::helpers::sparse_buffer_read_vec::<B, f32>(context, &layer.values, expected_values.len());+ 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 {@@ -328,10 +324,8 @@ fn kv_cache_slice_apply_contiguous_window() {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> =- common::helpers::sparse_buffer_read_vec::<Metal, f32>(&context, &layer.keys, elements_count);- let values_after: Vec<f32> =- common::helpers::sparse_buffer_read_vec::<Metal, f32>(&context, &layer.values, elements_count);+ 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");}@@ -367,10 +361,8 @@ fn kv_cache_slice_apply_wrap_window() {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> =- common::helpers::sparse_buffer_read_vec::<Metal, f32>(&context, &layer.keys, elements_count);- let values_after: Vec<f32> =- common::helpers::sparse_buffer_read_vec::<Metal, f32>(&context, &layer.values, elements_count);+ 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");}diff --git a/crates/backend-uzu/tests/unit/kernel/attention/attention_update_kv_cache_test.rs b/crates/backend-uzu/tests/unit/kernel/attention/attention_update_kv_cache_test.rsindex 9b2c7d760..306f0dd6e 100644--- a/crates/backend-uzu/tests/unit/kernel/attention/attention_update_kv_cache_test.rs+++ b/crates/backend-uzu/tests/unit/kernel/attention/attention_update_kv_cache_test.rs@@ -335,7 +335,8 @@ fn test_internal<T: ArrayElement + Float + Debug + Display>(}fn test_basic<T: ArrayElement + Float + Debug + Display>() {- for keys_in_place in [false] {+ {+ 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);diff --git a/crates/backend-uzu/tests/unit/kernel/delta_net_test.rs b/crates/backend-uzu/tests/unit/kernel/delta_net_test.rsindex 53f926601..24275dc30 100644--- a/crates/backend-uzu/tests/unit/kernel/delta_net_test.rs+++ b/crates/backend-uzu/tests/unit/kernel/delta_net_test.rs@@ -304,7 +304,7 @@ fn run_prefill_with_norm_gate(let value_dim = num_v_heads * head_v_dim;let conv_dim = 2 * key_dim + value_dim;let total_proj_dim = conv_dim + value_dim + num_v_heads + num_v_heads;- let num_dv_groups = (head_v_dim as u32 + 7) / 8;+ let num_dv_groups = (head_v_dim as u32).div_ceil(8);let context = <Metal as Backend>::Context::new().expect("context");let in_proj_array = context.create_array_from(&[in_proj.len()], in_proj);@@ -586,7 +586,7 @@ fn bench_delta_net_prefill() {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 num_dv_groups = (head_v_dim as u32 + 7) / 8;+ let num_dv_groups = (head_v_dim as u32).div_ceil(8);let prep_k = <<Metal as Backend>::Kernels as Kernels>::DeltaNetPrefillPrepKernel::new(&context,diff --git a/crates/backend-uzu/tests/unit/kernel/embedding/quant_embedding_test.rs b/crates/backend-uzu/tests/unit/kernel/embedding/quant_embedding_test.rsindex fc220c657..8ec59df75 100644--- a/crates/backend-uzu/tests/unit/kernel/embedding/quant_embedding_test.rs+++ b/crates/backend-uzu/tests/unit/kernel/embedding/quant_embedding_test.rs@@ -47,7 +47,7 @@ fn get_test_data<T: ArrayElement + Float>(quant_mode: QuantizationMode) -> (Inpu.map(|i| ((i % 16) as u8) | ((((i + 3) % 16) as u8) * 16)).collect();- let num_groups = (model_dim + group_size - 1) / group_size;+ let num_groups = model_dim.div_ceil(group_size);let scales: Vec<T> = (0..vocab_size as usize * num_groups as usize).map(|i| T::from(0.5 + (i as f32 * 0.1).sin() * 0.3).unwrap()).collect();@@ -90,7 +90,7 @@ fn get_test_data_zero_point_group16<T: ArrayElement + Float>() -> (Input<T>, Vec.map(|i| ((i % 16) as u8) | ((((i + 3) % 16) as u8) * 16)).collect();- let num_groups = (model_dim + group_size - 1) / group_size;+ let num_groups = model_dim.div_ceil(group_size);let scales: Vec<T> = (0..vocab_size as usize * num_groups as usize).map(|i| T::from(0.5 + (i as f32 * 0.1).sin() * 0.3).unwrap()).collect();@@ -131,7 +131,7 @@ fn get_test_data_symmetric_u8<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {let weights: Vec<u8> =(0..vocab_size as usize * model_dim as usize).map(|i| ((i * 37 + 11) & 0xFF) as u8).collect();- let num_groups = (model_dim + group_size - 1) / group_size;+ let num_groups = model_dim.div_ceil(group_size);let scales: Vec<T> = (0..vocab_size as usize * num_groups as usize).map(|i| T::from(0.5 + (i as f32 * 0.1).sin() * 0.3).unwrap()).collect();@@ -167,7 +167,7 @@ fn get_test_data_oob<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {let weights: Vec<u8> = (0..vocab_size as usize * model_dim as usize).map(|i| (i % 200) as u8).collect();- let num_groups = (model_dim + group_size - 1) / group_size;+ let num_groups = model_dim.div_ceil(group_size);let scales: Vec<T> =(0..vocab_size as usize * num_groups as usize).map(|i| T::from(0.5 + i as f32 * 0.1).unwrap()).collect();let biases: Vec<T> =@@ -207,7 +207,7 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {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 + input.group_size as usize - 1) / input.group_size as usize;+ 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);diff --git a/crates/backend-uzu/tests/unit/kernel/layer_norm_test.rs b/crates/backend-uzu/tests/unit/kernel/layer_norm_test.rsindex b9e441d1b..66cc28480 100644--- a/crates/backend-uzu/tests/unit/kernel/layer_norm_test.rs+++ b/crates/backend-uzu/tests/unit/kernel/layer_norm_test.rs@@ -189,9 +189,9 @@ fn test_basic<ACC: ArrayElement + Float,>() {let in_place_values: &[bool] = if IN::data_type() == OUT::data_type() {- &BOOL_ALL+ BOOL_ALL} else {- &BOOL_FALSE+ BOOL_FALSE};for in_place in in_place_values {@@ -209,9 +209,9 @@ fn test_edge<ACC: ArrayElement + Float,>() {let in_place_values: &[bool] = if IN::data_type() == OUT::data_type() {- &BOOL_ALL+ BOOL_ALL} else {- &BOOL_FALSE+ BOOL_FALSE};for in_place in in_place_values {diff --git a/crates/backend-uzu/tests/unit/kernel/matmul/dispatch_paths_test.rs b/crates/backend-uzu/tests/unit/kernel/matmul/dispatch_paths_test.rsindex d62f0fed8..a42f5d912 100644--- a/crates/backend-uzu/tests/unit/kernel/matmul/dispatch_paths_test.rs+++ b/crates/backend-uzu/tests/unit/kernel/matmul/dispatch_paths_test.rs@@ -76,7 +76,7 @@ fn matches_cpu_reference_bf16(#[test]fn matches_cpu_reference_f32() {- run_matrix::<f32>(|shape| Case::new(shape), 0.01);+ run_matrix::<f32>(Case::new, 0.01);}#[test]diff --git a/crates/backend-uzu/tests/unit/kernel/mod.rs b/crates/backend-uzu/tests/unit/kernel/mod.rsindex e4675a0c5..7e9bdfff2 100644--- a/crates/backend-uzu/tests/unit/kernel/mod.rs+++ b/crates/backend-uzu/tests/unit/kernel/mod.rs@@ -1,7 +1,3 @@-#[macro_use]-#[path = "../../common/mod.rs"]-mod common;-mod activation_test;mod attention;mod audio;diff --git a/crates/backend-uzu/tests/unit/kernel/moe/moe_scatter_test.rs b/crates/backend-uzu/tests/unit/kernel/moe/moe_scatter_test.rsindex c736788a8..35ab07e5c 100644--- a/crates/backend-uzu/tests/unit/kernel/moe/moe_scatter_test.rs+++ b/crates/backend-uzu/tests/unit/kernel/moe/moe_scatter_test.rs@@ -74,7 +74,7 @@ fn get_output_topk<B: Backend, T: ArrayElement + Float>(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()).expect("router_topk");+ <<B as Backend>::Kernels as Kernels>::MoeRouterTopKKernel::new(ctx, T::data_type()).expect("router_topk");let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");topk_kernel.encode(input_array.allocation(),diff --git a/crates/backend-uzu/tests/unit/kernel/rms_norm_test.rs b/crates/backend-uzu/tests/unit/kernel/rms_norm_test.rsindex 2b862b551..b5d7150ed 100644--- a/crates/backend-uzu/tests/unit/kernel/rms_norm_test.rs+++ b/crates/backend-uzu/tests/unit/kernel/rms_norm_test.rs@@ -199,7 +199,7 @@ fn test_internal<input.full_layer,input.in_place,);- assert_eq_float::<OutputT>(&expected, &output, eps, &msg);+ assert_eq_float::<OutputT>(expected, &output, eps, &msg);});}@@ -210,9 +210,9 @@ fn test_basic<AccumT: ArrayElement + Float,>() {let in_place_values: &[bool] = if InputT::data_type() == OutputT::data_type() {- &BOOL_ALL+ BOOL_ALL} else {- &BOOL_FALSE+ BOOL_FALSE};for in_place in in_place_values {@@ -230,9 +230,9 @@ fn test_edge<AccumT: ArrayElement + Float,>() {let in_place_values: &[bool] = if InputT::data_type() == OutputT::data_type() {- &BOOL_ALL+ BOOL_ALL} else {- &BOOL_FALSE+ BOOL_FALSE};for in_place in in_place_values {diff --git a/crates/backend-uzu/tests/unit/kernel/sampling/argmax_test_old.rs b/crates/backend-uzu/tests/unit/kernel/sampling/argmax_test_old.rsindex 2ff6cb85f..120c214db 100644--- a/crates/backend-uzu/tests/unit/kernel/sampling/argmax_test_old.rs+++ b/crates/backend-uzu/tests/unit/kernel/sampling/argmax_test_old.rs@@ -92,7 +92,7 @@ fn get_output_two_pass<T: ArrayElement + Float, B: Backend>(input: &Input<T>) ->let block_size = 1024;let grain_size = 4;let elements_per_group = block_size * grain_size;- let vocab_groups_per_batch = (input.vocab_size as usize + elements_per_group - 1) / elements_per_group;+ let vocab_groups_per_batch = (input.vocab_size as usize).div_ceil(elements_per_group);let partial_results_count = input.batch_size as usize * vocab_groups_per_batch;let mut partial_results = context.create_array_uninitialized(&[partial_results_count * size_of::<ArgmaxPair>()], DataType::U8)diff --git a/crates/backend-uzu/tests/unit/kernel/sampling/bitmask_test.rs b/crates/backend-uzu/tests/unit/kernel/sampling/bitmask_test.rsindex 1c1c1f084..72ebfef3a 100644--- a/crates/backend-uzu/tests/unit/kernel/sampling/bitmask_test.rs+++ b/crates/backend-uzu/tests/unit/kernel/sampling/bitmask_test.rs@@ -28,7 +28,7 @@ fn get_test_data_basic<T: ArrayElement + Float>(in_place: bool) -> (Input<T>, Velet len = (batch_size * vocab_size) as usize;let logits: Vec<T> = (0..len).map(|i| T::from((i as f32 * 0.1).sin() * 2.0).unwrap()).collect();- let bitmask_size = ((vocab_size + 31) / 32) as usize;+ let bitmask_size = vocab_size.div_ceil(32) as usize;let mut bitmask = vec![0u32; batch_size as usize * bitmask_size];// Allow every other tokenfor b in 0..batch_size as usize {@@ -56,7 +56,7 @@ fn get_test_data_all_allowed<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {let len = (batch_size * vocab_size) as usize;let logits: Vec<T> = (0..len).map(|i| T::from(i as f32 * 0.5).unwrap()).collect();- let bitmask_size = ((vocab_size + 31) / 32) as usize;+ let bitmask_size = vocab_size.div_ceil(32) as usize;let bitmask = vec![0xFFFFFFFFu32; batch_size as usize * bitmask_size];let input = Input {@@ -78,7 +78,7 @@ fn get_test_data_none_allowed<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {let len = (batch_size * vocab_size) as usize;let logits: Vec<T> = (0..len).map(|i| T::from(i as f32 * 0.5).unwrap()).collect();- let bitmask_size = ((vocab_size + 31) / 32) as usize;+ let bitmask_size = vocab_size.div_ceil(32) as usize;let bitmask = vec![0u32; batch_size as usize * bitmask_size];let input = Input {@@ -101,7 +101,7 @@ fn get_test_data_non_aligned<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {let len = (batch_size * vocab_size) as usize;let logits: Vec<T> = (0..len).map(|i| T::from((i as f32 * 0.3).cos() * 3.0).unwrap()).collect();- let bitmask_size = ((vocab_size + 31) / 32) as usize;+ let bitmask_size = vocab_size.div_ceil(32) as usize;let mut bitmask = vec![0u32; batch_size as usize * bitmask_size];// Set specific bitsfor b in 0..batch_size as usize {diff --git a/crates/backend-uzu/tests/unit/kernel/ssm/ssm_prefill_test.rs b/crates/backend-uzu/tests/unit/kernel/ssm/ssm_prefill_test.rsindex 45d6132e9..645484063 100644--- a/crates/backend-uzu/tests/unit/kernel/ssm/ssm_prefill_test.rs+++ b/crates/backend-uzu/tests/unit/kernel/ssm/ssm_prefill_test.rs@@ -129,7 +129,7 @@ fn get_output<B: Backend, T: ArrayElement + Float>(&mut state,&mut y,input.suffix_len as u32,- input.group_size as u32,+ input.group_size,input.state_dim as u32,&x_strides,&dt_strides,@@ -154,7 +154,7 @@ fn get_output<B: Backend, T: ArrayElement + Float>(&mut state,&mut y,input.suffix_len as u32,- input.group_size as u32,+ input.group_size,input.state_dim as u32,&x_strides,&dt_strides,diff --git a/crates/backend-uzu/tests/unit/trie_test.rs b/crates/backend-uzu/tests/unit/trie_test.rsindex dd9b8c9d0..21d7fe278 100644--- a/crates/backend-uzu/tests/unit/trie_test.rs+++ b/crates/backend-uzu/tests/unit/trie_test.rs@@ -37,7 +37,7 @@ fn verify_sprout(let flat_trie = trie_root.linearize();assert_eq!(flat_trie.len(), 1);- assert_eq!(flat_trie.index(&trie_root), Some(0));+ 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);@@ -95,8 +95,8 @@ fn verify_stick(assert_eq!(token_seeds[position], rng.derive(0));for i in 1..10 {- cur_node = cur_node.get(i as u64).unwrap();- assert_eq!(cur_node.token(), i as u64);+ cur_node = cur_node.get(i).unwrap();+ assert_eq!(cur_node.token(), i);assert_eq!(cur_node.seed(), rng.derive(i));let position = flat_trie.index(cur_node).unwrap();@@ -158,7 +158,7 @@ fn verify_bush(assert_eq!(token_positions.len(), 4);assert_eq!(token_seeds.len(), 4);- let root_position = flat_trie.index(&trie_root).unwrap();+ let root_position = flat_trie.index(trie_root).unwrap();assert_eq!(token_ids[root_position], 0);assert_eq!(token_positions[root_position], 0);assert_eq!(token_seeds[root_position], rng.derive(0));@@ -168,7 +168,7 @@ fn verify_bush(assert_eq!(leaf.token(), leaf_token);assert_eq!(leaf.seed(), rng.derive(1));- let position = flat_trie.index(&leaf).unwrap();+ let position = flat_trie.index(leaf).unwrap();assert_eq!(token_ids[position], leaf.token());assert_eq!(token_positions[position], 1);assert_eq!(token_seeds[position], rng.derive(1));@@ -226,14 +226,14 @@ fn verify_tree(assert_eq!(token_positions.len(), 7);assert_eq!(token_seeds.len(), 7);- let root_position = flat_trie.index(&trie_root).unwrap();+ let root_position = flat_trie.index(trie_root).unwrap();assert_eq!(token_ids[root_position], 0);assert_eq!(token_positions[root_position], 0);assert_eq!(token_seeds[root_position], rng.derive(0));for mid_token in [1, 2, 3] {let node = trie_root.get(mid_token).unwrap();- let position = flat_trie.index(&node).unwrap();+ let position = flat_trie.index(node).unwrap();assert_eq!(token_ids[position], mid_token);assert_eq!(token_positions[position], 1);assert_eq!(token_seeds[position], rng.derive(1));diff --git a/crates/benchmarks/Cargo.toml b/crates/benchmarks/Cargo.tomlindex e29d8a2f0..a0aa1bbe3 100644--- a/crates/benchmarks/Cargo.toml+++ b/crates/benchmarks/Cargo.toml@@ -17,3 +17,6 @@ sysinfo.workspace = truedefault = ["metal"]metal = ["backend-uzu/metal"]++[lints]+workspace = truediff --git a/crates/benchmarks/src/runner/runner.rs b/crates/benchmarks/src/runner/runner.rsindex 062bce671..83e144087 100644--- a/crates/benchmarks/src/runner/runner.rs+++ b/crates/benchmarks/src/runner/runner.rs@@ -105,12 +105,10 @@ impl Runner {let cpu_name = system_info.cpus().first().map(|cpu| cpu.brand().to_string());let memory_total = system_info.total_memory();- let device = Device {+ Device {os_name,cpu_name,memory_total,- };-- device+ }}}diff --git a/crates/bindings-types/Cargo.toml b/crates/bindings-types/Cargo.tomlindex acc7ac3e6..5a1577149 100644--- a/crates/bindings-types/Cargo.toml+++ b/crates/bindings-types/Cargo.toml@@ -51,3 +51,6 @@ tsify = { workspace = true, optional = true }[build-dependencies]napi-build = { workspace = true, optional = true }pyo3-build-config = { workspace = true, optional = true }++[lints]+workspace = truediff --git a/crates/bindings/Cargo.toml b/crates/bindings/Cargo.tomlindex 2d596aa2f..4573d58ef 100644--- a/crates/bindings/Cargo.toml+++ b/crates/bindings/Cargo.toml@@ -16,3 +16,6 @@ heck.workspace = trueproc-macro2.workspace = truequote.workspace = truesyn.workspace = true++[lints]+workspace = truediff --git a/crates/bindings/src/backends/pyo3.rs b/crates/bindings/src/backends/pyo3.rsindex 8605ebb7f..11180870e 100644--- a/crates/bindings/src/backends/pyo3.rs+++ b/crates/bindings/src/backends/pyo3.rs@@ -359,18 +359,14 @@ fn type_path_last_ident(ty: &syn::Type) -> Option<&Ident> {}fn unwrap_result(ty: &syn::Type) -> &syn::Type {- if let syn::Type::Path(type_path) = ty {- if let Some(last) = type_path.path.segments.last() {- if last.ident == "Result" {- if let syn::PathArguments::AngleBracketed(arguments) = &last.arguments {- if let Some(syn::GenericArgument::Type(inner)) =- arguments.args.iter().find(|argument| matches!(argument, syn::GenericArgument::Type(_)))- {- return inner;- }- }- }- }+ if let syn::Type::Path(type_path) = ty+ && let Some(last) = type_path.path.segments.last()+ && last.ident == "Result"+ && let syn::PathArguments::AngleBracketed(arguments) = &last.arguments+ && let Some(syn::GenericArgument::Type(inner)) =+ arguments.args.iter().find(|argument| matches!(argument, syn::GenericArgument::Type(_)))+ {+ return inner;}ty}diff --git a/crates/bindings/src/backends/uniffi.rs b/crates/bindings/src/backends/uniffi.rsindex bdb1239e3..83614efa0 100644--- a/crates/bindings/src/backends/uniffi.rs+++ b/crates/bindings/src/backends/uniffi.rs@@ -181,14 +181,13 @@ impl syn::fold::Fold for SelfReplacer {&mut self,ty: syn::Type,) -> syn::Type {- if let syn::Type::Path(path) = &ty {- if path.qself.is_none()- && path.path.segments.len() == 1- && path.path.segments[0].ident == "Self"- && path.path.segments[0].arguments.is_empty()- {- return self.self_type.clone();- }+ if let syn::Type::Path(path) = &ty+ && path.qself.is_none()+ && path.path.segments.len() == 1+ && path.path.segments[0].ident == "Self"+ && path.path.segments[0].arguments.is_empty()+ {+ return self.self_type.clone();}syn::fold::fold_type(self, ty)}diff --git a/crates/cli-storage/Cargo.toml b/crates/cli-storage/Cargo.tomlindex 088cab137..402bc2927 100644--- a/crates/cli-storage/Cargo.toml+++ b/crates/cli-storage/Cargo.toml@@ -25,3 +25,6 @@ tracing-appender.workspace = truedotenvy.workspace = trueclap.workspace = truedownload-manager.workspace = true++[lints]+workspace = truediff --git a/crates/cli-storage/src/events.rs b/crates/cli-storage/src/events.rsindex e358dd4b3..b3935cfb8 100644--- a/crates/cli-storage/src/events.rs+++ b/crates/cli-storage/src/events.rs@@ -21,11 +21,11 @@ impl EventHandler {}pub async fn poll_event(&mut self) -> io::Result<bool> {- if event::poll(Duration::from_millis(100))? {- if let Event::Key(key) = event::read()? {- self.last_event = Some(AppEvent::Key(key.code));- return Ok(true);- }+ if event::poll(Duration::from_millis(100))?+ && let Event::Key(key) = event::read()?+ {+ self.last_event = Some(AppEvent::Key(key.code));+ return Ok(true);}Ok(false)}diff --git a/crates/cli-storage/src/main.rs b/crates/cli-storage/src/main.rsindex 70ccde174..26aadbe3c 100644--- a/crates/cli-storage/src/main.rs+++ b/crates/cli-storage/src/main.rs@@ -97,19 +97,17 @@ async fn run_app<B: ratatui::backend::Backend>(app.spawn_state_listener().await;loop {- terminal- .draw(|f| ui::draw(f, &mut app))- .map_err(|error| io::Error::new(io::ErrorKind::Other, error.to_string()))?;+ terminal.draw(|f| ui::draw(f, &mut app)).map_err(|error| io::Error::other(error.to_string()))?;if app.should_quit {break;}// Handle events- if event_handler.poll_event().await? {- if let Some(event) = event_handler.next_event() {- app.handle_event(event).await;- }+ if event_handler.poll_event().await?+ && let Some(event) = event_handler.next_event()+ {+ app.handle_event(event).await;}// Small delay to reduce CPU usagediff --git a/crates/cli-storage/src/ui.rs b/crates/cli-storage/src/ui.rsindex 69563fa81..dfa1d9b7d 100644--- a/crates/cli-storage/src/ui.rs+++ b/crates/cli-storage/src/ui.rs@@ -96,10 +96,10 @@ fn render_section(state.select(None);} else if state.selected().is_none() {state.select(Some(0));- } else if let Some(selected) = state.selected() {- if selected >= section_models.len() {- state.select(Some(section_models.len().saturating_sub(1)));- }+ } else if let Some(selected) = state.selected()+ && selected >= section_models.len()+ {+ state.select(Some(section_models.len().saturating_sub(1)));}frame.render_stateful_widget(list, area, state);@@ -253,7 +253,7 @@ fn render_downloading_model())).gauge_style(gauge_style).label(label)- .ratio(progress.min(1.0).max(0.0));+ .ratio(progress.clamp(0.0, 1.0));frame.render_widget(gauge, area);}diff --git a/crates/cli-tools/Cargo.toml b/crates/cli-tools/Cargo.tomlindex e0f5589c9..527f1ea7d 100644--- a/crates/cli-tools/Cargo.toml+++ b/crates/cli-tools/Cargo.toml@@ -26,3 +26,6 @@ minijinja.workspace = trueanyhow.workspace = trueindexmap.workspace = truecolored.workspace = true++[lints]+workspace = truediff --git a/crates/cli-tools/src/configs/platforms.rs b/crates/cli-tools/src/configs/platforms.rsindex fd26f969e..7e507499e 100644--- a/crates/cli-tools/src/configs/platforms.rs+++ b/crates/cli-tools/src/configs/platforms.rs@@ -90,11 +90,8 @@ impl PlatformsConfig {let language_config = self.languages.get(&language).context("Language not found")?;let language_targets = language_config.targets.clone();- let resolved_targets = language_targets- .iter()- .filter(|target| requested_targets.contains(target))- .map(|target| target.clone())- .collect::<Vec<_>>();+ let resolved_targets =+ language_targets.iter().filter(|target| requested_targets.contains(target)).cloned().collect::<Vec<_>>();Ok(resolved_targets)}@@ -103,7 +100,7 @@ impl PlatformsConfig {target: String,) -> Result<Backend> {let target_config = self.targets.get(&target).context("Target not found")?;- Ok(target_config.backend.clone())+ Ok(target_config.backend)}pub fn capabilities_for_target(@@ -122,7 +119,7 @@ impl PlatformsConfig {Ok(requested_capabilities.iter().filter(|capability| supported_capabilities.contains(capability))- .map(|capability| capability.clone())+ .copied().collect::<Vec<_>>())}diff --git a/crates/cli-tools/src/languages/mod.rs b/crates/cli-tools/src/languages/mod.rsindex a2372f959..b93038ca1 100644--- a/crates/cli-tools/src/languages/mod.rs+++ b/crates/cli-tools/src/languages/mod.rs@@ -41,7 +41,7 @@ pub trait LanguageBackend {fn language(&self) -> Language;fn expects_prebuild_for_run(&self) -> bool {- return true;+ true}fn install(&self) -> Result<()> {@@ -161,14 +161,14 @@ pub trait LanguageBackend {let backend = self.config().backend_for_target(target.clone())?;let resolved_capabilities =self.config().capabilities_for_target(target.clone(), capabilities.clone())?;- let features = vec![+ let features = [vec![backend.feature()],resolved_capabilities.iter().map(|capability| capability.feature()).collect::<Vec<_>>(),bindings.iter().map(|binding| binding.feature()).collect::<Vec<_>>(),].iter().flatten()- .map(|feature| feature.clone())+ .cloned().collect::<Vec<_>>();println!("Backend: {}", format!("{:?}", backend).green());diff --git a/crates/cli-tools/src/languages/rust.rs b/crates/cli-tools/src/languages/rust.rsindex 65c4c0402..39d9b5420 100644--- a/crates/cli-tools/src/languages/rust.rs+++ b/crates/cli-tools/src/languages/rust.rs@@ -28,7 +28,7 @@ impl LanguageBackend for RustLanguageBackend {}fn expects_prebuild_for_run(&self) -> bool {- return false;+ false}fn build_targets(diff --git a/crates/cli-tools/src/languages/swift.rs b/crates/cli-tools/src/languages/swift.rsindex 5664e254e..b9e43b126 100644--- a/crates/cli-tools/src/languages/swift.rs+++ b/crates/cli-tools/src/languages/swift.rs@@ -142,12 +142,8 @@ impl LanguageBackend for SwiftLanguageBackend {.run()?;let (checksum, _) = Command::swift_compute_checksum(zip_path.clone()).output()?;- let checksum = checksum- .lines()- .filter(|line| !line.trim().is_empty())- .last()- .context("Empty checksum output")?- .to_string();+ let checksum =+ checksum.lines().rfind(|line| !line.trim().is_empty()).context("Empty checksum output")?.to_string();let source_package_swift = paths.bindings_for_language_path(Language::Swift).join("Package.swift");let body = fs::read_to_string(&source_package_swift)@@ -241,10 +237,10 @@ fn find_static_lib(slice_path: &Path) -> Result<PathBuf> {if path.is_file() && path.extension().and_then(|extension| extension.to_str()) == Some("a") {return Some(path);}- if path.is_dir() {- if let Some(found) = walk(&path) {- return Some(found);- }+ if path.is_dir()+ && let Some(found) = walk(&path)+ {+ return Some(found);}}Nonediff --git a/crates/cli-tools/src/languages/swift_extensions.rs b/crates/cli-tools/src/languages/swift_extensions.rsindex 65c469416..c1a199fa4 100644--- a/crates/cli-tools/src/languages/swift_extensions.rs+++ b/crates/cli-tools/src/languages/swift_extensions.rs@@ -513,14 +513,14 @@ fn render_factory(factory: &Factory) -> String {let swift_method = AsLowerCamelCase(&factory.method_name).to_string();let free_function = format!("{}{}",- AsLowerCamelCase(AsSnakeCase(&factory.type_name).to_string()).to_string(),+ AsLowerCamelCase(AsSnakeCase(&factory.type_name).to_string()),capitalize_first(&swift_method),);let args_signature = factory.arguments.iter()- .map(|arg| format!("{label}: {ty}", label = AsLowerCamelCase(&arg.name).to_string(), ty = arg.swift_type,))+ .map(|arg| format!("{label}: {ty}", label = AsLowerCamelCase(&arg.name), ty = arg.swift_type,)).collect::<Vec<_>>().join(", ");diff --git a/crates/cli-tools/src/main.rs b/crates/cli-tools/src/main.rsindex 831b371f9..84b6cb2dd 100644--- a/crates/cli-tools/src/main.rs+++ b/crates/cli-tools/src/main.rs@@ -65,13 +65,11 @@ enum Commands {}fn run_setup(include_platform_specific: bool) -> Result<()> {- if include_platform_specific {- if cfg!(target_vendor = "apple") {- Command::xcodebuild_first_launch().run()?;- Command::xcodebuild_download_metal_toolchain().run()?;- Command::cmake_setup().run()?;- Command::clang_format_setup().run()?;- }+ if include_platform_specific && cfg!(target_vendor = "apple") {+ Command::xcodebuild_first_launch().run()?;+ Command::xcodebuild_download_metal_toolchain().run()?;+ Command::cmake_setup().run()?;+ Command::clang_format_setup().run()?;}Command::rustup_setup().run()?;@@ -85,7 +83,7 @@ fn run_setup(include_platform_specific: bool) -> Result<()> {fn run_verify(config: &PlatformsConfig) -> Result<()> {for language in config.languages.keys() {- let backend = language_backend(language.clone(), config.clone())?;+ let backend = language_backend(*language, config.clone())?;backend.build(Configuration::Release, vec![config.host_target()?], vec![])?;}let (output, _) = Command::git_status_porcelain().output()?;diff --git a/crates/cli-tools/src/sync/package_json.rs b/crates/cli-tools/src/sync/package_json.rsindex 5c8b050b4..eed732f7f 100644--- a/crates/cli-tools/src/sync/package_json.rs+++ b/crates/cli-tools/src/sync/package_json.rs@@ -89,7 +89,7 @@ fn replace_string_array_field() -> Result<String> {let pattern = format!(r#"("{key}"\s*:\s*)\[[^\]]*\]"#);let regex = Regex::new(&pattern)?;- let items = values.iter().map(|value| serde_json::to_string(value)).collect::<Result<Vec<_>, _>>()?;+ let items = values.iter().map(serde_json::to_string).collect::<Result<Vec<_>, _>>()?;let replacement = format!("$1[\n {}\n ]", items.join(",\n "));Ok(regex.replace(input, replacement.as_str()).into_owned())}diff --git a/crates/cli-tools/src/types/command.rs b/crates/cli-tools/src/types/command.rsindex d88ad3c4f..a3872704b 100644--- a/crates/cli-tools/src/types/command.rs+++ b/crates/cli-tools/src/types/command.rs@@ -1,6 +1,6 @@use std::{io::{BufRead, BufReader},- path::PathBuf,+ path::{Path, PathBuf},process::{Command as StdCommand, Stdio},thread,};@@ -30,10 +30,10 @@ impl Command {pub fn with_current_path(&self,- path: &PathBuf,+ path: &Path,) -> Self {Self {- current_path: Some(path.clone()),+ current_path: Some(path.to_path_buf()),..self.clone()}}diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.tomlindex 8f0bee8bd..b6d58de13 100644--- a/crates/cli/Cargo.toml+++ b/crates/cli/Cargo.toml@@ -29,3 +29,6 @@ clap.workspace = truecomfy-table.workspace = trueindicatif.workspace = trueserde_json.workspace = true++[lints]+workspace = truediff --git a/crates/download-manager/Cargo.toml b/crates/download-manager/Cargo.tomlindex 28bd0a99d..a1f5fb6d8 100644--- a/crates/download-manager/Cargo.toml+++ b/crates/download-manager/Cargo.toml@@ -39,6 +39,9 @@ mock-registry.workspace = truewiremock.workspace = truechrono.workspace = true+[lints]+workspace = true+[[test]]name = "unit"path = "tests/unit/test_entry.rs"diff --git a/crates/download-manager/src/backends/common/manager.rs b/crates/download-manager/src/backends/common/manager.rsindex f5010fc7c..a1a0657fa 100644--- a/crates/download-manager/src/backends/common/manager.rs+++ b/crates/download-manager/src/backends/common/manager.rs@@ -173,7 +173,6 @@ impl<B: Backend> FileDownloadManager for DownloadManager<B> {}}-#[allow(clippy::too_many_arguments)]pub(crate) async fn observe_startup<B: Backend>(download_id: crate::DownloadId,source_url: &str,@@ -195,7 +194,6 @@ pub(crate) async fn observe_startup<B: Backend>(.await}-#[allow(clippy::too_many_arguments)]pub(crate) async fn prepare_startup<B: Backend>(startup: Startup,context: &B::Context,diff --git a/crates/download-manager/src/file_download_task_actor/download_task_actor.rs b/crates/download-manager/src/file_download_task_actor/download_task_actor.rsindex fa7fcdf68..ef493a15a 100644--- a/crates/download-manager/src/file_download_task_actor/download_task_actor.rs+++ b/crates/download-manager/src/file_download_task_actor/download_task_actor.rs@@ -51,7 +51,6 @@ pub struct DownloadTaskActor<B: DownloadBackend> {}impl<B: DownloadBackend> DownloadTaskActor<B> {- #[allow(clippy::too_many_arguments)]pub fn new(config: Arc<DownloadConfig>,context: Arc<B::Context>,diff --git a/crates/hanashi/Cargo.toml b/crates/hanashi/Cargo.tomlindex 104fa50c4..bde07dbbe 100644--- a/crates/hanashi/Cargo.toml+++ b/crates/hanashi/Cargo.toml@@ -26,3 +26,6 @@ indexmap.workspace = true[build-dependencies]serde_json.workspace = true++[lints]+workspace = truediff --git a/crates/hanashi/src/chat/hanashi/config/mod.rs b/crates/hanashi/src/chat/hanashi/config/mod.rsindex 2a9687920..9fbb2f20c 100644--- a/crates/hanashi/src/chat/hanashi/config/mod.rs+++ b/crates/hanashi/src/chat/hanashi/config/mod.rs@@ -102,11 +102,11 @@ impl Config {} => *limit,_ => None,})- .map_or(true, |limit| limit > 1);+ .is_none_or(|limit| limit > 1);let supports_disable_reasoning = rendering.get_rendering_field_for_block_type(&ChatContentBlockType::ReasoningEffort)- .map_or(false, |field| match &field.config {+ .is_some_and(|field| match &field.config {FieldConfig::Unique {mapping: Some(mapping),..diff --git a/crates/hanashi/src/chat/hanashi/messages/rendered/message.rs b/crates/hanashi/src/chat/hanashi/messages/rendered/message.rsindex e7b2b25cb..ce2ba7ca1 100644--- a/crates/hanashi/src/chat/hanashi/messages/rendered/message.rs+++ b/crates/hanashi/src/chat/hanashi/messages/rendered/message.rs@@ -42,13 +42,13 @@ impl Message {} => blocks.clone(),};for block_type in block_types {- if let Some(existing_field) = seen_block_types.get(&block_type) {- if existing_field != field_name {- return Err(Error::DuplicateBlock {- role: role.clone(),- block_type,- });- }+ if let Some(existing_field) = seen_block_types.get(&block_type)+ && existing_field != field_name+ {+ return Err(Error::DuplicateBlock {+ role: role.clone(),+ block_type,+ });}seen_block_types.insert(block_type, field_name.clone());}@@ -185,14 +185,14 @@ fn apply_field_value(});}- if let Some(allowed) = allowed_values {- if !allowed.contains(value) {- return Err(Error::ValueNotAllowed {- role: role.clone(),- block_type: block_type.clone(),- allowed_values: format!("{:?}", allowed),- });- }+ if let Some(allowed) = allowed_values+ && !allowed.contains(value)+ {+ return Err(Error::ValueNotAllowed {+ role: role.clone(),+ block_type: block_type.clone(),+ allowed_values: format!("{:?}", allowed),+ });}if let Some(mapping) = mapping {@@ -220,14 +220,14 @@ fn apply_field_value(} else {let entry = destination.entry(field_name.to_string()).or_insert_with(|| Value::Array(vec![]));if let Value::Array(array) = entry {- if let Some(limit) = limit {- if array.len() >= *limit {- return Err(Error::LimitExceeded {- role: role.clone(),- block_type: block_type.clone(),- limit: *limit,- });- }+ if let Some(limit) = limit+ && array.len() >= *limit+ {+ return Err(Error::LimitExceeded {+ role: role.clone(),+ block_type: block_type.clone(),+ limit: *limit,+ });}array.push(value.clone());}diff --git a/crates/hanashi/src/chat/hanashi/mod.rs b/crates/hanashi/src/chat/hanashi/mod.rsindex d7271bd6c..1a5c23678 100644--- a/crates/hanashi/src/chat/hanashi/mod.rs+++ b/crates/hanashi/src/chat/hanashi/mod.rs@@ -149,33 +149,26 @@ impl Encoding {continue;}- match &field.config {- FieldConfig::Unique {- block,- allowed_values: Some(allowed_values),- ..- } => {- if !allowed_values.len() == 1 {- continue;- }- if let Some(expected_value) =- allowed_values.first().cloned().and_then(|value| value.as_str().map(|s| s.to_string()))- {- if !modified_message- .content- .iter()- .any(|message_block| message_block.get_type() == *block)- {- modified_message.content.insert(- 0,- ChatContentBlock::Text {- value: expected_value,- },- );- }- }- },- _ => {},+ if let FieldConfig::Unique {+ block,+ allowed_values: Some(allowed_values),+ ..+ } = &field.config+ {+ if !allowed_values.len() == 1 {+ continue;+ }+ if let Some(expected_value) =+ allowed_values.first().cloned().and_then(|value| value.as_str().map(|s| s.to_string()))+ && !modified_message.content.iter().any(|message_block| message_block.get_type() == *block)+ {+ modified_message.content.insert(+ 0,+ ChatContentBlock::Text {+ value: expected_value,+ },+ );+ }}}}@@ -199,12 +192,9 @@ impl Encoding {.collect();let result = self.state.synchronize_messages(&streamed_messages)?;- match result {- SynchronizationResult::Inserted => {- let last_message = self.state.messages.last().ok_or(SynchronizationError::Desynchronization)?;- self.validator.validate_next(&last_message.role)?;- },- _ => {},+ if result == SynchronizationResult::Inserted {+ let last_message = self.state.messages.last().ok_or(SynchronizationError::Desynchronization)?;+ self.validator.validate_next(&last_message.role)?;}Ok(())diff --git a/crates/hanashi/src/chat/hanashi/renderer/config/jinja_function.rs b/crates/hanashi/src/chat/hanashi/renderer/config/jinja_function.rsindex c6c428894..e7f323853 100644--- a/crates/hanashi/src/chat/hanashi/renderer/config/jinja_function.rs+++ b/crates/hanashi/src/chat/hanashi/renderer/config/jinja_function.rs@@ -45,6 +45,6 @@ impl Serialize for JinjaFunction {impl<'d> Deserialize<'d> for JinjaFunction {fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {let name = String::deserialize(deserializer)?;- Ok(JinjaFunction::from_str(&name).map_err(de::Error::custom)?)+ JinjaFunction::from_str(&name).map_err(de::Error::custom)}}diff --git a/crates/hanashi/src/chat/harmony/mod.rs b/crates/hanashi/src/chat/harmony/mod.rsindex b71714533..5aabc08ef 100644--- a/crates/hanashi/src/chat/harmony/mod.rs+++ b/crates/hanashi/src/chat/harmony/mod.rs@@ -57,7 +57,7 @@ impl EncodingTrait for Encoding {let parser = StreamableParser::new(encoding.clone(), None).map_err(|_| Error::UnableToLoadEncoding)?;Ok(Self {encoding,- parser: parser,+ parser,state: State::default(),})}@@ -118,7 +118,7 @@ impl Encoding {if let Some(current_role) = self.parser.current_role() {let mut content: Vec<HarmonyContent> = vec![];- if let Some(current_content) = self.parser.current_content().ok() {+ if let Ok(current_content) = self.parser.current_content() {content.push(HarmonyContent::Text(HarmonyTextContent {text: current_content,}));@@ -143,7 +143,7 @@ fn resolve_token(encoding: &HarmonyEncoding,token_id: TokenId,) -> Result<Token, Error> {- let value = encoding.tokenizer().decode_utf8(&[token_id]).map_err(|_| Error::UnableToDecodeToken)?;+ let value = encoding.tokenizer().decode_utf8([token_id]).map_err(|_| Error::UnableToDecodeToken)?;let is_special = encoding.tokenizer().is_special_token(token_id);Ok(Token {id: token_id,diff --git a/crates/hanashi/tests/test_encoding.rs b/crates/hanashi/tests/test_encoding.rsindex 13d7bcaa3..01e370b9e 100644--- a/crates/hanashi/tests/test_encoding.rs+++ b/crates/hanashi/tests/test_encoding.rs@@ -186,39 +186,34 @@ fn test_encoding_gpt_oss() {if let Some(original_developer_message) = original_developer_message {for block in original_developer_message.content {let new_block = block.clone();- match block {- ChatContentBlock::Tools {- namespaces,- } => {- if namespaces.iter().any(|namespace| !namespace.tools.is_empty()) {- developer_message.content.push(new_block);- }- },- _ => {},+ if let ChatContentBlock::Tools {+ namespaces,+ } = block+ && namespaces.iter().any(|namespace| !namespace.tools.is_empty())+ {+ developer_message.content.push(new_block);}}}if let Some(original_system_message) = original_system_message {for block in original_system_message.content {- match block {- ChatContentBlock::Text {- value,- } => {- developer_message.content.push(ChatContentBlock::Text {- value: format!(- "{}{}",- value,- if developer_message.content.is_empty() {- "\n\n"- } else {- ""- }- )- .to_string(),- });- break;- },- _ => {},+ if let ChatContentBlock::Text {+ value,+ } = block+ {+ developer_message.content.push(ChatContentBlock::Text {+ value: format!(+ "{}{}",+ value,+ if developer_message.content.is_empty() {+ "\n\n"+ } else {+ ""+ }+ )+ .to_string(),+ });+ break;}}}@@ -336,11 +331,12 @@ fn test_encoding_functiongemma() {if matches!(message.role, ChatRole::System {}) {message.role = ChatRole::Developer {};}- if let Some(last) = result.last_mut() {- if matches!(last.role, ChatRole::Developer {}) && matches!(message.role, ChatRole::Developer {}) {- last.content.extend(message.content);- continue;- }+ if let Some(last) = result.last_mut()+ && matches!(last.role, ChatRole::Developer {})+ && matches!(message.role, ChatRole::Developer {})+ {+ last.content.extend(message.content);+ continue;}result.push(message);}diff --git a/crates/json-transform/Cargo.toml b/crates/json-transform/Cargo.tomlindex be352f4ab..81560f5fd 100644--- a/crates/json-transform/Cargo.toml+++ b/crates/json-transform/Cargo.toml@@ -21,3 +21,6 @@ tracing.workspace = true[dev-dependencies]tracing-subscriber.workspace = truetracing-tree.workspace = true++[lints]+workspace = truediff --git a/crates/mock-registry/Cargo.toml b/crates/mock-registry/Cargo.tomlindex d49067fd9..182f99e48 100644--- a/crates/mock-registry/Cargo.toml+++ b/crates/mock-registry/Cargo.toml@@ -22,3 +22,6 @@ thiserror.workspace = truetokio.workspace = truetracing.workspace = truewiremock.workspace = true++[lints]+workspace = truediff --git a/crates/nagare/Cargo.toml b/crates/nagare/Cargo.tomlindex 4f7b202c1..83e6634e9 100644--- a/crates/nagare/Cargo.toml+++ b/crates/nagare/Cargo.toml@@ -78,3 +78,6 @@ tsify = { workspace = true, optional = true }[build-dependencies]napi-build = { workspace = true, optional = true }pyo3-build-config = { workspace = true, optional = true }++[lints]+workspace = truediff --git a/crates/proc-macros/Cargo.toml b/crates/proc-macros/Cargo.tomlindex caac6ed98..299e28512 100644--- a/crates/proc-macros/Cargo.toml+++ b/crates/proc-macros/Cargo.toml@@ -15,3 +15,6 @@ proc-macro = trueproc-macro2.workspace = truequote.workspace = truesyn.workspace = true++[lints]+workspace = truediff --git a/crates/proc-macros/src/dsl.rs b/crates/proc-macros/src/dsl.rsindex d405182d1..bcb2cf8a6 100644--- a/crates/proc-macros/src/dsl.rs+++ b/crates/proc-macros/src/dsl.rs@@ -6,7 +6,7 @@ pub fn kernel(args: TokenStream,input: TokenStream,) -> TokenStream {- let file = format!("/cpu/{}.rs", args.to_string());+ let file = format!("/cpu/{}.rs", args);let mut func = parse_macro_input!(input as ItemFn);diff --git a/crates/shoji/Cargo.toml b/crates/shoji/Cargo.tomlindex 3d837b4d0..1ff46b9ce 100644--- a/crates/shoji/Cargo.toml+++ b/crates/shoji/Cargo.toml@@ -67,3 +67,6 @@ tsify = { workspace = true, optional = true }[build-dependencies]napi-build = { workspace = true, optional = true }pyo3-build-config = { workspace = true, optional = true }++[lints]+workspace = truediff --git a/crates/shoji/src/types/basic/reasoning_effort.rs b/crates/shoji/src/types/basic/reasoning_effort.rsindex eea58ca4e..01246f04a 100644--- a/crates/shoji/src/types/basic/reasoning_effort.rs+++ b/crates/shoji/src/types/basic/reasoning_effort.rs@@ -58,6 +58,6 @@ impl Serialize for ReasoningEffort {impl<'d> Deserialize<'d> for ReasoningEffort {fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {let name = String::deserialize(deserializer)?;- Ok(ReasoningEffort::from_str(&name).map_err(de::Error::custom)?)+ ReasoningEffort::from_str(&name).map_err(de::Error::custom)}}diff --git a/crates/shoji/src/types/session/chat/config.rs b/crates/shoji/src/types/session/chat/config.rsindex ed2fc2de2..884ab2063 100644--- a/crates/shoji/src/types/session/chat/config.rs+++ b/crates/shoji/src/types/session/chat/config.rs@@ -6,23 +6,13 @@ use crate::types::{};#[bindings::export(Structure(Class))]-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]pub struct ChatConfig {pub context_length: ContextLength,pub sampling_seed: SamplingSeed,pub speculation_preset: Option<ChatSpeculationPreset>,}-impl Default for ChatConfig {- fn default() -> Self {- Self {- context_length: ContextLength::default(),- sampling_seed: SamplingSeed::default(),- speculation_preset: None,- }- }-}-#[bindings::export(Implementation)]impl ChatConfig {#[bindings::export(Method(Factory))]diff --git a/crates/shoji/src/types/session/chat/reply/config.rs b/crates/shoji/src/types/session/chat/reply/config.rsindex 413f60998..eb33a5b6d 100644--- a/crates/shoji/src/types/session/chat/reply/config.rs+++ b/crates/shoji/src/types/session/chat/reply/config.rs@@ -3,23 +3,13 @@ use serde::{Deserialize, Serialize};use crate::types::basic::{Grammar, SamplingMethod, SamplingPolicy};#[bindings::export(Structure(Class))]-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]pub struct ChatReplyConfig {pub token_limit: Option<u32>,pub sampling_policy: SamplingPolicy,pub grammar: Option<Grammar>,}-impl Default for ChatReplyConfig {- fn default() -> Self {- Self {- token_limit: None,- sampling_policy: SamplingPolicy::default(),- grammar: None,- }- }-}-#[bindings::export(Implementation)]impl ChatReplyConfig {#[bindings::export(Method(Factory))]diff --git a/crates/shoji/src/types/session/chat/role.rs b/crates/shoji/src/types/session/chat/role.rsindex 1fa75f04e..a490c4ad2 100644--- a/crates/shoji/src/types/session/chat/role.rs+++ b/crates/shoji/src/types/session/chat/role.rs@@ -67,6 +67,6 @@ impl Serialize for ChatRole {impl<'d> Deserialize<'d> for ChatRole {fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<Self, D::Error> {let name = String::deserialize(deserializer)?;- Ok(ChatRole::from_str(&name).map_err(de::Error::custom)?)+ ChatRole::from_str(&name).map_err(de::Error::custom)}}diff --git a/crates/token-stream-parser/Cargo.toml b/crates/token-stream-parser/Cargo.tomlindex 515dc075e..eca811308 100644--- a/crates/token-stream-parser/Cargo.toml+++ b/crates/token-stream-parser/Cargo.toml@@ -21,3 +21,6 @@ tracing.workspace = truetokenizers.workspace = truetracing-subscriber.workspace = truetracing-tree.workspace = true++[lints]+workspace = truediff --git a/crates/token-stream-parser/src/extraction/resolver.rs b/crates/token-stream-parser/src/extraction/resolver.rsindex 1cda3718d..8a51f9b77 100644--- a/crates/token-stream-parser/src/extraction/resolver.rs+++ b/crates/token-stream-parser/src/extraction/resolver.rs@@ -166,16 +166,16 @@ fn compose_typed_sections(child_values: Vec<(String, Value)>) -> Value {let mut sections: Vec<Value> = Vec::new();for (name, value) in child_values {// Spread arrays for non-text children into separate sections- if name != NODE_NAME_TEXT {- if let Value::Array(items) = value {- for item in items {- let mut map = serde_json::Map::new();- map.insert(SECTION_KEY_TYPE.to_string(), Value::String(name.clone()));- map.insert(SECTION_KEY_VALUE.to_string(), item);- sections.push(Value::Object(map));- }- continue;+ if name != NODE_NAME_TEXT+ && let Value::Array(items) = value+ {+ for item in items {+ let mut map = serde_json::Map::new();+ map.insert(SECTION_KEY_TYPE.to_string(), Value::String(name.clone()));+ map.insert(SECTION_KEY_VALUE.to_string(), item);+ sections.push(Value::Object(map));}+ continue;}let mut map = serde_json::Map::new();map.insert(SECTION_KEY_TYPE.to_string(), Value::String(name));@@ -224,11 +224,11 @@ fn merge_or_push_text(results: &mut Vec<(String, Value)>,text: String,) {- if let Some((name, Value::String(existing))) = results.last_mut() {- if name == NODE_NAME_TEXT {- existing.push_str(&text);- return;- }+ if let Some((name, Value::String(existing))) = results.last_mut()+ && name == NODE_NAME_TEXT+ {+ existing.push_str(&text);+ return;}results.push((NODE_NAME_TEXT.to_string(), Value::String(text)));}diff --git a/crates/token-stream-parser/src/reduction/config.rs b/crates/token-stream-parser/src/reduction/config.rsindex ba32fd54a..2a94752a6 100644--- a/crates/token-stream-parser/src/reduction/config.rs+++ b/crates/token-stream-parser/src/reduction/config.rs@@ -138,10 +138,10 @@ impl ReductionParserConfig {tokens: &mut Vec<TokenValue>,) {for group in groups {- if let Some(open) = group.open_token() {- if !tokens.contains(open) {- tokens.push(open.clone());- }+ if let Some(open) = group.open_token()+ && !tokens.contains(open)+ {+ tokens.push(open.clone());}if let ReductionParserGroup::Bounded {close_tokens,@@ -170,12 +170,12 @@ fn validate_sibling_groups(groups: &[ReductionParserGroup]) -> Result<(), Reduct});}- if let Some(open_token) = group.open_token() {- if !seen_open_tokens.insert(open_token) {- return Err(ReductionParserError::DuplicateOpenToken {- token: open_token.clone(),- });- }+ if let Some(open_token) = group.open_token()+ && !seen_open_tokens.insert(open_token)+ {+ return Err(ReductionParserError::DuplicateOpenToken {+ token: open_token.clone(),+ });}validate_sibling_groups(group.groups())?;diff --git a/crates/token-stream-parser/tests/helpers/mod.rs b/crates/token-stream-parser/tests/helpers/mod.rsindex 495d18ecf..2c7e2f4c6 100644--- a/crates/token-stream-parser/tests/helpers/mod.rs+++ b/crates/token-stream-parser/tests/helpers/mod.rs@@ -139,14 +139,14 @@ impl TestSuite {"name" => {},"marker" | "open" | "close" => {if let Value::String(token_value) = field {- *field = serde_json::to_value(&self.token(token_value)).unwrap();+ *field = serde_json::to_value(self.token(token_value)).unwrap();}},"text" => {if let Value::Array(items) = field {for item in items.iter_mut() {if let Value::String(token_value) = item {- *item = serde_json::to_value(&self.token(token_value)).unwrap();+ *item = serde_json::to_value(self.token(token_value)).unwrap();}}}diff --git a/crates/uzu/Cargo.toml b/crates/uzu/Cargo.tomlindex b170efbcd..1510d5920 100644--- a/crates/uzu/Cargo.toml+++ b/crates/uzu/Cargo.toml@@ -138,3 +138,6 @@ path = "tests/unit/test_entry.rs"[build-dependencies]napi-build = { workspace = true, optional = true }pyo3-build-config = { workspace = true, optional = true }++[lints]+workspace = truediff --git a/crates/uzu/examples/chat_structured_output.rs b/crates/uzu/examples/chat_structured_output.rsindex 055027035..0247a5a8f 100644--- a/crates/uzu/examples/chat_structured_output.rs+++ b/crates/uzu/examples/chat_structured_output.rs@@ -44,11 +44,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {schema: schema_string,}));let replies = session.reply(messages, chat_reply_config).await?;- if let Some(reply) = replies.first() {- if let Some(text) = reply.message.text() {- let parsed: CountryList = serde_json::from_str(&text)?;- println!("{parsed:#?}");- }+ if let Some(reply) = replies.first()+ && let Some(text) = reply.message.text()+ {+ let parsed: CountryList = serde_json::from_str(&text)?;+ println!("{parsed:#?}");}Ok(())diff --git a/crates/uzu/src/cli/components/application.rs b/crates/uzu/src/cli/components/application.rsindex 5b57cda40..074ff1d47 100644--- a/crates/uzu/src/cli/components/application.rs+++ b/crates/uzu/src/cli/components/application.rs@@ -260,7 +260,7 @@ pub fn Application(ContextProvider(value: Context::owned(state)) {View(flex_direction: FlexDirection::Column,- width: width as u16,+ width: width,) {View(padding_left: state.read().theme.padding(),diff --git a/crates/uzu/src/cli/components/command_input.rs b/crates/uzu/src/cli/components/command_input.rsindex 4dc956597..73a83a3ce 100644--- a/crates/uzu/src/cli/components/command_input.rs+++ b/crates/uzu/src/cli/components/command_input.rs@@ -29,7 +29,7 @@ pub fn CommandInput(let on_submit = props.on_submit.clone();let state = *hooks.use_context::<State<ApplicationState>>();- let mut input = hooks.use_state(|| String::new());+ let mut input = hooks.use_state(String::new);let (width, _) = hooks.use_terminal_size();let input_text = input.read().clone();@@ -96,19 +96,15 @@ fn hint_component() -> AnyElement<'static> {let mut hints = Vec::new();match state.read().model_state.as_ref() {- Some(model_state) => {- if model_state.model.is_downloadable() {- if !matches!(model_state.download_state.phase, DownloadPhase::Downloaded {}) {- hints.push(HINT_STORAGE_PAUSE_RESUME.to_string());- } else {- hints.push(HINT_SEND.to_string());- }- hints.push(HINT_STORAGE_DELETE.to_string());+ Some(model_state) if model_state.model.is_downloadable() => {+ if !matches!(model_state.download_state.phase, DownloadPhase::Downloaded {}) {+ hints.push(HINT_STORAGE_PAUSE_RESUME.to_string());} else {hints.push(HINT_SEND.to_string());}+ hints.push(HINT_STORAGE_DELETE.to_string());},- None => {+ _ => {hints.push(HINT_SEND.to_string());},}diff --git a/crates/uzu/src/cli/components/history_cell.rs b/crates/uzu/src/cli/components/history_cell.rsindex 7f8d66f68..c640b7ce5 100644--- a/crates/uzu/src/cli/components/history_cell.rs+++ b/crates/uzu/src/cli/components/history_cell.rs@@ -86,16 +86,13 @@ pub fn HistoryCell(.into(),Some(HistoryCellType::ChatReply {reply,- }) => {- chat_reply_component(reply, theme.subtitle_color, theme.overlay_color(), theme.padding())- .into()- },+ }) => chat_reply_component(reply, theme.subtitle_color, theme.overlay_color(), theme.padding()),Some(HistoryCellType::ClassificationOutput {output,- }) => classification_output_component(output, theme.subtitle_color, theme.padding()).into(),+ }) => classification_output_component(output, theme.subtitle_color, theme.padding()),Some(HistoryCellType::TextToSpeechOutput {stats,- }) => text_to_speech_output_component(stats, theme.subtitle_color, theme.padding()).into(),+ }) => text_to_speech_output_component(stats, theme.subtitle_color, theme.padding()),None => element! { View }.into(),};viewdiff --git a/crates/uzu/src/cli/components/logo.rs b/crates/uzu/src/cli/components/logo.rsindex a83f1c58d..cf3b5a2f8 100644--- a/crates/uzu/src/cli/components/logo.rs+++ b/crates/uzu/src/cli/components/logo.rs@@ -36,7 +36,7 @@ fn about_text() -> String {#[component]pub fn Logo(mut hooks: Hooks) -> impl Into<AnyElement<'static>> {let state = hooks.use_context::<State<ApplicationState>>();- let about = hooks.use_const(|| about_text());+ let about = hooks.use_const(about_text);element! {View(diff --git a/crates/uzu/src/cli/components/rendered_text.rs b/crates/uzu/src/cli/components/rendered_text.rsindex 24d3a4f1e..5714175e5 100644--- a/crates/uzu/src/cli/components/rendered_text.rs+++ b/crates/uzu/src/cli/components/rendered_text.rs@@ -126,7 +126,7 @@ impl RenderedText {let previous_grapheme_byte_index = self.original_text[..position_byte_index].grapheme_indices(true)- .last()+ .next_back().map(|(byte_index, _)| byte_index).unwrap_or(0);@@ -185,7 +185,7 @@ fn graphemes_length(text: &str) -> usize {}pub fn grapheme_at_visual_position(- text: &String,+ text: &str,target_row: usize,target_col: usize,maximal_width: usize,@@ -225,7 +225,7 @@ pub fn grapheme_at_visual_position(}pub fn grapheme_visual_position(- text: &String,+ text: &str,position: usize,maximal_width: usize,) -> (usize, usize) {diff --git a/crates/uzu/src/cli/components/selected_model.rs b/crates/uzu/src/cli/components/selected_model.rsindex d40784db9..94fb44c86 100644--- a/crates/uzu/src/cli/components/selected_model.rs+++ b/crates/uzu/src/cli/components/selected_model.rs@@ -42,10 +42,10 @@ pub fn SelectedModel(let mut stream = engine.storage_subscribe().await;- if let Some(initial) = downloader.state().await {- if let Some(model_state) = state.write().model_state.as_mut() {- model_state.download_state = initial;- }+ if let Some(initial) = downloader.state().await+ && let Some(model_state) = state.write().model_state.as_mut()+ {+ model_state.download_state = initial;}if downloader.resume().await.is_err() {diff --git a/crates/uzu/src/cli/components/selector.rs b/crates/uzu/src/cli/components/selector.rsindex 4e6c98b1a..49b4f2ad3 100644--- a/crates/uzu/src/cli/components/selector.rs+++ b/crates/uzu/src/cli/components/selector.rs@@ -186,22 +186,20 @@ fn item_component(let row = element! {View(flex_direction: FlexDirection::Row, column_gap: columns_padding, width: 100pct) {- View(width: title_column_width as u16) {+ View(width: title_column_width) {Text(content: title_text, color: title_color, weight: title_weight)}#(description_view.into_iter())}};- if is_selected {- if let Some(color) = item.color {- return element! {- Gradient(from_color: Some(color.darker(0.25)), to_color: Some(color), width: 100pct) {- #(row)- }+ if is_selected && let Some(color) = item.color {+ return element! {+ Gradient(from_color: Some(color.darker(0.25)), to_color: Some(color), width: 100pct) {+ #(row)}- .into();}+ .into();}row.into()diff --git a/crates/uzu/src/cli/components/text_input.rs b/crates/uzu/src/cli/components/text_input.rsindex b70bc45de..e4211d959 100644--- a/crates/uzu/src/cli/components/text_input.rs+++ b/crates/uzu/src/cli/components/text_input.rs@@ -70,7 +70,7 @@ pub fn TextInput(handlers.on_submit = props.on_submit.take();}- let mut state = hooks.use_state(|| RenderedText::new());+ let mut state = hooks.use_state(RenderedText::new);let mut pending_enter_identifier = hooks.use_state(|| None::<u64>);let mut enter_identifier = hooks.use_state(|| 0u64);let (enter_timeout_sender, mut enter_timeout_receiver) = hooks.use_memo(|| watch::channel(None::<u64>), ());diff --git a/crates/uzu/src/cli/flows/model_families.rs b/crates/uzu/src/cli/flows/model_families.rsindex 95d683d61..8ef4e9432 100644--- a/crates/uzu/src/cli/flows/model_families.rs+++ b/crates/uzu/src/cli/flows/model_families.rs@@ -79,7 +79,7 @@ fn ModelFamilies(color: None,}).collect();- let height = (items.len() as u16).min(5).max(1);+ let height = (items.len() as u16).clamp(1, 5);element! {Loading(loaded: loaded) {diff --git a/crates/uzu/src/cli/flows/model_registries.rs b/crates/uzu/src/cli/flows/model_registries.rsindex bec2943e1..cdffe2e28 100644--- a/crates/uzu/src/cli/flows/model_registries.rs+++ b/crates/uzu/src/cli/flows/model_registries.rs@@ -89,7 +89,7 @@ fn ModelRegistries(color: None,}).collect();- let height = (items.len() as u16).min(5).max(1);+ let height = (items.len() as u16).clamp(1, 5);element! {Loading(loaded: loaded) {diff --git a/crates/uzu/src/cli/flows/models.rs b/crates/uzu/src/cli/flows/models.rsindex 2a692f07b..fdfd52688 100644--- a/crates/uzu/src/cli/flows/models.rs+++ b/crates/uzu/src/cli/flows/models.rs@@ -61,11 +61,11 @@ fn Models(.await.unwrap_or_default().into_iter()- .filter(|model| registry_id.as_ref().map_or(true, |id| &model.registry.identifier == id))+ .filter(|model| registry_id.as_ref().is_none_or(|id| &model.registry.identifier == id)).filter(|model| {family_id.as_ref()- .map_or(true, |id| model.family.as_ref().map_or(false, |family| &family.identifier == id))+ .is_none_or(|id| model.family.as_ref().is_some_and(|family| &family.identifier == id))}).collect();let download_statuses = engine.download_states().await;@@ -96,7 +96,7 @@ fn Models(}}).collect();- let height = (items.len() as u16).min(5).max(1);+ let height = (items.len() as u16).clamp(1, 5);element! {Loading(loaded: loaded) {diff --git a/crates/uzu/src/cli/sessions/text_to_speech.rs b/crates/uzu/src/cli/sessions/text_to_speech.rsindex 8a92acbfe..75ac1a04b 100644--- a/crates/uzu/src/cli/sessions/text_to_speech.rs+++ b/crates/uzu/src/cli/sessions/text_to_speech.rs@@ -162,7 +162,9 @@ pub async fn run_session({let mut state = state.write();if let Some(text_to_speech_state) = text_to_speech_state_mut(&mut state) {- text_to_speech_state.runtime.as_ref().map(|runtime| runtime.player.stop());+ if let Some(runtime) = text_to_speech_state.runtime.as_ref() {+ runtime.player.stop();+ }text_to_speech_state.pending_stats = None;text_to_speech_state.cancel_token = None;text_to_speech_state.status = TextToSpeechSessionStatus::Synthesizing;diff --git a/crates/uzu/src/engine/downloader.rs b/crates/uzu/src/engine/downloader.rsindex 7a20fa4a5..86a469890 100644--- a/crates/uzu/src/engine/downloader.rs+++ b/crates/uzu/src/engine/downloader.rs@@ -78,7 +78,8 @@ impl Downloader {let state = self.state().await.ok_or(StorageError::ItemNotFound {identifier: self.identifier.clone(),})?;- let result = match state.phase {++ match state.phase {DownloadPhase::Downloading {} | DownloadPhase::Downloaded {} => Ok(()),DownloadPhase::NotDownloaded {} | DownloadPhase::Paused {} | DownloadPhase::Locked {} => {let stream = self.storage.lock().await.subscribe();@@ -95,8 +96,7 @@ impl Downloader {drop(storage);self.wait_for_resume_to_be_observable(stream).await},- };- result+ }}#[bindings::export(Method)]diff --git a/crates/uzu/src/engine/mod.rs b/crates/uzu/src/engine/mod.rsindex a3549a7ab..f95e5790b 100644--- a/crates/uzu/src/engine/mod.rs+++ b/crates/uzu/src/engine/mod.rs@@ -463,7 +463,7 @@ impl Engine {let session = ChatSession::new(backend.clone(), config, model, path).await?;Ok(session)} else {- return Err(EngineError::BackendNotFound {});+ Err(EngineError::BackendNotFound {})}}@@ -479,7 +479,7 @@ impl Engine {let session = ClassificationSession::new(backend.clone(), model, path).await?;Ok(session)} else {- return Err(EngineError::BackendNotFound {});+ Err(EngineError::BackendNotFound {})}}@@ -495,7 +495,7 @@ impl Engine {let session = TextToSpeechSession::new(backend.clone(), model, path).await?;Ok(session)} else {- return Err(EngineError::BackendNotFound {});+ Err(EngineError::BackendNotFound {})}}}diff --git a/crates/uzu/src/helpers/reachability.rs b/crates/uzu/src/helpers/reachability.rsindex 3c5a0c1db..6297cbedb 100644--- a/crates/uzu/src/helpers/reachability.rs+++ b/crates/uzu/src/helpers/reachability.rs@@ -10,7 +10,7 @@ pub async fn is_endpoint_reachable(endpoint: &str) -> bool {let Some(host) = url.host_str().map(|host| host.to_string()) else {return false;};- let Some(port) = url.port_or_known_default().map(|port| port) else {+ let Some(port) = url.port_or_known_default() else {return false;};diff --git a/crates/uzu/src/logs/mod.rs b/crates/uzu/src/logs/mod.rsindex 06ba9da62..c2ff29ce9 100644--- a/crates/uzu/src/logs/mod.rs+++ b/crates/uzu/src/logs/mod.rs@@ -76,7 +76,7 @@ fn trim_log_file(let reader = BufReader::new(file);let lines: Vec<String> = reader.lines()- .filter_map(Result::ok)+ .map_while(Result::ok).collect::<Vec<_>>().into_iter().rev()@@ -107,10 +107,10 @@ fn start_trim_thread(std::thread::spawn(move || {loop {std::thread::sleep(std::time::Duration::from_secs(60));- if let Ok(metadata) = fs::metadata(&log_path) {- if metadata.len() > max_size_bytes {- let _ = trim_log_file(&log_path, keep_lines);- }+ if let Ok(metadata) = fs::metadata(&log_path)+ && metadata.len() > max_size_bytes+ {+ let _ = trim_log_file(&log_path, keep_lines);}}});diff --git a/crates/uzu/src/player/mod.rs b/crates/uzu/src/player/mod.rsindex 478dd7825..7894f1174 100644--- a/crates/uzu/src/player/mod.rs+++ b/crates/uzu/src/player/mod.rs@@ -54,7 +54,7 @@ impl Player {})?;let channel_count = channels.get() as usize;- if batch.samples.len() % channel_count != 0 {+ if !batch.samples.len().is_multiple_of(channel_count) {return Err(PlayerError::InvalidPcmBatch {message: "Sample count must be divisible by channel count".to_string(),});diff --git a/crates/uzu/src/registry/cached.rs b/crates/uzu/src/registry/cached.rsindex 8b8ad5029..1dafeb56e 100644--- a/crates/uzu/src/registry/cached.rs+++ b/crates/uzu/src/registry/cached.rs@@ -35,7 +35,7 @@ impl Registry for CachedRegistry {Box::pin(async {let mut cached_models = self.models.lock().await;if let Some(cached_models) = cached_models.as_ref() {- return Ok(cached_models.clone());+ Ok(cached_models.clone())} else {let models = match self.registry.models().await {Ok(models) => models.clone(),@@ -44,7 +44,7 @@ impl Registry for CachedRegistry {},};*cached_models = Some(models.clone());- return Ok(models);+ Ok(models)}})}diff --git a/crates/uzu/src/registry/mirai/types.rs b/crates/uzu/src/registry/mirai/types.rsindex 7dc4ab7e8..83e0bee88 100644--- a/crates/uzu/src/registry/mirai/types.rs+++ b/crates/uzu/src/registry/mirai/types.rs@@ -8,7 +8,7 @@ use shoji::types::{};fn get_metadata(- metadatas: &Vec<Metadata>,+ metadatas: &[Metadata],identifier: String,) -> Option<Metadata> {metadatas.iter().find(|metadata| metadata.identifier == identifier).cloned()@@ -24,13 +24,13 @@ pub struct Registry {impl Registry {fn to(&self,- metadatas: &Vec<Metadata>,+ metadatas: &[Metadata],) -> Option<ModelRegistry> {let metadata = get_metadata(metadatas, self.metadata_id.clone())?;- return Some(ModelRegistry {+ Some(ModelRegistry {identifier: self.id.clone(),- metadata: metadata,- });+ metadata,+ })}}@@ -45,14 +45,14 @@ pub struct Backend {impl Backend {fn to(&self,- metadatas: &Vec<Metadata>,+ metadatas: &[Metadata],) -> Option<ModelBackend> {let metadata = get_metadata(metadatas, self.metadata_id.clone())?;- return Some(ModelBackend {+ Some(ModelBackend {identifier: self.id.clone(),version: self.version.clone(),- metadata: metadata,- });+ metadata,+ })}}@@ -66,13 +66,13 @@ pub struct Vendor {impl Vendor {fn to(&self,- metadatas: &Vec<Metadata>,+ metadatas: &[Metadata],) -> Option<ModelVendor> {let metadata = get_metadata(metadatas, self.metadata_id.clone())?;- return Some(ModelVendor {+ Some(ModelVendor {identifier: self.id.clone(),- metadata: metadata,- });+ metadata,+ })}}@@ -87,15 +87,15 @@ pub struct Family {impl Family {fn to(&self,- metadatas: &Vec<Metadata>,+ metadatas: &[Metadata],) -> Option<ModelFamily> {let vendor = self.vendor.to(metadatas)?;let metadata = get_metadata(metadatas, self.metadata_id.clone())?;- return Some(ModelFamily {+ Some(ModelFamily {identifier: self.id.clone(),- vendor: vendor,- metadata: metadata,- });+ vendor,+ metadata,+ })}}@@ -111,15 +111,15 @@ pub struct Properties {impl Properties {fn to(&self,- metadatas: &Vec<Metadata>,+ metadatas: &[Metadata],) -> Option<ModelProperties> {let metadata = get_metadata(metadatas, self.metadata_id.clone())?;- return Some(ModelProperties {+ Some(ModelProperties {identifier: self.id.clone(),size: self.size,version: self.version.clone(),- metadata: metadata,- });+ metadata,+ })}}@@ -136,17 +136,17 @@ pub struct Quantization {impl Quantization {fn to(&self,- metadatas: &Vec<Metadata>,+ metadatas: &[Metadata],) -> Option<ModelQuantization> {let vendor = self.vendor.to(metadatas)?;let metadata = get_metadata(metadatas, self.metadata_id.clone())?;- return Some(ModelQuantization {+ Some(ModelQuantization {identifier: self.id.clone(),method: self.method.clone(),bits_per_weight: self.bits_per_weight,- vendor: vendor,- metadata: metadata,- });+ vendor,+ metadata,+ })}}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]@@ -165,7 +165,7 @@ pub struct ResponseModel {impl ResponseModel {fn to(&self,- metadatas: &Vec<Metadata>,+ metadatas: &[Metadata],) -> Option<Model> {let registry = self.registry.to(metadatas)?;let backends = self.backends.iter().flat_map(|backend| backend.to(metadatas)).collect::<Vec<_>>();@@ -186,16 +186,16 @@ impl ResponseModel {};let specializations = self.specializations.clone();let accessibility = self.accessibility.clone();- return Some(Model {+ Some(Model {identifier: self.id.clone(),- registry: registry,- backends: backends,- family: family,- properties: properties,- quantization: quantization,- specializations: specializations,- accessibility: accessibility,- });+ registry,+ backends,+ family,+ properties,+ quantization,+ specializations,+ accessibility,+ })}}@@ -213,6 +213,6 @@ impl Response {if models.len() != self.models.len() {return None;}- return Some(models);+ Some(models)}}diff --git a/crates/uzu/src/registry/openai/mod.rs b/crates/uzu/src/registry/openai/mod.rsindex 19f491b9a..72bf09adf 100644--- a/crates/uzu/src/registry/openai/mod.rs+++ b/crates/uzu/src/registry/openai/mod.rs@@ -87,7 +87,7 @@ impl RegistryTrait for Registry {self.model_filter.as_ref().is_none_or(|regex| regex.is_match(identifier).unwrap_or(false))}).map(|identifier| {- let model = ShojiModel::external(+ ShojiModel::external(identifier.clone(),self.config.identifier.clone(),self.config.name.clone(),@@ -98,8 +98,7 @@ impl RegistryTrait for Registry {ModelAccessibility::Remote {repository: None,},- );- model+ )}).collect();diff --git a/crates/uzu/src/storage/types/download_state.rs b/crates/uzu/src/storage/types/download_state.rsindex 19f5874e1..e626418e4 100644--- a/crates/uzu/src/storage/types/download_state.rs+++ b/crates/uzu/src/storage/types/download_state.rs@@ -125,19 +125,16 @@ pub fn reduce_file_download_states(file_states: &[FileDownloadState]) -> Downloalet any_downloaded = file_states.iter().any(|f| matches!(f.phase, FileDownloadPhase::Downloaded));let any_downloading = file_states.iter().any(|f| matches!(f.phase, FileDownloadPhase::Downloading));let any_paused = file_states.iter().any(|f| matches!(f.phase, FileDownloadPhase::Paused));- let any_error = file_states.iter().any(|f| matches!(f.phase, FileDownloadPhase::Error(_)));let any_locked = file_states.iter().any(|f| matches!(f.phase, FileDownloadPhase::LockedByOther(_)));if all_downloaded {return DownloadState::downloaded(total_bytes as i64);}- if any_error {- if let Some(error_state) = file_states.iter().find(|f| matches!(f.phase, FileDownloadPhase::Error(_))) {- if let FileDownloadPhase::Error(err) = &error_state.phase {- return DownloadState::error(err.clone());- }- }+ if let Some(error_state) = file_states.iter().find(|f| matches!(f.phase, FileDownloadPhase::Error(_)))+ && let FileDownloadPhase::Error(err) = &error_state.phase+ {+ return DownloadState::error(err.clone());}if any_locked {diff --git a/crates/uzu/src/storage/types/item.rs b/crates/uzu/src/storage/types/item.rsindex 08ba0b331..9133a308f 100644--- a/crates/uzu/src/storage/types/item.rs+++ b/crates/uzu/src/storage/types/item.rs@@ -97,8 +97,7 @@ impl Item {}pub async fn state(&self) -> DownloadState {- let state = self.download_state.lock().await.clone();- state+ self.download_state.lock().await.clone()}async fn get_file_download_states(&self) -> Vec<FileDownloadState> {@@ -113,12 +112,11 @@ impl Item {if !cache_guard.is_empty() && cache_guard.len() == num_file_tasks {let mut states = cache_guard.clone();for (i, state) in states.iter_mut().enumerate() {- if state.total_bytes == 0 {- if let Some(file_info) = self.files.get(i) {- if file_info.size > 0 {- state.total_bytes = file_info.size as u64;- }- }+ if state.total_bytes == 0+ && let Some(file_info) = self.files.get(i)+ && file_info.size > 0+ {+ state.total_bytes = file_info.size as u64;}}return states;@@ -145,12 +143,11 @@ impl Item {// Patch total_bytes from registry if missing (safety net)for (i, state) in states.iter_mut().enumerate() {- if state.total_bytes == 0 {- if let Some(file_info) = self.files.get(i) {- if file_info.size > 0 {- state.total_bytes = file_info.size as u64;- }- }+ if state.total_bytes == 0+ && let Some(file_info) = self.files.get(i)+ && file_info.size > 0+ {+ state.total_bytes = file_info.size as u64;}}@@ -536,12 +533,11 @@ impl Item {streams.push((idx, stream));let mut state = file_task.state().await;- if state.total_bytes == 0 {- if let Some(file_info) = self.files.get(idx) {- if file_info.size > 0 {- state.total_bytes = file_info.size as u64;- }- }+ if state.total_bytes == 0+ && let Some(file_info) = self.files.get(idx)+ && file_info.size > 0+ {+ state.total_bytes = file_info.size as u64;}initial_states.push(state);}@@ -624,12 +620,11 @@ impl Item {if let Some(mut s) = slot.take() {if i < cache_guard.len() {// Patch total bytes if 0 in incoming update- if s.total_bytes == 0 {- if let Some(file_info) = model.files.get(i) {- if file_info.size > 0 {- s.total_bytes = file_info.size as u64;- }- }+ if s.total_bytes == 0+ && let Some(file_info) = model.files.get(i)+ && file_info.size > 0+ {+ s.total_bytes = file_info.size as u64;}cache_guard[i] = s;} else {diff --git a/crates/uzu/tests/test_engine.rs b/crates/uzu/tests/test_engine.rsindex 1f6013680..4033f2f10 100644--- a/crates/uzu/tests/test_engine.rs+++ b/crates/uzu/tests/test_engine.rs@@ -31,7 +31,7 @@ async fn test_engine_chat() {let quantization_vendor_identifier =model.quantization.as_ref().map(|quantization| quantization.vendor.identifier.clone());let quantization_identifier = model.quantization.as_ref().map(|quantization| quantization.identifier.clone());- let download_phase = engine.downloader(&model).state().await.map_or(None, |state| Some(state.phase));+ let download_phase = engine.downloader(&model).state().await.map(|state| state.phase);println!("identifier: {}", identifier);println!("name: {}", name);println!("repo_ids: {:?}", repo_ids);diff --git a/deny.toml b/deny.tomlindex 0519c8b89..b1edb3eda 100644--- a/deny.toml+++ b/deny.toml@@ -3,7 +3,6 @@ ignore = ["RUSTSEC-2024-0370", # proc-macro-error is unmaintained"RUSTSEC-2024-0436", # paste - no longer maintained"RUSTSEC-2024-0375", # `atty` is unmaintained- "RUSTSEC-2025-0057", # fxhash - no longer maintained"RUSTSEC-2024-0384", # instant is unmaintained"RUSTSEC-2025-0012", # backoff is unmaintained]