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 Aug 14, 2024
1 parent 53ce65f commit e2ac837
Show file tree
Hide file tree
Showing 35 changed files with 54 additions and 71 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
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
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
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/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
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
10 changes: 3 additions & 7 deletions candle-pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -518,9 +518,7 @@ impl PyTensor {
// Check that the index is in range
if actual_index < 0 || actual_index >= dims[current_dim] as isize {
return Err(PyValueError::new_err(format!(
"index out of range for dimension '{i}' with indexer '{value}'",
i = current_dim,
value = index
"index out of range for dimension '{current_dim}' with indexer '{index}'"
)));
}
Ok(actual_index as usize)
Expand Down Expand Up @@ -580,8 +578,7 @@ impl PyTensor {
Ok((Indexer::Expand, current_dim))
} else {
Err(PyTypeError::new_err(format!(
"unsupported indexer {}",
py_indexer
"unsupported indexer {py_indexer}"
)))
}
}
Expand Down Expand Up @@ -1423,8 +1420,7 @@ fn save_gguf(path: &str, tensors: PyObject, metadata: PyObject, py: Python<'_>)
gguf_file::Value::Array(x)
} else {
return Err(PyErr::new::<PyValueError, _>(format!(
"unsupported type {:?}",
v
"unsupported type {v:?}"
)));
};
Ok(v)
Expand Down
6 changes: 2 additions & 4 deletions candle-pyo3/src/shape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,7 @@ impl<'source> pyo3::FromPyObject<'source> for PyShapeWithHole {
let any_invalid_dimensions = dims.iter().any(|&x| x < -1 || x == 0);
if negative_ones > 1 || any_invalid_dimensions {
return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Invalid dimension in shape: {:?}",
dims
"Invalid dimension in shape: {dims:?}"
)));
}

Expand Down Expand Up @@ -89,8 +88,7 @@ impl PyShapeWithHole {
new_dims.push(elements);
} else {
return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Invalid dimension in shape: {}",
dim
"Invalid dimension in shape: {dim}"
)));
}
}
Expand Down
2 changes: 1 addition & 1 deletion candle-transformers/src/models/mmdit/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ impl MMDiTCore {
joint_blocks.push(JointBlock::new(
hidden_size,
num_heads,
vb.pp(format!("joint_blocks.{}", i)),
vb.pp(format!("joint_blocks.{i}")),
)?);
}

Expand Down
2 changes: 1 addition & 1 deletion candle-transformers/src/models/moondream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ impl VisionTransformer {
let blocks = (0..cfg.num_blocks)
.map(|i| {
VitBlock::new(
vb.pp(&format!("blocks.{}", i)),
vb.pp(&format!("blocks.{i}")),
cfg.embed_dim,
cfg.num_heads,
cfg,
Expand Down
2 changes: 1 addition & 1 deletion candle-transformers/src/models/quantized_moondream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ impl VisionTransformer {
let blocks = (0..cfg.num_blocks)
.map(|i| {
VitBlock::new(
vb.pp(format!("blocks.{}", i)),
vb.pp(format!("blocks.{i}")),
cfg.embed_dim,
cfg.num_heads,
cfg,
Expand Down
Loading

0 comments on commit e2ac837

Please sign in to comment.