Skip to content

Commit

Permalink
style: simplify string formatting for readability
Browse files Browse the repository at this point in the history
  • Loading branch information
hamirmahal committed Oct 6, 2024
1 parent f856b5c commit 714b72e
Show file tree
Hide file tree
Showing 41 changed files with 64 additions and 81 deletions.
6 changes: 3 additions & 3 deletions candle-book/src/simplified.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ async fn simplified() -> anyhow::Result<()> {
break;
},
Err(e) => {
println!("Error: {}", e);
println!("Error: {e}");
continue;
}
}
Expand All @@ -142,8 +142,8 @@ async fn simplified() -> anyhow::Result<()> {
.argmax(D::Minus1)?
.to_dtype(DType::F32)?
.get(0).map(|x| x.to_scalar::<f32>())??;
println!("real_life_votes: {:?}", real_world_votes);
println!("neural_network_prediction_result: {:?}", result);
println!("real_life_votes: {real_world_votes:?}");
println!("neural_network_prediction_result: {result:?}");

Ok(())

Expand Down
4 changes: 2 additions & 2 deletions candle-core/benches/benchmarks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ impl BenchDevice for Device {
#[cfg(feature = "cuda")]
return Ok(device.synchronize()?);
#[cfg(not(feature = "cuda"))]
panic!("Cuda device without cuda feature enabled: {:?}", device)
panic!("Cuda device without cuda feature enabled: {device:?}")
}
Device::Metal(device) => {
#[cfg(feature = "metal")]
return Ok(device.wait_until_completed()?);
#[cfg(not(feature = "metal"))]
panic!("Metal device without metal feature enabled: {:?}", device)
panic!("Metal device without metal feature enabled: {device:?}")
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion candle-core/benches/benchmarks/qmatmul.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ fn run_bench(c: &mut Criterion, device: &Device, dtype: GgmlDType) {

let flops = b * m * n * k;

let mut group = c.benchmark_group(device.bench_name(format!("qmatmul_{:?}", dtype)));
let mut group = c.benchmark_group(device.bench_name(format!("qmatmul_{dtype:?}")));
group.sample_size(200);
group.throughput(Throughput::Bytes(flops as u64));
group.bench_function("iter", move |b| {
Expand Down
2 changes: 1 addition & 1 deletion candle-core/benches/benchmarks/unary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ fn criterion_benchmark(c: &mut Criterion) {
let handler = BenchDeviceHandler::new().unwrap();
for device in handler.devices {
for dtype in [DType::F32, DType::BF16, DType::F16] {
let name = format!("sqrt_{:?}", dtype);
let name = format!("sqrt_{dtype:?}");
run_unary_benchmark(c, &device, dtype, &name);
}
}
Expand Down
8 changes: 4 additions & 4 deletions candle-core/src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ impl Tensor {
let device_str = match self.device().location() {
crate::DeviceLocation::Cpu => "".to_owned(),
crate::DeviceLocation::Cuda { gpu_id } => {
format!(", cuda:{}", gpu_id)
format!(", cuda:{gpu_id}")
}
crate::DeviceLocation::Metal { gpu_id } => {
format!(", metal:{}", gpu_id)
format!(", metal:{gpu_id}")
}
};

Expand Down Expand Up @@ -502,10 +502,10 @@ impl std::fmt::Display for Tensor {
let device_str = match self.device().location() {
crate::DeviceLocation::Cpu => "".to_owned(),
crate::DeviceLocation::Cuda { gpu_id } => {
format!(", cuda:{}", gpu_id)
format!(", cuda:{gpu_id}")
}
crate::DeviceLocation::Metal { gpu_id } => {
format!(", metal:{}", gpu_id)
format!(", metal:{gpu_id}")
}
};

Expand Down
7 changes: 1 addition & 6 deletions candle-core/tests/quantized_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,12 +378,7 @@ fn compare_with_error(values: &[f32], expected: &[f32], tolerance: f32) {

assert!(
difference < tolerance,
"Error at index {}: value = {}, expected = {}. Difference = {} exceeds tolerance = {}.",
i,
value,
expected_value,
difference,
tolerance
"Error at index {i}: value = {value}, expected = {expected_value}. Difference = {difference} exceeds tolerance = {tolerance}."
);
}
}
Expand Down
4 changes: 2 additions & 2 deletions candle-examples/examples/clip/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ pub fn main() -> anyhow::Result<()> {
let (_logits_per_text, logits_per_image) = model.forward(&images, &input_ids)?;
let softmax_image = softmax(&logits_per_image, 1)?;
let softmax_image_vec = softmax_image.flatten_all()?.to_vec1::<f32>()?;
println!("softmax_image_vec: {:?}", softmax_image_vec);
println!("softmax_image_vec: {softmax_image_vec:?}");
let probability_vec = softmax_image_vec
.iter()
.map(|v| v * 100.0)
Expand All @@ -105,7 +105,7 @@ pub fn main() -> anyhow::Result<()> {
let start = i * probability_per_image;
let end = start + probability_per_image;
let prob = &probability_vec[start..end];
println!("\n\nResults for image: {}\n", img);
println!("\n\nResults for image: {img}\n");
for (i, p) in prob.iter().enumerate() {
println!("Probability: {:.4}% Text: {} ", p, vec_seq[i]);
}
Expand Down
5 changes: 2 additions & 3 deletions candle-examples/examples/codegeex4-9b/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ impl TextGeneration {
let start_gen = std::time::Instant::now();

println!("\n start_gen");
println!("samplelen {}", sample_len);
println!("samplelen {sample_len}");
let mut count = 0;
let mut result = vec![];
for index in 0..sample_len {
Expand Down Expand Up @@ -103,8 +103,7 @@ impl TextGeneration {
.expect("Token error");
if self.verbose_prompt {
println!(
"[Count: {}] [Raw Token: {}] [Decode Token: {}]",
count, next_token, token
"[Count: {count}] [Raw Token: {next_token}] [Decode Token: {token}]"
);
}
result.push(token);
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/efficientvit/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ impl Which {
Self::M4 => "m4",
Self::M5 => "m5",
};
format!("timm/efficientvit_{}.r224_in1k", name)
format!("timm/efficientvit_{name}.r224_in1k")
}

fn config(&self) -> efficientvit::Config {
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/fastvit/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl Which {
Self::SA36 => "sa36",
Self::MA36 => "ma36",
};
format!("timm/fastvit_{}.apple_in1k", name)
format!("timm/fastvit_{name}.apple_in1k")
}

fn config(&self) -> fastvit::Config {
Expand Down
3 changes: 1 addition & 2 deletions candle-examples/examples/glm4/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,7 @@ impl TextGeneration {
.expect("Token error");
if self.verbose_prompt {
println!(
"[Count: {}] [Raw Token: {}] [Decode Token: {}]",
count, next_token, token
"[Count: {count}] [Raw Token: {next_token}] [Decode Token: {token}]"
);
}
result.push(token);
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/hiera/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ impl Which {
Self::Large => "large",
Self::Huge => "huge",
};
format!("timm/hiera_{}_224.mae_in1k_ft_in1k", name)
format!("timm/hiera_{name}_224.mae_in1k_ft_in1k")
}

fn config(&self) -> hiera::Config {
Expand Down
3 changes: 1 addition & 2 deletions candle-examples/examples/llava/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,7 @@ fn main() -> Result<()> {

println!("generating conv template");
let image_token_se = format!(
"{}{}{}",
DEFAULT_IM_START_TOKEN, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_END_TOKEN
"{DEFAULT_IM_START_TOKEN}{DEFAULT_IMAGE_TOKEN}{DEFAULT_IM_END_TOKEN}"
);
let qs = if args.prompt.contains(IMAGE_PLACEHOLDER) {
if llava_config.mm_use_im_start_end {
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/mamba-minimal/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ enum Which {

impl std::fmt::Display for Which {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
write!(f, "{self:?}")
}
}

Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/mamba/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ enum Which {

impl std::fmt::Display for Which {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
write!(f, "{self:?}")
}
}

Expand Down
6 changes: 3 additions & 3 deletions candle-examples/examples/mobileclip/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl Which {
Self::S1 => "S1",
Self::S2 => "S2",
};
format!("apple/MobileCLIP-{}-OpenCLIP", name)
format!("apple/MobileCLIP-{name}-OpenCLIP")
}

fn config(&self) -> mobileclip::MobileClipConfig {
Expand Down Expand Up @@ -107,7 +107,7 @@ pub fn main() -> anyhow::Result<()> {
let (_logits_per_text, logits_per_image) = model.forward(&images, &input_ids)?;
let softmax_image = softmax(&logits_per_image, 1)?;
let softmax_image_vec = softmax_image.flatten_all()?.to_vec1::<f32>()?;
println!("softmax_image_vec: {:?}", softmax_image_vec);
println!("softmax_image_vec: {softmax_image_vec:?}");
let probability_vec = softmax_image_vec
.iter()
.map(|v| v * 100.0)
Expand All @@ -118,7 +118,7 @@ pub fn main() -> anyhow::Result<()> {
let start = i * probability_per_image;
let end = start + probability_per_image;
let prob = &probability_vec[start..end];
println!("\n\nResults for image: {}\n", img);
println!("\n\nResults for image: {img}\n");

for (i, p) in prob.iter().enumerate() {
println!("Probability: {:.4}% Text: {}", p, vec_seq[i]);
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/mobilenetv4/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl Which {
Self::Large => "conv_large.e600_r384",
Self::HybridLarge => "hybrid_large.ix_e600_r384",
};
format!("timm/mobilenetv4_{}_in1k", name)
format!("timm/mobilenetv4_{name}_in1k")
}

fn resolution(&self) -> u32 {
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/mobileone/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl Which {
Self::S3 => "s3",
Self::S4 => "s4",
};
format!("timm/mobileone_{}.apple_in1k", name)
format!("timm/mobileone_{name}.apple_in1k")
}

fn config(&self) -> mobileone::Config {
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/moondream/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ impl TextGeneration {
}
};
load_t = start_gen.elapsed();
println!("load_t: {:?}", load_t);
println!("load_t: {load_t:?}");
logits
};
let logits = logits.squeeze(0)?.to_dtype(DType::F32)?;
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/paligemma/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ fn main() -> Result<()> {
.to_device(&device)?
.to_dtype(dtype)?
.unsqueeze(0)?;
println!("loaded image with shape {:?}", image);
println!("loaded image with shape {image:?}");
let start = std::time::Instant::now();
let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, dtype, &device)? };
let model = Model::new(&config, vb)?;
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/pixtral/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ fn main() -> Result<()> {
)?
};
let image = image.to_device(&device)?.unsqueeze(0)?;
println!("loaded image with shape {:?}", image);
println!("loaded image with shape {image:?}");
let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, dtype, &device)? };

if args.vision_only {
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/quantized-phi/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ impl Args {

fn format_size(size_in_bytes: usize) -> String {
if size_in_bytes < 1_000 {
format!("{}B", size_in_bytes)
format!("{size_in_bytes}B")
} else if size_in_bytes < 1_000_000 {
format!("{:.2}KB", size_in_bytes as f64 / 1e3)
} else if size_in_bytes < 1_000_000_000 {
Expand Down
5 changes: 2 additions & 3 deletions candle-examples/examples/quantized-qwen2-instruct/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ impl Args {

fn format_size(size_in_bytes: usize) -> String {
if size_in_bytes < 1_000 {
format!("{}B", size_in_bytes)
format!("{size_in_bytes}B")
} else if size_in_bytes < 1_000_000 {
format!("{:.2}KB", size_in_bytes as f64 / 1e3)
} else if size_in_bytes < 1_000_000_000 {
Expand Down Expand Up @@ -213,8 +213,7 @@ fn main() -> anyhow::Result<()> {
let mut tos = TokenOutputStream::new(tokenizer);
let prompt_str = args.prompt.unwrap_or_else(|| DEFAULT_PROMPT.to_string());
let prompt_str = format!(
"<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n",
prompt_str
"<|im_start|>user\n{prompt_str}<|im_end|>\n<|im_start|>assistant\n"
);
print!("formatted instruct prompt: {}", &prompt_str);
let tokens = tos
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/quantized/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ impl Args {

fn format_size(size_in_bytes: usize) -> String {
if size_in_bytes < 1_000 {
format!("{}B", size_in_bytes)
format!("{size_in_bytes}B")
} else if size_in_bytes < 1_000_000 {
format!("{:.2}KB", size_in_bytes as f64 / 1e3)
} else if size_in_bytes < 1_000_000_000 {
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/repvgg/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ impl Which {
Self::B2G4 => "b2g4",
Self::B3G4 => "b3g4",
};
format!("timm/repvgg_{}.rvgg_in1k", name)
format!("timm/repvgg_{name}.rvgg_in1k")
}

fn config(&self) -> repvgg::Config {
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/rwkv/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ enum Which {

impl std::fmt::Display for Which {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
write!(f, "{self:?}")
}
}

Expand Down
8 changes: 4 additions & 4 deletions candle-examples/examples/segformer/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,16 @@ enum Commands {
}

fn get_vb_and_config(model_name: String, device: &Device) -> anyhow::Result<(VarBuilder, Config)> {
println!("loading model {} via huggingface hub", model_name);
println!("loading model {model_name} via huggingface hub");
let api = hf_hub::api::sync::Api::new()?;
let api = api.model(model_name.clone());
let model_file = api.get("model.safetensors")?;
println!("model {} downloaded and loaded", model_name);
println!("model {model_name} downloaded and loaded");
let vb =
unsafe { VarBuilder::from_mmaped_safetensors(&[model_file], candle::DType::F32, device)? };
let config = std::fs::read_to_string(api.get("config.json")?)?;
let config: Config = serde_json::from_str(&config)?;
println!("{:?}", config);
println!("{config:?}");
Ok((vb, config))
}

Expand Down Expand Up @@ -138,7 +138,7 @@ fn classification_task(args: ClassificationArgs, device: &Device) -> anyhow::Res
classification.to_vec1::<f32>()?
);
let label_id = classification.argmax(0)?.to_scalar::<u32>()?;
let label_id = format!("{}", label_id);
let label_id = format!("{label_id}");
println!("label: {}", config.id2label[&label_id]);
Ok(())
}
Expand Down
4 changes: 2 additions & 2 deletions candle-examples/examples/siglip/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ pub fn main() -> anyhow::Result<()> {
let (_logits_per_text, logits_per_image) = model.forward(&images, &input_ids)?;
let softmax_image = softmax(&logits_per_image, 1)?;
let softmax_image_vec = softmax_image.flatten_all()?.to_vec1::<f32>()?;
println!("softmax_image_vec: {:?}", softmax_image_vec);
println!("softmax_image_vec: {softmax_image_vec:?}");
let probability_vec = softmax_image_vec
.iter()
.map(|v| v * 100.0)
Expand All @@ -99,7 +99,7 @@ pub fn main() -> anyhow::Result<()> {
let start = i * probability_per_image;
let end = start + probability_per_image;
let prob = &probability_vec[start..end];
println!("\n\nResults for image: {}\n", img);
println!("\n\nResults for image: {img}\n");
for (i, p) in prob.iter().enumerate() {
println!("Probability: {:.4}% Text: {} ", p, vec_seq[i]);
}
Expand Down
2 changes: 1 addition & 1 deletion candle-examples/examples/trocr/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ pub fn main() -> anyhow::Result<()> {
.get("model.safetensors")?
}
};
println!("model: {:?}", model);
println!("model: {model:?}");
unsafe { VarBuilder::from_mmaped_safetensors(&[model], DType::F32, &device)? }
};

Expand Down
4 changes: 2 additions & 2 deletions candle-nn/benches/benchmarks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ impl BenchDevice for Device {
#[cfg(feature = "cuda")]
return Ok(device.synchronize()?);
#[cfg(not(feature = "cuda"))]
panic!("Cuda device without cuda feature enabled: {:?}", device)
panic!("Cuda device without cuda feature enabled: {device:?}")
}
Device::Metal(device) => {
#[cfg(feature = "metal")]
return Ok(device.wait_until_completed()?);
#[cfg(not(feature = "metal"))]
panic!("Metal device without metal feature enabled: {:?}", device)
panic!("Metal device without metal feature enabled: {device:?}")
}
}
}
Expand Down
Loading

0 comments on commit 714b72e

Please sign in to comment.